text
stringlengths 7
3.69M
|
|---|
#!/usr/bin/env node
require('colors');
const { readFileSync } = require('fs');
const { get } = require('https');
const { getFiles, sleep } = require('./include');
let args = process.argv.slice(2);
let pattern = 'https?://(?:osu|new|old|jizz|news|status)\\.ppy\\.sh/';
if (args[0] === '--uri') {
pattern += args[1].replace(/^\/+/g, '');
args = args.slice(2);
}
pattern = `\\]\\((${pattern}.+?)\\)|^\\[.+\\]: (${pattern}.+?)(?: "|$)|["<](${pattern}.+?)[">]`;
(async () => {
for (const path of await getFiles(args, 'md')) {
const content = readFileSync(path, 'utf8');
for (const match of content.matchAll(RegExp(pattern, 'gm'))) {
const url = match[1] || match[2] || match[3];
get(url, res => {
switch (res.statusCode) {
case 301:
case 302:
case 404:
console.log(url.red);
return;
case 200:
break;
default:
console.error(`${url}: Got status code ${res.statusCode}`.yellow);
return;
}
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
if (data.includes('The page you were looking for can\'t be found...'))
console.log(url.red);
});
})
.on('error', err => console.error(`${url}: ${err}`.red));
await sleep(1500);
}
}
})();
|
/**
* MyVehicle
* @constructor
*/
class MyVehicle extends CGFobject {
constructor(scene, slices, stacks) {
super(scene);
this.slices = slices;
this.stacks = stacks;
this.angle = 0;
this.v = 0;
this.x = 0;
this.y = 0;
this.z = 0;
this.scale = 1.0;
this.autopilot = false;
this.time = 0;
this.intiObjects();
this.initMaterials();
this.initBuffers();
}
intiObjects(){
this.sphere = new MySphere(this.scene, this.slices, this.stacks);
this.cylinder = new MyCylinder(this.scene, this.slices, this.stacks);
this.rudders = new MyVehicleRudders(this.scene);
this.engine = new MyEngine(this.scene, this.slices, this.stacks);
this.gondola = new MyGondola(this.scene, this.slices, this.stacks);
this.flag = new MyFlag(this.scene);
}
initMaterials(){
//------ Vehicle texture
this.vehicleTex = new CGFappearance(this.scene);
this.vehicleTex.setAmbient(1, 1, 1, 1);
this.vehicleTex.setDiffuse(0.8, 0.8, 0.8, 1);
this.vehicleTex.setSpecular(0.1, 0.1, 0.1, 1);
this.vehicleTex.setShininess(10.0);
this.vehicleTex.loadTexture('images/vehicle.jpg');
this.vehicleTex.setTextureWrap('REPEAT', 'REPEAT');
}
displayObject(){
//---Big elipsoide
this.scene.pushMatrix();
this.scene.scale(1, 1, 2);
this.sphere.display();
this.scene.popMatrix();
//---
this.gondola.display();
this.engine.display();
this.scene.pushMatrix();
this.scene.translate(-0.4, 0, 0);
this.engine.display();
this.scene.popMatrix();
this.rudders.display();
}
display(){
this.scene.pushMatrix();
this.scene.translate(this.x, this.y, this.z);
this.scene.rotate(this.angle, 0, 1, 0);
this.scene.translate(0, 10, 0);
this.scene.scale(this.scale, this.scale, this.scale);
this.flag.displayResized();
this.vehicleTex.apply();
this.scene.scale(0.5, 0.5, 0.5);
this.displayObject();
this.scene.popMatrix();
}
updateBuffers(complexity){
this.slices = 3 + Math.round(9 * complexity); //complexity varies 0-1, so slices varies 3-12
// reinitialize buffers
this.initBuffers();
this.initNormalVizBuffers();
}
update(speed, scale, t){
if (this.autopilot)
this.updateAutoPilot(t);
else{
this.x += this.v * Math.sin(this.angle) * speed;
this.z += this.v * Math.cos(this.angle) * speed;
this.engine.update(this.v, speed);
}
this.scale = scale;
}
updateAutoPilot(t){
if (this.time == 0){
this.time = t;
}
else{
this.x = this.center[0] - this.replace[0]*5;
this.z = this.center[2] - this.replace[2]*5;
this.angle += ((t - this.time)/1000)*2*Math.PI/5;
this.engine.update(0.2, 1);
this.updatePerpendiculars();
this.time = t;
}
this.rudders.update(0.2);
}
turn(val){
this.angle += val;
this.rudders.update(val);
}
resetturn(){
this.rudders.resetturn();
}
accerlerate(val){
this.v += val;
}
reset(){
this.x = 0;
this.y = 0;
this.z = 0;
this.angle = 0;
this.v = 0;
this.autopilot = false;
this.time = 0;
}
startAutoPilot(){
this.autopilot = true;
this.updatePerpendiculars();
this.center = [this.x + this.replace[0]*5, this.y, this.z + this.replace[2]*5];
}
resetAutoPilot(){
this.v = Math.PI / 10;
this.time = 0;
this.autopilot = false;
}
updatePerpendiculars(){
this.perpendicular = this.angle + Math.PI/2;
this.replace = [Math.sin(this.perpendicular), 0, Math.cos(this.perpendicular)];
}
}
|
var arr,
len,
i,
j,
k,
l,
mid,
checker,
newArr;
arr = [64, 25, 12, 7, 33,22, 11, 1000, 101, 77];
len = arr.length;
checker = arr[0];
newArr = new Array();
mid = 0;
do {
leng = arr.length;
checker = arr[0];
for (i = 1; i < leng; i++) {
if (arr[i] < checker) {
checker = arr[i];
//console.log(checker+'checker');
}
}
for (j = 0; j < len; j++) {
if (checker == arr[j]) {
delete arr[j];
}
}
arr = arr.filter( Boolean );
newArr[mid] = checker;
console.log(newArr[mid]);
mid++;
} while (mid < len);
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose as reduxCompose } from 'redux';
import thunk from 'redux-thunk';
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';
import RootReducer from './reducers';
import customMuiStyles from './css/customMuiStyles';
// Add redux devtools to our application if available
const compose = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || reduxCompose
const theme = createMuiTheme(customMuiStyles);
const getInitState = () => {
const initialStateElement = document.getElementById('initState');
let initState = {};
if (initialStateElement) {
initState = JSON.parse(initialStateElement.innerHTML || '{}');
}
return initState;
};
const store = createStore(RootReducer, getInitState(), compose(applyMiddleware(thunk)));
ReactDOM.render(
<Provider store={store}>
<MuiThemeProvider theme={theme}>
<App />
</MuiThemeProvider>
</Provider>,
document.getElementById('root'),
);
|
/**
* Binary Search Algorithm
* @param {Array} sortedArray Sorted Array to be searched
* @param {Number} element Element to be searched
* @return {Number} Index of the element, if found
*/
const binarysearch = (sortedArray, element, left, right) => {
left = left === undefined ? 0 : left;
right = right === undefined ? sortedArray.length - 1 : right;
while (left <= right) {
const mid = (left) + ((right - left) >> 1);
if (sortedArray[mid] === element) {
return mid;
}
if (sortedArray[mid] < element) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
};
module.exports = binarysearch;
|
import React, { Component } from 'react';
import { StyleSheet, FlatList, Modal, Text, View, Alert, Image, TouchableOpacity, ScrollView, Picker } from 'react-native';
import { SideMenu, List, ListItem } from 'react-native-elements';
import Products from './Product'
import CartElement from './CartElement.js'
export default class Cart extends React.Component {
constructor(props) {
super(props)
this.state = {
showCart: props.showCart,
currentCart: props.currentCart
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.showCart !== this.state.showCart) {
this.setState({ showCart: !this.state.showCart })
}
if (nextProps.currentCart !== this.state.currentCart) {
this.setState({ currentCart: this.state.currentCart })
}
}
renderCart= () => {
this.forceUpdate()
}
renderSeparator = () => (
<View
style={{
backgroundColor: '#696969',
height: 1,
}}
/>
);
render() {
return (
<View style={styles.modal}>
<Modal
animationType="slide"
transparent={false}
visible={this.state.showCart}>
<View style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'center', alignItems: 'center' }}>
<View style={styles.modal}>
<Text style={styles.cartText}>Your Cart:</Text>
<FlatList
ItemSeparatorComponent={this.renderSeparator}
data = {this.props.currentCart}
renderItem={({ item }) => <CartElement renderCart={this.renderCart} deleteCartItem={this.props.deleteCartItem} name={item}></CartElement>}
/>
<TouchableOpacity
style={styles.cancelButton}
activeOpacity={.7}
onPress={() => { this.props.toggleCart() }}>
<Text style={styles.cancelText}>Close</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
</View>
);
}
}
const styles = StyleSheet.create({
cartText:{
fontSize: 30,
fontWeight: 'bold',
marginBottom: 20,
marginLeft: 5,
marginTop: 20,
color: '#696969'
},
modal: {
position: 'absolute',
top: 100,
// left: 6,
flexDirection: 'column',
justifyContent: 'center',
backgroundColor: '#F0F7FC',
width: '90%',
height: '80%',
borderRadius: 5,
shadowOffset: { width: 0, height: 5, },
shadowRadius: 5,
shadowColor: 'black',
shadowOpacity: 0.1,
paddingBottom: 20
},
cancelText: {
color: 'white',
textAlign: 'center',
fontWeight: 'bold',
fontSize: 20,
},
cancelButton: {
marginTop: 20,
marginBottom: 10,
paddingTop: 15,
paddingBottom: 15,
marginLeft: 25,
marginRight: 25,
backgroundColor: '#1F89DC',
borderRadius: 14,
borderWidth: 1,
borderColor: '#1F89DC',
shadowOffset: { width: 0, height: 5, },
shadowRadius: 5,
shadowColor: 'black',
shadowOpacity: .1,
},
});
|
(function() {
// 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释
var imports = [
'rd.controls.ScoreIndicator'
];
var extraModules = [ ];
var controllerDefination = ['$scope', main];
function main(scope) {
scope.isMark = false;
scope.config = [{
label: '优秀',
color: '#64D083',
value: 20,
mark: true
}, {
label: '良',
color: '#6AA6C5',
value: 20,
mark: false
}, {
label: '中间内容',
color: '#FC9B58',
value: 20,
mark: false
}, {
label: '差太多',
color: '#EE6D66',
value: 20,
mark: false
}, {
label: '新值测试',
color: '#006D66',
value: 20,
mark: false
}];
scope.changeImgAttr = function() {
scope.isMark = !scope.isMark;
if(scope.isMark){
scope.config[0].mark = false;
scope.config[0].value = 40;
scope.config[1].mark = true;
scope.config[1].value = 15;
scope.config[2].value = 15;
scope.config[3].value = 15;
scope.config[4].value = 15;
}else{
scope.config[0].mark = true;
scope.config[0].value = 20;
scope.config[1].mark = false;
scope.config[1].value = 20;
scope.config[2].value = 20;
scope.config[3].value = 20;
scope.config[4].value = 20;
}
}
}
var controllerName = 'DemoController';
//==========================================================================
// 从这里开始的代码、注释请不要随意修改
//==========================================================================
define(/*fix-from*/application.import(imports)/*fix-to*/, start);
function start() {
application.initImports(imports, arguments);
rdk.$injectDependency(application.getComponents(extraModules, imports));
rdk.$ngModule.controller(controllerName, controllerDefination);
}
})();
|
import React, { useState } from 'react'
import { useHistory } from 'react-router-dom';
import Swal from 'sweetalert2';
import api from '../api/api.instance';
import Botao from '../components/Compartilhado/Botao/Botao';
import GridDiv from '../components/Compartilhado/GridDiv'
import InputGroup from '../components/Compartilhado/InputGroup'
function Registrar() {
const [email, setEmail] = useState("");
const [senha, setSenha] = useState("");
const [confirmacaoDaSenha, setConfirmacaoDaSenha] = useState("");
const [nome, setNome] = useState("");
const history = useHistory();
const registrar = async () => {
if(senha !== confirmacaoDaSenha) {
Swal.fire('Algo deu errado', 'As senhas não são iguais', 'error');
return;
}
try {
await api.post('autenticacao/registrar', {email, senha, nome});
Swal.fire('Sucesso!', 'Usuário cadastrado com sucesso, faça o login agora!', 'success').then();
history.push('/login');
} catch (error) {
if(error.response) {
const {status, message} = error.response.data;
Swal.fire(`${status} - Algo deu errado...`, message, 'error');
} else {
console.log(error);
}
}
}
return (
<GridDiv>
<InputGroup>
<label htmlFor="nome">Nome</label>
<input
type="text"
name="nome"
id="nome"
value={nome}
onChange={(e) => setNome(e.target.value)}/>
</InputGroup>
<InputGroup>
<label htmlFor="email">Email</label>
<input
type="text"
name="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}/>
</InputGroup>
<InputGroup>
<label htmlFor="senha">Senha</label>
<input
type="password"
name="senha"
id="senha"
value={senha}
onChange={(e) => setSenha(e.target.value)}/>
</InputGroup>
<InputGroup>
<label htmlFor="confirmacaoDaSenha">Confirme a senha</label>
<input
type="password"
name="confirmacaoDaSenha"
id="confirmacaoDaSenha"
value={confirmacaoDaSenha}
onChange={(e) => setConfirmacaoDaSenha(e.target.value)}/>
</InputGroup>
<InputGroup>
<Botao onClick={() => registrar()}>Registrar</Botao>
</InputGroup>
</GridDiv>
)
}
export default Registrar
|
import Population from './population';
import { FOOD, DIE, NOTHING, SAME } from './constants';
export default class Arena {
constructor(config) {
this.config = config;
this.iterations = this.config.iterations;
this.arena = {};
this.tickCount = 0;
}
getCompare(ent, ents) {
let hasEnemy = false;
let hasFood = false;
let same = false;
ents.forEach(nent => {
if (nent.type < ent.type && nent.visited.indexOf(ent) === -1) {
hasFood = true
} else if (nent.type > ent.type) {
hasEnemy = true
} else {
same = true;
}
})
return hasEnemy ? DIE : hasFood ? FOOD : same ? SAME : NOTHING;
}
getNeighbours(individual) {
const { x, y } = individual;
const { width, height } = this.config.map;
const neigh = [];
for (let i = x - 1; i <= x + 1; i++) {
for (let j = y - 1; j <= y + 1; j++) {
if (i !== x || j !== y) {
if (i === x || j === y) {
const ent = this.arena[`${i}-${j}`];
if (i < 0 || j < 0 || i > width || j > height) {
neigh.push(DIE)
} else if (Array.isArray(ent)) {
neigh.push(this.getCompare(individual, ent))
} else {
neigh.push(NOTHING)
}
}
}
}
}
return neigh;
}
addToArena(individual) {
const { x, y } = individual;
const key = `${x}-${y}`;
const obj = this.arena[key];
if (obj) {
obj.push(individual);
} else {
this.arena[key] = [individual]
}
}
resetArena() {
this.arena = {}
this.populations.forEach(pop => {
pop.individuals.forEach(ind => {
if (ind.energy > 0 && ind.alive) {
this.addToArena(ind);
}
})
})
}
nextGen() {
if (this.config.onIterationEnd) {
this.config.onIterationEnd(this);
}
this.iterations++;
this.populations.forEach(pop => {
pop.evolve(this.tickCount)
})
this.tickCount = 0;
this.resetArena();
}
reset() {
const { seed, populations, map: { width, height } } = this.config;
Math.seedrandom(seed);
this.populations = []
populations.forEach(pop => {
const { randomPoints, startX: predefStartX, startY: predefStartY } = pop;
const [sx, sy] = [predefStartX || Math.floor(Math.random() * width), predefStartY || Math.floor(Math.random() * height)];
const population = new Population(this.config.tf, pop, this.config.map);
population.getNeighbours = ind => this.getNeighbours(ind);
population.individuals.forEach(ind => {
const startX = randomPoints ? Math.floor(Math.random() * width) : sx;
const startY = randomPoints ? Math.floor(Math.random() * height) : sy
Object.assign(ind, {
startX,
startY,
x: startX,
y: startY
});
})
this.populations.push(population);
});
this.resetArena();
}
tick() {
return new Promise(res => {
this.tickCount++;
const decisions = this.populations.reduce((memo, pop) => {
return memo.concat(pop.decide());
}, []);
Promise.all(decisions).then(() => {
this.resetArena()
this.totalActive = 0;
this.populations.forEach(pop => {
pop.act();
});
Object.values(this.arena).forEach(arr => {
if (arr.length > 1) {
for (let i = 0; i < arr.length - 1; i++) {
const left = arr[i];
for (let j = i + 1; j < arr.length; j++) {
const right = arr[j];
let weak, strong;
if (left.type !== right.type) {
if (left.type < right.type) {
weak = left;
strong = right;
} else {
weak = right;
strong = left;
}
}
if (weak && strong && weak.visited.indexOf(strong) === -1) {
strong.energy += weak.energy;
strong.lastEat = 1;
strong.lastEatTime = 0;
weak.visited.push(strong);
if (this.config.removeWeak) {
weak.die();
}
if (strong.energy > 1) {
strong.energy = 1;
}
}
}
}
}
});
this.populations.forEach(pop => {
this.totalActive += pop.getActiveCount();
});
if (this.config.renderer) {
this.config.renderer.render(this);
}
if (this.totalActive === 0) {
this.config.removeWeak = false;
this.nextGen()
}
res();
})
});
}
}
|
import React from "react";
import CardSummary from "./CardSummary";
export default class Container extends React.Component {
state = {};
render() {
return <CardSummary />;
}
}
|
'use strict';
/*
RockMUD move an entity toward a given refID
@stayInArea boolean can be toggled to keep the entity from searching outside of its current area.
@getTarget function returns the target the entity is searching for
*/
module.exports = {
getTarget: function(World, behavior, mob, roomObj) {
var target = null;
if (behavior.targetRefId) {
target = World.getEntityByRefId(behavior.targetRefId);
}
return target;
},
stayInArea: true,
check: 1, // 1 out 10 chance to fire this onAlive event
targetRefId: '',
onAlive: function(World, behavior, mob, roomObj) {
var roll = World.dice.roll(1, 10),
target,
targetRoomObj,
exitObj,
direction;
behavior.targetRefId = mob.refId;
if (!mob.fighting && roll > behavior.check && mob.position === 'standing') {
target = behavior.getTarget(behavior, mob, roomObj);
if (target) {
targetRoomObj = World.getRoomObject(target.area, target.roomid);
direction = World.room.getClosestExit(roomObj, targetRoomObj);
/*
exitObj = World.room.getExit(roomObj, direction);
if (exitObj && ((behavior.stayInArea === false)
|| (behavior.stayInArea === true && mob.area === exitObj.area))) {
World.addCommand({
cmd: 'move',
arg: direction,
roomObj: roomObj
}, mob);
}
*/
} else {
console.log('could not find target');
}
}
}
};
|
const { config } = require('../../framework/index.js');
const height = wx.getSystemInfoSync().windowHeight;
Page({
data: {
sticky: false,
opacity: 0,
height,
},
onShareAppMessage() {
return config.shareData;
},
});
|
import {state} from '../index';
import {maxHours, minHours, standardTime} from './time';
import * as music from './music';
import {elements} from '../views/base';
export const upgWeek = (type,sign) => {
// upgrade the value of time table week when clicked
let value = state.weekTimes[`${type}Hours`];
const valueTot = state.weekTimes['totHours'];
let deltavalue;
if(type ==='work') deltavalue = standardTime[type] + standardTime['commute'];
else deltavalue = standardTime[type];
// values cannot be less than 0
if (sign === 'less' && value > minHours[type]){
state.weekTimes[`${type}Hours`] -= standardTime[type];
if(type ==='work') state.weekTimes["commuteHours"] -= standardTime['commute'];
if (music.musicOn) elements.audioBtnMinus.play();
} else if(sign === 'more' && valueTot < 168 && valueTot+deltavalue <= 168 && Math.floor(value/standardTime[type]) < maxHours[type]) {
// taking care if the total number of hours is not greater than 168
state.weekTimes[`${type}Hours`] += standardTime[type];
if(type ==='work') state.weekTimes["commuteHours"] += standardTime['commute'];
//adding sound
if (music.musicOn) elements.audioBtnPlus.play();
};
state.weekTimes.calcTotHours();
};
|
import React, { Component } from 'react'
import Item from '../item/item'
export default class Show extends Component {
render() {
const {isFirst,isLoading,users,error} = this.props
if(isFirst){
return <h2>第一次打开页面请输入关键字点击搜索</h2>
}else if(isLoading){
return <h2>loading...</h2>
}else if(error){
return <h2>{error}</h2>
}else{
return (
<div className="row">
{
users.map((user) => {
return <Item key={user.login} {...user}/>
})
}
</div>
)
}
}
}
|
// Unbounce.js
var fusionResize,fusionWidth,fusionHeight,fusionDevice="";
$(window).load(function() {
window.onresize = function() {
clearTimeout(fusionResize);
fusionResize = setTimeout(fusionUpdate, 1);
};
function checkDevice(fusionDevice, fusionWidth) {
if (fusionWidth > 600) {
fusionDevice = "desktop";
} else {
fusionDevice = "mobile";
}
return fusionDevice;
}
function fusionUpdate() {
fusionWidth = $(window).width();
fusionHeight = $(window).height();
fusionDevice = checkDevice(fusionDevice, fusionWidth);
}
fusionUpdate();
footerUpdate();
});
function footerUpdate() {
var number = $('a[href^="tel:"]').attr('href').replace('tel:', '');
var fusionButton = '<a id="lp-pom-footer-button" class="lp-element lp-pom-button" href="tel:'+number+'">CALL '+number.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3')+'</a>';
$('#lp-pom-root').append(fusionButton);
$(window).scroll(function() {
if (fusionDevice=="mobile") {
if ($(window).scrollTop() >= ($(selector).offset().top + $(selector).outerHeight()) ) {
$('#lp-pom-footer-button').addClass('fixed');
} else{
$('#lp-pom-footer-button').removeClass('fixed');
}
}
});
}
|
export { default as Debounce } from './Debounce';
export { default as Hover } from './Hover';
export { default as Input } from './Input';
export { default as List } from './List';
export { default as Modal } from './Modal';
export { default as Request } from './Request';
export { default as FocusRef } from './FocusRef';
|
var a = 10;
var b = 20;
var c = a + b;
document.write( c );
|
const Track = require("../tracks/Track")
const timeFormater = require("../util/Time")
const path = require("path")
class Song {
/**
* constructor
*
* load a song from a filepath and the files metadata
*
* @param {String} path
* @param {Object} metadata
*/
constructor(path, metadata) {
this.track = undefined
this.path = path
this.metadata = metadata
this.loadTrack()
}
/**
* loadTrack
*
* take all the data from the file metadata and extracts all the necessary data
*/
loadTrack() {
const track = new Track()
track.title = this.metadata.common.title
track.artist = this.metadata.common.artist
track.album = this.metadata.common.album
track.type = "Song"
track.ref = this.path
track.duration = timeFormater(this.metadata.format.duration)
track.extension = path.extname(this.path)
this.track = track
}
}
module.exports = Song
|
class FormDataCollector
{
constructor(originalData, data, uploads)
{
this.originalData = originalData;
this.data = data;
this.uploads = uploads;
}
collect()
{
let formData = new FormData();
for (let attribute in this.originalData) {
this.dataFormRecursive(formData, attribute, this.data);
}
for (let attribute in this.uploads) {
formData.append(attribute, this.uploads[attribute], this.uploads[attribute].name);
}
return formData;
}
toObject(formData)
{
if ( ! formData) {
formData = this.collect();
}
let object = {};
for (let pair of formData) {
object[pair[0]] = pair[1];
}
return object;
}
dataFormRecursive(formData, attribute, data)
{
if (Array.isArray(data[attribute])) {
return data[attribute].map((el, i) => {
this.handleArrayOrObject(formData, attribute, el, i);
});
}
if (typeof data[attribute] === 'object' && data[attribute] !== null) {
for (let [i, el] of Object.entries(data[attribute])) {
this.handleArrayOrObject(formData, attribute, el, i);
}
return;
}
if (data[attribute] !== null) {
formData.append(attribute, data[attribute]);
}
}
handleArrayOrObject(formData, attribute, el, i)
{
let tmp = {};
let arrAttribute = attribute + '[' + i + ']';
tmp[arrAttribute] = el;
this.dataFormRecursive(formData, arrAttribute, tmp);
}
}
export default FormDataCollector;
|
import * as THREE from 'three';
// const THREE = AFRAME.THREE;
// Some local constants, maybe make this params of the component
const PARTICLE_COUNT = 1000;
const PARTICL_CLOUD_SIZE = 500;
const SPAWN_TIME_MAX = 5;
const vert = `
uniform float time;
uniform vec3 camera_pos;
attribute float offsetTime;
varying float vAlpha;
const float minPointScale = 0.1;
const float maxPointScale = 0.7;
const float maxDistance = 100.0;
void main() {
gl_Position = projectionMatrix
* modelViewMatrix
* vec4(position, 1.0);
float cameraDist = distance(position.xyz, camera_pos);
float pointScale = 1.0 - (cameraDist / maxDistance);
pointScale = max(pointScale, minPointScale);
pointScale = min(pointScale, maxPointScale);
gl_PointSize = 20.0 * pointScale;
vAlpha = (cos((time + offsetTime) / 2000.0) * 0.3) + 0.8;
}`;
const frag = `
varying float vAlpha;
void main() {
gl_FragColor = vec4(1.0, 1.0, 1.0, vAlpha);
}`;
function random(a, b) {
const dif = b - a;
return (a + (Math.random() * dif));
}
AFRAME.registerShader('particles', {
schema: {
time: { type: 'time', is: 'uniform' },
camera_pos: { type: 'vec3', is: 'uniform' },
offsetTime: { type: 'array', is: 'attribute' },
position: { type: 'array', is: 'attribute' },
},
vertexShader: vert,
fragmentShader: frag,
});
AFRAME.registerComponent('space-particles', {
schema: {},
/**
* Initial creation and setting of the mesh.
*/
init: function () {
var data = this.data;
var el = this.el;
this.camPos = new THREE.Vector3(0,0,0);
this.geometry = new THREE.BufferGeometry();
this.geometry.setAttribute('position', new THREE.Float32BufferAttribute(new Array(PARTICLE_COUNT * 3).fill(0.0), 3));
this.geometry.setAttribute('offsetTime', new THREE.Float32BufferAttribute(new Array(PARTICLE_COUNT).fill(0), 1));
const positionAttribute = this.geometry.getAttribute('position');
const offsetTimeAttribute = this.geometry.getAttribute('offsetTime');
// set up particles
for (let i = 0; i < PARTICLE_COUNT; i++) {
positionAttribute.array[i * 3] = random(-PARTICL_CLOUD_SIZE, PARTICL_CLOUD_SIZE);
positionAttribute.array[i * 3 + 1] = random(-PARTICL_CLOUD_SIZE, PARTICL_CLOUD_SIZE);
positionAttribute.array[i * 3 + 2] = random(-PARTICL_CLOUD_SIZE, PARTICL_CLOUD_SIZE);
offsetTimeAttribute.array[i] = Math.random() * 10000;
}
positionAttribute.needsUpdate = true;
offsetTimeAttribute.needsUpdate = true;
// Create mesh.
this.mesh = new AFRAME.THREE.Points(this.geometry, this.material);
// console.log(this.mesh)
// Set mesh on entity.
el.setObject3D('mesh', this.mesh);
},
tick: function(time, dt) {
this.camPos.copy(this.el.sceneEl.camera.el.getAttribute('position'));
this.el.setAttribute('material', 'camera_pos', this.camPos);
// this.spawnTimer += dt;
// if (this.spawnTimer >= SPAWN_TIME_MAX) {
// this.spawnTimer = 0;
// this.spawnParticle(time);
// this.currentParticle += 1;
// // Reset particle counter
// if (this.currentParticle >= PARTICLE_COUNT) {
// this.currentParticle = 0;
// }
// }
}
});
|
console.log("JS Hello JavaScript!");
|
function myJsFunction(){
var radius = document.getElementById('input1').value;
var preArea = Math.pow(radius, 2);
var area = preArea * Math.PI;
document.getElementById("result").innerHTML = "r = " + radius + " area = " + area;
}
|
const calculateScores = (board) =>
board.reduce(
(scores, { takenBy }) =>
takenBy > -1
? {
...scores,
[takenBy]: (scores[takenBy] || 0) + 1,
}
: scores,
{}
);
const determineWinner = (boardSize, scores) => {
const boxesAmount = Math.pow(boardSize, 2);
const scoreNeeded = Math.floor(boxesAmount / 2) + 1;
return Object.keys(scores).reduce(
(winner, player) =>
(scores[player] || 0) >= scoreNeeded ? Number(player) : winner,
-1
);
};
module.exports = {
calculateScores,
determineWinner,
};
|
const Education = require('../lib/models/education.model');
const assert = require('chai').assert;
const testInvalid = require('./test-invalid')(Education);
let testEducation = {
educationLevel: 'Vocational',
educationCost: 20000
};
describe('tests Education Model', () => {
it('validation fails without educationLevel value', () => {
return testInvalid({
educationCost: 20000
});
});
it('validation fails without educationCost value', () => {
return testInvalid({
educationLevel: 'Vocational'
});
});
it('validation passes with all education values', () => {
return new Education(testEducation)
.validate();
});
});
|
$(function () {
$('form').submit(function () {
$.ajax({
url: 'index/search',
method: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
var film = '';
var tableBody = $('tbody');
var filmTable = $('#filmTable');
tableBody.html(filmTable);
function hours(secondsTime){
var seconds = secondsTime;
var minutes = seconds / 60;
var hours = minutes / 60;
minutes = minutes % 60;
return Math.trunc(hours) + 'h' + Math.trunc(minutes)
}
for (var i in data.films) {
film = tableBody.append(
'<tr><td>' + data.films[i].title + '</td><br><br>' +
'<td>' + data.films[i].first_name+' '+data.films[i].last_name + '</td><br><br>' +
'<td>' + data.films[i].gender + '</td><br><br>' +
'<td>' + data.films[i].year + '</td><br><br>' +
'<td>' + data.films[i].synopsis + '</td><br><br>' +
'<td>' + hours(data.films[i].duration) + '</td><br><br></tr>'
);
}
},
error: function (data, status, error) {
var showErrors = '';
data = JSON.parse(data.responseText);
for (var d in data.errors) {
showErrors += d + ' :' + data.errors[d] + '<br>';
}
}
});
return false;
});
});
|
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';
import { store } from './util/store';
import { App } from './App';
import './index.css'
/* const theme = createMuiTheme({
palette: {
primary: {
main: "#54AAB3",
contrastText: '#fff'
}
},
overrides: {
MuiIconButton: {
root: {
color: 'white'
},
}
}
}); */
const theme = createMuiTheme({
palette: {
primary: {
main: '#54AAB3',
dark: '#3c8f98',
contrastText: '#ffffff'
},
secondary: {
main: '#ffffff',
contrastText: '#000000'
}
}/* ,
overrides: {
MuiListItem: {
root: {
backgroundColor: '#ffffff',
'&$selected': {
backgroundColor: '#54AAB3',
color: '#ffffff'
},
'&$selected:hover': {
backgroundColor: '#3c8f98',
color: '#ffffff'
}
},
},
} */
});
render(
<MuiThemeProvider theme={theme}>
<Provider store={store}>
<App />
</Provider>
</MuiThemeProvider>,
document.getElementById('root')
);
|
import React from 'react';
import { useRouter } from 'next/router';
import { NextSeo } from 'next-seo';
import Link from 'next/link';
import Query from 'components/query';
import PRODUCT_QUERY from 'apollo/queries/product/product';
import BreadcrumbsArrow from 'components/svg/breadcrumbsArrow';
import Layout from './components/Layout';
import Form from './components/form';
import FormDelivery from './components/formDelivery';
import Forminfo from './components/formInfo';
import Filter from './components/filter';
import Slider from './components/slider';
import Tabs from './components/tabs';
import Gallery from './components/gallery';
let SEO;
const Product = () => {
const router = useRouter();
return (
<Layout>
<Query query={PRODUCT_QUERY} id={router.query.id}>
{({ data: { product } }) => {
SEO = {
title:
product.titleHe !== null
? `משלוחים Booma | ${product.seo.titleHe}`
: `משלוחים Booma | ${product.productNameHe}`,
description: `${product.seo.descriptionHe}`,
openGraph: {
locale: 'he_IL',
url: `https://shop.booma.co.il/ru/home/appliances/product?id=${product.id}`,
site_name: 'Booma Israel',
title:
product.seo.ogTitleHe !== null
? `משלוחים Booma | ${product.seo.ogTitleHe}`
: `משלוחים Booma | ${product.seo.titleHe}`,
description:
product.seo.ogDescriptionHe !== null
? `${product.seo.ogDescriptionHe}`
: `${product.seo.descriptionHe}`,
images: [
{
url: `${process.env.API_URL + product.seo.ogImage.url}`,
width: 250,
height: 250,
alt: `${product.seo.titleHe}`,
},
],
},
};
return (
<>
<NextSeo {...SEO} />
<div className="productHe">
<section className="section about">
<div className="container">
<div className="row">
<div className="col-lg-11 col-12 offset-lg-1 offset-0">
<div className="breadcrumbs">
<ul className="breadcrumbs__list">
<li className="breadcrumbs__item">
<Link href="/ru">
<a className="breadcrumbs__link">עמוד ראשי</a>
</Link>
<BreadcrumbsArrow />
</li>
<li className="breadcrumbs__item">
<Link href="/ru/home">
<a className="breadcrumbs__link">לבית</a>
</Link>
<BreadcrumbsArrow />
</li>
<li className="breadcrumbs__item">
<Link href="/ru/home/appliances">
<a className="breadcrumbs__link">מכשירים</a>
</Link>
<BreadcrumbsArrow />
</li>
<li className="breadcrumbs__item">
<Link href={router.asPath}>
<a className="breadcrumbs__link">
{product.productNameHe}
</a>
</Link>
</li>
</ul>
</div>
</div>
</div>
<div className="row flex-lg-row flex-column align-content-end">
<div className="col-lg-8 col-md-8 col-12 d-lg-none d-md-none d-block pb-lg-4 pb-md-4 pb-3">
<h1 className="about__title">
{product.productNameHe}
</h1>
</div>
<div className="col-lg-4 col-md-4 col-12 d-lg-none d-md-none d-flex justify-content-end align-aitems-center pb-lg-4 pb-md-4 pb-3">
<p className="about__sku">SKU:{product.productID}</p>
</div>
</div>
<div className="row">
<Slider />
<div className="col-lg-5 offset-lg-1 offset-0 order-lg-0 order-md-0 order-1">
<div className="container p-0">
<div className="row d-lg-flex d-md-flex d-none flex-row-reverse">
<div className="col-8">
<h1 className="about__title">
{product.productNameHe}
</h1>
</div>
<div className="col-4">
<p
className="about__sku"
style={{
textAlign: 'right',
}}
>
SKU:{product.productID}
</p>
</div>
</div>
<div className="row">
<div className="col-12">
<p className="about__description">
{product.seo.ogDescriptionHe}
</p>
</div>
</div>
<div className="row">
<div className="col-12">
<div className="about__prices">
<div className="about__price">
<span className="price price--new">
{product.price.new}₪
</span>
<span className="price price--old">
{product.price.old}₪
</span>
</div>
<span className="about__sale">
{Math.ceil((100 * product.price.new / product.price.old - 100), 10)}%
</span>
</div>
</div>
</div>
<div className="row">
<div className="col-12">
<div className="about__filter filter">
<div className="filter__topline">
<h4 className="filter__title">:צבע</h4>
<p className="filter__parameter-name">
פרמטר
</p>
</div>
<ul className="filter__parameters-array">
<Filter />
</ul>
</div>
</div>
</div>
<div className="row">
<div className="col-12">
<div className="about__basket basket">
{/* <div className="basket__amount">
<p className="basket__title">:Количество</p>
</div> */}
<div className="basket__controls">
<a
href="#form"
className="basket__button basket__button--order"
onClick={(event) => {
event.preventDefault();
if (window.innerWidth <= 576) {
document
.querySelector('#form')
.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'start',
});
} else {
document
.querySelector('#form')
.scrollIntoView({
behavior: 'smooth',
block: 'center',
inline: 'start',
});
}
}}
>
להזמין
</a>
{/* <button
className="basket__button basket__button--add"
type="button"
>
В корзину
</button> */}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section className="section details">
<div className="container">
<div className="row flex-row-reverse">
<Gallery />
<Tabs />
</div>
</div>
</section>
<section className="section form" id="form">
<div className="container">
<div className="row justify-content-center">
<div className="col-12 order-0">
<h3 className="form__title about__title">
<span>להזמין</span>
<span className="about__title about__title--uppercase">
”
{product.productNameHe !== null
? product.productNameHe
: ''}
“
</span>
<span>עכשיו</span>
</h3>
</div>
<div className="col-xl-6 col-lg-7 col-md-9 col-sm-11 col-12 pl-0 pr-0 pl-lg-3 pr-lg-3 pr-md-3 pl-md-3">
<Form />
<FormDelivery />
</div>
{/* <Forminfo /> */}
</div>
</div>
</section>
</div>
</>
);
}}
</Query>
</Layout>
);
};
export default Product;
|
// Get a reference to the database service
var database = firebase.database();
function register(){
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var message=document.getElementById('message').value;
var firebaseRef = firebase.database().ref('users/');
var newmsg = firebaseRef.push();
if(email=='' || name ==''){
alert('please enter name and email ');
}
else{
newmsg.set({
username: name,
email: email,
user_mssage : message
})
}
}
//function writeUserData(userId, name, email, message) {
// firebase.database().ref('users/' + userId).set({
// username: name,
// email: email,
// user_mssage : messages
//
// });
//
//}
//
// writeUserData('',name,email,message);
// var firebaseRef;
//function register(){
//
//
// var name = document.getElementById('name').value;
// firebaseRef=firebase.database().ref();
//
//
// firebaseRef.on('value',snap => name = snap.value());
//
// }
|
import React, { Component } from "react";
import { Navbar, Home, OneItem } from "./components";
import {Switch, Route, BrowserRouter} from "react-router-dom";
import ShoppingCart from "./components/ShoppingCart";
class App extends Component {
render() {
return (
<BrowserRouter>
<div className="App">
<header className="header">
<Navbar />
</header>
<main>
<Home/>
{/*<Switch>*/}
{/*<Route*/}
{/*exact path="/"*/}
{/*component={ Home }*/}
{/*/>*/}
{/*<Route*/}
{/*exact path="/cart"*/}
{/*component={ ShoppingCart }*/}
{/*/>*/}
{/*<Route*/}
{/*exact path="/:id"*/}
{/*component={ OneItem }*/}
{/*/>*/}
{/*</Switch>*/}
</main>
</div>
</BrowserRouter>
);
}
}
export default App;
|
/*
James Cryer / Huddle 2014
URL: https://github.com/Huddle/Resemble.js
*/
'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const pngjs_1 = require("pngjs");
const fs_1 = __importDefault(require("fs"));
const jpeg_js_1 = __importDefault(require("jpeg-js"));
//keeping wrong indentation and '_this' for better diff with origin resemble.js
let _this = {};
let pixelTransparency = 1;
let errorPixelColor = {
// Color for Error Pixels. Between 0 and 255.
red: 255,
green: 0,
blue: 255,
alpha: 255,
};
let errorPixelTransform = {
flat: function (d1, d2) {
return {
r: errorPixelColor.red,
g: errorPixelColor.green,
b: errorPixelColor.blue,
a: errorPixelColor.alpha,
};
},
movement: function (d1, d2) {
return {
r: (d2.r * (errorPixelColor.red / 255) + errorPixelColor.red) / 2,
g: (d2.g * (errorPixelColor.green / 255) + errorPixelColor.green) / 2,
b: (d2.b * (errorPixelColor.blue / 255) + errorPixelColor.blue) / 2,
a: d2.a,
};
},
};
let errorPixelTransformer = errorPixelTransform.flat;
let largeImageThreshold = 1200;
function resemble(fileData) {
let data = {};
let images = [];
let updateCallbackArray = [];
let tolerance = {
// between 0 and 255
red: 16,
green: 16,
blue: 16,
alpha: 16,
minBrightness: 16,
maxBrightness: 240,
};
let ignoreAntialiasing = false;
let ignoreColors = false;
let ignoreRectangles = null;
function triggerDataUpdate() {
let len = updateCallbackArray.length;
let i;
for (i = 0; i < len; i++) {
if (typeof updateCallbackArray[i] === 'function') {
updateCallbackArray[i](data);
}
}
}
function loop(x, y, callback) {
let i, j;
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
callback(i, j);
}
}
}
function parseImage(sourceImageData, width, height) {
let pixleCount = 0;
let redTotal = 0;
let greenTotal = 0;
let blueTotal = 0;
let brightnessTotal = 0;
loop(height, width, function (verticalPos, horizontalPos) {
let offset = (verticalPos * width + horizontalPos) * 4;
let red = sourceImageData[offset];
let green = sourceImageData[offset + 1];
let blue = sourceImageData[offset + 2];
let brightness = getBrightness(red, green, blue);
pixleCount++;
redTotal += (red / 255) * 100;
greenTotal += (green / 255) * 100;
blueTotal += (blue / 255) * 100;
brightnessTotal += (brightness / 255) * 100;
});
data.red = Math.floor(redTotal / pixleCount);
data.green = Math.floor(greenTotal / pixleCount);
data.blue = Math.floor(blueTotal / pixleCount);
data.brightness = Math.floor(brightnessTotal / pixleCount);
triggerDataUpdate();
}
function loadImageData(fileData, callback) {
if (Buffer.isBuffer(fileData)) {
let png = new pngjs_1.PNG();
png.parse(fileData, function (err, data) {
callback(data, data.width, data.height);
});
}
else {
let ext = fileData.substring(fileData.lastIndexOf('.') + 1);
if (ext == 'png') {
let png = new pngjs_1.PNG();
fs_1.default.createReadStream(fileData)
.pipe(png)
.on('parsed', function () {
callback(this, this.width, this.height);
});
}
if (ext == 'jpg' || ext == 'jpeg') {
let jpegData = fs_1.default.readFileSync(fileData);
fileData = jpeg_js_1.default.decode(jpegData);
callback(fileData, fileData.width, fileData.height);
}
}
}
function isColorSimilar(a, b, color) {
let absDiff = Math.abs(a - b);
if (typeof a === 'undefined') {
return false;
}
if (typeof b === 'undefined') {
return false;
}
if (a === b) {
return true;
}
else if (absDiff < tolerance[color]) {
return true;
}
else {
return false;
}
}
function isNumber(n) {
return !isNaN(parseFloat(n));
}
function isPixelBrightnessSimilar(d1, d2) {
let alpha = isColorSimilar(d1.a, d2.a, 'alpha');
let brightness = isColorSimilar(d1.brightness, d2.brightness, 'minBrightness');
return brightness && alpha;
}
function getBrightness(r, g, b) {
return 0.3 * r + 0.59 * g + 0.11 * b;
}
function isRGBSame(d1, d2) {
let red = d1.r === d2.r;
let green = d1.g === d2.g;
let blue = d1.b === d2.b;
return red && green && blue;
}
function isRGBSimilar(d1, d2) {
let red = isColorSimilar(d1.r, d2.r, 'red');
let green = isColorSimilar(d1.g, d2.g, 'green');
let blue = isColorSimilar(d1.b, d2.b, 'blue');
let alpha = isColorSimilar(d1.a, d2.a, 'alpha');
return red && green && blue && alpha;
}
function isContrasting(d1, d2) {
return Math.abs(d1.brightness - d2.brightness) > tolerance.maxBrightness;
}
function getHue(r, g, b) {
r = r / 255;
g = g / 255;
b = b / 255;
let max = Math.max(r, g, b), min = Math.min(r, g, b);
let h;
let d;
if (max == min) {
h = 0; // achromatic
}
else {
d = max - min;
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return h;
}
function isAntialiased(sourcePix, data, cacheSet, verticalPos, horizontalPos, width) {
let offset;
let targetPix;
let distance = 1;
let i;
let j;
let hasHighContrastSibling = 0;
let hasSiblingWithDifferentHue = 0;
let hasEquivilantSibling = 0;
addHueInfo(sourcePix);
for (i = distance * -1; i <= distance; i++) {
for (j = distance * -1; j <= distance; j++) {
if (i === 0 && j === 0) {
// ignore source pixel
}
else {
offset = ((verticalPos + j) * width + (horizontalPos + i)) * 4;
targetPix = getPixelInfo(data, offset, cacheSet);
if (targetPix === null) {
continue;
}
addBrightnessInfo(targetPix);
addHueInfo(targetPix);
if (isContrasting(sourcePix, targetPix)) {
hasHighContrastSibling++;
}
if (isRGBSame(sourcePix, targetPix)) {
hasEquivilantSibling++;
}
if (Math.abs(targetPix.h - sourcePix.h) > 0.3) {
hasSiblingWithDifferentHue++;
}
if (hasSiblingWithDifferentHue > 1 || hasHighContrastSibling > 1) {
return true;
}
}
}
}
if (hasEquivilantSibling < 2) {
return true;
}
return false;
}
function errorPixel(px, offset, data1, data2) {
let data = errorPixelTransformer(data1, data2);
px[offset] = data.r;
px[offset + 1] = data.g;
px[offset + 2] = data.b;
px[offset + 3] = data.a;
}
function copyPixel(px, offset, data) {
px[offset] = data.r; //r
px[offset + 1] = data.g; //g
px[offset + 2] = data.b; //b
px[offset + 3] = data.a * pixelTransparency; //a
}
function copyGrayScalePixel(px, offset, data) {
px[offset] = data.brightness; //r
px[offset + 1] = data.brightness; //g
px[offset + 2] = data.brightness; //b
px[offset + 3] = data.a * pixelTransparency; //a
}
function getPixelInfo(data, offset, cacheSet) {
let r;
let g;
let b;
let d;
let a;
r = data[offset];
if (typeof r !== 'undefined') {
g = data[offset + 1];
b = data[offset + 2];
a = data[offset + 3];
d = {
r: r,
g: g,
b: b,
a: a,
};
return d;
}
else {
return null;
}
}
function addBrightnessInfo(data) {
data.brightness = getBrightness(data.r, data.g, data.b); // 'corrected' lightness
}
function addHueInfo(data) {
data.h = getHue(data.r, data.g, data.b);
}
function analyseImages(img1, img2, width, height) {
let data1 = img1.data;
let data2 = img2.data;
//TODO
let imgd = new pngjs_1.PNG({
width: img1.width,
height: img1.height,
deflateChunkSize: img1.deflateChunkSize,
deflateLevel: img1.deflateLevel,
deflateStrategy: img1.deflateStrategy,
});
let targetPix = imgd.data;
let mismatchCount = 0;
let time = Date.now();
let skip;
let currentRectangle = null;
let rectagnlesIdx = 0;
if (!!largeImageThreshold &&
ignoreAntialiasing &&
(width > largeImageThreshold || height > largeImageThreshold)) {
skip = 6;
}
loop(height, width, function (verticalPos, horizontalPos) {
let offset = (verticalPos * width + horizontalPos) * 4;
if (skip) {
// only skip if the image isn't small
if (verticalPos % skip === 0 || horizontalPos % skip === 0) {
copyPixel(targetPix, offset, {
r: 0,
b: 0,
g: 0,
a: 0,
});
return;
}
}
let pixel1 = getPixelInfo(data1, offset, 1);
let pixel2 = getPixelInfo(data2, offset, 2);
if (pixel1 === null || pixel2 === null) {
return;
}
if (ignoreRectangles) {
for (rectagnlesIdx = 0; rectagnlesIdx < ignoreRectangles.length; rectagnlesIdx++) {
currentRectangle = ignoreRectangles[rectagnlesIdx];
//console.log(currentRectangle, verticalPos, horizontalPos);
if (verticalPos >= currentRectangle[1] &&
verticalPos < currentRectangle[1] + currentRectangle[3] &&
horizontalPos >= currentRectangle[0] &&
horizontalPos < currentRectangle[0] + currentRectangle[2]) {
copyGrayScalePixel(targetPix, offset, pixel2);
//copyPixel(targetPix, offset, pixel1, pixel2);
return;
}
}
}
if (ignoreColors) {
addBrightnessInfo(pixel1);
addBrightnessInfo(pixel2);
if (isPixelBrightnessSimilar(pixel1, pixel2)) {
copyGrayScalePixel(targetPix, offset, pixel2);
}
else {
errorPixel(targetPix, offset, pixel1, pixel2);
mismatchCount++;
}
return;
}
if (isRGBSimilar(pixel1, pixel2)) {
copyPixel(targetPix, offset, pixel1);
}
else if (ignoreAntialiasing &&
(addBrightnessInfo(pixel1), // jit pixel info augmentation looks a little weird, sorry.
addBrightnessInfo(pixel2),
isAntialiased(pixel1, data1, 1, verticalPos, horizontalPos, width) ||
isAntialiased(pixel2, data2, 2, verticalPos, horizontalPos, width))) {
if (isPixelBrightnessSimilar(pixel1, pixel2)) {
copyGrayScalePixel(targetPix, offset, pixel2);
}
else {
errorPixel(targetPix, offset, pixel1, pixel2);
mismatchCount++;
}
}
else {
errorPixel(targetPix, offset, pixel1, pixel2);
mismatchCount++;
}
});
data.rawMisMatchPercentage = (mismatchCount / (height * width)) * 100;
data.misMatchPercentage = data.rawMisMatchPercentage.toFixed(2);
data.matchPercentage = 100 - data.misMatchPercentage;
data.analysisTime = Date.now() - time;
data.getDiffImage = () => imgd;
data.getDiffImageAsJPEG = function (quality) {
return jpeg_js_1.default.encode({
data: targetPix,
width: img1.width,
height: img1.height,
}, quality !== undefined ? quality : 50).data;
};
}
function compare(one, two) {
function onceWeHaveBoth(img) {
let width;
let height;
images.push(img);
if (images.length === 2) {
width = images[0].width > images[1].width ? images[0].width : images[1].width;
height = images[0].height > images[1].height ? images[0].height : images[1].height;
if (images[0].width === images[1].width && images[0].height === images[1].height) {
data.isSameDimensions = true;
}
else {
data.isSameDimensions = false;
}
data.dimensionDifference = {
width: images[0].width - images[1].width,
height: images[0].height - images[1].height,
};
//lksv: normalization removed
analyseImages(images[0], images[1], width, height);
triggerDataUpdate();
}
}
images = [];
loadImageData(one, onceWeHaveBoth);
loadImageData(two, onceWeHaveBoth);
}
function getCompareApi(param) {
let secondFileData, hasMethod = typeof param === 'function';
if (!hasMethod) {
// assume it's file data
secondFileData = param;
}
let self = {
ignoreNothing: function () {
tolerance.red = 16;
tolerance.green = 16;
tolerance.blue = 16;
tolerance.alpha = 16;
tolerance.minBrightness = 16;
tolerance.maxBrightness = 240;
ignoreAntialiasing = false;
ignoreColors = false;
if (hasMethod) {
param();
}
return self;
},
ignoreAntialiasing: function () {
tolerance.red = 32;
tolerance.green = 32;
tolerance.blue = 32;
tolerance.alpha = 32;
tolerance.minBrightness = 64;
tolerance.maxBrightness = 96;
ignoreAntialiasing = true;
ignoreColors = false;
if (hasMethod) {
param();
}
return self;
},
ignoreColors: function () {
tolerance.alpha = 16;
tolerance.minBrightness = 16;
tolerance.maxBrightness = 240;
ignoreAntialiasing = false;
ignoreColors = true;
if (hasMethod) {
param();
}
return self;
},
//array of rectangles, each rectangle is defined as (x, y, width. height)
//e.g. [[325, 170, 100, 40]]
ignoreRectangles: function (rectangles) {
ignoreRectangles = rectangles;
return self;
},
repaint: function () {
if (hasMethod) {
param();
}
return self;
},
onComplete: function (callback) {
updateCallbackArray.push(callback);
let wrapper = function () {
compare(fileData, secondFileData);
};
wrapper();
return getCompareApi(wrapper);
},
async: function () {
return new Promise(res => {
updateCallbackArray.push(res);
let wrapper = function () {
compare(fileData, secondFileData);
};
wrapper();
getCompareApi(wrapper);
});
},
};
return self;
}
return {
onComplete: function (callback) {
updateCallbackArray.push(callback);
loadImageData(fileData, function (imageData, width, height) {
parseImage(imageData.data, width, height);
});
},
async: function () {
return new Promise(res => {
updateCallbackArray.push(res);
loadImageData(fileData, (imageData, width, height) => {
parseImage(imageData.data, width, height);
});
});
},
compareTo: function (secondFileData) {
return getCompareApi(secondFileData);
},
};
}
resemble.outputSettings = function (options) {
let key;
let undefined;
if (options.errorColor) {
for (key in options.errorColor) {
errorPixelColor[key] =
options.errorColor[key] === undefined ? errorPixelColor[key] : options.errorColor[key];
}
}
if (options.errorType && errorPixelTransform[options.errorType]) {
errorPixelTransformer = errorPixelTransform[options.errorType];
}
pixelTransparency = options.transparency || pixelTransparency;
if (options.largeImageThreshold !== undefined) {
largeImageThreshold = options.largeImageThreshold;
}
return this;
};
resemble.compareImg = (inputImage, compareWith) => __awaiter(void 0, void 0, void 0, function* () {
return yield resemble(inputImage).compareTo(compareWith).ignoreNothing().async();
});
module.exports = resemble;
|
const name = 1 ;
const name1= "Sara";
|
function fillUpdate() {
hasPermission('mods-edit', true, {'gameshort': gameshort, 'modid': mod_id}, function(canUpdate) {
if (!canUpdate) {
window.location.href = "{{ path_for('not-found') }}";
return;
}
when(getJSON(backend + '/api/users/current'),
getJSON(backend + '/api/games/' + gameshort + '/versions'),
getJSON(backend + '/api/mods/' + gameshort + '/' + mod_id)).
done(function(currentUser, gameversions, mod) {
if (mod.error) {
window.location.href = "{{ path_for('not-found') }}";
return;
}
app = new Vue({
el: '#site',
data: {
'currentUser': currentUser.error ? null : currentUser.data,
'game_versions': gameversions.data,
'mod': mod.data,
'window': window
},
methods: {
'loginUserHotbar': loginUserHotbar,
'logoutUser': logoutUser,
'onUploadClick': onUploadClick,
'selectFile': selectFile,
'onSubmitClick': onSubmitClick
},
delimiters: ['${', '}']
});
window.setInterval(updateUpdate, update_interval);
window.addEventListener('dragenter', dragNop, false);
window.addEventListener('dragleave', dragNop, false);
window.addEventListener('dragover', dragNop, false);
window.addEventListener('drop', function(e) {
dragNop(e);
selectFile(e.dataTransfer.files[0]);
}, false);
$('#submit').removeAttr('disabled');
$.loadingBlockHide();
})});
}
function updateUpdate() {
hasPermission('mods-edit', true, {'gameshort': gameshort, 'modid': mod_id}, function(canUpdate) {
if (!canUpdate) {
window.location.href = "{{ path_for('not-found') }}";
return;
}
when(getJSON(backend + '/api/users/current'),
getJSON(backend + '/api/games/' + gameshort + '/versions'),
getJSON(backend + '/api/mods/' + gameshort + '/' + mod_id)).
done(function(currentUser, gameversions, mod) {
if (mod.error) {
window.location.href = "{{ path_for('not-found') }}";
return;
}
app.$data.currentUser = currentUser.error ? null : currentUser.data;
app.$data.game_versions = gameversions.data;
app.$data.window = window;
})});
}
function onUploadClick() {
$('.upload-mod input').click();
}
function dragNop(e) {
e.stopPropagation();
e.preventDefault();
}
var zipFile;
var loading = false;
function onSubmitClick(mod) {
$('.has-error').removeClass('has-error');
$('#error-alert').addClass('hidden');
var version = $('#mod-version').val();
var gameVersion = $('#mod-game-version').val();
var changelog = $('#changelog').val();
var notifyFollowers = $('#notify-followers').is(":checked");
var isBeta = $('#isBeta').is(":checked");
var valid = true;
if (version == '') {
error('mod-version');
valid = false;
}
if (gameVersion == '') {
error('mod-game-version');
valid = false;
}
if (zipFile == null) {
valid = false;
}
if (!valid) {
return;
}
if (loading) {
return;
}
loading = true;
showLoading();
updateMod(mod, version, gameVersion, notifyFollowers, isBeta, changelog, zipFile, function(i, data) {
$('#progress').removeClass('active');
if (!data.error) {
window.location.href = `{{ path_for("mod.view", {"id": "${mod.id}", "name": "${mod.name}"}) }}`;W
return;
} else {
$('#error-alert').removeClass('hidden');
$('#error-alert').text(data.reasons.join('\n'));
loading = false;
$.loadingBlockHide();
}
});
}
function selectFile(file) {
zipFile = file;
var parent = document.querySelector('.upload-mod');
parent.querySelector('a').classList.add('hidden');
var p = document.createElement('p');
p.textContent = 'Ready.';
parent.appendChild(p);
}
function error(name) {
document.getElementById(name).parentElement.classList.add('has-error')
document.getElementById('error-alert').classList.remove('hidden')
}
|
var app = app || {};
(function () {
'use strict';
app.IntroGroup = function (elementId) {
app.BaseGroup.call(this, elementId);
this.dirt1 = document.querySelector('#dirt1'),
this.dirt2 = document.querySelector('#dirt2'),
this.dirt3 = document.querySelector('#dirt3'),
this.rock1 = document.querySelector('#rock1');
};
app.IntroGroup.prototype = Object.create(app.BaseGroup.prototype);
app.IntroGroup.prototype.update = function () {
if (this.isGroupOnScreen()) {
// A little workaround for the chrome background-attachment/position relative bug
this.el.style.visibility = 'visible';
this.letItFly();
} else {
this.el.style.visibility = 'hidden';
}
};
app.IntroGroup.prototype.letItFly = function () {
var lastScrollY = this.main.lastScrollY;
var y1 = lastScrollY / 1.5,
y2 = lastScrollY / 2,
y3 = lastScrollY / 3,
y4 = -lastScrollY / 3,
x4 = -lastScrollY / 2;
this.translate(this.dirt1, 0, y1);
this.translate(this.dirt2, 0, y2);
this.translate(this.dirt3, 0, y3);
// TODO scale()
var r = lastScrollY / 4; // lastScrollY % 360
this.translateAndRotate(this.rock1, x4, y4, r);
};
}());
|
import { mapState, mapActions } from 'vuex';
import editTable from '@/components/edit-table';
export default {
data() {
return {
isValid: false,
loading: false,
pageSize: 10,
pageSizes: [10, 20, 30, 50, 100],
dataToUpdate: null,
editIndex: -1,
keys: [
{
name: 'category',
},
{
name: 'data',
type: 'textarea',
},
{
name: 'creator',
readonly: true,
},
],
dataToAdd: null,
};
},
methods: {
...mapActions([
'settingList',
'settingUpdate',
'settingAdd',
]),
getItems: async function getItems() {
if (this.loading) {
return;
}
this.loading = true;
try {
await this.settingList({
'cache-control': 'no-cache',
});
} catch (err) {
this.$alert(err);
} finally {
this.loading = false;
}
},
handleEdit: function handleEdit(index) {
editTable.handleEdit.bind(this)(index);
const {
data,
} = this.dataToUpdate;
if (data) {
this.dataToUpdate.data = JSON.stringify(data, null, 2);
}
},
update: function update(id, data) {
return this.settingUpdate(id, data);
},
handleUpdate: function handleUpdate(index) {
editTable.handleUpdate.bind(this)(index, 'name');
},
save: function save(data) {
try {
data.data = JSON.parse(data.data);
} catch (err) {
this.$alert(err);
throw err;
}
return this.settingAdd(data);
},
handleAdd: editTable.handleAdd,
handleSave: editTable.handleSave,
handleChangePage: editTable.handleChangePage,
handleSizeChange: editTable.handleSizeChange,
handleSortChange: editTable.handleSortChange,
handleSearch: editTable.handleSearch,
},
computed: {
...mapState({
userInfo: state => state.user.info,
items: (state) => {
const items = state.setting.items;
if (!items) {
return null;
}
return items.concat({});
},
total: state => state.setting.total,
}),
type: editTable.type,
},
};
|
module.exports = {
// purge: [],
purge: ["./src/**/*.js", "./public/index.html"],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {
colors: {
orange: {
200: "#FFAB91",
300: "#FF8A65",
400: "#FF7043",
500: "#FF5722",
600: "#F4511E",
700: "#E64A19",
800: "#D84315",
900: "#BF360C",
A400: "#FF3D00",
},
},
borderWidth: {
3: "3px",
},
margin: {
34: "8.7rem",
},
screens: {
xs: { max: "639px" },
},
},
},
variants: {},
plugins: [],
};
|
#pragma strict
var skySetMode : int;
var sky : MeshRenderer;
var sun : Light;
var reverse : Light;
var low : Light;
var skArray : Color [];
var suArray : Color [];
var reArray : Color [];
var loArray : Color [];
function Start ()
{
SkySet ();
}
function Update ()
{
if (Input.GetKeyDown (KeyCode.P) && (skySetMode < skArray.Length))
{
skySetMode ++;
SkySet ();
}
if (Input.GetKeyDown (KeyCode.O) && (skySetMode > 0))
{
skySetMode --;
SkySet ();
}
}
function SkySet ()
{
sky.enabled = true;
if (skySetMode != 0)
{
sky.material.color = skArray [skySetMode -1];
sun.color = suArray [skySetMode -1];
reverse.color = reArray [skySetMode -1];
low.color = loArray [skySetMode -1];
}
else
{
sky.enabled = false;
sun.color = Color.white;
}
}
|
import { Carousel } from 'react-bootstrap';
const CarouselHome = () => {
return (
<>
<div className='container-fluid' style={{ 'padding': "0" }} >
<Carousel fade>
<Carousel.Item>
<img
className="d-block w-100"
src="https://res.cloudinary.com/dzbcqgzcb/image/upload/v1627242527/IronHome/Iron%20Home/1_tqegg6.jpg"
alt="First slide"
/>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block w-100"
src="https://res.cloudinary.com/dzbcqgzcb/image/upload/v1627242525/IronHome/Iron%20Home/2_whdjup.jpg"
alt="Second slide"
/>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block w-100"
src="https://res.cloudinary.com/dzbcqgzcb/image/upload/v1627242536/IronHome/Iron%20Home/4_x78w4b.jpg"
alt="Third slide"
/>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block w-100"
src="https://res.cloudinary.com/dzbcqgzcb/image/upload/v1627242522/IronHome/Iron%20Home/3_l0gvjk.jpg"
alt="Third slide"
/>
</Carousel.Item>
</Carousel>
</div>
</>
)
}
export default CarouselHome
|
import React, {useState, useContext} from 'react'
import { GlobalState } from '../../GS'
import {FaHamburger, FaTimes, FaShoppingCart, FaUtensils} from 'react-icons/fa';
import {Link} from 'react-router-dom';
import axios from 'axios';
const Header = () => {
const state = useContext(GlobalState);
const [isLogged, setIsLogged] = state.userAPI.isLogged;
const [isAdmin, setIsAdmin] = state.userAPI.isAdmin;
const [cart] = state.userAPI.cart;
const logoutUser = async () =>{
await axios.get('/user/logout');
localStorage.clear();
setIsAdmin(false);
setIsLogged(false);
}
const adminRouter = ()=>{
return(
<>
<li><Link to="/create_item">Create Item</Link></li>
<li><Link to="/category">Categories</Link></li>
</>
)
}
const loggedRouter = ()=>{
return(
<>
<li><Link to="/history">Order History</Link></li>
<li><Link to="/" onClick={logoutUser}>Logout</Link></li>
</>
)
}
return (
<header>
<div className="menu">
<i><FaHamburger size="30px"/></i>
</div>
<div className="logo">
<h1><Link to="/">{isAdmin ? 'Admin' : 'Burger'}</Link></h1>
</div>
<ul>
<li><Link to="/">{isAdmin ? 'Burger' : 'Burger' }</Link></li>
{isAdmin && adminRouter()}
{
isLogged ? loggedRouter() : <li><Link to="/login">Login & Register</Link></li>
}
<li>
<i><FaTimes size="30px" className="menu" /></i>
</li>
</ul>
{
isAdmin ? ''
: <div className="cart-icon">
<span>{cart.length}</span><Link to="/cart"><FaUtensils size="30" /></Link>
</div>
}
</header>
)
}
export default Header
|
var gulp = require('gulp');
var sass = require('gulp-sass');
var notify = require("gulp-notify");
var bower = require('gulp-bower');
var jshint = require('gulp-jshint');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var cssnano = require('gulp-cssnano');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var config = {
assetsFolderName: 'assets',
sassPath: './src/styles',
imgPath: './src/images',
jsPath: './src/scripts'
}
var concat = require('gulp-concat');
gulp.task('scripts', function() {
return gulp.src([
config.jsPath + '/partials/*.js'
])
.pipe(concat('script.js')).pipe(uglify())
.pipe(gulp.dest('./' + config.assetsFolderName + '/js/'));
});
gulp.task('styles', function() {
return gulp.src(config.sassPath + '/notes.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer())
.pipe(cssnano())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./' + config.assetsFolderName + '/css/'));
});
gulp.task('images', function() {
return gulp.src(config.imgPath + '/**/*')
.pipe(gulp.dest('./' + config.assetsFolderName + '/img/'));
});
// Rerun the task when a file changes
gulp.task('watch', function() {
gulp.watch(config.sassPath + '/**/*.scss', ['styles']);
gulp.watch(config.imgPath + '/**/*', ['images']);
gulp.watch(config.jsPath + '/**/*.js', ['scripts']);
});
gulp.task('default', ['styles', 'scripts', 'images', 'watch']);
gulp.task('build', ['styles', 'scripts', 'images']);
|
/**
* @module main
* @description This is the main js module included via require.js
* @copyright mehrwert
* @version $Id: main.js 3478 2012-12-10 15:30:48Z m.straschek $
*/
require.config({
// @TODO This should not be necessary:
paths: {
jquery: 'libs/jquery/jquery',
breakpoint: 'libs/jquery/jquery.mw_breakpoint',
pageHandler: 'libs/jquery/jquery.dtag_pageHandler',
headerLoader: 'libs/jquery/jquery.dtag_headerLoader',
dialogHandler: 'libs/jquery/jquery.dtag_dialogHandler',
transit: 'libs/jquery/jquery.transit',
chosen: 'libs/jquery/chosen.jquery'
}
});
/**
* Main require function
* Actually does nothing more but require wrapper module
*
* @requires wrapper
*/
define([
'jquery',
'shared/config/jquery',
'template/drawerSlider',
'template/helpdesk',
'transit',
'template/headerLoader',
'components/rowevents',
'components/forms',
'components/tables',
'breakpoint',
'components/tooltip',
'components/toolbar',
'components/treelist',
'components/dialogHandler',
'components/dialog',
'components/validate'
], function(
$,
cfg,
drawerSlider,
helpdesk
) {
var settingsSlider,
settingsDropdown,
exports = {
/**
* Callback functions
*/
callbacks: {
/**
* Smartphone view
* @scope exports
*/
smartphone: function() {
/**
* @requires template/moveSearch
* @requires template/moveSettings
* @requires template/moveTitleBar
* @requires template/settingsSlider
*/
require([
'template/moveSearch',
'template/moveSettings',
'template/moveTitleBar',
'template/settingsSlider'
], function(
moveSearch,
moveSettings,
moveTitleBar,
settingsSliderObj
) {
moveSearch.move('back');
moveSettings.move();
moveTitleBar.move();
settingsSlider = settingsSliderObj;
settingsSlider.setDrawerSliderObject(drawerSlider);
// detach due to possible headerLoader issues
settingsSlider.detach();
settingsSlider.attach();
if ( typeof settingsDropdown === 'object' ) {
settingsDropdown.detach();
}
});
drawerSlider.moveCaller('#dtag_brandlevel .dtag-grid-col-right');
},
/**
* Tablet view
* @scope exports
*/
tablet: function() {
/**
* @requires template/moveSearch
* @requires template/moveSettings
* @requires template/moveTitleBar
* @requires template/settingsDropdown
*/
require([
'template/moveSearch',
'template/moveSettings',
'template/moveTitleBar',
'template/settingsDropdown'
], function(
moveSearch,
moveSettings,
moveTitleBar,
settingsDropdownObj
) {
moveSearch.move();
moveSettings.move('back');
moveTitleBar.move('back');
settingsDropdown = settingsDropdownObj;
// detach due to possible headerLoader issues
settingsDropdown.detach();
settingsDropdown.attach();
if ( typeof settingsSlider === 'object' ) {
settingsSlider.detach();
}
});
drawerSlider.moveCaller('#dtag_brandlevel .dtag-grid-col-center');
},
/**
* Desktop view
* @scope exports
*
*/
desktop: function() {
/**
* @requires template/moveSearch
* @requires template/settingsDropdown
*/
require([
'template/moveSearch',
'template/settingsDropdown'
], function(
moveSearch,
settingsDropdownObj
) {
moveSearch.move();
settingsDropdown = settingsDropdownObj;
// detach due to possible headerLoader issues
settingsDropdown.detach();
settingsDropdown.attach();
});
}
},
/**
* Init function
*/
init: function() {
$('#dtag_jumpmarks').hide();
$('#dtag_wrapper').css('padding-bottom', '2em');
drawerSlider.attach();
if ($('body.dtag-start-page').length > 0) {
helpdesk.appendToTitleBar();
} else {
helpdesk.appendToServiceLevel();
}
// due to jumpmark issues (having addressed element on top of screen)
// the wrapper was css-ed with a huge padding bottom
$('#wrapper').css('padding-bottom', 0);
$.fn.mw_breakpoint({
callback: function(device) {
switch (device) {
case 'smartphone':
exports.callbacks.smartphone();
break;
case 'tablet':
exports.callbacks.tablet();
break;
case 'desktop':
exports.callbacks.desktop();
break;
default:
// do nothing;
break;
}
}
});
}
};
$(function() {
exports.init();
});
});
|
import React from 'react'
import skills from '../data/skills.js'
export default function Skills() {
return (
<div id='skills-container' className='tabcontent'>
{skills.map((skill) => {
return (
<React.Fragment key={skill.title.toLowerCase().trim()}>
<span className='skill-titles'>
<img src={require(`../assets/${skill.icon}`)} alt='Skill icon'></img>
{skill.title}
</span>
<div>
<span
className='meter'
style={{
width: `${skill.percent}%`,
animation: `fill${skill.percent} 1.5s cubic-bezier(.29,.23,0,.81)`,
}}></span>
</div>
</React.Fragment>
)
})}
</div>
)
}
|
import React, { Component } from 'react';
import moment from 'moment';
import Chart from './Chart';
class SingleCurr extends Component {
constructor(props) {
super(props);
this.state = {
displayChart: 'month' // six-months, year
}
}
changeChart = (displayChart) => {
this.setState({ displayChart });
[...this.choose.children].forEach(p => p.classList.remove('active'));
this.choose.querySelector(`.${displayChart}`).classList.add('active');
}
render() {
const { currency, code, rates, deleteCurrency } = this.props;
const lastRate = rates[rates.length - 1].mid;
const date = rates[rates.length - 1].effectiveDate;
let labels = [], data = [];
rates.forEach(rate => {
labels.push(rate.effectiveDate);
data.push(rate.mid);
});
return (
<div className="currencyCard" id={code}>
<div className="currencyCard__header">
<p className="currencyCard__header__currency">{currency}</p>
<p className="currencyCard__header__code">1 {code}</p>
<p className="currencyCard__header__rate"><span>{Number(lastRate).toFixed(4)}</span> PLN</p>
<p className="currencyCard__header__delete" onClick={() => deleteCurrency(code)}>✕</p>
</div>
<div className="currencyCard__chart">
<div className="currencyCard__chart__date">
<p>{moment(date).format('DD-MM-YYYY')}</p>
</div>
<div className="currencyCard__chart__choose" ref={ref => (this.choose = ref)}>
<p onClick={() => this.changeChart('month')} className="chooseDisplay month active">miesiąc</p>
<p onClick={() => this.changeChart('six-months')} className="chooseDisplay six-months">pół roku</p>
<p onClick={() => this.changeChart('year')} className="chooseDisplay year">rok</p>
</div>
<Chart code={code} labels={labels} data={data} display={this.state.displayChart} />
</div>
</div>
);
}
}
export default SingleCurr;
|
$(document).ready(function(){
$("strong.cooking").click(function(){
$("#comment").hide();
$("#cooking").show();
});
$("strong.comment").click(function(){
$("#cooking").hide();
$("#comment").show();
});
$("span").click(function(){
$("div.reply").show();
});
});
|
import { searchedTracks } from './searchedTracks';
import { trackList } from './trackList';
import { responseStatus } from './responseStatus';
import { combineReducers } from 'redux';
const rootReducer = combineReducers({
searchedTracks,
trackList,
responseStatus,
});
export default rootReducer;
|
// jsが機能してるかどうか
window.onload = function () {
var obj = document.getElementById("idname");
obj.style.color = 'red'; //文字色を赤にする
};
function test2() {
var keyname = event.key
var test = document.getElementById('key_test')
var problem_ro = document.getElementById('problem_ro')
var problem_ja = document.getElementById('problem_ja')
var judge = document.getElementById('judge')
if (keyname === 'Enter') {
if (test.innerText === problem_ro.innerText) {
var rand = Math.floor(Math.random()*gon.problem_ja.length)
problem_ja.innerText = gon.problem_ja[rand]
problem_ro.innerText = gon.problem_ro[rand]
test.innerText = ""
judge.innerText = "正解"
judge.style.color = 'red'
} else {
test.innerText = ""
judge.innerText = "不正解"
judge.style.color = 'blue'
}
} else if (keyname === 'Backspace') {
test.innerText = test.innerText.slice(0, -1);
} else {
test.innerText += keyname
judge.innerText = ""
}
};
document.body.addEventListener('keydown', test2);
document.getElementById('reset_btn').onclick = function () {
document.getElementById('key_test').innerText = "";
}
|
module.exports = function()
{
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProfessorSchema = new Schema(
{
nome:String,
data_vinculo: {type: Date, default: Date.now},
curso_atuante:String,
formacao:String
});
return mongoose.model('Professores', ProfessorSchema);
}
|
import { createStore } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage'
import rootReducer from './Reducers/rootReducers';
const persistConfig = {
key:'root',
storage: storage
}
const persistedReducer = persistReducer(persistConfig, rootReducer)
let store = createStore(persistedReducer);
let persistor = persistStore(store);
export {store, persistor};
|
var warriorQuotes = [
'Out of suffering have emerged the strongest souls; the most massive characters are seared with scars. -Kahil Gibran',
'The successful warrior is the average man, with laser-like focus. -Bruce Lee',
'He who conquers himself is the mightiest warrior. -Confucius',
'Weapons may be carried by creatures who are evil, dishonest, violent or lazy. The true warrior is good, gentle and honest. His bravery comes from within himself; he learns to conquer his own fears and misdeeds. -Brian Jacques',
'The basic difference between an ordinary man and a warrior is that a warrior takes everything as a challenge while an ordinary man takes everything as a blessing or a curse. -Carlos Castaneda',
"Fate whispers to the warrior, ‘You can not withstand the storm.’ The warrior whispers back, ‘I am the storm.' -Jake Remington",
]
function nextQuote() {
var selectQuote = Math.floor(Math.random() * (warriorQuotes.length));
document.getElementById('warriorMind').innerHTML = warriorQuotes[selectQuote];
}
|
const mongoose = require('mongoose');
const MAX_PER_PAGE = 500;
const SORT_DESC = -1;
const MIN_PAGE = 1;
const LinkSchema = mongoose.Schema(
{
reference: String,
url: String,
title: String,
authorUserAgent: String,
},
{ timestamps: true }
);
const LinkModel = mongoose.model('Link', LinkSchema);
const failWithError = msg => {
throw new Error(msg);
};
class Database {
saveLink(
reference = failWithError('Reference is required'),
link = failWithError('Link is required'),
authorUserAgent = 'unknown'
) {
const parameters = {
reference,
url: link.url || failWithError('URL is required'),
title: link.title || failWithError('Title is required'),
authorUserAgent,
};
return LinkModel.create(parameters);
}
find(reference = failWithError('Reference is required'), page, perPage) {
page = Number(page < MIN_PAGE ? MIN_PAGE : page);
perPage = Number(perPage > MAX_PER_PAGE ? MAX_PER_PAGE : perPage);
return LinkModel.find({ reference })
.limit(perPage)
.skip((page - 1) * perPage)
.sort({ createdAt: SORT_DESC });
}
}
module.exports = (...args) => new Database(...args);
|
$(document).ready(function() {
var position = navigator.geolocation.getCurrentPosition(LatLong,null);
FindLocation();
LatLong(position);
});
function FindLocation() {
if (!navigator.geolocation) {
$("#display").text("Use a different bowser");
console.log("error");
} else {
console.log("nice");
}
}
function LatLong(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var WeatherType;
var weather;
var DynamicWeather;
var wind;
var area;
var html;
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&appid=" + "1c3dfe0d9317c6d9db73bc54e907d7de", function (data) {
weather = data.weather[0].main;
WeatherType = data.weather[0].description;
wind = data.wind.speed;
area = data.name;
if(weather === "Rain"){
$("body").css("background-image",'url("http://i.imgur.com/8aX07js.jpg")');
}
if(weather === "Clouds"){
$("body").css("background-image",'url("http://i.imgur.com/IaEHwyB.jpg")');
}
if(weather === "Clear") {
$("body").css("background-image",'url("https://farm1.staticflickr.com/691/20664938416_4e4b224684_h.jpg")');
}
html = '<p>';
html += area;
html += '</p>';
$( '<p>' + area + '</p>').appendTo(".area");
$( '<p>' + weather + '</p>').appendTo(".type");
});
}
|
var helpers = {
HOUR: function() {
return HOUR
},
DAY: function() {
return DAY
},
MONTH: function() {
return MONTH
},
hours: function() {
return [
{name: "1", value: 1},
{name: "2", value: 2},
{name: "3", value: 3},
{name: "4", value: 4},
{name: "5", value: 5},
{name: "6", value: 6},
{name: "7", value: 7},
{name: "8", value: 8},
{name: "9", value: 9},
{name: "10", value: 10},
{name: "11", value: 11},
{name: "12", value: 0},
] },
minutes: function() {
return [
{name: "00", value: 0},
{name: "15", value: 15},
{name: "30", value: 30},
{name: "45", value: 45},
] },
duration: function() {
return this.quantity + " " + this.unit + "s"
},
dateAgo: function(date) {
return moment(date).fromNow()
},
dateSpecific: function(date) {
return moment(date).format('lll')
},
dateSlashed: function(date) {
return moment(date).format('ll')
},
monthlyNums: function() {
return monthNums
},
dailyNums: function() {
return dayNums
},
// Must be 18 to play
dobYears() {
var now = 2016
return _.map(buildFullArray(now - 121, now - 18), year => {
return {value: year, label: year}
})
},
dobMonths() {
return [
{value: 1, label: "January"},
{value: 2, label: "February"},
{value: 3, label: "March"},
{value: 4, label: "April"},
{value: 5, label: "May"},
{value: 6, label: "June"},
{value: 7, label: "July"},
{value: 8, label: "August"},
{value: 9, label: "September"},
{value: 10, label: "October"},
{value: 11, label: "November"},
{value: 12, label: "December"},
]
},
dobDays() {
return _.map(dayNums, day => {
return {value: day, label: day}
})
},
hourlyNums: function() {
return [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
},
ampm: function() {
return [
{name: AM, value: AM},
{name: PM, value: PM},
]
},
}
_.each(helpers, function(helper, name) {
Template.registerHelper(name, helper)
})
var monthNums = [1,2,3,4,5,6,7,8,9,10,11,12]
var dayNums = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,30, 31
]
|
import React from "react"
import styled from "styled-components"
const Container = styled.span`
padding: 5rem 0;
font-family: "Playfair Display", serif;
font-weight: 700;
font-size: 6rem;
font-style: oblique;
text-align: center;
display: block;
color: #fff;
span {
color: #0074b8;
}
@media only screen and(max-width: 56.25em) {
font-size: 5rem;
}
@media only screen and (max-width: 41em) {
font-size: 4rem;
span {
display: block;
}
}
`
const Tagline = ({ children }) => <Container>{children}</Container>
export default Tagline
|
require('string.prototype.startswith')
require('string.prototype.endswith')
require('es6-promise').polyfill()
require('flexible')
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import {census} from './utils'
census()
import App from './routes'
import '../assets/scss/main.scss'
import axios from 'axios'
axios.defaults.withCredentials = true
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
const app = document.getElementById('app')
if (process.env.NODE_ENV === `develop`) {
ReactDOM.render(<AppContainer><App/></AppContainer>, app)
if (module.hot) {
module.hot.accept('./routes', () => {
const NextApp = require('./routes').default
ReactDOM.render(
<AppContainer>
<NextApp />
</AppContainer>,
app
)
})
}
} else {
ReactDOM.render(<App/>, app)
}
|
// Find elements
var showPrevBtn = document.getElementById("show_previous");
var showNextBtn = document.getElementById("show_next");
var slideImage = document.getElementById("slide_image");
showPrevBtn.addEventListener("click", showPrevBtnClick);
showNextBtn.addEventListener("click", showNextBtnClick);
// Create images array
var imagesSrcs = [];
imagesSrcs.push("images/provence1.jpg");
imagesSrcs.push("images/provence_side_view.png");
imagesSrcs.push("images/provence_full_size.png");
var currentImageIndex = 0;
slideImage.src = imagesSrcs[currentImageIndex];
showPrevBtn.disabled = true;
// Functions definitions
function showPrevBtnClick() {
currentImageIndex--;
slideImage.src = imagesSrcs[currentImageIndex];
showNextBtn.disabled = false;
// Disable Next Button if it needs
if (currentImageIndex === 0) {
showPrevBtn.disabled = true;
}
}
function showNextBtnClick() {
currentImageIndex++;
slideImage.src = imagesSrcs[currentImageIndex];
showPrevBtn.disabled = false;
// Disable Next Button if it needs
if (currentImageIndex === (imagesSrcs.length - 1)) {
showNextBtn.disabled = true;
}
}
|
var mongoose = require('mongoose');
var http = require('http');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var conn = mongoose.connect('mongodb://admin:123@ds151232.mlab.com:51232/sumit');
var details = mongoose.Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
firstname: { type: String, required: true },
lastname: { type: String, required: true }
}, {
collection: 'users',
strict: true
});
var user_address = mongoose.Schema({
user_id: { type: String, required: true, ref: 'users_model' },
address: Array,
phone_no: Number
}, {
collection: 'address',
strict: true
});
var users_model = conn.model('users_model', details);
var user_address_model = conn.model('user_address_model', user_address);
module.exports = {
user: users_model,
address: user_address_model,
}
|
angular.module('ChartModule', ['ngSanitize'])
.controller('ChartController', function($scope, $connector, $sce) {
$scope.sliderPos = 0;
$scope.content = function() {
var res = $scope.userState.entries[$scope.sliderPos];
return $sce.trustAsHtml(res);
};
$scope.moveSlider = function(val) {
$scope.sliderPos = val;
$scope.sliderUpdated();
};
$scope.sliderUpdated = function() {
$connector.setDeferredVariable("sliderPos", parseInt($scope.sliderPos));
};
$scope.clickButton = function() {
$connector.button_click();
};
});
|
Template.SideNav.events({
'click .link': function() {
console.log("Hello World");
}
})
|
(function arrayExtension() {
Array.prototype.last = function () {
return this[this.length - 1];
};
Array.prototype.skip = function (n) {
let newArr = [];
n = Math.abs(n);
for (let i = n; i < this.length; i++) {
newArr.push(this[i]);
}
return newArr;
};
Array.prototype.take = function (n) {
let newArr = [];
n = Math.abs(n);
for (let i = 0; i < n; i++) {
newArr.push(this[i]);
}
return newArr;
};
Array.prototype.sum = function () {
return this.reduce((acc, current) => acc + current);
};
Array.prototype.average = function () {
return this.sum() / this.length;
};
})()
let arr = [1, 2, 3];
console.log(typeof arr);
console.log(Array.prototype.hasOwnProperty('last'));
console.log(arr.last());
console.log(arr.skip(2));
console.log(arr.take(2));
console.log(arr.sum());
|
import React, { useState } from "react";
export const EditField = ({
editValue,
handleEditChange,
handleEditSubmit,
}) => {
return (
<div>
<form onSubmit={handleEditSubmit}>
<input type="text" value={editValue} onChange={handleEditChange} />
<input className="btn btn-success" type="submit" value="ADD" />
</form>
</div>
);
};
|
import React from 'react';
import LanguageContext from '../contexts/LanguageContext' ;
class Button extends React.Component {
static contextType = LanguageContext; // This is actually kind of similar to using the useContext hook. useContext is slightly more readable. contextType is a property of a React.Component class component. useContext hook can be used in functional components, doesn\'t require the class.
render(){
const text = this.context === 'English' ? 'Submit' : 'Clic'
return(
<button>{text}</button>
);
}
}
export default Button;
|
/**
* 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', './util/rest', './util/ui_util', './graph/table', './graph/timeline'], function($, rest, ui_util, table, timeline) {
var COMPARATOR_DROPDOWN_CONTENTS = ['less than',
'greater than',
'greater than or equal to',
'less than or equal to',
'equals',
'not equals',
'contains'];
var CUSTOM_SEARCH_CRITERIA = ["Cluster Size", "tag"];
var getAttributeList = function(baseURL, datasetName, callback) {
rest.get(baseURL + "rest/data/attributes/" + datasetName, 'Get attributes', callback);
};
var getAttributeValues = function(baseURL, datasetName, attributeName, callback){
rest.get(baseURL + "rest/data/values/" + datasetName + "/" + attributeName, 'Get values', callback);
};
var searchClusters = function(baseURL, datasetName, outputName, filters, callback){
rest.post(baseURL + "rest/search",
{ datasetName : datasetName, outputName : outputName, filters: filters},
"Search ads", callback, false);
};
var createFilterRow = function(widget) {
var rowObject = {};
rowObject.type = "filter";
rowObject.attributeDiv = $('<div/>');
var attributeDropdownContents = widget.attributes.slice(0);
for (var i = 0; i < CUSTOM_SEARCH_CRITERIA.length; i++) {
attributeDropdownContents.unshift(CUSTOM_SEARCH_CRITERIA[i]);
}
rowObject.attributeDropdown = ui_util.createDropdown(attributeDropdownContents, 90, function(event) {});
rowObject.attributeDiv.append(rowObject.attributeDropdown);
rowObject.attributeDropdown.value = 'name';
rowObject.conditionDropdown = ui_util.createDropdown(COMPARATOR_DROPDOWN_CONTENTS, 90, function(event){});
rowObject.attributeDiv.append(rowObject.conditionDropdown);
rowObject.conditionDropdown.value = 'contains';
rowObject.inputBox = $('<input/>');
rowObject.inputBox.css({left:'180px',right:'30px',position:'absolute'});
rowObject.attributeDiv.append(rowObject.inputBox);
var removeButton = $('<button/>');
removeButton.text('x');
removeButton.click(function() {
rowObject.attributeDiv.remove();
var rmIdx = widget.attributeRows.indexOf(rowObject);
widget.attributeRows.splice(rmIdx, 1);
}).css({position:'absolute',right:'0px'});
rowObject.attributeDiv.append(removeButton);
widget.attributeArea.appendChild(rowObject.attributeDiv.get(0));
return rowObject;
};
var updateAttributeRows = function(widget) {
for (var i=0; i<widget.attributeRows.length; i++) {
var rowObject = widget.attributeRows[i];
ui_util.setDropdownOptions(rowObject.attributeDropdown, widget.attributes);
}
};
var createWidget = function(container, baseUrl) {
var subsetWidget = {
attributes: [],
attributeRows: [],
datasetInput: null,
attributeArea: null,
resultArea: null,
init: function() {
var that = this;
var datasetLabel = document.createTextNode("Dataset Name:");
container.appendChild(datasetLabel);
this.datasetInput = document.createElement('input');
this.datasetInput.value = 'ads';
container.appendChild(this.datasetInput);
this.attributeArea = document.createElement('div');
container.appendChild(this.attributeArea);
var addButton = document.createElement("button");
addButton.innerHTML = '+';
$(addButton).click(function() {
that.createAttributeRow();
});
container.appendChild(addButton);
container.appendChild(document.createElement('br'));
var outputLabel = document.createTextNode("Output Name:");
container.appendChild(outputLabel);
this.outputInput = document.createElement('input');
this.outputInput.value = 'subset';
container.appendChild(this.outputInput);
var searchButton = document.createElement("button");
searchButton.innerHTML = 'search';
$(searchButton).click(function() {
that.doSearch();
});
container.appendChild(searchButton);
var linksButton = document.createElement("button");
linksButton.innerHTML = 'links';
$(linksButton).click(function() {
window.location.assign(baseUrl + '#link');
window.location.reload(true);
});
container.appendChild(linksButton);
this.resultArea = document.createElement('div');
container.appendChild(this.resultArea);
getAttributeList(baseUrl, this.datasetInput.value, function(response) {
that.attributes = response.columns.list;
if(!that.attributes){
return;
}
that.attributes.splice(0,0,"NONE");
updateAttributeRows(that);
});
},
doSearch: function() {
var that = this;
var filters = [];
for (var i=0; i<this.attributeRows.length; i++) {
filters.push({
filterAttribute: this.attributeRows[i].attributeDropdown.value,
comparator: this.attributeRows[i].conditionDropdown.value,
value: this.attributeRows[i].inputBox.val()
});
}
searchClusters(baseUrl, this.datasetInput.value, this.outputInput.value, filters, function(response) {
$(that.resultArea).empty();
that.resultArea.appendChild(document.createTextNode('Matches: ' + response.memberDetails.length));
var tableDiv = $('<div></div>');
tableDiv.addClass('searchTable');
$(that.resultArea).append(tableDiv);
var headers = [];
var dataRows = [];
for (var i=0; i<response.memberDetails.length; i++) {
var entries = response.memberDetails[i].map.entry;
var values = {};
for (var j=0; j<entries.length; j++) {
var entry = entries[j];
if (i==0) {
headers.push(entry.key);
}
values[entry.key] = entry.value;
}
dataRows.push(values);
}
that.table = table.createJQTable(baseUrl,tableDiv, headers, dataRows);
var timelineDiv = document.createElement('div');
$(timelineDiv).css({position:'absolute',top:'150px',height:'150px',left:'0px',right:'0px'});
that.resultArea.appendChild(timelineDiv);
that.timeline = new timeline.widget(timelineDiv, dataRows);
that.timeline.resize($(container).width(), 150);
});
},
createAttributeRow: function() {
// var rowObject = createAttributeRow(baseUrl, this);
var rowObject = createFilterRow(this);
this.attributeRows.push(rowObject);
},
resize: function(width,height) {
if (this.table) {
this.table.fnAdjustColumnSizing();
}
}
}
subsetWidget.init();
return subsetWidget;
}
return {
createWidget:createWidget
}
});
|
import React, {Component} from 'react';
import {StyleSheet, View, FlatList, RefreshControl, ActivityIndicator} from 'react-native';
import { NavigationEvents } from 'react-navigation';
import {loadProjects} from '../../Networking';
import {CommonCell} from '../UIKit';
import {routes} from '../../Constants';
class CurrentProjectsScreen extends Component {
constructor(props) {
super(props);
this.state = {
projectView: { SignedProjects: [] },
loading: true,
};
}
componentDidMount() {
this._loadProjects();
}
_loadProjects = () => {
loadProjects((error, projectView) => {
if (error) {
this.setState({loading: false});
alert(error);
} else {
this.setState({projectView, loading: false});
}
});
};
_renderItem = ({item}) => {
const project = {
id: item.Id,
title: item.Title,
description: item.Description,
};
return (
<CommonCell
key={item.Id}
{...item}
onPress={() => this.props.navigation.navigate(routes.ProjectDetailsStack, {project})}
/>
);
};
render() {
const {projectView, loading} = this.state;
if (loading) {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<ActivityIndicator size="large" color="#03bafc" />
</View>
);
}
return (
<View style={{flex: 1}}>
<NavigationEvents
onWillFocus={() => {
this._loadProjects();
}}
/>
<FlatList
style={styles.container}
contentContainerStyle={styles.contentContainer}
data={projectView?.acceptedProjects}
keyExtractor={(item, index) => index.toString()}
renderItem={this._renderItem}
refreshControl={<RefreshControl refreshing={loading} onRefresh={this._loadProjects} />}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
},
contentContainer: {
marginTop: 10,
paddingBottom: 30,
},
});
export default CurrentProjectsScreen;
|
import { Thing } from "./thing.js";
import { Circuit } from "./circuit.js";
import * as gate from "./logicGate.js";
import { Wire } from "./wire.js";
import { Camera } from "./camera.js";
class Vertical extends gate.Constant {
/**
* Vertical constructor
* @param {Circuit} circuit parent circuit
* @param {Number} x x position
*/
constructor(circuit, x) {
super(circuit, x, 0);
this.connectionLocationIsDynamic = true;
this.fixedPositionY = true;
this.inputLength = null;
this.outputLength = null;
this.width = 4;
this.height = null;
}
/**
* attaches a wire to the input of gate
* @param {Wire} wire wire to attach to
* @param {Number} index where the wire attaches to
* @return {Number} index of gate wire connected to
*/
setIn(wire, index) {
const ix = this.inputWires.length;
this.inputWires[ix] = wire;
wire.gateOut = this;
wire.gateOutIndex = ix;
wire.validate();
return ix;
// wire.setOut(this, ix); // causes an equivent to "push"
// return ix;
}
/**
* attaches a wire to the input of gate
* @param {Wire} wire wire to attach to
* @param {Number} index where the wire attaches to
* @returns {Number} index of gate wire connected to
*/
setOut(wire, index) {
const ix = this.outputWires.length;
// wire.setIn(this, index);
wire.gateIn = this;
wire.gateInIndex = 0;
wire.validate();
this.outputWires[ix] = wire;
return ix;
}
/**
* draw vertical
* @param {CanvasRenderingContext2D} X rendering context
* @param {Camera} camera camera
*/
draw(X, camera) {
camera.transformTo(X, this);
if (this.getState(0)) {
X.strokeStyle = "#ff0000";
} else {
X.strokeStyle = "#000000";
}
X.beginPath();
X.moveTo(this.x, this.y);
X.lineTo(this.x, this.circuit.app.canvas.height);
X.lineWidth = this.width;
X.stroke();
camera.resetTransform(X);
}
}
Vertical.gateName = "Vertical";
export { Vertical };
|
function getJson (url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200) {
callback(xhr.response);
}
}
xhr.send();
}
getJson("https://sheets.googleapis.com/v4/spreadsheets/1ia0LY4uPcuykG2bCx-UABblSO8XpquZGEHoggMJz52A/values/YB!A2:G10?key=AIzaSyCNfqumw4j2MuN5yr5jBiFC9ZhF3Gv0-p8", function(data) {
let val = data.values;
let elem = document.querySelector('#offer');
let createDomElem = '';
val.forEach((item, i) => {
// console.log(item);
createDomElem += `
<div class="offer-box" style="background-image: url(${item["0"]})">
<div class="of-label">ALE</div>
<span class="of-price">${item["2"]}<sup>€</sup></span>
<span class="of-offer">${item["1"]}<sup>€</sup></span>
<span class="of-new-item">${item["4"]}</span>
<h5>${item["3"]}</h5>
<p>${item["5"]}</p>
</div>`
});
elem.innerHTML = createDomElem;
// Show or hide offer novelty
let novelty = document.querySelectorAll('.of-new-item');
for (let j = 0; j < novelty.length; j++) {
if (novelty[j].textContent == "0") {
novelty[j].style.visibility = 'hidden';
} else if (novelty[j].textContent == "1") {
novelty[j].textContent = "uutus";
}
}
// Show or hide offer description
let txt = document.querySelectorAll('.offer-box p');
for (let j = 0; j < txt.length; j++) {
if (txt[j].textContent == "undefined") {
txt[j].remove();
}
}
});
|
/*graph_control.js: class for scaling and repositioning objects on the graph*/
class GraphControl{
constructor(){}
/******** CONVERSION FUNCTIONS *****/
/*Converts mz, rt coordinate to grid space (0 to GRID_RANGE)*/
static mzRtToGridSpace = (mz, rt) => {
let vr = Graph.viewRange;
let mz_norm = (mz - vr.mzmin) / vr.mzrange;
let rt_norm = (rt - vr.rtmin) / vr.rtrange;
return { x: mz_norm * Graph.gridRange, z: (1 - rt_norm) * Graph.gridRange };
}
/******* DATA RANGE AND VIEWING AREA ****/
static adjustIntensity = (peaks, scale) => {
//low peak height stays the same as 0.05 until the scaled value becomes > 0.05
//peak.height = adjusted y (current Y), peak.int = original intensity
peaks.forEach((peak) => {
if (peak.lowPeak){
let resultHeight = scale * peak.int;
if (resultHeight < Graph.minPeakHeight){
//peak y should be updated so that the resulting height is still 0.05
let newY = Graph.minPeakHeight/ scale;
peak.geometry.attributes.position.array[4] = newY;
peak.geometry.attributes.position.needsUpdate = true;
}else{
//when the scaled intensity would be > 0.05
peak.geometry.attributes.position.array[4] = peak.int;
peak.geometry.attributes.position.needsUpdate = true;
}
}
})
}
/*resizes the renderer and camera, especially in response to a window resize*/
static repositionPlot = (r) => {
let heightScale = Graph.viewRange.intmax;
// This step allows points to be plotted at their normal mz,rt locations in plotPoint,
// but keeping them in the grid. Scaling datagroup transforms the coordinate system
// from mz,rt to GRID_RANGE. RT is also mirrored because the axis runs in the "wrong" direction.
let mz_squish = Graph.gridRange / (r.mzmax - r.mzmin);
let rt_squish = - Graph.gridRange / (r.rtmax - r.rtmin);
let int_squish = (Graph.gridRangeVertical / heightScale) * r.intscale;
if (Graph.viewRange.intmax < 1){
//there is a problem when there is no peak --> this.dataRange.intmax becomes 0 and inte_squish is a result of dividing by zero
int_squish = 0;
}
let dataGroup = Graph.scene.getObjectByName("dataGroup");
let markerGroup = Graph.scene.getObjectByName("markerGroup");
let tickLabelGroup = Graph.scene.getObjectByName("tickLabelGroup");
let ticksGroup = Graph.scene.getObjectByName("ticksGroup");
dataGroup.scale.set(mz_squish, int_squish, rt_squish);
markerGroup.scale.set(1,1,rt_squish);
// Reposition the plot so that mzmin,rtmin is at the correct corner
dataGroup.position.set(-r.mzmin*mz_squish, 0, Graph.gridRange - r.rtmin*rt_squish);
markerGroup.position.set(0, 0, Graph.gridRange - r.rtmin*rt_squish);
// update tick marks
GraphUtil.emptyGroup(tickLabelGroup);
let markMaterial = new THREE.LineBasicMaterial({ color: 0x000000});
// draws a tick mark at the given location
let makeTickMark = (mzmin, mzmax, rtmin, rtmax) => {
let markGeo = new THREE.Geometry();
markGeo.vertices.push(new THREE.Vector3(mzmin, 0, rtmin));
markGeo.vertices.push(new THREE.Vector3(mzmax, 0, rtmax));
let markLine = new THREE.Line(markGeo, markMaterial);
ticksGroup.add(markLine);
};
// draws a tick label for the given location
let makeTickLabel = (which, mz, rt) => {
let text;
let xoffset = 0;
let zoffset = 0;
if (which == "mz") {
text = GraphUtil.roundTo(mz, Graph.roundMz);
zoffset = 2.0;
} else if (which == "rt") {
text = GraphUtil.roundTo(rt/60, Graph.roundRt);
xoffset = -1.5;
zoffset = 0.2;
}
let label = GraphLabel.makeTextSprite(text, {r:0, g:0, b:0}, 15);
let gridsp = GraphControl.mzRtToGridSpace(mz, rt);
label.position.set(gridsp.x + xoffset, 0, gridsp.z + zoffset);
tickLabelGroup.add(label);
};
// calculate tick frequency
let mzSpacing = Math.pow(10, Math.floor(Math.log(r.mzrange)/Math.log(10) - 0.5));
let rtSpacing = Math.pow(10, Math.floor(Math.log(r.rtrange)/Math.log(10) - 0.5));
GraphUtil.emptyGroup(ticksGroup);
// properly check if floating-point "value" is a multiple
// of "divisor" within a tolerance
let isMultiple = (value, divisor) => {
let rem = Math.abs(value % divisor);
return (rem < 1e-4) || (divisor-rem < 1e-4);
};
// place mz marks...
let mz, rt, long;
let mzFirst = r.mzmin - (r.mzmin % mzSpacing);
rt = r.rtmin;
for (mz = mzFirst + mzSpacing; mz < r.mzmax; mz += mzSpacing) {
// This little gem makes it so that tick marks that are a multiple
// of (10 * the spacing value) are longer than the others
long = isMultiple(mz, mzSpacing * 10);
let rtlen = r.rtrange * (long ? 0.05 : 0.02);
makeTickMark(mz, mz, rt, rt - rtlen);
if (long) {
makeTickLabel("mz", mz, rt);
}
}
// ...and rt marks
let rtFirst = r.rtmin - (r.rtmin % rtSpacing);
mz = r.mzmin;
for (rt = rtFirst + rtSpacing; rt < r.rtmax; rt += rtSpacing) {
long = isMultiple(rt, rtSpacing * 10);
let mzlen = r.mzrange * (long ? 0.05 : 0.02);
makeTickMark(mz, mz - mzlen, rt, rt);
if (long) {
makeTickLabel("rt", mz, rt);
}
}
};
/*update labels and legend to reflect a new view range*/
static updateViewRange = (newViewRange) => {
Graph.viewRange = newViewRange;
GraphControl.repositionPlot(newViewRange);
GraphLabel.drawDataLabels();
}
/*prevent user from going outside the data range or zooming in so far that math breaks down*/
static constrainBoundsZoom = (newmzmin, newmzrange, newrtmin, newrtrange) => {
//if range is too small, set to minimum range of 0.01
if (newrtrange < 0.01){
newrtrange = 0.01;
}
if (newmzrange < 0.01){
newmzrange = 0.01;
}
//if value goes below zero in rt or mz, set to 0
if (newmzmin < 0){
newmzmin = 0;
}
if (newrtmin < 0){
newrtmin = 0;
}
//if max value is going to go over the max mz, rt, set them to be the max value, no going over the limit
if (newmzmin + newmzrange > Graph.dataRange.mzmax){
newmzrange = Graph.dataRange.mzmax - newmzmin;
}
if (newrtmin + newrtrange > Graph.dataRange.rtmax){
newrtrange = Graph.dataRange.rtmax - newrtmin;
}
return {
mzmin: newmzmin, mzmax: newmzmin + newmzrange, mzrange: newmzrange,
rtmin: newrtmin, rtmax: newrtmin + newrtrange, rtrange: newrtrange,
}
}
static constrainBoundsPan = (newmzmin, newmzrange, newrtmin, newrtrange) => {
//if range is too small, set to minimum range of 0.01
if (newrtrange < 0.01){
newrtrange = 0.01;
}
if (newmzrange < 0.01){
newmzrange = 0.01;
}
if (newmzmin < 0){
newmzmin = 0;
}
if (newrtmin < 0){
newrtmin = 0;
}
let newmzmax = newmzmin + newmzrange;
let newrtmax = newrtmin + newrtrange;
//if max value is going to go over the max mz, rt, set them to be the max value, no going over the limit
if (newmzmin + newmzrange > Graph.dataRange.mzmax){
//no panning
newmzmin = Graph.viewRange.mzmin;
newmzmax = Graph.dataRange.mzmax;
newmzrange = newmzmax - newmzmin;
}
if (newrtmin + newrtrange > Graph.dataRange.rtmax){
//no panning
newrtmin = Graph.viewRange.rtmin;
newrtmax = Graph.dataRange.rtmax;
newrtrange = newrtmax - newrtmin;
}
return {
mzmin: newmzmin, mzmax: newmzmax, mzrange: newmzrange,
rtmin: newrtmin, rtmax: newrtmax, rtrange: newrtrange,
}
}
static resizeCameraUserControl = () => {
let size = new THREE.Vector3();
Graph.renderer.getSize(size);
let aspectRatio = size.x / size.y;
let vs = Graph.viewSize ;
if (aspectRatio > 1)
{
// width greater than height; scale height to view size to fit content
// and scale width based on the aspect ratio (this creates extra space on the sides)
Graph.camera.left = vs * aspectRatio / -2;
Graph.camera.right = vs * aspectRatio / 2;
Graph.camera.top = vs / 2;
Graph.camera.bottom = vs / -2;
}
else
{
// height greater than width; same as above but with top+bottom switched with left+right
Graph.camera.left = vs / -2;
Graph.camera.right = vs / 2;
Graph.camera.top = vs / aspectRatio / 2;
Graph.camera.bottom = vs / aspectRatio / -2;
}
// render the view to show the changes
Graph.camera.updateProjectionMatrix();
GraphRender.renderImmediate();
Graph.resizedCamera = Graph.camera;
}
static resizeCamera = () => {
Graph.renderer.setSize(Graph.graphEl.clientWidth, Graph.graphEl.clientHeight, true);
let size = new THREE.Vector3();
Graph.renderer.getSize(size);
let aspectRatio = size.x / size.y;
let vs = Graph.viewSize;
if (aspectRatio > 1)
{
// width greater than height; scale height to view size to fit content
// and scale width based on the aspect ratio (this creates extra space on the sides)
Graph.camera.left = vs * aspectRatio / -2;
Graph.camera.right = vs * aspectRatio / 2;
Graph.camera.top = vs / 2;
Graph.camera.bottom = vs / -2;
}
else
{
// height greater than width; same as above but with top+bottom switched with left+right
Graph.camera.left = vs / -2;
Graph.camera.right = vs / 2;
Graph.camera.top = vs / aspectRatio / 2;
Graph.camera.bottom = vs / aspectRatio / -2;
}
// render the view to show the changes
Graph.camera.updateProjectionMatrix();
GraphRender.renderImmediate();
Graph.resizedCamera = Graph.camera;
};
}
|
/*
* 滚动图片
* @date:2016-03-17
* @author:kotenei(kotenei@qq.com)
*/
define('km/scrollImg', ['jquery'], function ($) {
var ScrollImg = function ($el, options) {
this.$el = $el;
this.options = $.extend(true, {
padding: 30,
delay: 3000,
width: 'auto',
height: 150,
showNum: 3,
toggleDealy:700
}, options);
this.init();
};
/**
* 初始化
* @return {Void}
*/
ScrollImg.prototype.init = function () {
var $lis;
this.tm = null;
this.isStop = false;
this.$prev = this.$el.find('div.k-scrollImg-prev');
this.$next = this.$el.find('div.k-scrollImg-next');
this.$container = this.$el.find('div.k-scrollImg-container').css({
width: this.options.width,
height: this.options.height
});
this.$el.css({
paddingLeft: this.options.padding,
paddingRight: this.options.padding,
width: this.options.padding * 2 + this.$container.outerWidth()
});
this.$ul = this.$container.find('ul');
var $lis = this.$ul.children('li');
if ($lis.length <= this.options.showNum) {
this.options.showNum = $lis.length;
}
this.crateItem();
$lis = this.$ul.children('li');
this.total = $lis.length / this.options.showNum;
this.max = this.total - 2;
this.index = 0;
if (this.max > 1) {
this.$ul.css("marginLeft", -(this.index + 1) * this.options.showNum * this.i_w);
this.run();
this.watch();
}
};
/**
* 创建项
* @return {Void}
*/
ScrollImg.prototype.crateItem = function () {
var $lis = this.$ul.children('li');
var width = this.$container.outerWidth();
var html = [];
var margin = 10;
var flag = 0;
var totalWidth = 0;
var li_w = width / this.options.showNum - margin;
var len = $lis.length;
this.i_w = li_w + margin;
if (len % this.options.showNum != 0) {
for (var i = 0; i < len; i++) {
for (var j = 0; j < this.options.showNum; j++) {
html.push($lis[flag].outerHTML);
totalWidth += this.i_w;
flag++;
if (flag >= len) { flag = 0 }
}
}
}
if (html.length) {
var pre = [];
var next = [];
for (var i = 0; i < this.options.showNum; i++) {
next.push(html[i]);
}
for (var i = html.length - this.options.showNum ; i < html.length ; i++) {
pre.push(html[i]);
}
Array.prototype.push.apply(html, next);
Array.prototype.push.apply(pre, html);
totalWidth += (this.i_w) * this.options.showNum * 2;
this.$ul.html(pre.join('')).width(totalWidth);
} else {
if (len > this.options.showNum) {
var pre = [];
var next = [];
for (var i = 0; i < this.options.showNum; i++) {
next.push($lis[i].outerHTML);
}
for (var i = len - this.options.showNum ; i < len ; i++) {
pre.push($lis[i].outerHTML);
}
len += this.options.showNum * 2;
this.$ul.append(next.join(''));
this.$ul.prepend(pre.join(''));
}
this.$ul.width(len * (this.i_w));
}
this.$ul.children('li').css('width', li_w);
};
/**
* 事件监控
* @return {Void}
*/
ScrollImg.prototype.watch = function () {
var self = this;
if (this.isWatch) {
return;
}
this.isWatch = true;
this.$el.on('mouseenter.scrollImg', function () {
self.stop();
}).on('mouseleave.scrollImg', function () {
self.run();
}).on('click.scrollImg', '.k-scrollImg-prev', function () {
self.index--;
self.active();
}).on('click.scrollImg', '.k-scrollImg-next', function () {
self.index++;
self.active();
});
};
/**
* 运行
* @return {Void}
*/
ScrollImg.prototype.run = function () {
var self = this;
this.isStop = false;
this.tm = setTimeout(function () {
self.index++;
self.active(function () {
if (!self.isStop) {
self.run();
}
});
}, this.options.delay);
};
/**
* 停止运行
* @return {Void}
*/
ScrollImg.prototype.stop = function () {
if (this.tm) {
clearTimeout(this.tm);
this.isStop = true;
}
};
/**
* 切换图片
* @return {Void}
*/
ScrollImg.prototype.active = function (callback) {
var self = this;
var tmpIndex = this.index + 1;
var width = this.i_w * this.options.showNum;
if (this.index == this.max) {
this.index = 0;
}
if (this.index < 0) {
this.index = this.max - 1;
}
this.$ul.stop().animate({
marginLeft: -tmpIndex * width
},this.options.toggleDealy, function () {
if (tmpIndex == self.total - 1) {
self.$ul.css('marginLeft', -1 * width);
}
if (tmpIndex == 0) {
self.$ul.css('marginLeft', -(self.max) * width);
}
if (typeof callback === 'function') {
callback();
}
});
};
return function ($elms, settings) {
$elms.each(function () {
var $el = $(this),
options = $el.attr('data-options'),
data = $.data(this, 'scrollerImg');
if (!data) {
if (options) {
options = eval('(0,' + options + ')');
} else {
options = settings;
}
data = new ScrollImg($(this), options);
$.data(this, 'scrollerImg', data);
}
});
}
});
|
import React from 'react';
import { Flex, Text, Link, Box} from 'rebass';
const Footer = function (props) {
return (<Flex
px={2}
mt={5}
py={50}
color='white'
bg='#373543'
alignItems='center'>
<Text p={2} color="gray" fontWeight='bold'>(c) 2018. Julius Vering.</Text>
<Box mx='auto' />
<Link
href='https://www.github.com/juliusvering'
p={2}
color='white'>
github.
</Link>
<Link
href='https://www.linkedin.com/in/julius-vering'
p={2}
color='white'>
linkedin.
</Link>
<Link
href='https://www.juliusvering.com'
p={2}
color='white'>
personal website.
</Link>
<Link
href='mailto:julius.vering@berkeley.edu'
p={2}
color='white'>
email.
</Link>
</Flex>);
};
export default Footer;
|
/* eslint-disable no-param-reassign */
/* eslint-disable no-underscore-dangle */
const MenuGenerator = {
init({ container, menus }) {
this._generateMenu(container, menus);
},
_generateMenuItem(menus) {
const result = menus.map((menu) => {
const menuName = menu.name;
return `<li>${menuName}</li>`;
});
return result.join().replace(/,/g, '');
},
_generateMenu(container, menus) {
// eslint-disable-next-line array-callback-return
Object.entries(menus).forEach((menu) => {
container.innerHTML += `
<div class="menu-category">
<button class="menu-dropdown-btn">${menu[0].toUpperCase()}</button>
<ul class="menu-dropdown" id="menu-${menu[0]}-dropdown">${this._generateMenuItem(menu[1])}</ul>
</div>
`;
});
},
};
export default MenuGenerator;
|
define(function(require,exports,modules){
var p = require('./a');
// p.sayName();
// console.log('hello');
console.log(p);
modules.exports =123;
})
|
/**
* require ./base
* require_dir bootstrap.js
*/
|
// Used for pagination on feed lists that exceeds a certain amount
function PageContainer () {
this.messageList = {}
this.nextPage = function (msg) {
if (this.messageList[msg.id].currentPage + 1 > this.messageList[msg.id].pages.length - 1) return
this.messageList[msg.id].currentPage++
let pageMsg = this.messageList[msg.id]
msg.channel.fetchMessage(msg.id).then(m => m.edit({embed: pageMsg.pages[pageMsg.currentPage]})).catch(console.error)
}
this.prevPage = function (msg) {
if (this.messageList[msg.id].currentPage - 1 < 0) return
this.messageList[msg.id].currentPage--
let pageMsg = this.messageList[msg.id]
msg.channel.fetchMessage(msg.id).then(m => m.edit({embed: pageMsg.pages[pageMsg.currentPage]})).catch(console.error)
}
}
let pageMsgs = new PageContainer()
exports.add = function (msgId, pages) {
pageMsgs.messageList[msgId] = {
currentPage: 0,
pages: pages
}
}
exports.nextPage = function (msg) {
pageMsgs.nextPage(msg)
}
exports.prevPage = function (msg) {
pageMsgs.prevPage(msg)
}
exports.has = function (id) {
return pageMsgs.messageList[id]
}
|
var map, crsChernarus;
function InitMap() {
var tilesUrl = 'http://static.dayzdb.com/tiles/{z}/{x}_{y}.png',
tilesAttrib = '© Crosire, Chernarus map data from <a href="http://dayzdb.com/map">DayZDB</a>',
tiles = new L.TileLayer(tilesUrl, {noWrap: true, continuousWorld: true, attribution: tilesAttrib, tileLimits: {2: {x: 4, y: 4}, 3: {x: 8, y: 7}, 4: {x: 16, y: 14}, 5: {x: 32, y: 27}, 6: {x: 64, y: 54}}});
var b = 1 / 14.524823, c = L.latLng([1.920978, 0.284574]);
crsChernarus = L.Util.extend({}, L.CRS, {
latLngToPoint: function(e, d) {
var a = this.projection.project(L.latLng([e.lat - c.lat, e.lng - c.lng])), b = this.scale(d);
return a = this.transformation._transform(a, b)
},
pointToLatLng: function(b, d) {
var a = this.scale(d);
a = this.projection.unproject(this.transformation.untransform(b, a));
a.lat += c.lat;
a.lng += c.lng;
return a
},
projection: L.Projection.LonLat,
transformation: new L.Transformation(b, 0, b, 0)
})
// Set up the map
map = new L.Map('map', {center: [7.5, 7], zoom: 2, minZoom: 2, maxZoom: 6, markerZoomAnimation: false, attributionControl: false, crs: crsChernarus});
// Create tile layer
map.addLayer(tiles);
}
|
var SERVER_URL = document.location.protocol + '//' + document.location.host + '/';
function sendAjaxRequest(url, data, success, error, async) {
$('#loader').show();
$('#send_btn').addClass('disabled');
function successCallback (response) {
$('#loader').hide();
$('#send_btn').removeClass('disabled');
if(success)
success(response);
}
function errorCallback (response) {
$('#loader').hide();
$('#send_btn').removeClass('disabled');
if(error)
error(response);
}
$.ajax({
url : url,
type : 'POST',
async : (async) ? async : true,
data : data,
//dataType : 'json',
cache : false,
crossDomain: true,
success : successCallback,
error : errorCallback,
});
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Radio } from 'antd';
import { Link } from 'react-router-dom';
export default class ComponentTabs extends React.Component{
render(){
return(
<div>
<Radio.Group defaultValue={this.props.mode} buttonStyle="solid">
<Radio.Button value="unit"><Link to="unit">内部单位</Link></Radio.Button>
<Radio.Button value="equ"><Link to="equ">用能设备</Link></Radio.Button>
</Radio.Group>
</div>
)
}
}
|
export const state = () => ({
postion: {}
})
export const mutations = {
setPosition(state, val) {
state.postion = val
}
}
export const actions = {
setPosition: ({
commit
}, position) => {
commit('setPosition', position)
}
}
|
document.addEventListener('keydown', () => {
var audio = new window.Audio('error.mp3')
audio.play()
})
|
const run = require('./run');
module.exports = {
env: async function env(path) {
try {
await run('python3', ['-m', 'venv', './env'], { cwd: path });
} catch (error) {
throw Error(`Failed to setup Python venv on ${path}`);
}
},
pip: async function pip(path) {
try {
await run(
'./env/bin/pip',
['install', '-r', 'requirements.txt'],
{ cwd: path },
);
} catch (error) {
throw Error(`Failed to run pip install on ${path}.`);
}
},
};
|
import Column from "../column/Column";
import React from "react";
import {connect} from "react-redux";
function Cards(props) {
return (
<div>
<nav className="navbar navbar-dark bg-dark form-inline jd-flex bd-highlight mb-3">
<button type="button" className="btn btn-outline-info p-2 bd-highlight" onClick={() => props.toggle('CARD_ADD_NEW')}>✚ Add new card</button>
<button type="button" className="btn btn-outline-warning p-2 bd-highlight" onClick={() => props.toggle('TRASH')}
disabled={!props.cards.find(({trash}) => trash === true)}>♺ Trash can</button>
<button type="button" className="btn btn-outline-danger p-2 bd-highlight" onClick={() => props.toggle('DELETE_ALL')}
disabled={!props.cards.find(({trash}) => trash === false)}> ⚠ Delete all cards</button>
<button type="button" className="btn btn-outline-success p-2 bd-highlight" onClick={() => props.toggle('ADD_COLUMN')}>✚ Add new column</button>
<button type="button" className="btn btn-outline-danger p-2 bd-highlight" onClick={() => props.toggle('DELETE_COLUMN')}> ⚠ Delete column</button>
<button type="button" className="btn btn-outline-secondary ms-auto p-2 bd-highlight logout" onClick={() => props.toggle('LOGOUT')}>⟲ Logout</button>
</nav>
<div className="row align-items-start cards">
{props.columns.map(el => <Column key={el._id} column={el} cards={props.cards}/>)}
</div>
</div>
)
}
const mapDispatchToProps = (dispatch) => ({
toggle: (component) => dispatch({type: "TOGGLE", payload: component}),
})
export default connect (null, mapDispatchToProps)(Cards);
|
// CADA REDUCER TIENE SU PROPIO ESTATE
import {
ADD_PRODUCT,
ADD_PRODUCT_SUCCESS,
ADD_PRODUCT_ERROR,
START_PRODUCTS_DOWNLOAD,
PRODUCTS_DONWLOAD_SUCCESS,
PRODUCTS_DONWLOAD_ERROR,
INIT_PRODUCT_ELIMINATE,
PRODUCT_ELIMINATED_SUCCESS,
PRODUCT_ELIMINATED_ERROR,
GET_EDIT_PRODUCT,
INIT_EDIT_PRODUCT,
EDIT_PRODUCT_SUCCESS,
EDIT_PRODUCT_ERROR,
} from "../types";
const initialState = {
products: [],
error: false,
loading: false,
productSelected: null,
};
const productsReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_PRODUCT:
return {
...state,
loading: action.payload.loading,
};
case ADD_PRODUCT_SUCCESS:
return {
...state,
products: [...state.products, action.payload.products],
loading: action.payload.loading,
};
case ADD_PRODUCT_ERROR:
return {
...state,
error: action.payload.error,
loading: action.payload.loading,
};
case START_PRODUCTS_DOWNLOAD:
return {
...state,
loading: action.payload.loading,
};
case PRODUCTS_DONWLOAD_SUCCESS:
return {
...state,
products: action.payload.products,
loading: false,
};
case PRODUCTS_DONWLOAD_ERROR:
return {
...state,
error: action.payload.error,
};
case INIT_PRODUCT_ELIMINATE:
return {
...state,
loading: action.payload.loading,
};
case PRODUCT_ELIMINATED_SUCCESS:
return {
...state,
products: state.products.filter(
(product) => product.id !== action.payload.id
),
loading: action.payload.loading,
};
case PRODUCT_ELIMINATED_ERROR:
return {
...state,
error: action.payload.error,
};
case GET_EDIT_PRODUCT:
return {
...state,
productSelected: action.payload.product,
};
case INIT_EDIT_PRODUCT:
return {
...state,
loading: action.payload.loading,
};
case EDIT_PRODUCT_SUCCESS:
return {
...state,
loading: action.payload.loading,
products: state.products.map((product) =>
product.id === action.payload.id
? (product = action.payload.product)
: product
),
productSelected: null,
};
case EDIT_PRODUCT_ERROR:
return {
error: action.payload.error,
};
default:
return state;
}
};
export default productsReducer;
|
import React, { useEffect, useState } from "react";
import { isLoaded, withFirestore, useFirestore } from 'react-redux-firebase';
import Dashboardfooter from '../Layout/DashboardFooter';
import Dashboardheader from '../Layout/DashboardHeader';
import CompanySideBar from '../Layout/CompanySideBar';
import images from "../../utils/ImageHelper";
import {toast} from "react-toastify";
import * as actions from "../../redux/action/actions";
import {useDispatch} from "react-redux";
const initialState = {
FullName: "-",
ProfileImage: "",
Base64: "",
AboutUs: "-",
UserType: 'private',
OrganizationNo: 123456,
Address: '',
telephone: ''
}
const CompanySettingsAccountEditColleagues = () => {
const dispatch = useDispatch();
const [isModal, setIsModal] = useState(false);
const [userDetail, setUserDetails] = useState(initialState);
const [colleagues, setColleagues] = useState([]);
const [colleaguesList, setColleaguesList] = useState([]);
const [searchColleague, setSearchColleague] = useState('');
const [filterColleagues, setFilterColleagues] = useState([]);
const [selectedColleague, setSelectedColleague] = useState({id: ''});
const firebase = useFirestore();
React.useEffect(() => {
const UserId = localStorage.getItem('userId')
var doctblUser = firebase.collection("tblUser").doc(UserId);
doctblUser.get()
.then(function (querySnapshot) {
if (querySnapshot.exists) {
const data = querySnapshot.data();
data.id = querySnapshot.id;
let merged = { ...initialState, ...data };
setUserDetails(merged)
console.log("Document data:", data);
} else {
console.error("No such document!");
}
}).catch(function (error) {
console.error("Error getting documents: ", error);
});
firebase.collection("tblUser")
.where("UserType", "==", "private")
.get()
.then(querySnapshot => {
const postData = [];
querySnapshot.forEach((doc) => postData.push({ ...doc.data(), id: doc.id }))
setColleagues(postData)
firebase.collection("tblColleague").get().then(querySnapshot => {
const data = [];
querySnapshot.forEach((doc) => data.push({ ...doc.data(), id: doc.id }))
const colleague = []
postData.map((x) => {
data.map((y) => {
if(y.ColleagueId === x.id){
const obj = {...x, ColleagueId: y.id}
colleague.push(obj)
}
})
})
setColleaguesList(colleague)
});
});
}, [])
const onSearch = (event) => {
setSearchColleague(event.target.value)
const clone= [...colleagues]
let filterData = clone.filter((ser) => {
return ser.Name.includes(event.target.value) || ser.Email.includes(event.target.value)
});
setFilterColleagues(filterData)
}
const selectColleague = (record) => {
setSelectedColleague(record)
}
const onRemoveColleagues = (record) => {
dispatch(actions.setLoader(true));
firebase.collection("tblColleague").doc(record.ColleagueId).delete().then((res) => {
const clone = [...colleaguesList]
const index = clone.findIndex((y) => y.ColleagueId === record.ColleagueId)
clone.splice(index, 1)
setColleaguesList(clone)
dispatch(actions.setLoader(false));
toast.success("Colleague delete successfully");
}).catch((error) => {
dispatch(actions.setLoader(false));
toast.error("Something went wrong please try again");
})
}
const onAddColleague = () => {
dispatch(actions.setLoader(true));
const UserId = localStorage.getItem('userId')
const record = colleaguesList.find((x) => x.id === selectedColleague.id) || {}
if(record.id === selectedColleague.id){
toast.error("Colleague already Added");
dispatch(actions.setLoader(false));
} else {
firebase.collection("tblColleague").add({
ColleagueId: selectedColleague.id,
companyId: UserId,
IsActive: true,
CreatedDate: new Date(),
UpdatedDate: new Date(),
}).then((result) => {
const clone = [...colleaguesList]
clone.push(selectedColleague)
setColleaguesList(clone)
setSelectedColleague({})
setSearchColleague('')
dispatch(actions.setLoader(false));
toast.success("Colleague Added successfully");
}).catch((error) => {
dispatch(actions.setLoader(false));
toast.error("Something went wrong please try again");
});
}
}
const onOpenModal = () => {
setIsModal(true)
}
const onCloseModal = () => {
setIsModal(false)
setSearchColleague('')
}
return (
<div className="colleaguebox">
<div className="colleague-title">
<h2>{userDetail.FullName}, <span>Colleagues</span></h2>
<div className="colleague-btn">
<button onClick={onOpenModal}><a className="colleague">Add Colleague</a></button>
</div>
<div className={`add-colleagues-box ${isModal ? 'box' : ''}`}>
<h3>Add New Colleague</h3>
<button className="close-colleagues" onClick={onCloseModal}><i className="fas fa-times"/></button>
<div className="add-colleagues">
<div className="colleague-img">
<img src={selectedColleague.ProfileImage || images.setting1} alt={selectedColleague.ProfileImage || images.setting1} style={{width: 292, height:292}}></img>
<h4>{selectedColleague.FullName || "-"}</h4>
<h5>
<a className="dotshap" href={`mailto:${selectedColleague.Email || "-"}`}>{selectedColleague.Email || "-"}</a>
<a href={`tel:${selectedColleague.telephone || "-"}`}>{selectedColleague.Phone || "-"}</a>
</h5>
</div>
</div>
<div className="colleague-search">
<div className="colleague-add-search-box">
<div className="colleague-search-box">
<input type="text" name="searchColleague" value={searchColleague} onChange={onSearch} placeholder="Search Colleague" className="search-colleagues"/>
<i className="fas fa-search colle-icon"/>
</div>
<button onClick={onAddColleague} disabled={selectedColleague.id === ""} style={{border: 0, padding: 0,outline: "none",}}><a >Add Colleague</a></button>
</div>
</div>
{searchColleague === "" ? "" : <div className="search-colleague-data"><div className="row">
{
(filterColleagues || []).map((x, i) => {
return (
<div className="col-xxl-4 col-md-6 col-sm-6 col-12" key={i} onClick={() => selectColleague(x)}>
<div className="first-img">
<img src={x.ProfileImage || images.setting1} alt={x.ProfileImage || images.setting1}></img>
<h4>{x.FullName || "-"}</h4>
<h5>
<a className="dotshap" href={`mailto:${x.Email || "-"}`}>{x.Email || "-"}</a>
<a href={`tel:${x.telephone || "-"}`}>{x.telephone || "-"}</a>
</h5>
</div>
</div>
)
})
}
</div></div>}
</div>
</div>
<div className="row">
{
(colleaguesList || []).map((x, i) => {
return(
<div className="col-xxl-4 col-md-6 col-sm-6 col-12" key={i} >
<div className="first-img">
<img src={x.ProfileImage || images.setting1} alt={x.ProfileImage || images.setting1} ></img>
<h4>{x.FullName || "-"}</h4>
<h5>
<a className="dotshap" href={`mailto:${x.Email || "-"}`}>{x.Email || "-"}</a>
<a href={`tel:${x.telephone || "-"}`}>{x.telephone || "-"}</a>
</h5>
<button onClick={() => onRemoveColleagues(x)}>Remove</button>
</div>
</div>
)
})
}
</div>
</div>
);
}
export default CompanySettingsAccountEditColleagues;
|
import messages from './messages'
import { ADD_MESSAGE } from '../constants/actionTypes'
describe('messages reducer', () => {
it('should return the initial state, empty', () => {
expect(messages(undefined, {})).toEqual([])
})
it('should handle ADD_MESSAGE and store every message', () => {
expect(
messages([], {
type: ADD_MESSAGE,
message: 'Hi',
author: 'Me'
})
).toEqual([{ message: 'Hi', author: 'Me' }])
expect(
messages([{ message: 'Hi', author: 'Me' }], {
type: ADD_MESSAGE,
message: 'Hi again',
author: 'Me again'
})
).toEqual([
{ message: 'Hi', author: 'Me' },
{ message: 'Hi again', author: 'Me again' }
])
})
})
|
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/registration_server", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const User = mongoose.model("User", {
fname: String,
lname: String,
email: String,
password: String,
city: String,
});
module.exports = {
User,
};
|
// dependencies
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
// containers
import GameContainer from './containers/GameContainer';
import ConnectFourContainer from './containers/ConnectFourContainer';
// root reducer
import rootReducer from './reducers/index';
// services
import GameService from './services/GameService';
const initStore = () => {
const store = createStore(
// root reducer
rootReducer,
// dev tools
window.devToolsExtension ? window.devToolsExtension() : undefined,
);
if (module.hot) {
module.hot.accept('./reducers/index', () =>
store.replaceReducer(require('./reducers/index').default)
);
}
return store;
};
const initRender = sandbox => {
const el = sandbox.renderTarget;
if (!el) {
console.log('no render target');
return;
}
ReactDOM.render(
<Provider store={sandbox.store}>
<ConnectFourContainer sandbox={sandbox} />
</Provider>,
el
);
};
const initServices = sandbox => {
new GameService(sandbox);
}
// private properties
let store;
class Sandbox {
constructor (framework, opt) {
this.$ = framework;
this.opt = opt;
store = initStore(this);
initRender(this);
initServices(this);
}
get store () {
return store;
}
get renderTarget () {
return this.$.DOM.query(this.opt.renderTarget);
}
get isGameOver () {
return store.getState().game.winner;
}
}
export default Sandbox;
|
/**
* Created by a on 2017/11/14.
*/
const dbpool = require("../config/dbconfig");
const appointmentcontroller={
show(params){
return new Promise(function(resolve,reject){
dbpool.connect("select * from t_appointment",params,
(err,data)=>{
if(!err){
resolve(data)
}else{
reject(err)
}
})
})
},
star(params){
return new Promise(function(resolve,reject){
dbpool.connect("update t_appointment set state=0 where app_id=?",
params,(err,data)=>{
if(!err){
resolve(data)
}else{
reject(err)
}
})
})
},
stop(params){
return new Promise(function(resolve,reject){
dbpool.connect("update t_appointment set state=1 where app_id=?",
params,(err,data)=>{
if(!err){
resolve(data)
}else{
reject(err)
}
})
})
},
revise(params){
return new Promise(function(resolve,reject){
dbpool.connect("update t_appointment set d_id=?,addr_id=?,app_time=? where app_id=?",
params,(err,data)=>{
if(!err){
resolve(data)
}else{
reject(err)
}
})
})
}
};
module.exports=appointmentcontroller;
|
const navn = document.querySelector('#navn');
const password = document.querySelector('#password');
const login = document.querySelector('#login');
const fejl = document.querySelector('#fejl');
async function post(url, objekt) {
const respons = await fetch(url, {
method: "POST",
body: JSON.stringify(objekt),
headers: { 'Content-Type': 'application/json' }
});
if (respons.status !== 201) // Created
throw new Error(respons.status);
return await respons.json();
}
login.onclick = async () => {
try {
await post("/login", { navn: navn.value, password: password.value });
window.location.href = "/chat";
} catch (e) {
password.value = "";
fejl.innerHTML = "Forkert password eller intet navn!";
}
}
|
/*
* ! SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global','sap/ui/core/Renderer','./DialogRenderer'],function(q,R,D){"use strict";var P=R.extend(D);P.CSS_CLASS="sapMPersoDialog";P.render=function(r,c){D.render.apply(this,arguments);var i=c._getVisiblePanelID();var p=c.getVisiblePanel();if(i&&p){r.write("<div");r.writeAttribute("id",i);r.write(">");r.renderControl(p);r.write("</div>")}};return P},true);
|
import React from 'react';
import logo from '../logo.svg';
import '../css/App.css';
import PropTypes from 'prop-types';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import CssBaseline from '@material-ui/core/CssBaseline';
import useScrollTrigger from '@material-ui/core/useScrollTrigger';
import Box from '@material-ui/core/Box';
import { createMuiTheme, makeStyles } from '@material-ui/core/styles';
import { ThemeProvider } from '@material-ui/styles';
import Avatar from '@material-ui/core/Avatar';
import Grid from '@material-ui/core/Grid';
import $ from 'jquery';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import ScrollAnimation from 'react-animate-on-scroll';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import ReactDOM from 'react-dom'
import { ScrollTo } from "react-scroll-to";
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
|
import * as AgreeService from '../services/agree.js';
import * as LoginService from "../services/login";
export const GET_SESSION_TOKEN_REQUEST = 'GET_SESSION_TOKEN_REQUEST';
export const GET_SESSION_TOKEN_ERROR = 'GET_SESSION_TOKEN_ERROR';
export const GET_SESSION_TOKEN_SUCCESS = 'GET_SESSION_TOKEN_SUCCESS';
export const GET_APP_PERMISSIONS_REQUEST = 'GET_APP_PERMISSIONS_REQUEST';
export const GET_APP_PERMISSIONS_ERROR = 'GET_APP_PERMISSIONS_ERROR';
export const GET_APP_PERMISSIONS_SUCCESS = 'GET_APP_PERMISSIONS_SUCCESS';
export const getSessionToken = (appId, name, email, password) => {
const request = LoginService.getSessionToken(appId, name, email, password);
return (dispatch) => {
dispatch({
type: GET_SESSION_TOKEN_REQUEST
});
request.then(
response => response.json().then((payload) =>
dispatch({
type: GET_SESSION_TOKEN_SUCCESS,
payload,
})
).catch((error) => dispatch({
type: GET_SESSION_TOKEN_ERROR,
error,
}))
).catch(
error => dispatch({
type: GET_SESSION_TOKEN_ERROR,
error,
})
);
};
};
export const getPermissions = (appId) => {
const request = AgreeService.getPermissions(appId);
return (dispatch) => {
dispatch({
type: GET_APP_PERMISSIONS_REQUEST
});
request.then(
response => response.json().then((payload) =>
dispatch({
type: GET_APP_PERMISSIONS_SUCCESS,
payload,
})
).catch((error) => dispatch({
type: GET_APP_PERMISSIONS_ERROR,
error,
}))
).catch(
error => dispatch({
type: GET_APP_PERMISSIONS_ERROR,
error,
})
);
};
};
|
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useParams } from 'react-router-dom';
import { Button, Typography } from '@material-ui/core';
import { updateBlog } from '../reducers/blogReducer';
import { notify } from '../reducers/notificationReducer';
import Comments from './Comments';
const BlogDetail = () => {
const blogsSelector = useSelector(({ blog }) => blog);
const dispatch = useDispatch();
const { id } = useParams();
const blog = blogsSelector.find((b) => b.id === id);
if (!blog) {
return null;
}
const handleLike = async (blogId) => {
const udpatedBlog = {
...blog,
likes: blog.likes + 1,
};
try {
dispatch(updateBlog(blogId, udpatedBlog));
dispatch(
notify(
{
type: 'success',
content: `${udpatedBlog.title} blog liked`,
},
5000
)
);
} catch (error) {
dispatch(
notify({ type: 'error', content: 'Could not increase likes' }, 5000)
);
}
};
return (
<div>
<Typography>
<b>Title:</b> {blog.title}
</Typography>
<Typography className="url">
<b>URL:</b> {blog.url}
</Typography>
<Typography className="likes">
<b>Likes:</b> {blog.likes}
<Button
style={{ marginLeft: 10 }}
color="primary"
variant="contained"
className="likeButton"
onClick={() => handleLike(id)}
>
LIKE
</Button>
</Typography>
<Typography className="userName">
<b>Author:</b>
{blog.author}
</Typography>
<Comments blog={blog} />
</div>
);
};
export default BlogDetail;
|
/*Check to see if jquery script is loaded
$(document).ready(function() {
alert("js is working");
});
*/
/* https://stackoverflow.com/questions/20060467/add-active-navigation-class-based-on-url */
$(document).ready(function() {
var CurrentUrl= document.URL;
console.log(CurrentUrl,"CurrentUrl");
var CurrentUrlEnd = CurrentUrl.split('/').filter(Boolean).pop();
console.log(CurrentUrlEnd,"CurrentUrlEnd");
$( "#navbarMenu ul li a" ).each(function() {
var ThisUrl = $(this).attr('href');
var ThisUrlEnd = ThisUrl.split('/').filter(Boolean).pop();
console.log (ThisUrlEnd, "ThisUrlEnd")
console.log (CurrentUrlEnd,"CurrentUrlEnd")
if(ThisUrlEnd == CurrentUrlEnd){
$(this).closest('li').addClass('active')
}
});
});
/* Get current path, find same in href of nav-links and add class (doesn't work, parent?)
$(document).ready(function() {
// get current URL path and assign 'active' class
var pathname = window.location.pathname;
console.log(pathname);
$('.navbarMenu > ul > li > a[href="'+pathname+'"]').addClass('active');
})
*/
/* This (w/o the e.preventDefault();) changes the active tab highlight, changes the page, but then the highlight reverts to the original link
$(document).ready(function () {
$('.navbar-custom .nav-item .nav-link').click(function(e) {
alert("click 0");
var myVar = $(this);
console.log(myVar,"Link was clicked");
$('.navbar-custom .nav-item .nav-link').removeClass('active');
$(this).addClass('active');
console.log(e,"event");
});
})
*/
/* Attempt to set active when page loads; did not work
$(function(){
var current = location.pathname;
console.log(current);
$('.navbar-custom .nav-item .nav-link ').each(function(){
var $this = $(this);
console.log($this.attr('href').indexOf(current));
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.parent().addClass('active');
}
})
})
*/
/* This changes the active tab highlight but does not change the page
$(document).ready(function () {
$('.navbar-custom .nav-item .nav-link').click(function(e) {
alert("click 0");
$('.navbar-custom .nav-item .nav-link').removeClass('active');
$(this).addClass('active');
e.preventDefault();
});
})
*/
/* This ...........................changes the active tab highlight but does not change the page
$(document).ready(function () {
$('.navbar-custom .nav-item .nav-link').click(function(e) {
alert("click 0");
$('.navbar-custom .nav-item .nav-link').removeClass('active')
var $this = $(this);
if (!$this.hasClass('active')) {
$this.addClass('active');
}
e.preventDefault();
});
})
*/
/* This changes the active tab highlight, changes the page, then highlight returns to the original link
$(document).ready(function () {
$('.navbar-custom .nav-item .nav-link').click(function(e) {
alert("click 0");
$('.navbar-custom .nav-item .nav-link').removeClass('active')
var $this = $(this);
if (!$this.hasClass('active')) {
$this.addClass('active');
}
$('#content').load($(this).find(a).attr('href'));
});
})
*/
/*
$(function(){
$('.navbarMenu .navbar-nav .nav-item .nav-link').on("click",function(e){
alert("Link clicked 1")
$('.navbar-custom .nat-item .nav-link').removeClass('active');
$(this).addClass('active');
}
e.preventDefault();
});
/* -------------------------------------------
$(document).ready((function(){
$('.navbar-custom .nav-item .nav-link').on("click",function(e){
alert("link clicked 2");
$('.navbar-custom .nav-item .nav-link').removeClass('active');
alert("link clicked 3");
var $this = $(this);
if (!$this.hawClass('active')) {
$this.addClass('active');
}
e.preventDefault();
});
})
*/
/*
$(function(){
var current = location.pathname;
$('#nav li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
e.preventDefault();
})
})
*/
/* $(document).ready(function(){
$("p").bind("click", function(){
alert("Click 2 occurred.")
});
});
*/
/*
jquery(document).ready(function() {
$("nav-link").on("click",function(){
alert("nav-link clicked 3");
$(".nav-link").find(".active").removeClass("active");
$(this).addClass("active");
});
})
*/
/*
$(document).ready(function() {
$('div ul li a').on("click", function() {
alert(" a link clicked 4");
$('a.active').removeClass('active');
$(this).addClass('active');
});
});
*/
/*
$(document).ready(function(){
$('.nav li').click(function(event){
alert("link clicked 5");
//remove all pre-existing active classes
$('.active').removeClass('active');
//add the active class to the link we clicked
$(this).addClass('active');
//Load the content
//e.g.
//load the page that the link was pointing to
//$('#content').load($(this).find(a).attr('href'));
event.preventDefault();
});
});
*/
/*
$(document).ready(function(){
$("a").on("click", function(){
alert("The paragraph was clicked 6.");
});
});
$(document).ready(function(){
$(".nav .nav-link").on("click", function(){
alert("click 7");
$(".nav").find(".active").removeClass("active");
$(this).addClass("active");
});
});
*/
|
run_spec(__dirname, [
"babel",
// "flow",
"typescript",
]);
run_spec(
__dirname,
[
"babel",
// "flow",
"typescript",
],
{ semi: false }
);
|
import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Home from "./pages/Home";
import Detail from "./pages/Detail";
import Login from "./pages/Login";
class Routes extends React.Component {
render() {
return (
<BrowserRouter>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/detail/:id" exact component={Detail} />
<Route path="/login" exact component={Login} />
</Switch>
</BrowserRouter>
);
}
}
export default Routes;
|
const mysql = require('mysql');
//创建连接池,效率更高,不需要每次操作数据库都创建连接
let pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'newpass',
database: 'mynotebook',
port: '3306',
connectionLimit: 3,//允许连接数
multipleStatements: true, //是否允许执行多条sql语句
timezone: '08:00' //大坑,必须加这句,否则时间可能不对
})
//封装数据库sql请求操作,返回的是一个包含对象的数组
let Query = (sql, ...params) => {
return new Promise(function (resolve, reject) {
//从连接池拿出一条链接
pool.getConnection(function (err, connection) {
if (err) {
return reject(err);
}
connection.query(sql, params, function (error, res) {
// console.log(res);
connection.release();
if (error) {
return reject(error);
}
resolve(res);
})
})
})
}
// 录入单词
let inputNewWordDB = function (params) {
let sql = `
insert into
word (cn_word,en_word)
values
('${params.cn_word}', '${params.en_word}');
`;
return sql;
}
let listAllWordDB = function () {
let sql = `
select
*
from
word;
`;
return sql;
}
module.exports = {
Query,
inputNewWordDB,
listAllWordDB
}
|
$(document).ready(function(){
var nameInput = $("#teacher_name");
var teacherList = $("#divbody");
var teacherContainer = $(".teacher-container");
$(document).on("submit", "#teacher-form", handleTeacherFormSubmit);
$(document).on("click", ".delete-teacher", handleDeleteButton);
getTeachers();
function handleTeacherFormSubmit(event){
event.preventDefault();
if(!nameInput.val().trim().trim()){
return;
}
upsertTeacher ({
teacher_name: nameInput.val().trim()
});
}
function upsertTeacher(teacherData){
$.post("/api/teachers", teacherData)
.then(getTeachers);
}
//create a new list of teachers
function createTeacherRow(teacherData){
var newTeacherDiv = $("<tr>");
newTeacherDiv.data("teacher", teacherData);
newTeacherDiv.append("<td>" + teacherData.teacher_name + "</td>");
newTeacherDiv.append("<td><a class='delete-teacher waves-effect waves-light btn deep-orange lighten-2'> Delete </a></td>");
return newTeacherDiv;
}
//retrieve teacher, get them ready to render on page
function getTeachers(){
$.get("/api/teachers", function(data){
var rowsToAdd = [];
for (var i = 0; i < data.length; i++){
rowsToAdd.push(createTeacherRow(data[i]));
}
renderTeacherList(rowsToAdd);
nameInput.val("");
});
}
function renderTeacherList(rows){
teacherList.children().not(":last").remove();
teacherContainer.children(".alert").remove();
if(rows.length){
console.log(rows);
teacherList.prepend(rows);
}
else {
renderEmpty();
}
}
//display when there are no teachers
function renderEmpty() {
var pleaseCreate = $("<div>");
pleaseCreate.text("Please create a Teacher.");
teacherContainer.append(pleaseCreate);
}
function handleDeleteButton() {
var listItemData = $(this).parent().parent().data("teacher");
var id = listItemData.id;
$.ajax({
method: "DELETE",
url: "/api/teachers/" + id
}).then(getTeachers);
}
});
|
/* import directs from 'components/directs.json' */
export default function getDirects(user, directs){
for(var u of directs){
if(u.user === user)
return u;
}
return null;
}
|
import React from "react";
import Link from "gatsby-link";
import vegas from "./vegas.png";
import smo from "./smo.png";
export default () =>
<div style={{margin: `3rem auto`, maxWidth: 1000}}>
<Link to="/"><h1>Fredo's Blog</h1></Link>
<h2>Portfolio</h2>
<a href="https://brave-northcutt-5b215f.netlify.com/" target="_blank"><img style={{height: '300px'}} src={vegas} alt="Vegas App" /></a>
<br />
<br />
<a href="https://adoring-raman-8394b5.netlify.com/" target="_blank"><img style={{height: '300px'}} src={smo} alt="Mario Blog" /></a>
<br />
</div>
|
const BetterDB = require('better-sqlite3');
const updateFeatureStatusSync = require('./updateFeatureStatusSync');
/**
* Delete all feature data by projectCode. Sync mode.
* @param {string} projectDir - Project directory
* @param {string} projectCode - Project code
*/
function deleteFeature(projectDir, projectCode) {
let dbDir = projectDir.substr(0, projectDir.lastIndexOf(".")) + ".db";
let resultDb = new BetterDB(dbDir);
let stmt = resultDb.prepare(`DROP TABLE IF EXISTS env_feature;`);
stmt.run();
stmt = resultDb.prepare(`DROP TABLE IF EXISTS feature;`);
stmt.run();
resultDb.close();
updateFeatureStatusSync(0, projectCode);
}
module.exports = deleteFeature;
|
(var bsm = {
panels: {
panel: function (type, title, content) {
switch (type) {
case 'info':
return this.panelInfo(title, content)
break;
case 'default':
return this.panelDefault(title, content)
break;
case 'success':
return this.panelSuccess(title, content)
break;
default:
break;
}
},
panelInfo: function (title, content) {
return m('div', { class: 'panel panel-info' }, [
m('div', { class: 'panel-heading' }, [
m('h3', { class: 'panel-title' }, title)
]),
m('div', { class: 'panel-body' }, [
content
])
])
},
panelDefault: function (title, content) {
return m('div', { class: 'panel panel-default' }, [
m('div', { class: 'panel-heading' }, [
m('h3', { class: 'panel-title' }, title)
]),
m('div', { class: 'panel-body' }, [
content
])
])
},
panelSuccess: function (title, content) {
return m('div', { class: 'panel panel-success' }, [
m('div', { class: 'panel-heading' }, [
m('h3', { class: 'panel-title' }, title)
]),
m('div', { class: 'panel-body' }, [
content
])
])
}
},
container: {
jumbotron: function (content) {
return m('div', { class: 'jumbotron' }, content);
},
jumboContainer: function (content, className) {
return m('div', { class: 'jumbotron ' + className }, [
m('div', { class: 'container' }, content)
]);
},
container: function (content) {
return m('div', {class:'container'}, content)
}
},
alerts: {
success: function (alert, msg) {
return m('div', { class: 'alert alert-success' }, [
m('strong', alert),
m('span', msg)
])
},
info: function (alert, msg) {
return m('div', { class: 'alert alert-info' }, [
m('strong', alert),
m('span', msg)
])
},
warning: function (alert, msg) {
return m('div', { class: 'alert alert-warning' }, [
m('strong', alert),
m('span', msg)
])
},
danger: function (alert, msg) {
return m('div', { class: 'alert alert-danger' }, [
m('strong', alert),
m('span', msg)
])
}
},
buttons: {
def: function (content) {
return m('div', { class: 'btn btn-default' }, content);
},
primary: function (content) {
return m('div', { class: 'btn btn-primary' }, content);
},
success: function (content) {
return m('div', { class: 'btn btn-succcess' }, content);
},
warning: function (content) {
return m('div', { class: 'btn btn-warning' }, content);
},
info: function (content) {
return m('div', { class: 'btn btn-info' }, content);
},
danger: function (content) {
return m('div', { class: 'btn btn-danger' }, content);
},
submit: function (click) {
//click is a function that takes event
return m('button[type=submit]', { class: 'btn btn-primary', onclick: click }, 'Submit');
},
},
images: {
circle: function (src, alt, width) {
return m('img', { class: 'img-circle', 'src': src, 'alt': alt, 'width':width })
},
rounded: function (src, alt, width) {
return m('img', { class: 'img-rounded', 'src': src, 'alt': alt, 'width': width })
},
thumb: function (src, alt, width) {
return m('img', { class: 'img-thumbnail', 'src': src, 'alt': alt, 'width': width })
}
},
code: {
inline: function (content) {
return m('code', content)
},
input: function (content) {
return m('kbd', content)
},
basic: function (content) {
return m('pre', content)
},
vars: function (content) {
return m('var', content)
},
samp: function (content) {
return m('samp', content)
}
},
forms: {
form: function (content) {
return m('form', { 'role': 'form' }, content)
},
group: function(content) {
return m('div', { class: 'form-group' }, content)
},
text: function (content, placeholder) {
return m('label', content, [
m('input[type=text]', { class: 'form-control', 'placeholder': placeholder })
])
},
textarea: function (content, placeholder, rows) {
//takes the placeholder, number of rows
return m('label', content, [
m('textarea', {class:'form-control', 'rows':rows})
])
},
pwd: function (content, placeholder) {
if (placeholder === "") {
placeholder = "Password";
}
return m('label', {}, [
m('input[type=password]', { class: 'form-control', 'placeholder': placeholder })
], content)
},
chk: function (content) {
return m('label', {}, [
m('input[type=checkbox]', { class: 'form-control' })
], content)
},
radio: function (content) {
return m('label', {}, [
m('input[type=radio]', { class: 'form-control'})
], content)
},
input: function (content, placeholder) {
return m('input[type=text]', {class:'form-control', 'placeholder':placeholder});
}
},
wells: {
well: function(content) {
return m('div', { class: 'well' }, content)
},
large: function (content) {
return m('div', {class:'well well-lg'}, content)
},
small: function (content) {
return m('div', { class: 'well well-sm' }, content)
}
}
})();
|
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import { HTTP } from 'meteor/http';
import { Meteor } from 'meteor/meteor';
//import './home.html';
// ReactiveTabs.createInterface({
// template: 'dynamicTabs',
// onChange: function (slug, template) {
// // This callback runs every time a tab changes.
// // The `template` instance is unique per {{#basicTabs}} block.
// console.log('[tabs] Tab has changed! Current tab:', slug);
// console.log('[tabs] Template instance calling onChange:', template);
// }
// });
Template.homePage.onRendered(function onRendered(){
if(Session.get('accountVerify') =='verified')
{
Router.go('/welcome-to-tripwire');
}
// alert('hello');
/*$(document).ready(function() {
$("#owl-demo").owlCarousel({
navigation : true, // Show next and prev buttons
slideSpeed : 300,
paginationSpeed : 400,
singleItem:true
// "singleItem:true" is a shortcut for:
// items : 1,
// itemsDesktop : false,
// itemsDesktopSmall : false,
// itemsTablet: false,
// itemsMobile : false
});
});*/
});
Template.homePage.onCreated(function helloOnCreated() {
// counter starts at 0
// alert('hello world');
this.counter = new ReactiveVar(0);
document.body.style.backgroundColor = '#fff';
//document.body.style.color = ' #00827f !important';
});
Template.homePage.helpers({
destroy: function() {
this.dom.remove();
},
tabs: function(){
var temp = Iform.find({parent_id: null},{sort: {ordernumber: 1}}).fetch();
if(temp !== null){
// Every tab object MUST have a name and a slug!
return temp;
}
},
IsactiveTab: function(){
// var temp = Iform.find({parent_id: null},{sort: {ordernumber: 1}}).fetch();
// alert(temp[0]._id);//.addClass = 'Active';
// Use this optional helper to reactively set the active tab.
// All you have to do is return the slug of the tab.
// You can set this using an Iron Router param if you want--
// or a Session variable, or any reactive value from anywhere.
var temp = document.getElementsByClassName('dynamicTabs-container');
temp.className = "";
return;
// If you don't provide an active tab, the first one is selected by default.
// See the `advanced use` section below to learn about dynamic tabs.
//return Session.get('activeTab'); // Returns "people", "places", or "things".
}
});
// Template.foo.helpers({
// destroy: function() {
// this.dom.remove();
// }
// });
Template.homePage.events({
});
|
const redis = require('async-redis');
const uuid = require('uuid/v4');
const { runRequestAt } = require('./libs');
const client = redis.createClient({
host: process.env.REDIS_HOST,
port: process.env.REDIS_HOST,
password: process.env.REDIS_PASSWORD,
});
const EXPIRY_SECS = process.env.REDIS_TTL;
// FIXME: actual validation, ideally via openAPI spec
const validatePayload = data => data;
// TODO: add logic to set rule for scheduling reservation
const setReservationSchedule = () => {
};
module.exports.createBonfimFixtureById = async (event) => {
const id = uuid();
let date;
let time;
let court;
try {
({ date, time, court } = validatePayload(
JSON.parse(event.body),
));
} catch (e) {
return {
statusCode: 400,
body: JSON.stringify({ code: 400, message: e }),
};
}
try {
const reserveAt = runRequestAt(date, 'bonfim');
const data = {
date,
time,
court,
reserveAt: reserveAt.toISOString(),
status: 'acknowledged',
};
// into ['id', id, 'date', date, ...]
const zipped = Object.entries(data).reduce(
(arr, keyValue) => [...arr, ...keyValue],
[],
);
await client.hmset(id, zipped);
await client.expire(id, EXPIRY_SECS);
// async send schedule; we don't await the response
setReservationSchedule();
return {
statusCode: 202,
headers: {
link: `/bonfim/${id}`,
},
body: JSON.stringify({ id }),
};
} catch (e) {
return {
statusCode: 500,
body: JSON.stringify({ code: 500, message: e }),
};
}
};
module.exports.showBonfimFixtureById = async (event) => {
const { id } = event.pathParameters;
const data = await client.hgetall(id);
return {
statusCode: data ? 200 : 404,
body: data ? JSON.stringify(data) : undefined,
};
};
module.exports.deleteBonfimFixtureById = async (event) => {
const { id } = event.pathParameters;
const deleted = await client.del(id);
return {
statusCode: deleted ? 204 : 404,
};
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.