text
stringlengths
7
3.69M
import React, { useState, useEffect, useRef } from "react"; import { Title, useDataProvider } from "react-admin"; import moment from "moment"; import { Card, CardContent, CardActions, Button } from "@material-ui/core"; import monthToRoman from "./monthToRoman"; import SimCanvas from "./SimCanvas"; import ReactToPrint from "react-to-print"; const SimPrint = ({ match: { params: { id } } }) => { const dataProvider = useDataProvider(); const componentRef = useRef(); const [sim, setSim] = useState(); const [jenis_pengajuan_sim, setPengajuanSim] = useState(); const [gol_sim, setGolonganSim] = useState(); const [penyelenggara, setPenyelenggara] = useState(); const [markas, setMarkas] = useState(); const [komandan, setKomandan] = useState(); const [pangkat_komandan, setPangkatKomandan] = useState(); const [korps_komandan, setKorpsKomandan] = useState(); const [personel, setPersonel] = useState(); const [gol_darah, setGolonganDarah] = useState(); const [pangkat, setPangkat] = useState(); const [korps, setKorps] = useState(); useEffect(() => { dataProvider.getOne("sim", { id: id }).then(({ data }) => { dataProvider .getOne("jenis_pengajuan_sim", { id: data.jenis_pengajuan_sim_id }) .then(({ data }) => setPengajuanSim(data)); dataProvider .getOne("gol_sim", { id: data.gol_sim_id }) .then(({ data }) => setGolonganSim(data)); dataProvider .getOne("penyelenggara", { id: data.penyelenggara_id }) .then(({ data }) => { dataProvider .getOne("personel", { id: data.komandan_id }) .then(({ data }) => { dataProvider .getOne("pangkat", { id: data.pangkat_id }) .then(({ data }) => setPangkatKomandan(data)); dataProvider .getOne("korps", { id: data.korps_id }) .then(({ data }) => setKorpsKomandan(data)); setKomandan(data); }); dataProvider .getOne("ibukota_provinsi", { id: data.markas_id }) .then(({ data }) => setMarkas(data)); setPenyelenggara(data); }); dataProvider .getOne("personel", { id: data.personel_id }) .then(({ data }) => { dataProvider .getOne("gol_darah", { id: data.gol_darah_id }) .then(({ data }) => setGolonganDarah(data)); dataProvider .getOne("pangkat", { id: data.pangkat_id }) .then(({ data }) => setPangkat(data)); dataProvider .getOne("korps", { id: data.korps_id }) .then(({ data }) => setKorps(data)); setPersonel(data); }); setSim(data); }); }, [dataProvider, id]); const display_sim_id = sim ? sim.id : null; const display_kode_sim_kode_sim_penyelenggara_kode = penyelenggara ? penyelenggara.kode : null; const display_kode_sim_no_urut_sim = sim ? "." + sim.id.toString().padStart(4, "0") : null; const display_kode_sim_tanggal_lahir = personel ? "." + moment(personel.tanggal_lahir).format("MMYY") : null; const display_kode_sim_gol_sim_nama = gol_sim ? "/" + gol_sim.nama : null; const display_kode_sim_jenis_pengajuan_sim_kode = jenis_pengajuan_sim ? "." + jenis_pengajuan_sim.kode : null; const display_kode_sim_tanggal_pembuatan_sim = sim ? "/" + monthToRoman(moment(sim.created).format("M")) + "/" + moment(sim.created).format("YYYY") : null; const display_kode_sim = display_kode_sim_kode_sim_penyelenggara_kode + display_kode_sim_no_urut_sim + display_kode_sim_tanggal_lahir + display_kode_sim_gol_sim_nama + display_kode_sim_jenis_pengajuan_sim_kode + display_kode_sim_tanggal_pembuatan_sim; const display_nama = personel ? personel.nama : ""; const display_tempat_lahir = personel ? personel.tempat_lahir + "/" : ""; const display_tanggal_lahir = personel ? moment(personel.tanggal_lahir).format("DD-MM-YYYY") : null; const display_tempat_tanggal_lahir = display_tempat_lahir + display_tanggal_lahir; const display_pangkat = pangkat ? pangkat.kode + " " : ""; const display_korps = korps ? korps.kode + "/" : ""; const display_no_identitas = personel ? personel.no_identitas : ""; const display_pangkat_korps_no_identitas = display_pangkat + display_korps + +display_no_identitas; const display_kesatuan = personel ? personel.kesatuan : null; const display_gol_darah = gol_darah ? gol_darah.nama : null; const display_pas_foto = sim ? sim.pas_foto : null; const display_sidik_jari = sim ? sim.sidik_jari ? sim.sidik_jari.src : null : null; const display_tanda_tangan = sim ? sim.tanda_tangan : null; const display_diberikan_di = markas ? markas.nama : null; const display_pada_tanggal = sim ? moment(sim.created).format("DD-MM-YYYY") : null; const display_berlaku_hingga = sim ? moment(sim.berlaku_hingga).format("DD-MM-YYYY") : null; const display_label_komandan = () => { if (penyelenggara) { if (penyelenggara.lingkup_id === 1) { return "DANPUSPOMAD"; } if (penyelenggara.lingkup_id === 2) { return ( "DANPOMDAM " + (penyelenggara.kode_romawi ? penyelenggara.kode_romawi + "/" : "") + penyelenggara.kode ); } } }; const display_nama_komandan = komandan ? komandan.nama : ""; const display_pangkat_komandan = pangkat_komandan ? pangkat_komandan.kode + " " : ""; const display_korps_komandan = korps_komandan ? korps_komandan.kode + "/" : null; const display_no_identitas_komandan = komandan ? komandan.no_identitas : null; const display_pangkat_korps_no_identitas_komandan = display_pangkat_komandan + display_korps_komandan + display_no_identitas_komandan; const display_tanda_tangan_komandan = penyelenggara ? penyelenggara.tanda_tangan : null; const display_stempel = penyelenggara ? penyelenggara.stempel : null; return ( <Card> <Title title="Cetak SIM" /> <CardContent> {display_sim_id && display_kode_sim && display_nama && display_tempat_tanggal_lahir && display_gol_darah && display_diberikan_di && display_pada_tanggal && display_berlaku_hingga && display_label_komandan && display_nama_komandan && display_pangkat_korps_no_identitas_komandan && ( <SimCanvas ref={componentRef} sim_id={display_sim_id} kode_sim={display_kode_sim} nama={display_nama} tempat_tanggal_lahir={display_tempat_tanggal_lahir} pangkat_korps_no_identitas={display_pangkat_korps_no_identitas} kesatuan={display_kesatuan} gol_darah={display_gol_darah} diberikan_di={display_diberikan_di} pada_tanggal={display_pada_tanggal} berlaku_hingga={display_berlaku_hingga} label_komandan={display_label_komandan()} nama_komandan={display_nama_komandan} pangkat_korps_no_identitas_komandan={ display_pangkat_korps_no_identitas_komandan } pas_foto={display_pas_foto} tanda_tangan={display_tanda_tangan} tanda_tangan_komandan={display_tanda_tangan_komandan} sidik_jari={display_sidik_jari} stempel={display_stempel} /> )} </CardContent> <CardActions> <ReactToPrint trigger={() => ( <Button variant="contained" color="primary"> Cetak </Button> )} content={() => componentRef.current} /> </CardActions> </Card> ); }; export default SimPrint;
import React, { useState, useContext } from 'react' import styled from 'styled-components' import MealItem from './MealItem'; const Container = styled.div` display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); /* This is better for small screens, once min() is better supported */ /* grid-template-columns: repeat(auto-fill, minmax(min(200px, 100%), 1fr)); */ grid-gap: 1rem; /* This is the standardized property now, but has slightly less support */ margin: 1rem; `; function MealList(props) { const { meals, showMealOverlay } = props; return ( <Container> { meals.map((meal, index) => ( <MealItem onClickCb={(e) => { e.preventDefault(); showMealOverlay(meal.id); }} key={index} image={meal.mealImage} name={meal.name} /> )) } </Container> ) } export default MealList
const MongoClient = require('mongodb').MongoClient async function schools (db) { const schools = db.collection('schools') await schools.insertOne({ name: 'Lycée Liberté', city: 'Paris', loc: { type: 'Point', coordinates: [1, 2] } }) return schools.createIndex({ name: 'text', city: 'text' }) } async function actors (db) { const actors = db.collection('actors') await actors.insertOne({ name: 'Cirque du vent', description: 'Ateliers de cirque à partir de 4 ans.', domains: ['cirque', 'spectacle vivant'], loc: { type: 'Point', coordinates: [1, 2] } }) return actors.createIndex({ name: 'text', description: 'text' }) } async function seed () { const client = await MongoClient.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/eac', { useNewUrlParser: true }) const db = await client.db() await schools(db) await actors(db) client.close() } seed()
var signalr_connection = null; $(function () { //创建连接对象connection signalr_connection = new signalR.HubConnectionBuilder() .withUrl(ApiService.SignalRUrl.APIService + "/chatHub") .configureLogging(signalR.LogLevel.Information) .build(); //启动connection signalr_connection.start() .then(function () { //记录用户登陆 signalr_connection.invoke("UserLoginSignalR", localStorage.LoginUser) .then(() => { //当有新的用户连接上服务器时,重新获取用户列表 signalr_connection.invoke("GetUserList"); }) .catch(err => console.error("登陆失败:" + err.toString()) ); }).catch(function (ex) { console.log("连接失败" + ex); //SignalR JavaScript 客户端不会自动重新连接,必须编写代码将手动重新连接你的客户端 setTimeout(() => start(), 5000); }); signalr_connection.onclose(async () => { start(); }); //绑定事件("ReceiveMessage"和服务器端的SendMessage方法中的第一个参数一致) signalr_connection.on("ReceiveUserList", function (data) { var list = JSON.parse(data); localStorage.ReceiveUserList = data; // var str = '<option value="" >请选择</option>'; // $.each(list, function (i, val) { // if (val.OnLine) { // str += '<option value="">' + val.Name + '(' + val.OnLineStr + ')</option>'; // } else { // str += '<option value="' + val.ConnectionId + '">' + val.Name + '</option>'; // } // }); // $("#sel_user").html(str); }); //绑定事件("ReceiveMessage"和服务器端的SendMessage方法中的第一个参数一致) signalr_connection.on("ReceiveMessage", function (res) { var data = JSON.parse(res); $("#resultHtml").append("<h1>" + data.message + "</h1>"); }); }); async function start() { try { await signalr_connection.start(); console.log("connected"); } catch (err) { console.log(err); setTimeout(() => start(), 5000); } }; //发送指定人消息 function btnSendMsg() { var userId = $.trim($("#sel_user").val()); var msgcontent = $.trim($("#msgcontent").val()); var msgObj = {}; msgObj.message = msgcontent; signalr_connection.invoke("SendPrivateMessage", userId, JSON.stringify(msgObj)) .catch(err => console.error("发送失败:" + err.toString()) ); }
// cria uma função e retorna um objeto // com valores fixos ou com parametros // factory simples é uma função que retorna um novo obj function criarPessoa() { return{ nome: 'João', sobrenome: 'Vicente' } } console.log(criarPessoa()) /* MINHA TENTATIVA function criarProduto (){ return{ produto: 'Matizador', valor: 65 } desconto: 0.1 } console.log(criarProduto())*/ // EXPLICAÇÃO DO CURSO function criarProdt(nome, preco) { return { // o return faz com que a função rt um obj nome, // não precisa colocar 'nome :nome do produto' preco, // motivo: já esta sendo passado em parametros desconto: 0.1 // 10% } } console.log(criarProdt('NOTBOOK', 2199.99)) console.log(criarProdt('CELULAR', 599.99)) console.log(criarProdt('IMPRESSORA', 199.99)) console.log(criarProdt('TECLADO', 299.99)) // DESSA FORMA CONSIGO CRIAR VARIOS PRODUTOS // POUPANDO MAIS TEMPO
//执行用时 :104 ms 在所有 JavaScript 提交中击败了97.27% 的用户 //内存消耗 :36.8 MB, 在所有 JavaScript 提交中击败了71.93% 的用户 var combinationSum = function(candidates, target) { let res = []; let tempRes = []; let length = candidates.length; let temp = 0; candidates.sort((a,b) => { return a - b > 0 }); res = getRes (candidates, temp, res, tempRes,target, 0, length) return res; }; function getRes (arr, temp, res, tempRes,target, i, length) { if(temp === target) { res.push(JSON.parse(JSON.stringify(tempRes))); } if(temp > target) { return; } for(let j = i; j < length; j++) { temp += arr[j]; tempRes.push(arr[j]); getRes (arr, temp, res, tempRes,target, j, length); // 这里不用写成res = getRes (arr, temp, res, tempRes,target, j, length);因为上面的if返回中没有返回res if(tempRes.length > 0) { tempRes.pop(); temp -= arr[j]; } } return res; } let candidates = [2,3,5], target = 8; let res = combinationSum(candidates, target);
var app = angular.module("yoursearch", []); app.controller("core", function ($scope, $http) { $scope.values = []; $scope.temp = []; $scope.init = function () { runApis("nfl"); //Default Search Term }; $scope.checkIfEnterKeyWasPressed = function ($event, myValue) { var keyCode = $event.which || $event.keyCode; if (keyCode === 13) { runApis(myValue); } }; function runApis(myValue) { $scope.values = []; var google_url = 'http://ajax.googleapis.com/ajax/services/search/web?callback=JSON_CALLBACK&v=1.0&q=' + myValue; var duckduckgo_url = 'http://api.duckduckgo.com/?callback=JSON_CALLBACK&q=' + myValue + '&format=json'; var reddit_url = 'https://www.reddit.com/r/all.json'; // var rottenTomatoes = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=3wu47t4b7vkjx2q4qq3hzwxg&q=' + encodeURI(myValue) + '&page_limit=1'; fetch(duckduckgo_url, 'duck'); fetch(google_url, 'google'); // fetch(reddit_url, 'reddit'); } function fetch(apiUrl, engine) { $http.jsonp(apiUrl).success(function (data) { if (engine === 'duck') { $scope.temp = { titles: data.Heading, urls: data.RelatedTopics[1].FirstURL, dis: data.RelatedTopics[1].Text, sources: "DuckDuckGo" }; $scope.values.push($scope.temp); } else if (engine === 'reddit') { console.log(data); $scope.temp = { titles: data.children.data.title, urls: data.children.data.url, dis: 'ss', sources: "DuckDuckGo" }; $scope.values.push($scope.temp); } else if (engine === 'google') { $scope.temp = { titles: data.responseData.results[1].title, urls: data.responseData.results[1].unescapedUrl, dis: data.responseData.results[1].content, sources: "Google" }; $scope.values.push($scope.temp); } }); } });
(function () { 'use strict'; angular .module('Egharpay') .factory('YouTubeService', YouTubeService); YouTubeService.$inject = ['$http']; function YouTubeService($http) { var service = { search: search }; return service; function search(searchKeyword) { var url = "/Youtube/search", data = { searchKeyword: searchKeyword }; return $http.post(url, data); } } })();
/** * @author Mario Arturo Lopez Martinez * @author Chris Holle */ import React from "react" import { useQuery } from "@apollo/react-hooks" import TeamCard from "components/cards/teamCard" import { Mutation } from "react-apollo" import { TEAM_DELETE_QUERY, TEAM_QUERY } from "data/queries" export default () => { const { loading, error, data } = useQuery(TEAM_QUERY, { pollInterval: 5000, }) return ( <div style={{ display: "flex", flexWrap: "wrap", width: "100%", height: "auto", paddingBottom: "3vh", }} > {loading && <p>Loading...</p>} {error && <p>Error: ${error.message}</p>} {data && data.teams && data.teams.map(node => { return ( <div key={node.id}> <Mutation mutation={TEAM_DELETE_QUERY} update={client => { const { teams } = client.readQuery({ query: TEAM_QUERY }) client.writeQuery({ query: TEAM_QUERY, // Filter to only include teams that haven't been deleted data: { teams: teams.filter(team => team.id !== node.id), }, }) }} key={node.id} > {postMutation => !node.archived ? ( <TeamCard id={node.id} projectName={ node.project && node.project.name !== null ? node.project.name : "Unassigned" } semester={ node.project && node.project.course.semester !== null ? node.project.semester : "" } year={ node.project && node.project.course.year !== null ? node.project.year : "" } teamName={node.name} logo={node.logo} users={node.users} onChildClick={e => { postMutation({ variables: { id: e } }) }} /> ) : ( "" ) } </Mutation> </div> ) })} </div> ) }
import React from 'react'; import './index.css'; import { Descriptions } from 'antd'; class ShowDescription extends React.Component { shouldComponentUpdate(newprops){ if (this.props.data===newprops.data){ return false; } return true; } render() { let bordered = true; let layout = 'horizontal'; let column = 3; let title = ''; let descriptions = []; if (this.props.data && this.props.data.cpdata){ if (this.props.data.cpdata.total){ bordered = this.props.data.cpdata.total.border !== 'no-bordered'; layout = this.props.data.cpdata.total.layout || layout; column = this.props.data.cpdata.total.column || column; title = this.props.data.cpdata.total.title || title; } descriptions = this.props.data.cpdata.descriptions || []; } return ( <Descriptions bordered={bordered} layout={layout} column={column} title={title}> { descriptions.map((value,index)=>{ return( <Descriptions.Item key={index} label={value.label} span={value.span||1}> {value.content} </Descriptions.Item> ) }) } </Descriptions> ); } } ShowDescription.elementName = 'ShowDescription'; export default ShowDescription;
import React, { Component } from 'react' import './css/header.css'; export default class HeaderUserProfile extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(event) { this.props.clickToggle(); } render() { return ( <div className='header-item header-user-profile' onClick={this.handleClick}> <img src="./img/avatar.png" alt="sd"/> <span>John Doe</span> <div className='arrow-block'> <span className='arrow down' ></span> </div> </div> ) } }
/*global RefinementCategory, searchDepartmentsComparator*/ var RefinementCategories = Phoenix.Collection.extend({ model: RefinementCategory, comparator: function(filter) { return searchDepartmentsComparator(filter.attributes); }, setSelState: function(selectedRefinementIds, options) { if (!_.isArray(selectedRefinementIds) || _.isEmpty(selectedRefinementIds) ) { return; } this.each(function(model) { options = _.extend({silent: true}, options || (options = {})); var selectedItems = model.items.filter(function(item) { return _.indexOf(selectedRefinementIds, item.id) >= 0; }); _.each(selectedItems, function(item) { item.set({selected:true}, options); }); }); }, saveSelState: function() { // We need to store the previously selected refinements so when the fetch // returns we can re-mark then as selected. Each new refinement returns // a new list of narrower refinements. var selectedRefinementIds = [], selections; this.each(function(model) { selections = model.getSelectedItems(); selectedRefinementIds = _.union(selectedRefinementIds, _.pluck(selections, 'id')); }); this.previousSelections = selectedRefinementIds; }, getSelectedState: function() { return this.previousSelections; }, restoreSelState: function(models) { // Set **selected** on previously selected models (if they were returned in // new set). The difference between this and setSelState is that this runs // over raw models. var selectedRefinementIds = this.previousSelections || [], foundRefinements = []; if (selectedRefinementIds.length > 0) { _.each(models, function(model) { _.each(model.items, function(item) { if (_.indexOf(selectedRefinementIds, item.id) >= 0) { item.selected = true; foundRefinements.push({ id: item.id, browseToken: item.browseToken }); } }); }); delete this.previousSelections; } return foundRefinements; }, parse: function(refinementGroups) { this.totalCount = 0; var pureFilterGroups = _.reject(refinementGroups, function(refinementGroup) { var isDepartment = Phoenix.Data.boolean(refinementGroup.isDepartment); if (isDepartment) { return true; } // Reject departments with no items refinementGroup.totalCount = parseInt(refinementGroup.totalCount, 10); if (refinementGroup.totalCount === 0) { return true; } }); return _.map(pureFilterGroups, function(refinementGroup) { this.totalCount += refinementGroup.totalCount; var refinements = _.map(refinementGroup.refinements, function(refinement) { return { id: refinement.id, name: refinement.name, browseToken: refinement.browseToken, count: parseInt(refinement.stats, 10) }; }); refinements = _.sortBy(refinements, refinementsComparator); return { id: refinementGroup.name, name: refinementGroup.name, count: refinementGroup.totalCount, items: refinements }; }, this); }, getPropertyById: function(id, property) { var retval = this.getRefinement(id); return retval ? retval.get(property) : null; }, getRefinement: function(id) { var retval; this.find(function(model) { return (retval = model.items.get(id)); }); return retval; } }); var _refinementWithNumberPattern = /^\$?([\d,\+]+)\b.*/; var _refinementNumberCleanupPattern = /[,\+]/i; function refinementsComparator(refinement) { var match = refinement.name.match(_refinementWithNumberPattern); if (match) { var val = match[1].replace(_refinementNumberCleanupPattern, ''); return parseInt(val, 10); } else { return refinement.name; } }
export default { header: "Search", view: "Search" };
const observe = require('../../lib/Vue/observeObject') const arr = [1,2,{l:12},4]; const obj = {q:1,w:2,u:{e:12}}; observe(arr, (type,value) => { console.log(`set handle from ${type}, value is ${value}`); }) observe(obj, (type,value) => { console.log(`set handle from ${type}, value is ${value}`); },false) obj.u = 14; // arr.pop(); // arr.push("12") // arr.shift(); // arr.unshift("24"); // arr.sort();
import withSplitting from 'lib/withSplitting'; export const Main = withSplitting(() => import('./Main'));
if (DashboardServiceDetailsTool == null || typeof (DashboardServiceDetailsTool) != "object") { var DashboardServiceDetailsTool = new Object(); }; (function ($) { (function (context) { context.itemsPerPage = '10'; context.loadTool = function () { TdcAsyncWebPartLoader.ShowTool({ toolname: "DashboardServiceDetailsTool", context: { }, callback: function (data) { context.paginateTable(); } }); }; context.ResetSelectedServicePerf = function () { var checkedServices = [] $(".serviceCheckClass:checked").each(function () { checkedServices.push($(this).attr("data-serviceId")); }); GetServiceResponseTime(checkedServices.join(","), "ResetServicePerformance"); }; context.TrackSelectedServicePerf = function () { var checkedServices = [] $(".serviceCheckClass:checked").each(function () { checkedServices.push($(this).attr("data-serviceId")); }); GetServiceResponseTime(checkedServices.join(","), "TrackServiceResponseTime"); }; context.ShowServiceErrorDetailPopup = function (sender, e) { var serviceId = sender.closest("tr").getAttribute("data-serviceid") if (context.StringCompare(sender.closest("td").getAttribute("data-value"), "ERROR")) { DashboardErrorDetailPopup.ShowServiceErrorDetails(serviceId, e); } }; //Region Internal Functions function ClearFilters() { document.getElementById('ddlSelectServicesByAgent').selectedIndex = 0; document.getElementById('txtSearch').value = ""; } context.StringCompare = function (string1, string2) { regex = new RegExp('^' + string1 + '$', 'i'); if (regex.test(string2)) { return true; } return false; }; function comparer(index) { return function (a, b) { var valA = getCellValue(a, index), valB = getCellValue(b, index); return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB); }; } function getCellValue(row, index) { return $(row).children('td').eq(index).attr('data-value'); } function GetServiceResponseTime(mergedServiceIds, actionName) { var dFlag = 0; if (mergedServiceIds == "" || mergedServiceIds == undefined) { mergedServiceIds = ""; } if (mergedServiceIds != "") { $("#overlayServiceDashboardTop").css("z-index", "1"); if (actionName.toLowerCase() == ("TrackServiceResponseTime").toLowerCase()) { dFlag = 1; } TdcAsyncWebPartLoader.ShowTool({ toolname: "DashboardServiceDetailsTool", action: actionName, context: { mergedServiceIds: mergedServiceIds, }, callback: function (data) { $("#overlayServiceDashboardTop").css("z-index", "-1"); context.paginateTable(); var result = data[0].getElementsByClassName("hiddenExecutionStatus")[0].value DashboardPieChartTool.DrawServiceExecutionPieChart(result, "pieExecutionResult"); DashboardBarGraphTool.drawServiceOverviewGraph("", "divResponseOverviewGraph"); DashboardPartitionGraphTool.ShowServicePartitionGraph(dFlag); }, errorcallback: function (error) { $("#overlayServiceDashboardTop").css("z-index", "-1"); } }); } }; //Region Table Filters And Search context.ShowFilteredServices = function (mergedServiceIds) { if (mergedServiceIds != "" && mergedServiceIds != null) { ClearFilters(); var array1 = mergedServiceIds.split(",") if (mergedServiceIds.toLowerCase() == "NOVA".toLowerCase()) { $(".trServiceDetails").slideDown(); $(".trServiceDetails").each(function () { $(this).addClass("filtered");/*temp ajinkya*/ }); } else { $(".trServiceDetails").hide(); $(".trServiceDetails").each(function () { if ($.inArray($(this).attr("data-serviceid"), array1) >= 0) { $(this).slideDown(); $(this).addClass("filtered");/*temp ajinkya*/ } else { $(this).removeClass("filtered");/*temp ajinkya*/ } }); } context.paginateTable(); } }; context.ddlSelectServicesByAgentChanged = function (sender, event) { document.getElementById('txtSearch').value = ""; var ServiceAgent = sender.selectedOptions[0].value; if (ServiceAgent === "ALL") { $(".trServiceDetails").slideDown(); $(".trServiceDetails").each(function () { $(this).addClass("filtered");/*temp ajinkya*/ }); } else if (ServiceAgent === "SELECTED") { $(".trServiceDetails").hide(); $(".trServiceDetails").each(function () { if ($(this).find('#chkService')[0].checked) { $(this).slideDown(); $(this).addClass("filtered");/*temp ajinkya*/ } else { $(this).removeClass("filtered");/*temp ajinkya*/ } }); } else { $(".trServiceDetails").hide(); $(".trServiceDetails").each(function () { if ($(this).attr("data-agent") === ServiceAgent) { $(this).slideDown(); $(this).addClass("filtered");/*temp ajinkya*/ } else if ($(this).attr("data-type") === ServiceAgent) { $(this).slideDown(); $(this).addClass("filtered"); } else { $(this).removeClass("filtered");/*temp ajinkya*/ } }); } context.paginateTable(); } context.txtSearchFilterChanged = function () { var table = $('#tblserviceDetails') var tbody = table.find('tbody'); document.getElementById('ddlSelectServicesByAgent').selectedIndex = 0; tbody.find('tr').each(function () { var searchString = document.getElementById("txtSearch").value; var aText = $(this).find('#tdServiceName').attr('data-value'); if (aText.toString().toLowerCase().indexOf(searchString.toLowerCase()) >= 0) { $(this).show(); $(this).addClass("filtered");/*temp ajinkya*/ } else { $(this).removeClass("filtered");/*temp ajinkya*/ $(this).hide(); } }).appendTo(tbody); context.paginateTable(); }; context.SortServiceDetails = function (sender, index) { var table = $('#tblserviceDetails'); var headers = table.find('thead th'); var tbody = table.find('tbody'); var rows = tbody.find('tr.trServiceDetails').toArray().sort(comparer(index)); sender.asc = !sender.asc; headers.removeClass('header-sort-up header-sort-down'); if (!sender.asc) { rows = rows.reverse(); $(sender).addClass('header-sort-down'); } else { $(sender).addClass('header-sort-up'); } for (var i = 0; i < rows.length; i++) { table.append(rows[i]); } context.paginateTable(); }; context.onServiceCheckChanged = function () { var serviceCountBadges = document.getElementsByClassName('ServiceCountBadge'); var totalServices = $(".serviceCheckClass").length; var selectedServices = $(".serviceCheckClass:checked").length; if (selectedServices < totalServices) { document.getElementById("chkAllServices").checked = false; } else if (selectedServices == totalServices) { document.getElementById("chkAllServices").checked = true; } $.each(serviceCountBadges, function (index) { this.innerHTML = $(".serviceCheckClass:checked").length }); }; context.CheckUnCheckAllServices = function (chkHeader) { if ($(chkHeader).prop("checked")) { // check select status $('.serviceCheckClass').each(function () { //loop through each checkbox this.checked = true; //select all checkboxes with class "serviceCheckClass" }); } else { $('.serviceCheckClass').each(function () { //loop through each checkbox this.checked = false; //deselect all checkboxes with class "serviceCheckClass" }); } context.onServiceCheckChanged(); }; context.ddlItemsPerPageChanged = function (sender, event) { context.itemsPerPage = sender.selectedOptions[0].value; context.paginateTable(); } context.paginateTable = function () { $('#tblserviceDetails').each(function () { var currentPage = 0; var $table = $(this); var numPerPage = context.itemsPerPage === 'ALL' ? $table.find('tbody tr.filtered').length : parseInt(context.itemsPerPage); $("#pgrServiceDetails").remove(); $table.bind('repaginate', function () { $table.find('tbody tr.filtered').hide().slice(currentPage * numPerPage, (currentPage + 1) * numPerPage).show(); }); $table.trigger('repaginate'); var numRows = $table.find('tbody tr.filtered').length; var numPages = Math.ceil(numRows / numPerPage); var $pager = $('<div id="pgrServiceDetails" class="pager"></div>'); for (var page = 0; page < numPages; page++) { $('<span class="page-number page-button"></span>').text(page + 1).bind('click', { newPage: page }, function (event) { currentPage = event.data['newPage']; $table.trigger('repaginate'); $(this).addClass('active').siblings().removeClass('active'); }).appendTo($pager).addClass('clickable'); } $pager.insertBefore($table).find('span.page-number:first').addClass('active'); }); }; context.HideServicesDetailsTool = function () { $("#DashboardServiceDetailsTool_placeholder").html(""); } context.ShowServicesDetailsTool = function () { DashboardServiceDetailsTool.loadTool(); } })(DashboardServiceDetailsTool); })(jQuery);
import path from 'path'; import pkg from './package.json'; import json from '@rollup/plugin-json'; import typescript from '@rollup/plugin-typescript'; import resolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; const NAME = pkg.name; const UMD_NAME = pkg['umd-name']; const tsConfigPath = path.resolve(process.cwd(), "tsconfig.json"); const srcPath = path.resolve(process.cwd(), "src"); const inputFilePath = path.join(srcPath, "index.ts"); const distPath = path.resolve(process.cwd(), "dist"); const umdDistPath = path.join(distPath, "umd", `${NAME}.js`); const esmDistPath = path.join(distPath, "esm", `${NAME}.js`); // **************** Utils Start **************** // PASS // **************** Utils End **************** /** @type {import('rollup').RollupOptions} */ const config = { input: inputFilePath, output: [ { file: umdDistPath, name: UMD_NAME, format: 'umd', sourcemap: true }, { file: esmDistPath, format: 'esm', sourcemap: true }, ], plugins: [ json(), typescript({ tsconfig: tsConfigPath }), commonjs(), resolve(), ] }; export default config;
const CACHE_NAME = "Progressive-v2"; var urlsToCache = [ "/", "../../nav.html./", "../../index.html./", "../../pages/home.html./", "../../pages/about.html./", "../../pages/contact.html./", "../../css/materialize.min.css./", "../../js/materialize.min.js./", "../../js/nav.js./" ]; // install cache self.addEventListener("install", function(event) { event.waitUntil( caches.open(CACHE_NAME).then(function(cache) { return cache.addAll(urlsToCache).catch(reason => console.error(reason)); }) ); }); // Halaman agar disimpan kedalam cache meski dalam kondisi offline self.addEventListener("fetch",function (event) { event.respondWidth( caches.match(event.request, { cacheName : CACHE_NAME}) .then(function (response) { if (response) { console.log("ServiceWorker : Gunakan aset dari cache :". response.url); return response; } console.log("ServiceWorker : Memnuat aset dari server :", event.request.url); return fetch(event.request); }) ); }); // agar selau up to date self.addEventListener("activate", function (event) { event.waitUntil( caches.keys().then(function (cacheNames) { return Promise.all( cacheNames.map(function (cacheName) { if (cacheName != CACHE_NAME) { console.log("ServiceWorker: cache " + cacheName + " dihapus"); return caches.delete(cacheName); } }) ); }) ); });
// Drawable Functions CharacterHandler.component_classes[General.COMPONENT_MOVER] = function(info) { var values = info["val"]; this.magnitude = values["ms"]; this.accelerate = General.unpack_boolean(info["a"]); this.vector = new Point3(info["c"].x, info["c"].y, info["c"].z); this.face_direction = General.unpack_point(new Point3(0, 1, 0), info["f"]); this.on_tick = function(delta_time) { var transfrom = this.character[General.COMPONENT_TRANSFORM]; if (transfrom) { if (this.accelerate) { transfrom.velocity = transfrom.velocity.add(this.vector.mul(delta_time)); } else { transfrom.position = transfrom.position.add(this.vector.mul(delta_time)); } } } this.on_update = function(info) { var values = info["val"]; if (values) { if (values["m"] || values["m"] === 0) { this.magnitude = values["m"]; } } this.vector = General.unpack_point(this.vector, info["c"]); this.face_direction = General.unpack_point(this.face_direction, info["f"]); } }
import React, { useState } from 'react'; import useFetchJobs from './useFetchJobs.js'; import { Container } from 'react-bootstrap'; import JobDetail from './JobDetail'; import Job from './Job'; import Header from './Header'; import InfiniteScroll from 'react-infinite-scroll-component'; import SearchJob from './SearchJob'; import styled, { ThemeProvider } from 'styled-components'; import { lightTheme, darkTheme, GlobalStyles } from './themes'; const StyledApp = styled.div``; const epochs = [ ['year', 31536000], ['month', 2592000], ['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1], ]; const getDuration = (timeAgoInSeconds) => { for (let [name, seconds] of epochs) { const interval = Math.floor(timeAgoInSeconds / seconds); if (interval >= 1) { return { interval: interval, epoch: name, }; } } }; const timeAgo = (date) => { const timeAgoInSeconds = Math.floor((new Date() - new Date(date)) / 1000); const { interval, epoch } = getDuration(timeAgoInSeconds); const suffix = interval === 1 ? '' : 's'; return `${interval} ${epoch}${suffix} ago`; }; function App() { // Destructure jobs from the api const [params, setParams] = useState({}); const [page, setPage] = useState(1); const [newJob, setJob] = useState({}); const [click, setClick] = useState(false); const { jobs, error, hasNextPage } = useFetchJobs(params, page); const [theme, setTheme] = useState('light'); function handleChange(e) { setParams((p) => { if (e.target.name === 'full_time') return { [e.target.name]: true }; else return { ...p, [e.target.name]: e.target.value }; }); console.log('PARAMS -> ', e.target.name, e.target.value); } function toggleTheme() { theme === 'light' ? setTheme('dark') : setTheme('light'); } function handleSubmit(e) { e.preventDefault(); setParams({ location: e.target.location.value, description: e.target.description.value, }); } return click === false ? ( <ThemeProvider theme={theme === 'light' ? lightTheme : darkTheme}> <GlobalStyles /> <StyledApp> <Header toggleTheme={toggleTheme} /> <SearchJob params={params} handleChange={handleChange} handleSubmit={handleSubmit} click={click} setClick={setClick} /> <Container> <div> {error ? ( <h1> Error, please refresh the page</h1> ) : click === false ? ( <InfiniteScroll dataLength={jobs.length} next={() => setPage(page + 1)} hasMore={hasNextPage} loader={<h4>Loading...</h4>} > <div className='jobsContainer'> {jobs.map((job, index) => { return ( <Job key={job.id} job={job} setClick={setClick} setJob={setJob} timeAgo={timeAgo} /> ); })} </div> </InfiniteScroll> ) : ( <JobDetail job={newJob} timeAgo={timeAgo} setClick={setClick} /> )} </div> </Container> </StyledApp> </ThemeProvider> ) : ( <ThemeProvider theme={theme === 'light' ? lightTheme : darkTheme}> <GlobalStyles /> <StyledApp> <Header toggleTheme={toggleTheme} /> <div> <JobDetail timeAgo={timeAgo} job={newJob} click={click} setClick={setClick} /> </div> </StyledApp> </ThemeProvider> ); } export default App;
var nlp = require('compromise') nlp.extend(require('compromise-numbers')) var t = nlp('dinasour').nouns().toPlural() console.log(t.text()) // .match() - Match text let doc = nlp('i went on a talk, i walk') let m = doc.match('. walk', { fuzzy: 0.7 }) console.log(m.text()) let ex = nlp("You are Ankita Patel").match('#FirstName @isTitleCase').text() console.log(ex); let exGirlFriend = nlp("You are Sapna Chauhan").match('#LastName @isTitleCase') console.log(exGirlFriend.text()); // named capture let named = nlp('first, turn left and enter the tunnel').match('turn [<direction>(left|right|up|down)]', 'direction').text() console.log(named); // return left // .verbs() - conjugate and negate verbs in any tense: let verb = nlp('she sells seashells by the seashore.') verb.verbs().toPastTense() // Convert sentence to past tense console.log(verb.text()) // Future tense let example = nlp('I sell some gadgets to him.') example.verbs().toFutureTense() console.log(example.text()); let example2 = nlp('I call her in evening.') example2.verbs().toFutureTense() console.log(example2.text()); let example3 = nlp('we go to the river in evening.') examplee.verbs().toFutureTense() console.log(example3.text()); let ex2 = nlp('I tell her one joke.') ex2.verbs().toFutureTense() console.log(ex2.text()); // .nouns() - Play between plural. singular and possesive form let newNoun = nlp('the yellow car') newNoun.nouns().toPlural() console.log(newNoun.text()); let roses = nlp('The children play in garden.') roses.nouns().toSingular() console.log(roses.text()); // The child play in garden. // .numbers() let myNum = nlp('one hundred twenty two') myNum.numbers().add(2) console.log(myNum.text()) // 'one hundred twenty two four' // .topics() - access name, places, org etc. let spot = nlp('buddyHolly') spot.people().if('mary').json() // spot = nlp('the opera about Axay visiting japan') spot = nlp('Vivek to come up with powerpoint UX wireframes and validate with Hemant in Bangalore. Hemant can validate with his contacts too in Mumbai. Kamal and Akshay to pair and develop a skeleton app in lambda and s3 using react so that we can prove to ourselves that we do not need a running server and can do it using only the on-demand priced components (Hyderabad).') console.log(spot.topics().json()); // [ { text: 'japan', terms: [ [Object] ] } ] var jack = nlp("I have to go to Chennai and meet Jigar for his work, then we both have to go to Delhi togather.") console.log(jack.topics().json()); // contractions - Handle implicit terms let term = nlp("we're not gonna take it, no we aren't gonna take it.") // match term term.has('going') // true // transform term.contractions().expand() console.log(term.text()) // we are not going to take it, no we are not going to take it. // nagative var negative = nlp('Kella is calling') negative.verbs().toNegative() console.log(negative.text()); // Kella is not calling var positive = nlp("I'm not there") // convert to positive positive.verbs().toPositive() console.log(positive.text()); var pos = nlp("She can't talk to me!, but i always not trying to impress her...") pos.verbs().toPositive() console.log(pos.text()); var text = nlp("They aren't coming tomorrow") text.verbs().toPositive() console.log(text.text()); // They are coming tomorrow // NUMBERS - Plus, minus or arithmetic math operations var bottle = nlp('two bottles of juice') bottle.numbers().minus(1) console.log(bottle.text()); // one bottle of juice var money = nlp('I have one lakh dollars') money.numbers().plus(200124) console.log(money.text()); // I have two hundred thousand one hundred and twenty five lakhs dollars let superman = nlp("i have two questions for Homer - 'Why lie?' and 'Lies, why?'") let numbers = superman.values() console.log(numbers.out('array')); // [ 'two' ] var money = nlp('I have two lakh dollars') money.numbers().increment() console.log(money.text()); // I have two lakh dollars money.numbers().decrement() console.log(money.text()); // Compromise accessors // .first() - use only first result // this type not working only gives first result, when try to access last property it still return first property. let cars = nlp(`Ferrari, ford mustang, Lamborghini`) cars.first() // cars.last() // console.log(cars.text()); // Ferrari // .last() // let cars2 = nlp(`Pontiac Buick, Ford Mustang, Honda Civic`).nouns() // cars2.last().text() // console.log(cars2.text()) let bikes = nlp('Harley Davidson', 'Ducati', 'KTM') bikes.last() console.log(bikes.text()); let umbrella = nlp(`Rihanna, Ember Island, Moonshine`) umbrella.first() console.log(umbrella.text()); // not working only return whole string not first or last words /* // .extend() method let myWords = { jhon: 'FirstName', doe: 'FirstName' } let user = nlp(muppetText, myWords) // make heavier changes nlp.extend((Doc,world) => { // add new tags world.addTags({ Charcter: { isA: 'Person', notA: 'Adjective', }, }) // add or change word in lexicon world.addWords({ jhon: 'Character', jane: 'Character', }) // add method to run after the tagger world.postProcess(doc => { doc.match('light the lights').tag('#verb . #Plural') }) // add the whole new method Doc.proptotype.johnVoice = () => { this.sentences().prepend('well,') this.match('i [(am|was)]').prepend('um,') return this } }) */ var myPlugin = function(Doc, world) { // add method Doc.prototype.beNice = () => { this.match('#Infinitive').prepend('kindly') return this } // add some tags world.addTags({ Charcter: { isA: 'Person', notA: 'Adjective', // conflicting tags can be array color: 'red' } }) // add some words world.addWords({ gonzo: 'MaleName', kermot: 'Frog', 'minnie mouse': 'Character' }) // post-process tagger world.postProcess(doc => { doc.match('light the light').tag('#verb', '#plural') }) } // { // nlp.extend(myPlugin) // return console.log(nlp('wash the floor').beNice().text()) // } let logexample = nlp(`gonzo, minnie mouse and kermit the frog`) logexample = logexample.splitAfter('@hasComma') let z = logexample.match('#character+') console.log(z.out('array')); // [] return empty array // custom verb conjugations nlp.extend((_Doc, world) => { world.addConjugations({ swell: {Pasttense: 'got swol'}}) }) const conjuc = nlp('swell').tag('Verb') console.log(conjuc.verbs().conjugate()[0]); // { // Pasttense: 'got swol', // Gerund: 'swelling', // PastTense: 'swelled', // PresentTense: 'swells', // Infinitive: 'swell', // FutureTense: 'will swell' // } var url = nlp('visit https://en.m.wikipedia.org/wiki/Main_Page').urls().out('array') console.log(url); // raised PR for this issue var url2 = nlp('visit www.yahoo.com').urls().out('array') console.log(url2) // [ 'www.yahoo.com' ] var url3 = nlp('visit http://www.yahoo.com').urls().out('array') console.log(url3) // [ 'http://www.yahoo.com' ] var url4 = nlp('visit http://in.en.yahoo.com').urls().out('array') console.log(url4) // [ 'http://in.en.yahoo.com' ] var url5 = nlp('visit https://en.m.wikipedia.org').urls().out('array') console.log(url5) // raised PR for this issue var url6 = nlp('visit yahoo.com').urls().out('array') console.log(url6); // ['yahoo.com'] var url7 = nlp('visit www.yahoo.com/app').urls().out('array') console.log(url7); const word = 'silent'; console.log(nlp(word).terms().syllables()[0].syllables);
$(document).ready(function() { //check for returning player if (localStorage.getItem('visited') != 'true') { //set score and round number to default localStorage.setItem('score', 0); localStorage.setItem('round', 1); //run setup for new players firstTime(); } }) let firstTime = () => { //display tutorial text $('#tutorialContainer').css('display','inline-flex'); } let gameOver = () => { //set score and round number to default localStorage.setItem('score', 0); localStorage.setItem('round', 1); //hide UI elements $('#timerContainer', '#scoreContainer', '#roundContainer').css('display', 'none'); $('#tutorialContainer').css('display','inline-flex'); score = 0; curRound = 1; } let curRound = 0; let timer = () => { //set variables for the round and time remaining in the current round curRound = localStorage.getItem('round'); $('#roundNumber').html(curRound); let timeLeft = 35 + (curRound * 5); let roundTimer = setInterval(() => { //function to start next round start(); //if life reaches 0, end the timer if (curLife == 0) { timeLeft = 0; } //set div element text as round and score variables $('#scoreCount').html(score); //subtract 1 second from timer timeLeft--; //set div element text as time remaining document.getElementById("countdownTimer").textContent = timeLeft; //run when round timer reaches 0 if (timeLeft < 1) { clearInterval(roundTimer); //remove remaining spawned elements $('div[id^="red"], div[id^="green"], div[id^="yellow"], div[id^="blue"]').remove(); //show play button $('.fa-play').css('display', 'block'); //hide UI elements $('#lifeCounter, #timerContainer, #scoreContainer, #roundContainer').css('display', 'none'); //reset variable showing if round is started started = 0; //if current life is above 0, increment round number by 1 if (curLife > 0) { curRound++; } //set values for round and score, and set that the player has played before now that they have completed a round localStorage.setItem('visited', 'true'); localStorage.setItem('round', curRound); localStorage.setItem('score', score); } }, 1000); } //change color of centre circle as life value lowers let lifeColor = (percentage, hue0, hue1) => { hue0 = 0; hue1 = 110; percentage = (curLife / maxLife); let hue = (percentage * (hue1 - hue0)) + hue0; return 'hsl(' + hue + ', 80%, 40%)'; } let makeid = () => { //set variables of empty text string, and a a string of possible characters available let text = ''; let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; //create 7 character long string to later append to div names for (let i = 0; i < 7; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } } //sets direction generated elements will spawn let position = () => { let randPosition = Math.floor((Math.random() * 4) + 1); return randPosition; }; //begin shape generation and start the next round let start = () => { //show timer $('#timerContainer').css('display', "block"); //start function to generate id names makeid(); //start function to pick direction shapes come from position(); //create empty div element let div = document.createElement('div'); //positions shapes based on direction spawned if (position() == 1) { $(div).css('top', "-150px"); $(div).css('left', Math.floor((Math.random() * screen.width) + 1)); } else if (position() == 2) { $(div).css('right', "-150px"); $(div).css('top', Math.floor((Math.random() * screen.height) + 1)); } else if (position() == 3) { $(div).css('bottom', "-150px"); $(div).css('left', Math.floor((Math.random() * screen.width) + 1)); } else if (position() == 4) { $(div).css('left', "-150px"); $(div).css('top', Math.floor((Math.random() * screen.height) + 1)); } else { return; } //picks a random value between 1 and 100 let randValue = Math.floor((Math.random() * 100) + 1); //assigns IDs matched to specific colors based on weighted rolls from randValue if (randValue <= 60) { document.getElementById('hideOverflow').appendChild(div); $(div).addClass('redrectangle'); div.id = "red"+makeid(); } else if (randValue <= 80 && randValue >=61) { document.getElementById('hideOverflow').appendChild(div); $(div).addClass('greendiamond'); div.id = "green"+makeid(); } else if (randValue <= 92 && randValue >=81) { document.getElementById('hideOverflow').appendChild(div); $(div).addClass('yellowcircle'); div.id = "yellow"+makeid(); } else if (randValue <= 100 && randValue >=93) { document.getElementById('hideOverflow').appendChild(div); $(div).addClass('blueparallelogram'); div.id = "blue"+makeid(); } //sets animation towards center $(div).animate({ 'top': ((window.innerHeight / 2) - ($(div).outerHeight() / 2)) + 'px', 'left': ((window.innerWidth / 2) - ($(div).outerWidth() / 2)) + 'px', }, 15000 - (curRound * 1000)); //subtracts life when shape enters center $(div).promise().done(function(){ //delete shape $(div).remove(); //subtract life curLife--; //if life hits 0, end the game and reset all values to default if (curLife < 1) { curLife = 0; gameOver(); } //update color of life circle lifeColor(); $('#start-button').css('background-color', lifeColor()); //reset life count $('#lifeCounter').html(curLife); }); } let started; let maxLife = 20; let curLife; //when start button is clicked, begin the game $('#start-button').on('click touch', function() { //if the game hasn't been started, set the current life to maximum, and then start if (started != 1) { curLife = maxLife; started = 1; //starts shape generation for the current round start(); //starts timer for the current round timer(); //hide tutorial text, and the start button $('#tutorialContainer, .fa-play').css('display','none'); //sets start button background color $('#start-button').css('background-color', 'hsl(104.5, 80%, 40%)') //show the life, score, and round numbers $('#lifeCounter, #scoreContainer, #roundContainer').css('display', "block"); $('#lifeCounter').html(curLife); } }); let shapeID; let score = parseInt(localStorage.getItem('score')); //shrink shapes when clicked $('body').on('click touchstart touchmove', ('div[id^="red"], div[id^="green"], div[id^="yellow"], div[id^="blue"]'), function() { //target this object shapeID = $(this); //calculate score increase on click score += (curRound * 3); //display updated score $('#scoreCount').html(score); //decrease shape size on click $(shapeID).css('width', "-=10px"); $(shapeID).css('height', "-=10px"); let size = $(shapeID).css('width'); //if shape is smaller than 30px, delete shape if (size < "30px") { $(shapeID).remove(); } });
/** * * playlist list view * */ define([ 'configuration', 'utilities', 'backbone', 'underscore', 'jquery', // using require js text for templates 'text!application/templates/playlist/list-0.0.1.html', 'text!application/collections/playlists-0.0.1' ], function(configuration, utilities, Backbone, _, $, playlistListTemplate, playlistCollection) { 'use strict'; return Backbone.View.extend({ el: $('#content'), initialize: function() { utilities.log('[PLAYLIST VIEW] initialization...', 'blue'); }, render: function () { var playlistsCollection = new playlistCollection(); playlistsCollection.fetch({ success: function(playlists) { $(this.el).html(_.template(playlistListTemplate, {playlists: playlists, _: _})); } }); } }); });
import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; import reportWebVitals from "./reportWebVitals"; import { createStore } from "redux"; import { Provider } from "react-redux"; import { act } from "@testing-library/react"; ///////////////INITIALIZE REDUCER//////////////////// let initializeReducer = { content: [], inputType: "All", }; ////////////////SET REDUCER///////////////////////// let reducer = (state = initializeReducer, action) => { if (action.type === "ADD_ITEM") { let newState = { ...state }; newState.content.push({ name: action.value, completed: false, timing: action.timing, }); state = { ...newState }; } if (action.type === "DELETE_ELEMENT") { let newState = { ...state }; newState.content.splice(action.index, 1); state = { ...newState }; } if (action.type === "CANCEL_ELEMENT") { let newState = { ...state }; newState.content[action.index].completed = !newState.content[action.index] .completed; state = { ...newState }; } if (action.type === "CHANGE_DATA") { let newState = { ...state }; newState.inputType = action.value; state = { ...newState }; } return state; }; //////////////////CREATE STORE///////////////////// let store = createStore(reducer); ReactDOM.render( <Provider store={store}> <React.StrictMode> <App /> </React.StrictMode> </Provider>, document.getElementById("root") ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
import React, { Component } from "react"; import PropTypes from "prop-types"; import classnames from 'classnames'; import Card from '@material-ui/core/Card'; import CardHeader from '@material-ui/core/CardHeader'; import CardMedia from '@material-ui/core/CardMedia'; import CardContent from '@material-ui/core/CardContent'; import CardActions from '@material-ui/core/CardActions'; import Collapse from '@material-ui/core/Collapse'; import Avatar from '@material-ui/core/Avatar'; import IconButton from '@material-ui/core/IconButton'; import Typography from '@material-ui/core/Typography'; import red from '@material-ui/core/colors/red'; import FavoriteIcon from '@material-ui/icons/Favorite'; import ShareIcon from '@material-ui/icons/Share'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import MoreVertIcon from '@material-ui/icons/MoreVert'; import CardActionArea from '@material-ui/core/CardActionArea'; import ClassifiedContent from './ClassifiedContent' class PlayerBody extends Component { state = { expanded: false }; handleExpandClick = () => { this.setState(state => ({ expanded: !state.expanded })); }; render(){ const { data, name } = this.props; const number_of_lable = data.length return ( <div style={{width: "100%", margin:4}}> <Card style={{width: "100%"}}> <CardActionArea onClick={this.handleExpandClick} style={{width: "100%", height:80}}> <Typography variant="title" style={{float:'left'}}> {name} </Typography> <Typography variant="caption" style={{margin:4, float:'left'}}> ({number_of_lable}) </Typography> </CardActionArea> <Collapse in={this.state.expanded} timeout="auto" unmountOnExit> <CardContent> <ClassifiedContent data={data} /> </CardContent> </Collapse> </Card> </div> ); } } //ArticleTagList.propTypes = { //data: PropTypes.array.isRequired, //}; export default PlayerBody;
/* Magic Mirror * Module: MMM-MyWeather * * By John Wade * MIT Licensed. */ Module.register("MMM-MyWeather", { defaults: { updateInterval: 10 * 60 * 1000, animationSpeed: 5, initialLoadDelay: 10, retryDelay: 2500, image: false, days: 5, header: false, zip: 14904, key: '', rotateInterval: 5 * 1000, }, getScripts: function() { return ["moment.js"]; }, getStyles: function() { return ["MMM-MyWeather.css"]; }, start: function() { Log.info("Starting module: " + this.name); requiresVersion: "2.1.0", // Set locale. moment.locale(config.language); this.today = ""; this.url = "http://api.apixu.com/v1/forecast.json?key="+this.config.key+"&q="+this.config.zip+"&days="+this.config.days; this.activeItem = 0; this.rotateInterval = null; this.scheduleUpdate(); }, scheduleCarousel: function() { console.log("Scheduling weather..."); this.rotateInterval = setInterval(() => { this.activeItem++; this.updateDom(this.config.animationSpeed); }, this.config.rotateInterval); }, processWeather: function(data) { this.today = data.Today; this.weather = data.forecast.forecastday; this.current = data.current; this.location = data.location; this.week = data.Week; }, scheduleUpdate: function() { setInterval(() => { this.getWeather(); }, this.config.updateInterval); this.getWeather(this.config.initialLoadDelay); }, stripZeros: function (dateStr){ return dateStr.split('-').reduce(function(date, datePart){ return date += parseInt(datePart) + '-' }, '').slice(0, -1); }, getWeather: function() { this.sendSocketNotification('GET_WEATHER', this.url); }, socketNotificationReceived: function(notification, payload) { if (notification === "WEATHER_RESULT") { this.processWeather(payload); if (this.rotateInterval == null) { this.scheduleCarousel(); } this.updateDom(this.config.animationSpeed); } }, getDom: function() { var current = this.current; var location = this.location; var large = document.createElement("div"); var wrapper = document.createElement("div"); if (this.config.header != false){ var header = document.createElement("header"); header.innerHTML = "Weather Info"; wrapper.appendChild(header); } var top = document.createElement("div"); var weatherTable = document.createElement("table"); var locationRow = document.createElement("tr"); var locationCol = document.createElement("th"); locationCol.classList.add("small", "bright", "location"); locationCol.setAttribute("colspan", 3); if (this.config.days > 1){ locationCol.innerHTML = "Weather for the next "+this.config.days+ " days for "+location.name+", "+location.region; } else if (this.config.days === 1){ locationCol.innerHTML = "Current weather for "+location.name+", "+location.region; } else { locationCol.innerHTML = "Please input number of Days for "+location.name+", "+location.region; } locationRow.appendChild(locationCol); weatherTable.appendChild(locationRow); var currentRow = document.createElement("tr"); var currentDay = document.createElement("th"); currentDay.classList.add("xsmall", "bright"); currentDay.innerHTML = "Current Temp: "+Math.round(current.temp_f)+"&#730; Wind speed: "+current.wind_mph+" Wind Direction: "+current.wind_dir; currentRow.appendChild(currentDay); weatherTable.appendChild(currentRow); var nextcurrentRow = document.createElement("tr"); var nextcurrentDay = document.createElement("th"); nextcurrentDay.classList.add("xsmall", "bright"); nextcurrentDay.innerHTML = "Current Condition: "+current.condition.text+ " and Humidity is "+current.humidity+"%"; nextcurrentRow.appendChild(nextcurrentDay); weatherTable.appendChild(nextcurrentRow); var firstrow = document.createElement("tr"); firstrow.classList.add('xsmall','bright'); var day = document.createElement("th"); day.classList.add("small", "bright"); day.innerHTML = "Date"; firstrow.appendChild(day); weatherTable.appendChild(firstrow); var dayhigh = document.createElement("th"); dayhigh.classList.add("small", "bright"); dayhigh.innerHTML = "High"; firstrow.appendChild(dayhigh); weatherTable.appendChild(firstrow); var daylow = document.createElement("th"); daylow.classList.add("small", "bright"); daylow.innerHTML = "Low"; firstrow.appendChild(daylow); weatherTable.appendChild(firstrow); var sunrise = document.createElement("th"); sunrise.classList.add("small", "bright"); sunrise.innerHTML = "Sunrise"; firstrow.appendChild(sunrise); weatherTable.appendChild(firstrow); var sunset = document.createElement("th"); sunset.classList.add("small", "bright"); sunset.innerHTML = "Sunset"; firstrow.appendChild(sunset); weatherTable.appendChild(firstrow); var humidity = document.createElement("th"); humidity.classList.add("small", "bright"); humidity.innerHTML = "H%"; firstrow.appendChild(humidity); weatherTable.appendChild(firstrow); var condition = document.createElement("th"); condition.classList.add("small", "bright"); condition.innerHTML = "Expected Condition"; firstrow.appendChild(condition); weatherTable.appendChild(firstrow); if(this.config.image === true){ var weatherPic = document.createElement("th"); weatherPic.classList.add("small", "bright"); weatherPic.innerHTML = " "; firstrow.appendChild(weatherPic); weatherTable.appendChild(firstrow); } var weather = this.weather; var keys = Object.keys(this.weather); if (keys.length > 0) { if (this.activeItem >= keys.length) { this.activeItem = 0; } var weather = this.weather[keys[this.activeItem]]; console.log(weather); wdate = weather.date; var newDate = moment(wdate).format('MM-DD-YYYY'); var row = document.createElement("tr"); var dateColumn = document.createElement("td"); var today = new Date(); var dd = today.getDate(); var dayPlus = today.getDate() + 14; var mm = today.getMonth() + 1;// January is 0! var nMonth = today.getMonth() + 6; var yyyy = today.getFullYear(); if(mm<10){mm='0'+mm;} var weekday = new Array(7); weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var dddd = weekday[today.getDay()]; var weatherDate = moment(weather.date).format('MM-DD-YYYY'); var currentDate = mm + '-' + dd + '-' + yyyy; var currentDay = dddd; var withoutZero = this.stripZeros(weatherDate); if (weatherDate === currentDate){ dateColumn.classList.add("xsmall", "bright"); dateColumn.innerHTML = "Today is "+currentDay; } else { dateColumn.classList.add("xsmall", "dimmed"); dateColumn.innerHTML = withoutZero; } row.appendChild(dateColumn); weatherTable.appendChild(row); var highColumn = document.createElement("td"); if (weather.day.maxtemp_f < 60){ highColumn.classList.add("xsmall", "dimmed"); highColumn.innerHTML = Math.round(weather.day.maxtemp_f)+"&#730;"; } else if (weather.day.maxtemp_f > 80){ highColumn.classList.add("xsmall", "bright", "hitemp"); highColumn.innerHTML = Math.round(weather.day.maxtemp_f)+"&#730;"; } else { highColumn.classList.add("xsmall", "dimmed"); highColumn.innerHTML = Math.round(weather.day.maxtemp_f)+"&#730;"; } row.appendChild(highColumn); weatherTable.appendChild(row); var lowColumn = document.createElement("td"); if (weather.day.mintemp_f < 35){ lowColumn.classList.add("xsmall", "bright", "lowtemp"); lowColumn.innerHTML = Math.round(weather.day.mintemp_f)+"&#730;"; } else { lowColumn.classList.add("xsmall", "dimmed"); lowColumn.innerHTML = Math.round(weather.day.mintemp_f)+"&#730;"; } row.appendChild(lowColumn); weatherTable.appendChild(row); var sunriseColumn = document.createElement("td"); sunriseColumn.classList.add("xsmall", "dimmed"); sunriseColumn.innerHTML = weather.astro.sunrise; row.appendChild(sunriseColumn); weatherTable.appendChild(row); var sunsetColumn = document.createElement("td"); sunsetColumn.classList.add("xsmall", "dimmed"); sunsetColumn.innerHTML = weather.astro.sunset; row.appendChild(sunsetColumn); weatherTable.appendChild(row); var humidColumn = document.createElement("td"); if (weather.day.avghumidity > 85){ humidColumn.classList.add("xsmall", "bright", "humid"); humidColumn.innerHTML = weather.day.avghumidity+"%"; } else { humidColumn.classList.add("xsmall", "dimmed"); humidColumn.innerHTML = weather.day.avghumidity+"%"; } humidColumn.innerHTML = weather.day.avghumidity+"%"; row.appendChild(humidColumn); weatherTable.appendChild(row); var imageUrl = weather.day.condition.icon; var weatherImage = "<img src="+imageUrl+" height=25px; width=25px;>"; if(this.config.image === false){ if (weather.day.condition.text != "undefined" || null){ var currentColumn = document.createElement("td"); if(weather.day.condition.text==='Sunny'){ currentColumn.classList.add("xsmall","bright","sun"); currentColumn.innerHTML = weather.day.condition.text; } else if (weather.day.condition.text==='Partly cloudy') { currentColumn.classList.add("xsmall","pcloudy"); currentColumn.innerHTML = weather.day.condition.text; } else if (weather.day.condition.text==='Overcast'){ currentColumn.classList.add("xsmall","overcast"); currentColumn.innerHTML = weather.day.condition.text; } else if (weather.day.condition.text==='Moderate or heavy rain shower') { currentColumn.classList.add("xsmall","modrain"); currentColumn.innerHTML = weather.day.condition.text; } else { currentColumn.classList.add("xsmall","bright"); currentColumn.innerHTML = weather.day.condition.text; } row.appendChild(currentColumn); weatherTable.appendChild(row); } } if(this.config.image === true){ var weatherIcon = document.createElement("td"); weatherIcon.innerHTML = weatherImage; row.appendChild(weatherIcon); weatherTable.appendChild(row); } large.appendChild(weatherTable); wrapper.appendChild(large); } return wrapper; }, });
export const dateFilter = (a,b) => a.dates[a.dates.length-1].start - b.dates[b.dates.length-1].start
import React, { Component } from 'react' import { StyleSheet } from 'quantum' import Header from './Header' const styles = StyleSheet.create({ self: { width: '100%', overflow: 'hidden', }, }) class Selector extends Component { static defaultProps = { base: [], update: [], filter: '', } constructor(props, context) { super(props, context) this.state = { base: props.base, update: props.update, } } componentWillReceiveProps(nextProps) { if (nextProps.base !== this.props.base) { this.setState({ base: nextProps.base }) } if (nextProps.update !== this.props.update) { this.setState({ update: nextProps.update }) } } onFilter = ({ target }) => { this.setState({ filter: target.value }) } getTitle() { return this.props.title } renderHeader() { const { filter } = this.state return ( <Header title={this.getTitle()} filter={filter} onFilter={this.onFilter} /> ) } renderItems() { return null } render() { return ( <div className={styles()}> {this.renderHeader()} {this.renderItems()} </div> ) } } export default Selector
import React, { Component } from 'react'; import { Navbar, Nav } from 'react-bootstrap'; import { Link } from 'react-router-dom'; import styled from 'styled-components'; export default class TopBar extends Component { constructor(props) { super(props) this.state = { } } render() { return ( <Div> <Navbar expand="lg" > <Navbar.Brand href="/"> <img alt="logo" style={styles.logo} src="https://s3-us-west-1.amazonaws.com/gregkalamdaryanbucket2/website_files/Logo.png"/> <span>Gregory Kalamdaryan </span><small>VFX Artist</small></Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="ml-auto" style={{display: 'flex', width: 400, justifyContent: 'space-between'}}> {/* <LinkContainer exact={true} to='/'> <Nav.Link >Home</Nav.Link> </LinkContainer> <LinkContainer to='/demo-reel'> <Nav.Link>Demo Reel</Nav.Link> </LinkContainer> <LinkContainer to='/other-works'> <Nav.Link>Other Works</Nav.Link> </LinkContainer> <LinkContainer to='/about'> <Nav.Link>About</Nav.Link> </LinkContainer> */} <Link to='/'> Home </Link> <Link to='/demo-reel'> Demo Reel </Link> <Link to='/other-works'> Other Works </Link> <Link to='/about'> About </Link> </Nav> </Navbar.Collapse> </Navbar> <Line></Line> </Div> ); } } const Line = styled.hr` border: 1px solid #3681f0; margin-top: 0; ` const Div = styled.div` position: fixed; top: 0; width: 100%; z-index: 100; ` const styles = { logo: { width: "90px", height: "60px" } }
import Vue from 'vue/dist/vue' import StarRating from 'vue-star-rating' var star = new Vue({ el: "#reviews-index", components: { 'star-rating': StarRating }, })
import React, {Component} from 'react'; import { Text, View, StyleSheet, ScrollView, TextInput, TouchableOpacity, FlatList, } from 'react-native'; import DataList from './DataList'; import {storeData} from '../utils/Method'; import AsyncStorage from '@react-native-community/async-storage'; import {Colors, FontSizes} from '../config/Theme'; export default class ToDoList extends Component { constructor(props) { super(props); this.state = { dataText: null, DataArry: [], }; } async componentDidMount() { const todoData = await this.getData(); if (todoData) { this.setState({DataArry: todoData}); } } getData = async () => { try { const jsonValue = await AsyncStorage.getItem('todoData'); return jsonValue != null ? JSON.parse(jsonValue) : null; } catch (e) { // error reading value } }; addData = () => { const {dataText, DataArry} = this.state; if (dataText) { var d = new Date(); const todo = { date: d.getFullYear() + '/' + d.getMonth() + '/' + d.getDate(), name: dataText, isDone: false, }; const updatedArray = [todo, ...DataArry]; this.setState({ DataArry: updatedArray, dataText: null, }); storeData('todoData', updatedArray); } }; deleteNote = (deleteIndex) => { const {DataArry} = this.state; const updatedData = DataArry.filter((item, index) => { return index !== deleteIndex; }); this.setState({ DataArry: updatedData, }); storeData('todoData', updatedArray); }; checkTodo = (value, idx) => { const {DataArry} = this.state; const updatedData = DataArry.map((item, index) => { if (index === idx) { return { ...item, isDone: value, }; } else { return item; } }); this.setState({ DataArry: updatedData, }); storeData('todoData', updatedData); }; renderitems = ({item, index}) => { return ( <DataList val={item} deletemethod={() => this.deleteNote(index)} checkTodo={(val) => this.checkTodo(val, index)} /> ); }; render() { return ( <View style={styles.container}> <View style={styles.header}> <Text style={styles.headerText}>ToDoApp</Text> </View> {/* <ScrollView style={styles.scrollContainer}>{Data}</ScrollView> */} <FlatList contentContainerStyle={{paddingBottom: 150}} data={this.state.DataArry} renderItem={this.renderitems} keyExtractor={(item, index) => index.toString()} /> <View style={styles.footer}> <TextInput style={styles.textinput} placeholder="add list" value={this.state.dataText} onChangeText={(text) => this.setState({dataText: text})} placeholderTextColor="white" /> </View> <TouchableOpacity onPress={this.addData} style={styles.addbutton}> <Text style={styles.addbuttontext}> +</Text> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, header: { backgroundColor: Colors.PRIMARY, alignItems: 'center', borderBottomWidth: 10, borderBottomColor: Colors.FADER_WHITE, }, headerText: { color: Colors.WHITE, fontSize: FontSizes.MEDIUM, padding: 26, }, scrollContainer: { flex: 1, marginBottom: 100, }, footer: { position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 10, }, textinput: { alignSelf: 'stretch', color: Colors.GREY, padding: 20, backgroundColor: Colors.BLACK, borderTopWidth: 2, borderTopColor: Colors.FADE_WHITE, }, addbutton: { position: 'absolute', zIndex: 2, right: 10, bottom: 12, backgroundColor: Colors.PRIMARY, width: 40, height: 40, borderRadius: 20, alignItems: 'center', justifyContent: 'center', elevation: 3, }, addbuttontext: { color: '#fff', fontSize: FontSizes.X_LARGE, right: 2, }, });
const { Model, DataTypes } = require("sequelize"); class Producer extends Model { static init(connection) { super.init( { name: DataTypes.STRING, email: DataTypes.STRING, phone: DataTypes.INTEGER, }, { sequelize: connection, } ); } static associate(models) { this.hasMany(models.Farms, { foreignKey: "producer_id", as: "farms", }); } } module.exports = Producer;
import React, { Fragment , useState, useEffect} from 'react'; import { animated, useSpring } from 'react-spring' import InputNumber from 'react-input-number'; import 'react-bootstrap-range-slider/dist/react-bootstrap-range-slider.css'; import RangeSlider from 'react-bootstrap-range-slider'; import './App.css'; const OFFSET = Math.random() const map = function (value, in_min, in_max, out_min, out_max) { console.log(value) console.log((value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min) if (value === 0) { console.log('00000') return out_min } return (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } function App() { const r = 200 const cx = 250 const cy = 250 const [state, setState] = useState({ x: 10, y: 10 }); const [num, setNum] = useState("Number of players"); const [power, setPower] = useState(0) const [acc, setAcc] = useState(0) const config = { mass: 50, tension: 200, friction: 200, precision: 0.001 } const [props, set] = useSpring(() => ({ transform: 'rotate(0deg)', immediate: false })) useEffect(() => { set({ from: { transform: `rotate(${map(acc, 0, 200, 0, 900)}deg)` }, transform: `rotate(${map(acc + power, 0, 200, 0, 900)}deg)`, immediate: false, config }) setAcc(acc + power) }, [power]) const rederItems = (numOfItems) => { let items = [] for (let i = 0; i < numOfItems; i++) { let xLength = Math.cos(2 * Math.PI * (i / numOfItems + OFFSET)) * (r - 5) let yLength = Math.sin(2 * Math.PI * (i / numOfItems + OFFSET)) * (r - 5) let txLength = Math.cos(2 * Math.PI * ((i + 0.5) / numOfItems + OFFSET)) * (r / 2) let tyLength = Math.sin(2 * Math.PI * ((i + 0.5) / numOfItems + OFFSET)) * (r / 2) items.push(<Fragment key={i}> <line className= "line" fill= "radial-gradient(circle, rgb(0, 0,0) 0%,rgb(0, 0, 0) 90%)" stroke='white' strokeWidth='7' x1={cx + xLength} y1={cy + yLength} x2={cx} y2={cy} /> <text x={cx + txLength} y={cy + tyLength} paddingTop="5px" fill="white" fontSize= "30px" fontFamily= "Aladin" transform={`rotate(${((i + 0.5) / numOfItems + OFFSET) * 360} ${cx + txLength}, ${cy + tyLength})`} >{i+1}</text> </Fragment>) } return items } return ( <div className = "body"> <link href='https://fonts.googleapis.com/css?family=Aladin' rel='stylesheet'></link> <h1 >Wicked Wheel</h1> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500" style={{ width: "300px", heigt: "300px"}}> <g fill=" #e60000" stroke="white" strokeWidth="10"> <circle cx="250" cy="250" r={r} /> </g> <animated.g style={{ transform: props.transform, transformOrigin: "center" }} > {rederItems(state.x)} </animated.g> <g fill="white"> <circle cx="250" cy="250" r="10" /> </g> <g fill="white"> <circle cx="250" cy="250" r="5" /> </g> <g fill="white" stroke="darkgrey" strokeWidth="2"> <polygon points="250,70 230,30 270,30" /> </g> </svg> <div className ="inputNr" > How many players? <div> <Slider axis="x" x={state.x} xmax={10} onChange={({ x }) => setState(state => ({ ...state, x }))} styles={{ active: { backgroundColor: 'orange' } }} ></Slider> </div></div> <PressButton setPower={setPower} style={{ height: "20vh" }}/> </div> ); } const PressButton = ({ setPower }) => { const [pressed, toggle] = useState(false) const [width, setWidth] = useState(0) const [props, set] = useSpring(() => ({ width: '0%', backgroundColor: 'hotpink' })) useEffect(() => { if (pressed) set({ from: { width: '0%', backgroundColor: 'white' }, to: { width: '100%', backgroundColor: "white" }, immediate: false, config: { duration: 1000 } }) else { setPower(parseInt(width*7)) set({ to: { width: '0%', backgroundColor: 'white' }, immediate: true }) } }, [pressed]) return <button className="main" onMouseDown={() => { toggle(!pressed); }} onMouseUp={() => { toggle(!pressed); }} onTouchStart={() => { toggle(!pressed); }} onTouchEnd={() => { toggle(!pressed); }} > <animated.div className="fill" style={{ width: props.width, background: props.backgroundColor }} /> <animated.div className="content">{props.width.interpolate(x => { setWidth(parseInt(x)) return x === '0%' ? "Press and hold to spin" :"" })}</animated.div> </button> } export default App;
import React from 'react'; import { Router, Route, hashHistory, IndexRoute } from 'react-router'; import App from './components/app' import Test from './components/test' export default ( <Router history={hashHistory}> <Route path="/" component={App} > <IndexRoute component={Test} /> </Route> </Router> );
'use strict'; let config = { // 服务端 host host: 'http://localhost:3000', // web 开发环境的 host webHost: 'http://localhost:8080', // 跨域白名单 whiteOrigins: [ 'http://localhost:8080', 'http://www.paidepaiper.top', 'http://www.paidepaiper.xyz' ] }; module.exports = config;
const words = new URLSearchParams(window.location.search); var loc = words.get('location'), cords; var currentUnixTime = Math.round(Date.now() / 1000), targetDate = new Date(); var timestamp = targetDate.getTime()/1000 + targetDate.getTimezoneOffset() * 60; var localDate, offsets; var formattedAd; var day, temp, rain, windy, cloudy; var locLower = loc.toLowerCase(); console.log(locLower); window.onload = function(){ document.getElementById('locationName').innerHTML = locLower; //'formattedAd' to display formal location; document.getElementsByClassName("content")[0].innerHTML = temp; displayLogic(); }; function displayLogic(){ if(day && !cloudy){ setBackgroundImage('bgday1.jpg'); setWeatherBoxOpacity('25%'); setWeatherBoxBackground('day.gif'); if(windy){ if(temp<60){ setMessage("Grab a jacket."); setWeatherBoxOpacity('35%'); setWeatherBoxBackground('windy2.gif'); }else{ setMessage("It's wonderful out."); setBackgroundImage('bgday2.jpg'); setWeatherBoxOpacity('35%'); setWeatherBoxBackground('windy1.gif'); } }else{ (temp>60 && temp<75)?setMessage("It's wonderful out."):setMessage("Enjoy your day."); } } if(day && cloudy){ setBackgroundImage('bgovercast.jpg'); setWeatherBoxOpacity('20%'); if (rain){ setMessage("Take an umbrella."); setWeatherBoxBackground('rainday.gif'); } else if(windy){ setWeatherBoxOpacity('20%'); setMessage("Enjoy your day."); setWeatherBoxBackground('windy3.gif'); }else{ setMessage("Enjoy your day."); } } if(!day){ setBackgroundImage('bgnight1.jpg'); setWeatherBoxOpacity('35%'); setMessage("The night is calm."); if(rain){ setWeatherBoxOpacity('20%'); setWeatherBoxBackground('rainnight.gif'); setMessage("It's a rainy night."); } else if(windy){ setBackgroundImage('bgnight2.jpg'); setWeatherBoxBackground('windy3.gif'); setMessage("It's a windy night."); }else{ setBackgroundImage('bgnight2.jpg'); document.getElementsByClassName("content")[0].style.color= "grey"; setWeatherBoxOpacity('20%'); setWeatherBoxBackground('moon.gif'); } } } function setBackgroundImage(s){ console.log("setting background to " + s); //s = "imgs/"+s; (if using local imgs) s = "https://res.cloudinary.com/jkrsn98/image/upload/v1586562326/weather/"+s; document.getElementById("weatherBody").style.backgroundImage= "url("+'\''+s+'\''+")"; } function setWeatherBoxOpacity(s){ console.log("setting weatherbox opacity to " + s); document.getElementsByClassName("weatherBox")[0].style.opacity= s; } function setWeatherBoxBackground(s){ console.log("setting weatherbox background to " + s); //s = "imgs/"+s; (if using local imgs) s = "https://res.cloudinary.com/jkrsn98/image/upload/v1586562326/weather/"+s; document.getElementsByClassName("weatherBox")[0].style.backgroundImage= "url("+'\''+s+'\''+")"; } function setMessage(s){ document.getElementsByClassName("msg")[0].innerHTML = s; } /* ------------------------------------------------------------------------------ Connecting to the APIs and getting the required data: ------------------------------------------------------------------------------ */ //Gets coordinates from user inputted location var googleURL = "https://maps.googleapis.com/maps/api/geocode/json?address=" + loc + "&key=AIzaSyBICDS3opgWm-qTJPBthMe0DU4gX58pJCE"; $.ajax({ async:false, url: googleURL, success: function(data){ console.log(data); cords = data.results[0].geometry.location.lat+","+data.results[0].geometry.location.lng; formattedAd = data.results[0].formatted_address; } }); //Gets local user time var googleURL2 ="https://maps.googleapis.com/maps/api/timezone/json?location="+ cords + "&timestamp=" + currentUnixTime + "&key=AIzaSyBICDS3opgWm-qTJPBthMe0DU4gX58pJCE"; $.ajax({ async:false, url: googleURL2, success: function(data){ console.log(data); offsets = data.dstOffset*1000+data.rawOffset*1000; localDate = new Date(timestamp * 1000 + offsets); day = (localDate.getHours() > 6 && localDate.getHours() < 20)?true:false; console.log("is day?" + day); } }); console.log("local date : " + localDate); console.log(cords); //Gets weather data. Requires a proxy for some reason (using "herokuapp")... var darkSkyURL = "https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/0640ebe06d6b9791120ae72443eef475/" + cords + ","+ currentUnixTime + "?exclude=minutely,hourly,daily,alerts,flags"; $.ajax({ async:false, url: darkSkyURL, success: function(data){ console.log(data); temp= Math.floor(data.currently.temperature); windy = Math.floor(data.currently.windSpeed)>9?true:false; rain = (data.currently.precipProbability)>.5?true:false; cloudy = (data.currently.cloudCover)>.45?true:false; console.log("windy?" + windy); console.log("cloudy?" + cloudy); console.log("rain: " + rain); console.log("temp: " + temp); } });
import React from "react" import Responsive from "react-responsive" import { Box } from "rebass" import styled, { ThemeProvider } from "styled-components" import Footer from "../components/footer" import Header from "../components/header" import { theme } from "../utils/styles" import { rhythm } from "../utils/typography" import Menu from "./menu" const Mobile = props => <Responsive {...props} maxWidth={899} /> const Main = styled.main` @media all and (min-width: 900px) { padding-block-start: 9rem; } ` export default ({ location, children }) => { // const rootPath = `${__PATH_PREFIX__}/` return ( <ThemeProvider theme={theme}> <Box id="outer-container"> <Mobile> <Menu location={location} /> </Mobile> <Box mx="auto" px={3} pb={3} pt={1} style={{ maxWidth: rhythm(35), overflowX: `hidden`, }} > <Header location={location} maxHeaderWidth={rhythm(35)} /> <Main id="page-wrap">{children}</Main> <Footer /> </Box> </Box> </ThemeProvider> ) }
// controller.js // This class handles input and converts it to control signals var inherits = require("inherits"); var extend = require("extend"); var EventEmitter = require("events").EventEmitter; // TODO https://developer.mozilla.org/en-US/docs/Web/Guide/API/Gamepad function ControlManager() { var self = this; this.setKeyConfig(); $(function(){ $(document).on("keydown", function(e){ self.onKeyDown(e); }); $(document).on("keyup", function(e){ self.onKeyUp(e); }); $("#chatbox").on("focus", function(e){ console.log("CHAT FOCUS"); self.inputContext.push("chat"); }); $("#chatbox").on("blur", function(e){ console.log("CHAT BLUR"); if (self.inputContext.top == "chat") self.inputContext.pop(); }); self.touchManager(); }) } inherits(ControlManager, EventEmitter); extend(ControlManager.prototype, { inputContext : ["game"], keys_config : { Up: [38, "Up", 87, "w"], Down: [40, "Down", 83, "s"], Left: [37, "Left", 65, "a"], Right: [39, "Right", 68, "d"], Interact: [13, "Enter", 32, " "], Cancel: [27, "Escape", 17, "Ctrl"], Run: [16, "Shift"], Menu: [8, "Backspace", 46, "Delete"], FocusChat: [191, "/"], }, keys_active : {}, keys_down : { Up: false, Down: false, Left: false, Right: false, Interact: false, FocusChat: false, Run: false, Cancel: false, }, pushInputContext: function(ctx) { this.inputContext.push(ctx); this.emit("inputContextChanged"); }, popInputContext: function(ctx) { if (!ctx || this.inputContext.top == ctx) { var c = this.inputContext.pop(); this.emit("inputContextChanged"); return c; } }, removeInputContext: function(ctx) { if (!ctx) return; var index = this.inputContext.lastIndexOf(ctx); if (index > -1) { this.inputContext.splice(index, 1); this.emit("inputContextChanged"); return ctx; } }, isDown : function(key, ctx) { if ($.isArray(ctx)) { var go = false; for (var i = 0; i < ctx.length; i++) go |= ctx[i]; if (!go) return; } else { if (this.inputContext.top != ctx) return; } return this.keys_down[key]; }, isDownOnce : function(key, ctx) { if ($.isArray(ctx)) { var go = false; for (var i = 0; i < ctx.length; i++) go |= ctx[i]; if (!go) return; } else { if (this.inputContext.top != ctx) return; } if( this.keys_down[key] == 1 ) { this.keys_down[key]++; //so no other check may pass this test return true; } }, setKeyConfig : function() { this.keys_active = extend(true, {}, this.keys_config); }, onKeyDown : function(e) { for (var action in this.keys_active) { var keys = this.keys_active[action]; for (var i = 0; i < keys.length; i++) { if (e.which == keys[i]) { // Key is now down! this.emitKey(action, true); } } } }, onKeyUp : function (e) { for (var action in this.keys_active) { var keys = this.keys_active[action]; for (var i = 0; i < keys.length; i++) { if (e.which == keys[i]) { // Key is now up! this.emitKey(action, false); } } } }, submitChatKeypress : function(key) { switch(key) { } }, emitKey : function(action, down) { if (this.keys_down[action] != down) { if (down) { this.keys_down[action]++; } else { this.keys_down[action] = 0; } this.emit("control-action", action, down); } }, _tick : function() { for (var name in this.keys_down) { if (this.keys_down[name] > 0) this.keys_down[name]++; } } }); ControlManager.prototype.touchManager = function() { var self = this; $(document).one("touchstart", function(){ $("html").addClass("touchmode"); if (!$("#touchcontrols").length) { function __map(btn, key) { btn.on("touchstart", function(e){ console.log("TOUCHSTART: ", key); e.preventDefault(); self.emitKey(key, true); }); btn.on("touchend", function(e){ console.log("TOUCHEND: ", key); e.preventDefault(); self.emitKey(key, false); }); btn.on("touchcancel", function(e){ console.log("TOUCHCANCEL: ", key); e.preventDefault(); self.emitKey(key, false); }); btn.on("touchmove", function(e){ console.log("TOUCHMOVE: ", key); e.preventDefault(); }) return btn; } $("<div>").attr("id", "touchcontrols") .append ( __map($("<div>").addClass("button").addClass("a"), "Interact") ).append ( __map($("<div>").addClass("button").addClass("b"), "Cancel") ).append ( __map($("<div>").addClass("button").addClass("menu"), "Menu") ).append ( __map($("<div>").addClass("button").addClass("run"), "Run") ).append ( $("<div>").addClass("dpad") .append ( __map($("<div>").addClass("button").addClass("up"), "Up") ).append ( __map($("<div>").addClass("button").addClass("down"), "Down") ).append ( __map($("<div>").addClass("button").addClass("left"), "Left") ).append ( __map($("<div>").addClass("button").addClass("right"), "Right") ) ).appendTo("body"); } }); } module.exports = new ControlManager();
import { describe, it } from 'mocha'; import React from 'react'; import { Link } from 'react-router'; import { shallow } from 'enzyme'; import { expect } from 'chai'; import App from './App'; describe('<App />', () => { const app = shallow(<App />); it('has link to chat', () => { expect(app.contains(<Link to="/chat">Chat</Link>)).to.equal(true); }); });
import { Button } from '@material-ui/core'; import React, { useState } from 'react'; import Main from './components/BMT/Main'; const App = () => { const [remittance, setRemittance] = useState(null); const switchRemittance = () => { switch (remittance) { case 1: return <Main />; case 2: return <h4>Under Maintanance!!!</h4>; default: return ( <> <Button onClick={() => setRemittance(1)} variant='outlined'> BMT </Button> <Button style={{ marginLeft: '20px' }} onClick={() => setRemittance(2)} variant='outlined' > City Express </Button> </> ); } }; return <>{switchRemittance()}</>; }; export default App;
const express = require('express'); const dotenv = require('dotenv'); const logger = require('./middelware/logger'); const morgan = require('morgan'); const color = require('colors'); const connectDB = require('./config/db'); // load env vars dotenv.config({ path: './config/config.env'}); const app = express(); // Body parser app.use(express.json()); //connect database connectDB(); // middle ware //app.use(logger); app.use(morgan('dev')); //route files const bootcamps = require('./routes/bootcamps') //mount routes app.use('/api/v1/bootcamp', bootcamps ); const PORT = process.env.PORT || 5000 ; app.listen(PORT, () => { console.log(`App listening on process.env.PORT ${process.env.PORT} or port ${PORT}!`); });
import { SEARCH_USER } from "./type"; export const searchUserMsg = (data)=>{ return (dispatch)=>{ dispatch({ type : SEARCH_USER, payload : data }) } }
var React = require('react'); var NavMenuButton = React.createClass({ render: function(){ return ( <div id='pf-nav-menu-btn' className={this.props.menuOpen ? 'pf-nav-menu-btn pf-nav-close-icon' : 'pf-nav-menu-btn pf-nav-open-icon'} onClick={this.props.handleClick}> </div>); } }); module.exports = NavMenuButton;
import React, { Component } from 'react'; //import logo from './logo.svg'; // src={logo} import { borderBox } from '../style-lib'; import { widthFlex } from '../style-lib'; import styled from 'styled-components'; const CheckList = styled.aside` padding: 30px; text-align: left; overflow-y: auto; min-height: 100vh; ${ borderBox() } ${ widthFlex('25%') } @media (max-width: 1200px) { ${ widthFlex('35%') } } @media (max-width: 420px) { display: none } ul { li { margin-top: 10px; font-size: .8rem; line-height: 1rem; &:first-child{ font-weight: bold; margin-top: 30px; } input { margin-right: 5px; &:checked { & + span{ text-decoration: line-through; font-style: italic; color: rgba(0,0,0,.5) } } } textarea { ${ borderBox() } resize: none; border: 1px solid rgba(0,0,0,.1); background: rgba(0,0,0,.05); border-radius: 4px; width: 100%; padding: 10px; } } } `; class Checklist extends Component { render() { return ( <CheckList> <h2>Task Checklist</h2> <ul> <li>Basic version</li> <li> <label> <input checked readOnly type="checkbox" /> <span> Create a search field with a (repo) typeahead, where user can type any github username and the search would return the list of users github repos </span> </label> </li> <li> <label> <input checked readOnly type="checkbox" /> <span> User can then select a repo from the typeahead dropdown and the app should display a graph of contributions per user for this repo (x axis users, y axis number of contributions) </span> </label> </li> <li> <label> <input checked readOnly type="checkbox" /> <span> Make sure to handle the case, when username does not exist or user has no repos </span> </label> </li> </ul> <ul> <li>Fancy version</li> <li> <label> <input checked readOnly type="checkbox" /> <span> Use ECMAScript 6 </span> </label> </li> <li> <label> <input checked readOnly type="checkbox" /> <span> Make it look nice design wise </span> </label> </li> </ul> <ul> <li>Additional info</li> <li> <label> <input checked readOnly type="checkbox" /> <span> API endpoints needed (repos and contributors) - e.g.: <textarea defaultValue="https://api.github.com/users/angular/repos" /> <textarea defaultValue="https://api.github.com/repos/angular/angular/contributors" /> </span> </label> </li> <li> <label> <input checked readOnly type="checkbox" /> <span> Feel free to use any other open API, that could make the assignment better/easier </span> </label> </li> </ul> <ul> <li>General guidelines</li> <li> <label> <input checked readOnly type="checkbox" /> <span>Project should be build with one of the Javascript frameworks/libraries of your choosing</span> </label> </li> <li> <label> <input checked readOnly type="checkbox" /> <span>The code should be readable and clearly commented when needed</span> </label> </li> <li> <label> <input checked readOnly type="checkbox" /> <span>The project should be pushed to a public github repository</span> </label> </li> <li> <label> <input checked readOnly type="checkbox" /> <span>You can use all the open source libraries you need</span> </label> </li> <li> <label> <input type="checkbox" /> <span>README.md should contain project documentation (how to run and build the project locally from scratch, project structure, gotchas,... anything worth mentioning)</span> </label> </li> <li> <label> <input checked readOnly type="checkbox" /> <span>The project should support IE10+, Android native browser 4.4+ and all modern browsers (current version - 1)</span> </label> </li> <li> <label> <input checked readOnly type="checkbox" /> <span>The UI should be responsive</span> </label> </li> <li> <label> <input checked readOnly type="checkbox" /> <span>HTML should be semantic</span> </label> </li> </ul> </CheckList> ); } } export default Checklist;
import template from './template'; import to from './to'; import fromUser from './from'; export default { template, to, from: fromUser, };
import React from "react"; import { QuizResult } from "./QuizResult"; import { Link } from "react-router-dom"; export const QuizCompleted = ({ result, questions, answers, isCorrect, isSelectedOption, }) => { return ( <div className="result-box"> <QuizResult result={result} /> {questions.map((question, questionIndex) => ( <div key={questionIndex}> <h2>{question.question}</h2> <div className="input-group"> {answers.map((answer, answerIndex) => ( <div style={{ backgroundColor: isCorrect( questionIndex, answerIndex ) ? "green" : isSelectedOption( questionIndex, answerIndex ) ? "red" : "intial", }} key={answerIndex} > <span className="quizCompleteButton"> {answer} </span> </div> ))} </div> </div> ))} <Link to="/" className="quizHover"> Start New Quiz </Link> </div> ); };
module.exports = function(app) { require('./application')(app); require('./site')(app); require('./notFound')(app); require('./helo')(app); };
const initState = { name: 'hazyzh', num: 11 } /** * todos reducer * @param {Array} [state=[]] initstate * @param {Object} action action * @return {object} same as the initstate */ const inofoReducers = (state = initState, action) => { switch (action.type) { case 'ADD_NUM': { return {...state, num: state.num + 1} } default: return state } } export default inofoReducers
'use strict' module.exports = function (sequelize, DataTypes) { var Pin = sequelize.define('Pin', { uid: DataTypes.STRING, name: DataTypes.STRING, title: DataTypes.STRING, hex: DataTypes.STRING, lat: DataTypes.DECIMAL, lng: DataTypes.DECIMAL, heading: DataTypes.INTEGER, pitch: DataTypes.INTEGER, zoom: DataTypes.INTEGER, userId: DataTypes.INTEGER }, { classMethods: { associate: function (models) { Pin.belongsTo(models.User, { foreignKey: 'userId', onDelete: 'CASCADE' }) } } }) return Pin }
console.log("connected"); function printReverse(arr){ for(var i=arr.length-1;i>=0;i--) console.log(arr[i]); } } printReverse([3,6,2,5]); function isUniform(arr){ var first=arr[0]; for(car i=1;i<arr.length;i++) { if(arr[i]!==first){ return false; } } return true; } isUniform([1,1,1]); isUniform([1,1,2]); function max(arr){ var max=arr[0]; for(var i=1; i<arr.length;i++){ if(arr[i]>max){ max=arr[i]; } } return max; } max([1,20,2,3,-99]); function sumArray(arr){ var total=0; for(var i=1;i<arr.length;i++) { if(arr[i]>max) { max=arr[i]; } } return max } sumArray([1,2,3]);
/* eslint-env mocha */ const color = require('../') const chai = require('chai') chai.should() const red = '\u001b[38;2;255;0;0m\u001b[10m' const redbg = '\u001b[48;2;255;0;0m\u001b[10m' describe('the color function', () => { it('should handle single red, green and blue values as well as # color codes and color names', () => { color('red').should.equal(red) color('#ff0000').should.equal(red) color(255, 0, 0).should.equal(red) color('red', 1).should.equal(redbg) color('green').should.equal(color(0, 128, 0)) }) })
define( [ "ember", "ember-data" ], function( Ember, DS ) { var get = Ember.get, nocache_url = "%@?_=%@"; function nocache( attr ) { return Ember.computed( attr, function() { return nocache_url.fmt( get( this, attr ), +new Date() ); }); } return DS.Model.extend({ large: DS.attr( "string" ), medium: DS.attr( "string" ), small: DS.attr( "string" ), template: DS.attr( "string" ), large_nocache: nocache( "large" ), medium_nocache: nocache( "medium" ), small_nocache: nocache( "small" ) }); });
var router = require("express").Router(); //allows joining of file names var path = require("path"); //returns the notes.html file //best practice is separate files //one file for these and one file for api routes router.get("/notes", function (req, res) { //.sendfile contatonates //belongs to the response object res.sendFile(path.join(__dirname, "../public/notes.html")); }); //returns the index.html file router.get("*", function (req, res) { res.sendFile(path.join(__dirname, "../public/index.html")); }); module.exports = router;
// @flow import * as React from 'react'; import { defaultTokens } from '@kiwicom/mobile-orbit'; import { View } from 'react-native'; import { type TranslationType } from '@kiwicom/mobile-localization'; import type { OnLayout } from '../types/Events'; import Text from './Text'; import StyleSheet from './PlatformStyleSheet'; import Price from './Price'; type Props = {| +startLabel: TranslationType | React.Element<typeof Price>, +startValue: number, +endLabel?: TranslationType | React.Element<typeof Price>, +endValue?: number, +max: number, +min: number, |}; type State = {| width: number, labelStartWidth: number, labelStartAtMax: boolean, labelEndWidth: number, paddingLeft: number, paddingRight: number, |}; export default class SliderLabels extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { width: 0, labelStartWidth: 0, labelStartAtMax: false, labelEndWidth: 0, paddingLeft: 0, paddingRight: 0, }; } componentDidMount() { if (this.props.endValue) { requestAnimationFrame(this.setPaddingForTwoLabels); } else { requestAnimationFrame(this.setPaddingForOneLabel); } } getMaxPadding = (gap: number): number => { return Math.floor( this.state.width - this.state.labelStartWidth - this.state.labelEndWidth - gap, ); }; calculateMarkerStartOffset = (): number => { const { min, max, startValue } = this.props; let val; if (startValue > max) { val = max; } else if (startValue < min) { val = min; } else { val = startValue; } return Math.round((val / (max - min)) * this.state.width); }; calculateMarkerEndOffset = (): number => { const { min, max, endValue } = this.props; if (!endValue) { return 0; } let val; if (endValue > max) { val = max; } else if (endValue < min) { val = min; } else { val = endValue; } const w = (val / (max - min)) * this.state.width; return Math.round(this.state.width - w); }; getStartLabelOffset = (): number => { const startMarkerOffset = this.calculateMarkerStartOffset(); const startLabelHalf = this.state.labelStartWidth / 2; return startMarkerOffset < startLabelHalf ? 0 : startMarkerOffset - startLabelHalf; }; isBelowMaxPadding = (value: number, gap: number = 0): boolean => { const maxPadding = this.getMaxPadding(gap); return value + gap < maxPadding; }; setPaddingForTwoLabels = (): void => { const startLabelOffset = this.getStartLabelOffset(); const endMarkerOffset = this.calculateMarkerEndOffset(); const endLabelHalf = this.state.labelEndWidth / 2; const endLabelOffset = endMarkerOffset < endLabelHalf ? 0 : endMarkerOffset - endLabelHalf; const isBelowMaxPadding = this.isBelowMaxPadding( startLabelOffset + endLabelOffset, 10, ); const hasOffsetChanged = this.state.paddingLeft !== startLabelOffset || this.state.paddingRight !== endLabelOffset; if (isBelowMaxPadding && hasOffsetChanged) { this.setState({ paddingLeft: startLabelOffset, paddingRight: endLabelOffset, }); } requestAnimationFrame(this.setPaddingForTwoLabels); }; setPaddingForOneLabel = (): void => { const startLabelOffset = this.getStartLabelOffset(); const isBelowMaxPadding = this.isBelowMaxPadding(startLabelOffset); const hasOffsetChanged = this.state.paddingLeft !== startLabelOffset; if (isBelowMaxPadding) { if (hasOffsetChanged) { this.setState({ paddingLeft: startLabelOffset, }); } if (this.state.labelStartAtMax) { this.setState({ labelStartAtMax: false }); } } else if (this.state.labelStartAtMax === false) { this.setState({ labelStartAtMax: true }); } requestAnimationFrame(this.setPaddingForOneLabel); }; saveFullWidth = (e: OnLayout) => { this.setState({ width: Math.floor(e.nativeEvent.layout.width) }); }; saveLabelStartWidth = (e: OnLayout) => { this.setState({ labelStartWidth: Math.floor(e.nativeEvent.layout.width) }); }; saveLabelEndWidth = (e: OnLayout) => { this.setState({ labelEndWidth: Math.floor(e.nativeEvent.layout.width) }); }; render() { return ( <View style={[ styles.sliderLabels, { paddingLeft: this.state.paddingLeft, paddingRight: this.state.paddingRight, justifyContent: this.state.labelStartAtMax ? 'flex-end' : 'space-between', }, ]} onLayout={this.saveFullWidth} > <View onLayout={this.saveLabelStartWidth}> <Text style={styles.label}>{this.props.startLabel}</Text> </View> {this.props.endLabel && ( <View onLayout={this.saveLabelEndWidth}> <Text style={styles.label}>{this.props.endLabel}</Text> </View> )} </View> ); } } const styles = StyleSheet.create({ sliderLabels: { width: '100%', flexDirection: 'row', marginTop: 10, marginBottom: 5, }, label: { fontSize: 14, color: defaultTokens.paletteBlueNormal, }, });
class APIFeatures { constructor(query, queryObject) { this.query = query; this.queryObject = queryObject; } filter() { //filtering and advanced filtering const excludeFieldsObj = { sort: 'sort', limit: 'limit', page: 'page', fields: 'fields', }; let queryObj = {}; for (let key in this.queryObject) { excludeFieldsObj[key] ? null : (queryObj[key] = this.queryObject[key]); } // console.log('check1'); let queryStr = JSON.stringify(queryObj); queryStr = queryStr.replace( /\b(gte|gt|lte|lt)\b/, ///advanced filtering (match) => `$${match}` ); this.query = this.query.find(JSON.parse(queryStr)); //returns query object to which methods like sorting can be added since it is available in iots prototype. //sorting return this; //to return the object to facilitate chaining of features object } sorting() { if (this.queryObject.sort) { let sortby = this.queryObject.sort.split(',').join(' '); this.query = this.query.sort(sortby); //sort('price ratingsAverage') } else { this.query = this.query.sort('-createdAt'); } return this; } limiting() { // //fields limiting if (this.queryObject.fields) { const fields = this.queryObject.fields.split(',').join(' '); console.log(fields); this.query = this.query.select(fields); //projjections of select fields // console.log(query); } else { this.query.select('-__v'); //exclude __v from all tours } return this; } paginate() { if (this.queryObject.page || this.queryObject.limit) { const page = this.queryObject.page * 1 || 1; const limit = this.queryObject.limit * 1 || 3; const skip = (page - 1) * limit; this.query = this.query.skip(skip).limit(limit); } return this; } } module.exports = APIFeatures;
console.log("Hello"); console.log("Apples"); console.log("This is a statement"); console.log("This is also a statement"); var myFunc = function (name, weather) { console.log('This is a statement'); console.log("Hello " + name + "."); console.log("It is " + weather + " today"); }; myFunc("Jeong", "sunny"); var defaultFunc = function (name, weather) { if (weather === void 0) { weather = "rainy"; } console.log("Hello " + name); console.log("It is " + weather + " today"); }; defaultFunc("Jeong"); var restParamFunc = function (name, weather) { var extraArgs = []; for (var _i = 2; _i < arguments.length; _i++) { extraArgs[_i - 2] = arguments[_i]; } console.log("Hello " + name + "."); console.log("It is " + weather + " today."); for (var i = 0; i < extraArgs.length; i++) { console.log("Extra Args: " + extraArgs[i]); } }; restParamFunc("Jeong", "gloomy", "one", "two", "Three"); // using functions as argument to other functions var otherFunc = function (nameFunc) { return ("Hello " + nameFunc() + "."); }; console.log(otherFunc(function () { return "Jeong"; })); // using arrow functions var arrowFunc = function (nameFunc) { return ("Hello " + nameFunc() + "."); }; var printName = function (nameFunc, printFunc) { return printFunc(arrowFunc(nameFunc)); }; printName(function () { return "Jeong"; }, console.log); // template strings var templateFunc = function (weather) { var msg = "It is " + weather + " today"; console.log(msg); }; templateFunc("awesome"); // array enumeration var myArray = [100, "Jeong", true]; myArray.forEach(function (value, index) { console.log("Index " + index + ": " + value); }); // built-in array methods var products = [ { name: "Hat", price: 24.5, stock: 10 }, { name: "Kayak", price: 289.99, stock: 1 }, { name: "Soccer Ball", price: 10, stock: 0 }, { name: "Running Shoes", price: 116.50, stock: 20 } ]; var totalValue = products.filter(function (item) { return item.stock > 0; }).reduce(function (prev, item) { return prev + (item.price * item.stock); }, 0); console.log("Total value: $" + totalValue.toFixed(2));
var passport = require('passport'), LocalStrategy = require('passport-local').Strategy, User = require('../models/User.js') //creating session for cookie, does login passport.serializeUser(function(user,done){ done(null, user.id) }) //takes cookie, translate, find id, find user with id, go to user page passport.deserializeUser(function(id,done){ User.findById(id, function(err,user){ done(err,user) }) }) //PASSPORT LOCAL Strategy //local sign-up passport.use('local-signup', new LocalStrategy({ usernameField: 'email', passwordField: 'password', passReqToCallback: true }, function(req, email, password, done){ User.findOne({'local.email': email}, function(err,user){ //creating error possibility //if there is a problem if(err) return done(err) //check password length if(password.length < 6) return done(null, false, req.flash('signupMessage', 'Please choose a password that is 6 characters or more.')) //if email user is taken if(user){ console.log("there's already a username"); return done(null,false, req.flash('signupMessage', 'This email is already taken. Please log in or use a different email.')) } //create newUser is above doesnt happen var newUser = new User() newUser.local.first_name = req.body.first_name newUser.local.last_name = req.body.last_name newUser.local.email = email newUser.local.password = password newUser.save(function(err){ if(err) throw err return done(null, newUser) }) }) })) //creating local log in: passport.use('local-login', new LocalStrategy({ usernameField: 'email', passwordField: 'password', passReqToCallback: true }, function(req,email,password,done){ //makesure that user exists by searching through DB: User.findOne({'local.email':email}, function(err,user){ if(err) return done(err) //no user email found, flash would say so if(!user) { return done (null, false, req.flash('loginMessage', 'Error: Cannot find user with '+email))} //passworld invalid if(!user.validPassword(password)) return done(null, false, req.flash('loginMessage', 'Error: Invalid Password')) return done(null,user) }) })) module.exports = passport
my.controller('allProjects',["$scope","$http" ,function($scope, $http){ var url= "http://localhost:3000/allprojects" $http({ url:url, method: "GET", isArray: true }) .success(function(data){ console.log(data) $scope.as= data.projects; console.log($scope.as) }) .error(function(data){ console.log("error found") }) }]);
//已经战胜 20.44 % 的 javascript 提交记录 //解决思路: 先通过二分法找到与target相等的位置,然后再分别找到与出现最早的位置和最晚的位置 //时间复杂度: O(logn) var searchRange = function(nums, target) { let len = nums.length; if(len === 0) return [-1,-1]; let left = 0; let right = len-1; let mid = left + parseInt((right-left)/2); while(mid<=len-1 && mid>=0 && left<right && nums[mid] !== target){ if(nums[mid] > target){ right = mid-1; }else if(nums[mid] < target){ left = mid+1; }else{ break; } mid = left + parseInt((right-left)/2); } if(nums[mid] === target){ let min = mid; let max = mid; while(min >= 0 && nums[min] === target){ min--; } while(max <= len-1 && nums[max] === target){ max++; } return [min+1,max-1]; }else{ return [-1,-1]; } }; let nums = [5,7,7,8,8,10]; let target = 6; console.log(searchRange(nums,target));
import Info from '@material-ui/icons/Info'; import Tilt from 'react-tilt'; import InfoOutlinedIcon from '@material-ui/icons/InfoOutlined'; import React from 'react'; import './navbar.css'; export const AboutButton = () => { return ( <Tilt className="Tilt aboutButton" options={{ max : 70 }} style={{}} > <div className="Tilt-inner"> <InfoOutlinedIcon /> </div> </Tilt> ); }
var view={ displayMessage: function(msg){ var messageArea = document.getElementById('messageArea'); messageArea.innerHTML = msg; $(messageArea).addClass('show'); var a = controller.guesses; setTimeout(function () { if ((!model.gameOver) && a == controller.guesses) {$(messageArea).removeClass('show');}}, 8000); }, displayHit:function(location){ var cell = document.getElementById(location); cell.setAttribute('class', 'hit'); }, displayMiss:function(location){ var cell = document.getElementById(location); cell.setAttribute('class', 'miss'); } }; var model = { boardSize:10, numShips: 10, shipLength: 3, shipsSunk:0, ShipsLive: 10, gameOver: false, ships:[ {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:4, heals: 4}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:3, heals: 3}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:3, heals: 3}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:2, heals: 2}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:2, heals: 2}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:2, heals: 2}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:1, heals: 1}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:1, heals: 1}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:1, heals: 1}, {locations: ['0', '0', '0' ], hits: ['', '', ''], space: [], Length:1, heals: 1}], generateShipLocations: function(){ var locations; for (var i = 0; i < this.numShips; i++){ this.shipLength = this.ships[i].Length; do { locations = this.generateShip(); }while(this.collision(locations)); this.ships[i].space = unique(this.spaceGeneration(locations)); this.ships[i].locations = locations; } }, generateShip: function(){ var direction = Math.floor(Math.random() * 2); var row, col; if (direction === 1){ row = Math.floor(Math.random() * this.boardSize); col = Math.floor(Math.random() * (this.boardSize - this.shipLength)); } else { row = Math.floor(Math.random() * (this.boardSize - this.shipLength)); col = Math.floor(Math.random() * this.boardSize); } var newShipLocations = []; for (var i = 0; i < this.shipLength; i++){ if (direction === 1){ newShipLocations.push(row + '' + (col + i)); } else{ newShipLocations.push((row + i) + '' + col); } } return newShipLocations; }, collision: function(locations){ console.log(locations); var a = false; for (var i=0; i < this.numShips; i++){ var ship = model.ships[i]; console.log(ship.space); for (var j = 0; j < locations.length; j++){ var s = (ship.space.indexOf(locations[j]) - 0) console.log(s); if (((ship.space.indexOf(locations[j])) - 0) >=0){ a = true; } } } console.log(a);return a; }, spaceGeneration: function(locations){ var space = []; var space2 = []; for (var i = 0; i < locations.length; i++){ loc = locations[i]; loc = loc - 11; for (var q = 0; q < 3; q++){ var s1 = ([(loc + q)]) var s2 =([(loc + q) + 10]); var s3 =([(loc + q) + 20]); if ((s1 >= 0) && (s1 <=9)){ s1 = '0' + s1; } if ((s2 >= 0) && (s2 <=9)){ s2 = '0' + s2; } if ((s3 >= 0) && (s3 <=9)){ s3 = '0' + s3; } space.push(s1); space.push(s2); space.push(s3); console.log(s1 + ' ,'+ s2 + ' ,'+ s3); }; if ((+locations [i]+1)%10 == 0){ for (var d = 0; d < space.length; d++){ if ((+space[d]) % 10 == 0){ space[d] = -99; } } } if ((+locations [i])%10 == 0){ for (var d = 0; d < space.length; d++){ if ((+space[d]+1) % 10 == 0){ space[d] = -99; } } } } return unique(space); }, fire: function(guess){ for (var i=0; i < this.numShips; i++){ var ship = this.ships[i]; var index = ship.locations.indexOf(guess); if (index >= 0){ ship.hits[index] = 'hit'; ship.heals = ship.heals - 1; view.displayHit(guess); view.displayMessage('Ранен! Еще жизней: '+ ship.heals ); if (this.isSunk(ship)){ model.shipsSunk++; model.ShipsLive = model.ShipsLive -1; view.displayMessage('Корабль потоплен! Еще кораблей: '+ model.ShipsLive ); console.log(model.ships[i].space.length); for (var q = 0; q < model.ships[i].space.length; q++){ var id = ship.space[q]; $('#' + id).addClass('miss'); console.log(id); } } return true; } } view.displayMiss(guess); view.displayMessage('Пусто'); return false }, isSunk: function(ship){ for (var i=0; i < ship.Length; i++){ if (ship.hits[i] !=='hit'){ return false; } } return true; } }; var controller = { guesses: 0, processGuess: function(guess){ var location = guess; this.guesses++; var hit = model.fire(location); if (hit && model.shipsSunk === model.numShips){ model.gameOver = true; view.displayMessage('Все корабли потоплены за ' + this.guesses + ' выстрелов'); } } } $(document).ready(function() { $("td").click(function () { if ((!model.gameOver) && (($(this).attr("class") == undefined))){ console.log($(this).attr("class")); controller.processGuess($(this).attr("id")); } }); }); function unique(arr) { var obj = {}; for (var i = 0; i < arr.length; i++) { var str = arr[i]; obj[str] = true; } return Object.keys(obj); } window.onload = model.generateShipLocations();
'use strict'; const _ = require('lodash'); const useragent = require('useragent'); const uaParser = require('ua-parser-js'); const seeagent = require('../lib'); const ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36'; const uas = []; for (let i = 0; i < 1000; i++) { uas.push(`${ua}.${i}`); } function getUA() { return uas[_.random(0, uas.length - 1)]; } let timesOptions = [10, 100, 10000, 100000]; seeagent.config({ // useragent default cache 5000 items size: 5000 }); console.log('1000 useragent samples, cache 5000 items\n') for (let times of timesOptions) { let counter = times; let start = Date.now(); while (counter--) { // useragent 做了缓存,TODO 研究一下 useragent.lookup(getUA()); } let end = Date.now(); console.log(`${times} times, useragent consume: ${end - start}ms`); counter = times; start = Date.now(); while (counter--) { uaParser(getUA()); } end = Date.now(); console.log(`${times} times, ua-parser-js consume: ${end - start}ms`); counter = times; start = Date.now(); while (counter--) { seeagent(getUA()); } end = Date.now(); console.log(`${times} times, seeagent consume: ${end - start}ms\n`); } // 比较结果 // [10]useragent consume: 4ms // [10]uaParser consume: 6ms // [100]useragent consume: 0ms // [100]uaParser consume: 8ms // [10000]useragent consume: 7ms // [10000]uaParser consume: 409ms // [100000]useragent consume: 95ms // [100000]uaParser consume: 4039ms
import React from 'react'; import Select from './Select'; import renderer from 'react-test-renderer'; import { shallow } from 'enzyme'; test('It renders the select component when you pass in an array of options', () => { const props = { name: 'Test', options: ['calico', 'pooch', 'spaghetti'], value: 'test', }; const component = renderer.create(<Select {...props} />); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); test('It renders the select component when you pass and object into options prop', () => { const props = { name: 'Test', value: 'test', chosenKey: '_id', chosenVal: 'breed', chosenText: 'breed', options: [{petType: 'dog', breed:'bulldog', _id: '12312312', petName: 'fluffy'}, {petType: 'cat', breed:'calico', _id: '123213', petName: 'meow'}] }; const component = renderer.create(<Select {...props} />); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); test('It renders the select component with an inline label if you pass the labelInline prop', () => { const props = { name: 'Tiff', value: 'Tiff', labelText: 'Select your pet', labelInline: true, chosenKey: 'petName', options: ['calico', 'pooch', 'spaghetti'], }; const component = renderer.create(<Select {...props} />); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); test('It calls the function that gets passed into handle change', () => { const props = { name: 'Tiff', value: 'Tiff', chosenKey: 'petName', options: [{petType: 'dog', petName: 'fluffy'}, {petType: 'cat', petName: 'meow'}] }; const mockHandleChange = jest.fn(); const select = shallow(<Select {...props} handleChange={mockHandleChange} />); select.find('select').simulate('change', {target: {value: 'fluffy'}}); expect(mockHandleChange).toHaveBeenCalled(); });
const { Entrypoint } = require('@pm2/io') const pm2 = require('pm2') class App extends Entrypoint { onStart (cb) { this._config = this.io.initModule({ events: ['adonis:hop'] }) pm2.connect((err) => { if (err) { return cb(err) } pm2.launchBus((err, bus) => { if (err) { return cb(err) } this._bus = bus cb() }) }) } onStop (_err, cb) { pm2.disconnect(cb) } sensors () { this._processes = new Map() this.io.gauge({ name: 'Processes', value: () => JSON.stringify([...this._processes.entries()].reduce((res, [name, ids]) => { res[name] = [...ids] return res }, {})) }) this._eventsCounter = this.io.counter({ name: 'Total broadcasted', unit: 'events' }) this._eventsMeter = this.io.meter({ name: 'Events recieved', unit: 'evts/sec' }) this._buildProcessList(() => { this._bus.on('process:event', this._onProcessEvent.bind(this)) for (const event of this._config.events) { this._bus.on(event, this._onBroadcast.bind(this, event)) } }) } _buildProcessList (cb) { pm2.list((err, list) => { if (err) { return cb(err) } list.forEach((proc) => this._addProcess(proc.pm2_env)) cb() }) } _onProcessEvent ({ process, event }) { if (event === 'online') { this._addProcess(process) } else if (event === 'exit') { this._deleteProcess(process) } } _onBroadcast (type, { process, data }) { if (!this._processes.has(process.name)) { return } this._processes.get(process.name).forEach((pid) => { if (pid === process.pm_id) { return } pm2.sendDataToProcessId(pid, { type, topic: 'broadcast', data }, (err) => { if (err) { return this.io.notifyError(err) } }) }) this._eventsCounter.inc() this._eventsMeter.mark() } _addProcess (proc) { if (proc.exec_mode !== 'cluster_mode') { return } if (!this._processes.has(proc.name)) { this._processes.set(proc.name, new Set()) } this._processes.get(proc.name).add(proc.pm_id) } _deleteProcess (proc) { if (!this._processes.has(proc.name)) { return } const ids = this._processes.get(proc.name) if (ids.delete(proc.pm_id) && ids.size === 0) { this._processes.delete(proc.name) } } } new App()
class Visualization extends ISteppable{ constructor(element) { super(); this.squareSize = 100; this.colors = ["#ff3232", "#32CD32", "#3232ff", "#ffa500"]; this.currentStep = 0; this.maxStep = 8; this.init(element); } init(element){ this.scene = new THREE.Scene(); // renderer this.renderer = new THREE.WebGLRenderer(); this.renderer.setClearColor( 0xffffff ); this.renderer.setSize(window.innerWidth, window.innerHeight, false); this.camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 1, 10000); let pos = new THREE.Vector3(500, 750, 500); this.camera.position.set(pos.x, pos.y, pos.z); // init controls this.controls = new THREE.OrbitControls( this.camera, element );// new THREE.TrackballControls( this.camera ); // this.controls.rotateSpeed = 8.0; // this.controls.zoomSpeed = 1.2; // this.controls.panSpeed = 0.8; // not sure what this is for this.controls.enableZoom = true; this.controls.enablePan = true; // right mouse => translates this.controls.enableDamping = true; this.controls.dampingFactor = 0.3; this.controls.keys = [ 65, 83, 68 ]; // a, s, d this.controls.addEventListener( 'change', this.render.bind(this) ); // document.body.insertBefore(this.renderer.domElement, $("#mathContainer").get(0).nextSibling); element.appendChild(this.renderer.domElement); this.cubeGeometry = new THREE.BoxGeometry(this.squareSize, this.squareSize, this.squareSize); this.materials = []; for(let i = 0; i < this.colors.length; i++){ var material = new THREE.MeshBasicMaterial({color: this.colors[i], wireframe: false, polygonOffset: true, polygonOffsetFactor: 1.0, polygonOffsetUnits: 5.0}); // needed to make EdgesHelper look good when rotating (otherwise edges go inside mesh) this.materials.push(material); } window.addEventListener( 'resize', this.onWindowResize.bind(this), false ); this.animate(); this.redraw(0); } clearScene(){ while(this.scene.children.length > 0) this.scene.remove(this.scene.children[0]); } onWindowResize(){ this.camera.aspect = window.innerWidth / window.innerHeight; this.camera.updateProjectionMatrix(); this.renderer.setSize( window.innerWidth, window.innerHeight, false); // this.controls.handleResize(); // not needed for OrbitControls this.render(); } animate(){ requestAnimationFrame(this.animate.bind(this)); TWEEN.update(); this.controls.update(); this.render(); } render() { // gets called from controls.change this.renderer.render(this.scene, this.camera); } createScene(step) { let blockSize = this.colors.length * this.squareSize; let margin = 100; let offset = new THREE.Vector3(-1, 0, -1).multiplyScalar((blockSize + margin)/2 ); let layers = this.colors.length; switch(step){ case 0: { let blockGeometry = new THREE.Geometry(); let blockGeomInit = false; if(typeof this.blockGeometry === 'undefined'){ blockGeomInit = true; } for(let i = 0; i < layers; i++){ for(let j = 0; j < i + 1; j++){ for(let k = 0; k < i + 1; k++){ let cube = new THREE.Mesh(this.cubeGeometry, this.materials[i]); let pos = new THREE.Vector3(j * this.squareSize, (layers - 1 - i) * this.squareSize, k * this.squareSize); cube.position.set(pos.x, pos.y, pos.z ); this.scene.add(cube); let edges = new THREE.EdgesHelper(cube, 0x000000); this.scene.add(edges); if(blockGeomInit){ cube.updateMatrix(); blockGeometry.merge(cube.geometry, cube.matrix); } } } } if(blockGeomInit){ this.blockGeometry = blockGeometry; this.blockGeometry.center(); this.blockGeometry.mergeVertices(); // removes duplicate vertices } } break; case 1: { let rotationTime = 3000, rotationDelay = 0; for(let i = 0; i < 3; i++){ let block = new THREE.Mesh(this.blockGeometry, this.materials[i]); let pos; if(i == 0){ pos = new THREE.Vector3(0, 0, 0); } else if(i == 1){ pos = new THREE.Vector3(blockSize + margin, 0, 0); let tween = new TWEEN.Tween(block.rotation) .to({ x: Math.PI/2, z: Math.PI/2}, rotationTime) .delay(rotationDelay) .start(); } else{ pos = new THREE.Vector3(0, 0, blockSize + margin); let tween = new TWEEN.Tween(block.rotation) .to({ x: -Math.PI / 2, y: Math.PI/2}, rotationTime) .delay(rotationDelay + rotationTime) .onComplete(() => {stepper.onForward();}) .start(); } pos.add(offset); block.position.set(pos.x, pos.y, pos.z ); this.scene.add(block); let edges = new THREE.EdgesHelper(block, 0x000000); this.scene.add(edges); } } break; case 2: case 3: { let translationTime = 2000; for(let i = 0; i < 3; i++){ let block = new THREE.Mesh(this.blockGeometry, this.materials[i]); let pos; if(i == 0){ pos = new THREE.Vector3(0, 0, 0); } else if(i == 1){ pos = new THREE.Vector3(blockSize + margin, 0, 0); block.rotation.x = Math.PI / 2; block.rotation.z = Math.PI / 2; if(step === 3){ let tween = new TWEEN.Tween(pos) .to(new THREE.Vector3(this.squareSize, 0, 0), translationTime) .onUpdate(() => { let p = pos.clone().add(offset); block.position.set(p.x, p.y, p.z); }) .onComplete(() => {stepper.onForward();}) .start(); } } else{ pos = new THREE.Vector3(0, 0, blockSize + margin); block.rotation.x = -Math.PI / 2; block.rotation.y = Math.PI / 2; } pos.add(offset); block.position.set(pos.x, pos.y, pos.z ); this.scene.add(block); let edges = new THREE.EdgesHelper(block, 0x000000); this.scene.add(edges); } } break; case 4: case 5: { let translationTime = 2000; for(let i = 0; i < 3; i++){ let block = new THREE.Mesh(this.blockGeometry, this.materials[i]); let pos; if(i == 0){ pos = new THREE.Vector3(0, 0, 0); } else if(i == 1){ pos = new THREE.Vector3(this.squareSize, 0, 0); block.rotation.x = Math.PI / 2; block.rotation.z = Math.PI / 2; } else{ pos = new THREE.Vector3(0, 0, blockSize + margin); block.rotation.x = -Math.PI / 2; block.rotation.y = Math.PI / 2; if(step === 5){ let tweenA = new TWEEN.Tween(pos) .to(new THREE.Vector3(0, this.squareSize, blockSize + margin), translationTime/2) .onUpdate(() => { let p = pos.clone().add(offset); block.position.set(p.x, p.y, p.z); }) let tweenB = new TWEEN.Tween(pos) .to(new THREE.Vector3(0, this.squareSize, 0), translationTime) .onUpdate(() => { let p = pos.clone().add(offset); block.position.set(p.x, p.y, p.z); }) .onComplete(() => {stepper.onForward();}); tweenA.chain(tweenB); tweenA.start(); } } pos.add(offset); block.position.set(pos.x, pos.y, pos.z ); this.scene.add(block); let edges = new THREE.EdgesHelper(block, 0x000000); this.scene.add(edges); } } break; case 6: { for(let i = 0; i < 3; i++){ let block = new THREE.Mesh(this.blockGeometry, this.materials[i]); let pos; if(i == 0){ pos = new THREE.Vector3(0, 0, 0); } else if(i == 1){ pos = new THREE.Vector3(this.squareSize, 0, 0); block.rotation.x = Math.PI / 2; block.rotation.z = Math.PI / 2; } else{ pos = new THREE.Vector3(0, this.squareSize, 0); block.rotation.x = -Math.PI / 2; block.rotation.y = Math.PI / 2; } pos.add(offset); block.position.set(pos.x, pos.y, pos.z ); this.scene.add(block); let edges = new THREE.EdgesHelper(block, 0x000000); this.scene.add(edges); } } break; case 7: case 8: { // build first two blocks for(let i = 0; i < 2; i++){ let block = new THREE.Mesh(this.blockGeometry, this.materials[i]); let pos; if(i == 0){ pos = new THREE.Vector3(0, 0, 0); } else if(i == 1){ pos = new THREE.Vector3(this.squareSize, 0, 0); block.rotation.x = Math.PI / 2; block.rotation.z = Math.PI / 2; } else{ pos = new THREE.Vector3(0, this.squareSize, 0); block.rotation.x = -Math.PI / 2; block.rotation.y = Math.PI / 2; } pos.add(offset); block.position.set(pos.x, pos.y, pos.z ); this.scene.add(block); let edges = new THREE.EdgesHelper(block, 0x000000); this.scene.add(edges); } // build bottom layers of third block let offset2 = new THREE.Vector3(-layers * this.squareSize, -this.squareSize/2, -layers * this.squareSize); for(let i = 0; i < layers; i++){ for(let j = 0; j < i + 1; j++){ for(let k = 1; k < i + 1; k++){ let cube = new THREE.Mesh(this.cubeGeometry, this.materials[2]); let pos = new THREE.Vector3(j * this.squareSize, (layers - 1 - k) * this.squareSize, i * this.squareSize); pos.add(offset2); cube.position.set(pos.x, pos.y, pos.z ); this.scene.add(cube); let edges = new THREE.EdgesHelper(cube, 0x000000); this.scene.add(edges); } } } // Split top row of third block into 2 half/size cubes if(typeof this.halfBlockGeometry === 'undefined'){ let halfCubeGeometry = new THREE.BoxGeometry(this.squareSize, this.squareSize/2, this.squareSize); let halfBlockGeometry = new THREE.Geometry(); for(let i = 0; i < layers; i++){ for(let j = 0; j < i + 1; j++){ let cube = new THREE.Mesh(halfCubeGeometry, this.materials[2]); let pos = new THREE.Vector3(j * this.squareSize, (layers - 1 - 0.25) * this.squareSize, i * this.squareSize); cube.position.set(pos.x, pos.y, pos.z ); cube.updateMatrix(); halfBlockGeometry.merge(cube.geometry, cube.matrix); } } this.halfBlockGeometry = halfBlockGeometry; this.halfBlockGeometry.center(); this.halfBlockGeometry.mergeVertices(); // removes duplicate vertices } let upperSquares; for(let i = 0; i < 2; i++){ let pos = offset2.clone().add(new THREE.Vector3(1.5 * this.squareSize, (2.75 + i/2) * this.squareSize, 1.5 * this.squareSize)); let block = new THREE.Mesh(this.halfBlockGeometry, this.materials[2]); block.position.set(pos.x, pos.y, pos.z ); this.scene.add(block); let edges = new THREE.EdgesHelper(block, 0x000000); this.scene.add(edges); if(i === 1) upperSquares = block; } if(step === 7){ let rotationTime = 2000, translationTime = 1000; let tweenA = new TWEEN.Tween(upperSquares.rotation) .to({ y: Math.PI}, rotationTime) let tweenB = new TWEEN.Tween(upperSquares.position) .to({ x: "+" + this.squareSize}, translationTime) let tweenC = new TWEEN.Tween(upperSquares.position) .to({ y: "-" + this.squareSize/2}, translationTime) .onComplete(() => {stepper.onForward();}); tweenA.chain(tweenB); tweenB.chain(tweenC); tweenA.start(); } else{ upperSquares.rotation.y = Math.PI; let pos = upperSquares.position.clone().add(new THREE.Vector3(this.squareSize, -this.squareSize/2, 0)); upperSquares.position.set(pos.x, pos.y, pos.z); } } break; } } redraw(step = this.currentStep){ this.currentStep = step; let _this = this; this.clearScene(); this.createScene(this.currentStep); this.render(); // render new scene } onStep(forward){ TWEEN.removeAll(); let ret = super.onStep(forward); return ret; } } // Tween.js // https://github.com/tweenjs/tween.js/blob/master/docs/user_guide.md
import React from 'react' import { connect } from 'react-redux' import { Grid, Icon } from 'semantic-ui-react' import { pushRoute, unavailable } from '../../../actions' const items = [{ icon: 'home', route: '/', feature: '首頁', },{ icon: 'food', route: '/food', feature: '飲食熱量紀錄', },{ icon: 'camera', route: '/camera', feature: '食物相機', },{ icon: 'bicycle', route: '/exercise', feature: '運動熱量消耗紀錄', },{ icon: 'group', route: '/activity', feature: '運動活動揪團', },] const Footer = ({ route, pushRoute, unavailablePopup }) => ( <div style={{ position: 'fixed', bottom: 0, width: '100%', height: '4rem', backgroundColor: 'white', borderTop: '1px', borderTopStyle: 'solid', borderTopColor: 'lightgray', }}> <Grid columns={5} padded relaxed textAlign={'center'} verticalAlign={'middle'}> <Grid.Row> {items.map( item => { const isOnRoute = route.path == item.route const onClick = item.route ? () => pushRoute(item.route) : () => unavailablePopup(item.feature) return <Grid.Column key={item.feature} onClick={onClick}> <Icon color={isOnRoute? 'teal': null} size={isOnRoute? 'big': 'large'} name={item.icon} /> </Grid.Column> })} </Grid.Row> </Grid> </div> ) export default connect( ({ route }) => ({ route }), dispatch => ({ pushRoute: (route) => dispatch(pushRoute(route)), unavailablePopup: (feature) => dispatch(unavailable(feature)), }) )(Footer)
myApp.factory('messages',function(){ var messages = {}; messages.list = [ { id: 0, text: "Welcome" }]; messages.add = function(message){ messages.list.push( { id: messages.list.length, text: message }); }; return messages; });
module.exports = (Plugin, BD, Vendor, v1) => { const {Api, Storage} = BD; let {$} = Vendor; const minDIVersion = '1.3'; if (!window.DiscordInternals || !window.DiscordInternals.version || window.DiscordInternals.versionCompare(window.DiscordInternals.version, minDIVersion) < 0) { const message = `Lib Discord Internals v${minDIVersion} or higher not found! Please install or upgrade that utility plugin. See install instructions here https://goo.gl/kQ7UMV`; Api.log(message, 'warn'); return (class EmptyStubPlugin extends Plugin { onStart() { Api.log(message, 'warn'); alert(message); return false; } onStop() { return true; } }); } const {monkeyPatch, WebpackModules, ReactComponents, getOwnerInstance, React, Renderer} = window.DiscordInternals; const moment = WebpackModules.findByUniqueProperties(['parseZone']); const Constants = WebpackModules.findByUniqueProperties(['Routes', 'ChannelTypes']); const GuildsStore = WebpackModules.findByUniqueProperties(['getGuild']); const UsersStore = WebpackModules.findByUniqueProperties(['getUser', 'getCurrentUser']); const MembersStore = WebpackModules.findByUniqueProperties(['getNick']); const UserSettingsStore = WebpackModules.findByUniqueProperties(['developerMode', 'locale']); const MessageActions = WebpackModules.findByUniqueProperties(['jumpToMessage', '_sendMessage']); const MessageQueue = WebpackModules.findByUniqueProperties(['enqueue']); const MessageParser = WebpackModules.findByUniqueProperties(['createMessage', 'parse', 'unparse']); const HistoryUtils = WebpackModules.findByUniqueProperties(['transitionTo', 'replaceWith', 'getHistory']); const PermissionUtils = WebpackModules.findByUniqueProperties(['getChannelPermissions', 'can']); const ModalsStack = WebpackModules.findByUniqueProperties(['push', 'update', 'pop', 'popWithKey']); const ContextMenuItemsGroup = WebpackModules.find(m => typeof m === "function" && m.length === 1 && m.toString().search(/className\s*:\s*["']item-group["']/) !== -1); ContextMenuItemsGroup.displayName = 'ContextMenuItemsGroup'; const ContextMenuItem = WebpackModules.find(m => typeof m === "function" && m.length === 1 && m.toString().search(/\.label\b.*\.hint\b.*\.action\b/) !== -1); ContextMenuItem.displayName = 'ContextMenuItem'; const ExternalLink = WebpackModules.find(m => typeof m === "function" && m.length === 1 && m.prototype && m.prototype.onClick && m.prototype.onClick.toString().search(/\.trusted\b/) !== -1); ExternalLink.displayName = 'ExternalLink'; const ConfirmModal = WebpackModules.find(m => typeof m === "function" && m.length === 1 && m.prototype && m.prototype.handleCancel && m.prototype.handleSubmit && m.prototype.handleMinorConfirm); ConfirmModal.displayName = 'ConfirmModal'; const BASE_JUMP_URL = 'https://github.com/samogot/betterdiscord-plugins/blob/master/v2/Quoter/link-stub.md'; class QuoterPlugin extends Plugin { // Life cycle constructor(props) { super(props); this.cancelPatches = []; this.quotes = []; this.copyKeyPressed = false; this.onCopyKeyPressed = this.onCopyKeyPressed.bind(this); this.onCopy = this.onCopy.bind(this); } onStart() { if (v1) { $ = Vendor.$; } Api.injectStyle(QuoterPlugin.styleId, QuoterPlugin.style); $(document).on("keydown.quoter", this.onCopyKeyPressed); $(document).on("copy.quoter", this.onCopy); // Embeds engine this.patchSendMessageWithEmbed(); this.patchRetrySendMessageFromOptionPopout(); this.patchRetrySendMessageFromContextMenu(); // Main extension point this.patchSendMessageForSplitAndPassEmbeds(); // UI this.patchJumpLinkClick(); this.patchEmbedDate(); this.patchMessageContextMenuRender(); this.patchMessageRender(); return true; } onStop() { Api.removeStyle(QuoterPlugin.styleId); $(document).off("keydown.quoter", this.onCopyKeyPressed); $(document).off("copy.quoter", this.onCopy); this.cancelAllPatches(); return true; } cancelAllPatches() { for (let cancel of this.cancelPatches) { cancel(); } } // Helpers static getCurrentChannel() { return getOwnerInstance($('.chat')[0], {include: ["Channel"]}).state.channel; } static getIdsFromLink(href) { const regex = new RegExp('^' + BASE_JUMP_URL + '\\?guild_id=([^&]+)&channel_id=([^&]+)&message_id=([^&]+)(?:&author_id=([^&]+))?$'); const match = regex.exec(href); if (!match) return null; return { guild_id: match[1], channel_id: match[2], message_id: match[3], author_id: match[4], }; } // Embeds engine patchSendMessageWithEmbed() { const cancel = monkeyPatch(MessageActions, '_sendMessage', { before: ({methodArguments: [channel, message]}) => { if (message.embed && message.embed.quoter) { monkeyPatch(MessageQueue, 'enqueue', { once: true, before: ({methodArguments: [action]}) => { if (action.type === 'send') { action.message.embed = message.embed; } } }); monkeyPatch(MessageParser, 'createMessage', { once: true, after: ({returnValue}) => { if (returnValue) { returnValue.embeds.push(message.embed); } } }); } } }); this.cancelPatches.push(cancel); } patchRetrySendMessageFromOptionPopout() { ReactComponents.get('OptionPopout', OptionPopout => { const cancel = monkeyPatch(OptionPopout.prototype, 'handleRetry', { before: this.patchCallbackPassEmbedFromPropsToSendMessage }); this.cancelPatches.push(cancel); this.cancelPatches.push(Renderer.rebindMethods(OptionPopout, ['handleRetry'])); }); } patchRetrySendMessageFromContextMenu() { const MessageResendItem = WebpackModules.findByDisplayName('MessageResendItem'); moment.locale(UserSettingsStore.locale); const cancel = monkeyPatch(MessageResendItem.prototype, 'handleResendMessage', { before: this.patchCallbackPassEmbedFromPropsToSendMessage }); this.cancelPatches.push(cancel); this.cancelPatches.push(Renderer.rebindMethods(MessageResendItem, ['handleResendMessage'])); } patchCallbackPassEmbedFromPropsToSendMessage({thisObject}) { if (thisObject.props.message && thisObject.props.message.embeds) { const embed = thisObject.props.message.embeds.find(embed => embed.quoter); if (embed) { monkeyPatch(MessageActions, '_sendMessage', { once: true, before: ({methodArguments: [channel, message]}) => { message.embed = embed; } }); } } } // Main extension point patchSendMessageForSplitAndPassEmbeds() { const cancel = monkeyPatch(MessageActions, 'sendMessage', { instead: ({methodArguments: [channelId, message], originalMethod, thisObject}) => { const sendMessageDirrect = originalMethod.bind(thisObject, channelId); const currentChannel = QuoterPlugin.getCurrentChannel(); const serverIDs = this.getSetting('noEmbedsServers').split(/\D+/); if (this.getSetting('embeds') && !serverIDs.includes(currentChannel.guild_id) && (currentChannel.isPrivate() || PermissionUtils.can(0x4800, {channelId}))) { this.splitMessageAndPassEmbeds(message, sendMessageDirrect); } else { const sendMessageFallback = QuoterPlugin.sendWithFallback.bind(null, sendMessageDirrect, channelId); this.splitMessageAndPassEmbeds(message, sendMessageFallback); } } }); this.cancelPatches.push(cancel); } // Send Logic static sendWithFallback(sendMessage, channelId, message) { if (message.embed) { const timestamp = moment(message.embed.timestamp); if (Storage.getSetting('utc')) timestamp.utc(); const author = Storage.getSetting('mention') ? `<@${message.embed.author.id}>` : message.embed.author.name; message.content += `\n*${author} - ${timestamp.format('YYYY-MM-DD HH:mm Z')}${message.embed.footer.text ? ' | ' + message.embed.footer.text : ''}*`; message.content += `\n${'```'}\n${MessageParser.unparse(message.embed.description, channelId).replace(/\n?(```((\w+)?\n)?)+/g, '\n').trim()}\n${'```'}`; message.content = message.content.trim(); message.embed = null; } sendMessage(message); } splitMessageAndPassEmbeds(message, sendMessage) { const regex = /([\S\s]*?)(::(?:re:)?quote(\d+)(?:-(\d+))?::)/g; let match, lastIndex = 0; const currChannel = QuoterPlugin.getCurrentChannel(); while (match = regex.exec(message.content)) { lastIndex = match.index + match[0].length; let text = match[1]; const embeds = []; const from_i = +match[3]; const to_i = +match[4] || from_i; if (to_i <= this.quotes.length) { for (let i = from_i; i <= to_i; ++i) { const quote = this.quotes[i - 1]; if (embeds.length > 0 && embeds[embeds.length - 1].author.id === quote.message.author.id && (!embeds[embeds.length - 1].image || !quote.message.attachments.some(att => att.width))) { this.appendToEmbed(embeds[embeds.length - 1], quote); } else { embeds.push(this.parseNewEmbed(quote, currChannel)); } } } else { text += match[2]; } text = text.trim() || ' '; if (embeds.length > 0) { for (let embed of embeds) { sendMessage(Object.assign({}, message, {content: text, embed})); text = ' '; } } else { sendMessage(Object.assign({}, message, {content: text})); } } if (lastIndex < message.content.length) { sendMessage(Object.assign({}, message, {content: message.content.substr(lastIndex)})); } for (let quote of this.quotes) { quote.message.quotedContent = undefined; } this.quotes = []; } appendToEmbed(embed, quote) { if (!embed.description) embed.description = quote.text.trim(); else embed.description += '\n' + quote.text.trim(); for (let attachment of quote.message.attachments) { if (attachment.width) { embed.image = attachment; } else { let emoji = '📁'; if (/(.apk|.appx|.pkg|.deb)$/.test(attachment.filename)) { emoji = '📦'; } if (/(.jpg|.png|.gif)$/.test(attachment.filename)) { emoji = '🖼'; } if (/(.zip|.rar|.tar.gz)$/.test(attachment.filename)) { emoji = '📚'; } if (/(.txt)$/.test(attachment.filename)) { attachment.filename = '📄'; } embed.fields.push({ name: `${this.L.attachment} #${embed.fields.length + 1}`, value: `${emoji} [${attachment.filename}](${attachment.url})` }); } } } parseNewEmbed(quote, currChannel) { const embed = { author: { id: quote.message.author.id, name: quote.message.nick || quote.message.author.username, icon_url: quote.message.author.avatar_url || new URL(quote.message.author.getAvatarURL(), location.href).href, }, footer: {}, timestamp: quote.message.timestamp.toISOString(), fields: [], color: quote.message.colorString && Number(quote.message.colorString.replace('#', '0x')), url: `${BASE_JUMP_URL}?guild_id=${quote.channel.guild_id || '@me'}&channel_id=${quote.channel.id}&message_id=${quote.message.id}&author_id=${quote.message.author.id}`, quoter: true }; if (currChannel.id !== quote.channel.id) { if (quote.channel.guild_id && quote.channel.guild_id !== '@me') { embed.footer.text = '#' + quote.channel.name; if (currChannel.guild_id !== quote.channel.guild_id) { embed.footer.text += ' | ' + GuildsStore.getGuild(quote.channel.guild_id).name } } else if (quote.channel.footer_text) { embed.footer.text = quote.channel.footer_text; } else { embed.footer.text = quote.channel.recipients .slice(0, 5) .map(id => currChannel.guild_id && MembersStore.getNick(currChannel.guild_id, id) || UsersStore.getUser(id).username) .concat(quote.channel.recipients.length > 5 ? '...' : []) .join(', '); if (quote.channel.name) { embed.footer.text = `${quote.channel.name} (${embed.footer.text})`; } else if (quote.channel.recipients.length === 1) { embed.footer.text = '@' + embed.footer.text; } } } this.appendToEmbed(embed, quote); return embed; } // UI patchEmbedDate() { ReactComponents.get('Embed', Embed => { const cancel = Renderer.patchRender(Embed, [ { selector: { className: 'embed-footer', child: { text: true, nthChild: -1 } }, method: 'replace', content: thisObject => moment(thisObject.props.timestamp).locale(UserSettingsStore.locale).calendar() } ]); this.cancelPatches.push(cancel); }); } patchJumpLinkClick() { const cancel = monkeyPatch(ExternalLink.prototype, 'onClick', { instead: ({thisObject, callOriginalMethod, methodArguments: [e]}) => { let ids; if (thisObject.props.href && (ids = QuoterPlugin.getIdsFromLink(thisObject.props.href))) { HistoryUtils.transitionTo(Constants.Routes.MESSAGE(ids.guild_id, ids.channel_id, ids.message_id)); e.preventDefault(); } else callOriginalMethod(); } }); this.cancelPatches.push(cancel); this.cancelPatches.push(Renderer.rebindMethods(ExternalLink, ['onClick'])); } patchMessageRender() { ReactComponents.get('Message', Message => { const Tooltip = WebpackModules.findByDisplayName('Tooltip'); const cancel = Renderer.patchRender(Message, [ { selector: { className: 'markup', }, method: 'before', content: thisObject => React.createElement(Tooltip, {text: this.L.quoteTooltip}, React.createElement("div", { className: "btn-quote", onClick: this.onQuoteMessageClick.bind(this, thisObject.props.channel, thisObject.props.message), onMouseDown: e => { e.preventDefault(); e.stopPropagation(); } })) } ]); this.cancelPatches.push(cancel); }); } patchMessageContextMenuRender() { ReactComponents.get('MessageContextMenu', MessageContextMenu => { const cancel = Renderer.patchRender(MessageContextMenu, [ { selector: { type: ContextMenuItemsGroup, }, method: 'append', content: thisObject => React.createElement(ContextMenuItem, { label: this.L.quoteContextMenuItem, hint: 'Ctrl+Shift+C', action: this.onQuoteMessageClick.bind(this, thisObject.props.channel, thisObject.props.message) }) } ]); this.cancelPatches.push(cancel); }); } // Listeners onCopyKeyPressed(e) { if (e.which === 67 && e.ctrlKey && e.shiftKey) { e.preventDefault(); const channel = QuoterPlugin.getCurrentChannel(); let text = this.quoteSelection(channel); text += this.getMentions(channel); if (text) { this.copyKeyPressed = text; document.execCommand('copy'); } } } onCopy(e) { if (!this.copyKeyPressed) { return; } e.originalEvent.clipboardData.setData('Text', this.copyKeyPressed); this.copyKeyPressed = false; e.preventDefault(); } onQuoteMessageClick(channel, message, e) { e.preventDefault(); e.stopPropagation(); const {$channelTextarea, oldText} = this.tryClearQuotes(); const citeFull = this.getSetting('citeFull'); let newText; if (QuoterPlugin.isMessageInSelection(message)) { newText = this.quoteSelection(channel); } else if (e.ctrlKey || e.shiftKey || citeFull && !e.altKey) { const group = QuoterPlugin.getMessageGroup(message); if (e.shiftKey) { newText = this.quoteMessageGroup(channel, group); } else { newText = this.quoteMessageGroup(channel, group.slice(group.indexOf(message))); } } else { newText = this.quoteMessageGroup(channel, [message]); } newText += this.getMentions(channel, oldText); if (newText) { if (!$channelTextarea.prop('disabled')) { const text = !oldText ? newText : /\n\s*$/.test(oldText) ? oldText + newText : oldText + '\n' + newText; $channelTextarea.val(text).focus()[0].dispatchEvent(new Event('input', {bubbles: true})); } else { const L = this.L; this.copyKeyPressed = newText; document.execCommand('copy'); ModalsStack.push(function(props) { // Can't use arrow function here return React.createElement(ConfirmModal, Object.assign({ title: L.canNotQuoteHeader, body: L.canNotQuoteBody, // confirmText: Constants.Messages.OKAY }, props)); }) } } } // Quote Logic tryClearQuotes() { const $channelTextarea = $('.content textarea'); const oldText = $channelTextarea.val(); if (!/::(?:re:)?quote\d+(?:-\d+)?::/.test(oldText)) { this.quotes = []; } return {$channelTextarea, oldText}; } static isMessageInSelection(message) { const selection = window.getSelection(); if (selection.isCollapsed) return false; const range = selection.getRangeAt(0); return !range.collapsed && $('.message').is((i, element) => range.intersectsNode(element) && getOwnerInstance(element, {include: ["Message"]}).props.message.id === message.id); } static getMessageGroup(message) { const $messageGroups = $('.message-group').toArray(); for (let element of $messageGroups) { const messages = getOwnerInstance(element, {include: ["MessageGroup"]}).props.messages; if (messages.includes(message)) { return messages; } } return [message]; } getMentions(channel, oldText) { let mentions = ''; if (this.getSetting('embeds') && this.getSetting('mention')) { for (let quote of this.quotes) { const mention = MessageParser.unparse(`<@${quote.message.author.id}>`, channel.id); if (!mentions.includes(mention) && (!oldText || !oldText.includes(mention))) { mentions += mention + ' '; } } } return mentions } quoteMessageGroup(channel, messages) { let count = 0; for (let message of messages) { if ((message.quotedContent || message.content).trim() || message.attachments.length > 0) { ++count; this.quotes.push({text: message.quotedContent || message.content, message, channel}); } } if (count > 1) { return `::quote${this.quotes.length - count + 1}-${this.quotes.length}::\n`; } else if (count === 1) { return `::quote${this.quotes.length}::\n`; } return ''; } quoteSelection(channel) { const range = getSelection().getRangeAt(0); const $clone = $(range.cloneContents()); const $markupsAndAttachments = $('.markup:not(.embed-field-value),.attachment-image,.embed-thumbnail-rich').filter((i, element) => range.intersectsNode(element)); const $markups = $markupsAndAttachments.filter('.markup'); if ($markups.length === 0 && $markupsAndAttachments.length === 0) { return ''; } const quotes = []; const $clonedMarkups = $clone.children().find('.markup:not(.embed-field-value)'); if ($markups.length === 0) { const quote = QuoterPlugin.getQuoteFromMarkupElement(channel, $markupsAndAttachments[0]); if (quote) { quote.message.quotedContent = quote.text = ''; quotes.push(quote); } } else if ($markups.length === 1) { const quote = QuoterPlugin.getQuoteFromMarkupElement(channel, $markups[0]); if (quote) { quote.message.quotedContent = quote.text = QuoterPlugin.parseSelection(channel, $clonedMarkups.add($('<div>').append($clone)).first()); quotes.push(quote); } } else { $markups.each((i, e) => { const quote = QuoterPlugin.getQuoteFromMarkupElement(channel, e); if (quote) { quotes.push(quote); } }); quotes[0].message.quotedContent = quotes[0].text = QuoterPlugin.parseSelection(channel, $clonedMarkups.first()); quotes[quotes.length - 1].message.quotedContent = quotes[quotes.length - 1].text = QuoterPlugin.parseSelection(channel, $clonedMarkups.last()); } let string = ''; const group = []; const processGroup = () => { if (group[0].re) { this.quotes.push(group[0]); string += `::re:quote${this.quotes.length}::\n`; } else { string += this.quoteMessageGroup(channel, group.map(g => g.message)); } }; for (let quote of quotes) { if (quote.text.trim() || quote.message.attachments.length > 0) { if (group.length === 0 || !group[0].re && !quote.re && $(quote.markup).closest('.message-group').is($(group[0].markup).closest('.message-group'))) { group.push(quote); } else { processGroup(); group.length = 0; group.push(quote); } } } if (group.length > 0) { processGroup(); } return string; } static parseSelection(channel, $markup) { $markup.find('a').each((i, e) => { const $e = $(e); $(e).html(`[${$e.text()}](${$e.attr('href')})`); }); $markup.find('pre').each((i, e) => { const $e = $(e); $e.html(`${$e.find('code').attr('class').split(' ')[1] || ''}\n${$e.find('code').text()}`); }); $markup.find('.emotewrapper').each((i, e) => { const $e = $(e); $e.html($e.find('img').attr('alt')); }); $markup.find('.emoji').each((i, e) => { const $e = $(e); if ($e.attr('src').includes('assets/')) { $e.html($e.attr('alt')); } if ($e.attr('src').includes('emojis/')) { $e.html(`<${$e.attr('alt')}${$e.attr('src').split('/').pop().replace('.png', '')}>`); } }); $markup.find('.edited,.timestamp,.username-wrapper').detach(); $markup.html($markup.html().replace(/<\/?pre>/g, "```")); $markup.html($markup.html().replace(/<\/?code( class="inline")?>/g, "`")); $markup.html($markup.html().replace(/<\/?strong>/g, "**")); $markup.html($markup.html().replace(/<\/?em>/g, "*")); $markup.html($markup.html().replace(/<\/?s>/g, "~~")); $markup.html($markup.html().replace(/<\/?u>/g, "__")); return MessageParser.parse(channel, $markup.text()).content } static getQuoteFromMarkupElement(channel, markup) { if ($(markup).closest('.embed').length > 0) { const $embed = $(markup).closest('.embed-rich'); const $embedAuthorName = $embed.find('.embed-author-name'); if ($embed.length > 0 && $embedAuthorName.attr('href').indexOf(BASE_JUMP_URL) === 0) { const ids = QuoterPlugin.getIdsFromLink($embedAuthorName.attr('href')); const embed = getOwnerInstance($embed[0], {include: ["Embed"]}).props; const attachments = $embed.find('.embed-field-value a').map((i, e) => ({ url: $(e).attr('href'), filename: $(e).text() })); if (embed.image) attachments.push(embed.image); return { re: true, message: { id: ids.message_id, author: { id: ids.author_id, username: '> ' + embed.author.name, avatar_url: embed.author.icon_url }, timestamp: moment(embed.timestamp), colorString: embed.color && '#' + embed.color.toString(16), attachments: attachments, content: embed.description, }, channel: { guild_id: ids.guild_id, id: ids.channel_id, footer_text: embed.footer && embed.footer.text, name: embed.footer && embed.footer.text ? embed.footer.text.substr(1).split(' | ')[0] : channel.name }, text: embed.description, markup } } } else { const props = getOwnerInstance(markup, {include: ["Message"]}).props; return { message: props.message, channel: props.channel, text: props.message.content, markup } } } // Resources static get style() { // language=CSS return ` .message-group .btn-quote { opacity: 0; -webkit-transition: opacity .2s ease; transition: opacity .2s ease; float: right; width: 16px; height: 16px; background-size: 16px 16px; cursor: pointer; user-select: none; background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 33 25"><path fill="#99AAB5" d="M18 6.5c0-2 .7-3.5 2-4.7C21.3.6 23 0 25 0c2.5 0 4.4.8 6 2.4C32.2 4 33 6 33 8.8s-.4 5-1.3 7c-.8 1.8-1.8 3.4-3 4.7-1.2 1.2-2.5 2.2-3.8 3L21.4 25l-3.3-5.5c1.4-.6 2.5-1.4 3.5-2.6 1-1.4 1.5-2.7 1.6-4-1.3 0-2.6-.6-3.7-1.8-1-1.2-1.7-2.8-1.7-4.8zM.4 6.5c0-2 .6-3.5 2-4.7C3.6.6 5.4 0 7.4 0c2.3 0 4.3.8 5.7 2.4C14.7 4 15.5 6 15.5 8.8s-.5 5-1.3 7c-.7 1.8-1.7 3.4-3 4.7-1 1.2-2.3 2.2-3.6 3C6 24 5 24.5 4 25L.6 19.5C2 19 3.2 18 4 17c1-1.3 1.6-2.6 1.8-4-1.4 0-2.6-.5-3.8-1.7C1 10 .4 8.5.4 6.5z"/></svg>') 50% no-repeat; margin-right: 4px } .message-group .btn-quote:hover { opacity: 1 !important } .theme-dark .btn-quote { background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 33 25"><path fill="#FFF" d="M18 6.5c0-2 .7-3.5 2-4.7C21.3.6 23 0 25 0c2.5 0 4.4.8 6 2.4C32.2 4 33 6 33 8.8s-.4 5-1.3 7c-.8 1.8-1.8 3.4-3 4.7-1.2 1.2-2.5 2.2-3.8 3L21.4 25l-3.3-5.5c1.4-.6 2.5-1.4 3.5-2.6 1-1.4 1.5-2.7 1.6-4-1.3 0-2.6-.6-3.7-1.8-1-1.2-1.7-2.8-1.7-4.8zM.4 6.5c0-2 .6-3.5 2-4.7C3.6.6 5.4 0 7.4 0c2.3 0 4.3.8 5.7 2.4C14.7 4 15.5 6 15.5 8.8s-.5 5-1.3 7c-.7 1.8-1.7 3.4-3 4.7-1 1.2-2.3 2.2-3.6 3C6 24 5 24.5 4 25L.6 19.5C2 19 3.2 18 4 17c1-1.3 1.6-2.6 1.8-4-1.4 0-2.6-.5-3.8-1.7C1 10 .4 8.5.4 6.5z"/></svg>') } .message-group .comment > div:hover .btn-quote, .message-group .system-message > div:hover .btn-quote { opacity: .4 } `; } static get styleId() { return "Quoter-plugin-style"; } get locales() { return { 'pt-BR': { quoteContextMenuItem: "Citar", quoteTooltip: "Citar", attachment: "Anexo", }, 'ru': { quoteContextMenuItem: "Цитировать", quoteTooltip: "Цитировать", attachment: "Вложение", canNotQuoteHeader: "Вы не можете цитировать в этот канал", canNotQuoteBody: "Код цитаты помещен в буфер обмена, Вы можете использовать его в другом канале. Также Вы можете воспользоватся комбинацией клавиш Ctrl+Shift+C, чтобы скопировать цытату выделеного текста.", }, 'uk': { quoteContextMenuItem: "Цитувати", quoteTooltip: "Цитувати", attachment: "Додаток", canNotQuoteHeader: "Ви не можете цитувати в цей канал", canNotQuoteBody: "Код цитити поміщений до буферу обміну, Ви можете використати його в іншому каналі. Також ви можете скористатися комбінацію клавиш Ctrl+Shift+C, щоб скопіювати цитату виділеного тексту.", }, 'en-US': { quoteContextMenuItem: "Quote", quoteTooltip: "Quote", attachment: "Attachment", canNotQuoteHeader: "You can not quote into this channel", canNotQuoteBody: "Quotation code placed into clipboard, you can use it in other channel. Also you can use Ctrl+Shift+C shortcut to copy quote of selected text.", } } } get L() { return new Proxy(this.locales, { get(locales, property) { return locales[UserSettingsStore.locale] && locales[UserSettingsStore.locale][property] || locales['en-US'][property] } }); } } window.jQuery = $; return QuoterPlugin; };
import React, { useState } from 'react'; import { ListItem, ListItemText, Typography, IconButton, Box, Popover, } from '@material-ui/core'; import DeleteIcon from '@material-ui/icons/Delete'; import EditIcon from '@material-ui/icons/Edit'; import { useSelector, useDispatch } from 'react-redux'; import CommentsBlock from './CommentsBlock'; import CommentForm from './CommentForm'; import { DELETE_COMMENT } from '../app/actions'; import RouteLink from './RouteLink'; function Comment(props) { const { id, message, user_id, commentable_id, commentable_type, created_at } = props; const user = useSelector((state) => state.userData.id) const dispatch = useDispatch(); const [showEditModal, setShowEditModal] = useState(null); return ( <ListItem style={{ paddingRight: 0, paddingLeft: 8 }}> <ListItemText> <RouteLink to={`/profiles/${user_id}`}>{`${user_id} `}</RouteLink> <Typography variant="caption" style={{ color: 'gray' }}>{new Date(created_at).toUTCString()}</Typography> <Typography paragraph>{message}</Typography> { user === user_id && ( <Box> <Popover open={Boolean(showEditModal)} onClose={() => setShowEditModal(null)} anchorEl={showEditModal}> <CommentForm defaultValue={message} edit id={id} type={commentable_type} onClose={() => setShowEditModal(null)}/> </Popover> <IconButton onClick={(event) => { setShowEditModal(event.currentTarget); }} size="small"> <EditIcon /> </IconButton> <IconButton size="small" onClick={() => { dispatch({ type: DELETE_COMMENT, payload: { id, commentable_id, commentable_type } }); }} > <DeleteIcon /> </IconButton> </Box> ) } <CommentsBlock id={id} type="comment"/> </ListItemText> </ListItem> ) } export default Comment;
import { Block, BlockTitle, Button, Col, Link, List, ListItem, Navbar, NavLeft, NavRight, NavTitle, Page, Card, Icon, Row, CardHeader, CardFooter, Stepper, CardContent, f7, } from "framework7-react"; import React from "react"; const StarForReviews = ({ starNumber }) => { return ( <div className="transform -translate-y-1"> <Icon f7={starNumber >= 1 ? "star_fill" : "star"} size="10px" color="yellow" ></Icon> <Icon f7={starNumber >= 2 ? "star_fill" : "star"} size="10px" color="yellow" ></Icon> <Icon f7={starNumber >= 3 ? "star_fill" : "star"} size="10px" color="yellow" ></Icon> <Icon f7={starNumber >= 4 ? "star_fill" : "star"} size="10px" color="yellow" ></Icon> <Icon f7={starNumber >= 5 ? "star_fill" : "star"} size="10px" color="yellow" ></Icon> </div> ); }; export default StarForReviews;
import HomeIcon from './img/home-7.svg'; import TVIcon from './img/tv-21.svg'; export default [ { name: 'Home', icon: HomeIcon }, { name: 'Manage TV Shows', icon: TVIcon } ]
import { CHANGE_SEARCH, LOAD_VENUES, LOAD_VENUES_SUCCESS, LOAD_VENUES_ERROR, LOCATION_CHANGED, } from './constants'; export function changeSearch(search) { return { type: CHANGE_SEARCH, search }; } export function loadVenues() { return { type: LOAD_VENUES, }; } export function venuesLoaded(payload, search) { return { type: LOAD_VENUES_SUCCESS, payload, search, }; } export function venuesLoadingError(error) { return { type: LOAD_VENUES_ERROR, error, }; } export function changeLocation(position) { return { type: LOCATION_CHANGED, payload: position }; }
import React from "react"; import { Typography } from '@material-ui/core'; export default function OComponent(props) { return ( <> <Typography variant="h1" style={{ color: "orange", fontWeight: 700 }}>O</Typography> </> ) }
import React from 'react'; import {NavigationContainer} from '@react-navigation/native'; import firebase from '@react-native-firebase/app'; import Routes from './src/routes'; const firebaseConfig = { apiKey: 'AIzaSyDFrLX-eiA37O30bHhxZPWu2CIQC6KKQMg', authDomain: 'meau-550bb.firebaseapp.com', databaseURL: 'https://meau-550bb.firebaseio.com', projectId: 'meau-550bb', storageBucket: 'meau-550bb.appspot.com', messagingSenderId: '1080192839844', appId: '1:1080192839844:web:b7d99abce60889ab16f631', }; // Initialize Firebase if (firebase.apps.length === 0) { firebase.initializeApp(firebaseConfig); } export default function meau() { return ( <NavigationContainer> <Routes /> </NavigationContainer> ); }
import axios from "axios"; const addCommentForm = document.getElementById("jsAddComment"); const commentList = document.getElementById("jsCommentList"); const commentNumber = document.getElementById("jsCommentNumber"); const addCommentButton = document.getElementById("jsAddCommentButton"); const removeCommentButton = document.querySelectorAll(".fa-times"); const findCommentId = async () => { let videoId = window.location.href.split("/videos/")[1]; videoId = videoId.replace("?", ""); const response = await axios({ url: `/api/${videoId}/findId`, method: "get", data: "", }); // const li = commentList.querySelector("li"); // console.log("li ID: ", li); console.log("findCommentId response: ", response); console.log("findCommentId response.data: ", response.data); }; const increaseNumber = () => { commentNumber.innerHTML = parseInt(commentNumber.innerHTML, 10) + 1; }; const sendComment = async (comment) => { let videoId = window.location.href.split("/videos/")[1]; videoId = videoId.replace("?", ""); const response = await axios({ url: `/api/${videoId}/comment`, method: "post", data: { comment, }, }); const li = commentList.querySelector("li"); console.log("li ID: ", li); console.log("response: ", response); findCommentId(); if (response.status === 200) { addComment(comment, response.data.commentId); } }; const removeComment = async (element, event) => { let videoId = window.location.href.split("/videos/")[1]; videoId = videoId.replace("?", ""); console.log("element.id:", element.id); const response = await axios({ url: `/api/${videoId}/delcomment`, method: "post", data: { commentId: element.id, }, }); console.log("response: ", response); if (response.status === 200) { //event.preventDefault(); //새로고침 방지 element.remove(); commentNumber.innerHTML = parseInt(commentNumber.innerHTML, 10) - 1; } }; const handleSubmit = (event) => { event.preventDefault(); //새로고침 방지 const commentInput = addCommentForm.querySelector("input"); const comment = commentInput.value; sendComment(comment); commentInput.value = ""; }; const handleRemoveComment = (event) => { console.log(event.path[1].id, this); const btn = event.target; const li = btn.parentNode; commentList.removeChild(li); removeComment(event.path[1], event); }; const addComment = (comment, commentId) => { const li = document.createElement("li"); const span = document.createElement("span"); const div = document.createElement("div"); const i = document.createElement("i"); li.setAttribute("id", commentId); div.classList.add("video__comment-box"); i.classList.add("fas"); i.classList.add("fa-times"); span.innerHTML = comment; div.append(span); li.append(div); li.append(i); commentList.prepend(li); li.addEventListener("click", handleRemoveComment); increaseNumber(); }; const init = () => { addCommentForm.addEventListener("submit", handleSubmit); addCommentButton.addEventListener("click", handleSubmit); removeCommentButton.forEach((element) => { element.addEventListener("click", handleRemoveComment); }); }; if (addCommentForm) { init(); }
import React, { Component } from 'react'; class WorkFooter extends Component { render() { return( <div className='footer'> {this.props.work.endnotes && <div className='notes'> <h6>End Notes</h6> <div dangerouslySetInnerHTML={{__html: this.props.work.endnotes}}> </div> </div>} </div> ) } } export default WorkFooter
const mongoose = require('mongoose'); const chai = require('chai'); const User = require('../src/users'); describe('/users', () => { beforeEach((done) => { User.deleteMany({}, () => { done(); }) .catch(error => done(error)); }); describe('POST /users', () => { it('creates a new user in the database', (done) => { chai.request(server) .post('/users') .send({ firstName: 'stevie', lastName: 'wonder', email: 'steviewonders@gmail.com', password: 'superstitious09', }) .end((error, res) => { console.log(res.body); expect(error).to.equal(null); expect(res.status).to.equal(201); User.findById(res.body._id, (err, users) => { expect(err).to.equal(null); expect(users.firstName).to.equal('stevie'); expect(users.lastName).to.equal('wonder'); expect(users.email).to.equal('steviewonders@gmail.com'); expect(res.body).not.to.have.property('password'); done(); }); }); }); }); });
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /* Record layout: * 00: ProtocolType * 01: Version_Major (MSB) * 02: Version_Minor (LSB) * 03: Epoch MSB * 04: Epoch LSB * 05: Sequence Number MSB * 06: Sequence Number (continued) * 07: Sequence Number (continued) * 08: Sequence Number (continued) * 09: Sequence Number (continued) * 10: Sequence Number LSB * 11: Length MSB * 12: Length LSB * 13+: SslCiphertext Fragment */ // cryptoutils let CryptoUtils = require("./CryptoUtils.js"); // enums let enums = require('./enums.js'); // constants const HEADER_LENGTH = 13; // const MAX_PLAINTEXT_FRAGMENT_LENGTH = 16384; const MAIN_COMPRESSEDTEXT_FRAGMENT_LENGTH = MAX_PLAINTEXT_FRAGMENT_LENGTH + 1024; const MAIN_CIPHERTEXT_FRAGMENT_LENGTH = MAIN_COMPRESSEDTEXT_FRAGMENT_LENGTH + 1024; // const MAX_EPOCH = (1 << 16) - 1; const MAX_SEQUENCE_NUMBER = (1 << 48) - 1; function DtlsRecord() { this.protocolType = null; this.dtlsVersion = null; this.epoch = null; this.sequenceNumber = null; this.fragment = null; } exports.createFromPlaintext = function(type, dtlsVersion, epoch, sequenceNumber, fragment) { // validate inputs // // type if (!enums.isProtocolTypeValid(type)) { throw new RangeError(); } // dtlsVersion if (!enums.isDtlsVersionValid(dtlsVersion)) { throw new RangeError(); } // epoch // note: all positive integers up to (2^16)-1 are valid for epoch if (typeof epoch !== "number") { throw new TypeError(); } else if ((epoch < 0) || (epoch > Math.pow(2, 16) - 1) || (Math.floor(epoch) != epoch)) { throw new RangeError(); } // sequenceNumber // note: all positive integers up to (2^48)-1 are valid for sequenceNumber if (typeof sequenceNumber !== "number") { throw new TypeError(); } else if ((sequenceNumber < 0) || (sequenceNumber > Math.pow(2, 48) - 1) || (Math.floor(sequenceNumber) != sequenceNumber)) { throw new RangeError(); } // fragment if (Object.prototype.toString.call(fragment) != "[object Uint8Array]") { throw new TypeError(); } else if (fragment.length > MAX_PLAINTEXT_FRAGMENT_LENGTH) { throw new RangeError(); } // create and initialize the new DtlsRecord object let result = new DtlsRecord(); result.protocolType = type; result.dtlsVersion = dtlsVersion; result.epoch = epoch; result.sequenceNumber = sequenceNumber; result.fragment = fragment; // return the new Dtls record object return result; } // NOTE: this function returns null if a complete record could not be parsed (and does not validate any data in the returned record) // NOTE: offset is optional (default: 0) exports.fromEncryptedBuffer = function(buffer, offset, bulkEncryptionAlgorithm, blockEncryptionKey, macAlgorithm, macSecret) { // use currentOffset to track the current offset while reading from the buffer let initialOffset; let currentOffset; // validate inputs // // offset if (typeof offset === "undefined") { initialOffset = 0; } else if (typeof offset !== "number") { // if the offset is provided, but is not a number, then return an error throw new TypeError(); } else if (offset >= buffer.length) { throw new RangeError(); } else { initialOffset = offset; } currentOffset = initialOffset; // buffer if (typeof buffer === "undefined") { throw new TypeError(); } else if (buffer === null) { // null buffer is NOT acceptable } else if (Object.prototype.toString.call(buffer) != "[object Uint8Array]") { throw new TypeError(); } else if (buffer.length - currentOffset < HEADER_LENGTH) { // buffer is not long enough for a full record; return null. return null; } // create the new DtlsRecord object let result = new DtlsRecord(); // if we are expecting an encrypted ciphertext (i.e. not NULL encryption), create a RandomIVLength now let randomIVLength = 0; if (bulkEncryptionAlgorithm !== enums.BulkEncryptionAlgorithm.NULL) { randomIVLength = enums.getBulkAlgorithmBlockSize(bulkEncryptionAlgorithm); } // parse buffer // // type (octet 0) result.protocolType = buffer[currentOffset]; currentOffset += 1; // dtlsVersion (octets 1-2) result.dtlsVersion = buffer.readUInt16BE(currentOffset); currentOffset += 2; // epoch (octets 3-4) result.epoch = buffer.readUInt16BE(currentOffset); currentOffset += 2; // sequenceNumber (octets 5-10) result.sequenceNumber = buffer.readUIntBE(currentOffset, 6); currentOffset += 6; // length (octets 11-12) let ciphertextLength = buffer.readUInt16BE(currentOffset); currentOffset += 2; // verify that the buffer length is long enough to fit the sslCiphertext if (buffer.length - currentOffset < ciphertextLength) { // if the buffer is not big enough, return null return null; } // randomIV let randomIV = null; if (randomIVLength < ciphertextLength) { randomIV = Buffer.alloc(randomIVLength); buffer.copy(randomIV, 0, currentOffset, currentOffset + randomIVLength); currentOffset += randomIVLength; // subtract the randomIVLength from the ciphertextLength (so that we do not try to include the randomIV in the ciphertext) ciphertextLength -= randomIVLength; } else { // invalid randomIVLength; assume an invalid packet randomIVLength = 0; return null; } // ciphertext let ciphertext = Buffer.alloc(ciphertextLength); buffer.copy(ciphertext, 0, currentOffset, currentOffset + ciphertextLength); currentOffset += ciphertextLength; // decrypt the ciphertext let compressedtext; if (bulkEncryptionAlgorithm === enums.BulkEncryptionAlgorithm.NULL || randomIV === null || randomIV.length === 0) { compressedtext = ciphertext; } else { if (!CryptoUtils.verifyCrypto()) return null; // decrypt with bulkEncryptionAlgorithm let bulkEncryptionAlgorithmAsString = enums.getBulkAlgorithmAsString(bulkEncryptionAlgorithm); let decryptionCrypto = CryptoUtils.crypto.createDecipheriv(bulkEncryptionAlgorithmAsString, blockEncryptionKey, randomIV); decryptionCrypto.setAutoPadding(false); let decryptData = decryptionCrypto.update(ciphertext); let finalBlock = decryptionCrypto.final(); compressedtext = Buffer.concat([decryptData, finalBlock]); if (compressedtext.length === 0) return null; // verify padding // NOTE: to ensure constant-time operation, we check every byte of the compressedtext--including non-padding bytes. let paddingLength = compressedtext[compressedtext.length - 1]; let paddingValueLength = 1; let paddingError = false; if (paddingLength + paddingValueLength > compressedtext.length) { paddingError = true; } if (paddingError) { for (let iPaddingByte = compressedtext.length - 1; iPaddingByte >= 0; iPaddingByte--) { if (compressedtext[iPaddingByte] != 0) { // do nothing useful } } } else { for (let iPaddingByte = compressedtext.length - 1; iPaddingByte > compressedtext.length - paddingLength - paddingValueLength - 1; iPaddingByte--) { if (compressedtext[iPaddingByte] != paddingLength) { paddingError = true; } } for (let iPaddingByte = compressedtext.length - paddingLength - paddingValueLength - 1; iPaddingByte >= 0; iPaddingByte--) { if (compressedtext[iPaddingByte] != 0) { // do nothing useful } } } // verify MAC hash regardless of if padding is valid or not let macHashError = false; // create a buffer which prepends the MAC info header let macHashLength = enums.getMacAlgorithmHashSize(macAlgorithm); let compressedtextWithoutMacOrPadding = compressedtext.slice(0, compressedtext.length - paddingLength - paddingValueLength - macHashLength); let macHash = compressedtext.slice(compressedtext.length - paddingLength - paddingValueLength - macHashLength, compressedtext.length - paddingLength - paddingValueLength) let bufferForMacCalculation = buildBufferForMacCalculation(result.epoch, result.sequenceNumber, result.protocolType, result.dtlsVersion, compressedtextWithoutMacOrPadding); // generate the MAC hash let macSecretAsBuffer = new Buffer(macSecret); let macHashVerify = CryptoUtils.crypto.createHmac('sha1', macSecretAsBuffer).update(bufferForMacCalculation).digest(); // compare MAC hash to macHashVerify for (let iMacHash = 0; iMacHash < macHashLength; iMacHash++) { if (macHashVerify[iMacHash] !== macHash[iMacHash]) { macHashError = true; } } // remove mac and hash from compressedtext compressedtext = compressedtextWithoutMacOrPadding; if (macHashError) { return null; } if (paddingError) { return null; } } // decompress the compressedtext // NOTE: compression is not allowed by our implementation; simply copy the compressedtext reference to the result's fragment variable in case we add compression in the future result.fragment = Buffer.alloc(compressedtext.length) compressedtext.copy(result.fragment, 0, 0, result.fragment.length); // return the new DtlsRecord object return {record: result, bytesConsumed: currentOffset - initialOffset}; } DtlsRecord.prototype.toEncryptedBuffer = function(bulkEncryptionAlgorithm, blockEncryptionKey, macAlgorithm, macSecret) { // compress the plaintext // // NOTE: compression is not allowed by our implementation; simply copy the fragment reference to the compressedtext variable in case we add compression in the future let compressedtext = this.fragment; // encrypt the compressedtext // let ciphertext; let randomIV = null; if (bulkEncryptionAlgorithm == enums.BulkEncryptionAlgorithm.NULL) { ciphertext = compressedtext; } else { if (!CryptoUtils.verifyCrypto()) return null; // generate an IV equal to the length of our cipher block let encryptionblockSize = enums.getBulkAlgorithmBlockSize(bulkEncryptionAlgorithm); randomIV = CryptoUtils.crypto.randomBytes(encryptionblockSize); // // create a buffer which prepends the MAC info header let bufferForMacCalculation = buildBufferForMacCalculation(this.epoch, this.sequenceNumber, this.protocolType, this.dtlsVersion, compressedtext); // generate the MAC hash let macSecretAsBuffer = new Buffer(macSecret); let macHash = CryptoUtils.crypto.createHmac('sha1', macSecretAsBuffer).update(bufferForMacCalculation).digest(); // // for encryption, append the MAC hash to the fragment and then append padding to the closest blocksize let bufferForEncryption = buildBufferForEncryption(compressedtext, macHash, enums.getBulkAlgorithmBlockSize(bulkEncryptionAlgorithm)); // // encrypt with bulkEncryptionAlgorithm let bulkEncryptionAlgorithmAsString = enums.getBulkAlgorithmAsString(bulkEncryptionAlgorithm); let encryptionCrypto = CryptoUtils.crypto.createCipheriv(bulkEncryptionAlgorithmAsString, blockEncryptionKey, randomIV); encryptionCrypto.setAutoPadding(false); let encryptData = encryptionCrypto.update(bufferForEncryption); let finalBlock = encryptionCrypto.final(); ciphertext = Buffer.concat([encryptData, finalBlock]); } // create our buffer (which we will then populate) let randomIVLength = (randomIV !== null ? randomIV.length : 0); let ciphertextLength = ciphertext.length; let result = Buffer.alloc(HEADER_LENGTH + randomIVLength + ciphertextLength); // use offset to track the current offset while writing to the buffer let offset = 0; // populate record header // // type (octet 0) result[offset] = this.protocolType; offset += 1; // dtlsVersion (octets 1-2) result.writeUInt16BE(this.dtlsVersion, offset); offset += 2; // epoch (octets 3-4) result.writeUInt16BE(this.epoch, offset); offset += 2; // sequenceNumber (octets 5-10) result.writeUIntBE(this.sequenceNumber, offset, 6); offset += 6; // length (octets 11-12) result.writeUInt16BE(ciphertextLength + randomIVLength, offset); offset += 2; // randomIV (octets 13+) if (randomIV !== null) { randomIV.copy(result, offset, 0, randomIVLength); offset += randomIVLength; } // ciphertext ciphertext.copy(result, offset, 0, ciphertextLength); offset += ciphertextLength; // return the buffer (result) return result; } function buildBufferForMacCalculation(epoch, sequenceNumber, protocolType, dtlsVersion, fragment) { let fragmentLength = fragment.length; let result = Buffer.alloc(8 /* epoch + sequenceNumber */ + 5 /* protocolType + dtlsVersion */ + fragmentLength); let offset = 0; // epoch (octets 0-1) result.writeUInt16BE(epoch, offset); offset += 2; // sequenceNumber (octets 2-7) result.writeUIntBE(sequenceNumber, offset, 6); offset += 6; // protocolType (octet 8) result[offset] = protocolType; offset += 1; // dtlsVersion (octets 9-10) result.writeUInt16BE(dtlsVersion, offset); offset += 2 // fragmentLength (octets 11-12) result.writeUInt16BE(fragmentLength, offset); offset += 2 // fragmentBuffer fragment.copy(result, offset, 0, fragmentLength); offset += fragmentLength; return result; } function buildBufferForEncryption(fragment, macHash, paddingBlockSize) { let nonPaddedLength = fragment.length + macHash.length + 1 /* +1 is for the padding length byte which goes _after_ the padding */; let numBlocks = Math.ceil(nonPaddedLength / paddingBlockSize); let paddedLength = numBlocks * paddingBlockSize; let paddingLength = paddedLength - nonPaddedLength; // let offset = 0; let result = Buffer.alloc(paddedLength); // fragment.copy(result, offset, 0, fragment.length); offset += fragment.length; // macHash.copy(result, offset, 0, macHash.length); offset += macHash.length; // the padding result.fill(paddingLength, offset, offset + paddingLength); offset += paddingLength; // paddingLength result[offset] = paddingLength; // return result; }
import './modal.css' import {AnimatePresence, motion} from "framer-motion"; import {forwardRef, useImperativeHandle, useState} from "react"; function SmallModal(props, ref) { const [open, setOpen] = useState(false) useImperativeHandle(ref, () => { return { add: () => setOpen(true), end: () => setOpen(false) } }) return <AnimatePresence> {open && <> <motion.div initial={{ opacity: 0, }} animate={{ opacity: 1, transition: { duration: .3 } }} exit={{ opacity: 0, }} onClick={() => setOpen(p => !p)} className="my-modal-backdrop"/> <motion.div initial={{ scale: 0 }} animate={{ scale: 1, transition: { duration: .3 } }} exit={{ scale: 1.1, }} className="my-modal-content-wrapper small-modal"> <motion.div className="my-modal-content">{props.children}</motion.div> </motion.div> </>} </AnimatePresence> } export default forwardRef(SmallModal)
import styles from './index.less' import 'braft-editor/dist/index.css' import 'braft-extensions/dist/code-highlighter.css' import React from 'react' import { Base64 } from 'js-base64' import ArticleComment from './ArticleComment' import BraftEditor from 'braft-editor' import CodeHighlighter from 'braft-extensions/dist/code-highlighter' import { Avatar, BackTop, Button, Col, Comment, Form, Icon, Input, message, Row } from 'antd' import { queryArticle } from '../../services/newBlog' import moment from 'moment' import { generateImgSrc as idcon } from '../../components/Img/DefaultAvatar' import { connect } from 'dva' // 代码高亮插件 BraftEditor.use(CodeHighlighter()) // 本页可解析的文章 parseType 标记 const parseType = 'draft-0.0.1' // 用 braft-editor 编写提交的文本在展示时有小bug, 需要修改相应 class const fixBraftBug = () => { // 清除高度, 默认是500px if (document.querySelector('.bf-content')) { document.querySelector('.bf-content').classList = '' } // 清除 .bf-hr .bf-media-toolbar, 当出现 <hr> 标签时, 显示异常 if (document.querySelectorAll('.bf-hr')) { document.querySelectorAll('.bf-hr') .forEach(ele => { ele.innerHTML = '<hr><br>' }) if (document.querySelector('.bf-hr')) { document.querySelector('.bf-hr').innerHTML = '' } } } // comment 评论 const Editor = ({ onChange, onSubmit, submitting, value }) => ( <div> <Form.Item> <Input.TextArea rows={ 4 } onChange={ onChange }/> </Form.Item> <Form.Item> <Button htmlType="submit" loading={ false } onClick={ onSubmit } type="primary" className="pull-right"> Add Comment </Button> </Form.Item> </div> ) class ViewBlog extends React.Component { constructor(props) { super(props) this.state = { author: { id: null, username: null, nickname: null, appId: null, avatar: null, }, articleInfo: { id: null, like: null, dislike: null, star: null, comment: null, read: null, }, title: null, createAt: null, blogId: this.props.match.params.blogId, editorState: BraftEditor.createEditorState(null), comments: this.props.comments, } } componentDidMount() { queryArticle(this.state.blogId) .then(resp => { if (resp && resp.data) { const article = resp.data if (article.parseType && parseType === article.parseType) { this.setState({ createAt: article.createAt, title: article.title, author: article.author, articleInfo: article.articleInfo, editorState: BraftEditor.createEditorState(`${ decodeURIComponent(Base64.decode(article.text)) }`), }) } else { message.error(`不能够渲染的文章类型 ${ article.parseType }`) } } }) this.props.dispatch({ type: 'testMockArticleComment/list_' }) } // 路由切换/手动改uri, 需要重新加载文章 componentWillReceiveProps(nextProps, nextContext) { const blogIdNew = nextProps.match.params.blogId if (blogIdNew !== this.props.match.params.blogId) { queryArticle(blogIdNew) .then(resp => { if (resp && resp.data) { const article = resp.data if (article.parseType && parseType === article.parseType) { this.setState({ createAt: article.createAt, title: article.title, author: article.author, articleInfo: article.articleInfo, editorState: BraftEditor.createEditorState(`${ decodeURIComponent(Base64.decode(article.text)) }`), }) } else { message.error(`不能够渲染的文章类型 ${ article.parseType }`) } } }) } } componentDidUpdate(prevProps, prevState, snapshot) { fixBraftBug() } render() { const { editorState } = this.state return ( <Row justify="space-around" type="flex"> <Col xxl={ 16 } xl={ 18 } lg={ 18 } span={ 24 }> <div style={ { backgroundColor: 'white', padding: '8px', } }> <div> <h1 style={ { textAlign: 'center' } }> <span style={ { fontSize: '32px' } }>{ this.state.title }</span></h1> </div> <div style={ { textAlign: 'center' } }> <div className={ styles.extra }> <Avatar src={ this.state.author.avatar ? this.state.author.avatar : idcon(this.state.author.username) } alt="alt" size="small"/> <a> { this.state.author.username } </a> 发布于 { moment(this.state.createAt) .format('YYYY-MM-DD HH:mm:ss') } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style={ { margin: '0 0.5em' } }> <Icon type="like-o"/> { this.state.articleInfo.like } </span> | <span style={ { margin: '0 0.5em' } }> <Icon type="dislike-o"/> { this.state.articleInfo.dislike } </span> | <span style={ { margin: '0 0.5em' } }> <Icon type="star-o"/> { this.state.articleInfo.star } </span> | <span style={ { margin: '0 0.5em' } }> <Icon type="message"/> { this.state.articleInfo.comment } </span>| <span style={ { margin: '0 0.5em' } }> <Icon type="read"/> { this.state.articleInfo.read } </span> </div> </div> <BraftEditor value={ editorState } controls={ [] } readOnly="true" /> </div> <hr/> <div style={ { backgroundColor: 'white', padding: '10px 40px', } }> <Comment avatar={ <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" alt="Han Solo" /> } content={ <Editor value=""/> } /> <ArticleComment comments={ this.props.comments } pagination={ { onChange: (page, pageSize) => { this.props.dispatch({ type: 'testMockArticleComment/list_', payload: { page, pageSize, }, }) }, pageSize: this.props.comments.pageSize, total: this.props.comments.total, } }/> </div> </Col> <BackTop/> </Row> ) } } export default connect(state => { return state.testMockArticleComment })(ViewBlog)
import React, { useState } from 'react' import { PostService } from '../../../services/post.service'; function CommentAdd({postId,onCommentAdd}) { const [content, setContent] = useState(''); async function submit(e) { e.preventDefault(); const comment = await PostService.addComment(postId, content); onCommentAdd(comment); setContent(''); } return( <form onSubmit={submit}> <div className="mb-2"> <textarea onChange={(e) =>setContent(e.target.value)} className="form-control" value= {content}> </textarea> </div> <button className="form-control">submit</button> </form> ) } export default CommentAdd;
'use strict'; import { STORE_BANKS_DATA } from '../actions/actionTypes'; import { ListView } from 'react-native'; const initialState = { banksList: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}) }; export default function rates(state = initialState, action) { if (action.type === 'STORE_BANKS_DATA') { return { ...state, ...action.payload }; } return state; };
$(function(){ //页面加载完成之后执行 //pageInit();//ajax获取数据 //myPageInit();//本地数据 pageInitCustom();//自定义数据解析 }); //formatter:对列进行格式化时设置的函数名 function editFormaterLiner(cellValue, options, rowObject) { console.log(options); if (cellValue) { return "<a href='javascript:void(0);' data-val='" + JSON.stringify(rowObject) + "' onclick=\"jqGridEditRow(this,'" + options.rowId + "');\">" + cellValue + "</a>"; } else { return "空字符串"; } } function jqGridEditRow(e, obj) {//e==>this,当前<a>标签对象;obj==>options.rowId var rowData = JSON.parse($(e).attr("data-val")); alert(rowData+"\n"+obj); } function action(cellValue, options, rowObject) { return "<a href='javascript:void(0)'>编辑</a>"; } /*________________________________________________ajax获取数据___________________________________________________________________**/ function pageInit(){ //创建jqGrid组件 $("#dataTable").jqGrid({ url : 'data/JSONData.json',//组件创建完成之后请求数据的url mtype : "get",//向后台请求数据的ajax的类型。可选post,get datatype : "json",//请求数据返回的类型。可选json,xml,txt loadComplete: function (data) { console.log("Grid Load Data Complete",data);},//当从服务器返回响应时执行,xhr:XMLHttpRequest 对象 colNames : [ '序号', '日期', '客户', '金额', '税金','合计', '备注' ],//jqGrid的列显示名字 colModel : [ //jqGrid每一列的配置信息。包括名字,索引,宽度,对齐方式..... {name : '序号',index : 'id',width : 55,sorttype:'integer'},//sorttype用在当datatype为local时,定义搜索列的类型,可选值:int/integer - 对integer排序float/number/currency - 排序数字;date - 排序日期;text - 排序文本 {name : '日期',index : 'date',width : 90}, {name : '客户',index : 'client',width : 100,formatter:editFormaterLiner},//formatter:对列进行格式化时设置的函数名 一定要有返回值 {name : '金额',index : 'amount',width : 80}, {name : '税金',index : 'tax',width : 80}, {name : '合计',index : 'total',width : 80}, {name : '备注',index : 'note',width : 150} ], jsonReader : {//Json数据:需要定义jsonReader来跟服务器端返回的数据做对应,其默认值: root: "rows",//包含实际数据的数组 page: "page",//当前页 total: "total",//总页数 records: "records",//查询出的记录数 repeatitems: true,//repeatitems :指明每行的数据是可以重复的,如果设为false,则会从返回的数据中按名字来搜索元素,这个名字就是colModel中的名字 cell: "cell",//当前行的所有单元格 id: "id",//当前行id userdata: "userdata",//用户数据(user data) 在某些情况下,我们需要从服务器端返回一些参数但并不想直接把他们显示到表格中,而是想在别的地方显示,那么我们就需要用到userdata标签 subgrid: { root:"rows", repeatitems: true, cell:"cell" }, }, height:"auto",//表格高度,可以是数字,像素值或者百分比 //width:800, "auto"//如果设置则按此设置为主,如果没有设置则按colModel中定义的宽度计算 rowNum : 13,//一页显示多少条 在grid上显示记录条数,这个参数是要被传递到后台 hidegrid:false,//启用或者禁用控制表格显示、隐藏的按钮,只有当caption 属性不为空时起效 rowList : [ 5, 10, 20],//可供用户选择一页显示多少条 pager : '#pager',//表格页脚的占位符(一般是div)的id sortname : '序号',//初始化的时候排序的字段 默认的排序列。可以是列名称或者是一个数字,这个参数会被提交到后台 sortorder : "asc",//排序方式,可选desc降序,asc升序 viewrecords : true,//定义是否要显示总记录数 caption : "我的第一个jqGrid表格",//表格的标题名字 viewsortcols:[false,'vertical',true],//定义排序列的外观跟行为。数据格式:[false,'vertical',true].第一个参数是说,是否都要显示排序列的图标,false就是只显示 当前排序列的图标;第二个参数是指图标如何显示,vertical:排序图标垂直放置,horizontal:排序图标水平放置;第三个参数指单击功能,true:单击列可排序,false:单击图标排序。说明:如果第三个参数为false则第一个参数必须为true否则不能排序 onSortCol: function (index, iCol, sortorder)//onSortCol index,iCol,sortorder 当点击排序列但是数据还未进行变化时触发此事件。index:列索引index;iCol:当前单元格位置索引,从0开始;sortorder:排序状态:desc或者asc { //列排序事件 //console.log('index=>'+index +", iCol=>"+iCol +", sortorder=>"+sortorder); /* index=>id, iCol=>0, sortorder=>desc index=>date, iCol=>1, sortorder=>asc index=>client, iCol=>2, sortorder=>asc index=>amount, iCol=>3, sortorder=>asc index=>tax, iCol=>4, sortorder=>asc index=>total, iCol=>5, sortorder=>asc */ }, }); /*创建jqGrid的操作按钮容器*/ /*可以控制界面上增删改查的按钮是否显示*/ $("#dataTable").jqGrid('navGrid', '#pager', {edit : true,add :true,del : true}); //$("#dataTable").jqGrid('getGridParam', 'userData')//返回请求的参数信息 } /*________________________________________________本地数据获取___________________________________________________________________**/ function myPageInit(){ //这个例子告诉我们如何加载数组数据。在这里我们需要用到addRowData方法。 var myData=[ {"序号":"1","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"2","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"3","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"4","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"5","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"6","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"7","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"8","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"9","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"10","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"11","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"12","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"13","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"14","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"15","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"16","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"17","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"18","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"19","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"13","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"13","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"13","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"13","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"13","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"13","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"13","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"13","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"13","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, {"序号":"13","日期":"2007-10-06","客户":"Client 13","金额":"1000.00","税金":"0.00","合计":"1000.00","备注":""}, ]; //创建jqGrid组件 $("#dataTable").jqGrid({ data:myData, datatype : "local",//请求数据返回的类型。可选本地; colNames : [ '序号', '日期', '客户', '金额', '税金','合计', '备注','操作' ],//jqGrid的列显示名字 colModel : [ //jqGrid每一列的配置信息。包括名字,索引,宽度,对齐方式..... {name : '序号',index : 'id',width : 55,sorttype:'integer'},//sorttype用在当datatype为local时,定义搜索列的类型,可选值:int/integer - 对integer排序 float/number/currency - 排序数字;date - 排序日期;text - 排序文本 {name : '日期',index : 'date',width : 90,sortable:false}, {name : '客户',index : 'client',width : 100,sortable:false}, {name : '金额',index : 'amount',width : 80,sortable:false}, {name : '税金',index : 'tax',width : 80,sortable:false}, {name : '合计',index : 'total',width : 80,sortable:false}, {name : '备注',index : 'note',width : 150,sortable:false}, {name : '操作',index : 'action',width : 150,sortable:false,formatter:action} ], //userData:"userdata", height:"auto",//表格高度,可以是数字,像素值或者百分比 //width:800,//如果设置则按此设置为主,如果没有设置则按colModel中定义的宽度计算 rowNum : 2,//一页显示多少条 rowList : [ 10, 20, 30],//可供用户选择一页显示多少条 pager : '#pager',//表格页脚的占位符(一般是div)的id sortname : '序号',//初始化的时候排序的字段 sortorder : "asc",//排序方式,可选desc降序,asc升序 viewrecords : true,//定义是否要显示总记录数 caption : "我的第一个jqGrid表格",//表格的标题名字 }); /*创建jqGrid的操作按钮容器,可以控制界面上增删改查的按钮是否显示*/ $("#dataTable").jqGrid('navGrid', '#pager', {edit : true,add :true,del : true}); //$("#dataTable").jqGrid('getGridParam', 'userData')//返回请求的参数信息 //或者data:myData, /*for ( var i = 0; i <= myData.length; i++){ $("#dataTable").jqGrid('addRowData', i + 1, myData[i]); }*/ /* 这样就能生成一个jqgrid表格。 有时候我们需要动态的重新加载数据,其实这很简单,在此基础上只需要增加以下代码即可: $("#jqGrid_ds").jqGrid('clearGridData'); //清空表格 $("#jqGrid_ds").jqGrid('setGridParam',{ // 重新加载数据 datatype:'local', data : newdata, // newdata 是符合格式要求的需要重新加载的数据 page:1 }).trigger("reloadGrid"); */ } /*________________________________________________自定义数据解析_________________________________________________________________**/ function pageInitCustom(){ //创建jqGrid组件 $("#dataTable").jqGrid({ url : 'data/jsonCustomDataObj.json',//组件创建完成之后请求数据的url 或者'data/jsonCustomData.json', mtype : "get",//向后台请求数据的ajax的类型。可选post,get datatype : "json",//请求数据返回的类型。可选json,xml,txt loadComplete: function (data) { console.log("Grid Load Data Complete",data);},//当从服务器返回响应时执行,xhr:XMLHttpRequest 对象 colNames : [ '序号', '日期', '客户', '金额', '税金','合计', '备注' ],//jqGrid的列显示名字 colModel : [ //jqGrid每一列的配置信息。包括名字,索引,宽度,对齐方式..... {name : 'id',index : 'id',width : 55,sorttype:'integer'},//sorttype用在当datatype为local时,定义搜索列的类型,可选值:int/integer - 对integer排序float/number/currency - 排序数字;date - 排序日期;text - 排序文本 {name : 'date',index : 'date',width : 90,sortable:false}, {name : 'client',index : 'client',width : 100,sortable:false},//formatter:对列进行格式化时设置的函数名或者类型 {name : 'amount',index : 'amount',width : 80,sortable:false}, {name : 'tax',index : 'tax',width : 80,sortable:false}, {name : 'total',index : 'total',width : 80,sortable:false}, {name : 'note',index : 'note',width : 150,sortable:false} ], //userData:"userdata", jsonReader : {//Json数据:需要定义jsonReader来跟服务器端返回的数据做对应,其自定义如下值: root: "result",//包含实际数据的数组 page: "currpage",//当前页 total: "totalpages",//总页数 records: "totalrecords",//查询出的记录数 cell: "cell",//当前行的所有单元格 id: "id",//行id }, height:"auto",//表格高度,可以是数字,像素值或者百分比 //width:800, "auto"//如果设置则按此设置为主,如果没有设置则按colModel中定义的宽度计算 rowNum : 13,//一页显示多少条 在grid上显示记录条数,这个参数是要被传递到后台 hidegrid:false,//启用或者禁用控制表格显示、隐藏的按钮,只有当caption 属性不为空时起效 rowList : [ 5, 10, 20],//可供用户选择一页显示多少条 pager : '#pager',//表格页脚的占位符(一般是div)的id sortname : '序号',//初始化的时候排序的字段 默认的排序列。可以是列名称或者是一个数字,这个参数会被提交到后台 sortorder : "asc",//排序方式,可选desc降序,asc升序 viewrecords : true,//定义是否要显示总记录数 caption : "我的第一个jqGrid表格",//表格的标题名字 viewsortcols:[false,'vertical',true],//定义排序列的外观跟行为。数据格式:[false,'vertical',true].第一个参数是说,是否都要显示排序列的图标,false就是只显示 当前排序列的图标;第二个参数是指图标如何显示,vertical:排序图标垂直放置,horizontal:排序图标水平放置;第三个参数指单击功 能,true:单击列可排序,false:单击图标排序。说明:如果第三个参数为false则第一个参数必须为ture否则不能排序 onSortCol: function (index, iCol, sortorder)//onSortCol index,iCol,sortorder 当点击排序列但是数据还未进行变化时触发此事件。index:列索引index;iCol:当前单元格位置索引,从0开始;sortorder:排序状态:desc或者asc { //列排序事件 console.log('index=>'+index +", iCol=>"+iCol +", sortorder=>"+sortorder); /* index=>id, iCol=>0, sortorder=>desc index=>date, iCol=>1, sortorder=>asc index=>client, iCol=>2, sortorder=>asc index=>amount, iCol=>3, sortorder=>asc index=>tax, iCol=>4, sortorder=>asc index=>total, iCol=>5, sortorder=>asc */ }, }); /*创建jqGrid的操作按钮容器*/ /*可以控制界面上增删改查的按钮是否显示*/ $("#dataTable").jqGrid('navGrid', '#pager', {edit : true,add :true,del : true}); //$("#dataTable").jqGrid('getGridParam', 'userData')//返回请求的参数信息 }
import React from "react"; import "./Footer.css"; import TwitterIcon from "@material-ui/icons/Twitter"; import InstagramIcon from "@material-ui/icons/Instagram"; import FacebookIcon from "@material-ui/icons/Facebook"; import { NavLink } from "react-router-dom"; import Footer_data from "./F__Data"; export default function Footer() { return ( <div class="footer"> <span className="footer__title">Quizando</span> <div class="footer-content"> {Footer_data.fdata.map((item1, idx1) => { return ( <div className="footer-descr"> {item1.map((item2, idx2) => { return ( <NavLink to={item2.link} style={{ textDecoration: "none", color: "black" }} > <h2>{item2.title}</h2> </NavLink> ); })} </div> ); })} <div className="footer__payments"> <h2 className="footer__title">Connect with us:</h2> <div className="socials"> <TwitterIcon className="footer__social" /> <FacebookIcon className="footer__social" /> <InstagramIcon className="footer__social" /> </div> <h2 className="customer__support">Customer Support</h2> <div className="payment__options"> <img src="https://www.quizando.com/assets/visa.png" /> <img src="https://www.quizando.com/assets/mastercard.png" /> <img src="https://www.quizando.com/assets/PayPal.png" /> </div> </div> </div> <div className="copywrite"> <span> Quizando is a company operating in Malta with the registration number C-67170 and its registered office at Quizando, Web Matters Limited, Ferris Building Level 1, 1, St Luke's Rd G'Mangia, Pieta PTA 1020, Malta. </span> </div> <div className="footer__bottom"> <div className="footer__bottom__content"> <div className="left__section"> <img src="https://www.quizando.com/assets/Quizando-Logo.png" /> <span>Copyright © {new Date().getFullYear()}</span> </div> <img className="webmatters" src="https://www.quizando.com/assets/webmatters.png" /> </div> </div> </div> ); }
import React, { Component } from 'react'; import './App.css'; import TodoItem from './components/TodoItem' import arrdown from './image/icon/arrow-down.svg' class App extends Component { constructor() { super(); this.state = { toDoList: [ { title: "Đi Làm", isComplete: false }, { title: "Đi Chơi", isComplete: false }, { title: "Đi Ngủ", isComplete: false } ], inputValue: "" } this.onKeyUp = this.onKeyUp.bind(this); this.onChange = this.onChange.bind(this); } onItemClicked(item) { let toDoList = this.state.toDoList let index = toDoList.indexOf(item); return (event) => { this.setState({ toDoList: [ ...toDoList.slice(0, index), { ...item, isComplete: !item.isComplete }, ...toDoList.slice(index + 1) ] // toDoList: toDoList.map((action) => { // console.log('aa'); // return action !== item ? {...action} : {...action, isComplete: !action.isComplete}; // }) }) } } onKeyUp(event) { let toDoList = this.state.toDoList; let text = event.target.value; if (event.keyCode === 13) { if (!text) { return } text = text.trim(); if (!text) { return; } this.setState({ inputValue: "", toDoList: [ ...toDoList, { title: text, isComplete: false } ] }) } } onChange(event) { let text = event.target.value; this.setState({ inputValue: text }) } render() { const toDoList = this.state.toDoList; let inputValue = this.state.inputValue; return ( <div className="App"> <div className="Header"> <img src={arrdown} width={32} height={32} /> <input type="text" placeholder="Add the new item" value={inputValue} onChange={this.onChange} onKeyUp={this.onKeyUp} /> </div> {toDoList.length && toDoList.map((item, index) => <TodoItem key={index} item={item} onClick={this.onItemClicked(item)} /> ) } </div> ); } } export default App;
var foo = true; if (foo) { let bar = foo * 2; console.log( bar ); } console.log( bar ); // ReferenceError
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { addComment } from '../actions/commentAction'; class AddComment extends Component { state = { comment: '' }; onSubmit = event => { event.preventDefault(); this.props.addComment(this.state.comment); this.setState({ comment: '' }); }; onChange = event => { this.setState({ [event.target.name]: event.target.value }); }; render() { return ( <> <form onSubmit={this.onSubmit}> <label htmlFor="comment"> Add a comment : </label> <input type="text" id="comment" name="comment" value={this.state.comment} onChange={this.onChange} /> <button onClick={this.onClick}> Add </button> </form> </> ); } } export default connect( null, { addComment } )(AddComment);
months=['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; months_complete=['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']; var current_year = (new Date).getFullYear(); var current_month = (new Date).getMonth(); var current_day = (new Date).getDate(); var month_view = current_month; var year_view = current_year; var idglobal = 0; function get_content() { $.when( $.getScript(media_url+'js/aux/date.js'), $.ready.promise() ).then(function(){ $.post(base_url+'/partials/employees_admin_enterprise', function(template, textStatus, xhr) { $('#main').html(template); employees_list(); }); }); } function employees_list() { $.getJSON(api_url+'enterprises/list_employees?callback=?', function(data){ if(data.status=='success'){ var wrapper = $('#employees_list'); if(data.data.employees.length>0){ wrapper.empty(); var table_wrapper=$('<div></div>').attr('class','table-responsive'); wrapper.append(table_wrapper); var table=$('<table></table>').attr('class','table'); table_wrapper.append(table); var thead=$('<thead></thead>'); table.append(thead); var tr=$('<tr></tr>'); thead.append(tr); var th=$('<th></th>').text('Nombre'); tr.append(th); var th=$('<th></th>').text('Apellidos'); tr.append(th); var th=$('<th></th>').text('Email'); tr.append(th); var th=$('<th></th>').text('Teléfono'); tr.append(th); var th=$('<th></th>').text('Código'); tr.append(th); var th=$('<th></th>').text(''); tr.append(th); var tbody=$('<tbody></tbody>'); table.append(tbody); $.each(data.data.employees, function(index, employee) { if(employee.corporate_code.length==4) var clase = 'active'; else var clase = 'inactive'; var tr=$('<tr></tr>').attr({'class':clase, 'data-id':employee.id}); tbody.append(tr); var td=$('<td id="name'+employee.id+'"></td>').text(employee.name); tr.append(td); var td=$('<td id="surname'+employee.id+'"></td>').text(employee.surname); tr.append(td); var td=$('<td id="email'+employee.id+'"></td>').text(employee.email); tr.append(td); var td=$('<td id="phone'+employee.id+'"></td>').text(employee.phone); tr.append(td); var td=$('<td></td>').text(employee.corporate_code); tr.append(td); var td=$('<td></td>').attr({'class':'botonera'}); tr.append(td); var edit_btn = $('<span></span>').attr({'class':'button edit', 'title':'Editar empleado'}).html('<i class="fa fa-pencil-square-o fa-fw"></i>'); td.append(edit_btn); edit_btn.click(function(){ edit_employee(employee.id, this); }); var unlink_btn = $('<span></span>').attr({'class':'button unlink', 'title':'Desvincular empleado'}).html('<i class="fa fa-trash-o fa-fw"></i>'); td.append(unlink_btn); unlink_btn.click(function(){ unlink_employee(employee.id, this); }); if(clase=='active'){ var sendpin_btn = $('<span></span>').attr({'class':'button sendpin', 'title':'Enviar PIN'}).html('<i class="fa fa-paper-plane-o fa-fw"></i>'); td.append(sendpin_btn); sendpin_btn.click(function(){ sendpin_employee(employee.id, this); }); } var stadistics_btn = $('<span></span>').attr({'class':'button stadistics', 'title':'Estadísticas'}).html('<i class="fa fa-bar-chart-o fa-fw"></i>'); td.append(stadistics_btn); stadistics_btn.click(function(){ stadistics_employee(employee.auth_id, this); }); var authorize_btn = $('<span></span>').attr({'class':'button authorize', 'title':'Autorizar'}).html('<i class="fa fa-unlock fa-fw"></i>'); td.append(authorize_btn); authorize_btn.click(function(){ authorize_employee(employee.id, this); }); var ban_btn = $('<span></span>').attr({'class':'button ban', 'title':'Desautorizar'}).html('<i class="fa fa-ban fa-fw"></i>'); td.append(ban_btn); ban_btn.click(function(){ ban_employee(employee.id, this); }); var project_btn = $('<span></span>').attr({'class':'button project', 'title':'Proyectos'}).html('<i class="fa fa-sitemap fa-fw"></i>'); td.append(project_btn); project_btn.click(function(){ modal_projects(employee.id, this); }); $.getScript(media_url+'js/aux/modals.js', function(){ $.getScript(media_url+'js/aux/journeys.js', function(){ var historical_btn = $('<span></span>').attr({'class':'button project', 'title':'Histórico'}).html('<i class="fa fa-h-square fa-fw"></i>'); td.append(historical_btn); historical_btn.click(function(){ modal_passenger_details_enterprise(employee.id, this); }); }); }); }); } else wrapper.empty().html('<div class="notice full animated fadeInDown"><div class="icon"><i class="fa fa-frown-o"></i></div><div class="text">Sin empleados.</div></div>'); } else super_error('Locations failure'); }); } function modal_projects(id,element){ idglobal=id; $(element).html('<i id="wait-projects" class="fa fa-cog fa-spin"></i>'); $.getScript(media_url+'js/aux/date.js'); $.getScript(media_url+'js/aux/modals.js', function(){ var mymodal=newModal('projects_modal',true, true); modalAddTitle(mymodal,'Proyectos a los que está vinculado'); doModalBigger(mymodal); $('.modal-dialog').css('width','600px'); template=$('<div></div>'); $.getJSON(api_url+'enterprises/get_projects_employee?callback=?', { id:id}, function(data){ if(data.status=='success'){ $(element).html('<i class="fa fa-sitemap fa-fw"></i>'); for(var i=0; i<data.data.projects.length; i++){ template.append('<span>'+data.data.projects[i].name+'</span><br>'); } } else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); }); modalAddBody(mymodal,template); mymodal.modal('show'); }); } function edit_employee(id,element){ if($('#name'+id).hasClass('editactive')){ $('#name'+id).removeClass('editactive'); var name=$('#nameemployee').val(); var surname=$('#surnameemployee').val(); var email=$('#emailemployee').val(); var phone=$('#phoneemployee').val(); $('#name'+id).html(''); $('#name'+id).text(name); $('#surname'+id).html(''); $('#surname'+id).text(surname); $('#email'+id).html(''); $('#email'+id).text(email); $('#phone'+id).html(''); $('#phone'+id).text(phone); $.getJSON(api_url+'enterprises/edit_employee?callback=?', { id:id, name:name, surname:surname, email:email, phone:phone}, function(data){ if(data.status=='success'){ launch_alert('<i class="fa fa-smile-o"></i> Empleado editado',''); $(element).html('<i class="fa fa-pencil-square-o fa-fw"></i>'); } else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); }); }else{ $(element).html('<i class="fa fa-floppy-o fa-fw"></i>'); $('#name'+id).addClass('editactive'); var name=$('#name'+id).html(); var surname=$('#surname'+id).html(); var email=$('#email'+id).html(); var phone=$('#phone'+id).html(); $('#name'+id).html('<input style="width:100%; height: 19px;" type="text" name="nameemployee" id="nameemployee">'); $('#nameemployee').val(name); $('#surname'+id).html('<input style="width:100%; height: 19px;" type="text" name="surnameemployee" id="surnameemployee">'); $('#surnameemployee').val(surname); $('#email'+id).html('<input style="width:100%; height: 19px;" type="email" name="emailemployee" id="emailemployee">'); $('#emailemployee').val(email); $('#phone'+id).html('<input style="width:100%; height: 19px;" type="text" name="phoneemployee" id="phoneemployee">'); $('#phoneemployee').val(phone); } } function show_new_employee() { if($('#new_employee_wrapper').css('display')=='none'){ $('#new_employee_wrapper').slideDown(); $('#new_employee').submit(false).submit(function(e){ new_employee(); return false; }); } else $('#new_employee_wrapper').slideUp(); } function passwordgenerate(length, special) { var iteration = 0; var password = ""; var randomNumber; if(special == undefined){ var special = false; } while(iteration < length){ randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33; if(!special){ if ((randomNumber >=33) && (randomNumber <=47)) { continue; } if ((randomNumber >=58) && (randomNumber <=64)) { continue; } if ((randomNumber >=91) && (randomNumber <=96)) { continue; } if ((randomNumber >=123) && (randomNumber <=126)) { continue; } } iteration++; password += String.fromCharCode(randomNumber); } return password; } function new_employee() { var name=$('#new_employee_name').val(); var surname=$('#new_employee_surname').val(); var email=$('#new_employee_email').val(); var pass=""; var prefix=""; var phone=$('#new_employee_phone').val(); $.getJSON(api_url+'auth/get?callback=?', function(data){ if(data.status=='success'){ prefix=data.data.auth_profile.prefix; pass=passwordgenerate(8); if (name.length>0 || true){ if (email.length>0){ if (pass.length>0 || true){ $('#new_employee_submit').html('<i class="fa fa-cog fa-spin"></i>'); $.getJSON(api_url+'enterprises/add_employee?callback=?', { name:name, surname:surname, email:email, prefix:prefix, phone:phone, password:pass}, function(data){ if(data.status=='success'){ employees_list(); launch_alert('<i class="fa fa-smile-o"></i> Empleado añadido',''); } else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); $('#new_employee_submit').html('Guardar'); }); }else launch_alert('<i class="fa fa-frown-o"></i> Debes añadir una contraseña','warning'); }else launch_alert('<i class="fa fa-frown-o"></i> Debes añadir el email','warning'); }else launch_alert('<i class="fa fa-frown-o"></i> Debes añadir el nombre','warning'); } }); } function unlink_employee(id) { var confirmacion=confirm('¿Seguro que quieres eliminar empleado?'); if (confirmacion==true) { $.getJSON(api_url+'enterprises/unlink_employee?callback=?', {id:id}, function(data){ if(data.status=='success') launch_alert('<i class="fa fa-smile-o"></i> Empleado eliminado',''); else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); employees_list(); }); } } function authorize_employee(id, element) { $(element).html('<i class="fa fa-cog fa-spin"></i>'); $.getJSON(api_url+'enterprises/set_corporate_code?callback=?', {id:id}, function(data){ if(data.status=='success'){ launch_alert('<i class="fa fa-smile-o"></i> Empleado autorizado',''); $.getJSON(api_url+'enterprises/send_corporate_code?callback=?', {passenger_id:id}, function(data){ if(data.status=='success'){ launch_alert('<i class="fa fa-smile-o"></i> Empleado autorizado y PIN enviado satisfactoriamente',''); }else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); }); }else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); employees_list(); }); } function sendpin_employee(id, element){ $(element).html('<i id="wait-send" class="fa fa-cog fa-spin"></i>'); $.getJSON(api_url+'enterprises/send_corporate_code?callback=?', {passenger_id:id}, function(data){ if(data.status=='success'){ launch_alert('<i class="fa fa-smile-o"></i> PIN enviado satisfactoriamente',''); }else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); $(element).html('<i class="fa fa-paper-plane-o fa-fw"></i>'); }); } function stadistics_employee(id, element){ idglobal=id; $(element).html('<i id="wait-stadistics" class="fa fa-cog fa-spin"></i>'); $.post('partials/modal_employees_stadistics', function(template, textStatus, xhr) { $.getScript(media_url+'js/aux/date.js'); $.getScript(media_url+'js/aux/modals.js', function(){ var mymodal=newModal('employee_stadistics_modal',true, true); mymodal.attr('data-employee-auth-id',id); modalAddTitle(mymodal,''); doModalBigger(mymodal); modalAddBody(mymodal,template); mymodal.modal('show'); $('#current_year').html('<i class="fa fa-cog fa-spin"></i>'); $('#graphical-wait').html('<div class="waiting"><i class="fa fa-cog fa-spin"></i></div>'); $('#current_year').html(year_view); $('#employee_stadistics_modal > .modal-dialog > .modal-content').attr({'style': 'height: 100%;'}); selectMonthEmployee(month_view); $(element).html('<i class="fa fa-bar-chart-o fa-fw"></i>'); }); }); } function selectMonthEmployee(month){ $('#accordion_wait').show(); $('#accordion_wait').html('<div class="waiting"><i class="fa fa-cog fa-spin"></i></div>'); month_view=month; for(var i=0; i<months.length; i++){ $('#'+months[i]).removeClass('month-selected'); } $('#'+months[month_view]).addClass('month-selected'); $('#'+months[month_view]).focus(); $('#graphical-content').attr({'style':'display:all;'}); $('#accordion_wait').hide(); loadFirstGraphicalEmployee(month_view,year_view); } function loadGraphicalJourneysYearEmployee(){ $('#rgraph_key').remove(); $('#graphical-wait').html('<div class="waiting"><i class="fa fa-cog fa-spin"></i></div>').show(); RGraph.ObjectRegistry.Clear(); $('#link-graphical-journeys-year').addClass('active'); $('#link-graphical-journeys-month').removeClass('active'); $('#link-graphical-money-year').removeClass('active'); $('#link-graphical-money-month').removeClass('active'); var width= $("#dashboard-graphical").width(); var height=(width*300)/632; $("#cvs").attr({'width':width}); $("#cvs").attr({'height':height}); $.getJSON(api_url+'enterprises/get?callback=?', function(data){ if(data.status=='success'){ var enterprise_id=data.data.enterprise.id; $.getJSON(api_url+'journeys/list_num_journeys_by_employee_year?callback=?', { enterprise_id:enterprise_id, employee_auth_id:idglobal, year:year_view}, function(data2){ if(data2.status=='success'){ var lista_meses = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic']; $('#dashboard-graphical').append($('<div style="width:100%;"><table id="rgraph_key" cellspacing="0" cellpadding="0" border="0" style="width:129px;"><tbody><tr><td><div id="legend-color"> </div></td><td><span "="">Carreras / Mes</span></td></tr></tbody></table></div>')); lista_tooltip=new Array(12); for (var i=0; i<lista_tooltip.length; i++){ lista_tooltip[i] = data2.data[i].toString()+' carreras'; } var desp=0; if(window.innerWidth>992){ desp=50; }else{ desp=40; } var bar4 = new RGraph.Bar('cvs', data2.data) .set('labels', lista_meses) .set('colors', ['#075a8f']) .set('tooltips', lista_tooltip) .set('chart.gutter.left', desp) .draw(); $('#graphical-wait').hide(); } else launch_alert('<i class="fa fa-frown-o"></i> '+data2.response,'warning'); }); } else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); }); } function loadGraphicalExpensesYearEmployee(){ $('#rgraph_key').remove(); $('#graphical-wait').html('<div class="waiting"><i class="fa fa-cog fa-spin"></i></div>').show(); RGraph.ObjectRegistry.Clear(); $('#link-graphical-journeys-year').removeClass('active'); $('#link-graphical-journeys-month').removeClass('active'); $('#link-graphical-money-year').addClass('active'); $('#link-graphical-money-month').removeClass('active'); var width= $("#dashboard-graphical").width(); var height=(width*300)/632; $("#cvs").attr({'width':width}); $("#cvs").attr({'height':height}); $.getJSON(api_url+'enterprises/get?callback=?', function(data){ if(data.status=='success'){ var enterprise_id=data.data.enterprise.id; var currency = data.data.enterprise.currency; $.getJSON(api_url+'journeys/list_expenses_progress_by_employee_year?callback=?', { enterprise_id:enterprise_id, employee_auth_id:idglobal, year:year_view}, function(data2){ if(data2.status=='success'){ var lista_meses = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic']; if(currency=='EUR'){ currency='Euros'; } $('#dashboard-graphical').append($('<div style="width:100%;"><table id="rgraph_key" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td><div id="legend-color"> </div></td><td><span "="">'+currency+' / Mes</span></td></tr></tbody></table></div>')); lista_tooltip=new Array(12); for (var i=0; i<lista_tooltip.length; i++){ if(data2.data[i]==0){ lista_tooltip[i] = data2.data[i].toString()+' '+currency; }else{ lista_tooltip[i] = data2.data[i].toFixed(2).toString()+' '+currency; } } var desp=0; if(window.innerWidth>992){ desp=50; }else{ desp=40; } var bar4 = new RGraph.Bar('cvs', data2.data) .set('labels', lista_meses) .set('colors', ['#075a8f']) .set('tooltips', lista_tooltip) .set('chart.gutter.left', desp) .draw(); $('#graphical-wait').hide(); } else launch_alert('<i class="fa fa-frown-o"></i> '+data2.response,'warning'); }); } else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); }); } function loadGraphicalJourneysMonthEmployee(){ $('#rgraph_key').remove(); $('#graphical-wait').html('<div class="waiting"><i class="fa fa-cog fa-spin"></i></div>').show(); RGraph.ObjectRegistry.Clear(); $('#link-graphical-journeys-year').removeClass('active'); $('#link-graphical-journeys-month').addClass('active'); $('#link-graphical-money-year').removeClass('active'); $('#link-graphical-money-month').removeClass('active'); var width= $("#dashboard-graphical").width(); var height=(width*300)/632; $("#cvs").attr({'width':width}); $("#cvs").attr({'height':height}); $.getJSON(api_url+'enterprises/get?callback=?', function(data){ if(data.status=='success'){ var enterprise_id=data.data.enterprise.id; $.getJSON(api_url+'journeys/list_num_journeys_by_employee_month?callback=?', { enterprise_id:enterprise_id, employee_auth_id:idglobal, month:month_view+1, year:year_view}, function(data2){ if(data2.status=='success'){ var lista_dias = new Array(data2.data.num_days); for (var i=0; i<lista_dias.length; i++){lista_dias[i] = (i+1).toString();} $('#dashboard-graphical').append($('<div style="width:100%;"><table id="rgraph_key" cellspacing="0" cellpadding="0" border="0" style="width:129px;"><tbody><tr><td><div id="legend-color"> </div></td><td><span "="">Carreras / Día</span></td></tr></tbody></table></div>')); var lista_tooltip = new Array(data2.data.num_days); var lista_data = new Array(data2.data.num_days); if(month_view==current_month && year_view==current_year){ for (var i=0; i<lista_tooltip.length; i++){lista_tooltip[i] = data2.data.list_month[i].toString()+' carreras';} for (var i=0; i<current_day; i++){lista_data[i] = data2.data.list_month[i];} }else{ for (var i=0; i<lista_tooltip.length; i++){lista_tooltip[i] = data2.data.list_month[i].toString()+' carreras';} for (var i=0; i<lista_data.length; i++){lista_data[i] = data2.data.list_month[i];} } var desp=0; if(window.innerWidth>992){ desp=50; }else{ desp=40; } var line = new RGraph.Line('cvs', lista_data) .set('labels', lista_dias) .set('tooltips', lista_tooltip) .set('colors', ['#075a8f']) .set('tickmarks', 'circle') .set('linewidth', 3) .set('chart.gutter.left', desp) .draw(); $('#graphical-wait').hide(); } else launch_alert('<i class="fa fa-frown-o"></i> '+data2.response,'warning'); }); } else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); }); } function loadGraphicalExpensesMonthEmployee(){ $('#rgraph_key').remove(); $('#graphical-wait').html('<div class="waiting"><i class="fa fa-cog fa-spin"></i></div>').show(); RGraph.ObjectRegistry.Clear(); var d = new Date(); $('#link-graphical-journeys-year').removeClass('active'); $('#link-graphical-journeys-month').removeClass('active'); $('#link-graphical-money-year').removeClass('active'); $('#link-graphical-money-month').addClass('active'); var width= $("#dashboard-graphical").width(); var height=(width*300)/632; $("#cvs").attr({'width':width}); $("#cvs").attr({'height':height}); $.getJSON(api_url+'enterprises/get?callback=?', function(data){ if(data.status=='success'){ var enterprise_id=data.data.enterprise.id; var currency = data.data.enterprise.currency; $.getJSON(api_url+'journeys/list_expenses_progress_by_employee_month?callback=?', { enterprise_id:enterprise_id, employee_auth_id:idglobal, month:month_view+1, year:year_view}, function(data2){ if(data2.status=='success'){ var lista_dias = new Array(data2.data.num_days); for (var i=0; i<lista_dias.length; i++){lista_dias[i] = (i+1).toString();} if(currency=='EUR'){ currency='Euros'; } $('#dashboard-graphical').append($('<div style="width:100%;"><table id="rgraph_key" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td><div id="legend-color"> </div></td><td><span "="">'+currency+' / Día</span></td></tr></tbody></table></div>')); var lista_tooltip = new Array(data2.data.num_days); var lista_data = new Array(data2.data.num_days); if(month_view==current_month && year_view==current_year){ for (var i=0; i<lista_tooltip.length; i++){ if(data2.data.list_expenses[i]==0){ lista_tooltip[i] = data2.data.list_expenses[i].toString()+' '+currency; }else{ lista_tooltip[i] = data2.data.list_expenses[i].toFixed(2).toString()+' '+currency; } } for (var i=0; i<current_day; i++){lista_data[i] = data2.data.list_expenses[i];} }else{ for (var i=0; i<lista_tooltip.length; i++){ if(data2.data.list_expenses[i]==0){ lista_tooltip[i] = data2.data.list_expenses[i].toString()+' '+currency; }else{ lista_tooltip[i] = data2.data.list_expenses[i].toFixed(2).toString()+' '+currency; } } for (var i=0; i<lista_data.length; i++){lista_data[i] = data2.data.list_expenses[i];} } var desp=0; if(window.innerWidth>992){ desp=50; }else{ desp=40; } var line = new RGraph.Line('cvs', lista_data) .set('labels', lista_dias) .set('tooltips', lista_tooltip) .set('colors', ['#075a8f']) .set('tickmarks', 'circle') .set('linewidth', 3) .set('chart.gutter.left', desp) .draw(); $('#graphical-wait').hide(); } else launch_alert('<i class="fa fa-frown-o"></i> '+data2.response,'warning'); }); } else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); }); } function loadFirstGraphicalEmployee(month,year){ $('#rgraph_key').remove(); $('#graphical-wait').html('<div class="waiting"><i class="fa fa-cog fa-spin"></i></div>').show(); var canvas = $('#cvs'); RGraph.ObjectRegistry.Clear(); RGraph.Reset(canvas); var string_aux = 'Informe de importes ('+months_complete[month_view]+')'; $('#link-graphical-money-month').html(string_aux); var string_aux = 'Informe de importes ('+year_view+')'; $('#link-graphical-money-year').html(string_aux); var string_aux = 'Informe de carreras ('+months_complete[month_view]+')'; $('#link-graphical-journeys-month').html(string_aux); var string_aux = 'Informe de carreras ('+year_view+')'; $('#link-graphical-journeys-year').html(string_aux); $('#link-graphical-journeys-year').removeClass('active'); $('#link-graphical-journeys-month').removeClass('active'); $('#link-graphical-money-year').removeClass('active'); $('#link-graphical-money-month').addClass('active'); var width= 514; var height=(width*300)/632; $("#cvs").attr({'width':width}); $("#cvs").attr({'height':height}); $.getJSON(api_url+'enterprises/get?callback=?', function(data){ if(data.status=='success'){ var enterprise_id=data.data.enterprise.id; var currency = data.data.enterprise.currency; $.getJSON(api_url+'journeys/list_expenses_progress_by_employee_month?callback=?', { enterprise_id:enterprise_id, employee_auth_id:idglobal, month:month_view+1, year:year_view}, function(data2){ if(data2.status=='success'){ var lista_dias = new Array(data2.data.num_days); for (var i=0; i<lista_dias.length; i++){lista_dias[i] = (i+1).toString();} if(currency=='EUR'){ currency='Euros'; } $('#dashboard-graphical').append($('<div style="width:100%;"><table id="rgraph_key" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td><div id="legend-color"> </div></td><td><span "="">'+currency+' / Día</span></td></tr></tbody></table></div>')); var lista_tooltip = new Array(data2.data.num_days); var lista_data = new Array(data2.data.num_days); if(month_view==current_month && year_view==current_year){ for (var i=0; i<lista_tooltip.length; i++){ if(data2.data.list_expenses[i]==0){ lista_tooltip[i] = data2.data.list_expenses[i].toString()+' '+currency; }else{ lista_tooltip[i] = data2.data.list_expenses[i].toFixed(2).toString()+' '+currency; } } for (var i=0; i<current_day; i++){lista_data[i] = data2.data.list_expenses[i];} }else{ for (var i=0; i<lista_tooltip.length; i++){ if(data2.data.list_expenses[i]==0){ lista_tooltip[i] = data2.data.list_expenses[i].toString()+' '+currency; }else{ lista_tooltip[i] = data2.data.list_expenses[i].toFixed(2).toString()+' '+currency; } } for (var i=0; i<lista_data.length; i++){lista_data[i] = data2.data.list_expenses[i];} } var desp=0; if(window.innerWidth>992){ desp=50; }else{ desp=40; } var line = new RGraph.Line('cvs', lista_data) .set('labels', lista_dias) .set('tooltips', lista_tooltip) .set('colors', ['#075a8f']) .set('tickmarks', 'circle') .set('linewidth', 3) .set('chart.gutter.left', desp) .draw(); $('#graphical-wait').hide(); } else launch_alert('<i class="fa fa-frown-o"></i> '+data2.response,'warning'); }); } else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); }); } function ban_employee(id, element) { $(element).html('<i class="fa fa-cog fa-spin"></i>'); $.getJSON(api_url+'enterprises/ban_employee?callback=?', {id:id}, function(data){ if(data.status=='success') { launch_alert('<i class="fa fa-smile-o"></i> Empleado desautorizado',''); }else launch_alert('<i class="fa fa-frown-o"></i> '+data.response,'warning'); employees_list(); }); }
const RefundsPage = require('../pageObjects/refundsPage.js'); const headerPage = require('../pageObjects/headerPage'); const { defineSupportCode } = require('cucumber'); defineSupportCode(function ({ Then, When }) { let refundsPage = new RefundsPage(); When(/^I click on Refunds button$/, async function () { await headerPage.clickRefunds(); }); Then(/^Refunds page should be displayed$/, async function () { let refundPageHeadings = [ 'Refund list', 'Refunds to be approved', 'Refunds returned to caseworker' ]; await browser.waitForAngular(); let renderedHeadings = await refundsPage.amOnPage(); expect(renderedHeadings).to.include.all.members(refundPageHeadings); }); When(/^I click Review case$/, async function () { await refundsPage.clickReviewCase(); }); Then(/^Review case page should be displayed$/, async function () { expect(await refundsPage.amOnReviewCasePage()).to.equal('Case list'); }); When(/^I click Process refund$/, async function () { await refundsPage.clickProcessRefund(); }); Then(/^Process refund page should be displayed$/, async function () { let processRefundPageHeadings = [ 'Review refund details', 'What do you want to do with this refund?' ]; let renderedHeadings = await refundsPage.amOnProcessRefundPage(); let processRefundPageFields = { reviewRefundDetailsTableColumns: [ 'Payment to be refunded', 'Reason for refund', 'Amount to be refunded', 'Submitted by', 'Date submitted' ], refundActionsLabels: [ 'Approve', 'Reject', 'Return to caseworker' ], refundActionsHints: [ 'Send to middle office', 'There is no refund due', 'Some information needs correcting' ] }; let processDetailsInfo = await refundsPage.getProcessRefundsInfo(); expect(renderedHeadings).to.include.all.members(processRefundPageHeadings); Object.keys(processRefundPageFields).forEach((key) => { expect(processDetailsInfo[key]).to.include.all.members(processRefundPageFields[key]); }); }); When(/^I click Review refund$/, async function () { await refundsPage.clickReviewRefund(); }); Then(/^Review refund page should be displayed$/, async function () { let reviewRefundPageHeadings = [ 'Refund details', 'Refund status history' ]; let renderedHeadings = await refundsPage.amOnReviewRefundPage(); let reviewRefundPageFields = { refundDetailsTableColumns: [ 'Refund reference', 'Payment to be refunded', 'Reason for refund', 'Amount refunded' ], refundStatusHistoryColumns: [ 'Status', 'Date and time', 'Users', 'Notes' ] }; let reviewDetailsInfo = await refundsPage.getReviewRefundsInfo(); expect(renderedHeadings).to.include.all.members(reviewRefundPageHeadings); Object.keys(reviewRefundPageFields).forEach((key) => { expect(reviewDetailsInfo[key]).to.include.all.members(reviewRefundPageFields[key]); }); }); });
const fs = require('fs'); const util = require('util'); const path = require('path'); const dataPath = path.join(__dirname, 'mockData.json'); const writeFile = util.promisify(fs.writeFile); const readFile = util.promisify(fs.readFile); const saveMockData = async (data) => await writeFile(dataPath, JSON.stringify(data, null, 2)); const readMockData = async () => await readFile(dataPath, 'utf8'); module.exports = { saveMockData, readMockData, };
var msg = 'Hello World'; console.log(msg); var http = require('http'); var os = require('os'); var hostname = os.hostname(); var fs = require('fs'); var qs = require('qs'); var moment = require('moment'); var port = process.env.PORT || 3000; function handleRequest (request, response) { response.writeHeader(200, {"Content-Type": "text/html"}); fs.readFile('./index.html', function (err, html){ if (err) { response.writeHead(404); respone.write('Whoops! File not found!'); } else { response.write(html); } response.end('<h2 style="text-align: center;">Sample Node.js Sample Application. Serving requests from [' + hostname + ']. Request URL:' + request.url + '</h2>'); }); } var server = http.createServer(handleRequest); server.listen(port, function () { console.log('Server listening on port', port); });
import React from 'react'; import styled, { ThemeProvider, createGlobalStyle } from 'styled-components'; import styledNormalize from 'styled-normalize'; import { Helmet } from 'react-helmet'; import Header from '../components/header'; import Footer from '../components/footer'; const GlobalStyle = createGlobalStyle` ${styledNormalize} html { font-size: 10px; } a { text-decoration: none; color: inherit; } `; // how do we set the media query breakpoints to be // universally accessible here? const theme = { breakpoint: { mobileXS: '380px', mobileS: '420px', mobileM: '580px', mobileL: '660px', tablet: '780px', tabletWide: '1000px', desktop: '1200px', desktopWide: '1600px' }, headerTextHeight: '72px', fontDefault: 'sans-serif', fontPost: `'Montserrat', sans-serif`, fontHeader: `'Quicksand', sans-serif`, fontSubheader: 'Poppins', fontLocation: 'Poppins' }; const Wrapper = styled.div``; const Page = styled.div` margin-top: ${props => (props.withHero ? '0px' : props.theme.headerTextHeight)}; `; class Base extends React.Component { render() { const { children, location } = this.props; const withHero = location.pathname === '/'; return ( <ThemeProvider theme={theme}> <Wrapper className="Wrapper"> <Helmet> <meta charSet="utf-8" /> <title>Internationally Gringo</title> <link rel="canonical" href="https://intlgringo.com" /> <meta property="og:title" content="Internationally Gringo" /> <meta name="keywords" content="travel,world,blog,writing,local,language,asia,america" /> <meta property="og:description" content="Traveling the world - so you don't have to." /> <meta property="og:type" content="article" /> <meta property="og:url" content="https://intlgringo.com" /> <meta property="og:image" content="https://res.cloudinary.com/burncartel/image/upload/v1561453037/gringo-sintra-square.jpg" /> </Helmet> <GlobalStyle /> <Header withHero={withHero} /> <Page withHero={withHero} className="Page"> {children} </Page> <Footer /> </Wrapper> </ThemeProvider> ); } } export default Base;
const mongoose = require('mongoose'); let menuItemSchema = new mongoose.Schema({ name: { type: String, required: true, unique: true }, restaurant_id: { type: mongoose.ObjectId, ref: 'Restaurant', required: true }, description: { type: String, required: true }, price: { type: Number, required: true, } }); const Menu = mongoose.model('MenuItem', menuItemSchema); // Menu.insertMany([ // {restaurant_id:"5f99d05e0eb41585eb070fc3", // name:"Mocha Latte", // description:"Proin mi nisi, commodo sed turpis nec, consectetur volutpat urna.", // price:5.21}, // {restaurant_id:"5f99d05e0eb41585eb070fc3", // name:"Espresso", // description:"Sed odio nisi, scelerisque quis elit ac, tristique finibus odio. In tempus luctus dui, id fringilla sapien euismod eu.", // price:2.9}, // {restaurant_id:"5f99d05e0eb41585eb070fc3", // name:"Salad", // description:"Nulla et nisl congue, efficitur nulla nec, auctor sapien.", // price:7.89}, // {restaurant_id:"5f99d05e0eb41585eb070fc3", // name:"Matcha Latte", // description:"Aenean neque metus, tincidunt in aliquet id, ullamcorper in tellus.", // price:5.62}, // {restaurant_id:"5f99d13f0eb41585eb070fc5", // name:"BBQ Chicken", // description:"Donec pretium vulputate arcu, ac interdum arcu vulputate at.", // price:12.48}, // {restaurant_id:"5f99d13f0eb41585eb070fc5", // name:"Salt & Pepper Chicken", // description:"Aenean faucibus rhoncus cursus. Donec pretium vulputate arcu, ac interdum arcu vulputate at.", // price:12.68}, // {restaurant_id:"5f99d13f0eb41585eb070fc5", // name:"Honey Mustard Chicken", // description:"Ut lacus tellus, lacinia ac mi ullamcorper, maximus consequat nunc.", // price:12.68}, // {restaurant_id:"5f99d02b0eb41585eb070fc2", // name:"Bibimbap", // description:"Sed ante nisi, tincidunt sit amet eros eu, mattis auctor augue.", // price:11.68}, // {restaurant_id:"5f99d02b0eb41585eb070fc2", // name:"Tteokbokki (stir-fried rice cakes)", // description:"Ut vitae malesuada tortor. Curabitur sed bibendum libero.", // price:7.38}, // {restaurant_id:"5f99d02b0eb41585eb070fc2", // name:"Kimchi Fried Rice", // description:"Nunc in libero et arcu maximus congue ac sit amet diam.", // price:12.75}, // {restaurant_id:"5f98b0dbb681030e6e36b68b", // name:"Poutine", // description:"Aenean porta bibendum metus, eu malesuada ipsum pretium ut.", // price:10.75}, // {restaurant_id:"5f98b0dbb681030e6e36b68b", // name:"Bacon Poutine", // description:"Integer et arcu vitae dolor fermentum ultrices. Phasellus sed justo neque.", // price:12.75}, // {restaurant_id:"5f98b0dbb681030e6e36b68b", // name:"Smoked Salmon Benedict", // description:"Sed ultrices convallis ex.", // price:15.97}, // {restaurant_id:"5f98b0dbb681030e6e36b68b", // name:"Egg Benny", // description:"Morbi feugiat hendrerit lectus, eu pharetra dui lobortis in.", // price:14.21} // ]) module.exports = Menu;
/* eslint indent: 0 */ const DOMPurify = require('dompurify'); const marked = require('marked'); const yo = require('yo-yo'); const cardClass = 'cardContainer'; const RENDER_MD = 1; module.exports = (cardInfo) => { const cardId = `yellowCard-${cardInfo.id}`; let dragging = false; let x0 = 0; let x1 = 0; let y0 = 0; let y1 = 0; function mouseDown(e) { e.preventDefault(); dragging = true; x0 = e.clientX; y0 = e.clientY; } function mouseMove(e) { if (dragging) { e.preventDefault(); x1 = x0 - e.clientX; y1 = y0 - e.clientY; x0 = e.clientX; y0 = e.clientY; const element = e.path.find(elt => elt.className.includes(cardClass)); element.style.top = `${element.offsetTop - y1}px`; element.style.left = `${element.offsetLeft - x1}px`; } } function mouseUp() { dragging = false; } const timeStr = new Date(cardInfo.created * 1000) .toLocaleDateString(); const closeCard = () => { if (cardInfo.close) { cardInfo.close(); } const elt = document.getElementById(cardId); if (elt) { elt.remove(); } }; const contentId = `${cardId}-content`; const result = yo` <div class="${cardClass}" id="${cardId}" onmousedown=${mouseDown} onmousemove=${mouseMove} onmouseup=${mouseUp} > <div class="cardHeader" > <span class="cardAuthor" >${cardInfo.author}</span> <span class="cardDate" >${timeStr} <a onclick=${closeCard}>X</a></span> </div> <div class="cardContent" id="${contentId}" ></div> </div> `; const contentElt = Array.from(result.children) .find(x => x.id === contentId); if (cardInfo.renderHint === RENDER_MD) { contentElt.innerHTML = `<div class="cardContent" id="${contentId}" > ${DOMPurify.sanitize(marked(cardInfo.content))} </div>`; } else { // rely on yo-yo to sanitize content contentElt.innerHTML = `<div class="cardContent" id="${contentId}" > <pre>${[yo`${cardInfo.content}`]}</pre> </div>`; } return result; };
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { Box, Avatar } from '@material-ui/core'; import RoomIcon from '@material-ui/icons/Room'; import VideocamIcon from '@material-ui/icons/Videocam'; const useStyles = makeStyles((theme) => ({ avatar: { height: 24, width: 24, }, })); export default function EventComponent(props) { const { event } = props; const classes = useStyles(); return ( <Box display="flex" flexDirection="column" > <Box display="flex" justifyContent="space-around"> <Avatar alt={event.booked_by.name} src={event.booked_by.avatar} className={classes.avatar} /> {event.camera_needed && <VideocamIcon />} {event.room_needed && <RoomIcon />} </Box> </Box> ); }
var app = angular.module('MasteryMaster', ['ngRoute']); app.config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'champMasteries.html', controller: 'champMasteriesController', activeTab: 'champMasteries' }) .when('/achievements', { templateUrl: 'achievements.html', controller: 'achievementsController', activeTab: 'achievements' }) .when('/about', { templateUrl: 'about.html', activeTab: 'about' }); });
import React, {Component} from 'react'; import { View, Text, StyleSheet, TabBarIOS } from 'react-native'; import { Actions } from 'react-native-router-flux'; const base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg=='; class Main extends Component { constructor(props) { super(props); this.state = { selectedTab: 'redTab', notifCount: 0, presses: 0 }; } statics = { title: '<TabBarIOS>', description: 'Tab-based navigation.', } displayName = 'TabBarExample' componentDidMount() { // ... } _renderContent(color: string, pageText: string, num?: number) { return ( <View style={[styles.tabContent, {backgroundColor: color}]}> <Text style={styles.tabText}>{pageText}</Text> <Text style={styles.tabText}>{num} re-renders of the {pageText}</Text> </View> ); } render() { return ( <TabBarIOS unselectedTintColor="yellow" tintColor="white" barTintColor="darkslateblue"> <TabBarIOS.Item title="Blue Tab" icon={{uri: base64Icon, scale: 3}} selected={this.state.selectedTab === 'blueTab'} onPress={() => { this.setState({ selectedTab: 'blueTab', }); }}> {this._renderContent('#414A8C', 'Blue Tab')} </TabBarIOS.Item> <TabBarIOS.Item systemIcon="history" badge={this.state.notifCount > 0 ? this.state.notifCount : undefined} selected={this.state.selectedTab === 'redTab'} onPress={() => { this.setState({ selectedTab: 'redTab', notifCount: this.state.notifCount + 1, }); }}> {this._renderContent('#783E33', 'Red Tab', this.state.notifCount)} </TabBarIOS.Item> <TabBarIOS.Item icon={require('./flux.png')} selectedIcon={require('./relay.png')} renderAsOriginal title="More" selected={this.state.selectedTab === 'greenTab'} onPress={() => { this.setState({ selectedTab: 'greenTab', presses: this.state.presses + 1 }); }}> {this._renderContent('#21551C', 'Green Tab', this.state.presses)} </TabBarIOS.Item> </TabBarIOS> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center' }, btn: { paddingVertical: 5, paddingHorizontal: 15, borderColor: '#0086b3', borderWidth: 1, borderRadius: 4, marginTop: 10 }, btnText: { color: '#0086b3' }, tabContent: { flex: 1, alignItems: 'center', }, tabText: { color: 'white', margin: 50, } }); export default Main;
'use strict'; import {Utils} from '../util' let utils = new Utils(); export const actions = { /** * 通过手机验证码获取jwt token * @param commit * @param state * @param verify_payload */ getAuthToken ({commit, state}, verify_payload) { return new Promise((resolve, reject) => { utils.post('/auth/verifysms', {phone_number: verify_payload.phone, verify_number: verify_payload.code, unbind: verify_payload.unbind}).then(res => { resolve(res.data); }).catch(res => { reject(res); }) }); }, /** * 发送验证短信 * @param commit * @param state * @param sendsms_payload * @returns {Promise} */ sendSMS ({commit, state}, sendsms_payload) { return new Promise((resolve, reject) => { utils.post('/auth/sendsms', {phone: sendsms_payload.phone}).then(res => { resolve(res); }).catch(res => { reject(res); }); }) }, /** * 初始化微信接口 * @param commit * @param state * @param sign_url */ getWeChatSign ({commit, state}, sign_url) { return new Promise((resolve, reject) => { utils.post('/base/wechat', { sign_url: sign_url }).then(res => { resolve(res); }).catch(res => { reject({status: res.status, res: res}) }); }) } };
// I got to use the css toggle switch // https://ghinda.net/css-toggle-switch/ //THINGS TO CONSIDER: // Key value pair >>>>this is what I need to look up // I could I use the changing property setting to save settings????? // REDOFOME THE DATABASE AND ADD CLASSES TO IT //ALERT FUNCTIONALITY const alertBanner = document.getElementById("alert"); // create the html for the banner alertBanner.innerHTML = ` <div class="alert-banner"> <p><strong>Alert:</strong> You have <strong>6</strong> overdue tasks to complete</p> <p class="alert-banner-close">x</p> </div> ` alertBanner.addEventListener('click', e => { const element = e.target; if (element.classList.contains("alert-banner-close")) { alert.style.display = "none" } }); //DASHBOARD fUNCTION const main_header = document.querySelector('div.main_header'); const search_it = document.querySelector('input#search_it'); //APPLIED THE JAVASCRIPT CLASSES TO SYMPLYFY ARRAY PROCESS class Total_Members { constructor(name, email, birthDate) { this.name = name; this.email = email; this.birthDate = birthDate; } } //TOTAL MEMBERS VARIABLES const victoria = new Total_Members("Victoria Chambers", "victoria.chambers80@example.com", "10/15/15"); const dale = new Total_Members("Dale Byrd", "dale.byrd52@example.com", "10/15/15"); const dawn = new Total_Members("Dawn Wood", "dawn.wood16@example.com", "10/15/15"); const dan = new Total_Members("Dan Oliver", "dan.oliver82@example.com", "10/15/15"); //DASHBOARD LISTENER /* <a class="profile-email" href="#">victoria.chambers80@example.com</a> */ //Could the href help????? search_it.addEventListener('keyup', (event) => { //TEST console.log('main header listerer working...yea haww'); //STORE THE EVENT INTO A VARIABLE & PUSH IT INTO A COLLECTION let search_results = event.target; const search_string = []; for (let i = 0; i < search_string.length; i += 1) { search_string.push(search_results.charAt(i)); } //MATCH THE SEARCH STRING TO THE TOTAL MEMBER VARIABLES //THE MATCHING ISN'T WORKING & FLAGGING A PROBLEM WITH LINE 44 if (search_string.length = Total_Members.length) { if (search_string.length = victoria.this.Total_Members) { console.log('It refers to Victoria'); } else if (search_string.length = dale) { console.log('It refers to Dale'); } else if (search_string.length = dawn) { console.log('It refers to Dawn'); } else if (search_string.length = dan) { console.log('It refers to Dan'); } else { console.log('No go'); } } }); //TRAFFIC NAV COLOR const traffic_nav = document.querySelector('ul.traffic-nav'); // TRAFFIC HIGHLIGHTING traffic_nav.addEventListener('click', (event) => { let traffic_nav_indicator = event.target; //WHEN I CLICK INBETTEEN EACH MENU OPTION, IT COMPLETLEY CHANGES TO SOMETHING ELSE //iF i CLICK THE ITEM, IT MAKE A DOT INSTEAD OF APPLY THE STYLING // for (let i; traffic_nav.length; i++) { if (traffic_nav_indicator.className = "traffic-nav-hourly") { console.log('The hourly thing is responding'); traffic_nav_indicator.className = 'selected-traffic-nav'; } if (traffic_nav_indicator.className = "traffic-nav-daily") { console.log('The daily thing is responding'); traffic_nav_indicator.className = 'selected-traffic-nav'; } if (traffic_nav_indicator.className = "traffic-nav-weekly") { console.log('The weekly thing is responding'); traffic_nav_indicator.className = 'selected-traffic-nav'; } if (traffic_nav_indicator.className = "traffic-nav-monthly") { console.log('The montlh thing is responding'); traffic_nav_indicator.className = 'selected-traffic-nav'; } // } }); // if (traffic_nav_indicator.className = "traffic-nav-link-1") { // console.log('The hourly thing is responding'); // traffic_nav_indicator.className = 'selected-traffic-nav'; // } if (traffic_nav_indicator.className = "traffic-nav-link-2") { // console.log('The daily thing is responding'); // traffic_nav_indicator.className = 'selected-traffic-nav'; // } if (traffic_nav_indicator.className = "traffic-nav-link-active-3") { // console.log('The weekly thing is responding'); // traffic_nav_indicator.className = 'selected-traffic-nav'; // } if (traffic_nav_indicator.className = "traffic-nav-link-4") { // console.log('The montlh thing is responding'); // traffic_nav_indicator.className = 'selected-traffic-nav'; // } // }); //EMAIL NOTIFICATION SETTINGS FUNCTION const email_settings = document.querySelector('label#email_group'); email_settings.addEventListener('click', (event) => { let email_notify = event.target; const email_input = document.querySelector('input#email-checkbox'); //TRIED TO MAKE IT SAY SOMETHIGN DIFFERENT IF IT WAS ON OR OFF // const email_input_on = document.querySelector('input#email-checkbox') + document.querySelector('span.email-active-on'); // const email_input_off = document.querySelector('input#email-checkbox') + document.querySelector('span.email-active-off'); // const active_on = document.querySelector('span.email-active-on'); // const active_off = document.querySelector('span.email-active-off'); if (email_notify = email_input) { alert('You email notifications have been turned on on'); } // else if (email_notify === email_input_off) { // alert('You email notifications have been turned on off'); // } }); //Profile Notifcations SETTINGS FUNCTION const profile_settings = document.querySelector('label#profile_group'); profile_settings.addEventListener('click', (event) => { let profile_notify = event.target; const profile_input = document.querySelector('input#profile-checkbox'); //TRIED TO MAKE IT SAY SOMETHIGN DIFFERENT IF IT WAS ON OR OFF // const email_input_on = document.querySelector('input#email-checkbox') + document.querySelector('span.email-active-on'); // const email_input_off = document.querySelector('input#email-checkbox') + document.querySelector('span.email-active-off'); // const active_on = document.querySelector('span.email-active-on'); // const active_off = document.querySelector('span.email-active-off'); if (profile_notify === profile_input) { alert('You email notifications have been turned on on'); } // else if (email_notify === email_input_off) { // alert('You email notifications have been turned on off'); // } }); // MESSAGING FUNCTIONALITY const user = document.getElementById("userField"); const message = document.getElementById("messageField"); const send = document.getElementById("send"); send.addEventListener('click', () => { // ensure user and message fields are filled out if (user.value === "" && message.value === "") { alert("Please fill out user and message fields before sending"); } else if (user.value === "" ) { alert("Please fill out user field before sending"); } else if (message.value === "" ) { alert("Please fill out message field before sending"); } else { alert(`Message successfully sent to: ${user.value}`); } }); // SAVE SETTINGS FUNCTION // const settings = document.querySelector('fieldset.switch-toggle'); const settings = document.querySelector('select#timezone'); // const optional_responses = document.querySelector('option#timezone_options'); const optional_responses = document.querySelector('option#timezone_options'); //Listening Event settings.addEventListener('click', (event) => { console.log('Im in the time function function'); //LISTEN FOR INPUT selected_input_time = event.target; // let input_memory = []; // input_memory.push(selected_input_time); if (selected_input_time === optional_responses) { console.log("I'm in the timezone if statement"); if (optional_responses.value = "est-zone") { console.log('green light on Eastern'); alert('Time zone has been updated to Eastern zone'); } else if (optional_responses.value = "pac-zone") { console.log('green light on Pacific'); alert('Time zone has been updated to Pacific zone'); } else if (optional_responses.value = "gm-zone") { console.log('green light on GM'); alert('Time zone has been updated to GM Central zone'); } else if (optional_responses.value = "java-zone") { console.log('green light on java'); alert('Time zone has been updated to Javascript Time zone zone'); } else if (optional_responses.value = "code-zone") { console.log('green light on code'); alert('Time zone has been updated to Coding Time zone zone'); } else if (optional_responses.value = "jedi-zone") { console.log('green light on Jedi'); alert('Young padawan, time is only the force within you - Jedi Force Time zone zone'); } else { alert('Unable the update time zone'); } } }); // if (selected_input_time === optional_responses) { // console.log("I'm in the timezone if statement"); // if (optional_responses.className = "est-zone") { // console.log('green light on Eastern'); // alert('Time zone has been updated to Eastern zone'); // } else if (optional_responses.className = "pac-zone") { // console.log('green light on Pacific'); // alert('Time zone has been updated to Pacific zone'); // } else if (optional_responses.className = "gm-zone") { // console.log('green light on GM'); // alert('Time zone has been updated to GM Central zone'); // } else if (optional_responses.className = "java-zone") { // console.log('green light on java'); // alert('Time zone has been updated to Javascript Time zone zone'); // } else if (optional_responses.className = "code-zone") { // console.log('green light on code'); // alert('Time zone has been updated to Coding Time zone zone'); // } else if (optional_responses.className = "jedi-zone") { // console.log('green light on Jedi'); // alert('Young padawan, time is only the force within you - Jedi Force Time zone zone'); // } else { // alert('Unable the update time zone'); // } // } //======================================= // ARCHIVES WORKING //======================================= // CREATE A DATABASE WITH ARRAYS // const total_members = [ // {name:"Victoria Chambers", // email:"victoria.chambers80@example.com", // birthDate:"10/15/15"}, // {name:"Dale Byrd", // email:"dale.byrd52@example.com", // birthDate:"10/15/15"}, // {name:"Dawn Wood", // email:"dawn.wood16@example.com", // birthDate:"10/15/15"}, // {name:"Dan Oliver", // email:"dan.oliver82@example.com", // birthDate:"10/15/15"}, // ]; // if (selected_input_time === optional_responses) { // console.log("I'm in the timezone if statement"); // if (selected_input_time === option.className = "est-zone") { // console.log('green light on Eastern'); // alert('Time zone has been updated to Eastern zone'); // } if (optional_responses.className = "pac-zone") { // console.log('green light on Pacific'); // alert('Time zone has been updated to Pacific zone'); // } if (selected_input_time === option.className = "gm-zone") { // console.log('green light on GM'); // alert('Time zone has been updated to GM Central zone'); // } if (selected_input_time === option.className = "java-zone") { // console.log('green light on java'); // alert('Time zone has been updated to Javascript Time zone zone'); // } if (selected_input_time === option.className = "code-zone") { // console.log('green light on code'); // alert('Time zone has been updated to Coding Time zone zone'); // } if (selected_input_time === option.className = "jedi-zone") { // console.log('green light on Jedi'); // alert('Yong padawan, time is only the force within you - Jedi Force Time zone zone'); // } else { // alert('Unable the update time zone'); // } // } // console.log(input_memory.length); // TEST // console.log(selected_input_time); // REMOVE THE LAST ITEM AND KEEP THE NEW ONE //HAVE A MESSAGE THAT INDICATES THAT ____ TIME ZONE BEEN SAVED //IF STATEMENT OF IF THE EVENT TARGET CHOSE ___ TIME XONE // alert('You has saved your time zone settings!') //why not add a visual clock too!!!!!!!! // });
//apply redux in the ContactList element import React from 'react'; import { connect } from 'react-redux'; import {menuChangeView, entryLogoutAccount,menuPopulateUsers} from '../../../../actions'; import Header from '../header'; import SearchBar from '../searchbar'; import Filter from '../filter'; import ContactList from '../contactList'; class RootElement extends React.Component { componentDidMount(){ this.props.menuPopulateUsers(this.props.filter, 'all'); } render(){ return ( <> <Header menu = {[ { name: 'My Profile', onClick: () => this.props.menuChangeView('profile') }, { name: 'Settings', onClick: () => this.props.menuChangeView('settings') }, { name: 'Log Out', onClick: () => this.props.entryLogoutAccount(this.props.history, this.props.socket) }, ]} /> <SearchBar/> <Filter/> <ContactList/> {/* redux not applied yet */} </> ) } } const mstp = (state) => { return { filter: state.menu.filter, socket: state.menu.socket } } export default connect(mstp,{menuChangeView,entryLogoutAccount,menuPopulateUsers})(RootElement);