text
stringlengths 7
3.69M
|
|---|
const func = (word, prefix = 'hi') => {
if (word) {
return `${prefix}${word}`;
}
return (word) => {
prefix = `${prefix}i`;
return func(word, prefix);
}
}
/*
func("world") --> returns --> hiworld
func()("world") --> returns --> hiiworld
func()()("world") --> returns --> hiiiworld
func()()()("world") --> returns --> hiiiiworld
func()()()()("world") --> returns --> hiiiiiworld
func()()()()()("world") --> returns --> hiiiiiiworld
*/
|
import React from 'react'
import { shallow } from 'enzyme'
import App from '../../refactor/components/App'
import * as GameContext from '../../refactor/GameContext'
const MockConsumer = () => (<div id="MockConsumer" />)
const MockProvider = () => (<div id="MockProvider" />)
GameContext.default = {
Consumer: MockConsumer,
Provider: MockProvider
}
describe('App', () => {
const wrapper = shallow(<App />)
it('instantiates context provider @instantiate-context-provider', () => {
const contextProvider = wrapper.find(MockProvider)
expect(contextProvider.exists(), 'Did you instantiate the Game.Provider?').toBeTruthy()
expect(contextProvider.props().value, 'Did you pass the state object to the provider as value?').toEqual({
numTiles: 36,
playing: false,
previousTileIndex: null,
tiles: [],
toBeCleared: null
})
expect(contextProvider.children(), 'Did you wrap the OptionsPanel and the Board?').toHaveLength(2)
})
})
|
var Reflux = require('reflux');
var Actions = Reflux.createActions([
'getPokemons',
'getPokemon',
'searchPokemon',
'changeFilter'
]);
module.exports = Actions;
|
import {connect} from 'react-redux';
import {loadMenu, dropRedirect, clickBurger, clickApplyBurger, clickCancelBurger,
clickNewBurger, clickFinishOrder} from '../redux/actions';
import Main from './Main';
import {selectUserName, selectRedirect, selectMenuMap, selectBurgerSelected, selectBurgerOrder,
selectIsMenuLoaded, selectIsError, selectRequestError} from '../redux/selectors';
function mapStateToProps(state) {
return {
userName: selectUserName(state),
redirect: selectRedirect(state),
isMenuLoaded: selectIsMenuLoaded(state),
isError: selectIsError(state),
menuMap: selectMenuMap(state),
burgerSelected: selectBurgerSelected(state),
burgerOrder: selectBurgerOrder(state),
requestError: selectRequestError(state)
};
};
function mapDispatchToProps(dispatch) {
return {
loadMenu: () => dispatch(loadMenu()),
dropRedirect: () => dispatch(dropRedirect()),
clickBurger: (id) => dispatch(clickBurger(id)),
clickApplyBurger: () => dispatch(clickApplyBurger()),
clickCancelBurger: () => dispatch(clickCancelBurger()),
clickNewBurger: () => dispatch(clickNewBurger()),
clickFinishOrder: () => dispatch(clickFinishOrder())
};
};
const MainHandler = connect(mapStateToProps, mapDispatchToProps)(Main);
export default MainHandler;
|
var ResultSet = function(tbl) {
this.result = tbl.data;
this.getResultSet = function() {
return this.result;
}
};
module.exports = ResultSet;
|
import React, { Component } from 'react';
import './LoginForm.scss';
import { Link } from 'react-router-dom';
import { IconContext } from 'react-icons';
import { FaGoogle, FaFacebookSquare } from 'react-icons/fa';
import { GoogleLogin } from 'react-google-login';
import FacebookLogin from 'react-facebook-login/dist/facebook-login-render-props';
import { createBrowserHistory } from 'history';
import { bake_cookie } from 'sfcookies';
import ReactSVG from 'react-svg';
import NaverLoginIcon from 'static/images/naverLoginIcon.svg';
const responseGoogle = response => {
console.log(response);
const { googleId, accessToken } = response;
const { email, imageUrl } = response.profileObj;
const user = {
type: 'G',
id: googleId,
accessToken,
email,
thumbnail: imageUrl
};
console.log('googleuser:' + user);
if (response.accessToken) {
fetch('http://localhost:9090/api/auth/login', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(res => {
console.log(res);
if (res.status === 200) {
res.json().then(data => {
console.log(JSON.stringify(data.userVo));
localStorage.setItem(
'webber_user',
JSON.stringify(data.userVo)
);
bake_cookie('access_token', data.token);
window.location.replace('/');
});
}
if (res.status === 400) {
console.log(res.body);
const browserHistory = createBrowserHistory();
browserHistory.push('/register', user);
browserHistory.go(0);
}
})
.catch(err => {
// 에러코드 -1 회원가입
console.log(err.body);
if (err.code === -1) {
const browserHistory = createBrowserHistory();
browserHistory.push('/register', user);
browserHistory.go(0);
}
});
}
};
const responseFacebook = response => {
console.log(response);
const { id, accessToken } = response;
const { email } = response;
//const { picture } = response.data;
const user = {
type: 'F',
id: id,
accessToken,
email,
thumbnail: 'https://metadisplay.de/wp-content/uploads/2017/01/user_m.png'
};
console.log(user);
if (response.accessToken) {
fetch('http://localhost:9090/api/auth/login', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(res => {
if (res.status === 200) {
res.json().then(data => {
localStorage.setItem(
'webber_user',
JSON.stringify(data.userVo)
);
bake_cookie('access_token', data.token);
window.location.replace('/');
});
}
if (res.status === 400) {
console.log(res.body);
const browserHistory = createBrowserHistory();
browserHistory.push('/register', user);
browserHistory.go(0);
}
})
.catch(err => {
// 에러코드 -1 회원가입
console.log(err.body);
if (err.code === -1) {
const browserHistory = createBrowserHistory();
browserHistory.push('/register', user);
browserHistory.go(0);
}
});
}
};
class LoginForm extends Component {
constructor() {
super();
window.addEventListener('message', e => {
console.log(e.data);
if (e.data.email) {
const user = {
type: 'N',
id: e.data.id,
email: e.data.email,
thumbnail: e.data.profile_image,
accessToken: ''
};
fetch('http://localhost:9090/api/auth/login', {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(res => {
if (res.status === 200) {
res.json().then(data => {
localStorage.setItem(
'webber_user',
JSON.stringify(data.userVo)
);
bake_cookie('access_token', data.token);
window.location.replace('/');
});
}
if (res.status === 400) {
console.log(res.body);
const browserHistory = createBrowserHistory();
browserHistory.push('/register', user);
browserHistory.go(0);
}
})
.catch(err => {
// 에러코드 -1 회원가입
console.log(err.body);
if (err.code === -1) {
const browserHistory = createBrowserHistory();
browserHistory.push('/register', user);
browserHistory.go(0);
}
});
}
});
}
componentWillUpdate() {
window.scrollTo(0, 0);
}
componentDidMount() {
const naverLogin = new window.naver.LoginWithNaverId({
clientId: 'Dw8kgklN2EzkVFun66kZ',
callbackUrl: 'http://localhost:3000/auth/naver',
isPopup: true /* 팝업을 통한 연동처리 여부 */,
loginButton: {
color: 'white',
type: 3,
height: 60
}
/* 로그인 버튼의 타입을 지정 */
});
/* 설정정보를 초기화하고 연동을 준비 */
naverLogin.init();
// naverLogin.getLoginStatus(function(status) {
// if (status) {
// var email = naverLogin.user.getEmail();
// var profileImage = naverLogin.user.getProfileImage();
// console.log('이메일: ' + email);
// console.log('프로필사진: ' + profileImage);
// } else {
// console.log('AccessToken이 올바르지 않습니다.');
// }
// });
}
render() {
return (
<div className="LoginForm">
<div className="LoginForm_title">Make easy, Save time.</div>
{/* <GoogleLogout buttonText="Logout" onLogoutSuccess={logout} /> */}
<div>
<GoogleLogin
className="LoginForm_google"
clientId="961890564278-7tds7bjmf82km0e491bc2b68tuotjrnt.apps.googleusercontent.com"
onSuccess={responseGoogle}
onFailure={responseGoogle}
>
<IconContext.Provider value={{ size: '30' }}>
<FaGoogle className="LoginForm_logo" />
</IconContext.Provider>
<div className="LoginForm_name">Google</div>
</GoogleLogin>
</div>
<div>
<FacebookLogin
appId="177648546460414"
autoLoad={false}
fields="name,email,picture"
onClick={null}
callback={responseFacebook}
render={renderProps => (
<div
className="LoginForm_facebook"
onClick={renderProps.onClick}
>
<IconContext.Provider value={{ size: '35' }}>
<FaFacebookSquare className="LoginForm_logo" />
</IconContext.Provider>
<div className="LoginForm_name">Facebook</div>
</div>
)}
/>
</div>
<div className="LoginForm_naver">
<div id="naverIdLogin" />
<div className="naverWrapper">
<ReactSVG
src={NaverLoginIcon}
evalScripts="always"
renumerateIRIElements={false}
svgClassName="icon_naver_svg"
svgStyle={{
width: '3.3rem',
height: '3.3rem',
color: 'white',
fill: '#01bd38'
}}
className="icon_naver_wrapper"
/>
<span>Naver</span>
</div>
</div>
<div className="LoginForm_bottom">
<Link to="/template">look around without Login!</Link>
</div>
</div>
);
}
}
export default LoginForm;
|
(function (dm) {
var s = {
insertSort: (function () {
var insertSort = function (arr, func) {
/*@param array arr 待排序数组*/
func = func || function (prev, current) {
if (prev > current)
return 1;
else
return 0;
};
var i, j, k, key;
for (i = 1, k = arr.length; i < k; i++) {
key = arr[i];
j = i - 1;
while ((j > -1) && (func(arr[j], key))) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
};
return insertSort;
})(),
heapSort: (function () {
var utils = {
parent: function (i) {
return Math.floor(i / 2);
},
left: function (i) {
return 2 * i;
},
right: function (i) {
return 2 * i + 1;
},
maxHeap: function (arr, i) {
var k, l, r, largest = null, temp;
var status;
var heapSize = arr.length;
k = i;
status = true;
while (status) {
l = utils.left(k);
r = utils.right(k);
if ((l < heapSize) && (arr[l] > arr[k]))
largest = l;
else
largest = k;
if (r < heapSize && (arr[r] > arr[largest]))
largest = r;
if (largest != k) {
temp = arr[k];
arr[k] = arr[largest];
arr[largest] = temp;
k = largest;
}
else {
status = false;
}
}
},
buildMaxHeap: function (arr) {
var heapSize = arr.length,
node = Math.floor((heapSize - 1) / 2),
i, j;
for (i = node, j = 0; i >= j; i--) {
utils.maxHeap(arr, i);
}
},
minHeap: function (arr, i) {
}
};
return function (arr, func, method) {
/*
* @param array arr 要排序的数组
* @param Function func 排序函数
* @param string method 构建堆方式默认为最大堆[optional] max min*/
func = func || undefined;
method = method || "max";
if (method == "max")
utils["buildMaxHeap"](arr);
var i, j, length = arr.length;
var temp, result = [];
for (i = length - 1, j = 0; i >= j; i--) {
temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
result.unshift(arr.pop());
utils.maxHeap(arr, 0);
}
return result;
}
})(),
quickSort: (function () {
function partition(arr, p, r) {
var x, i, j;
x = arr[r];
i = p - 1;
var temp;
var temp2;
for (j = p; j < r; j++) {
if (arr[j] < x) {
i += 1;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
temp2 = arr[i + 1];
arr[i + 1] = arr[r];
arr[r]=temp2;
return i+1;
}
function __qucikSort(arr, p, r) {
var q;
if (p < r) {
q = partition(arr, p, r);
(arguments.callee)(arr, p, q - 1);
(arguments.callee)(arr, q + 1, r);
}
}
return function (arr) {
var p = 0, r = arr.length - 1;
__qucikSort(arr, p, r);
}
})()
};
var sort = function (method) {
/*@param string method 选择排序方法
* @return 返回的结果为调用的排序方法对应的返回值*/
var args = Array.prototype.slice.call(arguments, 0);
args.shift();
var m = method.toLowerCase() + "Sort";
var r = s[m];
return r;
};
dm.registLib("sort", sort);
})(dm);
|
import { actions } from './../actions'
const initialState = {
mobileMenu: false,
}
export default function workspace(state = initialState, { type }) {
switch (type) {
case actions.openMobileMenu:
return {
...state,
mobileMenu: true,
}
case actions.closeMobileMenu:
return {
...state,
mobileMenu: false,
}
default:
return state
}
}
|
function sendMessage() {
var request = new XMLHttpRequest();
request.open(
"POST",
"https://discord.com/api/webhooks/742864526373945505/8ICR6Jl3yY8OtZydV9bhjMjIJSNQcz_bZICA7LKLfRlF4KZz79L-5lshMdCEP370Zn9e"
);
request.setRequestHeader("Content-type", "application/json");
var message_content = document.getElementById("Message").value;
var username = document.getElementById("username").value;
var params = {
username: username,
avatar_url: "",
content: "``".concat(message_content.concat("``"))
};
request.send(JSON.stringify(params));
alert("Message Sent!")
}
|
export const server = {
url : 'http://192.168.0.4:3333'
}
|
green_25_interval_name = ["玉井","鹿陶洋","楠西","密枝","雙溪","茶水站","第一莊","第三莊","嘉義農場","大茅埔","大埔"];
green_25_interval_stop = [
["玉井站","玉安街口","玉田里"], // 玉井
["後旦","竹圍","鹿陶廟","鹿陶","埔頭子","大林路口","鹿陶洋","東西煙"], // 鹿陶洋
["油車","楠西橋","楠西區圖書館","楠西區公所","楠西街","楠西","楠西國中","水庫路口"], // 楠西
["檨仔坑","山頂","風窗","埤仔坑","密枝南","密枝","密枝北"], // 密枝
["東勢坑","坊子頭","吊橋頭","雙溪","社區口"], // 雙溪
["復興站","茶水站"], // 茶水站
["風吹嶺","第一莊","第二莊"], // 第一莊
["第三莊","第四莊"], // 第三莊
["嘉義農場","第六莊","草嶺","第八莊"], // 嘉義農場
["過山","第十莊","長枝坑","大茅埔","泰山","楓康","枋樹林"], // 大茅埔
["大埔路口","大埔鄉公所","土地公廟","大埔(嘉義)","大埔街"] // 大埔
];
green_25_fare = [
[26],
[26,26],
[26,26,26],
[45,28,26,26],
[54,38,29,26,26],
[64,47,38,26,26,26],
[72,55,46,27,26,26,26],
[83,66,57,38,28,26,26,26],
[90,73,64,45,35,26,26,26,26],
[110,94,85,65,56,47,39,28,26,26],
[130,113,104,85,75,66,58,47,40,26,26]
];
// format = [time at the start stop] or
// [time, other] or
// [time, start_stop, end_stop, other]
green_25_main_stop_name = ["玉井","鹿陶","鹿陶洋","楠西","密枝","社區口","風吹嶺","嘉義<br />農場","大茅埔","大埔<br />路口","大埔街"];
green_25_main_stop_time_consume = [0, 7, 9, 15, 25, 32, 40, 45, 55, 63, 65];
green_25_important_stop = [0, 3, 7, 10]; // 玉井, 楠西, 嘉義農場, 大埔街
green_25_time_go = [["06:10"],["07:50"],["12:50"],["15:50"]];
green_25_time_return = [["07:20"],["08:55"],["14:00"],["17:00"]];
|
var requestJson;
$(document).ready(function () {
$("#addItemInListBtn").click(function () {
let item = $("#inputItemInList").val();
let amount = $("#inputItemAmount").val();
if (amount == "") {
alert("Enter Amount")
} else if (!item == "") {
var code;
for (var bar in index) {
if (bar == item) {
code = index[bar];
}
}
if ($(".itemList").length == 0) {
$("#productList").append('<li class="itemList" data-barcode = \"' + code + '\" data-amount = \"' + amount + '\" data-value=\"' + item + '\">' + item +
'<span class="badge">' + amount + '</span><span class = "delItem">X</span></li>');
$("#inputItemInList").val('');
$("#inputItemAmount").val('');
}
else {
for (let i = 0; i < $(".itemList").length; i++) {
if ($(".itemList").get(i).dataset.value == item) {
var doubleAmount = $(".itemList").get(i).dataset.amount;
amount = +amount + +doubleAmount;
$(".itemList").get(i).remove();
}
}
$("#productList").append('<li class="itemList" data-barcode = \"' + code + '\" data-amount = \"' + amount + '\" data-value=\"' + item + '\">' + item +
'<span class="badge">' + amount + '</span><span class = "delItem">X</span></li>');
$("#inputItemInList").val('');
$("#inputItemAmount").val('');
}
} else {
alert("Enter the name of the product!")
}
if ($("#productList").children().length > 0) {
$("#doneItemListBtn,#createItemListBtn").show();
}
$(".delItem").click(function () {
$(this).parents(".itemList").remove();
if ($("#productList").children().length <= 0) {
$("#doneItemListBtn,#createItemListBtn").hide();
}
})
});
$("#createItemListBtn").click(function () {
sessionStorage.removeItem("request");
$("#productList").children().remove();
$("#doneItemListBtn,#createItemListBtn").hide();
});
$("#doneItemListBtn").click(function () {
let itemsList = $(".itemList");
let items = {};
let barcode;
let amount;
let name;
for (let i = 0; i < itemsList.length; i++) {
barcode = itemsList[i].dataset.barcode;
amount = itemsList[i].dataset.amount;
name = itemsList[i].dataset.value;
items[barcode] = {
amount: amount,
name: name
};
}
requestJson = {
location: {
lng: longitude,
lat: latitude
},
radius: 10.0,
items
};
console.log(requestJson);
requestJson = JSON.stringify(requestJson);
sessionStorage.setItem("request", requestJson);
});
});
|
var searchData=
[
['input_5fnumber_54',['input_number',['../classclasses_1_1nag_1_1_nag.html#a0cc27ba2edc3da1e1c92002f35f39782',1,'classes.nag.Nag.input_number(self)'],['../classclasses_1_1nag_1_1_nag.html#a0cc27ba2edc3da1e1c92002f35f39782',1,'classes.nag.Nag.input_number(self)']]]
];
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
// Create the dropdown list of available Viewpoints through the corresponding XML file
setDropdownViewpoints(this);
// Display corresponding description of the selected viewpoint AND
// change to that viewpoint
$('#dropdownViewpointsMenu button').click(function() {
// Show description
$('#viewpointDescArea').text($(this).val());
// Change text value of dropdown-button (to the name of current viewpoint)
$('#dropdownViewpointsButton').text($(this).text());
// Change viewpoint
changeViewpoint($(this).attr('id'));
// Reset the current view (??)
document.getElementById('x3dScene').runtime.resetView();
});
}
};
xhttp.open("GET", "assets/xml/viewpointsxml.xml", true);
xhttp.send();
$(function () {
// Modify button element to allow tooltips to popup when being hovered only
$('[data-toggle="tooltip"]').tooltip({
trigger: 'hover' // avoid tooltip staying visible when "focused"
});
$('[data-tooltip="tooltip"]').tooltip({
trigger: 'hover'
});
// Hide all "hidden" class (show the default one: Walk-mode description)
$('.hiddenDesc').hide();
$('.hiddenShortcut').hide();
$('.hiddenInstruction').hide();
// Hide "Turntable" settings
$('#turntableSettings').hide();
// Update corresponding information based on the selected item in dropdownModesButton
// + Change current mode's description & shortcut
// + Change text value of dropdown-button
// + Change text value of shortcut
// + Update control buttons/keys table (for each mode) accordingly
// + Show/Hide Turntable settings
// + "Flash" notification (for the changed interactive mode)
$('#dropdownModesMenu button').click(function() {
// Hide all descriptions and shortcuts first
$('.hiddenDesc').hide();
$('.hiddenShortcut').hide();
$('.hiddenInstruction').hide();
// Show description and shortcut of the selected one
$('#' + $(this).val() + "Description").show();
$('#' + $(this).val() + "Shortcut").show();
$('.' + $(this).val() + "Instruction").show();
// Change value of dropdown button
$('#dropdownModesButton').text($(this).text());
// Change table-header of button column if "Game" mode
if ($(this).val() === "game") {
$('#buttonHeader').text("Key");
} else {
$('#buttonHeader').text("Mouse button");
}
// Show "Turntable" setting if "Turntable" mode
if ($(this).val() === "turntable") {
$('#turntableSettings').show();
// Initialize canvas
updateArc(0.2, 1.4);
} else {
$('#turntableSettings').hide();
}
// Set up specific column's width for "Examine" and "Turntable" modes
if ($(this).val() === "examine" || $(this).val() === "turntable") {
$('#functionHeader').css('width', '30%');
$('#buttonHeader').css('width', '70%');
} else {
$('#functionHeader').css('width', '');
$('#buttonHeader').css('width', '');
}
// Notification for the changed interactive mode
$('#modeNoti').text($(this).text());
$('#notification').css('opacity', '1.0');
setTimeout(function() {
$('#notification').css('opacity', '0.0');
}, 2000);
// Change into selected mode in X3D scene
updateNavigationMode($(this).val());
});
});
//var rotated = false;
var showStats = false; // current state of the statistics-toggle
var showDebugWindow = false; // current state of debug window-toggle
window.addEventListener("DOMContentLoaded", function() {
// Event Listener for buttonResetView
document.getElementById("buttonResetView").addEventListener("click", function() {
// Retrieve x3d scene
var e = document.getElementById("x3dScene");
// Reset view
e.runtime.resetView();
});
// Event Listener for buttonShowAll
document.getElementById("buttonShowAll").addEventListener("click", function() {
// Retrieve x3d scene
var e = document.getElementById("x3dScene");
// Show all
e.runtime.showAll();
});
// Event Listener for buttonToggleStats
document.getElementById("buttonToggleStats").addEventListener("click", function() {
// Retrieve x3d scene
var e = document.getElementById("x3dScene");
// Flip the state
showStats = !showStats;
// Show statistics
e.runtime.statistics(showStats);
});
document.addEventListener("keydown", function(event) {
// If SPACE pressed
if (event.which === 32) {
// Toggle state of the corresponding button
if (!showStats) {
document.getElementById("buttonToggleStats").classList.add("active");
}
else {
document.getElementById("buttonToggleStats").classList.remove("active");
}
// Flip the state
showStats = !showStats;
}
});
// Event Listener for buttonToggleDebugWindow
document.getElementById("buttonToggleDebugWindow").addEventListener("click", function() {
// Retrieve x3d scene
var e = document.getElementById("x3dScene");
// Flip the state
showDebugWindow = !showDebugWindow;
// Show debug window
e.runtime.debug(showDebugWindow);
});
document.addEventListener("keydown", function(event) {
// If key "D" is pressed
if (event.which === 68) {
// Toggle state of the corresponding button
if (!showDebugWindow) {
document.getElementById("buttonToggleDebugWindow").classList.add("active");
}
else {
document.getElementById("buttonToggleDebugWindow").classList.remove("active");
}
// Flip the state
showDebugWindow = !showDebugWindow;
}
});
// Event Listener for upper bound input-form
document.getElementById("upperBound").addEventListener("change", function() {
var nav = document.getElementById("navType");
var upperBound = parseFloat(document.getElementById("upperBound").value);
var lowerBound = parseFloat(document.getElementById("lowerBound").value);
if (lowerBound > upperBound) {
// Configure parameters for Turntable mode in NavigationInfo
var str = '0.0 0.0 ' + upperBound.toFixed(1) + ' ' + lowerBound.toFixed(1);
nav.setAttribute("typeParams", str);
// Update canvas
updateArc(upperBound, lowerBound);
} else {
// Restrict upperBound to be always less then lowerBound at least 0.1
document.getElementById("upperBound").value = (lowerBound - 0.1).toFixed(1);
}
});
// Event Listener for lower bound input-form
document.getElementById("lowerBound").addEventListener("change", function() {
var nav = document.getElementById("navType");
var upperBound = parseFloat(document.getElementById("upperBound").value);
var lowerBound = parseFloat(document.getElementById("lowerBound").value);
if (lowerBound > upperBound) {
// Configure parameters for Turntable mode in NavigationInfo
var str = '0.0 0.0 ' + upperBound.toFixed(1) + ' ' + lowerBound.toFixed(1);
nav.setAttribute("typeParams", str);
// Update canvas
updateArc(upperBound, lowerBound);
} else {
// Restrict upperBound to be always less then lowerBound at least 0.1
document.getElementById("lowerBound").value = (upperBound + 0.1).toFixed(1);
}
});
// Event Listener for mode keyboard input
document.addEventListener("keydown", function(event) {
// "Walk" mode (key: W - which: 87)
if (event.which === 87) {
document.getElementById("walkMode").click();
}
// "Examine" mode (key: E - which: 69)
else if (event.which === 69) {
document.getElementById("examineMode").click();
}
// "Fly" mode (key: F - which: 70)
else if (event.which === 70) {
document.getElementById("flyMode").click();
}
// "Look at" mode (key: L - which: 76)
else if (event.which === 76) {
document.getElementById("lookatMode").click();
}
// "Helicopter" mode (key: H - which: 72)
else if (event.which === 72) {
document.getElementById("helicopterMode").click();
}
// "Turntable" mode (key: N - which: 78)
else if (event.which === 78) {
document.getElementById("turntableMode").click();
}
// "Game" mode (key: G - which: 71)
else if (event.which === 71) {
document.getElementById("gameMode").click();
}
});
});
/**
* Retrieve the necessary data from the designated XML file and create a list
* of all available Viewpoints for users to choose through the dropdown button.
*
* @param {type} xml
* @returns {undefined}
*/
function setDropdownViewpoints(xml) {
var xmlDoc, innerHTML, viewpoints, i;
xmlDoc = xml.responseXML;
innerHTML = "";
viewpoints = xmlDoc.getElementsByTagName("viewpoint");
for (i = 0; i < viewpoints.length; ++i) {
innerHTML += "<button class=\"dropdown-item\" type=\"button\" value=\""
+ viewpoints[i].getElementsByTagName("longDescription")[0].childNodes[0].nodeValue
+ "\" id=\""
+ viewpoints[i].getElementsByTagName("id")[0].childNodes[0].nodeValue
+ "\">"
+ viewpoints[i].getElementsByTagName("description")[0].childNodes[0].nodeValue
+ "</button>\n";
}
document.getElementById("dropdownViewpointsMenu").innerHTML = innerHTML;
}
// Update navigation mode
function updateNavigationMode(mode) {
var element = document.getElementById("x3dScene");
if (mode === "walk") element.runtime.walk();
else if (mode === "examine") element.runtime.examine();
else if (mode === "fly") element.runtime.fly();
else if (mode === "lookat") element.runtime.lookAt();
else if (mode === "helicopter") element.runtime.helicopter();
else if (mode === "game") element.runtime.game();
else if (mode === "turntable") element.runtime.turnTable();
else console.log("INVALID NAVIGATION MODE FOR X3D SCENE");
}
// Update (arc) represetantion for "Turntable" mode parameters
function updateArc(min, max) {
var canvas = document.getElementById("turntableCanvas");
var context = canvas.getContext("2d");
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = canvas.width / 2 - 10;
// Extract actual radian values of min and max
min = min - Math.PI / 2;
max = max - Math.PI / 2;
// Draw the white background (half-)circle
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.arc(centerX, centerY, radius, -0.5 * Math.PI, 0.5 * Math.PI, false);
context.fillStyle = "white";
context.fill();
context.lineWidth = 2;
context.strokeStyle = '#999';
context.stroke();
// Draw the arc between min and max (i.e. upper and lower bound, respectively)
context.beginPath();
context.arc(centerX, centerY, radius, min, max, false);
context.strokeStyle = '#003300';
context.stroke();
// Draw a line from center to max (i.e. lower bound)
// Note: origin of coordinate is at the top left position (upper-left)
context.beginPath();
context.moveTo(centerX, centerY);
context.lineTo(centerX + (radius * Math.cos(max)), centerY + (radius * Math.sin(max)));
context.strokeStyle = '#FF0000';
context.stroke();
// Draw a line from center to min (i.e. upper bound)
// Note: origin of coordinate is at the top left position (upper-left)
context.beginPath();
context.moveTo(centerX, centerY);
context.lineTo(centerX + (radius * Math.cos(min)), centerY + (radius * Math.sin(min)));
context.strokeStyle = '#0000FF';
context.stroke();
}
// Change to the specified viewpoint
function changeViewpoint(viewpointButtonID) {
// Extract the id of the viewpoint element
var viewpointID = viewpointButtonID.replace('Button', '');
// Get the specified viewpoint element -> set bind to true
document.getElementById(viewpointID).setAttribute("bind", "true");
}
// Move to the specified viewpoint
function moveToViewpoint(viewpointID) {
document.getElementById(viewpointID).setAttribute("bind", "true");
}
|
module.exports = {
PORT: 3001,
DB_CLUSTER_NAME: 'barnpals-cluster-name',
DB_PASSWORD: 'password123',
DB_USER: 'exampleUser',
};
|
/*
* Login Action Creator
*/
//dependencies
import { GET_CATEGORIES,
GET_CURENT_CATEGORY,
GET_CURENT_PRICELIST,
GET_PRICELISTS,
LOGIN,
GET_OVERVIEW,
GET_USERS ,
CREATE_GROUP,
GET_GROUPS,
GET_CURRENT_USER,
UPDATE_USER,
GET_CURRENT_GROUP,
UPDATE_GROUP,
CHANGE_LANGUAGE,
GET_CURRENT_CAR
} from './actionTypes';
export const login = userData => {
return {
type : LOGIN,
userData : userData
}
}
export const getOverview = stats => {
return {
type : GET_OVERVIEW,
stats : stats
}
}
export const getUsers = users => {
return {
type : GET_USERS,
users : users
}
}
export const getGroups = groups => {
return {
type : GET_GROUPS,
groups : groups
}
}
export const createNewGroup = group => {
return {
type : CREATE_GROUP,
group : group
}
}
export const getCurrentUser = user => {
// console.log(user);
return {
type : GET_CURRENT_USER,
user : user
}
}
export const updateUser = user => {
return {
type : UPDATE_USER,
user : user
}
}
export const getCurrentGroup = group => {
// console.log(user);
return {
type : GET_CURRENT_GROUP,
group : group
}
}
export const updateGroup = group => {
return {
type : UPDATE_GROUP,
group : group
}
}
export const getCategories = categories => {
return {
type : GET_CATEGORIES,
categories : categories
}
}
export const getCurrentCategory = category => {
return {
type : GET_CURENT_CATEGORY,
category : category
}
}
export const getPricelists = pricelists => {
return {
type : GET_PRICELISTS,
pricelists : pricelists
}
}
export const getCurrentPriceList = pricelist => {
return {
type : GET_CURENT_PRICELIST,
pricelist : pricelist
}
}
export const changeLanguage = language => {
return {
type : CHANGE_LANGUAGE,
language : language
}
}
export const getCurrentCar = currentCar => {
return {
type : GET_CURRENT_CAR,
currentCar : currentCar
}
}
|
import {Bar} from 'vue-chartjs'
export default{
extends:Bar,
data() {
return {
label: [1,2,3,4,5,6,7,8,9,10],
}
},
props: ['data','value'],
mounted() {
//alert(this.label)
this.renderBarChart();
},
computed: {
chartData: function() {
return this.data;
}
},
methods: {
renderBarChart: function() {
this.renderChart( {
labels: this.label,
datasets: [{
label: "Investment Principal",
backgroundColor: "blue",
data: this.chartData
},
{
label: "Investment Growth",
backgroundColor: "red",
data: this.value
},
],
},
{
title: {
display: true,
text: 'Investment Growth Chart',
fontSize: 28,
},
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
},
},
);
}
},
watch: {
data: function() {
//alert(this.chartData)
//this._chart.destroy();
this.label = [];
for (let i = 1; i < this.data.length+1; i++) {
this.label.push(i);
}
for (let i = 0; i < this.data.length; i++) {
this.value[i] = this.data[i] - this.value[i];
this.data[i] = this.data[i] - this.value[i]
}
this.renderBarChart();
},
},
/*
data:()=>({
chartdata: {
labels: [1,2,3,4,5,6,7,8,9,10],
datasets: [
{
label: 'Principal',
data: this.growth,//[10000,15000,20000,25000,30000,35000,40000,45000,50000,55000],
backgroundColor:'#AA6',
borderWidth:1.0,
}
,
{
label: 'Profit',
data: this.growth,
backgroundColor:'#7C1'
}
]
},
options: {
title: {
display: true,
text: 'Investment Growth Chart',
fontColor: 'Black',
fontSize: 30,
},
legend: {
position: 'top',
},
layout: {
padding: {
left: 0,
right: 0,
top: 0,
bottom: 0
}
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 300000,
},
scaleLabel: {
display: true,
labelString: 'Investment Value'
}
}],
xAxes: [{
stacked: true,
scaleLabel: {
display: true,
labelString: 'Number of Years'
}
}],
},
maintainAspectRatio: false,
responsive: true
}
}),
watch: {
growth: function() {
alert(this.growth);
this.renderChart(this.chartdata,this.options);
}
},
mounted(){
this.renderChart(this.chartdata,this.options)
},
*/
};
|
//only for dev mode needs to be removed on prod
import devBundle from "./devBundle";
import { config } from "./../config/config";
import app from "./express";
import mongoose from "mongoose";
mongoose.Promise = global.Promise;
mongoose.connect(config.mongoUri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
const mongoUri = config.mongoUri
console.log(mongoUri, 'MONGO URI')
mongoose.connection.on('error', (err) => {
console.log(err)
})
// app.get("/", (req, res) => {
// res.status(200).send(template());
// });
//const CURRENT_WORKING_DIR = process.cwd();
// app.use("/dist", express.static(path.join(CURRENT_WORKING_DIR, "dist")));
app.listen(config.port, function onStart(err) {
if (err) {
console.log(err);
}
console.info("Server started on port %s.", config.port);
});
devBundle.compile(app);
|
import React, { useMemo } from "react";
import ContentHeader from "./helpers/content-header";
import ExperienceDetails from "./helpers/experience-details";
import moment from "moment";
function WorkExperience() {
const date = useMemo(() => {
const currentTime = moment();
const joiningDateDiff = currentTime.diff(moment("2018-06-18"));
const joiningDuration = moment.duration(joiningDateDiff, "ms");
return joiningDuration;
}, []);
const jobDetails = useMemo(() => {
if (date) {
return [
{
image_url: "/assets/images/talview.png",
role: "Sales and Marketing Intern",
org: "SkillGenic Academy",
duration: "Feb 2021 – Mar 2021 (1 mos)"
}
];
}
return [];
}, [date]);
return (
<div className="ui segments box-shadow-none margin-five-bottom">
<ContentHeader title="Work Experience" />
<div className="ui segment padding-no box-shadow-none">
<div className="ui segments border-none box-shadow-none">
{jobDetails.map((data, i) => (
<ExperienceDetails key={i} data={data} />
))}
</div>
</div>
</div>
);
}
export default WorkExperience;
|
import { useState } from 'react';
import marked from 'marked';
import './Note.css';
const Note = ({ text='', id, onDeleteNote, onTextUpdate}) => {
const [isEditing, setIsEditing] = useState(false);
const toggleEditor = () => {
setIsEditing(prevValue => !prevValue);
};
return (
<div className="note">
<div className="tools">
<button className="edit" onClick={toggleEditor}>
<i className="fas fa-edit"></i>
</button>
<button className="delete" onClick={() => onDeleteNote(id)}>
<i className="fas fa-trash-alt"></i>
</button>
</div>
<div className={isEditing ? 'main hidden' : 'main'} dangerouslySetInnerHTML={{__html: marked(text)}}></div>
<textarea className={isEditing ? '' : 'hidden'} onChange={event => onTextUpdate(event, id)} value={text}></textarea>
</div>
);
};
export default Note;
|
var Utils = require('utils'),
_ = require('underscore'),
Handlebars = require('handlebars/runtime')['default'];
var Self;
module.exports = Self = {
template: function (item, id) {
var tiposMidia =
'<option value="Youtube">Youtube</option>' +
'<option value="Flickr">Flickr</option>' +
'<option value="Instagram">Instagram</option>';
return '<div class="input-group">' +
'<span class="input-group-addon">' +
'<select>' + tiposMidia + '</select>' +
'</span>' +
'<input type="text" data-type="midias" name="' + item.camelCase + '" class="form-control">' +
'<span class="input-group-btn">' +
'<button class="btn btn-success" id="midia-add-' + item.camelCase + '" type="button"><i class="glyphicon glyphicon-plus"></i> Incluir</button>' +
'</span>' +
'</div>' +
'<div class="midia" id="midia-' + item.camelCase + '" data-camel-case="' + item.camelCase + '"></div>';
},
init: function () {
// Percorre cada campo do tipo "midia"
$('[data-type=midias]').each(function (idx, el) {
// Define a ação do botão "+"
$('#midia-add-' + $(el).attr('name')).on('click', function () {
Self.incluir(el);
});
$(el).keydown(function (ev) {
if (ev.keyCode == 13) {
ev.preventDefault();
Self.incluir(el);
}
});
});
},
bind: function (value, key, view) {
if (value) {
value = JSON.parse(JSON.parse("\"" + value + "\""));
_.each(value, function (item) {
// Adiciona uma tag na midia pelo DOM
$('#midia-' + key).append(
'<label class="tag tag-default">' +
'<span class="tipo">' + item.tipoMidia + '</span>: <span class="value">' + item.midia + '</span>' +
'<span class="remove midia-remove">' +
'<i class="glyphicon glyphicon-remove"></i>' +
'</span>' +
'</label>'
);
});
// Define a ação de remover a tag do DOM
$('.midia-remove').on('click', function (ev) {
$(this).parent().remove();
});
}
},
save: function (json, view) {
$('.midia').each(function (idx, container) {
var arrayTags = [];
// Para cada tag, monta uma objeto
$(container).find('label').each(function (idx, label) {
// Joga o objeto no array de tags
arrayTags.push({
tipoMidia: $(label).find('.tipo').html(),
midia: $(label).find('.value').html()
});
});
// Adiciona o array cheio de tags ao Json
var myString = JSON.stringify(JSON.stringify(arrayTags));
json[$(container).attr('data-camel-case')] = myString.substring(1, myString.length - 1);
});
return json;
},
show: function (item, model) {
if (model[item.camelCase]) {
var parsed = JSON.parse(JSON.parse('"' + model[item.camelCase] + '"'));
_.each(parsed, function (item) {
if (item.tipoMidia == "Youtube") {
var video_id = item.midia.split('v=')[1],
ampersandPosition = video_id ? video_id.indexOf('&') : -1;
item.midia = ampersandPosition === -1 ? video_id : video_id.substring(0, ampersandPosition);
}
});
return Handlebars.partials['templates/controls/_showMidias.tpl'](parsed);
}
else {
return '';
}
},
incluir: function (el) {
var tipoMidia = $(el).parent().find('select option:checked').val(),
valor = $(el).val().trim(),
slug = Utils.slugify(tipoMidia + '-' + valor);
// Adiciona uma tag na midia pelo DOM
$('#midia-' + $(el).attr('name')).append(
'<label class="tag tag-default">' +
'<span class="tipo">' + tipoMidia + '</span>: <span class="value">' + valor + '</span>' +
'<span class="remove midia-remove">' +
'<i class="glyphicon glyphicon-remove"></i>' +
'</span>' +
'</label>'
);
// Define a ação de remover a tag do DOM
$('.midia-remove').on('click', function (ev) {
$(this).parent().remove();
});
// Limpa o campo de digitação
$(el).val('');
}
};
|
import Organization from '../../db/models/Organization'
import User_Organization from '../../db/models/User_Organization'
export default async function(src, args, ctx) {
try {
return await Organization.create(
{
...args,
users: [
{
userId: args.creatorId,
role: 'admin'
}
]
},
{
include: [
{
model: User_Organization,
as: 'users'
}
]
}
)
} catch (ex) {
console.error(ex)
}
}
|
// Sign In View
// =============
// Includes file dependencies
define([ "firebase", "jquery", "backbone", "auth", "debug" ],
function( Firebase, $, Backbone, Auth, Debug ) {
// Extends Backbone.View
var entrySignInView = Backbone.View.extend({
el: $("#signInView"),
events: {
"click #signInButton": "signIn"
},
initialize: function() {
Debug.log('View - SignIn View - Init!!!!');
this.render();
},
render: function() {
Debug.log('View - SignIn View - Render!!!!');
$.mobile.changePage( "#signInView" , { reverse: false, changeHash: false } );
$("#signInView #signInNav").addClass("ui-btn-active");
},
signIn: function() {
var email = $('#signInView #emailInput').val();
var password = $('#signInView #passwordInput').val();
Debug.log('View - SignIn View - Attemping to login ' + email + ' with ' + password);
Auth.client.login('password', {
email: email,
password: password
});
$('#signInView #passwordInput').val('');
}
});
// Returns the View class
return entrySignInView;
} );
|
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { createTranslate } from '../locales/translate'
import ReduxToastr from 'react-redux-toastr'
import { ActionCreators as AuthActions } from '../modules/authentication/actions'
import { ActionCreators as FormShortcutActions } from '../modules/form-shortcut/actions'
import { getUser } from '../modules/authentication/selectors'
import { getLocale } from '../modules/app/selectors'
import FormShortcutSelectors from '../modules/form-shortcut/selectors'
import NavBar from './components/NavBar'
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(AuthActions, dispatch),
formShortcutActions: bindActionCreators(FormShortcutActions, dispatch)
}
}
class Layout extends React.PureComponent {
constructor (props) {
super(props)
this.message = createTranslate(null, this)
this.handleLogout = this.handleLogout.bind(this)
}
componentWillMount () {
this.props.formShortcutActions.fetchList()
}
handleLogout () {
this.props.actions.logoutUser()
}
render () {
return (
<div className="page-content">
<NavBar
location={this.context.router.location.pathname}
locale={this.props.locale}
user={this.props.user}
onLogout={this.handleLogout}
formShortcuts={this.props.formShortcuts}
/>
<div className="mr-4 ml-4">
{this.props.children}
</div>
<ReduxToastr timeOut={4000}
newestOnTop={false}
preventDuplicates
position="bottom-right"
transitionIn="fadeIn"
transitionOut="fadeOut"
progressBar />
</div>
)
}
}
function mapStateToProps (state) {
return {
user: getUser(state),
locale: getLocale(state),
formShortcuts: FormShortcutSelectors.getEntitiesPage(state)
}
}
Layout.propTypes = {
children: PropTypes.object,
params: PropTypes.object,
user: PropTypes.object,
locale: PropTypes.string
}
Layout.contextTypes = {
router: PropTypes.object.isRequired
}
const LayoutConnected = connect(mapStateToProps, mapDispatchToProps)(Layout)
export default LayoutConnected
|
let registerForm = document.querySelector("#register-form");
registerForm.addEventListener("submit", registerHandler);
let loginForm = document.querySelector("#login-form");
loginForm.addEventListener("submit", loginHandler);
let url = "http://localhost:3030/users";
async function registerHandler(e) {
e.preventDefault();
let form = e.target;
let formData = new FormData(form);
let newUser = {
email: formData.get("email"),
password: formData.get("password")
}
if (!newUser.email || !newUser.password) {
return alert("All fields are required!");
}
if (newUser.password != formData.get("rePass")) {
return alert("Passwords don\'t match");
}
let registerResponse = await fetch(`${url}/register`, {
headers: { "Content-Type": "application/json" },
method: "Post",
body: JSON.stringify(newUser)
});
let registerResult = await registerResponse.json();
if (registerResponse.ok) {
localStorage.setItem("token", registerResult.accessToken);
localStorage.setItem("userId", registerResult._id);
localStorage.setItem("email", registerResult.email);
location.assign("./index.html");
}
else {
alert(`Cannot register! ${registerResult.message}.`);
window.location.reload();
}
}
async function loginHandler(e) {
e.preventDefault();
let form = e.target;
let formData = new FormData(form);
let newUser = {
email: formData.get("email"),
password: formData.get("password")
}
if (!newUser.email || !newUser.password) {
return alert("All fields are required!");
}
let loginResponse = await fetch(`${url}/login`, {
headers: { "Content-Type": "application/json" },
method: "Post",
body: JSON.stringify(newUser)
});
let loginResult = await loginResponse.json();
if (loginResponse.ok) {
localStorage.setItem("token", loginResult.accessToken);
localStorage.setItem("userId", loginResult._id);
localStorage.setItem("email", loginResult.email);
location.assign("./index.html");
}
else {
alert("Cannot login! You are not registered or your password is invalid.");
window.location.reload();
}
}
function validateInput(email, password) {
return email.trim() == "" || password.trim() == "";
}
|
const mazo = document.getElementById("mazo");
const tablero = document.getElementById("tablero");
const cambiarJugador = document.getElementById("cambiarjugador");
const tl = gsap.timeline();
let cantidadCartasPozo = 0;
// Mazo de prueba, funciona con mayusculas y minusculas.
const mazoCartas = [
"1Y",
"3Y",
"1B",
"0R",
"0B",
"0G",
"1r",
"VR",
"+4r",
"SKY",
"2b",
"5B",
"4y",
"3G",
"0Y",
"8R",
"5G",
"9B",
"3R",
];
//Indicamos quien esta jugando en este equipo.
// En este caso el jugdor 1 es quien juega en este equipo.
const jugadorEsteEquipo = 1;
// Indicamos que jugador esta jugando en este turno.
let turno = 1;
// En sentido horario incremento es = 1, en antihorario debe cambiar a -1.
let incremento = 1;
// Al redimensionar la ventana, las cartas del pozo quedan desplazadas del pozo, esta funcion las vuelve a alinear con el pozo cada vez que se redimensiona la ventana.
// Prueba comentando desde la funcion y la linea que aparece justo despues de esta.
function alinearCartasPozo() {
let pozo = document.getElementById("pozo").getBoundingClientRect();
gsap.to(".cartajugada", {
top: pozo.top,
x: 0,
left: pozo.left,
duration: 0,
});
}
window.onresize = alinearCartasPozo;
class Carta {
constructor() {
this.cartaPozo = "3g";
this.currentNumero = document.getElementById("currentNumero");
this.currentColor = document.getElementById("currentColor");
this.colorPicker = document.getElementById("colorPicker");
this.anchoCarta = 71;
this.altoCarta = 100;
this.separacionCartas = 10;
this.cartasActivas;
this.soundFlip = new Sound("./assets/sonidos/dealingcard.wav");
this.soundVolteaTablero = new Sound("./assets/sonidos/voltearjuego.wav");
this.soundSaltaTurno = new Sound("./assets/sonidos/pierdeturno.mp3");
this.cartasCambioSentido = ["VR", "VB", "VG", "VY"];
this.cartasSaltaTurno = ["SKR", "SKB", "SKG", "SKY"];
this.cartasWild = ["WDB", "WDG", "WDR", "WDY"];
this.cartasActivasMas4 = ["+4B", "+4R", "+4Y", "+4G"];
this.colors = {
R: "red",
B: "blue",
G: "green",
Y: "yellow",
};
}
zoomIn(e) {
gsap.to(e.target, { scale: 1.4 });
}
zoomOut(e) {
gsap.to(e.target, { scale: 1 });
}
zoomCarta() {
this.cartasActivas = Array.from(
document.querySelectorAll(`.jugador${jugadorEsteEquipo}`)
);
this.cartasActivas.map((cartaActiva) => {
cartaActiva.addEventListener("mouseenter", (e) => this.zoomIn(e));
});
this.cartasActivas.map((cartaActiva) => {
cartaActiva.addEventListener("mouseleave", (e) => this.zoomOut(e));
});
}
setColor(colorSelected) {
// color de la carta del pozo.
const cardColor = this.cartaPozo[this.cartaPozo.length - 1].toUpperCase();
if (colorSelected) {
this.currentColor.style.backgroundColor = this.colors[colorSelected];
} else if (
// Si la carta del pozo es un wild o un + 4, currentColor no se le asigna un valor a currentColor.
this.cartasWild.includes(this.cartaPozo.toUpperCase()) ||
this.cartasActivasMas4.includes(this.cartaPozo.toUpperCase())
) {
this.currentColor.style.backgroundColor = "unset";
} else {
this.currentColor.style.backgroundColor = this.colors[cardColor];
}
}
setNumero() {
this.currentNumero.textContent = this.cartaPozo
.split("")
.slice(0, this.cartaPozo.length - 1)
.join("");
}
setCartaPozoInfo() {
this.setNumero();
this.setColor();
}
}
class Jugador {
constructor(idJugador, nombre, avatar) {
this.cantidadCartasMano = 0;
this.manoDeCartas;
this.idJugador = idJugador;
this.nombre = nombre;
this.avatar = avatar;
}
crearElemento({ el, id, clase, src, text, padre }) {
if (el && padre) {
const elemento = document.createElement(el);
if (id) {
elemento.setAttribute("id", id);
}
if (clase) {
elemento.classList.add(clase);
}
if (src) {
elemento.src = src;
}
if (text) {
elemento.textContent = text;
}
padre.appendChild(elemento);
return elemento;
}
}
imprimirInfo() {
this.imprimirNombreTablero();
this.imprimirEmoticones();
}
imprimirNombreTablero() {
const infoJugador = this.crearElemento({
el: "div",
clase: `infojugador${this.idJugador}`,
padre: tablero,
});
console.log(infoJugador);
const avatar = this.crearElemento({
el: "img",
src: this.avatar,
clase: `avatarjugador${this.idJugador}`,
padre: infoJugador,
});
const nombre = this.crearElemento({
el: "div",
text: this.nombre,
clase: `nombrejugador${this.idJugador}`,
padre: infoJugador,
});
// Si el jugador es el que esta en este pc, se imprime además el boton UNO
if (this.idJugador == jugadorEsteEquipo) {
const boton = this.crearElemento({
el: "div",
id: "botoncastigo",
clase: "botoncastigo",
padre: infoJugador,
});
}
}
imprimirEmoticones() {
if (this.idJugador == jugadorEsteEquipo) {
const infoJugador = document.getElementsByClassName(
`infojugador${this.idJugador}`
)[0];
const emoticonMenu = this.crearElemento({
el: "nav",
clase: "circular-menu",
padre: infoJugador,
});
const circle = this.crearElemento({
el: "div",
clase: "circle",
padre: emoticonMenu,
});
const emoticones = [
"enamorado.svg",
"frio.svg",
"guino.svg",
"indignacion.svg",
"riendo.svg",
"sorprendido.svg",
];
emoticones.map((emoticon) => {
this.crearElemento({
el: "img",
src: `assets/img/emoticons/${emoticon}`,
clase: "emoticon",
padre: circle,
});
});
const botonEmoticon = this.crearElemento({
el: "img",
src: "/assets/img/emoticons/ejemplo.svg",
clase: "menu-button",
padre: emoticonMenu,
});
// funcion para posicionar emoticones y darles clase open al presionar boton emoticones
var items = document.querySelectorAll(".emoticon");
for (var i = 0, l = items.length; i < l; i++) {
items[i].style.left =
(
78 -
10 * Math.cos(-0.5 * Math.PI - 2 * (1 / l) * i * Math.PI)
).toFixed(4) + "%";
items[i].style.top =
(
30 +
35 * Math.sin(-0.5 * Math.PI - 2 * (1 / l) * i * Math.PI)
).toFixed(4) + "%";
}
document.querySelector(".menu-button").onclick = function (e) {
e.preventDefault();
document.querySelector(".circle").classList.toggle("open");
};
}
}
robarCarta() {
this.cantidadCartasMano++;
const newCard = document.createElement("div");
newCard.classList.add("carta", `jugador${this.idJugador}`);
// Si es el jugador de este pc se muestra su carta, en caso contrario se muestra boca abajo.
if (this.idJugador == jugadorEsteEquipo) {
// Se imprime en la carta el id de la primera carta del mazo.
newCard.setAttribute("id", mazoCartas[0]);
newCard.style.backgroundImage = `url("./assets/img/mazo/${mazoCartas[0].toUpperCase()}.svg")`;
} else {
newCard.style.backgroundImage = `url("./assets/img/mazo/UNOPortada.svg")`;
}
// Imprime la carta.
tablero.appendChild(newCard);
// Inicia la animación de robar carta.
this.animRobarCarta();
// Inicia el sonido al robar carta.
carta.soundFlip.play();
// Inicia la animación al hacer zoom a la carta.
carta.zoomCarta();
// Elimina la carta del array mazoCartas.
mazoCartas.shift();
// Se reordenan las cartas.
this.animReordenarCartas();
}
animRobarCarta() {
// posicionMazo nos sirve para que green sock sepa que las cartas deben salir desde las coordenadas del mazo.
let posicionMazo = document.getElementById("mazo").getBoundingClientRect();
this.manoDeCartas = Array.from(
document.querySelectorAll(`.jugador${this.idJugador}`)
);
const cartaRobada = this.manoDeCartas[this.manoDeCartas.length - 1];
switch (this.idJugador) {
case 1:
tl.fromTo(
cartaRobada,
{
bottom: posicionMazo.bottom,
x: 0,
left: posicionMazo.left,
},
{
duration: 0.8,
bottom: "6rem",
x: 0,
ease: "back.out(1.2)",
}
);
break;
case 2:
tl.fromTo(
cartaRobada,
{
right: posicionMazo.right,
},
{
duration: 1,
y: 0,
right: `${2 + carta.anchoCarta / 16}rem`,
ease: "back.out(1.2)",
}
);
break;
case 3:
tl.fromTo(
cartaRobada,
{
bottom: posicionMazo.bottom,
x: 0,
left: posicionMazo.left,
},
{
duration: 1,
top: "6rem",
x: 0,
ease: "back.out(1.2)",
}
);
break;
case 4:
tl.fromTo(
cartaRobada,
{
left: posicionMazo.left,
},
{
duration: 1,
y: 0,
left: `${2 + carta.anchoCarta / 16}rem`,
ease: "back.out(1.2)",
}
);
break;
default:
break;
}
}
animReordenarCartas() {
// Variable que determina la posicion de cada carta.
let posCarta = -(
((this.cantidadCartasMano - 1) *
(carta.separacionCartas + carta.anchoCarta)) /
2
);
// La funcion ordena cada una de las cartas de la mano.
this.manoDeCartas.map((cartaEnMano) => {
const clasesCartaMano = Array.from(cartaEnMano.classList);
if (clasesCartaMano.includes(`jugador${this.idJugador}`)) {
switch (this.idJugador) {
case 1:
tl.to(cartaEnMano, {
duration: 0.15,
x: -posCarta,
});
posCarta += +carta.anchoCarta + carta.separacionCartas;
break;
case 2:
tl.to(cartaEnMano, {
duration: 0.15,
y: -posCarta,
rotate: -90,
});
posCarta += +carta.anchoCarta + carta.separacionCartas;
break;
case 3:
tl.to(cartaEnMano, {
duration: 0.15,
x: -posCarta,
rotate: 180,
});
posCarta += +carta.anchoCarta + carta.separacionCartas;
break;
case 4:
tl.to(cartaEnMano, {
duration: 0.15,
y: -posCarta,
rotate: 90,
});
posCarta += +carta.anchoCarta + carta.separacionCartas;
break;
default:
break;
}
}
});
}
seleccionarColor() {
// Aparece el color picker.
gsap.to(carta.colorPicker, {
display: "flex",
opacity: 1,
duration: 1,
});
// Al seleccionar un color del color picker.
carta.colorPicker.addEventListener("click", (e) => {
const colorSelected = e.target.classList[0];
// Fijamos la variable carta.currentColor con el color seleccionado.
carta.setColor(colorSelected);
// Desaparece el color picker.
gsap.to(carta.colorPicker, {
display: "none",
opacity: 0,
duration: 1,
});
});
}
animSeleccionarCarta(e) {
let idCarta = e.target.getAttribute("id");
let pozo = document.getElementById("pozo").getBoundingClientRect();
tl.to(`[id='${idCarta}']`, {
top: pozo.top,
x: 0,
left: pozo.left,
duration: 1,
zIndex: cantidadCartasPozo,
});
if (carta.cartasCambioSentido.includes(idCarta)) {
// Si la carta es un cambio de sentido, cambia el sentido del juego
this.animVolteaJuego();
} else if (carta.cartasSaltaTurno.includes(idCarta)) {
// Si la carta es un salto de turno, el siguiente jugador pierde su turno
this.saltaTurno();
} else if (carta.cartasWild.includes(idCarta.toUpperCase())) {
// Si la carta es un wild, se llama al color picker.
this.seleccionarColor();
} else if (carta.cartasActivasMas4.includes(idCarta.toUpperCase())) {
// Si la carta es un +4, se llama al color picker.
this.seleccionarColor();
}
// Para que las cartas de la mano se reordenen
this.animReordenarCartas();
}
seleccionarCarta() {
// carta.cartasActivas son las cartas que tiene en la mano el jugador.
carta.cartasActivas.map((cartaActiva) => {
cartaActiva.addEventListener("click", (e) => {
let listadoClasesCarta = Array.from(e.target.classList);
if (listadoClasesCarta.includes(`jugador${jugadorEsteEquipo}`)) {
this.cantidadCartasMano--;
cantidadCartasPozo++;
carta.cartaPozo = e.target.getAttribute("id");
e.target.classList.remove(`jugador${this.idJugador}`);
e.target.classList.add("cartajugada");
// Animacion cuando carta seleccionada va al pozo
this.animSeleccionarCarta(e);
// Se define el numero y color de la carta del pozo
carta.setCartaPozoInfo();
}
});
});
}
animVolteaJuego() {
gsap.to(".flecha1", {
scaleX: -1,
rotate: -90,
duration: 1,
});
gsap.to(".flecha2", {
scaleX: -1,
rotate: 90,
duration: 1,
});
gsap.to(".flecha3", {
scaleX: -1,
rotate: -90,
duration: 1,
});
gsap.to(".flecha4", {
scaleX: -1,
rotate: 90,
duration: 1,
});
carta.soundVolteaTablero.play();
}
saltaTurno() {
carta.soundSaltaTurno.play();
}
turno() {
this.robarCarta();
this.seleccionarCarta();
}
}
// Clase para crear los sonidos, se instancia dentro de las propiedades de la clase Carta.
class Sound {
constructor(src) {
this.sound = document.createElement("audio");
this.sound.src = src;
this.sound.setAttribute("preload", "auto");
this.sound.setAttribute("controls", "none");
this.sound.style.display = "none";
}
play() {
document.body.appendChild(this.sound);
this.sound.play();
}
stop() {
this.sound.pause();
}
}
const carta = new Carta();
// Dimensiones cartas
mazo.style.width = `${carta.anchoCarta}px`;
mazo.style.height = `${carta.altoCarta}px`;
// Se inicializan los valores del numero actual y color actual de la carta del pozo
carta.setColor();
carta.setNumero();
// Creación de jugadores
const jugador4 = new Jugador(4, "Leonardo", "assets/img/avatares/01-mexican.svg");
const jugador1 = new Jugador(1, "Raphael", "assets/img/avatares/02-man.svg");
const jugador2 = new Jugador(2, "Miguel Ángel", "assets/img/avatares/03-pirates.svg");
const jugador3 = new Jugador(3, "Donatello", "assets/img/avatares/04-girl.svg");
const jugadores = [jugador2, jugador3, jugador4, jugador1];
/* const jugadores = [jugador1, jugador2, jugador3]; */
jugadores.map((jugador) => {
jugador.imprimirInfo()
jugador.robarCarta()
});
// Al cambiar de turno
cambiarJugador.addEventListener("click", (e) => {
e.preventDefault();
turno == 4 ? (turno = 1) : (++turno);
//reiniciar segundos del contador
gameContador.reset();
});
// Al presionar el mazo
mazo.addEventListener("click", () => {
switch (turno) {
case 1:
jugador1.turno();
break;
case 2:
jugador2.turno();
break;
case 3:
jugador3.turno();
break;
case 4:
jugador4.turno();
break;
default:
break;
}
});
class Contador {
constructor(time) {
this.isWaiting = false;
this.isRunning = false;
this.initialSeconds = time;
this.seconds = time;
this.countdownTimer;
this.finalCountdown = false;
}
logic() {
let minutes = Math.round((this.seconds - 30) / 60);
let remainingSeconds = this.seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById("waiting_time").innerHTML =
minutes + ":" + remainingSeconds;
if (remainingSeconds < 10) {
document.getElementById("waiting_time").classList.add("timealert");
}
if (this.seconds == 0) {
this.finalCountdown = true;
} else {
this.isWaiting = true;
this.seconds--;
}
}
start() {
setInterval(this.logic.bind(this), 1000);
}
reset() {
this.seconds = this.initialSeconds;
document.getElementById("waiting_time").classList.remove("timealert");
}
}
// Nueva instancia de contador
const gameContador = new Contador(20);
// Iniciar gameContador
gameContador.start();
// To do
// Implementar para 2 jugadores y 3 jugadores
|
"use strict";
import {
arryLi
} from "./arryBase.js";
//
const inpDocType = document.querySelector("#inpDocType"),
divPageTypes = document.createElement('div'),
divTypes = document.createElement('div'),
resultTypesDiv = document.createElement('div'),
noDocDiv = document.querySelector('#noDocDiv');
inpDocType.addEventListener('click', (e, i, id = (`checkbox`), returnIdDiv = (`label`)) => {
const clickE = e.target.dataset.show;
switch (clickE) {
case 'false':
divPageTypes.dataset.show = true;
divPageTypes.dataset.pressed = 'divPageTypes';
inpDocType.dataset.show = true;
divPageTypes.classList = 'showPage';
divTypes.classList = 'showLi';
arryLi.forEach(elements => {
i = Math.floor(1000 * Math.random());
divTypes.appendChild(addLiFunc(elements, (id + i), (returnIdDiv + i)));
});
divPageTypes.appendChild(divTypes);
noDocDiv.appendChild(divPageTypes);
break;
case 'true':
hiddenFunc(e);
break;
}
});
divPageTypes.addEventListener('click', e => {
const clickELabel = e.target.dataset.pressed;
const clickECheckbox = e.target.type;
switch (clickELabel || clickECheckbox) {
case 'divPageTypes':
divPageTypes.classList = 'hiddenElement';
divTypes.classList = 'hiddenElement';
break;
case 'checkbox':
resultTypesDiv.classList = 'checkedTypeDiv';
searchCheckbox(e, e.target.checked);
break;
}
});
resultTypesDiv.addEventListener('click', (e, returnIdDiv = 'returnIdDiv') => {
removeTypesF(`${returnIdDiv}${e.target.id}`);
const changess = document.querySelector(`#${e.target.id}`);
changess.checked = false;
});
function searchCheckbox(e, clickECheckbox, labelText, returnId = ('return'), returnIdDiv = 'returnIdDiv') {
switch (clickECheckbox) {
case true:
labelText = e.target.labels[0].outerText;
resultTypesDiv.appendChild(addLiFunc(
labelText,
`${e.target.id}`,
`${returnIdDiv}${e.target.id}`,
true
));
noDocDiv.appendChild(resultTypesDiv);
break;
case false:
removeTypesF(`${returnIdDiv}${e.target.id}`);
break;
}
}
function addLiFunc(e, id, returnIdDiv, checkedss = false,) {
const text = document.createTextNode(e);
const checkbox = document.createElement('input');
const hr = document.createElement('hr');
const label = document.createElement('label');
const li = document.createElement('li');
const labelLiDiv = document.createElement('div');
checkbox.type = ('checkbox');
checkbox.id = id;
checkbox.checked = checkedss;
labelLiDiv.id = returnIdDiv;
label.htmlFor = id;
label.dataset.pressed = 'checkbox';
labelLiDiv.appendChild(hr);
li.appendChild(checkbox);
label.appendChild(text);
li.appendChild(label);
labelLiDiv.appendChild(li);
return labelLiDiv;
}
function hiddenFunc(e) {
divPageTypes.classList = 'showPage';
divTypes.classList = 'showLi';
}
function removeTypesF(e) {
const removTage = document.querySelector(`#${e}`);
removTage.remove();
}
|
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http)
var treedoc = require('./treedoc.js');
var converter = require('./converter.js');
var fs = require('fs');
var siteID = 0;
var tree;
var docs = require('./docType.js');
require('ponyfill-array');
var docList = new docs.DocList();
//restore saved documents
converter.loadDocuments(docList);
//save documents
setInterval(function() {converter.saveDocuments(docList)}, 10000);
//Serving every file in same directory as index.js, should fix this by putting client side scripts in a public folder
app.use(express.static(__dirname));
app.param('id', function (req, res, next, id) {
console.log("Sent room page: " + id);
res.sendFile(__dirname + '/room.html');
});
app.get('/:id', function (req, res, next) {
next();
});
// app.get('/', function(req,res){
// console.log("Sent index page");
// res.sendFile(__dirname + '/index.html');
// });
io.on('connection', function(socket){
var doc;
console.log('User connected');
//Handler for join document request
socket.on('joinDoc', function(joinObj){
var docName = joinObj.name.toString();
doc = joinDocument(socket, docName);
var nextSiteID = doc.nextSiteID();
io.to(socket.id).emit('init', {tree : doc.tree, siteID : nextSiteID});
});
//Handlers for receiving an instruction from client
socket.on('add', function(addObj){
atom = addObj.atom.toString();
//Making sure atom is a valid char by checking its length
if (atom.length == 1) {
treedoc.insert(doc.tree, addObj.posID, atom);
console.log('Handled add instruction :: ' + atom);
socket.broadcast.to(doc.name).emit('add', addObj);
console.log('Broadcasted add instruction');
} else {
console.log("Invalid add instruction. Trying to add: " + atom + ".");
}
});
socket.on('remove', function(posID){
treedoc.remove(doc.tree, posID);
console.log('Handled remove instruction');
socket.broadcast.to(doc.name).emit('remove', posID);
console.log('Broadcasted remove instruction');
});
});
http.listen(8888, function(){
console.log('listening on port: 8888');
});
function joinDocument(socket, docName) {
console.log("Trying to join doc with active index: " + docList.isActive(docName) + " and passive index: " + docList.isPassive(docName));
var doc;
//Find out if document is active, passive or nonexistent.
var index;
if ((i = docList.isActive(docName)) != -1) {
console.log("Doc with index " + i + " and name: " + docName + " was active.");
doc = docList.active[i];
} else if ((i = docList.isPassive(docName)) != -1) {
console.log("Doc index " + i + " and name: " + docName + " was passive.");
docList.makeActive(i);
doc = docList.active[i];
}
else {
//Create new doc if it is not passive or active
console.log("Doc " + docName + " was not passive or active.");
doc = createNewDoc(docName);
}
socket.join(docName);
return doc;
}
function createNewDoc(docName) {
var newDoc = new docs.Document(docName);
docList.active.push(newDoc);
return newDoc;
}
|
const User = require('../models/user');
/*
refresh_user_token function updates the token of the user
given the id and the new token. It extracts the id and token
from the request body then updates the token of the associated user
*/
exports.refresh_user_token = (req, res, next) => {
if (req.body.id === undefined || req.body.token === undefined || req.body.id === "" || req.body.token === "") {
res.status(400).json({error: "id and token are required"});
} else {
const id = req.body.id;
const newToken = req.body.token;
User.update({userId: id}, {$set: {token: newToken}}).exec().then(response => {
res.status(200).json(response);
}).catch(err => {
res.status(500).json({error: err});
}
);
}
};
|
import KulinariaDataSource from '../../data/dataSource';
import UrlParser from '../../routes/url-parser';
import { createRestaurantDetailTemplate, errorMessageTemplate } from '../templates/template-creator';
import Scroll from '../../utils/scroll';
import LikeButtonInitiator from '../../utils/like-button-presenter';
import Preloader from '../../utils/loader-initiator';
const Detail = {
async render() {
return `
<div id="detail"> </div>
<div id="likeButtonContainer"></div>
`;
},
async afterRender() {
Scroll.toTop();
Preloader.displayPreloader();
const url = UrlParser.parseActiveUrlWithoutCombiner();
const restaurant = await KulinariaDataSource.detailResto(url.id);
const restaurantContainer = document.querySelector('#detail');
Preloader.removePreloader();
if (!restaurant.restaurant) {
document.querySelector('.skip-link').innerHTML = '';
restaurantContainer.innerHTML = errorMessageTemplate();
return;
}
restaurantContainer.innerHTML = createRestaurantDetailTemplate(restaurant.restaurant);
LikeButtonInitiator.init({
likeButtonContainer: document.querySelector('#likeButtonContainer'),
resto: restaurant.restaurant,
});
document.querySelector('#submit').addEventListener('click', async (e) => {
e.preventDefault();
const reviewerName = document.querySelector('#name');
const reviewerReview = document.querySelector('#reviews');
const reviewData = {
id: restaurant.restaurant.id,
name: reviewerName.value,
review: reviewerReview.value,
};
if (reviewerName.value === '' || reviewerReview.value === '') {
alert('Name atau Pendapat Tidak Boleh Kosong!');
} else {
await KulinariaDataSource.addReview(reviewData);
reviewerName.value = '';
reviewerReview.value = '';
this._renderReview(reviewData.name, reviewData.review);
}
});
},
_renderReview(name, review) {
const reviewContainer = document.querySelector('.review__list');
const date = new Date().toLocaleDateString('id-ID', { year: 'numeric', month: 'long', day: 'numeric' });
const dataReview = `
<div class="review__item">
<h3 class="review__item__name">${name}</h3>
<p class="review__item__review">
<q>${review}</q>
</p>
<p class="review__item__date">${date}</p>
</div>
`;
reviewContainer.innerHTML += dataReview;
},
};
export default Detail;
|
const conexionMysql = require("../../DB/conexionMysql");
const { formatearDateMysql } = require('../../helpers');
/**
* Reserva una plaza de cierta experiencia. 👍
* @param {} req
* @param {*} res
* @param {*} next
*/
async function reservarExperiencia(req, res, next) {
let conexion;
try {
conexion = await conexionMysql();
const idExperiencia = req.params.id;
const idUsuario = req.userAuth.id;
await existeReserva(conexion, [idUsuario, idExperiencia]);
await quedanPlazas(conexion, idExperiencia);
await insertarReserva(conexion, [idUsuario, idExperiencia]);
res.send({
status: 'Ok',
message: 'reserva efectuada'
});
} catch (err) {
next(err)
} finally {
if (conexion) conexion.release();
}
}
/**
* Inserta en la tabla reservas la tupla necesaria.
* @param {Object} conexion - Conexion a pool de mysql
* @param {[number]} param1 - ID del usuario e ID de la experiencia
*/
async function insertarReserva(conexion, [idUsuario, idExperiencia]) {
await conexion.query(
`
INSERT INTO reservas (fecha, id_experiencia, id_usuario)
VALUES (?,?,?)
`,
[formatearDateMysql(new Date()), idExperiencia, idUsuario]
);
}
/**
* Comprueba si ya existe la reserva.
* @param {Object} conexion - Conexion a pool de mysql
* @param {[number]} param1 - ID del usuario e ID de la experiencia
*/
async function existeReserva(conexion, [idUsuario, idExperiencia]) {
const [data] = await conexion.query(
`
SELECT id FROM reservas
WHERE id_experiencia=? AND id_usuario=? AND cancelada=false
`,
[idExperiencia, idUsuario]
);
if (data.length > 0) {
const error = new Error('Usuario ya cuenta con reserva');
error.httpStatus = 303;
throw error;
}
}
/**
* Comprueba si quedan plazas disponibles teniendo en cuenta las plazas_totales de la experiencia y el número de reservas que hay registradas de esta en la tabla reservas.
* @param {Object} conexion - Conexion a pool de mysql
* @param {[number]} param1 - ID del usuario e ID de la experiencia
*/
async function quedanPlazas(conexion, idExperiencia) {
const [plazas] = await conexion.query(
`
SELECT exp.plazas_totales FROM experiencias exp
INNER JOIN reservas res ON res.id_experiencia = exp.id
WHERE exp.id = ?
`,
[idExperiencia]
);
if (
typeof plazas !== 'undefined' &&
plazas.length > 0 &&
plazas.length >= plazas[0].plazas_totales
) {
const error = new Error('No quedan plazas disponibles');
error.httpStatus = 303;
throw error;
}
}
module.exports = reservarExperiencia;
|
let word = prompt('Введите слово').toLowerCase();
// if(!isNaN(+word) && word !== '') {
// alert('Число не подходит');
// } else if(word === '') {
// alert('В строке пусто');
// } else if(word === word.split('').reverse().join('')) {
// console.log(true);
// } else {
// console.log(false);
// }
let val = '';
if(!isNaN(+word) && word != '') {
alert('Число не подходит');
} else if(word === '') {
alert('В строке пусто');
} else {
for(let i = word.length - 1; i >= 0; i--) {
val += word[i];
}
if(word === val) {
console.log(true);
} else {
console.log(false);
}
}
|
var Vector = require("./vector");
/**
* Creates a complex number
* @constructor
* @extends Vector
* @param {number} x - The real part
* @param {number} y - The imaginary part
*/
function Complex(x, y) {
Vector.call(this, x, y);
}
Complex.prototype = Object.create(Vector.prototype);
/**
* Multiplies two complex numbers.
* @method
* @return {Complex}
*/
Complex.prototype.times = function(other) {
var newX = this.x*other.x - this.y*other.y,
newY = this.x*other.y + this.y*other.x;
return new Complex(newX, newY);
};
/**
* Squares the instance of Complex
* @method
* @return {Complex}
*/
Complex.prototype.square = function() {
return this.times(this);
};
/**
* @prop {number} length
* @this Complex
* @instance
* @readonly
*/
Object.defineProperty(Complex.prototype, "length", {
get: function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
});
/**
* More computationally efficient than Complex.length
* @prop {number} squareLength
* @this Complex
* @instance
* @readonly
*/
Object.defineProperty(Complex.prototype, "squareLength", {
get: function() {
return this.x * this.x + this.y * this.y;
}
});
|
define(['require'], function(require) {
'use strict';
var ngApp, ls, _siteid;
ls = location.search;
_siteid = ls.match(/[\?&]site=([^&]*)/)[1];
ngApp = angular.module('app', ['ngRoute', 'ui.bootstrap', 'ui.tms', 'ui.xxt', 'http.ui.xxt', 'notice.ui.xxt', 'service.matter', 'protect.ui.xxt']);
ngApp.config(['$routeProvider', '$controllerProvider', '$locationProvider', '$uibTooltipProvider', 'srvSiteProvider', function($routeProvider, $controllerProvider, $locationProvider, $uibTooltipProvider, srvSiteProvider) {
var RouteParam = function(name, htmlBase, jsBase) {
var baseURL = '/views/default/pl/fe/site/';
this.templateUrl = (htmlBase || baseURL) + name + '.html?_=' + (new Date * 1);
this.controller = 'ctrl' + name[0].toUpperCase() + name.substr(1);
this.resolve = {
load: function($q) {
var defer = $q.defer();
require([(jsBase || baseURL) + name + '.js'], function() {
defer.resolve();
});
return defer.promise;
}
};
};
ngApp.provider = {
controller: $controllerProvider.register,
};
$routeProvider
.when('/rest/pl/fe/site/basic', new RouteParam('basic'))
.when('/rest/pl/fe/site/coworker', new RouteParam('coworker'))
.when('/rest/pl/fe/site/home', new RouteParam('home'))
.when('/rest/pl/fe/site/invoke', new RouteParam('invoke'))
.when('/rest/pl/fe/site/user', new RouteParam('user', '/views/default/pl/fe/site/home/', '/views/default/pl/fe/site/home/'))
.when('/rest/pl/fe/site/subscriber', new RouteParam('subscriber', '/views/default/pl/fe/site/home/', '/views/default/pl/fe/site/home/'))
.when('/rest/pl/fe/site/analysis', new RouteParam('analysis', '/views/default/pl/fe/site/home/', '/views/default/pl/fe/site/home/'))
.when('/rest/pl/fe/site/received', new RouteParam('received', '/views/default/pl/fe/site/message/', '/views/default/pl/fe/site/message/'))
.otherwise(new RouteParam('basic'));
$locationProvider.html5Mode(true);
$uibTooltipProvider.setTriggers({
'show': 'hide'
});
srvSiteProvider.config(_siteid);
}]);
ngApp.controller('ctrlFrame', ['$scope', '$location', 'srvSite', function($scope, $location, srvSite) {
$scope.subView = '';
$scope.opened = '';
$scope.$on('$locationChangeSuccess', function(event, currentRoute) {
var subView = currentRoute.match(/([^\/]+?)\?/);
$scope.subView = subView[1] === 'site' ? 'basic' : subView[1];
switch ($scope.subView) {
case 'basic':
case 'coworker':
case 'home':
case 'invoke':
$scope.opened = 'define';
break;
case 'user':
case 'subscriber':
case 'received':
case 'analysis':
$scope.opened = 'data';
break
default:
$scope.opened = '';
}
});
$scope.switchTo = function(subView) {
var url = '/rest/pl/fe/site/' + subView;
$location.path(url);
};
$scope.update = function(prop) {
srvSite.update(prop);
};
srvSite.get().then(function(oSite) {
$scope.site = oSite;
});
}]);
/***/
require(['domReady!'], function(document) {
angular.bootstrap(document, ["app"]);
});
/***/
return ngApp;
});
|
import { Link } from "gatsby"
import React from "react";
import CoupleAC from "./AbigailCaio/coupleAC";
import CoupleMK from "./MarlenaKyle/coupleMK";
import CoupleOT from "./OliviaTJ/coupleOT";
import CoupleSL from "./SirleyLamont/coupleSL";
import CoupleRA from "./RoshniAllwyn/coupleRA";
import "./couples.scss";
const Couples = () => (
<div className="couples-block">
<div className="couple">
<Link to="/weddings/olivia-tj">
<div className="couple-image">
<CoupleOT />
<div className="tint" />
<h2>O+T</h2>
</div>
</Link>
</div>
<div className="couple">
<Link to="/weddings/sirley-lamont">
<div className="couple-image">
<CoupleSL />
<div className="tint" />
<h2>S+L</h2>
</div>
</Link>
</div>
<div className="couple">
<Link to="/weddings/abigail-caio">
<div className="couple-image">
<CoupleAC />
<div className="tint" />
<h2>A+C</h2>
</div>
</Link>
</div>
<div className="couple">
<Link to="/weddings/marlena-kyle">
<div className="couple-image">
<CoupleMK />
<div className="tint" />
<h2>M+K</h2>
</div>
</Link>
</div>
<div className="couple">
<Link to="/weddings/roshni-allwyn">
<div className="couple-image">
<CoupleRA />
<div className="tint" />
<h2>R+A</h2>
</div>
</Link>
</div>
</div>
)
export default Couples
|
var searchData=
[
['gettimestamp_8',['getTimeStamp',['../functions_8h.html#ab01f25e9d4ea3af4aaae53a6524e1229',1,'functions.h']]]
];
|
const parseLang = fileName => {
const lang = fileName.replace(" ", "").split(".");
return lang[lang.length - 1];
}
export {
parseLang
}
|
import Vue from 'vue'
import Vuex from 'vuex'
import { db } from "../firebase"
Vue.use(Vuex)
export const GET_PROJECTS = 'GET_PROJECTS'
export const SET_CURRENT_PROJECT = 'SET_CURRENT_PROJECT'
export const REMOVE_CURRENT_PROJECT = 'REMOVE_CURRENT_PROJECT'
export const GET_PROJECT_TASKS = 'GET_PROJECT_TASKS'
export const GET_USERS = 'GET_USERS'
export let unsubscribe
export const store = new Vuex.Store({
state: {
projects: [],
users: [],
currentProject: {
id: "",
name: "",
dateStart: "",
dateEnd: "",
tasks: {
toDo: [],
inProgress: [],
inTest: [],
done: []
}
}
},
actions: {
getProjects({ commit }) {
db.collection("projects").onSnapshot(querySnapshot => {
let projectsArray = []
querySnapshot.forEach(doc => {
let project = doc.data()
project.id = doc.id
projectsArray.push(project)
})
commit(GET_PROJECTS, projectsArray)
})
},
setCurrentProject({ commit }, payload) {
commit(SET_CURRENT_PROJECT, payload)
},
removeCurrentProject({ commit }) {
unsubscribe()
const emptyProject = {
id: "",
name: "",
dateStart: "",
dateEnd: "",
tasks: {
toDo: [],
inProgress: [],
inTest: [],
done: []
}
}
commit(REMOVE_CURRENT_PROJECT, emptyProject)
},
getTasksByProjectId({ commit }, payload) {
unsubscribe = db.collection("projects").doc(payload).collection("tasks").onSnapshot(querySnapshot => {
let tasksArray = {
toDo: [],
inProgress: [],
inTest: [],
done: [],
}
querySnapshot.forEach(doc => {
let task = doc.data()
task.id = doc.id
switch (task.category) {
case "toDo":
tasksArray.toDo.push(task)
break
case "inProgress":
tasksArray.inProgress.push(task)
break
case "inTest":
tasksArray.inTest.push(task)
break
case "done":
tasksArray.done.push(task)
break
}
})
commit(GET_PROJECT_TASKS, tasksArray)
})
},
getUsers({ commit }) {
db.collection("users").onSnapshot(querySnapshot => {
let userArray = []
querySnapshot.forEach(doc => {
let user = doc.data()
user.id = doc.id
userArray.push(user)
})
commit(GET_USERS, userArray)
})
},
},
mutations: {
[GET_PROJECTS](state, payload) {
state.projects = payload
},
[SET_CURRENT_PROJECT](state, payload) {
state.currentProject.id = payload.id
state.currentProject.name = payload.name
state.currentProject.dateEnd = payload.dateEnd
state.currentProject.dateStart = payload.dateStart
},
[REMOVE_CURRENT_PROJECT](state, payload) {
state.currentProject = payload
},
[GET_PROJECT_TASKS](state, payload) {
state.currentProject.tasks = payload
},
[GET_USERS](state, payload) {
state.users = payload
}
}
})
|
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Option = require("./Option");
/* eslint-disable no-trailing-spaces */
/**
* @class Argument
*
* An argument is an option passed to a {@link Command}. In the CLI sentence (See
* [App.isCliSentence]{@link App#isCliSentence}) `/testapp foo bar`, `bar` would be the
* value of the first argument.
*
* @param {object} options
*
* @param {string} options.name
*
* The Argument name. This options has two purposes: to document the command help, and to
* identify the option in the `argv.args` variable passed back to the command function.
*
* @param {string} options.desc
*
* A description about what the Argument is and what information the user is expected to
* supply. It is used to show the command help to the user.
*
* @param {string} options.type
*
* The Argument data type, either `string` or `number`.
*
* @param {boolean} [options.required=false]
*
* Whether or not the Argument is required for the command to work. If the user fails to supply
* every required Argument, Clapp will warn them about the problem and redirect them to the
* command help.
*
* @param {string|number} [options.default]
*
* A default value that will be passed into the `argv.args` if the user does not supply a value.
* This only works if `required` is set to false; it has no effect otherwise. If `required` is
* set to false (its default value), then `default` is mandatory.
*
* @param {validation[]} [options.validations]
*
* An array with every validation check that you want to perform on the user provided value. See
* {@link validation}.
*
* @example
* let arg = new Clapp.Argument({
* name: "file",
* desc: "The file where the data will be saved",
* type: "string",
* required: false,
* default: "defaultfile.dat"
* });
*/
/* eslint-enable */
var Argument = function (_Option) {
_inherits(Argument, _Option);
function Argument(options) {
_classCallCheck(this, Argument);
var _this = _possibleConstructorReturn(this, (Argument.__proto__ || Object.getPrototypeOf(Argument)).call(this, options));
if (_this.type !== "string" && _this.type !== "number") {
throw new Error(_this._genErrStr("type is not string or number"));
}
if (typeof options.required !== "boolean") {
_this.required = false;
} else {
_this.required = options.required;
}
if (typeof options.default !== "undefined") {
_this.default = options.default;
}
// If the argument is not required, it must have a default value
if (!_this.required && typeof _this.default !== "undefined") {
if (_typeof(_this.default) !== _this.type) {
throw new Error(_this._genErrStr("its default value doesn't match its data type"));
}
} else if (
// If it doesn't have a default value, then show an error.
!_this.required && typeof _this.default === "undefined") {
throw new Error(_this._genErrStr("it's not required, and no default value was" + " provided"));
}
return _this;
}
return Argument;
}(Option);
module.exports = Argument;
|
import PropTypes from 'prop-types';
import PropsInit from '../../Utils/PropsInit';
import { Colors } from '../../Theme';
export default props=(Component) => {
propTypes={
containerStyle: PropTypes.oneOfType([PropTypes.object,PropTypes.array]),
valueStyle: PropTypes.oneOfType([PropTypes.object,PropTypes.array]),
badgeStyle: PropTypes.oneOfType([PropTypes.object,PropTypes.array]),
value: PropTypes.string,
valueSize: PropTypes.number,
valueColor: PropTypes.string,
badgeSize: PropTypes.number,
badgeColor: PropTypes.string,
};
defaultProps={
valueSize: 20,
valueColor: Colors.white,
badgeColor: Colors.primary[0],
};
PropsInit(Component,propTypes,defaultProps)
}
|
require.config({
// baseUrl in this config means path relative to index.html
// 1. if no data-main defined then baseUrl relative to the folder where require.js lies
// 2. if data-main defined then baseUrl relative to the folder where data-main="xxx" lies
// 3. if in require.config({baseUrl: 'xxx'}) defined then base Url relative to the folder where index.html lies
baseUrl: './',
waitSeconds: 0,
paths: {
'ngCordova': 'lib/ngCordova/dist/ng-cordova'
,'cordova': 'cordova'
,'ionic': 'lib/ionic/release/js/ionic'
,'ionicAngular': 'lib/ionic/release/js/ionic-angular'
,'angular': 'lib/angular/angular'
,'ngAnimate': 'lib/angular-animate/angular-animate'
,'ngSanitize': 'lib/angular-sanitize/angular-sanitize'
,'ngUiRouter': 'lib/angular-ui-router/release/angular-ui-router'
,'ngUiRouterExtras': 'lib/ui-router-extras/release/ct-ui-router-extras'
,'ngTimeline': 'lib/angular-timeline/dist/angular-timeline'
,'moment': 'lib/moment/min/moment-with-locales'
,'ngMoment': 'lib/angular-moment/angular-moment'
,'ngElastic': 'lib/angular-elastic/elastic'
,'AutoLinker': 'lib/Autolinker.js/dist/Autolinker'
,'lodash': 'lib/lodash/lodash'
,'restangular': 'lib/restangular/dist/restangular'
,'angular-loading-bar': 'lib/angular-loading-bar/build/loading-bar'
,'ng-tags-input': 'lib/ng-tags-input/ng-tags-input'
,'ionic-filter-bar': 'lib/ionic-filter-bar/dist/ionic.filter.bar'
,'google-libphonenumber': 'lib/google-libphonenumber/dist/browser/libphonenumber'
,'ion-sticky': 'lib/ion-sticky/ion-sticky'
},
shim: {
'angular': {exports: 'angular'}
, 'ngCordova': {deps: ['angular']}
, 'cordova': {deps: ['ngCordova']}
, 'ionic': {deps: ['angular'], exports: 'ionic'}
, 'ngAnimate': {deps: ['angular']}
, 'ngSanitize': {deps: ['angular']}
, 'ngUiRouter': {deps: ['angular']}
, 'ngUiRouterExtras': {deps: ['ngUiRouter']}
, 'ionicAngular': {deps: ['ngAnimate', 'ngSanitize', 'ngUiRouter', 'ionic']}
, 'ngTimeline': {deps: ['angular']}
, 'ngMoment': {deps: ['angular', 'moment']}
, 'ngElastic': {deps: ['angular']}
, 'AutoLinker': {deps: ['angular']}
, 'restangular': {deps: ['angular', 'lodash']}
, 'angular-loading-bar': {deps: ['angular']}
, 'ng-tags-input': {deps: ['angular']}
, 'ionic-filter-bar': {deps: ['ionic']}
, 'google-libphonenumber': {exports: 'google-libphonenumber'}
, 'ion-sticky': {deps: ['ionic'], exports: 'ion-sticky'}
}
});
require([
'cordova'
,'angular'
,'app/namespace'
,'app/app'
,'app/routes'
],
function (cordova, angular, namespace) {
angular.element(document).ready(function() {
// since app/app depends on a lot of other stuff (by requirejs),
// so we just need to bootstrap ['app'] then all stuff in this project is up
angular.bootstrap(document, [namespace]);
});
});
|
// Functor 函子
// 面向对象写法
class Container {
constructor (value) {
this._value = value
}
map (fn) {
return new Container(fn(this._value))
}
}
let r = new Container(5)
.map(x => x + 1)
.map(x => x * x)
console.log(r) // Container { _value: 36 }
|
/* ------------------------------------
sec219 現在時刻とsetTimeout後の時刻を表示するサンプル
-------------------------------------*/
function sec219() {
let time219 = document.querySelector('#time219');
time219.innerHTML = '起動時の時刻' + new Date().toLocaleTimeString();
setTimeout(() => {
time219.innerHTML = 'setTimeout後の時刻' + new Date().toLocaleTimeString();
}, 1000);
}
/* ------------------------------------
sec221 現在時刻とsetInterval後の時刻を表示するサンプル
-------------------------------------*/
function sec221() {
let time221 = document.querySelector('#time221');
time221.innerHTML = '起動時の時刻' + new Date().toLocaleTimeString();
setInterval(() => {
time221.innerHTML = 'setInterval後の時刻' + new Date().toLocaleTimeString();
}, 1000);
}
/* ------------------------------------
sec222 現在時刻の表示を5秒後に解除するサンプル
-------------------------------------*/
function sec222() {
let count = 0;
let time222 = document.querySelector('#time222');
time222.innerHTML = '起動時の時刻' + new Date().toLocaleTimeString();
const intervalId = setInterval(timer222, 1000);
function timer222() {
count += 1;
time222.innerHTML = 'setInterval後の時刻' + new Date().toLocaleTimeString();
if (count === 5) {
clearInterval(intervalId);
}
};
}
/* ------------------------------------
sec223 1秒後に続く処理をPromiseを使って実行
-------------------------------------*/
function sec223() {
const promise = new Promise((resolve) => {
setTimeout(() => {
//resolve()を呼び出すとPromiseの処理が完了
resolve('次の処理');
}, 1000);
});
//then()で続く処理を記述
promise.then((value) => {
alert(value);
});
}
/* ------------------------------------
sec224 Promiseで処理の成功時・失敗時の処理を行う
-------------------------------------*/
function sec224() {
let flag;
document.querySelector('.resolve').addEventListener('click', () => {
flag = true;
promise224();
});
document.querySelector('.reject').addEventListener('click', () => {
flag = false;
promise224();
});
function promise224() {
const promise = new Promise((resolve, reject) => {
if (flag === true) {
resolve('成功');
} else {
reject('失敗');
}
});
//then
promise.then((value) => {
alert(value);
});
//catch
promise.catch((value) => {
alert(value);
});
}
//メソッドチェーンで記述
function sample() {
new Promise((resolve, reject) => {
if (flag === true) {
resolve('成功');
} else {
reject('失敗');
}
})
.then((value) => {
alert(value);
})
.catch((value) => {
alert(value);
});
}
} sec224();
/* ------------------------------------
sec225 Promiseで並列処理をする
-------------------------------------*/
function sec225() {
//非同期処理を行う関数の配列を作成
const arrFunc = [];
const log225 = document.querySelector('.log225');
for (let i = 0; i < 5; i++) {
//非同期処理を行う関数
const func = (resolve) => {
log225.insertAdjacentHTML('beforeend', `処理${i}を開始、`);
//0〜3秒で遅延
const delayMsec = 3000 * Math.random();
//遅延処理
setTimeout(() => {
log225.insertAdjacentHTML('beforeend', `<p>処理${i}が完了</p>`);
resolve();
}, delayMsec);
};
//配列に保存
arrFunc.push(func);
}
//上の配列をPromiseの配列に変換
const arrPromise = arrFunc.map((func) => new Promise(func));
//並列処理を実行
Promise.all(arrPromise).then(() => {
alert('すべての処理が完了しました');
});
}
/* ------------------------------------
sec226 Promiseで直列処理をする
-------------------------------------*/
function sec226() {
//Promiseのみ
function promise226() {
Promise.resolve()
.then(
() => new Promise((resolve) => {
setTimeout(() => {
alert('1つ目のPromise(Promiseのみ)');
resolve();
}, 1000);
})
)
.then(
() => new Promise((resolve) => {
setTimeout(() => {
alert('2つ目のPromise(Promiseのみ)');
resolve();
}, 1000);
})
);
}
//await・async
async function async226() {
await new Promise((resolve) => {
setTimeout(() => {
alert('1つ目のPromise(await・async)');
resolve();
}, 1000);
});
await new Promise((resolve) => {
setTimeout(() => {
alert('2つ目のPromise(await・async)');
resolve();
}, 1000);
});
}
//clickEvent
document.querySelector('.promise226').addEventListener('click', function () {
promise226();
});
document.querySelector('.async226').addEventListener('click', function () {
async226();
});
} sec226();
/* ------------------------------------
sec227 Promiseで動的に直列処理をする
-------------------------------------*/
function sec227() {
const log227 = document.querySelector('.log227');
//配列を作成
const listFuctions = [];
//動的に関数を追加
for (let i = 0; i < 5; i++) {
//1秒後に処理をする非同期関数を作成
const func = (resolve) => {
setTimeout(() => {
log227.insertAdjacentHTML('beforeend', `処理${i}が完了、`);
resolve(); //Promiseを完了
}, 1000);
};
//配列に保存
listFuctions.push(func);
}
//execute()
async function execute() {
//非同期処理を順番に実行
for (let i = 0; i < listFuctions.length; i++) {
const func = listFuctions[i];
await new Promise(func);
}
}
document.querySelector('.btn227').addEventListener('click', () => {
execute();
});
} sec227();
|
//Tipos de comunicación:
/*File communication (EXPRESS):
+El cliente pide al servido un archivo (Ex: playerImg.png)
mywebsite.com :2000 /client/playerImg.png
URL = DOMAIN PORT PATH*/
/*Package communication (Socket.io):
+El cliente envia datos al servidor (Ex: input)
+El servidor envia datos al cliente (Ex: Enemy position)*/
/*MONGO====MONGO====MONGO====MONGO====MONGO====MONGO====MONGO====MONGO====MONGO====MONGO====MONGO====MONGO*/
//var mongojs = require("mongojs");
var db = null;//var db = mongojs('localhost:27017/myGame', ['account', 'progress']); //url:puerto/bd, ['colección1', 'col2', etc.])
//db.account.insert({username:"b", password:"bb"}); //Insertar!!
/*========================================================================================================*/
/*EXPRESS====EXPRESS====EXPRESS====EXPRESS====EXPRESS====EXPRESS====EXPRESS====EXPRESS====EXPRESS====EXPRESS*/
var express = require('express');
var app = express();
var serv = require('http').Server(app); //Creamos el servidor
app.get('/', function(req, res){
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));
//De esta forma solo se puede acceder '/' (y te redirecciona a /client/index) y a lo que hay dentro de '/client'
//No se podría acceder, por ejemplo, a /server/archivoSecreto.xml
//serv.listen(2000); //El puerto al que escucha el servidor
serv.listen(process.env.PORT || 2000); //HEROKU
console.log("Servidor iniciado.")
/*===========================================================================================================*/
var SOCKET_LIST = {};
/*ENTITY====ENTITY====ENTITY====ENTITY====ENTITY====ENTITY====ENTITY====ENTITY====ENTITY====ENTITY====ENTITY*/
var Entity = function(param){
var self = {
x:250,
y:250,
spdX:0,
spdY:0,
id:"",
map:'house',
}
if(param){
if(param.x)
self.x = param.x;
if(param.y)
self.y = param.y;
if(param.map)
self.map = param.map;
if(param.id)
self.id = param.id;
}
self.update=function(){
self.updatePosition();
}
self.updatePosition = function(){
self.x += self.spdX;
self.y += self.spdY;
}
self.getDistance = function(pt){
return Math.sqrt(Math.pow(self.x-pt.x,2) + Math.pow(self.y-pt.y,2));
}
return self;
}
/*==========================================================================================================*/
/*BULLET====BULLET====BULLET====BULLET====BULLET====BULLET====BULLET====BULLET====BULLET====BULLET====BULLET====BULLET*/
var Bullet = function(param){
var self = Entity(param);
self.id = Math.random();
self.angle = param.angle;
self.spdX = Math.cos(self.angle/180*Math.PI) * 10;
self.spdY = Math.sin(self.angle/180*Math.PI) * 10;
self.parent = param.parent; //No puedes dispararte a ti mismo papu
self.timer = 0;
self.toRemove = false;
var super_update = self.update;
self.update = function(){
if(self.timer++ > 100)
self.toRemove = true;
super_update();
var minus = true;
for(var i in Player.list){
var p = Player.list[i];
if(self.map === p.map && self.getDistance(p) < 32 && self.parent !== p.id){
p.hp -= 1;
if(p.hp <= 0){ //Si ha muerto
var shooter = Player.list[self.parent];
if(shooter) //Si el que dispara no se ha desconectado (porque no podríamos sumarle en el score)
shooter.score += p.score+1;
p.hp = p.hpMax;
p.x = Math.random() * 500;
p.y = Math.random() * 500;
p.score = 0;
}
self.toRemove = true;
}
}
}
self.getInitPack = function(){
return{
id:self.id,
x:self.x,
y:self.y,
map:self.map,
};
}
self.getUpdatePack = function(){
return{
id:self.id,
x:self.x,
y:self.y,
};
}
Bullet.list[self.id] = self;
initPack.bullet.push(self.getInitPack());
return self;
}
Bullet.list = {};
Bullet.update = function(){
var pack = [];
for(var i in Bullet.list){
var bullet = Bullet.list[i];
bullet.update();
if(bullet.toRemove){
delete Bullet.list[i];
removePack.bullet.push(bullet.id);
}else{
pack.push(bullet.getUpdatePack());
}
}
return pack;
}
Bullet.getAllInitPack = function(){
var bullets = [];
for(var i in Bullet.list)
bullets.push(Bullet.list[i].getInitPack());
return bullets;
}
/*====================================================================================================================*/
/*PLAYER====PLAYER====PLAYER====PLAYER====PLAYER====PLAYER====PLAYER====PLAYER====PLAYER====PLAYER====PLAYER====PLAYER*/
var Player = function(param){
var self = Entity(param);
self.number = "" + Math.floor(9 * Math.random()+1);
self.username = param.username;
self.muerto = false;
self.pressingRight = false;
self.pressingLeft = false;
self.pressingUp = false;
self.pressingDown = false;
self.pressingAttack = false;
self.mouseAngle = 0;
self.bulletTime = 0;
self.hp = 10;
self.hpMax = 10;
self.score = 0;
self.maxSpd = 5;
var super_update = self.update; //La de ENTITY
self.update = function(){
self.updateSpd(); //Calcula la velocidad
super_update(); //Llama al update() de ENTITY
if(self.pressingAttack && self.bulletTime === 0){
self.shootBullet(self.mouseAngle);
self.bulletTime += 1;
}
if(self.bulletTime !== 0){
self.bulletTime += 1;
if(self.bulletTime === 10)
self.bulletTime = 0;
}
}
self.shootBullet = function(angle){
Bullet({
parent:self.id,
angle: angle,
x:self.x,
y:self.y,
map:self.map,
});
}
self.updateSpd = function(){
if(self.pressingRight)
self.spdX = self.maxSpd;
else if(self.pressingLeft)
self.spdX = -self.maxSpd;
else
self.spdX = 0;
if(self.pressingDown)
self.spdY = self.maxSpd;
else if(self.pressingUp)
self.spdY = -self.maxSpd;
else
self.spdY = 0;
if((self.pressingDown || self.pressingUp) && (self.pressingLeft || self.pressingRight)){ //PARA QUE EN DIAGONAL NO VAYA MÁS RÁPIDO
self.spdX = self.spdX*0.75;
self.spdY = self.spdY*0.75;
}
}
self.getInitPack = function(){
return{
id:self.id,
x:self.x,
y:self.y,
number:self.number,
hp:self.hp,
hpMax:self.hpMax,
score:self.score,
map:self.map,
};
}
self.getUpdatePack = function(){
return{
id:self.id,
x:self.x,
y:self.y,
hp:self.hp,
score:self.score,
map:self.map,
};
}
Player.list[self.id] = self;
initPack.player.push(self.getInitPack());
return self;
}
Player.list = {};
Player.onConnect = function(socket,username){
var map = 'house';
if(Math.random() < 0.5)
map = 'field';
var player = Player({
username:username,
id:socket.id,
map:map,
});
socket.on('keyPress', function(data){
if(data.inputId === 'left')
player.pressingLeft = data.state;
if(data.inputId === 'right')
player.pressingRight = data.state;
if(data.inputId === 'up')
player.pressingUp = data.state;
if(data.inputId === 'down')
player.pressingDown = data.state;
if(data.inputId === 'attack')
player.pressingAttack = data.state;
if(data.inputId === 'mouseAngle')
player.mouseAngle = data.state;
});
socket.on('changeMap', function(data){
if(player.map === 'field')
player.map = 'house';
else
player.map = 'field';
});
//CHAT
socket.on('sendMsgToServer', function(data){
for(var i in SOCKET_LIST){
SOCKET_LIST[i].emit('addToChat', player.username + ': ' + data);
}
});
socket.on('sendPmToServer', function(data){ //data:{username,message}
var recipientSocket = null;
for(var i in Player.list)
if(Player.list[i].username === data.username)
recipientSocket = SOCKET_LIST[i];
if(recipientSocket === null){
socket.emit('addToChat','El usuario '+ data.username +' no está en linea o no existe.')
}else{
recipientSocket.emit('addToChat', 'De '+player.username+': '+data.message);
socket.emit('addToChat', 'Para '+data.username+': '+data.message);
}
});
socket.emit('init',{
selfId:socket.id,
player: Player.getAllInitPack(),
bullet: Bullet.getAllInitPack(),
});
}
Player.getAllInitPack = function(){
var players = [];
for(var i in Player.list)
players.push(Player.list[i].getInitPack());
return players;
}
Player.onDisconnect = function(socket){
delete Player.list[socket.id];
removePack.player.push(socket.id);
}
Player.update = function(){
var pack = [] //tendrá la información de cada player
for(var i in Player.list){
var player = Player.list[i];
player.update(); //Muevete vago!
pack.push(player.getUpdatePack());
}
return pack;
}
/*====================================================================================================================*/
var DEBUG = true; //PELIGRO PAPU PELIGRO
var USERS = {
//username:password
"cosa":"cosa",
"coso":"coso",
"cosi":"cosi",
}
var isValidPassword = function(data,callback){
return callback(true);
/*db.account.find({username:data.username, password:data.password},function(error, result){
if(result.length > 0)
callback(true);
else
callback(false);
});*/
}
var isUsernameTaken = function(data,callback){
return callback(false);
/*db.account.find({username:data.username},function(error, result){
if(result.length > 0)
callback(true);
else
callback(false);
});*/
}
var addUser = function(data,callback){
return callback();
/*db.account.insert({username:data.username, password:data.password},function(error){
callback();
});*/
}
/*SOCKET.IO====SOCKET.IO====SOCKET.IO====SOCKET.IO====SOCKET.IO====SOCKET.IO====SOCKET.IO====SOCKET.IO====SOCKET.IO*/
var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket){
socket.id = Math.random(); //CAMBIAR ESTO A ALGO MAS PRO
SOCKET_LIST[socket.id] = socket;
//Player.onConnect(socket);
socket.on('disconnect', function(){
delete SOCKET_LIST[socket.id];
Player.onDisconnect(socket);
});
socket.on('evalServer', function(data){
if (!DEBUG){
socket.emit('evalAnswer', "DEBUG MODE OFF");
return;
}
//Esto es peligroso D:
var res = eval(data);
socket.emit('evalAnswer', res);
});
//LOGIN - REGISTRO
socket.on('signIn',function(data){ //{username,password}
isValidPassword(data,function(res){
if(res){
Player.onConnect(socket,data.username);
socket.emit('signInResponse',{success:true});
} else {
socket.emit('signInResponse',{success:false});
}
});
});
socket.on('signUp',function(data){
isUsernameTaken(data,function(res){
if(res){
socket.emit('signUpResponse',{success:false});
} else {
addUser(data,function(){
socket.emit('signUpResponse',{success:true});
});
}
});
});
});
/*=================================================================================================================*/
/*LOOP====LOOP====LOOP====LOOP====LOOP====LOOP====LOOP====LOOP====LOOP====LOOP====LOOP====LOOP====LOOP====LOOP*/
var initPack = {player:[], bullet:[]};
var removePack = {player:[], bullet:[]};
setInterval(function(){ //LOOP
var pack = { //tendrá la información de los player y las bullets
player: Player.update(),
bullet: Bullet.update(),
}
for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
socket.emit('init',initPack);
socket.emit('update',pack);
socket.emit('remove',removePack);
}
initPack.player = [];
initPack.bullet = [];
removePack.bullet = [];
removePack.player = [];
},1000/50); //Será llamado cada 40ms
/*============================================================================================================*/
|
var shequhudong=document.getElementById("shequhudong");
var shouQ=document.getElementById("shouQ");
var weixinGZH=document.getElementById("weixinGZH");
var weixinQZ=document.getElementById("weixinQZ");
var guangfangWB=document.getElementById("guangfangWB");
var tipsPlayer=document.getElementById("tipsPlayer");
var tips_img1=document.getElementById("tips-img1");
var tips_img2=document.getElementById("tips-img2");
var tips_img3=document.getElementById("tips-img3");
var tips_img4=document.getElementById("tips-img4");
shequhudong.onmouseover=function(){
tipsPlayer.style.display="block";
};
shequhudong.onmouseout=function(){
tipsPlayer.style.display="none";
};
shouQ.onmouseover=function(){
tips_img1.style.display="block";
tips_img2.style.display="none";
tips_img3.style.display="none";
tips_img4.style.display="none";
shouQ.className="on";
weixinGZH.className="";
weixinQZ.className="";
guangfangWB.className="";
};
shouQ.onmouseout=function(){
tips_img1.style.display="none";
shouQ.className="";
};
weixinGZH.onmouseover=function(){
tips_img1.style.display="none";
tips_img2.style.display="block";
tips_img3.style.display="none";
tips_img4.style.display="none";
shouQ.className="";
weixinGZH.className="on";
weixinQZ.className="";
guangfangWB.className="";
};
weixinGZH.onmouseout=function(){
tips_img2.style.display="none";
weixinGZH.className="";
};
weixinQZ.onmouseover=function(){
tips_img1.style.display="none";
tips_img2.style.display="none";
tips_img3.style.display="block";
tips_img4.style.display="none";
shouQ.className="";
weixinGZH.className="";
weixinQZ.className="on";
guangfangWB.className="";
};
weixinQZ.onmouseout=function(){
tips_img3.style.display="none";
weixinQZ.className="";
};
guangfangWB.onmouseover=function(){
tips_img1.style.display="none";
tips_img2.style.display="none";
tips_img3.style.display="none";
tips_img4.style.display="block";
shouQ.className="";
weixinGZH.className="";
weixinQZ.className="";
guangfangWB.className="on";
};
guangfangWB.onmouseout=function(){
tips_img4.style.display="none";
guangfangWB.className="";
};
var YXZL=document.getElementById("YXZL");
var yx_sub=document.getElementById("yx_sub");
var wuqiPJ=document.getElementById("wuqiPJ");
var banbenGX=document.getElementById("banbenGX");
YXZL.onmouseover=function(){
yx_sub.style.display="block";
};
YXZL.onmouseout=function(){
yx_sub.style.display="none";
};
wuqiPJ.onmouseover=function(){
wuqiPJ.style.color="#ffb400";
};
wuqiPJ.onmouseout=function(){
wuqiPJ.style.color="#ffffff";
};
banbenGX.onmouseover=function(){
banbenGX.style.color="#ffb400";
};
banbenGX.onmouseout=function(){
banbenGX.style.color="#ffffff";
};
var ost_go=document.getElementById("ost_go")
var ost_d=document.getElementById("ost_d");
var ost_g=document.getElementById("ost_g");
ost_g.onmouseover=function(){
ost_go.style.display="none";
ost_d.style.display="block";
};
ost_d.onmouseout=function(){
ost_go.style.display="block";
ost_d.style.display="none";
};
|
class EditorCtrl {
constructor(Articles, article, $state) {
'ngInject';
this._Articles = Articles;
this._$state = $state;
if (!article) {
this.article = {
title: '',
description: '',
body: '',
tagList: []
};
} else {
this.article = article;
}
}
submit() {
this.isSubmitting = true;
this._Articles.save(this.article).then(
(newArticle) => {
this._$state.go('app.article', { slug: newArticle.slug });
},
(err) => {
this.isSubmitting = false;
this.errors = err.data.errors;
}
);
}
addTag() {
if (!this.article.tagList.includes(this.tagField)) {
this.article.tagList.push(this.tagField);
this.tagField = '';
}
}
removeTag(tagName) {
var indexOf = this.article.tagList.indexOf(tagName);
if (indexOf != -1) {
this.article.tagList.splice(indexOf, 1);
}
// We can also use array.filter but this will iterate through all the items and also
// generate a new array, which is not what I personally preffer.
// You decide if you preffer to pay "readability" (and coolness) with inneficiency, if it's your choice:
/*
this.article.tagList = this.article.tagList.filter(
(slug) => slug != tagName
);
*/
}
}
export default EditorCtrl;
|
/////////////////////////////////////////////
//////////////// EXPORTING REQUIRED MODULES
const crypto = require('crypto'); // it is build in node module so no need to install it.
const mongoose = require('mongoose');
const validator = require('validator');
const bcrypt = require('bcryptjs');
/////////////////////////////////////////////////////////
/////////////// CREATING A SCHEMA
// name, email, photo, password, passwordConfirm
const userSchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
required: [true, 'Please tell us your name'],
},
email: {
type: String,
required: [true, 'Please provide your email'],
unique: true,
lowercase: true, // it will automatically transform the email into lowercase
validate: [validator.isEmail, 'please provide a valid email'],
},
photo: {
type: String,
},
role: {
type: String,
enum: ['user', 'guide', 'lead-guide', 'admin'],
default: 'user',
},
password: {
type: String,
required: [true, 'please provide a password'],
minlength: 8,
select: false,
},
passwordConfirm: {
type: String,
required: [true, 'please confirm your password'],
validate: {
// this only works on save & create!!!
validator: function (el) {
return el === this.password;
},
message: 'passowrds are not same!',
},
},
passwordChangedAt: Date,
passwordResetToken: String,
passwordResetExpires: Date,
active: {
type: Boolean,
default: true,
select: false, // not allowed user to see it
},
},
{}
);
/////////////////////////////////////////////////////////////////
////////// USING MONGOOSE PRE MIDDLEWARE TO ENCRYPT THE PASSWORD.
// its best time to manipulate the data before saving (i.e encrypting the password)
userSchema.pre('save', async function (next) {
// isModified is the function provided by mongoose which we can use on documents if password is not modified return immediatly by calling next;
if (!this.isModified('password')) return next();
// hash function will take two arguments first one is user password and second one is cost to the cpu, default value for cost is 10, but we used 12
this.password = await bcrypt.hash(this.password, 12); // it will encrypt the user password
this.passwordConfirm = undefined;
// passwordConfirm is required for the input not to be persisted in the database
next();
});
userSchema.pre('save', function (next) {
// we want to save the password only when it will get modified othewise no need to save the password & other case when documents is new in that case as well we don't want to call this middleware.
if (!this.isModified('password') || this.isNew) return next();
// it will ensure that token has been created after the password changed.
this.passwordChangedAt = Date.now() - 1000;
next();
});
// we don't want to see the deleted user in our getAllUser method for that we will use queryMiddleware this middleware apply to all the query that start with find
userSchema.pre(/^find/, function (next) {
// this points to current query
this.find({ active: { $ne: false } });
next();
});
/////////////////////////////
//////////// INSTANCE METHODS
// Instance method is a method which will be available on all the documents of certain collection. In instance method this always points to current documents
userSchema.methods.correctPassword = async function (
candidatePassword,
userPassword
) {
return await bcrypt.compare(candidatePassword, userPassword);
};
userSchema.methods.changedPasswordAfter = function (JWTTimestamp) {
if (this.passwordChangedAt) {
// getTime will give us time in millisecond so we need to convert it in seconds parseInt takes two arguments one is no itself and second is base to which we want to convert.
const changedTimestamp = parseInt(
this.passwordChangedAt.getTime() / 1000,
10
);
return JWTTimestamp < changedTimestamp;
}
// FALSE means NOT changed
return false;
};
userSchema.methods.createPasswordResetToken = function () {
// creating a random token
const resetToken = crypto.randomBytes(32).toString('hex');
// encrypting the randomly created token, never store plan reset token in data base if hacker get access to it then they may change your password
this.passwordResetToken = crypto
.createHash('sha256') // sha256 alogrithm
.update(resetToken)
.digest('hex');
// setting expiry date to this token
this.passwordResetExpires = Date.now() + 10 * 60 * 1000;
// returning plan text token to the user
return resetToken;
};
///////////////////////////////////////////////
//////////// CREATE A MODEL FROM THE SCHEMA
const User = mongoose.model('User', userSchema);
module.exports = User;
|
import Settings, { HIDE_FROM_EVERYONE_OPTION } from '../settings/index.js';
import { CSS_PREFIX } from '../module.js';
import { icon, emptyNode, img, div, span, appendText } from './html.js';
import { updateCustomAttributeRow } from './custom-attribute-display.js';
import * as attributeLookups from '../attribute-lookups/index.js';
import AttributeRow, { calculateValue } from './attribute-row.js';
const CSS_TOOLTIP = `${CSS_PREFIX}tooltip`;
const CSS_NAME = `${CSS_PREFIX}name`;
const CSS_DATA = `${CSS_PREFIX}data`;
const CSS_SHOW = `${CSS_PREFIX}show`;
const CSS_ROW = `${CSS_PREFIX}row`;
const CSS_LABEL = `${CSS_PREFIX}label`;
const CSS_VALUE = `${CSS_PREFIX}value`;
const CSS_CURRENT = `${CSS_PREFIX}current`;
const CSS_MAX = `${CSS_PREFIX}max`;
const CSS_TEMP = `${CSS_PREFIX}temp`;
class StandardRow {
constructor(attributeLookup, minimumPermissionSetting, hideFromGMSetting) {
this.attributeLookup = attributeLookup;
this.minimumPermissionSetting = minimumPermissionSetting;
this.hideFromGMSetting = hideFromGMSetting;
this.row = null;
}
update(tooltip, actor) {
if (showDataType(actor, this.minimumPermissionSetting, this.hideFromGMSetting)) {
if (this.row === null) {
this.row = new AttributeRow(this.attributeLookup.label(), this.attributeLookup.icon());
}
tooltip._updateRow(this.row, this.attributeLookup.value(actor));
}
}
}
class Tooltip {
constructor() {
this.element = div(CSS_TOOLTIP);
this.nameElement = div(CSS_NAME);
this.element.appendChild(this.nameElement);
this.dataElement = div(CSS_DATA);
this.element.appendChild(this.dataElement);
this.standardRows = [
new StandardRow(
attributeLookups.hp,
Settings.HPMinimumPermission,
Settings.HidePlayerHPFromGM
),
new StandardRow(
attributeLookups.ac,
Settings.ACMinimumPermission,
Settings.HidePlayerACFromGM
),
];
for (let movement of attributeLookups.movements) {
this.standardRows.push(
new StandardRow(
movement,
Settings.MovementMinimumPermission,
Settings.HidePlayerMovementFromGM
)
);
}
for (let passive of attributeLookups.passives) {
this.standardRows.push(
new StandardRow(
passive,
Settings.PassivesMinimumPermission,
Settings.HidePlayerPassivesFromGM
)
);
}
for (let damageResImmVuln of attributeLookups.damageResImmVuln) {
this.standardRows.push(
new StandardRow(
damageResImmVuln,
Settings.DmgResVulnMinimumPermission,
Settings.HidePlayerDmgResVulnFromGM
)
);
}
for (let conditionImmunity of attributeLookups.conditionImmunities) {
this.standardRows.push(
new StandardRow(
conditionImmunity,
Settings.CondImmMinimumPermission,
Settings.HidePlayerCondImmFromGM
)
);
}
for (let resource of attributeLookups.resources) {
this.standardRows.push(
new StandardRow(
resource,
Settings.ResourcesMinimumPermission,
Settings.HidePlayerResourcesFromGM
)
);
}
for (let spellSlot of attributeLookups.spellSlots) {
this.standardRows.push(
new StandardRow(
spellSlot,
Settings.SpellsMinimumPermission,
Settings.HidePlayerSpellsFromGM
)
);
}
this.customRows = [];
document.body.appendChild(this.element);
window.addEventListener('mousedown', () => {
this.element.classList.remove(CSS_SHOW);
});
Hooks.on('hoverToken', (token, hovered) => {
this.onHover(token, hovered);
});
}
onHover(token, hovered) {
if (hovered && shouldShowTooltip(token)) {
this.updateData(token);
this.fixPosition(token);
this.show();
} else {
this.hide();
}
}
fixPosition(token) {
if ( Settings.ShowOnLeft.get() ) {
const right = window.innerWidth - Math.ceil(token.worldTransform.tx - 8);
this.element.style.right = `${right}px`;
this.element.style.left = '';
} else {
const tokenWidth = token.w * canvas.stage.scale.x;
const left = Math.ceil(token.worldTransform.tx + tokenWidth + 8);
this.element.style.left = `${left}px`;
this.element.style.right = '';
}
const top = Math.floor(token.worldTransform.ty - 8);
this.element.style.top = `${top}px`;
}
show() {
this.element.classList.add(CSS_SHOW);
}
hide() {
this.element.classList.remove(CSS_SHOW);
}
updateData(token) {
this.clearElements();
this.updateName(token);
const actor = token.actor;
for (let standardRow of this.standardRows) {
standardRow.update(this, actor);
}
this.updateItems(actor);
this.updateCustomRows(actor);
}
clearElements() {
emptyNode(this.nameElement);
emptyNode(this.dataElement);
}
updateName(token) {
this.nameElement.appendChild(document.createTextNode(token.name));
}
_updateRow(row, attribute) {
const value = calculateValue(attribute);
if (value) {
row.setValue(value);
this.dataElement.appendChild(row.element);
}
}
updateItems(actor) {
if (showDataType(actor, Settings.ItemsMinimumPermission, Settings.HidePlayerItemsFromGM)) {
const items = attributeLookups.items.get(actor);
for (let item of items) {
const attributeRow = new AttributeRow(item.name, item.icon);
this._updateRow(attributeRow, item.value);
}
}
}
updateCustomRows(actor) {
const customRows = Settings.CustomOptions.get();
if (!customRows || customRows.length === 0) {
return;
}
customRows.forEach((customRow, i) => {
if (!showDataType(actor, customRow.permission, customRow.hideFromGM)) {
return;
}
const row = updateCustomAttributeRow(actor, customRow, this.customRows, i);
if (row) {
this.dataElement.appendChild(row.element);
}
});
}
sortAndAdd(attributeArray) {
attributeArray.sort(attributeSort);
attributeArray.forEach((attr) => {
this.dataElement.appendChild(attr.element);
});
}
}
const perm = (minimumPermissionSetting) => {
if (!minimumPermissionSetting) {
return 'NONE';
}
if (typeof minimumPermissionSetting === 'string') {
return minimumPermissionSetting;
}
return minimumPermissionSetting.get() || 'NONE';
};
const boolOrBoolSetting = (boolSetting) => {
if (typeof boolSetting === 'boolean') {
return boolSetting;
}
return boolSetting && boolSetting.get();
};
const showDataType = (actor, minimumPermissionSetting, hideFromGMSetting) => {
const minimumPermission = perm(minimumPermissionSetting);
if (minimumPermission === HIDE_FROM_EVERYONE_OPTION) {
return false;
} else if (game.user.isGM) {
return !(actor.hasPlayerOwner && boolOrBoolSetting(hideFromGMSetting));
} else {
return actor.hasPerm(game.user, minimumPermission);
}
};
const attributeSort = (a, b) => {
return a.sort - b.sort;
};
const shouldShowTooltip = (token) => {
if (!(token && token.actor)) {
return false;
}
if (game.user.isGM) {
return true;
}
return Settings.Visibility.shouldShowTooltip(token);
};
Hooks.once('ready', () => {
new Tooltip();
});
|
import { connect } from 'react-redux';
import LoadSettings from '../components/LoadSettings';
import { GetSettings } from '../utils/db';
import { SCALE_CHANGED } from '../actions/file';
import { setImageScale } from '../features/note/noteSlice';
// this is obsolete
function asyncLoadSettings() {
return (dispatch) => {
console.log('111');
return GetSettings().then((settings) => {
console.log('got settings ', settings);
if ((settings || {}).scale) {
dispatch({ type: SCALE_CHANGED, scale: settings.scale });
}
if ((settings || {}).noteImageScale) {
console.log('load noteImageScale = ', settings.noteImageScale);
dispatch(setImageScale(settings.noteImageScale));
}
return true;
});
};
}
function mapDispatchToProps(dispatch) {
return {
loadSettings: () => dispatch(asyncLoadSettings()),
};
}
export default connect(null, mapDispatchToProps)(LoadSettings);
|
function Hidden(x, y){
this.x = x;
this.y = y;
this.width = 15;
this.height = 20;
}
Hidden.prototype.draw = function(){
ctx.drawImage(hiddenPaper, this.x, this.y, this.width, this.height);
}
|
const {Schema, model, Types} = require('mongoose')
const schema = new Schema({
_idList: Schema.Types.ObjectId,
title: {type: String, required: true},
completed: {type: Boolean,default: false}
})
module.exports = model('Todo', schema)
|
import React from "react";
import "./Logo.css";
const Logo = () => {
const onMenuEvent = (e) => {
const navigation = e.target.parentNode.parentNode.parentNode;
navigation.classList.toggle("open");
e.target.attributes[0].value = (navigation.classList.contains("open")) ? "chevrons-left" : "chevrons-right";
}
return (
<div className="logo_content">
<div className="logo">
<box-icon name='game'/>
<div className="logo_name">Title</div>
</div>
<div id="nav_btn" onClick={onMenuEvent}>
<box-icon name='chevrons-left'/>
</div>
</div>
)
}
export default Logo;
|
const path = require('path');
const express = require('express');
const PORT = process.env.PORT || 3000;
const { FORGE_CLIENT_ID, FORGE_CLIENT_SECRET, MODEL_URN } = process.env;
if (!FORGE_CLIENT_ID || !FORGE_CLIENT_SECRET || !MODEL_URN) {
console.warn('Some of the following env. variables are missing: FORGE_CLIENT_ID, FORGE_CLIENT_SECRET, MODEL_URN');
return;
}
const app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', require('./routes/api'));
app.listen(PORT || 3000, function() { console.log(`HTTP server listening on port ${PORT}`); });
|
export default {
transformers: {
name: 'index.js',
options: {
useEslintrc: false,
envs: ['browser'],
rules: {
'no-unused-vars': 2,
quotes: [1, 'single', 'avoid-escape']
}
}
}
}
|
var express = require('express');
var path = require('path');
var less = require('express-less');
exports.initialize = function(app, RedisStore){
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/less', less(__dirname + '/less', { compress: true }));
app.use(express.cookieParser());
app.use(express.session({
store : new RedisStore({host: 'localhost', port: 6379}),
secret: 'change-this-to-a-super-secret-message',
cookie: { maxAge: 60 * 60 * 1000 }
}));
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:9000');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
// res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Headers', 'content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
// res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.use(app.router);
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
};
|
import React, { Component } from 'react'
import { Text, View, Image } from 'react-native'
export const ImageCard = ({ img, score }) => {
return (
<View>
<Text> textInComponent </Text>
<Image
style={{ width: '100%', height: 250 }}
source={img}
/*source={{ uri: img }}*/ />
<Text>Score is - {score + 1}</Text>
</View>
)
}
export default ImageCard
|
import React from 'react';
import { Link } from "react-router-dom";
import {
AssignmentOutlined, ChatBubbleOutline, DashboardOutlined
} from "@material-ui/icons";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import HomeOutlined from "@material-ui/icons/HomeOutlined";
import Drawer from "@material-ui/core/Drawer";
import Divider from "@material-ui/core/Divider";
import { Typography, useTheme, IconButton } from '@material-ui/core';
export default function Menu({ classes, handleDrawerClose, open }) {
const theme = useTheme();
return (
<Drawer
className={classes.drawer}
variant="persistent"
anchor="left"
open={open}
classes={{
paper: classes.drawerPaper
}}
>
<div className={classes.drawerHeader}>
<IconButton onClick={handleDrawerClose}>
{theme.direction === "ltr" ? (
<ChevronLeftIcon color="secondary" />
) : (
<ChevronRightIcon color="secondary" />
)}
</IconButton>
</div>
<Divider />
<ListItem button component={Link} to={"/provider/home"}>
<ListItemIcon>
<HomeOutlined color="secondary" />
</ListItemIcon>
<ListItemText
className={classes.colorsecondary}
secondary={<Typography color="secondary">Home</Typography>} />
</ListItem>
<Divider />
<ListItem button component={Link} to={"/provider/dashboard"}>
<ListItemIcon>
<DashboardOutlined color="secondary" />
</ListItemIcon>
<ListItemText
className={classes.colorsecondary}
secondary={<Typography color="secondary">Dashboard</Typography>}
/>
</ListItem>
<Divider />
<ListItem button component={Link} to={"/provider/modalities"}>
<ListItemIcon>
<AssignmentOutlined color="secondary" />
</ListItemIcon>
<ListItemText
className={classes.colorsecondary}
secondary={<Typography color="secondary">Modalidades</Typography>}
/>
</ListItem>
<Divider />
<ListItem button component={Link} to={"/provider/negociations"}>
<ListItemIcon>
<ChatBubbleOutline color="secondary" />
</ListItemIcon>
<ListItemText
className={classes.colorsecondary}
secondary={<Typography color="secondary">Negociações</Typography>}
/>
</ListItem>
</Drawer>
);
}
|
import React, { Component } from 'react'
import styled from 'styled-components'
import {
Table,
HeaderRow,
HeaderCell,
BodyRow,
BodyCell,
TableThumb,
Sorter
} from '../../mia-ui/tables'
import { Link, NextA } from '../../mia-ui/links'
import { Button } from '../../mia-ui/buttons'
import PropTypes from 'prop-types'
import ImgSrcProvider from '../../shared/ImgSrcProvider'
import { Search } from '../../mia-ui/forms'
import { Box } from 'grid-styled'
const Thumb = ImgSrcProvider(TableThumb)
export default class StoryList extends Component {
static defaultProps = {
stories: []
}
static propTypes = {
stories: PropTypes.array.isRequired
}
state = {
variables: this.props.variables
}
render() {
// if (!this.props.variables) return null
//
// if (!this.props.variables.search) return null
const {
handleLoadMore,
handleSort,
handleSearch,
props: {
stories,
router: {
query: { subdomain }
},
organization
},
state: { variables }
} = this
return (
<Table id={'story-list'}>
<Box>
<Search
value={variables.filter.search || ''}
name={'search'}
onChange={handleSearch}
/>
</Box>
<HeaderRow>
<HeaderCell width={[1 / 3, 1 / 6]} />
<HeaderCell width={[1 / 3, 1 / 3]}>
Title
<Sorter
variables={variables}
column={'title'}
upValue={'ASC'}
downValue={'DESC'}
onSort={handleSort}
/>
</HeaderCell>
<HeaderCell width={[0, 1 / 5]}>Template</HeaderCell>
<HeaderCell width={[0, 1 / 5]}>
Updated
<Sorter
variables={variables}
column={'updatedAt'}
upValue={'ASC'}
downValue={'DESC'}
onSort={handleSort}
/>
</HeaderCell>
</HeaderRow>
{stories
? stories.map(
({
id: storyId,
previewImage,
title,
updatedAt,
template,
slug: storySlug
}) => (
<BodyRow key={storyId}>
<BodyCell width={[1 / 3, 1 / 6]}>
{previewImage ? (
<NextA
href={{
pathname: '/cms/edit',
query: {
subdomain,
storySlug
}
}}
as={`/${subdomain}/${storySlug}`}
>
<Thumb image={previewImage} />
</NextA>
) : null}
</BodyCell>
<BodyCell width={[1 / 3, 1 / 3]}>
<Link
href={{
pathname: '/cms/edit',
query: {
subdomain,
storySlug
}
}}
as={`/${subdomain}/${storySlug}`}
>
{title || 'Untitled Story'}
</Link>
</BodyCell>
<BodyCell width={[0, 1 / 5]}>{template}</BodyCell>
<BodyCell width={[0, 1 / 5]}>
{new Date(updatedAt).toLocaleDateString()}
</BodyCell>
</BodyRow>
)
)
: null}
</Table>
)
}
bounce = true
debounce = (func, wait) => {
if (this.bounce) {
clearTimeout(this.bounce)
this.bounce = setTimeout(func, wait)
}
}
handleSearch = ({ target: { name, value } }) => {
this.setState(
({ variables: oldVariables }) => {
let variables = { ...oldVariables }
variables.filter.search = value
return {
variables
}
},
() => {
this.debounce(() => this.props.refetch(this.state.variables), 2000)
}
)
}
handleSort = ({ column, newValue }) => {
this.setState(
prevState => {
let variables = { ...this.props.variables }
for (let [index, order] of variables.filter.order.entries()) {
if (order.column === column) {
variables.filter.order.splice(index, 1)
variables.filter.order.unshift({
column,
direction: newValue
})
return {
variables
}
}
}
variables.filter.order.unshift({
column,
direction: newValue
})
return {
variables
}
},
() => {
this.props.refetch(this.state.variables)
}
)
}
handleLoadMore = async () => {
try {
const {
props: { fetchMore, stories },
state: { variables }
} = this
let newVariables = {
filter: {
...variables.filter,
limit: variables.filter.limit,
offset: this.props.stories.length
}
}
fetchMore({
variables: newVariables,
updateQuery: (previousResult, { fetchMoreResult }) => {
if (!fetchMoreResult) {
return previousResult
}
return Object.assign({}, previousResult, {
stories: [...previousResult.stories, ...fetchMoreResult.stories]
})
}
})
} catch (ex) {
console.error(ex)
}
}
}
|
import React from "react";
import styled from "styled-components";
const Wrapper = styled.div`
width: 100%;
display: flex;
justify-content: center;
`;
const Loading = props => (
<Wrapper className="Loading">
<p>Loading...</p>
</Wrapper>
);
export default Loading;
|
const io = require('socket.io')();
// handling client connection
io.on('connection', (client) => {
// here you can also respond to events being emitted from the client
client.on('subscribeToTimer', (interval) => {
console.log('client is subscribing to timer with interval ', interval);
setInterval(function () {
// here you can start emitting events
client.emit('timer', new Date());
}, interval);
})
});
const port = 8000;
io.listen(port);
console.log('listening on port ', port);
|
import React from "react";
class Link extends React.Component {
render() {
let {title, url} = this.props.link;
return (
<div className="link">
<a href={url}>{title}</a>
</div>
);
}
}
export default Link;
|
/** @jsx jsx */
import StyledComponent, { Container } from '../StyledComponent';
import { css } from '@emotion/react';
import styled from '@emotion/styled/macro';
import { jsx } from 'theme-ui';
const Pumpkin = styled(StyledComponent)`
bottom: 0;
left: 20px;
background: #c54c17;
width: 100px;
height: 80px;
border-radius: 50px;
z-index: 2;
&::before {
background-color: #ee8228;
border-radius: 40px;
width: 50%;
height: 100%;
left: 25%;
}
&::after {
width: 50%;
height: 100%;
left: 0;
background-color: rgba(160, 32, 3, 0.4);
border-radius: 50px 0 0 50px;
}
&:nth-of-type(3) {
left: 60%;
transform: scale(0.7);
transform-origin: bottom center;
}
&:nth-of-type(2) {
left: 60px;
transform: scale(0.5);
transform-origin: bottom center;
}
`;
const PumpkinTop = styled(StyledComponent)`
width: 30px;
height: 30px;
border: 10px solid #329399;
border-radius: 0 50px 0 0;
border-bottom: 0;
border-left: 0;
z-index: -1;
top: -20px;
left: 25px;
`;
const DynamicShadowStyle = ({ theme: { colors } }) => css`
background-color: transparent !important;
transform: scale(1.05, 1.1) translateY(-5px);
*,
*:after,
*:before,
* > * {
background-color: ${colors.shadow.dark} !important;
box-shadow: none !important;
}
${PumpkinTop} {
background-color: transparent !important;
border-color: ${colors.shadow.dark};
}
`;
const PumpkinContainer = styled(StyledComponent)`
bottom: 22px;
left: 22px;
height: 100px;
width: 100%;
${({ shadow }) => shadow && DynamicShadowStyle};
`;
const StyledPumpkins = (props) => (
<PumpkinContainer {...props}>
<Pumpkin>
<PumpkinTop />
</Pumpkin>
<Pumpkin>
<PumpkinTop />
</Pumpkin>
</PumpkinContainer>
);
const Pumpkins = (props) => (
<Container {...props}>
<StyledPumpkins shadow />
<StyledPumpkins />
</Container>
);
export default Pumpkins;
|
const categoryController = require('../controllers/categoryController');
module.exports = (app) => {
app.route('/categories')
.post(categoryController.createCategory)
.get(categoryController.getAllCategories)
.delete(categoryController.deleteAllCategories);
app.route('/categories/:categoryId')
.get(categoryController.getCategory)
.delete(categoryController.deleteCategory);
};
|
import React from 'react'
import { ListOfCategories } from './components/listOfCategories'
import { ListOfPhotoCard } from './components/listOfPhotoCard'
import { GlobalStyle } from './GlobalStyles'
const App = () => {
return (
<>
<GlobalStyle />
<ListOfCategories />
<ListOfPhotoCard />
</>
)
}
export default App
|
import React, { Component } from 'react'
import styled from 'styled-components'
import Div from 'components/Div'
import HeightTransition from 'components/HeightTransition'
export default class HeightTransitionExample extends Component {
state = {
show1: false,
show2: false,
show3: false
}
render() {
return (
<Wrapper>
<div>
<Div as="button" mBottom={8} onClick={() => this.setState({ show1: !this.state.show1 })}>
Show
</Div>
<HeightTransition isActive={this.state.show1}>
<Container column>
<Item />
<Item />
<Item />
</Container>
</HeightTransition>
</div>
<div>
<Div as="button" mBottom={8} onClick={() => this.setState({ show2: !this.state.show2 })}>
Show
</Div>
<HeightTransition isActive={this.state.show2}>
<Container column>
<Item justifyCenter itemsCenter>
<Div as="button" onClick={() => this.setState({ show3: !this.state.show3 })}>
Show
</Div>
</Item>
<HeightTransition isActive={this.state.show3}>
<Container column>
<Item />
<Item />
<Item />
</Container>
</HeightTransition>
</Container>
</HeightTransition>
</div>
</Wrapper>
)
}
}
const Wrapper = styled.div`
display: grid;
grid-template-columns: repeat(auto-fit, 300px);
grid-gap: 8px;
`
const Container = styled(Div)`
background: powderblue;
width: 300px;
`
const Item = styled(Div)`
height: 60px;
background: tomato;
margin: 20px;
`
|
import React, { Component } from 'react';
import {Link} from 'react-router-dom';
class Footer extends Component {
render() {
return (
<footer>
<div className="container-fluid">
<div className="row">
<div className="footerHeader">
</div>
</div>
<div className="row">
<div className="col">
<div className="footerNav">
<ul>
<li><h5><u>Links</u></h5></li>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/Products">Products</Link>
</li>
<li>
<Link to="/Aboutpage">About Us</Link>
</li>
<li>
<Link to="/Contact">Contact Us</Link>
</li>
</ul>
</div>
</div>
<div className="col">
<ul className="footer-social">
<li><h5><u>Follow Us</u></h5></li>
<li><a className="facebook" href="Insert URL Here" target="_blank">Facebook</a></li>
<li><a className="twitter" href="Insert URL Here" target="_blank">Twitter</a></li>
<li><a className="pinterest" href="Insert URL Here" target="_blank">Pinterest</a></li>
<li><a className="instagram" href="Insert URL Here" target="_blank">Instagram</a></li>
<li><a className="youtube" href="Insert URL Here" target="_blank">YouTube</a></li>
</ul>
</div>
<div className="col">
<ul className="contactFooterList">
<li><h5><u>Contact</u></h5></li>
<li>1-800-555-5555</li>
<li>support@nomail.com</li>
<li>123 Main St<br/>New York, NY 12345</li>
</ul>
</div>
</div>
<div className="row">
<div className="container">
<div className="footer-copyright">
<p>© 2017 Copyright: Luke Roemmele</p>
</div>
</div>
</div>
</div>
</footer>
);
}
}
export default Footer;
|
const bcrypt = require('bcryptjs')
module.exports = {
getMembersByCompany: (req, res) => {
const { co_id } = req.params
const db = req.app.get("db")
db.getTeamMembers({ co_id })
.then(results => {
res.status(200).send(results)
})
},
deleteMember: (req, res) => {
const { team_member_id: id } = req.params
const team_member_id = +id
const db = req.app.get("db")
db.deleteTeamMember({ team_member_id })
.then(res.sendStatus(200))
.catch((err) => { console.log(`Delete Member Error: ${err}`) })
},
addMember: async (req, res) => {
const { firstname, lastname, email, isadmin, company_id, img } = req.body
const db = req.app.get("db")
const addTeamMember = await db.addTeamMember({ firstname, lastname, isadmin, company_id, img })
const team_member_id = addTeamMember[0].team_member_id
await db.addTeamMemberLogin({ email, team_member_id })
// .then(res.sendStatus(200))
.then(results => {
res.status(200).send(results)
})
.catch((err) => { console.log(`Add Member Error: ${err}`) })
},
updateMember: (req, res) => {
const { firstname, lastname, isadmin, team_member_id, email, img } = req.body
const db = req.app.get("db")
db.updateMember({ firstname, lastname, isadmin, team_member_id, email, img })
.then(() => {
req.session.user.img = img
res.sendStatus(200)
})
.catch((err) => { console.log(`Updatae Member Error: ${err}`) })
},
onBoardingTeamMember: (req, res) => {
const { team_member_id } = req.params
const db = req.app.get('db')
db.onBoardingTeamMember({ team_member_id })
.then(user => {
// console.log(user[0], '111')
res.send(user[0])
})
.catch((error) => { console.log(`Error with OnBoarding: ${error}`) })
},
onBoardingUpdatePassword: (req, res) => {
const { team_member_id } = req.params
const { oldPassword, password } = req.body
// console.log(oldPassword, password)
const db = req.app.get('db')
// db.onBoardingTeamMember({})
const salt = bcrypt.genSaltSync(10)
const hash = bcrypt.hashSync(password, salt)
db.onBoardingUpdatePassword({ team_member_id, hash })
.then(resp => {
res.status(200).send(resp)
}).catch((error) => { console.log(`error at updatePassword ${error}`) })
},
getMember(req, res) {
const db = req.app.get('db')
const {team_member_id} = req.params
db.getMember({team_member_id}).then(member => {
res.status(200).send(member[0])
}).catch(console.log)
}
}
|
var csv = require('fast-csv');
var q = require('q');
var Fridge = require('../model/fridge');
var Ingredient = require('../model/ingredient');
/**
* Parser strategy for fridge data
*
* @param {string} contents
* @returns {q@call;defer.promise}
*/
module.exports.getModel = function(contents) {
var f = new Fridge(),
d = q.defer();
csv.fromString(contents, {headers: ['name', 'amount', 'unit', 'useBy']})
.on('data', function(data) {
f.add(new Ingredient(
data.name, data.amount, data.unit, data.useBy));
})
.on('end', function() {
d.resolve(f);
});
return d.promise;
};
|
"use strict";
var Model = require('./../models/user.model');
var CustomError = require('./../utils/custom-error');
var mongoose = require('mongoose');
// Get All
function getAll(req, res, next){
Model.getAll((err, objects)=>{
if(err){return next(err);}
if(!objects){return next(new CustomError('No data found',400));}
res.status(200).json(objects);
});
};
// Get single object by id
function getOneById(req, res, next){
if(!mongoose.Types.ObjectId.isValid(req.params.id)){
return next(new CustomError('Invalid Id',400));
}
Model.getById(req.params.id,(err, object)=>{
if(err){return next(err);}
if(!object){return next(new CustomError('No data found', 400));}
res.status(200).json(object);
});
};
// Get single object by Email
function getOneByEmail(req, res, next){
Model.getByEmail(req.params.email,(err, object)=>{
if(err){return next(err);}
if(!object){return next(new CustomError('No data found', 400));}
res.status(200).json(object);
});
};
// Create new object
function createObject(req, res, next){
const newObject = new Model({
nombre: req.body.nombre,
apellidos: req.body.apellidos,
correo: req.body.correo,
password: req.body.password,
tipo: req.body.tipo,
fechaNacimiento: req.body.fechaNacimiento,
genero: req.body.genero,
foto: req.body.foto,
rutinas: req.body.rutinas
});
// Check if the user already exists
Model.getByEmail(newObject.correo,(err, object)=>{
if(err){return next(err);}
if(object){return next(new CustomError('User already exists', 400));}
// If the user does not exist, create a new one
Model.createObject(newObject, next, (err, object)=>{
if(err){return next(err);}
res.status(200).json(object);
});
});
};
// Remove object
function removeObject(req, res, next){
if(!mongoose.Types.ObjectId.isValid(req.params.id)){
return next(new CustomError('Invalid Id',400));
}
Model.removeObject(req.params.id, (err, object)=>{
if(err){return next(err);}
res.status(200).json(object);
})
}
// Update object
function updateObject(req, res, next){
const data = {
nombre: req.body.nombre,
apellidos: req.body.apellidos,
correo: req.body.correo,
tipo: req.body.tipo,
fechaNacimiento: req.body.fechaNacimiento,
genero: req.body.genero,
foto: req.body.foto,
password: req.body.password,
rutinas: req.body.rutinas
};
Model.updateObject(req.params.id, data, next, (err, object)=>{
if(err){return next(err);}
res.status(200).json(object);
})
}
module.exports = {
getAll: getAll,
getOneById: getOneById,
getOneByEmail:getOneByEmail,
createObject: createObject,
removeObject: removeObject,
updateObject: updateObject
};
|
/**
* Contrôleur de l'application.
*/
var ApplicationController = function($scope, $location, $cookies) {
/**
* Données de l'application
*/
$scope.main = {
brand: "[[Planning]]",
name: "Thomas GIRAULT"
};
/**
* Méthode page spécifique
*/
$scope.isSpecificPage = function() {
var path;
return path = $location.path(), _.contains(["/404", "/500", "/login", "/signin", "/signup", "/forgot", "/lock-screen"], path)
};
/**
* Méthode authentification
*/
$scope.isAuthenticated = function() {
var accessToken = $cookies.get("access_token");
if (!accessToken) {
// On redirige vers la page de connexion
$location.path('/signin').replace();
}
return accessToken;
};
};
// On injecte les dépendences dans le contrôleur
ApplicationController.$inject = ["$scope", "$location", "$cookies"];
// On enregistre le contrôleur auprès du module de l'application
angular.module("application").controller("ApplicationController", ApplicationController);
|
var searchData=
[
['trie',['Trie',['../classTrie.html',1,'']]],
['trienode',['TrieNode',['../classTrieNode.html',1,'']]]
];
|
import React from "react";
import logo from "../assets/download.png";
import axios from "axios";
import { Outlet, Link } from "react-router-dom";
class artist extends React.Component {
render() {
return (
<div>
<div className="header">
<header>
<img src={logo} />
<a href="#default"></a>
<div class="header-right">
<Link to="/home">
<a>Home</a>
</Link>
<Link to="/addartist">
<a className="active">Add Artist</a>
</Link>
<Link to="/addsongs">
<a>addsongs</a>
</Link>
</div>
</header>
</div>
<div class="songget">
<img src={logo}></img>
<form method="POST" action="http://localhost:8080/artist/addArtist" >
<div class="form-group">
<label for="aname">Artist name</label>
<input
type="text"
class="form-control"
placeholder="Name"
name="aname"
/>
<div>
<label for="country">Country of the artist</label>
<input
type="text"
class="form-control"
placeholder="Country"
name="country"
/>
</div>
<button className="button">
<input
type="submit"
value="Add Artist"
class="formbutton"
></input>
</button>
</div>
</form>
</div>
</div>
);
}
}
export default artist;
|
// ==UserScript==
// @name 修改弹幕流基础件
// @version 0.2
// @namespace https://github.com/shugen002/userscript
// @description 修改直播弹幕流基础件
// @license MIT
// @author Shugen002
// @match https://live.bilibili.com/*
// @match https://live.bilibili.com/blanc/*
// @exclude https://live.bilibili.com/p/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=bilibili.com
// @grant none
// @updateURL https://github.com/shugen002/userscript/raw/master/%E4%BF%AE%E6%94%B9%E5%BC%B9%E5%B9%95%E6%B5%81%E5%9F%BA%E7%A1%80%E4%BB%B6.user.js
// @downloadURL https://github.com/shugen002/userscript/raw/master/%E4%BF%AE%E6%94%B9%E5%BC%B9%E5%B9%95%E6%B5%81%E5%9F%BA%E7%A1%80%E4%BB%B6.user.js
// @run-at document-start
// ==/UserScript==
(function () {
'use strict';
function replaceFunction(ptype) {
ptype.$$initialize=ptype.initialize
ptype.initialize=function(...args){
args[0].$$onReceivedMessage = args[0].onReceivedMessage
args[0].onReceivedMessage = function (...args2){
if(window.$$danmuPatcher){
try{
window.$$danmuPatcher.forEach((e)=>{
e(...args2)
})
}catch(e){
console.error("执行修改时出现错误",e)
}
}
return this.$$onReceivedMessage(...args2)
}
console.log('[修改弹幕流基础件UserScript] onReceivedMessage 替换成功');
return ptype.$$initialize(...args)
}
console.log(ptype)
}
function noUndefindErrorAllowed(obj, propertyName) {
try {
return obj.exports.prototype[propertyName]
} catch (error) {
return undefined;
}
}
function findBase(prequire) {
let level = 0;
while (prequire) {
for (const k in prequire.cache) {
const cachedModule = prequire.cache[k];
if (!!noUndefindErrorAllowed(cachedModule, 'initialize')&& !!noUndefindErrorAllowed(cachedModule, 'getAuthInfo')) {
return cachedModule.exports.prototype;
}
}
prequire = prequire.parent;
level++;
}
}
var timeout;
var count=0;
function tick(){
const ptype = findBase(window.parcelRequire);
if (!ptype) {
if(count>1000){
console.log('[修改弹幕流基础件UserScript] 没有找到 initialize 和 getAuthInfo 所在的 prototype', window.location.href);
clearInterval(timeout)
}
} else {
replaceFunction(ptype);
console.log('[修改弹幕流基础件UserScript] initialize 替换成功');
clearInterval(timeout)
}
}
timeout=setInterval(tick,10)
})();
|
var my_url="Initial value";
var spsheet= SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1GZr1yOOvi-R76HKKdFQy-6p204-ZgBy-rSuqix0OpC8/edit#gid=0');
var ssheet = spsheet.getSheets();
var sheet = ssheet[0];
function doGet(e) {
if(e.parameter.row!=null && e.parameter.col!=null)
{
//var userProperties = PropertiesService.getUserProperties();
//var newProperties = {col: 'Unpressed'};
//userProperties.setProperties(newProperties);
}
else if(e.parameter.col!=null)
{
//--------------------------//
/*
//my_url=e.parameter.col;
var userProperties = PropertiesService.getUserProperties();
var newProperties = {col: e.parameter.col};
userProperties.setProperties('col', 'hello');
*/
//var np = e.parameter.col;
//var sp = Session.getActiveUser().getEmail().toString();
//tmp.pstn=sp;
//var userProperties = PropertiesService.getUserProperties();
//var newProperties = {col: sp};
//userProperties.setProperties(newProperties);
//----------------------------//
var col=e.parameter.col;
var name=e.parameter.name;
var tmp = HtmlService.createTemplateFromFile("profile");
var date1 = new Date();
var date2 = Utilities.formatDate(date1, "GMT+5:30", "MM/dd/yyyy");
tmp.date = date2;
var row=0;
//var sheet= SpreadsheetApp.getActiveSheet();
var date_list = sheet.getRange(3, 1, sheet.getMaxRows(), 1).getValues();
for(var i=0; i<date_list.length; i++)
{
if(date_list[i][0]==date2)
{
row=i+3;
break;
}
}
var weekly = 0;
for(var i=1; i<=7; i++)
{
if(row-i>2)
{
var temp = Number(sheet.getRange(row-i, col).getValue());
weekly = weekly+temp;
}
}
var total= 0;
var totl_col=sheet.getRange(3,col,sheet.getMaxRows(),1).getValues();
for(var i=0; i<totl_col.length; i++)
{
total+=Number(totl_col[i][0]);
}
var phone = sheet.getRange(2, col).getValue();
tmp.row=row;
tmp.col=col;
tmp.name=name;
tmp.phone = phone;
tmp.weekly=weekly;
tmp.total=total;
tmp.date = date2;
tmp.link = ScriptApp.getService().getUrl();
var raw=tmp.evaluate();
return raw.addMetaTag('viewport', 'width=device-width, initial-scale=1');
}
else
{
/* Publish as User code
var sheet=SpreadsheetApp.create("mySheet");
var id=sheet.getId();
return ContentService.createTextOutput(JSON.stringify(id))
.setMimeType(ContentService.MimeType.JSON);
*/
//var sheet= SpreadsheetApp.getActiveSheet();
//var ssheet = spsheet.getSheets();
//var sheet = ssheet[0];
//-----------------Colour To coloumns------------//
var date1 = new Date();
var date2 = Utilities.formatDate(date1, "GMT+5:30", "MM/dd/yyyy");
var row=0;
var date_list = sheet.getRange(3, 1, sheet.getMaxRows(), 1).getValues();
for(var i=0; i<date_list.length; i++)
{
if(date_list[i][0]==date2)
{
row=i+3;
break;
}
}
var today_col = sheet.getRange(row, 1, 1, sheet.getMaxColumns()).getValues();
var sum=0;
for(var i=1;i<sheet.getMaxColumns(); i++)
{
var temp=Number(today_col[0][i]);
sum += temp;
}
//--------------Colour To coloumns------------------//
var list = sheet.getRange(1, 1, 1, sheet.getMaxColumns()).getValues();
var htmlListArray = list.map(function(r){
var html="";
for(var i=1; i<sheet.getMaxColumns(); i++)
{
if(today_col[0][i]!="")
html+='<tr><td class="success text-center">'+r[i]+'</td><td class="success text-center">'+today_col[0][i]+'</td><td class="success text-center"><a href="'+ ScriptApp.getService().getUrl()+'?col='+(i+1)+'&name='+r[i].toString()+'" target="_top"><button type="button" class="btn btn-info"><span class="glyphicon glyphicon-chevron-right"></span></button></a></td></tr>';
else
html+='<tr><td class="text-center">'+r[i]+'</td><td class="text-center">'+today_col[0][i]+'</td><td class="text-center"><a href="'+ ScriptApp.getService().getUrl()+'?col='+(i+1)+'&name='+r[i].toString()+'" target="_top"><button type="button" class="btn btn-info"><span class="glyphicon glyphicon-chevron-right"></span></button></a></td></tr>';
//html += '<tr><td>'+"ID"+'</td><td>'+r[0]+'</td><td>'+"Amount"+'</td></tr>';
}
return html;
//return '<tr><td>'+"ID"+'</td><td>'+r[0]+'</td><td>'+"Amount"+'</td></tr>';
}).join('');
var tmp = HtmlService.createTemplateFromFile("page");
tmp.list = htmlListArray;
tmp.sum = sum;
//tmp.url = PropertiesService.getUserProperties().getProperty('col');
var raw=tmp.evaluate();
return raw.addMetaTag('viewport', 'width=device-width, initial-scale=1');
}
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
function userClicked(userInfo){
//var sheet= SpreadsheetApp.getActiveSheet();
var done = sheet.getRange(Number(userInfo.row), Number(userInfo.col)).setValue(userInfo.val);
//var urlString= "https://wa.me/+91"+userInfo.phone+"?text=Collected+"+userInfo.val+"+rupees+today.+Collected+"+userInfo.weekly+"rupees+in+last+7+days.+Total+Collection+up+to+yesterday+is+"+userInfo.total+"Rupees.+Thank+You+ধন্যবাদ.";
var urlString= "https://wa.me/+91"+userInfo.phone+"?text=আজি+আপোনাৰ+পৰা+"+userInfo.val+"+টকা+জমা+লোৱা+হ'ল।+ধন্যবাদ।+-+ইতি+প্ৰশান্ত+শৰ্মা";
var encoded=(urlString);
//Logger.log(encoded);
return encoded;
//encodeURIComponent
//Logger.log(userInfo);
//Logger.log(userInfo.row, userInfo.col, userInfo.val);
//Logger.log(userInfo.val);
}
function userClicked2(userInfo){
//var sheet= SpreadsheetApp.getActiveSheet();
//var urlString= "sms:+91"+userInfo.phone+"?body=Collected+"+userInfo.val+"+rupees+today.+Collected+"+userInfo.weekly+"rupees+in+last+7+days.+Total+Collection+up+to+yesterday+is+"+userInfo.total+"Rupees.+Thank+You.+ধন্যবাদ";
var urlString= "sms:+91"+userInfo.phone+"?body=আজি+আপোনাৰ+পৰা+"+userInfo.val+"+টকা+জমা+লোৱা+হ'ল।+ধন্যবাদ।+-+ইতি+প্ৰশান্ত+শৰ্মা";
var encoded=(urlString);
Logger.log(encoded);
return encoded;
//encodeURIComponent
//Logger.log(userInfo);
//Logger.log(userInfo.row, userInfo.col, userInfo.val);
//Logger.log(userInfo.val);
}
function doSomething() {
Logger.log('I was called!');
}
|
import React from 'react';
const Home = () => {
return (
<div>
<div className="JumboBanner">
<h1>Mighty Muf'ler</h1>
<h2>Arizona's Quality Shop since 1979</h2>
</div>
<div className="Margins">
<div className="TwoColumnGrid">
<div className="Padding">
<div className="OneColumnGrid">
<h1>Services Provided</h1>
<div className="ListItems">
<h3>-Custom Exhaust</h3>
<h3>-Muffler Replacement</h3>
<h3>-Exhaust Repair</h3>
<h3>-Catalytic Converter Replacement</h3>
</div>
</div>
</div>
<div className="ImgWrapper">
<img alt="The front of the store" src="https://images.squarespace-cdn.com/content/v1/5e9fa98348d28b20b3f39b36/1587803065032-7X0GNQ25GDPSESU7WDN8/ke17ZwdGBToddI8pDm48kPoswlzjSVMM-SxOp7CV59BZw-zPPgdn4jUwVcJE1ZvWQUxwkmyExglNqGp0IvTJZamWLI2zvYWH8K3-s_4yszcp2ryTI0HqTOaaUohrI8PIeQMKeWYgwh6Mn73n2eZmZLHHpcPIxgL2SArp_rN2M_AKMshLAGzx4R3EDFOm1kBS/duals+pic.jpg?format=1500w"></img>
</div>
</div>
<div className="TwoColumnGrid">
<div>
<h1>Arizona's Quality Shop</h1>
<span className="yelp-review" data-review-id="lrfhxiFX0qQG0KGkVvT2RQ" data-hostname="www.yelp.com">Read <a href="https://www.yelp.com/user_details?userid=g5D3r6Onzl8v2Yjj7RMBvQ" rel="nofollow noopener">Cale M.</a>'s <a href="https://www.yelp.com/biz/mighty-mufler-phoenix?hrid=lrfhxiFX0qQG0KGkVvT2RQ" rel="nofollow noopener">review</a> of <a href="https://www.yelp.com/biz/Vf-rSLHzPuxSGALuXreIEQ" rel="nofollow noopener">Mighty Muf'ler</a> on <a href="https://www.yelp.com" rel="nofollow noopener">Yelp</a><script async="async" src="https://www.yelp.com/embed/widgets.js" type="text/javascript"></script></span>
</div>
<div>
<h1>Hours</h1>
<p>Monday–Friday</p>
<p>9am–6pm</p>
<p>Saturday - Sunday</p>
<p>Closed</p>
<h1>Phone</h1>
<p>(602) 944-5210 </p>
</div>
</div>
<div>
<h1>Visit Us</h1>
<p>10032 N Cave Creek Rd</p>
<p>Phoenix, AZ 85020</p>
<div className="google-maps"><iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d13296.226117394699!2d-112.0549261!3d33.5778815!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x8c5a164d90109436!2sMighty%20Muf'ler!5e0!3m2!1sen!2sus!4v1592152940614!5m2!1sen!2sus" width="100%" height="100%" frameBorder="0" allowFullScreen="" aria-hidden="false" tabIndex="0"></iframe></div>
</div>
</div>
</div>
);
}
export default Home;
|
var MovementSystem = System.extend('MovementSystem',
function(input) {
this.input = input;
this.zeroSpeedThreshold = 0.001;
this.nodes = {movables: []};
this.lastDelta = 1/30;
},
{
aspects: {
movables: Aspect.all(['Movement', 'RigidBody', 'GroundSensor'])
},
onUpdate: function(dt, nodes) {
this.lastDelta = dt;
this.nodes = nodes;
for (var i = 0; i < this.nodes.movables.length; ++i) {
var body = ecs.getComponent('RigidBody', this.nodes.movables[i]);
var movement = ecs.getComponent('Movement', this.nodes.movables[i]);
var ground_sensor = ecs.getComponent('GroundSensor', this.nodes.movables[i]);
var body_vel = body.getLinearVelocity();
var speed = ground_sensor.isOnGround ? movement.speed : movement.airSpeed;
if (this.input.isDown(KeyCodes.A)) {
if (body_vel.x > -speed) {
var dx = -speed - body_vel.x;
var acc_x = dx / (1/5);
body.setAwake(true);
body.applyAcceleration({x: acc_x, y: 0});
}
}
if (this.input.isDown(KeyCodes.D)) {
if (body_vel.x < speed) {
var dx = speed - body_vel.x;
var acc_x = dx / (1/5);
body.setAwake(true);
body.applyAcceleration({x: acc_x, y: 0});
}
}
if (!this.input.isDown(KeyCodes.A) && !this.input.isDown(KeyCodes.D)) {
if (Math.abs(body_vel.x) <= this.zeroSpeedThreshold) {
var dx = -body_vel.x;
var acc_x = dx / this.lastDelta;
body.applyAcceleration({x: acc_x, y: 0});
} else {
var dx = 0 - body_vel.x;
var acc_x = dx / (1/8);
body.applyAcceleration({x: acc_x, y: 0});
}
}
}
}
}
);
BUILTIN_COMPONENTS['Movement'] = {
speed: 10,
airSpeed: 7
};
|
/**
* Renders a view into a DOM element and runs assertions against it
* Locale calls simply return the key value
* @param {Object} view View under test
* @param {Function} assertions Method containing assertions
* @param {Object} options Rendering options
* @param {Function} [options.environment=undefined] Gets passed playground as argument, return value used as wrapper element. Defaults to playground.
*/
jasmine.renderView = function (view, assertions, options) {
options = options || {};
// set up DOM element to inject view into
var playground = $('<div id="jasmine-playground"></div>');
playground.appendTo('body');
var viewContainer = playground;
if (typeof(options.environment) === 'function') {
viewContainer = options.environment(playground);
}
try {
view.$el.appendTo(viewContainer);
view.render();
assertions.call(view);
} finally {
// tear down
playground.remove();
}
};
|
import React from 'react';
import './search.styles.scss';
import { connect } from 'react-redux';
import { setSearchField } from '../../redux/search/search.actions';
import { searchUser } from "../../redux/user/user.actions";
import { searchPost } from "../../redux/post/post.actions";
class Search extends React.Component{
render(){
const { onSetSearchField, onSearchUser, onSearchPost, search } = this.props;
return (
<div className="search-container">
{
search === 'user:' ?
<input className="search-box-user" id="user" type="text" onChange={onSearchUser} /> :
search === 'post:' ?
<input className="search-box-post" id="post" type="text" onChange={onSearchPost} />
:
<input className="search-box-default" type="text" onChange={onSetSearchField} />
}
</div>
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
onSetSearchField: (event) => dispatch(setSearchField(event.target.value)),
onSearchUser: (event) => dispatch(searchUser(event.target.value)),
onSearchPost: (event) => dispatch(searchPost(event.target.value)),
}
}
const mapStateToProps = (state) => {
return {
search: state.search.search
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Search);
|
import React from 'react';
import escapeRegExp from 'escape-string-regexp'
class Places extends React.Component {
// state ={
// query:''
// }
// A function to update the input the query state with the input
// updateQuery=(query)=>{
// this.setState({query: query.trim()})
// }
render(){
const {myPlaces, query, markers} = this.props
// A function to update the list and markers dynamically
let showingPlaces, showingMarkers
if(query){
markers.map((marker)=>{marker.setVisible(false)})
const match = new RegExp(escapeRegExp(query), 'i')
showingPlaces = myPlaces.filter((place)=>match.test(place.text))
showingMarkers = markers.filter((marker)=>match.test(marker.title))
showingMarkers.map((marker)=>{marker.setVisible(true)})
}else{
showingPlaces = myPlaces
showingMarkers = markers
showingMarkers.map((marker)=>{marker.setVisible(true)})
}
return(
<div className="list">
<div className='search'>
<input type='text' placeholder='Search for places!' value={this.props.squery} onChange={(event)=>this.props.updateQuery(event.target.value)}></input>
</div>
<ul>
{showingPlaces.map((place)=>
<li key={place.text.toString()} id={place.text.toString()}>{place.text}</li>
)
}
</ul>
</div>
)
}
}
export default Places;
|
import React, { Component } from 'react';
import Web3 from 'web3';
import './App.css';
import Color from './contracts/Color.json';
function colorHexToString(hexStr) {
return '#' + hexStr.substring(2);
}
function colorStringToBytes(str) {
if (str.length !== 7 || str.charAt(0) !== '#') {
throw new Error('invalid color string');
}
const hexStr = '0x' + str.substring(1);
return Web3.utils.hexToBytes(hexStr);
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
account: '',
contract: null,
totalSupply: 0,
colors: [],
};
}
async componentWillMount() {
await this.loadWeb3();
await this.loadBlockchainData();
}
async loadWeb3() {
if (window.ethereum) {
// current web3 providers
window.web3 = new Web3(window.ethereum);
await window.ethereum.enable();
}
else if (window.web3) {
// fallback for older web3 providers
window.web3 = new Web3(window.web3.currentProvider);
}
else {
// no web3 provider, user needs to install one in their browser
window.alert(
'No injected web3 provider detected');
}
console.log(window.web3.currentProvider);
}
async loadBlockchainData() {
const web3 = window.web3;
// Load account
const accounts = await web3.eth.getAccounts();
console.log ('account: ', accounts[0]);
this.setState({ account: accounts[0] });
const networkId = await web3.eth.net.getId();
const networkData = Color.networks[networkId];
if (!networkData) {
window.alert('Smart contract not deployed to detected network.');
return;
}
const abi = Color.abi;
const address = networkData.address;
const contract = new web3.eth.Contract(abi, address);
this.setState({ contract });
const totalSupply = await contract
// .methods.totalSupply().call();
.methods.balanceOf(this.state.account).call();
this.setState({ totalSupply });
// Load Colors
for (var i = 1; i <= totalSupply; i++) {
const colorBytes = await contract
.methods.colors(i - 1).call();
const colorStr = colorHexToString(colorBytes);
this.setState({
colors: [...this.state.colors, colorStr],
});
}
}
mint = (colorStr) => {
const colorBytes = colorStringToBytes(colorStr);
console.log(colorBytes);
this.state.contract.methods
.mint(colorBytes)
.send({ from: this.state.account })
.once('receipt', (receipt) => {
console.log ('transaction receipt: ', receipt)
console.log('colorBytes:',colorBytes);
this.setState({
colors: [...this.state.colors, colorStr],
});
});
}
render() {
return (
<div>
<nav className="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow">
<span className="navbar-brand col-sm-3 col-md-2 mr-0">
Color Tokens
</span>
<ul className="navbar-nav px-3">
<li className="nav-item text-nowrap d-none d-sm-none d-sm-block">
<small className="text-white"><span id="account">{this.state.account}</span></small>
</li>
</ul>
</nav>
<div className="container-fluid mt-5">
<div className="row">
<main role="main" className="col-lg-12 d-flex text-center">
<div className="content mr-auto ml-auto">
<h1>Issue Token</h1>
<form onSubmit={(event) => {
event.preventDefault();
const colorStr = this.color.value;
this.mint(colorStr);
}}>
<input
type='text'
className='form-control mb-1'
placeholder='e.g. #FF00FF'
ref={(input) => { this.color = input }}
/>
<input
type='submit'
className='btn btn-block btn-primary'
value='MINT'
/>
</form>
</div>
</main>
</div>
<hr/>
<div className="row text-center">
{ this.state.colors.map((colorStr, key) => {
return (
<div key={key} className="col-md-3 mb-3">
<div className="token" style={{ backgroundColor: colorStr }}></div>
<div>{colorStr}</div>
</div>
);
})}
</div>
</div>
</div>
);
}
}
export default App;
|
import ActionTimer from '..';
describe('ActionTimer', () => {
it('.start() runs interval, that increments tick value every second', () => {
const timer = new ActionTimer();
timer.start();
const result = new Promise(resolve => {
global.setTimeout(() => {
timer.cancel();
resolve();
}, 3000);
});
return result.then(() => {
expect(timer.store.state.tick).toEqual(2);
});
});
it('constructor accepts handlers, that run when specified tick is reached', () => {
const timer = new ActionTimer({
3: cancel => {
cancel();
expect(timer.state.tick).toEqual(3);
},
});
timer.start();
});
it('can be used to make sure async event is fired in time', () => {
const asyncAction = new Promise((resolve, reject) => {
const timer = new ActionTimer();
const timeoutID = global.setTimeout(() => {
resolve(timer);
}, 1000);
timer.handlers = {
3: cancel => {
cancel();
global.clearTimeout(timeoutID);
reject(timer);
},
};
timer.start();
});
return asyncAction.then(timer => {
expect(timer.state.tick <= 1).toEqual(true);
});
});
});
|
import React from "react";
import "./DoctorBatchCard.css";
import {withRouter} from 'react-router-dom'
class DocterBatchCard extends React.Component {
processRequest(){
const patient = JSON.parse(localStorage.getItem("userToken"))
let d = new Date();
if(patient){
const body = JSON.stringify({
patientid: patient.email,
firstname:patient.firstname,
lastname: patient.lastname,
doctorid: this.props.pro.email,
requesttime: d.toLocaleTimeString(),
dateofreq: d.toDateString(),
status: "request"
})
fetch("http://localhost:4000/appoint",{
method: "POST",
headers:{
"Content-type":"application/json"
},
body
})
.then(res => res.json())
.then(resp => {
alert("Requested Successfully !")
})
.catch(err => {
alert("Already Request sends!")
})
}else{
alert("Login to Continue")
this.props.history.push('/login')
}
}
render() {
return (
<div className="batchDiv">
<h3>{this.props.pro.firstname} {this.props.pro.lastname}</h3>
<h5 className="em">{this.props.pro.email}</h5>
<hr />
<p className="spec">Specialist: {this.props.pro.specialist}</p>
<p className="hosp">Hospital name: {this.props.pro.hospital_name}</p>
<address className="addre">{this.props.pro.address}</address>
<button className="get-appoin" onClick={this.processRequest.bind(this)}>Get Appoinment</button>
</div>
);
}
}
export default withRouter(DocterBatchCard);
|
import React from "react";
// Components:
import Placeholder from "../Placeholder";
const Practice = () => {
return <Placeholder title="Practice" />;
};
export default Practice;
|
import Home from "./Pages/Home/home";
import Design from "./Pages/Editors/Editors";
import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
function App() {
return (
<div>
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/editor/:type/:design" component={Design} />
</Switch>
</Router>
</div>
);
}
export default App;
|
const fs = require('fs')
const path = require('path')
const { camelCase, replace, forEach } = require('lodash')
const modelPath = path.join(__dirname, '../models')
const modelFiles = fs.readdirSync(modelPath)
const createModelName = (file) => camelCase(replace(file, '.js', ''))
const models = {}
const modelsCreator = () => {
forEach(modelFiles, (file) => {
const Model = require('../models/' + file)
models[createModelName(file)] = new Model()
})
}
modelsCreator()
module.exports = models
|
var coinChange = function(coins, amount) {
let ans = dp(coins, amount, {})
if (ans === Number.MAX_VALUE) {return -1}
return ans
};
function dp(coins, amount, h) {
if (amount === 0) {return 0}
if (amount < 0) {return -1}
if (h[amount]) {return h[amount]}
let min = Number.MAX_VALUE
let included = false;
for (let i = 0; i < coins.length; i++) {
let node = dp(coins,amount-coins[i], h)
if (node < min && node > 0) {
included = true;
min = node
}
}
h[amount] = min;
return min
}
// console.log(coinChange([1,2,5], 11))
console.log(coinChange([2], 3))
|
import { gql } from '@apollo/client'
export const GET_SERIES = gql`
{
getAllSeries {
_id
poster_path
}
}
`;
export const GET_ONESERIES = gql`
query getSeriesById($_id: ID) {
getSeriesById(id: $_id) {
_id
poster_path
overview
popularity
title
tags
}
}
`;
export const ADD_SERIES = gql`
mutation addSeries(
$title: String!
$overview: String!
$poster_path: String!
$popularity: Float!
$tags: [String]!
) {
addSeries(
series: {
title: $title
overview: $overview
poster_path: $poster_path
popularity: $popularity
tags: $tags
}
) {
_id
poster_path
}
}
`
export const DELETE_SERIES = gql`
mutation deleteSeries($id: ID) {
deleteSeries(id: $id) {
_id
}
}
`
export const UPDATE_SERIES = gql`
mutation updateSeries($_id: ID, $updates: series) {
updateSeries(id: $_id, updates: $updates) {
_id
}
}
`
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('audioCat.state.command.CommandManager');
goog.require('audioCat.state.command.CommandHistoryChangedEvent');
goog.require('audioCat.state.command.Event');
goog.require('audioCat.utility.EventTarget');
goog.require('goog.asserts');
/**
* Manages command history. Performs undos and redos.
* @param {!audioCat.utility.IdGenerator} idGenerator Generates IDs unique
* throughout the application.
* @param {!audioCat.state.Project} project The project.
* @param {!audioCat.state.TrackManager} trackManager Manages the state of
* audio tracks.
* @param {!audioCat.state.MemoryManager} memoryManager Manages memory.
* @constructor
* @extends {audioCat.utility.EventTarget}
*/
audioCat.state.command.CommandManager = function(
idGenerator,
project,
trackManager,
memoryManager) {
goog.base(this);
/**
* @private {!audioCat.utility.IdGenerator}
*/
this.idGenerator_ = idGenerator;
/**
* The project.
* @private {!audioCat.state.Project}
*/
this.project_ = project;
/**
* Manages tracks.
* @private {!audioCat.state.TrackManager}
*/
this.trackManager_ = trackManager;
/**
* Manages memory.
* @private {!audioCat.state.MemoryManager}
*/
this.memoryManager_ = memoryManager;
/**
* A list of commands in the order in which they were run.
* @private {!Array.<!audioCat.state.command.Command>}
*/
this.commands_ = [];
/**
* The ID of the current series of commands. A new series could begin for
* instance if the user loads a project.
* @private {audioCat.utility.Id}
*/
this.epochId_ = idGenerator.obtainUniqueId();
/**
* The index into the commands list that pertains to the current command - the
* most recent command. If less than 0, no more recent command exists.
* @private {number}
*/
this.currentCommandIndex_ = -1;
};
goog.inherits(audioCat.state.command.CommandManager,
audioCat.utility.EventTarget);
/**
* @return {audioCat.utility.Id} The ID of the current epoch, which is a label
* for any one series of commands.
*/
audioCat.state.command.CommandManager.prototype.getCurrentEpochId = function() {
return this.epochId_;
};
/**
* Performs a command and enqueues the command into the command history.
* @param {!audioCat.state.command.Command} command The command to enqueue.
* @param {boolean=} opt_suppressPerform If provided and true, the command is
* not performed upon being enqueued into the command manager. This should
* be specified if the command is to be performed outside the command
* manager - for instance, when the track is changed as the user drags. If
* not provided or false, the command manager calls the perform method of
* the command.
*/
audioCat.state.command.CommandManager.prototype.enqueueCommand =
function(command, opt_suppressPerform) {
if (!opt_suppressPerform) {
command.perform(this.project_, this.trackManager_);
this.memoryManager_.addBytes(command.getMemoryAdded());
}
var commands = this.commands_;
var newIndex = this.currentCommandIndex_ + 1;
commands[newIndex] = command;
var newLengthOfCommandsArray = newIndex + 1;
// Note any memory that we just got rid of by removing references to commands.
var memorySubtracted = 0;
for (var c = newLengthOfCommandsArray; c < commands.length; ++c) {
memorySubtracted += commands[c].getMemoryAdded();
}
if (memorySubtracted == 0) {
// No memory subtracted, but memory needed to represent project might have
// decreased.
this.memoryManager_.noteMemoryNeededChange();
} else {
// Overall memory changed.
this.memoryManager_.subtractBytes(memorySubtracted);
}
commands.length = newLengthOfCommandsArray;
this.currentCommandIndex_ = newIndex;
this.dispatchEvent(new audioCat.state.command.CommandHistoryChangedEvent());
};
/**
* Undos a command and moves the current command back. Throws an exception if
* no previous command exists.
* @return {string} A summary of what happened during undo.
*/
audioCat.state.command.CommandManager.prototype.dequeueCommand = function() {
var currentCommandIndex = this.getCurrentCommandIndex();
// The current state must allow for undo.
goog.asserts.assert(this.isUndoAllowed());
var commands = this.commands_;
var command = commands[currentCommandIndex];
var project = this.project_;
var trackManager = this.trackManager_;
if (command.isUndoable()) {
command.undo(project, trackManager);
} else {
// TODO(chizeng): Be careful about book-keeping memory here. Haven't really
// tested out this logic much yet ...
this.trackManager_.revertToOpeningState();
this.project_.revertToOpeningState();
for (var i = 0; i < currentCommandIndex; ++i) {
commands[i].perform(project, trackManager);
}
}
this.currentCommandIndex_ -= 1;
this.dispatchEvent(new audioCat.state.command.CommandHistoryChangedEvent());
// Memory needed could have changed from this.
this.memoryManager_.noteMemoryNeededChange();
// False means get the backward direction description of the command.
return command.getSummary(false);
};
/**
* Redoes the previously undone command. Throws an exception if no later
* command exists.
* @return {string} A summary of what happened during redo.
*/
audioCat.state.command.CommandManager.prototype.redoCommand = function() {
var commands = this.commands_;
// The current state must allow for redo.
goog.asserts.assert(this.isRedoAllowed());
this.currentCommandIndex_ += 1;
var command = commands[this.currentCommandIndex_];
command.perform(this.project_, this.trackManager_);
this.dispatchEvent(new audioCat.state.command.CommandHistoryChangedEvent());
// Note that memory usage could have changed.
this.memoryManager_.noteMemoryNeededChange();
// True means get the forward direction description of the command.
return command.getSummary(true);
};
/**
* @return {number} The index of the current command.
*/
audioCat.state.command.CommandManager.prototype.getCurrentCommandIndex =
function() {
return this.currentCommandIndex_;
};
/**
* @return {audioCat.state.command.Command} The command that would be undo-ed
* next. Or null if no such command exists - for example, perhaps no
* commands have been performed yet.
*/
audioCat.state.command.CommandManager.prototype.getNextCommandToUndo =
function() {
return this.isUndoAllowed() ?
this.commands_[this.currentCommandIndex_] : null;
};
/**
* @return {number} The number of commands remembered.
*/
audioCat.state.command.CommandManager.prototype.getNumberOfCommands =
function() {
return this.commands_.length;
};
/**
* @return {boolean} True if and only if undo is allowed.
*/
audioCat.state.command.CommandManager.prototype.isUndoAllowed =
function() {
// Allow undo so long as previous commands exist.
return this.currentCommandIndex_ >= 0;
};
/**
* @return {boolean} True if and only if redo is allowed.
*/
audioCat.state.command.CommandManager.prototype.isRedoAllowed =
function() {
// Allow redo so long as later elements exist.
return this.currentCommandIndex_ < this.commands_.length - 1;
};
/**
* Clears the entire history of commands, obliterating the current state of
* redos and undos allowed. Call this function sparingly and carefully. Does not
* change any memory information.
*/
audioCat.state.command.CommandManager.prototype.obliterateHistory =
function() {
this.commands_.length = 0;
this.currentCommandIndex_ = -1;
this.epochId_ = this.idGenerator_.obtainUniqueId();
this.dispatchEvent(new audioCat.state.command.CommandHistoryChangedEvent());
};
/**
* Performs a command without leaving a trace in the history.
* @param {!audioCat.state.command.Command} command The command to perform.
* @param {boolean=} opt_backward If true, performs the backwards (undo)
* direction. Else performs the forward command.
*/
audioCat.state.command.CommandManager.prototype.justDoCommand = function(
command, opt_backward) {
(opt_backward ? command.undo : command.perform).call(
command, this.project_, this.trackManager_);
// Note that memory usage could have changed.
this.memoryManager_.noteMemoryNeededChange();
};
|
var searchData=
[
['knight_2ehpp',['knight.hpp',['../knight_8hpp.html',1,'']]]
];
|
var tableid=0;
function setData()
{
var key=document.getElementById("key").value;
var value=document.getElementById("value").value;
localStorage.setItem(key,value);
document.getElementById("key").innerHTML="";
document.getElementById("value").innerHTML="";
}
function renderTable()
{
var newTable = document.createElement('table');
var table = document.getElementById("table");
table.parentNode.replaceChild(newTable,table);
newTable.setAttribute('id','table');
newTable.setAttribute('margin-left','220px');
newTable.setAttribute('position','relative');
var data = Object.entries(localStorage);
for(let i=0;i<data.length;i++)
{
updateTableEntry(data[i][0],data[i][1]);
}
}
function updateTableEntry(key,value)
{
var table = document.getElementById("table");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2)
var cell4 = row.insertCell(3);
cell1.innerHTML = key;
cell2.innerHTML = value;
var buton = document.createElement('button');
buton.style.color='black';
buton.style.width='50px';
buton.style.height='30px';
buton.style.borderRadius='5px';
buton.innerHTML="delete";
buton.onclick = function(){window.localStorage.removeItem(key); table.deleteRow(row.rowIndex);}
cell4.appendChild(buton);
var editButton = document.createElement('button');
editButton.style.width = '50px';
editButton.style.height= '30px';
editButton.style.borderRadius='5px';
editButton.innerHTML = 'edit';
editButton.style.color='black';
cell3.appendChild(editButton);
editButton.onclick = function(){
var editbox1=document.createElement('input');
var editbox2=document.createElement('input');
editbox1.setAttribute('type','text');
editbox2.setAttribute('type','text');
cell1.appendChild(editbox1);
cell2.appendChild(editbox2);
this.innerHTML='save';
this.onclick=function(){
this.innerHTML='edit';
localStorage.removeItem(key);
localStorage.setItem(editbox1.value,editbox2.value);
renderTable();
}
}
}
|
import React from "react";
import product7 from "./images/product-7.jpg";
import product8 from "./images/product-8.jpg";
import product9 from "./images/product-9.jpg";
import product10 from "./images/product-10.jpg";
function RecentProduct() {
const styleRecent = {
position: "relative",
padding: "30px 0",
};
return (
<div style={styleRecent} class="recent-product product">
<div class="container-fluid">
<div class="section-header">
<h1>Recent Product</h1>
</div>
<div class="row align-items-center product-slider product-slider-4">
<div class="col-lg-3">
<div class="product-item">
<div class="product-title">
<a href="#">Product Name</a>
<div class="ratting">
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
</div>
</div>
<div class="product-image">
<a href="product-detail.html">
<img src={product10} alt="Product Image" />
</a>
<div class="product-action">
<a href="#">
<i class="fa fa-cart-plus"></i>
</a>
<a href="#">
<i class="fa fa-heart"></i>
</a>
<a href="#">
<i class="fa fa-search"></i>
</a>
</div>
</div>
<div class="product-price">
<h3>
<span>$</span>99
</h3>
<a class="btn" href="">
<i class="fa fa-shopping-cart"></i>Buy Now
</a>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="product-item">
<div class="product-title">
<a href="#">Product Name</a>
<div class="ratting">
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
</div>
</div>
<div class="product-image">
<a href="product-detail.html">
<img src={product7} alt="Product Image" />
</a>
<div class="product-action">
<a href="#">
<i class="fa fa-cart-plus"></i>
</a>
<a href="#">
<i class="fa fa-heart"></i>
</a>
<a href="#">
<i class="fa fa-search"></i>
</a>
</div>
</div>
<div class="product-price">
<h3>
<span>$</span>99
</h3>
<a class="btn" href="">
<i class="fa fa-shopping-cart"></i>Buy Now
</a>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="product-item">
<div class="product-title">
<a href="#">Product Name</a>
<div class="ratting">
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
</div>
</div>
<div class="product-image">
<a href="product-detail.html">
<img src={product8} alt="Product Image" />
</a>
<div class="product-action">
<a href="#">
<i class="fa fa-cart-plus"></i>
</a>
<a href="#">
<i class="fa fa-heart"></i>
</a>
<a href="#">
<i class="fa fa-search"></i>
</a>
</div>
</div>
<div class="product-price">
<h3>
<span>$</span>99
</h3>
<a class="btn" href="">
<i class="fa fa-shopping-cart"></i>Buy Now
</a>
</div>
</div>
</div>
<div class="col-lg-3">
<div class="product-item">
<div class="product-title">
<a href="#">Product Name</a>
<div class="ratting">
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
</div>
</div>
<div class="product-image">
<a href="product-detail.html">
<img src={product9} alt="Product Image" />
</a>
<div class="product-action">
<a href="#">
<i class="fa fa-cart-plus"></i>
</a>
<a href="#">
<i class="fa fa-heart"></i>
</a>
<a href="#">
<i class="fa fa-search"></i>
</a>
</div>
</div>
<div class="product-price">
<h3>
<span>$</span>99
</h3>
<a class="btn" href="">
<i class="fa fa-shopping-cart"></i>Buy Now
</a>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default RecentProduct;
|
import AuthPage from '../pageobjects/AuthPage'
describe('auth', () => {
const page = new AuthPage()
it('init', () => {
page.open()
page.screenshot('init')
})
it('change lange', () => {
page.changeLange()
page.screenshot('change lange')
})
it('register', () => {
page.register()
page.screenshot('register')
})
})
|
'use strict';
//public createTable(tableName: String, attributes: Object, options: Object, model: Model): Promise
const Sequelize = require('sequelize');
let attributes = {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
uuid: {
unique: true,
allowNull: false,
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4
},
username: {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
email: {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
password: {
type: Sequelize.STRING,
defaultValue: null
},
is_verified: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
},
first_name: Sequelize.STRING,
last_name: Sequelize.STRING,
backup_email: {
type: Sequelize.STRING,
defaultValue: null
},
cell_phone: {
type: Sequelize.STRING,
defaultValue: null
},
created_at: {
allowNull: true,
type: Sequelize.INTEGER(10).UNSIGNED,
defaultValue: null
},
updated_at: {
allowNull: true,
type: Sequelize.INTEGER(10).UNSIGNED,
defaultValue: null
},
deleted_at: {
allowNull: true,
type: Sequelize.INTEGER(10).UNSIGNED,
defaultValue: null
}
};
let options = {
timestamps: false,
engine: 'InnoDB', // default: 'InnoDB'
charset: 'utf8mb4' // default: null
}
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('jp_users', attributes, options);
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('jp_users');
}
};
|
const fs = require('fs')
const glob = require("glob")
const px2vw = require("postcss-px-to-viewport")
const webpack = require('webpack')
const path = require('path')
const resolve = dir => {
return path.join(__dirname, dir)
}
const pages = {}
let entries
try {
// 获取相关入口
entries = glob('src/pages/*/index.js', {
sync: true
})
} catch (err) {
entries = []
throw err
}
// 格式化生成入口
entries.forEach((file) => {
// file字符串为 src/views/.../index.js
const fileSplit = file.split('/')
const pageName = fileSplit[2]
let pageHtml = fileSplit.slice(0, 3).join('/') + '/index.html'
if (!fs.existsSync(pageHtml)) {
// 入口如果不配置直接使用 _default.html
pageHtml = fileSplit.slice(0, 2).join('/') + '/_default.html'
}
pages[pageName] = {
entry: file,
template: pageHtml,
filename: `${pageName}.html`
}
})
//项目路径
const BASE_URL = process.env.NODE_ENV === 'production' ?
'/prize' :
'/'
module.exports = {
pages,
baseUrl: BASE_URL,
lintOnSave: false,
configureWebpack: {
plugins: [
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery'
})
]
},
chainWebpack: config => {
config.resolve.alias
.set('@', resolve('src')) // key,value自行定义,比如.set('@@', resolve('src/components'))
.set('_c', resolve('src/components'))
.set('_conf', resolve('config'))
},
// 打包时不生成.map文件
productionSourceMap: false,
css: {
loaderOptions: {
css: {
// options here will be passed to css-loader
},
postcss: {
plugins: () => [px2vw({
viewportWidth: 750,
viewporHeight: 134,
unitPrecision: 3,
viewportUnit: 'vw',
selectorBlackList: ['.ignore', '.hairlines'],
minPixelValue: 1,
mediaQuery: false
})]
}
}
},
// 这里写你调用接口的基础路径,来解决跨域,如果设置了代理,那你本地开发环境的axios的baseUrl要写为 '' ,即空字符串
devServer: {
host: '',
port: 3030,
proxy: {
'/api': {
// target: 'http://localhost:3000/api/',
target:"http://192.168.1.103:9090",
changeOrigin: true,
pathRewrite: {
'^/api': '/api'
}
}
}
}
}
|
// @flow
/* **********************************************************
* File: types/appWideActionTypes.js
*
* Brief: Type def for Actions that span the entire app
*
* Authors: Craig Cheney
*
* 2017.09.18 CC - Document created
*
********************************************************* */
export type updatePendingActionType = {
type: 'UPDATE_PENDING',
payload: {
version: string
}
};
export type showUserSettingsActionT = {
type: 'SHOW_USER_SETTINGS',
payload: {
show: boolean
}
};
export type enableDeveloperActionT = {
type: 'ENABLE_DEVELOPER',
payload: {
developer: boolean
}
};
/* [] - END OF FILE */
|
'use strict'
module.exports = {
NODE_ENV: '"production"',
AIRTABLE_API_KEY: '"keyysM2h2Va9vpmru"',
AIRTABLE_BASE: '"appH4DsvAZMNZ3VJU"'
}
|
import { cons } from 'hexlet-pairs';
import { randomPositiveInt, isYesNoAnswer, isEven } from '../utils';
import startGame from '../game';
const getProblem = () => {
const num = randomPositiveInt();
const answerText = isEven(num) ? 'yes' : 'no';
return cons(`${num}: `, answerText);
};
const startBrainEvenGame = () => {
startGame(getProblem, isYesNoAnswer);
};
export default startBrainEvenGame;
|
import useStyles from "../styles/main-style";
function ImageStructure({ planetName, images }) {
const { img } = useStyles();
return (
<img
className={img}
src={images.internal}
alt={`${planetName} internal structure`}
/>
);
}
export default ImageStructure;
|
/**
* This is essentially a Level class, which delegates logic to each game object where possible
*/
var statePlay = function () {
var self = this,
playerStartX = 15,
playerStartY = -10,
paintColor,
platformVerticalSpacing = 56,
platformHeight = 10,
// State info
pixelCount = 0,
animationScene = false,
roomComplete = false,
// Game objects
player,
playerGroup,
graphicsLayer,
graphics,
grapple,
platforms,
stonePlatforms,
signposts,
ginkians,
paint,
hud;
self.preload = function () {
game.load.image('platform', 'assets/platform.png');
game.load.image('stonePlatform', 'assets/stone-platform.png');
game.load.atlasJSONHash('player', 'assets/player.png', 'assets/player.json');
game.load.spritesheet('grapple', 'assets/grapple.png', 5, 5);
game.load.image('buttonPause', 'assets/blank.png');
game.load.image('buttonLeft', 'assets/button-left.png');
game.load.image('buttonRight', 'assets/button-right.png');
game.load.image('buttonJump', 'assets/button-jump.png');
game.load.image('buttonGrapple', 'assets/button-grapple.png');
game.load.image('heart', 'assets/heart.png');
game.load.image('heartEmpty', 'assets/heart-empty.png');
game.load.image('signpost', 'assets/signpost.png');
game.load.image('ginkian', 'assets/ginkian.png');
};
self.create = function () {
var levelWidth,
levelXml;
eventController = new EventController();
inputController = new InputController();
inputController.build();
levelXml = loadLevel();
levelWidth = levelXml.getElementsByTagName('width')[0].innerHTML;
game.world.setBounds(0, 0, parseInt(levelWidth), 336);
game.physics.arcade.checkCollision.up = false; // or you'll hit your head on the cave ceiling
game.stage.backgroundColor = '#000000';
paintColor = 0xc58917;
// For grapple and paint
graphicsLayer = game.add.group();
graphicsLayer.z = 1;
graphics = game.add.graphics(0, 0);
graphicsLayer.add(graphics);
playerGroup = game.add.group();
playerGroup.enableBody = true;
// Level
paint = new Paint();
paint.setGraphics(graphics);
buildLevel(levelXml);
//buildRandomLevel(levelWidth, 5);
//exportLevelToXml();
game.world.bringToTop(graphicsLayer);
game.world.bringToTop(playerGroup);
// Player
player = PlayerFactory.create(playerStartX, playerStartY);
player.registerEvents();
player.setGraphics(graphics);
grapple = GrappleFactory.create(player.x, player.y);
grapple.registerEvents();
grapple.setGraphics(graphics);
// Let the player and grapple know about each other
player.setGrapple(grapple);
grapple.setPlayer(player);
playerGroup.add(player);
playerGroup.add(grapple);
hud = new HUD();
hud.registerEvents();
hud.build();
eventController.trigger('UPDATE_HEARTS');
};
// Game loop
self.update = function () {
var isTouchingButtonLeft = false,
isTouchingButtonRight = false,
isTouchingButtonGrapple = false,
isTouchingButtonJump = false;
if (!dev && !game.scale.isFullScreen) {
game.physics.arcade.isPaused = true;
}
redrawScreen();
// All drawing to the graphics object (by other game objects) must happen after redrawScreen
eventController.trigger('UPDATE');
checkCollisions();
if (animationScene) {
return;
}
if (player.body.touching.down) {
eventController.trigger('PLAYER_TOUCHING_DOWN');
if (isTouchingButtonLeft) {
eventController.trigger('BUTTON_LEFT');
} else if (isTouchingButtonRight) {
eventController.trigger('BUTTON_RIGHT');
}
} else {
eventController.trigger('PLAYER_NOT_TOUCHING_DOWN');
}
// Check touch movement
if (!game.physics.arcade.isPaused) {
isTouchingButtonLeft = inputController.isTouchingButtonLeft();
isTouchingButtonRight = inputController.isTouchingButtonRight();
isTouchingButtonGrapple = inputController.isTouchingButtonGrapple();
isTouchingButtonJump = inputController.isTouchingButtonJump();
}
if (isTouchingButtonLeft) {
if (isTouchingButtonGrapple) {
eventController.trigger('GRAPPLE_ANGLE_LEFT');
isTouchingButtonLeft = false;
} else {
isTouchingButtonLeft = true;
eventController.trigger('BUTTON_LEFT');
}
}
if (isTouchingButtonRight) {
if (isTouchingButtonGrapple) {
eventController.trigger('GRAPPLE_ANGLE_RIGHT');
isTouchingButtonRight = false;
} else {
isTouchingButtonRight = true;
eventController.trigger('BUTTON_RIGHT');
}
}
if (isTouchingButtonJump) {
eventController.trigger('BUTTON_JUMP');
eventController.trigger('GRAPPLE_CANCEL');
}
if (isTouchingButtonGrapple) {
eventController.trigger('GRAPPLE_CANCEL');
eventController.trigger('GRAPPLE_AIM');
isTouchingButtonGrapple = true;
isTouchingButtonLeft = false;
isTouchingButtonRight = false;
// Slow time while aiming
game.time.advancedTiming = true;
game.time.desiredFps = 1200;
}
if (!isTouchingButtonLeft && !isTouchingButtonRight) {
eventController.trigger('BUTTON_LEFT_RIGHT_NOT_PRESSED');
}
// Shoot grapple
if (!isTouchingButtonGrapple && grapple.isAiming()) {
eventController.trigger('GRAPPLE_SHOOT');
// Restore time
game.time.advancedTiming = false;
game.time.desiredFps = 60;
}
if (paint.totalMarks() === pixelCount) {
pixelCount = 0;
beatRoom();
}
};
var loadLevel = function () {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'levels/level' + level + '.xml', false);
xmlhttp.send();
return xmlhttp.responseXML;
};
var buildLevel = function (levelXml) {
var i,
allPlatformsElem,
allStonePlatformsElem,
allSignpostsElem,
allGinkiansElem,
messageText,
messagePosition,
textPositionX,
textPositionY;
// Platforms
platforms = game.add.group();
platforms.enableBody = true;
stonePlatforms = game.add.group();
stonePlatforms.enableBody = true;
pixelCount = 0;
allPlatformsElem = levelXml.getElementsByTagName('platform');
for (i = 0; i < allPlatformsElem.length; i += 1) {
var platform = allPlatformsElem[i].childNodes[0].nodeValue;
var row = parseInt(platform.split(' ')[0]);
var x = parseInt(platform.split(' ')[1]);
var length = parseInt(platform.split(' ')[2]);
createPlatform(x, platformVerticalSpacing * row, length, platformHeight);
pixelCount += length;
}
platforms.forEach(function (platform) {
platform.body.immovable = true;
platform.body.checkCollision.left = false;
platform.body.checkCollision.right = false;
}, self);
// Stone platforms
allStonePlatformsElem = levelXml.getElementsByTagName('stone-platform');
for (i = 0; i < allStonePlatformsElem.length; i += 1) {
var platform = allStonePlatformsElem[i].childNodes[0].nodeValue;
var row = parseInt(platform.split(' ')[0]);
var x = parseInt(platform.split(' ')[1]);
var length = parseInt(platform.split(' ')[2]);
createStonePlatform(x, platformVerticalSpacing * row, length, platformHeight);
}
platforms.forEach(function (platform) {
platform.body.immovable = true;
platform.body.checkCollision.left = false;
platform.body.checkCollision.right = false;
}, self);
stonePlatforms.forEach(function (stonePlatform) {
stonePlatform.body.immovable = true;
stonePlatform.body.checkCollision.left = false;
stonePlatform.body.checkCollision.right = false;
}, self);
// Level text
if (levelXml.getElementsByTagName('message_text').length > 0) {
messageText = levelXml.getElementsByTagName('message_text')[0].innerHTML;
messagePosition = levelXml.getElementsByTagName('message_position')[0].innerHTML;
textPositionY = 30 * parseInt(messagePosition.split(' ')[0]) - 5;
textPositionX = parseInt(messagePosition.split(' ')[1]);
game.add.bitmapText(textPositionX, textPositionY, 'carrier_command', messageText, 10);
}
// Sign posts
signposts = game.add.group();
signposts.enableBody = true;
allSignpostsElem = levelXml.getElementsByTagName('signpost');
for (i = 0; i < allSignpostsElem.length; i += 1) {
var signpost = allSignpostsElem[i].childNodes[0].nodeValue;
var row = parseInt(signpost.split(' ')[0]);
var x = parseInt(signpost.split(' ')[1]);
createSignpost(x, platformVerticalSpacing * row);
}
// Ginkians
ginkians = game.add.group();
ginkians.enableBody = true;
allGinkiansElem = levelXml.getElementsByTagName('ginkian');
for (i = 0; i < allGinkiansElem.length; i += 1) {
var ginkian = allGinkiansElem[i].childNodes[0].nodeValue;
var row = parseInt(ginkian.split(' ')[0]);
var x = parseInt(ginkian.split(' ')[1]);
createGinkian(x, platformVerticalSpacing * row);
}
};
var buildRandomLevel = function (width, rows) {
var i;
pixelCount = 0;
platforms = game.add.group();
platforms.enableBody = true;
// ground
createPlatform(5, platformVerticalSpacing * rows, width - 5, platformHeight);
pixelCount = width - 5;
// platforms
for (i = 1; i < rows; i++) {
createRow(i, width);
}
platforms.forEach(function (platform) {
platform.body.immovable = true;
platform.body.checkCollision.left = false;
platform.body.checkCollision.right = false;
}, self);
};
// TODO: Create a platform class
var createRow = function (rowNumber, maxRightEdge) {
var minWidth = 15,
platformX = randomInRange(1, Math.floor(maxRightEdge / minWidth) / 4) * minWidth,
newMaxX = 0,
platformWidth = 0,
rowCount = 0;
while (platformX < maxRightEdge) {
newMaxX = platformX + randomInRange(3, 10) * minWidth;
if (newMaxX > maxRightEdge) {
break;
}
platformWidth = newMaxX - platformX;
createPlatform(platformX, platformVerticalSpacing * rowNumber, platformWidth, platformHeight);
rowCount += (newMaxX - platformX);
// Create a gap
newMaxX += randomInRange(5, 15) * minWidth;
platformX = newMaxX;
}
pixelCount += rowCount;
};
// TODO: Create a platform class
var createPlatform = function (x, y, width, height) {
var platform = game.add.tileSprite(x, y, width, height, 'platform');
platforms.add(platform);
return platform;
};
// TODO: Create a platform class
var createStonePlatform = function (x, y, width, height) {
var stonePlatform = game.add.tileSprite(x, y, width, height, 'stonePlatform');
stonePlatforms.add(stonePlatform);
return stonePlatform;
};
var exportLevelToXml = function () {
platforms.forEach(function (platform) {
var platformXml,
row,
x,
width;
row = Math.floor((platform.y + 5) / platformVerticalSpacing);
x = platform.body.x;
width = platform.body.width;
platformXml = '<platform>' + row + ' ' + x + ' ' + width + '</platform>';
console.log(platformXml);
}, self);
};
// TODO: Create a signpost class
var createSignpost = function (x, y) {
var signpost = game.add.sprite(x, y + 1, 'signpost');
signposts.add(signpost);
signpost.anchor.set(.5, 1);
signpost.body.setSize(25, 2, 8, 34); // collision box
signpost.body.immovable = true;
};
// TODO: Create a ginkian class
var createGinkian = function (x, y) {
var ginkian = game.add.sprite(x, y + 2, 'ginkian');
ginkians.add(ginkian);
ginkian.anchor.set(.5, 1);
};
var beatRoom = function () {
redrawScreen(); // Make sure the last paint is displayed
eventController.trigger('BEAT_ROOM');
animationScene = true;
roomComplete = true;
animateBeatRoom(30, function () {
nextRoom();
game.state.start(game.state.current);
});
function animateBeatRoom (i, callback) {
if (i < 0) {
paintColor = 0xc58917;
callback();
return;
}
if (i === 0 || i % 4 === 0) {
paintColor = 0x55ffff;
} else if (i === 1 || i % 4 === 1) {
paintColor = 0x00aa00;
} else if (i === 2 || i % 4 === 2) {
paintColor = 0xffffff;
} else if (i === 3 || i % 4 === 3) {
paintColor = 0xaa0000;
}
game.time.events.add(50, function () {
animateBeatRoom(i - 1, callback);
}, self).autoDestroy = true;
}
};
var killPlayer = function () {
var rotateDirection = 1;
player.kill();
game.camera.target = null;
rotatePlayer();
function rotatePlayer() {
// Stop condition
if ((rotateDirection === -1 && player.angle <= -90) || (rotateDirection === 1 && player.angle >= 90)) {
game.time.events.add(Phaser.Timer.SECOND, panCameraToEdge, self).autoDestroy = true;
return;
}
// Animation
player.angle = player.angle + (5 * rotateDirection);
game.time.events.add(10, rotatePlayer, self).autoDestroy = true;
}
function panCameraToEdge() {
var panDirection = -1
// Stop condition
if (game.camera.x <= 0) {
game.camera.x = 0;
if (player) {
player.unregisterEvents()
player.body.velocity.x = 0;
player.kill();
player.visible = false;
player = null;
}
player = PlayerFactory.create(playerStartX, playerStartY);
player.registerEvents()
animationScene = false;
return;
}
// Animation
game.camera.x = game.camera.x + (15 * panDirection);
game.time.events.add(10, panCameraToEdge, self).autoDestroy = true;
}
};
var redrawScreen= function () {
graphics.clear();
// TODO: Trigger an event instead
paint.draw(platformHeight, paintColor, platformVerticalSpacing);
};
var nextRoom = function () {
roomComplete = false;
animationScene = false;
if (level % 4 === 0) {
heartCount = 3;
}
level++;
};
var collidePlayerPlatform = function (player, platform) {
// Allow player to jump up through the platform
if (player.body.velocity.y >= 0) {
// Only mark the platform if the player is standing on it
if ((player.y + player.height / 2 - 4) < platform.y) {
paint.newPaint(platform, player, platformVerticalSpacing);
return true;
}
}
return false;
};
var collidePlayerStonePlatform = function (player, stonePlatform) {
// Allow player to jump up through the platform
if (player.body.velocity.y >= 0) {
return true;
}
return false;
};
var collidePlayerSignpost = function (player, signpost) {
return true;
};
var collideGrapplePlatform = function (grapple, platform) {
eventController.trigger('GRAPPLE_HIT_PLATFORM');
};
var checkCollisions = function () {
// Collisions
game.physics.arcade.collide(player, platforms, null, collidePlayerPlatform);
game.physics.arcade.collide(player, stonePlatforms, null, collidePlayerStonePlatform);
game.physics.arcade.collide(player, signposts, null, collidePlayerSignpost);
game.physics.arcade.collide(grapple, platforms, null, collideGrapplePlatform);
};
};
|
$(window).on('load', function(event) {
$('body').removeClass('preloading');
// $('.load').delay(1000).fadeOut('fast');
$('.loader').delay(1000).fadeOut('fast');
});
$(document).ready(function() {
$('.button-menu-mobile').click(function(event) {
$('.is_menu').toggleClass('show-button-menu-mobile');
});
$('.categories').click(function(event){
$('.main-menu-mobile').addClass('show-menu-categories');
});
$('.menu-categories div').click(function(event){
$('.main-menu-mobile').removeClass('show-menu-categories');
});
var dataMenu = $('.main-menu-mobile').attr('data-menu');
var arrMenu = $('.this-is-menu a').toArray();
if (dataMenu == "home") {
$('.button-menu-mobile').addClass('main-menu-mobile');
$('.logo').addClass('main-menu-mobile');
}
if (dataMenu == "about") {
$('.button-menu-mobile').addClass('about-menu-mobile');
}
var dataIsMenu ="";
for (var i = 0; i < arrMenu.length; i++) {
dataIsMenu = $(arrMenu[i]).attr('data-is-menu');
if (dataMenu == dataIsMenu) {
$(arrMenu[i]).addClass('active-menu');
}
}
$('.slider').slick({
slidesToShow: 2,
slidesToScroll: 1,
nextArrow: $('.slide_next'),
pauseOnHover: true,
centerMode: true,
focusOnSelect: true,
responsive: [
{
breakpoint: 767,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
if(screen.width <= 1024 && screen.width >= 768 || screen.width <= 768){
$('.this-slider-menu-3').removeClass('slider-menu-3');
}
var play_work = 0;
tl4 = new TimelineMax({paused: true});
function slide_works(src1,src2,src3, title1, title2, title3, content1, content2, content3, titlesp1, titlesp2, titlesp3){
tl4.set('.slide-work-1 .img-work img',{attr:{src:src1}}, 0.8);
tl4.set('.slide-work-2 .img-work img', {attr:{src:src2}}, 0.8);
tl4.set('.slide-work-3 .img-work img', {attr:{src:src3}}, 0.8);
tl4.to('.slide-work-1 .content-work > div > article', 0, {text: title1}, 0.6);
tl4.to('.slide-work-1 .content-work > div:nth-child(1) span', 0, {text: content1}, 0.6);
tl4.to('.slide-work-1 .content-work > div:nth-child(2)', 0, {text: titlesp1}, 0.6);
tl4.to('.slide-work-2 .content-work > div > article', 0, {text: title2}, 0.6);
tl4.to('.slide-work-2 .content-work > div:nth-child(1) span', 0, {text: content2}, 0.6);
tl4.to('.slide-work-2 .content-work > div:nth-child(2)', 0, {text: titlesp2}, 0.6);
tl4.to('.slide-work-3 .content-work > div > article', 0, {text: title3}, 0.6);
tl4.to('.slide-work-3 .content-work > div:nth-child(1) span', 0, {text: content3}, 0.6);
tl4.to('.slide-work-3 .content-work > div:nth-child(2)', 0, {text: titlesp3}, 0.6);
}
if(screen.width <= 1023 && screen.width >= 768 || screen.width <= 768){
$('.work > div').removeClass('slide-work-1');
$('.work > div').removeClass('slide-work-2');
$('.work > div').removeClass('slide-work-3');
}
$('.slide_next_work').click(function(event) {
tl4.clear();
tl4.to('.slide-work-1 .img-work > article', 0, {transformOrigin:"0% 0%"}, 0);
tl4.to('.slide-work-1 .img-work > article', 0.8, {scaleY: 1});
tl4.to('.slide-work-2 .img-work > article', 0, {transformOrigin:"0% 100%"}, 0);
tl4.to('.slide-work-2 .img-work > article', 0.8, {scaleY: 1}, 0);
tl4.to('.slide-work-3 .img-work > article', 0, {transformOrigin:"0% 0%"}, 0);
tl4.to('.slide-work-3 .img-work > article', 0.8, {scaleY: 1}, 0);
tl4.to('.slide-work-1 .content-work', 0.5, {opacity: 0, y: 30}, 0);
tl4.to('.slide-work-1 .content-work', 0, {opacity: 0, y: -30}, 0.5);
tl4.to('.slide-work-2 .content-work', 0.5, {opacity: 0, y: -30}, 0);
tl4.to('.slide-work-2 .content-work', 0, {opacity: 0, y: 30}, 0.5);
tl4.to('.slide-work-3 .content-work', 0.5, {opacity: 0, y: 30}, 0);
tl4.to('.slide-work-3 .content-work', 0, {opacity: 0, y: -30}, 0.5);
if(play_work == 0){
play_work = 1;
let src1 = "assets/images/img-menu-3-3.png",
src2 = "assets/images/img-menu-3-1.png",
src3 = "assets/images/img-menu-3-2.png",
title1 = "cheese coffee",
title2 = "tết kỷ hợi",
title3 = "wrap & roll",
content1 = "cheese sytem",
content2 = "personal",
content3 = "restaurent sytem",
titlesp1 = "brand identity",
titlesp2 = "advertising",
titlesp3 = "brand identity";
slide_works(src1,src2,src3, title1, title2, title3, content1, content2, content3, titlesp1, titlesp2, titlesp3);
tl4.to('.slide-work-1 .img-work > article', 0, {transformOrigin:"0% 100%"}, 0.9);
tl4.to('.slide-work-1 .img-work > article', 0.8, {scaleY: 0}, 0.9);
tl4.to('.slide-work-2 .img-work > article', 0, {transformOrigin:"0% 0%"}, 0.9);
tl4.to('.slide-work-2 .img-work > article', 0.8, {scaleY: 0}, 0.9);
tl4.to('.slide-work-3 .img-work > article', 0, {transformOrigin:"0% 100%"}, 0.9);
tl4.to('.slide-work-3 .img-work > article', 0.8, {scaleY: 0}, 0.9);
tl4.to('.work .content-work', 0.7, {opacity: 1, y: 0}, 0.7);
tl4.to('.pagingInfo', 0, {text: "2/2"}, 0.7);
tl4.progress(0).play();
}else if(play_work == 1){
play_work = 0;
let src1 = "assets/images/img-menu-3-1.png",
src2 = "assets/images/img-menu-3-2.png",
src3 = "assets/images/img-menu-3-3.png",
title1 = "tết kỷ hợi",
title2 = "wrap & roll",
title3 = "cheese coffee",
content1 = "personal",
content2 = "restaurent sytem",
content3 = "cheese sytem",
titlesp1 = "advertising",
titlesp2 = "brand identity",
titlesp3 = "brand identity";
slide_works(src1,src2,src3, title1, title2, title3, content1, content2, content3, titlesp1, titlesp2, titlesp3);
tl4.to('.slide-work-1 .img-work > article', 0, {transformOrigin:"0% 100%"}, 0.9);
tl4.to('.slide-work-1 .img-work > article', 0.8, {scaleY: 0}, 0.9);
tl4.to('.slide-work-2 .img-work > article', 0, {transformOrigin:"0% 0%"}, 0.9);
tl4.to('.slide-work-2 .img-work > article', 0.8, {scaleY: 0}, 0.9);
tl4.to('.slide-work-3 .img-work > article', 0, {transformOrigin:"0% 100%"}, 0.9);
tl4.to('.slide-work-3 .img-work > article', 0.8, {scaleY: 0}, 0.9);
tl4.to('.work .content-work', 0.7, {opacity: 1, y: 0}, 0.7);
tl4.to('.pagingInfo', 0, {text: "1/2"}, 0.7);
tl4.progress(0).play();
}
});
var arrContentLy4 = $('.content-ly-4').toArray();
var arrDetlLy4 = $('.detail-ly4').toArray();
for (let i = 0; i < arrDetlLy4.length; i++) {
$(arrDetlLy4[i]).click(function(event){
$("html, body").animate({ scrollTop: 50 }, 1500);
for (let j = 0; j < arrDetlLy4.length; j++) {
$(arrContentLy4[j]).removeClass('show-content-ly-4');
}
$(arrContentLy4[i]).addClass('show-content-ly-4');
});
}
var services_menusp = $('.menu-4-menusp ul li').toArray();
var play_menusp = 0;
var content_menusp = "";
tl2 = new TimelineMax({paused: true, onComplete: function(){
play_menusp = 1;
} });
function slide_services(src1,src2,src3){
tl2.set('.img-services > div:nth-child(1) img',{attr:{src:src1}});
tl2.set('.img-services > div:nth-child(2) img', {attr:{src:src2}});
tl2.set('.img-services > div:nth-child(3) img', {attr:{src:src3}});
}
for (let i = 0; i < services_menusp.length; i++) {
$(services_menusp[i]).click(function(event) {
content_menusp = $(this).attr('data-menusp');
for (let j = 0; j < services_menusp.length; j++) {
$(services_menusp[j]).removeClass('active-menusp');
}
$(this).addClass('active-menusp');
play_menusp = i;
tl2.clear();
tl2.to('.img-services > div:nth-child(1) > article', 0, {transformOrigin:"0% 0%"});
tl2.to('.img-services > div:nth-child(2) > div > article', 0, {transformOrigin:"100% 0%"});
tl2.to('.img-services > div:nth-child(3) > div > article', 0, {transformOrigin:"0% 100%"});
tl2.to('.img-services > div:nth-child(1) > article', 1, {scaleY: 1});
tl2.to('.img-services > div:nth-child(2) > div > article', 1, {scaleX: 1}, 0);
tl2.to('.img-services > div:nth-child(3) > div > article', 1, {scaleY: 1}, 0);
tl2.to('.img-services > div:nth-child(4) > div section', 0.5, {opacity: 0}, 0);
tl2.to('.img-services > div:nth-child(4) > div section', 0, {y: "100%"}, 0.5);
slide_services();
if(play_menusp == 0){
let src1 = "assets/images/menu4-images-1.png",
src2 = "assets/images/menu4-images-2.png",
src3 = "assets/images/menu4-images-3.png";
slide_services(src1,src2,src3);
}
if(play_menusp == 1){
let src1 = "assets/images/menu4-images-1_2.png",
src2 = "assets/images/menu4-images-3_2.png",
src3 = "assets/images/menu4-images-2_2.png";
slide_services(src1,src2,src3);
}
if(play_menusp == 2){
let src1 = "assets/images/menu4-images-3_2.png",
src2 = "assets/images/menu4-images-2_2.png",
src3 = "assets/images/menu4-images-1_2.png";
slide_services(src1,src2,src3);
}
if(play_menusp == 3){
let src1 = "assets/images/menu4-images-2_2.png",
src2 = "assets/images/menu4-images-3_2.png",
src3 = "assets/images/menu4-images-1_2.png";
slide_services(src1,src2,src3);
}
tl2.to('.img-services > div:nth-child(4) > div section', 0, {text: content_menusp}, 0.55);
tl2.to('.img-services > div:nth-child(1) > article', 0, {transformOrigin:"0% 100%"});
tl2.to('.img-services > div:nth-child(2) > div > article', 0, {transformOrigin:"0% 0%"}, 1);
tl2.to('.img-services > div:nth-child(3) > div > article', 0, {transformOrigin:"0% 0%"}, 1);
tl2.to('.img-services > div:nth-child(1) > article', 1, {scaleY: 0}, 1.05);
tl2.to('.img-services > div:nth-child(2) > div > article', 1, {scaleX: 0}, 1.05);
tl2.to('.img-services > div:nth-child(3) > div > article', 1, {scaleY: 0}, 1.05);
tl2.to('.img-services > div:nth-child(4) > div section', 1, {opacity: 1, y: 0}, 0.6);
tl2.progress(0).play();
});
}
const slide_main_next = $('.slide_main_next');
var playing = 0;
tl = new TimelineMax({paused: true});
slide_main_next.click(function(){
tl.clear();
tl.to('.main-1-left > article', 0, {transformOrigin:"0% 0%"}, 0);
tl.to('.main-1-left > article', 0.85, {scaleY: 1}, 0);
if(playing == 0){
playing = 1;
tl.to('.layout-01', 0.5, {background: '#dddddd'}, 0.15);
tl.to('.main-1-left-1', 0, {opacity: 0});
tl.to('.main-1-left-2', 0, {opacity: 1});
tl.to('.main-1-left > article', 0, {transformOrigin:"0% 100%"}, 0.85);
tl.to('.main-1-left > article', 0.85, {scaleY: 0}, 0.9);
tl.to('.slide-content-mid-1 h3', 0, {opacity: 0}, 0.5);
tl.to('.slide-content-mid-1 .main-1-icon-1', 0, {opacity: 0}, 0.5);
tl.to('.slide-content-mid-1 .main-1-icon-1 img', 0, {opacity: 0}, 0.5);
tl.to('.slide-content-mid-1 h3', 0, {y: "100%"}, 0.5);
tl.to('.slide-content-mid-1 .main-1-icon-1', 0, {y: 50}, 0.5);
tl.to('.slide-content-mid-1 .main-1-icon-1 img', 0, {x: -50}, 0.5);
tl.to('.slide-content-mid-2 h3', 0, {y: "100%"}, 0.5);
tl.to('.slide-content-mid-2 .main-1-icon-1', 0, {y: 50}, 0.5);
tl.to('.slide-content-mid-2 .main-1-icon-1 img', 0, {x: -50}, 0.5);
tl.to('.slide-content-mid-2 h3', 0.7, {opacity: 1, y: 0}, 0.55);
tl.to('.slide-content-mid-2 .main-1-icon-1', 0.7, {opacity: 1, y: 0}, 1.5);
tl.to('.slide-content-mid-2 .main-1-icon-1 img', 0.5, {opacity: 1, x: 0}, 2);
tl.progress(0).play();
}
else if(playing == 1){
playing = 0;
tl.to('.layout-01', 0.5, {background: '#ffcb08'}, 0.15);
tl.to('.main-1-left-1', 0, {opacity: 1});
tl.to('.main-1-left-2', 0, {opacity: 0});
tl.to('.main-1-left > article', 0, {transformOrigin:"0% 100%"}, 0.85);
tl.to('.main-1-left > article', 0.85, {scaleY: 0}, 0.9);
tl.to('.slide-content-mid-2 h3', 0, {opacity: 0}, 0.5);
tl.to('.slide-content-mid-2 .main-1-icon-1', 0, {opacity: 0}, 0.5);
tl.to('.slide-content-mid-2 .main-1-icon-1 img', 0, {opacity: 0}, 0.5);
tl.to('.slide-content-mid-2 h3', 0, {y: "100%"}, 0.5);
tl.to('.slide-content-mid-2 .main-1-icon-1', 0, {y: 50}, 0.5);
tl.to('.slide-content-mid-2 .main-1-icon-1 img', 0, {x: -50}, 0.5);
tl.to('.slide-content-mid-1 .main-1-icon-1', 0, {y: 50}, 0.5);
tl.to('.slide-content-mid-1 .main-1-icon-1 img', 0, {x: -50}, 0.5);
tl.to('.slide-content-mid-1 h3', 0.7, {opacity: 1, y: 0}, 0.55);
tl.to('.slide-content-mid-1 .main-1-icon-1', 0.7, {opacity: 1, y: 0}, 1.5);
tl.to('.slide-content-mid-1 .main-1-icon-1 img', 0.5, {opacity: 1, x: 0}, 2);
tl.progress(0).play();
}
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.