text
stringlengths 7
3.69M
|
|---|
const wordSearch = (letters, word) => {
if (letters.length) {
const horizontalJoin = letters.map(ls => ls.join(''));
const verticalJoin = transpose(letters).map(ls => ls.join(''));
const orientation = [horizontalJoin, verticalJoin];
for (const each of orientation) {
for (const l of each) {
if (l.includes(word)) {
return true;
}
}
}
}
return false;
};
const transpose = function(search) {
const finalSearch = [];
for (let x = 0; x < search[0].length; x++) {
const newSearch = [];
for (let y = 0; y < search.length; y++) {
newSearch.push(search[y][x]);
}
finalSearch.push(newSearch);
}
return finalSearch;
};
module.exports = wordSearch;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _radium = require('radium');
var _radium2 = _interopRequireDefault(_radium);
var _icons = require('./icons');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var VerticalMenu = _react2.default.createClass({
displayName: 'VerticalMenu',
getInitialState: function getInitialState() {
return {
isOpen: false
};
},
componentDidMount: function componentDidMount() {
document.addEventListener('click', this.handleDocumentClick, false);
},
componentWillUnmount: function componentWillUnmount() {
document.removeEventListener('click', this.handleDocumentClick, false);
},
handleDocumentClick: function handleDocumentClick(e) {
var menu = this.refs.root;
if (!menu.contains(e.target) && this.state.isOpen) {
this.setState({ isOpen: false });
}
},
onTouch: function onTouch(e) {
e.stopPropagation();
e.preventDefault();
var isOpen = this.state.isOpen ? false : true;
this.setState({
isOpen: isOpen
});
},
onSelectOption: function onSelectOption(action, e) {
e.stopPropagation();
e.preventDefault();
action();
var isOpen = this.state.isOpen ? false : true;
this.setState({
isOpen: isOpen
});
},
renderMenuItem: function renderMenuItem(item, i) {
return _react2.default.createElement(
'li',
{
key: i,
style: {
display: "block",
padding: "10px 14px",
listStyle: "none",
':hover': {
background: "#EFEFEF"
}
},
onClick: this.onSelectOption.bind(this, item.action)
},
item.render
);
},
render: function render() {
var menuItemList = this.props.menuItemList.map(this.renderMenuItem);
var showList = this.state.isOpen ? "block" : "none";
var openMenuStyle = this.state.isOpen ? {
background: "#EFEFEF",
color: "black"
} : { color: "grey" };
return _react2.default.createElement(
'div',
{ ref: 'root' },
_react2.default.createElement(
'div',
{
style: _extends({}, openMenuStyle, {
cursor: "pointer",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "17px",
borderRadius: "50%",
height: "35px",
width: "35px"
}),
onClick: this.onTouch
},
_react2.default.createElement(_icons.VerticalMenuIcon, { size: 24, style: { top: "0px" } })
),
_react2.default.createElement(
'ul',
{
style: {
display: showList,
width: "200px",
position: "absolute",
background: "white",
right: "40px",
top: "0px",
padding: "6px 0px",
zIndex: "200",
boxShadow: "0px -1px 0 #e5e5e5, 0px 0px 2px rgba(0, 0, 0, 0.12), 0px 2px 4px rgba(0, 0, 0, 0.24)"
}
},
menuItemList
)
);
}
});
exports.default = (0, _radium2.default)(VerticalMenu);
|
(function(){
'use strict';
angular.module('app')
.factory('loginService', loginService);
loginService.$inject = ['$http', 'appConstants','$uibModal', '$state', "defineUser"];
function loginService($http, appConstants, $uibModal, $state, defineUser) {
return {
enterLogin: enterLogin,
isLogged: isLogged,
authorizeRole: authorizeRole,
logOut: logOut
};
function isLogged() {
return $http.get(appConstants.isLoggedURL).then(function (response) {
if (response.data.response == "logged") {
return response;
} else if (response.data.response == "non logged") {
$state.go('login');
$uibModal.open({
templateUrl: 'app/modal/templates/islogged-dialog.html',
controller: 'modalController as modal',
backdrop: true
});
}
});
}
function logOut() {
return $http.get(appConstants.logOutURL).then(function (response) {
return response
});
}
function enterLogin(data) {
return $http.post(appConstants.logInURL, data)
.then(enterLoginComplete, enterLoginFailed)
}
function enterLoginComplete(response) {
localStorage.userRole = response.data.roles[1];
return response;
}
function enterLoginFailed(response) {
$uibModal.open({
templateUrl: 'app/modal/templates/login-failed-dialog.html',
controller: 'modalController as modal',
backdrop: true
});
return response;
}
function authorizeRole() {
return $http.get(appConstants.isLoggedURL)
.then(function(response) {
return (response.data.response === "logged" &&
(response.data.roles[1] === defineUser.admin || response.data.roles[1] === defineUser.user));
}, function (response) {
return response;
});
}
}
}());
|
(function() {
var taskForm = {
templateUrl: "partials/taskForm.html",
controller: function FormController(TodoService) {
var $ctrl = this;
refreshList();
$ctrl.input = "";
$ctrl.add = function(input) {
if ($ctrl.input !== "") {
TodoService.setList(input).then(refreshList);
$ctrl.input = "";
}
};
function refreshList() {
TodoService.getList().then(function(tasks){
$ctrl.list = tasks;
});
}
}
};
angular.module("app")
.component("taskForm", taskForm);
})();
|
function Pattern(){
// var n = Number(document.getElementById("h1").value);
// console.log(n)
var k = 3;
for(var i=1; i<=4; i++)
{
for(var j=1; j<=k; j++)
{
document.write("  ");
}
for(var p=1; p<=i; p++)
{
document.write(" "+(p%2)+" ");
}
k--;
document.write("<br/>");
}
}
document.getElementById("btn").addEventListener("click", Pattern);
|
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import { Provider } from 'react-redux'
import { BrowserRouter,HashRouter, Route, Redirect, Switch } from 'react-router-dom'
// import './index.css';
// import { counter } from "./index.redux";
import reducers from './reducer'
import Auth from './Auth'
import Dashboard from './Dashboard'
import './config'
// import registerServiceWorker from './registerServiceWorker';
// registerServiceWorker();
const reduxDevtools = window.devToolsExtension ? window.devToolsExtension() : f => f;
// applyMiddleware 管理中间件
const store = createStore(reducers, compose(
applyMiddleware(thunk),
reduxDevtools
));
// class Test extends React.Component{
// render(){
// console.log(this.props);
// return <h2>测试 {this.props.match.params.location}</h2>
// }
// }
ReactDOM.render(
<Provider store={store}>
<HashRouter>
{/*<App />*/}
<Switch>
{/*只渲染命中的第一个Route*/}
<Route path='/login' exact component={Auth} />
<Route path='/dashboard' component={Dashboard} />
<Redirect to='/dashboard' />
</Switch>
</HashRouter>
</Provider>,
document.getElementById('root')
);
|
/* RegExp类型
var expression = /pattern/flags;
flags有三种取值 g:全局模式 i:不区分大小写模式 m:多行模式
*/
// flags = g
const str = 'catdat'
const pattern1 = /at/g
//flags = i
const pattern2 = /[bc]at/i
//元字符必须转义
// ([{\^$|?*+.}])
const pattern3 = /\[bc\]at/
const pattern4 = /\.at/
//前面的形式是以字面量形式定义正则表达式,也可以以构造函数形式定义
const pattern = /[bc]at/i
const pattern2 = new RegExp('[bc]at','i') //等价
//在构造函数定义时元字符要双重转义
/*
/\[bc\]at/ '\\[bc\\]at'
/\.at/ '\\.at'
/\w\\hello\\123/ '\\w\\\\hello\\\\123'
*/
//字面量模式必须像构造函数一样每次都创建一个RegExp实例
|
/**
* Created by a on 2017/11/14.
*/
/**
* Created by a on 2017/10/25.
*/
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest()
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
function myAjax(method,url,params,callback,avsn){
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
callback()
}
}
if(method=="get"){
xhr.open(method,url+"?"+params,avsn);
xhr.send(null)
}else if(method=="post"){
xhr.open(method,url,avsn);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(params)
}
}
|
var person ={
firstName: "Robert",
lastName: "White",
phone: "253.1402",
birthday: "10/27",
fullName: function (){
return this.firstName + " " + this.lastName;
}
};
function printDetails (p){
if(typeof p.email!="undefined"){
console.log(p.email);
}
console.log(p.firstName);
console.log(p.lastName);
console.log(p.phone);
console.log(p.birthday);
console.log(p.fullName());
}
printDetails(person);
|
import React, { useState } from "react";
import { API, graphqlOperation } from "aws-amplify";
import { Link } from "react-router-dom";
import * as mutations from "../graphql/mutations";
import TodoForm from "./TodoForm";
const TodoListItemDetails = ({ todo, onEdit }) => {
return (
<React.Fragment>
<div className="flex-fill">
<Link to={"/todos/" + todo.id}>
{!!todo.completedAt ? <del>{todo.name}</del> : todo.name}
</Link>
</div>
<div className="btn-group dropleft">
<button
type="button"
className="btn btn-secondary btn-sm dropdown-toggle"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
>
Action
</button>
<div className="dropdown-menu">
<div className="dropdown-item" onClick={onEdit}>
Edit
</div>
<div
className="dropdown-item"
onClick={() => {
API.graphql(
graphqlOperation(mutations.deleteTodo, {
input: { id: todo.id }
})
);
}}
>
Delete
</div>
<div
className="dropdown-item"
onClick={() => {
API.graphql(
graphqlOperation(mutations.updateTodo, {
input: {
id: todo.id,
completedAt: !!todo.completedAt
? null
: new Date().toISOString()
}
})
);
}}
>
{!!todo.completedAt ? "Uncomplete" : "Complete"}
</div>
</div>
</div>
</React.Fragment>
);
};
const TodoListItem = ({ todo }) => {
const [isEditing, setIsEditing] = useState(false);
return (
<div className="d-flex border rounded py-1 px-2 mt-1">
{isEditing ? (
<TodoForm todo={todo} onClose={() => setIsEditing(false)} />
) : (
<TodoListItemDetails todo={todo} onEdit={() => setIsEditing(true)} />
)}
</div>
);
};
export default TodoListItem;
|
var express = require('express');
var app = express();
var fs = require('fs');
//获取用户列表
app.get('/listUsers', function (req, res) {
fs.readFile(__dirname + "/" + "users.json", 'utf8', function (err, data) {
console.log(data);
res.end(data);
});
});
//添加用户,此示例并没有更改到文件内部
var user4 = {
"user4": {
"name": "mohit",
"password": "password4",
"profession": "teacher",
"id": 4
}
}
app.get('/addUser', function (req, res) {
fs.readFile(__dirname+"/users.json",'utf8',function(err,data){
data=JSON.parse(data);
data["user4"]=user4["user4"];
console.log(data);
res.end(JSON.stringify(data));
})
});
//删除用户
app.get('/deleteUser/:id',function(req,res){
fs.readFile(__dirname+'/users.json','utf8',function(err,data){
data=JSON.parse(data);
delete data["user"+req.params.id];
res.end(JSON.stringify(data));
})
});
//显示用户详情
app.get('/:id',function(req,res){
fs.readFile(__dirname+'/users.json','utf8',function(err,data){
data=JSON.parse(data);
var user=data["user"+req.params.id]; //获取请求参数
console.log(user);
delete data["user"+2];
res.end(JSON.stringify(user));
})
});
var server = app.listen(8008, function () {
var host = server.address().address;
var port = server.address().port;
console.log("应用实例,访问地址为 http://", host, port)
})
|
import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import Style from './index.module.less';
import EditAccounts from './components/edit/index';
import ChangePassword from './components/changePassword/index';
import Nav from '@components/nav/index';
import Footer from '@components/footer/index';
@inject('rootStore')
@withRouter
@observer
class Account extends Component {
state = {
navList: ['编辑主页', '更改密码'],
currIndex: 0,
};
changeCurrIndex = currIndex => () => {
this.setState({
currIndex,
});
};
render() {
return (
<main>
<Nav />
<div className="page-container">
<section className={Style['accounts']}>
<nav>
<ul className={Style['operation-list']}>
{
this.state.navList.map((item, index) => {
return (
<li className={index === this.state.currIndex ? Style['active'] : ''} key={index} onClick={this.changeCurrIndex(index)}>
{item}
</li>
)
})
}
</ul>
</nav>
<section className={Style['operation-content']}>
{
this.state.currIndex === 0 ?
<EditAccounts onClick={this.changeCurrIndex(0)}/>
:
<ChangePassword onClick={this.changeCurrIndex(1)}/>
}
</section>
</section>
<Footer />
</div>
</main>
);
}
}
export default Account;
|
const swaggerUi = require('swagger-ui-express')
const swaggerJsDoc = require('swagger-jsdoc')
function swagger (app){
const swaggerOptions = {
swaggerDefinition: {
info: {
title: "Express Races",
description: "Users races API information",
contact: {
name: "Max Buinevich"
},
servers: ["http://localhost:3000"]
}
},
apis:["./api/**/*.router.js"]
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocs));
}
module.exports = swagger;
|
declare module 'glob' {
declare function sync(path: string): string[];
};
|
import styled from "styled-components";
export const StyledAlert = styled.div`
width: 200px;
height: 40px;
background-color: #2dcc70;
border-radius: 10px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
`;
|
const express = require("express");
const router = express.Router();
const BetterDB = require("better-sqlite3");
/**
* Express.js router for /getExperimentList
*
* Return array of all experiments with given project id
*/
let getExperimentList = router.get('/getExperimentList', function (req,res) {
console.log("Hello, getExperimentList!");
const uid = req.session.passport.user.profile.id;
const pid = req.query.pid;
let resultDb = new BetterDB("./db/projectDB.db");
let stmt = resultDb.prepare(`SELECT eid AS eid, ename AS ename FROM Experiment WHERE pid = ?;`);
let queryResult = stmt.all(pid);
resultDb.close();
// console.log(queryResult);
res.write(JSON.stringify(queryResult));
res.end();
});
module.exports = getExperimentList;
|
import * as R from 'rodin/core';
export class SkySphere extends R.Sphere {
constructor(map) {
const material = new THREE.MeshBasicMaterial({
map,
side: THREE.DoubleSide
});
super(50, 24, 24, material);
this.material = material;
this.rotation.y = Math.PI;
}
dispose() {
this.parent = null;
this.material.dispose();
}
}
|
export default class Product{
constructor(sku, name,image, longDescription, shortDescription, manufacturer, price ) {
this.sku = sku;
this.name = name;
this.image = image;
this.longDescription = longDescription;
this.shortDescription = shortDescription;
this.manufacturer = manufacturer;
this.price = price;
}
}
|
import React from 'react'
import { plainText } from '../store/db'
function ExtraFeature() {
const ExtraFet = (props) => {
return(
<div className="col-lg-6">
<div className={`box wow ${props.class}`}>
<div className="icon"><i className={props.icon}></i></div>
<h4 className="title"><a href="">{props.title}</a></h4>
<p className="description">{props.desc}</p>
</div>
</div>
)
}
return (
<section id="more-features" className="section-bg">
<div className="container">
<div className="section-header">
<h3 className="section-title">More Features</h3>
<span className="section-divider"></span>
<p className="section-description">{plainText[27]}</p>
</div>
<div className="row">
<ExtraFet icon="ion-ios-stopwatch-outline" class="fadeInLeft" desc={plainText[23]} title="Lorem Ipsum"/>
<ExtraFet icon="ion-ios-bookmarks-outline" class="fadeInRight" desc={plainText[24]} title="Dolor Sitema" />
<ExtraFet icon="ion-ios-heart-outline" class="fadeInLeft" desc={plainText[25]} title="Sed ut perspiciatis"/>
<ExtraFet icon="ion-ios-analytics-outlinee" class="fadeInRight" desc={plainText[26]} title="Magni Dolores" />
</div>
</div>
</section>
)
}
export default ExtraFeature
|
import React from 'react'
import { Card, Skeleton } from 'antd'
const Module = ({ title, loading, children, bordered }) => {
return (
<Card className={'module-card' + (bordered ? ' no-margin' : '')} bordered={bordered ? true : false}>
{loading ? (
<Skeleton active />
) : (
<>
{title}
{children}
</>
)}
</Card>
)
}
export default Module
|
$(document).ready(function () {
buildhtml();
// addJumboTron();
// addEmployeeTable();
//Starting to build html by adding a container to the body
function buildhtml(){
$("body").append($("<div>").addClass("container"));
addJumboTron();
addEmployeeTable();
}
//creating the jumbotron
function addJumboTron(){
$(".container").append($("<div>").addClass("jumbotron").attr("id", "myJumbotron"));
$("#myJumbotron").append($("<h1>").addClass("text-center").html("Employee Data Management "))
$("#myJumbotron").append($("<h3>").addClass("text-center").html("Comprehensive directory of Employee Billable Hours"))
}
//creating the table
function addEmployeeTable(){
$(".container").append($("<div>").addClass("row").attr("id", "firstRow"));
$("#firstRow").append($("<div>").addClass("col-lg-12").attr("id", "firstColumn"));
$("#firstColumn").append($("<div>").addClass("card").attr("id","firstCard"));
$("#firstCard").append($("<div>").addClass("panel-heading").attr("id","table-heading"));
$("#table-heading").append($("<h3>").addClass("panel-title").attr("id","panelTitle").html("<strong>Current Employee</strong>"));
$("#firstCard").append($("<div>").addClass("panel-body").attr("id","panelBody"));
$("#panelBody").append($("<table>").addClass("table table-hober").attr("id","train-table"));
$("#train-table").append($("<thead>").attr("id", "firstThead"));
$("#firstThead").append($("<tr>").attr("id","firstTR"));
$("#firstTR").append($("<th>").html("Employee Name"));
$("#firstTR").append($("<th>").html("Role"));
$("#firstTR").append($("<th>").html("Start Date"));
$("#firstTR").append($("<th>").html("Months Worked"));
$("#firstTR").append($("<th>").html("Monthly Rate ($)"));
$("#firstTR").append($("<th>").html("Total BIlled ($)"));
$("#train-table").append($("<tbody>").attr("id", "table-tbody"));
//this is where we will add all the train info
$("#firstColumn").append($("<div>").addClass("card").attr("id","trainInfoPanel"));
$("#trainInfoPanel").append($("<div>").addClass("panel-heading").attr("id","panelHeading"));
// $("#panelHeading").append($("<h3>").addClass("panel-title").attr("id","trainPanelTitle").html("<strong>Add Train</strong>"));
$("#trainInfoPanel").append($("<div>").addClass("panel-body").attr("id","trainPanelBody"));
$('#trainPanelBody').append($("<div>").addClass("panel-heading").attr("id","form-heading"));
$('#form-heading').append($("<h3>").addClass("panel-title").attr("id","panelTitle").html("<strong>Add Employee</strong>"));
$("#trainPanelBody").append($("<form>").attr("id","trainForm"));
$("#trainForm").append($('<div>').addClass("form-group").attr("id", 'form-group1'));
$('#form-group1').append($("<label>").attr("for", "employee-name").html("Employee Name"));
$('#form-group1').append($("<input>").addClass("form-control").attr("id", "employee-name"));
$("#trainForm").append($('<div>').addClass("form-group").attr("id", 'form-group1'));
$('#form-group1').append($("<label>").attr("for", "employee-role").html("Role"));
$('#form-group1').append($("<input>").addClass("form-control").attr("id", "employee-role"));
$("#trainForm").append($('<div>').addClass("form-group").attr("id", 'form-group1'));
$('#form-group1').append($("<label>").attr("for", "employee-startDate").html("Start Date (MM/DD/YYYY)"));
$('#form-group1').append($("<input>").addClass("form-control").attr("id", "employee-startDate"));
$("#trainForm").append($('<div>').addClass("form-group").attr("id", 'form-group1'));
$('#form-group1').append($("<label>").attr("for", "employee-monthlyRate").html("Monthly Rate"));
$('#form-group1').append($("<input>").addClass("form-control").attr("id", "employee-monthlyRate"));
$("#trainForm").append($("<button>").addClass("btn btn-primary btn-block").attr({id: "add-train-btn", type: "submit"}).html("Submit"));
}
});
$("#trainPanelBody").append($("<form>").attr("id","trainForm"));
$("#trainForm").append($("<button>").addClass("btn btn-primary btn-block").attr({id: "add-train-btn", type: "submit"}).html("Add Employee"));
}
// Initialize Firebase
var config = {
apiKey: "AIzaSyCaGRbwU1SrfhHiZj3X_BpjPtEgOislx3M",
authDomain: "employeedata-7c4b8.firebaseapp.com",
databaseURL: "https://employeedata-7c4b8.firebaseio.com",
projectId: "employeedata-7c4b8",
storageBucket: "employeedata-7c4b8.appspot.com",
messagingSenderId: "31454540790"
};
firebase.initializeApp(config);
var dataRef = firebase.database();
// Initial Values
var name = "";
var role = "";
var start = "";
var rate = "";
// Capture Button Click
$("#add-user").on("click", function(event) {
event.preventDefault();
// YOUR TASK!!!
// Code in the logic for storing and retrieving the most recent user.
// Don't forget to provide initial data to your Firebase database.
name = $("#name-input").val().trim();
role = $("#email-input").val().trim();
start = $("#age-input").val().trim();
rate = $("#comment-input").val().trim();
// Code for the push
dataRef.ref().push({
name: name,
role: role,
start: start,
rate: rate,
dateAdded: firebase.database.ServerValue.TIMESTAMP
});
});
// Firebase watcher + initial loader HINT: This code behaves similarly to .on("value")
dataRef.ref().on("child_added", function(childSnapshot) {
// Log everything that's coming out of snapshot
console.log(childSnapshot.val().name);
console.log(childSnapshot.val().role);
console.log(childSnapshot.val().start);
console.log(childSnapshot.val().rate);
console.log(childSnapshot.val().dateAdded);
// full list of items to the well
$("#full-member-list").append("<div class='well'><span class='member-name'> " +
childSnapshot.val().name +
" </span><span class='member-email'> " + childSnapshot.val().email +
" </span><span class='member-age'> " + childSnapshot.val().age +
" </span><span class='member-comment'> " + childSnapshot.val().comment +
" </span></div>");
// Handle the errors
}, function(errorObject) {
console.log("Errors handled: " + errorObject.code);
});
dataRef.ref().orderByChild("dateAdded").limitToLast(1).on("child_added", function(snapshot) {
snap = snapshot.val()
// Change the HTML to reflect
$("#name-display").text(snap.name);
$("#role-display").text(snap.role);
$("#start-display").text(snap.start);
$("#date-display").text(snap.rate);
});
});
|
/* eslint require-jsdoc: 'off' */
import StageLoader from './StageLoader';
import simpleObjectExtend from '../utils/simpleObjectExtend';
function estimatedLoadingTime(array) {
return array.map(item => item.totalSize / item.bandwidth.value).reduce((a, b) => a + b);
}
function elapsedLoadingTime(array) {
const toSubtract = array.map(function (actual, index) {
const previous = array[index - 1];
if (previous) {
if (previous.end > actual.start) {
return Math.min(previous.end, actual.end) - actual.start;
}
}
return 0;
}).reduce((a, b) => a + b);
return (array.map(item => item.duration).reduce((a, b) => a + b) - toSubtract) / 1000;
}
function totalSize(array) {
return array.map(item => item.totalSize).reduce((a, b) => a + b);
}
function groupByType(array) {
const ret = {};
array.forEach((item) => {
ret[item.type] = ret[item.type] || [];
ret[item.type].push(item);
});
return ret;
}
export default function (system) {
const obj = {};
const loaders = {};
let files = [];
const stats = [];
obj.addLoader = function (fileTypes, loader) {
fileTypes.forEach((type) => {
loaders[type] = loader;
});
};
obj.addManifest = function (manifest, params = {}) {
simpleObjectExtend(manifest, params);
if (manifest instanceof Array) {
manifest.forEach(function (item) {
simpleObjectExtend(item, params);
});
}
files = files.concat(manifest);
};
obj.loadStage = function (stages, quality, bandwidth, { MaxRetry, RetryTimeout, forcedAssetsQuality } = {}) {
const original = [].concat(stages)
.map(stage => files.filter(file => [].concat(file.stage).indexOf(stage) !== -1))
.reduce((itA, itB) => itA.concat(itB))
.filter(item => item.state !== 'loaded' || forcedAssetsQuality);
original.forEach(item => item.state = 'loading');
const stageFiles = JSON.parse(JSON.stringify(original));
const groupedRes = groupByType(stageFiles);
const stageLoader = StageLoader(groupedRes, loaders, quality,
bandwidth.value, { system, MaxRetry, RetryTimeout });
stageLoader.on('complete', (stat) => {
const item = { stages: [].concat(stages), bandwidth };
original.forEach(item => {
const state = 'loaded';
const {size} = stat.resourcesStats.filter(i => item.url.indexOf(i.url) !== -1)[0] || {};
simpleObjectExtend(item, { size, state });
});
simpleObjectExtend(item, stat);
stats.push(item);
});
stageLoader.on('error', () => {
original.forEach(item => item.state = undefined);
});
return stageLoader;
};
obj.totalSize = function (stages, quality, bandwidth) {
const stageFiles = []
.concat(stages)
.map(stage => files.filter(file => file.stage === stage))
.reduce((itA, itB) => itA.concat(itB));
const groupedRes = groupByType(stageFiles);
const stageLoader = StageLoader(groupedRes, loaders, quality, bandwidth.value);
return stageLoader.totalSize();
};
obj.stats = function () {
return {
stages: stats.map((item) => {
return {
stages: item.stages.join(', '),
estimatedLoadingTime: estimatedLoadingTime([item]),
elapsedLoadingTime: elapsedLoadingTime([item]),
totalSize: item.totalSize,
sampleSize: item.bandwidth.sampleSize
};
}),
estimatedLoadingTime: estimatedLoadingTime(stats),
elapsedLoadingTime: elapsedLoadingTime(stats),
totalSize: totalSize(stats),
sampleSize: stats[0] ? stats[0].bandwidth.sampleSize : 0
};
};
return obj;
}
|
/**
* 保障房项目初始化
*/
var projecManage = {
id: "ProjectTable", //表格id
seItem: null, //选中的条目
table: null,
layerIndex: -1,
url:"",
secondLayerIndex:-1
};
/**
* 初始化表格的列
*/
projecManage.initColumn = function () {
return [
{field: '', radio: false,formatter:function(value,row,index){
return '<input type="hidden" value="'+row.id+'">';
}
},
{title: '项目名称', field: 'name', align: 'center', valign: 'middle', sortable: true},
{title: '项目地址', field: 'address', align: 'center', valign: 'middle', sortable: true},
{title: '建设单位', field: 'constructionUnit', align: 'center', valign: 'middle', sortable: true},
{title: '建设套数', field: 'houseNumber', align: 'center', valign: 'middle', sortable: true},
{title: '操作', align: 'center', valign: 'middle',
formatter:function(value,row,index){
var str = '';
if(row.canChange == '1'){
str += '<a onclick="projecManage.detail('+'\'' + row.id + '\',\'1\')">编辑</a> | ';
if(bindingHouseTablePower == 'true'){
str += '<a onclick="projecManage.chooseHouseTable('+'\'' + row.id + '\')">绑定楼盘表</a> | ';
}
}
str += '<a onclick="projecManage.detail('+'\'' + row.id + '\',\'0\')">查看</a>';
return str;
}
}
];
};
projecManage.query = function(){
var param = {
"name":$("#condition").val()
};
projecManage.table.refresh({query: param});
};
/**
* 项目详情
* @param id
* @param num
*/
projecManage.detail = function (id,num) {
var index = layer.open({
type: 2,
title: '项目详情',
area: ['100%', '100%'], //宽高
fix: false, //不固定
maxmin: true,
content: Feng.ctxPath + '/project/project_detail?id='+id + '&num=' + num
});
projecManage.layerIndex = index;
layer.full(index);
};
/**
* 选择楼盘表
* @param id
* @param num
*/
projecManage.chooseHouseTable = function (id) {
var index = layer.open({
type: 2,
title: '选择楼盘表',
area: ['100%', '100%'], //宽高
fix: false, //不固定
maxmin: true,
content: Feng.ctxPath + '/project/choose_houseTable?id=' + id
});
projecManage.layerIndex = index;
layer.full(index);
};
/**
* 关闭此对话框
*/
projecManage.close = function () {
parent.layer.close(window.parent.projecManage.layerIndex);
};
projecManage.openExport = function () {
}
projecManage.exportExc = function (num) {
var formData=new FormData();
formData.append('excelExport', $("#excelExport")[0].files[0]); /*获取上传的excel*/
formData.append('num', num); /*获取上传的excel*/
if(num==1){
$.ajax({
url: '/excel/import_excel',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (args) {
if(args == '导入成功'){
window.location.reload();
Feng.success(args);
}else{
Feng.info(args);
}
}
});
}else{
$("#numInput").val(num);
$("#import_excel").submit();
}
}
//保存项目信息
projecManage.save = function () {
var data = $("#projectInfoForm").serializeJSON();
if(data.name == null || data.name == "" || data.name == undefined){
Feng.info("项目名称不能为空!");
return ;
}
if(data.startTime == null || data.startTime == "" || data.startTime == undefined) {
data.startTime = new Date(1900,0,1);
}
if(data.endTime == null || data.endTime == "" || data.endTime == undefined){
data.endTime = new Date(1900,0,1);
}
data = {json:JSON.stringify(data)};
$.ajax({
url:'/project/save',
type:'POST',
// contentType: 'application/json; charset=UTF-8',
async:false,
// dataType:'json',
data:data,
success: function (response) {
if(response == 'Error'){
Feng.info('保存失败');
}else{
projecManage.close();
parent.location.reload();
Feng.success('保存成功');
}
}
})
};
projecManage.deleteProject = function () {
layer.open({
content: '确定删除所选项目?删除后无法恢复'
,btn: ['确定', '关闭']
,yes: function(index, layero){
var id = '';
$.each($('input[name="btSelectItem"]:checked'),function(){
var valId = $(this).parent().find("input[type=hidden]").val();
id += valId + ',';
});
var data = {id:id};
$.ajax({
url:'/project/delete',
type:'POST',
// contentType: 'application/json; charset=UTF-8',
async:false,
// dataType:'json',
data:data,
success: function (response) {
if(response == 'Error'){
Feng.info('删除失败');
}else{
location.reload();
Feng.success('删除成功');
}
}
})
}
,btn2: function(index, layero){
//按钮【按钮二】的回调
//return false 开启该代码可禁止点击该按钮关闭
}
,cancel: function(){
//右上角关闭回调
}
});
};
$(function () {
projecManage.url = "/project/list";
var defaultColunms = projecManage.initColumn();
var table = new BSTable(projecManage.id, projecManage.url, defaultColunms);
projecManage.table = table.init();
});
|
var express = require("express");
var Router = express.Router;
var UserController = require("./controllers/users");
var VideoController = require("./controllers/videos");
var ImageController = require("./controllers/images");
var DeviceController = require("./controllers/devices");
var path = require("path");
const front = require("./controllers/front-react");
const router = Router();
router.get("/", (req, res) => {
res.json({
status: 200,
message: "JIFCAM API",
data: null,
errors: []
});
});
exports.mountRoutes = function(app) {
const Users = new UserController();
const Videos = new VideoController();
const Image = new ImageController();
const device = new DeviceController();
const pathDocs = path.resolve(__dirname, "./apidoc");
const pathPublic = path.resolve(__dirname, "./public");
//console.log(pathDocs);
app.use("/", front.serverRender());
app.use("/admin", front.serverRender());
app.use("/admin/*", front.serverRender());
app.use("/api/users", Users.router());
app.use("/api/devices", device.router());
app.use("/api/videos", Videos.router());
app.use("/api/images", Image.router());
app.use("/api/docs", express.static(path.join(pathDocs)));
app.use("/static", express.static(path.join(pathPublic)));
};
|
var cubeW=20;
var cubeArr=[[6,7,12,13],[7,8,11,12],[6,7,11,12],[7,12,17,8],[7,12,16,17],[7,12,17,22],[7,11,12,13]];
var colorArr=['#ffc0cb','#dda0dd','#9370db','#6495ed','#fa8072','#ff8c00','#008000'];
var rotateArr=[4,9,14,19,24,3,8,13,18,23,2,7,12,17,22,1,6,11,16,21,0,5,10,15,20];
var canvas=document.getElementById('can');
var ctx=canvas.getContext('2d');
var score=document.getElementById('score');
var canWidth=canvas.width;
var canHeight=canvas.height;
var downInfor={}, staticCube=[];
var myinter;
window.onload=function() //初始化
{
drawline();
for(var i=0;i<(canWidth/cubeW);i++)
{
staticCube[i]=[];
for(var j=0;j<(canHeight/cubeW);j++)
{
staticCube[i][j]=0;
}
}
initCube();
myinter=setInterval('movedown()',1000); //第一个参数要加引号
}
function drawline()
{
ctx.lineWidth=1;
ctx.strokeStyle='#ddd';
for(var i=0;i<(canWidth/cubeW);i++)
{
ctx.moveTo(cubeW*i,0);
ctx.lineTo(cubeW*i,canHeight);
}
ctx.stroke();
for(var j=0;j<(canHeight/cubeW);j++)
{
ctx.moveTo(0,cubeW*j);
ctx.lineTo(canHeight,cubeW*j);
}
ctx.stroke();
}
function initCube()
{
var index=Math.floor(Math.random()*cubeArr.length);//随机生成
downInfor.cubeNow=cubeArr[index].concat();
downInfor.index=index;
downInfor.prepoint=[5,-1];
downInfor.point=[5,-1];
drawEle(colorArr[downInfor.index]);
}
function movedown()
{
//判断下一个位置是否合理
var length,isempty=true,px,py,movex,movey,max=0;
for(var i=0;i<4;i++)
{
if(max<downInfor.cubeNow[i])
max=downInfor.cubeNow[i];
}
length=Math.ceil(max/5);
for(var i=0;i<4;i++)
{
px=downInfor.point[0]+downInfor.cubeNow[i]%5;
py=downInfor.point[1]+1+Math.floor(downInfor.cubeNow[i]/5);
if(staticCube[px][py]==1)
{
isempty=false;
break;
}
}
if((downInfor.point[1]+length)<(canHeight/cubeW)&&isempty)
{
downInfor.prepoint=downInfor.point.concat();//注意引用类型
downInfor.point[1]=downInfor.point[1]+1;
clearEle();
drawEle(colorArr[downInfor.index]);
}
else//不能移动的时候
{
for(var i=0;i<4;i++)
{
px=downInfor.point[0]+downInfor.cubeNow[i]%5;
py=downInfor.point[1]+Math.floor(downInfor.cubeNow[i]/5);
staticCube[px][py]=1;
}
drawEle('#555');
checkfullLine();
}
}
function moveLeft()
{
var leftroom=4,isempty=true,px,py,movex,movey;
for(var i=0;i<4;i++)
{
px=downInfor.point[0]-1+downInfor.cubeNow[i]%5;
py=downInfor.point[1]+Math.floor(downInfor.cubeNow[i]/5);
if((downInfor.cubeNow[i]%5)<leftroom)
leftroom=downInfor.cubeNow[i]%5;
if(staticCube[px][py]==1)
{
isempty=false;
break;
}
}
if((downInfor.point[0]+leftroom)>=0&&isempty)
{
downInfor.prepoint=downInfor.point.concat();
downInfor.point[0]=downInfor.point[0]-1;
clearEle();
drawEle(colorArr[downInfor.index]);
}
}
function moveRight()
{
var rightroom=0,isempty=true,px,py,movex,movey;
for(var i=0;i<4;i++)
{
px=downInfor.point[0]+1+downInfor.cubeNow[i]%5;
py=downInfor.point[1]+Math.floor(downInfor.cubeNow[i]/5);
if((downInfor.cubeNow[i]%5)>rightroom)
rightroom=downInfor.cubeNow[i]%5;
if(staticCube[px][py]==1)
{
isempty=false;
break;
}
}
if((downInfor.point[0]+rightroom+1)<(canWidth/cubeW)&&isempty)
{
downInfor.prepoint=downInfor.point.concat();
downInfor.point[0]=downInfor.point[0]+1;
clearEle();
drawEle(colorArr[downInfor.index]);
}
}
function moverotate()//处理旋转
{
var isempty=true,px,py,movex,movey, tempRotate=[0,0,0,0];
for(var i=0;i<4;i++)
{
tempRotate[i]=rotateArr[downInfor.cubeNow[i]];
}
for(var i=0;i<4;i++)
{
px=downInfor.point[0]+tempRotate[i]%3;
py=downInfor.point[1]+Math.floor(tempRotate[i]/3);
if(staticCube[px][py]==1)
{
isempty=false;
break;
}
}
if(isempty)
{
downInfor.prepoint=downInfor.point.concat();
clearEle();
downInfor.cubeNow=tempRotate.concat();
drawEle(colorArr[downInfor.index]);
}
}
function drawEle(color)
{
ctx.fillStyle=color;
ctx.strokeStyle='#fff';
for(var i=0;i<4;i++)
{
var movex=downInfor.cubeNow[i]%5;
var movey=Math.floor(downInfor.cubeNow[i]/5);
ctx.fillRect(cubeW*(downInfor.point[0]+movex),cubeW*(downInfor.point[1]+movey),cubeW,cubeW);
ctx.strokeRect(cubeW*(downInfor.point[0]+movex),cubeW*(downInfor.point[1]+movey),cubeW,cubeW)
}
}
function clearEle()
{
ctx.lineWidth=1;
ctx.strokeStyle='#ddd';
for(var i=0;i<4;i++)
{
var movex=downInfor.cubeNow[i]%5;
var movey=Math.floor(downInfor.cubeNow[i]/5);
ctx.clearRect(cubeW*(downInfor.prepoint[0]+movex),cubeW*(downInfor.prepoint[1]+movey),cubeW,cubeW);
ctx.strokeRect(cubeW*(downInfor.prepoint[0]+movex),cubeW*(downInfor.prepoint[1]+movey),cubeW,cubeW)
}
}
function checkfullLine()//检测是否有一行满了
{
var isFullLine=true,index=0,changeScore=false;
for(var i=0;i<canWidth/cubeW;i++)
{
if(staticCube[i][0]==1)
{
alert('游戏结束!');
clearInterval(myinter);
return;
}
}
for(var i=canHeight/cubeW-1;i>=0;i--)
{
isFullLine=true;
for(var j=0;j<(canWidth/cubeW);j++)
{
if(staticCube[j][i]==0)
{
isFullLine=false;
}
}
if(isFullLine)//加一分
{
score.innerHTML=parseInt(score.innerText)+1;
changeScore=true;
for(var s=i;s>=0;s--) {
for (var j = 0; j < (canWidth / cubeW); j++) {
(s- 1) >= 0 ? staticCube[j][s] = staticCube[j][s - 1] : staticCube[j][s] = 0;
}
}
}
}
if(changeScore)
{
ctx.clearRect(0,0,canWidth,canHeight);
drawline();
ctx.fillStyle='555';
ctx.strokeStyle='#fff';
for(var i=0;i<(canWidth/cubeW);i++)
{
for(var j=0;j<(canHeight/cubeW);j++)
{
if(staticCube[i][j]==1)
{
ctx.fillRect(cubeW*i,cubeW*j,cubeW,cubeW);
ctx.strokeRect(cubeW*i,cubeW*j,cubeW,cubeW);
}
}
}
}
initCube();
}
window.onkeydown=function (evt)
{
switch(evt.keyCode)
{
case 37: //左
moveLeft();
break;
case 38: //上
moverotate();
break;
case 39: //右
moveRight();
break;
case 40: //下
movedown();
break;
}
}
|
import React from "react";
import { StyleSheet, Text, View, ScrollView, Image } from "react-native";
import { useSelector } from "react-redux";
const DeetsFotos = ({ route, navigation }) => {
const { fotoId } = route.params;
const fotoSelecionada = useSelector((state) =>
state.fotos.fotos.find((foto) => foto.id === fotoId)
);
return (
<ScrollView contentContainerStyle={{ alignItems: "center" }}>
<View style={styles.alinhar}>
<Text style={styles.titulo}>{fotoSelecionada.titulo}</Text>
<View style={styles.containerImagem}>
<Image
source={{ uri: fotoSelecionada.imagemUri }}
style={styles.imagem}
/>
</View>
<View style={styles.detalhes}>
<View style={{ marginTop: 15 }}>
<Text style={{ fontSize: 17, fontWeight: "bold" }}>Endereço:</Text>
<Text style={styles.endereco}> {fotoSelecionada.endereco}</Text>
<View
style={{ flexDirection: "row", justifyContent: "space-around" }}
>
<Text style={styles.coords}>Latitude: {fotoSelecionada.lat}</Text>
<Text style={styles.coords}>
Longitude: {fotoSelecionada.lng}
</Text>
</View>
</View>
</View>
</View>
</ScrollView>
);
};
export default DeetsFotos;
const styles = StyleSheet.create({
alinhar: {
marginTop: 25,
justifyContent: "center",
},
imagem: {
marginTop: "5%",
alignSelf: "center",
width: "90%",
minHeight: 200,
},
titulo: {
fontSize: 25,
alignSelf: "center",
},
containerImagem: {
marginBottom: 20,
},
endereco: {
margin: 10,
padding: 5,
borderBottomWidth: 1,
borderBottomColor: "#ccc",
},
coords: {
padding: 10,
borderBottomWidth: 1,
borderBottomColor: "#ccc",
},
detalhes: {
marginHorizontal: 15,
},
});
|
{
"summary":"My Favorite Books",
"books":[
{
"title":"The Thornbirds",
"genre":"fiction",
"author":"Collen McCullough",
"yearPubbed":"1977",
"image":"http://placekitten.com/g/200/133",
"buy":"http://www.amazon.com/The-Thorn-Birds-Colleen-McCullough/dp/0380018179"
},
{
"title":"The Shock Doctrine: The Rise of Disaster Capitalism",
"genre":"non-fiction",
"author":"Naomi Klein",
"yearPubbed":"2008",
"image":"http://placekitten.com/g/200/133",
"buy":"http://www.amazon.com/The-Shock-Doctrine-Disaster-Capitalism/dp/0312427999"
},
{
"title":"Night of the Gun",
"genre":"memoir",
"author":"David Carr",
"yearPubbed":"2008",
"image":"http://placekitten.com/g/200/133",
"buy":"http://www.amazon.com/Night-Gun-reporter-investigates-darkest-ebook/dp/B001DXNZ9Q/"
},
]
}
|
function mostrar()
{
var contador=0;
var numeroingresado
var numeronegativo
var numeropositivo
var cantidaddepositivos
var cantidaddenegativos
var cantidaddeceros
var cantidaddenumeropares
var promediopositivos
var promedionegativos
var diferenciaposneg
//declarar contadores y variables
var respuesta="si";
numeronegativo=0
numeropositivo=0
cantidaddepositivos=0;
cantidaddenegativos=0;
cantidaddeceros=0
cantidaddenumeropares=0
promedionegativos=0
promediopositivos=0
while(respuesta!="no")
{
numeroingresado=prompt("ingrese numero");
numeroingresado=parseInt(numeroingresado);
if(numeroingresado<0){
numeronegativo=numeronegativo+numeroingresado
cantidaddenegativos=cantidaddenegativos+1;
}
if(numeroingresado>0){
numeropositivo=numeropositivo+numeroingresado
cantidaddepositivos=cantidaddepositivos+1;
}
if(numeroingresado==0)
{
cantidaddeceros=cantidaddeceros+1;
}
if(numeroingresado %2 ==0 && numeroingresado !=0)
{
cantidaddenumeropares=cantidaddenumeropares+1;
}
respuesta=prompt("ingrese no para salir","escribe aqui");
}
promediopositivos=numeropositivo/cantidaddepositivos
promedionegativos=numeronegativo/cantidaddenegativos
diferenciaposneg=numeropositivo-numeronegativo
console.log("la suma de negativos es " +numeronegativo)
console.log("la suma de positivos es " +numeropositivo)
console.log("la cantidad de positivos es " +cantidaddepositivos)
console.log("la cantidad de negativos es " +cantidaddenegativos)
console.log("la cantidad de ceros es " +cantidaddeceros)
console.log("la cantidad de numeros pares es " +cantidaddenumeropares)
console.log("el promedio negativo es " +promedionegativos)
console.log("el promedio positivo es " +promediopositivos)
console.log("la diferencia del negativo y el positivo es " +diferenciaposneg)
}
|
$(function() {
// 暂时是全局变量;
nodeItem;
//debugger;
var nodeItem;
//对象检测类
function ObjWatch(){
//默认对象结构
this.obj = {};//操作对象,用来保存临时操作状态
this.backupObj = {};//备份对象,当不保存时,用来还原数据
};
ObjWatch.prototype = {
constructor : ObjWatch,
init : function(){
//设置默认值
var obj = {
"identity" : "", // mongo数据库id
"alias" : "",
"name" : "",
"option" : {
show : [ // 要显示哪些字段,还要兼顾字段显示顺序
//[{字段ID}, {字段类型},{关联对象ID}],
],
enumerate :
{
"property" : "enumerate_id"
},
show_type : "view", // 显示类型。可选"view" || "edit"
star : false
}
}
//根据参数0覆盖最顶层属性,如果存在
for(var i in arguments[0]){
if(Object.prototype.hasOwnProperty.call(arguments[0],i)){
obj[i] !== undefined && obj[i] !== null && ( obj[i] = arguments[0][i] );
}
}
this.obj = obj;
this.backupObj = obj;
return this;
},
set : function(){
var key = arguments[0],
value = arguments[1],
obj = arguments[2] || this.obj;
if(typeof key === "string"){
key && (new Function('obj','value','obj.'+key+'!==undefined && obj.'+key+' !== null && ( obj.'+key+' = value );'))(obj,value);
}else if(typeof key === 'object'){
obj = arguments[1] || this.obj;
for(var i in key){
if(Object.prototype.hasOwnProperty.call(key,i)){
i && (new Function('obj','value','obj.'+i+'!==undefined && obj.'+i+' !== null && ( obj.'+i+' = value );'))(obj,key[i]);
}
}
}
return this;
},
setShow: function (fn){
var result = fn(JSON.parse(JSON.stringify(this.obj.option.show)));
this.set("option.show",result);
return this;
},
reset: function(){
this.obj = JSON.parse(JSON.stringify(this.backupObj));
return this;
},
build: function (){
this.backupObj = this.obj;
return this;
},
get: function(){
return this.obj;
}
}
ObjWatch.getInstance = function(){
var watch = new ObjWatch();
watch.init();
return watch;
}
function ToolClass(){
this.watchs = {};
this.extra = {};
}
ToolClass.prototype.getWatch = function(){
return this.watchs[arguments[0]].reset();
}
ToolClass.prototype.setWatch = function(){
this.watchs[arguments[0]] = arguments[1];
}
ToolClass.prototype.keepVar = function(){
var args = arguments[0];
if(typeof args === 'string'){
this.extra[args] = arguments[1];
}else if(typeof args === 'object' && !(args instanceof Array)){
for(var i in arguments[0]){
if(Object.prototype.hasOwnProperty.call(arguments[0],i)){
this.extra[i] = arguments[0][i];
}
}
}
return this;
}
ToolClass.prototype.getVar = function(){
var result = [],
args = arguments[0];
if(args === undefined){
result = this.extra;
}
if(typeof args === 'string'){
result = this.extra[args];
}else if(args instanceof Array){
for(var i = 0,len = args.length; i<len; i++){
result.push(this.extra[args[i]]);
}
}
result = result instanceof Array ? result.length ? result : null :result;
return result;
}
ToolClass.prototype.buildData = function(){
var data = arguments[0],
obj = arguments[1],
objProperty = arguments[2];
if(data.option){
this.watchs[data.id].init(data);
}else{
var show = [];
for(var i in objProperty){
if(Object.prototype.hasOwnProperty.call(objProperty,i)){
if(i !== 'id'){
show.push([objProperty[i]._id,objProperty[i].datatype]);
}
}
}
this.watchs[data.id].set({
"option.show" : show,
"identity" : obj._id
}).set(obj);
}
}
ToolClass.getInstance = (function(){
var instance;
return function(){
if(!instance){
instance = new ToolClass();
}
return instance;
}
})();
//modal DOM id
var modalId = "#obj-config-modal";
var $modal = $(modalId);
var tool = ToolClass.getInstance();
//注册一个Modal型、对象配置框
(function(tool) {
var ConfigModal = function (spec, inherit) {
inherit = inherit || Design.modal.root;
var that = inherit(spec);
var watch ;
//modal init
var init = function(){
//data
var args = arguments[0],
data = args['config'],
obj = args['obj'],
properties = args['properties'],
relations = args['relations'];
//DOMs
var modal = $(modalId),
itemTemplate = modal.find('.item-template'),
modalBodyContent = modal.find( ".modal-body-content" ),
modalFooter = modal.find( ".modal-footer" ),
submitButton = modalFooter.find('button[data-type="submit"]'),
nextButton = modalFooter.find('button.obj-next-btn'),
preButton = modalFooter.find('button.obj-pre-btn'),
list = $('<ul></ul>').addClass('list-group obj_sortable'),
groupTemplate = $('#objectPropertyListTemplate'),
groups = [];
//如果已经添加了List节点,则清空
modalBodyContent.find('.obj_sortable').remove();
// 打开流程content页面
modalBodyContent.on('click', '.add-flow', function(){
var propPair = $(this.parentElement).data('value'),
objId = watch.get().identity,
iframe, enumKey,
propName = $(this).siblings('span').text().trim();
if (typeof propPair === 'object' && propPair.length && objId){
enumKey = 'enumerate_'+propPair[0];
// 打开流程content
iframe = parent.breadcrumbApi.add(enumKey, propName, 'content_'+enumKey+'.html');
iframe.data('obj-id', objId);
}else{
alert('打开流程出错,请重新刷新页面.');
}
})
//初始化Modal底部按钮组
toggleBtn(true)
//上一步按钮监听
preButton.off('click').on('click',function(event){
event.preventDefault();
//设置Modal底部按钮组
toggleBtn();
//显示所有字段
modalBodyContent.find('.obj_sortable').toggleClass('hidden');
});
//下一步按钮监听
nextButton.off('click').on('click',function(event){
event.preventDefault();
var showPropertyDoms = modal.find('.list-group-item.show').clone(true);
//删除排序页已生成的list,防止再次进入时,重复内容
modal.find('.obj_sortable[init]').remove();
//隐藏所有字段
modalBodyContent.find('.obj_sortable').toggleClass('hidden');
//添加显示的字段到排序页中
modalBodyContent.append(initSortableList.call(this,list.clone(),showPropertyDoms,{config:watch.get(),properties:properties}))
//设置Modal底部按钮组
toggleBtn();
});
//设置查看模式
modal.find('.show-type')
.data('value',watch.get().option.show_type)
.children('span').text(watch.get().option.show_type === 'view' ?'查看模式':'编辑模式')
//如果存在关系
if(relations){
for(var i = 0,len = relations.length;i<len;i++){
if(tool.getVar(relations[i].id)){
groups.push(initPanelGroup.call(this,groupTemplate.clone(),{
index:i,
config:data,
relation:relations[i],
list : initList.call(this,list.clone(),tool.getVar(relations[i].id).properties)
}));
}
}
}
//绑定Modal事件-查看模式
modal.find('.show-type').off('click').on('click',function(){
var current = $(this),
value = current.data('value');
value = value === 'view'?'edit':'view';
current.data('value',value);
current.children('span').text(value === 'view'?'查看模式':'编辑模式');
});
//添加到DOM中
modalBodyContent.find('#obj_config_modal_group').append(groups);
/**
* [toggleBtn description] 设置底部按钮
* @param {[type]} init [description] Boolean 表示是否为初始化按钮
* @return {[type]} [description]
*/
function toggleBtn(init){
if(init){
//初始化Modal底部按钮组
preButton.addClass('hidden');
submitButton.removeClass('hidden');
nextButton.removeClass('hidden');
}else{
//toggle显示Modal底部按钮组
preButton.toggleClass('hidden');
nextButton.toggleClass('hidden');
}
}
//初始化折叠面板
function initPanelGroup(group,data){
var relation = data.relation,
index = data.index,
list = data.list;
var id = relation.id;
var isFirst = index === 0;
var panelHeader = group.find('[panel-header]'),
panelControl = group.find('[panel-control]'),
panelGroup = group.find('[panel-group]'),
panelUL = group.find('[panel-ul]'),
panelLI = group.find('[panel-li]');
group.removeAttr('id').addClass('obj_sortable');
panelGroup.append(list)
.addClass(isFirst ? 'in' :'');
panelHeader.attr('id',id+'header');
panelControl.attr('href',"#"+id+"group")
.attr('aria-controls',id+"group")
.text(relation.text)
.attr('aria-expanded',isFirst)
.removeClass(isFirst?'collapsed':'');
panelGroup.attr('aria-labelledby',id+'header').attr('id',id+"group");
return group;
}
//初始化可排序List
function initSortableList(list,items,data){
for(var i = 0,items = changeItem(items,data),len = items.length;i<len;i++){
list.append(items[i]);
}
// 给list每一项加上一个按钮,用于打开流程设计
list.find('li.list-group-item').append('<span class="add-flow glyphicon glyphicon-flag pull-right" aria-hidden="true"></span>');
//设置拖拽
list.sortable({
update: function(event){
var $target = $(event.toElement),
nodeName = event.toElement.nodeName;
var $parent = $target.parent(),
$childs = $parent.find(nodeName);
var oldIndex = $target.data('index'),
newIndex = $childs.index($target);
watch.setShow(function(show){
show.splice(newIndex,0,show.splice(oldIndex,1)[0]);
return show;
});
}
});
list.disableSelection();
list.attr('init',true);
function changeItem(doms,data){
var result = [],
backlist = {},
whitelist = {},
properties = data.properties,
haveList = data.config && data.config.option && data.config.option.show || [];
doms.each(function(index,dom){
var propertyId = $(dom).data('value')[0];
whitelist[propertyId] = true;
})
$.each(haveList,function(index,item){
if(whitelist[item[0]]){
var alias = '';
if(item[2]){
alias = tool.getVar(item[2]) && tool.getVar(item[2]).properties[item[0]].alias || '';
}else{
alias = properties[item[0]].alias;
}
result.push(initSortableItem({
value:item,
alias:alias,
index:result.length
}));
backlist[item[0]] = true;
}
})
doms.each(function(index,dom){
var $dom = $(dom),
propertyId = $dom.data('value')[0];
if(!backlist[propertyId]){
$dom.find('span.is-show').remove();
result.push($dom);
backlist[propertyId] = true;
}
});
return result;
}
/**
* [initSortableItem description]
* @param {[type]} data [description] data.value 字段最终数据结构[] ; data.alias 字段别名
* @return {[type]} [description]
*/
function initSortableItem(data){
var newItem = itemTemplate.clone();
newItem.removeClass('item-template')
.data('value',data.value)
.data('index',data.index)
.children('.text').text(data.alias);
newItem.find('span.is-show').remove();
return newItem;
}
return list;
}
//初始化普通List节点
function initList(list,properties){
var obj = watch.get();
for(var i in properties){
if(Object.prototype.hasOwnProperty.call(properties,i)){
//排除数据结构中的id字段
if(i !== 'id'){
//是否存在option.show中,即是否显示
var index = indexofById(properties[i],obj.option.show);
var id = properties[i]._id,
type = properties[i].datatype,
objId = properties['id']._id,
relationId = obj.identity;
//初始化节点
var item = initItem({
data:relationId === objId ? [id,type]:[id,type,objId],
index:index !== -1 ? index :'',
alias:properties[i].alias,
isShow:index !== -1
});
list.append(item);
}
}
}
//显示Bootstrap提示
list.find('.is-show').tooltip('show');
//绑定列表事件
list.off('click').on('click','.is-show',function(e){
var target = $(e.currentTarget),
currentTarget = target.closest('.list-group-item'),
data = currentTarget.data('value'),
index = currentTarget.data('index'),
status = !target.data('value');
target.data('value',status);
watch.setShow(function(show){
if(index === ''){
currentTarget.data('index',show.length);
show.push(data);
}else{
status?show.splice(index,0,data):show.splice(index,1);
}
return show;
});
target.removeClass('show').addClass(status?'show':'');
currentTarget.removeClass('show disabled').addClass(status?'show':'disabled');
target.children('.text').text(status?'是':'否');
target.children('.glyphicon')
.removeClass('glyphicon-eye-open glyphicon-eye-close')
.addClass(status?'glyphicon-eye-open':'glyphicon-eye-close');
});
/**
* [initItem description]初始化List子节点
* @param {[type]} options [description] options.data 字段最终数据结构 ; options.alias 字段别名 ; options.isShow 字段是否显示
* @return {[type]} [description]
*/
function initItem(options){
options = options ||{};
var newItem = itemTemplate.clone();
newItem.removeClass('item-template')
.addClass(options.isShow ? 'show' : 'disabled')
.data('value',options.data)
.data('index',options.index)
.children('.text').text(options.alias);
newItem.children('.is-show')
.data('value',options.isShow)
.removeClass(options.isShow?'':'show');
newItem.find('.is-show>.text').text(options.isShow?'是':'否');
newItem.find('.is-show>.glyphicon')
.removeClass('glyphicon-eye-open glyphicon-eye-close')
.addClass(options.isShow?'glyphicon-eye-open':'glyphicon-eye-close');
return newItem;
}
//根据Id判断子节点是否属于显示状态,即是否在show字段中
function indexofById(item,arr){
for(var i = 0,len = arr.length;i<len;i++){
if(item._id === arr[i][0]){
return i;
}
}
return -1;
}
return list;
}
};
var preprocess = function preprocess(id) {
var objId = $('#'+id).data('obj-id'),
objInfo = tool.getVar(id);
watch = tool.getWatch(id);
$.when(Design.utils.getRelations(objId)).then(function(relation){
objInfo.relations = relation;
tool.keepVar(id,objInfo);
if(relation && relation.length !== 1 && relation.length){
var requests = [];
for(var i = 0,len = relation.length;i<len;i++){
requests.push(Design.utils.getObjProps(relation[i].obj_id));
}
$.when.apply(this,requests).then(function(){
for(var j = 0,j = arguments.length,temp = {},data;j<len;j++){
data = tool.getVar(relation[j].id) || {};
data.properties = arguments[j];
temp[relation[j].id] = data;
}
tool.keepVar(temp);
init.call(this,objInfo);
})
}else init.call(this,objInfo);
});
},
prefinish = function prefinish(id){
var list = $modal.find('.obj_sortable.list-group:not(.hidden)'),
showType = $modal.find('span.show-type').data('value'),
items = list.children('.list-group-item'),
result = [];
$.each(items,function(ix,ele){
result.push($(ele).data('value'))
})
watch.set({
'option.show_type':showType
}).build();
},
product = function product(id) {
return watch.get();
};
that.preprocess = preprocess;
that.product = product;
that.prefinish = prefinish;
return that;
}
configModal = ConfigModal({'modalName': modalId});
Design.modal.register(modalId, configModal);
})(tool);
// 声明一个NodeItem类型
NodeItem = function(spec, inherit){
inherit = inherit || Design.item.root;
var that = inherit(spec),
superApplyEvents = Object.superior.call(that, 'applyEvents'),
superSetConfig = Object.superior.call(that, 'setConfig'),
superGetConfig = Object.superior.call(that, 'getConfig');
var applyEvents = function nodeApplyEvents($elm){
superApplyEvents.apply(that, arguments);
$elm.find('.icon-container > .icon.sign').on('click', function(event){
event.preventDefault();
$(this).parents('.window:first').toggleClass('sign');
});
$elm.find('.icon-container > .icon.star').on('click', function(event){
event.preventDefault();
$elm.toggleClass('star');
});
},
setConfig = function setConfig(id, config){
superSetConfig.apply(that, arguments);
var elm = document.getElementById(id);
var objId = $(elm).data('obj-id');
if ( elm.length == 0 ){
return true;
}
if ( config.first ){
elm.className += ' sign';
}
if ( config.static ){
elm.className += ' static';
}
if ( config.option&&config.option.star ){
elm.className += ' star';
}
//获取数据,并临时保存
$.when(Design.utils.getObjInfo(objId),Design.utils.getObjProps(objId))
.then(function(obj,properties){
if(!(obj && properties))return;
tool.setWatch(config.id,ObjWatch.getInstance())
//构建默认数据
tool.buildData(config,obj,properties);
//保存临时数据
tool.keepVar(config.id,{
properties:properties,
obj:obj,
config:config
}).keepVar(config.dataId,{
properties:properties,
obj:obj,
config:config
});
});
},
getConfig = function getConfig(id){
var _config = superGetConfig.apply(that, arguments),
$elm = $(document.getElementById(id));
var data = tool.getWatch(_config.id).get();//modal data
for(var i in data){
if(Object.prototype.hasOwnProperty.call(data,i)){
_config[i] = data[i]
}
}
_config.data = null;
if ( $elm.hasClass('sign') ) {
_config['first'] = true;
}
_config.option['star'] = $elm.hasClass('star');
return _config
},
getScope = function($elm){
var distance = 80;
//针对left:auto;top:auto;利用jq计算取得
var offset = $elm.offset();
var wh = $elm.css(["width","height"]);
var width = parseInt(wh.width) + distance,
height = parseInt(wh.height) + distance,
left = offset.left - distance / 2,
top = offset.top - distance / 2 ;
return {
"id": safeGuid(),
"type": "page",
"html_layout": {
width:width,
height:height,
offset:{
left:left,
top:top
}
},
"identity": "", // mongo数据库id
"alias": "Page Name",
"name": "PageName", // name里面不能有空格
"url": "",
"category": "",
"description": "",
};
};
that.applyEvents = applyEvents;
that.getConfig = getConfig;
that.setConfig = setConfig;
that.getScope = getScope;
return that;
}
// 注册一个NodeItem类型
nodeItem = NodeItem({'className': 'object', 'modalName': modalId});
Design.item.register('object', nodeItem);
});
|
let wins = 0;
let losses = 0;
let guessesLeft = 9;
let lettersGuessed = [];
let ranLetter = 0;
let letters = "abcdefghijklmnopqrstuvwxyz"
ranLetter = letters[Math.floor(Math.random() * letters.length)];
console.log(ranLetter);
function userGuess() {
ranLetter = letters[Math.floor(Math.random() * letters.length)];
console.log(ranLetter);
reset
};
document.onkeyup = function (event) {
let playersGuess = event.key;
if (playersGuess === ranLetter) {
wins++;
reset ()
} else{
if (lettersGuessed.indexOf(playersGuess) >= 0) {
console.log("guess a different letter!")
} else {
guessesLeft--;
if (guessesLeft === 0) {
losses++;
reset ()
}
lettersGuessed.push(playersGuess);
document.getElementById('playersGuess').innerHTML = lettersGuessed;
console.log(lettersGuessed);
}
}
document.getElementById('wins').innerHTML = wins;
document.getElementById('losses').innerHTML = losses;
document.getElementById('guessesLeft').innerHTML = guessesLeft;
};
function reset(){
lettersGuessed = [];
guessesLeft = 9;
userGuess ();
document.getElementById('playersGuess').innerHTML = lettersGuessed;
}
|
var Invite=function(){
return this;
}
Invite.prototype={
init:function(){
this.pageInit();
this.loadMore();
},
pageInit:function(){
var _this = this;
_this.getRule();
_this.getEventInfo();
GHutils.isLogin(function(){
$("#myInvite").removeClass("gh_none").prev().addClass("gh_none")
_this.getInviteUrl();
_this.getMyInvites(1,false);
$("#copyLink").prev().addClass("gh_none")
},function(){
$("#myInvite").addClass("gh_none").prev().removeClass("gh_none")
$("#copyLink").addClass('gh_none').prev().removeClass("gh_none")
});
_this.getInvivateDate();
},
getRule:function(){
GHutils.load({
url:GHutils.API.ACCOUNT.getActRuleInfo+'?typeId=INVITE',
type:'post',
callback:function(result){
$("#rule").html(result.content)
}
})
},
getEventInfo:function(){
GHutils.load({
url:GHutils.API.ACCOUNT.getEventInfo,
data:{
eventType: "friend",
couponType: "coupon"
},
type:'post',
callback:function(result){
if(result.errorCode == 0){
$("#invitiveMoneyBox").show()
$("#invitiveMoney").html(result.money)
}
}
})
},
getInviteUrl:function () {
var _this = this;
GHutils.load({
url: GHutils.API.CMS.getshareconfig+"?pageCode=invite",
data: {},
type: "post",
callback: function(result) {
if(result.errorCode != 0){
$("#noData").removeClass("gh_none")
return false;
}
$("#copyLink").removeClass('gh_none')
if(!GHutils.userinfo){
GHutils.userinfo = GHutils.getUserInfo();
}
var _href = "";
if(result.shareUrl.indexOf('?') > -1) {
_href = result.shareUrl + '&inviteCode=' + result.sceneid + "&telnum=" + GHutils.userinfo.userAcc
} else {
_href = result.shareUrl + '?inviteCode=' +result.sceneid+ "&telnum=" + GHutils.userinfo.userAcc
}
$('#copyBtn').attr('data-clipboard-text',_href).prev().html(_href)
_this.bindEvent();
}
})
},
// getUserInfo:function(){
// var _this = this;
// // 获取用户信息 生成邀请二维码
// GHutils.load({
// url: GHutils.API.ACCOUNT.userinfo,
// data: {},
// type: "post",
// callback: function(result) {
// if(result.errorCode != 0){
// return false;
// }
// var invitUrl = h5Url+'/share/register.html?inviteCode='+result.sceneid+'&telnum='+result.userAcc;
// $('#copyBtn').attr('data-clipboard-text',invitUrl).prev().html(invitUrl)
// _this.bindEvent();
// }
// })
// },
bindEvent:function(){
var _this = this;
var clipboard = new Clipboard('#copyBtn');
clipboard.on('success', function(e) {
alert("复制成功")
e.clearSelection();
});
clipboard.on('error', function(e) {
alert("您使用的浏览器不支持此复制功能,请使用Ctrl+C或鼠标右键。")
console.error('Action:', e.action);
console.error('Trigger:', e.trigger);
});
},
getMyInvites:function(page,isAppend){
var _this = this;
page = Number(page)
GHutils.load({
url: GHutils.API.ACCOUNT.getmyinvites+'?page='+page+'&rows=10',
data: {},
type: "post",
callback: function (result) {
var _data= []
if(page == 1 && result.errorCode != 0 ){
$("#myInvite").html('<div class="gh_tcenter gh_mt35">暂无数据</div>');
}else if(result.errorCode == 0){
if(page != 1){
$("#myInvite").css('overflow-y',"auto")
}else{
$("#myInvite").css('overflow-y',"hidden")
}
GHutils.mustcache("#invite-template","#myInvite",{"invites":(_this.parseData(result,'myInvite',page))},isAppend);
if(GHutils.Fsub(result.total,GHutils.Fmul(page,10)) > 0){
$("#myInvite").attr('data-page',(page+1)).attr('data-more','yes')
}else{
$("#myInvite").removeAttr("data-page").removeAttr("data-more"); //attr('data-page',(page+1)).attr('data-more',true)
}
}
}
})
},
//邀请排行榜
getInvivateDate:function(){
var _this = this;
GHutils.load({
url:GHutils.API.ACCOUNT.invitecharts,
data:{},
type:'post',
callback:function(result){
if(result.errorCode !=0 ){
$("#topInvite").html('<div class="gh_tcenter gh_mt35">暂无数据</div>');
}else{
GHutils.mustcache("#invite-template","#topInvite",{"invites":(_this.parseData(result.rows,"top",1))});
}
},
errcallback:function(){
}
})
},
parseData:function(data,dataType,page){
var _this = this;
var invites = [];
GHutils.forEach(data,function(idx,item){
item["idx"] = (page - 1) *10 + idx +1;
item.realName = item.realName || "--"
item[dataType]=dataType
item["phone"]=item.phone || item.phoneNum || "--"
invites.push(item);
})
if(invites.length == 0){
invites = null;
}
return invites;
},
loadMore:function(){
var _this = this;
$("#myInvite").unbind("scroll").bind("scroll", function(e){
var sum = this.scrollHeight;
var page = $(this).attr('data-page');
var more = $(this).attr('data-more');
if(more == "yes" && sum <= $(this).scrollTop() + $(this).height()){
_this.getMyInvites(page,true)
}
}).on('mouseover',function(){
var page = $(this).attr('data-page');
var more = $(this).attr('data-more');
if(page == "2" && more == "yes"){
_this.getMyInvites(page,true);
}
}).on('mouseout',function(){
});
}
}
$(function(){
new Invite().init();
})
|
module.exports = function(sequelize, DataTypes) {
return sequelize.define('peer', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
remote_ip: { type: DataTypes.STRING },
local_ip: DataTypes.STRING,
owner_user_id: DataTypes.INTEGER,
});
};
|
/* jshint browser:true */
/* global Phaser, BasicGame */
// create Game function in BasicGame
BasicGame.Game = function (game) {
};
// set Game function prototype
BasicGame.Game.prototype = {
// Called when the game is being initiated, via game.state.add
init: function () {
this.stage.backgroundColor = '#fff'; //white
this.world.alpha = 1;
this.physics.startSystem(Phaser.Physics.P2JS);
this.physics.p2.restitution = 0.2; //this gives bounce
this.physics.p2.gravity.y = 500;
//draw the board
var graphics = this.add.graphics(0, 0);
this.boundaryLine = this.world.height/2;
graphics.beginFill(0xadd8e6,1); // blue
graphics.drawRect(0,0,this.world.width,this.boundaryLine);
graphics.beginFill(0x98fb98,0.5); //green 0.5 opacity
graphics.drawRect(0,this.boundaryLine,this.world.width,this.boundaryLine);
graphics.lineStyle(6, 0x6F4E37, 1);//The line across the screen
graphics.moveTo(0, this.boundaryLine);
graphics.lineTo(this.world.width, this.boundaryLine);
//Set collision groups http://phaser.io/examples/v2/p2-physics/collision-groups
this.physics.p2.setImpactEvents(true);
// Create our collision groups. One for the rocks, one for the bottles
this.rockCollisionGroup = this.physics.p2.createCollisionGroup();
this.bottleCollisionGroup = this.physics.p2.createCollisionGroup();
this.boardCollisionGroup = this.physics.p2.createCollisionGroup();
this.molotovCollisionGroup = this.physics.p2.createCollisionGroup();
this.darkBottleCollisionGroup = this.physics.p2.createCollisionGroup();
this.goldenBottleCollisionGroup= this.physics.p2.createCollisionGroup();
this.physics.p2.updateBoundsCollisionGroup();
},
// Called when the game is being created, via new BasicGame.Game()
create: function () {
this.clouds = this.add.group();
for(var i = 0; i<3; i++){
var cloud = this.clouds.create(this.rnd.integerInRange(-50,this.world.width)
,this.rnd.integerInRange(30,200)
,'cloud');
cloud.angle=this.rnd.integerInRange(-20,20);
var rand = this.rnd.realInRange(0.4, 1);
cloud.scale.setTo(rand,rand);
cloud.alpha = this.rnd.realInRange(0.6, 1);
}
// Add rock to the center of the stage
this.rock = this.add.sprite(this.world.centerX, this.world.centerY, 'rock');
this.rock.anchor.setTo(0.5, 0.5);
this.rock.scale.setTo(0.06,0.06);
// Adds the death rock
this.deathRock= this.add.sprite(0, 0, "deathrock");
this.deathRock.animations.add("toheaven");
this.deathRock.visible= false;
this.deathRock.anchor.setTo(0.5, 0.5);
// turn false the collision circle in production
this.physics.p2.enable(this.rock, false); //change to true to see hitcircle
this.rock.body.setRectangle(25,20);
this.rock.body.collideWorldBounds = true;
this.rock.body.velocity.x = 20;
this.rock.body.velocity.y = 150;
this.rock.body.angularDamping = 0.5;
//new set collision group note: no callbacks on rock.body.collides
this.rock.body.setCollisionGroup(this.rockCollisionGroup);
this.rock.body.collides([this.bottleCollisionGroup,this.boardCollisionGroup, this.goldenBottleCollisionGroup, this.darkBottleCollisionGroup,this.molotovCollisionGroup]);
//green BOTTLE group code code ****************
this.bottles = this.add.group();
for(var i = 0; i<BasicGame.numGreenBottles; i++){
var bottle = this.bottles.create(10,this.rnd.integerInRange(10,100),'bottleSht');
bottle.animations.add('splode');
}
//enable physics on the whole group
this.physics.p2.enable(this.bottles, false);
this.spawnBottles();
// initialize wood boards *******************
this.boards = this.add.group();
this.addToSpecialGroup(this.boards, 3, 'woodBlocker', 0.7, 0.25);
this.physics.p2.enable(this.boards, false);
this.spawnBoards();
//***********************************************
// initialize lives boards *******************
this.lifeGroup = this.add.group();
this.addToSpecialGroup(this.lifeGroup, 3, 'livesSht', 0.3, 0.3);
this.lifeGroup.forEach(function(life){
life.revive();
life.y = this.world.height - 60;
},this);
this.lifeGroup.getAt(1).x = 50;
this.lifeGroup.getAt(2).x = 100;
//***********************************************
// initialize molotovs boards *******************
this.molotovs = this.add.group();
this.addToSpecialGroup(this.molotovs, 3, 'molotovSht', 0.35, 0.35, function(molotov) {
molotov.animations.add('fire');
molotov.animations.play('fire',8,true,false);
});
this.physics.p2.enable(this.molotovs, false);
this.spawnMolotovs();
//***********************************************
// initialize dark bottles
this.darkBottles= this.add.group();
this.addToSpecialGroup(this.darkBottles, 3, 'darkBottleSht', 0.3, 0.3, function(dark) {
dark.animations.add('toxic');
//dark.animations.play('toxic',4,true,false);
});
this.physics.p2.enable(this.darkBottles,false);
this.spawnDarkBottles();
// only ever one golden bottle
this.goldenBottle= this.add.sprite(0, 0, "goldenBottle");
this.physics.p2.enable(this.goldenBottle,false);
this.goldenBottle.body.setRectangle(15, 30);
this.goldenBottle.animations.add("glow");
this.goldenBottle.animations.play("glow", 3, true);
this.goldenBottle.scale.setTo(0.65, 0.65);
this.goldenBottle.kill();
this.spawnGoldenBottle();
this.bottleBreak = this.add.audio('breakBottle');
this.bottleExplode = this.add.audio('explodeBottle');
this.rockHitSnd = this.add.audio('rockHit');
//add start marker to rock hit sound
this.rockHitSnd.addMarker('rockSrt',0.15,0.5);
//this.bottleBreak.addMarker('breakSrt',0,1);
this.rock.body.onBeginContact.add(this.rockHit, this);
//*************
//input (grab functionality)
this.rock.grabbed = false;
this.throwHandle = this.add.sprite(0, 0);
this.physics.p2.enable(this.throwHandle, false);
this.throwHandle.body.static = true;
this.throwConstraint = null;
//event listeners
this.input.onDown.add(this.rockGrab, this);
this.input.onUp.add(this.rockDrop, this);
this.input.addMoveCallback(this.rockMove, this);
this.scoreText= this.add.text(10, this.world.centerY-22, "Score: "+BasicGame.score+"\nLevel: "+BasicGame.level, {
fontFamily: "arial",
fontSize: "16px",
fill: "#101820"
});
this.levelTxt = this.add.text(this.world.centerX, this.world.centerY/2, "Level: "+BasicGame.level, {
fontFamily: "arial",
fontSize: "28px",
fill: "#FDF5E6"
});
this.levelTxt.anchor.set(0.5,0.5);
this.levelTxt.lifespan = 2500;
this.highScoreText= this.add.text(10, this.world.height-75, "High Score: "+BasicGame.highScore, {
fontFamily: "arial",
fontSize: "14px",
fill: "#101820"
});
this.gameoverTxt = this.add.text(this.world.centerX, this.world.centerY+100, "Throw the Rock.", {
fontFamily: "arial",
fontSize: "28px",
fill: "#6F4E37"
});
this.gameoverTxt.anchor.set(0.5,0.5);
this.gameoverTxt.lifespan = 1500;
// Add lives
this.lives= 3;
// game overlay menu ... code at very bottom
this.initGameMenu();
},
// Creates a group for the special items, so we don't repeat ourselves
addToSpecialGroup: function(group, size, textureID, scaleX, scaleY, modifyEvent) {
for(var i = 0; i<size; i++)
{
// Variables
var temp = group.create(0, 0, textureID);
if(modifyEvent)
{
modifyEvent(temp);
}
temp.scale.setTo(scaleX, scaleY);
temp.kill();
}
},
// Updates the game. Remember it should be at 60Hz
update: function(){
this.clouds.children.forEach(function(cloud){
if(cloud.x>this.world.width){
cloud.x = this.rnd.integerInRange(-120,-20);
cloud.y = this.rnd.integerInRange(30,200);
cloud.angle=this.rnd.integerInRange(-20,20);
var rand = this.rnd.realInRange(0.4, 1);
cloud.scale.setTo(rand,rand);
cloud.alpha = this.rnd.realInRange(0.6, 1);
}else{
cloud.x+=0.5;
}
},this);
/*if(!this.rock.alive){
this.bThrasherMode= false;
}*/
if(this.bThrasherMode)
{
if(this.getSpeed(this.rock.body.velocity.x, this.rock.body.velocity.y)> 400)
this.rockTrailing();
else
{
this.rock.tint= 0xffffff;
if(this.trails!== null)
this.deleteRockTrailing();
}
}
// to eliminate remnant smoke trails if not bThrashermode
if(!this.bThrasherMode && this.trails!= null){
if(this.trails.length!= 0)
this.deleteRockTrailing();
else
this.trails= null;
}
// kill golden bottle
if(this.goldenBottle.alive && this.goldenBottle.body.x>this.world.width)
this.goldenBottle.kill();
this.bottles.forEachAlive(this.resetObjLocation,this);
this.boards.forEachAlive(this.resetObjLocation,this);
this.molotovs.forEachAlive(this.resetObjLocation,this);
this.darkBottles.forEachAlive(this.resetObjLocation, this);
//****************************************
},
// Resets the location to the begining of any given Phaser P2 Physics object
resetObjLocation: function(obj) {
if(obj.body.x> this.world.width+25)
obj.body.x= -10;
},
// utility functions for the rock grab *****************
rockGrab: function (pointer) {
//check if rock is alive!!
if(pointer.y > this.boundaryLine && this.rock.alive && this.rock.y > this.boundaryLine){
this.rock.body.angularVelocity = 0;
this.rock.grabbed = true;
//move the blank sprite to the pointer
this.throwHandle.body.x = pointer.x;
this.throwHandle.body.y = pointer.y;
//create a constraint with the rock and the blank sprite
this.throwConstraint = this.physics.p2.createLockConstraint(this.rock, this.throwHandle );
}
},
rockMove: function(pointer, x, y, isDown) {
if(this.rock.grabbed){
this.throwHandle.body.x = x;
this.throwHandle.body.y = y;
//ROCK DROP at BOUNDARY -- can remove this for testing
if(this.rock.body.y<this.boundaryLine){
this.rockDrop();
}
}
},
rockDrop: function(){
if(this.rock.grabbed){
this.physics.p2.removeConstraint(this.throwConstraint);
this.throwConstraint = null;
this.rock.grabbed = false;
}
},
// Creates the rock's trailing effect
rockTrailing: function() {
var temp;
if(this.trails== null)
this.trails= this.add.group();
if(this.trails.length> 10)
this.trails.removeChildAt(0);
temp= this.add.sprite(this.rock.x, this.rock.y, "firepuff");
temp.anchor.setTo(0.5, 0.5);
temp.scale.setTo(this.rock.scale.x*4, this.rock.scale.y*4);
temp= temp.sendToBack();
temp.animations.add('light').play('light');
this.rock.bringToTop();
this.rock.tint= 0xac2010;
this.trails.add(temp);
},
// Slowly deletes the rock's trailing effect one by one, to not overload with objects and to not completely destroy the trail
deleteRockTrailing: function() {
if(this.trails!= null && this.trails.length> 0)
this.trails.removeChildAt(0);
},
// Called when the rock has hit an object of the respective collision group
rockHit: function(){
if(!this.rock.grabbed){
if(BasicGame.sound){
this.rockHitSnd.play('rockSrt',0,this.rnd.realInRange(0.3,1));//last arg is randome volume
}
}
},
//*************************************
// Rock2 Bottle utility methods
// Called when the green bottle has been hit
bottleHit2: function(bottle,rock){
try {
// bottle needs to be going fast enough and not playing its animation
if(this.getSpeed(rock.velocity.x, rock.velocity.y) > BasicGame.breakSpeedGreenBottle && !bottle.sprite.animations.currentAnim.isPlaying){
if(BasicGame.sound){
this.bottleBreak.play();
}
bottle.sprite.animations.play('splode',30,false,true);
this.spawnShards(bottle.sprite);
bottle.sprite.events.onKilled.addOnce(function(arg){
this.spawnGoldenBottle();
if(this.combo== null)
this.combo= 0;
this.combo++;
this.increaseScore((10+12*(BasicGame.level-1))*this.combo,arg.x,arg.y);
if(this.comboText!= null)
{
if(this.combo> 1){
this.comboText.setText("Combo! x"+this.combo);
this.comboText.x = this.rock.x;
this.comboText.y = this.rock.y;
}
}
else
this.comboText= this.add.text(this.rock.x, this.rock.y,
((this.combo> 1) ? "Combo! x"+this.combo : ""),
{
fontFamily: "arial",
fontSize: "14px",
fill: "#fff"
}
);
if(this.comboTimer!= null)
this.time.events.remove(this.comboTimer);
this.comboTimer= this.time.events.add(Phaser.Timer.SECOND, function(){
this.combo= 0;
this.comboText.setText("");
}, this);
if(this.bottles.countDead()===BasicGame.numGreenBottles){
BasicGame.level+=1;
this.announceLevel();
this.spawnBottles();
this.spawnBoards();
this.spawnMolotovs();
this.spawnGoldenBottle();
};
},this);
}
}catch(e){}
},
// Spawns the green bottles
spawnBottles: function(){
this.bottles.forEach(function (bottle) {
bottle.animations.stop('splode',true);
bottle.body.x = -1*this.rnd.integerInRange(10,90);
// NEED a better level up AI
if(BasicGame.level<14)
bottle.body.velocity.x = this.rnd.integerInRange(50,170)*BasicGame.level/2.0; // whoa...
else
bottle.body.velocity.x = this.rnd.integerInRange(50,170)*13/2.0;
bottle.body.angularVelocity = this.rnd.integerInRange(-5,5);
if(bottle.body.angularVelocity== 0)
bottle.body.angularVelocity= 4;
var scaleFactor = this.rnd.realInRange(0.3,0.6);
bottle.scale.setTo(scaleFactor,scaleFactor);
bottle.body.setRectangle(scaleFactor*20,scaleFactor*100);
bottle.body.static = true;
bottle.body.setCollisionGroup(this.bottleCollisionGroup);
bottle.body.collides(this.rockCollisionGroup,this.bottleHit2,this);
bottle.revive();
},this);
},
// Generalized version to spawn in the specialized items
spawnSpecialsGroup: function(group, collisionGroup, rockHitEvent, modifyEvent) {
// Variables
var num= 0;
if(BasicGame.level< 5) num= 1;
else if(BasicGame.level>= 5 && BasicGame.level< 10) num= 2;
else num= 3;
for(var i= 0; i< num-group.countLiving(); i++)
{
// Variables
var item= group.getFirstDead();
if(item)
{
item.body.x= -10;
item.body.y= this.world.centerY-this.rnd.integerInRange(10, 100);
item.body.velocity.x= this.rnd.integerInRange(50, 200);
item.body.velocity.y= 0;
item.body.angularVelocity= this.rnd.integerInRange(-5, 5);
if(item.body.angularVelocity== 0)
item.body.angularVelocity= 4;
item.body.setCollisionGroup(collisionGroup);
item.body.collides(this.rockCollisionGroup, rockHitEvent, this);
item.body.static= true;
if(modifyEvent)
{
this.deletemelaterfunc= modifyEvent;
this.deletemelaterfunc(item);
this.deletemelaterfunc= null;
}
item.revive();
}
}
},
// Spawns in the boards
spawnBoards: function(){
this.spawnSpecialsGroup(this.boards, this.boardCollisionGroup, this.boardHit, function(board){
board.frame= 0;
});
},
// Called when the board has been hit by the rock
boardHit: function(arg){
var board = arg.sprite;
if(this.bThrasherMode) board.frame=4;
if(board.frame===4){
board.lifespan = 1000;
board.body.velocity.y=75;
board.body.angularVelocity = this.rnd.integerInRange(20,45);
this.increaseScore(25,board.x,board.y);
}else{
board.frame+=1;
}
},
// Spawns in the molotovs
spawnMolotovs: function(){
this.spawnSpecialsGroup(this.molotovs, this.molotovCollisionGroup, this.molotovHit, function(molotov) {
molotov.body.setRectangle(20, 60);
molotov.body.setCollisionGroup(this.molotovCollisionGroup);
});
},
// Called when the molotov has been hit by the rock
molotovHit: function(arg){
var molotov = arg.sprite;
if(this.getSpeed(this.rock.body.velocity.x, this.rock.body.velocity.y) > BasicGame.breakSpeedMolotov && molotov.alive){
molotov.kill();
if(BasicGame.sound){
this.bottleBreak.play();
this.bottleExplode.play();
};
var temp= this.add.sprite(molotov.x, molotov.y, "firepuff");
temp.anchor.setTo(0.5, 0.5);
temp.animations.add('explode').play('explode',30,true);
if(!this.bThrasherMode) // Only take damage if thrasher mode is off
this.damageLife();
else // get points for molotov kill if thrasher mode is on
this.increaseScore(Math.round(25*BasicGame.level/2),molotov.x,molotov.y);
}
},
// Called when the green bottle gets destroyed, spawns in the shards off it for effect
spawnShards: function(sprite){
var shards = this.add.group();
shards.create(sprite.body.x,sprite.body.y,'shard01');
shards.create(sprite.body.x,sprite.body.y,'shard02');
shards.create(sprite.body.x,sprite.body.y,'shard03');
shards.create(sprite.body.x,sprite.body.y,'shard04');
this.physics.p2.enable(shards, false);
//MEMORY LEAK CHECK: destry these shards and group?
shards.forEach(function (shard) {
shard.scale.setTo(0.5,0.5);
shard.body.velocity.x = this.rnd.integerInRange(20,100);
shard.body.angularVelocity = this.rnd.integerInRange(1,30);;
shard.lifespan = 1000; //kill at end of time I think?
// destroy shard but the group survives (or is it a local var?)
shard.events.onKilled.addOnce(function(arg){arg.destroy()},this);
},this);
},
// Spawns in the dark bottles
spawnDarkBottles: function(){
this.spawnSpecialsGroup(this.darkBottles, this.darkBottleCollisionGroup, this.darkBottleHit,function(darkbottle){
darkbottle.frame= 0;
darkbottle.body.setRectangle(15, 50);
darkbottle.body.setCollisionGroup(this.darkBottleCollisionGroup);
});
},
// Called when the dark bottle has been hit by the rock
darkBottleHit: function(args){
// Variables
var dbottle= args.sprite;
if(this.getSpeed(this.rock.body.velocity.x, this.rock.body.velocity.y) > BasicGame.breakSpeedDarkBottle){
// this.rock gets BIG for 3 seconds or so
if(BasicGame.sound){this.bottleBreak.play()};
dbottle.animations.play('toxic',15,false,true); // last true gives a kill
this.rock.scale.setTo(0.2,0.2);
this.rock.body.setRectangle(100, 85);
this.rock.body.setCollisionGroup(this.rockCollisionGroup);
this.rock.body.collides([this.bottleCollisionGroup,this.boardCollisionGroup, this.goldenBottleCollisionGroup, this.darkBottleCollisionGroup,this.molotovCollisionGroup]);
this.rock.body.collideWorldBounds = true;
//this.rock.body.setRectangle(40,40);
this.time.events.add(Phaser.Timer.SECOND *3, function(){
//back to normal
this.rock.scale.setTo(0.06,0.06);
this.rock.body.setRectangle(25, 20);
this.rock.body.setCollisionGroup(this.rockCollisionGroup);
this.rock.body.collides([this.bottleCollisionGroup,this.boardCollisionGroup, this.goldenBottleCollisionGroup, this.darkBottleCollisionGroup,this.molotovCollisionGroup]);
this.rock.body.collideWorldBounds = true;
// scale the hit rectangle back
//this.rock.body.setRectangle(25,20);
this.spawnDarkBottles();
}, this);
}
},
// Spawns in the golden bottle
spawnGoldenBottle: function() {
if(this.goldenBottle.alive || this.bThrasherMode)
return;
if(this.rnd.integerInRange(0, 4)=== 0) // 20% Chance of spawning
{
this.goldenBottle.body.x= -10;
this.goldenBottle.body.y= this.world.centerY-this.rnd.integerInRange(10, 100);
this.goldenBottle.body.velocity.x= this.rnd.integerInRange(50, 200);
this.goldenBottle.body.velocity.y= 0;
this.goldenBottle.body.angularVelocity= this.rnd.integerInRange(-5, 5);
if(this.goldenBottle.body.angularVelocity== 0)
this.goldenBottle.body.angularVelocity= 4;
this.goldenBottle.body.setCollisionGroup(this.goldenBottleCollisionGroup);
this.goldenBottle.body.collides(this.rockCollisionGroup, this.goldenBottleHit, this);
this.goldenBottle.body.static= true;
this.goldenBottle.revive();
}
},
// Called when the golden bottle has been hit by the rock
goldenBottleHit: function(args) {
if(this.getSpeed(this.rock.body.velocity.x, this.rock.body.velocity.y) > BasicGame.breakSpeedDarkBottle && this.rock.alive){
if(BasicGame.sound){this.bottleBreak.play()};
this.goldenBottle.kill();
this.bThrasherMode= true;
//change color of stage to indicate thrasher mode.
this.stage.backgroundColor = '#ff0000';
//annouce thrasher mode
this.levelTxt.setText("Thrasher mode!\nNo death 8 sec.");
this.levelTxt.revive();
this.levelTxt.lifespan = 2000;
var tmText = this.add.text(this.rock.x, this.rock.y, "Thrasher\nMode!", {
fontFamily: "arial",
fontSize: "14px",
fill: "#A00000",
align: "center"
});
this.game.add.tween(tmText).to(
{
x:this.world.centerX,
y:this.world.height*0.75,
alpha: 0
}, 7000, Phaser.Easing.Linear.In).start().onComplete.add(function(){
tmText.destroy();
}, this);
this.time.events.add(Phaser.Timer.SECOND *8, function(){
this.bThrasherMode= false;
this.rock.tint= 0xffffff;
this.stage.backgroundColor = '#ffffff';
this.spawnGoldenBottle();
}, this);
}
},
// Increases the score by the given amount, and shows the score on the given x and y coordinates
increaseScore: function(amount,positionX,positionY)
{
BasicGame.score+= amount;
this.scoreText.setText("Score: "+BasicGame.score+"\nLevel: "+BasicGame.level);
var stylePoints = { font: "bold 14px Arial ", fill: "#fff", align: "center" };
var pointsTxt = this.add.text(positionX, positionY, "+"+amount, stylePoints);
this.game.add.tween(pointsTxt).to({
y: this.world.centerY/2,
alpha: 0
}, 1800, Phaser.Easing.Linear.In).start().onComplete.add(function(){
pointsTxt.destroy();
}, this);
},
// Announces which level the player is on
announceLevel: function(){
this.levelTxt.setText("Level: "+BasicGame.level);
this.levelTxt.revive();
this.levelTxt.lifespan = 2000;
// update the score
this.scoreText.setText("Score: "+BasicGame.score+"\nLevel: "+BasicGame.level);
},
// Gets the speed of the velocity of whatever object, *vector notation
getSpeed: function(x, y){ return Math.sqrt(x*x+y*y);},
// Called when the player dies, but still has more lives
dieYouDie: function(){
this.levelTxt.setText("You died!\n"+this.lives+" "+((this.lives> 1) ? "lives" : "life")+" left.");
this.levelTxt.revive();
this.levelTxt.lifespan = 2000;
this.lifeGroup.getAt(2-this.lives).frame = 1;
},
// Called when the player dies and does not have any more lives
dieGameOver: function() {
this.gameoverTxt.setText("Game Over!");
this.gameoverTxt.revive();
if(BasicGame.score>=BasicGame.highScore){
BasicGame.highScore = BasicGame.score;
this.levelTxt.setText("Game Over.\nHigh Score!");
this.game.add.tween(this.scoreText).to({
y: this.highScoreText.y,
alpha: 0
}, 1800, Phaser.Easing.Linear.In).start().onComplete.add(function(){
this.highScoreText.setText("High Score: "+BasicGame.highScore);
}, this);
//HTML5 localStorage
if(typeof(Storage) !== "undefined") {
localStorage.setItem("highScore", BasicGame.highScore);
//console.log(localStorage.getItem("highScore"));
} else {
// Sorry! No Web Storage support..
}
}else{
this.levelTxt.setText("Game Over!");
}
if(BasicGame.level>=BasicGame.highLevel){
BasicGame.highLevel=BasicGame.level;
//HTML5 localStorage
if(typeof(Storage) !== "undefined") {
localStorage.setItem("highLevel", BasicGame.highLevel);
//console.log(localStorage.getItem("highScore"));
} else {
// Sorry! No Web Storage support..
}
//should probably say something.
}
this.levelTxt.revive();
this.levelTxt.lifespan= 2000;
this.lifeGroup.getAt(2).frame = 1;
// Stop game here dispatch the game overlay menu
this.levelTxt.events.onKilled.addOnce(function(){
this.toggleMenu();
},this);
},
// Deals damage to the player, this is for the death rock animation
damageLife: function() {
this.lives--;
this.rock.visible= false;
this.rockDrop();
this.rock.kill();
this.deathRock.visible= true;
this.deathRock.x= this.rock.x;
this.deathRock.y= this.rock.y;
this.deathRock.alpha= 1;
this.deathRock.animations.play("toheaven", 4, true);
if(this.rock.scale.x== 0.2)
this.deathRock.scale.setTo(2, 2);
else
this.deathRock.scale.setTo(1, 1);
this.game.add.tween(this.deathRock).to(
{
x: this.rock.x,
y: this.rock.y-40,
alpha: 0
}, 1800, Phaser.Easing.Linear.In
).start().onComplete.add(function(){
this.deathRock.animations.stop("toheaven");
this.deathRock.visible= false;
this.rock.body.x= this.world.centerX;
this.rock.body.y= this.world.centerY;
this.rock.body.velocity.x= 0;
this.rock.body.velocity.y= 10;
this.rock.body.angularVelocity= 0;
if(this.lives>0){
this.rock.visible= true;
this.rock.revive();
}
}, this);
if(this.lives> 0)
this.dieYouDie();
else
this.dieGameOver();
},
// Initiates the in-game menu
initGameMenu: function(){ // Game Menu Overlay **************************************
this.menuGroup = this.add.group();
this.menuGroup.add(this.add.image(this.world.centerX-100, -250, 'rope'));
this.menuGroup.add(this.add.image(this.world.centerX+87, -250, 'rope'));
this.menuButton = this.add.button(this.world.width -5, this.world.centerY , "menubutton", this.toggleMenu,this);
this.menuButton.anchor.set(1,1);
this.menuButton.scale.setTo(0.5,0.5);
var mm = this.add.button(this.world.width / 2, -30, "mainmenu", function () {
this.state.start('MainMenu');
},this);
mm.anchor.set(0.5);
this.menuGroup.add(mm);
var pa = this.add.button(this.world.width / 2, -80, "playagain", function () {
this.lives = 3;
BasicGame.score=0;
BasicGame.level=1;
this.game.state.start('Game');
}, this);
pa.anchor.set(0.5);
this.menuGroup.add(pa);
var mo = this.add.button(this.world.centerX-50, -140, 'musicToggle',function(btn){
if(BasicGame.music){
BasicGame.backgroundMusic.stop();
btn.frame=1;
BasicGame.music = false;
}else{
BasicGame.backgroundMusic.play();
btn.frame=0;
BasicGame.music = true;
}
}, this);
BasicGame.music?mo.frame=0:mo.frame=1; // init. button
var so = this.add.button(this.world.centerX +50, -140, 'soundfxToggle',function(btn){
if(BasicGame.sound){
btn.frame=1;
BasicGame.sound = false;
}else{
btn.frame=0;
BasicGame.sound = true;
}
}, this);
BasicGame.sound?so.frame=0:so.frame=1; // init. button
mo.anchor.set(0.5);
mo.scale.setTo(0.5,0.5);
so.anchor.set(0.5);
so.scale.setTo(0.5,0.5);
this.menuGroup.add(mo);
this.menuGroup.add(so);
var st = this.add.text(this.world.centerX, 14, "iThrowRock", {
fontFamily: "arial",
fontSize: "14px",
fontStyle: "italic",
fill: "#fff"
});
st.anchor.set(0.5);
this.menuGroup.add(st);
},
// Toggles open the in-game menu
toggleMenu: function () {
if(this.menuGroup.y === 0){
this.menuButton.frame = 1;
this.add.tween(this.menuGroup).to({
y: 210
}, 500, Phaser.Easing.Bounce.Out, true);
}else{
this.menuButton.frame = 0;
this.add.tween(this.menuGroup).to({
y: 0
}, 500, Phaser.Easing.Bounce.Out, true);
}
},
};
|
var searchData=
[
['garde',['GARDE',['../Labyrinthe_8h.html#a8f83164c16577696f81094ea3e6f9377',1,'Labyrinthe.h']]],
['gardien',['Gardien',['../classGardien.html',1,'Gardien'],['../classGardien.html#afc1e450fa7ad919d801475b34ced6e8d',1,'Gardien::Gardien()']]],
['gardien_2ecc',['Gardien.cc',['../Gardien_8cc.html',1,'']]],
['gardien_2eh',['Gardien.h',['../Gardien_8h.html',1,'']]],
['get',['get',['../old__gardien_8cc.html#aa5c560f7afd17ce3beb8a16243c3dd50',1,'old_gardien.cc']]],
['get_5fpotentiel_5fdefense',['get_potentiel_defense',['../classGardien.html#acb0376cc8fd56e65812e23bf32eaa31c',1,'Gardien']]],
['get_5fshortest_5fpath',['get_shortest_path',['../old__gardien_8cc.html#ae81f08560bddf0eb415da84705946738',1,'old_gardien.cc']]],
['get_5fx',['get_x',['../classFireBall.html#a4c71d3cf7209ef9e03ea38ea90c0d508',1,'FireBall']]],
['get_5fy',['get_y',['../classFireBall.html#a1b262f0d003fa19f87ce1d944fae56ab',1,'FireBall']]]
];
|
'use strict';
// Routes client requests to handlers
module.exports = function(server, handlers) {
// For the server status
server.get('/status', handlers.status.get);
// Test REST
server.get('/test', handlers.test.index.get);
server.post('/test', handlers.test.index.post);
server.get('/test/:id', handlers.test.testid.index.get);
server.put('/test/:id', handlers.test.testid.index.put);
server.del('/test/:id', handlers.test.testid.index.del);
};
|
window.onload = function() {
let txtArrayNumerico = document.getElementById("txtArrayNumerico")
let txtValorNumerico = document.getElementById("txtValorNumerico")
let txtFinal = document.getElementById("txtFinal")
let btnMedia = document.getElementById("btnMedia")
btnMedia.addEventListener("click", function(){
let numeros = txtArrayNumerico.value.split(",")
let soma =0, cont = 0
for (let i = 0; i < numeros.length; i++) {
if (parseInt(numeros[i]) > parseInt(txtValorNumerico.value)) {
soma += parseInt(numeros[i])
cont ++
}
}
let media = soma / cont
//txtFinal.innerHTML = media
txtFinal.setAttribute("value",media)
})
}
|
import {StyleSheet} from 'react-native';
const styles = StyleSheet.create ({
headerContainer: {
padding: 25,
backgroundColor: '#5784BA',
borderBottomStartRadius: 20,
borderBottomEndRadius: 20,
paddingBottom: 35
},
contentHeader: {
display: 'flex',
flexDirection:'column',
marginLeft: 30,
},
headerText: {
fontFamily: 'Kanit-Medium',
color: '#F9F9F9',
fontSize: 31,
width: 150,
height: 47,
marginBottom: 20
},
nameText: {
fontFamily: 'Kanit-Medium',
color: '#F9F9F9',
fontSize: 24
},
status: {
fontFamily: 'Kanit-Light',
color: '#F9F9F9',
fontSize: 16
},
accountContainer: {
padding: 30
},
listTitle: {
fontFamily: 'Kanit-Medium',
fontSize: 16
},
logoutTitle: {
fontFamily: 'Montserrat-Bold',
fontSize: 16,
color: '#FF1313',
marginLeft: 5
}
})
export default styles
|
function runTest()
{
FBTest.setPref("filterSystemURLs", true);
FBTest.progress("The filterSystemURLs Option is true for this test");
FBTest.openNewTab(basePath + "script/3309/issue3309.html", function(win)
{
FBTest.enableScriptPanel(function(win)
{
var panelNode = FBTest.selectPanel("script").panelNode;
// Check the content
var header = panelNode.querySelector(".disabledPanelHead");
if (FBTest.ok(header, "The header must be there"))
{
var text = FW.FBL.$STR("script.warning.no_javascript");
FBTest.compare(text, header.textContent,
"The page must display expected text: " + text);
}
FBTest.reload(function(win)
{
var panelNode = FBTest.selectPanel("script").panelNode;
var header = panelNode.querySelector(".disabledPanelHead");
if (FBTest.ok(header, "The header must be there"))
{
var text = FW.FBL.$STR("script.warning.no_javascript");
FBTest.compare(text, header.textContent,
"The page must display expected text: " + text);
}
FBTest.testDone();
});
});
});
}
|
var count = 0;
document.getElementById('result').innerHTML = '已投人数:' + count;
var inp = document.getElementsByTagName('input');
var data = []
data[0] = {
name: '1号',
num: 0
}
data[1] = {
name: '2号',
num: 0
}
data[2] = {
name: '3号',
num: 0
}
data[3] = {
name: '4号',
num: 0
}
var ul = document.getElementById('ph_ol')
//排序
function px(data) {
for (var index = 0; index < data.length - 1; index++) {
for (var j = index; j < data.length; j++) {
if (data[index].num < data[j].num) {
var t = data[index];
data[index] = data[j];
data[j] = t;
}
}
}
return data;
}
function close_tp(params) {
document.getElementById('result').innerHTML = '投票以结束';
}
function add(n) {
count += 1;
document.getElementById('result').innerHTML = '已投人数:' + count;
for (var key in data) {
if ((n + '号') == data[key].name) {
data[key].num += 1;
}
}
//删除ul下的所有子节点
// for (var i = childs.length - 1; i >= 0; i--) {
// ul.removeChild(childs.item(i));
// }
ul.innerHTML ='';
px(data);
//动态添加ul下子节点
for (var key in data) {
var li = document.createElement("li");
li.innerHTML = "第"+(parseInt(key)+1)+"名:" + data[key].name + '票数:' + data[key].num;
ul.appendChild(li);
}
if(count==10){
document.getElementById('result').innerHTML = '投票以结束';
for(var i =0; i<inp.length; i++){
inp[i].style.display ='none';
}
for (let index = 0; index < data.length; index++) {
if(index>0){
if(data[index].num==data[0].num){
document.getElementById('err').innerHTML ='票数相同,情重投';
return;
}
}
}
document.getElementById('err').innerHTML='第一名'+data[0].name;
return;
}
}
|
import fetch from 'isomorphic-fetch';
import h from 'mgmt/utils/helpers';
import * as types from './constants';
function makeTaskRequest(){
return {
type: types.REQUEST_TASKS,
};
}
export function hydrateTasks(){
return (dispatch, getState) => {
let state = getState(),
{ list, rob_tasks } = state.config.tasks;
dispatch({
type: types.HYDRATE_TASKS,
list,
robTasks: rob_tasks,
});
};
}
function receiveTasks(tasks){
return {
type: types.RECEIVE_TASKS,
tasks,
};
}
export function fetchTasks(){
return (dispatch, getState) => {
let state = getState();
if (state.tasks.isFetching) return;
dispatch(makeTaskRequest());
let { host, tasks } = state.config;
const url = h.getListUrl(host, tasks.url);
return fetch(url, h.fetchGet)
.then((response) => response.json())
.then((json) => dispatch(receiveTasks(json)));
};
}
|
NOW_DISPLAY_RECORD = "當前顯示記錄";
TOTAL = "共計";
NOTHING_DISPLAY = "沒有記錄可以顯示";
SELECT = "請選擇";
EPAPER = "活動頁面";
NEWS = "最新消息";
ANNOUNCE = "訊息公告";
EDM = "電子報";
MAPID = "編號";
SITE = "站台名稱";
PAGE = "網頁名稱";
AREA = "區域名稱";
TYPE = "元素類型";
INFONAME = "元素名稱";
SORT = "排序";
CREATEDATE = "創建時間"
UPDATEDATE = "更改時間";
UPDATEUSER = "更改人";
ISCLOSE = "是否關閉";
WINTITLE = "元素關係設定新增/修改";
INSERTIMAGE = "插入圖片";
ID = "編號";
TITLE = "標題";
ANNOUNCETYPE = "類型";
SELECT = "請選擇";
SORT = "排序";
ANNOUNCECONTENT = "訊息公告內容";
STATUS = "狀態";
SHOW = "顯示";
HIDE = "隱藏";
SAVE = "保存";
ANNOUNCETIP = "請輸入訊息公告內容";
ISCLOSE = "是否關閉";
CREATOR = "上稿者";
KEY = "關鍵字";
SEARCH = "查詢";
RESET = "重置";
EDMEMAILTIP = "郵件內容不能為空!";
|
const sieve = require('./index').sieve;
const semiPrimes = require('./index').semiPrimes;
test('finds list of primes LTEQ n', () => {
expect(sieve(23)).toEqual([2,3,5,7,11,13,17,19,23]);
});
test('finds list of primes LTEQ n', () => {
expect(sieve(2)).toEqual([2]);
});
test('finds list of primes LTEQ n', () => {
expect(sieve(1)).toEqual([]);
});
test('it counts semiprimes', () => {
const n = 26;
const p = [1,4,16];
const q = [26,10,20];
expect(semiPrimes(n, p, q)).toEqual([10,4,0]);
})
|
var messagesLib = require('../../lib/messages');
describe('messages library', function() {
var session, message;
var messageActions = {
error: 'appendError',
info: 'appendInfo',
success: 'appendSuccess'
};
beforeEach(function() {
// Reset the messages object before each test.
session = {
messages: {}
};
});
it('should append an error message to the messages object', function() {
message = 'Error Message';
session.messages.should.be.empty;
// Assert that a new message both populates the message object, and adds
// a value to the list.
messagesLib.appendError(session, message);
session.messages.error.should.be.an.Array.and.containEql(message);
});
it('should append an info message to the messages object', function() {
message = 'Info Message';
session.messages.should.be.empty;
// Assert that a new message both populates the message object, and adds
// a value to the list.
messagesLib.appendInfo(session, message);
session.messages.info.should.be.an.Array.and.containEql(message);
});
it('should append a success message to the messages object', function() {
message = 'Success Message';
session.messages.should.be.empty;
// Assert that a new message both populates the message object, and adds
// a value to the list.
messagesLib.appendSuccess(session, message);
session.messages.success.should.be.an.Array.and.containEql(message);
});
it('should not add a message when a session is not provided', function() {
session = undefined;
message = 'Error Message';
// Assert that session object is still undefined for each of the message
// types. Messages cannot be appended to an undefined object.
for (var action in messageActions) {
var method = messageActions[action];
messagesLib[method](session, message);
(session === undefined).should.be.true;
}
});
it('should provide a default message based on type when a message is missing',
function() {
message = null;
// Assert that a default message is provided for each action when a
// message is missing.
for (var action in messageActions) {
var method = messageActions[action];
var defaultMessage = messagesLib.defaultMessages[action];
messagesLib[method](session, message);
session.messages[action].should.be.an.Array.
and.containEql(defaultMessage);
}
});
});
|
var currency = require('./currency.js');
console.log('50 C$ to USD');
console.log(currency.canadianToUS(50));
console.log('30 USD to C$');
console.log(currency.USToCanadian(30));
|
'use strict'
import GlobalStoreService from '@/utils/auth'
/**
* 通用工具类
* @attr <Object> CommonUtil, used like `import CommonUtil from '@/utils/commonUtil'`
* Create by longwang, 2018.07.05
*/
const CommonUtil = {
/**
* 筛选树的叶子节点
* @attr <Array> isLeafs 叶子节点id列表
* @attr <Function> filter 递归tree
* @param <Array> leafList 节点id列表
* @param <Array> treeData 树形结构
* @param <String> leafIdName 叶子id字段名称
* @param <String> treeIdName 树id字段名称
* @param <String> treeChildName 数child字段名称
* @attr <Function> getLeafs 获取结果
*/
dynamicTreeLeafsFilter: {
isLeafs: [],
filter: (leafList, treeData, leafIdName, treeIdName, treeChildName) => {
if (!!leafList && leafList.length > 0 && !!treeData && treeData.length > 0) {
treeData.map(treeVO => {
if (!!treeVO[treeChildName] && treeVO[treeChildName].length > 0) {
CommonUtil.dynamicTreeLeafsFilter.filter(leafList, treeVO[treeChildName], leafIdName, treeIdName, treeChildName)
} else {
leafList.map(leaf => {
if (leaf[leafIdName] === treeVO[treeIdName]) {
CommonUtil.dynamicTreeLeafsFilter.isLeafs.push(leaf[leafIdName])
}
})
}
})
}
},
getLeafs: (leafList, treeData, leafIdName, treeIdName, treeChildName) => {
CommonUtil.dynamicTreeLeafsFilter.isLeafs = []
CommonUtil.dynamicTreeLeafsFilter.filter(leafList, treeData, leafIdName, treeIdName, treeChildName)
return CommonUtil.dynamicTreeLeafsFilter.isLeafs
}
},
IEVersion: () => {
const userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
const isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 // 判断是否IE<11浏览器
const isEdge = userAgent.indexOf('Edge') > -1 && !isIE // 判断是否IE的Edge浏览器
const isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1
if (isIE) {
const reIE = new RegExp('MSIE (\\d+\\.\\d+);')
reIE.test(userAgent)
const fIEVersion = parseFloat(RegExp['$1'])
if (fIEVersion === 7) {
return 7
} else if (fIEVersion === 8) {
return 8
} else if (fIEVersion === 9) {
return 9
} else if (fIEVersion === 10) {
return 10
} else {
return 6 // IE版本<=7
}
} else if (isEdge) {
return 'edge' // edge
} else if (isIE11) {
return 11 // IE11
} else {
return -1 // 不是ie浏览器
}
},
placeholderSupport: () => {
return {
ifSpt: ('placeholder' in document.createElement('input')),
click: (e) => {
const prefix = e.target
const parentNode = prefix.parentNode.parentNode // span > .el-input__prefix > .el-input el-input--prefix
const childNodes = parentNode.childNodes
if (childNodes && childNodes.length > 0) {
let i = 0
let input
let child
for (; i < childNodes.length; i++) {
child = childNodes[i]
if (child.nodeName.toUpperCase() === 'INPUT') {
input = child
break
}
}
if (input) {
input.focus()
}
}
}
}
},
/**
* 将tArray合到oriArray,返回超集
* oriArray - 全数据列表
* oriAttrName - 外键属性名
* tArray - 自定义列表
* tAttrName - 外键属性名
*/
concatArrayByParams: (oriArray, oriAttrName, tArray, tAttrName) => {
let fullArray = JSON.parse(JSON.stringify(oriArray))
if (oriArray instanceof Array && oriArray.length > 0 &&
typeof oriAttrName === 'string' && oriAttrName.length > 0 &&
tArray instanceof Array && tArray.length > 0 &&
typeof tAttrName === 'string' && tAttrName.length > 0) {
const _list = JSON.parse(JSON.stringify(oriArray))
let _tArray = []
fullArray = _list.map(obj => {
_tArray = tArray.filter(items => {
return (obj[oriAttrName] + '') === (items[tAttrName] + '')
})
if (_tArray instanceof Array && _tArray.length > 0) {
return Object.assign({}, obj, _tArray[0])
} else {
return obj
}
})
}
// console.log('[CommonUtil concatArrayByParams] oriArray ', oriArray)
// console.log('[CommonUtil concatArrayByParams] tArray ', tArray)
// console.log('[CommonUtil concatArrayByParams] oriArray + tArray = fullArray ', fullArray)
return fullArray
},
getRqHeader: () => {
const currentUser = GlobalStoreService.get('currentUser')
const _obj = {
// 'Content-Type': 'multipart/form-data', // no need to set, see `https://blog.csdn.net/sanjay_f/article/details/47407063`
'bsType': navigator.userAgent,
'bsVersion': navigator.appVersion,
'jsToken': !!currentUser && !!currentUser.jsToken ? currentUser.jsToken : '',
'jsCurAccNo': !!currentUser && !!currentUser.accountNo ? currentUser.accountNo : ''
}
return _obj
},
fwLogout: () => { // 主框架注销登录,跳转登录页
const winParent = window.parent
const _msg = {
source: 'baseProject',
command: 'JPC.cmd.logout'
}
const _origin = '*'
winParent.postMessage(_msg, _origin)
}
}
export default CommonUtil
/**
* picker-options.disabledDate function for date picker
* @param {*} time
* @param {*} plusOrMinus
* @param {*} targetTime
*/
export function commonDisabledDate(time, plusOrMinus, targetTime) {
const _targetTime = targetTime
if (typeof _targetTime === 'string' && _targetTime.length > 0) {
if (plusOrMinus === 'plus') {
return time.getTime() > new Date(_targetTime).getTime()
} else if (plusOrMinus === 'minus') {
return time.getTime() < new Date(_targetTime).getTime()
} else {
return false // 不禁用
}
} else {
return false // 不禁用
}
}
|
const csv=require('csvtojson');
const fs = require('fs')
const csvFile2 = './customer_data_two.csv';
const csvFile1 = '/home/sriram/Sowmya-Project/dave.io/customer_data_one.csv';
var data1, data2;
csv().fromFile(csvFile1).then((jsonObj) => {
fs.writeFile('one.json', JSON.stringify(jsonObj), function(err, result) {
if(err) { console.log(err) }
data1 = require('./one.json')
})
});
csv().fromFile(csvFile2).then((jsonObj) => {
fs.writeFile('two.json', JSON.stringify(jsonObj), function(err, result) {
if(err) { console.log(err) }
data2 = require('./two.json');
compareJSON(data1, data2);
})
})
function compareJSON(d1, d2){
const result = JSON.parse(JSON.stringify(d1));
d2.forEach(d => {
const existingObjIndex = result.findIndex(r => r.first_name === d.first_name && r.mobile_number === d.mobile_number);
if(existingObjIndex === -1) {
result.push(d)
} else {
result[existingObjIndex] = d;
}
})
result.sort((a, b) => a.first_name.localeCompare(b.first_name))
fs.writeFile('two.json', JSON.stringify(result), function(err, res) {
if(err) { console.log(err); return {} }
})
}
|
import React, { Component } from 'react';
import Activities from './component/Activities';
import Navbar from './component/Navbar'
import { BrowserRouter as Router, Route} from 'react-router-dom';
class App extends Component {
render() {
return (
<div className="App">
<h1>App</h1>
<Router>
<Route exact path="/" component={Activities} />
</Router>
</div>
);
}
}
export default App;
|
const express = require('express');
const app = express();
const port = 8000;
// use exppress router
app.use('/',require('./routes/index'));
app.listen(port,function(err){
if(err)
{
// interpolation method
console.log(`Error in running the server : ${err}`);
}
console.log(`Server is running on : ${port}`);
})
|
import React from 'react';
import { Grid, Row, Col } from 'react-bootstrap';
import AvList from './AvList';
import BvList from './BvList';
export class MainList extends React.Component {
render() {
return (
<Grid style={{marginTop:'50px'}}>
<Row>
{/* <h3> Analog Values </h3> */}
<AvList />
</Row>
<Row>
{/* <h3> Binary Values </h3> */}
<BvList />
</Row>
</Grid>
)
}
}
export default MainList;
|
/*
============================================
; Title: Discussion 4.1
; Author: Sarah Kovar
; Date: 22 December 2019
; Modified By: Micah Connelly
; Description: This program utilizes an array
; that contains two errors.
;===========================================
*/
// import
const header = require('../week-2/header');
console.log(header.display("Micah", "Connelly", "Assignment 4.4 - Header") + '\n');
//declare array
const artistArray = ["Johnny Cash", "Dolly Parton", "Miranda Lambert", "P!nk", "Good Charlotte"];
//#1 replaced ";" with a "," to correct array
//#2 iterate over array, displaying each artist and rank. Parameters: array. Output string.
function rankArtists(array) {
//put for loop in parentheses "()"
for (i = array.length - 1; i >= 0; i--) {
console.log(i + 1 + "\t" + array[i]);
}
}
//display list title
console.log("My Top 5 Musical Artists");
//display list by calling rankArtists function
rankArtists(artistArray);
|
/*
输入字符串,按字典序打印所有排列
如输入abc,则打印:abc,acb,bac,bca,cab,cba
*/
/*
分析:
递归思想:把大问题转换为若干小问题;
n个元素的全排列 = (n-1) 个元素全排列 + 一个元素作为前缀。
递归出口:只有一个元素的全排列,此时排序完成,输出数组。
解题:
遍历字符串,将每个字符放在第一个元素作为前缀,并将其余元素继续全排列。
新建一个isRepeat空对象,用来判断字符是否重复,若重复则跳过排序。
*/
function Permutation(str) {
var result = []
if (!str) return result
var arr = str.split('')
var sortTemp = ''
result = sortString(arr, sortTemp, [])
return result
}
function sortString(arr, sortTemp, result) {
if (arr.length === 0) {
result.push(sortTemp)
} else {
var isRepeat = {}
arr.forEach((val, i) => {
if (!isRepeat[val]) {
var temp = arr.splice(i, 1)[0]
sortTemp += temp
sortString(arr, sortTemp, result)
arr.splice(i, 0, temp)
sortTemp = sortTemp.slice(0, sortTemp.length - 1)
isRepeat[temp] = true
}
})
}
return result
}
/*
var result = Permutation('abbc')
console.log(result.toString(), result.length)
*/
|
appicenter.filter("asDate", function() {
return function(input) {
return new Date(input);
}
});
|
$(function () {
myWp('');
myLy();
homeNum();
myTopic();
myReply();
myInfo();
$('.num1').text(localStorage.getItem("name"));
})
//点击我的闲置物品
$('#info2').on('click',function () {
$('.right').load("myWp.html");
window.location.reload();
})
//点击我的个人信息
$('#info1').on('click',function () {
$('.right').load("myInfo.html");
})
//点击修改我的个人信息
$('.edit').on('click',function () {
editMyInfo();
})
//点击我的主题
$('#info3').on('click',function () {
$('.right').load("myTopic.html");
})
//点击我的回帖
$('#info4').on('click',function () {
$('.right').load("myReply.html");
})
//点击我的留言
$('#info5').on('click',function () {
$('.right').load("myLy.html");
})
//头部数字统计
var homeNum=function () {
var xh=localStorage.getItem("xh");
$.ajax({
method: 'GET',
url: 'http://127.0.0.1:9999/home/headNum',
data:{
xh:xh,
},
success:function (response) {
if(response.responseCode=='1000'){
$('.num2').text(response.content.zt)
$('.num3').text(response.content.ht)
}
}
})
}
//我的回帖
var myReply=function () {
var xh=localStorage.getItem("xh");
$.ajax({
method:'GET',
data:{
xh:xh,
},
url: 'http://127.0.0.1:9999/home/myReply',
success:function (response) {
$('.replyList').html("");
if(response.responseCode == '1000') {
if (response.content.length > 0) {
for(var i = 0;i < response.content.length;i++){
var newTr = '<tr>'
+ '<td>' + response.content[i].rownum +'</td>'
+ '<td style="width: 60px">' + response.content[i].ftr + '</td>'
+ '<td>' + response.content[i].ftnr + '</td>'
+ '<td>' + response.content[i].ftsj + '</td>'
+ '<td>' + response.content[i].htr + '</td>'
+ '<td>' + response.content[i].htnr + '</td>'
+ '<td>' + response.content[i].htsj + '</td>'
+ '</tr>'
$('.replyList').append(newTr)
}
}
}
}
})
}
function updateState(data) {
var topic_xh=$(data)[0].attributes[1].value;
$.ajax({
method:'GET',
data:{
topic_xh:topic_xh,
},
url:'http://127.0.0.1:9999/home/updateState',
success:function (response) {
alert("确定交易.......");
}
})
}
//我的留言
var myLy=function () {
var xh=localStorage.getItem("xh");
$.ajax({
method:'GET',
data:{
xh:xh,
},
url: 'http://127.0.0.1:9999/home/myLy',
success:function (response) {
$('.toLyList').html("");
$('.fromLyList').html("");
if(response.responseCode == '1000') {
if (response.content.to.length > 0) {
for(var i=0;i<response.content.to.length;i++){
var newTr = '<tr>'
+ '<td>' + response.content.to[i].rownum +'</td>'
+ '<td style="width:200px;margin-left: 100px">' + response.content.to[i].ftr + '</td>'
+ '<td style="width:200px;margin-left: 100px">' + response.content.to[i].scwp + '</td>'
+ '<td style="width:400px;margin-left: 100px">' + response.content.to[i].yxjhwp + '</td>'
+ '<td style="width:200px;margin-left: 100px">' + response.content.to[i].lyr + '</td>'
+ '<td style="width:200px;margin-left: 100px">' + response.content.to[i].lysj + '</td>'
+ '<td onclick="updateState(this)" topic_xh="'+response.content.to[i].xh+'" style="width:200px;margin-left: 100px;cursor: pointer"><img src="home/img/ok1.png"></td>'
+ '</tr>'
$('.toLyList').append(newTr)
}
}
if (response.content.from.length > 0) {
for(var i=0;i<response.content.from.length;i++){
var newTr = '<tr>'
+ '<td>' + response.content.from[i].rownum +'</td>'
+ '<td style="width:220px">' + response.content.from[i].ftr + '</td>'
+ '<td style="width:210px;margin-left: 200px">' + response.content.from[i].scwp + '</td>'
+ '<td style="width:270px;margin-left: 200px">' + response.content.from[i].yxjhwp + '</td>'
+ '<td style="width:270px;margin-left: 500px">' + response.content.from[i].lyr + '</td>'
+ '<td>' + response.content.from[i].lysj + '</td>'
+ '</tr>'
$('.fromLyList').append(newTr)
}
}
}
}
})
}
//我的主题
var myTopic=function () {
var xh=localStorage.getItem("xh");
$.ajax({
method:'GET',
data:{
xh:xh,
},
url: 'http://127.0.0.1:9999/home/myTopic',
success:function (response) {
$('.TopicList').html("");
if(response.responseCode == '1000') {
if (response.content.length > 0) {
for(var i = 0;i < response.content.length;i++){
var newTr = '<tr>'
+ '<td>' + response.content[i].rownum +'</td>'
+ '<td style="width: 740px">' + response.content[i].ftnr + '</td>'
+ '<td style="width:50px">' + response.content[i].zhhtr + '</td>'
+ '<td style="width: 220px">' + response.content[i].htl + '</td>'
+ '<td style="width:270px">' + response.content[i].ftsj + '</td>'
+ '</tr>'
$('.TopicList').append(newTr)
}
}
}
}
})
}
//我的个人信息
var myInfo=function () {
var xh=localStorage.getItem("xh");
$.ajax({
method:'GET',
data:{
xh:xh,
},
url: 'http://127.0.0.1:9999/home/myInfo',
success:function (response) {
if(response.responseCode == '1000') {
$('.myName1').text(response.content.name);
$('.myBirthday').val(response.content.birthday);
$('.myEmail').val(response.content.email);
$('.myBirthday1').text(response.content.birthday);
$('.myName').val(response.content.name);
$('.myNc').val(response.content.nc);
$('.myPassword').val(response.content.password);
$('.mytp').attr('src',response.content.url);
}
}
})
}
//编辑我的个人信息
var editMyInfo=function () {
var xh = localStorage.getItem("xh");
$('.myXh').val(xh);
var formData = new FormData(document.getElementById("form1"));
$.ajax({
method:'POST',
data:formData,
url:'http://127.0.0.1:9999/home/editMyInfo',
async: false,
cache: false,
contentType: false,
processData: false,
success:function () {
alert("个人信息修改成功!!!");
myInfo()
}
})
}
//我上传的物品
var myWp=function () {
var xh=localStorage.getItem("xh");
$.ajax({
method:'GET',
data:{
xh:xh,
},
url: 'http://127.0.0.1:9999/home/myWp',
success:function (response) {
console.log(response)
if(response.responseCode == '1000') {
if (response.content.length > 0) {
for(var i = 0;i < response.content.length;i++){
var newTr = '<tr>'
+ '<td>' + response.content[i].rownum +'</td>'
+ '<td>' + response.content[i].scwp + '</td>'
+ '<td style="width:450px">' + response.content[i].wpms + '</td>'
+ '<td>' + response.content[i].wplx + '</td>'
+ '<td style="width:170px">' + response.content[i].yxjhwp + '</td>'
+ '<td style="width:100px">' + response.content[i].scdd + '</td>'
+ '<td style="width:170px;">' + response.content[i].jyzt + '</td>'
+ '<td>' + response.content[i].scsj + '</td>'
+ '</tr>'
$('.homeList').append(newTr)
}
}
}
}
})
}
//导入excel表
$('.excel').on('mouseover',function () {
var xh=localStorage.getItem("xh");
$(this).attr('href',"http://127.0.0.1:9999/home/excelMyWp?xh="+xh)
})
//弹出物品上传框
$('.upload').on('click',function () {
$('.wp_detail').slideDown();
$('#form2').reset();
})
//删除物品上传框
$('.del').on('click',function () {
$('.wp_detail').slideUp();
})
//物品上传
$('.wp_button').on('click',function () {
var user_xh=localStorage.getItem("xh");
$('.xh').val(user_xh);
var formData = new FormData(document.getElementById("form2"));
$.ajax({
method:'POST',
url:'http://127.0.0.1:9999/home/upload',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success:function () {
$('.wp_detail').slideUp(100);
}
})
})
|
import { BASE_PATH, apiVersion } from "../config";
export function agregarRollApi(data) {
const url = `${BASE_PATH}/${apiVersion}/agregar-rol`;
const params = {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
};
return fetch(url, params).then(response => {
return response.json()
}).then(result => {
return result;
}).catch(err => {
return err;
})
}
export function getRolApi() {
const url = `${BASE_PATH}/${apiVersion}/roles`;
const params = {
method: "GET",
headers: {
"Content-Type": "application/json"
},
mode: "cors"
};
return fetch(url, params).then(response => {
return response.json()
}).then(result => {
return result;
}).catch(err => {
return err;
})
}
export function updateRolApi(user, userId) {
const url = `${BASE_PATH}/${apiVersion}/updateRol/${userId}`;
const params = {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(user)
}
return fetch(url, params).then(response => {
return response.json();
}).then(result => {
return result;
}).catch(err => {
return err;
})
}
export function deleteRolaApi(id) {
const url = `${BASE_PATH}/${apiVersion}/deleteRol/${id}`;
const params = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
};
return fetch(url, params).then(response => {
return response.json();
}).then(result => {
return result;
}).catch(err => {
return err;
})
}
export function getRoleName() {
const url = `${BASE_PATH}/${apiVersion}/nameRol`;
const params = {
method: "GET",
headers: {
"Content-Type": "application/json"
},
mode: "no-cors"
};
return fetch(url, params).then(response => {
return response.json()
}).then(result => {
return result;
}).catch(err => {
return err;
})
}
|
var mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Marker = new Schema({
lng: {type: String, required: true},
lat: {type: String, required: true},
type: {type: String, required: true},
activityType: {type: String, required: true},
date: {type: Date, default: Date.now},
activityName: {type: String, required: true},
description: {type: String, required: true},
agencyName: {type: String, required: true}
})
module.exports = mongoose.model('Marker', Marker);
|
var Todo = function(title) {
this.title = title;
this.done = false;
this.deleted = false;
}
module.exports = Todo;
|
var giphyConfig = require('../config/giphy.js'),
logger = require('../config/logger');
env = process.env.NODE_ENV || 'development',
giphyHost = giphyConfig.host,
giphyKey = giphyConfig[env].key,
request = require('request');
/**
* Builds a gifphy endpoint
* @param {string} host
* @param {object} options
*/
function buildEndpoint(options) {
return options.host + options.endpoint + '?api_key=' + options.key + '&tag=' + encodeURI(options.tag);
}
/**
* Removes .gif from a url and adds another type of file
* @param {string} url
* @param {string} format
* @returns {string}
*/
function convertGifFormat(url, format) {
var targetLength = 4,
webp;
if (url) {
webp = url.slice(0, url.length - targetLength) + format;
return webp;
} else {
return null;
}
}
/**
* Gets a gif from giphy's random endpoint
* @param {string} tag
* @param {function} done
* @returns {function}
*/
exports.getRandomGif = function(tag, done) {
var endpoint = buildEndpoint({ host: giphyHost, endpoint: giphyConfig.endpoints.random, key: giphyKey, tag: tag }),
gifPixelLimit = 700;
request({ url: endpoint, json: true }, function(err, response, body) {
if (err) {
logger.log('error', err);
return done(err);
}
if (body.data) {
var data = body.data,
gif = data.image_url;
if (data.image_width > gifPixelLimit || data.image_height > gifPixelLimit) {
gif = data.fixed_height_downsampled_url;
}
if (gif) {
return done(null, gif);
} else {
return done(err);
}
}
});
}
|
try {
const form = document.querySelector('.input-group')
const listItemsButtons = document.querySelectorAll('.list-group-item > button')
const listItems = document.querySelectorAll('.list-group-item.to-update > p')
const clearAllButton = document.querySelector('#clearAll')
const clearDoneButton = document.querySelector('#clearDone')
const ulLists = document.querySelectorAll('.list-group.auto-show')
const formArchiv = document.querySelector('#form-archiv')
listItemsButtons.forEach(el => el.addEventListener('click', closeToDo))
listItems.forEach(el => el.addEventListener('click', markAsDone))
form.addEventListener('submit', ShowTodoList)
clearAllButton.addEventListener('click', clearAll)
clearDoneButton.addEventListener('click', clearDone)
formArchiv.addEventListener('submit', showArchiv)
async function ShowTodoList(evt) {
evt.preventDefault()
let input = document.querySelector('.form-control').value
if (input.length == 0) {
return false
}
await fetch('/features', {
method: 'POST',
body: JSON.stringify({
'input': input
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
window.location.href = '/features'
}
async function closeToDo(elementList) {
let innerText = elementList.target.previousSibling.innerText //.slice(3)
innerText = innerText.substring(3, innerText.indexOf("-") - 1)
await fetch('/features/delete', { // /features-delete
method: 'POST',
body: JSON.stringify({
'deleteElement': innerText
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
window.location.href = '/features'
}
async function markAsDone(el) {
// get text from target element
let innerText = el.srcElement.innerText //.slice(3)
// if I clicked on time span rewrite the innerText variable
if (el.currentTarget !== el.target) {
innerText = el.srcElement.parentElement.innerText
}
// text of todo will be from from 3rd position up to first '-'
innerText = innerText.substring(3, innerText.indexOf('-') - 1)
await fetch('/features/update', { // /features-update
method: 'POST',
body: JSON.stringify({
'element': innerText
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
window.location.href = '/features'
}
async function clearAll(el) {
await fetch('/features/clear-all', { // features-clear-all
method: 'POST'
})
window.location.href = '/features'
}
async function clearDone(el) {
await fetch('/features/clear-done', { // features-clear-done
method: 'POST'
})
window.location.href = '/features'
}
ulLists.forEach(ul => {
if (ul.children.length == 0) {
ul.previousSibling.style.display = 'none'
} else {
ul.previousSibling.style.display = 'block'
}
})
async function showArchiv(event) {
event.preventDefault()
const from = document.querySelector('#from').value
const to = document.querySelector('#to').value
const archiv = await fetch('/features/archiv', {
method: 'POST',
body: JSON.stringify({
'from' : from,
'to' : to
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
const archivJSON = await archiv.json()
await showArchivList(archivJSON)
}
function showArchivList(data) {
const archiv = document.querySelector('#archiv')
let out = `<ul class='list-group list-archiv my-4'>`
for (let i=0; i<data.length; i++) {
out += `<li class='list-group-item to-archiv'>
<p> ${i+1}. ${data[i]['text']} ----- <span><b>done</b>
${new Date(Date.parse(data[i]['date'])).toLocaleString()}</span></p></li>`
}
out += `</ul>`
out += `<div class='delete-archiv-precautions'><button class='btn btn-outline-danger' id='archiv-delete'>Delete all archiv todos</button>
<p><b>Note</b>: this action is irreversible!</p>`
archiv.innerHTML = out
const deleteArchiv = document.querySelector('#archiv-delete')
deleteArchiv.addEventListener('click', deleteAllArchiv)
showDeleteArchivButton()
}
async function deleteAllArchiv() {
await fetch('/features/archiv-delete', {
method: 'POST'
})
window.location.href = '/features'
}
function showDeleteArchivButton() {
let archiv = document.querySelector('#archiv')
let div = document.querySelector('.delete-archiv-precautions')
if (archiv.firstChild.children.length == 0) {
div.style.display = 'none'
} else {
div.style.display = 'block'
}
}
} catch (e) {
console.log(e.message)
}
|
// Objects in javascript
let student = {
first: 'Mohammad',
last: 'Tasib',
age: 19,
nickName: 'Ohidul',
studentInfo: function () {
return this.first + '\n' + this.last + '\n' + this.age;
}
}
console.log(student.first);
console.log(student['last']);
student.age++ // increment age
console.log(student.age);
student.nickName = 'Tasib'; // change value
console.log(student.nickName);
console.log(student.studentInfo());
|
({
doInit: function (component, event, helper) {
helper.doInit(component, event);
},
onDragStart: function (component, event, helper) {
helper.onDragStart(component, event);
},
ondragEnd: function (component, event, helper) {
helper.ondragEnd(component, event);
},
onView : function(component, event, helper) {
helper.onView(component, event, helper);
},
refresh : function(component, event, helper) {
helper.refresh(component, event);
},
})
|
/*
* Copyright (c) 2017 Peter SOLYOM-NAGY <info@snp.hu>
*/
'use strict';
ifbControllers
//<editor-fold desc="LoginController">
.controller('LoginController', ['$scope', 'ngDialog', '$localStorage', 'authFactory', function ($scope, ngDialog, $localStorage, authFactory) {
$scope.loginData = $localStorage.getObject('userinfo', '{}');
$scope.doLogin = function () {
if ($scope.rememberMe)
$localStorage.storeObject('userinfo', $scope.loginData);
authFactory.login($scope.loginData);
$scope.closeThisDialog();
};
$scope.openRegister = function () {
ngDialog.open({template: 'modules/register/register.html', /*scope: $scope,*/ className: 'ngdialog-theme-default', controller: "RegisterController as ctl"});
$scope.closeThisDialog();
};
}])
//</editor-fold>
;
|
import {
createStore,
applyMiddleware
} from 'redux';
import reducers from '../reducers'
import thunk from 'redux-thunk'
/* reducer只支持同步操作,不支持异步操作,thunk是异步的中间件,所有中间件交给applyMiddleware */
//1.创建一个仓库 3.将数据放到store
//reducers是一个很多个reducer组成的对象
const store = createStore(reducers, applyMiddleware(thunk));
export default store;
|
const sequelize = require('sequelize');
const { userElements, elements } = require('../models');
async function addElements(userId, addElements) {
for (const element of addElements) {
const getElement = await elements.findOne({ where: { symbol: element } }, { type: sequelize.QueryTypes.SELECT });
const elementId = getElement.dataValues.id;
const getUserElement = await userElements.findOne({ where: { userId, elementId } }, { type: sequelize.QueryTypes.SELECT });
if (!getUserElement) {
await userElements.create({ userId, elementId, count: 1 });
} else {
await getUserElement.update({ count: getUserElement.dataValues.count + 1 });
}
}
}
async function deleteElements(userId, deleteElements) {
for (const element of deleteElements) {
const getElement = await elements.findOne({ where: { symbol: element } }, { type: sequelize.QueryTypes.SELECT });
const elementId = getElement.dataValues.id;
const getUserElement = await userElements.findOne({ where: { userId, elementId } }, { type: sequelize.QueryTypes.SELECT });
if (!getUserElement) {
throw "no element found";
} else {
await getUserElement.update({ count: getUserElement.dataValues.count - 1 });
}
}
}
module.exports = {
addElements,
deleteElements
}
|
/* eslint-disable */
'use strict';
// data + translator
const data = [
{"id":"france","name":"Франция"},
{"id":"finland","name":"Финляндия"},
{"id":"estonia","name":"Эстония"}
];
module.exports = {
getNameById: function(id) {
const country = data.filter(function(c) {
return c.id === id;
})[0];
return country ? country.name : null;
}
};
|
import React, { useState } from "react";
import "/src/styles.css";
export default ({category, name}) => {
return (
<div>
<div>
{category}
{name}
</div>
</div>
);
};
|
'use strict';
module.exports = (sequelize, DataTypes) => {
const Room = sequelize.define('Room', {
name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
is: /^[a-z0-9_-]+$/i,
len: [3, 32],
},
},
title: DataTypes.STRING,
description: DataTypes.TEXT,
visibility: {
type: DataTypes.STRING,
defaultValue: "public",
validate: {
// eslint-disable-next-line array-bracket-newline
isIn: [["public", "unlisted", "private"]],
},
},
ownerId: {
type: DataTypes.INTEGER,
defaultValue: -1,
allowNull: false,
},
}, {});
// eslint-disable-next-line no-unused-vars
Room.associate = function(models) {
Room.belongsTo(models.User, { foreignKey: "ownerId", as: "owner" });
};
return Room;
};
|
function Sentence(){
this.constructor.apply(this,arguments);
}
Sentence.prototype.constructor = function(options,sender_id,text,messageSender){
this.options = options;
this.sender_id = sender_id;
this.text = text;
this.messageSender = messageSender;
};
Sentence.prototype.run = function(){
this.messageSender.sendSimpleMessage(this.sender_id,this.options.message);
};
module.exports = Sentence;
|
import React from 'react'
import AgentComponent from '../../index.jsx'
import { shallow, mount } from 'enzyme'
const setup = () => {
const props = {
data: [
{
"name": "bjstdmngbdr01.thoughtworks.com",
"os": "windows",
"status": "idle",
"type": "physical",
"ip": "192.168.1.102",
"location": "/var/lib/cruise-agent",
"resources": [
"Safari",
"Firefox",
"Ubuntu",
"Chrome"
],
"id": 1
},
{
"name": "bjstdmngbdr08.thoughtworks.com",
"os": "windows",
"status": "building",
"type": "virtual",
"ip": "192.168.1.80",
"location": "/var/lib/cruise-agent",
"resources": [
"Firefox",
"Safari",
"Ubuntu",
"Chrome"
],
"id": 2
},
{
"name": "bjstdmngbdr10.thoughtworks.com",
"os": "ubuntu",
"status": "building",
"type": "physical",
"ip": "192.168.1.117",
"location": "/var/lib/cruise-agent",
"resources": [
"Firefox",
"Safari",
"Ubuntu",
"Chrome"
],
"id": 3
},
{
"name": "bjstdmngbdr11.thoughtworks.com",
"os": "debin",
"status": "building",
"type": "virtual",
"ip": "192.168.1.102",
"location": "/var/lib/cruise-agent",
"resources": [
"Firefox",
"Safari",
"Ubuntu",
"Chrome"
],
"id": 4
},
{
"name": "bjstdmngbdr15.thoughtworks.com",
"os": "suse",
"status": "idle",
"type": "physical",
"ip": "192.168.1.110",
"location": "/var/lib/cruise-agent",
"resources": [
"Test",
"Hello",
"World",
"Awesome"
],
"id": 5
},
{
"name": "bjstdmngbdr01.thoughtworks.com",
"os": "cent_os",
"status": "idle",
"type": "virtual",
"ip": "192.168.1.103",
"location": "/var/lib/cruise-agent",
"resources": [
"Firefox",
"Safari",
"Ubuntu",
"Chrome"
],
"id": 6
}
]
}
const wrapper = shallow(<AgentComponent {...props} />)
return { props, wrapper }
}
describe('<AgentComponent />', () => {
const { wrapper } = setup();
it('Test AgentComponent should be render', () => {
expect(wrapper.find('div.agent__overview').exists())
})
it('Missed Props data:[]', () => {
try {
let errorWrapper = shallow(<AgentComponent />)
expect(errorWrapper.find('div.agent__items').length).toBe(0)
} catch (error) {
// if we don't use Unit Test,our component will be show this error.
expect(error.toString()).toEqual('TypeError: Cannot read property \'map\' of undefined')
}
})
})
describe('<Modal />', () => {
it('Agent Items should be correctly render', () => {
const { props } = setup()
const wrapper = mount(<AgentComponent {...props}/>)
expect(wrapper.find('.agent-item').length > 0 ).toBe(true)
})
it('Add resouce modal could be render', () => {
const { props } = setup()
const wrapper = mount(<AgentComponent {...props}/>)
expect(wrapper.find('div.modal input').length).toBe(0)
wrapper.find('button.add-button').first().simulate('click')
expect(wrapper.find('div.modal input').length).toBe(1)
})
})
|
import BmuiSelect from './bmui-select';
import './bmui-select.less';
export default BmuiSelect;
|
// ==UserScript==
// @name Nemlig Extensions
// @namespace fillipuster.com
// @version 1.0
// @description Provides useful functionality to Nemlig.com, such as calculating and sorting by percentage savings.
// @author Fillipuster
// @match *://www.nemlig.com/*
// ==/UserScript==
(function () {
'use strict';
let productsListElement = document.querySelector(".productlist-show-all__item-container")
let productElements = document.querySelectorAll(".productlist-item");
let headerElement = document.querySelector(".site-header__content");
let sortSavingsBtn = document.createElement("button");
sortSavingsBtn.innerText = "Sort by savings percentage";
sortSavingsBtn.addEventListener("click", () => { sortByPercentSavings() });
headerElement.parentNode.prepend(sortSavingsBtn);
let sortKiloPriceBtn = document.createElement("button");
sortKiloPriceBtn.innerText = "Sort by kilo/litre price";
sortKiloPriceBtn.addEventListener("click", () => { sortByKiloPrice() });
headerElement.parentNode.prepend(sortKiloPriceBtn);
let recalculateSavingsBtn = document.createElement("button");
recalculateSavingsBtn.innerText = "Re-calculate percentage savings";
recalculateSavingsBtn.addEventListener("click", () => { calculatePercentSavings() });
headerElement.parentNode.prepend(recalculateSavingsBtn);
function calculatePercentSavings() {
console.log("Calculating percentage savings for products.");
// Refetch elements, as they may be fetched prematurely during initialization
productsListElement = document.querySelector(".productlist-show-all__item-container")
productElements = document.querySelectorAll(".productlist-item");
productElements.forEach(productElement => {
// Only checks for products with direct savings, not X for Y specials.
let priceElement = productElement.querySelector(".pricecontainer.has-campaign")
if (priceElement && !productElement.fp_percentSaving) {
let campaignPriceElement = priceElement.children[0];
let basePriceElement = priceElement.children[1];
let campaignPriceStr = campaignPriceElement.children[0].innerText + "." + campaignPriceElement.children[1].innerText;
let basePriceStr = basePriceElement.children[0].innerText + "." + basePriceElement.children[1].innerText;
let campaignPrice = parseFloat(campaignPriceStr);
let basePrice = parseFloat(basePriceStr);
let percentSaving = (1 - campaignPrice / basePrice) * 100;
// priceElement.appendChild(document.createElement("br"));
priceElement.appendChild(document.createTextNode(` ${Math.round(percentSaving * 10) / 10}%`));
productElement.fp_percentSaving = percentSaving;
} else {
productElement.fp_percentSaving = -1; // Maybe not the best, but ensures correct sorting.
}
});
}
function sortByPercentSavings() {
console.log("Sorting products by percentage savings.");
let productElementsArray = Array.prototype.slice.call(productElements, 0);
productElementsArray.sort((a, b) => {
// Notice the inverted sorting. We want to highest savings first in the array.
if (a.fp_percentSaving > b.fp_percentSaving) return -1;
if (a.fp_percentSaving < b.fp_percentSaving) return 1;
return 0
});
productsListElement.innerHTML = "";
productElementsArray.forEach(e => {
productsListElement.appendChild(e);
})
}
function sortByKiloPrice() {
console.log("Sorting products by kilo/litre price.");
let productElementsArray = Array.prototype.slice.call(productElements, 0);
productElementsArray.sort((a, b) => {
if (a.querySelector(".pricecontainer-unitprice__label").innerText == "kr./Stk." || b.querySelector(".pricecontainer-unitprice__label").innerText == "kr./Stk.") return 1;
let aPrice = a.querySelector(".pricecontainer-unitprice__campaign-price").innerText || a.querySelector(".pricecontainer-unitprice__base-price").innerText;
let bPrice = b.querySelector(".pricecontainer-unitprice__campaign-price").innerText || b.querySelector(".pricecontainer-unitprice__base-price").innerText;
aPrice = parseFloat(aPrice);
bPrice = parseFloat(bPrice);
if (aPrice > bPrice) return 1;
if (aPrice < bPrice) return -1;
return 0
});
productsListElement.innerHTML = "";
productElementsArray.forEach(e => {
productsListElement.appendChild(e);
})
}
// Doesn't work?
// window.onhashchange = function () {
// setTimeout(calculatePercentSavings, 3000);
// }
setTimeout(calculatePercentSavings, 3000);
})();
|
import React, { Component } from 'react';
import { PostComment } from './postComment';
import { ScrollView, View } from 'react-native';
export default class CommentBox extends Component {
render() {
return (
<ScrollView style={styles.commentsContainer}>
<PostComment post={{username: 'Bob', comment: 'This is a comment'}} />
<PostComment post={{username: 'Jake', comment: 'Yea its a comment'}} />
<PostComment post={{username: 'Chris', comment: 'This is a comment'}} />
<PostComment post={{username: 'Jason', comment: 'This is a comment'}} />
</ScrollView>
);
}
};
const styles = {
commentsContainer: {
width: '98%',
marginTop: '2%',
backgroundColor: 'white',
paddingLeft: '2%',
paddingRight: '2%',
paddingBottom: '2%',
borderBottomLeftRadius: 5,
borderBottomRightRadius: 5,
borderTopLeftRadius: 5,
borderTopRightRadius: 5
}
}
|
$(function(){
//Главный слайдер
$('.main-slider').slick({
dots:true,
infinite: true,
speed: 500,
fade: true,
cssEase: 'linear',
draggable:false,
prevArrow: '.slider-arrow__prev',
nextArrow: '.slider-arrow__next',
})
function activated(activeItem) {
$(activeItem).click(function(){
$(this).parent().children().removeClass("active");
$(this).addClass("active");
})
}
//Активация спииска иконок
activated(".list-icon__elem");
//Активация галереи
activated(".gallery__card");
//Добавление фона меню при прокрутке
$(window).on("scroll", function() {
if ($(window).scrollTop() >=50 ) {
$(".header-nav-wrap").addClass("scroll");
}
if ($(window).scrollTop() <50 ) {
$(".header-nav-wrap").removeClass("scroll");
}
})
//Управление видео
$("#video-play").click(function() {
document.querySelector("#video").play();
$(".video-info-wrap").css("display","none");
})
$("#video").click(function() {
document.querySelector("#video").pause();
$(".video-info-wrap").css("display","");
})
//Адаптивное меню
$(window).resize(function() {
if($(document).width()<960) {
$(".menu-icon").css("display", "block");
$(".nav").addClass("nav-mini");
$(".nav").css("display", "none");
} else if($(".nav").hasClass("nav-mini")) {
$(".menu-icon").css("display", "");
$(".nav").removeClass("nav-mini");
$(".nav").css("display", "");
}
});
$(".menu-icon").click(function() {
$(".nav-mini").slideToggle(200);
$(".header-nav-wrap").addClass("scroll");
})
$(window).resize();
$(window).scroll();
});
|
jsfac.module('dashboard', ['diagnostics'], function (register) {
register('fooWidgetViewModel', ['eventLog'], function (eventLog) {
var count = 0;
return {
click: function () {
eventLog.log({
source: 'fooWidget',
message: 'Click ' + ++count + ' on fooWidgetViewModel'
});
}
};
});
});
|
jQuery('.bookmark').css('margin-bottom','0px');
jQuery('.bookmark').css('padding','0px');
jQuery('.display').css('padding','2px');
jQuery('.star').hide();
jQuery('.display').each(function() {
$(this).find( "br" ).hide();
$(this).find('.description').hide();
$(this).find('.when').hide();
//$(this).find('.tag').hide();
$(this).find('.bookmark_count').hide();
$(this).find('.copy_link').hide();
$(this).find('.edit_links').prev('a').hide();
});
$('.display').html(function (i, old) {
return old
.replace('by', '');
});
$('.display:odd').css('background','#f5f5f5');
$('.bookmark_title').each(function(){
if ($(this).text().length > 50) {
$(this).text($(this).text().substr(0, 47));
$(this).append('...');
}
});
|
"use strict";
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var babelify = require('babelify');
var util = require('gulp-util');
var size = require('gulp-size');
var uglify = require('gulp-uglify');
var rename = require("gulp-rename");
gulp.task('bundle', function () {
var bundle = browserify({
debug: false,
extensions: ['.js', '.jsx'],
entries: 'lib/main.js'
});
return bundle
.transform(babelify)
.bundle()
.on("error", function (error) { util.log(util.colors.red(error.message)); })
.pipe(source('mojito.js'))
.pipe(gulp.dest('dist'))
.pipe(size({title: "scripts"}));
});
gulp.task('uglify', ['bundle'], function () {
return gulp.src('dist/mojito.js')
.pipe(uglify({
compress: {
unused: false,
properties: false,
side_effects: false
},
options: {
mangle : false,
}
}))
.on('error', function(error){
console.log(error);
})
.pipe(rename('mojito.min.js'))
.pipe(gulp.dest('dist'))
.pipe(size({title: "scripts"}));
});
gulp.task('scripts', ['uglify']);
|
const initialState = {
ContactList: [],
CurrentContact: null,
};
const ContactListReducer = (state = initialState, action) => {
console.log("action", action);
switch (action.type) {
case "UPDATE_CONTACT_LIST":
return {
...state,
ContactList: action.payload,
};
case "SET_CURRENT_CONTACT":
return {
...state,
CurrentContact: action.payload,
};
default:
return state;
}
};
export default ContactListReducer;
|
var socketio = require('socket.io');
// Listening to Port 9000
var io = socketio.listen(9000);
io.sockets.on('connection', function(socket) {
// Broadcast a user's message to everyone in the chat room
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
|
var CreateGoal = Backbone.Model.extend({
urlRoot : function(){ return '/api/goals/';},
parse : function(response){
if(response.status && response.status.code == 1000){
return response.data;
}
return response;
},
validate: function(attrs) {
if(!attrs.name || attrs.name.trim() == ''){
return 'Goal Name can not be blank';
}
if(!attrs.url || attrs.url.trim() == ''){
return 'Goal URL can not be blank';
}
}
});
Views.CreateGoalView = Views.BaseView.extend({
events : {
"click #submit-btn" : "createGoal",
"click #reset-btn" : "render",
},
initialize : function(){
this.$el = $("#dashboard-content");
this.model = new CreateGoal();
this._super('initialize');
this.loadTemplate('goal-create');
this.model.bind('error', this.error, this);
this.model.bind('sync', this.synced, this);
eventBus.on( 'close_view', this.close, this );
},
init : function(){
this.render();
this.name = this.$('#name');
this.type = this.$('#type');
this.url = this.$('#url');
this.alert = this.$('#goal-alert');
this.submitBtn = this.$('#submit-btn');
this.resetBtn = this.$('#reset-btn');
},
render : function(){
this.$el.html(this.template());
},
close : function(){
this._super('close');
},
error : function(model, error){
if(error.status == 500){
var data = $.parseJSON(error.responseText);
this.showError(data.message);
}else if(error.statusText != undefined){
this.showError(error.statusText);
}else{
this.showError(error);
}
},
synced : function(model, response){
this.showSuccess(response.status.message);
this.$('form').each(function(){
this.reset();
});
},
showError : function(msg){
this.enable();
this.alert.find('.alert').removeClass('alert-success');
this.alert.find('.alert').addClass('alert-error');
this.alert.find('.alert').html(msg);
this.alert.show();
},
showSuccess : function(msg){
this.enable();
this.alert.find('.alert').removeClass('alert-error');
this.alert.find('.alert').addClass('alert-success');
this.alert.find('.alert').html(msg);
this.alert.show();
},
disable : function(){
this.$el.find('input').prop('disabled' , true);
this.$el.find('a').prop('disabled' , true);
},
enable : function(){
this.$el.find('input').prop('disabled' , false);
this.$el.find('a').prop('disabled' , false);
},
createGoal : function(){
this.disable();
this.model.set('name', this.name.val(), {silent : true});
this.model.set('type', this.type.val(), {silent : true});
this.model.set('url', this.url.val(), {silent : true});
this.model.save();
},
});
|
/**
* Created by andycall on 15/5/4.
*/
var api = require('./api');
var cache = require('./cache');
var logger = require('./logger');
module.exports = {
api : api,
cache : cache,
logger : logger
};
|
import { createAsyncThunk, createSlice, nanoid } from '@reduxjs/toolkit';
// async API call to add randomly delected notes
export const getRandomNoteAsync = createAsyncThunk(
'notes/getRandomNoteAsync',
async () => {
const response = await fetch('https://www.boredapi.com/api/activity');
if (response.ok) {
const note = await response.json();
return { note };
}
}
);
export const noteSlice = createSlice({
name: 'notes',
initialState: [],
reducers: {
addNote: (state, action) => {
const note = {
id: nanoid(),
title: action.payload.title,
content: action.payload.content,
};
state.push(note);
},
deleteNote: (state, action) => {
return state.filter((note) => note.id !== action.payload.id);
},
},
// reducer processes API return into a note object, adds to state
extraReducers: {
[getRandomNoteAsync.fulfilled]: (state, action) => {
const note = {
id: nanoid(),
title: action.payload.note.type,
content: action.payload.note.activity,
};
state.push(note);
},
},
});
export const { addNote, deleteNote } = noteSlice.actions;
export default noteSlice.reducer;
|
import React, {Component} from 'react';
import {StyleSheet, View, ActivityIndicator, FlatList, RefreshControl} from 'react-native';
import { FloatingAction } from 'react-native-floating-action';
import Icon from 'react-native-vector-icons/Ionicons';
import {addProjectMember, deleteProjectMember} from '../../Networking/Projects';
import {AppPopup} from '../UIKit';
import {loadTasks, updateUser} from '../../Networking';
import MembersCell from './MembersCell';
import LoginManager from '../../Helpers/LoginManager';
class MembersScreen extends Component {
constructor(props) {
super(props);
this.user = LoginManager.shared().getUser();
this.state = {
users: [],
loading: true,
isDialogVisible: false,
isModalVisible: false,
isRightModalVisible: false,
right: '',
};
}
componentDidMount() {
this._loadMembers();
}
_loadMembers = () => {
const {project} = this.props.navigation.state?.params;
loadTasks(project.id, (error, response) => {
if (error) {
this.setState({loading: false});
alert(error);
} else {
console.log('MEN', response.caller.right)
this.setState({users: response.users, isAdmin: response.caller.right.Id !== 1, loading: false});
}
});
};
_addMember = () => {
const {project} = this.props.navigation.state?.params;
const {login} = this.state;
if (!login || !login.trim()) {
alert('Вы не ввели имя участника!');
return;
}
addProjectMember({ProjectId: project.id.toString(), UserName: login}, (error, response) => {
if (error) {
alert(error.message);
} else {
this._loadMembers();
this.setState((prevState) => {
return {
isDialogVisible: false,
login: '',
};
});
}
});
};
_removeMember = (currentUser) => {
const {project} = this.props.navigation.state?.params;
const filteredMembers = this.state.users.filter((item) => item.Id !== currentUser.Id);
this.setState({ isModalVisible: false });
deleteProjectMember({ProjectId: project.id.toString(), UserId: currentUser.Id}, (error, response) => {
if (error) {
this.setState({loading: false});
alert(error);
} else {
this.setState({ users: filteredMembers });
}
});
};
_changeUserRight = (index, user) => {
const {project} = this.props.navigation.state?.params;
const body = {
userLogin: user.login,
rightId: index.toString(),
projectId: project.id.toString(),
}
console.log(body)
updateUser(
body,
(error, response) => {
if (error) {
this.setState({loading: false});
alert(error);
} else {
this._loadMembers();
this.setState({ isRightModalVisible: false });
}
},
);
};
_renderItem = ({item}) => {
return (
<MembersCell
{...item}
currentUser={this.user}
isAdmin={this.state.isAdmin}
selectedValue={this.state.right}
value={this.state.right}
onPressRight={() => {
this.setState({isRightModalVisible: true, currentUser: item});
}}
onPressDelete={() => {
this.setState({isModalVisible: true, currentUser: item});
}}
/>
);
};
render() {
const {users, loading, isDialogVisible, isModalVisible, currentUser, isRightModalVisible} = this.state;
if (loading) {
return (
<View style={styles.loadingIndicator}>
<ActivityIndicator size="large" color="#03bafc" />
</View>
);
}
return (
<View style={{flex: 1}}>
<FlatList
style={styles.container}
contentContainerStyle={styles.contentContainer}
data={users}
keyExtractor={(item, index) => index.toString()}
renderItem={this._renderItem}
refreshControl={<RefreshControl refreshing={loading} onRefresh={this._loadMembers} />}
/>
<AppPopup
isDialogVisible={isDialogVisible}
title="Добавить нового участника"
message="Введите никнейм участника, которого хотите пригласить в данный проект."
firstHintInput="Никнейм"
submit={this._addMember}
closeDialog={() => { this.setState({isDialogVisible: false}); }}
onChangeFirstText={(login) => this.setState({login})}
/>
<AppPopup
isDialogVisible={isModalVisible}
title="Вы действительно хотите исключить данного участника?"
submit={() => this._removeMember(currentUser)}
closeDialog={() => { this.setState({isModalVisible: false}); }}
/>
<AppPopup
isDialogVisible={isRightModalVisible}
title={`Изменить права пользователя ${currentUser?.login}`}
onChangeRight={(item, index) => this.setState({right: index})}
submit={() => this._changeUserRight(this.state.right, currentUser)}
closeDialog={() => { this.setState({isRightModalVisible: false}); }}
/>
{this.props.isAdmin &&
<FloatingAction
color="#03bafc"
floatingIcon={<Icon name="md-person-add" size={30} color="#FFF" />}
onPressMain={() => {
this.setState({isDialogVisible: true});
}}
showBackground={false}
/>}
</View>
);
}
}
const styles = StyleSheet.create({
contentContainer: {
marginTop: 10,
},
container: {
flex: 1,
},
navigationBar: {
width: '100%',
},
scene: {
flex: 1,
},
title: {
marginLeft: 20,
fontSize: 17,
letterSpacing: 0.15,
color: '#FFF',
},
loadingIndicator: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
menuIcon: {
},
addIcon: {
paddingHorizontal: 16,
},
flexSpacing: {
flex: 1,
},
});
export default MembersScreen;
|
var lat = null;
var lon = null;
var gPosition = null;
var cardCycleID = -1;
var WHY = ["", "#one!", "#two!", "#three!", "#four!", "#five!", "#six!", "#seven!", "#eight!"]; // carousel
var refreshID = -1;
function getLocation() {
// handles the "can we even use the geolocation api" crap
if (navigator.geolocation) {
console.log("location supported!");
navigator.geolocation.getCurrentPosition(locationSuccess)
} else {
console.log("location unsupported!");
return false;
}
}
function locationSuccess(position) {
// kicks off the lat/lon to my script, which returns the json from darksky
window.lat = position.coords.latitude;
window.lon = position.coords.longitude;
window.gPosition = position;
var hurl = "/weather/getForecast?lat=" + lat + "&lon=" + lon;
$.ajax({
type: "POST",
dataType: "json",
url: hurl,
success: updateCards
});
}
function carouselCycle() {
// for the automated carousel cycling crap
$(".carousel").carousel("next");
cardCycleID = setTimeout(carouselCycle, 15000);
}
function refresh() {
// handles the pretty splash screen + getting stuff + setting timeouts
$('.button-collapse').sideNav('hide');
$("#load").show();
clearTimeout(refreshID);
clearTimeout(cardCycleID);
cardCycleID = -1;
getLocation();
if (refreshID != -1) {
refreshID = setTimeout(refresh, 3600000);
}
}
function updateCards(data) {
// clears out stuff
$("#curWeather").empty();
$("#forecast").empty().removeClass("initialized");
// sets up the "current" card
var now = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
var dayForecast = data["daily"]["data"][0];
var current = data["currently"]
var card =
"<div class='row'>\
<div class='col s12 m8 offset-m2 l8 offset-l2'>\
<div class='card grey darken-2 blue-grey-text text-lighten-5'>\
<div class='card-image'>\
<canvas id='currentIcon' width='128' height='128'></canvas>\
</div>\
<div class='card-content grey darken-2 blue-grey-text text-lighten-5'>\
/*have fun reading the next lines, sucker*/\
<span class='card-title'>Current Weather: " + current["summary"] + "\n<small>" + dayForecast["summary"] + "</small></span>\
<p>It is currently " + now + ".\nCurrent temperatute: " + Math.round(current["temperature"]) + "F\nHigh: " + Math.round(dayForecast["temperatureMax"]) + "F | Low: " + Math.round(dayForecast["temperatureMin"]) + "F\nThere is a " + Math.round(dayForecast["precipProbability"]*100) + "% chance of rain today!</p>\
</div>\
</div>\
</div>\
</div>";
$("#curWeather").html(card);
var skycons = new Skycons({"color": "white"});
skycons.add("currentIcon", current["icon"]);
for(var i = 1; i < 8; ++i) {
// creates the 7 forecast cards
var day = data["daily"]["data"][i];
var dayString = new Date(day["time"] * 1000).toLocaleDateString([], {weekday: 'long', month: 'long', day: 'numeric'});
var card =
"<div id='card-" + i + "' class='carousel-item' href='" + WHY[i] + "'>\
<div class='card grey darken-2 blue-grey-text text-lighten-5'>\
<div class='card-image'>\
<canvas id='forecast-" + i + "-icon' width='128' height='128'></canvas>\
</div>\
<div class='card-content'>\
<span class='card-title'>" + dayString + "\n<small>" + day["summary"] + "</small></span>\
/* same as before, enjoy reading */\
<p>High: " + Math.round(day["temperatureMax"]) + "F | Low: " + Math.round(day["temperatureMin"]) + "F\nThere is a " + Math.round(day["precipProbability"]*100) + "% chance of rain today!</p>\
</div>\
<div class='card-action hide-on-med-and-down'>\
<a class='waves-effect waves-light btn-flat btn-prev'>Previous day</a>\
<a class='waves-effect waves-light btn-flat btn-next'>Next day</a>\
</div>\
</div>\
</div>";
$("#forecast").append(card);
skycons.add("forecast-" + i + "-icon", day["icon"]);
}
// animate icons, kick off carousel, bind card click events
skycons.play();
$('.carousel').carousel();
$(".btn-prev").on("click", function() {
$(".carousel").carousel("prev");
clearTimeout(cardCycleID);
cardCycleID = setTimeout(carouselCycle, 30000);
});
$(".btn-next").on("click", function() {
$(".carousel").carousel("next");
clearTimeout(cardCycleID);
cardCycleID = setTimeout(carouselCycle, 30000);
});
$("#load").hide(); // hide the spinner, and set the refresh timeout!
cardCycleID = setTimeout(carouselCycle, 20000);
}
$(document).ready(function() {
refreshID = setTimeout(refresh, 0); // kick off the updater
// bind shit
$(".cycle-toggle").on("click", function() {
if (cardCycleID == -1) {
cardCycleID = setTimeout(carouselCycle, 5000);
$(".cycle-toggle span").text("Disable forecast cycling");
} else {
clearTimeout(cardCycleID);
cardCycleID = -1;
$(".cycle-toggle span").text("Enable forecast cycling");
}
});
$(".refresh-toggle").on("click", function() {
if (refreshID == -1) {
refreshID = setTimeout(refresh, 900000);
$(".refresh-toggle span").text("Disable autorefresh");
} else {
clearTimeout(refreshID);
refreshID = -1;
$(".refresh-toggle span").text("Enable autorefresh");
}
});
$(".refresh-btn").on("click", refresh);
$(".button-collapse").sideNav();
});
|
function playSound(e) {
const audio = document.querySelector(`audio[data-key ="${e.keyCode}"]`);
const key = document.querySelector(`.key[data-key ="${e.keyCode}"]`);
if (!audio) return; // function will stop
key.classList.add("playing");
audio.currentTime = 0; // will rewind audio clip to the beginning of clip
audio.play();
}
function removeTransition(e) {
if (e.propertyName !== "transform") return; // will skip if not a transform property
e.target.classList.remove("playing");
}
const keys = Array.from(document.querySelectorAll(".key"));
keys.forEach(key =>
key.addEventListener('transitionend', removeTransition)
);
console.table(keys);
function clickSound(e) {
const elementSelector = document.querySelector(``);
}
window.addEventListener("keydown", playSound);
window.addEventListener("click", clickSound);
|
$(document).ready(function () {
// thisUser: username as a String
// gameID: game ID as a string
// Canvas dimensions
var canvas = document.getElementById("Goofspiel");
canvas.width = 1600;
canvas.height = 900;
canvasTop = canvas.offsetTop;
canvasLeft = canvas.offsetLeft;
var ctx = canvas.getContext("2d");
var colorThemePrimary = "#B63546";
var colorThemeSecondary = "#D9CAB3";
var winColor = "#5BD22E";
var loseColor = "#FF0033";
var tieColor = "#CBA249";
var textColor = "#000000";
ctx.fillStyle = colorThemePrimary;
ctx.strokeStyle = colorThemeSecondary;
class Card {
// static cards = [];
static getAllCards() {
if (!this._cards) this.initializeCards();
return this._cards
};
static initializeCards() {
var result = [];
['Spade', 'Heart', 'Club', 'Diamond'].forEach(mySuit => {
['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'].forEach((myName, index) => {
result.push(new Card(myName, mySuit, index + 1))
})
});
this._cards = result;
};
static fromObject(object) { return this.allCards().find(each => object.name === each.name && object.suit === each.suit) };
static fromObjects(collection) { return collection.map(each => this.fromObject(each)) };
static allCards() { return this._cards };
static getSuit(aSuit) { return this.getAllCards().filter(each => each.suit === aSuit) };
static getHearts() { return this.getSuit("Heart") };
static getSpades() { return this.getSuit("Spade") };
static getClubs() { return this.getSuit("Club") };
static getDiamonds() { return this.getSuit("Diamond") };
static getCardFor(name, suit) { return this.allCards().find(each => each.name === name && each.suit === suit) }
static width() { return 80 };
static height() { return 120 };
static dimensions() { return {x: this.width(), y: this.height()} }
isSameAs(card) { return (card.name === this.name && card.suit === this.suit) }
cardHolderForXY(xyPosition) { return new CardHolder(this, xyPosition) };
imageFilename() { return `/images/png/${this.name}${this.suit}.png`};
constructor(name, suit, number) {
this.name = name;
this.suit = suit;
this.value = number;
};
}
class CoveredCard extends Card {
constructor() {
super();
this.name = "Unknown"
this.suit = "Unknown"
this.value = 0;
}
imageFilename() { return "/images/png/playingcardback.png" }
static default() {
if(this.myDefault === undefined) this.myDefault = new CoveredCard();
return this.myDefault;
}
}
class CardHolder {
constructor(card, xyPos) {
this.card = card;
this.xyPos = xyPos;
this.cardName = card.name;
this.cardSuit = card.suit;
}
addOffset(offset, count) {
this.xyPos = { x: this.xyPos.x + Math.round((offset.x * count)),
y: this.xyPos.y + Math.round((offset.y * count)) };
return this;
}
encompass(xPos, yPos) { return xPos > this.xyPos.x && xPos < this.xyPos.x + Card.width() &&
yPos > this.xyPos.y && yPos < this.xyPos.y + Card.height() }
}
class GoofspeilGameState {
constructor(gameState, myUser) {
this.player1 = gameState.player1;
this.player2 = gameState.player2;
this.turnHistory = gameState.turnHistory;
this.currentUser = myUser;
console.log("currentUser: ", [this.currentUser]);
console.log("player1", [this.player1]);
console.log("this.currentPlay == Player1", this.currentUser == player1)
console.log("gameSate: ", gameState);
this.initialize();
console.log(TableMap.default())
};
initialize() {
this.prizeCard = this.toCard(this.turnHistory[this.turnHistory.length - 1].prizeCard);
this.currentPlayerKey = (this.currentUser === this.player1) ? "player1" : "player2";
this.opponentPlayerKey = (this.currentUser === this.player1) ? "player2" : "player1";
this.allMyCards = Card.getSuit(this.getPlayerSuit());
this.myTurnHistory = this.turnHistory.map(turn => turn[this.currentPlayerKey]).filter(playedThisTurn => (playedThisTurn));
this.opponentTurnHistory = this.turnHistory.map(turn => turn[this.opponentPlayerKey]).filter(playedThisTurn => (playedThisTurn));
this.prizeDeckHistory = this.turnHistory.map(turn => turn['prizeCard']).filter(revealed => (revealed));
this.myHand = this.allMyCards.filter(card => !myTurnHistory.find(played => card.isSameAs(played)));
this.theirHand = 13 - this.opponentTurnHistory.length;
this.prizeDeck = 13 - this.prizeDeckHistory.length;
this.playerPlayed = this.toCard(this.turnHistory[this.turnHistory.length - 1][this.currentPlayerKey]);
this.opponentPlayed = this.toCard(this.turnHistory[this.turnHistory.length - 1][this.opponentPlayerKey]);
this.extractPrizeCards();
}
getOpponentPlayed() {
if(this.opponentPlayed)
return this.playerPlayed ? this.opponentPlayed : CoveredCard.default()
else
return this.opponentPlayed }
getPlayerSuit() { return this.currentPlayerKey === "player1" ? "Spade" : "Club"}
static current() { return this.current };
static setCurrent(gs) { this.current = gs };
toCard(obj) { return obj ? Card.fromObject(obj) : obj }
calculateScores() {
var myScore1 = 0;
var myScore2 = 0;
this.turnHistory.forEach(function (turn) {
if ((turn.prizeCard) && (turn.player1) && (turn.player2)) {
if (turn.player1.value > turn.player2.value) {
myScore1 += turn.prizeCard.value;
} else if (turn.player2.value > turn.player1.value) {
myScore2 += turn.prizeCard.value;
}
else return;
}
});
this.score1 = myScore1;
this.score2 = myScore2;
}
extractPrizeCards() {
this.playerPrizeCards = [];
this.opponentPrizeCards = [];
this.turnHistory.forEach(turn => {
if(turn.player1 !== undefined && turn.player2 !== undefined) {
if(turn[this.currentPlayerKey].value > turn[this.opponentPlayerKey].value) {
this.playerPrizeCards.push(turn.prizeCard)
}
if(turn[this.currentPlayerKey].value < turn[this.opponentPlayerKey].value) {
this.opponentPrizeCards.push(turn.prizeCard)
}
}
})
}
renderOn(tableMap) {
this.calculateScores();
tableMap.renderPlayerCards(this.myHand);
tableMap.renderOpponentCards([...Array(this.theirHand)].fill(CoveredCard.default()));
tableMap.renderDeck(this.prizeDeck);
tableMap.renderPrizeCard(this.prizeCard);
tableMap.renderPlayerPlayedCard(this.playerPlayed);
tableMap.renderOpponentPlayedCard(this.getOpponentPlayed());
// console.log(this.getOpponentPlayed())
tableMap.renderScoreboard(this.player1, this.player2, this.score1, this.score2);
// tableMap.renderPlayerPrizeCards(this.playerPrizeCards);
}
}
class TableMap {
constructor(playerPos, opponentPos, deckPos, playerDiscardPos, opponentDiscardPos, prizeCardPos, prizeCardsPos, opponentPrizeCardsPos) {
this.playerXY = playerPos;
this.opponentXY = opponentPos;
this.deckXY = deckPos;
this.playerDiscardXY = playerDiscardPos;
this.opponentDiscardXY = opponentDiscardPos;
this.prizeCardXY = prizeCardPos;
this.prizeCardsXY = prizeCardsPos;
this.opponentPrizeCardsXY = opponentPrizeCardsPos;
this.playerCardHolders = [];
}
static defaultMap() { return new TableMap({x: 210, y: 760}, {x: 400, y: 20}, {x: 880, y: 390}, {x: 495, y: 540}, {x: 1080, y: 220}, {x: 760, y: 390}) };
static default() {
if(!this._default) this._default = this.defaultMap();
return this._default;
}
get cardPositions() { return this._cardPositions };
set cardPositions(collection) { this._cardPositions = collection};
addCardPositon(xyCord) { this.cardPositions().push(xyCord)};
xPosToCenterFor(numberOfCards) { return Math.round((canvas.width - ((numberOfCards * Card.width()) + ((numberOfCards-1) * 20))) / 2) }
renderDeck(count) { this.renderCards([...Array(count)].fill(CoveredCard.default()), this.deckXY, {x: -0.35, y: -0.35} )}
renderPlayerPrizeCards(cards) { this.renderCards(cards, this.prizeCardXY.x, this.prizeCardXYy, { x: -0.35, y: -0.35 }) }
renderPrizeCard(card) { this.renderCardWithOutline(card, this.prizeCardXY, 20) };
renderPlayerPlayedCard(card) { this.renderCardWithOutline(card, this.playerDiscardXY, 20) }
renderOpponentPlayedCard(card) {
// console.log("opponentCard", card);
this.renderCardWithOutline(card, this.opponentDiscardXY, 20) }
renderPlayerCards(cards) {
this.playerCardHolders = this.renderCards(cards, {x: this.xPosToCenterFor(cards.length), y: this.playerXY.y}, { x: (Card.width() + 20), y: 0 }) };
renderOpponentCards(cards) {
var cardBackCards = cards.map(each => CoveredCard.default());
this.renderCards(cardBackCards, {x: this.xPosToCenterFor(cards.length), y: this.opponentXY.y}, { x: (Card.width() + 20), y: 0 }) };
renderCardWithOutline(card, initialPos, padding) {
this.renderCard(card, initialPos, {x: 0, y: 0});
this.renderCardOutline(initialPos, Card.dimensions(), padding) }
renderCard(card, initialPos, offset) {
// console.log("RenderCard", card, initialPos);
if(card !== undefined) return this.renderCards([card], initialPos, offset)[0] }
renderCards(cards, initialPos, offset) {
// console.log("renderPlayerCards", cards, initialPos, offset)
var cardHolders = cards.map((each, index) => each.cardHolderForXY(initialPos).addOffset(offset, index));
cardHolders.forEach(cardHolder => this.renderCardHolder(cardHolder));
return cardHolders;
}
renderCardHolder(cardHolder) {
// console.log("Display image: ", cardHolder.xyPos.x, cardHolder.xyPos.y, Card.width(), Card.height())
var img = new Image();
img.src = cardHolder.card.imageFilename();
ctx.drawImage(img, cardHolder.xyPos.x, cardHolder.xyPos.y, Card.width(), Card.height());
}
renderScoreboard(player1Name, player2Name, p1Score, p2Score) {
var myFont = "20px Pacifico" || "20px cursive";
this.renderBox(20, 325, 200, 50, colorThemePrimary, "SCORE", myFont, 85, 360, textColor);
this.renderBox(20, 375, 133, 50, colorThemeSecondary, player1Name, myFont, 30, 405, textColor);
this.renderBox(153, 375, 67, 50, colorThemeSecondary, p1Score, myFont, 187, 405, textColor);
this.renderBox(20, 425, 133, 50, colorThemeSecondary, player2Name, myFont, 30, 455, textColor);
this.renderBox(153, 425, 67, 50, colorThemeSecondary, p2Score, myFont, 187, 455, textColor);
}
renderCardOutline(fromXY, dimensionsXY, padding) {
ctx.beginPath();
ctx.rect(fromXY.x - padding, fromXY.y - padding, dimensionsXY.x + (padding*2), dimensionsXY.y + (padding*2));
ctx.strokeStyle = colorThemeSecondary;
ctx.stroke();
ctx.closePath();
}
renderBox(rectPosX, rectPosY, width, height, fillSyle, text, font, textPosX, textPosY, textColor) {
ctx.beginPath();
ctx.rect(rectPosX, rectPosY, width, height);
ctx.fillStyle = fillSyle;
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.font = font;
ctx.fillStyle = textColor;
ctx.fillText(text, textPosX, textPosY);
ctx.closePath();
}
}
function renderTest() {
GoofspeilGameState.current.renderOn(TableMap.default());
}
// card specifications
var cardNames = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"];
var cardValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
var playingCard = {
width: 80,
height: 120,
backColor: colorThemePrimary,
frontColor: colorThemeSecondary
}
var loaded;
// properties extracted from gamestate
var player1 = "Waiting ...";
var player2 = "Waiting ...";
var score1 = 0;
var score2 = 0;
var playerSuit = "Diamond";
// turn histories
var turnHistory = [];
var myTurnHistory = [];
var opponentTurnHistory = [];
// stored as an array of cards
var myHand = Card.getSuit(playerSuit);
// stored as numbers for card rendering
var theirHand = 13;
var prizeDeck = 13;
var myWinnings = Card.getHearts();
var theirWinnings = Card.getHearts();
// play area cards
var prizeCard = {};
var playerPlayed = {};
var opponentPlayed = {};
// card.top and card.left keys are for collision detection
var playerHandCollision = [];
var opponentHandCollision = [];
// times for animated events
var turnResolutionTime;
var playerWonTurn = -1;
// 0 -> lost, 1 -> won, 2 -> tie
var matchResolutionTime;
// polling server for new gamestate
function poll() {
$.ajax({
method: "GET",
url: "/gs/" + (gameID).toString()
}).done((gs) => {
loaded = window.performance.now();
parseGameState(gs);
// turnResolve();
})
}
var intervalID;
function doPoll() {
intervalID = setInterval(poll, 5000);
}
$("canvas").on('click', function (event) {
var mouseX = event.pageX - canvasLeft;
var mouseY = event.pageY - canvasTop;
console.log("currentUser", thisUser)
console.log("MousePos", mouseX, mouseY) // TEMP logging of mouse click
console.log(globalGS);
console.log(Card.getAllCards())
console.log(Card.fromObject(
{name: "3", suit: "Diamond", value: 3}) )
if(!GoofspeilGameState.current.playerPlayed) {
var tableMap = TableMap.default();
console.log( tableMap.playerCardHolders)
var selectedCardHolder = tableMap.playerCardHolders.find(cardHolder => cardHolder.encompass(mouseX, mouseY));
if(selectedCardHolder) {
$.ajax({
method: "POST",
url: "/gs/",
data: { gameid: gameID,
card: selectedCardHolder.card}
}).done(function () {
console.log(`Played card:, ${selectedCardHolder.card}`)
})
}
}
// playerHandCollision.forEach(function (card) {
// if (// mouseclick collision detection
// ((mouseX > card.left && mouseX < card.left + playingCard.width)
// && (mouseY > card.top && mouseY < card.top + playingCard.height))
// && // move validation, does not pass if move is illegal
// !playerPlayed && (player1 !== "Waiting ...") && (player2 !== "Waiting ...")) {
// var myData = {};
// myData.gameid = gameID;
// var cardData = {};
// cardData.name = card.name;
// cardData.suit = card.suit;
// myData.card = cardData;
// playerPlayed = cardData;
// $.ajax({
// method: "POST",
// url: "/gs/",
// data: myData
// }).done(function () {
// console.log(`Played card:, ${myData.card.name}, suit: ${myData.card.suit}`)
// })
// }
// })
})
function rect(x, y, w, h, a) {
// console.log("rect: ", x, y, w, h, a)
}
function fillText(text, x, y) {
// console.log("text", text, x, y)
}
// Renders the scoreboard
function renderScoreBoard() {
return ///////////*************** */
var width = 200;
var height = 150; // recommend value divisible by 3
var xpos = 20;
var ypos = canvas.height / 2 - height / 2;
// SCORE rectangle
ctx.beginPath();
ctx.rect(xpos, ypos - height / 3, width, height / 3);
rect(xpos, ypos - height / 3, width, height / 3, "**********");
ctx.fillStyle = colorThemePrimary;
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.font = "20px Pacifico" || "20px cursive";
ctx.fillStyle = colorThemeSecondary;
ctx.fillText("SCORE", xpos + width / 3, ypos - height / 7);
fillText("SCORE", xpos + width / 3, ypos - height / 7);
ctx.closePath();
// Player 1 name rectangle
ctx.beginPath();
ctx.rect(xpos, ypos, width / 3 * 2, height / 3);
rect(xpos, ypos, width / 3 * 2, height / 3);
ctx.fillStyle = colorThemeSecondary;
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.font = "20px Pacifico" || "20px cursive";
ctx.fillStyle = textColor;
ctx.fillText(player1, xpos + 10, ypos + 30);
fillText(player1, xpos + 10, ypos + 30);
ctx.closePath();
// Player 1 score rectangle
ctx.beginPath();
ctx.rect(xpos + width / 3 * 2, ypos, width / 3, height / 3);
rect(xpos + width / 3 * 2, ypos, width / 3, height / 3);
ctx.fillStyle = colorThemeSecondary;
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.font = "20px Pacifico" || "20px cursive";
ctx.fillStyle = textColor;
ctx.fillText(score1, xpos + 5 * width / 6, ypos + 30);
fillText(score1, xpos + 5 * width / 6, ypos + 30);
ctx.closePath();
// Player 2 name rectangle
ctx.beginPath();
ctx.rect(xpos, ypos + height / 3, width / 3 * 2, height / 3);
rect(xpos, ypos + height / 3, width / 3 * 2, height / 3);
ctx.fillStyle = colorThemeSecondary;
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.font = "20px Pacifico" || "20px cursive";
ctx.fillStyle = textColor;
ctx.fillText(player2, xpos + 10, ypos + height / 3 + 30);
fillText(player2, xpos + 10, ypos + height / 3 + 30);
ctx.closePath();
// Player 2 score rectangle
ctx.beginPath();
ctx.rect(xpos + width / 3 * 2, ypos + height / 3, width / 3, height / 3);
rect(xpos + width / 3 * 2, ypos + height / 3, width / 3, height / 3);
ctx.fillStyle = colorThemeSecondary;
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.font = "20px Pacifico" || "20px cursive";
ctx.fillStyle = textColor;
ctx.fillText(score2, xpos + 5 * width / 6, ypos + height / 3 + 30);
fillText(score2, xpos + 5 * width / 6, ypos + height / 3 + 30);
ctx.closePath();
}
// Renders a card on canvas. Specify inner color and value if card is face up
function renderPlayingCard(xpos, ypos, innerColor, name) {
// return //////////////***************** */
var img = new Image();
img.src = "/images/playingcardback.png";
ctx.drawImage(img, xpos, ypos, playingCard.width, playingCard.height);
if (innerColor) {
ctx.beginPath();
ctx.rect(xpos + 3, ypos + 3, playingCard.width - 6, playingCard.height - 6);
ctx.fillStyle = colorThemePrimary;
ctx.fill();
ctx.stroke();
ctx.closePath;
ctx.beginPath();
ctx.font = "16px Georgia";
ctx.fillStyle = colorThemeSecondary;
ctx.fillText(name, xpos + 12, ypos + 25);
ctx.closePath();
ctx.beginPath();
ctx.font = "16px Georgia";
ctx.fillStyle = colorThemeSecondary;
ctx.fillText(name, xpos + playingCard.width - 25, ypos + playingCard.height - 20);
ctx.closePath();
}
}
// Accepts an array of cards representing player cards and renders them in a row
function renderPlayerHand(myCards) {
return ///*************** */
var offsetX = 20;
if (myCards.length % 2 === 0) {
var xpos = canvas.width / 2 - (myCards.length / 2 * (playingCard.width + offsetX)) + offsetX / 2;
} else {
var xpos = canvas.width / 2 - (myCards.length + 1) / 2 * playingCard.width + playingCard.width / 2 - offsetX * (myCards.length - 1) / 2;
}
var ypos = canvas.height - playingCard.height - 20;
playerHandCollision = []
for (var i = 0; i < cardNames.length; i++) {
for (var j = 0; j < myCards.length; j++) {
if (cardNames[i] === myCards[j].name) {
var cardObj = {};
cardObj.name = cardNames[i];
cardObj.initial = cardInitial(cardNames[i]);
cardObj.suit = myCards[j].suit;
cardObj.value = cardValues[i];
cardObj.left = xpos;
cardObj.top = ypos;
playerHandCollision.push(cardObj);
renderPlayingCard(cardObj.left, cardObj.top, playingCard.frontColor, cardObj.initial);
xpos = xpos + playingCard.width + offsetX;
}
}
}
}
// Accepts a number and renders that number of cards face down in a row
function renderOpponentHand(n) {
return //////**************** */
var offsetX = 20;
if (n % 2 === 0) {
var xpos = canvas.width / 2 - (n / 2 * (playingCard.width + offsetX)) + offsetX / 2;
} else {
var xpos = canvas.width / 2 - (n + 1) / 2 * playingCard.width + playingCard.width / 2 - offsetX * (n - 1) / 2;
}
var ypos = 20;
opponentHandCollision = [];
for (var i = 0; i < n; i++) {
var cardObj = {};
cardObj.left = xpos;
cardObj.top = ypos;
opponentHandCollision.push(cardObj);
renderPlayingCard(cardObj.left, cardObj.top);
xpos = xpos + playingCard.width + offsetX;
}
}
// TODO: accepts a number and renders that number of cards face down stacked up
function renderPrizeDeck(n) {
return; //******* */
initialXPos = 20;
var xpos = canvas.width / 2 + playingCard.width + initialXPos;
var ypos = canvas.height / 2 - playingCard.height / 2;
var offset = 2;
var thisOffset = offset;
for (var i = 0; i < n; i++) {
renderPlayingCard(xpos - thisOffset, ypos - thisOffset);
thisOffset = thisOffset + offset;
}
}
// Accepts a card and renders it on the center of the screen
function renderPrizeCard(card) {
return ///////////************ */
xpos = canvas.width / 2 - playingCard.width / 2;
ypos = canvas.height / 2 - playingCard.height / 2;
ctx.beginPath();
ctx.rect(xpos - 20, ypos - 20, playingCard.width + 40, playingCard.height + 40);
ctx.strokeStyle = colorThemeSecondary;
ctx.stroke();
ctx.closePath();
if (!turnResolutionTime && !matchResolutionTime && card !== undefined && (card.name)) {
var cardName = cardInitial(card.name);
renderPlayingCard(xpos, ypos, playingCard.frontColor, cardName);
}
}
// Accepts a card object and renders it to the left and offset down to a card on the center of the screen face up
function renderPlayerPlayed(card) {
return //////////************ */
var xpos = canvas.width / 3 - playingCard.width / 2;
var ypos = canvas.height / 3 * 2 - playingCard.height / 2;
ctx.beginPath();
ctx.rect(xpos - 20, ypos - 20, playingCard.width + 40, playingCard.height + 40);
if (playerWonTurn === 0) {
ctx.fillStyle = loseColor;
ctx.fill();
}
if (playerWonTurn === 1) {
ctx.fillStyle = winColor;
ctx.fill();
}
if (
playerWonTurn === 2) {
ctx.fillStyle = tieColor;
ctx.fill()
}
ctx.strokeStyle = colorThemeSecondary;
ctx.stroke();
ctx.closePath();
if (card !== undefined && (card.name)) {
var cardName = cardInitial(card.name);
renderPlayingCard(xpos, ypos, playingCard.frontColor, cardName);
}
}
// Accepts a card object and renders it to the right and offset up to a card on the center of the screen face down
function renderOpponentPlayed(card) {
return ///////**************** */
var xpos = canvas.width / 3 * 2 - playingCard.width / 2;
var ypos = canvas.height / 3 - playingCard.height / 2;
ctx.beginPath();
ctx.rect(xpos - 20, ypos - 20, playingCard.width + 40, playingCard.height + 40);
if (playerWonTurn === 0) {
ctx.fillStyle = winColor;
ctx.fill();
}
if (playerWonTurn === 1) {
ctx.fillStyle = loseColor;
ctx.fill();
}
if (playerWonTurn === 2) {
ctx.fillStyle = tieColor;
ctx.fill()
}
ctx.strokeStyle = colorThemeSecondary;
ctx.stroke();
ctx.closePath();
if (card !== undefined && (card.name)) {
var cardName = cardInitial(card.name);
if (playerPlayed) {
renderPlayingCard(xpos, ypos, playingCard.frontColor, cardName);
} else {
//play animation here
renderPlayingCard(xpos, ypos);
}
}
}
// Accepts an array of card objects and render them to the right of the player face up
function renderWinnings() {
var myXpos = canvas.width / 3 - playingCard.width - 90;
var myYpos = canvas.height / 3 * 2 - playingCard.height / 2;
var theirXpos = canvas.width / 3 * 2 + playingCard.width + 30;
var theirYpos = canvas.height / 3 - playingCard.height / 2;
var offset = 0;
var increment = 2;
var myCurrentWinnings = myWinnings;
var theirCurrentWinnings = theirWinnings;
ctx.beginPath();
ctx.font = "20px Pacifico" || "20px cursive";
ctx.fillStyle = colorThemeSecondary;
ctx.fillText("My winnings", myXpos - playingCard.width - 80, myYpos + playingCard.height / 2);
ctx.closePath();
myCurrentWinnings.forEach(function (card) {
renderPlayingCard(myXpos - offset, myYpos - offset, playingCard.frontColor, cardInitial(card.name));
offset = offset + increment;
});
offset = 0;
ctx.beginPath();
ctx.font = "20px Pacifico" || "20px cursive";
ctx.fillStyle = colorThemeSecondary;
ctx.fillText("Their winnings", theirXpos + playingCard.width + 50, theirYpos + playingCard.height / 2);
ctx.closePath();
theirCurrentWinnings.forEach(function (card) {
renderPlayingCard(theirXpos - offset, theirYpos - offset, playingCard.frontColor, cardInitial(card.name));
offset = offset + increment;
});
}
function renderSpecialCondition(renderfn, eventStartTime, duration) {
// Exit condition: no start time
if (!eventStartTime) {
return;
}
if (duration) {
var timeStamp = window.performance.now();
var eventEndTime = eventStartTime + duration;
// Exit condition: event has ended
if (timeStamp > eventEndTime) {
return;
}
}
renderfn();
return eventStartTime;
}
function renderTurnResolution() {
if (!playerPlayed || !opponentPlayed || !prizeCard) {
return;
}
var xpos = canvas.width / 2;
var ypos = canvas.height / 3 * 2;
var boxWidth = 400;
var boxHeight = 100;
var scoreIncrease = prizeCard.value;
ctx.beginPath();
ctx.rect(xpos - boxWidth / 2, ypos - boxHeight / 2, boxWidth, boxHeight);
ctx.font = "32px Pacifico" || "32px cursive";
ctx.strokeStyle = colorThemePrimary;
if (playerPlayed.value > opponentPlayed.value) {
playerWonTurn = 1;
ctx.stroke();
ctx.fillStyle = colorThemeSecondary;
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = textColor;
ctx.fillText(`You won ${scoreIncrease} points!`, xpos - boxWidth * 5 / 16, ypos + boxHeight / 10);
} else if (playerPlayed.value < opponentPlayed.value) {
playerWonTurn = 0;
ctx.stroke();
ctx.fillStyle = colorThemeSecondary;
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = textColor;
ctx.fillText(`Opponent won ${scoreIncrease} points.`, xpos - boxWidth * 2 / 5, ypos + boxHeight / 10);
} else {
playerWonTurn = 2;
ctx.stroke();
ctx.fillStyle = colorThemeSecondary;
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = textColor;
ctx.fillText(`It's a draw!`, xpos - boxWidth * 1 / 5, ypos + boxHeight / 10);
}
ctx.closePath();
}
function renderMatchResolution() {
var xpos = canvas.width / 2;
var ypos = canvas.height / 2;
var boxWidth = 500;
var boxHeight = 200;
ctx.beginPath();
ctx.rect(xpos - boxWidth / 2, ypos - boxHeight / 2, boxWidth, boxHeight);
ctx.font = "48px Pacifico" || "48px cursive";
ctx.strokeStyle = colorThemePrimary;
ctx.stroke();
// Player won
if (((playerNum === "player1") && (score1 > score2))
|| ((playerNum === "player2") && (score2 > score1))) {
ctx.fillStyle = colorThemeSecondary;
ctx.fill();
ctx.closePath;
ctx.beginPath;
ctx.fillStyle = textColor;
ctx.fillText(`You won this match!`, xpos - boxWidth / 2 + 35, ypos + 10);
ctx.closePath();
// Player lost
} else if (((score1 > score2) && (playerNum === "player2")) ||
(score1 < score2) && (playerNum === "player1")) {
ctx.fillStyle = colorThemeSecondary;
ctx.fill();
ctx.closePath;
ctx.beginPath;
ctx.fillStyle = textColor;
ctx.fillText(`You lost this match.`, xpos - boxWidth / 2 + 40, ypos + 10);
ctx.closePath();
// Draw
} else {
ctx.fillStyle = colorThemeSecondary;
ctx.fill();
ctx.closePath;
ctx.beginPath;
ctx.fillStyle = textColor;
ctx.fillText(`This match is a draw.`,xpos - boxWidth / 2 + 40, ypos + 10);
ctx.closePath();
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (loaded) {
/// ****** temp test
renderTest();
renderScoreBoard();
// renderPlayerHand(myHand);
// renderOpponentHand(theirHand);
// renderPrizeDeck(prizeDeck);
// if (!turnResolutionTime && !matchResolutionTime) {
// playerWonTurn = -1;
// }
// renderPrizeCard(prizeCard);
// renderPlayerPlayed(playerPlayed);
// renderOpponentPlayed(opponentPlayed);
// turnResolutionTime = renderSpecialCondition(renderTurnResolution, turnResolutionTime, 5000);
// renderWinnings();
// matchResolutionTime = renderSpecialCondition(renderMatchResolution, matchResolutionTime);
} else {
ctx.beginPath();
ctx.font = "120px Pacifico" || "120px cursive";
ctx.fillStyle = colorThemeSecondary;
ctx.fillText("Loading...", canvas.width / 3, canvas.height / 2);
ctx.closePath();
}
requestAnimationFrame(draw);
}
let globalGS;
// Helper functions to extract game state information and save them into global variables
function parseGameState(gameState) {
GoofspeilGameState.setCurrent(new GoofspeilGameState(gameState, thisUser));
console.log("GS/ThisUser", gameState, thisUser)
console.log(GoofspeilGameState.current)
// globalGS = gameState;
// player1 = gameState.player1 || "Waiting ...";
// player2 = gameState.player2 || "Waiting ...";
// turnHistory = gameState.turnHistory;
// prizeCard = turnHistory[turnHistory.length - 1].prizeCard;
// playerNum = playerAssignments(true);
// myTurnHistory = turnHistory.map(turn => turn[playerAssignments(true)]).filter(playedThisTurn => (playedThisTurn));
// opponentTurnHistory = turnHistory.map(turn => turn[playerAssignments(false)]).filter(playedThisTurn => (playedThisTurn));
// prizeDeckHistory = turnHistory.map(turn => turn['prizeCard']).filter(revealed => (revealed));
// myHand = myHand.filter(card => !myTurnHistory.find(played => card.isSameAs(played)));
// theirHand = 13 - opponentTurnHistory.length;
// prizeDeck = 13 - prizeDeckHistory.length;
// playerPlayed = turnHistory[turnHistory.length - 1][playerAssignments(true)];
// opponentPlayed = turnHistory[turnHistory.length - 1][playerAssignments(false)];
// calculateScore(turnHistory);
// if (playerNum === "player1") {
// myWinnings = player1PrizeCards(turnHistory);
// theirWinnings = player2PrizeCards(turnHistory);
// } else if (playerNum === "player2") {
// theirWinnings = player1PrizeCards(turnHistory);
// myWinnings = player2PrizeCards(turnHistory);
// }
}
function player1PrizeCards(history) {
var result = [];
history.forEach(turn => {
if(turn.player1 !== undefined && turn.player2 !== undefined) {
if(turn.player1.value > turn.player2.value) {
result.push(turn.prizeCard)
}
}
})
return result;
}
function player2PrizeCards(history) {
var result = [];
history.forEach(turn => {
if(turn.player1 !== undefined && turn.player2 !== undefined) {
if(turn.player2.value > turn.player1.value) {
result.push(turn.prizeCard)
}
}
})
return result;
}
// Return string "player1" or "player2" for user if given true, for opponent if given false
// Used to extract value from output key in a turn object
function playerAssignments(boolean) {
if (!thisUser) {
return;
}
if (boolean) {
if (thisUser === player1) {
return "player1"
} else {
return "player2"
}
} else {
if (thisUser === player2) {
return "player1";
} else {
return "player2";
}
}
}
// Other helper functions
function calculateScore(history) {
score1 = 0;
score2 = 0;
history.forEach(function (turn) {
if ((turn.prizeCard) && (turn.player1) && (turn.player2)) {
if (turn.player1.value > turn.player2.value) {
score1 = score1 + turn.prizeCard.value;
} else if (turn.player2.value > turn.player1.value) {
score2 = score2 + turn.prizeCard.value;
}
else return;
}
})
}
function cardInitial(name) {
var result = name;
if (name === "Ace") {
result = "A";
} else if (name === "Jack") {
result = "J";
} else if (name === "Queen") {
result = "Q";
} else if (name === "King") {
result = "K";
}
return result;
}
function turnResolve() {
if (playerPlayed && opponentPlayed && !turnResolutionTime) {
// hard coded match resolution condition as 13 turns
if (turnHistory.length === 13) {
matchResolutionTime = window.performance.now();
}
else {
turnResolutionTime = window.performance.now();
}
}
}
// Polling and draw function invocations to start game!
doPoll();
draw();
})
|
import React from 'react'
import styled from 'styled-components'
const AstronomyCard = (props) => {
const { title, url, hdurl, explanation, date, copyright } = props.data
return (
<div className='astronomy-card'>
<Heading className='astronomy-title'>{title}</Heading>
<a href={hdurl} className='astronomy-image-wrapper'>
<ImgStyled src={url} alt={title} />
</a>
<p>{explanation}</p>
<span>{date}, {copyright}</span>
</div>
)
}
const Heading = styled.h1`
font-size: 3em;
font-family: Helvetica;
`
const ImgStyled = styled.img`
width: 100%;
`
export default AstronomyCard
|
$(document).ready( function() {
$("#meow").click( function() {
$("#animals").append("<img class='animal' src='images/cat.png' alt='He Peek'/> ");
});
$("#bunbun").click( function() {
$("#animals").append("<img class='animal' src='images/bunny.png' alt='He Hop'/> ");
});
$(".animal").click( function() {
this.css('visibility', 'hidden')
});
});
|
(function (window, $, undefined) {
'use strict';
String.prototype.format = function () {var args = arguments; return this.replace(/\{(\d+)\}/g, function (m, i) {return args[i]; }); };
$.extend({CA: function (o) {
var option = $.extend({}, {
speed: 500,
stepspeed: 500,
target: ".ca_container",
size: {x: 10, y: 7},
threshold: 5,
template: {line: "#temp_line", item: "#temp_item"},
isClose: true,
noHoldExt: false,
noColor: false
}, o),
nodesContainer,
allNodes,
matArray = [],
nextArray = [],
timerStep,
timerLoop,
countStep = 0,
countLoop = 0,
isLock = false,
isStep = false,
isLoop = false,
runState = false,
_deepCopy = function (obj) {
var out = [], i, len = obj.length;
for (i = 0; i < len; i += 1) {
if (obj[i] instanceof Array) {
out[i] = _deepCopy(obj[i]);
} else {
out[i] = obj[i];
}
}
return out;
},
_randomNum = function (x, y) {
return parseInt(Math.random() * (x - y + 1) + y, 10);
},
_getTemplate = function (temp) {
var ret = {}, thtml, t;
for (t in temp) {
thtml = $(temp[t]).html();
ret[t] = thtml.substring(6, thtml.length - 3);
}
return ret;
},
_getMat = function (x, y) {
return matArray[x][y];
},
_getNode = function (x, y) {
return allNodes.eq(y * option.size.x + x);
},
_setMat = function (x, y, val, b) {
matArray[x][y] = val;
var obj = allNodes.eq(y * option.size.x + x);
obj.find("span").text(val);
if(!option.noColor && !b)_cssTransition(obj, undefined, val);
},
_cssTransition = function (obj, obj2, val) {
if(obj2 === undefined) {
if(obj.hasClass("act"))
obj.attr("class", "act c"+val);
else obj.attr("class", "c"+val);
}else{
var o = _getNode(obj, obj2);
if(o.hasClass("act"))
o.attr("class", "act c"+val);
else o.attr("class", "c"+val);
}
},
_loop = function () {
if(isLoop)return;
isLoop = true;
var ret = 0;
$("#circle").text(++countLoop);
nextArray = _deepCopy(matArray);
if(!option.noColor && option.noHoldExt)allNodes.removeClass("loop");
if(!option.noColor)allNodes.removeClass("curloop");
else allNodes.attr("class", "");
for(var i = 0;i<option.size.x;i++) {
for(var j = 0;j<option.size.y;j++) {
if(_getMat(i, j)<option.threshold)continue;
if(i>0)
nextArray[i-1][j] += 1 , nextArray[i][j] -= 1;
else if( !option.isClose ) nextArray[i][j] -= 1;
if(j>0)
nextArray[i][j-1] += 1 , nextArray[i][j] -= 1;
else if( !option.isClose ) nextArray[i][j] -= 1;
if(i<option.size.x-1)
nextArray[i+1][j] += 1 , nextArray[i][j] -= 1;
else if( !option.isClose ) nextArray[i][j] -= 1;
if(j<option.size.y-1)
nextArray[i][j+1] += 1 , nextArray[i][j] -= 1;
else if( !option.isClose ) nextArray[i][j] -= 1;
}
}
for(var i = 0;i<option.size.x;i++) {
for(var j = 0;j<option.size.y;j++) {
if( nextArray[i][j] != _getMat(i, j) ) {
_setMat(i, j, nextArray[i][j]);
if(!option.noColor)_getNode(i, j).addClass("loop").addClass("curloop");
else _getNode(i, j).attr("class", "loop");
}
ret += (_getMat(i, j)>= option.threshold);
}
}
if(ret === 0) {
isLock = false;
clearInterval(timerLoop);
}
isLoop = false;
};
return {
init: function (o) {
option = $.extend({}, option, o);
nodesContainer = $(option.target);
matArray = [];
for(var i = 0;i<option.size.x;i++) {
matArray.push(new Array(option.size.y));
for(var j = 0;j<option.size.y;j++)
matArray[i][j] = 0;
}
this.build();
},
build: function () {
var html = '', temp = _getTemplate(option.template), thtml = '';
for(var j = 0;j<option.size.y;j++) {
thtml = '';
for(var i = 0;i<option.size.x;i++)
thtml += temp.item.format(i, j, 0);
html += temp.line.format(j, thtml);
}
nodesContainer.append(html);
allNodes = nodesContainer.find("li div");
},
start: function () {
if(runState) {return; }
if(isStep) {return; }
runState = true;
isStep = true;
void function () {
isLock = true;
isLoop = false;
countLoop = 0;
timerLoop = setInterval(_loop, option.speed);
}();
timerStep = setInterval(function () {
if(isLock)return;
$("#times").text(countStep++);
if(!option.noColor)allNodes.removeClass("act").removeClass("loop").removeClass("curloop");
else allNodes.attr("class", "");
if(!option.noColor && !option.noHoldExt)allNodes.removeClass("loop").removeClass("curloop");
var r = {x: 0, y: 0} , cur; r.x = _randomNum(-1, option.size.x); r.y = _randomNum(-1, option.size.y);
cur = _getNode(r.x, r.y);
_setMat(r.x, r.y, _getMat(r.x, r.y)+1);
cur.addClass("act");
if( _getMat(r.x, r.y) >= option.threshold )
{
isLock = true;
countLoop = 0;
isLoop = false;
timerLoop = setInterval(_loop, option.speed);
}
else{isLock = false; }
isStep = false;
if(countLoop>1)console.log("step: "+countStep+";circle: "+countLoop+";");
}, option.stepspeed);
},
nextStep: function () {
this.pause();
isLock = true;
void function () {
isLoop = false;
_loop();
}();
void function () {
if(isLock)return;
$("#times").text(countStep++);
if(!option.noColor)allNodes.removeClass("act");
else allNodes.attr("class", "");
if(!option.noColor && !option.noHoldExt)allNodes.removeClass("loop").removeClass("curloop");
var r = {x: 0, y: 0} , cur; r.x = _randomNum(-1, option.size.x); r.y = _randomNum(-1, option.size.y);
cur = _getNode(r.x, r.y);
_setMat(r.x, r.y, _getMat(r.x, r.y)+1);
cur.addClass("act");
isLock = false;
}();
},
pause: function () {
runState = false;
isLock = false;
isLoop = false;
isStep = false;
clearInterval(timerStep);
clearInterval(timerLoop);
},
setV: function (val) {
var ts;
if(runState) {ts = true;runState = false; }
for(var i = 0;i<option.size.x;i++)
for(var j = 0;j<option.size.y;j++)
_setMat(i, j, val);
if(ts)runState = true;
},
setRandom: function () {
var ts;
if(runState) {ts = true;runState = false; }
for(var i = 0;i<option.size.x;i++)
for(var j = 0;j<option.size.y;j++)
_setMat(i, j, _randomNum(-1, 5));
if(ts)runState = true;
},
runState: function () {return runState; },
setOption: function (opt,val) { option[opt] = val ? true : false; },
getOption: function (opt) { return option[opt]; }
};
}});
})(window, jQuery);
(function (window, $, undefined) {
$(document).ready(function () {
var t = $.CA();
t.init({speed: 10, stepspeed: 10, size: {x: 40, y: 40}, isClose: true, noHoldExt: false, noColor: false});
$("#run-check").on("click", function () {
if(t.runState() === false)
t.start(), $(this).val("Stop");
else
t.pause(), $(this).val("Start");
});
$("#run-next").on("click", function () {
t.nextStep(), $("#run-check").val("Start");
});
$(".ca_tools .check").each(function () {
var self = $(this) , val = t.getOption( self.data("fn") );
val === true ? self.attr("checked","checked") : self.removeAttr("checked");
});
$(".ca_tools .check").on("click",function () {
var self = $(this);
t.setOption( self.data("fn") , self.attr("checked") );
});
$("#set-val-4").on("click", function () {t.setV(4); });
$("#set-val-3").on("click", function () {t.setV(3); });
$("#set-val-2").on("click", function () {t.setV(2); });
$("#set-val-1").on("click", function () {t.setV(1); });
$("#set-val-rnd").on("click", function () {t.setRandom(); });
});
})(window, jQuery);
|
self.assetsManifest = {
"assets": [
{
"hash": "sha256-BHNhq10T\/9aejlrFEhS\/NYeYS3Djwv\/pqg2xUjQCx\/s=",
"url": "css\/app.css"
},
{
"hash": "sha256-rldnE7wZYJj3Q43t5v8fg1ojKRwyt0Wtfm+224CacZs=",
"url": "css\/bootstrap\/bootstrap.min.css"
},
{
"hash": "sha256-xMZ0SaSBYZSHVjFdZTAT\/IjRExRIxSriWcJLcA9nkj0=",
"url": "css\/bootstrap\/bootstrap.min.css.map"
},
{
"hash": "sha256-jA4J4h\/k76zVxbFKEaWwFKJccmO0voOQ1DbUW+5YNlI=",
"url": "css\/open-iconic\/FONT-LICENSE"
},
{
"hash": "sha256-BJ\/G+e+y7bQdrYkS2RBTyNfBHpA9IuGaPmf9htub5MQ=",
"url": "css\/open-iconic\/font\/css\/open-iconic-bootstrap.min.css"
},
{
"hash": "sha256-OK3poGPgzKI2NzNgP07XMbJa3Dz6USoUh\/chSkSvQpc=",
"url": "css\/open-iconic\/font\/fonts\/open-iconic.eot"
},
{
"hash": "sha256-sDUtuZAEzWZyv\/U1xl\/9D3ehyU69JE+FvAcu5HQ+\/a0=",
"url": "css\/open-iconic\/font\/fonts\/open-iconic.otf"
},
{
"hash": "sha256-+P1oQ5jPzOVJGC52E1oxGXIXxxCyMlqy6A9cNxGYzVk=",
"url": "css\/open-iconic\/font\/fonts\/open-iconic.svg"
},
{
"hash": "sha256-p+RP8CV3vRK1YbIkNzq3rPo1jyETPnR07ULb+HVYL8w=",
"url": "css\/open-iconic\/font\/fonts\/open-iconic.ttf"
},
{
"hash": "sha256-cZPqVlRJfSNW0KaQ4+UPOXZ\/v\/QzXlejRDwUNdZIofI=",
"url": "css\/open-iconic\/font\/fonts\/open-iconic.woff"
},
{
"hash": "sha256-aF5g\/izareSj02F3MPSoTGNbcMBl9nmZKDe04zjU\/ss=",
"url": "css\/open-iconic\/ICON-LICENSE"
},
{
"hash": "sha256-p\/oxU91iBE+uaDr3kYOyZPuulf4YcPAMNIz6PRA\/tb0=",
"url": "css\/open-iconic\/README.md"
},
{
"hash": "sha256-qU+KhVPK6oQw3UyjzAHU4xjRmCj3TLZUU\/+39dni9E0=",
"url": "favicon.ico"
},
{
"hash": "sha256-IpHFcQvs03lh6W54zoeJRG1jW+VnGmwymzxLoXtKX7Y=",
"url": "icon-512.png"
},
{
"hash": "sha256-rcP0ry+52ORKL\/QdnzAH2lrQJYgZllZB8NdWfQdMJxc=",
"url": "index.html"
},
{
"hash": "sha256-XayvQ6lN2g+DwvVevrf8x5VwkK7PsSNvzUhI6sbsGQU=",
"url": "manifest.json"
},
{
"hash": "sha256-yzFf+O\/mlH+Q9klUSqXP2kxGKOUFLPxaww8da8fKhGU=",
"url": "sample-data\/weather.json"
},
{
"hash": "sha256-8Gz3znEA7zTdL3zSEHWe+lTcpMiUk4R9iB9XH5M+qUY=",
"url": "_framework\/_bin\/InvestUtils.dll"
},
{
"hash": "sha256-aAeZ2dwG4Cd57CAdGjPH7W9of+sb6iHdPIHFsSX\/YQo=",
"url": "_framework\/_bin\/Microsoft.AspNetCore.Components.dll"
},
{
"hash": "sha256-vVy28zXTx1TEKZRVK9OzonxDxEPK3ymTkIHEc1Sa4p8=",
"url": "_framework\/_bin\/Microsoft.AspNetCore.Components.Web.dll"
},
{
"hash": "sha256-n3EYxlXymYa+o4feoGvPqm4QJaK9jmwEl+Az2vroFk4=",
"url": "_framework\/_bin\/Microsoft.AspNetCore.Components.WebAssembly.dll"
},
{
"hash": "sha256-jzHgXWAvWMkKIGFjZoT84tbe72E+H7CvTr\/Dryh4QPs=",
"url": "_framework\/_bin\/Microsoft.Bcl.AsyncInterfaces.dll"
},
{
"hash": "sha256-DDzBFhx1fuyxKFN5PH9Ikz7SJrVg06hWkKo9rYYf8KY=",
"url": "_framework\/_bin\/Microsoft.Extensions.Configuration.Abstractions.dll"
},
{
"hash": "sha256-lpNUf5CzZOivM4xFDXeuoNz+8o7jRPNOBP8864eG2Z4=",
"url": "_framework\/_bin\/Microsoft.Extensions.Configuration.dll"
},
{
"hash": "sha256-iz8CBebuDJZwW40RCK8\/4B3tjvx4oteJ82T9s4xa6lo=",
"url": "_framework\/_bin\/Microsoft.Extensions.Configuration.Json.dll"
},
{
"hash": "sha256-GiiP3WjBZri38DK5hLIBqOHpI+P4n9FTqNoYIWrrwR4=",
"url": "_framework\/_bin\/Microsoft.Extensions.DependencyInjection.Abstractions.dll"
},
{
"hash": "sha256-zzydQ4cuCzOx\/welBM0sdm8SVk9eRyJeZoZLoYMJt0o=",
"url": "_framework\/_bin\/Microsoft.Extensions.DependencyInjection.dll"
},
{
"hash": "sha256-qhh5caBDJeBuNsoO6SQ95UXUVXJZnbOZzYbAFM+YngE=",
"url": "_framework\/_bin\/Microsoft.Extensions.Logging.Abstractions.dll"
},
{
"hash": "sha256-6T\/QC2V8OhjXeBQuVi+7Qjlc22pd5pRE3OKg4ciVAh8=",
"url": "_framework\/_bin\/Microsoft.Extensions.Logging.dll"
},
{
"hash": "sha256-0CVcL1yANiR6\/oZqPhCGB1jf+c9i9RPF00KL9MNtEOs=",
"url": "_framework\/_bin\/Microsoft.Extensions.Options.dll"
},
{
"hash": "sha256-xe6TgwIQV0GwcY4blX89uBUJznAHp78n22OBqTQk8wI=",
"url": "_framework\/_bin\/Microsoft.Extensions.Primitives.dll"
},
{
"hash": "sha256-3cbvJEo8k8VJVQwyEZWWQ6yGRFQW8\/219DaOnmsX3e4=",
"url": "_framework\/_bin\/Microsoft.JSInterop.dll"
},
{
"hash": "sha256-zV\/OfJNfNsG404X30Pwkdymdh1KmZpTVEmG\/JNFVc\/k=",
"url": "_framework\/_bin\/Microsoft.JSInterop.WebAssembly.dll"
},
{
"hash": "sha256-x2U6Iv+nDpLctcR0JCNXvlzrqFvMNMfg7aqoAMjtIWc=",
"url": "_framework\/_bin\/mscorlib.dll"
},
{
"hash": "sha256-GcY9BeAHq6lkt\/eUMbVX6uPZNChMyYlzVXMjbSgmS5k=",
"url": "_framework\/_bin\/System.Core.dll"
},
{
"hash": "sha256-GF9+JotIicCXvxK9iteQ1wGsR99ukZt656CIBF55lWQ=",
"url": "_framework\/_bin\/System.dll"
},
{
"hash": "sha256-Ohrf7kg7bMd6Vb3latk5utGYHJyVW7AfDNgBN1CTKBE=",
"url": "_framework\/_bin\/System.Net.Http.dll"
},
{
"hash": "sha256-JPvzV7+jljH8kyK1jrUw5FxvpVyHhsPPYAwP5apOzTM=",
"url": "_framework\/_bin\/System.Net.Http.Json.dll"
},
{
"hash": "sha256-AGTi8uHywuoQNm6fA\/cqgcPzePF1ol6Em5Cey0UuH58=",
"url": "_framework\/_bin\/System.Net.Http.WebAssemblyHttpHandler.dll"
},
{
"hash": "sha256-FVCwv7hk5JiHJR3+3lw+CM8g1vjNUs8ZpmVdrCUm4Mc=",
"url": "_framework\/_bin\/System.Runtime.CompilerServices.Unsafe.dll"
},
{
"hash": "sha256-JRAkWCxUL1UfUrlmN2KYUgwXzBf0nEXH9mLjwQzZSRg=",
"url": "_framework\/_bin\/System.Text.Encodings.Web.dll"
},
{
"hash": "sha256-sEhHzRa38HVHYzGwDEMxWcIgLXu3sF2r8+\/b+Ed\/jsA=",
"url": "_framework\/_bin\/System.Text.Json.dll"
},
{
"hash": "sha256-cgQGNp2mn\/ayTPwJ1hA9ixTTxVdx36YG8xyD4OobIBw=",
"url": "_framework\/_bin\/WebAssembly.Bindings.dll"
},
{
"hash": "sha256-mPoqx7XczFHBWk3gRNn0hc9ekG1OvkKY4XiKRY5Mj5U=",
"url": "_framework\/wasm\/dotnet.3.2.0.js"
},
{
"hash": "sha256-3S0qzYaBEKOBXarzVLNzNAFXlwJr6nI3lFlYUpQTPH8=",
"url": "_framework\/wasm\/dotnet.timezones.dat"
},
{
"hash": "sha256-UC\/3Rm1NkdNdlIrzYARo+dO\/HDlS5mhPxo0IQv7kma8=",
"url": "_framework\/wasm\/dotnet.wasm"
},
{
"hash": "sha256-SPHS1EAPAcMFN4TEIUYl3FWtoCQTsNJch0XVGgok1eE=",
"url": "_framework\/blazor.webassembly.js"
},
{
"hash": "sha256-LpZ3en7W8tWQDJtVU9GMtBQILBMT4PszbdwHutBh4\/8=",
"url": "_framework\/blazor.boot.json"
}
],
"version": "aCB+lSpC"
};
|
angular
.module('MainApp')
.controller('MainController', ['$scope', '$rootScope','$location', 'MainService', MainController]);
function MainController($scope, $rootScope, $location, MainService) {
// ****variable declaration*****
$scope.lists=[];
// Function Declaration
$scope.getlists = function () {
$scope.loading=true;
MainService.getlists().then(function (result) {
if (result.data) {
$scope.lists = result.data;
$scope.loading=false;
}
}, function (error) {
});
}
$scope.addList = function(){
$scope.addListItem = true;
}
$scope.addingList = function(listName){
$scope.lists.push({"id":$scope.lists.length+1,"listName":listName,"cardTitles":[]});
$scope.addListItem = false;
}
$scope.addCard = function(index){
$scope.lists[index].addItem = true;
}
$scope.edittedCard=function(listName,index,cardName){
var listIndex = $scope.validateIndex(listName, index,cardName);
if(listIndex !=-1){
$scope.lists[listIndex].cardTitles[index].updateItem = true;
}
}
$scope.updateCard = function(listName, index,cardName){
var listIndex = $scope.validateIndex(listName,index,cardName);
if(listIndex != -1){
$scope.lists[listIndex].cardTitles[index].updateItem = false;
$scope.lists[listIndex].cardTitles[index].title=cardName;
}
}
$scope.removeItem = function(listName, index){
var listIndex = $scope.validateIndex(listName, index);
if(listIndex != -1){
$scope.lists[listIndex].cardTitles.splice(index,1);
}
}
$scope.validateIndex=function(listName, index,cardName){
for(let i=0;i<$scope.lists.length ;i++){
if($scope.lists[i].listName == listName){
return i;
break;
}
}
}
$scope.closeItem = function(listName,index,cardName){
var listIndex = $scope.validateIndex(listName, index,cardName);
if(listIndex != -1){
$scope.lists[listIndex].cardTitles[index].updateItem = false;
}
}
$scope.addingCard = function(index,cardName){
if(cardName){
$scope.lists[index].cardTitles.push({title:cardName});
$scope.lists[index].addItem= false;
}
else{
return;
}
}
$scope.closeUpdate= function(index){
$scope.lists[index].addItem= false;
}
$scope.getlists();
};
|
(function($) {
$('.mobile-primary-menu a').click(function () {
if ($('#primary-menu').find('ul.mobile-primary-menu').length > 0) {
$('ul.mobile-primary-menu').toggleClass("show");
}
});
})(jQuery);
|
const router = require('express').Router()
const {catchErrors} = require('../handlers/errorHandlers')
const chatroomController = require('../controllers/chatroomController')
const auth = require('../middlewares/auth')
router.post("/",auth,catchErrors(chatroomController.createChatroom))
router.get("/",auth,catchErrors(chatroomController.getAllChatrooms))
module.exports = router;
|
export default class servicePartie {
constructor(dataService, $rootScope) {
this.dataService = dataService;
this.partie = {tourJoueur : 1, message : "Lancez les dés"};
this.goNextStep = false;
this.$rootScope = $rootScope;
this.$rootScope.$on('nfcEvent', function() {
console.log('NFC EVENT');
});
}
getPartie(){
return this.partie;
}
lancerDes(){
//Faire des nombres aléatoires + déplacer joueur
//while(this.goNextStep == false){
this.dataService.readNfc()
.then((data) => {
console.log(data.data);
if (data.data == "code nfc de"){
//tirage de
this.de1 = 2;
this.de2 = 1;
this.partie.message = "De 1 = "+ this.de1 + " De 2 = "+ this.de2;
}
})
.catch((error) => {
console.log(error);
});
//}
}
lanceTour(){
this.lancerDes();
}
listen2nfc(){
this.dataService.readNfc()
.then((data) => {
this.$rootScope.$broadcast('nfcEvent');
console.log(data.data);
})
.catch((error) => {
console.log(error);
});
}
/*$rootScope.$on('nfcEvent', function() {
console.log('NFC EVENT');
})*/
bougeJoueur(){
}
}
servicePartie.$inject = ['dataService', '$rootScope'];
|
/**
* 更新 package.json 版本号
*/
const fetch = require("node-fetch");
//const md5 = require("js-md5");
const fs = require("fs");
const getVersion = async() => {
const latestVersion = await fetch("https://registry.npmjs.org/muggledy-blog-html/latest").then(res => res.json()).then(res => {
return res.version;
})
return latestVersion;
}
const update = async() => {
const version = await getVersion();
var verArray = version.split(".");
//verArray[2] = verArray[2].split("-")[0];
if (verArray[2] < 99) {
verArray[2] = String(Number(verArray[2])+1);
} else if (verArray[1] < 99) {
verArray[1] = String(Number(verArray[1])+1);
verArray[2] = 0;
} else {
verArray[0] = String(Number(verArray[0])+1);
verArray[1] = 0;
verArray[2] = 0;
}
var newVersion = `${verArray[0]}.${verArray[1]}.${verArray[2]}`
//var newVersion = newVersion + "-" + md5(`${new Date().getTime()}${newVersion}`);
console.log(newVersion);
var packageJson = fs.readFileSync("./package.json");
packageJson = JSON.parse(packageJson);
packageJson.version = newVersion;
var newPackage = JSON.stringify(packageJson);
fs.writeFileSync("./package.json", newPackage);
console.log("Complete!!");
}
update();
|
<script>alert('This is a test!');</script>
|
var particles = [];
// create 15 particles
for( var i = 0; i < 15; i++ ) {
particles.push( {
x:Math.random()*window.innerWidth, //Math.randome() returns a floating point in range [0,1).
y:Math.random()*window.innerHeight,
vx:(Math.random()*2)-1,
vy:(Math.random()*2-1),
history: [],
size: 4+Math.random()*6,
//color = random > 0.5 ? "black": random > 0.5 ? "red": "yellow"
color: Math.random() > .5 ? "#ffffff" : Math.random() > .5 ? "#FF0000" : "#FFFF00"
} );
}
var mouse = { x: 0, y: 0 };
var canvas = document.getElementById('canvas');
if (canvas && canvas.getContext) {
var context = canvas.getContext('2d');
Initialize();
}
function Initialize() {
canvas.addEventListener('mousemove', MouseMove, false);
window.addEventListener("scroll", MouseScroll,false);
window.addEventListener('resize', ResizeCanvas, false);
setInterval( TimeUpdate, 20 ); // velocity : lower number = faster speed
context.beginPath();
ResizeCanvas();
}
function TimeUpdate(e) {
context.clearRect(0, 0, window.innerWidth, window.innerHeight);
for( var i = 0; i < particles.length; i++ ) {
particles[i].x += particles[i].vx;
particles[i].y += particles[i].vy;
if( particles[i].x > window.innerWidth ) {
particles[i].vx = -1-Math.random();
}
else if ( particles[i].x < 0 ) {
particles[i].vx = 1+Math.random();
}
else {
particles[i].vx *= 1 + (Math.random()*0.005);
}
if( particles[i].y > window.innerHeight ) {
particles[i].vy = -1-Math.random();
}
else if ( particles[i].y < 0 ) {
particles[i].vy = 1+Math.random();
}
else {
particles[i].vy *= 1 + (Math.random()*0.005);
}
context.strokeStyle = particles[i].color;
context.beginPath();
for( var j = 0; j < particles[i].history.length; j++ ) {
context.lineTo( particles[i].history[j].x, particles[i].history[j].y );
}
context.stroke();
particles[i].history.push({ x: particles[i].x, y: particles[i].y });
if( particles[i].history.length > 45 ) {
particles[i].history.shift();
}
var distanceFactor = DistanceBetween( mouse, particles[i] );
distanceFactor = Math.max( Math.min( 15 - ( distanceFactor / 10 ), 10 ), 1 );
// fill color
context.fillStyle = particles[i].color;
//show as a line
context.beginPath();
//make circle at the beginning of the path
context.arc(particles[i].x,particles[i].y,particles[i].size*distanceFactor,0,Math.PI*2,true);
context.closePath();
context.fill();
}
}
// when user move mouse near the particles
function MouseMove(e) {
mouse.x = e.layerX;
mouse.y = e.layerY;
addText();
}
function addText(){
context.font="20px Verdana";
// Create gradient
var gradient=context.createLinearGradient(0,0,window.innerWidth,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");
// Fill color with gradient
context.fillStyle=gradient;
// Fill text
context.fillText("JavaScript",particles[0].x-50,particles[0].y);
context.fillText("CSS",particles[1].x-23,particles[1].y);
context.fillText("HTML5",particles[2].x-30,particles[2].y);
context.fillText("Bootstrap",particles[3].x-50,particles[3].y);
context.fillText("AngularJs",particles[4].x-50,particles[4].y);
context.fillText("PHP",particles[5].x-25,particles[5].y);
context.fillText("Node.js",particles[6].x-35,particles[6].y);
context.fillText("Meteor",particles[7].x-30,particles[7].y);
context.fillText("jQuery",particles[8].x-30,particles[8].y);
context.fillText("WordPress",particles[9].x-50,particles[9].y);
context.fillText("Java",particles[10].x-25,particles[10].y);
context.fillText("MySQL",particles[11].x-30,particles[11].y);
context.fillText("Photoshop",particles[12].x-50,particles[12].y);
context.fillText("CSS3",particles[13].x-30,particles[13].y);
context.fillText("AWS",particles[14].x-25,particles[14].y);
}
function MouseScroll(e) {
addText();
}
function Draw( x, y ) {
context.strokeStyle = '#ff0000';
context.lineWidth = 4;
context.lineTo(x, y);
context.stroke();
}
function ResizeCanvas(e) {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
function DistanceBetween(p1,p2) {
var dx = p2.x-p1.x;
var dy = p2.y-p1.y;
return Math.sqrt(dx*dx + dy*dy);
}
|
/*
* @Description:
* @Author: rodchen
* @Date: 2020-11-01 18:02:20
* @LastEditTime: 2020-11-01 18:06:58
* @LastEditors: rodchen
*/
import { request as sulaRequest } from 'sula';
// sula的请求配置
sulaRequest.use({
bizRequestAdapter: (requestConfig) => {
// eslint-disable-next-line no-param-reassign
requestConfig.url = `https://www.easy-mock.com/mock/5f9e6df90bf9ee0300940a04${ requestConfig.url}`
return requestConfig;
},
});
|
/**
* logic line-523:cookie can't set punctuation ";". Fix it;
* logic line-367:setAttr isn't action.
*/
/**
* Create By
* 2014-12-1 16:48:11
* Last Modify
* 2015-4-20 16:48:11
* http://www.iWuYc.com/
* @author iWuYc
* Version:1.0.1
* @Charset UTF-8
*/
/**
* namespace List:
* iWuYc
* iWuYc.Methods
* iWuYc.Methods.Unit
* iWuYc.Methods.Unit.DateUnit
* iWuYc.Methods.Unit.StringUnit
* iWuYc.Methods.Unit.NumberUnit
* iWuYc.Methods.Unit.DomUnit
* iWuYc.Methods.Unit.ObjectUnit
* iWuYc.Methods.Unit.JSONUnit
* iWuYc.Methods.Unit.EventUnit
* iWuYc.Methods.Unit.CookiesUnit
* iWuYc.Methods.Unit.MD5Unit
*
*/
/**
* Contants Definition
*/
var isPrint = true;
(function (window) {
var iWuYc = {
Constants: {
defaultMethodsNamespace: "iWuYc.Methods"
},
Methods: {
/**
* Description:
* unit tools methods.
*/
Unit: {
/**
* Description:
* date tools methods.
* Namespace:
* iWuYc.Methods.Unit.DateUnit
*/
DateUnit: {
/**
* Paramter:
* date:<Date> the date is what you want to format object.
* fmt:<String> the fmt is date format style.
* Return:
* returnVal:<String> return a formatted string.
* Description:
* format date method:
* {year}→{y} {quarter}→{q} {month}→{M} {day}→{d} {hour}→{h:12h,H:24h}
* {A.M,P.M}→{XX} {minute}→{m} {second}→{s} {weekDay EN}→{w} {weekDay CHN}→{W}
*/
DateFormat: function (date, fmt) {
if (!(date instanceof Date)) {
throw "It's not a date type,can't format this object.Check it and try again,please.";
};
var o = {
"M+": date.getMonth() + 1, //month
"d+": date.getDate(), //day
"H+": date.getHours(), //hour 24H type
"m+": date.getMinutes(), //minute
"s+": date.getSeconds() //seconde
};
var w = {
0: "Sunday",
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday"
};
var W = {
0: "星期天",
1: "星期一",
2: "星期二",
3: "星期三",
4: "星期四",
5: "星期五",
6: "星期六"
}
var Q = {
1: "春",
2: "夏",
3: "秋",
4: "冬"
}
var q = {
1: "spring",
2: "summer",
3: "autumn",
4: "winter"
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
if (/(h+)/.test(fmt)) {//12H type
var hour = date.getHours();
var h = hour < 12 ? hour : hour - 12;
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (h) : (("00" + h).substr(("" + h).length)));
if (new RegExp("(XX)").test(fmt)) {
var tmp = hour < 12 ? "AM" : "PM";
fmt = fmt.replace(RegExp.$1, tmp);
}
}
if (/(S+)/.test(fmt)) {
var millisecond = date.getMilliseconds() + "";
var matchStr = RegExp.$1;
var targetStr = "";
switch (matchStr.length) {
case 1:
targetStr = millisecond.substr(0, 1);
break;
case 2:
var tmp = millisecond.substr(0, 2);
targetStr = tmp.length < 2 ? "0" + tmp : tmp;
break;
case 3:
var tmp = millisecond.substr(0, 3);
targetStr = tmp.length < 2 ? "00" + tmp : (tmp.length < 3 ? "0" + tmp : tmp);
break;
}
fmt = fmt.replace(matchStr, targetStr);
}
if (/(w+)/.test(fmt)) {
var weekDay = date.getDay();
fmt = fmt.replace(RegExp.$1, w[weekDay]);
}
if (/(W+)/.test(fmt)) {
var weekDay = date.getDay();
fmt = fmt.replace(RegExp.$1, W[weekDay]);
}
if (/(q+)/.test(fmt)) {
var quarter = Math.floor((date.getMonth() + 3) / 3);
fmt = fmt.replace(RegExp.$1, q[quarter]);
} else if (/(Q+)/.test(fmt)) {
var quarter = Math.floor((date.getMonth() + 3) / 3);
fmt = fmt.replace(RegExp.$1, Q[quarter]);
}
return fmt;
}
},
/**
* Description:
* String tools units
* Namespace:
* iWuYc.Methods.Unit.StringUnit
*/
StringUnit: {
/**
* Paramter:
* str:<String> The str is what you want to judge.
* Return:
* returnVal:<Boolean> return true if str is not empty else return false.
* Description:
* judg string is empty or not.
*/
isNotEmpty: function (str) {
return (str === null || typeof str === "undefined" || str === "" || iWuYc.Methods.Unit.StringUnit.trim(str) === "") ?
false : true;
},
/**
* Paramter:
* str:<String> The str is what you want to judge.
* Return:
* returnVal:<Boolean> return false if str is not empty else return true.
* Description:
* judg string is empty or not.
*/
isEmpty: function (str) {
return (str === null || typeof str === "undefined" || str === "" || iWuYc.Methods.Unit.StringUnit.trim(str) === "") ?
true : false;
},
/**
* Paramter:
* str:<String> The str is what you want to trim.This method will trim behind and
*/
trim: function (str) {
if (str === null || typeof str === "undefined" || str === "") {
return str;
};
var result = str.replace(/(^\s*)|(\s*$)/g, "");
return result;
},
trimLeft: function (str) {
if (str === null || typeof str === "undefined" || str === "") {
return str;
};
var result = str.replace(/(^\s*)/g, "");
return result;
},
trimRight: function (str) {
if (str === null || typeof str === "undefined" || str === "") {
return str;
};
var result = str.replace(/(\s*$)/g, "");
return result;
},
replaceAll: function (str, sourceStr, targetStr) {
iWuYc.setConstants('sUnit', 'iWuYc.Methods.Unit.StringUnit');
var isNotEmpty = iWuYc.getMethod('isNotEmpty', 'sUnit');
if (!isNotEmpty(str) || !isNotEmpty(sourceStr)) {
return;
}
targetStr = isNotEmpty(targetStr) ? targetStr : "";
var regExp = "/(" + sourceStr + ")/g"
var exp = eval(regExp);
var result = str.replace(exp, targetStr);
return result;
},
encodeURI: function (str) {
return encodeURI(str);
},
decodeURI: function (str) {
return decodeURI(str);
},
validate: function (str, regExpObj) {
var typeStr = Object.prototype.toString.call(regExpObj).toLowerCase();
if (typeStr === "[object regexp]") {
return regExpObj.test(str);
} else {
throw "regExpObj is not RegExp!check it and try again!";
}
}
},
/**
* Namespace:
* iWuYc.Methods.Unit.NumberUnit
*/
NumberUnit: {
isNumber: function (val) {
return (val !== null && typeof val !== undefined && val !== "" && !isNaN(val));
}
},
/**
* Namespace:
* iWuYc.Methods.Unit.DomUnit
*/
DomUnit: {
/**
* Paramter:
* domName:<String> The dom's tagName that you want create.
* attrJson:<JSON> The attrJson string that be will create tag's attribute.
* content:<String> The dom's innerText.
* Return:
* returnVal:<String> return a dom's string.
* Description:
* Create a new dom by domName and attrJson and content.
*
*/
mkDom: function (domName, attrJson, content) {
iWuYc.setConstants('sUnit', 'iWuYc.Methods.Unit.StringUnit');
var isNotEmpty = iWuYc.getMethod('isNotEmpty', 'sUnit');
if (!isNotEmpty(domName)) {
return;
}
var newDom = "<" + domName;
content = isNotEmpty(content) ? content : "";
iWuYc.setConstants('jUnit', 'iWuYc.Methods.Unit.JSONUnit');
var isJSON = iWuYc.getMethod('isJSON', 'jUnit');
var attr = "";
if (isJSON(attrJson)) {
for (var key in attrJson) {
attr = attr + " " + key + "=\"" + attrJson[key] + "\"";
}
} else if (!isNotEmpty(content)) {//Change attrJson to content if attrJson is not JSON and content is empty.
content = attrJson;
} else {//Throw a error if attrJson is not JSON and content is not empty.
throw "The seconde paramter is not json or content.";
}
newDom = newDom + attr + " >" + content + "</" + domName + ">";
return newDom;
},
/**
* Paramter:
* insertField:<DOM> inseterField is what you want to insert word into area.
* insertVal:<String> insertVal is what you want to insert word.
* Return:
* not return val.
* Description:
* Insert 'insertVal' into insertField of dom where is cursor location.
*/
insertAtCursor: function (insertField, insertVal) {
if (document.selection) {//IE support
insertField.focus();
sel = document.selection.createRange();
sel.text = insertVal;
sel.select();
} else if (insertField.selectionStart || insertField.selectionStart == '0') {//MOZILLA/NETSCAPE support
var startPos = insertField.selectionStart;
var endPos = insertField.selectionEnd;
// save scrollTop before insert
var restoreTop = insertField.scrollTop;
insertField.value = insertField.value.substring(0, startPos) + insertVal + insertField.value.substring(endPos, insertField.value.length);
if (restoreTop > 0) {// restore previous scrollTop
insertField.scrollTop = restoreTop;
}
insertField.focus();
insertField.selectionStart = startPos + insertVal.length;
insertField.selectionEnd = startPos + insertVal.length;
} else {
insertField.value += insertVal;
insertField.focus();
}
},
/**
* Paramter:
* obj:<DOM>The object is what you want to judge.
* Return:
* returnVal:<boolean> if the object is dom then return true,else return false.
* Description:
* To Judge object is dom or not.
*/
isDom: function (obj) {
var typeStr = $i.typeOf(obj);
return $i(typeStr).validate(/[object html[a-z]*element]/);
},
//TODO2
getElemetById: function (selector, dom) {
if (!!!dom) {
throwError(selector,isPrint);
return document.getElementById(selector);
} else {
throwError(selector + " " + $i.typeOf(dom),isPrint);
}
},
getElementsByClassName: function (dom, selector) {
if (!!document.getElementsByClassName) {
return document.getElementsByClassName(selector);
} else {
var array = new Array();
}
},
getAttr: function (dom, attrName) {
var attrObj = iWuYc.Methods.Unit.DomUnit.getAttrObj(dom, attrName);
return attrObj && attrObj.value;
},
getAttrObj: function (dom, attrName) {
if (!$i.isDom(dom)) {
throw "It's not a Dom.Check and try again."
}
if (attrName === null || $i.typeOf(attrName) !== "[object string]") {
throw "attrName is wrong.Check and try again."
}
var attributes = dom.attributes;
var attribute = attributes[attrName];
return attribute;
}, setAttr: function (dom, attrName, attrVal) {
if (!$i.isDom(dom)) {
throw "It's not a Dom.Check and try again."
}
if (attrName === null || $i.typeOf(attrName) !== "[object string]") {
throw "attrName is wrong.Check and try again."
}
if (attrVal === null || $i.typeOf(attrVal) !== "[object string]") {
throw "attrVal is wrong.Check and try again."
}
var comm = "var attrObj = dom.attributes['" + attrName + "'] = { value : '" + attrVal + "'}";
eval(comm);
},
setAttrObj: function (dom, attrObj) {
}
},
/**
* Namespace:
* iWuYc.Methods.Unit.ObjectUnit
*/
ObjectUnit: {
toString: function (obj) {
if (typeof obj !== 'object') {
return obj;
}
var str = obj.toString();
if (str != "[object Object]") {
return str;
}
if (obj instanceof Date) {
iWuYc.setConstants('dUnit', 'iWuYc.Methods.Unit.DateUnit');
var method = iWuYc.getMethod('DateFormat', 'dUnit');
return method(obj, 'yyyy-MM-dd hh:mm:ss');
}
str = "";
for (var key in obj) {
str = str + key + ":" + obj[key] + ",";
}
return str.substr(0, str.lastIndexOf(','));
}
},
/**
* Namespace:
* iWuYc.Methods.Unit.JSONUnit
*/
JSONUnit: {
/**
* Paramter:
* obj:<Object> The obj is taget that you want you judge.
* Return:
* returnVal:<Boolean> return true if obj was JSON object otherwise false.
* Description:
* Judge a Object is JSON object or not.
*/
isJSON: function (obj) {
isJson = typeof obj === "object" && obj.toString().toLowerCase() === "[object object]" && !obj.length;
return isJson;
},
/**
* Paramter:
* obj:<Object> The obj is taget that you want to turned into other.
* Return:
* returnVal:<Boolean> return json obj.
* Description:
* Turn object into json object.
*/
toJSON: function (obj) {
var json = "{";
for (var attr in obj) {
var o = obj[attr];
var typeStr = typeof o;
if (typeStr === "object") {
o = "new Object(obj['" + attr + "'])";
} else if (typeStr === "string") {
o = "'" + obj[attr] + "'";
}
json = json + attr + ":" + o + ",";
}
if (json.length > 1) {
json = json.substr(0, json.length - 1);
}
json = json + "}";
eval("var obj=" + json);
return obj;
}
},
/**
* Namespace:
* iWuYc.Methods.Unit.EventUnit
*/
EventUnit: {
/**
* Paramter:
* event:<Event> The event is current souce.
* Return:
* returnVal:<Boolean> return current browser event.
* Description:
* Return current browser event.
*/
getEvent: function (event) {
var e = event || window.event;
return e;
},
/**
* Paramter:
* event:<Event> The event is current event souce.
* Return:
* returnVal:<Boolean> return current browser event.
* Description:
* Return current browser event source.
*/
getSource: function (event) {
iWuYc.setConstants("eUnit", "iWuYc.Methods.Unit.EventUnit");
var getEvent = iWuYc.getMethod("getEvent", "eUnit");
var source = event.srcElement || event.target;
return source;
}
},
/**
* Namespace:
* iWuYc.Methods.Unit.CookiesUnit
*/
CookiesUnit: {
/**
* Paramter:
* key:<String> Cookie's key
* val:<String> Cookie's val
* timeout:<Integer> Cookie's live time.
* Description:
* Set val into cookie and live timeout time.
*
*/
setCookie: function (key, val, timeout) {
iWuYc.Methods.Unit.CookiesUnit.removeCookie(key);//Remove it before add.
val = escape(val);//Transcode value first.
var cookie = key + "=" + val + ";";
if (timeout) {
var date = new Date();
date.setTime(date.getTime() + timeout);//30天2592000000=30*24*60*60*1000
cookie = key + "=" + val + "; expires=" + date.toGMTString();
};
document.cookie = cookie;
},
/**
* Paramter:
* key:<String> Cookie's key.
* Return:
* returnVal:<String> Return value get from cookie by key.
* Description:
* Get value from cookie by key.
*
*/
getCookie: function (key) {
var cookie = document.cookie;
var startIndex = cookie.indexOf(key + "=");
var val = "";
if (startIndex > -1) {
var lastIndex = cookie.indexOf(";", startIndex);
lastIndex = lastIndex < 0 ? cookie.length : lastIndex;
val = cookie.substring(startIndex, lastIndex).split("=")[1];
val = unescape(val);
}
return val;
},
/**
* Paramter:
* key:<String> Cookie's key.
* Description:
* Remove cookie by key.
*
*/
removeCookie: function (key) {
var date = new Date();
date.setTime(date.getTime() - 1);
var cookie = key + "=; expires=" + date.toGMTString();
document.cookie = cookie;
}
},
/**
* Namespace:
* iWuYc.Methods.Unit.MD5Unit
*/
MD5Unit: {
}
}
},
/**
* Put the val into windows obj,or get the value by objectDomain when val empty.
*/
getOrCreateObj: function (objectDomain, val) {
var iWuYcObj = window;
var constantsNames = objectDomain.split('.');
for (var item in constantsNames) {
var constantsName = constantsNames[item];
var obj = iWuYcObj[constantsName];
if (!obj) {
obj = {};
iWuYcObj[constantsName] = obj;
}
if (item == constantsNames.length - 1) {
if (val) {
iWuYcObj[constantsName] = val;
} else {
iWuYcObj = iWuYcObj[constantsName];
}
} else {
iWuYcObj = iWuYcObj[constantsName];
}
}
return iWuYcObj;
},
/**
* Put the value into Constants where the keyName is constantsName
*/
setConstants: function (constantsNameStr, val) {
iWuYc.getOrCreateObj("iWuYc.Constants." + constantsNameStr, val);
var obj = iWuYc.getOrCreateObj("iWuYc.Constants." + constantsNameStr);
throwError(JSON.stringify(iWuYc),isPrint);
return iWuYc;
},
/**
* Get the value from Constants by constantsName
*/
getConstants: function (constantsName) {
var objectDomain = "iWuYc.Constants." + constantsName;
var constants = iWuYc.getOrCreateObj(objectDomain);
return constants;
},
/**
* Clean Constants to release space
*/
clsConstants: function () {
iWuYc.Constants = {};
},
/**
* get the method what name is methodName
*/
getMethod: function (methodName, nameSpaceNikename) {
var nameSpace = null;
if (nameSpaceNikename != null && typeof nameSpaceNikename !== undefined) {//get namespace from Constants if nameSpaceNikename is nothingness
nameSpace = iWuYc.getConstants(nameSpaceNikename);
}
if (nameSpace === null) {//get default namespace from Constants if discontaint
nameSpace = iWuYc.getConstants("defaultMethodsNamespace");
}
var comm = nameSpace + "." + methodName;
var method = iWuYc.getOrCreateObj(comm);
return method;
},
/**
* get type from object.
*/
getType: function (obj) {
return Object.prototype.toString.call(obj).toLowerCase();
}
}
function throwError(msg,isPrint) {
if (isPrint) {
console.error(msg);
}
throw msg;
}
var isSelector = function (str) {
if (str.length < 2) {
return false;
}
if (str.indexOf("@") === 0 && str[1] !== "@") {
return true;
}
return false;
}
function instance(obj, paramJson) {
var typeStr = $i.typeOf(obj);//Object.prototype.toString.call(obj).toLowerCase();
if (typeStr === "[object date]") {
return new iDate(obj);
} else if (typeStr === "[object string]") {
if (isSelector(obj)) {
return new iDom(obj);
} else {
return new iString(obj);
}
} else if (typeStr === "[object htmlanchorelement]") {
return new iDom(obj);
} else if (typeStr.indexOf("event") > 0) {
return new iEvent(obj);
} else if (typeStr === "[object function]") {
methodQueue.addMethod(obj, paramJson);
} else if (typeStr == "[object htmlselectelement]") {
throwError("selectelement",isPrint);
return new iSelectorDom(obj);
} else if ($i(typeStr).validate(/\[object html[a-z]*element\]/)) {
//TODO dom节点函数
return new iDom(obj);
}
}
var methodQueue = {
addMethod: function (method, level) {
var comm = "";
if (!!!iWuYc.getConstants("onLoadedMethodQueue")) {
level = !!level ? level : 0;
comm = "var arr={" + level + ":" + method + ",count:1};";
eval(comm);
iWuYc.setConstants("onLoadedMethodQueue", arr);
} else {
var arr = iWuYc.getConstants("onLoadedMethodQueue");
level = !!level ? level : arr.count + 1;
arr[level] = method;
//comm= "arr["+level+"]="+method;
//eval(comm);
arr.count++;
var arr1 = iWuYc.getConstants("onLoadedMethodQueue");
for (var key in arr1) {
if (key === "count") {
console.log(arr[key]);
} else {
arr[key]();
}
}
}
}
}
$i = function (obj) {
return instance(obj);
}
$i.import = function (package,nickname,isWindowDomain){
var packages = iWuYc.Constants["packages"];
if (!!!package) {
package = {};
iWuYc.Constants["package"] = package;
}
if (!!!nickname) {
var index = Object.getOwnPropertyNames(package).length - 1;
nickname = "nickname-" + index;
}
package[nickname] = package;
var obj = iWuYc.getOrCreateObj(package);
if (!!isWindowDomain){
window[nickname] = obj;
}
$i[nickname] = obj;
return obj;
}
function init() {
$i.mkDom = function (domName, attrJson, content) {
return iWuYc.Methods.Unit.DomUnit.mkDom(domName, attrJson, content);
}
$i.insertAtCursor = function (insertField, insertVal) {
return iWuYc.Methods.Unit.DomUnit.insertAtCursor(insertField, insertVal)
}
$i.toString = function (obj) {
return iWuYc.Methods.Unit.ObjectUnit.toString(obj)
}
$i.isJSON = function (obj) {
return iWuYc.Methods.Unit.JSONUnit.isJSON(obj);
}
$i.toJSON = function (obj) {
return iWuYc.Methods.Unit.JSONUnit.toJSON(obj);
}
$i.setCookie = function (key, val, timeout) {
return iWuYc.Methods.Unit.CookiesUnit.setCookie(key, val, timeout);
}
$i.getCookie = function (key) {
return iWuYc.Methods.Unit.CookiesUnit.getCookie(key);
}
$i.removeCookie = function (key) {
return iWuYc.Methods.Unit.CookiesUnit.removeCookie(key);
}
$i.typeOf = function (obj) {
return iWuYc.getType(obj);
}
$i.isDom = function (obj) {
return iWuYc.Methods.Unit.DomUnit.isDom(obj);
}
$i.iMap = function () {
return new iMap();
}
$i.iSet = function () {
return new iSet();
}
$i.version = "1.0.1";
}
init();
var domSelector = {
"tagName": "document",
"#": function (selector, dom) {
return iWuYc.Methods.Unit.DomUnit.getElemetById(selector, dom);
},//id selector
".": "getElementsByC"
}
//iWuYc.Methods.Unit.DomUnit
var iDom = function (dom) {
//TODO1
var typeStr = $i.typeOf(dom);
if ($i(typeStr).validate(/\[object html[a-z]*element\]/)) {
this.idom = dom;
} else {
var regExp = /[.#a-zA-Z][a-zA-Z]*[ ]?/g;
var resule;
while ((result = regExp.exec(dom)) !== null) {
var selectorMarkReg = /([.#])/;
var selectorReg = /([a-zA-Z]+)/;
var selectorStr;
if (selectorReg.test(result)) {
selectorStr = RegExp.$1;
} else {
return;
}
if (selectorMarkReg.test(result)) {
throwError(domSelector[RegExp.$1] + " :: " + selectorStr,isPrint);
} else {
throwError(domSelector["tagName"] + " :: " + selectorStr,isPrint);
}
}
}
iDom.prototype.insertAtCursor = function () {
}
iDom.prototype.attr = function (attrName, attrVal) {
var argsLength = arguments.length;
if (argsLength < 1) {
throw "Argument list can't empty.";
} else if (argsLength === 1) {
return iWuYc.Methods.Unit.DomUnit.getAttr(this.idom, attrName);
} else if (argsLength === 2) {
return iWuYc.Methods.Unit.DomUnit.setAttr(this.idom, attrName, attrVal);
}
}
iDom.prototype.addClass = function (clsName) {
}
}
/**
* Selectable Dom element object;
* @param {*} dom
*/
var iSelectorDom = function (dom) {
iDom.call(this, dom);
/**
* 以Json格式,返回选择下拉框的信息
*/
iSelectorDom.prototype.selected = function () {
var index = this.idom.selectedIndex;
var selectOption = this.idom.options[index];
var text = selectOption.text;
var val = selectOption.value;
var attr = { "index": index, "text": text, "val": val };
return attr;
}
};
//initSelectorDom
(function () {
var Parent = function () { };
Parent.prototype = iDom.prototype;
iSelectorDom.prototype = new Parent();
})();
var iEvent = function (event) {
this.event = event;
iEvent.prototype.getEvent = function () {
return iWuYc.Methods.Unit.EventUnit.getEvent(this.event);
}
iEvent.prototype.getSource = function () {
return iWuYc.Methods.Unit.EventUnit.getSource(this.event);
}
}
var iString = function (obj) {
this.iStr = obj;
iString.prototype.isNotEmpty = function () {
return iWuYc.Methods.Unit.StringUnit.isNotEmpty(this.iStr);
}
iString.prototype.isEmpty = function () {
return iWuYc.Methods.Unit.StringUnit.isEmpty(this.iStr);
}
iString.prototype.isJSON = function () {
try {
eval("var obj=" + this.iStr);
return iWuYc.Methods.Unit.JSONUnit.isJSON(obj);
} catch (e) {
return false;
}
}
iString.prototype.toJSON = function () {
if (this.isJSON()) {
eval("var json=" + this.iStr);
return json;
} else {
throw "Is not a json String ,please check it and try again.";
}
}
iString.prototype.trim = function () {
return iWuYc.Methods.Unit.StringUnit.trim(this.iStr);
}
iString.prototype.trimLeft = function () {
return iWuYc.Methods.Unit.StringUnit.trimLeft(this.iStr);
}
iString.prototype.trimRight = function () {
return iWuYc.Methods.Unit.StringUnit.trimRight(this.iStr);
}
iString.prototype.replaceAll = function (sourceStr, targetStr) {
return iWuYc.Methods.Unit.StringUnit.replaceAll(this.iStr, sourceStr, targetStr);
}
iString.prototype.isNumber = function () {
throwError(this.iStr,isPrint);
return iWuYc.Methods.Unit.NumberUnit.isNumber(this.iStr);
}
iString.prototype.validate = function (regExpObj) {
return iWuYc.Methods.Unit.StringUnit.validate(this.iStr, regExpObj);
}
iString.prototype.encodeURI = function () {
return iWuYc.Methods.Unit.StringUnit.encodeURI(this.iStr);
}
iString.prototype.decodeURI = function () {
return iWuYc.Methods.Unit.StringUnit.decodeURI(this.iStr);
}
return this;
}
// iDate: Begin
{
var iDate = function (obj) {
this.innerData = obj;
}
iDate.prototype.format = function (fmt) {
return iWuYc.Methods.Unit.DateUnit.DateFormat(this.innerData, fmt);
}
iDate.prototype.year = function(year) {
if (typeof month != "number"){
return this.innerData.getFullYear();
}
this.innerData.setFullYear(year);
return year;
}
iDate.prototype.month = function(month){
if (typeof month != "number"){
return this.innerData.getMonth() + 1;
}
this.innerData.setMonth(month - 1);
return month;
}
iDate.prototype.date = function(date){
if (typeof date != "number"){
return this.innerData.getMonth();
}
this.innerData.setDate(date);
return date;
}
iDate.prototype.hour = function(hour){
if (typeof hour != "number"){
return this.innerData.getHour();
}
this.innerData.setHours(hour);
return hour;
}
iDate.prototype.minute = function(minute){
if (typeof minute != "number"){
return this.innerData.getMinutes();
}
this.innerData.setMinutes(minute);
return minute;
}
iDate.prototype.second = function(second){
if (typeof second != "number"){
return this.innerData.getSeconds();
}
this.innerData.setSeconds(second);
return second;
}
iDate.prototype.millisecond = function(millisecond){
if (typeof millisecond != "number"){
return this.innerData.getMilliseconds();
}
this.innerData.setMilliseconds(millisecond);
return millisecond;
}
};
// iDate: End
// iSet:Begin
{
var emptyVal = new Object();
var iSet = function (){
this.type = "iSet";
this.datas = new iMap();
this.size = 0;
}
iSet.prototype.has = function (data){
return Object.hasOwnProperty(data);
};
iSet.prototype.add = function (data) {
var has = this.has(data);
if (has) {
return false;
}
this.datas.put(data,emptyVal);
return true;
};
iSet.prototype.remove = function (data) {
return this.datas.remove(data);
};
iSet.prototype.clear = function () {
return this.datas.clear();
};
iSet.prototype.arrays = function () {
return this.datas.keys();
};
iSet.prototype.toString = function () {
var params = "";
var vals = this.arrays();
for (var index in vals) {
params += ",'" + vals[index] + "'";
}
if (params.length > 1) {
params = params.substr(1);
}
var str = "{" + params + "}";
return str;
};
iSet.prototype.addAll = function (datas) {
var type = iWuYc.getType(datas);
if ("[object array]" !== type && datas.type !== "iSet") {
return false;
};
if (datas.type === "iSet"){
datas = datas.arrays();
};
for (var index in datas) {
this.add(datas[index]);
};
};
iSet.prototype.removeAll = function (datas) {
var type = iWuYc.getType(datas);
if ("[object array]" !== type) {
return;
};
for (var index in datas) {
this.remove(datas[index]);
};
};
}
// iSet:End
// iMap:Begin
{
var iMap = function () {
this.datas = {};
this.size = 0;
this.type = "iMap";
}
/**
* Validation the key is containing or not.
*/
iMap.prototype.containKey = function (key) {
return this.datas.hasOwnProperty(key);
};
/**
* Put key and val into the map;
* Return old val if present else return null;
*/
iMap.prototype.put = function (key, val) {
var oldVal = null;
if (!!!this.datas[key]){
this.size++;
} else {
oldVal = this.datas[key];
}
this.datas[key] = val;
return oldVal;
};
/*
* Get the val by key.
* Return all if key is null;
* TODO : support regex
*/
iMap.prototype.get = function (key) {
if (!!key) {
return this.datas[key];
}
var vals = [];
for (var key in this.datas) {
vals.push(this.datas[key]);
}
return vals;
};
/*
* Remove the val by key.
*/
iMap.prototype.remove = function (key) {
if (!this.containKey(key)) {
return false;
}
delete this.datas[key];
this.size--;
return true;
};
/*
* Clear this map.
*/
iMap.prototype.clear = function () {
this.datas = {};
this.size = 0;
return true
};
iMap.prototype.keys = function () {
return Object.getOwnPropertyNames(this.datas);
};
iMap.prototype.putAll = function (obj){
if(!!obj["type"] && obj.type === "iMap"){
obj = obj.datas;
}
var $iMap = new iMap();
var oldVal = null;
for (var key in obj) {
oldVal = this.put(key,obj[key]);
if (oldVal === null){
continue;
}
$iMap.put(key,oldVal);
}
return $iMap;
}
/**
* Put val into map,return old val if present,return
*/
iMap.prototype.putIfAbsent = function (key,val) {
if (this.containKey(key)){
throw "The key is present,can't put."
}
this.put(key,val);
}
iMap.prototype.toString = function () {
return JSON.stringify(this.datas);
};
}
// iMap:End
/**
* set iWuYc object into window object,than using nikename '$i' to call iWuYc object
* window is browser's object
*/
window.iWuYc = iWuYc;
window.$i = $i;
})(window);
|
/**
* Created by Max on 4/30/2018.
*/
import {connect} from 'react-redux';
import {postMessage} from '../actions';
import InputMessage from '../components/inputMessage';
const mapStateToProps = state => {
return{
userName: state.CurrentUser.email,
}
};
const mapDispatchToProps = (dispatch)=>{
return{
postMessage: (username,message)=>{
console.log("message dispatched");
dispatch(postMessage(username, message))
}
}
};
export default connect (mapStateToProps, mapDispatchToProps)(InputMessage);
|
import React from "react";
import { Button } from "semantic-ui-react";
import { Link } from "react-router-dom";
function UseFundingButton({ address, managerAccount }) {
return (
<>
<Link
to={{
pathname: `/new/request/${address}`,
state: { managerAccount },
}}
>
<Button fluid style={{ marginBottom: "10px" }} primary size="medium">
<p>펀딩 사용 요청</p>
</Button>
</Link>
</>
);
}
export default UseFundingButton;
|
import React from 'react';
export default function Home() {
return (
<div>
<h1>Seytech</h1>
<p>Fullstack Software Developer Bootcamp</p>
<h5>WHERE OUR GRADS WORK</h5>
<h5>Testimonials</h5>
<h5>AVAILABLE COURSES</h5>
<h5>Full-Time! Real Time! Online!</h5>
<h5>ACT.JS What You Will Learn!</h5>
<h5>Why Choose Use?</h5>
<h5>Our Team</h5>
<h5>AREER CAREER SERVICES</h5>
<h5>Our Alumni</h5>
<h5>Placement-Based Tuition</h5>
<h5>Get In Touch</h5>
</div>
);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.