text
stringlengths 7
3.69M
|
|---|
const PROD_DOMAIN = 'https://localhost:8000';
const DEV_DOMAIN = 'https://localhost:8000';
const getDomain = (NODE_ENV = 'dev') => {
switch (NODE_ENV) {
case 'prod':
return PROD_DOMAIN;
case 'dev':
default:
return DEV_DOMAIN;
}
};
const SERVER_DOMAIN = getDomain(process.env.NODE_ENV);
export const oaKaryRoute = (endpoint) => `${SERVER_DOMAIN}/${endpoint}/`;
|
import { combineReducers } from 'redux';
import BreedSearchReducer from './BreedSearchReducer';
import TopBreedsReducer from './TopBreedsReducer';
import BreedsReducer from './BreedsReducer';
export default combineReducers({
BreedsReducer,
BreedSearchReducer,
TopBreedsReducer
});
|
var blank1 = "Letters";
var blank2 = "Numbers";
var blank3 = "Underscore";
var blank4 = "$";
var blank5 = "letter";
var blank6 = "underscore";
var blank7 = "$";
var blank8 = "sensitive";
var blank9 = "keywords";
document.write("<h1>" + "Rules for naming JS Variables" + "</h1>");
document.write("Variables name can only contain" + " " + blank1 + "," + blank2 + "," + blank3 + " " + " " + "and" + " " + blank4 + "." );
document.write(" For example: $my_1stVariable" + "<br>" );
document.write("Variables must begin with a" + " " + blank5 + "," + blank6 + " " + "or" + " " + blank7 + "." );
document.write("For Example $name, _name, or name" + "<br>" );
document.write("Variables name are case" + " " + blank8 + "." + "<br>");
document.write("Variables name should not be JS " + blank9);
|
'use strict';
// модуль, который создаёт данные
(function () {
var catalogCardsElement = document.querySelector('.catalog__cards');
// функция для первичной загрузки данных и рендера каталога
var onSuccessLoadData = function (data) {
for (var i = 0; i < data.length; i++) {
data[i].id = i;
data[i].isFavorite = false;
}
// для первоначального фильтра
data.sort(function (a, b) {
return b.rating.number - a.rating.number;
});
window.data.catalogObjArray = data.slice();
window.slider.resetRangeFiltersValue();
var catalogFragment = window.catalog.renderCatalog(data);
catalogCardsElement.append(catalogFragment);
window.filters.setMinMaxPrices();
window.utils.disableOrderForm(true);
catalogCardsElement.classList.remove('catalog__cards--load');
catalogCardsElement.querySelector('.catalog__load').classList.add('visually-hidden');
window.filters.displayCounters();
};
window.data = {
catalogObjArray: [],
basketObjArray: []
};
window.backend.load(onSuccessLoadData, window.backend.showErrorPopup);
})();
|
/**
* Library layout.
*/
P.views.library.Layout = P.views.Layout.extend({
templateId: 'library.layout',
regions: {
rContext: '#r-context'
}
});
|
import axios from 'axios'
export function getFilmNews () {
const url = '/news/NewsList.api'
return axios.get(url).then((res) => {
return Promise.resolve(res.data)
}).catch((err) => {
console.log(err)
})
}
export function getNewsDetails (id) {
const url = '/news/Detail.api'
return axios.get(url, {
params: {
newsId: id
}
}).then((res) => {
return Promise.resolve(res.data)
}).catch((err) => {
console.log(err)
})
}
|
/* variables locales de T_FCTRCKPKKMJDY_588*/
|
const DISPLAY_WIDGET = 'DISPLAY_WIDGET';
const CLOSE_WIDGET = 'CLOSE_WIDGET';
const ADD_NOTE = 'ADD_NOTE';
const DELETE_NOTE = 'DELETE_NOTE';
export {
DISPLAY_WIDGET,
CLOSE_WIDGET,
ADD_NOTE,
DELETE_NOTE,
};
|
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
export const TextReconstruction = (props) => {
const [checked, setChecked] = useState(
props.checkedToPrint[props.printName] === true,
);
const handleChange = (event) => {
const value = event.target.checked;
setChecked(value);
props.addToPrint(props.printName, value);
};
return (
<>
<p>
Promysli, co vše se bude rekonstruovat a <strong>rozpočet</strong>. Vzor
rozpočtu ti poskytne banka či poradce, ale stačí vzít papír a na začátek
si to sepsat přibližně. Nejlepší je odborně vypracovaný rozpočet
stavební firmou. Ideálně na doporučení, aby se pak nenavyšoval.
</p>
<p>
Plánuješ rekonstruovat <strong>svépomocí</strong>? O to víc se nad
rozpočtem zamysli. Bude rekonstrukce rozsáhlá a máš připravenou
projektovou dokumentaci? Určitě ji do banky vezmi.
</p>
<p>
Nevíš, zda plánovaná rekonstrukce vyžaduje
<strong> nahlášení stavebnímu úřadu </strong> nebo celý proces získání
<strong> stavebního povolení</strong>? Je dobré se na to informovat.
Očekávej, že pokud je hlášení nutné, tak banka ho bude chtít časem
vidět. Pozor na rady kamarádů, na stavební úřad to radši nehlásit.
Jakmile se k rekonstrukci vyjádří odhadce, tak banka bude chtít zákon
dodržet. Jistě tě ale nic takového nenapadlo.
</p>
<p>
Rekonstruuješ nemovitost v pronájmu? Budeš potřebovat
<strong> souhlas majielů s rekonstrukcí</strong>
</p>
<p>
Chceš půjčit polovinu a bance nic není do toho, kolik bude rekonstrukce
stát celkem? To není bohužel pravda. Banka bude chtít jistotu, že stavba
bude dokončena. Připrav si i
<strong> informaci, jak dofinancuješ celý rozpočet:</strong>
</p>
<ul>
<li>Peníze na účtu</li>
<li>Končící investice za nějaký čas</li>
<li>Prodej současného bydlení atd.</li>
</ul>
<div className="row-print">
<label className="checkbox">
Přidat do tisku:
<input
className="print"
type="checkbox"
checked={checked}
onChange={handleChange}
/>
<span></span>
</label>
<Link to="/print">Prohlédnout tisk</Link>
</div>
<div className="buttons-row__buttons">
<Link to="/">
<button className="button--back ">Domů</button>
</Link>
<Link to="/prijem">
<button className="button--forward">Pokračovat</button>
</Link>
</div>
</>
);
};
|
var mutations = {
'SET_MENU_FLAG_TRUE': function(state) {
state.menuShowFlag = true;
},
'SET_MENU_FLAG_FALSE': function(state) {
state.menuShowFlag = false;
},
'ADD_DONE_LIST': function(state, listObj) {
state.doneList.push(listObj);
},
'REMOVE_DONE_LIST': function(state) {
state.doneList.pop();
},
'ADD_DOING_LIST': function(state, listObj) {
state.doingList.push(listObj);
},
'REMOVE_DOING_LIST': function(state) {
state.doingList.pop();
},
'ADD_DELETED_LIST': function(state, listObj) {
state.deletedList.push(listObj);
},
'REMOVE_DELETED_LIST': function(state) {
state.deleteList.pop();
},
'SET_DONE_LIST_COUNT': function(state, count) {
state.menuList[1].count = count;
},
'SET_DOING_LIST_COUNT': function(state, count) {
state.menuList[2].count = count;
},
'SET_DELETED_LIST_COUNT': function(state, count) {
state.menuList[3].count = count;
},
'SET_ALL_LIST_COUNT': function(state, count) {
state.menuList[0].count = count;
}
};
module.exports = mutations;
|
const authenticationRoutes = require('./auth');
const categoryRoutes = require('./category');
const entityRoutes = require('./entity');
const reviewRoutes = require('./review');
const homeRoutes = require('./home');
module.exports = (app) => {
homeRoutes(app);
authenticationRoutes(app);
categoryRoutes(app);
entityRoutes(app);
reviewRoutes(app);
}
|
import React, { Component } from 'react'
export class HighOrder extends Component {
constructor(props) {
super(props)
this.state = {
count: 0
}
}
addCOunt =()=>{
this.setState({
count: this.state.count + 1
})
}
render() {
const {count} = this.state
return (
<div>
<button onClick={this.addCOunt}>Clicked {count} times</button>
</div>
)
}
}
export default HighOrder
/***
* the JSX sample that will be in App.js
<HighOrder />
* **/
|
/**
* Copyright (c) 2013 Oculus Info Inc.
* http://www.oculusinfo.com/
*
* Released under the MIT License.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
define(['jquery'], function($) {
var getRange = function(data) {
var result = {
minX:null,
maxX:null,
minY:null,
maxY:null
};
for (var i=0; i<data.length; i++) {
var datum = data[i];
if (result.minX==null || result.minX>datum.lon) result.minX = datum.lon;
if (result.maxX==null || result.maxX<datum.lon) result.maxX = datum.lon;
if (result.minY==null || result.minY>datum.lat) result.minY = datum.lat;
if (result.maxY==null || result.maxY<datum.lat) result.maxY = datum.lat;
}
return result;
};
var initKmeans = function(data,k) {
var range = getRange(data);
var xsteps = Math.ceil(Math.sqrt(k));
var xstep = (range.maxX-range.minX)/xsteps;
var ysteps = Math.ceil(k/xsteps);
var ystep = (range.maxY-range.minY)/ysteps;
var clusters = [];
var curX = 0, curY = 0;
for (var i=0; i<k; i++) {
curX = Math.floor(i/ysteps);
curY = i-curX*ysteps;
clusters.push({lon:range.minX+xstep*curX,lat:range.minY+ystep*curY,members:[]});
}
return clusters;
};
var assignClusters = function(data, clusters) {
var anyChanges = false;
for (var i=0; i<data.length; i++) {
var datum = data[i];
var bestMatch = null;
var bestDistance = null;
for (var j=0; j<clusters.length; j++) {
var cluster = clusters[j];
var distance = Math.pow(cluster.lon-datum.lon,2)+Math.pow(cluster.lat-datum.lat,2);
if (bestDistance==null || distance<bestDistance) {
bestMatch = j;
bestDistance = distance;
}
}
if ((!datum.cluster)||(datum.cluster!=bestMatch)) {
anyChanges = true;
datum.cluster = bestMatch;
}
clusters[bestMatch].members.push(datum);
}
return anyChanges;
};
var computeCentroids = function(clusters) {
for (var i=0; i<clusters.length; i++) {
var cluster = clusters[i];
var sumX = 0, sumY = 0;
for (var j=0; j<cluster.members.length; j++) {
sumX += cluster.members[j].lon;
sumY += cluster.members[j].lat;
}
if (cluster.members.length!=0) {
cluster.lon = sumX/cluster.members.length;
cluster.lat = sumY/cluster.members.length;
}
}
};
var clearClusters = function(clusters) {
for (var i=0; i<clusters.length; i++) {
clusters[i].members.length = 0;
}
};
var kmeans = function(data, k) {
var clusters = initKmeans(data,k);
assignClusters(data, clusters);
var anyChanges = true;
var iteration = 0;
while (anyChanges && iteration<100) {
computeCentroids(clusters);
clearClusters(clusters);
anyChanges = assignClusters(data, clusters);
iteration++;
}
var result = [];
for (var i=0; i<clusters.length; i++) {
var cluster = clusters[i];
if (cluster.members.length>0) result.push(cluster);
}
return result;
};
return {
kmeans:kmeans
}
});
|
import { useEffect, useState } from 'react'
import { getGitBranches, checkIfDirectoryIsGitRepo } from '../utilities/gitLogic.js'
export const useGitBranchesForDirectory = directory => {
const [branches, setBranches] = useState({ active: null, all: [] })
useEffect(() => {
checkIfDirectoryIsGitRepo(directory).then(verdict => {
if (verdict) {
getGitBranches(directory).then(rawBranches => {
if (rawBranches.length !== 0) {
const branches = rawBranches.split('\n').map(item => {
return item.trim()
}).reduce((acc, item) => {
if (item.length > 0) {
if (item[0] === '*') {
const activeBranch = item.split('* ')[1]
acc.active = activeBranch
acc.local.push(activeBranch)
acc.list.push(activeBranch)
} else if (item.indexOf('remotes/') === 0) {
acc.remote.push(item)
acc.list.push(item)
} else {
acc.local.push(item)
acc.list.push(item)
}
}
return acc
}, {
active: '',
list: [],
local: [],
remote: []
})
setBranches(branches)
} else {
setBranches({
active: '[No Branches Yet]',
list: [],
local: [],
remote: []
})
}
}).catch(error => {
console.error(error)
})
}
})
}, [directory])
return branches
}
|
var Stack = function() {
var someInstance = Object.create(stackMethods);
someInstance.storage = {};
someInstance.count = 1;
return someInstance;
};
var stackMethods = {
size: function() {
return Object.keys(this.storage).length;
},
push: function(value) {
this.count++;
this.storage[this.count] = value;
},
pop: function() {
var temp = this.storage[this.count];
delete this.storage[this.count];
this.count--;
return temp;
},
};
|
import React, {useState, useEffect } from 'react';
import './App.css';
function CharDetail({match}) {
useEffect(() => {
fetchChar();
console.log(match)
}, []);
const [character, setCharacter] = useState({});
const fetchChar = async () => {
const fetchChar = await fetch(`https://rickandmortyapi.com/api/character/${match.params.urlId}`);
const character = await fetchChar.json();
setCharacter(character);
console.log(character)
};
return (
<div>
<h1>{character.name}</h1>
<img src={character.image}></img>
<h4>Gender: {character.gender}</h4>
<h4>Status: {character.status}</h4>
<h4>Species: {character.species}</h4>
<h4>Type: {(character.type == '') ? ('No type assigned') : (character.type)}</h4>
</div>
);
}
export default CharDetail;
|
#!/usr/bin/env nodejs
var util = require('util');
var bitcoin = require('bitcoin');
var client = new bitcoin.Client({
host: 'localhost',
port: 8332,
user: 'bitcoinrpc',
pass: '9erTnrzdQBMbcStyuQvnKTWSvb1KWVM76VZzZzRTye5D'
});
var cc = function (msg) {
console.log(util.inspect(msg, false, null))
};
var stdin = process.openStdin();
var data = "";
stdin.on('data', function (chunk) {
data += chunk;
});
stdin.on('end', function () {
data = data.split("|");
key = data[0];
data = JSON.parse(data[1]);
client.signRawTransaction(data.trn.hex, data.inputs, [key], function (err, res) {
if (err) {
return console.error(err);
}
process.stdout.write(JSON.stringify({"trn": res}));
});
});
|
import React, { Component } from 'react'
import CounterContainer from './container/counter_container'
import PersonContainer from './container/person_container'
export default class App extends Component {
render() {
return (
<div>
<h2>Counter组件</h2>
<CounterContainer/>
<h2>Person组件</h2>
<PersonContainer/>
</div>
)
}
}
|
/**
* Created by candellc on 2016-02-18.
*/
window.onload=function(){
var $container = $('.container'),
$boxes = $container.find('.brick'),
columns = $container.data('width'),
multiplicator = $container.width()/columns,
positionArray = [];
function isFree(position, width, height) {
var free = true,
column = position % columns;
if (column+width <= columns) {
for (var i=position; free && i<=position+(height-1)*columns; i+=columns) {
for (var j=i; free && j < i + width; j++) {
if (positionArray[j] === false){
free = false;
}
}
}
if (free) {
for (var i = position; i <= position + (height - 1) * columns; i += columns) {
for (var j=i; j < i + width; j++) {
positionArray[j] = false;
}
}
return true;
}
} else {
return false;
}
}
function positionTile(tile, position) {
var positionX = position % columns,
positionY = Math.floor(position / columns);
tile.css({left:positionX * multiplicator, top:positionY * multiplicator});
}
$.each($boxes, function ( key, value ) {
var $this = $( value ),
goOn = true;
for (var i = 0; goOn === true; i++) {
if (isFree(i, $this.data('width'), $this.data('height'))) {
positionTile($this, i);
goOn = false;
}
}
});
// XORCipher - Super simple encryption using XOR and Base64
//
// Depends on [Underscore](http://underscorejs.org/).
//
// As a warning, this is **not** a secure encryption algorythm. It uses a very
// simplistic keystore and will be easy to crack.
//
// The Base64 algorythm is a modification of the one used in phpjs.org
// * http://phpjs.org/functions/base64_encode/
// * http://phpjs.org/functions/base64_decode/
//
// Examples
// --------
//
// XORCipher.encode("test", "foobar"); // => "EgocFhUX"
// XORCipher.decode("test", "EgocFhUX"); // => "foobar"
//
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, strict:true,
undef:true, unused:true, curly:true, browser:true, indent:2, maxerr:50 */
/* global _ */
(function(exports) {
"use strict";
var XORCipher = {
encode: function(key, data) {
data = xor_encrypt(key, data);
return b64_encode(data);
},
decode: function(key, data) {
data = b64_decode(data);
return xor_decrypt(key, data);
}
};
var b64_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function b64_encode(data) {
var o1, o2, o3, h1, h2, h3, h4, bits, r, i = 0, enc = "";
if (!data) { return data; }
do {
o1 = data[i++];
o2 = data[i++];
o3 = data[i++];
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
enc += b64_table.charAt(h1) + b64_table.charAt(h2) + b64_table.charAt(h3) + b64_table.charAt(h4);
} while (i < data.length);
r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + "===".slice(r || 3);
}
function b64_decode(data) {
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, result = [];
if (!data) { return data; }
data += "";
do {
h1 = b64_table.indexOf(data.charAt(i++));
h2 = b64_table.indexOf(data.charAt(i++));
h3 = b64_table.indexOf(data.charAt(i++));
h4 = b64_table.indexOf(data.charAt(i++));
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >> 16 & 0xff;
o2 = bits >> 8 & 0xff;
o3 = bits & 0xff;
result.push(o1);
if (h3 !== 64) {
result.push(o2);
if (h4 !== 64) {
result.push(o3);
}
}
} while (i < data.length);
return result;
}
function keyCharAt(key, i) {
return key.charCodeAt( Math.floor(i % key.length) );
}
function xor_encrypt(key, data) {
return _.map(data, function(c, i) {
return c.charCodeAt(0) ^ keyCharAt(key, i);
});
}
function xor_decrypt(key, data) {
return _.map(data, function(c, i) {
return String.fromCharCode( c ^ keyCharAt(key, i) );
}).join("");
}
exports.XORCipher = XORCipher;
})(this);
myArray = $('.brick');
}
|
require('./info.tag')
require('./list.tag')
require('./selectbox.tag')
require('./markdown.tag')
var items = [{subject: 'subject1'}];
var sub = require('./SubjectList.js');
var subjects = new sub.SubjectList();
riot.mount('info', {});
riot.mount('list', {
'items': items,
'subjects': subjects
});
riot.mount('markdown', {
'subjects': subjects
});
|
var Utils = {
testMint(contract, accounts, account0, account1, account2) {
return contract.mint([accounts[0]], [account0])
.then(function () {
return contract.finishMinting()
}).catch((err) => {
throw new Error(err) });
}
}
module.exports = Utils
|
var a; // a is declared, but undefined.
console.log(a);
// NOTE: undefine is a special keyword in javascript
if (a === undefined) {
console.log('a is undefined!');
}
else {
console.log('a is defined!');
}
|
var rs = require('readline-sync');
var cont = rs.questionInt('Coloca um numero ai: ')
var contfin = rs.questionInt('Coloca outro numero ai: ')
for(var i = cont; i <= contfin; i++){
console.log(i)
}
// variavel contadora inicia apenas de onde quero iniciar
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mongoose = require("mongoose");
const DataAccess_1 = require("../DataAccess");
class BalanceSheetReportSchema {
static get schema() {
let schemaDefinition = {
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
csv: {
type: mongoose.Schema.Types.ObjectId,
ref: 'File',
required: true
},
month: {
type: Number,
required: true
},
year: {
type: Number,
required: true
}
};
let schema = DataAccess_1.DataAccess.initSchema(schemaDefinition);
schema.index({ userId: 1, year: -1, month: -1, deletedAt: 1 }, { unique: true });
return schema;
}
}
exports.default = DataAccess_1.DataAccess.connection.model('BalanceSheetReport', BalanceSheetReportSchema.schema);
|
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import { scenePadding } from 'kitsu/screens/Profiles/constants';
export const ScrollItem = ({ spacing, ...props }) => (
<View style={{ marginLeft: spacing }} {...props} />
);
ScrollItem.propTypes = {
spacing: PropTypes.number,
};
ScrollItem.defaultProps = {
spacing: scenePadding,
};
|
import React from "react";
import NavBar from "./NaviBar";
import "./HomePage.css";
import { Row, Col } from "react-bootstrap";
import Icon1 from "./github.svg";
import Icon2 from "./linkedin.svg";
class Home extends React.Component {
render() {
return (
<div>
<div><NavBar /></div>
<Row >
<Col xs={{ span: 12 }} md={{ span: 10, offset: 1 }} lg={{ span: 8, offset: 2 }} className="paper">
<Row className="Firstsection" >
<Col xs={{ span: 6, offset: 3 }} md={{ span: 4, offset: 1 }} className="Photo">
</Col>
<Col xs={{ span: 6, offset: 3 }} md={{ span: 5, offset: 1 }} className="Title">
<h1 className="Name">Yue Xiong</h1>
<h6 className="Name"> Frontend Developer | Fullstack Developer</h6>
<p className="totalIcon">
<a href="https://github.com/Christinayue" target="_blank" rel="noopener noreferrer" className="icon"><img src={Icon1} alt="github" /></a>
<a href="https://www.linkedin.com/in/yue-xiong-450172177/" target="_blank" rel="noopener noreferrer" className="icon"><img src={Icon2} alt="linkedin" /></a>
</p>
</Col>
</Row>
<Row className="introduce">
<Col xs={{ span: 12 }} md={{ span: 6 }} >
<h3 className="aboutme">About <span style={{ color: "rgba(34, 110, 148, 0.8)" }}>Me</span></h3>
<p className="text">Excellent frontend developer who can also design the wonderful web pages according to the customer’s demand. I am a faster learner and learning new techniques quickly, as well as having good communication skills.
In addition, I have a foundation in architectural design and a strong interest in designing and implementing a website.</p>
</Col>
<Col xs={{ span: 12 }} md={{ span: 6 }} >
<ul className="text1">
<li><span className="title1">Age:</span> <span className="value"> 25</span></li>
<li><span className="title1">Residence:</span> <span className="value"> Australia</span></li>
<li><span className="title1">Address:</span> <span className="value"> Kingsford</span></li>
<li><span className="title1">E-mail:</span> <span className="value" style={{ color: "rgba(34, 110, 148, 0.8)" }}> 1564488470@qq.com</span></li>
<li><span className="title1">Phone:</span> <span className="value"> +0414037786</span></li>
</ul>
</Col>
</Row>
</Col>
</Row>
<Row>
<Col xs={12} md={{ span: 6, offset: 3 }}>
<p style={{ textAlign: "center", marginTop: "70px", color: "rgba(51, 42, 42, 0.7)" }}><span>Australia IT Professional Community</span> <span style={{ color: "rgba(34, 110, 148, 0.8)" }}>UNSW Master</span></p>
</Col>
</Row>
</div >
);
}
}
export default Home;
|
import React from 'react'
const App = typeof USER_APP !== 'undefined' && USER_APP
? require(USER_APP).default || require(USER_APP)
: props => props.render()
export default Component => props =>
<App
render={appProps => (
<Component
{...props}
{...appProps}
/>
)}
/>
|
import React from 'react';
const Footer = ()=> {
return (
<footer className=" p-4 foot">
<p className="float-right"><a href="#">Наверх</a></p>
<p>© 2017-2020 Company, Inc.</p>
</footer>
);
}
export default Footer;
|
// @codekit-append "gambit-fullwidth.js"
// @codekit-append "gambit-fullheight.js"
// @codekit-append "gambit-parallax.js"
// @codekit-append "gambit-video-bg.js"
// @codekit-append "gambit-hover.js"
// @codekit-append "gambit-background.js"
/**
* Finds the parent VC row. If it fails, it returns a parent that has a class name of *row*.
* If it still fails, it returns the immediate parent.
*/
document.gambitFindElementParentRow = function( el ) {
// find VC row
var row = el.parentNode;
while ( ! row.classList.contains('vc_row') && ! row.classList.contains('wpb_row') ) {
if ( row.tagName === 'HTML' ) {
row = false;
break;
}
row = row.parentNode;
}
if ( row !== false ) {
return row;
}
// If vc_row & wpb_row have been removed/renamed, find a suitable row
row = el.parentNode;
var found = false;
while ( ! found ) {
Array.prototype.forEach.call( row.classList, function(className, i) {
if ( found ) {
return;
}
if ( className.match(/row/g) ){
found = true;
return;
}
})
if ( found ) {
return row;
}
if ( row.tagName === 'HTML' ) {
break;
}
row = row.parentNode;
}
// Last resort, return the immediate parent
return el.parentNode;
}
jQuery(document).ready(function($) {
// Add zIndex to order all the layers
var elements = document.querySelectorAll('.gambit_background_row, .gambit_parallax_row, .gambit_hover_row, .gambit_video_row');
Array.prototype.forEach.call(elements, function(el, i) {
el.style.zIndex = ( i + 1 ) * -1;
el.setAttribute('data-zindex', ( i + 1 ) * -1 );
});
function _isMobile() {
return navigator.userAgent.match(/(Mobi|Android)/);
}
$('.gambit_parallax_row').each(function() {
$(this).gambitImageParallax({
image: $(this).attr('data-bg-image'),
direction: $(this).attr('data-direction'),
mobileenabled: $(this).attr('data-mobile-enabled'),
mobiledevice: _isMobile(),
opacity: $(this).attr('data-opacity'),
width: $(this).attr('data-bg-width'),
height: $(this).attr('data-bg-height'),
velocity: $(this).attr('data-velocity'),
align: $(this).attr('data-bg-align'),
repeat: $(this).attr('data-bg-repeat'),
zIndex: $(this).attr('data-zindex'),
target: $( document.gambitFindElementParentRow( $(this)[0] ) ),
complete: function() {
}
});
});
});
jQuery(document).ready(function($) {
"use strict";
function fixFullWidthRows() {
$('.gambit_fullwidth_row').each(function(i) {
// Find the parent row
var row = $( document.gambitFindElementParentRow( $(this)[0] ) );
var origWebkitTransform = row.css('webkitTransform');
var origMozTransform = row.css('mozTransform');
var origMSTransform = row.css('msTransform');
var origTransform = row.css('transform');
// Reset changed parameters for contentWidth so that width recalculation on resize will work
row.css({
'width': '',
'position': '',
'maxWidth': '',
'left': '',
'paddingLeft': '',
'paddingRight': '',
'webkitTransform': '',
'mozTransform': '',
'msTransform': '',
'transform': ''
});
var contentWidth = $(this).attr('data-content-width') || row.children(':not([class^=gambit])').width() + 'px';
// Make sure our parent won't hide our content
row.parent().css('overflowX', 'visible');
// Reset the left parameter
row.css('left', '');
// Assign the new full-width styles
row.css({
'width': '100vw',
'position': 'relative',
'maxWidth': $(window).width(),
'left': -row.offset().left,
'webkitTransform': origWebkitTransform,
'mozTransform': origMozTransform,
'msTransform': origMSTransform,
'transform': origTransform
});
if ( contentWidth === '' ) {
return;
}
// Calculate the required left/right padding to ensure that the content width is being followed
var padding = 0, actualWidth, paddingLeft, paddingRight;
if ( contentWidth.search('%') !== -1 ) {
actualWidth = parseFloat( contentWidth ) / 100 * $(window).width();
} else {
actualWidth = parseFloat( contentWidth );
}
padding = ( $(window).width() - actualWidth ) / 2;
paddingLeft = padding + parseFloat( row.css('marginLeft' ) );
paddingRight = padding + parseFloat( row.css('marginRight' ) );
// If the width is too large, don't pad
if ( actualWidth > $(window).width() ) {
paddingLeft = 0;
paddingRight = 0;
}
row.css({
'paddingLeft': paddingLeft,
'paddingRight': paddingRight
});
});
}
// setTimeout( function() {
fixFullWidthRows();
// }, 2);
$(window).resize(function() {
fixFullWidthRows();
// setTimeout( function() {
// fixFullWidthRows();
// }, 2);
});
});
jQuery(document).ready(function($) {
"use strict";
function fixFullWidthRows() {
$('.gambit_fullheight_row').each(function(i) {
// Find the parent row
var row = $( document.gambitFindElementParentRow( $(this)[0] ) );
var contentWidth = $(this).attr('data-content-location') || 'center';
// We need to add minheight or else the content can go past the row
row.css('minHeight', row.height() + 60);
// Let CSS do the work for us
row.addClass('gambit-row-fullheight gambit-row-height-location-' + contentWidth);
// If center, remove top margin of topmost text & bottom margin of bottommost text
if ( contentWidth === 'center' ) {
row.find('> .vc_column_container > .wpb_wrapper > .wpb_text_column > .wpb_wrapper > *:first-child')
.css('marginTop', 0);
row.find('> .vc_column_container > .wpb_wrapper > .wpb_text_column > .wpb_wrapper > *:last-child')
.css('marginBottom', 0);
}
});
}
fixFullWidthRows();
});
/**
* requestAnimationFrame polyfill
*
* http://paulirish.com/2011/requestanimationframe-for-smart-animating/
* http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
* requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
* requestAnimationFrame polyfill under MIT license
*/
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for( var x = 0; x < vendors.length && ! window.requestAnimationFrame; ++x ) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function( callback, element ) {
return window.setTimeout( function() { callback(); }, 16 );
};
}
}());
// Don't re-initialize our variables since that can delete existing values
if ( typeof _gambitImageParallaxImages === 'undefined' ) {
var _gambitImageParallaxImages = [];
var _gambitScrollTop;
var _gambitWindowHeight;
var _gambitScrollLeft;
var _gambitWindowWidth;
}
;(function ( $, window, document, undefined ) {
// Create the defaults once
var pluginName = "gambitImageParallax",
defaults = {
direction: 'up', // fixed
mobileenabled: false,
mobiledevice: false,
width: '',
height: '',
align: 'center',
opacity: '1',
velocity: '.3',
image: '', // The background image to use, if empty, the current background image is used
target: '', // The element to apply the parallax to
repeat: false,
loopScroll: '',
loopScrollTime: '2',
removeOrig: false,
zIndex: '-1', // Carry over the z-index of the placeholder div (this was set so we can layer different backgrounds properly)
id: '',
complete: function() {}
};
// The actual plugin constructor
function Plugin ( element, options ) {
this.element = element;
// jQuery has an extend method which merges the contents of two or
// more objects, storing the result in the first object. The first object
// is generally empty as we don't want to alter the default options for
// future instances of the plugin
this.settings = $.extend( {}, defaults, options );
if ( this.settings.align == '' ) {
this.settings.align = 'center';
}
if ( this.settings.id === '' ) {
this.settings.id = +new Date();
}
this._defaults = defaults;
this._name = pluginName;
this.init();
}
// Avoid Plugin.prototype conflicts
$.extend(Plugin.prototype, {
init: function () {
// Place initialization logic here
// You already have access to the DOM element and
// the options via the instance, e.g. this.element
// and this.settings
// you can add more functions like the one below and
// call them like so: this.yourOtherFunction(this.element, this.settings).
// console.log("xD");
// $(window).bind( 'parallax', function() {
// self.gambitImageParallax();
// });
// If there is no target, use the element as the target
if ( this.settings.target === '' ) {
this.settings.target = $(this.element);
}
this.settings.target.addClass( this.settings.direction );
// If there is no image given, use the background image if there is one
if ( this.settings.image === '' ) {
//if ( typeof $(this.element).css('backgroundImage') !== 'undefined' && $(this.element).css('backgroundImage').toLowerCase() !== 'none' && $(this.element).css('backgroundImage') !== '' )
if ( typeof $(this.element).css('backgroundImage') !== 'undefined' && $(this.element).css('backgroundImage') !== '' ) {
this.settings.image = $(this.element).css('backgroundImage').replace( /url\(|\)|"|'/g, '' );
}
}
_gambitImageParallaxImages.push( this );
this.setup();
this.settings.complete();
this.containerWidth = 0;
this.containerHeight = 0;
},
setup: function () {
if ( this.settings.removeOrig !== false ) {
$(this.element).remove();
}
this.resizeParallaxBackground();
},
doParallax: function () {
// if it's a mobile device and not told to activate on mobile, stop.
if ( this.settings.mobiledevice && ! this.settings.mobileenabled ) {
return;
}
// fixed backgrounds need no movement
// if ( this.settings.direction === 'fixed' ) {
//
// // Chrome retina bug where the background doesn't repaint
// // Bug report: https://code.google.com/p/chromium/issues/detail?id=366012
// if ( window.devicePixelRatio > 1 ) {
// $(this.settings.target).hide().show(0);
// //this.settings.target[0].style.display = 'none';
// //this.settings.target[0].style.display = '';
// }
//
// }
// check if the container is in the view
if ( ! this.isInView() ) {
return;
}
// Continue moving the background
if ( typeof this.settings.inner === 'undefined' ) {
// this.settings.inner = this.settings.target.find('.parallax-inner-' + this.settings.id);
this.settings.inner = this.settings.target[0].querySelectorAll('.parallax-inner-' + this.settings.id)[0];
}
var $target = this.settings.inner;
// Retrigger a resize if the container's size suddenly changed
// var w = this.settings.target.width() + parseInt( this.settings.target.css( 'paddingRight' ) ) + parseInt( this.settings.target.css( 'paddingLeft' ) );
// var h = this.settings.target.height() + parseInt( this.settings.target.css( 'paddingTop' ) ) + parseInt( this.settings.target.css( 'paddingBottom' ) );
if ( typeof this.settings.doParallaxClientLastUpdate === 'undefined'
|| +new Date() - this.settings.doParallaxClientLastUpdate > 2000 + Math.random() * 1000 ) {
this.settings.doParallaxClientLastUpdate = +new Date();
this.settings.clientWidthCache = this.settings.target[0].clientWidth;
this.settings.clientHeightCache = this.settings.target[0].clientHeight;
}
if ( this.containerWidth !== 0
&& this.containerHeight !== 0
&& ( this.settings.clientWidthCache !== this.containerWidth
|| this.settings.clientHeightCache !== this.containerHeight ) ) {
this.resizeParallaxBackground();
}
this.containerWidth = this.settings.clientWidthCache;
this.containerHeight = this.settings.clientHeightCache;
// If we don't have anything to scroll, stop
// if ( typeof $target === 'undefined' || $target.length === 0 ) {
// return;
// }
// compute for the parallax amount
var percentageScroll = (_gambitScrollTop - this.scrollTopMin) / (this.scrollTopMax - this.scrollTopMin);
var dist = this.moveMax * percentageScroll;
// change direction
if ( this.settings.direction === 'left' || this.settings.direction === 'up' ) {
dist *= -1;
}
// IE9 check, IE9 doesn't support 3d transforms, so fallback to 2d translate
var translateHori = 'translate3d(';
var translateHoriSuffix = 'px, 0px, 0px)';
var translateVert = 'translate3d(0px, ';
var translateVertSuffix = 'px, 0px)';
if ( typeof _gambitParallaxIE9 !== 'undefined' ) {
translateHori = 'translate(';
translateHoriSuffix = 'px, 0px)';
translateVert = 'translate(0px, ';
translateVertSuffix = 'px)';
}
if ( $target.style.backgroundRepeat === "no-repeat" ) {
if ( this.settings.direction === 'down' && dist < 0 ) {
dist = 0;
}
if ( this.settings.direction === 'up' && dist > 0 ) {
dist = 0;
}
}
// Apply the parallax transforms
if ( this.settings.direction === 'left' || this.settings.direction === 'right' ) {
$target.style.transition = 'transform 1ms linear';
$target.style.webkitTransform = translateHori + dist + translateHoriSuffix;
$target.style.transform = translateHori + dist + translateHoriSuffix;
}
else {
$target.style.transition = 'transform 1ms linear';
$target.style.webkitTransform = translateVert + dist + translateVertSuffix;
$target.style.transform = translateVert + dist + translateVertSuffix;
}
// In some browsers, parallax might get jumpy/shakey, this hack makes it better
// by force-cancelling the transition duration
$target.style.transition = 'transform -1ms linear';
},
// Checks whether the container with the parallax is inside our viewport
isInView: function() {
// if ( typeof $target === 'undefined' || $target.length === 0 ) {
// return;
// }
// Cache some values for faster calculations
if ( typeof this.settings.offsetLastUpdate === 'undefined'
|| +new Date() - this.settings.offsetLastUpdate > 4000 + Math.random() * 1000 ) {
this.settings.offsetLastUpdate = +new Date();
var $target = this.settings.target[0];
// this.settings.offsetTopCache = $target.offset().top;
// this.settings.elemHeightCache = $target.height()
// + parseInt( $target.css('paddingTop') )
// + parseInt( $target.css('paddingBottom') );
this.settings.offsetTopCache = $target.getBoundingClientRect().top + window.pageYOffset;
this.settings.elemHeightCache = $target.clientHeight;
}
var elemTop = this.settings.offsetTopCache;
var elemHeight = this.settings.elemHeightCache;
if ( elemTop + elemHeight < _gambitScrollTop || _gambitScrollTop + _gambitWindowHeight < elemTop ) {
return false;
}
return true;
},
computeCoverDimensions: function( imageWidth, imageHeight, container ) {
/* Step 1 - Get the ratio of the div + the image */
var imageRatio = imageWidth / imageHeight;
var coverRatio = container.offsetWidth / container.offsetHeight;
/* Step 2 - Work out which ratio is greater */
if ( imageRatio >= coverRatio ) {
/* The Height is our constant */
var finalHeight = container.offsetHeight;
var scale = ( finalHeight / imageHeight );
var finalWidth = imageWidth * scale;
} else {
/* The Width is our constant */
var finalWidth = container.offsetWidth;
var scale = ( finalWidth / imageWidth );
var finalHeight = imageHeight * scale;
}
return finalWidth + 'px ' + finalHeight + 'px';
},
// Resizes the parallax to match the container size
resizeParallaxBackground: function() {
var $target = this.settings.target;
if ( typeof $target === 'undefined' || $target.length === 0 ) {
return;
}
// Repeat the background
var isRepeat = this.settings.repeat === 'true' || this.settings.repeat === true || this.settings.repeat === 1;
// Assert a minimum of 150 pixels of height globally. Prevents the illusion of parallaxes not rendering at all in empty fields.
$target[0].style.minHeight = '150px';
/*
* None, do not apply any parallax at all.
*/
if ( this.settings.direction === 'none' ) {
// Stretch the image to fit the entire window
var w = $target.width() + parseInt( $target.css( 'paddingRight' ) ) + parseInt( $target.css( 'paddingLeft' ) );
// Compute position
var position = $target.offset().left;
if ( this.settings.align === 'center' ) {
position = '50% 50%';
}
else if ( this.settings.align === 'left' ) {
position = '0% 50%';
}
else if ( this.settings.align === 'right' ) {
position = '100% 50%';
}
else if ( this.settings.align === 'top' ) {
position = '50% 0%';
}
else if ( this.settings.align === 'bottom' ) {
position = '50% 100%';
}
$target.css({
opacity: Math.abs( parseFloat ( this.settings.opacity ) / 100 ),
backgroundSize: 'cover',
backgroundAttachment: 'scroll',
backgroundPosition: position,
backgroundRepeat: 'no-repeat'
});
if ( this.settings.image !== '' && this.settings.image !== 'none' ) {
$target.css({
opacity: Math.abs( parseFloat ( this.settings.opacity ) / 100 ),
backgroundImage: 'url(' + this.settings.image + ')'
});
}
/*
* Fixed, just stretch to fill up the entire container
*/
} else if ( this.settings.direction === 'fixed' ) {
// Stretch the image to fit the entire window
var w = $target.width() + parseInt( $target.css( 'paddingRight' ) ) + parseInt( $target.css( 'paddingLeft' ) );
var h = _gambitWindowHeight;
// Compute alignment position
var align = '0%';
if ( this.settings.align === 'center' ) {
align = '50%';
} else if ( this.settings.align === 'right' ) {
align = '100%';
}
var left = $target.offset().left;
// IE, IE11, edge
var isIE = !!navigator.userAgent.match(/MSIE/) || !!navigator.userAgent.match(/Trident.*rv[ :]*11\./) || !!navigator.userAgent.match(/Edge\/12/);
var isEdge = !!navigator.userAgent.match(/Edge\/12/);
if ( ! isIE && $target.find('.fixed-wrapper-' + this.settings.id).length < 1 ) {
$('<div></div>')
.addClass('fixed-wrapper-' + this.settings.id)
.prependTo( $target );
}
if ( $target.find('.parallax-inner-' + this.settings.id).length < 1 ) {
$('<div></div>')
.addClass('gambit_parallax_inner')
.addClass('parallax-inner-' + this.settings.id)
.addClass( this.settings.direction )
.prependTo( isIE ? $target : $target.find('.fixed-wrapper-' + this.settings.id) );
}
// Apply the required styles
$target.css({
position: 'relative',
overflow: 'hidden',
zIndex: 1,
});
// This is where the magic happens, we use clip to force the position:fixed + overflow:hidden to work,
// this needs a position:absolute parent to work in other browsers. Webkit browsers work right away, so no
// need to absolute the parent.
// @see http://stackoverflow.com/questions/12463658/parent-child-with-position-fixed-parent-overflowhidden-bug
$target.find('.fixed-wrapper-' + this.settings.id).css({
// position: navigator.userAgent.match(/webkit/i) ? 'relative' : 'absolute',
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
clip: isIE ? 'auto' : 'rect(auto,auto,auto,auto)',
webkitTransform: 'none',
transform: 'none'
});
// .attr('style', 'background-image: none !important; ' + $target.attr('style'))
$target.find('.parallax-inner-' + this.settings.id ).css({
pointerEvents: 'none',
width: w,
height: h,
position: isIE ? 'absolute' : 'fixed',
zIndex: this.settings.zIndex,
top: 0,
left: isIE ? 0 : left,
opacity: Math.abs( parseFloat ( this.settings.opacity ) / 100 ),
// backgroundSize: 'cover',
backgroundSize: isRepeat ? 'auto' : ( isIE ? this.computeCoverDimensions( this.settings.width, this.settings.height, $target[0].querySelectorAll('.parallax-inner-' + this.settings.id)[0] ) : 'cover' ),
backgroundAttachment: 'fixed',
backgroundPosition: isRepeat ? '0 0 ' : '50% 50%',
backgroundRepeat: isRepeat ? 'repeat' : 'no-repeat',
webkitTransform: 'translateZ(0)',
transform: 'translateZ(0)'
});
// Edge doesn't follow background-attachment fixed if you have transforms!
if ( isEdge ) {
$target.css({
transform: 'none',
transformStyle: 'flat'
});
$target.find('.parallax-inner-' + this.settings.id ).css({
transform: 'none',
transformStyle: 'flat'
});
}
if ( this.settings.image !== '' && this.settings.image !== 'none' ) {
$target.find('.parallax-inner-' + this.settings.id ).css({
opacity: Math.abs( parseFloat ( this.settings.opacity ) / 100 ),
backgroundImage: 'url(' + this.settings.image + ')'
});
}
// Deactivate on mobile. Normal deactivation doesn't work, we need
// to do this manually.
if ( this.settings.mobiledevice && ! this.settings.mobileenabled ) {
$target.find('.parallax-inner-' + this.settings.id ).css({
position: 'absolute',
backgroundAttachment: 'initial',
backgroundSize: 'cover',
left: '0',
right: '0',
bottom: '0',
top: '0',
height: 'auto',
width: 'auto'
});
}
/*
* Left & right parallax - Stretch the image to fit the height & extend the sides
*/
} else if ( this.settings.direction === 'left' || this.settings.direction === 'right' ) {
// Stretch the image to fit the entire window
var w = $target.width() + parseInt( $target.css( 'paddingRight' ) ) + parseInt( $target.css( 'paddingLeft' ) );
var h = $target.height() + parseInt( $target.css( 'paddingTop' ) ) + parseInt( $target.css( 'paddingBottom' ) );
var origW = w;
w += 400 * Math.abs( parseFloat( this.settings.velocity ) );
// Compute left position
var top = '0%';
if ( this.settings.align === 'center' ) {
top = '50%';
} else if ( this.settings.align === 'bottom' ) {
top = '100%';
}
// Compute top position
var left = 0;
if ( this.settings.direction === 'right' ) {
left -= w - origW;
}
if ( $target.find('.parallax-inner-' + this.settings.id).length < 1 ) {
$('<div></div>')
.addClass('gambit_parallax_inner')
.addClass('parallax-inner-' + this.settings.id)
.addClass( this.settings.direction )
.prependTo( $target );
}
// Apply the required styles
$target.css({
position: 'relative',
overflow: 'hidden',
zIndex: 1
})
// .attr('style', 'background-image: none !important; ' + $target.attr('style'))
.find('.parallax-inner-' + this.settings.id ).css({
pointerEvents: 'none',
width: w,
height: h,
position: 'absolute',
zIndex: this.settings.zIndex,
top: 0,
left: left,
opacity: Math.abs( parseFloat ( this.settings.opacity ) / 100 ),
// backgroundSize: isRepeat ? '100%' : 'cover',
backgroundSize: isRepeat ? 'auto' : this.computeCoverDimensions( this.settings.width, this.settings.height, $target[0].querySelectorAll('.parallax-inner-' + this.settings.id)[0] ),
backgroundPosition: isRepeat ? '0 0 ' : '50% ' + top,
backgroundRepeat: isRepeat ? 'repeat' : 'no-repeat'
});
if ( this.settings.image !== '' && this.settings.image !== 'none' ) {
$target.find('.parallax-inner-' + this.settings.id ).css({
opacity: Math.abs( parseFloat ( this.settings.opacity ) / 100 ),
backgroundImage: 'url(' + this.settings.image + ')'
});
}
// Compute for the positions to save cycles
var scrollTopMin = 0;
if ( $target.offset().top > _gambitWindowHeight ) {
scrollTopMin = $target.offset().top - _gambitWindowHeight;
}
var scrollTopMax = $target.offset().top + $target.height() + parseInt( $target.css( 'paddingTop' ) ) + parseInt( $target.css( 'paddingBottom' ) );
this.moveMax = w - origW;
this.scrollTopMin = scrollTopMin;
this.scrollTopMax = scrollTopMax;
/*
* Up & down parallax - Stretch the image to fit the width & extend vertically
*/
} else { // Up or down
// We have to add a bit more to DOWN since the page is scrolling as well,
// or else it will not be visible
var heightCompensate = 800;
if ( this.settings.direction === 'down' ) {
heightCompensate *= 1.2;
}
// Stretch the image to fit the entire window
var w = $target.width() + parseInt( $target.css( 'paddingRight' ) ) + parseInt( $target.css( 'paddingLeft' ) );
var h = $target.height() + parseInt( $target.css( 'paddingTop' ) ) + parseInt( $target.css( 'paddingBottom' ) );
var origH = h;
h += heightCompensate * Math.abs( parseFloat(this.settings.velocity) );
// Compute left position
var left = '0%';
if ( this.settings.align === 'center' ) {
left = '50%';
} else if ( this.settings.align === 'right' ) {
left = '100%';
}
// Compute top position
var top = 0;
if ( this.settings.direction === 'down' ) {
top -= h - origH;
}
if ( $target.find('.parallax-inner-' + this.settings.id).length < 1 ) {
$('<div></div>')
.addClass('gambit_parallax_inner')
.addClass('parallax-inner-' + this.settings.id)
.addClass( this.settings.direction )
.prependTo( $target );
}
// Apply the required styles
$target.css({
position: 'relative',
overflow: 'hidden',
zIndex: 1
})
// .attr('style', 'background-image: none !important; ' + $target.attr('style'))
.find('.parallax-inner-' + this.settings.id).css({
pointerEvents: 'none',
width: w,
height: h,
position: 'absolute',
zIndex: this.settings.zIndex,
top: top,
left: 0,
opacity: Math.abs( parseFloat ( this.settings.opacity ) / 100 ),
// backgroundSize: isRepeat ? '100%' : 'cover',
backgroundSize: isRepeat ? 'auto' : this.computeCoverDimensions( this.settings.width, this.settings.height, $target[0].querySelectorAll('.parallax-inner-' + this.settings.id)[0] ),
backgroundPosition: isRepeat ? '0' : left + ' 50%',
backgroundRepeat: isRepeat ? 'repeat' : 'no-repeat'
});
if ( this.settings.image !== '' && this.settings.image !== 'none' ) {
$target.find('.parallax-inner-' + this.settings.id).css({
opacity: Math.abs( parseFloat ( this.settings.opacity ) / 100 ),
backgroundImage: 'url(' + this.settings.image + ')'
});
}
// Compute for the positions to save cycles
var scrollTopMin = 0;
if ( $target.offset().top > _gambitWindowHeight ) {
scrollTopMin = $target.offset().top - _gambitWindowHeight;
}
var scrollTopMax = $target.offset().top + $target.height() + parseInt( $target.css( 'paddingTop' ) ) + parseInt( $target.css( 'paddingBottom' ) );
this.moveMax = h - origH;
this.scrollTopMin = scrollTopMin;
this.scrollTopMax = scrollTopMax;
}
},
});
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[ pluginName ] = function ( options ) {
this.each(function() {
if ( !$.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
});
// chain jQuery functions
return this;
};
})( jQuery, window, document );
function _gambitRefreshScroll() {
var $ = jQuery;
_gambitScrollTop = window.pageYOffset;//$(window).scrollTop();
_gambitScrollLeft = window.pageXOffset;//$(window).scrollLeft();
}
function _gambitParallaxAll() {
_gambitRefreshScroll();
for ( var i = 0; i < _gambitImageParallaxImages.length; i++) {
_gambitImageParallaxImages[ i ].doParallax();
}
}
jQuery(document).ready(function($) {
"use strict";
$( window ).on(
'scroll touchmove touchstart touchend gesturechange mousemove', function( e ) {
requestAnimationFrame( _gambitParallaxAll );
}
);
function mobileParallaxAll() {
_gambitRefreshScroll();
for ( var i = 0; i < _gambitImageParallaxImages.length; i++) {
_gambitImageParallaxImages[ i ].doParallax();
}
requestAnimationFrame(mobileParallaxAll);
}
if ( navigator.userAgent.match(/(Mobi|Android)/)) {
requestAnimationFrame(mobileParallaxAll);
}
// Adjust parallax when VC grid items screws up row sizes
$(window).on( 'grid:items:added', function() {
setTimeout( function() {
var $ = jQuery;
_gambitRefreshWindow();
$.each( _gambitImageParallaxImages, function( i, parallax ) {
parallax.resizeParallaxBackground();
} );
}, 1 );
})
// When the browser resizes, fix parallax size
// Some browsers do not work if this is not performed after 1ms
$(window).on( 'resize', function() {
setTimeout( function() {
var $ = jQuery;
_gambitRefreshWindow();
$.each( _gambitImageParallaxImages, function( i, parallax ) {
parallax.resizeParallaxBackground();
} );
}, 1 );
} );
// setTimeout( parallaxAll, 1 );
setTimeout( function() {
var $ = jQuery;
_gambitRefreshWindow();
$.each( _gambitImageParallaxImages, function( i, parallax ) {
parallax.resizeParallaxBackground();
} );
}, 1 );
// setTimeout( parallaxAll, 100 );
setTimeout( function() {
var $ = jQuery;
_gambitRefreshWindow();
$.each( _gambitImageParallaxImages, function( i, parallax ) {
parallax.resizeParallaxBackground();
} );
}, 100 );
function _gambitRefreshWindow() {
_gambitScrollTop = window.pageYOffset;//$(window).scrollTop();
_gambitWindowHeight = window.innerHeight;//$(window).height()
_gambitScrollLeft = window.pageXOffset;//$(window).scrollLeft();
_gambitWindowWidth = window.innerWidth;//$(window).width()
}
});
/**
* These are in charge of initializing YouTube
*/
function _vcRowGetAllElementsWithAttribute( attribute ) {
var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0, n = allElements.length; i < n; i++) {
if (allElements[i].getAttribute(attribute)) {
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}
function _vcRowOnPlayerReady(event) {
var player = event.target;
player.playVideo();
if ( player.isMute ) {
player.mute();
}
if ( player.forceHD ) {
player.setPlaybackQuality( 'hd720' );
}
var prevCurrTime = player.getCurrentTime();
var timeLastCall = +new Date() / 1000;
var currTime = 0;
var firstRun = true;
player.loopInterval = setInterval(function() {
if ( typeof player.loopTimeout !== 'undefined' ) {
clearTimeout( player.loopTimeout );
}
if ( prevCurrTime == player.getCurrentTime() ) {
currTime = prevCurrTime + ( +new Date() / 1000 - timeLastCall );
} else {
currTime = player.getCurrentTime();
timeLastCall = +new Date() / 1000;
}
prevCurrTime = player.getCurrentTime();
if ( currTime + ( firstRun ? 0.45 : 0.21 ) >= player.getDuration() ) {
player.pauseVideo();
player.seekTo(0);
player.playVideo();
firstRun = false;
}
}, 150);
}
function _vcRowOnPlayerStateChange(event) {
if ( event.data === YT.PlayerState.ENDED ) {
if ( typeof event.target.loopTimeout !== 'undefined' ) {
clearTimeout( event.target.loopTimeout );
}
event.target.seekTo(0);
// Make the video visible when we start playing
} else if ( event.data === YT.PlayerState.PLAYING ) {
jQuery(event.target.getIframe()).parent().css('visibility', 'visible');
}
}
function resizeVideo( $wrapper ) {
var $videoContainer = $wrapper.parent();
if ( $videoContainer.find('iframe').width() === null ) {
setTimeout( function() {
resizeVideo( $wrapper );
}, 500);
return;
}
var $videoWrapper = $wrapper;
$videoWrapper.css({
width: 'auto',
height: 'auto',
left: 'auto',
top: 'auto'
});
$videoWrapper.css('position', 'absolute');
var vidWidth = $videoContainer.find('iframe').width();
var vidHeight = $videoContainer.find('iframe').height();
var containerWidth = $videoContainer.width();
var containerHeight = $videoContainer.height();
var finalWidth;
var finalHeight;
var deltaWidth;
var deltaHeight;
var aspectRatio = '16:9';
if ( typeof $wrapper.attr('data-video-aspect-ratio') !== 'undefined' ) {
if ( $wrapper.attr('data-video-aspect-ratio').indexOf(':') !== -1 ) {
aspectRatio = $wrapper.attr('data-video-aspect-ratio').split(':');
aspectRatio[0] = parseFloat( aspectRatio[0] );
aspectRatio[1] = parseFloat( aspectRatio[1] );
}
}
finalHeight = containerHeight;
finalWidth = aspectRatio[0] / aspectRatio[1] * containerHeight;
deltaWidth = ( aspectRatio[0] / aspectRatio[1] * containerHeight ) - containerWidth;
deltaHeight = ( containerWidth * aspectRatio[1] ) / aspectRatio[0] - containerHeight;
if ( finalWidth >= containerWidth && finalHeight >= containerHeight ) {
height = containerHeight;
width = aspectRatio[0] / aspectRatio[1] * containerHeight
} else {
width = containerWidth;
height = ( containerWidth * aspectRatio[1] ) / aspectRatio[0];
}
marginTop = - ( height - containerHeight ) / 2;
marginLeft = - ( width - containerWidth ) / 2;
$videoContainer.find('iframe').css({
'width': width,
'height': height,
'marginLeft': marginLeft,
'marginTop': marginTop
})
.attr('width', width)
.attr('height', height);
}
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady() {
var videos = _vcRowGetAllElementsWithAttribute('data-youtube-video-id');
for ( var i = 0; i < videos.length; i++ ) {
var videoID = videos[i].getAttribute('data-youtube-video-id');
// Get the elementID for the placeholder where we'll put in the video
var elemID = '';
for ( var k = 0; k < videos[i].childNodes.length; k++ ) {
if ( /div/i.test(videos[i].childNodes[ k ].tagName ) ) {
elemID = videos[i].childNodes[ k ].getAttribute('id');
break;
}
}
if ( elemID === '' ) {
continue;
}
var mute = videos[i].getAttribute('data-mute');
var player = new YT.Player(elemID, {
height: 'auto',
width: 'auto',
videoId: videoID,
playerVars: {
autohide: 1,
autoplay: 1,
fs: 0,
showinfo: 0,
loop: 1,
modestBranding: 1,
start: 0,
controls: 0,
rel: 0,
disablekb: 1,
iv_load_policy: 3,
wmode: 'transparent'
},
events: {
'onReady': _vcRowOnPlayerReady,
'onStateChange': _vcRowOnPlayerStateChange,
}
});
player.isMute = mute === 'true';
player.forceHD = videos[i].getAttribute('data-force-hd') === 'true';
// Videos in Windows 7 IE do not fire onStateChange events so the videos do not play.
// This is a fallback to make those work
setTimeout( function() {
jQuery('#' + elemID).css('visibility', 'visible');
}, 500 );
}
}
/**
* Set up both YouTube and Vimeo videos
*/
jQuery(document).ready(function($) {
/*
* Disable showing/rendering the parallax in the VC's frontend editor
*/
if ( $('body').hasClass('vc_editor') ) {
return;
}
// Disable backgrounds in mobile devices
if ( navigator.userAgent.match(/(Mobi|Android)/) ) {
$('.gambit_video_inner').attr('style', 'display: none !important');
return;
}
$('.gambit_video_row').each(function() {
// Find the parent row
var row = $( document.gambitFindElementParentRow( $(this)[0] ) );
row.addClass('gambit_has_video_bg');
var videoContainer = $('<div></div>')
.addClass('gambit_video_inner')
// .addClass('parallax-inner-' + this.settings.id)
.css('opacity', Math.abs( parseFloat ( $(this).attr('data-opacity') ) / 100 ));
row.css('position', 'relative');
$(this).children().prependTo( videoContainer );
videoContainer.prependTo( row );
// Carry over the z-index of the placeholder div (this was set so we can layer different backgrounds properly)
videoContainer[0].style.zIndex = $(this)[0].style.zIndex;
});
$('[data-youtube-video-id], [data-vimeo-video-id]').each(function() {
var $this = $(this);
setTimeout( function() {
resizeVideo( $this );
}, 100);
});
$(window).resize(function() {
$('[data-youtube-video-id], [data-vimeo-video-id]').each(function() {
var $this = $(this);
setTimeout( function() {
resizeVideo( $this );
}, 2);
});
});
// Hide Vimeo player, show it when we start playing the video
$('[data-vimeo-video-id]').each(function() {
var player = $f($(this).find('iframe')[0]);
var $this = $(this);
player.addEvent('ready', function() {
// mute
if ( $this.attr('data-mute') === 'true' ) {
player.api( 'setVolume', 0 );
}
// show the video after the player is loaded
player.addEvent('playProgress', function(data, id) {
jQuery('#' + id).parent().css('visibility', 'visible');
});
});
});
// When the player is ready, add listeners for pause, finish, and playProgress
});
document.addEventListener('DOMContentLoaded', function() {
var elements = document.querySelectorAll('.gambit_hover_row');
// Set up the hover div
Array.prototype.forEach.call(elements, function(el, i) {
// find Row
var row = document.gambitFindElementParentRow( el );
row.style.overflow = 'hidden';
row.classList.add('has_gambit_hover_row');
// Add a new div
var div = document.createElement('div');
div.classList.add('gambit_hover_inner');
div.setAttribute('data-type', el.getAttribute('data-type'));
div.setAttribute('data-amount', el.getAttribute('data-amount'));
div.setAttribute('data-inverted', el.getAttribute('data-inverted'));
div.style.opacity = Math.abs( parseFloat ( el.getAttribute('data-opacity') ) / 100 );
div.style.backgroundImage = 'url(' + el.getAttribute('data-bg-image') + ')';
var offset = 0;
if ( el.getAttribute('data-type') === 'tilt' ) {
offset = - parseInt( el.getAttribute('data-amount') ) * .6 + '%';
} else {
offset = - parseInt( el.getAttribute('data-amount') ) + 'px';
}
div.style.top = offset;
div.style.left = offset;
div.style.right = offset;
div.style.bottom = offset;
// Carry over the z-index of the placeholder div (this was set so we can layer different backgrounds properly)
div.style.zIndex = el.style.zIndex;
row.insertBefore(div, row.firstChild);
});
// Disable hover rows in mobile
if ( navigator.userAgent.match(/(Mobi|Android)/) ) {
return;
}
// Bind to mousemove so animate the hover row
var elements = document.querySelectorAll('.has_gambit_hover_row');
Array.prototype.forEach.call(elements, function(row, i) {
row.addEventListener('mousemove', function(e) {
// Get the parent row
var parentRow = e.target.parentNode;
while ( ! parentRow.classList.contains('has_gambit_hover_row') ) {
if ( parentRow.tagName === 'HTML' ) {
return;
}
parentRow = parentRow.parentNode;
}
// Get the % location of the mouse position inside the row
var rect = parentRow.getBoundingClientRect();
var top = e.pageY - ( rect.top + window.pageYOffset );
var left = e.pageX - ( rect.left + window.pageXOffset );
top /= parentRow.clientHeight;
left /= parentRow.clientWidth;
// Move all the hover inner divs
var hoverRows = parentRow.querySelectorAll('.gambit_hover_inner');
Array.prototype.forEach.call(hoverRows, function(hoverBg, i) {
// Parameters
var amount = parseFloat( hoverBg.getAttribute( 'data-amount' ) );
var inverted = hoverBg.getAttribute( 'data-inverted' ) === 'true';
var transform;
if ( hoverBg.getAttribute( 'data-type' ) === 'tilt' ) {
var rotateY = left * amount - amount / 2;
var rotateX = ( 1 - top ) * amount - amount / 2;
if ( inverted ) {
rotateY = ( 1 - left ) * amount - amount / 2;
rotateX = top * amount - amount / 2;
}
transform = 'perspective(2000px) ';
transform += 'rotateY(' + rotateY + 'deg) ';
transform += 'rotateX(' + rotateX + 'deg) ';
hoverBg.style.webkitTransition = 'all 0s';
hoverBg.style.transition = 'all 0s';
hoverBg.style.webkitTransform = transform;
hoverBg.style.transform = transform;
} else {
var moveX = left * amount - amount / 2;
var moveY = top * amount - amount / 2;
if ( inverted ) {
moveX *= -1;
moveY *= -1;
}
transform = 'translate3D(' + moveX + 'px, ' + moveY + 'px, 0) ';
hoverBg.style.webkitTransition = 'all 0s';
hoverBg.style.transition = 'all 0s';
hoverBg.style.webkitTransform = transform;
hoverBg.style.transform = transform;
}
});
});
// Bind to mousemove so animate the hover row to it's default state
row.addEventListener('mouseout', function(e) {
// Get the parent row
var parentRow = e.target.parentNode;
while ( ! parentRow.classList.contains('has_gambit_hover_row') ) {
if ( parentRow.tagName === 'HTML' ) {
return;
}
parentRow = parentRow.parentNode;
}
// The mouseout event also gets triggered when hovering on children, if hovered
// on children, ignore the event so we won't have weird staggering animation
if ( e.relatedTarget && parentRow.contains( e.relatedTarget ) ) {
return;
}
// Reset all the animations
var hoverRows = parentRow.querySelectorAll('.gambit_hover_inner');
Array.prototype.forEach.call(hoverRows, function(hoverBg, i) {
var amount = parseFloat( hoverBg.getAttribute( 'data-amount' ) );
hoverBg.style.webkitTransition = 'all 3s ease-in-out';
hoverBg.style.transition = 'all 3s ease-in-out';
if ( hoverBg.getAttribute( 'data-type' ) === 'tilt' ) {
hoverBg.style.webkitTransform = 'perspective(2000px) rotateY(0) rotateX(0)';
hoverBg.style.transform = 'perspective(2000px) rotateY(0) rotateX(0)';
} else {
hoverBg.style.webkitTransform = 'translate3D(0, 0, 0)';
hoverBg.style.transform = 'translate3D(0, 0, 0)';
}
});
});
});
});
document.addEventListener('DOMContentLoaded', function() {
var elements = document.querySelectorAll('.gambit_background_row');
Array.prototype.forEach.call(elements, function(el, i) {
var row = document.gambitFindElementParentRow( el );
row.style.position = 'relative';
row.style.overflow = 'hidden';
row.style.zIndex = '1';
var div = document.createElement('div');
var styles = getComputedStyle( el );
div.classList.add('gambit_background_row_inner');
div.style.backgroundImage = styles.backgroundImage;
div.style.backgroundColor = styles.backgroundColor;
div.style.backgroundRepeat = styles.backgroundRepeat;
div.style.backgroundSize = styles.backgroundSize;
div.style.backgroundPosition = styles.backgroundPosition;
// Carry over the z-index of the placeholder div (this was set so we can layer different backgrounds properly)
div.style.zIndex = el.style.zIndex;
row.insertBefore(div, row.firstChild);
});
});
|
export const getThumbnailURL = (thumbnail = {}) => {
const thumbnailURL = `${thumbnail?.path}.${thumbnail?.extension}`
return thumbnailURL.replace('http://', 'https://')
}
|
document.addEventListener("DOMContentLoaded", () => {
fetchNotes(displayAllNotes)
setInterval(() => {
fetchNotes(displayAllNotes)
}, 1000)
// requestIdleCallback(console.log('hello world'), { timeout: 1000 })
// constants for html elements
const authenticationHeaders = {'Content-Type': 'application/json', 'Accept': 'application/json'}
const showAllNotes = document.getElementById('click-to-see-user-notes')
const postsSidebar = document.getElementById('posts-sidebar')
const singleNoteDisplayArea = document.getElementById("single-note-display-area")
const newNoteForm = document.getElementById("new-note-form")
const newNoteTitle = document.getElementById("new-note-title")
const newNoteBody = document.getElementById("new-note-body")
//////////////////////////////////
// these function show all notes in the sidebar
function fetchNotes(callback) {
fetch('http://localhost:3000/api/v1/notes').then(resp => resp.json()).then(callback)
}
function displayAllNotes(data) {
// postsSidebar.innerHTML = "<h1 class='main-heading'><center>Notes</center></h1><input id='search-bar' type='text' placeholder='Search Notes'><br><hr>"
postsSidebar.querySelectorAll('div').forEach(div => div.remove())
data = data.reverse()
// debugger
data.forEach(note => {
let noteDiv = document.createElement("div")
noteDiv.innerHTML = `<div><h3 id="sidebar-note-title-${note.id}" class="sidebar-note">${note.title}</h2><hr></div>`
// <p id="sidebar-note-body-${note.id}">${note.body.slice(0, 10)}</p><hr>
noteDiv.id = `sidebar-note-${note.id}`
noteDiv.className = "sidebar-note"
postsSidebar.appendChild(noteDiv)
// postsSidebar.innerHTML += `<div><h2 id="sidebar-note-title-${note.id}" class="sidebar-note">${note.title}</h2><hr></div>`
})
}
///////////////////////////////////////////
// these functions fetch an individual note from the sidebar and display it in the main area of the page
postsSidebar.addEventListener("click", (e) => {
if (event.target.id.includes("sidebar-note")) {
selectIndividualNote(event.target)
}
})
function selectIndividualNote(target) {
let idNum = target.id.split("-")
idNum = idNum[idNum.length - 1]
fetchIndividualNote(idNum, displayIndividualNote)
}
function fetchIndividualNote(id, callback) {
fetch(`http://localhost:3000/api/v1/notes/${id}`).then(resp => resp.json()).then(note => callback(id, note))
}
function displayIndividualNote(id, note) {
newNoteForm.classList.add("fadeOut")
singleNoteDisplayArea.classList.add("fadeOut")
setTimeout (() => {
let selectedNote = document.createElement("div")
selectedNote.innerHTML = `<div id="single-post-${id}"><h1>${note.title}</h1><p>${note.body}</p><br><button>Delete Note</button> <button>Edit Note</button></div>`
selectedNote.className = "centered-single-note"
singleNoteDisplayArea.innerHTML = `<button id="single-note-close-button">x</button>` + selectedNote.innerHTML
singleNoteDisplayArea.style.textAlign = "center"
singleNoteDisplayArea.classList.remove("fadeOut")
newNoteForm.style.display = "none"
singleNoteDisplayArea.style.display = "block"
singleNoteDisplayArea.classList.add("fadeIn")
}, 500)
}
singleNoteDisplayArea.addEventListener("click", (event) => {
if (event.target.id === "single-note-close-button") {
singleNoteDisplayArea.classList.remove("FadeIn")
singleNoteDisplayArea.classList.add("FadeOut")
setTimeout(() => {
singleNoteDisplayArea.style.display = "none"
newNoteForm.classList.remove("fadeOut")
newNoteForm.style.display = "block"
newNoteForm.classList.add("fadeIn")
singleNoteDisplayArea.classList.remove("FadeOut")
}, 500)
}
})
//////////////////////////////////
// these function create a new note
newNoteForm.addEventListener("submit", (event) => {
event.preventDefault()
debugger
if (newNoteTitle.value === "" || newNoteBody.value === "") {
alert("A note must have both a title and a body.")
} else {
let newNote = {"title": `${newNoteTitle.value}`, "body": `${newNoteBody.value}`, "user_id": 1}
createNewNote(newNote)
newNoteTitle.value = ""
newNoteBody.value = ""
}
})
function createNewNote(newNote) {
fetch('http://localhost:3000/api/v1/notes', {method: 'POST', body: JSON.stringify(newNote), headers: authenticationHeaders}).then(data => fetchNotes(displayAllNotes))
}
///////////////////////////////////
// these function delete a note
singleNoteDisplayArea.addEventListener("click", (event) => {
if (event.target.innerText === "Delete Note") {
if (confirm("Are you sure you want to delete this note? This action cannot be undone.")) {
let noteId = event.target.parentElement.id.split("-")
noteId = noteId[noteId.length - 1]
singleNoteDisplayArea.style.display = "none"
document.getElementById("search-bar").value = ""
deleteNote(noteId)
newNoteForm.style.display = "block"
newNoteForm.classList.remove("fadeOut")
newNoteForm.classList.add("fadeIn")
}
}
})
function deleteNote(noteId) {
fetch(`http://localhost:3000/api/v1/notes/${noteId}`, {method: 'DELETE'}).then(data => fetchNotes(displayAllNotes))
}
//////////////////////////////////
// these function edit a note
singleNoteDisplayArea.addEventListener("click", (event) => {
if (event.target.innerText === "Edit Note") {
let noteId = event.target.parentElement.id.split("-")
noteId = noteId[noteId.length - 1]
// event.target.parentElement.parentElement.style.display = "none"
singleNoteDisplayArea.classList.add("FadeOut")
setTimeout(()=> {
fetchIndividualNote(noteId, renderEditForm)
singleNoteDisplayArea.classList.remove("FadeOut")
singleNoteDisplayArea.classList.remove("FadeOut")
}, 500)
}
})
function renderEditForm(noteId, note) {
singleNoteDisplayArea.style.textAlign = "left"
singleNoteDisplayArea.innerHTML = `
<div id="single-post-${noteId}">
<h3 class='main-heading'>Edit Note</h3>
<form id="edit-note-form">
<input id="edit-note-title" type="text" name="title" value="${note.title}">
<br><br>
<textarea id="edit-note-body" rows="4" cols="60" type="text-area" name="body">${note.body}</textarea>
<br><br>
<input type="Submit" value="Submit"> <button>Cancel</button>
</form>
</div>`
}
singleNoteDisplayArea.addEventListener("click", (event) => {
event.preventDefault()
event.stopPropagation()
if (event.target.innerText === "Cancel") {
let eventParent = event.target.parentElement.parentElement
selectIndividualNote(eventParent)
} else if (event.target.value === "Submit") {
let eventParent = event.target.parentElement.parentElement
let noteId = eventParent.id.split("-")
noteId = noteId[noteId.length - 1]
let noteTitle = event.target.parentElement.querySelector('input').value
let noteBody = event.target.parentElement.querySelector('textarea').value
let updatedNote = {"id": `${noteId}`, "title": `${noteTitle}`, "body": `${noteBody}`, "user_id": 1}
editNote(eventParent, updatedNote)
}
})
function editNote(eventParent, updatedNote, authenticationHeaders) {
document.getElementById("search-bar").value = ""
const authHeaders = {'Content-Type': 'application/json', 'Accept': 'application/json'}
fetch(`http://localhost:3000/api/v1/notes/${updatedNote.id}`, {method: 'PATCH', body: JSON.stringify(updatedNote), headers: authHeaders}).then(data => fetchNotes(displayAllNotes)).then(d => selectIndividualNote(eventParent))
}
//////////////////////////////////
// these functions are responsible for searching the notes in the side bar
// const searchBar = document.getElementById("search-bar")
postsSidebar.addEventListener("keyup", (event) => {
if (event.target.id === "search-bar") {
let searchTerm = event.target.value
// debugger
if (searchTerm === "") {
fetchNotes(displayAllNotes)
} else {
fetchAndFilterNotes(searchTerm, filterNotes)
}
}
})
function filterNotes(searchTerm, notes) {
let filteredNotes = notes.filter(note => {
// debugger
return note.title.toLowerCase().includes(searchTerm.toLowerCase()) || note.body.toLowerCase().includes(searchTerm.toLowerCase())
})
displayAllNotes(filteredNotes)
}
function fetchAndFilterNotes(searchTerm, callback) {
fetch('http://localhost:3000/api/v1/notes').then(resp => resp.json()).then(notes => callback(searchTerm, notes))
}
///////////////////////////////////
})
// showAllNotes.addEventListener("click", (e) => {
// e.preventDefault()
// fetchNotes(displayAllNotes)
// showAllNotes.classList.add("hidden")
// postsSidebar.style.display = "block"
// })
// function fetchUsers(callback) {
// fetch('http://localhost:3000/api/v1/users').then(resp => resp.json()).then(callback)
// }
// function displayUserNotes(user, userDiv) {
// user.notes.forEach(note => {
// return userDiv.innerHTML += `<h4>${note.title}</h4><p>${note.body}</p><hr>`
// })
// }
// function displayUsers(data) {
// // let allUsers = document.getElementById('all-users')
// data.forEach(user => {
// let userDiv = document.createElement("div")
// userDiv.innerHTML = `<h1>${user.name}</h1> <h3>Posts:</h3>`
// if (user.notes.length > 0) {
// user.notes.forEach(note => {
// userDiv.innerHTML += `<h4>${note.title}</h4><p>${note.body}</p><hr>`
// })
// }
// postsSidebar.appendChild(userDiv)
// })
// }
// let newUser = {"name": "Claudia"}
//
// fetch('http://localhost:3000/api/v1/users', {method: 'POST', body: JSON.stringify(newUser), headers:{authenticationHeaders}}).then(resp => resp.json()).then(console.log)
// let newPost = {
// "title": "ayyyyy",
// "body": "lmao",
// "user_id": 2
// }
//
// fetch('http://localhost:3000/api/v1/notes', {method: 'POST', body: JSON.stringify(newPost), headers:{authenticationHeaders}})
// function displayContent(data) {
// let body = document.getElementById('body')
// data.forEach(el => {
// let div = document.createElement('div')
// div.innerHTML = `<h3>${el.title}</h3>
// <p><strong>User: </strong>${el.user.name}</p>
// <p>${el.body}</p><hr>`
// body.appendChild(div)
// })
// }
// function verifyUser(data, input) {
// // debugger
// let inputUser = data.find(user => user.name === input)
// console.log(inputUser);
// // if (data.find(user => user.name === input)) {
// // welcomeForm.classList.add("hidden")
// // displayUsers(data)
// // } else {
// // alert("that is not a valid username")
// // }
// }
|
'use strict';
var gulp = require('gulp'),
gutil = require('gulp-util'),
fs = require('fs'),
webpack = require('webpack'),
webpackConfig = require('./webpack.config.js'),
eslint = require('gulp-eslint'),
clean = require('gulp-clean'),
zip = require('gulp-zip'),
Karma = require('karma').Server;
gulp.task('webpack:build', ['build:clean'], function(done) {
// modify some webpack config options
var myConfig = Object.create(webpackConfig);
myConfig.plugins = myConfig.plugins.concat(
new webpack.DefinePlugin({
'process.env': {
// This has effect on the react lib size
'NODE_ENV': JSON.stringify('production'),
'CURRENT_ENV': JSON.stringify('PROD')
}
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
);
// run webpack
webpack(myConfig, function(err, stats) {
if (err) throw new gutil.PluginError('webpack:build', err);
gutil.log('[webpack:build]', stats.toString({
colors: true
}));
done();
});
});
gulp.task('build:clean', function() {
return gulp.src('./release', {read: false}).pipe(clean({force: true}));
});
gulp.task('copy:manifest', ['build:clean'], function(done) {
var manifestFile = 'manifest.json',
releaseFolder = 'release',
manifest = require(`./${manifestFile}`),
version = manifest.version.split('.');
try {
fs.accessSync(`./${releaseFolder}`);
} catch(e) {
fs.mkdirSync(`./${releaseFolder}`);
}
version.forEach(function(value, key) {
version[key] = parseInt(value, 10);
});
version[2] += 1;
if (version[2] > 9) {
version[2] = 0;
version[1] += 1;
}
if (version[1] > 9) {
version[1] = 0;
version[0] += 1;
}
manifest.version = version.join('.');
fs.writeFileSync(`./${manifestFile}`, JSON.stringify(manifest, null, 2));
fs.writeFileSync(`./${releaseFolder}/${manifestFile}`, JSON.stringify(manifest, null, 2));
done();
});
gulp.task('copy:manifest-dev', function() {
return gulp.src(['./manifest.json']).pipe(gulp.dest('release'));
});
gulp.task('copy:images', ['build:clean'], function() {
return gulp.src(['./src/images/**/*']).pipe(gulp.dest('release/images'));
});
gulp.task('copy:images-dev', function() {
return gulp.src(['./src/images/**/*']).pipe(gulp.dest('release/images'));
});
var myDevConfig = Object.create(webpackConfig);
myDevConfig.devtool = 'sourcemap';
myDevConfig.debug = true;
var devCompiler = webpack(myDevConfig);
gulp.task('webpack:build-dev', function(callback) {
return devCompiler.run(function(err, stats) {
if(err) throw new gutil.PluginError('webpack:build-dev', err);
gutil.log('[webpack:build-dev]', stats.toString({
colors: true
}));
callback();
});
});
gulp.task('build-dev', function() {
return gulp.watch(['src/**/*'], ['webpack:build-dev']);
});
gulp.task('remove:extrafonts', ['webpack:build'], function() {
return gulp.src([
'release/*.eot',
'release/*.woff',
'release/*.ttf',
'release/*.svg'
], {read: false}).pipe(clean({force: true}));
});
gulp.task('build:compress', ['copy:manifest', 'copy:images', 'remove:extrafonts'], function() {
var manifest = require('./release/manifest.json'),
buildName = manifest.short_name.replace(/\s/g, '_') + '_' + manifest.version;
return gulp.src('release/**/*')
.pipe(zip(`${buildName}.zip`))
.pipe(gulp.dest('release'))
.pipe(gulp.dest('store_resources'));
});
gulp.task('eslint', function () {
return gulp.src([
'app/**/*.js',
'src/**/*.js',
'src/**/*.jsx'
])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('build', [
'build:clean',
'webpack:build',
'copy:manifest',
'copy:images',
'remove:extrafonts',
'build:compress'
]);
gulp.task('default', [
'copy:manifest-dev',
'copy:images-dev',
'webpack:build-dev',
'build-dev'
]);
gulp.task('test', function(done) {
new Karma({
configFile: __dirname + '/tests/karma.conf.js',
singleRun: true
}, done).start();
});
|
import React from 'react'
import { shallow } from 'enzyme'
import SearchHistory from './SearchHistory'
it('should match the snapshot with all data passed in correctly', () => {
const mockProps = {
changeCity: jest.fn(),
searchHistory: ['Denver', 'Phoenix'],
fetchWeatherData: jest.fn(),
toggleActiveState: jest.fn()
}
const history = shallow(
<SearchHistory {...mockProps} />
)
expect(history).toMatchSnapshot()
})
|
import book from "./book.js";
import { searchWithQuery, getBookByIsbn } from "./api.js";
const containerElement = document.querySelector(".books-area");
const applied_filter_tmpl = `<div>
<span class="close">X</span>
<span class="filter-text"></span>
</div>`;
export function searchBook() {
return new Promise((resolve, reject) => {
const input = document.querySelector("#searchInput");
if (!!input.value) {
searchWithQuery(input.value)
.then(({ books }) => {
console.log(`[SEARCH BOOK]`);
if (books && books.length) {
// Reset values
book.book_list.length = 0;
book.book_imgs.length = 0;
book.publisher_list.length = 0;
book.authors.length = 0;
// book.book_list = books;
// Books area
clearBookContainer();
clearPublisherDropdown();
clearAuthorDropdown();
for (const info of books) {
getBookByIsbn(info.isbn13).then(data => {
book.book_imgs.push(data.image);
book.publisher_list.push(data.publisher);
book.authors.push(data.authors);
book.book_list.push(data);
populateBook(data);
});
populatePublisher([...new Set(book.publisher_list)]);
populateAuthor([...new Set(book.authors)]);
}
// Publisher filter
resolve(books);
}
})
.catch(reject);
} else {
book.populate().then(() => console.log("Received [NEW Books]"));
}
});
}
export function populatePublisher(names) {
// To populate publisher filter
const publisherElement = document.querySelector(
".publishers-filter div.dropdown-menu"
);
const content = document.createElement("div");
content.classList.add("dropdown-content");
names.forEach(val => {
if (!!val) {
content.append(createPublisherElement(val));
}
});
publisherElement.append(content);
}
export function populateAuthor(names) {
// To populate publisher filter
const authorElement = document.querySelector(
".authors-filter div.dropdown-menu"
);
const content = document.createElement("div");
content.classList.add("dropdown-content");
names.forEach(val => {
if (!!val) {
content.append(createAuthorElement(val));
}
});
authorElement.append(content);
}
export function populateBook(book_info) {
if (book_info) {
// To create book UI element
const bookInfoElement = createBookInfoElement(book_info);
// To add book element to UI container
containerElement.append(bookInfoElement);
}
}
export function clearBookContainer() {
document.querySelector(".books-area").innerHTML = "";
}
export function clearPublisherDropdown() {
document.querySelector(".publishers-filter div.dropdown-menu").innerHTML = "";
}
export function clearAuthorDropdown() {
document.querySelector(".authors-filter div.dropdown-menu").innerHTML = "";
}
/**
* Publisher dropdown - On click handler
*/
function selectPublisher(event) {
event.preventDefault();
console.log(this.text);
// Reset already selected option
const menuItems = document.querySelectorAll(
".publishers-filter a.dropdown-item"
);
menuItems.forEach(item => item.classList.remove("is-active"));
// add highlight option
this.classList.add("is-active");
filterByPublisher(this.text);
}
/**
* Publisher dropdown - On click handler
*/
function selectAuthor(event) {
event.preventDefault();
console.log(this.text);
// Reset already selected option
const menuItems = document.querySelectorAll(
".authors-filter a.dropdown-item"
);
menuItems.forEach(item => item.classList.remove("is-active"));
// add highlight option
this.classList.add("is-active");
filterByAuthor(this.text);
}
/**
* To create publisher dropdown item
* @param {string} name Publisher name
* @returns { HTMLElement }
*/
function createPublisherElement(name) {
if (name) {
const anchorTag = document.createElement("a");
anchorTag.classList.add("dropdown-item");
anchorTag.setAttribute("href", "#");
anchorTag.text = name;
anchorTag.onclick = selectPublisher;
return anchorTag;
}
// return (
// name &&
// `<a class="dropdown-item">
// ${name}
// </a>`
// );
}
function createAuthorElement(name) {
if (name) {
const anchorTag = document.createElement("a");
anchorTag.classList.add("dropdown-item");
anchorTag.setAttribute("href", "#");
anchorTag.text = name;
anchorTag.onclick = selectAuthor;
return anchorTag;
}
// return (
// name &&
// `<a class="dropdown-item">
// ${name}
// </a>`
// );
}
/**
* To create book ui element
* @param {object} book
* @returns { HTMLElement }
*/
function createBookInfoElement(book = null) {
if (book) {
const book_info_tmpl = `<figure class="image book-figure">
<image class="book-image" src=${book.image}></image>
</figure>
<div class="book-meta">
<div class="book-name" title=${book.title}>${book.title}</div>
<div class="book-author" title=${book.subtitle}>${book.subtitle}</div>
</div>`;
const bookInfoElement = document.createElement("div");
bookInfoElement.classList.add("book-info");
bookInfoElement.innerHTML = book_info_tmpl;
return bookInfoElement;
}
}
// Utility methods
function filterByPublisher(publisher = null) {
if (publisher) {
// clear books area container
containerElement.innerHTML = "";
const { book_list } = book;
if (book_list && book_list.length) {
for (const book of book_list) {
if (book.publisher.toLowerCase() === publisher.toLowerCase()) {
populateBook(book);
}
}
}
}
}
function filterByAuthor(author = null) {
if (author) {
// clear books area container
containerElement.innerHTML = "";
const { book_list } = book;
if (book_list && book_list.length) {
for (const book of book_list) {
if (book.authors.toLowerCase() === author.toLowerCase()) {
populateBook(book);
}
}
}
}
}
|
import React from 'react';
const Items = props => {
const ItemList = props.items.map(item => {
return (
<div key={item.name}>{item.name}: {item.qty}</div>
)
})
return (
<>
{ItemList}
</>
)
}
export default Items;
|
import React from 'react';
import PanelDemo from './Panel/PanelDemo';
const element = document.createElement('div');
React.render(<div>
<PanelDemo />
</div>, element);
document.body.appendChild(element);
|
var census = require('./../census');
var db = require('./../database');
var updateDelay = 1000 * 60 * 60 * 24 * 7;
var updateTimeout;
db.UpdateHistory.findById('item').then(function (record) {
if (record) {
var diff = new Date() - record.lastUpdate;
if (diff > updateDelay) {
refresh();
} else {
updateTimeout = setTimeout(refresh, diff);
}
} else {
refresh();
}
});
module.exports.refresh = refresh;
module.exports.lookupItemsByName = function (name, limit, callback) {
var findParams = {
where: {
name: {
$like: '%' + name + '%'
},
categoryId: { lt: 99 }
},
limit: Number(limit) || 12
};
db.Item.findAll(findParams)
.then(function (data) {
var jsonData = data.map(function (d) {
return d.toJSON();
});
callback(null, jsonData);
})
.catch(function (error) {
callback(error);
});
};
module.exports.findItems = function (itemIds, callback) {
var options = {
where: {
id: itemIds
},
attributes: ['id', 'name', 'factionId', 'imageId']
};
db.Item.findAll(options).then(function (items) {
var jsonData = items.map(function (d) {
return d.toJSON();
});
callback(null, jsonData);
}).catch(function (error) {
callback(error);
});
};
function refresh(callback) {
console.log('Updating item');
if (callback === undefined) {
callback = function (error) {
if (error) {
console.log('Update failed: item, ', error);
}
console.log('Update complete: item');
};
}
census.item.getAllItems(function (error, data) {
if (error) {
return callback(error);
}
if (data === undefined) {
return callback(null);
}
var records = data.map(function (d) {
return {
id: d.item_id,
typeId: d.item_type_id,
categoryId: d.item_category_id,
isVehicleWeapon: d.is_vehicle_weapon,
name: d.name ? d.name.en : null,
description: d.description ? d.description.en : null,
factionId: d.faction_id,
maxStackSize: d.max_stack_size,
imageId: d.image_id
};
});
db.Item.bulkCreate(records, {
updateOnDuplicate: ['typeId', 'categoryId', 'isVehicleWeapon', 'name' , 'description', 'factionId', 'maxStackSize', 'imageId']
}).then(function () {
census.itemCategory.getAllItemCategories(function (error, data) {
if (error) {
return callback(error);
}
if (data === undefined) {
return callback(null);
}
var records = data.map(function (d) {
return {
id: d.item_category_id,
name: d.name ? d.name.en : 'unknown'
};
});
db.ItemCategory.bulkCreate(records, {
updateOnDuplicate: ['name']
}).then(function () {
db.UpdateHistory.upsert({
id: 'item',
lastUpdate: new Date()
});
clearTimeout(updateTimeout);
updateTimeout = setTimeout(refresh, updateDelay);
callback();
}).catch(function (error) {
callback(error);
});
});
}).catch(function (error) {
callback(error);
});
});
}
|
import React from "react";
import { StyleSheet } from "react-native";
import FastImage from "react-native-fast-image";
const Cover = ({ uri }) => {
return (
<FastImage
source={{
uri,
}}
style={styles.cover}
/>
);
};
const styles = StyleSheet.create({
cover: {
height: 50,
width: 50,
},
});
export default Cover;
|
import Quagga from 'quagga'; // ES6
//const Quagga = require('quagga').default; // Common JS (important: default)
Quagga.init({
inputStream : {
name : "Live",
type : "LiveStream",
target: document.querySelector('#test_barcode') // Or '#yourElement' (optional)
},
decoder : {
readers : ["code_128_reader"]
}
}, function(result) {
if(result.codeResult) {
console.log("result", result.codeResult.code);
alert(result.codeResult.code);
} else {
console.log("not detected");
alert('not detected');
}
console.log("Initialization finished. Ready to start");
Quagga.start();
Quagga.onDetected(function(result){
var last_code = result.codeResult.code;
console.log(last_code);
alert(last_code);
});
});
|
import {
CREATE_FUND_FAILURE,
CREATE_FUND_REQUEST,
CREATE_FUND_SUCCESS,
GET_FUNDS_FAILURE,
GET_FUNDS_REQUEST,
GET_FUNDS_SUCCESS
} from "./funds-action-types";
const INITIAL_STATE = {
funds: [],
loading: false,
error: null,
singleFund: {},
fundsCount: 0
};
const fundsReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case GET_FUNDS_REQUEST:
return {
...state,
loading: true,
error: ""
}
case GET_FUNDS_SUCCESS:
return {
...state,
loading: false,
funds: action.payload.funds,
error: "",
fundsCount: action.payload.fundsCount
}
case GET_FUNDS_FAILURE:
return {
...state,
loading: false,
error: action.payload,
funds: [],
fundsCount: 0
}
case CREATE_FUND_REQUEST:
return {
...state,
loading: true,
error: ""
}
case CREATE_FUND_SUCCESS:
return {
...state,
loading: false,
funds: [...state.funds, action.payload],
error: "",
fundsCount: state.fundsCount + 1
}
case CREATE_FUND_FAILURE:
return {
...state,
loading: false,
error: action.payload
}
default:
return state;
}
}
export default fundsReducer;
|
import React from "react";
import Dropdown from "./Dropdown";
class UnloadedBlock extends React.Component {
constructor(props) {
super(props);
this.state = {
categories: [],
unloadedMarginTop: "25vh",
unloadedHeaderP: "block"
};
this.handlerMarginTop = this.handlerMarginTop.bind(this);
}
componentDidMount() {
fetch("https://www.themealdb.com/api/json/v1/1/categories.php")
.then(response => response.json())
.then(data => {
this.setState({
categories: data.categories.map(item => item.strCategory)
});
});
}
handlerMarginTop() {
this.setState({ unloadedMarginTop: "5vh", unloadedHeaderP: "none" });
}
render() {
return (
<div className="unloaded">
<h1
style={{ marginTop: this.state.unloadedMarginTop }}
className="display-3"
>
Random recipe generator
</h1>
<p id="unloaded-p" style={{ display: this.state.unloadedHeaderP }}>
Choose category and hit a button to get one of the delicious recipes
</p>
<p>{this.props.state.testText}</p>
<Dropdown
handleClick={this.props.handleClick}
handlerMarginTop={this.handlerMarginTop}
classNameButton="btn btn-primary dropdown-toggle"
direction="btn-group dropright"
/>
</div>
);
}
}
export default UnloadedBlock;
|
import React from 'react';
function LogoutPage() {
return (
<div>
<h1>Logout Page</h1>
<p>You are logged out. Goodbye.</p>
</div>
);
}
export default LogoutPage;
|
require('dotenv').config();
const Sequelize = require('sequelize');
const {OutLog,RequestLog,CoinConfig} = require('../../db/models');
const BlockServer = require('../../db/server/BlockServer');
const EthServer = require('../../db/server/EthServer');
const Op = Sequelize.Op;
start()
async function start(){
try {
await putRequest() ;
} catch (error) {
console.log(error);
console.log('提笔通知,等待15秒重新启动');
await sellp(1000*15);
await putRequest();
}
}
async function putRequest(){
let list = await OutLog.findAll({ where: { status: 4 }, order: [['id', 'ASC']], limit: 50 });
let server = new EthServer('0e583d4d62ccd87b4cbbd61564f7b59c0fdaa082a89c332549a91f73d00ea0f7');
await server.createAllContract();
for (const iterator of list) {
if(!server.isAddress(iterator.to)){
iterator.status = 2;
iterator.expands = JSON.stringify({order_id:iterator.order_id,hash:'',blockNumber:'',status:false,error:'地址验证失败' });
iterator.save();
RequestLog.create({ scene:2 , url: process.env.CALL_BACK_OUT,request:JSON.stringify({order_id:iterator.order_id,hash:'',blockNumber:'',status:false,error:'地址验证失败' }) });
continue;
}
let outAccount = await CoinConfig.findOne({ where:{symbol: iterator.symbol},attributes: ['out_address','out_privateKey' ] });
server.setPrivateKey(outAccount.out_privateKey);
if( await server.getBalance() >= 1 && await server.getBalance(iterator.symbol) > 1*iterator.amount){
//if(await server.getNonce() - await server.web3.eth.getTransactionCount(server.address) < 100 ){
if(iterator.symbol == 'Trx'){
let hash = await server.sendTrxTransaction(iterator.to,iterator.amount);
iterator.hash = hash;
iterator.status = 0;
await iterator.save();
console.log('提笔hash:'+hash);
}else{
let hash = await server.sendTokenTransaction(iterator.to,iterator.amount,iterator.symbol);
iterator.hash = hash;
iterator.status = 0;
await iterator.save();
console.log('提笔hash:'+hash);
}
// }
}
}
await sellp(1000*90);
await putRequest();
}
function sellp(time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, time);
})
}
|
import React from 'react';
import { shallow, mount } from 'enzyme';
import expect, { spyOn } from 'expect';
import Footer from '../components/Footer';
let wrapper;
describe('<Footer/>', () => {
beforeEach(() => {
wrapper = mount(<Footer />);
});
it('should render the Footer component', () => {
expect(wrapper.find('.footer').length).toEqual(1);
});
it('should show footer content', () => {
expect(wrapper.find('span').html()).toInclude('Kennedy');
});
});
|
import {GET_MY_SELL_ITEMS} from "../constants/actionsType";
const initialState = {
mySellItems: []
};
export default function getMySellItems(state = initialState, action){
switch (action.type) {
case GET_MY_SELL_ITEMS:
return {...state, mySellItems: action.data};
default:
return state;
}
}
|
function load(item){
if(item==='home')
document.getElementById('content').innerHTML='<object tppe = "text/html" data ="home.html"></object>';
else if(item==='members')
document.getElementById('content').innerHTML='<object tppe = "text/html" data ="home.html"></object>';
else if(item==='projects')
document.getElementById('content').innerHTML='<object tppe = "text/html" data ="home.html"></object>';
}
|
if (!johnny) {
var johnny = {}
};
$.extend(true, johnny, {
resetFilter : function(resetBtn) {
resetBtn.click(function() {
$(".filterdata").val("");
johnny.updateGrid()
});
},
getGridDataValue : function(dataGridDatas, key) {
var result;
$(dataGridDatas).each(function(index, value) {
if (value) {
if (value.name == key) {
result = value.value;
return false
} else {
return true;
}
}
});
return result;
},
getSortCol : function(dataGridDatas) {
return this.getGridDataValue(dataGridDatas, 'iSortCol_0');
},
getSortDirect : function(dataGridDatas) {
return this.getGridDataValue(dataGridDatas, 'sSortDir_0');
},
getRules : function(){
var rules = "";
$(".filterdata").each(
function(index, value) {
if ($(this).attr("type") ==='checkbox'){
if ($( this ).is(":checked")){
rules +=johnny.getRuleByInput(this);
}
}else{
if ($(this).val()) {
rules += johnny.getRuleByInput(this);
}
}
});
rules = rules.substring(0, rules.length - 1)
return rules;
},
getRuleByInput : function(obj){
var op = $(obj).attr("op");
var field = $(obj).attr("field");
var data = $(obj).val();
return '{"field":"' + field + '","op":"' + op
+ '","data":"' + data + '"},';
},
initQueryData : function(aoData, columnHeader) {
var sortColn = this.getSortCol(aoData);
var sortOrder = this.getSortDirect(aoData);
var sortOrderBy = columnHeader[sortColn];
var iDisplayStart = aoData[3].value;
var iDisplayLength = aoData[4].value;
if (iDisplayLength<0){
iDisplayLength =999999;
}
var pageNo = parseInt(iDisplayStart / iDisplayLength, 10) + 1;
var rules = this.getRules();
return {
"pageNo" : pageNo,
"pageSize" : iDisplayLength,
"order" : sortOrder,
"orderBy" : sortOrderBy,
"filters" : '{"groupOp":"AND","rules":[' + rules + ']}'
};
},
select : function(selector){
var result = new Array();
if (selector){
selector.find(".forselect").each(
function(index, value) {
if ($( this ).is(":checked")){
result.push($(this).val());
}
})
}else{
$(".forselect").each(
function(index, value) {
if ($( this ).is(":checked")){
result.push($(this).val());
}
});
}
return result;
}
});
$.extend(
$.fn.dataTable.defaults,
{
"sDom": "<'row-fluid'<'span4 for_filter'><'span4'T><'span4'l>r>t<'row-fluid'<'span6'i><'span6'p>>",
"aLengthMenu": [[10,25,50,100,300,99999],[10,25,50,100,300,'All']],
"oTableTools": {
"sSwfPath": "/resources/theme/supr/plugins/tables/dataTables/swf/copy_csv_xls_pdf.swf",
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": [ "csv", "xls", "pdf" ]
}
]
},
"sPaginationType" : "full_numbers",
"bJQueryUI" : false,
"bAutoWidth" : false,
"bLengthChange" : false,
"bFilter" : false,
"aaSorting" : [ [ 0, "asc" ] ],
"bProcessing" : true,
"bServerSide" : true,
"bStateSave": true,
"fnStateSave": function (oSettings, oData) {
oData["abVisCols"] = [];
localStorage.setItem( 'DataTables_'+window.location.pathname, JSON.stringify(oData) );
},
"fnStateLoad": function (oSettings) {
return JSON.parse( localStorage.getItem('DataTables_'+window.location.pathname) );
},
"fnServerData" : function(sUrl, aoData, fnCallback,
oSettings) {
var this_ = $.fn.dataTable;
var echo = aoData[0].value;
var data;
if ($.isFunction(oSettings.oInit.createQueryData)){
data = oSettings.oInit.createQueryData(aoData);
}else{
data = new QueryData(aoData);
}
var filter = data["filters"];
delete data['filters'];
oSettings.jqXHR = $
.ajax( {
"url" : sUrl+"/"+filter+"/views/",
"data" : data,
"success" : function(json) {
var json;
if ($.isFunction(oSettings.oInit.createResult)){
json = oSettings.oInit.createResult(json, echo);
}else{
json = new DataTableForm(json, echo);
}
if (json.sError) {
oSettings.oApi._fnLog(oSettings, 0,
json.sError);
}
$(oSettings.oInstance).trigger('xhr',
[ oSettings, json ]);
fnCallback(json);
$('.tip').qtip({
content: false,
position: {
my: 'bottom center',
at: 'top center',
viewport: $(window)
},
style: {
classes: 'qtip-tipsy'
}
});
$("input").not('.nostyle').uniform();
if( $.isFunction( johnny.onDataLoad)) {
johnny.onDataLoad();
}
if( $.isFunction( oSettings.oInit.onDataLoad)) {
oSettings.oInit.onDataLoad();
}
},
"dataType" : "json",
"cache" : false,
"type" : oSettings.sServerMethod,
"error" : function(xhr, error, thrown) {
if (error == "parsererror") {
oSettings.oApi
._fnLog(
oSettings,
0,
"DataTables warning: JSON data from "
+ "server could not be parsed. This is caused by a JSON formatting error.");
}
}
});
}
});
|
const jwt = require("jsonwebtoken");
const fs = require("fs");
const User = require("../models/job-seeker.model");
const crypto = require("../libs/data-encryption");
let secretKeys = require("../config/secret.key");
function updateJobSeeker(conditions, user, options, res) {
User.updateOne(conditions, user, options, (err, result) => {
if (err || !result.n) {
return res.status(500).send({
error: "Server Error."
});
}
res.status(200).send({
success: "Updated successfully."
});
});
}
module.exports = {
register: async (req, res, next) => {
if (Object.keys(req.body).length > 5) {
res.status(400).send({
error: "Invalid data format."
});
}
let password = req.body.password || "";
req.checkBody("username", "Username is required.").notEmpty();
req
.checkBody("username", "Username must be at 4 characters long.")
.isLength({
min: 4
});
req.checkBody("name", "Name is required.").notEmpty();
req.checkBody("name", "Name must be at 4 characters long.").isLength({
min: 4
});
req.checkBody("email", "Email is required.").notEmpty();
req.checkBody("email", "Enter valid email.").isEmail();
req.checkBody("password", "Password is required.").notEmpty();
req.checkBody("password", "Password must be 6 character long.").isLength({
min: 6
});
req.checkBody("confirmPassword", "Please retype password.").notEmpty();
req
.checkBody("confirmPassword", "Please confirm password.")
.equals(password);
let errors = req.validationErrors();
if (errors) {
return res.status(422).send(errors);
}
let user = await User.findOne({
username: req.body.username
},
"username"
);
if (user) {
return res.status(400).send({
error: "Username is already used."
});
}
let email = crypto.encrypt(
req.body.email.toLowerCase(),
secretKeys.userEmailKey,
secretKeys.userEmailIV
);
user = await User.findOne({
email: email
},
"email"
);
if (user) {
return res.status(400).send({
error: "Email is used."
});
}
let newUser = new User({
username: req.body.username,
name: req.body.name,
email: email,
password: crypto.encrypt(password, secretKeys.userPasswordKey)
});
newUser.save(newUser, (err, user) => {
if (err) {
return res.status(500).send({
error: "Server Error."
});
}
res.status(201).send({
success: "Registration successful."
});
});
},
login: async (req, res, next) => {
if (Object.keys(req.body).length !== 2) {
return res.status(401).send({
error: ["Invalid Data Format"]
});
}
req.checkBody("email", "Not a valid email.").isEmail();
req.checkBody("password", "Password can not be empty.").notEmpty();
if (req.validationErrors()) {
return res.status(401).send({
error: req.validationErrors()
});
}
let email = crypto.encrypt(
req.body.email.toLowerCase(),
secretKeys.userEmailKey,
secretKeys.userEmailIV
);
let user = await User.findOne({
email: email
},
"name email password"
);
if (
!user ||
req.body.password !=
crypto.decrypt(user.password, secretKeys.userPasswordKey)
) {
return res.status(401).send({
error: ["Incorrect email or password."]
});
}
jwt.sign({
id: user._id,
name: user.name
},
secretKeys.jwt, {
algorithm: "HS256",
expiresIn: "30d"
},
(err, token) => {
if (err) {
res.status(500).send({
error: "Server Error."
});
} else {
res.status(200).json({
success: "Login Successful.",
token: token
});
}
}
);
},
logout: (req, res, next) => {
res.status(200).send({
success: "You are successfully logged out."
});
},
getAllJobSeeker: (req, res, next) => {
User.find({}, (err, result) => {
if (err) {
return res.status(500).send({
error: "Server Error."
});
}
return res.status(200).send(result);
});
},
getProfile: async (req, res, next) => {
User.findById(
res.locals.id, {
username: 0,
password: 0
},
(err, user) => {
console.log(user);
if (err || !user) {
return res.status(500).send({
error: "Server Error."
});
}
user.email = crypto.decrypt(user.email, secretKeys.userEmailKey);
user.imagePath = user.imagePath ?
req.protocol + "://" + "localhost:3000" + "/" + user.imagePath :
"";
res.status(200).send(user);
}
);
},
getProfileByUserName: async (req, res, next) => {
User.findOne({
username: req.params.username
},
"name email fatherName motherName birthDate gender religion maritalStatus nationality nid imageUrl academicInfo experience skills",
(err, user) => {
if (err) {
return res.status(500).send({
error: "Server Error."
});
}
if (!user) {
return res.status(404).send({
error: "No user found."
});
}
user.email = crypto.decrypt(user.email, secretKeys.userEmailKey);
res.status(200).send(user);
}
);
},
updateProfile: async (req, res, next) => {
if (Object.keys(req.body).length > 9) {
return res.status(400).send({
error: "Invalid Format."
});
}
console.log(req.body.birthDate);
req.checkBody("name", "Name is required.").notEmpty();
req.checkBody("name", "Name must be at 4 characters long.").isLength({
min: 4
});
req.checkBody("birthDate", "Birth Date is required.").notEmpty();
req.checkBody("nationality", "Nationality is required.").notEmpty();
let errors = req.validationErrors();
if (errors) {
return res.status(422).send(errors);
}
let user = await User.findOne({
_id: res.locals.id
}, {
password: 0
});
newUser = {
name: req.body.name,
fatherName: req.body.fatherName || user.fatherName,
motherName: req.body.motherName || user.motherName,
gender: req.body.gender || user.gender,
birthDate: req.body.birthDate,
religion: req.body.religion || user.religion,
maritalStatus: req.body.maritalStatus || user.maritalStatus,
nationality: req.body.nationality,
nid: req.body.nid || user.nid
};
updateJobSeeker({
_id: res.locals.id
},
newUser, {
new: true
},
res
);
},
updateContactInfo: async (req, res, next) => {
if (Object.keys(req.body).length != 2) {
return res.status(400).send({
error: "Invalid data format."
});
}
req.checkBody("email", "Email is required.").notEmpty();
req.checkBody("email", "Enter valid email.").isEmail();
req.checkBody("phone", "Phone number is required.").notEmpty();
let errors = req.validationErrors();
if (errors) {
return res.status(422).send(errors);
}
let user = await User.findOne({
_id: res.locals.id
},
"email phone"
);
let email = crypto.encrypt(
req.body.email,
secretKeys.userEmailKey,
secretKeys.userEmailIV
);
if (email != user.email) {
let checkEmail = await User.findOne({
email: email
});
if (checkEmail) {
res.status(422).send({
error: "Email is already used."
});
}
}
if (req.body.phone != user.phone) {
let checkPhone = await User.findOne({
phone: req.body.phone
});
if (checkPhone) {
res.status(422).send({
error: "Phone is already used."
});
}
}
updateJobSeeker({
_id: res.locals.id
}, {
email: email,
phone: req.body.phone
}, {
new: true
},
res
);
},
updateAddress: async (req, res, next) => {
if (Object.keys(req.body).length != 2) {
return res.status(400).send({
error: "Invalid data format."
});
}
let user = await User.findOne({
_id: res.locals.id
},
"currentAddress permanentAddress"
);
updateJobSeeker({
_id: res.locals.id
}, {
currentAddress: req.body.currentAddress || user.currentAddress,
permanentAddress: req.body.permanentAddress || user.permanentAddress
}, {
new: true
},
res
);
},
updateOthers: async (req, res, next) => {
let user = await User.findOne({
_id: res.locals.id
},
"academicInfo workExperience skills"
);
updateJobSeeker({
_id: res.locals.id
}, {
skills: req.body.skills || user.skills,
academicInfo: req.body.academicInfo || user.academicInfo,
workExperience: req.body.workExperience || user.workExperience
}, {
new: true
},
res
);
},
updateProfileImage: async (req, res, next) => {
if (!req.file) {
return res.status(400).send({
error: "No file is selected."
});
}
let user = await User.findOne({
_id: res.locals.id
},
"imagePath"
);
if (user.imagePath) {
fs.unlinkSync(user.imagePath);
}
let imagePath = "public/uploads/" + req.file.filename || user.imagePath;
updateJobSeeker({
_id: res.locals.id
}, {
imagePath: imagePath
}, {
new: true
},
res
);
},
updatePassword: async (req, res, next) => {
let user = await User.findOne({
_id: res.locals.id
},
"password"
);
req.checkBody("newPassword", "Password is required.").notEmpty();
req
.checkBody("newPassword", "Password must be 6 character long.")
.isLength({
min: 6
});
let password = req.body.newPassword;
req.checkBody("confirmPassword", "Please retype password.").notEmpty();
req
.checkBody("confirmPassword", "Please confirm password.")
.equals(password);
let errors = req.validationErrors();
if (errors) {
return res.status(422).send(errors);
}
let oldPassword = crypto.decrypt(user.password, secretKeys.userPasswordKey);
if (req.body.oldPassword != oldPassword) {
return res.status(400).send({
error: "Incorrect Password"
});
}
updateJobSeeker({
_id: res.locals.id
}, {
password: crypto.encrypt(
req.body.newPassword,
secretKeys.userPasswordKey
)
},
res
);
},
deleteAccount: (req, res, next) => {
User.deleteOne({
_id: res.locals.id
},
err => {
if (err) {
return res.status(500).send({
error: "Server Error."
});
} else {
res.status(200).send({
success: "User deleted."
});
}
}
);
}
};
|
/******************************************
File Name: custom.js
Template Name: zustyse - Responsive HTML5 Theme
Created By: htmldotdesign
Envato Profile: https://themeforest.net/user/htmldotdesign
Website: https://html.design
Version: 1.0
******************************************/
"use strict";
/**== wow animation ==**/
new WOW().init();
/**== loader js ==*/
$(window).load(function() {
$(".bg_load").fadeOut("slow");
})
/**== Menu js ==**/
$("#navbar_menu").menumaker({
title: "Menu",
format: "multitoggle"
});
/**== gallery js ==**/
$(document).ready(function(){
$(".filter-button").click(function(){
var value = $(this).attr('data-filter');
if(value == "all")
{
//$('.filter').removeClass('hidden');
$('.filter').show('1000');
}
else
{
// $('.filter[filter-item="'+value+'"]').removeClass('hidden');
// $(".filter").not('.filter[filter-item="'+value+'"]').addClass('hidden');
$(".filter").not('.'+value).hide('3000');
$('.filter').filter('.'+value).show('3000');
}
});
if ($(".filter-button").removeClass("active")) {
$(this).removeClass("active");
}
$(this).addClass("active");
});
/** progress_bar js **/
$(document).ready(function() {
$('.progress .progress-bar').css("width",
function() {
return $(this).attr("aria-valuenow") + "%";
}
)
});
/** Casestudies Tab_bar js **/
$(document).ready(function(){
$(".filter-button").click(function(){
var value = $(this).attr('data-filter');
if(value == "all")
{
//$('.filter').removeClass('hidden');
$('.filter').show('1000');
}
else
{
// $('.filter[filter-item="'+value+'"]').removeClass('hidden');
// $(".filter").not('.filter[filter-item="'+value+'"]').addClass('hidden');
$(".filter").not('.'+value).hide('3000');
$('.filter').filter('.'+value).show('3000');
}
});
if ($(".filter-button").removeClass("active")) {
$(this).removeClass("active");
}
$(this).addClass("active");
});
/**===== Revolution Slider =====**/
var tpj = jQuery;
var revapi4;
tpj(document).ready(function() {
if (tpj("#rev_slider_4_1").revolution == undefined) {
revslider_showDoubleJqueryError("#rev_slider_4_1");
} else {
revapi4 = tpj("#rev_slider_4_1").show().revolution({
sliderType: "standard",
jsFileLocation: "revolution/js/",
sliderLayout: "fullwidth",
dottedOverlay: "none",
delay: 7000,
navigation: {
keyboardNavigation: "off",
keyboard_direction: "horizontal",
mouseScrollNavigation: "off",
onHoverStop: "off",
touch: {
touchenabled: "on",
swipe_threshold: 75,
swipe_min_touches: 1,
swipe_direction: "horizontal",
drag_block_vertical: false
},
arrows: {
style: "zeus",
enable: true,
hide_onmobile: true,
hide_under: 600,
hide_onleave: true,
hide_delay: 200,
hide_delay_mobile: 1200,
tmp: '<div class="tp-title-wrap"><div class="tp-arr-imgholder"></div></div>',
left: {
h_align: "left",
v_align: "center",
h_offset: 30,
v_offset: 0
},
right: {
h_align: "right",
v_align: "center",
h_offset: 30,
v_offset: 0
}
},
bullets: {
enable: true,
hide_onmobile: true,
hide_under: 600,
style: "metis",
hide_onleave: true,
hide_delay: 200,
hide_delay_mobile: 1200,
direction: "horizontal",
h_align: "center",
v_align: "bottom",
h_offset: 0,
v_offset: 30,
space: 5,
tmp: '<span class="tp-bullet-img-wrap"> <span class="tp-bullet-image"></span></span><span class="tp-bullet-title">{{title}}</span>'
}
},
viewPort: {
enable: true,
outof: "pause",
visible_area: "80%"
},
responsiveLevels: [1240, 1024, 778, 480],
gridwidth: [1240, 1024, 778, 480],
gridheight: [900, 900, 500, 400],
lazyType: "none",
parallax: {
type: "mouse",
origo: "slidercenter",
speed: 3000,
levels: [2, 3, 4, 5, 6, 7, 12, 16, 10, 50],
},
shadow: 0,
spinner: "off",
stopLoop: "off",
stopAfterLoops: -1,
stopAtSlide: -1,
shuffle: "off",
autoHeight: "off",
hideThumbsOnMobile: "off",
hideSliderAtLimit: 0,
hideCaptionAtLimit: 0,
hideAllCaptionAtLilmit: 0,
debugMode: false,
fallbacks: {
simplifyAll: "off",
nextSlideOnWindowFocus: "off",
disableFocusListener: false,
}
});
}
});
/**===== End slider =====**/
/** header fixed js **/
$(window).scroll(function(){
if ($(window).scrollTop() >= 300) {
$('.header_fixed_on_scroll').addClass('fixed-header');
}
else {
$('.header_fixed_on_scroll').removeClass('fixed-header');
}
});
/*!-- half slider --*/
$('.owl_half_slider').owlCarousel({
stagePadding: 60,
loop:true,
margin:20,
nav:true,
responsive:{
0:{
items:1
},
768:{
items:2
},
1200:{
items:3
}
}
})
/** mousewheel slider **/
var owl = $('.owl-carousel-mousewheel');
owl.owlCarousel({
loop: true,
nav: true,
responsive: {
0: {
items: 1
},
600: {
items: 2
},
960: {
items: 3
},
1200: {
items: 4
},
1640: {
items: 4
}
}
});
owl.on('mousewheel', '.owl-stage', function(e) {
if (e.deltaY > 0) {
owl.trigger('next.owl');
} else {
owl.trigger('prev.owl');
}
e.preventDefault();
});
//service and service options
function mservice(datavalue){
$.ajax({
url: 'action.php',
type: 'POST',
data: {data : datavalue},
success: function(result){
$('#services').html(result);
}
});
}
// Lawyer Signup form
$(document).ready(function(){
$('#myForm').on('submit', function(e){
e.preventDefault();
var fd = new FormData(this);
$.ajax({
url: 'action.php',
type: 'post',
data: fd,
dataType: 'JSON',
processData: false,
contentType: false,
cache: false,
success: function(data){
var result = data;
// console.log(result.message);
$.toast({
hading:'notification',
text: result.message,
position:'top-center',
icon: result.status
});
if(result.url && result.url.length > 0){
setTimeout(function(){
window.location.href = result.url
}, 3000)
}
}
});
});
});
// Client Signup form
$(document).ready(function(){
$('#cForm').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'action.php',
type: 'post',
data: $(this).serialize(),
success: function(data){
var result = JSON.parse(data);
$.toast({
hading:'notification',
text: result.message,
position:'top-center',
icon: result.status
});
if(result.url && result.url.length > 0){
setTimeout(function(){
window.location.href = result.url
}, 2000)
}
}
});
});
});
// Contact form submit
$(document).ready(function(){
$('#form_contact').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'action.php',
type: 'post',
data: $(this).serialize(),
success: function(data){
var result = JSON.parse(data);
$.toast({
hading:'notification',
text: result.message,
position:'top-center',
icon: result.status
});
if(result.url && result.url.length > 0){
setTimeout(function(){
window.location.href = result.url
}, 2000)
}
}
});
});
});
// Client form submit
$(document).ready(function(){
$('#pform').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'action.php',
type: 'post',
data: $(this).serialize(),
success: function(data){
var result = JSON.parse(data);
$.toast({
hading:'notification',
text: result.message,
position:'top-center',
icon: result.status
});
if(result.url && result.url.length > 0){
setTimeout(function(){
window.location.href = result.url
}, 2000)
}
}
});
});
});
// client submit case file
$(document).ready(function(){
$('#casedetails').on('submit', function(e){
e.preventDefault();
var fd = new FormData(this);
$.ajax({
url: 'action.php',
type: 'post',
data: fd,
dataType: 'JSON',
processData: false,
contentType: false,
cache: false,
success: function(data){
var result = data;
// console.log(result.message);
$.toast({
hading:'notification',
text: result.message,
position:'top-center',
icon: result.status
});
setTimeout(function(){
window.location.reload();
}, 2000)
}
});
});
$('.popupBtn').on('click', function(e){
e.preventDefault();
var id = $(this).val();
$('#exampleModal input[name=lid]').val(id);
$('#exampleModal').modal('show');
})
});
// Login popup
$('.loginPopup').on('click',function (e) {
e.preventDefault();
$('#loginModal').modal('show');
});
// Login form submit
$(document).ready(function(){
$('#lform').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'action.php',
type: 'post',
data: $(this).serialize(),
success: function(data){
var result = JSON.parse(data);
$.toast({
hading:'notification',
text: result.message,
position:'top-center',
icon: result.status
});
if(result.url && result.url.length > 0){
setTimeout(function(){
window.location.href = result.url
}, 2000)
}
}
});
});
});
// update profile
$(document).ready(function(){
var form = $('#pform');
$('#update').click(function(){
$.ajax({
url: form.attr("action"),
type: 'post',
data: $("pform input").serialize(),
success: function(data){
console.log(data);
}
});
});
});
//Click event handler for nav-items
$(document).ready(function(){
$('.first-ul li a').on("click", function(e) {
// $('.first-ul li a').removeClass("active");
$(this).addClass("active");
});
});
// user profile datatable
$(document).ready( function () {
$('#myTable').DataTable();
} );
// user case details datatable
$(document).ready( function () {
$('#myDataTable').DataTable();
} );
|
const initialState = [];
export default function nulandToken(state = initialState, action) {
if (action.type === 'ADD_TRAN') {
return [...state, action.payload];
} else if (action.type === 'UPD_TRAN') {
for(var index=0; index<state.length; index++) {
if( state[index].hash === action.payload.hash ) {
state[index] = action.payload
}
}
return [...state];
}
return state;
}
|
// If Installed from NPM include module with the following
//
// var ThrowAndTell = require('throwandtell');
//
// Here we require it from a local file.
var ThrowAndTell = require('../');
var throwandtell = new ThrowAndTell({
// Key Given in Dashboard
accessKey: process.env.THROWANDTELL_ACCESSKEY || 'PLACE_KEY_HERE'
// By default ThrowAndTell adds a listner for uncaught Errors
// to disable this place
//
// autoHookUncaught: false
//
// Another default is to NOT 'save' the app from crashing due
// to an uncaughtError, hoever it can, if you uncomment the following
//
// saveUncaught: true
//
});
throw new Error("Test Error");
// It's then reported to GitHub or wherevers been set in the dashboard
// and this app would exit.
|
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
maxWidth = window.innerWidth,
maxHeight = window.innerHeight
canvas.width = maxWidth
canvas.height = maxHeight
var rockets = []
particles = [],
maxParticles = 400
function Particle (ctx, x, y, r, deg, v, accX, accY) {
this.ctx = ctx
this.startX = x
this.startY = y
this.x = x
this.y = y
this.r = r
this.angle = Math.PI / 180 * deg
this.v = v
this.vx = Math.cos(this.angle) * v
this.vy = Math.sin(this.angle) * v
this.accX = accX || 0
this.accY = accY || 9.8 / 20
this.alpha = 1
this.fade = 0.02
this.color = Math.floor(Math.random() * 360 / 10) * 10
this.end = false
this.history = []
}
Particle.prototype = {
calcVelocity () {
this.vx += this.accX
this.vy += this.accY
},
calcPosition () {
this.x += this.vx
this.y += this.vy
this.alpha -= this.fade
if (this.alpha < 0) {
this.end = true
this.alpha = 0
}
this.history.push([this.x, this.y])
if (this.history.length > 20) {
this.history.shift()
}
},
update () {
this.calcVelocity()
this.calcPosition()
},
draw () {
const ctx = this.ctx
// ctx.fillStyle = 'green'
ctx.globalCompositeOperation = 'lighter'
let gradient = ctx.createRadialGradient(this.x, this.y, 0.1, this.x, this.y, this.r)
gradient.addColorStop(0.1, `rgba(255, 255, 255 , ${ this.alpha })`)
gradient.addColorStop(0.8, `hsla( ${this.color}, 100%, 50%, ${this.alpha})`)
gradient.addColorStop(1, `rgba(0, 0, 0, ${ this.alpha })`)
ctx.beginPath()
this.history.forEach(pos => {
if (Math.abs(pos[0] - this.x) > 5 || Math.abs(pos[1] -this.y) > 5) {
return
}
ctx.arc(pos[0], pos[1], this.r, 0, Math.PI * 2, true)
ctx.fill()
ctx.closePath()
})
},
reset () {
this.x = this.startX
this.y = this.startY
this.vx = Math.cos(this.angle) * this.v
this.vy = Math.sin(this.angle) * this.v
this.end = false
}
}
function Rocket (ctx, x, y, r, h, v, acc) {
this.ctx = ctx
this.startX = x
this.startY = y
this.startV = v
this.x = x
this.y = y
this.r = r
this.h = h || 500
this.v = v || -18
this.acc = acc || 9.8 / 20
this.end = false
this.history = []
}
Rocket.prototype = {
calcVelocity () {
this.v += this.acc
},
calcPosition () {
this.y += this.v
this.history.push([this.x, this.y])
if (this.history.length > 25) {
this.history.shift()
}
},
checkHeight () {
if (this.startY - this.y >= this.h || this.v >= 0) {
this.end = true
this.bomb()
}
},
bomb () {
let x = this.x
let y = this.y
let r = 2
let v = -2
let accX = 0
let accY = 0.05
let count = Math.floor(Math.random() * 20) + 40
for (let i = 0; i < count; i++) {
let deg = Math.floor(Math.random() * 360)
particles.push(new Particle(ctx, x, y, r, deg, v, accX, accY))
}
},
update () {
this.calcVelocity()
this.calcPosition()
this.checkHeight()
},
draw () {
const ctx = this.ctx
this.history.forEach(pos => {
ctx.beginPath()
ctx.fillStyle = 'rgba(255, 255, 255, 0.4)'
ctx.arc(pos[0], pos[1], this.r, 0, Math.PI * 2, true)
ctx.fill()
ctx.closePath()
})
},
reset () {
this.x = this.startX
this.y = this.startY
this.v = startV
this.end = false
}
}
;(function () {
for (var i = 0; i < 2; i++) {
let x = Math.random() * maxWidth
let y = maxHeight - 100
let r = 4
rockets.push(new Rocket(ctx, x, y, r))
}
})()
function render () {
ctx.clearRect(0, 0, maxWidth, maxHeight)
rockets.forEach(rocket => {
if (!rocket.end) {
rocket.update()
rocket.draw()
}
})
particles.forEach(particle => {
if (!particle.end) {
particle.update()
particle.draw()
}
})
requestAnimationFrame(render)
}
render()
|
import React from 'react';
import cloneDeep from 'lodash/cloneDeep';
class CreateCategory extends React.Component {
constructor(props) {
super(props);
this.state = {
title: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const state = cloneDeep(this.state);
state.title = event.target.value;
this.setState(state);
}
handleSubmit(event) {
event.preventDefault();
this.props.create(this.state.title);
}
render() {
return (
<div className="create-category panel-item">
<form onSubmit={this.handleSubmit} name="createCategory">
<div className="input-container">
<label>Title:</label>
<input
type="text"
name="title"
onChange={this.handleChange}
tabIndex="1" />
</div>
<div className="button-container">
<button type="button"
className="cancel"
onClick={this.props.cancel}>
Cancel
</button>
<button type="submit"
disabled={!this.state.title.length}>
Create
</button>
</div>
</form>
</div>
);
}
}
export default CreateCategory;
|
module.exports = {
"CallML6Soap": {
"namespace": "urn:callcredit.co.uk/soap:callmlapi6",
"serviceUrl": "https://www.callcreditsecure.co.uk/Services/CallML/CallML6.asmx",
"Search06b": {
"soapAction": "urn:callcredit.co.uk/soap:callmlapi6/Search06b",
"input": "ElementSearch06b",
"output": "ElementSearch06bResponse"
},
"SubsequentSearch06b": {
"soapAction": "urn:callcredit.co.uk/soap:callmlapi6/SubsequentSearch06b",
"input": "ElementSubsequentSearch06b",
"output": "ElementSubsequentSearch06bResponse"
},
"OverrideDecision06b": {
"soapAction": "urn:callcredit.co.uk/soap:callmlapi6/OverrideDecision06b",
"input": "ElementOverrideDecision06b",
"output": "ElementOverrideDecision06bResponse"
},
"AddressLinkSearch06b": {
"soapAction": "urn:callcredit.co.uk/soap:callmlapi6/AddressLinkSearch06b",
"input": "ElementAddressLinkSearch06b",
"output": "ElementAddressLinkSearch06bResponse"
},
"ChangePassword06b": {
"soapAction": "urn:callcredit.co.uk/soap:callmlapi6/ChangePassword06b",
"input": "ElementChangePassword06b",
"output": "ElementChangePassword06bResponse"
}
}
}
|
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require('mongoose');
var Campground = require("./models/campground");
var seedDB = require("./seeds");
// Seeding the database
seedDB();
// connecting to yelp_camp database
// if it doesn't exist, it'll be created
mongoose.connect("mongodb://localhost/yelp_camp");
// Now we don't need to write .ejs every time
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "ejs");
// ==========================================
// !!! THE ORDER OF ROUTES MATTERS !!!
// ==========================================
app.get("/", function (req, res) {
res.render("landing");
});
// INDEX – show all campgrounds
app.get("/campgrounds", function (req, res) {
// GET ALL CAMPGROUNDS FROM DB
Campground.find({}, function (err, allCampgrounds) {
if (err) {
console.log(err);
} else {
// { campgrounds: campgrounds } – the 1st -> name in campgrounds.ejs, 2nd -> data we're passing in
res.render("index", { campgrounds: allCampgrounds });
}
});
});
// CREATE (route) – add new campground to DB
app.post("/campgrounds", function (req, res) {
//get data from form and add to campgrounds array
var name = req.body.name;
var image = req.body.image;
var desc = req.body.description;
var newCampground = {name: name, image: image, description: desc};
// Create a new campground and save to DB
Campground.create(newCampground, function (err, newlyCreatedCampground) {
if (err) {
console.log(err);
} else {
//redirect back to campgrounds page
res.redirect("/campgrounds");
}
});
});
// NEW (route) – show form to create campground
app.get("/campgrounds/new", function (req, res) {
res.render("new");
});
// SHOW (route) – shows more info about one campground
app.get("/campgrounds/:id", function (req, res) {
// Find the campground with provided id
Campground.findById(req.params.id).populate("comments").exec(function (err, foundCampground) {
if (err) {
console.log(err);
} else {
// Render the template with that campground
res.render("show", { campground: foundCampground });
}
});
});
app.listen(3000, function () {
console.log('Yelp Camp Server Has Started! || Listen to the port 3000 || http://localhost:3000/');
});
|
'use strict';
const authorsDatabase = require('./database.js');
const createError = require('http-errors');
const fs = require('fs');
/**
* Adds a new music to the database. This endpoint receive some music's metadata
* and it's file and send it to the the database and internal storage.
*/
async function add(request, response, next) {
try {
const body = request.body;
// Get's music metadata
const author = new authorsDatabase.Author(body.name);
const queries = await authorsDatabase.connect();
const addedAuthor = await queries.addAuthor(author);
response.status(200).json({ id: addedAuthor.id, name: addedAuthor.name }).end();
await authorsDatabase.disconnect();
} catch (error) {
next(error);
}
}
async function getAll(request, response, next) {
try {
const queries = await authorsDatabase.connect();
const authors = await queries.getAllAuthors();
response.status(200).json(authors).end();
await authorsDatabase.disconnect();
} catch (error) {
next(error);
}
}
async function getByID(request, response, next) {
try {
if (!request.params.id) throw createError(401, `The author's id is missing`);
const queries = await authorsDatabase.connect();
const author = await queries.getAuthorByID(request.params.id);
response.status(200).json(author).end();
await authorsDatabase.disconnect();
} catch (error) {
next(error);
}
}
async function getByMusic(request, response, next) {
try {
if (!request.params.musicID) throw createError(401, `The musics's id is missing`);
const queries = await authorsDatabase.connect();
const authors = await queries.getAuthorsByMusic(request.params.musicID);
response.status(200).json(authors).end();
await authorsDatabase.disconnect();
} catch (error) {
next(error);
}
}
async function deleteAuthor(request, response, next) {
try {
if (!request.params.id) throw createError(401, `The author's id is missing`);
const queries = await authorsDatabase.connect();
const relatedMusics = await queries.deleteAuthor(request.params.id);
if (relatedMusics.length > 0) {
const obstacles = relatedMusics.map(music => ({ id: music.id, name: music.name, url: music.calculateFileURL() }));
response.status(403).json(obstacles).end();
}
response.status(200).end();
await authorsDatabase.disconnect();
} catch (error) {
next(error);
}
}
module.exports = { add, getAll, getByID, deleteAuthor, getByMusic }
|
/** @jsx jsx */
/** @jsxFrag React.Fragment */
// eslint-disable-next-line
import React from 'react';
import { jsx, css } from '@emotion/core';
import logo from './images/logo.png';
import fb from './images/fb.png';
import insta from './images/insta.png';
const centeredContainerStyles = css`
max-width: 100%;
text-align: center;
justify-content: center;
display: block;
position: relative;
`;
const headerStyles = css`
background: white;
font-weight: medium;
color: #515762;
font-size: 0.9375rem;
width: 100%;
position: fixed;
left: 0;
right: 0;
top: 0;
transition: transform 0.5s ease;
border-bottom: 2px solid #f2f3f4;
margin-bottom: 2px;
transition: transform 0.5s ease;
z-index: 10;
max-height: 44px;
`;
const navBar = css`
top: 0;
cursor: pointer;
display: flex;
`;
const navULLeft = css`
margin: 0;
padding: 0;
list-style: none;
display: flex;
height: 100%;
top: 0;
justify-content: flex-start;
transition: background-size 0.4s cubic-bezier(0.23, 1, 0.32, 1);
transition: outline-offset 0.15s ease-out;
align-items: center;
a {
margin-right: 20px;
text-decoration: none;
color: #4a4a4a;
transition: color 0.2s;
line-height: 31px;
transition: background-size 0.4s cubic-bezier(0.23, 1, 0.32, 1);
background-position-y: 100%;
&:hover {
background-image: linear-gradient(#bfbfbf, #bfbfbf);
background-size: 100% 4px;
background-position-x: 50%;
background-repeat: no-repeat;
}
}
img {
text-align: left;
padding: 0 0.625rem 0 0.85rem;
display: flex;
margin: 0;
align-items: top;
max-height: 141px;
}
`;
const navULRight = css`
display: flex;
justify-content: flex-end;
transition: background-size 0.4s cubic-bezier(0.23, 1, 0.32, 1);
transition: outline-offset 0.15s ease-out;
margin-left: auto;
align-items: center;
a {
margin-right: 20px;
text-decoration: none;
color: #4a4a4a;
transition: color 0.2s;
line-height: 31px;
transition: background-size 0.4s cubic-bezier(0.23, 1, 0.32, 1);
background-position-y: 100%;
&:hover {
background-image: linear-gradient(#bfbfbf, #bfbfbf);
background-size: 100% 4px;
background-position-x: 50%;
background-repeat: no-repeat;
}
}
`;
const signInButton = css`
background-color: transparent;
font-family: 'Cabin';
font-size: 15px;
padding: 10px 16px 6px;
border: 1px solid #515762;
min-width: 0;
/* display: flex; */
line-height: 1;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
/* justify-content: flex-end; */
/* align-self: center; */
&:hover {
transition: background-color 0.4s cubic-bezier(0.23, 1, 0.32, 1);
background-color: #e7e8e9;
}
`;
const videoContainer = css`
${centeredContainerStyles}
position: absolute;
text-align: center;
padding: 2rem 0.5rem;
align-items: center;
margin: 0;
left: 30%;
h1 {
color: #ffffff;
max-width: 40rem;
font-size: 64px;
margin-bottom: 1.5rem;
text-shadow: 1px 2px 2px rgba(0, 0, 0, 0.2);
}
`;
const videoDisplay = css`
position: relative;
max-width: 100%;
object-fit: contain;
display: block;
margin-top: 0px;
z-index: -1;
@media (min-width: 768px) {
overflow: hidden;
max-height: 78vh;
}
`;
const quizButton = css`
background-color: #dd2e3e;
border: 2px solid transparent;
cursor: pointer;
padding: 14px 22px 10px;
color: white;
font-size: 14px;
display: inline-block;
transition: background-color 0.4s cubic-bezier(0.23, 1, 0.32, 1);
&:hover {
transition: background-color 0.4s cubic-bezier(0.23, 1, 0.32, 1);
background-color: #cd243b;
}
`;
const firstSectionStyle = css`
${centeredContainerStyles}
margin: 40px 280px;
padding: 0 24px;
`;
const categoryImageHolder = css`
max-width: 100%;
margin: 0 auto;
display: flex;
flex-wrap: nowrap;
justify-content: center;
/* position: relative;
text-align: center; */
img {
max-width: 19.75rem;
margin: 0 0.75rem;
flex-grow: 0;
flex-shrink: 1;
flex-basis: auto;
}
button {
bottom: 8px;
left: 16px;
background-color: grey;
color: blue;
font-size: 16px;
padding: 12px 24px;
border: none;
cursor: pointer;
}
`;
const secondSectionStyle = css`
${centeredContainerStyles}
border: 1px solid #e7e8e9;
margin: 0 110px;
padding: 30px 0;
ul {
display: flex;
text-align: center;
margin: 30px 0;
list-style: none;
li {
padding: 10px, 32px;
margin: ;
border-right: 1px solid #e7e8e9;
}
}
`;
const highlight = css`
strong {
background-image: linear-gradient(#fef399, #fef399);
background-position-x: 80%;
background-repeat: no repeat;
}
`;
const thirdSectionStyle = css`
${centeredContainerStyles}
`;
const fourthSectionStyle = css`
${centeredContainerStyles}
`;
const fifthSectionStyle = css`
${centeredContainerStyles}
max-width: 44rem;
border: 1px solid #e7e8e9;
margin: 20px 25rem;
box-shadow: 10px 10px #e7e8e9;
`;
const footer = css`
border-top: 1px solid #d9d9d9;
display: flex;
transition: background-size 0.4s cubic-bezier(0.23, 1, 0.32, 1);
transition: outline-offset 0.15s ease-out;
a {
text-decoration: none;
color: #25282d;
transition: color 0.2s;
transition: background-size 0.4s cubic-bezier(0.23, 1, 0.32, 1);
background-position-y: 100%;
&:hover {
background-image: linear-gradient(#000000, #000000);
background-size: 100% 0.5px;
background-position-x: 0;
background-repeat: no-repeat;
}
}
`;
const finalDiv = css`
${centeredContainerStyles}
margin: 0 280px;
padding: 0 24px;
max-width: 100%;
margin: 0 auto;
display: flex;
flex-wrap: nowrap;
justify-content: space-evenly;
text-align: left;
/* div {
min-width: 85px;
} */
`;
const bottomLinks = css`
display: flex;
flex-direction: column;
`;
const trademark = css`
border-top: 1px solid #d9d9d9;
font-size: 13px;
color: #25282d;
transition: background-size 0.4s cubic-bezier(0.23, 1, 0.32, 1);
display: flex;
a {
text-decoration: none;
color: #25282d;
transition: color 0.2s;
transition: background-size 0.4s cubic-bezier(0.23, 1, 0.32, 1);
background-position-y: 100%;
&:hover {
background-image: linear-gradient(#000000, #000000);
background-size: 100% 0.5px;
background-position-x: 50%;
background-repeat: no-repeat;
}
}
> div {
margin-right: 0;
}
div:nth-child(2) {
margin-left: 0;
}
`;
function App() {
return (
<>
<div>
<header css={headerStyles}>
<nav css={navBar}>
<div css={navULLeft}>
<img src={logo} alt="Stitchfix logo" />
<a href="a#">Men </a>
<a href="a#">Women </a>
<a href="a#">Kids </a>
</div>
<div css={navULRight}>
<a href="a#">Style Guide</a>
<a href="a#">FAQ </a>
<a href="a#">Gift Cards </a>
<button css={signInButton}>Sign In</button>
</div>
</nav>
</header>
<section css={videoContainer}>
<h1>Personal styling for everybody</h1>
<button css={quizButton}>Take your style quiz</button>
</section>
<section css={videoDisplay}>
<video
src="https://d3ss0gp3e5d7m3.cloudfront.net/assets/images/gateway-stitch-fix-video.10yH0.mp4"
muted
loop
playsInline
autoPlay
/>
</section>
<section css={firstSectionStyle}>
<h2>We'll Find Style For Your Life</h2>
<p>
With clothing hand selected by our expert stylists for your unique
size & style, you’ll always look and feel your best. No subscription
required.
</p>
<div css={categoryImageHolder}>
<a href="a#">
<img
src="https://d3ss0gp3e5d7m3.cloudfront.net/assets/images/desktop-womens-plus-size-inclusive@1x.2GQbi.jpg"
alt="Stitch Fix plus-size clothing outfit including a plus-size navy and white printed jumpsuit with white tee."
/>
<button>Women</button>
</a>
<div css={categoryImageHolder}>
<a href="a#">
<img
src="https://d3ss0gp3e5d7m3.cloudfront.net/assets/images/desktop-mens-casual-outdoor@1x.Ar-ie.jpg"
alt="Stitch Fix men’s outfit including a pink tee, tan windbreaker jacket and black jogger sweatpants."
/>
<button>Men</button>
</a>
</div>
<div css={categoryImageHolder}>
<a href="a#">
<img
src="https://d3ss0gp3e5d7m3.cloudfront.net/assets/images/desktop-kids-activewear@1x.1L_Lm.jpg"
alt="Stitch Fix Kids blue ombre hoodie sweatshirt with palm tree graphic."
/>
<button>Kids</button>
</a>
</div>
</div>
</section>
<section css={secondSectionStyle}>
<h2>How Stitch Fix works</h2>
<ul>
<li>
Tell us your price range, size & style. You’ll pay just a $20
styling fee, which gets credited toward pieces you keep.
</li>
<li>
Get a Fix when you want. Try on pieces at home before you buy.
Keep your favorites, send back the rest.
</li>
<li>
Free shipping, returns & exchanges—a prepaid return envelope is
included. There are no hidden fees, ever.
</li>
</ul>
<p css={highlight}>
<strong>No subscription required.</strong> Try Stitch Fix once or
set up automatic deliveries.
</p>
</section>
<section css={thirdSectionStyle}>
<h2>Endless styles for your best fit</h2>
<p>
Your stylist gets to know you, discovering your perfect fit from
limitless style options.
</p>
</section>
<section css={fourthSectionStyle}>
<h2>1,000+ top brands</h2>
<p>
Women’s sizes 0-24W (XS-3X)—Plus, Petite and Maternity Men’s sizes
XS-3XL, waists 28-48ʺ and inseams 28-36ʺ—including Big & Tall
</p>
</section>
<section css={fifthSectionStyle}>
<h2>Ready to get started?</h2>
<button css={quizButton}>Take your style quiz</button>
<p>Already have an account? Sign in</p>
</section>
<footer css={footer}>
<div css={finalDiv}>
<div>Logo & Location</div>
<div css={bottomLinks}>
<h3>Service</h3>
<a href="a#">Iphone App</a>
<a href="a#">Plus Sizes</a>
<a href="a#">Gift Cards</a>
<a href="a#">Maternity</a>
<a href="a#">Petite</a>
<a href="a#">Big & Tall</a>
<a href="a#">Women's Jeans</a>
<a href="a#">Business Casual</a>
</div>
<div css={bottomLinks}>
<h3>The Company</h3>
<a href="a#">About Us</a>
<a href="a#">Press</a>
<a href="a#">Investor Relations</a>
<a href="a#">Careers</a>
<a href="a#">Tech Blog</a>
</div>
<div css={bottomLinks}>
<h3>Questions?</h3>
<a href="a#">FAQ's</a>
<a href="a#">Help</a>
</div>
<div>
<img src={fb} alt="Facebook" />
<img src={insta} alt="Instagram" />
<img alt="Pinterest" />
<img alt="Twitter" />
</div>
</div>
</footer>
<div css={trademark}>
<div>
<p>Stitch Fix and Fix are trademarks of Stitch Fix, Inc.</p>
</div>
<div>
<p>
<a href="#a">Terms of Use</a> - <a href="#a">Privacy Policy</a> -{' '}
<a href="#a">Supply Chain Information</a> -{' '}
<a href="#a">Ad Choices</a> -{' '}
<a href="#a">CA Notice at Collection</a> -{' '}
<a href="#a">Cookies Settings</a> - <a href="#a">Sitemap</a>
</p>
</div>
</div>
</div>
</>
);
}
export default App;
|
import React, {useEffect} from 'react';
import PropTypes from 'prop-types';
import bridge from '@vkontakte/vk-bridge';
import { platform, IOS } from '@vkontakte/vkui';
import Panel from '@vkontakte/vkui/dist/components/Panel/Panel';
import PanelHeader from '@vkontakte/vkui/dist/components/PanelHeader/PanelHeader';
import PanelHeaderButton from '@vkontakte/vkui/dist/components/PanelHeaderButton/PanelHeaderButton';
import Icon28ChevronBack from '@vkontakte/icons/dist/28/chevron_back';
import Icon24Back from '@vkontakte/icons/dist/24/back';
import { render } from 'react-dom';
const osName = platform();
const SamaraNew = (props) => {
useEffect(() => {
bridge.subscribe(({ detail: { type, data }}) => {
if (type === 'VKWebAppUpdateConfig') {
const schemeAttribute = document.createAttribute('scheme');
schemeAttribute.value = data.scheme ? data.scheme : 'client_light';
document.body.attributes.setNamedItem(schemeAttribute);
}
});
async function fetchData() {
const posts = await bridge.sendPromise("VKWebAppCallAPIMethod", {
"method": "wall.get",
"params": {
"owner_id": "86529522",
}
});
return posts;
}
console.log(1);
}, []);
return(
<Panel id={props.id}>
<PanelHeader
left={<PanelHeaderButton onClick={props.go} data-to="home">
{osName === IOS ? <Icon28ChevronBack/> : <Icon24Back/>}
</PanelHeaderButton>}
>
Новости Самары
</PanelHeader>
</Panel>
);
};
SamaraNew.propTypes = {
id: PropTypes.string.isRequired,
go: PropTypes.func.isRequired,
};
export default SamaraNew;
|
let BaseMenu = require("./basemenu.js");
/**
* The race select menu.
* @name SettingsMenu
* @type ElonaJS.UI.Menus.BaseMenu
* @memberOf ElonaJS.UI.Menus
*/
let SettingsMenu = new BaseMenu();
SettingsMenu.Customize({
position: {x: 175, y: 100},
centered: true,
size: {w: 450, h: 400}
});
SettingsMenu._OnLoad = function(category){
if(this.init){
this._BuildOptions(category);
return;
}
this.init = true;
new UI.Components.Image({id: "Paper", img: "interface.paper", position: {z: 0}, width: 450, height: 400, shadow: {distance: 10, blur: 0}}).Attach(this);
new UI.Components.Image({id: "BG_Deco", img: "cbg3", position: {x: 30, y: 40, z: 1}, width: 290, height: 350, alpha: 0.2}).Attach(this);
new UI.Components.PaperFooter({id: "Hint", position: {x: 30, y: 370}, text: {i18n: "hints.3b"}, rect: {width: 350}}).Attach(this);
new UI.Components.PaperHeader({id: "Display", text: {text:"Display Settings"}}).Attach(this);
new UI.Components.Text({id: "Desc", text: "", position: {x: 50, y: 340}, color: "blue", wrap: {width: 350, spacing: 16}}).Attach(this);
this._BuildOptions(category);
}
SettingsMenu._BuildOptions = function(category){
let setlist = DB.Settings.Search({category: category});
let options = [];
for(let i = 0; i < setlist.length; i++){
options.push(setlist[i].GetAsOption());
}
this.options.CustomizeList({position: {x: 60, y: 50}, spacing: 25});
this.options.CustomizeStyle({keyimage: {enabled: false}, keytext: {enabled: false}});
this.options.Set(options);
}
SettingsMenu._OnBack = function(){
UI.UnloadMenu(this);
UI.LoadMenu("TitleScreen");
}
module.exports = SettingsMenu;
|
import React from'react';
export default class Banner extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
var main = (
<div className="row">
<div className="col-12 mt-5">
<img className="img-fluid" src="img/isac-demonstrator-banner.jpg" alt="Das Bild zeigt eine menschliche Hand und eine computergenerierte Hand, die sich berühren. Dies ist eine grafische Veranschaulichung des Bereichs Mensch-Maschine Interaktion / Industrie 4.0." />
</div>
</div>
)
return main;
}
}
|
import BaseResponse from "../../middleware/base-response";
import BasicAuthMiddleware from "../../middleware/basic-auth"
import UserService from "./service";
export default class UserController extends BaseResponse {
getUsersList = async (req, res) => {
const { first_name, last_name, user_id } = req.query;
try {
const login = (BasicAuthMiddleware.decode(BasicAuthMiddleware.getToken(req)))[0];
const result = await UserService.getUsersList(login, first_name, last_name, user_id)
this.response(null, res, result)
} catch (e) {
this.response(e, res, null)
}
}
}
|
import { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { useToasts } from 'react-toast-notifications';
import { useHistory } from 'react-router-dom';
import { deleteAdminShipment, fetchAllAdminShipment, createAdminShipment } from '../../redux/actions/adminShipmentActionCreator';
import ShipmentModalDelete from './ShipmentModalDelete.component';
const Shipment = ({
dispatchFetchAllAdminShipmentAction,
dispatchDeleteAdminShipment,
dispatchCreateAdminShipment,
adminShipments
}) => {
const [selected, setSelected] = useState();
const [shipmentName, setShipmentName] = useState('');
const [shipmentCost, setShipmentCost] = useState();
const history = useHistory();
const { addToast } = useToasts();
const handleBack = () => {
history.replace('/dashboard')
};
//redux load data
useEffect(() => {
dispatchFetchAllAdminShipmentAction()
}, [dispatchFetchAllAdminShipmentAction]);
const showModalDeleteShipment = (event, id) => {
event.preventDefault();
setSelected(id);
window.$('#modalDeleteShipment').modal('show');
};
const handleOnDelete = () => {
dispatchDeleteAdminShipment(selected, () => {
window.$('#modalDeleteStore').modal('hide');
addToast('Delete Store Successfully.', {appearance:'warning'});
}, (message) => {
window.$('#modalDeleteStore').modal('hide');
addToast(`Error: ${message}`, {appearance:'error'});
});
};
const handleOnSubmit = (event) => {
event.preventDefault();
const data = {shipmentName, shipmentCost}
dispatchCreateAdminShipment( data , () => {
dispatchFetchAllAdminShipmentAction()
addToast('Create Shipment Method Successfully.', {appearance:'success'});
setTimeout(()=> {
window.location.reload();
}, 1000)
}, (message) => {
addToast(`Error: ${message}`, {appearance:'error'});
});
};
return (
<div className="con-dashboard-right">
<header className="px-3">
<button className="back my-auto px-2 py-1" onClick={handleBack}>
<i className="fas fa-arrow-left mr-2"/>
Back
</button>
<h4>Shipment</h4>
</header>
<div className="con-right shipment p-4">
<div className="d-flex">
<h4>Shipping Method</h4>
<h4>Price</h4>
</div>
{adminShipments.map((shipment) => (
<div className="d-flex" key={shipment.id}>
<label>{shipment.shippingMethodName}</label>
<label>{shipment.shippingCost}</label>
<span onClick={(e) => showModalDeleteShipment(e, shipment.id)}>
<i className="fas fa-trash ml-3"/>
</span>
</div>
))}
<form className="d-flex" onSubmit={handleOnSubmit}>
<input
className="form-control"
placeholder="Shipping Method"
onChange={(e) => setShipmentName(e.target.value)} />
<input
className="form-control ml-3"
placeholder="Price"
onChange={(e) => setShipmentCost(parseFloat(e.target.value))} />
<button type="submit" className="add py-1 px-2 my-auto ml-3">Add</button>
</form>
</div>
<ShipmentModalDelete handleOnDelete={handleOnDelete}/>
</div>
)
}
const mapStateToProps = state => ({
adminShipments : state.adminShipments
});
const mapDispatchToProps = dispatch => ({
dispatchFetchAllAdminShipmentAction: () => dispatch(fetchAllAdminShipment()),
dispatchDeleteAdminShipment: (id, onSuccess, onError) =>
dispatch(deleteAdminShipment(id, onSuccess, onError)),
dispatchCreateAdminShipment: (data, onSuccess, onError) =>
dispatch(createAdminShipment(data, onSuccess, onError))
});
export default connect(mapStateToProps, mapDispatchToProps)(Shipment);
|
describe("TagCollection", function () {
var tags;
beforeEach(function () {
tags = new TagCollection();
});
});
|
import React from 'react';
import {TouchableOpacity, Text} from 'react-native';
import 'react-native-gesture-handler';
import {createStackNavigator} from '@react-navigation/stack';
import {SvgXml} from 'react-native-svg';
import SVG from '../components/SvgComponent';
import SignIn from '../screens/LoginTwoScreen';
import SignUp from '../screens/JoinScreen';
import InputChildInformation from '../screens/BabyPlusScreen';
import InputChildAllergyInformation from '../screens/BabyAlergyScreen';
import LoginTwoScreen from '../screens/LoginTwoScreen';
const Stack = createStackNavigator();
const SignStack = ({navigation}) => {
return (
<Stack.Navigator>
<Stack.Screen //홈화면
name="Login"
component={LoginTwoScreen}
options={({route}) => ({headerShown: false})}
/>
<Stack.Screen // 로그인
name="SignIn"
component={SignIn}
options={({route}) => ({headerShown: false})}
/>
<Stack.Screen // 회원가입
name="SignUp"
component={SignUp}
options={({route}) => JoinHeader(navigation)}
/>
<Stack.Screen // 아이정보
name="InputChildInformation"
component={InputChildInformation}
options={() => ({headerShown: false})}
/>
<Stack.Screen //아이엘레르기정보
name="InputChildAllergyInformation"
component={InputChildAllergyInformation}
options={({route}) => ({headerShown: false})}
/>
</Stack.Navigator>
);
};
const JoinHeader = (navigation) => ({
headerLeft: () => (
<TouchableOpacity
style={{marginLeft: 24}}
onPress={() => {
navigation.navigate('Login');
}}>
<SvgXml xml={SVG('BACKIOS')} />
</TouchableOpacity>
),
headerTitleAlign: 'center',
headerTitle: () => (
<Text style={{fontSize: 17}}>추가 계정 정보 입력하기</Text>
),
headerStyle: {
shadowOffset: {
height: 0,
},
elevation: 0,
},
});
export default SignStack;
|
let arr = [20, 15, 65, 2, 80, 250, 3];
function maxValue(arr) {
let result = Math.max(...arr); // for Arr works only with ...
console.log("max value = ", result);
let x = arr[0];
for (let i in arr) {
if (arr[i] > arr[i - 1]) { x = arr[i] }
}
console.log("max value = ", x);
}
maxValue(arr);
// function.length, function.name ======================================================
function func(a, b, l) {
return a + b;
}
console.log("function.length = " + func.length);
console.log("function.name = " + func.name);
// Functions are Objects ========================================
const modifiers = [
function(x) { return x + 7 },
function(x) { return x * 2 },
function(x) { return 42 }
];
modifiers.map(f => f(11))
.forEach(x => console.log(x));
// arguments ====================================================
const someFunc = function(a) {
console.log("arg1 + arg2 = " + (arguments[0] + arguments[1]));
console.log(arguments);
}
console.log("arguments ---------------------");
console.log("f.length = " + someFunc.length);
someFunc(15, 20, 30);
|
import http from 'http';
import app from './app';
import { setupWebSocket } from './websocket';
const PORT = process.env.PORT || 3333;
const server = http.Server(app);
setupWebSocket(server);
server.listen(PORT, () => console.log(`Server listening on PORT: ${PORT}`));
|
import React from 'react';
import s from './Time.module.css'
const Time = (props) => {
const hours = () => {
if (props.time.h === 0) return "";
else {
return (<span>{(props.time.h >= 10)? props.time.h: "0" + props.time.h}</span>);
}
}
return (
<div className={s.content}>
<h1>S T O P W A T C H</h1>
{hours()}
<span>{(props.time.m >= 10)? props.time.m: "0" + props.time.m}</span> :
<span>{(props.time.s >= 10)? props.time.s: "0" + props.time.s}</span> :
<span>{(props.time.ms >= 10)? props.time.ms: "0" + props.time.ms}</span>
</div>
);
}
export default Time;
|
const path = require('path');
const moduleResolverConfig = {
root: path.resolve('./'),
alias: {
'react-native-eva-icons': path.resolve(__dirname, '../lib'),
},
};
module.exports = function (api) {
api.cache(true);
const presets = [
'babel-preset-expo',
];
const plugins = [
['module-resolver', moduleResolverConfig],
];
return { presets, plugins };
};
|
const Operation = require("src/app/Operation");
class OrderTask extends Operation {
constructor({ tasksRepository }) {
super();
this.tasksRepository = tasksRepository;
}
async execute(bodyData) {
const { SUCCESS, NOT_FOUND, VALIDATION_ERROR, ERROR } = this.outputs;
try {
const data = {
...bodyData
};
const responseData = await this.tasksRepository.order(data);
if (responseData.message && responseData.message === "NotFoundError") {
return this.emit(NOT_FOUND, responseData);
} else {
this.emit(SUCCESS, responseData);
}
} catch (error) {
switch (error.message) {
case "ValidationError":
return this.emit(VALIDATION_ERROR, error);
case "NotFoundError":
return this.emit(NOT_FOUND, error);
default:
this.emit(ERROR, error);
}
}
}
}
OrderTask.setOutputs(["SUCCESS", "NOT_FOUND", "VALIDATION_ERROR", "ERROR"]);
module.exports = OrderTask;
|
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export let store=new Vuex.Store({
state:{
arr:["aa","cc","bb"]
}
})
|
/**
* First we will load all of this project's JavaScript dependencies which
* includes React and other helpers. It's a great starting point while
* building robust, powerful web applications using React + Laravel.
*/
Number.prototype.format = function(n, x) {
let re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
};
import './bootstrap';
/**
* Next, we will create a fresh React component instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
import toastr from 'toastr/toastr';
window.toastr = toastr;
window.toastr.options = {
positionClass: "toast-bottom-right",
};
import './react';
|
"use strict";
const Env = use('Env');
/*
|--------------------------------------------------------------------------
| Adonis Auth Scaffold
|--------------------------------------------------------------------------
|
| Adonis Auth Scaffold is a CLI utility that gives you a functional authentication
| system in Adonis.js within seconds.
|
*/
module.exports = {
/*
|--------------------------------------------------------------------------
| Registration Route
|--------------------------------------------------------------------------
|
| Specifies the route to handle registration GET and POST requests.
|
*/
registrationRoute: "/register",
/*
|--------------------------------------------------------------------------
| Registration Success Redirect Route
|--------------------------------------------------------------------------
|
| Specifies the route to redirect the user to upon successful registration.
| Leave empty if you do not want any redirects.
|
*/
registrationSuccessRedirectTo: "/auth/dashboard",
/*
|--------------------------------------------------------------------------
| Login Route
|--------------------------------------------------------------------------
|
| Specifies the route to handle login GET and POST requests.
|
*/
loginRoute: "/login",
/*
|--------------------------------------------------------------------------
| Password Reset Route
|--------------------------------------------------------------------------
|
| Specifies the route to handle password reset GET and POST requests.
|
*/
passwordResetRoute: "/password/reset",
/*
|--------------------------------------------------------------------------
| Logout Route
|--------------------------------------------------------------------------
|
| Specifies the route to handle logout GET and POST requests.
|
*/
logoutRoute: "/logout",
/*
|--------------------------------------------------------------------------
| App URL
|--------------------------------------------------------------------------
|
| Specifies the URL for the app.
|
*/
appURL: "http://localhost:3333",
/*
|--------------------------------------------------------------------------
| Registration Rules
|--------------------------------------------------------------------------
|
| An object of validation rules to be used when running validation.
|
*/
validationRules: {
registration: {
email: "required|email",
username: "required",
password: "required",
password_confirmation: "required|same:password"
}
},
/*
|--------------------------------------------------------------------------
| Validation messages
|--------------------------------------------------------------------------
|
| An object of validation messages to be used when validation fails.
|
*/
validationMessages: action => {
return {
"uid.required": "Username or E-mail must be filled.",
"username.required": "Username must be filled.",
"email.required": "E-mail must be filled.",
"email.email": "Please use a valid e-mail address.",
"password.required": "Password must be filled.",
"password.mis_match": "Invalid password.",
"password_confirmation.same": `Password confirmation must be same as password.`
};
}
};
|
import { OAuth2Strategy as GoogleStrategy } from 'passport-google-oauth';
export default function ({ passport, login }) {
// https://github.com/jaredhanson/passport-google-oauth2
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: '/login/google/return',
passReqToCallback: true,
}, async (req, accessToken, refreshToken, profile, done) => {
try {
const user = await login(req, 'google', profile, { accessToken, refreshToken });
done(null, user);
} catch (err) {
done(err);
}
}));
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _preventEventDefault = require('./preventEventDefault');
var _preventEventDefault2 = _interopRequireDefault(_preventEventDefault);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
if (typeof exports !== 'undefined') Object.defineProperty(exports, 'babelPluginFlowReactPropTypes_proptype_PointerSurfaceProps', {
value: require('prop-types').shape({
active: require('prop-types').bool,
children: require('prop-types').any,
className: require('prop-types').string,
disabled: require('prop-types').bool,
id: require('prop-types').string,
onClick: require('prop-types').func,
onMouseEnter: require('prop-types').func,
style: require('prop-types').object,
title: require('prop-types').string,
value: require('prop-types').any
})
});
var PointerSurface = function (_React$PureComponent) {
(0, _inherits3.default)(PointerSurface, _React$PureComponent);
function PointerSurface() {
var _ref;
var _temp, _this, _ret;
(0, _classCallCheck3.default)(this, PointerSurface);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = PointerSurface.__proto__ || (0, _getPrototypeOf2.default)(PointerSurface)).call.apply(_ref, [this].concat(args))), _this), _this._clicked = false, _this._mul = false, _this._pressedTarget = null, _this._unmounted = false, _this.state = { pressed: false }, _this._onMouseEnter = function (e) {
_this._pressedTarget = null;
e.preventDefault();
var _this$props = _this.props,
onMouseEnter = _this$props.onMouseEnter,
value = _this$props.value;
onMouseEnter && onMouseEnter(value, e);
}, _this._onMouseLeave = function (e) {
_this._pressedTarget = null;
var mouseUpEvent = e;
_this._onMouseUpCapture(mouseUpEvent);
}, _this._onMouseDown = function (e) {
e.preventDefault();
_this._pressedTarget = null;
_this._clicked = false;
if (e.which === 3 || e.button == 2) {
// right click.
return;
}
_this.setState({ pressed: true });
_this._pressedTarget = e.currentTarget;
_this._clicked = false;
if (!_this._mul) {
document.addEventListener('mouseup', _this._onMouseUpCapture, true);
_this._mul = true;
}
}, _this._onMouseUp = function (e) {
e.preventDefault();
if (_this._clicked || e.type === 'keypress') {
var _this$props2 = _this.props,
_onClick = _this$props2.onClick,
_value = _this$props2.value,
_disabled = _this$props2.disabled;
!_disabled && _onClick && _onClick(_value, e);
}
_this._pressedTarget = null;
_this._clicked = false;
}, _this._onMouseUpCapture = function (e) {
if (_this._mul) {
_this._mul = false;
document.removeEventListener('mouseup', _this._onMouseUpCapture, true);
}
var target = e.target;
_this._clicked = _this._pressedTarget instanceof HTMLElement && target instanceof HTMLElement && (target === _this._pressedTarget || target.contains(_this._pressedTarget) || _this._pressedTarget.contains(target));
_this.setState({ pressed: false });
}, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
}
(0, _createClass3.default)(PointerSurface, [{
key: 'render',
value: function render() {
var _props = this.props,
className = _props.className,
disabled = _props.disabled,
active = _props.active,
id = _props.id,
style = _props.style,
title = _props.title,
children = _props.children;
var pressed = this.state.pressed;
var buttonClassName = (0, _classnames2.default)(className, {
active: active,
disabled: disabled,
pressed: pressed
});
return _react2.default.createElement(
'span',
{
'aria-disabled': disabled,
'aria-pressed': pressed,
className: buttonClassName,
disabled: disabled,
id: id,
onKeyPress: disabled ? _preventEventDefault2.default : this._onMouseUp,
onMouseDown: disabled ? _preventEventDefault2.default : this._onMouseDown,
onMouseEnter: disabled ? _preventEventDefault2.default : this._onMouseEnter,
onMouseLeave: disabled ? null : this._onMouseLeave,
onMouseUp: disabled ? _preventEventDefault2.default : this._onMouseUp,
role: 'button',
style: style,
tabIndex: disabled ? null : 0,
title: title
},
children
);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this._unmounted = true;
if (this._mul) {
this._mul = false;
document.removeEventListener('mouseup', this._onMouseUpCapture, true);
}
}
}]);
return PointerSurface;
}(_react2.default.PureComponent);
exports.default = PointerSurface;
|
window.GameManager = (function () {
var currentTurn = Piece.BLACK; // black goes first
var player1, player2, board;
function GameManager() {}
GameManager.prototype.setupGame = function () {
board = new Board();
player1 = new Player({color: Piece.BLACK});
player2 = new Player({color: Piece.RED});
};
GameManager.prototype.renderGame = function () {
var container = document.querySelector('.board-container');
container.innerHTML = '';
container.appendChild(board.render());
};
return new GameManager();
})();
|
const net = require('net');
const PORT = process.env.PORT || 3000;
const MAX_HISTORY = process.env.MAX_HISTORY || 20;
const history = [];
const server = net.createServer(connection => {
connection.on('data', data => {
const req = decodeHttpRequest(data);
const res = sendHttpResponse(connection, {
headers: {
"Access-Control-Allow-Origin": "*"
}
});
if (!req) return;
switch (req.endpoint) {
case "/history":
return onHistoryRequest(req, res);
default:
onDefaultRequest(req, res);
}
onRequest(req, res)
})
connection.on('error', error => logError(error.message))
})
server.on('error', error => logError(error.message))
server.listen(PORT);
logInfo(`tcp-echo server started on port ${PORT}`);
// REQUEST HANDLERS
function onHistoryRequest (req, res) {
const searchQuery = req.query.search;
const body = history
.filter(e => searchQuery ? new RegExp(searchQuery).test(e.rawData) : true);
if (acceptsJson(req)) {
res({ json: body })
} else {
res({ text: body.map(e => e.rawData).join("\n\n\n") })
}
}
function onDefaultRequest (req, res) {
if (acceptsJson(req)) {
res({ json: req })
} else {
res({ text: req.rawData })
}
// store current request data to history
logHistory(req);
}
function onRequest (req, res) {
// log every incoming message to stdout
process.stdout.write(req.rawData + '\n\n')
}
// UTILITY FUNCTIONS
function logHistory (data) {
if (history.length > MAX_HISTORY) {
history.splice(0, 1);
}
history.push(data);
}
function sendHttpResponse (connection, defaultOptions) {
return function (options) {
const merge = key => ({...defaultOptions[key], ...options[key]});
const mergedOptions = {
headers: merge("headers"),
...options
}
connection.write(encodeHttpRequest(mergedOptions))
connection.end();
}
}
function encodeHttpRequest ({ text = '', json, code = 200, headers = {} }) {
const headersStr = Object.keys(headers)
.map(e => `${e}: ${headers[e]}`)
.join("\n");
const body = json ? JSON.stringify(json) : text;
return `HTTP/1.1 ${code} OK` +
(headersStr.length > 0 ? `\n${headersStr}` : '') +
"\n\n" +
body;
}
function decodeHttpRequest (data) {
const strData = data.toString();
const httpMatch = strData.match(/ HTTP/);
if (!httpMatch) {
// not a valid HTTP request
return null;
}
const bodySeparatorIndex = strData.indexOf("\n\n");
const [initialLine, ...headerLines] = strData
// take whole string if body separator isn't found (there is no body)
.substring(0, bodySeparatorIndex < 0 ? strData.length : bodySeparatorIndex)
.split("\n");
const [method, path, protocol] = initialLine.split(" ");
const headers = headerLines
.map(e => {
const [key, value] = e.split(": ");
if (!(key && value)) return null;
return { key, value: parseKeyValue(value) };
})
.filter(e => !!e)
.reduce((p, c) => ({ ...p, [c.key]: c.value }), {});
const [endpoint, queryStr] = path.split("?")
const query = queryStr
? queryStr
.split("&")
.filter(e => !!e) // include only non-empty values
.map(e => {
const [key, value] = e.split("=");
return { key, value: parseKeyValue(value) }
})
.reduce((p, c) => ({ ...p, [c.key]: c.value }), {})
: {};
return { method, path, endpoint, query, protocol, headers, rawData: strData };
}
function parseKeyValue (value) {
const strValue = value.trim();
const numberValue = parseFloat(strValue);
const isNumber = !Number.isNaN(numberValue);
const parsedStrValue = strValue.includes(",")
? strValue.split(",").map(e => e.trim()).filter(e => !!e)
: strValue;
return isNumber ? numberValue : parsedStrValue;
}
function acceptsJson (req) {
// may have multiple values seperated by comma
// text/html,application/xhtml+xml,application/xml
const accept = req.headers["Accept"];
return accept instanceof Array
? accept.findIndex(e => equalsIgnoreCase(e, "application/json"))
: accept === '*/*';
}
function equalsIgnoreCase (a, b) {
return a.toLowerCase() === b.toLowerCase();
}
// LOGGER FUNCTIONS
function logInfo (message) {
process.stdout.write(`[INFO]: ${message}\n`);
}
function logError (message) {
process.stderr.write(`[ERROR]: ${message}\n`);
}
|
var input = document.getElementById("input-message");
input.value = ""
control = true
function getIdAndName() {
let cookies = document.cookie.split(';');
let list = []
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].split("=")
if (cookie[0] == "chatId") {
list[0] = cookie[1]
} else if (cookie[0] == " name") {
list[1] = cookie[1]
}
}
return list;
}
var data = getIdAndName()
var id = data[0]
var userName = data[1]
var ws;
function init() {
if (ws) {
ws.onerror = ws.onopen = ws.onclose = null;
ws.close();
}
ws = new WebSocket('ws://localhost:9001');
ws.onopen = () => {
console.log('Connection opened!');
ws.send(JSON.stringify({"message": '', "userName": userName, "chatId": id}))
}
ws.onmessage = ({ data }) => {
let json = JSON.parse(data)
addMessage(json.userName, json.message, 2);
}
ws.onclose = function() {
ws = null;
}
}
init();
input.addEventListener("keyup", (event) => {
if (event.key === "Enter") {
event.preventDefault();
let msg = input.value
addMessage(userName, msg, 1)
let to_send = {"message": msg, "userName": userName, "chatId": id}
if (!ws) {
console.log("No WebSocket connection :(")
return
}
ws.send(JSON.stringify(to_send));
input.value = ""
}
})
function addMessage(actor, message, user) {
var element = document.createElement("div")
element.style.backgroundColor = "white"
element.innerHTML = message
element.style.color = 'black'
element.style.maxWidth = "50%"
element.style.width = "max-content"
element.style.padding = "5px"
element.style.margin = "5px"
element.style.borderRadius = "5px"
element.style.fontSize = "18px"
element.style.clear = "both"
element.style.wordWrap = "break-word"
var n = document.createElement("div")
n.style.backgroundColor = "white"
n.innerHTML = actor
n.style.color = 'black'
n.style.width = "max-content"
n.style.padding = "5px"
n.style.borderRadius = "5px"
n.style.fontSize = "14px"
n.style.backgroundColor = "white"
if (user == 1) {
element.style.float = "left"
n.style.backgroundColor = "MediumSlateBlue"
} else {
element.style.float = "right"
element.style.backgroundColor = "MediumSlateBlue"
}
element.insertBefore(n, element.firstChild);
var messages = document.getElementsByClassName("messages")[0]
messages.appendChild(element)
messages.scrollTop = messages.scrollHeight;
}
|
(function (){
/**
* directive set focus on the field
*/
angular.module('Authentication' )
.directive('autofocus', focusMe)
focusMe.$inject = ['$timeout']
function focusMe($timeout){
return {
link: function($scope, $element){
$timeout(function(){
$element[0].focus();
});
}
}
}
})();
|
let HTML = "";
let lentele = document.querySelector('.table-content');
let income = document.querySelector('.income');
let expense = document.querySelector('.expense');
let balance = document.querySelector('.balance');
let NewAccount = [];
let income_total = 0;
let expense_total = 0;
let minExpensesCount = Infinity;
let minIncomeCount = Infinity;
let maxIncomeCount = 0;
let maxExpensesCount = 0;
function getData(account, men) {
if (Array.isArray(account)) {
for (let i = 0; i < account.length; i++) {
for (let x = 0; x < account.length; x++) {
if (account[x].month === i + 1) {
NewAccount.push(account[x]); //<-- Supushint viska eiles tvarka
}
}
}
for (let i = 0; i < NewAccount.length; i++) {
if (NewAccount[i].income == undefined) {
NewAccount[i].income = 0
}
if (NewAccount[i].income > maxIncomeCount && NewAccount[i].income !== 0) {
maxIncomeCount = NewAccount[i].income; //<-- Be infinity neranda max/min dar galima naudoti Math.max/min
maxIncome.innerHTML = men[i];
}
if (NewAccount[i].income < minIncomeCount && NewAccount[i].income !== 0) {
minIncomeCount = NewAccount[i].income;
minIncome.innerHTML = men[i];
}
if (NewAccount[i].expense == undefined) {
NewAccount[i].expense = 0
}
if (NewAccount[i].expense > maxExpensesCount && NewAccount[i].expense !== 0) {
maxExpensesCount = NewAccount[i].expense;
maxExpenses.innerHTML = men[i];
}
if (NewAccount[i].expense < minExpensesCount && NewAccount[i].expense !== 0) {
minExpensesCount = NewAccount[i].expense;
minExpenses.innerHTML = men[i];
}
income_total += NewAccount[i].income;
expense_total += NewAccount[i].expense;
HTML += `<div class="table-row">
<div class="cell">${NewAccount[i].month}</div>
<div class="cell">${men[i]}</div>
<div class="cell">${NewAccount[i].income} Eur</div>
<div class="cell">${NewAccount[i].expense} Eur</div>
<div class="cell">${NewAccount[i].income - NewAccount[i].expense} Eur</div>
</div>`;
}
lentele.innerHTML = HTML;
income.innerHTML = income_total + ' EUR';
expense.innerHTML = expense_total + ' EUR';
balance.innerHTML = income_total - expense_total + ' EUR';
}
}
getData(account, men);
|
import config from "../config"
import axios from "axios"
const mutation = {
async guest(){
const res = await axios.post(`${config.API_URL}/auth/guest`, {})
return res.data
}
}
const query = {
}
export default {
mutation,
query
}
|
import React, { useReducer } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Button, TextField, Typography } from '@material-ui/core';
import { loginUser } from '../reducers/loginReducer';
import { notify } from '../reducers/notificationReducer';
import Message from './Message';
const Login = () => {
const [loginInput, setLoginInput] = useReducer(
(state, newState) => ({ ...state, ...newState }),
{
username: '',
password: '',
}
);
const notificationSelector = useSelector(({ notification }) => notification);
const dispatch = useDispatch();
const handleInputChange = (event) => {
const { name, value } = event.target;
setLoginInput({ [name]: value });
};
const handleLogin = async (event) => {
event.preventDefault();
try {
await dispatch(loginUser(loginInput));
setLoginInput({ username: '', password: '' });
dispatch(
notify({ type: 'success', content: 'Successfully logged in' }, 5000)
);
} catch (error) {
dispatch(notify({ type: 'error', content: 'Wrong credentials' }, 5000));
}
};
return (
<div>
<Typography variant="h2">Log in to application</Typography>
<Message message={notificationSelector} />
<form onSubmit={handleLogin}>
<TextField
value={loginInput.username}
label="username"
name="username"
onChange={handleInputChange}
/>
<TextField
style={{ marginLeft: 10 }}
type="password"
value={loginInput.password}
label="password"
name="password"
onChange={handleInputChange}
/>
<Button style={{ marginLeft: 10 }} variant="outlined" type="submit">
login
</Button>
</form>
</div>
);
};
export default Login;
|
const landmarks = [
{
name: "Colosseum",
image: "./images/colosseum.jpg",
URL: "https://www.rome.net/colosseum"
},
{
name: "Cathedral of Santa Maria del Fiore",
image: "./images/Cathedral.jpg",
URL: "http://www.museumsinflorence.com/musei/cathedral_of_florence.html"
},
{
name: "Pantheon",
image: "./images/pantheon.jpg",
URL: "https://www.italyguides.it/en/lazio/rome/ancient-rome/pantheon"
},
{
name: "Trevi Fountain",
image: "./images/treviFountain.jpg",
URL: "https://www.rome.net/trevi-fountain"
},
{
name: "Leaning Tower of Pisa",
image: "./images/leaningtower.jpg",
URL: "http://www.towerofpisa.org/"
},
]
export const landmarksCopy = () => {
return landmarks.slice()
}
|
import styled from 'styled-components';
export const TotalContainer = styled.div`
height: auto;
width: 1300px;
`;
export const MainContentContainer = styled.div`
display: flex;
justify-content: center;
height: auto;
width: 1280px;
min-height: 500px;
max-height: 1186px;
`;
export const LeftContainer = styled.div`
flex-direction: column;
align-items: center;
width: 680px;
`;
export const RightContainer = styled.div`
flex-direction: column;
width: 550px;
margin-left: 40px;
`;
export const ImageContainer = styled.div`
width: 680px;
position: relative;
`;
export const CommentButton = styled.button`
font-family: Noto Sans KR;
font-style: normal;
font-weight: normal;
font-size: 18px;
line-height: 26px;
display: flex;
align-items: center;
width: 54px;
color: #ff534b;
background: none;
border: none;
marginleft: 20px;
outline: none;
justify-content: flex-end;
margin-left: 20px;
cursor: pointer;
`;
export const LeftBottomContainer = styled.div`
position: absolute;
left: 12px;
bottom: 10px;
display: flex;
align-items: center;
`;
export const TextBox = styled.label`
font-style: normal;
font-weight: 500;
font-size: 18px;
line-height: 26px;
color: #ffffff;
`;
export const LeftTopContainer = styled.div`
position: absolute;
top: 15px;
left: 20px;
display: flex;
align-items: center;
`;
export const Countbox = styled.p`
font-weight: 500;
font-size: 24px;
line-height: 35px;
display: flex;
align-items: center;
color: #ffffff;
`;
export const RightBottomContainer = styled.div`
position: absolute;
bottom: 12px;
right: 12px;
display: flex;
align-items: center;
`;
export const RightTopContainer = styled.div`
position: absolute;
top: 15px;
right: 12px;
display: flex;
align-items: center;
`;
export const CommentBox = styled.div`
::-webkit-scrollbar {
display: none;
}
`;
|
import React from "react";
import { NavLink } from "react-router-dom";
class Reports extends React.Component {
render() {
return (
<NavLink to="/reports" activeClassName="active-area">
<div className="reports-area">
<i className="material-icons">assessment</i>
<span>Reports</span>
</div>
</NavLink>
);
}
}
export default Reports;
|
$(document).ready(function () {
var name= $('input[name="name"').val()
console.log(name)
if (name.length>0) {
$('button').prop("disabled", false);
$('#form').submit(function (e) {
e.preventDefault();
var usuario = {
"name": $('input[name="name"').val(),
"web": $('input[name="web"').val()
}
$.post($(this).attr("action"), usuario, function (response) {
console.log(response)
}).done(function () {
alert("usuario añadido")
})
return false;
});
}
else{
alert("esta vacío")
$('button').prop("disabled", true);
}
})
|
/** @jsx React.DOM */
var postsData = [
{
title: 'woah',
body: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod'
},
{
title: 'oh baby guuurl',
body: 'Lorem ipsum dolor sit amet, jk i mean hes a fag elit, sed do eiusmod'
},
{
title: 'mmhmm',
body: 'omg, jake is such a faaaaaaaantastic guy elit, sed do eiusmod'
}
];
var posts = React.createClass({
getInitialState: function() {
return {data: postsData};
},
addPost: function(post) {
this.state.data.push(post);
this.setState({data: this.state.data})
},
render: function() {
var listOfPosts = this.state.data.map(function(individualPost) {
return (
<post data={individualPost} />
)
});
return (
<div>
<addPostForm submitPost={this.addPost}/>
{listOfPosts}
</div>
)
}
});
var post = React.createClass({
getInitialState: function() {
return {
data: {upvotes:0, downvotes:0}
}
},
upvote: function() {
this.state.data.upvotes++;
this.setState({
data: this.state.data
})
},
downvote: function() {
this.state.data.upvotes--;
this.setState({
data: this.state.data
})
},
render: function() {
return (
<div>
<h1>{this.props.data.title}</h1>
<p>
{this.props.data.body}
</p>
<div>
<span>karma: {this.state.data.upvotes}</span>
<button onClick={this.upvote}>
⤴
</button>
<button onClick={this.downvote}>
⤵
</button>
</div>
<div>
<comments />
</div>
</div>
)
}
});
var comments = React.createClass({
getInitialState: function() {
return {data: []}
},
addComment: function(comment) {
this.state.data.push(comment);
this.setState({data: this.state.data});
},
render: function() {
var listOfComments = this.state.data.map(function(individualComment) {
return (
<comment data={individualComment} />
);
})
return (
<div>
<div>
<addCommentForm submitComment={this.addComment} />
</div>
<div>
{listOfComments}
</div>
</div>
)
}
});
var comment = React.createClass({
getInitialState: function() {
return {
data: {upvotes:0, downvotes:0}
}
},
upvote: function() {
this.state.data.upvotes++;
this.setState({
data: this.state.data
})
},
downvote: function() {
this.state.data.upvotes--;
this.setState({
data: this.state.data
})
},
render: function() {
return (
<div>
<p>
{this.props.data.body}
</p>
<i>{this.props.data.author}</i>
<div>
<span>karma: {this.state.data.upvotes}</span>
<button onClick={this.upvote}>
⤴
</button>
<button onClick={this.downvote}>
⤵
</button>
</div>
</div>
)
}
});
var addPostForm = React.createClass({
submitPostForm: function(e) {
e.preventDefault();
var title = this.refs.title.getDOMNode().value;
var body = this.refs.body.getDOMNode().value;
this.props.submitPost({
title: title,
body: body
})
this.refs.title.getDOMNode().value = '';
this.refs.body.getDOMNode().value = '';
},
render: function() {
return (
<form>
<input type='text' ref="title" placeholder="title" /><br />
<textarea type='text' ref="body" placeholder="body" rows="8" cols="90"></textarea><br />
<input type='submit' onClick={this.submitPostForm}/>
</form>
)
}
})
var addCommentForm = React.createClass({
submitCommentForm: function(e) {
e.preventDefault();
var body = this.refs.body.getDOMNode().value;
var author = this.refs.author.getDOMNode().value;
this.props.submitComment({
body: body,
author: author
})
this.refs.body.getDOMNode().value = '';
this.refs.author.getDOMNode().value = '';
},
render: function() {
return (
<form>
<textarea type='text' ref="body" placeholder="comment" rows="8" cols="90"></textarea><br />
<input type='text' ref="author" placeholder="name" /><br />
<input type='submit' onClick={this.submitCommentForm}/>
</form>
)
}
});
React.renderComponent(
<posts />,
document.getElementById('content')
);
|
var waitLoadingdots;
var foundCountTo1;
class Wait extends React.Component {
constructor(props) {
super(props);
this.state = {
dots: '.',
count: 3,
countFired: false,
}
}
componentDidMount() {
function addDot(state) {
var dots = state.dots;
if (dots.length >= 3) {
dots = '.';
}
else {
dots = dots + '.';
}
return { dots: dots };
}
waitLoadingdots = setInterval(()=>{
this.setState((state)=>{return addDot(state);});
}, 1000);
}
componentWillUnmount() {
clearInterval(waitLoadingdots);
}
countDown = ()=>{
if ( this.state.countFired == true ) return;
function countTo1(state, toRoom) {
var count = state.count;
if (count <= 0) {
clearInterval(foundCountTo1);
toRoom();
}
else {
if (count == 1) {
document.querySelector('.wait').classList.add('disappearFadeOut');
document.querySelector('#foundTagline').classList.add('disappearFadeOut');
}
count = count - 1
}
return { count: count };
}
foundCountTo1 = setInterval(()=>{
this.setState((state)=>{return countTo1(state, this.props.goToRoom);});
}, 1500);
// ensure setInterval fired only once
this.setState({countFired: true});
}
componentDidUpdate() {
if (this.props.found == true) {
this.countDown();
}
}
render() {
var found = this.props.found;
var textCircle;
var waitTagline;
if (found === false) {
textCircle = 'Waiting';
let text = <p>Looking for other person{this.state.dots}</p>;
waitTagline = <div id="waitTagline">{text}</div>;
}
else {
textCircle = 'Found!';
let text = <p>Random topic of the day</p>;
let generatedWord = <p>{this.props.word}</p>;
let countToRoom = <p>Initiating conversation in {this.state.count}{this.state.dots}</p>;
waitTagline = <div id="foundTagline">{text}{generatedWord}{countToRoom}</div>;
let newAnimation = 'foundGreenPulse 2s ease-out forwards';
document.querySelector('#waitCircle').style.animation = newAnimation;
}
return (
<React.Fragment>
<div className="wait">
<div>
<span>{textCircle}</span>
</div>
<svg width="200" height="200">
<circle id="waitCircle" cx="100" cy="100" r="70"/>
</svg>
</div>
{waitTagline}
</React.Fragment>
);
}
}
|
let coucou = 123;
console.log(coucou);
var hey = coucou;
alert(hey)
|
import React, {Component, Fragment} from 'react';
import styled from 'styled-components';
import {Add} from '@material-ui/icons';
import {Button} from '@material-ui/core';
const ButtonStyled = styled(Button)`
margin: 0 ${({theme}) => theme.spacing}px ${({theme}) => theme.spacing}px 0 !important;
`;
export default class CreateCard extends Component {
constructor(props) {
super(props);
this.state = {
number: 1,
sides: 20
};
}
handleAdd = () => {
this.props.handleCreate(this.state);
};
render() {
return (
<Fragment>
<ButtonStyled onClick={this.handleAdd} variant="outlined">
<Add />
</ButtonStyled>
</Fragment>
);
}
}
|
_.isPlainObject = function(value){
}
|
import { makeStyles, Paper } from '@material-ui/core'
import React, { useState } from 'react'
import DataTable from '../../display/DataTable';
import PopModal from '../../display/PopModal';
import AddBtn from '../../input/AddBtn';
import DeleteBtn from '../../input/DeleteBtn';
import EditBtn from '../../input/EditBtn';
const useStyle = makeStyles((theme) => ({
paper: {
backgroundColor: '#999999',
padding: theme.spacing(2),
},
buttons: {
display: 'flex',
width: '100%',
},
btnSpace: {
marginRight: theme.spacing(1),
},
btnGray: {
backgroundColor: "#595959",
color: '#fff',
'&:hover': {
background: "#333333",
},
},
selectType: {
width: '25ch',
marginTop: theme.spacing(2)
// minWidth: 80
},
}))
function Result() {
const classes = useStyle()
const [open, setOpen] = useState(false)
const [header, setHeader] = useState('')
const showModal = (value) => {
open ? setHeader('') : setHeader(value + ' EXAM')
setOpen(!open)
}
const headCells = [
{ id: 'id', label: 'ID' },
{ id: 'desc', label: 'DESCRIPTION' },
{ id: 'subject', label: 'SUBJECT' },
{ id: 'numQ', label: 'No. Question' },
{ id: 'type', label: 'Type' },
{ id: 'status', label: 'STATUS' },
];
function createData(id, subject, desc, numQ, type, status) {
return { id, subject, desc, numQ, type, status };
}
const rows = [
createData(1, 'Hospitaly', 'First Test for hospitality', 30, 'Test', 'Finished'),
createData(2, 'Management', 'Short quiz', 10, 'Quiz', 'Finished'),
createData(3, 'Accounting', 'Short quiz', 20, 'Quiz', 'Finished'),
createData(4, 'Tourism', 'Midterm Exam', 50, 'Exam', 'On Going'),
createData(5, 'Culinary', '', 10, 'Quiz', 'Finished'),
createData(6, 'Kitchen Essentials', 'Simple Test', 30, 'Test', 'On Going'),
];
return (
<Paper className={classes.paper}>
<div className={classes.buttons}>
<AddBtn classes={classes} addBtnfx={showModal} />
<EditBtn classes={classes} editBtnfx={showModal} />
<DeleteBtn classes={classes} deleteBtnfx={showModal} />
</div>
{/* <Selector classes={classes} /> */}
<DataTable headCells={headCells} rows={rows} />
<PopModal status={open} showModalfx={showModal} header={header} />
</Paper>
)
}
export default Result
|
import ProceduresBanner from "./components/proceduresBanner";
import ProceduresSection1 from "./components/procedures-section1";
import Layout from "./layout/layout";
export default function Procedures() {
return (
<Layout>
<ProceduresBanner />
<ProceduresSection1 />
</Layout>
);
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DateTypes = void 0;
// Type of dates needed.
var DateTypes;
(function (DateTypes) {
DateTypes[DateTypes["DayOfWeek"] = 0] = "DayOfWeek";
DateTypes[DateTypes["Date"] = 1] = "Date";
})(DateTypes = exports.DateTypes || (exports.DateTypes = {}));
|
import path from 'path';
import ts from 'rollup-plugin-typescript2';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
const pkg = require('./package.json');
const banner = `/*!
* ${pkg.name} v${pkg.version}
* (c) ${new Date().getFullYear()} SuYan
* @license MIT
* @more https://lefex.gitee.io
*/`;
// all the module for build
const modules = {
// each file name has the format: `dist/${name}.${format}.js`
// format being a key of this object
'esm-bundler': {
file: pkg.module,
format: 'es'
},
cjs: {
file: pkg.main,
format: 'cjs'
},
global: {
file: pkg.unpkg,
format: 'iife'
},
esm: {
file: pkg.browser || pkg.module.replace('bundler', 'browser'),
format: 'es'
}
};
let hasTSChecked = false;
const allFormats = Object.keys(modules);
const packageFormats = allFormats;
const packageConfigs = packageFormats.map(format =>
createConfig(format, modules[format])
);
// only add the production ready if we are bundling the options
packageFormats.forEach(format => {
if (format === 'cjs') {
packageConfigs.push(createProductionConfig(format));
}
else if (format === 'global') {
packageConfigs.push(createMinifiedConfig(format));
}
});
function createConfig(format, output, plugins = []) {
output.sourcemap = !!process.env.SOURCE_MAP;
output.banner = banner;
output.externalLiveBindings = false;
output.globals = {
sytask: 'SyTask'
};
const isGlobalBuild = format === 'global';
if (isGlobalBuild) {
output.name = 'SYTask';
};
const shouldEmitDeclarations = !hasTSChecked;
const tsPlugin = ts({
check: !hasTSChecked,
tsconfig: path.resolve(__dirname, 'tsconfig.json'),
cacheRoot: path.resolve(__dirname, 'node_modules/.rts2_cache'),
tsconfigOverride: {
compilerOptions: {
sourceMap: output.sourcemap,
declaration: shouldEmitDeclarations,
declarationMap: shouldEmitDeclarations
},
exclude: ['__tests__']
}
});
// we only need to check TS and generate declarations once for each build.
// it also seems to run into weird issues when checking multiple times
// during a single build.
hasTSChecked = true;
const nodePlugins = [resolve(), commonjs()];
return {
input: 'src/index.ts',
plugins: [
tsPlugin,
...nodePlugins,
...plugins
],
output
};
}
function createProductionConfig(format) {
return createConfig(format, {
file: `dist/${pkg.name}.${format}.prod.js`,
format: modules[format].format
});
}
function createMinifiedConfig(format) {
// mini
const {terser} = require('rollup-plugin-terser');
return createConfig(
format,
{
file: `dist/${pkg.name}.${format}.prod.js`,
format: modules[format].format
},
[
terser({
module: /^esm/.test(format),
compress: {
ecma: 2015,
pure_getters: true
}
})
]
);
}
export default packageConfigs;
|
(function() {
"use strict";
function Data(){
this.original = [
{"item":"a","percent":[4,5,10,11],"rowStyle":"dark","terjedelem":[-100,100],"dimension":["just for test","of people never do anykind of test","of people rarely test something","of people frequently test something","of people are always testing"]},
{"item":"b","percent":[7,8,35,50],"rowStyle":"light","terjedelem":[-100,100],"dimension":["I'd recommend this program to a friend.","hate it","have forgot it","probably don't forget","definitely do"]},
{"item":"c","percent":[10,15,30,45],"rowStyle":"dark","terjedelem":[-100,100],"dimension":["I learned a lot in this program.","slept like a log","learnt nothing new","become better people","take a new lease on life"]},
{"item":"d","percent":[20,25,25,30],"rowStyle":"light","terjedelem":[-100,100],"dimension":["This program exceeded my expectations.","wish they have never fallen into line","didn't find anything new","were surprised","want to make it again"]},
{"item":"e","percent":[50,50,50,50],"rowStyle":"dark","terjedelem":[-100,100],"dimension":["Likert choices (4-point)","Strongly disagree","Disagree","Strongly agree","Agree"]}
]
}
function TransformData(){
}
var getData = new Data();
var data = getData.original;
function LikertEven() {
var myLikertEven = d3.select("#LikertEven").chart("LikertEvens", {
seriesCount: data.length
});
myLikertEven.margin({ top: 0, right: 240, bottom: 5, left: 10 })
.width([600])
.height([40])
.axisStyle("axis")
.duration(1000);
myLikertEven.draw(data);
d3.selectAll("button#Randomize").on("click", function() {
d3.selectAll(".textResult").remove();
d3.selectAll(".textResultKiem").remove();
var length = data.length,
row = null;
for (var i = 0; i < length-1; i++) {
row = data[i];
randomizeLikert(row.percent);
}
myLikertEven.draw(data);
});
d3.selectAll("button#Reset").on("click", function() {
d3.selectAll(".textResult").remove();
d3.selectAll(".textResultKiem").remove();
getData = new Data();
data = getData.original;
myLikertEven.draw(data);
});
}
function randomizeLikert(d) {
var total = 100;
if (!d.randomizer) d.randomizer = randomizer(d);
d[3] = d.randomizer(d[3],0,50);
total -= d[3];
d[2] = d.randomizer(d[2],0,total+1);
total -= d[2];
d[1] = d.randomizer(d[1],0,total+1);
total -= d[1];
d[0] = total;
return d;
}
// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomizer(d,min,max) {
return function(d,min,max) {
return getRandomInt(min,max);
};
}
LikertEven();
})();
|
import styled from 'styled-components';
export const IngredientsStyle = styled.div`
margin-top: 2rem;
text-align: center;
h1 {
font-size: 1.3rem;
font-weight: 300;
line-height: 1.2;
margin-bottom: 1rem;
color: var(--primary-color);
text-align: center;
text-transform: uppercase;
@media (max-width: 700px) {
font-size: 1.1rem;
}
}
div {
background-color: var(--secondary-color);
color: var(--light-color);
width: 100vw;
grid-column: 1/-1;
display: grid;
grid-template-columns: repeat(auto-fill, 200px);
align-items: center;
justify-items: center;
justify-content: center;
grid-gap: 30px;
padding: 30px;
@media (max-width: 700px) {
grid-template-columns: 1fr;
grid-template-rows: auto;
grid-gap: 20px;
width: 100vw;
font-size: 1.1rem;
}
}
`;
export const IngredientCardStyle = styled.label`
display: grid;
border: none;
justify-content: center;
align-items: center;
font-size: 20px;
height: 50px;
width: 100%;
border-radius: 3px;
text-align: center;
background: ${(props) => `var(--${props.background}-color)`};
color: ${(props) => `var(--${props.color}-color)`};
&:hover {
cursor: pointer;
}
@media (max-width: 700px) {
font-size: 1rem;
}
`;
export const LoaderStyle = styled.div`
color: var(--primary-color);
margin: auto 0;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
* {
margin-left: 1rem;
}
`;
|
var units = [
{name: HOUR, id: "#hourly-price"},
{name: DAY, id: "#daily-price"},
{name: MONTH, id: "#monthly-price"}
]
Template.spaceTopUnitSelection.events({
"click #hourly-price": function(event, template) {
event.preventDefault()
Session.set(unitSessionId(this._id), HOUR)
},
"click #daily-price": function(event, template) {
event.preventDefault()
Session.set(unitSessionId(this._id), DAY)
},
"click #monthly-price": function(event, template) {
event.preventDefault()
Session.set(unitSessionId(this._id), MONTH)
},
});
// Set to daily price by default if it exist. Otherwise set to first available price
Template.spaceTopUnitSelection.onCreated(function() {
var template = this
Tracker.autorun(function(){
var spaceId = template.data._id
var price = Mart.Prices.findOne({productId: spaceId, unit: DAY})
if(!price)
price = Mart.Prices.findOne({productId: spaceId})
if(price)
Session.setDefault(unitSessionId(spaceId), price.unit)
});
})
Template.spaceTopUnitSelection.helpers({
activeUnitClass: function(unit) {
let activeClass = 'unit-active'
if(unit === Session.get(unitSessionId(this._id))) {
return activeClass
}
}
});
|
/*
* @lc app=leetcode.cn id=463 lang=javascript
*
* [463] 岛屿的周长
*/
// @lc code=start
/**
* @param {number[][]} grid
* @return {number}
*/
var islandPerimeter = function(grid) {
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
if (grid[i][j] === 1) {
return dfs(grid, i, j)
}
}
}
return -1;
};
let dfs = (grid, row, col) => {
if (!isArea(grid, row, col)) return 1;
if (grid[row][col] == 0) return 1;
if (grid[row][col] == 2) return 0;
grid[row][col] = 2;
return dfs(grid, row - 1, col) + dfs(grid, row + 1, col) + dfs(grid, row, col - 1) + dfs(grid, row, col + 1)
}
let isArea = (grid, row, col) => {
return 0 <= row && row < grid.length && 0 <= col && col < grid[0].length;
}
// @lc code=end
|
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
export default new Router({
routes: [
// 登录
{
path: '/login',
name: 'Login',
meta: {
},
component: () => import('@/components/login/Login')
},
// 工作台
{
path: '/',
name: 'WorkBench',
meta: {
},
component: () => import('@/components/workbench/WorkBench')
},
{
path: '/basicsetting/BasicSetting',
name: 'BasicSetting',
meta:{
},
component: () => import('@/components/workbench/basicsetting/BasicSetting')
},
// 易知独秀
{
path: '/uniquebranch/WebsiteSet',
name: 'WebsiteSet',
meta: {
},
component: () => import('@/components/uniquebranch/WebsiteSet')
},
{
path: '/uniquebranch/ActivityGL',
name: 'ActivityGL',
meta: {
},
component: () => import('@/components/uniquebranch/ActivityGL')
},
{
path: '/uniquebranch/ShowCourse',
name: 'ShowCourse',
meta: {
},
component: () => import('@/components/uniquebranch/ShowCourse')
},
//营销中心
{
path: '/marketingcenter/GoodsGL',
name: 'GoodsGL',
meta: {
},
component: () => import('@/components/marketingcenter/GoodsGL')
},
{
path: '/marketingcenter/CouponGL',
name: 'CouponGL',
meta: {
},
component: () => import('@/components/marketingcenter/CouponGL')
},
{
path: '/marketingcenter/QuestionnaireGL',
name: 'QuestionnaireGL',
meta: {
},
component: () => import('@/components/marketingcenter/QuestionnaireGL')
},
{
path: '/marketingcenter/ReferralGL',
name: 'ReferralGL',
meta: {
},
component: () => import('@/components/marketingcenter/ReferralGL')
},
//销售管理
{
path: '/sales/NamelistGL',
name: 'NamelistGL',
meta: {
},
component: () => import('@/components/sales/namelistgl/NamelistGL')
},
{
path: '/sales/PotentialGL',
name: 'PotentialGL',
meta: {
},
component: () => import('@/components/sales/potentialgl/PotentialGL')
},
{
path: '/sales/VisitQuery',
name: 'VisitQuery',
meta: {
},
component: () => import('@/components/sales/VisitQuery')
},
{
path: '/sales/AuditionGL',
name: 'AuditionGL',
meta: {
},
component: () => import('@/components/sales/AuditionGL')
},
{
path: '/sales/OrderPush',
name: 'OrderPush',
meta: {
},
component: () => import('@/components/sales/OrderPush')
},
{
path: '/sales/RenewalWarn',
name: 'RenewalWarn',
meta: {
},
component: () => import('@/components/sales/RenewalWarn')
},
{
path: '/sales/ChannelGL',
name: 'ChannelGL',
meta: {
},
component: () => import('@/components/sales/ChannelGL')
},
//教务管理
{
path: '/educational/StudentCenter',
name: 'StudentCenter',
meta: {
},
component: () => import('@/components/educational/studentcenter/StudentCenter')
},
{
path: '/educational/ClasslGL',
name: 'ClasslGL',
meta: {
},
component: () => import('@/components/educational/classgl/ClasslGL')
},
{
path: '/educational/TimetableGL',
name: 'TimetableGL',
meta: {
},
component: () => import('@/components/educational/TimetableGL')
},
{
path: '/educational/AppointmentGL',
name: 'AppointmentGL',
meta: {
},
component: () => import('@/components/educational/appointmentgl/AppointmentGL')
},
{
path: '/educational/CourseSet',
name: 'CourseSet',
meta: {
},
component: () => import('@/components/educational/courseset/CourseSet')
},
{
path: '/educational/DataGL',
name: 'DataGL',
meta: {
},
component: () => import('@/components/educational/DataGL')
},
//日常课务
{
path: '/dailyaffairs/AffairsGL',
name: 'AffairsGL',
meta: {
},
component: () => import('@/components/dailyaffairs/affairsgl/AffairsGL')
},
{
path: '/dailyaffairs/OnlineCourse',
name: 'OnlineCourse',
meta: {
},
component: () => import('@/components/dailyaffairs/onlinecourse/OnlineCourse')
},
{
path: '/dailyaffairs/IntegralGL',
name: 'IntegralGL',
meta: {
},
component: () => import('@/components/dailyaffairs/IntegralGL')
},
{
path: '/dailyaffairs/MakeupLessons',
name: 'MakeupLessons',
meta: {
},
component: () => import('@/components/dailyaffairs/MakeupLessons')
},
{
path: '/dailyaffairs/StudentSignin',
name: 'StudentSignin',
meta: {
},
component: () => import('@/components/dailyaffairs/StudentSignin')
},
{
path: '/dailyaffairs/PickupGL',
name: 'PickupGL',
meta: {
},
component: () => import('@/components/dailyaffairs/PickupGL')
},
//我的授课
{
path: '/myteaching/MyTimetable',
name: 'MyTimetable',
meta: {
},
component: () => import('@/components/myteaching/MyTimetable')
},
{
path: '/myteaching/PunchIn',
name: 'PunchIn',
meta: {
},
component: () => import('@/components/myteaching/PunchIn')
},
{
path: '/myteaching/OnlineCourse',
name: 'OnlineCourse',
meta: {
},
component: () => import('@/components/myteaching/OnlineCourse')
},
//行政管理
{
path: '/administrative/NoticeGL',
name: 'NoticeGL',
meta: {
},
component: () => import('@/components/administrative/NoticeGL')
},
{
path: '/administrative/StockGL',
name: 'StockGL',
meta: {
},
component: () => import('@/components/administrative/StockGL')
},
{
path: '/administrative/StationGL',
name: 'StationGL',
meta: {
},
component: () => import('@/components/administrative/StationGL')
},
{
path: '/administrative/StaffGL',
name: 'StaffGL',
meta: {
},
component: () => import('@/components/administrative/staffgl/StaffGL')
},
{
path: '/administrative/StaffCheck',
name: 'StaffCheck',
meta: {
},
component: () => import('@/components/administrative/StaffCheck')
},
//财务管理
{
path: '/finance/OrderGL',
name: 'OrderGL',
meta: {
},
component: () => import('@/components/finance/OrderGL')
},
{
path: '/finance/DetailedCash',
name: 'DetailedCash',
meta: {
},
component: () => import('@/components/finance/DetailedCash')
},
{
path: '/finance/YishouBao',
name: 'YishouBao',
meta: {
},
component: () => import('@/components/finance/YishouBao')
},
{
path: '/finance/CostCash',
name: 'CostCash',
meta: {
},
component: () => import('@/components/finance/CostCash')
},
{
path: '/finance/WagesGL',
name: 'WagesGL',
meta: {
},
component: () => import('@/components/finance/WagesGL')
},
{
path: '/finance/SystemService',
name: 'SystemService',
meta: {
},
component: () => import('@/components/finance/SystemService')
},
//统计分析
{
path: '/statistical/SalesStatistics',
name: 'SalesStatistics',
meta: {
},
component: () => import('@/components/statistical/SalesStatistics')
},
{
path: '/statistical/EducationalSummary',
name: 'EducationalSummary',
meta: {
},
component: () => import('@/components/statistical/EducationalSummary')
},
{
path: '/statistical/NamelistAnalysis',
name: 'NamelistAnalysis',
meta: {
},
component: () => import('@/components/statistical/NamelistAnalysis')
},
{
path: '/statistical/FinanceAnalysis',
name: 'FinanceAnalysis',
meta: {
},
component: () => import('@/components/statistical/FinanceAnalysis')
},
],
mode: 'history'
})
|
// ────────────────────────────────────────────────────────────────────────────────
// MODULES
const path = require('path');
const {app, BrowserWindow} = require('electron');
const installExt = require('electron-devtools-installer');
// Install `vue-devtools`
app.on('ready', () => {
if (process.env.NODE_ENV === 'development') {
require('electron-debug')({ showDevTools: true });
installExt.default(installExt.VUEJS_DEVTOOLS)
.then(name => console.log(`Added Extensions: ${name}`))
.catch(err => console.log('Unable to install devtools: ', err));
}
});
// ────────────────────────────────────────────────────────────────────────────────
let mainWindow;
const winURL = process.env.NODE_ENV === 'development'
? `http://localhost:${process.env.PORT}`
: `file://${__dirname}/index.html`
function createWindow() {
mainWindow = new BrowserWindow({width: 1500, height: 1000});
mainWindow.loadURL(winURL);
mainWindow.on('closed', () => { mainWindow = null; });
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
if (mainWindow === null) { createWindow(); }
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.