text
stringlengths
7
3.69M
import SizeSelector from "./size-selector"; export default SizeSelector;
Array.prototype.pluck = function (input) { if (input) { setImmediate(() => console.log(this.reduce( (previousValue, currentValue) => (previousValue > currentValue) ? previousValue : currentValue))) } else { setImmediate(() => console.log(this.reduce( (previousValue, currentValue) => (previousValue > currentValue) ? currentValue : previousValue))) } } console.log('start'); [1, 2, 3, 4, 5, 6, 7, 8].pluck(true); [1, 2, 3, 4, 5, 6, 7, 8].pluck(false); console.log('end');
import { MaybeLink, } from "../toolbox"; import * as mixins from "codogo-utility-functions"; import EntryWrapper from "./EntryWrapper"; import marked from "marked"; import PropTypes from "prop-types"; import * as R from "ramda"; import React from "react"; import slugify from "slugify"; import styled from "styled-components"; import Table from "../Table"; const Cell = ({ entry, slug, children, GatsbyLink, }) => { return ( <td> <MaybeLink GatsbyLink = { GatsbyLink } to = { !entry.externalUrl && `/${ slug }/${ slugify( entry.title, { lower: true, } ) }` } href = { entry.externalUrl } > {children} </MaybeLink> </td> ); }; const TableEntry = ({ slug, entry, }) => { return ( <tr key = { `entry-${ slugify( entry.title.toLowerCase()) }` } > <Cell entry = { entry } slug = { slug }>{ entry.title && entry.title }</Cell> <Cell entry = { entry } slug = { slug }>{ entry.description && entry.description } </Cell> </tr> ); }; const TableEntries = ({ entries, slug, }) => { return ( <Table> <tbody> <tr> <th>{ slug || "Name" }</th> <th>Description</th> </tr> { entries.map( (entry) => { return ( <TableEntry slug = { slug } entry = { entry }/> ); }) } </tbody> </Table> ); }; export default TableEntries;
// pages/publishExam/publishExam.js const fuc = require('../../utils/fuc.js') const api = require('../../utils/api.js') const moment = require('../../utils/moment.js') Page({ /** * 页面的初始数据 */ data: { course: { crs_id: 1, te_id: 20, countStu: 6, crs_name: "大学数学", countExam: 3, cl_name: "信统17202", status: "1" }, userInfo: { t_id: 1, t_name: "张老师", t_createTime: "2020-08-06T16:00:00.000Z", t_openid: "", tno: "t001" }, knowledge: [], knowledgeList: [], isKnowSelected: false, isTimeSelected: false, isDateSelected: false, nowDate:'', nowTime:'00:00', date:"截止日期", time:"截止时间" }, /** * 选择日期 */ chooseDate:function(e){ let that = this console.log(e) that.setData({ date:e.detail.value, isDateSelected: true }) }, /** * 选择时间 */ chooseTime:function(e){ let that = this console.log(e) that.setData({ time:e.detail.value, isTimeSelected: true }) }, /** * 选择知识点 */ chooseKnow: function (e) { var that = this; // console.log(e) that.setData({ indexKnow: e.detail.value, isKnowSelected: true }) }, /** * 发布测试 */ commit: function (e) { var that = this; var flag = that.data.isTimeSelected&&that.data.isDateSelected&&that.data.isKnowSelected; let nowTime = new Date() let endTime = moment(`${that.data.date} ${that.data.time}`) let endTimeStand = new Date(endTime) console.log(endTimeStand-nowTime) if((endTimeStand-nowTime)/(1000*60)<10){ wx.showModal({ title: '时间过短', content:"截止时间距现在不得小于10分钟" }) }else{ var exName = "test"; var memo = "测试"; if (flag) { wx.showModal({ title: '确认发布', content: '是否发布测试?', success(res) { if (res.confirm) { var examData = {}; var knowledgeList = that.data.knowledgeList; var staKnName = that.data.knowledge[that.data.indexKnow]; for (var i in knowledgeList) { if (knowledgeList[i].kn_name == staKnName) { examData.kn_id = knowledgeList[i].kn_id } } var te_id = that.data.course.te_id; examData.endTime = endTime; examData.te_id = te_id; examData.exName = exName; examData.memo = memo; // console.log(examData) fuc.request(api.publicExamTest, examData).then(function (res) { wx.showToast({ title: '发布成功', icon: 'success', mask: true, complete(res) { wx.navigateTo({ url: '../teaIndex/teaIndex', }) } }) }) } else if (res.cancel) {} } }) } else { wx.showModal({ title: '信息缺失!', content: '请完善信息!', }) }} }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; /** * 接收参数,将json字符串转换成对象 */ var newCourse = JSON.parse(options.course); var userInfo = JSON.parse(options.userInfo); that.setData({ course: newCourse, userInfo }) /* 获取当前日期 */ // const rule = { weekday: undefined, year: 'numeric', month: 'long', day: 'numeric' }; let nowDate = new Date() nowDate = nowDate.getFullYear('zh')+'-'+(nowDate.getMonth('zh')+1)+'-'+nowDate.getDate('zh') that.setData({ nowDate }) // console.log(nowDate) /** * 获取课程列表 */ var crs_id = newCourse.crs_id; // var crs_id = that.data.course.crs_id; // console.log(crs_id) fuc.request(api.getKnowledgeBycrs_id, { crs_id }).then(function (res) { var knowledgeList = res.data; var knowledge = []; console.log(knowledgeList); for (var x in knowledgeList) { knowledge.push(knowledgeList[x].kn_name) } console.log(knowledge); that.setData({ knowledgeList: knowledgeList, knowledge: knowledge }) }) } })
'use strict'; // MrNodeBot const _ = require('lodash'); const fs = require('fs'); const Bot = require('./bot'); const args = require('minimist')(process.argv.slice(2)); const logger = require('./lib/logger'); // Check if specified config file exists if (_.isObject(args.config)) { fs.access(args.config, fs.F_OK, err => { if (err) { logger.warn('The config file you specified does not exist, defaulting to config.js'); return; } }); } const bot = new Bot(app => { // Set the ENV Flag for Request strict TLS if (!_.isUndefined(app.Config.bot.strictTLS) || !app.Config.bot.strictTLS) { process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'; } // Extend the max socket listeners process.setMaxListeners(0); // Code here will be executed after the bot is finished connecting if (process.stdin.setRawMode) process.stdin.setRawMode(true); process.stdin.on('data', (b) => { if (b[0] === 3) { if (!app._ircClient.conn) process.exit(); else app._ircClient.disconnect('I have been terminated from the Console. Goodbye cruel world...', () => { if (process.stdin.setRawMode) { process.stdin.setRawMode(false); } process.exit(); }); } }); }, args.config);
'use strict'; // Манипуляции со строкой function passThroughStringMethods() { let str = "урок-3-был слишком легким", strStartCapital = str[0].toUpperCase() + str.slice(1), strReplace = strStartCapital.replace(/-/g, " "), strCutJoin = strReplace.replace("легким", "легко"); console.log("1) " + strStartCapital); console.log("2) " + strReplace); console.log("3) " + strCutJoin); let strStartLower = strCutJoin.toLowerCase(), strJoin1 = strStartLower.replace("был", "было"), strJoin2 = strJoin1.replace("урок", "уроке"), strModifield = "На " + strJoin2; console.log("4) " + strModifield + " (своя версия=))"); }; passThroughStringMethods(); // Манипуляции с массивом function calcSquareRootOfSumOfCubesOfElementArr() { let arr = [20, 33, 1, "Человек", 2, 3], arr2 = [], arr2Sqrt; for (let i = 0; i < arr.length; i++) { if ((typeof(arr[i])) == "number") { find(arr, i); arr2.push(arr[i]); } } console.log(arr2); for (let i = 0; i < arr2.length; i++) { let arr2CubesItems = Math.pow(arr2[i], 3); arr2[i] = arr2CubesItems; } console.log(arr2); let arr2SumOfCubes = arr2.reduce(function(sum, current) { return sum + current; }, 0); console.log(arr2SumOfCubes); arr2Sqrt = Math.sqrt(arr2SumOfCubes); console.log(arr2Sqrt); } calcSquareRootOfSumOfCubesOfElementArr(); function stringCut(str) { if ((typeof(str)) === "string") { str = str.trim(); if (str.length > 50) { str = str.substring(1,51); str = str + " ..."; } } else { alert("Введите строчные элементы!"); } document.write(str); } stringCut(prompt("Введите статью!", ""));
angular.module('ngApp.courierAccount').controller('CourierAccountAddEditController', function ($scope, mode, CourierAccountService, CourierService, $state, $translate, SessionService, toaster, uiGridConstants, $uibModal, $uibModalInstance, CourierAccount, ModalService) { $scope.CourierAccount = { LogisticServiceCourierAccountId: 0, IntegrationAccountId: '', AccountNo: '', AccountCountryCode: '', Description: '', ColorCode: '', IsActive: false, OperationZone: { OperationZoneId: null, OperationZoneName: '' }, LogisticService: { LogisticServiceId: 0, OperationZoneId: null, LogisticCompany: '', LogisticCompanyDisplay: '', LogisticType: '', LogisticTypeDisplay: '', RateType: '', RateTypeDisplay: '', ModuleType: 'DirectBooking' } }; var setModalOptions = function () { $translate(['FrayteError', 'FrayteInformation', 'FrayteValidation', 'ErrorSavingRecord', 'PleaseCorrectValidationErrors', 'SuccessfullySavedInformation', 'records', 'ErrorGetting', 'FrayteSuccess', 'FrayteWarning_Validation', 'UpdateRecord_Validation', 'PleaseCorrectValidationErrors', 'RateCardSave_Validation', 'Select_CourierAccount', 'THP_Matrix_Saved', 'DataSaved_Validation', 'Record_Saved', 'APIkeyUserkey_Saved_Validation', 'ParcelHubKeysSavingErrorValidation', 'PleaseTryLater', 'ParcelHubKeyRemoved_Validation', 'PacelHub', 'Keys', 'SelectLogisticType_Validation', 'Cancel', 'Confirmation', 'Cancel_Validation', 'Courier_Account_Record_Saved_Successfully']).then(function (translations) { $scope.TitleFrayteError = translations.FrayteError; $scope.TitleFrayteInformation = translations.FrayteInformation; $scope.TitleFrayteValidation = translations.FrayteValidation; $scope.TextErrorSavingRecord = translations.ErrorSavingRecord; $scope.TextSuccessfullySavedInformation = translations.SuccessfullySavedInformation; $scope.RecordGettingError = translations.ErrorGetting + " " + translations.records; $scope.Success = translations.FrayteSuccess; $scope.FrayteWarningValidation = translations.FrayteWarning_Validation; $scope.PleaseCorrectValidationErrors = translations.PleaseCorrectValidationErrors; $scope.Courier_Account_Record_Saved_Successfullys = translations.Courier_Account_Record_Saved_Successfully; $scope.APIkeyUserkeySavedValidation = translations.APIkeyUserkey_Saved_Validation; $scope.ParcelHubKeysSavingErrorValidation = translations.ParcelHubKeysSavingError_Validation; $scope.ParcelHubKeyRemovedTryLaterValidation = translations.ParcelHubKeysSavingError_Validation + " " + translations.PleaseTryLater; $scope.ParcelHubKeyGettingValidation = translations.ErrorGetting + " " + translations.PacelHub + " " + translations.Keys; $scope.SelectLogisticTypeValidation = translations.SelectLogisticType_Validation; $scope.CancelConfirmation = translations.Cancel + " " + translations.Confirmation; $scope.CancelValidation = translations.Cancel_Validation; }); }; $scope.CourierAccountByOperationZone = function () { $scope.GetInfo(); }; $scope.changeLabelForparcelHub = function (value) { if (value !== undefined && value !== null && value.Name === "UK/EU - Shipment") { $scope.IsParcel = true; } else { $scope.IsParcel = false; } }; $scope.submit = function (IsValid, CourierAccount) { if (IsValid) { debugger; $scope.CourierAccount.LogisticService.OperationZoneId = CourierAccount.OperationZone.OperationZoneId; $scope.CourierAccount.LogisticService.LogisticCompany = $scope.CourierCompany.Value; $scope.CourierAccount.LogisticService.LogisticType = $scope.LogisticType1.Value; if ($scope.RateType1 !== undefined) { $scope.CourierAccount.LogisticService.RateType = $scope.RateType1.Value; } else { $scope.CourierAccount.LogisticService.RateType = null; } CourierAccountService.SaveCourierAccount(CourierAccount).then(function () { $uibModalInstance.close(CourierAccount); toaster.pop({ type: 'success', title: $scope.Success, body: $scope.Courier_Account_Record_Saved_Successfullys, showCloseButton: true }); }, function () { //toaster.pop('error', "Frayte-Validation", "Error while login"); toaster.pop({ type: 'error', title: $scope.TitleFrayteError, body: $scope.TextErrorSavingRecord, showCloseButton: true }); }); } else { toaster.pop({ type: 'warning', title: $scope.FrayteWarningValidation, body: $scope.PleaseCorrectValidationErrors, showCloseButton: true }); } }; $scope.CourierAccGoBack = function () { var modalOptions = { headerText: $scope.CancelConfirmation, bodyText: $scope.CancelValidation }; ModalService.Confirm({}, modalOptions).then(function () { //if ($state.is('admin.courier-accounts.easypost')) { // $state.go('admin.courier-accounts.easypost', null, { reload: true }); // $rootScope.getCourierAccounts(); //} //else if ($state.is('admin.courier-accounts.parcel-hub')) { // $state.go('admin.courier-accounts.parcel-hub', null); // $rootScope.getCourierAccounts(); //} $uibModalInstance.close(CourierAccount); }, function () { }); }; $scope.GetInfo = function () { CourierAccountService.GetInfo($scope.CourierAccount.OperationZone.OperationZoneId).then(function (response) { $scope.LogisticCompanies = response.data.LogisticCompanies; if (mode === "Modify") { for (var i = 0; i < $scope.LogisticCompanies.length; i++) { if ($scope.CourierAccount.LogisticService.LogisticCompany === $scope.LogisticCompanies[i].Value) { $scope.CourierCompany = $scope.LogisticCompanies[i]; break; } } } else { $scope.CourierCompany = $scope.LogisticCompanies[0]; } $scope.LogisticRateTypes = response.data.LogisticRateTypes; if (mode === "Edit") { for (var j = 0; j < $scope.LogisticRateTypes.length; j++) { if ($scope.CourierAccount.LogisticService.RateType === $scope.LogisticRateTypes[j].Value) { $scope.RateType1 = $scope.LogisticRateTypes[j]; break; } } } else{ $scope.RateType1 = $scope.LogisticRateTypes[0]; } $scope.LogisticTypes = response.data.LogisticTypes; if (mode === "Modify") { for (var k = 0; k < $scope.LogisticTypes.length; k++) { if ($scope.CourierAccount.LogisticService.LogisticType === $scope.LogisticTypes[k].Value) { $scope.LogisticType1 = $scope.LogisticTypes[k]; break; } } } else { $scope.LogisticType1 = $scope.LogisticTypes[0]; } $scope.ModuleType = response.data.ModuleType; }); }; function init() { $scope.EasyPostCourierAccountsList = []; $scope.ParcelHubCourierAccountsList = []; $scope.LogisticTypeValue = ""; $scope.IsLogisticTypeSelected = false; if (mode !== undefined) { $translate(mode).then(function (mode) { $scope.Mode = mode; }); } CourierAccountService.GetOperationZones().then(function (response) { $scope.OperationZones = response.data; $scope.OperationZoneId = response.data.OperationZoneId; if ($scope.OperationZones) { if (mode === "Add") { $scope.CourierAccount.OperationZone = $scope.OperationZones[0]; $scope.GetInfo(); } else { $scope.CourierAccount.OperationZone = CourierAccount.OperationZone; $scope.GetInfo(); } } }, function () { }); $scope.CourierAccount = CourierAccount; $scope.CourierAccount.OperationZone = CourierAccount.OperationZone; if (mode === "Add") { } else { $scope.CourierAccount.OperationZone = CourierAccount.OperationZone; } setModalOptions(); } init(); });
'use strict'; var Message = require('../message'); var inherits = require('util').inherits; var npwcore = require('npwcore-lib'); var BufferUtil = npwcore.util.buffer; /** * Masternode ping message * @extends Message * @param {Object} options * @constructor */ function MnpMessage(arg, options) { Message.call(this, options); this.command = 'mnp'; } inherits(MnpMessage, Message); MnpMessage.prototype.setPayload = function() {}; MnpMessage.prototype.getPayload = function() { return BufferUtil.EMPTY_BUFFER; }; module.exports = MnpMessage;
import * as React from 'react'; import Card from 'material-ui/Card'; import IndicatorContent from './IndicatorContent.js'; import { Route } from "react-router-dom"; class IndicatorCard extends React.Component { render() { return ( <Card style={{ position: 'absolute', left: '45px', width: '440px',top: '75px' }} containerStyle={{ boxShadow: "rgba(0, 0, 0, 0.25) 0px 14px 45px, rgba(0, 0, 0, 0.22) 0px 10px 18px" }}> <Route path={window.basepath + "indicator/:id/:iso3?"} render={props=><IndicatorContent {...props} map={this.props.map}/> }/> </Card> ); } } export default IndicatorCard;
import React, { Component } from "react"; import FakeTweet from "fake-tweet"; import './App.css'; import "fake-tweet/build/index.css"; class Tweet extends Component { render() { const details = this.props.details; return ( <div className="App"> <FakeTweet config={details} /> </div> ); } } export default Tweet;
const express = require('express'); const app = express(); const cors = require('cors') const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const useRouter = require('./rourters/userRouter'); const nasaRouter = require('./rourters/nasaPictureRouter'); const dotenv = require('dotenv'); dotenv.config(); app.use(bodyParser.json({ limit: "500mb", extended: false })); app.use(bodyParser.urlencoded({ limit: "500mb", extended: false })); const options = cors.CorsOptions = { allowedHeaders: ["Origin", "X-Requested-With", "Content-Type", "Accept", "X-Access-Token"], credentials: true, methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE", preflightContinue: false }; app.use(cors()); app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); next(); }); const connectionParams = { newUrlParser: true, useCreateIndex: true, useUnifiedTopology: true } mongoose.connect(process.env.DB_CONNECT, connectionParams) .then(() => { console.log('connected db') }) .catch((err) => { console.log(`err connected${err}`) }) app.use('/user', useRouter) app.use('/picture', nasaRouter) app.listen(3000, () => console.log('listening port 3000'));
var Router = require('./router'); var test = require('./models/test'); module.exports = App = function App() {}; App.prototype.start = function(){ router = new Router(); Backbone.history.start(); };
exports.getBriefTxs = function (txs) { const res = [] txs.forEach(tx => { tx = { hash: tx.hash, type: tx.type, raw: tx.raw.fee ? { fee: tx.raw.fee } : null } res.push(tx); }); return res; }
import React from 'react'; import { Grid, Container, Typography, Paper, Link } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; import arrowRight from '../../../../../../assets/images/arrowRight.svg' const useStyles = makeStyles(theme => ({ arrowRight: { "&:hover": { stroke:"#F84F06" } } })); export default function ArrowRight({ display = "block" }) { const classes = useStyles(); return ( <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg" display={display}> <path d="M12.5 5L19.5 12L12.5 19" className={classes.arrowRight} stroke="#636364" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg> ); };
jQuery(document).ready(function($) { document.getElementById('calm').play(); var box = $('.box'); $(window).scroll(function() { if ( $(this).scrollTop() >= $('#box2').offset().top ) { box.addClass('glitched'); document.getElementById('calm').pause(); document.getElementById('glitch').play(); $('h1').addClass('glitched-text'); function removeAll() { $('body *').not('.finish, .finish h1').remove(); $('.finish').css('display', 'block'); } setTimeout(removeAll, 10000); var title = $('title'), titles = [ 'hacked', 'game over', 'you are done', 'goodbye', 'njkdfv', 'sskllms', 'klfsll', 'fklsls', ',lvkf,vl', 'OVER', ',kldss', 'mqmq;', 'glfs;m', 'vm;msl,m' ], random = Math.floor(Math.random() * titles.length); console.log(random); function changeTitle() { setInterval (function() { title.text(titles[random]); }, 10); } changeTitle(); } }); });
import React, { Component } from "react"; import "./styles.scss"; import { connect } from "react-redux"; import { getSuppliesList } from "../../../redux/actions/suppliesActions "; import { getSupplyFamiliesList } from "../../../redux/actions/supplyFamiliesActions"; import { removeAlert } from "../../../redux/actions/alertsActions"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faPlusCircle } from "@fortawesome/free-solid-svg-icons"; import Alert from "../../Alert/Alert"; import Modal from "../../Modal/Modal"; import SupplyDetails from "../../SupplyDetails/SupplyDetails"; class SuppliesList extends Component { state = { showModal: false, selectedSupplyId: "", isForNewSupply: false }; componentDidMount() { const { idToken } = this.props.auth; const { supplyFamiliesList } = this.props.supplyFamilies; if (supplyFamiliesList.length === 0) { this.props.getSupplyFamiliesList(idToken); } this.props.getSuppliesList(idToken); } componentWillUnmount() { this.props.removeAlert("getSupplyFamiliesList"); this.props.removeAlert("getSuppliesList"); } closeModal = () => { this.setState({ showModal: false }); }; openEditModal = e => { this.setState({ showModal: true, selectedSupplyId: e.currentTarget.id, isForNewSupply: false }); }; openCreateModal = () => { this.setState({ showModal: true, selectedSupplyId: "", isForNewSupply: true }); }; render() { const { showModal, selectedSupplyId, isForNewSupply } = this.state; const { suppliesList } = this.props.supplies; return ( <div className="container mt-3"> <div className="row"> <div className="col"> <Alert triggeredBy={["getSuppliesList", "getSupplyFamiliesList"]} /> <div className="d-flex"> <h1>Insumos</h1> <FontAwesomeIcon icon={faPlusCircle} size={"2x"} className="ml-auto mt-1 text-success" onClick={this.openCreateModal} /> </div> {suppliesList.length > 0 ? ( <React.Fragment> <table className="table table-striped table-hover"> <thead> <tr> <th scope="col">Descripcion</th> <th scope="col" className="d-none d-lg-table-cell"> Familia </th> <th scope="col">Costo</th> </tr> </thead> <tbody> {suppliesList.map(supply => ( <tr key={supply._id} id={supply._id} className="cursor-pointer" onClick={this.openEditModal} > <td>{supply.description}</td> <td className="d-none d-lg-table-cell"> {supply.family.name} </td> <td>{supply.cost}</td> </tr> ))} </tbody> </table> </React.Fragment> ) : null} <Modal show={showModal} closeModal={this.closeModal} title="Detalle de insumo" > <SupplyDetails selectedSupplyId={selectedSupplyId} isForNewSupply={isForNewSupply} closeModal={this.closeModal} /> </Modal> </div> </div> </div> ); } } const mapStateToProps = state => { return { auth: state.authReducer, supplies: state.suppliesReducer, supplyFamilies: state.supplyFamiliesReducer }; }; const mapDispatchToProps = { getSuppliesList, getSupplyFamiliesList, removeAlert }; export default connect( mapStateToProps, mapDispatchToProps )(SuppliesList);
import React, {Component} from 'react'; import PropTypes from 'prop-types' import {connect} from "react-redux"; import {scrollingPage} from "../../actions"; class ScrollListener extends Component { static propTypes = { currentOffset: PropTypes.number.isRequired, oldOffset: PropTypes.number.isRequired, }; handleScroll = () => { this.props.scrollingPage({ currentOffset: window.pageYOffset, oldOffset: this.props.oldOffset }); }; componentWillMount() { window.addEventListener("scroll", (e)=> { this.handleScroll(e); }) } componentWillUnmount() { window.removeEventListener("scroll", (e)=> { this.handleScroll(e); }) } render() { return ( <> {this.props.children} </> ) } } const mapStateToProps = store => { return { currentOffset: store.scrollingPage.currentOffset, oldOffset: store.scrollingPage.oldOffset, scrollingDirection: store.scrollingPage.scrollingDirection, } }; const mapDispatchToProps = dispatch => { return { scrollingPage: obj => dispatch(scrollingPage(obj)), } }; export default connect(mapStateToProps, mapDispatchToProps)(ScrollListener);
const BaseXform = require('../base-xform'); class DispBlanksAsXform extends BaseXform { get tag() { return 'c:dispBlanksAs'; } render(xmlStream, model) { xmlStream.leafNode(this.tag, {val: 'gap'}); // xmlStream.leafNode(this.tag, {val: model.dispBlanksAs}); } parseOpen(node) { // if (node.name === this.tag) { // this.model = { // dispBlanksAs: node.attributes.dispBlanksAs, // }; // return true; // } // return false; } parseText() {} parseClose() { return false; } } module.exports = DispBlanksAsXform;
import { Chevron } from 'shared/components/navigation/primary.mjs' import { CoreSettingList as ListSetting } from './core-setting-list.mjs' import { CoreSettingOnly as OnlySetting } from './core-setting-only.mjs' import { CoreSettingMm as MmSetting } from './core-setting-mm.mjs' import { CoreSettingNr as NrSetting } from './core-setting-nr.mjs' import { CoreSettingBool as BoolSetting } from './core-setting-bool.mjs' import { CoreSettingSaBool as SaBoolSetting } from './core-setting-sa-bool.mjs' import { CoreSettingSaMm as SaMmSetting } from './core-setting-sa-mm.mjs' import { formatMm } from 'shared/utils.mjs' import { SecText, Li, Details, Summary, SumDiv, Deg, } from 'shared/components/workbench/menu/index.mjs' import { useTranslation } from 'next-i18next' const settings = { paperless: (props) => <SecText>{props.t(props.gist.paperless ? 'yes' : 'no')}</SecText>, complete: (props) => <SecText>{props.t(props.gist.complete ? 'yes' : 'no')}</SecText>, debug: (props) => <SecText>{props.t(props.gist.debug ? 'yes' : 'no')}</SecText>, locale: (props) => <SecText>{props.t(`i18n:${props.gist.locale}`)}</SecText>, units: (props) => <SecText>{props.t(`${props.gist.units}Units`)}</SecText>, margin: (props) => <SecText raw={formatMm(props.gist.margin, props.gist.units)} />, scale: (props) => props.gist.scale === 1 ? ( <SecText>{props.gist.scale}</SecText> ) : ( <span className="text-accent">{props.gist.scale}</span> ), saMm: (props) => <SecText raw={formatMm(props.gist.saMm, props.gist.units)} />, renderer: (props) => <SecText>{props.config.titles[props.gist.renderer]}</SecText>, only: (props) => props.gist?.only && props.gist.only.length > 0 ? ( <SecText>{props.gist.only.length}</SecText> ) : ( <span className="text-secondary-focus">{props.t('default')}</span> ), } const inputs = { locale: (props) => ( <ListSetting {...props} list={props.config.list.map((key) => ({ key, title: props.t(`i18n:${key}`), }))} /> ), units: (props) => ( <ListSetting {...props} list={props.config.list.map((key) => ({ key, title: props.t(`${key}Units`), }))} /> ), margin: (props) => <MmSetting {...props} {...props.config} />, scale: (props) => <NrSetting {...props} {...props.config} />, saMm: (props) => <SaMmSetting {...props} {...props.config} />, renderer: (props) => ( <ListSetting {...props} list={props.config.list.map((key) => ({ key, title: props.config.titles[key], }))} /> ), only: (props) => <OnlySetting {...props} />, } export const Setting = (props) => { const { t } = useTranslation(['app', 'i18n', 'settings']) if (props.setting === 'saBool') return <SaBoolSetting {...props} {...props.config} /> if (['paperless', 'complete', 'debug', 'xray'].indexOf(props.setting) !== -1) return <BoolSetting {...props} {...props.config} /> const Input = inputs[props.setting] const Value = settings[props.setting] return ( <Li> <Details> <Summary> <SumDiv> <Deg /> {props.setting === 'saMm' ? ( <> <span>{t(`settings:sa.t`)}</span> </> ) : ( <span>{t(`settings:${props.setting}.t`)}</span> )} </SumDiv> <Value setting={props.setting} {...props} t={t} /> <Chevron /> </Summary> <Input {...props} t={t} /> </Details> </Li> ) }
const { weatherforecast_7days } = require('../components/weatherforecast7days'); async function weather_forecast_7days(req, res, next) { console.log('request weather forecast 7 days'); let { Province } = req.body; const data = await weatherforecast_7days(Province); console.log(data); if (data) { return res.json({ status: 'success', Provinces: data.Provinces[0] }); } else { return res.json({ status: 'fail', msg: 'Please search for a valid city 😩', }); } } const https = require('https'); const xml2js = require('xml2js'); const fs = require('fs'); async function rain_regions(req, res, next) { console.log( '===============================Rain Regions==================================' ); let url = 'https://data.tmd.go.th/api/RainRegions/v1/?uid=u63glasrice&ukey=3e296702720f633d0a819d0f90c35deb'; var request = https.request(url, function (returnData) { var data = ''; returnData.on('data', function (chunk) { data += chunk; }); returnData.on('end', function () { xml2js.parseString(data, { mergeAttrs: true }, (err, result) => { if (err) { throw err; } const jsonData = JSON.stringify(result.RainRegions.Version).replace( /\\/g, '' ); // fs.writeFileSync('data1.json', jsonData); fs.writeFileSync( 'data2.json', JSON.stringify(result.RainRegions.Version) ); return res.json({ status: 'success', data: jsonData, }); // fs.writeFileSync('data1.json', jsonData); // console.log(jsonData.RainRegions); }); }); }); request.on('error', function (e) { console.log(e.message); }); request.end(); } module.exports.weather_forecast_7days = weather_forecast_7days; module.exports.rain_regions = rain_regions;
module.exports = db => ({ add: (user) => db.none('INSERT INTO users(email, picture, name) VALUES(${email}, ${picture}, ${name})', user), findByEmail: email => db.oneOrNone('SELECT * FROM users WHERE email LIKE $1', email), all: () => db.any('SELECT * FROM users') })
const express = require("express"); const router = express.Router(); const Product = require("../server/models/productModel"); const auth = require("../server/middlewares/auth"); const admin = require("../server/middlewares/admin"); const productController = require("../server/Controllers/productController"); router.route("/top-3-products").get(productController.topRatedProdcuts); router .route("/") .get(productController.getAllProducts) .post(auth, admin, productController.createProduct); router .route("/delete/:id") .delete(auth, admin, productController.deleteProduct); router.route("/:id").get(productController.getProduct); router.route("/:id/reviews").post(auth, productController.createReview); router.route("/edit/:id").put(auth, admin, productController.updateProduct); module.exports = router;
// Style var btnStyle = document.querySelector(".btnStyle"); var p = document.querySelector(".p"); btnStyle.onclick = function() { p.classList.toggle("active"); } // Ajouter noms var ajout = document.querySelector("#ajout"); var noms = new Array; ajout.onclick = function() { var nom = prompt("Entrez votre nom : ", ""); noms.push(nom); document.querySelector(".boxNoms").innerHTML=noms; } // Jouer var jouer = document.querySelector(".jouer"); jouer.onclick = function() { var i = Math.floor(Math.random() * noms.length); document.querySelector(".winner").innerHTML=noms[i]; }
const auth = require('../config/auth.json'); const commandService = require('./services/commandService.js'); const Discord = require('discord.js'); const client = new Discord.Client(); const ownerID = require('../config/owner.json').id; const commandChar = "!"; client.login(auth.token); // client.on('debug', console.log); client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); }); client.on('message', msg => { if (msg.author.bot || !msg.content.startsWith(commandChar)) return; let args = msg.content.slice(commandChar.length).trim().split(' '); let cmd = args.shift().toLowerCase(); commandService.handle(client, msg, cmd, args); });
var spServiceCache = (function ($) { var cache = {}; var sanitizeResource = function (resource) { var resArray = resource && resource.match(/^(.*)\?/); return resArray && resArray.length > 1 ? resArray[1] : resource; } return { isCached: function (resource) { // return sanitizeResource(resource) in cache; Caching is disabled at the moment return false; }, getData: function (resource) { return cache[sanitizeResource(resource)]; }, putData: function (resource, data) { if (resource != undefined && resource != "") { cache[sanitizeResource(resource)] = data; } }, getCache: function () { return cache; }, clearCache: function () { cache = {}; } }; })(jQuery);
/* we use objects to group different variables in arrays postiion matters but in objects it doesnt matter */ let john = { name: "john", // first name is the key and the name john is the value lastName: "smith", birthYear: "1997", familyMembers: ["jane","kurt","bob","shannon"], job: "teacher", isMarried:false } //you use curly brackets to store objects //how we access the object we use the dot notation console.log(john.name) console.log(john["lastname"]) let x = "birthYear" console.log(john[x]) //if you want to change the value john.job = "drug dealer" john['isMarried'] = true let jane = new Object() jane.name = "jane" jane.birthYear = "2001" jane["lastYear"] = "smith" // here we created a new objected and used the dot notation to add new vaulues to the key variable
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsPregnantWoman = { name: 'pregnant_woman', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M9 4c0-1.11.89-2 2-2s2 .89 2 2-.89 2-2 2-2-.89-2-2zm7 9a3.285 3.285 0 00-2-3c0-1.66-1.34-3-3-3s-3 1.34-3 3v7h2v5h3v-5h3v-4z"/></svg>` };
$(document).ready(function() { var timeBlocks = []; init(); function init() { $("#currentDay").text(moment().format("dddd, MMMM Do")); storeHours(); renderDescriptions(); } function determineHourState() { timeBlocks.forEach(function(hour) { var timeSlotHour = moment().hour(hour); var timeSlotContainer = $(".container"); if ((moment().isAfter(timeSlotHour))) { timeSlotContainer.find("#" + hour).addClass("past"); } else if ((moment().isBefore(timeSlotHour))) { timeSlotContainer.find("#" + hour).addClass("future"); } else { timeSlotContainer.find("#" + hour).addClass("present"); } }); } function storeHours() { $(".time-block").each(function(i, element) { timeBlocks.push($(element).attr("id")); }); determineHourState(); } function renderDescriptions() { for (var i = 0; i < localStorage.length; i++) { var key = localStorage.key(i); var descriptionText = localStorage.getItem(key); $(".container").find("#"+key+" textarea").val(descriptionText); }; } $(".button-save").on("click", function(event) { event.preventDefault(); var description = $(this).siblings(".description").val().trim(); var hour = $(this).parent().attr("id"); if (description == "") { return } localStorage.setItem(hour, description); renderDescriptions(); }); });
const state = {game: {leftScore: 0, rightScore: 0}}; const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const playButton = document.getElementById('playButton'); export function setup(game) { let throttle = false; function moveMouse(e) { const y = Math.min(Math.max(40, e.pageY - canvas.offsetTop), canvas.height - 40); if (!throttle) { game.trigger('move', {y}); throttle = true; setTimeout(() => { throttle = false; }, 33); } } function ready() { document.onmousemove = moveMouse; game.trigger('ready'); } playButton.onclick = function () { playButton.style.display = 'none'; ready(); }; game.handlePush = ({event, payload}) => { switch (event) { case 'join': break; default: state[event] = payload; draw(); } }; } export function draw() { ctx.fillStyle = '#333'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = 'rgb(64,64,64)'; const size = 4; for (let y = 0; y < canvas.height; y += size * 3) { ctx.fillRect(canvas.width / 2 - size / 2, y, size, size); } ctx.fillStyle = 'rgba(128,128,128,.6)'; ctx.font = '48px sans-serif'; const leftScoreSize = ctx.measureText(state.game.leftScore); ctx.fillText(state.game.leftScore, 200 - leftScoreSize.width / 2, 60); const rightScoreSize = ctx.measureText(state.game.rightScore); ctx.fillText(state.game.rightScore, 600 - rightScoreSize.width / 2, 60); if (state.game.left && state.game.right && state[state.game.left] && state[state.game.right]) { ctx.fillStyle = 'rgba(192,192,192,0.8)'; ctx.fillRect(0, state[state.game.left].y - 40, 4, 80); ctx.fillRect(796, state[state.game.right].y - 40, 4, 80); } if (state.game.countDown) { ctx.font = '96px sans-serif'; const size = ctx.measureText(state.game.countDown); ctx.fillStyle = 'rgba(128,128,128,.6)'; ctx.beginPath(); ctx.arc(400, 300, 50, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle = 'rgb(192,192,192)'; ctx.fillText(state.game.countDown, 400 - size.width / 2, 334); } else if (state.ball) { ctx.fillStyle = 'rgba(192,192,192,0.8)'; ctx.beginPath(); ctx.arc(state.ball.x, state.ball.y, state.ball.radius, 0, 2 * Math.PI); ctx.fill(); } }
import View from './view.js'; // import icons from 'url:../../img/icons.svg'; class SearchResultsView extends View { constructor() { super(); this._searchBtn = document.querySelector('.search__btn'); this._parentElement = document.querySelector('.results'); this._errorMessage = 'Sorry, we could not find any results for that search, try searching with another term.'; } _getSearch() { return document.querySelector('.search__field').value; } clearSearch() { document.querySelector('.search__field').value = ''; } addHandler(handler) { this._searchBtn.addEventListener('click', e => { e.preventDefault(); handler(this._getSearch()); }); } _generateMarkup(data) { //prettier-ignore const html = `${data.map(item => { return `<li class="preview"> <a class="preview__link" href="#${item.id}"> <figure class="preview__fig"> <img src="${item.image}" alt="${item.title}" /> </figure> <div class="preview__data"> <h4 class="preview__title">${item.title}</h4> <p class="preview__publisher">${item.publisher}</p> </div> </a> </li>` }).join('')}`; return html; } } export default new SearchResultsView();
const { ViewHelper } = require('components/View') const Factory = require('utilities/factory') const WithHeader = ViewHelper('header') const makeHeader = Factory(WithHeader) module.exports = { default: makeHeader, makeHeader, WithHeader }
import React from 'react'; import { Form, Button, Icon } from 'semantic-ui-react'; import { Link } from 'react-router-dom'; import { signin, signInWithGoogle } from '../helpers/auth'; export default class Login extends React.Component { constructor(props) { super(props); this.state = { error: null, email: '', password: '' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.googleSignIn = this.googleSignIn.bind(this); } handleChange(event) { this.setState({ [event.target.name]: event.target.value }); } async handleSubmit(event) { event.preventDefault(); this.setState({error: ''}); try { await signin(this.state.email, this.state.password); } catch(error) { this.setState({error: error.message}); } } async googleSignIn() { try { await signInWithGoogle(); } catch (error) { this.setState({error: error.message}); } } render() { return ( <Form onSubmit={this.handleSubmit}> <div className="account-header"> <h2>Log in to MedBase</h2> <p>Don't have an account? <Link to="/signup">Sign up here</Link>!</p> </div> <div className="account-forms"> <fieldset className="login-container"> <legend>Log in with email &amp; password</legend> <div className="formRow"> <label htmlFor="email">Email Address</label> <input id="email" placeholder="email@server.com" name="email" type="email" onChange={this.handleChange} value={this.state.email} /> </div> <div className="formRow"> <label htmlFor="password">Password</label> <input id="password" placeholder="Password" name="password" type="password" onChange={this.handleChange} value={this.state.password} /> </div> <div className="formRow"> {this.state.error ? ( <p>{this.state.error}</p> ): null } <Button primary type="submit">Log In</Button> </div> </fieldset> <fieldset className="login-container"> <legend>Log in with your Google account</legend> <Button type="button" color="red" onClick={this.googleSignIn}> <Icon name="google" /> &nbsp; Sign In with Google </Button> </fieldset> </div> </Form> ) } }
const AbidjanRadioButton = document.getElementById('inlineRadio1'); const OtherRadioButton = document.getElementById('inlineRadio2'); const CommuneEntry = document.getElementById('Commune'); const OthersCitySelect = document.getElementById('OthersCity'); AbidjanRadioButton.addEventListener('click', function() { console.log("jai cliquers"); OthersCitySelect.style.display = 'none'; CommuneEntry.style.display = 'block'; }); OtherRadioButton.addEventListener('click', function() { console.log("jai cliquer"); CommuneEntry.style.display = "none"; OthersCitySelect.style.display = 'block'; })
'use strict'; module.exports = (app, lando) => { // Merge some stuff into the lando object and its config return {}; };
var friendsData = [ { name: "John", photo: "https://vignette.wikia.nocookie.net/happytreefriends/images/e/e9/RusselZ.png/revision/latest?cb=20170115232854", scores: [ 5, 4, 3, 4, 5, 3, 1, 5, 4, 3 ] }, { name: "Sandra", photo: "https://vignette.wikia.nocookie.net/happytreefriends/images/7/7a/PetuniaProfilePictureImage.png/revision/latest?cb=20170728192603", scores: [ 4, 5, 5, 5, 5, 5, 5, 5, 5, 1 ] }, { name: "Kirk", photo: "https://vignette.wikia.nocookie.net/happytreefriends/images/3/3e/Handy_profile.png/revision/latest?cb=20170728192424", scores: [ 5, 5, 4, 5, 4, 3, 5, 5, 5, 5 ] }, { name: "Sandy", photo: "https://vignette.wikia.nocookie.net/happytreefriends/images/4/4f/Toothy%27s_profile_Z_recolor.png/revision/latest?cb=20170728191750", scores: [ 2, 3, 3, 4, 2, 3, 3, 3, 3, 2 ] }, { name: "Tammy", photo: "https://vignette.wikia.nocookie.net/happytreefriends/images/f/f8/Lammy.png/revision/latest?cb=20170110162229&path-prefix=es", scores: [ 1, 1, 3, 4, 2, 3, , 3, 3, 2 ] }, ]; // Note how we export the array. This makes it accessible to other files using require. module.exports = friendsData;
let rooms = { "start": { "description": "You are in a dark, musty room. You can see a faint light to the <b>north</b> and you hear a distant tapping to the <b>west</b><p> Type Help for list of commands.</p>", "directions": { "north": "clearing1", "west": "bridge1" } }, "clearing1": { "description": "You exit the dark, musty room and end up in a open clearing, you see a lighthouse to the <b>north</b> and there is a strange smell coming form the <b>east</b>", "directions": { "north": "lighthouse", "south": "start", "east": "trolls" } }, "lighthouse": { "description": "You arrive at the lighthouse and walk up to the door. A strange old lady opens the door, what do you do?", "directions": { "south": "clearing1" }, "npc": { "old lady": "The old lady farts" } }, "trolls": { "description": "You enter another clearing, there are some trolls. They haven't seen you yet. What do you do?", "directions": { "west": "clearing1" } }, "bridge1": { "description": "You You see a river and there is a bridge to the <b>west</b>.", "directions": { "east": "start", "west": "bridge2" } }, "bridge2": { "description": "You try to cross the bridge but a troll jumps out and bites you", "directions": { "east": "bridge1" } } }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Search extends Component { render () { return ( <div className='input-box'> <h1 className='header-text'>Headcount 2.0</h1> <input className='search-input' type='text' placeholder='Filter districts' onChange={(event) => this.props.updateCards(event.target.value)} /> </div> ); } } Search.propTypes = { updateCards: PropTypes.func }; export default Search;
// export const ACCESSTAB = "ACCESSTAB" export const OMANAGERTAB = "OMANAGERTAB" export const IMANAGERTAB = "IMANAGERTAB" export const PMANAGERTAB = 'PMANAGERTAB' export const switchAccessTab = reddit => ({ type:ACCESSTAB, reddit }) export const switchOmanagerTab = reddit =>({ type: OMANAGERTAB, reddit }) export const switchImanagerTab = reddit =>({ type: IMANAGERTAB, reddit }) export const switchPmanagerTab = reddit =>({ type: PMANAGERTAB, reddit })
const { USAGE, AMP_TIME_CANNOT_BE_LESS_THEN_COOKING_TIME, CANNOT_COOK_WITH_THESE_TIMES } = require('../config/messages'), MDC = require('../lib/mdc') /** * Parse process arguments basead on Game Parameters Rules * @param {Array} args game arguments * @returns {Array<Number>} parsed arguments * @throws {Error} if cannot parse params */ function parser (args) { const UsageError = new Error (USAGE) if (args.length !== 3) throw UsageError const parsedValue = args.map(el => { const value = parseInt(el) if (isNaN(value)) throw UsageError return value }) return validate(parsedValue) } /** * Validate Game Parameters * @param {Array} params parsed game parameters * @returns {Array} return the same passed params * @throws {Error} if there are some problem rules */ function validate (params) { const [ cookingTime, hg1, hg2 ] = params if (hg1 <= cookingTime || hg2 <= cookingTime) { throw new Error(AMP_TIME_CANNOT_BE_LESS_THEN_COOKING_TIME) } // the cooking time must have an exact division by the MDC if (cookingTime % MDC(hg1, hg2)) { throw new Error(CANNOT_COOK_WITH_THESE_TIMES) } return params } /** * Expose Parser */ module.exports = parser
/* * @lc app=leetcode.cn id=39 lang=javascript * * [39] 组合总和 */ // @lc code=start /** * @param {number[]} candidates * @param {number} target * @return {number[][]} */ var combinationSum = function (candidates, target) { let result = [], arr = [], sum = 0; const backTrack = (index) => { if (sum === target) { result.push([...arr]); return; } if (sum > target) return; for (let i = index; i < candidates.length; i++) { arr.push(candidates[i]); sum += candidates[i]; backTrack(i); sum -= candidates[i]; arr.pop(); } }; backTrack(0); return result; }; // @lc code=end
const KoaRouter = require('koa-router'); const index = require('./routes/index'); const locals = require('./routes/locals'); const users = require('./routes/users'); const requests = require('./routes/requests'); const activities = require('./routes/activities'); const store = require('./routes/store'); const api = require('./routes/api'); const router = new KoaRouter(); router.use(async (ctx, next) => { Object.assign(ctx.state, { index: ctx.router.url('index'), signIn: ctx.router.url('users-login'), logOut: ctx.router.url('users-logout'), signUp: ctx.router.url('users-signup'), allLocalsPath: ctx.router.url('locals'), profileUserPath: ctx.router.url('userProfile'), activitiesPath: ctx.router.url('activities'), storePath: ctx.router.url('store'), }); return next(); }); router.use(async (ctx, next) => { if (ctx.session.currentUser) { ctx.state.currentUser = ctx.session.currentUser; } return next(); }); router.use('/', index.routes()); router.use('/locals', locals.routes()); router.use('/users', users.routes()); router.use('/requests', requests.routes()); router.use('/activities', activities.routes()); router.use('/store', store.routes()); router.use('', api.routes()); module.exports = router;
const mongoose = require('mongoose'); const CourseSchema = mongoose.Schema({ name:{ type: String, required : true }, desciption:{ type:String, required : true }, type:{ type:String, required:true }, link:{ type:String }, content:{ type:Array } //rate + author }) const course = mongoose.model('Course',CourseSchema); module.exports = course;
import Box from '../Box' import { forwardProps } from '../utils' import { baseProps } from '../config/props' export default { name: 'CText', // <-- Vue does not allow components to be registered using built-in or reserved HTML elements as component id: like "Text". So need to rename this. inject: ['$theme', '$colorMode'], props: { as: { type: [String, Array], default: 'p' }, ...baseProps }, render (h) { return h(Box, { props: { as: this.as, fontFamily: this.as === 'kbd' ? 'mono' : 'body', ...forwardProps(this.$props) } }, this.$slots.default) } }
const express = require("express"); const router = express.Router(); const getNext = require("../library/getNext"); /** * Express.js router for /next * Return next scan number with given scan number */ const next = router.get('/next', function(req, res) { console.log("Hello, next!"); const projectDir = req.query.projectDir; const scanID = req.query.scanID; getNext(projectDir, scanID, function (err, row) { let nextID = row.next.toString(); res.write(nextID); res.end(); }) }); module.exports = next;
define([ 'apps/system3/statistics/statistics'], function (app) { app.module.factory("statisticsConService", function ($rootScope, Restangular, stdApiUrl, stdApiVersion) { var restSrv = Restangular.withConfig(function (configSetter) { configSetter.setBaseUrl(stdApiUrl + stdApiVersion); }) return { } }); });
import { combineReducers } from "redux"; import { configureStore } from "redux-starter-kit"; import playerReducer from "store/slices/player"; import gameReducer from "store/slices/game"; import levelReducer from "store/slices/level"; const reducer = combineReducers({ player: playerReducer, game: gameReducer, level: levelReducer, debug: () => false }); const store = configureStore({ reducer }); // Save state to local storage whenever it changes store.subscribe(() => { let state = JSON.stringify(store.getState()); window.localStorage.setItem("state", state); }); export default store;
import Dialog from '@material-ui/core/Dialog'; import DialogTitle from '@material-ui/core/DialogTitle'; import React, { useContext } from 'react'; import DialogContent from '@material-ui/core/DialogContent'; import Typography from '@material-ui/core/Typography'; import { FormContext } from '../Form/FormStateContext'; export function Modal() { const { formState, setFormState } = useContext(FormContext); const handleClose = () => { setFormState({ method: 'setShowModal', showModal: false, }); }; return ( <div> <Dialog aria-labelledby="simple-dialog-title" open={formState.showModal} onClose={handleClose} > <DialogTitle> <h3>Bravo</h3> <DialogContent> <Typography>You submitted the form successfully</Typography> </DialogContent> </DialogTitle> </Dialog> </div> ); }
let dates = new Date(); let date = dates.getDate(); console.log(date); let day = dates.getDay(); let week_days = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", }; day = week_days[day]; // console.log(day) let hour = dates.getHours(); // console.log(hour) let minutes = dates.getMinutes(); // console.log(minutes) document.querySelector("#smalltime").innerHTML = hour + ":" + minutes; document.querySelector("#timenow").innerHTML = hour + ":" + minutes; document.querySelector("#daytoday").innerHTML = day;
import LoginUser from './Authentication/Login' import EditContent from './Edit/EditContent' import {BrowserRouter as Router, Switch, Route} from 'react-router-dom' import './App.css' function App() { return( <Router> <Switch> <Route path="/" exact component={LoginUser} /> <Route path="/edit" exact component={EditContent} /> </Switch> </Router> ) } export default App;
import Control from '../control'; const MenuSeparator = Control.extend({ }); export default MenuSeparator;
const { buildSchema } = require("graphql"); module.exports = buildSchema(` type Album { _id: ID! userId: String! name: String! title: String! access: String description: String status: String! photos: [String] createdAt: String! } input AlbumInputData { userId: String! name: String! title: String! access: String description: String status: String! createdAt: String! } type RootMutation { addAlbum(albumInput: AlbumInputData): Album! removeAlbum(albumId: String!): Album! } type RootQuery { fetchAlbums(userId: String!, status: String!, access: String!): [Album]! } schema { query: RootQuery mutation: RootMutation } `);
require('mocha-as-promised')(); var vumigo = require("vumigo_v02"); var app = require("../lib/go-ndoh"); var assert = require('assert'); var GoNDOH = app.GoNDOH; var AppTester = vumigo.AppTester; fixtures = require('./fixtures'); describe('app', function () { var app; var tester; beforeEach(function () { app = new GoNDOH(); // mock out the time app.get_timestamp = function() { return '20130819144811'; }; app.get_uuid = function() { return 'b18c62b4-828e-4b52-25c9-725a1f43fb37'; }; tester = new AppTester(app); tester .setup.config.app({ jembi: { username: 'foo', password: 'bar', url: 'http://test/v1/' } }) .setup.user({addr: 'user_default'}) .setup(function(api) { fixtures().forEach(api.http.fixtures.add); }); }); it('should ask for the patients name', function() { return tester .start() .check.reply([ 'Welcome to the Pregnancy Registration Vumi Demo.', 'What is your name?' ].join('\n')) .check.user.state('states:name') .run(); }); it('should ask for the patients surname', function() { return tester .setup.user.state('states:name') .input('Simon') .check.reply('What is your surname?') .check.user.state('states:surname') .run(); }); it('should ask for the patients dob', function() { return tester .setup.user.state('states:surname') .input('de Haan') .check.reply('What is your date of birth? (YYYY-MM-DD)') .check.user.state('states:dob') .run(); }); it('should check the submitted dob format for correctness', function() { return tester .setup.user.state('states:dob') .input('foo') .check.reply('Please provide the date in the YYYY-MM-DD format:') .check.user.state('states:dob') .run(); }); it('should capture the dob and ask for the NID', function() { return tester .setup.user.state('states:dob') .input('1980-7-30') .check.reply('Please enter the first 4 digits of your National ID:') .check.user.state('states:nid_1') .run(); }); it('should capture the first 4 digits of the NID', function() { return tester .setup.user.state('states:nid_1') .input('1234') .check.reply('Please enter the second 4 digits of your National ID:') .check.user.state('states:nid_2') .run(); }); it('should capture the second 4 digits of the NID', function() { return tester .setup.user.state('states:nid_2') .input('1234') .check.reply('Please enter the next 4 digits of your National ID:') .check.user.state('states:nid_3') .run(); }); it('should capture the third 4 digits of the NID', function() { return tester .setup.user.state('states:nid_3') .input('1234') .check.reply('Please enter the last 4 digits of your National ID:') .check.user.state('states:nid_4') .run(); }); it('should capture the last 4 digits of the NID', function() { return tester .setup.user.answers({ 'states:nid_1': '1234', 'states:nid_2': '5678', 'states:nid_3': '1234' }) .setup.user.state('states:nid_4') .input('5678') .check.reply([ 'Please confirm your National ID:', '1234567812345678', '', '1. This is correct.', '2. This is incorrect.' ].join('\n')) .check.user.state('states:nid_confirm') .run(); }); it('should allow for correcting of the NID', function() { return tester .setup.user.state('states:nid_confirm') .input('2') .check.reply('Please enter the first 4 digits of your National ID:') .check.user.state('states:nid_1') .run(); }); it('should ask for the date of the last menstruation', function() { return tester .setup.user.state('states:nid_confirm') .input('1') .check.reply('When was your last menstruation? (YYYY-MM-DD)') .check.user.state('states:last_menstruation') .run(); }); it('should check the last menstruation date for correctness', function() { return tester .setup.user.state('states:last_menstruation') .input('foo') .check.reply('Please provide the date in the YYYY-MM-DD format:') .check.user.state('states:last_menstruation') .run(); }); it('should check the pregnancy status', function() { return tester .setup.user.state('states:last_menstruation') .input('2013-09-19') .check.reply([ 'Do you think you are pregnant or has it been confirmed?', '1. I suspect I am pregnant.', '2. It has been confirmed, I am pregnant.' ].join('\n')) .check.user.state('states:pregnancy_status') .run(); }); it('should end the menu and store the contact', function() { return tester .setup.user.state('states:pregnancy_status') .setup.user.answers({ 'states:name': 'Simon', 'states:surname': 'de Haan', 'states:dob': '1980-07-30', 'states:last_menstruation': '2013-09-19', 'states:pregnancy_status': 'suspected', 'states:nid_1': '1234', 'states:nid_2': '5678', 'states:nid_3': '90AB', 'states:nid_4': 'CDEF' }) .input('1') .check.reply('Thank you! Your details have been captured.') .check.user.state('states:end') .check(function (api) { var contact = api.contacts.store[0]; assert.equal(contact.name, 'Simon'); assert.equal(contact.surname, 'de Haan'); assert.equal(contact.dob, '1980-07-30T00:00:00.000Z'); assert.equal(contact.extra.last_menstruation, '2013-09-19T00:00:00.000Z'); assert.equal(contact.extra.pregnancy_status, 'suspected'); assert.equal(contact.extra.nid, '1234567890ABCDEF'); }) .run(); }); it('should allow building of the CDA doc', function () { return tester .setup.user.answers({ 'states:name': 'Simon', 'states:surname': 'de Haan', 'states:dob': '1980-07-30', 'states:last_menstruation': '2013-09-19', 'states:pregnancy_status': 'suspected', 'states:nid_1': '1234', 'states:nid_2': '5678', 'states:nid_3': '90AB', 'states:nid_4': 'CDEF' }) .check(function(api) { var doc = app.build_cda_doc(); var doc_str = doc.toString(); metadata = app.build_metadata(doc_str); assert.equal(metadata.documentEntry.size, doc_str.length); assert.equal(metadata.documentEntry.hash, '607b5e4a22f1a5fc75ef61b490de68e7f76323ac'); }) .run(); }); });
/* const viewMessage = document.getElementById("viewMessage"); const target = document.getElementById("target"); let clickMessages = false viewMessage.addEventListener("click" , function () { clickMessages = !clickMessages if(!clickMessages){ target.className = "hidden"; } else{target.className = "show";} console.log(clickMessages) }) */
// pages/assemble/pin_capital/pin_capital.js const request_01 = require('../../../utils/request/request_01.js'); const method = require('../../../utils/tool/method.js'); const router = require('../../../utils/tool/router.js'); const authorization = require('../../../utils/tool/authorization.js'); const alert = require('../../../utils/tool/alert.js'); const app = getApp(); //获取应用实例 Page({ /** * 页面的初始数据 */ data: { IMGSERVICE:app.globalData.IMGSERVICE, currentAddressItem:{}, storeList:[], pickerStoreList:[], storeIndex:0, positionKey:true, pinDetail:{}, pageType:'', }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { request_01.login(()=>{ this.initData(options) }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { const currentAddressItem = app.globalData.currentAddressItem;//收货人信息 const pinDetail = this.data.pinDetail;//拼团商品信息 this.setData({ currentAddressItem, }) //收货人信息必须填写 if( !currentAddressItem.area )return; //拼团商品 为快递时,不用获取门店 if( pinDetail.type == 2 )return; this.getLocation() }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, //页面初始化 initData(options){ let pinDetail = app.globalData.pinDetail;//获取全局商品信息 const userInfo = wx.getStorageSync('userInfo'); this.setData({ pinDetail, pageType:options.pageType, }) app.globalData.pinDetail = {};//清空全局商品信息 Promise.all([ request_01.defaultAddress({ user_id:userInfo.user_id }) ]) .then((value)=>{ //success const data = value[0].data.data; const toString = {}.toString; if( toString.call(data) == '[object Array]' ){ //为空数组 就是没有默认地址 } else{ //否则有默认地址 app.globalData.currentAddressItem = Object.assign(data, { real_address:data.area.replace(/\s+/g,"") + data.address }) this.onShow() } }) .catch((reason)=>{ //fail }) .then(()=>{ //complete }) }, //数量增减 addAndDelete(e){ const type = e.currentTarget.dataset.type; const pinDetail = this.data.pinDetail; if( type == 'dec' ){//减 if( pinDetail.__number <= 1 )return; pinDetail.__number = pinDetail.__number - 1; } else{//加 return; pinDetail.__number = pinDetail.__number + 1; } this.setData({ pinDetail, }) }, //定位 getLocation(){ const currentAddressItem = this.data.currentAddressItem; alert.loading({ str:'获取门店中' }) this.setData({//定位中关锁 positionKey:false, }) method.getPosition() .then((value)=>{ //success const location = value.result; return request_01.storeList({ city:currentAddressItem.area.split(' ')[1], lon:location.location.lng, lat:location.location.lat, is_groupbuy: 1, }) }) .catch((reason)=>{ //fail return request_01.storeList({ city:currentAddressItem.area.split(' ')[1], lon:'', lat:'', is_groupbuy: 1, }) }) .then((value)=>{ const storeList = value.data.data; const msg = value.data.msg; const status = value.data.status; let pickerStoreList; alert.loading_h() if( status == 1 ){//有门店数据返回 pickerStoreList = storeList.map((item)=>{ return item.name; }) this.setData({ storeList, pickerStoreList, storeIndex:0, }) } else{//门店数据返回出错 this.setData({ storeList:[], pickerStoreList:[], storeIndex:0, }) alert.alert({ str:'门店:' + msg, }) } }) .catch((reason)=>{ //fail this.setData({ storeList:[], pickerStoreList:[], storeIndex:0, }) alert.loading_h() alert.alert({ str:'门店:' + JSON.stringify(reason) }) }) .then(()=>{ //complete this.setData({//定位完开锁 positionKey:true, }) }) }, //获取收货人信息 getInfo(){ const positionKey = this.data.positionKey; if( !positionKey )return;//定位中不能操作 router.jump_nav({//跳转到我的地址页 选择地址 url:'/pages/o_address/o_address?pageType=back' }) }, //选择获取门店 bindPickerChange(e){ const storeIndex = e.detail.value; this.setData({ storeIndex, }) }, //选择获取门店提示 getStore(){ const currentAddressItem = this.data.currentAddressItem;//收货人信息 if( currentAddressItem.area ){//收货人信息必须填写 alert.alert({ str:'该区域没有找到相关门店,或门店相关信息出错' }) } else{//该区域没有门店 alert.alert({ str:'请填写收货人信息' }) } }, //结算 settlement(e){ const form_id = e.detail.formId; const currentAddressItem = this.data.currentAddressItem; const storeList = this.data.storeList; const storeIndex = this.data.storeIndex; const userInfo = wx.getStorageSync('userInfo'); const pinDetail = this.data.pinDetail; const pageType = this.data.pageType; let promise; //收货人信息必填 if( !currentAddressItem.address_id )return alert.alert({ str:'请填写收货人信息' }); //请选择领取的门店 if( !(pinDetail.type == 2) && !storeList.length )return alert.alert({ str:'请选择领取的门店' }); if( pageType == 'faqipintuan' ){//发起拼团 promise = request_01.launchPin({ user_id:userInfo.user_id,//用户id prize_id:pinDetail.prize_id,//拼团商品ID form_id,//form表单id address_id:currentAddressItem.address_id,//收货人信息 id dealer_code:pinDetail.type == 2 ? '' : storeList[storeIndex].code,//门店id 为快递时门店id非必选 }) } else if( pageType == 'lijicantuan' ){//立即参团 promise = request_01.joinPin({ user_id:userInfo.user_id,//用户id groupbuy_id:pinDetail.groupbuy_id,//拼团商品ID form_id,//form表单id address_id:currentAddressItem.address_id,//收货人信息 id dealer_code:pinDetail.type == 2 ? '' : storeList[storeIndex].code,//门店id 为快递时门店id非必选 }) } alert.loading({ str:'结算中' }) promise .then((value)=>{ //success const msg = value.data.msg; const status = value.data.status; const data = value.data.data; alert.loading_h() if( status == 1 ){//拼团成功 if( pageType == 'faqipintuan' ){//发起拼团 router.jump_red({ url:`/pages/assemble/o_pin/o_pin?groupbuy_id=${data.groupbuy_id}&user_id=${userInfo.user_id}`, }) } else if( pageType == 'lijicantuan' ){//立即参团 router.jump_red({ url:`/pages/assemble/o_pin/o_pin?groupbuy_id=${pinDetail.groupbuy_id}&user_id=${userInfo.user_id}`, }) } } else{//拼团失败 alert.alert({ str:msg }) } }) .catch((reason)=>{ //fail alert.loading_h() alert.alert({ str:JSON.stringify( reason ) }) }) .then(()=>{ //complete }) }, })
function getTowns() { var requestURL ='https://byui-cit230.github.io/weather/data/towndata.json' var request = new XMLHttpRequest(); request.open('GET', requestURL); request.responseType = 'json'; request.send(); request.onload = function() { var towns = request.response; console.log(towns); showTowns(towns); } function showTowns(jsonObj) { var towns = jsonObj['towns']; for (var i = 0; i < towns.length; i++) { if (i == 1 || i == 4 || i == 5) { /*----get town data----------*/ /*----setup elements---*/ var section = document.querySelector('.towns'); var myDiv1 = document.createElement('div'); var myDiv2 = document.createElement('div'); var myH3 = document.createElement('h3'); var myPara1 = document.createElement('p'); var myPara2 = document.createElement('p'); var myPara3 = document.createElement('p'); var myPara4 = document.createElement('p'); var myImg = document.createElement('img'); myPara1.setAttribute("class","p1"); myPara2.setAttribute("class","p2"); myPara3.setAttribute("class","p3"); myPara4.setAttribute("class","p4"); myDiv1.setAttribute("class","container"); myDiv2.setAttribute("class","box"); /*---populate elements with town data----*/ myH3.textContent = towns[i].name; myPara1.textContent = towns[i].motto; myPara2.textContent = 'Year Founded: ' + towns[i].yearFounded; myPara3.textContent = 'Population: ' + towns[i].currentPopulation; myPara4.textContent = 'Annual Rain Fall: ' +towns[i].averageRainfall + '"'; if (i==1){ myImg.src='images/fishhavensm.jpg'; myImg.setAttribute("alt","Fish Haven img"); } else if (i==4) { myImg.src='images/prestonsm.jpg'; myImg.setAttribute("alt","Preston img"); } else { myImg.src='images/sodaspringssm.jpg'; myImg.setAttribute("alt","Soda Springs img"); } /*---create the div with the elements and data---*/ myDiv2.appendChild(myH3); myDiv2.appendChild(myPara1); myDiv2.appendChild(myPara2); myDiv2.appendChild(myPara3); myDiv2.appendChild(myPara4); myDiv2.appendChild(myImg); myDiv1.appendChild(myDiv2); section.appendChild(myDiv1); } } } }
function Navigation(level, extension) { document.write("<span class='navlink'>"); document.write("<a href='"+GetPath(level+1)+"Section1/Project1.html'>Basic HTML</a>"); document.write("</span>"); document.write("<br>"); document.write("<span class='navlink'>"); document.write("<a href='"+GetPath(level+1)+"Section3/Project1.php'>PHP</a>"); document.write("</span>"); document.write("<br>"); document.write("<span class='navlink'>"); document.write("<a href='"+GetPath(level)+"Section1/Section2/Index.html'>Javascript</a>"); document.write("</span>"); document.write("<br>"); document.write("<span class='navlink'>"); document.write("<a href='"+GetPath(level+1)+"Section1/Project3.shtml'>Perl</a>"); document.write("</span>"); document.write("<br>"); document.write("<span class='navlink'>"); document.write("<a href='"+GetPath(level)+"Section1/Section4/Index"+GetExtension(extension)+"'>Java</a>"); document.write("</span>"); document.write("<br>"); document.write("<span class='navlink'>"); document.write("<a href='"+GetPath(level)+"Section1/Section5/Index"+GetExtension(extension)+"'>ASP.NET</a>"); document.write("<h5>"); document.write("<span class='navlink'>"); document.write("<a href='http://htkb.dyndns.org:81/WebApplication/Section1/Section5/Project1.cshtml'>Webpage Application</a>"); document.write("</span>"); document.write("<span class='navlink'>"); document.write("<a href='http://htkb.dyndns.org:81/WebForm/Section1/Section5/Project2.aspx'>Webform Application</a>"); document.write("</span>"); document.write("<span class='navlink'>"); document.write("<a href='http://htkb.dyndns.org:81/MVC/Section1_5/Project3'>MVC Application</a>"); document.write("</span>"); document.write("</h5>"); document.write("</span>"); document.write("<br>"); document.write("<span class='navlink'>"); document.write("<a href='"+GetPath(level)+"Section1/Section6/Index"+GetExtension(extension)+"'>Databases</a>"); document.write("</span>"); document.write("<br>"); document.write("<span class='navlink'>"); document.write("<a href='"+GetPath(level)+"Section1/Project7"+GetExtension(extension)+"'>HTML5</a>"); document.write("</span>"); document.write("<br>"); document.write("<span class='navlink'>"); document.write("<a href='"+GetPath(level)+"Section1/Project8"+GetExtension(extension)+"'>XSL</a>"); document.write("</span>"); document.write("<br>"); document.write("<span class='navlink'>"); document.write("<a href='"+GetPath(level)+"Section1/Project9"+GetExtension(extension)+"'>XML DOM</a>"); document.write("</span>"); document.write("<br>"); } function Title(input) { document.write("<title>"); if(input == 0) { document.write("Web Programming"); } document.write("</title>"); } function Header(input) { if(input == 0) { document.write("<h2>"); document.write("<u>"); document.write("ASP.NET Programming"); document.write("</u>"); document.write("</h2>"); } } function Content(input) { document.write("<p align='left'>"); if(input == 0) { document.write("This section is dedicated to ASP.NET programming."); } document.write("</p>"); }
export const EXAMPLE_ENDPOINT = id => { if (!id) { throw new Error('No ID provided for EXAMPLE_ENDPOINT') } return { MY_ENDPOINT: `/my-service/${id}/my-endpoint` } }
/*ДЕНЬ ПЕРВЫЙ*/ // alert(3 + // 1 // + 2);
import React, {Fragment, PureComponent} from 'react'; import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, TouchableOpacity, Image, Dimensions, } from 'react-native'; import {SvgXml} from 'react-native-svg'; import SVG from '../components/SvgComponent'; export default class MyWrote extends PureComponent { constructor(props) { super(props); this.state = {}; } render() { return ( <Fragment> <StatusBar barStyle="dark-content" /> <SafeAreaView /> <ScrollView style={{backgroundColor: '#f3f3f3', flex: 1}}> {/* */} <View style={{ marginTop: 25, marginLeft: 16, marginRight: 16, }}> {/* */} <View style={{ backgroundColor: 'white', borderRadius: 10, marginBottom: 16, }}> <View style={{ flexDirection: 'row', justifyContent: 'space-between', padding: 16, }}> <View style={{ width: 60, height: 60, borderRadius: 8, backgroundColor: 'gray', marginRight: 12, }}></View> <View style={{ flexGrow: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', }}> <View> <Text style={{color: 'gray', fontSize: 13, lineHeight: 22}}> 존슨즈베이비 </Text> <Text style={{ fontWeight: 'bold', fontSize: 15, lineHeight: 22, }}> 수딩내추럴 인텐스 모이스처 크림 </Text> </View> <View style={{alignSelf: 'flex-start'}}> <Text>more</Text> </View> </View> </View> <View style={{ backgroundColor: 'lightgray', height: 1, marginRight: 16, marginLeft: 16, }}></View> <View style={{ padding: 16, paddingTop: 10, }}> <SvgXml xml={SVG('STAR_CHECKED')} height="26" width="26" /> <Text style={{ fontSize: 12, lineHeight: 22, marginLeft: 8, marginTop: 8, }}> 허허 조쿠만,,촉촉해 아주 기냥 어허허 별점 하나는 기냥 안 줬어 </Text> </View> </View> {/* */} <View style={{ backgroundColor: 'white', borderRadius: 10, marginBottom: 16, }}> <View style={{ flexDirection: 'row', justifyContent: 'space-between', padding: 16, }}> <View style={{ width: 60, height: 60, borderRadius: 8, backgroundColor: 'gray', marginRight: 12, }}></View> <View style={{ flexGrow: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', }}> <View> <Text style={{color: 'gray', fontSize: 13, lineHeight: 22}}> 존슨즈베이비 </Text> <Text style={{ fontWeight: 'bold', fontSize: 15, lineHeight: 22, }}> 수딩내추럴 인텐스 모이스처 크림 </Text> </View> <View style={{alignSelf: 'flex-start'}}> <Text>more</Text> </View> </View> </View> </View> </View> </ScrollView> </Fragment> ); } } const styles = StyleSheet.create({});
var css = document.querySelector("h3"); var color1 = document.querySelector(".color1"); var color2 = document.querySelector(".color2"); var body = document.getElementById("gradient"); var color3 = document.querySelector(".color3"); // body.style.background = "red" 利用DOM更換背景顏色 function setGradient() { body.style.background = "linear-gradient(to right, " + color1.value + ", " + color2.value + ")"; css.textContent = body.style.background; } function randomColor() { var colorNember = (Math.floor(Math.random()*256)) if (colorNember < 16) { colorNember = 16; } return colorNember; } function setRandomColor() { var red1 = (randomColor()).toString(16); var green1 = (randomColor()).toString(16); var blue1 = (randomColor()).toString(16); // console.log(red1,green1,blue1); color1.value = "#" + red1 + green1 + blue1 var red2 = (randomColor()).toString(16); var green2 = (randomColor()).toString(16); var blue2 = (randomColor()).toString(16); // console.log(red2,green2,blue2); color2.value = "#" + red2 + green2 + blue2 setGradient(); } color1.addEventListener("input" , setGradient); color2.addEventListener("input" , setGradient); color3.addEventListener("click" , setRandomColor);
import can from 'can'; import QUnit from 'steal-qunit'; import plugin from '../bit-social'; import faker from 'faker'; import sinon from 'sinon'; import validUrl from 'valid-url'; import data from '../demo-data'; var windowOpen; var simpleCase = can.stache('<bit-social url="{url}" text="{text}" image="{image}"/>'); QUnit.module('bit-social', { beforeEach: function() { windowOpen = window.open; window.open = sinon.spy(); }, afterEach: function() { window.open = windowOpen; } }); QUnit.test('Initialized the plugin', function(){ QUnit.equal(typeof plugin, 'function', 'imported constructor'); var frag = simpleCase(); QUnit.equal(can.$(frag).find('a').length, 6, '6 links rendered by default'); frag = simpleCase({image: faker.image.imageUrl()}); QUnit.equal(can.$(frag).find('a').length, 7, '7 links rendered when passed an image path'); }); QUnit.test('Link click triggers popup', function(){ var frag = simpleCase(data[0]); can.$(frag).find('a:first').click(); QUnit.ok(window.open.calledOnce, 'called window.open'); QUnit.ok(validUrl.isWebUri(window.open.args[0][0]), 'called with valid url'); });
const express = require('express'); const router = express.Router(); const moviesController = require('../controllers/movies.controller'); router.get('/', moviesController.list) router.get('/new', moviesController.create) router.post('/new', moviesController.doCreate) router.get('/:id', moviesController.get) router.post('/:id/delete', moviesController.delete) router.get('/:id/edit', moviesController.edit) router.post('/:id/edit', moviesController.doEdit) module.exports = router;
function Main() { var _instance = document.createElement("div"); _instance.style.position = "fixed"; _instance.style.backgroundColor = UIColors.FONT_DARK; var _width = window.innerWidth; var _height = window.innerHeight; _instance.init = function () { setupStandards(); }; function setupStandards() { Assets.setupLayers(); AnimationUtils.apply(Assets.LAYER_TEMPLATE); setupResizeManager(); Assets.SCROLL_CONTROLLER = new ScrollController(); Assets.SCROLL_CONTROLLER.init(document); Assets.RETINA_HANDLE = new RetinaHandle(); setupContentManager(); addMainMenu();//si sacas esto falla Assets.PageTemplate Assets.MAIN_MENU.menuOffsetH <- es null // SiteGuides.drawDebugLines(); ContentManager.init(Assets.CONTENT_PAGES, "home"); } function setupResizeManager() { // resize manager var settings = new ResizeManagerSettings(); // settings.setMinWidth( 1024 ); // settings.setMinHeight( 620 ); settings.setRoundWidthTo(1); if (BrowserDetect.TABLET !== true && BrowserDetect.MOBILE !== true) { settings.setRemoveScrollbar(true); } else { settings.setRemoveScrollbar(false); } settings.setBreakPoints([{ width: 500, id: "mobile" }, { width: 1024, id: "tablet" }, { width: 999999, id: "desktop" } ]); if (BrowserDetect.TABLET === true) { settings.forceBreakPoint("tablet"); } if (BrowserDetect.MOBILE === true) { settings.forceBreakPoint("mobile"); } Assets.RESIZE_MANAGER = new ResizeManager(settings); } function setupContentManager() { Assets.CONTENT = document.getElementById("content"); Assets.CONTENT_PAGES = ContentManager.getChildByAttr(Assets.CONTENT, "name", "pages"); Assets.CONTENT_GENERAL = ContentManager.getChildByAttr(Assets.CONTENT, "name", "general-data"); // console.log(Assets.CONTENT); Assets.CONTENT.parentNode.removeChild(Assets.CONTENT); //remove content from the page ContentManager.AUTOMATICALLY_TRACK_GOOGLE_ANALYTICS = !Debug.isLocalhost(); ContentManager.addTemplate("home", TemplateHome); //contiene stories //ContentManager.addTemplate( "projects-0", TemplateCasesOverview );//contiene projects //ContentManager.addTemplate("principles", TemplatePrincip); //contiene ethos //ContentManager.addTemplate("profile", TemplateProfil); // contiene studio //ContentManager.addTemplate( "case-0", TemplateCase );//template for each } function addMainMenu() { Assets.MAIN_MENU = new MainMenu(); // Assets.LAYER_TOP.appendChild(Assets.MAIN_MENU); Assets.MAIN_MENU.init(); } return _instance; }
// Import não funcionava sem o Babel no ECMA 2015 import Pessoa from './pessoa' const pessoa = new Pessoa('Igor') console.log(pessoa.toString())
var Airport = function(){ this.planes = []; }; Airport.prototype.planeCount = function() { this.planes = []; }; Airport.prototype.park = function(plane) { this.planes.push(plane); }; Airport.prototype.takeOff = function(plane) { this.planes.splice(plane); };
console.log(sub(1,5));
var obj, dbParam, xmlhttp, myObj, x, txt = ""; obj = { "table":"questions"}; dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); for (x in myObj) { txt += myObj[x].username +": " + "<b><a href='totalqs.php?q_id=" + myObj[x].q_id + "&question=" + myObj[x].question + "&username="+myObj[x].username +"'" + ">" + myObj[x].question + "</a></b> Asked on " + myObj[x].q_date + "<br />" ; } //puts JSON in all questions page document.getElementById("test").innerHTML = txt; } }; //grabs file that converted database call to JSON xmlhttp.open("GET", "../public_html/model/testdbcall.php?x=" + dbParam, true); xmlhttp.send();
import React, { Children } from 'react' import './style.scss' const Button = ({children, ...otherProps}) =>{ return ( <button className="btan btn-primary" {...otherProps}> {children} </button> ) } export default Button
import React, { useEffect } from 'react'; import { Typography } from '@material-ui/core'; import history from '../../components/AppRouter/createHistory'; import { useSnackbar } from 'notistack' export const SignupCallback = () => { const { enqueueSnackbar } = useSnackbar(); useEffect(() => { const successful = window.history.state; if (!successful){ enqueueSnackbar("Failed to register! Something went wrong.", { variant: "error" }); history.push("/register") } enqueueSnackbar("Registration Successful! Please Sign in.", { variant:"success" }); return history.push("/") }, [enqueueSnackbar]); return ( <Typography>Callback</Typography> ) }; export default SignupCallback;
import Ember from 'ember'; export default Ember.Component.extend({ settings: Ember.inject.service(), showUser: true, catalog: null, stackId: null, actions: { newService() { var stackId = this.get('stackId'); if ( stackId ) { this.get('router').transitionTo('service.new', {queryParams: {stackId: stackId}}); } else { var stack = this.get('store').createRecord({ type: 'stack', name: 'Default', }); return stack.save().then(() => { this.get('router').transitionTo('service.new', {queryParams: {stackId: stack.get('id') }}); }); } }, } });
/** * Created by Wwei on 2016/9/1. */ Ext.define('Admin.view.brand.BrandForm', { extend: 'Ext.window.Window', xtype: 'brandform', title: '品牌添加', requires: [ 'Admin.view.brand.BrandFormController', 'Ext.form.Panel', 'Ext.form.field.ComboBox', 'Ext.form.field.Text', 'Ext.form.field.TextArea', 'Ext.layout.container.Fit' ], layout: 'fit', modal: true, height: 200, width: 370, controller: 'brandform', viewModel: { links: { theBrand: { type: 'brand.Brand', create: true } }, data: { roleComboQueryMode: 'remote' } }, items: [{ flex: 1, xtype: 'form', reference: 'form', modelValidation: true, defaults: { labelAlign: 'left', margin: 10, msgTarget: 'side' }, items: [{ xtype: 'textfield', name: 'id', fieldLabel: '品牌id', hidden: true, bind: '{theBrand.id}' },{ xtype: 'textfield', name: 'name', fieldLabel: '品牌名称', bind: '{theBrand.name}' }] }], buttons: [{ text: '确定', handler: 'editBrand' }, { text: '取消', handler: 'closeWindow' }] });
// ERRORS 'use strict'; let vassilis = 'hello'; //let vassilis = 'bye'; // syntaxError // arr= []; // ReferenceError (something is not defined) // LogicalError // 1 if (true) { console.log('hello'); } else { console.log(false); // never meets the else case } // 2 function average(a, b) { return a + b / 2 // should be (a+b)/2; } console.log(average(1, 2)); // expect 1.5 // 3. let array = [1, 2, 3, 4]; console.log(array[4]); // undefined //Debugging //node inspect ... //chrome://inspect console.log('before'); //debugger; // does not work with node console.log('after'); // inspect scope in chrome function myFunction() { let myVar = 'hello again'; // debugger; console.log('run after debugger'); let obj = { name: 'fatma', method: function () { // debugger; console.log(this.name); } } obj.method(); } myFunction(); function helloName(name) { console.log(name); } helloName(); function map(mapThisFunction) { if (mapThisFunction) { return [1, 2, 3, 4].map(mapThisFunction); } } map(); // undefined console.log(map(element => element * 2)); //better // tryCatch function tryCatch(mapThisFunction) { try { return [1, 2, 3, 4].map(mapThisFunction); } catch (error) { console.error('error occurred', error); } console.log('after catch try'); } tryCatch(); // undefined console.log(tryCatch(element => element * 2)); try { nonExistenceFunction() } catch (e) { console.error('other error', e); } console.log('the rest is working'); // error object const martinaError = new Error('give another message to the error object'); // Throw an error try { // if something is going wrong if (false) { throw ReferenceError('reference ' + vassilis) } else { throw martinaError; } } catch (e) { console.error(e); }
require('dotenv').config(); var express = require('express'); var mongoose = require('mongoose'); var app = express(); const path = require('path'); //DATABASE SETUP mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false, }); const connection = mongoose.connection; connection.once('open', function () { console.log('MongoDB database connection established successfully'); }); //body parse.. app.use(express.json({ extended: false })); //app.use(express.urlencoded({extended: true})); //DEFINE ROUTES app.use('/users', require('./routes/users')); app.use('/auth', require('./routes/auth')); app.use('/journals', require('./routes/journals')); app.use('/profile', require('./routes/profile')); // Serve static assets in production if (process.env.NODE_ENV === 'production') { // Set static folder app.use(express.static('client/build')); app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html')); }); } app.listen(process.env.PORT || 5000, () => console.log('Server started...'));
(function () { angular .module('myApp') .controller('createByFeedbackController', createByFeedbackController) createByFeedbackController.$inject = ['$state', '$scope', '$rootScope']; function createByFeedbackController($state, $scope, $rootScope) { $rootScope.setData('showMenubar', true); $rootScope.setData('backUrl', "choiceQuestionType"); $scope.selectedRadio = 0; $scope.listType = false; $scope.anonymous = false; $scope.selfRate = false; $scope.top_answers = 0; $scope.groupFeedback = 'team'; $scope.isInvestment = false; $scope.awardScore = 0; $scope.awardPeoples = 0; $rootScope.newQuestionKey = undefined $rootScope.safeApply(); $scope.$on('$destroy', function () { if ($scope.questionsRef) $scope.questionsRef.off('value') }) $scope.init = function () { $rootScope.setData('loadingfinished', false) $scope.getAllQuestions() } $scope.getAllQuestions = function () { $scope.questionsRef = firebase.database().ref("Questions") $scope.questionsRef.on('value', function (snapshot) { $scope.Questions = snapshot.val() || {} $rootScope.newQuestionKey = $scope.getCode() $rootScope.setData("loadingfinished", true) $rootScope.fileupload() $rootScope.result_image_upload() }) } $scope.getCode = function () { var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghijklmnopqrstuvwxyz1234567890'.split(''); var new_id = ''; do { new_id = ''; for (var i = 0; i < 5; i++) { new_id += chars[Math.floor(Math.random() * chars.length)]; } } while (Object.keys($scope.Questions).indexOf(new_id) > -1); return new_id; } // create feedback type question $scope.awardScoreChanged = function () { $scope.awardScore = Math.round($scope.awardScore); if ($scope.awardScore < 1) $scope.awardScore = 0; } $scope.awardPeopleChanged = function () { $scope.awardPeoples = Math.round($scope.awardPeoples); if ($scope.awardPeoples < 1) $scope.awardPeoples = 0; } $scope.getOrder = function () { let order = -1 let setQuestions = Object.values($scope.Questions).filter(qst => qst.Set == $rootScope.settings.questionSetKey); for (i = 0; i < setQuestions.length; i++) { if (setQuestions[i].order > order) order = setQuestions[i].order } return order + 1 } $scope.creatQuestion = function () { //if question doesn't exist, return if ($scope.mainQuestion == '' || $scope.mainQuestion == undefined) { $rootScope.error('Please Input Question!'); return; } //if feedback type is not selected, return if ($scope.feedbacktype == undefined) { $rootScope.error('Please Select Feedback Type!'); return; } var feedqts = []; //Scale 10 questions if ($scope.feedqt1) feedqts.push($scope.feedqt1); if ($scope.feedqt2) feedqts.push($scope.feedqt2); if ($scope.feedqt3) feedqts.push($scope.feedqt3); if ($scope.feedqt4) feedqts.push($scope.feedqt4); if ($scope.feedqt5) feedqts.push($scope.feedqt5); if ($scope.feedqt6) feedqts.push($scope.feedqt6); if ($scope.feedqt7) feedqts.push($scope.feedqt7); if ($scope.feedqt8) feedqts.push($scope.feedqt8); if ($scope.feedqt9) feedqts.push($scope.feedqt9); if ($scope.feedqt10) feedqts.push($scope.feedqt10); //user mail $scope.top_answers = Math.round($scope.top_answers); if ($scope.top_answers < 0) $scope.top_answers = 0; var links = angular.copy($rootScope.links); links = links.filter(function (link) { if (link.title == '' && link.url == '') { return false; } else { return true; } }) var qtdetails = { title: $scope.title ? $scope.title : {}, question: $scope.mainQuestion, type: $scope.feedbacktype, feedqts: feedqts, teacher: $rootScope.settings.userEmail, image: $rootScope.temp_image || {}, videoID: $scope.videoID || {}, Set: $rootScope.settings.questionSetKey, questionType: "Feedback Type", anonymous: $scope.anonymous || {}, selfRate: $scope.selfRate || {}, unRequired: $scope.unRequired || {}, listType: $scope.listType || {}, top_answers: $scope.top_answers || {}, links: links, isInvestment: $scope.isInvestment, groupFeedback: $scope.groupFeedback, awardScore: $scope.awardScore || {}, awardPeoples: $scope.awardPeoples || {}, instruction: $scope.instruction || {}, result_videoID: $scope.result_videoID || {}, result_image: $rootScope.temp_result_image || {}, result_string: $scope.result_string || {}, code: $rootScope.newQuestionKey, order: $scope.getOrder() };//Questions firebase.database().ref('Questions/' + $rootScope.newQuestionKey).set(qtdetails).then(function () { $rootScope.success('Question is created successfully!') $rootScope.safeApply(); setTimeout(function () { $state.reload() }, 500); }) } } })();
import fragments from "/lib/graph/fragments"; export const QUERY_FOLDER = ` query FOLDER_PAGE($path: String!, $language: String!) { folder: catalogue (path: $path, language: $language) { ...item children { ...item ...product } } } ${fragments} `
const withLess = require('@zeit/next-less') const withCSS = require('@zeit/next-css') module.exports = { publicRuntimeConfig: { // Will be available on both server and client }, ...withCSS(withLess({ cssModules: true, webpack(config) { config.module.rules.push({ test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/, use: { loader: 'url-loader', options: { limit: 8192, publicPath: '/_next/static/', outputPath: 'static/', name: '[name].[ext]', }, }, }); config.module.rules.forEach(rule => { if(rule.test.toString().includes('.css')){ rule.use = rule.use.map(useRule => { if(useRule.loader && useRule.loader.startsWith('css-loader')){ useRule = { loader: 'css-loader', options:{ modules: false, // localIdentName: "123" } } } return useRule; }) } }) // config.module.rules.forEach(rule => { // if(rule.test.toString().includes('.less')){ // rule.use = rule.use.map(useRule => { // if(useRule.loader && useRule.loader.startsWith('css-loader')){ // console.log(123) // useRule = { // loader: 'css-loader', // options:{ // modules: true, // localIdentName: "[name]__[local]___[hash:base64:5]" // } // } // } // return useRule; // }) // } // }) return config }, })), }
import * as actionTypes from "./actionTypes"; import axios from "../../axios-order"; export const addIngredients = name => { return { type: actionTypes.ADD_INDEGRIENTS, ingredientsName: name }; }; export const removeIngredients = name => { return { type: actionTypes.REMOVE_INDEGRIENTS, ingredientsName: name }; }; export const setIngredients = ingredients => { return { type: actionTypes.SET_INGREDIENTS, ingredients: ingredients }; }; export const fetchIngredientsFailed = () => { return { type: actionTypes.FETCH_INGREDIENTS_FAILED }; }; export const initialIngredients = () => { return dispatch => { axios .get(`https://react-my-burger-13557.firebaseio.com/ingredients.json`) .then(res => { dispatch(setIngredients(res.data)); }) .catch(error => { dispatch(fetchIngredientsFailed()); }); }; };
const requestEnum = require('../../enums/requests'); class PostRequestParameters { constructor(req) { this.request = { email: req.body.email, title: req.body.title, requestStatus: req.body.requestStatus, body: req.body.body }; } validate() { let errors = []; if (!this.request.email) { errors.push('email Invalid'); } if(!this.request.requestStatus || (this.request.requestStatus && !requestEnum[this.request.requestStatus])) { errors.push('Status Invalid. Access /requests/status/types route to get all disponible request status.'); } if (!this.request.title) { errors.push('title is invalid'); } if (!this.request.body) { errors.push('body is invalid'); } return errors; } } module.exports = PostRequestParameters;
const mongoose = require('mongoose'); const UserSchema = mongoose.Schema({ username: String, password: String }); UserSchema.statics.checkUserExists = function(username, cb) { return this.findOne({ username: username }, cb); } UserSchema.statics.createUser = function(username, password, cb) { return this.create({ username: username, password: password }, cb); } mongoose.model('User', UserSchema);
import React, { useState } from 'react' import PropTypes from 'prop-types' import { Form, FormGroup, FormText, Label, Input, Button } from 'reactstrap' import ImageSelect from 'components/ImageSelect' const NAME_LENGTH = [4, 32] const BIO_LENGTH = [4, 128] export default function StandardForm ({ onDone = () => {} }) { const [name, setName] = useState(null) const [bio, setDescription] = useState(null) const [icon, setIcon] = useState(null) function valid () { return ( name !== null && name.length >= NAME_LENGTH[0] && name.length <= NAME_LENGTH[1] && bio !== null && bio.length >= BIO_LENGTH[0] && bio.length <= BIO_LENGTH[1] && icon !== null ) } function toDir () { return [ { path: '/name.txt', content: Buffer.from(name) }, { path: '/bio.txt', content: Buffer.from(bio) }, { path: '/icon.jpg', content: icon } ] } return ( <Form> <FormGroup> <Label><b>Name:</b></Label> <Input type="text" onChange={e => setName(e.target.value)} placeholder={ `e.g. Ringo Starr (${NAME_LENGTH.join('-')} characters)` } /> </FormGroup> <FormGroup> <Label><b>Bio:</b></Label> <Input type="textarea" onChange={e => setDescription(e.target.value)} placeholder={ `Write about yourself. (${BIO_LENGTH.join('-')} characters)` } /> </FormGroup> <FormGroup> <Label><b>Icon:</b></Label> <ImageSelect onReady={ image => { setIcon(image) } } /> <FormText color="muted"> Image will be resized to 180x180px. </FormText> </FormGroup> <Button className={ valid() ? '' : 'd-none' } onClick={ () => onDone({ format: 'ipfs-standard-2019', dir: toDir() })} >Update</Button> </Form> ) } StandardForm.propTypes = { onDone: PropTypes.func }
//Multidimensional Arrays var myFirstSubarray = [['this','is'],['super','cool']]; //When working with two-dimensional arrays, if you want to print out all //of the values, you are going to need a loop inside of a loop! var nestedArr = [[1,2], [3,4]]; for(let i=0; i<nestedArr.length; i++){ console.log(nestedArr[i]); } // this will log out... // [1,2] // [3,4] var nestedArr = [[1,2], [3,4,5]]; for(let i=0; i<nestedArr.length; i++){ for(let j=0; j<nestedArr[i].length; j++){ // notice that we are going inside the outer array // and now inside of the inner array console.log(nestedArr[i][j]); } } // this will log out... // 1 // 2 // 3 // 4 var nestedArr = [[1,2,3], [4,5,6], [7,8,9,10,11,12]]; for(let i = 0; i < nestedArr.length; i++){ for(let j =0; j < nestedArr[i].length; j++){ console.log(nestedArr[i][j]); } } //Exercises var nestedArr = [[1,2,3], [4,5,6], [7,8,9,10,11,12]]; function printEvens(){ for(let i = 0; i < nestedArr.length; i++){ for(let j =0; j < nestedArr[i].length; j++){ if(nestedArr[i][j] % 2 === 0){ console.log(nestedArr[i][j]); } } } } printEvens(); var nestedArr = [[[1,2],[3,4]],[[5,6]]]; function sumTotal(){ let sum = 0; for(let i = 0; i < nestedArr.length; i++){ for(let j = 0; j < nestedArr[i].length; j++){ for(let k = 0; k < nestedArr[i][j].length; k++){ sum += nestedArr[i][j][k] } } } return sum; } sumTotal(); // 21 var arr = [] Array.isArray(arr) // true Array.isArray('Hello') // false //bonus // I solved it recursively function countVowels(input){ let count = 0; function counter(str){ for(let i = 0; i < str.length; i++){ let c = str[i].toLowerCase(); if(c === "a" || c === "e" || c === "i" || c === "o" || c === "u"){ count++; } } } for(let i = 0; i < input.length; i++){ if(Array.isArray(input[i])){ count += countVowels(input[i]); } else { counter(input[i]); } } return count; } var nestedArr = ['Elie', ['Matt', ['Tim']],['Colt',['Whisky',['Janey'], 'Tom']], 'Lorien']; countVowels(nestedArr); // //Nested Arrays Exercises function rotate(arr, num){ num = num % arr.length; for(let i = 0; i < num; i++){ let val = arr.pop(); arr.unshift(val); } return arr; } console.log(rotate([1,2,3], 1)); // [3,1,2] console.log(rotate([1,2,3], 2)); // [2,3,1] console.log(rotate([1,2,3], 3)); // [1,2,3] ////////// function makeXOGrid(x, y){ let result = []; let count = 0; for(let i = 0; i < x; i++){ let row = []; for(let j = 0; j < y; j++){ if(count % 2 === 0){ row.push("X"); count++; } else { row.push("O"); count++; } } result.push(row); } return result; } console.log(makeXOGrid(1,4)); /*/ [["X","O","X","O"]] /*/ console.log(makeXOGrid(3,2)); /*/ [["X","O"],["X","O"],["X","O"]] /*/ console.log(makeXOGrid(3,3)); /*/ [["X","O","X"],["O","X","O"],["X","O","X"]] /*/ ///theirs function makeXOGrid(rows,amount){ var finalArr = [] var startWithX = true for(var i=0; i<rows; i++){ var newRow = [] for(var j=0; j<amount; j++){ if(startWithX){ newRow.push("X") } else { newRow.push("O") } startWithX = !startWithX } finalArr.push(newRow) } return finalArr; }
// a loadqueue accepts an array of files and fires a callback when all of them loaded succesfully // groups should be an array with objects with a name and files property, files contains the actual paths to load var LoadQueue = function(groups, callbacks, maxLoading){ Test.assert(groups instanceof Array, "groups is an array"); Test.assert(groups.length, "you are loading at least one group"); this.groups = groups; this.cbInit = callbacks.init; this.cbLoading = callbacks.loading; this.cbLoaded = callbacks.loaded; this.cbFinished = callbacks.finished; this.toLoad = 0; this.loading = 0; this.loaded = 0; this.finished = false; this.maxLoading = maxLoading; for (var i=0; i<groups.length; ++i) { var group = groups[i]; Test.assert(group.name, "group should have a name"); Test.assert(group.files, "group should have files"); Test.assert(group.files instanceof Array, "files is an array"); Test.assert(group.files.length, "this group should be loading files"); group.loading = false; group.loaded = false; this.toLoad += group.files.length; if (i<(maxLoading||1)) this.next(group); } if (this.cbInit) this.cbInit(this.toLoad); }; LoadQueue.imageCache = {}; // global image cache LoadQueue.prototype = { next: function(group){ if (!group.loaded && !group.loading && this.loading < this.maxLoading) { var file = group.files.shift(); if (file) { var self = this; var cb = function(){ //console.log("loaded file: ["+group.name+"] : "+file); --self.loading; ++self.loaded; if (self.cbLoaded) self.cbLoaded(group, file); group.loading = false; if (group.files.length == 0) group.loaded = true; // if finished, call the callback if (self.loaded == self.toLoad && self.cbFinished) self.cbFinished(); else { // run through all groups for (var i=0; i<self.groups.length; ++i) { self.next(self.groups[i]); } } }; // simulate download lag setTimeout(function(){ if (file.substr(-3) == '.js') self.loadScript(file, cb); // purist in me says substr is not formally part of the language ;) else if (['.png','.jpg','.gif'].indexOf(file.substr(-4)) >= 0) self.loadImg(file, cb); // purist in me says substr is not formally part of the language ;) else Test.die("Unsupported resource type to load: "+file, cb); }, 0); ++self.loading; group.loading = true; if (self.cbLoading) self.cbLoading(group, file); } } }, loadImg: function(file, cb){ //console.log("loading an image"); var img = new Image; img.onload = function(){ LoadQueue.imageCache[file] = img; Test.assert(cb, "callback should exist"); cb(); img.onload = null; // clear onload event function }; img.src = file+'?'+Math.random(); }, loadScript: function(file, cb){ //console.log("loading a script"); var s = document.createElement('script'); var self = this; s.onload = function(){ document.body.removeChild(this); // remove script header tag cb(); }; s.src = file+'?'+Math.random(); document.body.appendChild(s); // (use body, head is not stable xbrowser, and seriously, it doesnt matter. }, 0:0};
var XLSX = require('xlsx'); var acctFormula1 = "IF(ISNA(VLOOKUP(" var acctFormuma2 = ',analysis!$A$1:$A$45, 1, FALSE)), "NO", "YES")'; var infile = process.argv[2]; var outfile = process.argv[3]; var workbook = XLSX.readFile(infile, {cellDates:true}); var assignmentsSheetName = 'assignments'; var bankSheetName = 'bank'; var creditSheetName = 'credit'; var assignments = getAssignments(workbook.Sheets[assignmentsSheetName]); var notFoundStrings = []; console.log("handling bank"); processWorkSheet(workbook.Sheets[bankSheetName], assignments); console.log("handling credit"); processWorkSheet(workbook.Sheets[creditSheetName], assignments); addNotFoundStrings(workbook.Sheets[assignmentsSheetName]); XLSX.writeFile(workbook, outfile, {cellDates:true,bookType:"xlsx"}); function getAssignments(workSheet) { var hdrDesc = 'description'; var hdrCat = 'category'; var hdrSubCat = 'subcategory'; var colAlpha=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M']; var colHdrs={}; var assignments = new Array(); var category; var subCategory; //Row 1. for (var cols=0; cols<colAlpha.length; cols++) { if (workSheet[colAlpha[cols]+1] !== undefined) { colHdrs[workSheet[colAlpha[cols]+1].v] = colAlpha[cols]; } } for (var rows = 2; rows < 10000; rows++) { if (workSheet[colHdrs[hdrDesc]+rows] === undefined) { break; } description = workSheet[colHdrs[hdrDesc]+rows].v; if (workSheet[colHdrs[hdrCat]+rows] !== undefined) { category = workSheet[colHdrs[hdrCat]+rows].v; } else { category = undefined; } if (workSheet[colHdrs[hdrSubCat]+rows] !== undefined) { subCategory = workSheet[colHdrs[hdrSubCat]+rows].v; } else { subCategory = undefined; } assignments[description] = [category, subCategory]; } console.log(`found ${rows} assignments`); return assignments; } function addNotFoundStrings(workSheet) { var hdrDesc = 'description'; var hdrCat = 'category'; var hdrSubCat = 'subcategory'; var colAlpha=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M']; var colHdrs={}; //Row 1. for (var cols=0; cols<colAlpha.length; cols++) { if (workSheet[colAlpha[cols]+1] !== undefined) { colHdrs[workSheet[colAlpha[cols]+1].v] = colAlpha[cols]; lastColumn = colAlpha[cols]; } } for (var rows = 2; rows < 10000; rows++) { if (workSheet[colHdrs[hdrDesc]+rows] === undefined) { break; } } for (key in notFoundStrings) { workSheet[colHdrs[hdrDesc]+rows] = {t:'s', v:key}; rows++; } var endOfSheet = lastColumn+rows; workSheet['!ref'] = 'A1:'+endOfSheet; console.log(`current ref ${workSheet['!ref']}`); } function processWorkSheet(workSheet, assignments) { var notfound = 0; var totFound = 0; var colAlpha=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M']; var colHdrs={}; var hdrDate='date'; var hdrAmount = 'amount'; var hdrDesc = 'description'; var hdrCat = 'category'; var hdrSubCat = 'subcategory'; var hdrAccounted = 'accounted'; //Row 1. for (var cols=0; cols<colAlpha.length; cols++) { if (workSheet[colAlpha[cols]+1] !== undefined) { colHdrs[workSheet[colAlpha[cols]+1].v] = colAlpha[cols]; } } for (var rows = 2; rows < 10000; rows++) { var found = false; if (workSheet[colHdrs[hdrDate]+rows] === undefined) { break; } if (workSheet[colHdrs[hdrAmount]+rows] !== undefined) { expense = workSheet[colHdrs[hdrDesc]+rows].v; expense = expense.toLowerCase(); for (var key in assignments) { if (expense.includes(key)) { thisCategory = assignments[key][0]; thisSub = assignments[key][1]; found=true; totFound++; break; } } if (found == true) { if (workSheet[colHdrs[hdrCat]+rows] !== undefined) { currentCategory = workSheet[colHdrs[hdrCat]+rows].v; if (currentCategory != thisCategory) { console.log(`row ${rows} make manual change from category ${currentCategory} to ${thisCategory}`); } if (workSheet[colHdrs[hdrSubCat]+rows] !== undefined) { var currentSubCat =workSheet[colHdrs[hdrSubCat]+rows].v; if (currentSubCat != thisSub) { console.log(`row ${rows} make manual change from subcategory ${currentSubCat} to ${thisSub}`); } } } else { workSheet[colHdrs[hdrCat]+rows] = {t:'s', v:thisCategory}; workSheet[colHdrs[hdrSubCat]+rows] = {t:'s', v:thisSub}; } } else { if (workSheet[colHdrs[hdrCat]+rows] === undefined) { console.log(`not found ${expense}`); for (var key in assignments) { if (expense.includes(key)) { console.log(`found ${expense} in ${key}`); break; } else { console.log(`key ${key} not in ${expense}`); } } notfound++; if (notFoundStrings[expense] === undefined) { notFoundStrings[expense] = 1; } } } if(workSheet[colHdrs[hdrAccounted]+rows] === undefined) { var formula = acctFormula1+colHdrs[hdrCat]+rows+acctFormuma2; workSheet[colHdrs[hdrAccounted]+rows] = {t:'f', f:formula}; } } } console.log(`found ${totFound} not found ${notfound}`); }
import firebase, { firestore } from "../../firebase/firebase"; import * as actionTypes from "../../redux/actions/actionTypes"; import { successNotification, warningNotification, } from "../../utils/notifications"; export const fetchJobById = (documentId) => { let promises = []; let job; return firestore .collection("jobs") .doc(documentId) .get() .then((doc) => { if (doc.exists) { job = doc.data(); job.id = doc.id; promises.push( job.authorRef.get().then((res) => { job.authorData = res.data(); }) ); return Promise.all(promises); } else return {}; }) .then(() => { return JSON.stringify(job); }); }; export const getAllJobsId = () => { let jobs = []; return firestore .collection("jobs") .get() .then((querySnapshot) => { querySnapshot.forEach((doc) => { jobs.push(doc.id); }); }) .then(() => JSON.stringify(jobs)) .catch((error) => { console.log("Error getting documents: ", error); }); }; export const addJob = (job) => { return firestore .collection("jobs") .add({ title: job.title, description: job.description, price: parseInt(job.price), location: job.location, userId: job.userId, authorRef: firestore.doc(`/users/${job.userId}`), date: firebase.firestore.FieldValue.serverTimestamp(), applied: [], done: false, }) .then(() => successNotification("Success", "Job Posted")) .catch((e) => { throw new Error(e.message); }); }; export const fetchJobs = () => { let jobs = []; let promises = []; return firestore .collection("jobs") .limit(10) .get() .then((querySnapshot) => { querySnapshot.forEach((doc) => { let jobData = doc.data(); jobData.id = doc.id; if (jobData.authorRef) { promises.push( jobData.authorRef.get().then((res) => { jobData.authorData = res.data(); }) ); } jobs.push(jobData); }); return Promise.all(promises); }) .then(() => { return JSON.stringify(jobs); }) .catch((err) => err.message); }; export const updateJob = (job) => { return firestore .collection("jobs") .doc(job.id) .update({ title: job.title, description: job.description, price: parseInt(job.price), location: job.location, }) .then(() => { successNotification("Success", "Job Updated"); }) .catch((e) => { return new Error(e.message); }); }; export const finishJob = (id) => { return firestore .collection("jobs") .doc(id) .update({ done: true, }) .then(() => { warningNotification("Success", "Job Closed"); }) .catch((e) => { throw new Error(e.message); }); }; export const deleteJob = (id) => { return firestore .collection("jobs") .doc(id) .delete() .then(() => { successNotification("Success", "Job Deleted"); }) .catch((e) => { return new Error(e.message); }); }; export const isJobApplied = (docId, consumerId) => { return (dispatch) => { const unsubscribe = firestore .collection("jobs") .doc(docId) .onSnapshot((doc) => { if (!doc.empty) { console.log(doc.data().applied.includes(consumerId)); if (!doc.data().applied.includes(consumerId)) dispatch({ type: actionTypes.NOT_APPLIED }); else dispatch({ type: actionTypes.APPLIED }); } }); return unsubscribe; }; }; export const applyJob = (jobId, userId) => { return firestore .collection("jobs") .doc(jobId) .update({ applied: firebase.firestore.FieldValue.arrayUnion(userId), }) .then(() => { successNotification("Success", "Job Applied"); }) .catch((e) => { throw new Error(e.message); }); }; export const withdrawJob = (jobId, userId) => { return firestore .collection("jobs") .doc(jobId) .update({ applied: firebase.firestore.FieldValue.arrayRemove(userId), }) .then(() => { warningNotification("Done", "Job Withdrawn"); }) .catch((e) => { throw new Error(e.message); }); }; export const getJobList = (userId, state) => { const jobList = []; return firestore .collection("jobs") .where("userId", "==", userId) .where("done", "==", state) .get() .then((querySnapshot) => { querySnapshot.forEach((doc) => { jobList.push({ id: doc.id, ...doc.data() }); }); }) .then(() => { console.log(jobList); return JSON.stringify(jobList); }) .catch((e) => { console.log(e.message); }); };
angular.module('sxroApp') .factory('folders', ['$rootScope', '$http', '$mdDialog', '$stateParams', '$state', 'utils', 'dashboardState', function($rootScope, $http, $mdDialog, $stateParams, $state, utils, dashboardState) { var folders = { //model for renaming/create new folder folderNameModel: {}, }; return folders; }]);
'use strict'; const tap = require('tap'); const rewire = require('rewire'); const loaduikits = rewire('../src/lib/loaduikits'); const testConfig = require('./util/patternlab-config.json'); const findModulesMock = function () { return [ { name: 'foo', modulePath: 'node_modules/@pattern-lab/uikit-foo', }, { name: 'bar', modulePath: 'node_modules/@pattern-lab/uikit-bar', }, { name: 'baz', modulePath: 'node_modules/@pattern-lab/uikit-baz', }, ]; }; const fsMock = { readFileSync: function(path, encoding) { return 'file'; }, }; loaduikits.__set__({ findModules: findModulesMock, fs: fsMock, }); tap.test('loaduikits - maps fields correctly', function (test) { //arrange const patternlab = { config: testConfig, uikits: [], }; const uikitFoo = { name: 'uikit-foo', enabled: true, outputDir: 'foo', excludedPatternStates: ['legacy'], excludedTags: ['baz'], }; patternlab.config.uikits = [uikitFoo]; //act loaduikits(patternlab).then(() => { //assert test.equals(patternlab.uikits['uikit-foo'].name, uikitFoo.name); test.equals(patternlab.uikits['uikit-foo'].modulePath, 'node_modules/@pattern-lab/uikit-foo'); test.ok(patternlab.uikits['uikit-foo'].enabled); test.equals(patternlab.uikits['uikit-foo'].outputDir, uikitFoo.outputDir); test.equals(patternlab.uikits['uikit-foo'].excludedPatternStates, uikitFoo.excludedPatternStates); test.equals(patternlab.uikits['uikit-foo'].excludedTags, uikitFoo.excludedTags); test.end(); }); }); tap.test('loaduikits - only adds files for enabled uikits', function (test) { //arrange const patternlab = { config: testConfig, uikits: [], }; patternlab.config.uikits = [ { name: 'uikit-foo', enabled: true, outputDir: 'foo', excludedPatternStates: ['legacy'], excludedTags: ['baz'], }, { name: 'uikit-bar', enabled: true, outputDir: 'bar', excludedPatternStates: ['development'], excludedTags: ['baz', 'foo'], }, { name: 'uikit-baz', enabled: false, outputDir: 'baz', excludedPatternStates: [''], excludedTags: [], }, ]; //act loaduikits(patternlab).then(() => { //assert test.ok(patternlab.uikits['uikit-foo']); test.ok(patternlab.uikits['uikit-bar']); test.notOk(patternlab.uikits['uikit-baz']); test.end(); }); });
import React, { Component } from 'react'; import Row from 'sub-antd/lib/row'; import Col from 'sub-antd/lib/col'; import { Form } from 'antd'; import {twoColLayout, fourColLayout, halfFourColLayout, halfFourColLayoutFn, fourColLayoutFn, twoColLayoutFn} from "components/layout/formLayout"; import TreeSelect from 'sub-antd/lib/tree-select'; import axios from 'axios'; import Cookies from 'js-cookie'; import PropTypes from 'prop-types'; import Input from 'sub-antd/lib/input'; import Checkbox from 'sub-antd/lib/checkbox'; import Table from 'sub-antd/lib/table'; import columnConf from 'components/columnConf/columnConf'; import Button from 'sub-antd/lib/button'; import Upload from 'sub-antd/lib/upload'; import message from "sub-antd/lib/message"; import qs from 'querystring'; import SysButton from 'components/sysButton' const InputGroup = Input.Group; import './main.scss'; const FormItem = Form.Item; const TreeNode = TreeSelect.TreeNode; class ColumnSetting extends Component { static defaultProps = { viewId: 1, listOption: { uri: '/sysware/api/viewRela/attrList', queryBuilder: (params) => params ? `?${qs.stringify(params)}` : '' }, showListOption: { uri: '/sysware/api/viewRela/relaList', queryBuilder: params => params ? `?${qs.stringify(params)}` : '' }, onChange: (result) => { console.log(this); const viewAttrRela = result.map(item => ({ ...item, viewId: this.props.viewId, attrId: item.id }) ) console.log(viewAttrRela, '=== viewAttrRela') } } constructor(props) { super(props) this.state = { isloading: true, query: { viewId: this.props.viewId, docId: qs.parse(location.search.replace('?', '')).id, name: '' }, selectedRowKeys: [], unselectedRowKeys: [], dataSource: [], //待选列数据 selectItems: [], cancelItems: [], targetSource: [], //显示列数据 }; } UNSAFE_componentWillReceiveProps(nextProp, nextState) { if (this.props.viewId !== nextProp.viewId) { this.setState({ viewId: nextProp.viewId }) } } onChangeSearch=(e)=> { const query = { ...this.state.query, name: e}; this.setState({ query }, () => this.fetchUnselectedList(this.state.query)) } handleClear=()=> { const query = { ...this.state.query, name:''}; this.setState({ query }, () => this.fetchUnselectedList(this.state.query)) } componentDidMount() { this.props.onRef && this.props.onRef(this) this.fetchUnselectedList(this.state.query); // this.setState({ targetSource: this.props.viewAttrRela }, () => this.injectOrderNum()); this.fetchShowList({ viewId: this.state.query.viewId }) } fetchUnselectedList(params) { axios.get(this.props.listOption.uri + this.props.listOption.queryBuilder(params)).then(res => { if (res.data.code == 200 || !res.data.code) { this.setState({ dataSource: [...res.data.data, ...this.state.dataSource.filter(item => new RegExp(params.name).test(item.name) )] }, () => console.log(this.state.dataSource, '=== dataSource')); } }) } fetchShowList(params) { axios.get(this.props.showListOption.uri + this.props.showListOption.queryBuilder(params)).then(res => { if (res.data.code == 200 || !res.data.code) { this.setState({ targetSource: res.data.data }, () => this.injectOrderNum()); } }) } injectOrderNum() { let max_id = this.state.targetSource.map(item => item.orderNum).reduce((prev, next) => Math.max(~~prev, ~~next), 0); const targetSource = this.state.targetSource.map(item => { if (!item.orderNum&&item.orderNum!==0) return { ...item, orderNum: ++max_id } return { ...item, orderNum: ~~item.orderNum } }) // console.log(max_id, targetSource); this.setState({ targetSource }, () => this.props.onChange(targetSource)); } onSelectSourceChange(selectedRowKeys) { //待选列选择的行 const selectItems = this.state.dataSource.filter(o=>selectedRowKeys.includes(o.id)) this.setState({ unselectedRowKeys:selectedRowKeys, selectItems }); } onSelectTargetChange(selectedRowKeys) { //显示列选择的行 const cancelItems = this.state.targetSource.filter(o=>selectedRowKeys.includes(o.id)) this.setState({ selectedRowKeys: selectedRowKeys, cancelItems }) } onClickReset() { this.fetchShowList({ viewId: this.state.query.viewId }) } onClickAddRight() { const ids = this.state.targetSource.map(item => item.id) const targetSource = [...this.state.targetSource, ...this.state.selectItems.filter(item => !ids.includes(item.id)) ]; // this.setState({ targetSource }, () => this.injectOrderNum()); this.setState({ unselectedRowKeys: [], targetSource, dataSource: this.state.dataSource.filter(o => !this.state.unselectedRowKeys.includes(o.id)) }, () => this.injectOrderNum()); } onClickAddLeft() { const ids = this.state.dataSource.map(item => item.id) console.log(ids) const dataSource = [...this.state.dataSource, ...this.state.cancelItems.filter(item => !ids.includes(item.id))] this.setState({ selectedRowKeys: [], dataSource, targetSource: this.state.targetSource.filter(o => !this.state.selectedRowKeys.includes(o.id)) }, () => this.injectOrderNum()); } move(type){ if(this.state.selectedRowKeys.length!=1){ message.warning("请选择一条数据"); return false; } let moveItem = this.state.targetSource.find(item => this.state.selectedRowKeys.includes(item.id)); const orderNums = this.state.targetSource.map( item => ~~item.orderNum ); const prevNum = orderNums.filter( item => item < moveItem.orderNum).reduce((prev, next) => Math.max(prev, next), 0); const nextNum = orderNums.filter( item => item > moveItem.orderNum).reduce((prev, next) => Math.min(prev, next), Infinity); if (type === 'up') { if (!prevNum) return message.warn('第一个无法上移') const targetSource = this.state.targetSource.map(item => { if (item.orderNum === moveItem.orderNum) { return {...item, orderNum: prevNum } } else if (item.orderNum === prevNum) { return {...item, orderNum: moveItem.orderNum } } return item }).sort((a, b) => a.orderNum - b.orderNum) // console.log(targetSource, '=== targetSource'); this.setState({ targetSource }, () => { let prevItem = this.state.targetSource.find(item => item.orderNum === prevNum); this.setState({ unselectedRowKeys: [prevItem.id] }, () => this.props.onChange(this.state.targetSource) ); message.success("上移成功"); }) } else if (type === 'down') { if (!isFinite(nextNum)) return message.warn('最后一个无法下移') const targetSource = this.state.targetSource.map(item => { if (item.orderNum === moveItem.orderNum) { return {...item, orderNum: nextNum } } else if (item.orderNum === nextNum) { return {...item, orderNum: moveItem.orderNum } } return item }).sort((a, b) => a.orderNum - b.orderNum) // console.log(targetSource, '=== targetSource'); this.setState({ targetSource }, () => { let nextItem = this.state.targetSource.find(item => item.orderNum === nextNum); this.setState({ unselectedRowKeys: [nextItem.id] }, () => this.props.onChange(this.state.targetSource)); message.success("下移成功"); }) } // moveItem = {...moveItem, opea}; // console.log(moveItem, '==== move item') } onRowAddLeftDoubleClick=(record, index, event)=>{ //添加到待选列 this.onClickAddLeft() } onRowAddRightDoubleClick=(record, index, event)=>{ //添加到显示列 this.onClickAddRight() } render() { const SourceRowSelection = { //待选列选择的行 selectedRowKeys:this.state.unselectedRowKeys, onChange: this.onSelectSourceChange.bind(this), }; const TargetRowSelection = { //显示列选择的行 selectedRowKeys:this.state.selectedRowKeys, onChange: this.onSelectTargetChange.bind(this), getCheckboxProps: record => ({ // [9,10,11].includes(record.attrId) || disabled: ['条目ID', '条目内容'].includes(record.attrCode) , // 配置无法勾选的列 }), } return ( <Form inline style={{paddingBottom:10}}> <div className="sys-transfer"> <div className="tool-bar fl"> 待选列: <Input.Search style={{width:'calc(100% - 66px)',marginLeft:20}} placeholder="输入名称过滤待选列" onClear={this.handleClear} clearIsBlur onChange={this.onChangeSearch} /> </div> <div className="tool-bar fr"> 导出属性: <SysButton title="上移" icon="moveup" onClick={this.move.bind(this,'up')} disabled={this.state.cancelItems[0]?this.state.cancelItems[0].orderNum === 0:false} /> <SysButton title="下移" icon="movedown" onClick={this.move.bind(this,'down')} disabled={this.state.cancelItems[0]?this.state.cancelItems[0].orderNum === this.state.targetSource.filter(record => !['条目ID', '条目内容'].includes(record.attrCode)).length + 1:false} /> </div> <div className="sys-transfer-left fl"> <Table scroll={{y:339,x:300}} size="small" rowKey={ record => record.id } rowSelection={SourceRowSelection} columns={columnConf['Modal_Table_Unselectlist_Requirement_Fullpage']} dataSource={this.state.dataSource} pagination={false} rowClickMultSelect onRowDoubleClick={this.onRowAddRightDoubleClick} /> </div> <div className="sys-transfer-center fl"> <div className="sys-transfer-operation"> <Button disabled={!this.state.unselectedRowKeys.length} type="ghost" size="small" onClick={this.onClickAddRight.bind(this)}>添加显示列</Button> <Button disabled={!this.state.selectedRowKeys.length} type="ghost" size="small" onClick={this.onClickAddLeft.bind(this)}>移除显示列</Button> <Button type="ghost" size="small" onClick={this.onClickReset.bind(this)} >重置默认列</Button> </div> </div> <div className="sys-transfer-right fl"> <Table showHeader={true} scroll={{y:339,x:300}} size="small" rowKey={ record => record.id } rowSelection={TargetRowSelection} columns={columnConf['Modal_Table_Showlist_Requirement_Fullpage'](this.props.form)} onRowDoubleClick={this.onRowAddLeftDoubleClick} dataSource={this.state.targetSource} pagination={false} rowClickMultSelect /> </div> </div> {/* <div className='clearfix' style={{display: 'flex', alignItems: 'center'}}> <div style={{ width: '35%', float: 'left'}}> <Table scroll={{y:330}} size="small" title={() => <InputGroup size="small"> <Col span="6">待选列:</Col> <Col span="18"><Input.Search placeholder="输入名称过滤待选列" onClear={this.handleClear} clearIsBlur onChange={this.onChangeSearch} /></Col> </InputGroup>} rowKey={ record => record.id } rowSelection={SourceRowSelection} columns={columnConf['Modal_Table_Unselectlist_Requirement_Fullpage']} dataSource={this.state.dataSource} pagination={false} rowClickMultSelect onRowDoubleClick={this.onRowAddRightDoubleClick} /> </div> <div style={{width: '15%', float: 'left', display: 'flex', justifyContent: 'center'}}> <ul> <li style={{margin: '15px 0', textAlign: 'center'}}><Button disabled={!this.state.unselectedRowKeys.length} type="ghost" size="small" onClick={this.onClickAddRight.bind(this)}>添加显示列</Button></li> <li style={{margin: '15px 0', textAlign: 'center'}}><Button disabled={!this.state.selectedRowKeys.length} type="ghost" size="small" onClick={this.onClickAddLeft.bind(this)}>移除显示列</Button></li> <li style={{margin: '15px 0', textAlign: 'center'}}><Button type="ghost" size="small" onClick={this.onClickReset.bind(this)} >重置默认列</Button></li> </ul> </div> <div style={{width:'50%', float: 'left'}}> <Table showHeader={true} scroll={{y:330}} title={() => <InputGroup size="small"> <Col span="4">显示列:</Col> <Col span="20"> <div className="opeation-icon"> {console.log(this.state.cancelItems[0], this.state.targetSource.length, '=== ')} <SysButton style={{marginTop:'0'}} title="上移" icon="moveup" onClick={this.move.bind(this,'up')} disabled={this.state.cancelItems[0]?this.state.cancelItems[0].orderNum === 0:false}/> <SysButton style={{marginTop:'0'}} title="上移" icon="movedown" onClick={this.move.bind(this,'down')} disabled={this.state.cancelItems[0]?this.state.cancelItems[0].orderNum === this.state.targetSource.filter(record => !['条目ID', '条目内容'].includes(record.attrCode)).length + 1:false}/> </div> </Col> </InputGroup>} size="small" rowKey={ record => record.id } rowSelection={TargetRowSelection} columns={columnConf['Modal_Table_Showlist_Requirement_Fullpage'](this.props.form)} onRowDoubleClick={this.onRowAddLeftDoubleClick} dataSource={this.state.targetSource} pagination={false} rowClickMultSelect /> </div> </div> */} </Form> ); } } // ColumnSetting = Form.create()(ColumnSetting) export default ColumnSetting
import React, { Component } from "react"; import "./index.scss"; import Button from "sub-antd/lib/button"; import SysTable from "components/sysTable"; import SysIcon from "components/sysIcon"; class SysShuttle extends Component { constructor(props) { super(props); this.state = { rightDataSource: this.props.rightDataSource ? this.props.rightDataSource: [], leftKeys: [], leftRows: [], rightKeys: [], rightRows: [], }; this.rowKey = this.props.rowKey||'id' } selectChangeLeft = (leftKeys, leftRows) => { this.setState({leftKeys, leftRows}) }; selectChangeRight = (rightKeys, rightRows) => { this.setState({rightKeys, rightRows}); }; moveToRightAll = () =>{ this.setState({rightDataSource:this.$tableLeft.state.dataSource}) } moveToRight = () =>{ if(this.state.rightDataSource.length === 0){ this.setState({ rightDataSource:this.state.leftRows }) return } const rightDataIds = this.state.rightDataSource.map(item=>item[this.rowKey]) const newDataSource = this.state.leftRows.filter((item)=>{ return !rightDataIds.includes(item[this.rowKey]) }) console.log(rightDataIds) console.log(newDataSource) this.setState({ rightDataSource:[...this.state.rightDataSource,...newDataSource] }) } removeAll = () => { this.setState({rightDataSource:[]}) } remove = () => { const newDataSource = this.state.rightDataSource.filter(item=>!this.state.rightKeys.includes(item[this.rowKey])) this.setState({rightDataSource:newDataSource}) } render() { return ( <div className="sys-shuttle" style={{ ...this.props.style }}> <div className="sys-shuttle-left fl"> <div className="tool-bar">待选用户</div> <SysTable ref={(el) => (this.$tableLeft = el)} rowKey={this.rowKey} dataUrl={this.props.dataUrl} columns={this.props.leftColumns} selectChange={this.selectChangeLeft} btnDisabled={this.btnDisabledLeft} /> </div> <div className="sys-shuttle-center fl"> <div className="sys-shuttle-operation"> <Button type="ghost" size="small" onClick={this.moveToRightAll} ><SysIcon name="double-right"/></Button> <Button type="ghost" size="small" onClick={this.moveToRight} ><SysIcon name="right"/></Button> <Button type="ghost" size="small" onClick={this.remove} ><SysIcon name="left"/></Button> <Button type="ghost" size="small" onClick={this.removeAll} ><SysIcon name="double-left"/></Button> </div> </div> <div className="sys-shuttle-right fl"> <div className="tool-bar">已选用户</div> <SysTable rowKey={this.rowKey} dataSource={this.state.rightDataSource} columns={this.props.rightColumns} selectChange={this.selectChangeRight} /> </div> </div> ); } } export default SysShuttle;
/** * Car class * -tanksize (how big the gas tank is) * -mpg (car's efficiency) * -fueLevel (current fuel level) * -odometer (distance driven) * * drive(distance); drive the car the distance, and update the odometer and fuel level * addFuel(gallons): add fuel to the car, and update the fuel level * actualMpg(); returns the actual effciency for the car. */ class Car { tankSize; mpg; fuelLevel; odometer; constructor(tankSize, mpg) { this.tankSize = tankSize this.mpg = mpg this.fuelLevel = 0; this.odometer = 0; } addFuel(gallons) { //not checking that I am not overfilling the tank //this is your assignment... this.fuelLevel += gallons; } actualMpg() { if (this.odometer > 20000) { return this.mpg * .92; } else if (this.odometer > 10000) { return this.mpg * .95; } else { return this.mpg; } } drive(distance) { //not checking that i have enough fuel //this is your assignment... this.odometer += distance; let fuelUsed = distance / this.actualMpg(); this.fuelLevel -= fuelUsed; } } /**Build a truck class which will extend the car class * and add 1 attribute: * -isLoaded (true or false) * * will add 2 methods * -load(); flip the loaded to true * -unload(); flip the loaded to false * * we want to overide: * -actualMpg(); by making this method aware of the efficiency loss when the truck is loaded */ class Truck extends Car { isLoaded; //represents if my truck is full of dirt or not load() { this.isLoaded = true; } unload() { this.isLoaded = false; } actualMpg(){ //if the truck is loaded, then just return 85% of the advertised efficiency if(this.isLoaded == true){ return this.mpg * .85; } else{ //otherwise, fall back to the parent classe's actualMpg() method return super.actualMpg(); } } } let emisCar = new Car(11, 50); for (let i = 0; i < 21; i++) { emisCar.addFuel(10); emisCar.drive(500); } // console.log("odometer: ", emisCar.odometer); // console.log("actual mpg: ", emisCar.actualMpg()); // console.log("advertised mpg: ", emisCar.mpg); let gilesTruck = new Truck(20, 25); gilesTruck.addFuel(20); //add 20 gallons gilesTruck.drive(50); //drive 50 miles console.log("giles truck fuel level after driving 50 miles, unloaded", gilesTruck.fuelLevel); // less than 18 gallons //gilesTruc.load() //load up with dirt gilesTruck.drive(50);// dirve 50 miles console.log('giles truck fuel level after driving 50 miles, loaded', gilesTruck.fuelLevel);
var addition = ["Mouse", "Screen", "Tablet", "Apple"]; addition.push("Computer"); console.log(addition); addition[addition.length] = "Phone"; console.log(addition);
function PhoneListController($scope, $http) { $http.get("sample.json") .success(function (data) { $scope.phones = data; }) $scope.orderProperty = "no"; };
import React, { useState } from 'react'; import ReactTestUtils from 'react-dom/test-utils'; import { render, fireEvent } from '@testing-library/react'; import { getDOMNode } from '@test/testUtils'; import Form from '../../Form'; import FormControl from '../FormControl'; import FormGroup from '../../FormGroup'; import Schema from '../../Schema'; describe('FormControl', () => { it('Should output a input', () => { const instance = getDOMNode( <Form> <FormControl name="username" /> </Form> ); assert.ok(instance.querySelector('input')); }); it('Should output a textarea', () => { const instance = getDOMNode( <Form> <FormControl name="username" accepter="textarea" /> </Form> ); assert.ok(instance.querySelector('textarea')); }); it('Should call onChange callback', done => { const doneOp = () => { done(); }; const instance = getDOMNode( <Form> <FormControl name="username" onChange={doneOp} /> </Form> ); ReactTestUtils.Simulate.change(instance.querySelector('input')); }); it('Should be readOnly', () => { const instance = getDOMNode( <Form readOnly> <FormControl name="username" /> </Form> ); assert.ok(instance.querySelector('input[readonly]')); }); it('Should be readOnly on accepter', done => { function Input(props) { // eslint-disable-next-line react/prop-types if (props && props.readOnly) { done(); } return <input {...props} />; } getDOMNode( <Form readOnly> <FormControl name="username" accepter={Input} /> </Form> ); }); it('Should call onBlur callback', done => { const doneOp = () => { done(); }; const instance = getDOMNode( <Form> <FormControl name="username" onBlur={doneOp} /> </Form> ); ReactTestUtils.Simulate.blur(instance.querySelector('input')); }); it('Should have a custom className', () => { const instance = getDOMNode( <Form> <FormControl className="custom" name="username" /> </Form> ); assert.include(instance.querySelector('.rs-form-control').className, 'custom'); }); it('Should have a custom style', () => { const fontSize = '12px'; const instance = getDOMNode( <Form> <FormControl style={{ fontSize }} name="username" /> </Form> ); assert.equal(instance.querySelector('input').style.fontSize, fontSize); }); it('Should have a custom className prefix', () => { const instance = getDOMNode( <Form> <FormControl classPrefix="custom-prefix" name="username" /> </Form> ); assert.ok(instance.querySelector('div').className.match(/\bcustom-prefix\b/)); }); it('Should render correctly when form value was null', () => { const instance = getDOMNode( <Form formValue={null}> <FormControl name="name" /> </Form> ); assert.equal(instance.querySelector('input').value, ''); }); it('Should render correctly form default value when set', () => { const mockValue = 'value'; const instance = getDOMNode( <Form formDefaultValue={{ name: mockValue }}> <FormControl name="name" /> </Form> ); assert.equal(instance.querySelector('input').value, mockValue); }); it('Should render correctly default value when explicitly set and form default is not set', () => { const mockValue = 'value'; const instance = getDOMNode( <Form formDefaultValue={null}> <FormControl name="name" defaultValue={mockValue} /> </Form> ); assert.equal(instance.querySelector('input').value, mockValue); }); it('Should render correctly default value when explicitly set over form default', () => { const mockValue = 'value'; const instance = getDOMNode( <Form formDefaultValue={{ name: 'another value' }}> <FormControl name="name" defaultValue={mockValue} /> </Form> ); assert.equal(instance.querySelector('input').value, mockValue); }); it('Should render correctly when form error was null', () => { const instance = getDOMNode( <Form formError={null}> <FormControl name="name" /> </Form> ); assert.ok(!instance.querySelector('.rs-form-control-message-wrapper')); }); it('Should render correctly when errorMessage was null', () => { const instance = getDOMNode( <Form formError={{ username: 'error' }}> <FormControl errorMessage={null} name="username" /> </Form> ); assert.ok(!instance.querySelector('.rs-form-control-message-wrapper')); }); it('Should render correctly when errorMessage was null 2', () => { const instance = getDOMNode( <Form formError={{ username: 'error' }} errorFromContext={false}> <FormControl name="username" /> </Form> ); assert.ok(!instance.querySelector('.rs-form-control-message-wrapper')); }); it('Should the priority of errorMessage be higher than formError', () => { const instance = getDOMNode( <Form formError={{ username: 'error1' }}> <FormControl errorMessage={'error2'} name="username" /> </Form> ); assert.equal(instance.querySelector('.rs-form-control-message-wrapper').textContent, 'error2'); }); it('Should be associated with ErrorMessage via aria-errormessage', () => { const { getByRole } = render( <Form> <FormGroup controlId="name1"> <FormControl errorMessage={'error2'} name="name1" /> </FormGroup> </Form> ); const input = getByRole('textbox'); const alert = getByRole('alert'); expect(input).to.have.attr('aria-invalid', 'true'); expect(alert).to.exist; expect(input).to.have.attr('aria-errormessage', alert.getAttribute('id')); }); it('Should remove value and error when unMountRemove is true', () => { let refValue = { username: '', email: '' }; let refError = {}; const model = Schema.Model({ username: Schema.Types.StringType().maxLength(2, 'The length cannot exceed 2') }); const Wrapper = () => { const [value, setValue] = useState(refValue); const [error, setError] = useState(refError); const [show, setShow] = useState(true); const handleChange = v => { refValue = v; setValue(v); }; const handleError = e => { refError = e; setError(e); }; const handleUnMount = () => { setShow(false); }; return ( <> <button onClick={handleUnMount} id="unmount"> unmount </button> <Form model={model} onChange={handleChange} onCheck={handleError} formError={error} formValue={value} > {show && <FormControl id="username" name="username" shouldResetWithUnmount />} <FormControl id="email" name="email" /> </Form> </> ); }; const { container } = render(<Wrapper />); fireEvent.change(container.querySelector('#username'), { target: { value: 'test' } }); assert.deepEqual(refValue, { username: 'test', email: '' }); assert.deepEqual(refError, { username: 'The length cannot exceed 2' }); fireEvent.click(container.querySelector('#unmount')); assert.deepEqual(refValue, { email: '' }); assert.deepEqual(refError, {}); }); describe('rule', () => { it("should check the field's rule", () => { const formRef = React.createRef(); const handleError = sinon.spy(); render( <Form ref={formRef} onError={handleError}> <FormControl name="items" rule={Schema.Types.StringType().isRequired('require')} /> </Form> ); formRef.current.check(); assert.equal(handleError.callCount, 1); assert.deepEqual(handleError.firstCall.firstArg, { items: 'require' }); }); it('Should not validate fields unmounted with rule', () => { const formRef = React.createRef(); const handleError = sinon.spy(); function Wrapper() { const [show, setShow] = useState(true); return ( <> <button onClick={() => { setShow(false); }} > hidden </button> <Form ref={formRef} onError={handleError}> <FormControl name="user" rule={Schema.Types.StringType().isRequired('require')} /> {show && ( <FormControl name="password" rule={Schema.Types.StringType().isRequired('require')} /> )} </Form> </> ); } const { container } = render(<Wrapper />); formRef.current.check(); assert.equal(handleError.callCount, 1); assert.deepEqual(handleError.firstCall.firstArg, { user: 'require', password: 'require' }); fireEvent.click(container.querySelector('button')); formRef.current.check(); assert.equal(handleError.callCount, 2); assert.deepEqual(handleError.secondCall.firstArg, { user: 'require' }); }); it("Should validate accurately,when field's rule is dynamic", () => { const formRef = React.createRef(); const handleError = sinon.spy(); function Wrapper() { const [rule, setRule] = useState(Schema.Types.StringType().isRequired('require')); return ( <> <button onClick={() => { setRule(Schema.Types.StringType().isRequired('second require')); }} > setRule </button> <Form ref={formRef} onError={handleError}> <FormControl name="user" rule={rule} /> </Form> </> ); } const { container } = render(<Wrapper />); formRef.current.check(); assert.equal(handleError.callCount, 1); assert.deepEqual(handleError.firstCall.firstArg, { user: 'require' }); fireEvent.click(container.querySelector('button')); formRef.current.check(); assert.equal(handleError.callCount, 2); assert.deepEqual(handleError.secondCall.firstArg, { user: 'second require' }); }); it("Should use the field's rule when both model and field have same name rule", () => { const formRef = React.createRef(); const handleError = sinon.spy(); function Wrapper() { const model = Schema.Model({ user: Schema.Types.StringType().isRequired('form require') }); return ( <Form ref={formRef} model={model} onError={handleError}> <FormControl name="user" rule={Schema.Types.StringType().isRequired('field require')} /> </Form> ); } render(<Wrapper />); formRef.current.check(); assert.equal(handleError.callCount, 1); assert.equal(handleError.firstCall.firstArg.user, 'field require'); }); }); });
import React from "react"; import SupportPageWrapp from "./Support/index"; import oops from "assets/oops.svg"; const ServerError = () => ( <SupportPageWrapp> <div className="sercer-error-wrapp"> <div className="sercer-error-content"> <img src={oops} alt="" /> <div className="d-flex justify-content-center text-left"> <div style={{ width: 0, opacity: 0 }}>.</div> <h3>Something wrong there...</h3> </div> <div className="text-left" style={{ width: 388, margin: "auto", marginLeft: 340, marginTop: 20 }} > {" "} <span> Sorry, we`re having some technical issues (as you can see) <br />{" "} try to refresh the page, sometime works :) </span> </div> </div> </div> </SupportPageWrapp> ); export default ServerError;
import formatDeclaration from "../formatDeclaration" describe("formatDeclaration", () => { it("should format a simple declaration", () => { expect(formatDeclaration("color", "red")).toBe("color:red;") }) it("should support camelcased declarations", () => { expect(formatDeclaration("lineHeight", "1").toLowerCase()).toBe("line-height:1;") expect(formatDeclaration("MozBorderBox", "box-sizing").toLowerCase()).toBe("-moz-border-box:box-sizing;") }) it("should repeat array values", () => { expect(formatDeclaration("border", ["blue", "red"])).toBe("border:red;\nborder:blue;") }) it("should automatically add the px unit when value needs a unit", () => { expect(formatDeclaration("border", 1)).toBe("border:1px;") expect(formatDeclaration("borderWidth", [1, 2])).toBe("border-Width:2px;\nborder-Width:1px;") }) it("should not add the px unit when the unit is not needed", () => { expect(formatDeclaration("lineHeight", 1).toLowerCase()).toBe("line-height:1;") expect(formatDeclaration("zIndex", 1).toLowerCase()).toBe("z-index:1;") expect(formatDeclaration("flex", [2, 1]).toLowerCase()).toBe("flex:1;\nflex:2;") }) it("should format the \"content\" property like a string", () => { expect(formatDeclaration("content", "foo")).toBe("content:\"foo\";") expect(formatDeclaration("content", "foo bar")).toBe("content:\"foo bar\";") expect(formatDeclaration("content", "foo \"bar")).toBe("content:\"foo \\\"bar\";") }) it("should keep double dash declaration", () => { expect(formatDeclaration("--foo", "bar")).toBe("--foo:bar;") }) })
import React from 'react'; import Image from './Image'; import Psalm from './Psalm'; const Home = () => { return ( <div className='flex sm:flex-col'> <div className='w-1/2 sm:w-full animate-fadeIn'> <Image /> </div> <div id='psalm' className='w-1/2 sm:w-full animate-fadeIn'> <Psalm /> </div> </div> ); }; export default Home;
import React, { Component } from 'react'; class Borrado extends Component { constructor(props){ super(props); var datosBorrado = JSON.parse(localStorage.getItem("datos")); var id = this.props.match.params.id; var ele = JSON.parse(localStorage.getItem("datos")).findIndex(function (iteracion) { return iteracion.id === id; }); datosBorrado.splice(ele,1); //console.log(ele); localStorage.removeItem("datos"); localStorage.setItem("datos", JSON.stringify(datosBorrado)); alert('Se ha eliminado la entrada correctamente!!!'); } render(){ return( <div></div> ); } } export default Borrado;
import { writable } from 'svelte/store'; export const loginRedirectTo = writable('/');
window.onload=function(){ $(function(){ var timer = setInterval(autoPlay,3000); var index = 0; function autoPlay(){ if(index == $("#ul_banner li").size()-1){ $("#ul_banner").css("left",0) index=1; }else{ index++; } removeSib(); olLi[index == olLi.length ? 0 : index].className="active"; $("#ul_banner").animate({ left:-index*1554 }) } //移入图片中停止轮播 $("#banner").hover(function(){ clearInterval(timer) },function(){ timer = setInterval(autoPlay,3000); }); //移入小圆点图片跳转对应图片 $(".slick_dots li").on("mouseover",function(){ clearInterval(timer) index = $(this).index() removeSib(); olLi[index == olLi.length ? 0 : index].className="active"; console.log(index) $("#ul_banner").animate({ left:-index*1554 }) }) //点击左右轮播 $(".btn_left").click(function(){ if(index == 5){ $("#ul_banner").animate({ left:0 }); index =1; } if(index == 0){ index=0; }else{ index--; } removeSib(); olLi[index == olLi.length ? 0 : index].className="active"; $("#ul_banner").animate({ left:-index*1554 }); }) $(".btn_right").click(function(){ if(index == 5){ $("#ul_banner").animate({ left:0 }); index = 0; } if(index == 4){ index=4; }else{ index++; } removeSib(); olLi[index == olLi.length ? 0 : index].className="active"; $("#ul_banner").animate({ left:-index*1554 }); }); var slick_dots=document.querySelector(".slick_dots") var olLi=slick_dots.children //定义一个排他 function removeSib(){ for (var i = 0; i < olLi.length; i++) { olLi[i].className=""; } } //头部的nav显示 $(".a_parent").hover(function(){ $(".jt").css("transform","rotateZ(180deg)") $(".card").slideDown(30) },function(){ $(".jt").css("transform","rotateZ(0)") $(".card").slideUp(30) }) $(".customer_father").hover(function(){ $(".jt2").css("transform","rotateZ(180deg)") $(".customer_card").show(100) },function(){ $(".jt2").css("transform","rotateZ(0)") $(".customer_card").hide(100) }); //吸顶部分 $(".icon-yf").hover(function(){ $(".hide_reg").slideDown(30) },function(){ $(".hide_reg").slideUp(30) }) $(".icon-gwc").hover(function(){ $(".get_gwc").slideDown(30) },function(){ $(".get_gwc").slideUp(30) }) //注册登录 $("#login").click(function(){ $(".masking").fadeIn(300); $(".yx-register").hide(100) }) //点击按钮关闭登录 $("#shut_login").click(function(){ $(".masking").fadeOut(200) }) //监听点击是否使用验证码登录 $("#yzm_login").click(function(){ $(".drag").toggle(200); $("#yx_login").height(407) }); //监听点击注册按钮 $("#register").click(function(){ $(".yx_login").hide(300) $(".yx-register").fadeIn(300) $(".masking").fadeIn(300); }); //监听快速注册 $("#query_reg").click(function(){ $(".yx_login").hide(300) $(".yx-register").fadeIn(300) $(".masking").fadeIn(300); }); //监听直接登录 $("#skip_login").click(function(){ $(".masking").fadeIn(300); $(".yx-register").hide(100) }); //监听关闭 $("#shut_register").click(function(){ $(".masking").hide(100) }); //登录验证拖拽 $(".piece").bind("mousedown",function(e){ var _this=$(this) var x = e.offsetX; $(document).bind({ mousemove:function(e){ e.preventDefault()//阻止事件默认行为 var l=e.pageX-x-600; var maxL = $(".drag").width() - $(".piece").width(); if(l<0){ l=0 }else{ l=l } if(l>maxL){ l=maxL }else{ l=l; } _this.css({ left:l }) }, mouseup:function(){ $(document).unbind("mousemove"); } }); }); //点击跳转详情页 $(".name").click(function(){ location.href="childIndex.html" }); //实现吸顶效果 $(Window).scroll(function(){ var stop = $("html,body").scrollTop(); if( stop >=150 ){ $(".warpper_fixed").slideDown(200) }else{ $(".warpper_fixed").slideUp(200) } }) }) }
$(function(){ $.ajax({ crossOrigin: true, dataType: "json", type: "GET", url: "http://www.ag47morning.com/js/lookup.php", success: function(data){ var info = 0; for(info=0; info<data.length; info++){ var inline_img = 'url(../images/'+data[info].pd_image+')'; $(".port_wr").append( '<div class="project" data-hash="'+data[info].pd_index+'" style="background-image:'+inline_img+'">' +'<div class="project_desc">' +'<div class="project_name">'+data[info].pd_name+'</div>' +'<div class="project_time">제작 기간 : <span>'+data[info].pd_time+'</span>시간</div>' +'<div class="project_per">제작 참여도 : <span>'+data[info].pd_per+'</span>%</div>' +'</div>' +'</div>' ) // $(".project").css("background-image","url(../"+data[info].pd_image+")"); } $(".project").on("click",function(e){ e.stopPropagation(); info = $(this).index(); var infos = $(this).attr("data-hash"); $(".project").eq(info).addClass('open'); $("#empty2").toggleClass('open'); $(".popup_wr").toggleClass('open'); $(".pp_img a").attr("href",data[info].pd_link).css("background-image","url(../images/"+data[info].pd_image+")"); $(".pp_name").text(data[info].pd_name); $(".pp_time").text(data[info].pd_time); $(".pp_per").text(data[info].pd_per); $(".pp_link").attr("href",data[info].pd_link).text(data[info].pd_link); $(".pp_lang").text(data[info].pd_lang); $(".pp_git").attr("href",data[info].pd_git).text(data[info].pd_git); $(".pp_txt").html(data[info].pd_descA); console.log(info); console.log(info); }) } }) })
// Масштабирование загруженного изображения 'use strict'; (function () { var SCALE_MIN = 25; var SCALE_MAX = 100; var SCALE_STEP = 25; var SCALE_DEFAULT = 100; var photoInput = document.querySelector('#upload-file'); var imageUploadForm = document.querySelector('.img-upload__overlay'); var uploadedImage = imageUploadForm.querySelector('.img-upload__preview img'); var uploadedImageScale = imageUploadForm.querySelector('.scale'); var uploadedImageScaleInput = uploadedImageScale.querySelector('.scale__control--value'); var setUploadedImageScale = function (bigger) { var scaleValue = parseInt(uploadedImageScaleInput.value.slice(0, -1), 10); scaleValue = bigger ? scaleValue + SCALE_STEP : scaleValue - SCALE_STEP; if (scaleValue >= SCALE_MIN && scaleValue <= SCALE_MAX) { uploadedImageScaleInput.value = scaleValue + '%'; uploadedImage.style.transform = 'scale(' + scaleValue / 100 + ')'; } }; var resetUploadedImageScale = function () { uploadedImageScaleInput.value = SCALE_DEFAULT + '%'; uploadedImage.style.transform = null; }; uploadedImageScale.querySelector('.scale__control--smaller').addEventListener('click', function () { setUploadedImageScale(); }); uploadedImageScale.querySelector('.scale__control--bigger').addEventListener('click', function () { setUploadedImageScale(true); }); photoInput.addEventListener('change', function () { resetUploadedImageScale(); }); })();