text stringlengths 7 3.69M |
|---|
const router = require("express").Router();
const updateProject = require("../helpers/updateProject");
const checkProject = require("../middleware/verifyProjects");
router.put("/projects/",checkProject, (req, res) => {
updateProject(req, res);
});
module.exports = router; |
$ ( document ).ready ( function( ) {
$ ( "#banner_logo-img" ).click ( function( ) {
location = "/";
} );
$ ( "#banner_title" ).click ( function( ) {
location = "/";
} );
var imgData = $ ( "#img-data" ).html ( );
$ ( "#public-share-image" ).html ( "<img id='public-share-image-img' src='" + imgData + "' >" );
} );
|
/* eslint-disable no-console */
import crypto from 'crypto';
import { mailchimpApi, formatUpdateResponse, formatFormInput } from '../utilities';
function md5(str) {
return crypto
.createHash('md5')
.update(str)
.digest('hex');
}
export default function doUpdateUser(event, _, cb) {
const mailingListId = process.env.MAILING_LIST_ID;
const body = formatFormInput(event, true);
const emailAddress = body.email_address.toLowerCase();
const link =
`https://us6.api.mailchimp.com/3.0/lists/${mailingListId}/members/` + md5(emailAddress);
return mailchimpApi(link, 'PATCH', JSON.stringify(body))
.then(json => {
console.log('updateUser request:', JSON.stringify(body, true, '..'));
const result = formatUpdateResponse(json, body);
cb(null, result);
})
.catch(err => {
cb(err);
});
}
|
const SearchResults = ({ userDetails }) =>{
let months = ["Jan","Feb","March","April","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"]
let joinDate = new Date(userDetails.created_at)
let date = joinDate.getDate()
let month = joinDate.getMonth()
let year = joinDate.getFullYear()
console.log(date,month,year)
return(
<div className="container">
<img src={userDetails.avatar_url} alt="" />
<div className="wrapper">
<div className="profile-info">
<div className="names">
<h3>{userDetails.name}</h3>
<p className="username">@{userDetails.login}</p>
<p className="bio">{userDetails.bio === null ? 'This profile has no bio' : userDetails.bio}</p>
</div>
<p className="date-joined">Joined {`${date} ${months[month + 1]} ${year}`}</p>
</div>
<div className="git-info">
<div className="repo">
<h3>Repo</h3>
<p>{userDetails.public_repos}</p>
</div>
<div className="followers">
<h3>Followers</h3>
<p>{userDetails.followers}</p>
</div>
<div className="following">
<h3>Following</h3>
<p>{userDetails.following}</p>
</div>
</div>
<footer>
<ul>
<li ><i className="fas fa-map-marker-alt" style={{color: userDetails.location === null || userDetails.location === "" ? "#ccc" : "#fff"}}></i>{userDetails.location === null ? "Not available" : userDetails.location}</li>
<li><i className="fab fa-twitter" style={{color: userDetails.twitter_username === null || userDetails.twitter_username === "" ? "#ccc" : "#fff"}} ></i>{userDetails.twitter_username === null ? "Not available" : userDetails.twitter_username}</li>
<li className="link"><i className="fas fa-link" style={{color: userDetails.blog === null || userDetails.blog === "" ? "#ccc" : "#fff"}}></i>{userDetails.blog === null || userDetails.blog === "" ? "Not available" : userDetails.blog}</li>
<li><i className="fas fa-building" style={{color: userDetails.company === null ? "#ccc" : "#fff"}}></i>{userDetails.company === null ? "Not Available" : userDetails.company}</li>
</ul>
</footer>
</div>
</div>
);
}
export default SearchResults |
var url = "https://fewd20.herokuapp.com/chat";
var user;
var message;
var usedMessage = [];
function messageData(){
$.get(url, function(data, status){
for (var i = 0; i < data.length; i++){
console.log(data[i]);
if (usedMessage.indexOf(data[i].message) === -1){
usedMessage.push(data[i].message);
$('#list').append('<li>' + '<b>Name:</b>' + ' ' + data[i].user + '</br> ' + '<b>Message:</b>' + ' ' + data[i].message + '</li>');
}
}
}).fail(function(data){
console.log('not working');
})
}
/* Print the initial message data that is already in the database */
messageData();
setInterval(function(){ messageData(); }, 3000);
/* submit message */
$('#submit').click(function(){
event.preventDefault();
user = $('#username').val();
message = $('#message').val();
var obj = {
user: user,
message: message
}
$.post(url, obj, function(data, status){
console.log('yay');
}).fail(function(data){
console.log('not working');
})
messageData();
$('input[type=text]').val('');
$('textarea[type=text]').val('');
})
|
const markmass = 78;
const markheight = 1.69;
const johnmass = 92;
const johnheight = 1.95;
const BMImark = markmass / markheight ** 2;
const BMIjohn = johnmass / (johnheight * johnheight)
console.log(BMImark, BMIjohn);
const firstName = 'vrushabh';
const age = 18;
const birthYear = 2002;
const idea = `${firstName}, ${age}, ${birthYear}`;
console.log(idea);
console.log(`lion\ntiger`);
const birthYear = 2000;
console.log(String(birthYear));
console.log(birthYear + 18);
console.log(typeof (birthYear));
const money = 0;
if (money) {
console.log(`job`);
} else {
console.log(`not job`);
}
const favourite = Number(prompt(`favourite number`));
if (favourite == 16) {
console.log("king`s birthday");
} else if (favourite == 04) {
console.log("king was coming in the world")
}
else {
console.log("nothing");
}
const bill = 275;
const tip = bill >= 300 && bill <= 50 ? bill * 0.15 : bill * 0.20;
console.log(`the bill is ${bill} , the tip is ${tip}, the total ${bill + tip}`);
const bill2 = 40;
const tip2 = bill2 >= 300 && bill2 <= 50 ? bill2 * 0.15 : bill2 * 0.20;
console.log(`the bill is ${bill2} , the tip is ${tip2}, the total ${bill2 + tip2}`);
const bill3 = 430;
const tip3 = bill3 >= 300 && bill3 <= 50 ? bill3 * 0.15 : bill3 * 0.20;
console.log(`the bill is ${bill3} , the tip is ${tip3}, the total ${bill3 + tip3}`);
function loger() {
console.log("javascript");
}
loger();
function food(apples, oranges) {
console.log(apples, oranges);
const juice = `juice with ${apples} apples, ${oranges} oranges`;
return juice;
}
const applejuice = food(5, 9);
console.log(applejuice);
function calAge(birthYear) {
return 2037 - birthYear;
}
const c1 = calAge(1992);
console.log(c1);
function food(oranges, apple) {
return oranges + apple;
}
console.log(food(5, 6));
const calAge = birthYear => {
const b1 = 2037 - birthYear;
const Age = 65 - b1;
return Age;
}
console.log(calAge(1991));
const calAge = function (birthYear) {
return 2037 - birthYear;
}
const A1 = function (birthYear) {
const Age = calAge(birthYear);
const retirment = 65 - Age;
return retirment;
}
console.log(A1(1991));
console.log(A1(1992));
const calcAverage = (a, b, c) => (a + b + c) / 3;
console.log(calcAverage(3, 4, 5));
let scoreD = calcAverage(44, 32, 81);
let scoreK = calcAverage(65, 61, 51);
console.log(scoreD, scoreK);
const checkWinner = function (avgD, avgK) {
if (avgD >= 2 * avgK) {
console.log(`Dolphins win (${avgD} vs. ${avgK})`);
} else if (avgK >= 2 * avgD) {
console.log(`Koalas win (${avgK} vs. ${avgD})`);
} else {
console.log('No team wins...');
}
}
checkWinner(scoreD, scoreK);
checkWinner(404, 101);
const friends = [`rahul`, `mihir`, `parth`];
friends.push(`hmm`);
friends.pop();
console.log(friends);
console.log(friends[0]);
const age = 45;
const firstName = `vrushabh`;
const v1 = [firstName, `mihir`, age]
console.log(v1);
const calcTip = function (bill) {
return bill >= 50 && bill <= 300 ? bill * 0.15 : bill * 0.2;
}
const bills = [125, 555, 44];
const tips = [calcTip(bills[0]), calcTip(bills[1]), calcTip(bills[2])];
const totals = [bills[0] + tips[0], bills[1] + tips[1], bills[2] + tips[2]];
console.log(bills, tips, totals);
const myObj = {
firstName: 'vrushabh',
lastName: 'vasoya',
age: 2037 - 2002,
job: 'programmer',
friends: ['hmm1', 'hmm2', 'hmm3']
};
console.log(myObj);
console.log(myObj.job);
const interestedIn = prompt('What do you want to know about vrushabh? Choose between firstName, lastName, age, job, and friends');
if (myObj[interestedIn]) {
console.log(myObj[interestedIn]);
} else {
console.log('Wrong request! Choose between firstName, lastName, age, job, and friends');
}
const myObj = {
firstName: 'vrushabh',
lastName: 'vasoya',
age: 2037 - 2002,
job: 'programmer',
friends: ['hmm1', 'hmm2', 'hmm3'],
calAge: function (birthYear) {
return 2037 - birthYear;
}
};
console.log(myObj.calAge(2002));
const mark = {
fullName: 'vrushabh',
mass: 78,
height: 1.69,
calcBMI: function () {
this.bmi = this.mass / this.height ** 2;
return this.bmi;
}
};
const mark1 = {
fullName: 'rahul',
mass: 92,
height: 1.95,
calcBMI: function () {
this.bmi = this.mass / this.height ** 2;
return this.bmi;
}
};
mark.calcBMI();
mark1.calcBMI();
console.log(mark.bmi, mark1.bmi);
for (let i = 0; i <= 10; i++) {
console.log("vrushabh is a king", i);
}
const year = [2001, 2004, 2003];
const age = [];
for (let i = 0; i < year.length; i++) {
age.push(2035 - year[i]);
};
g
let dice = Math.trunc(Math.random() * 6) + 1;
while (dice !== 6) {
console.log(`You rolled a ${dice}`);
dice = Math.trunc(Math.random() * 6) + 1;
if (dice === 6) console.log('Loop is about to end...');
}
|
import './App.css';
import Form from "./Form";
function App() {
return (
<div className="App">
<div className="container">
<div className="header">
<h1>Dictionary</h1>
<i className="sentence">dic·tio·nary | \ ˈdik-shə-ˌner-ē</i>
</div>
<div className="formrow">
<div className="row">
<Form />
</div>
</div>
<div className="styling">
<h2>Future</h2>
<p className="spelling">/ˈfjuːtʃə/</p>
<p className="noun">Noun</p>
<ul>
<li>a period of time following the moment of speaking or writing; time regarded as still to come.
"we plan on getting married in the near future"</li>
<li>contracts for assets (especially commodities or shares) bought at agreed prices but delivered and paid for later.</li>
</ul>
<p className="adjective">Adjective</p>
<ul>
<li>at a later time; going or likely to happen or exist.
"the needs of future generations"</li>
</ul>
<p className="synonyms">Synonyms</p>
<ul>
<li>time to come</li>
<li>time ahead</li>
<li>what lay/lies ahead</li>
<li>coming times</li>
</ul>
<div className="row">
<div className="col">
<img src="./future1.jpg" alt="" />
</div>
<div className="col">
<img src="./future2.jpg" alt="" />
</div>
</div>
<div className="row">
<div className="col">
<img src="./future3.jpg" class="img-fluid" alt="" />
</div>
<div className="col">
<img src="./future4.jpg" alt="" />
</div>
</div>
</div>
</div>
</div>
);
}
export default App;
|
// http://crbug.com/1079333: registerProtocolHandler() silently fails when
// called from a background page or popup, so we need to open a tab.
chrome.tabs.create({"url": "register.html", "selected": true});
|
import Picker from 'react-giphy-component'
import React, { Component} from 'react'
class Gif extends Component {
constructor(props){
super(props);
this.state={
visible:false
}
}
log = (gif) => {
{this.props.addGif(gif)};
this.setState({
visible:true
})
}
render () {
return (
<div>
<Picker onSelected={this.log} />
{this.state.visible ?<img alt="gif" src={this.props.url} ></img> : null}
</div>
)
}
}
export default Gif; |
var firebaseadmin = require('../firebase-admin.js');
var senderModel = require('../models/sender');
var recieverModel = require('../models/reciever');
var rtdb = firebaseadmin.database();
var userHelper = require('./userHelper');
var header = "[messagesHelper]";
var messageSocketURI = "messageSocket/";
var messagesHelper = {};
var messageCollection = [];
messagesHelper.getSentMessages = function(userId, callBack){
senderModel.find({senderId: userId})
.then(function(message){
if(message){
console.log(message);
}else{
console.log("No messages");
return;
}
});
}
messagesHelper.getMessage = function(id, rModel, callBack){
var model;
if(rModel) model = recieverModel;
else model = senderModel;
model.findOneAndUpdate({_id:id},{$set:{read:true}})
.then(function(message){
callBack(message);
})
.catch(function(err){
console.log(err);
console.log('The message with id '+ id + ' not found in sent list');
});
}
messagesHelper.getMessagesMetadata = function(me, rModel, callBack){
var model, field;
if(rModel) {model = recieverModel; field="recipientId";}
else {model = senderModel; field="senderId";}
userHelper.ifUserToken(me, function(result, user){
if(result){
if(rModel){
model.find({recipientId: user.userid})
.then(function(messages){
var messageList = [];
messages.forEach(function(message){
var messageListEntry = {
read: message.read,
senderName: message.senderName,
subject: message.subject,
timestamp:message.timestamp,
id:message._id,
senderId: message.senderId
}
messageList.push(messageListEntry);
});
callBack(messageList);
});
}else{
model.find({senderId: user.userid})
.then(function(messages){
var messageList = [];
messages.forEach(function(message){
var messageListEntry = {
subject: message.subject,
timestamp:message.timestamp,
id:message._id,
recipientName: message.recipientName
}
messageList.push(messageListEntry);
});
callBack(messageList);
});
}
}else{
callBack([]);
}
});
}
/*
100 - new message not saved to reciever
102 - new message copy not saved for sender
103 - new message saved successfully
*/
messagesHelper.sendMessage = function(payload, callBack){
payload.read = false;
var new_message = new recieverModel(payload);
new_message.save(function(err){
if(err){
console.log(err);
return callBack(100);
}else{
delete payload.read;
var new_message_sender = new senderModel(payload);
new_message_sender.save(function(err){
if(err){
//delete the message from sender
new_message.remove(function(err){if(err){console.log(header, "something messed up when deleting from reciever copy");}});
console.log(err);
return callBack(102);
}else{
return callBack(103);
}
});
}
});
}
messagesHelper.deleteMessage = function(messageId, inbox, callBack){
var model;
if(inbox){
model = recieverModel;
}else{
model = senderModel;
}
model.findOneAndRemove({_id:messageId}, function(err, doc){
if(err){
console.log(err);
callBack(false);
}else{
callBack(true);
}
});
}
messagesHelper.getSize = function(callBack){
senderModel.collection.stats(function(err,stat){
if(err){
console.log(header,err);
return callBack(0);
}else{
var result = stat.storageSize;
recieverModel.collection.stats(function(err, rstat){
if(err){
console.log(header,err);
}else{
result+=rstat.storageSize;
}
callBack(result);
});
}
});
}
module.exports = messagesHelper; |
//Create QR code object using imported script from HTML
var qrcode = new QRCode("qrcode");
var submit = document.getElementById("submit");
submit.addEventListener("click", function(){
console.log("Button pressed");
var request = new XMLHttpRequest();
var url = 'https://ms57713.starbucks.net/beta/api/starpay/qrcode/type2/encode';
request.open('POST', url);
request.onload = function() {
var data = JSON.parse(request.responseText);
console.log("request.onload activated");
console.log(request.responseText);
qrcode.makeCode(data);
//console.log(data);
};
request.send();
});
//Calls the makeCode function on the text input
function makeCode () {
var text = document.getElementById("text");
qrcode.makeCode(text.value);
}
//makeCode function declaration, definition coming from JS Script imported in head of HTML
makeCode();
//Calls the makeCode function when the enter key (keyCode 13) is pressed on the text input
$("#text").
on("keyup", function (e) {
if (e.keyCode == 13) {
makeCode();
}
});
|
import React from "react";
import "./Register.css";
import { Redirect } from "react-router-dom";
export default class Register extends React.Component {
constructor(props) {
super(props);
this.state = {
username: "",
email: "",
password: "",
repassword: "",
usertype: "",
isLoggedIn: false,
};
}
SubmitRegister() {
const body = JSON.stringify({
username: this.state.username,
email: this.state.email,
password: this.state.password,
usertype: this.state.usertype,
});
fetch("http://localhost:4000/register", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body,
})
.then((respo) => respo.json())
.then((res) => {
if (res.name === "OrientDB.RequestError") {
alert("Email already exit!");
} else {
this.setState({ isLoggedIn: !this.state.isLoggedIn });
alert("Registered successfully");
}
})
.catch((error) => {
console.log("error in test", error);
});
}
CheckUserPassword = (e) => {
e.preventDefault();
const { password, repassword } = this.state;
if (password === repassword) {
this.SubmitRegister();
} else {
alert("Password MisMatch!");
}
};
checkLogedIn() {
if (this.state.isLoggedIn) {
return <Redirect to="/login" />;
} else {
return null;
}
}
render() {
return (
<div className="contain">
<div className="register-contain">
<div className="emty">
<h1>SIGN UP</h1>
</div>
<form>
<input
type="text"
placeholder="User Name"
id="username"
email="username"
name="username"
onChange={(e) => {
this.setState({ username: e.target.value });
}}
required
/>
<input
type="email"
placeholder="abc@gmail.com"
id="email"
name="email"
onChange={(e) => {
this.setState({ email: e.target.value });
}}
required
/>
<div className="radiobutton">
<div className="rad-patient">
<input
type="radio"
name="usertype"
id="patient"
value="patient"
onClick={(e) => {
this.setState({ usertype: e.target.value });
}}
/>
<label>Patient</label>
</div>
<div className="rad-doctor">
<input
type="radio"
name="usertype"
id="doctor"
value="doctor"
onClick={(e) => {
this.setState({ usertype: e.target.value });
}}
/>
<label>Doctor</label>
</div>
</div>
<input
type="password"
placeholder="Password"
name="password"
id="password"
onChange={(e) => {
this.setState({ password: e.target.value });
}}
required
/>
<input
type="password"
placeholder="Confirm-password"
name="repassword"
id="repassword"
onChange={(e) => {
this.setState({ repassword: e.target.value });
}}
required
/>
<input
type="submit"
value="submit"
onClick={this.CheckUserPassword}
/>
</form>
</div>
{this.checkLogedIn()}
</div>
);
}
}
|
import axios from "axios";
import { getAuth } from "./auth";
const API_URL = `http://localhost:3000/api`;
const api = axios.create({
baseURL: API_URL,
headers: {
"Content-Type": "application/json",
},
});
api.interceptors.request.use((config) => {
const { token } = getAuth();
config.headers.tokens = token || null;
return config;
});
export default api;
|
var year = '2019';
var month = '04';
var day = '26';
var hour = '11';
var minute = '34';
var second = '27';
// var result = `${year}/${month}/${day} ${hour}:${minute}:${second}`//빈칸을 채워주세요
const result = year.concat('/',month,'/',day,' ',hour,':',minute,':',second);
//concat() 메서드는 매개변수로 전달된 문자열을 메서드를 호출한 문자열에 붙여 새로운 문자열로 반환합니다.
// var result = year.concat('/', month, '/', day, ' ', hour, ':', minute, ':', second);
console.log(result);
// 출력
// 2019/04/26 11:34:27 |
import React, { Component } from 'react'
import "./app-style.css";
import Logo from "../img/KDC-logo.png"
class Home extends Component {
render() {
return (
<div className="home-page">
<div className="home-box">
<h3 className="home-header">
<img className="img-fluid" src={Logo} alt="Logo" />
</h3>
<div className="home-text">
<h2>Hey there!</h2>
<p>Most of life's big decisions feel overwhelming, and deciding what to do with your career is one of the biggest ones. But it's gonna be okay, because KDC is here to help.</p>
<p>KDC offers a wide range of career opportunities and ways to achieve them. Start by logging in and taking our career survey to determine a variety of jobs suited to your unique needs. Click on each of them to learn more, and save your favorites to come back to later.</p>
<a href="/signup" className="btn button">Let's get started!</a>
</div>
</div>
</div>
)
}
}
export default Home
|
module.export ={
plugin:{
autoprefixer: {}
}
}
|
import React from 'react';
import { MyStylesheet } from './styles';
import DynamicStyles from './dynamicstyles';
import { addIcon } from './svg';
class FindEmployee {
showprofileimage() {
const dynamicstyles = new DynamicStyles();
const myuser = dynamicstyles.getuser.call(this);
const searchProfileImage = dynamicstyles.getsearchimage.call(this)
if (myuser.profileurl) {
return (<img src={myuser.profileurl} style={{ ...searchProfileImage }} alt={`${myuser.firstname} ${myuser.lastname}}`} />)
} else {
return;
}
}
showemployee(employee) {
const styles = MyStylesheet();
const dynamicstyles = new DynamicStyles();
const searchProfileImage = dynamicstyles.getsearchimage.call(this)
const addCompany = dynamicstyles.getAddCompany.call(this)
const regularFont = dynamicstyles.getRegularFont.call(this)
if (this.state.width > 800) {
return (<div style={{ ...styles.generalFlex, ...styles.bottomMargin15 }}>
<div style={{ ...styles.flex1, ...regularFont, ...styles.generalFont }}>
<div style={{ ...styles.generalContainer, ...styles.showBorder, ...searchProfileImage }}></div>
</div>
<div style={{ ...styles.flex5, ...regularFont, ...styles.generalFont }}>
{employee.firstname} {employee.lastname} <button style={{ ...styles.generalButton, ...addCompany }}
onClick={() => { this.addemployee(employee.providerid) }}>{addIcon()}</button>
</div>
</div>)
} else {
return (<div style={{ ...styles.generalFlex, ...styles.bottomMargin15 }}>
<div style={{ ...styles.flex1, ...regularFont, ...styles.generalFont }}>
<div style={{ ...styles.generalContainer, ...styles.showBorder, ...searchProfileImage }}></div>
</div>
<div style={{ ...styles.flex2, ...regularFont, ...styles.generalFont }}>
{employee.firstname} {employee.lastname} <button style={{ ...styles.generalButton, ...addCompany }}
onClick={() => { this.addemployee(employee.providerid) }}>{addIcon()}</button>
</div>
</div>)
}
}
getsearchresults() {
const dynamicstyles = new DynamicStyles();
const myuser = dynamicstyles.getuser.call(this)
let avail = [];
let search = [];
let searchterm = this.state.search;
let results = [];
const findemployee = new FindEmployee();
if (myuser) {
const allusers = dynamicstyles.getallusers.call(this)
// eslint-disable-next-line
allusers.map(user => {
if (!user.hasOwnProperty("company")) {
avail.push(user)
}
})
}
// eslint-disable-next-line
avail.map(myuser => {
if (searchterm) {
if (myuser.firstname.toLowerCase().startsWith(searchterm.toLowerCase()) || myuser.lastname.toLowerCase().startsWith(searchterm.toLowerCase())) {
search.push(myuser)
}
}
})
// eslint-disable-next-line
search.map(myuser => {
results.push(findemployee.showemployee.call(this, myuser))
})
return results;
}
showEmployeeSearch() {
const styles = MyStylesheet();
const findemployee = new FindEmployee();
const dynamicstyles = new DynamicStyles();
const regularFont = dynamicstyles.getRegularFont.call(this)
return (
<div style={{ ...styles.generalFlex }}>
<div style={{ ...styles.flex1 }}>
<div style={{ ...styles.generalFlex }}>
<div style={{ ...styles.flex1, ...regularFont, ...styles.generalFont, ...styles.bottomMargin15 }}>
Find An Employee By name <br /> <input type="text" style={{ ...styles.generalFont, ...regularFont, ...styles.addLeftMargin, ...styles.generalField }}
value={this.state.search}
onChange={event => { this.setState({ search: event.target.value }) }}
/>
</div>
</div>
{findemployee.getsearchresults.call(this)}
</div>
</div>)
}
}
export default FindEmployee; |
import React, {Component} from 'react'
import Catalog from '../../components/catalog'
export default class CatalogPage extends Component{
render(){
return (
<Catalog/>
)
}
}
/*const AddItem = styled.div`
display: flex;
flex-direction: row;
background-color: ${props => props.theme.navBarBackground};
width: 100%;
height: 75px;
justify-content: space-between;
`;*/ |
define([
'./auth.interceptor'
], function () {
'use strict';
}); |
import React, { useContext } from 'react';
import { TaskListContext } from '../context/TaskContext';
import {Task} from "./Task";
import {ListGroup} from "reactstrap";
export const TaskList = () => {
const { tasks } = useContext(TaskListContext);
return (
<ListGroup className="mt-4">
{tasks.length ? (
<>
{tasks.map(task => {
return <Task task={task} key={task.id} />;
})}
</>
) : (
<div className="no-tasks">No Tasks</div>
)}
</ListGroup>
)
}
|
import React from 'react'
import ReactMde from 'react-mde'
import 'react-mde/lib/styles/css/react-mde-all.css'
import * as Showdown from 'showdown'
// change this
// const selectedTab = 'write'
const selectedTab = 'preview'
const content = `
# This is a header And this is a paragraph
# This is a header And this is a paragraph
\`\`\`js
var a;
function aa() {}
\`\`\`
\`\`\`java
var a;
function aa() {}
\`\`\`
| Feature | Support |
| --------- | ------- |
| tables | ✔ |
| alignment | ✔ |
| wewt | ✔ |
hello
<h3>h3</h3>
`
const converter = new Showdown.Converter({
tables: true,
simplifiedAutoLink: true,
strikethrough: true,
tasklists: true,
})
class Editor4 extends React.Component {
handleValueChange = (value) => {
this.setState({ value })
}
handleTabChange = (tab) => {
this.setState({ tab })
}
render() {
return (
<ReactMde
value={ content }
onChange={ this.handleValueChange }
selectedTab={ selectedTab }
onTabChange={ this.handleTabChange }
generateMarkdownPreview={ markdown =>
Promise.resolve(converter.makeHtml(markdown))
}
/>
)
}
}
export default Editor4
|
import React from "react";
import Card from '../components/Card';
import ItemContainer from './ItemContainer'
import SearchBox from '../components/SearchBox'
//Selection list displays the info (in cards) of every item belonging
//to the selected category passed through the selectedCategory prop
class SelectionList extends React.Component {
constructor(props) {
super(props);
this.state = {
cards: [],
searchfield: '',
selectedCategory: this.props.selectedCategory,
selectedItem: '',
itemURL: '',
}
this.loadCards = this.loadCards.bind(this);
// this.selectTitle = this.selectTitle.bind(this);
this.onItemClickChange = this.onItemClickChange.bind(this);
this.onSearchChange = this.onSearchChange.bind(this);
}
// selectTitle() {
// if (this.selectedCategory === "films") {
// return "title"
// } else {
// return "name"
// }
// }
//update the cards[] state once fetching promise has been solved
async loadCards(newCards) {
this.setState({cards: newCards});
}
//Event Handler to catch the item selected whose info is to be displayed
onItemClickChange(event) {
let itemClicked = event.target.alt;
let url = event.target.attributes.getNamedItem('url').value;
// console.log("URL: ", url);
this.setState({
selectedItem: itemClicked,
itemURL: url,
})
}
//Search field event handler
onSearchChange(event) {
this.setState({searchfield: event.target.value})
console.log(this.state.searchfield);
}
//On component mount, fetch the selected category section of the Star Wars API
//and load the data updating the cards[] state
async componentDidMount(){
this.setState({
cards: [],
searchfield: '',
selectedCategory: this.props.selectedCategory,
selectedItem: '',
})
let resultsArray = [];
let category = this.props.selectedCategory;
let url = `https://swapi.co/api/${category}`;
//getData fetchs the info from the SWAPI and returns all the data
const getData = async function() {
do{
let temporaryResults = [];
const response = await fetch(url)
const data = await response.json()
temporaryResults = data.results
url = data.next
resultsArray = resultsArray.concat(temporaryResults);
} while (url !== null)
return resultsArray;
}
//call getData and load its results with the loadCards method.
let newCards = await getData();
this.loadCards(newCards);
}
render() {
//If the cards haven't been loaded yet, show "Loading" on the screen
if (this.state.cards.length === 0) {
return(
<h1>Loading</h1>
)
//If the cards have been loaded and no item has been selected
} else if(this.state.selectedItem === '') {
//Handling the Searchfield behavior:
//filtered cards is a variable that holds all the items that comply with the following:
//.filter the cards[] array and return every card that includes whatever value is
//inside the searchfield (returns all the cards if the value is empty)
let filteredCards;
//Same function, but the API returns .title attribute for films name
if (this.state.selectedCategory === "films") {
filteredCards = this.state.cards.filter(card => {
return card.title.toLowerCase().includes(this.state.searchfield.toLowerCase())
})
// and returns .name attribute for everything else
} else {
filteredCards = this.state.cards.filter(card => {
return card.name.toLowerCase().includes(this.state.searchfield.toLowerCase())
})
}
return(
<div>
{/* SearchBox is the Search Field Component */}
<SearchBox
key={"searchbox"}
searchChange={this.onSearchChange}
category = {this.state.selectedCategory}
/>
{
// .map through the filteredCards array and return a Card Component
// that will display all the filtered items (all of them if searchbox is empty)
// of the chosen category within a Card component
filteredCards.map((categoria, index) => {
//If the chosen category is films, a .title attribute is required
if (this.state.selectedCategory === "films") {
return (
<Card
key={categoria.title}
title={categoria.title}
clicked={this.onItemClickChange}
url={categoria.url}
/>
)
// If the chosen category is anything else, a .name is required
} else {
return (
<Card
key={categoria.name}
title={categoria.name}
clicked={this.onItemClickChange}
url={categoria.url}
/>
)
}
})
}
</div>
)
// If the cards have been loaded and an item has been already chosen, return ItemContainer
} else {
return(
<div>
{/* Item Container is a Container that manages all the information of a singular selected
item of a singular selected category*/}
<ItemContainer
name={this.state.selectedItem}
id={this.state.itemID}
category={this.state.selectedCategory}
url={this.state.itemURL}
/>
</div>
)
}
}
}
export default SelectionList; |
import faker from "faker";
const mount = (el) => {
let products = "";
for (let i = 0; i < 5; i++) {
const name = faker.commerce.productName();
products += `<div>${name}</div>`;
}
el.innerHTML = products;
};
// Context/Situation #1
// running file in development in isolation
// using local index.html
// which has element with id='dev-products'
// render app into element
if (process.env.NODE_ENV === "development") {
const el = document.querySelector("#dev-products");
// assuming our contianer doesn't have an el w/ id='dev-products
if (el) {
// prob running in isolation
mount(el);
}
}
// Context/Situation #2
// running file in development for prod
// through container app
// no gaurantee of element with id='dev-products'
// do not want to immediately render the app
export { mount };
|
import React, {} from 'react';
import { Bar } from 'react-chartjs-2';
import { ClipLoader } from 'react-spinners';
import {
onClearAll,
clearAll,
askQuestion,
connectToRoom,
onQuestionReceived,
answerStudentQuestion,
onStudentQuestionAnswered,
onLecturerQuestionAnswered,
onJoinError,
onRelogin
} from './api';
const HashMap = require('hashmap');
const cookieHandler = require('./CookieHandler');
class Lecturer extends React.Component {
constructor(props) {
super(props);
const credentials = cookieHandler.getCookie("auth");
let faq = ["I don't understand!", "Could you give an example?",
"Could you slow down?", "Could you speed up?"]
this.state ={
studentQuestionMap: new HashMap(),
lecturerQuestionMap: new HashMap(),
question_to_render: false,
view: "main",
setQuestionTextField: '',
option_set: [],
faq: faq,
room: props.room,
login: undefined,
name: undefined,
credentials: credentials,
errorMessage: undefined,
loading: (credentials !== undefined && credentials !== '') ? true : false,
data: {
labels: faq,
datasets: [{
label: '',
data: [0, 0, 0, 0],
backgroundColor: [
'rgba(255, 99, 132, 0.4)',
'rgba(255, 206, 86, 0.4)',
'rgba(54, 162, 235, 0.4)',
'rgba(75, 192, 192, 0.4)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(255, 206, 86, 1)',
'rgba(54, 162, 235, 1)',
'rgba(75, 192, 192, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}],
xAxes: [{
ticks:{
display: false
}
}]
},
legend:{
display:false
}
}
}
this.updateSetQuestionTextField = this.updateSetQuestionTextField.bind(this);
this.send_email = this.send_email.bind(this);
this.updateBarChart = this.updateBarChart.bind(this);
this.ask = this.ask.bind(this);
if(credentials !== undefined && credentials !== ''){
connectToRoom(credentials, this.state.room, "lecturer", questionMaps =>{
let map = new HashMap();
let map2 = new HashMap();
map.copy(questionMaps.sqm);
map2.copy(questionMaps.lqm);
this.updateBarChart(map);
this.setState({
studentQuestionMap: map,
lecturerQuestionMap:map2,
room: this.state.room,
options: this.state.options,
loading: false
})
});
}
onJoinError((error) => {
this.setState({errorMessage: error, loading: false});
});
onRelogin((user) => {
this.setState({
login: user.login,
name: user.displayName,
})
})
onQuestionReceived(received_question => {
if(received_question.type === "student") {
let map = this.state.studentQuestionMap;
if(received_question.data == null || received_question.data.count <= 0)
map.delete(received_question.question)
else
map.set(received_question.question, received_question.data);
this.updateBarChart(map);
this.setState({
studentQuestionMap: map,
room: this.state.room,
options: this.state.options
})
}
else if(received_question.data !== null){
let map = this.state.lecturerQuestionMap;
map.set(received_question.question, received_question.data);
this.setState({lecturerQuestionMap: map})
}
else {
let map = this.state.studentQuestionMap;
map.delete(received_question.question);
this.setState({
studentQuestionMap: map
})
}
});
onStudentQuestionAnswered(question => {
let map = this.state.studentQuestionMap;
map.delete(question);
this.updateBarChart(map);
this.setState({
studentQuestionMap: map,
room: this.state.room,
options: this.state.options
})
});
onLecturerQuestionAnswered((answer) => {
let map = this.state.lecturerQuestionMap;
map.get(answer.question).answers.push(answer.answer);
map.get(answer.question).count++;
this.setState({
lecturerQuestionMap: map
});
})
onClearAll(() => {
let map = new HashMap();
let map2 = new HashMap();
this.updateBarChart(map);
this.setState({
studentQuestionMap: map,
lecturerQuestionMap: map2,
});
});
}
updateBarChart(map) {
var dataNew=this.state.data;
dataNew.datasets[0].data=[
map.get(this.state.faq[0]) ? map.get(this.state.faq[0]).count : null,
map.get(this.state.faq[1]) ? map.get(this.state.faq[1]).count : null,
map.get(this.state.faq[2]) ? map.get(this.state.faq[2]).count : null,
map.get(this.state.faq[3]) ? map.get(this.state.faq[3]).count : null];
this.setState({data: dataNew})
}
updateSetQuestionTextField(e) {
this.setState({setQuestionTextField: e.target.value});
}
updateOptionSetTextField(n, e) {
let arr = this.state.option_set.slice(0);
arr[n] = e.target.value;
this.setState({option_set: arr});
this.forceUpdate();
}
ask(question_type){
let question = this.state.setQuestionTextField;
let options = this.state.option_set.slice();
askQuestion(question,
{question_type: question_type,
options: options,
user: {room: this.state.room,
login: this.state.login,
name: this.state.name,
type: "lecturer"}
});
this.setState({setQuestionTextField: '',
option_set: []});
}
componentDidMount(){
fetch('http://localhost:8080/data/' + this.state.room, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
start_time:0,
end_time:1546976183610
})
})
.then(res =>{
return res.json();
})
.then(data =>{
//console.log(data);
})
.catch((err) => {
//Error
})
}
send_email(question) {
let mail_link = "mailto:";
question[1].users.forEach(user => {
mail_link = mail_link + user.login + "@ic.ac.uk, ";
});
window.open(mail_link)
}
logout(){
cookieHandler.setCookie('auth', '');
window.location.href = '/';
}
render_question(question_text) {
let question = this.state.lecturerQuestionMap.get(question_text)
if(question.type === "text") {
let answerList = question.answers.map((user_answer) =>
<div className="row">
<p className="col-8 text-left">{user_answer.answer}</p>
<p className="col-4 text-right">{user_answer.user}</p>
<hr className=" w-100"/>
</div>
);
return (
<div>
<button className="btn btn-outline-dark" onClick={()=>this.setState({view: "viewingAnswers"})}>Back</button>
{answerList}
</div>
);
}
else if(question.type === "multiple choice") {
let counts = [];
for (let i = 0; i < question.options.length; i++) {
counts.push(0);
}
question.answers.forEach((user_answer) => {
for (let i = 0; i < counts.length; i++) {
if (user_answer.answer === question.options[i]) {
counts[i]++;
}
}
});
let results = {labels: question.options,
datasets: [{
label:'',
data: counts,
backgroundColor: [
'rgba(255, 99, 132, 0.4)',
'rgba(255, 206, 86, 0.4)',
'rgba(54, 162, 235, 0.4)',
'rgba(75, 192, 192, 0.4)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(255, 206, 86, 1)',
'rgba(54, 162, 235, 1)',
'rgba(75, 192, 192, 1)',
],
borderWidth: 1
}]}
let options = {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}],
xAxes: [{
ticks:{
display: true
}
}]
},
legend:{
display:true
}
}
return (
<div className="container my-3">
<button className="btn btn-outline-dark" onClick={()=>this.setState({view: "viewingAnswers"})}>Back</button>
<Bar
data={results}
options={options}
/>
</div>
);
}
}
render() {
let option_set_list = [];
for (let i = 0; i < this.state.option_set.length; i++) {
let j = i;
option_set_list.push(
<div className="row longWord">
<input type="text" className="form-control my-4"
value={this.state.option_set[i]} placeholder={"Option " + (i + 1)}
onChange={(e) => this.updateOptionSetTextField(j, e)}/>
{(this.state.option_set.length === i+1) ?
<div className = "input-group-append my-4">
<button className="btn btn-outline-dark px-4" type="button" onClick={() => {this.state.option_set.push(""); this.forceUpdate()}}>Add another option</button>
<button className="btn btn-outline-dark px-4" type="button" onClick={() => {this.ask("multiple choice")}}>Done!</button>
</div>:
undefined}
</div>);
}
let setView =
<div>
<h1>{this.state.room + " Question Setting Page"}</h1>
<div id="Change view">
<button className="btn btn-outline-dark" onClick={()=>this.setState({view: "main"})}>View student feedback</button>
<button className="btn btn-outline-dark" onClick={()=>this.setState({view: "viewingAnswers"})}>View student answers</button>
</div>
<div className="input-group container-fluid col-9 mt-5">
<input type="text" className="form-control my-4" placeholder="Ask your question here" value={this.state.setQuestionTextField} onChange={this.updateSetQuestionTextField}/>
<div className="input-group-append my-4">
<button className="btn btn-outline-dark px-4" type="button" onClick={() => {this.state.option_set.push(""); this.forceUpdate()}}>Multiple Choice</button>
<button className="btn btn-outline-dark px-4" type="button" onClick={()=> {this.ask("text")}}>Text answer</button>
</div>
</div>
<div>{option_set_list}</div>
</div>
let lecturerQuestions = this.state.lecturerQuestionMap.keys();
let lecturerQuestionList = lecturerQuestions.map((question_text) =>
<div className="row">
<hr className=" w-100"/>
<p className="col-8 text-left">{question_text}</p>
<button className="btn badge-pill btn-outline-success col-xl-2 col-lg-2 col-md-2 col-sm-3 col-xs-12"
onClick={() => this.setState({view: question_text})}>View answers</button>
</div>
);
let answerView =
<div>
<div id="Change view">
<button className="btn btn-outline-dark" onClick={()=>this.setState({view: "main"})}>View student feedback</button>
<button className="btn btn-outline-dark" onClick={()=>this.setState({view: "settingQuestions"})}>Set questions for students</button>
</div>
{lecturerQuestionList}
</div>
let studentQuestions = [];
this.state.studentQuestionMap.keys().forEach(
function(key) {
if(!this.state.faq.includes(key))
{studentQuestions.push([key, this.state.studentQuestionMap.get(key)]);}
}, this)
studentQuestions.sort(
function(a, b) {
return b[1].count - a[1].count;
}
)
let studentQuestionList = studentQuestions.map((question) =>
<div key={question[0]} className="row longWord">
<hr className=" w-100"/>
<div className="col-md-10 col-sm-9 col-xs-12 row text-right" key={question[0]}>
<p className="col-8 text-left">{question[0]}</p>: <p className="col-3">{question[1].count}</p>
<p>{"Asked by: " + question[1].users.map(user => {
return user.name;
})}</p>
</div>
<div className = "input-group-append my-4">
<button className="btn btn-outline-warning" onClick={()=>answerStudentQuestion(question[0], "Answered in lecture", this.state.room)}>Answered</button>
<button class="btn btn-outline-warning" onClick={()=>{answerStudentQuestion(question[0], "Answered by email", this.state.room);
this.send_email(question)}}>Answer askers via email</button>
<button className="btn btn-outline-warning" onClick={()=>{answerStudentQuestion(question[0], "Answered by class", this.state.room);
this.setState({setQuestionTextField : question[0]});
this.ask("text")}}>Send question to class</button>
</div>
</div>
);
let mainView;
if(this.state.credentials && this.state.credentials !== ""
&& !this.state.loading && !this.state.errorMessage){
mainView = <div>
<div>
<button onClick={() => this.logout()}>Logout</button>
</div>
<h6 id="logging_header">{"Logged in as: " + this.state.name}</h6>
{/* <p className="DontUnderstandText">Number of students who don't understand: {this.state.questionMap.get("I don't understand")}</p>
<p className="DontUnderstandText">Number of students who don't understand: {this.state.questionMap.get("I don't understand")}</p>
<p className="ExampleText">Number of students who want an example: {this.state.questionMap.get("Could you give an example?")}</p>
<p className="SlowDownText">Number of students who ask for slowing down: {this.state.questionMap.get("Could you slow down?")}</p>
<p className="SpeedUpText">Number of students who ask for speeding up: {this.state.questionMap.get("Could you speed up?")}</p> */}
<div className="container my-3">
<Bar
data={this.state.data}
options={this.state.options}
/>
</div>
<div id="Change view">
<button className="btn btn-outline-dark" onClick={()=>this.setState({view: "settingQuestions"})}>Set questions for students</button>
<button className="btn btn-outline-dark" onClick={()=>this.setState({view: "viewingAnswers"})}>View student answers</button>
</div>
<hr className="mt-5 mb-0"/>
<div className="container-fluid my-5 col-10" style={{display:"block"}}>{studentQuestionList}</div>
<div id="Clear">
<button className="btn btn-outline-dark" style={{margin:'50px'}} onClick={()=>clearAll(this.state.room)}>CLEAR ALL!</button>
</div>
</div>
}
if(this.state.view === "settingQuestions") {
return (
<div>
{setView}
</div>
)
}
else if(this.state.view === "viewingAnswers") {
return (
<div>
{answerView}
</div>
)
}
else if(this.state.view !== "main") {
return(this.render_question(this.state.view));
}
return (
<div>
<h1>{this.state.room}</h1>
{mainView}
{this.state.errorMessage ?
<div>
<p>{this.state.errorMessage}</p>
<a href="/">
<button>Back</button>
</a>
</div>
: undefined
}
{(this.state.credentials === undefined || this.state.credentials === '')?
<div>
<p>You have to login first</p>
<a href="/">
<button>Login</button>
</a>
</div>
: undefined
}
<ClipLoader
// className={override}
sizeUnit={"px"}
size={50}
color={'#0336FF'}
loading={this.state.loading}
/>
</div>
);
}
}
export default Lecturer;
|
import React from 'react';
const VideoBanner = () => {
return (
<React.Fragment>
<section className="banner" >
<div className="video-container">
<video className="featured_video" poster="" autoPlay="autoPlay" playsInline="playsInline" muted="muted" loop="loop">
<source src="./images/videos/4 shots.mp4" type="video/mp4" />
</video>
</div>
<div className="banner-text">
<h1>New Perspective In beautiful mountains.</h1>
</div>
<div className="search-bar">
<input type="text" placeholder="Discover Your Adventure..." />
<button><img src="images/assets/right-arrow.svg" alt="" /></button>
</div>
</section>
</React.Fragment>
);
}
export default VideoBanner; |
$(function () {
'use strict';
$('.tree-radio').on('change', function(){
if (this.checked) {
var selector = '#' + $(this).closest('.modal').attr('id');
console.log(selector);
var trigger = $('[href="' + selector +'"]');
var label = $(this).data('label');
if (label) {
trigger.text(label);
} else {
var stack = [];
var parent = $(this).closest('.tree--item--label');
var text = parent.find('.node-label').text();
stack.push(text);
parent = parent.parents('li').first().parents('li').first();
while (parent.length) {
text = parent.find('.node-label').first().text();
stack.push(text);
parent = parent.parents('li').first();
}
trigger.html(stack.reverse().join(' » '));
}
}
});
$('.remove-tree-input').on('click', function (e) {
e.preventDefault();
$(this).parent().find('.tree-open').text($(this).data('label'));
$($(this).data('target')).find('.tree-radio').removeAttr('checked');
});
}); |
import React, {Component} from 'react';
import MoreInfo from './MoreInfo';
export default function Map(props) {
return ( props.displayAllCharacters.map( (e,i) => {
return (
<div className="list-parent" key = {i} >
<div className="names-list">
<div className="names-list-separate"> Name: {e.name} <button onClick={() => props.deleteItem(i)} className="delete">X</button>
<div className="more-info">
< MoreInfo characterId={e.id} />
</div>
</div>
</div>
</div>
)
})
)
} |
import _ from 'lodash';
import { utils } from '../../../common/utils';
export const ROLE_ALL = '*';
/**
* Auth middleware
* @param {array} roles
* @param {string|function} failedCb
*/
export function auth(roles, failedCb) {
const reject = (req, res, next) => {
if (utils.isFunction(failedCb)) return failedCb(req, res);
const err = new Error('Access denied.');
return next(err);
};
return (req, res, next) => {
if (req.isAuthenticated()) {
if (!roles || roles === ROLE_ALL) return next();
roles = utils.isArray(roles) ? roles : [roles];
const user = req.user || {};
// fix role
if (_.includes(roles, user.role)) return next();
}
return reject(req, res);
};
}
|
/**
* LINKURIOUS CONFIDENTIAL
* Copyright Linkurious SAS 2012 - 2018
*
* - Created on 2014-11-25.
*/
'use strict';
// internal libs
const crypto = require('crypto');
const stream = require('stream');
// external libs
const _ = require('lodash');
const clarinet = require('clarinet');
const Promise = require('bluebird');
const _has = require('lodash/has');
const _uniq = require('lodash/uniq');
const _cloneDeep = require('lodash/cloneDeep');
const randomstring = require('randomstring');
const Valcheck = require('valcheck');
const CronParser = require('cron-parser');
// our libs
const LiteralsParser = require('../../lib/LiteralsParser');
const SemVer = require('../../lib/SemVer');
const Semaphore = require('../../lib/Semaphore');
const JSDiff = require('../../lib/JSDiff');
// services
const Errors = require('../services/errors');
const ALPHABET_LK_CUSTOMER_IDS = '0123456789ABCDEFGHJKMNPRSTUVWXYZ';
class Valcheck2 extends Valcheck {
constructor(errorHandler, bugHandler) {
// @ts-ignore (until utils get type checked)
super(errorHandler, bugHandler);
}
/**
* Check if the value is a valid CRON expression.
*
* @param {string} key
* @param {string} value
*
* @returns {*} error, if any
*/
cronExpression(key, value) {
let error;
if ((error = this.string(key, value, true, false, 1, 50))) { return error; }
try {
CronParser.parseExpression(value);
} catch(e) {
return this._error(key, 'must be a valid cron');
}
}
}
class MergerWriteStream extends stream.Writable {
constructor() {
super({objectMode: true});
/** @type {Array} */
this.accumulator = [];
}
_write(object, enc, next) {
this.accumulator.push(object);
next();
}
}
class ServerUtils {
/**
* @param {object} [logger]
* @param {function} logger.warn
* @param {function} logger.error
*/
constructor(logger) {
if (!logger) {
logger = {
warn: s => { console.error('warn: ' + s); },
error: s => { console.error('error: ' + s); }
};
}
this._logger = logger;
// @ts-ignore (until utils get type checked)
/** @type {LiteralsParser} */
this._literalsParser = new LiteralsParser(['"', '\''], '\\');
/** @type {Valcheck2} */
this._check = new Valcheck2(validationMessage => {
throw Errors.business('invalid_parameter', validationMessage);
}, bugMessage => {
throw Errors.technical('bug', bugMessage);
});
}
/**
* @type {Valcheck2}
*/
get check() {
return this._check;
}
/**
* @returns {{warn: function, error: function}}
*/
get logger() {
return this._logger;
}
/**
* Logs a warning if the number of milliseconds elapsed since `t0` is higher than `threshold`.
*
* @param {number} t0
* @param {number} threshold
* @param {string|function():string} getMessage
* @param {CustomLogger} [logger]
*/
logSlow(t0, threshold, getMessage, logger) {
const duration = Date.now() - t0;
if (duration < threshold) { return; }
const message = '[Slow: ' + duration + 'ms] ' + (
typeof getMessage === 'function' ? getMessage() : getMessage
);
if (logger) {
logger.warn(message);
} else {
this.logger.warn(message);
}
}
/**
* Deduplicate objects by the value of a nested property.
*
* @param {object[]} array
* @param {string} key
* @returns {object[]}
*/
uniqBy(array, key) {
const map = new Map();
for (let i = 0, l = array.length; i < l; ++i) {
map.set(array[i][key], array[i]);
}
return Array.from(map.values());
}
/**
* @param {object} proto an object prototype
* @param {boolean} [skipPrivate=false] don't include fields starting with `'_'`.
* @param {boolean} [skipObject=false] don't include fields from `Object` class.
* @returns {*}
*/
getFields(proto, skipPrivate, skipObject) {
let fields = [];
let p = proto;
while (p) {
if (skipObject && p.constructor.name === 'Object') { break; }
fields = fields.concat(Object.getOwnPropertyNames(p));
// @ts-ignore (until utils get type checked)
p = p.__proto__;
}
return _uniq(fields).filter(f => {
return f !== 'constructor' && (!skipPrivate || f[0] !== '_');
});
}
/**
* @param {*} o
* @returns {boolean}
*/
noValue(o) {
return o === undefined || o === null;
}
/**
* @param {*} o
* @returns {boolean}
*/
hasValue(o) {
return o !== undefined && o !== null;
}
/**
* Returns a catch-handler for a promise.
* If the caught error key is `ignoredErrorKey`, resolve with `returnValue`.
* Reject with the error otherwise.
*
* @param {string} ignoredErrorKey Error-key to ignore.
* @param {*} returnValue Return value if the caught error
* @returns {function(LkError):Promise<LkError|*>}
*/
catchKey(ignoredErrorKey, returnValue) {
return e => {
if (e && e.key === ignoredErrorKey) {
return Promise.resolve(returnValue);
} else {
return Promise.reject(e);
}
};
}
/**
* Split exactly once (on the first occurrence of the separator).
*
* @param {string} str
* @param {string} separator
* @returns {string[]} an array with at most two items
*/
splitOnce(str, separator) {
const i = str.indexOf(separator);
return i === -1 ? [str] : [str.slice(0, i), str.slice(i + separator.length)];
}
/**
* Is non-empty string
*
* @param {*} o
* @returns {boolean} true if non empty string
*/
isNEString(o) {
return (typeof o === 'string' || o instanceof String) && o.length > 0;
}
isPosInt(value) {
return !this.isNaN(value) && (value >= 0) && (Math.ceil(value) == value);
}
/**
* @param {*} value
* @param {string} valueKey
* @param {boolean} [allowUndefined]
* @param {number} [defaultValue] returned if value is undefined and allowUndefined is true
* @returns {number} return parsed value if a positive integer, throw an error otherwise
*
*/
tryParsePosInt(value, valueKey, allowUndefined, defaultValue) {
value = this.parseInt(value);
if (allowUndefined && value === undefined) {
return defaultValue;
}
this.check.posInt(valueKey, value);
return value;
}
/**
* @param {*} value
* @param {string} valueKey
* @param {boolean} [allowUndefined]
* @param {number} [defaultValue] returned if value is undefined and allowUndefined is true
* @returns {number} return parsed value if a number, throw an error otherwise
*/
tryParseNumber(value, valueKey, allowUndefined, defaultValue) {
value = this.parseFloat(value);
if (allowUndefined && value === undefined) {
return defaultValue;
}
this.check.number(valueKey, value);
return value;
}
/**
* @param {*} values
* @param {string} valueKey
* @returns {number[]} return parsed values if all are positive integers, throw an error otherwise
*/
tryParsePosInts(values, valueKey) {
const errorKey = 'invalid_parameter',
errorMessage = '"' + valueKey + '" must be an array of positive integers.';
const self = this;
if (!Array.isArray(values)) {
throw Errors.business(errorKey, errorMessage);
}
return values.map(value => {
value = self.parseInt(value);
if (isNaN(value)) {
throw Errors.business(errorKey, errorMessage);
}
if (value < 0 || !Number.isInteger(value)) {
throw Errors.business(errorKey, errorMessage);
}
return value;
});
}
/**
* Checks whether `v` is a non-null object.
*
* @param {*} v
* @returns {boolean}
*/
isObject(v) {
return v !== null && typeof v === 'object';
}
/**
* Check whether `n` is a boolean.
*
* @param {*} n
* @returns {boolean}
*/
isBoolean(n) {
return !!n === n;
}
/**
* Replacement of isNaN, because the original has the following problems:
* * return false when input is ""
* * return false when input is null
* * return false when input is a string comprised of whitespace only
*
* @param {*} input
* @returns {boolean} true if not a number
*/
isNaN(input) {
return isNaN(parseInt(input, 10));
}
/**
* Replace any entry in the array in input with its string.
*
* @param {any} a
* @returns {Array<string> | null | undefined}
*/
toStringArray(a) {
if (a === null) { return null; }
if (a === undefined) { return undefined; }
if (!Array.isArray(a)) { return undefined; }
return a.map(a => a + '');
}
/**
* Replacement for parseInt, because the original has the following problems:
* * infers base 8 when input starts with '0'
* * infers base 16 when input starts with '0x'
*
* @param {*} input
* @returns {number}
*/
parseInt(input) {
if (input === null || input === undefined) { return input; }
return parseInt(input, 10);
}
/**
* @param {*} input
* @returns {number|undefined|null}
*/
parseFloat(input) {
if (input === null || input === undefined) { return input; }
return parseFloat(input);
}
/**
* Parse any value an make the best boolean guess we can
*
* @param {*} b
* @returns {boolean|null|undefined}
*/
parseBoolean(b) {
if (b === null || b === undefined) { return b; }
return (b === true || b === 'true' || b === 'yes' || b === 'y' || b === '1' || b === 1);
}
localComparator(a, b) {
return a.localeCompare(b);
}
/**
* Compare two SemVer strings
*
* @param {string} x a string in the format "a.b.c"
* @param {string} y a string in the format "d.e.f"
* @returns {number} similar to (x-y): <0 if x<y, >0 if x>y, 0 if x=y
*/
compareSemVer(x, y) {
return SemVer.compare(x, y);
}
/**
* Generate a map from a string array.
*
* @param {Array<string | number>} array
* @param {any} [value=true]
* @returns {object}
*/
arrayToMap(array, value) {
if (value === undefined) { value = true; }
const map = {};
if (!array || !array.length) { return map; }
array.forEach(item => { map[item] = value; });
return map;
}
/**
* Creates a map with `array` items indexed by the key extracted by `keyReader`.
*
* @param {*[]} array
* @param {function(*):*} keyReader
* @returns {Map}
*/
indexBy(array, keyReader) {
const map = new Map();
array.forEach(item => map.set(keyReader(item), item));
return map;
}
extractHostPort(url) {
if (!url) { return undefined; }
const re = new RegExp('^([a-zA-Z+]+)://([^:/]+)(:\\d+)?(?:/|$)');
const groups = re.exec(url);
if (!groups) { return undefined; }
const scheme = groups[1].toLowerCase();
const host = groups[2];
let port;
if (groups.length === 4 && groups[3] !== undefined) {
port = groups[3].substr(1);
} else {
if (scheme === 'http' || scheme === 'ws') {
port = '80';
} else if (scheme === 'https' || scheme === 'wss') {
port = '443';
} else if (scheme === 'bolt' || scheme === 'bolt+routing') {
port = '7687';
} // else 'undefined'
}
return {scheme: scheme, host: host, port: port};
}
/**
* @param {Object} root an object (possibly null or undefined)
* @param {String[]|String} propertyChain a chain of properties to resolve on the root object
* @param {*} [defaultValue] a value to return if a null or undefined value is found along the chain
* @returns {*}
*/
safeGet(root, propertyChain, defaultValue) {
let value = root;
if (Array.isArray(propertyChain)) {
// no-op
} else if (typeof propertyChain === 'string') {
propertyChain = propertyChain.split('.');
} else {
throw new Error('bad "propertyChain" argument type: ' + (typeof propertyChain));
}
for (let i = 0, l = propertyChain.length, property; i < l; ++i) {
if (value === null || value === undefined) {
return defaultValue;
}
property = propertyChain[i];
const type = typeof property;
if (type === 'number' || type === 'string') {
value = value[property];
} else {
throw new Error('safeGet: property key of type "' + type + '" is not legal');
}
}
return (value === null || value === undefined) ? defaultValue : value;
}
/**
* Retry a promise multiple times if it fails.
*
* @param {String} actionName name of the action to try/retry
* @param {Function} action a function returning a promise
* @param {object} options retry options
* @param {function} [options.decide] if defined, will be called with the error and must return
* true to continue retrying or false to cancel retrying.
* @param {number} options.delay a number of milliseconds to wait between retries.
* @param {number} [options.retries=5] the maximum number of retries before actually failing.
* @param {boolean} [options.fullErrors=true] whether to include full errors or just messages
* @param {function} [options.giveUp] a boolean returning function. After an error, is this
* is defined, it is called with the error as first argument.
* If the result is true, the promise is rejected.
* @param {number} [doneRetries]
* @returns {Bluebird<any>} a promise
*/
retryPromise(actionName, action, options, doneRetries) {
// validate parameters
if (doneRetries === undefined) { doneRetries = 0; }
options = _.defaults(options, {});
if (options.retries === undefined) { options.retries = 5; }
if (options.fullErrors === undefined) { options.fullErrors = true; }
if (options.decide !== undefined) {
this.check.function('options.decide', options.decide);
}
if (!this.isPosInt(options.delay)) {
return Promise.reject(new Error('"delay" must be an integer >= 0'));
}
if (typeof(action) !== 'function') {
return Promise.reject(new Error('"action" must be a function'));
}
// @ts-ignore (until utils get type checked)
const promise = action();
if (!(promise instanceof Promise)) {
return Promise.reject(new Error('"action" must return a promise'));
}
// give-up method
const giveUp = (error, message) => {
// @ts-ignore (until utils get type checked)
this.logger.error(
'giving up "' + actionName + '" ' +
'[' + doneRetries + '/' + options.retries + ']: ' +
message
);
return Promise.reject(error);
};
// check if the actions
return promise.catch(error => {
// build a more user-friendly error message whenever possible
const message = error && error.message ? error.message : error;
const giveUpNow = options.giveUp && options.giveUp(error) === true;
++doneRetries;
// should retry ?
if ((doneRetries < options.retries || options.retries === null) && !giveUpNow) {
// cancel retry if option.retry returns "false"
if (options.decide && !options.decide(error)) {
return giveUp(error, message);
}
// @ts-ignore (until utils get type checked)
this.logger.warn('retrying "' + actionName + '" [' + doneRetries +
(options.retries ? '/' + options.retries : '') + ']' +
(options.fullErrors ? ': ' + message : '')
);
return Promise.delay(options.delay).then(() => {
// cancel retry if option.retry returns "false"
if (options.decide && !options.decide(error)) {
return giveUp(error, message);
}
return this.retryPromise(actionName, action, options, doneRetries);
});
} else {
return giveUp(error, message);
}
}).catch(Promise.CancellationError, error => {
return giveUp(error, 'cancelled');
});
}
/**
* Slice an array and call 'handler' with each slice.
*
* @param {*[]} array an array to break into smaller slices for processing by 'handler'
* @param {number} sliceSize an maximum slice size
* @param {function} handler a function taking an array as argument (possibly returning a promise)
* @param {number} [concurrency] a value indicating how many slices can run concurrently
* @returns {Bluebird<any>} returned when 'handler' has been called on each array slice and resolved
*/
sliceMap(array, sliceSize, handler, concurrency) {
if (array.length === 0) { return Promise.resolve([]); }
if (sliceSize <= 0) {
// @ts-ignore (until utils get type checked) (the error is due to not going through the Error service)
return Errors.business('invalid_parameter', 'sliceSize must be > 0', true);
}
const slices = [];
for (let i = 0; i < array.length; i += sliceSize) {
slices.push(array.slice(
i,
Math.min(i + sliceSize, array.length)
));
}
const options = concurrency === undefined ? undefined : {concurrency};
// @ts-ignore (until utils get type checked)
return Promise.resolve(slices).map(handler, options);
}
neverReject(promise) {
const self = this;
return promise.catch(error => {
// @ts-ignore (until utils get type checked)
self.logger.error('Ignoring error:', error.message ? error.message : 'Unknown error', error);
return Promise.resolve();
});
}
/**
* Clone an object in depth
*
* @param {any} o any object
* @returns {any} cloned object
*/
clone(o) {
return _cloneDeep(o);
}
/**
* This method compares two JS objects to determine if they have the same structure.
*
* Two object have the same structure if the intersection of their key list corresponds to the
* list of the key list of reference.
*
* Two Arrays have the same structure if each element have the same structure and that structure
* corresponds to the structure of the elements inside the array of reference
*
* @param {Object} reference - Object to be compared to (reference)
* @param {Object} compared - Object being compared
* @param {Object} [optionalPaths] a map of optional paths (dot separated)
* @param {boolean} [failEarly=false] whether to fail on first detected difference
* @param {string[]} [stack] property stack (for recursive calls)
* @returns {string[]} - structural differences described as strings
*/
compareStructures(reference, compared, optionalPaths, failEarly, stack) {
const self = this;
if (!optionalPaths) { optionalPaths = {}; }
if (!stack) { stack = ['root']; }
let diff = [];
// reference does not exist: adding new keys is OK.
if (reference === undefined || reference === null) {
return diff;
}
// type match ?
if (typeof reference !== typeof compared) {
diff.push(
'types don\'t match: ' +
'expected "' + (typeof reference) + '", ' +
'found "' + (typeof compared) + '" (' + stack.join('.') + ')'
);
return diff;
}
// array: compare each element with first element in reference
if (reference instanceof Array && compared instanceof Array) {
/**
* first we check that the type of all the element of the Array are consistent with the
* type of the first element of the default configuration (We consider the default
* configuration is consistent.
*/
if (reference.length > 0) {
const ref = reference[0];
for (let i = 0, l = compared.length; i < l; ++i) {
const nextStack = stack.concat('[' + i + ']');
diff = diff.concat(self.compareStructures(
ref, compared[i], optionalPaths, failEarly, nextStack
));
if (failEarly && diff.length > 0) {
return diff;
}
}
if (failEarly && diff.length > 0) { return diff; }
}
} else if (reference instanceof Object && compared instanceof Object) { // object, compare keys
Object.keys(reference).sort().forEach(key => {
const nextStack = stack.concat(key);
let path;
if (!_has(compared, key)) {
path = nextStack.join('.');
if (optionalPaths[path] === true) {
// no-op
} else {
diff.push('expected key not found (' + nextStack.join('.') + ')');
}
} else {
diff = diff.concat(self.compareStructures(
reference[key],
compared[key],
optionalPaths,
failEarly,
nextStack
));
}
});
if (failEarly && diff.length > 0) { return diff; }
}
return diff;
}
/**
* Compute the difference between objects
*
* @param {*} reference
* @param {*} compared
* @param {object} [ignoredPaths]
* return {string[]} human readable differences
*/
objectDiff(reference, compared, ignoredPaths) {
return JSDiff.compareValues(reference, compared, ignoredPaths);
}
/**
*
* @param {number} milliseconds
* @param {number} [precision=null] number of
* @returns {string}
*/
humanDuration(milliseconds, precision) {
const units = [
{name: 'day', millis: 24 * 60 * 60 * 1000},
{name: 'hour', millis: 60 * 60 * 1000},
{name: 'minute', millis: 60 * 1000},
{name: 'second', millis: 1000}
];
let chunks = [];
for (let i = 0; i < units.length; ++i) {
const unit = units[i];
const unitCount = Math.floor(milliseconds / unit.millis);
milliseconds = milliseconds % unit.millis;
if (unitCount > 0 || (chunks.length > 0 && precision !== undefined)) {
chunks.push({
count: unitCount,
unit: (unit.name + (unitCount === 1 ? '' : 's'))
});
}
}
if (precision !== undefined) {
chunks = chunks.slice(0, precision);
}
if (chunks.length === 0) {
chunks.push({count: 0, unit: 'seconds'});
}
return chunks.reduce((string, chunk, index) => {
if (chunk.count === 0 && chunks.length > 1) { return string; }
return string +
(index === 0 ? '' : index === chunks.length - 1 ? ' and ' : ', ') +
chunk.count + ' ' + chunk.unit;
}, '');
}
/**
* @param {number} size - size of the semaphore
* @returns {Semaphore} with 'acquire' and 'release' methods
*/
semaphore(size) {
return new Semaphore(size);
}
/**
* Extract a detailed JSON parse error
*
* @param {string} json
* @returns {{snippet: string, message: string, line: number, column: number}}
*/
getJSONParseError(json) {
const parser = clarinet.parser();
let firstError = undefined;
// generate a detailed error using the parser's state
function makeError(e) {
let currentNL = 0,
nextNL = json.indexOf('\n'),
line = 1;
while (line < parser.line) {
currentNL = nextNL;
nextNL = json.indexOf('\n', currentNL + 1);
++line;
}
return {
snippet: json.substr(currentNL + 1, nextNL - currentNL - 1),
message: (e.message || '').split('\n', 1)[0],
line: parser.line,
column: parser.column
};
}
// trigger the parse error
parser.onerror = error => {
firstError = makeError(error);
parser.close();
};
try {
parser.write(json).close();
} catch(e) {
if (firstError === undefined) {
return makeError(e);
} else {
return firstError;
}
}
return firstError;
}
/**
* The input is a possibly broken JSON string.
* This function is able to fix and parse a broken JSON string by discarding characters at the
* end of the string and closing the top-level data structure (be it an array or an object).
* This allows to recover all non-broken first-level children of the root object.
*
* @param {string} originalJson
* @returns {{parsed: any, error?: Error, discarded: string}}
*/
tryParseJson(originalJson) {
if (typeof originalJson !== 'string') {
return {parsed: undefined, error: undefined, discarded: ''};
}
let originalError = null;
let discardedChars = 0;
originalJson = originalJson.trim();
let json = originalJson;
let lastChar = '';
if (json[0] === '[') { lastChar = ']'; }
if (json[0] === '{') { lastChar = '}'; }
while (json.length > 0) {
try {
return {
parsed: JSON.parse(json),
error: originalError,
discarded: originalJson.substr(-discardedChars)
};
} catch(e) {
if (!originalError) {
// if this is the first error
json = json + lastChar;
originalError = e;
} else {
// if there was already an error
discardedChars++;
json = json.slice(0, -(1 + lastChar.length)) + lastChar;
}
}
}
return {
parsed: undefined,
error: originalError,
discarded: originalJson
};
}
stripLiterals(s) {
return this._literalsParser.removeLiterals(s);
}
/**
* @param {string} sourceKey
* @param {string} [name="sourceKey"]
* @param {boolean} [optional=false] Whether to allow undefined values
*/
checkSourceKey(sourceKey, name, optional) {
if (sourceKey === undefined && optional) { return; }
this.check.string(name ? name : 'sourceKey', sourceKey, true, true, 8, 8);
}
/**
* Generate 8 random HEX Bytes.
* Uses Math.random, so don't use this for cryptography.
*
* @returns {string}
*/
randomHex8() {
let s = Math.random().toString(16).substr(2, 8);
while (s.length < 8) { s = '0' + s; }
return s;
}
/**
* @param {number} bytes
* @returns {string} a hex string
*/
randomHex(bytes) {
return crypto.randomBytes(bytes).toString('hex');
}
/**
* Stringify in a stable and/or pretty way.
*
* @param {any} o
* @param {boolean} pretty Whether to indent the JSON object
* @param {boolean} [stable=true] Whether to sort the property keys
*/
toJSON(o, pretty, stable) {
return JSON.stringify(
o,
stable === false || !o || typeof o !== 'object' ? null : Object.keys(o).sort(),
pretty ? 2 : null
);
}
/**
* Generate an hash for a match.
*
* @param {string[]} nodes Ids
* @param {string[]} edges Ids
* @param {number} alertId
*
* @returns {string}
*/
hashMatch(nodes, edges, alertId) {
const nodesIdSet = new Set();
const edgesIdSet = new Set();
for (const nodeId of nodes) {
nodesIdSet.add(nodeId);
}
for (const edgeId of edges) {
edgesIdSet.add(edgeId);
}
const nodesId = Array.from(nodesIdSet);
const edgesId = Array.from(edgesIdSet);
nodesId.sort();
edgesId.sort();
return crypto.createHash('md5').update(alertId + JSON.stringify(nodesId) +
JSON.stringify(edgesId)).digest('hex');
}
/**
* Similar to source.pipe(target), but it pass along with the 'data' signals
* also the 'error' signals.
*
* @param {any} _streams
* @returns {any} a readable stream
*/
safePipe(_streams) {
if (arguments.length <= 1) {
throw Errors.technical('bug', 'streams must be > 1');
}
let readable = arguments[0];
const transforms = Array.prototype.slice.call(arguments, 1);
while (transforms.length > 0) {
const newReadable = transforms.shift();
readable.on('error', e => {
newReadable.emit('error', e);
});
readable.pipe(newReadable);
// hack to abort stream originated from request.js
if (typeof readable.abort === 'function') {
newReadable.abort = readable.abort.bind(readable);
}
readable = newReadable;
}
return readable;
}
/**
* @param {Readable} readableStream
* @param {number} timeout
* @returns {Bluebird<{timeout: boolean, result: any[]}>}
*/
mergeReadable(readableStream, timeout) {
return new Promise((resolve, reject) => {
let hasEnded = false;
let hasTimeout = false;
const merger = new MergerWriteStream();
// @ts-ignore (until utils get type checked)
readableStream.pipe(merger);
const done = () => {
if (hasEnded) { return; }
hasEnded = true;
clearTimeout(timer);
resolve({timeout: hasTimeout, result: merger.accumulator});
};
const timer = setTimeout(() => {
if (hasEnded) { return; }
hasTimeout = true;
done();
// @ts-ignore (until utils get type checked)
if (typeof readableStream.unpipe === 'function') {
// @ts-ignore (until utils get type checked)
readableStream.unpipe(merger);
}
// @ts-ignore (until utils get type checked)
if (typeof readableStream.abort === 'function') {
// @ts-ignore (until utils get type checked)
readableStream.abort.apply(merger);
}
}, timeout);
readableStream.on('error', reject);
readableStream.on('end', done);
});
}
/**
* Check that `customerId` has a length of 10 and that the checksum values match.
*
* @param {string} key
* @param {string} customerId
* @throws {LkError} if value is not a valid customer Id
*/
validateCustomerId(key, customerId) {
const prefix = customerId.slice(0, 2);
const firstPart = customerId.slice(2, 6);
const secondPart = customerId.slice(7);
let sum = 8; // 4312 modulo 16
for (const c of firstPart + secondPart) {
sum += Number.parseInt(c, 36);
}
const checksum = Number(sum % 16).toString(16).toUpperCase();
if (customerId.length !== 10 || customerId.slice(6, 7) !== checksum ||
prefix !== 'LK') {
throw Errors.business('invalid_parameter',
`"${key}": ${customerId} must be a valid customer id`);
}
}
/**
* Generate a valid unique customer id composed of:
* - 'LK' prefix
* - 4 random characters in the alphabet
* - 1 character of checksum equal to the sum of all the others characters + 8 modulo 16
* - 3 random characters in the alphabet
*
* @returns {string}
*/
generateUniqueCustomerId() {
const firstPart = randomstring.generate({charset: ALPHABET_LK_CUSTOMER_IDS, length: 4});
const secondPart = randomstring.generate({charset: ALPHABET_LK_CUSTOMER_IDS, length: 3});
let sum = 8; // 4312 modulo 16
for (const c of firstPart + secondPart) {
sum += Number.parseInt(c, 36);
}
// the checksum is always modulo 16 to avoid complicated tricks due to missing characters in the alphabet
const checksum = Number(sum % 16).toString(16).toUpperCase();
return 'LK' + firstPart + checksum + secondPart;
}
/**
* Generate a valid email used in authentication providers that may miss one.
*
* @param {string} customerId
* @returns {string}
*/
generateRandomEmail(customerId) {
return this.randomHex(4) + '-' + customerId + '@linkurio.us';
}
/**
* Compute the next time to schedule based on a cron and the last run.
*
* @param {string} cron
* @param {Date} [lastRun]
* @returns {Date}
*/
nextTimeToSchedule(cron, lastRun) {
/**
* By default, if we ask to schedule every minute, the CronParser library will generate
* as 'nextTimeToSchedule' the time hh.mm.00.000. But if we call it while the current
* time is 'hh.mm.00.xxx' it will produce 'hh.mm.00.xxx' instead of 'hh.(mm+1).00.xxx'.
*
* To fix this we ask CronParser to give us the 'nextTimeToSchedule' starting from
* Date.now() + 1 second.
*/
if (lastRun === undefined || lastRun === null) {
lastRun = new Date(Date.now() + 1000);
}
return CronParser.parseExpression(
cron, {currentDate: lastRun}
).next();
}
/**
* Remove an eventual last '/' in a url if present.
*
* @param {string} url
* @returns {string}
*/
normalizeUrl(url) {
return url.replace(/\/$/, '');
}
/**
* @param {IncomingMessage} req
* @returns {boolean}
*/
isRequestHTTPS(req) {
// getPeerCertificate is a function and it's not defined if req.connection is not a TLSSocket
// @ts-ignore (req.connection is just a 'Socket' so it doesn't have a getPeerCertificate)
return req.connection.getPeerCertificate !== undefined;
}
/**
* Throw an LkError.
*
* The signature says that it returns `any` so that
* type checking doesn't complain when we return `Utils.NOT_IMPLEMENTED()`
*
* @returns {any}
*/
NOT_IMPLEMENTED() {
throw Errors.business('not_implemented', 'Not implemented.');
}
}
module.exports = ServerUtils;
|
import { faUserCircle } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import React from 'react';
import { Link } from 'react-router-dom';
export default function Avatar(props) {
if (props.isLoading) {
return null;
}
return (
<Link to={props.isLoggedIn ? '/user/details' : '/user/login'} className="AppHeader__User">
{props.isLoggedIn ? <img alt="" src={props.user.photoURL} /> : <FontAwesomeIcon icon={faUserCircle} />}
</Link>
);
} |
import React, { Component } from 'react'
import axios from 'axios'
export class TestingAxios extends Component {
constructor(props) {
super(props)
this.state = {
posts: [],
title: '',
userID: '',
body: ''
}
this.getTitles();
}
// componentDidMount(){
// axios.get('http://jsonplaceholder.typicode.com/posts').then(res => {
// this.setState({
// posts: res.data
// })
// })
// }
changeHandler = (e) =>{
this.setState({
[e.target.name]: e.target.value
})
}
submitHandler = (e) => {
e.preventDefault()
// console.log(this.state);
axios.post('http://jsonplaceholder.typicode.com/posts',this.state).then(res => console.log(res.data))
this.getTitles();
}
getTitles = () =>{
let data = axios.get('http://jsonplaceholder.typicode.com/posts').then(res => {
this.setState({
posts:res.data
})
})
}
render() {
const {userID, title, body } = this.state
return (
<div>
<form onSubmit = {this.submitHandler}>
<label>input ID</label>
<input type = "text" name = "userID" value = {userID} onChange = {this.changeHandler}></input><br/>
<label>input Title</label>
<input type = "text" name = "title" value = {title} onChange = {this.changeHandler}></input><br/>
<label>input Body</label>
<input type = "text" name = "body" value = {body} onChange = {this.changeHandler}></input><br/>
<button type = "submit">Click Me</button>
</form>
<h2>{userID}</h2>
<h2>{title}</h2>
<h2>{body}</h2>
{this.state.posts.map(post => <div key = {post.id}>{post.title}</div>)}
</div>
)
}
}
export default TestingAxios
|
//5.1
/* const ages = [22, 14, 24, 55, 65, 21, 12, 13, 90];
const agesFiltered = ages.filter(function(age){
return age > 18
})
console.log(agesFiltered) */
//5.2
const ages = [22, 14, 24, 55, 65, 21, 12, 13, 90];
const agesFilteredPair = ages.filter(function(age){
return age%2===0
})
console.log(agesFilteredPair)
//5.3
/* const streamers = [
{name: 'Rubius', age: 32, gameMorePlayed: 'Minecraft'},
{name: 'Ibai', age: 25, gameMorePlayed: 'League of Legends'},
{name: 'Reven', age: 43, gameMorePlayed: 'League of Legends'},
{name: 'AuronPlay', age: 33, gameMorePlayed: 'Among Us'}
];
const streamersFiltered= streamers.filter(function(game){
return game.gameMorePlayed==='League of Legends'
})
console.log(streamersFiltered) */
//5.4
const streamers = [
{name: 'Rubius', age: 32, gameMorePlayed: 'Minecraft'},
{name: 'Ibai', age: 25, gameMorePlayed: 'League of Legends'},
{name: 'Reven', age: 43, gameMorePlayed: 'League of Legends'},
{name: 'AuronPlay', age: 33, gameMorePlayed: 'Among Us'}
];
const streamersFilteredByU= streamers.filter(function(name){
return name.name.includes("u")
})
console.log(streamersFilteredByU)
//5.5
let streamersFilteredByLolAge = streamers.filter((element) => {
if (element.gameMorePlayed.includes('Legends')) {
if (element.age>35) {
console.log(element.gameMorePlayed.toUpperCase());
return element.gameMorePlayed.toUpperCase();
}
}
});
console.log(streamersFilteredByLolAge);
//5.6
const streamers = [
{name: 'Rubius', age: 32, gameMorePlayed: 'Minecraft'},
{name: 'Ibai', age: 25, gameMorePlayed: 'League of Legends'},
{name: 'Reven', age: 43, gameMorePlayed: 'League of Legends'},
{name: 'AuronPlay', age: 33, gameMorePlayed: 'Among Us'}
];
const stream = document.querySelector(`input[data-function="toFilterStreamers"]`)
function changes() {
let letterMatch = streamers.filter(word => word.name.includes(`${stream.value}`));
letterMatch.forEach(streamer => console.log(streamer))
}
stream.addEventListener('change', changes)
|
import { Container, Typography } from "@material-ui/core";
import Hero from "../../Component/Reuseable/Hero";
const Location = () => {
return (
<>
<Container>
<Hero
title="Location"
p1content="IQ is a multinational group of companies employing more than 40 staff in 5 countries. We currently have product sales, support, and development staff in Australia, New Zealand, Canada, the UK and USA."
p2content="Please contact us to see for yourself why customers across the globe trust printIQ to run their business, increase their profits, and reduce their costs. With printIQ you get far more than just an MIS."
p3content="Why not arrange a demo for an upcoming show, meet some of the team, and see the future of print in action?"
/>
<Typography variant="body1">Hello World</Typography>
</Container>
</>
);
};
export default Location;
|
var changeImg, nextImg, prevImg;
changeImg = function(lnk) {
var project, sourceImg, sourceImgKey, targetImg;
project = $(lnk).parent().parent().parent().parent().parent().attr("id");
targetImg = $("#" + project + " .project_image img");
sourceImg = $(lnk).attr("href");
sourceImgKey = lnk.innerHTML;
targetImg.attr("src", sourceImg);
targetImg.attr("rel", sourceImgKey);
$("#" + project + " .project_image").height = "auto";
return false;
};
prevImg = function(lnk) {
var currentImg, key, pages, pagingList, project, sourceImg;
project = $(lnk).parent().parent().parent().attr("id");
pagingList = $("#" + project + " div.project_image_paging ul.paging_list");
currentImg = parseInt($("#" + project + " .project_image img").attr("rel"));
pages = pagingList.children();
if (currentImg !== "1") {
key = currentImg - 1;
} else {
key = pages.length;
}
$("#" + project + " li a").css("color", "#000000");
$("#" + project + " li.paging_list_item_" + key + " a").css("color", "#eeeeee");
sourceImg = $("#" + project + " li.paging_list_item_" + key + " a").attr("href");
$("#" + project + " .project_image img").attr("src", sourceImg);
$("#" + project + " .project_image img").attr("rel", key);
return false;
};
nextImg = function(lnk) {
var currentImg, key, pages, pagingList, project, sourceImg;
if ($(lnk).parent().attr("class") === "project_image") {
project = $(lnk).parent().parent().attr("id");
} else {
project = $(lnk).parent().parent().parent().attr("id");
}
pagingList = $("#" + project + " div.project_image_paging ul.paging_list");
currentImg = parseInt($("#" + project + " .project_image img").attr("rel"));
pages = pagingList.children();
if (currentImg !== pages.length) {
key = currentImg + 1;
} else {
key = 1;
}
$("#" + project + " li a").css("color", "#000000");
$("#" + project + " li.paging_list_item_" + key + " a").css("color", "#eeeeee");
sourceImg = $("#" + project + " li.paging_list_item_" + key + " a").attr("href");
$("#" + project + " .project_image img").attr("src", sourceImg);
$("#" + project + " .project_image img").attr("rel", key);
return false;
};
$(document).ready(function() {
$("div#sections > div").hide();
$("div#sections > a").click(function() {
$(this).next("div").slideToggle("fast").siblings("div:visible").slideUp("fast");
return $("div#Projects > div").hide();
});
$("div#Projects > div").hide();
$("div#Projects > a").click(function() {
return $(this).next("div").slideToggle("fast").siblings("div:visible").slideUp("fast");
});
$("div.project_element div.project_image_paging ul.paging_list li a").click(function() {
$("div.project_element div.project_image_paging ul.paging_list li a").css("color", "#000000");
$(this).css("color", "#eeeeee");
return changeImg(this);
});
$("div.project_element div.project_image_paging a.paging_prev").click(function() {
return prevImg(this);
});
$("div.project_element div.project_image_paging a.paging_next").click(function() {
return nextImg(this);
});
$("div.project_element div.project_image img").click(function() {
return nextImg(this);
});
$("div.project_element div.project_image img").css("cursor", "pointer");
$("a.paging_prev").css("cursor", "pointer");
return $("a.paging_next").css("cursor", "pointer");
});
|
import identifyPersonByPhone from './identifyPersonByPhone'
export default {
identifyPersonByPhone
} |
var gulp = require('gulp');
var sass = require('gulp-sass');
var fs = require('fs');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var clean = require('gulp-clean');
var gm = require('gulp-gm');
gulp.task('default', ['sass-styles', 'folder-structure'], function () {
browserSync.init({
server: {
baseDir: './',
index: 'index.html'
}
});
gulp.watch('index.html').on('change', browserSync.reload);
gulp.watch('sass/**/*.scss', ['sass-styles']).on('change', browserSync.reload);
gulp.watch('js/**/*.js').on('change', browserSync.reload);
});
gulp.task('sass-styles', function () {
return gulp.src('sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions']
}))
.pipe(gulp.dest('./css'))
.pipe(browserSync.stream());
});
gulp.task('folder-structure', function(){
var gallery = './images/gallery';
console.log('Scanning folders inside '+gallery+' \n');
var result = {};
var folders = fs.readdirSync(gallery);
for (var i = 0; i < folders.length; i++) {
var files = fs.readdirSync(gallery + '/' + folders[i]);
result[folders[i]] = files;
}
fs.writeFile('./images/folder-structure.js', 'var folderStructure = ' + JSON.stringify(result));
});
gulp.task('thumbnails-clean', function(){
return gulp.src('images/thumb_gallery', {read: false})
.pipe(clean());
});
gulp.task('thumbnails-generate', ['thumbnails-clean'], function(){
return gulp.src('images/gallery/**/*.{jpg,png}')
.pipe(gm(function(gmfile){
return gmfile.resize(200, 200);
}))
.pipe(gulp.dest('images/thumb_gallery'));
});
|
import React from 'react';
import Grid from './Grid';
export default function Shape({ name, grid, click }) {
const CLASS = 'gf-shape';
return (
<button className={CLASS} onClick={click} title={name} >
<Grid rows={grid} />
</button>
);
}
Shape.propTypes = {
name: React.PropTypes.string.isRequired,
grid: React.PropTypes.array.isRequired,
click: React.PropTypes.func.isRequired,
};
|
import React from 'react';
import AddBookForm from './AddBookForm';
import UpdateBookForm from './UpdateBookForm';
import DeleteBookForm from './DeleteBookForm';
import Board from './Board';
import store from '../store/index';
import { Provider } from 'react-redux';
function App() {
return (
<Provider store={store}>
<div className="App">
<div>
<React.Fragment>
<AddBookForm />
<UpdateBookForm />
<DeleteBookForm />
</React.Fragment>
</div>
<div>
<Board />
</div>
</div>
</Provider>
);
}
export default App;
|
//listen for form submit
document.getElementById('myform').addEventListener('submit', saveBookmark);
// Saves bookmark
function saveBookmark(e){
//form values
var siteName = document.getElementById('siteName').value;
var siteUrl = document.getElementById('siteUrl').value;
if (!validateForm(siteName, siteUrl)) {
return false;
}
var bookmark ={
name: siteName,
url: siteUrl
}
/*
//local storage test
localStorage.setItem('test', 'Hello World');
console.log(localStorage.getItem('test'));
localStorage.removeItem('test');
console.log(localStorage.getItem('test'));
*/
//tests if bookmark has a value
if(localStorage.getItem('bookmarks') === null){
//init array
var bookmarks = [];
//add to array
bookmarks.push(bookmark);
//set to local Storage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
} else {
//get bookmarks from local storage
var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
//add bookmark to array
bookmarks.push(bookmark);
//reset back to local storage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
}
// Clear form
document.getElementById('myForm').reset();
// re-fetch bookmarks
fetchBookmarks();
// prevents the form from submiting
e.preventDefault();
}
//Delete bookmark
function deleteBookmark(url){
//get bookmarks form local storage
var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
// loop through bookmarks
for (var i = 0; i < bookmarks.length ; i++) {
if (bookmarks[i].url == url) {
//remove form array
bookmarks.splice(i, 1);
}
}
//reset back to local storage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
// re-fetch bookmarks
fetchBookmarks();
}
//Edit bookmark
function deleteBookmark(url){
//get bookmarks form local storage
var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
// loop through bookmarks
for (var i = 0; i < bookmarks.length ; i++) {
if (bookmarks[i].url == url) {
//update url
bookmarks.splice(i, 1);
}
}
//reset back to local storage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
// re-fetch bookmarks
fetchBookmarks();
}
//toggle edit function
function editUrl() {
var x = document.getElementById("edit");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
//fetch bookmarks
function fetchBookmarks(){
//get bookmarks from local storage
var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
//get output ID
var bookmarksResults = document.getElementById('bookmarksResults');
//build output
bookmarksResults.innerHTML = '';
for(var i = 0; i < bookmarks.length; i++){
var name = bookmarks[i].name;
var url = bookmarks[i].url;
bookmarksResults.innerHTML += '<div class="card">'+
'<div class="card-body">'+
'<h3>'+name+
'</h3>'+
'<a class="btn btn-secondary" target="_blank" href="'+url+'">visit</a> ' +
'<a onclick="deleteBookmark(\''+url+'\')" class="btn btn-danger" href="#">Delete</a> ' +
'<button onclick="editUrl()" class="btn btn-primary">Edit</button> ' +
'<br>'+
'<div id="edit" style="display:none;"> '+
'<label>Site Url</label> '+
'<input type="text" class="form-control" id="siteUrl" placeholder="Website Url"> '+
'<br>'+
'<button onclick="saveUrl()" class="btn btn-success">Save</button> ' +
'</div>' +
'</div>'+
'</div> '+
'<br>';
}
}
//validate form
function validateForm(siteName, siteUrl){
if (!siteName || !siteUrl) {
alert('Please fill in the form properly');
return false;
}
var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if (!siteUrl.match(regex)) {
alert('Please Use a valid Url');
return false;
}
return true;
} |
import { auth } from './firebase';
// Register
export const doCreateUserWithEmailAndPassword = (email, password) =>
auth.createUserWithEmailAndPassword(email, password);
// Login
export const doSignInWithEmailAndPassword = (email, password) =>
auth.signInWithEmailAndPassword(email, password);
// Logout
export const doSignOut = () =>
auth.signOut();
//Fetch current UserId
export const getUserId = () => {
return auth.currentUser.uid;
} |
const mathFunctions = require('./models/math')
const hello = require('./models/hello')('Jamshidbek');
const port = 5000;
const http = require('http');
const server = http.createServer((req,res) => {
res.writeHead(200,{
'Content-Type': 'text/html',
})
res.write(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>goodreads</title>
</head>
<body>
<h1>bu lorem ipson matni</h1>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. A, molestiae voluptates placeat
dolore nobis assumenda
corrupti vero aut vitae ut excepturi numquam ea deserunt! Sint
deleniti nemo placeat aut sapiente!
</p>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSepLane0dsRd52TZT7jHu7HMVG1OZq7KYssg&usqp=CAU" alt="">
</body>
</html>
`);
res.end();
})
server.listen(port,()=>console.log(
'server run on port: ' + port
))
|
function sum(a) {
let currentSum = a;
let calc = true;
function f(b) {
if(b && calc){
currentSum += b;
}else{
calc = false;
}
return f;
}
f.toString = function() {
return currentSum ? currentSum : 0;
};
return f;
}
console.log(sum(1));
console.log(sum(1)(2));
console.log(sum(1)(2)());
console.log(sum(1)(2)()(7));
console.log(sum()); |
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useRouteMatch } from 'react-router-dom';
import 'react-semantic-ui-datepickers/dist/react-semantic-ui-datepickers.css';
import { changePath, useFetchNamesQuery } from '../../store';
import { LoadingComponent } from '../LoadingComponent';
import { ErrorNotification } from '../notifications/ErrorNotification';
import './HistoryComponent.css';
import { HistoryComponentUi } from './ui/HistoryComponentUi';
export const HistoryComponent = () => {
const { data: names, isLoading, isError } = useFetchNamesQuery();
const match = useRouteMatch();
const dispatch = useDispatch();
useEffect(() => {
dispatch(changePath('/history'));
}, []);
return (
<>
{isLoading ? (
<LoadingComponent />
) : isError ? (
<ErrorNotification
content={'Błąd połączenia. Spróbuj ponownie za chwile.'}
header={'Błąd połączenia'}
/>
) : (
<HistoryComponentUi names={names} />
)}
</>
);
};
|
export default {
props: {
config: {
type: Object,
required: true
},
fullscreen: {
type: Boolean,
default: false
}
},
mounted() {
this.bus.$on("dashboard.refresh", this.doRefresh);
},
beforeDestroy() {
this.bus.$off("dashboard.refresh", this.doRefresh);
},
methods: {
doRefresh(window, id) {
if (!id || id == this.config.id) {
this.refresh(window);
}
}
}
}; |
import React from 'react';
import PhotoUploadForm from './photo_upload_form_container';
class PhotoUploadButton extends React.Component {
render(){
return (
<div className='photo-upload-button-container'>
<button className='photo-upload-button'
onClick={() => this.props.openModal(<PhotoUploadForm/>)}>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="feather feather-plus-square"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg>
</button>
</div>
);}
}
export default PhotoUploadButton;
|
/*
* @lc app=leetcode id=1031 lang=javascript
*
* [1031] Maximum Sum of Two Non-Overlapping Subarrays
*/
// @lc code=start
/**
* @param {number[]} A
* @param {number} L
* @param {number} M
* @return {number}
*/
var maxSumTwoNoOverlap = function(A, L, M) {
// Lmax, max sum of contiguous L elements before the last M elements.
for (let i = 1; i < A.length; i++) {
A[i] += A[i - 1];
}
let value = A[L + M - 1];
let Lmax = A[L - 1];
let Mmax = A[M - 1];
let LFirstValue;
let MFirstValue;
for (let i = L + M; i < A.length; i++) {
// L first
Lmax = Math.max(Lmax, A[i - M] - A[i - M - L]);
LFirstValue = Lmax + A[i] - A[i - M];
// M first
Mmax = Math.max(Mmax, A[i - L] - A[i - L - M]);
MFirstValue = Mmax + A[i] - A[i - L];
value = Math.max(value, Math.max(LFirstValue, MFirstValue));
}
return value;
};
// @lc code=end
maxSumTwoNoOverlap([0,6,5,2,2,5,1,9,4], 1, 2);
|
// chiedo all'utente se vuole scommettere su pari o dispari
// chiedo all'utente di inserire un numero tra 1 e 5
// faccio generare all'AI un numero random tra 1 e 5
// tramite una funzione sommo i due numeri e controllo che la somme sia pari o dispari e la scelta dell'utente e ritorno una risposta a schermo
var scommessaUtente = prompt('scrivi se scommetti su pari o dispari');
var numeroUtente = parseInt(prompt('inserisci un numero da 1 a 5'));
var numeroRandom = Math.floor(Math.random() * 5) + 1;
console.log('hai scelto ' + scommessaUtente + ' con numero ' + numeroUtente);
console.log('l\' intelligenza artificiale ha scelto ' + numeroRandom);
if (pariDispari(true)) {
console.log('complimenti, hai vinto!');
} else {
console.log('mi dispiace, hai perso!');
}
function pariDispari () {
var sommaNumeri = numeroUtente + numeroRandom;
console.log(sommaNumeri);
if ((scommessaUtente.toLowerCase() === 'pari' && sommaNumeri % 2 == 0) || (scommessaUtente.toLowerCase() === 'dispari' && sommaNumeri % 2 == 1)) {
return true;
} else {
return false;
}
}
|
const renderFtl = require('./render-ftl')
module.exports = app => {
app.route('/').get((req, res) => renderFtl(req, res))
app.get('/js/lodash.min.js', (req, res) => {
res.sendFile('lodash/lodash.min.js', {
root: './node_modules/'
})
})
app.get('/js/react.development.js', (req, res) => {
res.sendFile('react/umd/react.development.js', {
root: './node_modules/'
})
})
app.get('/js/react-dom.development.js', (req, res) => {
res.sendFile('react-dom/umd/react-dom.development.js', {
root: './node_modules/'
})
})
app.get('/js/react.min.js', (req, res) => {
res.sendFile('react/umd/react.production.min.js', {
root: './node_modules/'
})
})
app.get('/js/react-dom.min.js', (req, res) => {
res.sendFile('react-dom/umd/react-dom.production.min.js', {
root: './node_modules/'
})
})
app.get('/js/redux.min.js', (req, res) => {
res.sendFile('redux/dist/redux.min.js', {
root: './node_modules/'
})
})
app.get('/js/polyfill.min.js', (req, res) => {
res.sendFile('babel-polyfill/dist/polyfill.min.js', {
root: './node_modules/'
})
})
app.get('/js/react-redux.min.js', (req, res) => {
res.sendFile('react-redux/dist/react-redux.min.js', {
root: './node_modules/'
})
})
app.get('/js/redux-thunk.min.js', (req, res) => {
res.sendFile('redux-thunk/dist/redux-thunk.min.js', {
root: './node_modules/'
})
})
app.get('/js/prop-types.min.js', (req, res) => {
res.sendFile('prop-types/prop-types.min.js', {
root: './node_modules/'
})
})
app.get('/css/bootstrap.min.css', (req, res) => {
res.sendFile('bootstrap/dist/css/bootstrap.min.css', {
root: './node_modules/'
})
})
app.get('/css/carousel.min.css', (req, res) => {
res.sendFile('react-responsive-carousel/lib/styles/carousel.min.css', {
root: './node_modules/'
})
})
}
|
/// <reference path="guidetools/guidestep.js" />
/// <reference path="tools/receivecall.js" />
/// <reference path="tools/parkedguides.js" />
/// <reference path="tabmanager.js" />
/// <reference path="asyncwebpartloader.js" />
/// <reference path="pagestatesmanager.js" />
if (TdcGuideManager == null || typeof (TdcGuideManager) != "object") {
var TdcGuideManager = new Object();
}
(function ($) {
(function (context) {
// Cached selectors.
context.$guideTools = null;
context.$guideSessionReplacableZones = null;
context.etrayGuideOrArticleTitle = "";
context.init = function () {
// Zones that are often filtered on together.
context.$guideSessionReplacableZones = $();
context.$guideSessionReplacableZones = context.$guideSessionReplacableZones.add('#GAASelector_placeholder');
context.$guideSessionReplacableZones = context.$guideSessionReplacableZones.add('#GuideStep_placeholder');
context.$guideSessionReplacableZones = context.$guideSessionReplacableZones.add('#GuideActionButtons_placeholder');
context.$guideSessionReplacableZones = context.$guideSessionReplacableZones.add(context.$guideTools);
context.$guideSessionReplacableZones = context.$guideSessionReplacableZones.add('#CustomerHistoryInformationGuide_placeholder');
};
//params: entityId, entityType, customerId, rootCustomerId, noteText, entityTitle, sectionTitle, subsectionTitle, portalSection
context.startGuideOrArticle = function (params) {
$(window).scrollTop(0);
//just activate tab if guide already opened and DON'T open the same guide twice
if (activateGuideTab(params.entityId)) return;
//TdcPageStatesManager.goToNewSession();
var dataContext = params;
dataContext.noteId = TdcUtils.createNewGuid(),
dataContext.tabType = 'GuideStep';
if (dataContext.rootCustomerId == undefined) dataContext.rootCustomerId = dataContext.customerId;
dataContext.jobCodeValue = TdcCustomerInformation.JobKode == undefined ? "" : TdcCustomerInformation.JobKode;
dataContext.orderType = TdcCustomerInformation.OrderType == undefined ? "" : TdcCustomerInformation.OrderType;
dataContext.orderId = TdcCustomerInformation.OrdreTypeID == undefined ? "" : TdcCustomerInformation.OrdreTypeID;
dataContext.svarsted = TdcReceiveCall.svarsted;
dataContext.contextId = TdcReceiveCall.contextId;
dataContext.departmentName = TdcMain.UserDepartment;
dataContext.taskID = TdcCustomerInformation.ToolCustomerTaskIDFSM;
TdcGuideManager.etrayGuideOrArticleTitle = params.entityTitle;
var $tab = TdcTabManager.addNewTab(params.entityTitle, dataContext, false);
$tab.attr('title', params.entityTitle + ' LID: ' + params.customerId);
$tab.attr('data-focusedlid', params.customerId);
$tab.attr('data-isarticle', params.entityType == "Article");
TdcAsyncWebPartLoader.ShowTool({
toolname: "GuideStep",
toolType: "guideTool",
action: 'Start' + params.entityType,
context: dataContext,
callback: function (webpart,requestData) {
if (TdcAsyncWebPartLoader.portalId == TdcAsyncWebPartLoader.portalIds.MyTP || TdcAsyncWebPartLoader.portalId == TdcAsyncWebPartLoader.portalIds.TP) {
}
else {
var noteField = $('.GuideNoteWP[data-noteid=' + requestData.context.noteId + '] textarea');
noteField.trigger("click");
noteField.focus();
}
if (dataContext.noteId == TdcTabManager.getDataContext(TdcTabManager.$activeTab).noteId) {
}
},
errorcallback: function ($errorHtml) { addCloseTabButton($errorHtml, $tab); }
});
};
context.resumeArticle = function (params) {
$(window).scrollTop(0);
//just activate tab if guide already opened and DON'T open the same guide twice
if (activateGuideTab(params.entityId)) return;
TdcPageStatesManager.goToNewSession();
var dataContext = params;
dataContext.noteId = TdcUtils.createNewGuid();
dataContext.departmentName = TdcMain.UserDepartment;
dataContext.tabType = 'GuideStep';
if (dataContext.rootCustomerId == undefined) dataContext.rootCustomerId = dataContext.customerId;
var $tab = TdcTabManager.addNewTab(params.entityTitle, dataContext, false);
$tab.attr('title', params.entityTitle + ' LID: ' + params.customerId);
$tab.attr('data-isarticle', params.entityType == "Article");
TdcAsyncWebPartLoader.ShowTool({
toolname: "GuideStep",
toolType: "guideTool",
action: 'Resume' + params.entityType,
context: dataContext,
callback: function () {
if (dataContext.noteId == TdcTabManager.getDataContext(TdcTabManager.$activeTab).noteId) {
}
},
errorcallback: function ($errorHtml) { addCloseTabButton($errorHtml, $tab); }
});
};
context.startGuideFromHop2fakt = function (customerId, jobCodeName, jobCodeValue, msosOrderType, msosOrderNumber, guideName) {
$(window).scrollTop(0);
var entityId = jobCodeName;
if (activateGuideTab(entityId)) return;
TdcPageStatesManager.goToNewSession();
var promise = TdcCustomerInformation.loadCustomer(customerId)
promise.then(function (result) {
if (msosOrderType != "CASTRO") {
var parentAccountNo = TdcCustomerInformation.getSelectedCustomerAccountNo();
var params = {
customerId: customerId,
rootCustomerId: customerId,
jobCodeName: jobCodeName,
jobCodeValue: jobCodeValue,
msosOrderType: msosOrderType,
msosOrderNumber: msosOrderNumber,
noteId: TdcUtils.createNewGuid(),
entityId: entityId,
guideName: guideName,
tabType: 'GuideStep',
parentAccountNo: parentAccountNo,
svarsted: TdcReceiveCall.svarsted,
departmentName : TdcMain.UserDepartment,
contextId: TdcReceiveCall.contextId,
portalSection: TdcMain.portalSection,
taskID: TdcCustomerInformation.ToolCustomerTaskIDFSM
};
var $tab = TdcTabManager.addNewTab(jobCodeName, params, false);
$tab.attr('title', guideName + ' LID: ' + params.customerId);
$tab.attr('data-isarticle', false);
TdcAsyncWebPartLoader.ShowTool({
toolname: "GuideStep",
toolType: "guideTool",
action: 'StartGuideFromHop2Fakt',
context: params,
callback: function ($html, newNoteId) { //guideStep returns new noteId and we need update it;
$html.filter('div').each(function () {
TdcTabManager.addTabContent($(this));
});
$tab.text($html.filter('.GuideStepWP').attr('data-entitytitle'));
},
errorcallback: function ($errorHtml) {
addCloseTabButton($errorHtml, $tab);
}
});
}
});
};
context.startGuideFromMyTP = function (customerId, jobCodeName, jobCodeValue, msosOrderType, msosOrderNumber, guideName) {
$(window).scrollTop(0);
var entityId = jobCodeName;
var deferred = $.Deferred();
if (activateGuideTab(entityId)) return;
TdcPageStatesManager.goToNewSession();
var promise = TdcCustomerInformation.loadCustomer(customerId, null, false, 'onsite_Ordredetaljer')
promise.then(function (result) {
if (msosOrderType != "CASTRO") {
var parentAccountNo = TdcCustomerInformation.getSelectedCustomerAccountNo();
var params = {
customerId: customerId,
rootCustomerId: customerId,
jobCodeName: jobCodeName,
jobCodeValue: jobCodeValue,
msosOrderType: msosOrderType,
msosOrderNumber: msosOrderNumber,
noteId: TdcUtils.createNewGuid(),
entityId: entityId,
guideName: guideName,
tabType: 'GuideStep',
parentAccountNo: parentAccountNo,
svarsted: TdcReceiveCall.svarsted,
departmentName: TdcMain.UserDepartment,
contextId: TdcReceiveCall.contextId,
portalSection: TdcMain.portalSection,
taskID: TdcCustomerInformation.ToolCustomerTaskIDFSM
};
var $tab = TdcTabManager.addNewTab(jobCodeName, params, false);
$tab.attr('title', guideName + ' LID: ' + params.customerId);
$tab.attr('data-isarticle', false);
TdcAsyncWebPartLoader.ShowTool({
toolname: "GuideStep",
toolType: "guideTool",
action: 'StartGuideFromHop2Fakt',
context: params,
callback: function ($html, newNoteId) { //guideStep returns new noteId and we need update it;
$html.filter('div').each(function () {
TdcTabManager.addTabContent($(this));
});
$tab.text($html.filter('.GuideStepWP').attr('data-entitytitle'));
deferred.resolve(true);
//if (context.userType == "COAX") {
//TdcMyOrder.ShowCSAMTab();
//}
},
errorcallback: function ($errorHtml) {
addCloseTabButton($errorHtml, $tab);
if (TdcAsyncWebPartLoader.portalId == TdcAsyncWebPartLoader.portalIds.MyTP && TdcMyOrder.userType == "COAX") {
TdcMyOrder.ShowCSAMTab();
}
deferred.resolve(true);
}
});
}
});
return deferred.promise();
};
context.resumeGuideOrShowHistoryInformation = function (noteId, entityId, entityTitle, portalId, callback) {
if (activateGuideTab(entityId)) return;
//TdcPageStatesManager.goToNewSession();
if (portalId != TdcAsyncWebPartLoader.portalId) {
//openGuideHistoryTab
context.openGuideHistoryTab(noteId, entityId, entityTitle);
}
else {
//resume
var dataContext = {
noteId: noteId,
tabType: 'GuideStep',
entityType: 'Guide',
entityId: entityId,
departmentName : TdcMain.UserDepartment,
};
var $tab = TdcTabManager.addNewTab(entityTitle, dataContext, false);
$tab.attr('data-isarticle', false);
$(window).scrollTop(0);
TdcAsyncWebPartLoader.ShowTool({
toolname: "GuideStep",
toolType: "guideTool",
action: 'ResumeGuide',
context: dataContext,
callback: function ($html, requestData) {
dataContext.customerId = $html.attr('data-customerid');
dataContext.rootCustomerId = $html.attr('data-rootcustomerid');
$tab.attr('title', entityTitle + ' LID: ' + dataContext.customerId);
callback($html, requestData);
},
errorcallback: function ($errorHtml) { addCloseTabButton($errorHtml, $tab); }
});
}
};
context.openGuideHistoryTab = function (noteId, entityId, entityTitle) {
$(window).scrollTop(0);
var $existingTab = TdcTabManager.$findTab({ noteId: noteId });
if ($existingTab.length > 0) {
TdcTabManager.activateTab($existingTab);
}
else {
TdcPageStatesManager.goToNewSession();
var dataContext = {
noteId: noteId,
tabType: 'CustomerHistoryInformationGuide'
};
var $tab = TdcTabManager.addNewTab(entityTitle, dataContext);
$tab.attr('data-isarticle', false);
$tab.wrapInner('<em></em>');
$('<span/>').attr('class', 'glyphicon glyphicon-lock margin-right-10').prependTo($tab);
TdcAsyncWebPartLoader.ShowTool({
toolname: "CustomerHistoryInformationGuide",
toolType: "guideTool",
context: dataContext,
errorcallback: function ($errorHtml) { addCloseTabButton($errorHtml, $tab); }
});
}
};
context.goToNextStep = function (noteId, responseId, stepStateData, noteText, entityType) {
var dataContext = {
noteId: noteId,
noteText: noteText,
responseId: responseId,
stepStateData: stepStateData,
entityType: entityType,
departmentName : TdcMain.UserDepartment,
};
var $existingGuideStepTools = $('[data-tooltype=guideStepTool][data-noteid=' + noteId + ']');
TdcAsyncWebPartLoader.ShowTool({
action: 'NextStep',
toolname: "GuideStep",
context: dataContext,
callback: function (html) {
var $tab = TdcTabManager.$findTab({ noteId: dataContext.noteId });
TdcTabManager.removeTabContent($tab, $existingGuideStepTools);
if (TdcTabManager.isTabActive($tab)) {
$(window).scrollTop(0);
}
}
});
};
context.goToPreviousStep = function (noteId, stepStateData, noteText, stepId /*optional*/) {
var curNoteId = noteId;
showStep({
action: 'PreviousStep',
toolname: "GuideStep",
context: {
noteId: noteId,
noteText: noteText,
stepStateData: stepStateData,
stepId: stepId,
departmentName: TdcMain.UserDepartment,
},
errorcallback: function () {
TdcGuideStep.EnableActionButtons(curNoteId);
},
});
};
context.showNextStep = function (noteId, responseId, stepStateData, noteText) {
var curNoteId = noteId;
showStep({
action: 'NextStep',
toolname: "GuideStep",
context: {
noteId: noteId,
noteText: noteText,
responseId: responseId,
stepStateData: stepStateData,
departmentName: TdcMain.UserDepartment,
},
errorcallback: function () {
TdcGuideStep.EnableActionButtons(curNoteId);
},
});
};
function showStep(requestData) {
var $existingGuideStepTools = $('[data-tooltype=guideStepTool][data-noteid=' + requestData.context.noteId + ']');
requestData.callback = function (html) {
var $tab = TdcTabManager.$findTab({ noteId: requestData.context.noteId });
TdcTabManager.removeTabContent($tab, $existingGuideStepTools);
if (TdcTabManager.isTabActive($tab)) {
$(window).scrollTop(0);
}
}
TdcAsyncWebPartLoader.ShowTool(requestData);
}
context.parkGuide = function (noteId, stepStateData, noteText, sender) {
TdcMain.atleastOneNoteSaved = true;
var $tab = TdcTabManager.$findTab({ noteId: noteId });
var curNoteId = noteId;
TdcAsyncWebPartLoader.DoAction({
toolname: "GuideStep",
action: 'ParkGuide',
context: {
stepStateData: stepStateData,
noteId: noteId,
noteText: noteText,
additionalValues: $(TdcTabManager.$getTabs()).filter(".active").data('tab-additionalvalues'),
departmentName: TdcMain.UserDepartment,
},
callback: function () {
TdcTabManager.removeTab($tab);
TdcParkedGuides.refresh();
},
errorcallback: function () {
TdcGuideStep.EnableActionButtons(curNoteId);
},
messageProcess: TranslationsJs.Parking_guide,
messageSuccess: TranslationsJs.Guide_parked_succesfully,
messageError: TranslationsJs.Aborting_guide + ' "' + TdcTabManager.getTabTitle($tab) + '" ' + TranslationsJs.failed + '.',
}, sender);
};
//Bug ID041 : Added parameters noteText and entityType
context.abortGuide = function (noteId, stepStateData, entityType, noteText, sender) {
var $tab = TdcTabManager.$findTab({ noteId: noteId });
var curNoteId = noteId;
TdcAsyncWebPartLoader.DoAction({
toolname: "GuideStep",
action: 'CancelGuide',
context: {
stepStateData: stepStateData,
noteId: noteId,
noteText: noteText,
entityType: entityType,
},
callback: function () {
//var noteText = TdcGuideStep.getNoteText(noteId);
TdcGuideSelector.setNoteText("");
TdcTabManager.removeTab($tab);
TdcParkedGuides.refresh();
},
errorcallback: function () {
TdcGuideStep.EnableActionButtons(curNoteId);
},
messageProcess: TranslationsJs.Aborting_guide,
messageSuccess: TranslationsJs.Guide_was_aborted,
messageError: TranslationsJs.Aborting_guide + ' "' + TdcTabManager.getTabTitle($tab) + '" ' + TranslationsJs.failed + '.',
}, sender);
};
context.restartGuide = function (noteId, stepStateData, noteText, sender) {
var $tab = TdcTabManager.$findTab({ noteId: noteId });
var $existingGuideStepTools = context.$guideSessionReplacableZones.find('[data-tooltype=guideStepTool][data-noteid=' + noteId + ']');
var curNoteId = noteId;
TdcAsyncWebPartLoader.ShowTool({
toolname: "GuideStep",
action: 'RestartGuide',
context: {
stepStateData: stepStateData,
noteId: noteId,
noteText: noteText,
departmentName: TdcMain.UserDepartment,
},
callback: function () {
TdcTabManager.removeTabContent($tab, $existingGuideStepTools);
},
errorcallback : function() {
TdcGuideStep.EnableActionButtons(curNoteId);
},
messageProcess: TranslationsJs.Restarting_guide,
messageSuccess: TranslationsJs.Guide_was_restarted,
messageError: TranslationsJs.Restarting_guide + ' "' + TdcTabManager.getTabTitle($tab) + '" ' + TranslationsJs.failed + '.',
}, sender);
};
context.completeGuide = function (noteId, noteText, stepStateData, sender, entityType, callfromDashboardLink) {
var $guideStepTool = TdcAsyncWebPartLoader.getToolByName("GuideStep", noteId);
if (TdcMain.etrayCIPTagsValues[noteId] != undefined && TdcMain.etrayCIPTagsValues[noteId].length > 0) {
var etrayCipTag = TdcMain.etrayCIPTagsValues[noteId][TdcMain.etrayCIPTagsValues[noteId].length - 1].tags; // get cip tags for etrayCallEvent
var etrayCipTagValue = TdcMain.etrayCIPTagsValues[noteId][TdcMain.etrayCIPTagsValues[noteId].length - 1].tagValues; // get cip tag values for etrayCallEvent
var etrayGuideSessionId = $('.GuideStepWP').filter(':visible').attr('data-sessionid');
var etrayCustomerId = TdcCustomerInformation.getSelectedCustomerId();
var etrayAccountNumber = TdcCustomerInformation.getSelectedCustomerAccountNo();
var userId = TdcCustomerInformation.UserId;
var technology = "FIXED";
var date = new Date();
var dateTime = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
var etraySectionTitle = $('.navbar-collapse').find("[data-portalsectionname='" + TdcMain.portalSection + "']")[0].innerText;
var etrayGuideOrArticleTitle = $guideStepTool.attr('data-entitytitle').replace("%", " "); // Handled % by replacing it by blank space as it was giving issue with the guide title while passing it in the etray URL
var etrayContextId = TdcReceiveCall.contextId;
var note = $('.tempGuideNoteTextarea').filter(":visible").val().replace(/ /g, "_");
var etrayUrl = "https://etray.yousee.dk/Privat/N/Portal/Master.html?token=Cjh7SalJdtN/obcQoB0eSMZzpIpCzPbM&CIP_SESSION_ID=" + etrayGuideSessionId + "&LID=" + etrayCustomerId + "&ACCOUNT_NO=" + etrayAccountNumber + "&USER_ID=" + userId + "&TECHNOLOGY=" + technology + "&CIP_TIMESTAMP=" + dateTime + "&AREA=" + etraySectionTitle + "&TITLE=" + etrayGuideOrArticleTitle + "&AVAYA_CALLID=" + etrayContextId + "&" + etrayCipTag + "=" + etrayCipTagValue + "&Note=" + note + "";
$("#iframeCallEventEtrayURL").attr('src', etrayUrl);
setTimeout(function () {
context.completeGuideCIPTag(noteId, noteText, stepStateData, sender, entityType, callfromDashboardLink);
}, 6000);
}
else {
context.completeGuideCIPTag(noteId, noteText, stepStateData, sender, entityType, callfromDashboardLink);
}
};
context.completeGuideCIPTag = function (noteId, noteText, stepStateData, sender, entityType, callfromDashboardLink) {
TdcMain.atleastOneNoteSaved = true;
var $tab = TdcTabManager.$findTab({ noteId: noteId });
var curNoteId = noteId;
TdcAsyncWebPartLoader.DoAction({
toolname: "GuideStep",
action: 'CompleteGuide',
context: {
stepStateData: stepStateData,
noteId: noteId,
noteText: noteText,
entityType: entityType,
additionalValues: $(TdcTabManager.$getTabs()).filter(".active").data('tab-additionalvalues'),
departmentName: TdcMain.UserDepartment,
},
callback: function () {
TdcTabManager.removeTab($tab);
if (typeof (callfromDashboardLink) == undefined || typeof (callfromDashboardLink) == "undefined" || callfromDashboardLink == false) {
//Bug 1360: Corrected logic to get the active guide tab count and then compare it if it is > 0
if (context.$getActiveGuideTabs().length > 0 || context.$getActiveFasoTabs().length > 0 || context.$getActiveLinkTabs().length > 0) {
TdcGuideSelector.activate();
TdcCustomerHistoryInformation.refresh();
} else {
TdcMain.goToDashboard = true;
TdcMain.showDashboard();
}
}
},
errorcallback: function () {
TdcGuideStep.EnableActionButtons(curNoteId);
},
messageProcess: TranslationsJs.Completing_guide,
messageSuccess: TranslationsJs.Guide_was_completed,
messageError: TranslationsJs.Complete_guide + ' "' + TdcTabManager.getTabTitle($tab) + '" ' + TranslationsJs.failed + '.',
}, sender);
};
context.parkOpenedGuides = function (sender, callfromDashboardLink) {
$.each(context.$getActiveGuideTabs(), function () {
var dataContext = TdcTabManager.getDataContext($(this));
var stepStateData = TdcGuideStep.getStepStateData(dataContext.noteId);
var noteField = $('.GuideNoteWP[data-noteid=' + dataContext.noteId + '] textarea');
var noteText = noteField.val();
if (!TdcGuideSelector.isValidNoteText(noteField)) {
TdcGuideSelector.errorOutNoteField(noteField);
TdcMain.goToDashboard = false;
var $tab = TdcTabManager.$findTab({ noteId: dataContext.noteId });
$tab.addClass("inValidNoteText");
return;
}
if ($(this).data("isarticle") == undefined || $(this).data("isarticle") != true)
{//dont call parkGuide in case of articles
context.parkGuide(dataContext.noteId, stepStateData, noteText, sender);
}
else if ($(this).data("isarticle") != undefined || $(this).data("isarticle") == true) {// call complete guide in case of Article
context.completeGuide(dataContext.noteId, noteText, stepStateData, sender, "Article", callfromDashboardLink);
}
});
};
context.closeAndSaveOpenedGuidesAndArticle = function (sender, callfromDashboardLink) {
$.each(context.$getActiveGuideTabs(), function () {
var dataContext = TdcTabManager.getDataContext($(this));
var stepStateData = TdcGuideStep.getStepStateData(dataContext.noteId);
var noteField = $('.GuideNoteWP[data-noteid=' + dataContext.noteId + '] textarea');
var noteText = noteField.val();
//if (!TdcGuideSelector.isValidNoteText(noteField)) {
// TdcGuideSelector.errorOutNoteField(noteField);
// TdcMain.goToDashboard = false;
// var $tab = TdcTabManager.$findTab({ noteId: dataContext.noteId });
// $tab.addClass("inValidNoteText");
// return;
//}
//if ($(this).data("isarticle") == undefined || $(this).data("isarticle") != true) {//dont call parkGuide in case of articles
// context.parkGuide(dataContext.noteId, stepStateData, noteText, sender);
//}
//else if ($(this).data("isarticle") != undefined || $(this).data("isarticle") == true) {
// call complete guide in case of Article
var entitytype = $(this).data("isarticle") != undefined || $(this).data("isarticle") == true ? "Article" : "Guide";
context.completeGuide(dataContext.noteId, noteText, stepStateData, sender, entitytype, callfromDashboardLink);
//}
});
};
context.$getActiveGuideTabs = function () {
return TdcTabManager.$findTabs({ tabType: 'GuideStep' });
};
context.$getActiveFasoTabs = function () {
return TdcTabManager.$findTabs({ tabType: 'Faso' });
};
//Gets the active Link tabs
context.$getActiveLinkTabs = function () {
return TdcTabManager.$findTabs({ tabType: 'Link' });
};
function activateGuideTab(entityId) { //returns Boolean
var $existingTab = TdcTabManager.$findTab({ entityId: entityId });
if ($existingTab.length != 0) {
TdcTabManager.activateTab($existingTab);
return true;
}
return false;
}
function addCloseTabButton($errorHtml, $tab) {
var $closeBtn = TdcUtils.instantiateTemplate("closeTabBtnTemplate")
.click(function (e) {
TdcTabManager.removeTab($tab);
e.preventDefault();
});
$errorHtml.find('.btnRetry').parent().append(' ').append($closeBtn);
}
})(TdcGuideManager);
$(TdcGuideManager.init);
$(document).ready(function () {
TdcAsyncWebPartLoader.$rootElement.on(TdcAsyncWebPartLoader.toolLoadedEventName, function (event, html) {
if ($(html).hasClass("GuideStepWP")) {
var noteId = $(html).data('noteid');
$tab = TdcTabManager.$findTab({ noteId: noteId });
TdcMain.SetPortalSection($tab);
}
});
});
})(jQuery); |
(function() {
var H = document.documentElement.clientHeight;
var fontSize = H / 10;
var curShowPage = 0;
document.documentElement.style.fontSize = fontSize + 'px';
var myScroll;
var elements = [];
var length = $('.bg-img').length;
for (var i = 0; i < length; i++) {
elements.push($('.bg-img').eq(i));
}
$('.cssloader').hide();
window.onload = function() {
myScroll = new IScroll('#wrapper', {
probeType: 3,
indicators: [{
el: document.getElementById('starfield1'),
resize: false,
ignoreBoundaries: true,
speedRatioY: 0.7
}]
});
myScroll.on('scroll', function() {
var y = -myScroll.y;
var page = ((y / H) >> 0);
var opacity = y < 0.04 ? 0 : (y % H) / H;
var scale = opacity / 2 + 1;
elements[page].css({
'opacity': 1 - opacity,
'-webkit-transform': 'scale3d(' + scale + ', ' + scale + ', 1)',
'transform': 'scale3d(' + scale + ', ' + scale + ', 1)'
});
if (elements[page + 1])
elements[page + 1].css('opacity', opacity);
});
}
document.addEventListener('touchmove', function(e) {
e.preventDefault();
return false;
}, false);
})(); |
'use strict';
var path = require("path");
var supportFile = ["js"];
module.exports = function (param) {
let _, fs;
fs = param.fs, _ = param._;
[].forEach(function (folder) {
let files;
files = fs.readdirSync(path.join(__dirname, folder));
return files.forEach((file) => {
if (!_.contains(supportFile, file.split(".")[1])) {
return;
}
return exports[file.replace(/\.js$/, "")] = require(path.join(__dirname, folder, file.replace(/\.js$/, "")))(param);
});
});
return exports;
};
|
import React from 'react';
import SearchPage from './SearchPage'
import { MainHeader } from 'Components'
class Search extends React.Component {
constructor(props) {
super(props);
const query = this.props.query;
this.state = {
value: query
};
}
componentWillReceiveProps(nextProps) {
const { query } = this.props;
const { query: nextQuery } = nextProps;
if (query !== nextQuery) {
this.setState({
value: nextQuery
})
}
}
render() {
const { value } = this.state
return (
<div>
<MainHeader title="Search" />
<SearchPage value={value} />
</div>
)
}
}
export default Search
|
import t from 'tcomb';
import _ from '//src/nodash';
import { match } from '../match';
import { value } from './value';
import { squish } from '../string.js';
export function extendProps(superProps, subProps, strict) {
const extendedProps = _.mapValues(subProps, (subProp, key) => {
// see if there was a super type
if (_.has(superProps, key)) {
const superType = superProps[key];
// there was.
// what we do depends on what the refinement
return match(subProp,
// it's another type
t.Type, subType => {
if (subType === superType) {
// it's identical to the super type, so just use it
return subType;
} else {
// it's a different type
// an intersection will make sure it satisfies both
// hopefully it's a sub-type of the super type, otherwise
// it will never satisfy
return t.intersection([superType, subType]);
}
},
// it's a function, which we take as the predicate for a refinement
t.Function, predicate => t.refinement(superType, predicate),
// it's some sort of value, which should be a member of the super
// type for it to make any sense
t.Any, v => {
// check that it satisfies the super type
t.assert(superType.is(v), () => squish(`
prop ${ key } given value ${ t.stringify(v) } that is not of
super type ${ t.getTypeName(superType) }
`));
// the new type is that exact value
return value(v);
},
);
} else {
// there is no super type
// if the super struct is strict this is an error since it would
// mean that there could be instances that satisfy the sub type
// but not the super
t.assert(!strict, () => squish(`
can not add prop ${ key } via extension because super type
is strict.
`));
return match(subProp,
t.Type, type => type,
t.Any, v => value(v),
);
}
});
const mergedProps = {
...superProps,
...extendedProps
};
return mergedProps;
}
export function struct(props, options = {}) {
const Struct = t.struct(props, options);
/**
* my extend allows defining of additional properties (when extending
* from non-strict structs) *and* refining of existing properties with the
* principle that if B is an extension of A then any instance that is
* of type B is also of type A.
*/
Struct.extend = function (props, options = {}) {
// deal with options
options = match(options,
// if options is a string it's the name
t.String, name => {name},
// otherwise it should be an object
// clone it so that we can modify it without potential effects outside
// this function
t.Object, {...options},
);
// merge super struct defaultProps
options.defaultProps = {
...Struct.meta.defaultProps,
...options.defaultProps
};
// handle strictness
if (_.has(options, 'strict')) {
// if the super struct is strict, then extended struct must be strict
// (and also must add no new props) - otherwise we could have a situation
// where instances were members of the sub struct type but not the super
// struct type.
if (Struct.meta.strict && options.strict === false) {
throw new TypeError(squish(`
can't create a non-strict sub-struct of strict struct
${ t.getTypeName(Struct) }
`));
}
} else {
// strict is not provided in the options, so inherit from the
// super struct
options.strict = Struct.meta.strict;
}
return struct(
extendProps(Struct.meta.props, props, Struct.meta.strict),
options
);
}
return Struct;
} |
var structvertex3_d =
[
[ "label", "structvertex3_d.html#a6294e6614f1bb7ac73020c203a5f34c1", null ],
[ "x", "structvertex3_d.html#a6c6ee4315d72adbc5abb17e6af802087", null ],
[ "y", "structvertex3_d.html#aa1f4823bf2a3f648b1b0b39ef7ea5891", null ],
[ "z", "structvertex3_d.html#a67f3819dff895cb47284c34ec85658d7", null ]
]; |
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const isDevelopment = process.argv.indexOf('--development') !== -1;
const entryPath = path.join(__dirname, 'src/js/index.js');
const entry = isDevelopment ? [
'webpack-hot-middleware/client?reload=true',
'react-hot-loader/patch',
entryPath
] : entryPath;
const plugins = [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(isDevelopment ? 'development' : 'production'),
__DEV__: isDevelopment
}),
new ExtractTextPlugin('css/bundle.css')
];
isDevelopment && plugins.push(new webpack.HotModuleReplacementPlugin());
!isDevelopment && plugins.push(new webpack.optimize.UglifyJsPlugin());
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: entry,
module: {
loaders: [
{
test: /\.js$/,
loaders: ['babel-loader'],
exclude: /node_modules/
},
{
test: /\.s?css/,
loaders: isDevelopment ? 'style-loader!css-loader?sourceMap!sass-loader?sourceMap' : ExtractTextPlugin.extract({
fallback: 'style-loader',
use: "css-loader!sass-loader"
})
},
{
test : /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
loader : 'file-loader?name=assets/fonts/[name].[ext]'
}
]
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'js/bundle.js'
},
plugins: plugins
}; |
'use strict';
var bluebird = require('bluebird');
var util = require('util');
var assert = require('assert');
/**
* typical callback
*/
function calculatorCB(input, outputCallback) {
util.log('calP', input);
setTimeout(function () {
util.log('calP done', input);
outputCallback(undefined, input * 10);
}, 1000)
}
/**
* promisify typical callback function.
*/
var calP = bluebird.promisify(calculatorCB);
function* calc(input) {
return (yield calP(input))
}
var test = bluebird.coroutine(function* () {
var result1 = yield [calP(1), calP(2)];
//var result1 = yield* runParallel(calc.bind(undefined,1), calc.bind(undefined,2));
util.log(result1);
});
function* runParallel(){
var promises = [];
for(var i = 0; i < arguments.length; i++){
promises.push(bluebird.coroutine(arguments[i])())
}
return yield bluebird.all(promises);
}
test();
|
const countOdd = function(numbers, start, end) {
if (start==end) {
return 0;
}
let isOdd = numbers[start] % 2 != 0 ? 1 : 0;
return isOdd + countOdd(start+1, end);
}
console.log(countOdd([1,2,3,4,5,], 0, 4))
module.exports = countOdd; |
console.log("coucou je vais recuperer les infos ici");
/*
let urlButtonActualisation = "a[href='https://authentification-candidat.pole-emploi.fr/compte/redirigervers?url=https://actualisation-authent.pole-emploi.fr/acces.htm&actu=true']";
let urlEspacePerso = "https://candidat.pole-emploi.fr/espacepersonnel/"
*/
var URLs;
var myRuntime = chrome.runtime.connect({name: "EspacePersonnel"});
myRuntime.postMessage({connect: "(Script de contenu) homepage.js Je te reçoit runtime"});
//Reçoit les messages du runtime
myRuntime.onMessage.addListener(function (msg) {
switch (true) {
case msg.hasOwnProperty('URLs'):
console.log("j'ai reçu les URLs");
URLs = JSON.parse(msg.URLs);
break;
case msg.hasOwnProperty('collectInfo'):
if (document.readyState === "complete") {
console.log("Je collecte les infos -----");
myRuntime.postMessage({news: JSON.stringify(collectInfo())});
} else {
document.addEventListener('readystatechange', (evt) => {
if (evt.target.readyState === "complete") {
console.log("Premiere tentative echoue");
setTimeout(() => {
myRuntime.postMessage({news: JSON.stringify(collectInfo())});
}, 3000);
} else {
console.log("Je patiente que le document finisse de charger");
}
});
}
break;
case msg.hasOwnProperty('actualisation'):
myRuntime.postMessage({greeting: "Ok je lance l'actualisation"});
actualisation(URLs.urlEspacePerso, URLs.urlButtonActualisation);
break;
default:
console.log("Message du runtime");
console.log(msg);
break;
}
});
/**
* collect les infos sur la page Espace personnel
*
* @return {JSON} Return un object JSON avec les données collecte
*/
function collectInfo() {
console.log("Dans la fonction collectInfo()");
//Data JSON qui seront stocké
let infos = {
"dateNextActualisation": "",
"dateLastPaiement": "",
"montantLastPaiement": "",
"countCourrier": ""
};
//Je recupere toutes les div .infos dans le .container-situation
var divInfos = document.querySelectorAll('.container-situation .info');
//Je recupere le nombre de courrier non lues .notification-bubble[0]
var bubbleCourrier = document.querySelector('.notification-bubble');
infos.dateNextActualisation = divInfos[0].firstChild.textContent.split('le')[1].split('et')[0];
//N'existe plus c'etais une div en dessous de la prochaine date d'actualisation
//infos.dateNextActualisation = divInfos[0].nextSibling.firstChild.textContent.split('le')[1].split('et')[0];
infos.dateLastPaiement = divInfos[2].firstChild.nodeValue.split('le')[1];
infos.montantLastPaiement = divInfos[2].firstChild.nodeValue.split(' ')[3];
infos.countCourrier = bubbleCourrier.firstChild.nodeValue;
console.log("Je te retourne les infos suivantes");
console.log(infos);
return infos;
}
/**
* * clique sur le boutton actualisation s'il existe
* @param {[type]} urlEspacePerso URL Homepage
* @param {[type]} urlButtonActualisation URL cible du button Actualisation
*
*/
function actualisation(urlEspacePerso, urlButtonActualisation) {
console.log(document.location.href + urlEspacePerso);
if (document.location.href === urlEspacePerso) {
let buttonActualisation = document.querySelector(urlButtonActualisation);
if (buttonActualisation != undefined) {
myRuntime.postMessage({actualisation: "J'ai cliquer sur actualisation"});
buttonActualisation.click();
} else
myRuntime.postMessage({finish: 'Vous êtes déjà actualisé'});
} else
myRuntime.postMessage({error: "Vous n'êtes sur la bonne page pour lancer l'actualisation"});
}
|
// @flow
import React from 'react';
import { View, StyleSheet, Text } from 'react-native';
import {
UIComponent,
UIStyle,
} from '../services/UIKit';
type Props = {
text: string,
colorFrom: string,
colorTo: string,
fotStyle: any,
length: ?number,
};
type State = {};
export default class TextGradient extends UIComponent<Props, State> {
render() {
const textArray = this.props.text.split('');
return (
<View>
<View style={[UIStyle.common.flex(), UIStyle.common.flexRow(), UIStyle.common.flexRowWrap()]}>
{textArray.map((char, i) => {
return (
<Text key={`to-${char}-${i}`} style={[this.props.fontStyle, { color: this.props.colorTo }]}>{char}</Text>
);
})}
</View>
<View style={[
{ position: 'absolute', top: 0 },
UIStyle.common.flex(),
UIStyle.common.flexRow(),
UIStyle.common.flexRowWrap(),
]}
>
{textArray.map((char, i) => {
return (
<Text
style={[
this.props.fontStyle,
{
color: this.props.colorFrom,
opacity: (1 / (this.props.length || textArray.length)) * (i + 1),
},
]}
key={`from-${char}-${i}`}
>
{char}
</Text>
);
})}
</View>
</View>
);
}
}
|
#! /usr/bin/env node
const childProcess = require('child_process');
const c = require('chalk');
const _ = require('lodash/fp');
const minimatch = require('minimatch');
const {headClean, headMessage, pushFiles} = require('./core/git');
const {makeError} = require('./core/utils');
const executeScript = require('./core/script');
const MAJOR = 'major';
const MINOR = 'minor';
const PATCH = 'patch';
const NOOP = 'noop';
const DEFAULT_KEYWORDS = {
noop: ['#noop', '#no{_,-,}release'],
major: '#major',
minor: ['#minor'],
patch: ['#patch', '#bug', '#fix', '#tweak', '#updates']
};
const DEFAULT_KEYWORD_PRIORITY = [NOOP, MAJOR, PATCH, MINOR];
const builtInSelectReleaseType = (config, message) => {
const {keywords, releasePriority} = config;
for (const releaseType of releasePriority) {
const releaseTypeConfig = keywords[releaseType];
if (!releaseTypeConfig) continue;
if (releaseTypeConfig === true) return releaseType;
const patterns = [releaseTypeConfig].flat();
if (_.some(pattern => minimatch(_.toLower(message), _.toLower(`*${pattern}*`)), patterns))
return releaseType;
}
return _.last(releasePriority);
};
const mergeCustomKeywordsWithDefault = customKeywords => {
if (!customKeywords) return DEFAULT_KEYWORDS;
return _.pipe(
_.toPairs,
_.map(([releaseType, defaultKeywords]) => [
releaseType,
[...[defaultKeywords].flat(), ...[_.getOr([], releaseType, customKeywords)].flat()]
]),
_.fromPairs
)(DEFAULT_KEYWORDS);
};
const getBuiltInSelection = async (config, messageOverride) => {
const message = messageOverride || (await headMessage());
const releasePriority = _.getOr(DEFAULT_KEYWORD_PRIORITY, 'priority', config);
const keywords =
_.get('keywords', config) || mergeCustomKeywordsWithDefault(_.get('custom-keywords', config));
return builtInSelectReleaseType({keywords, releasePriority}, message);
};
const getCustomSelection = cmd => {
try {
return childProcess.execSync(cmd, {encoding: 'utf-8'}).trim();
} catch (err) {
throw makeError('Failed to get release type', {
details: `Exit code of selection command '${cmd}' was ${err.status}`,
exitCode: 5
});
}
};
const getReleaseType = async relaseConfig => {
const releaseSelector = relaseConfig['release-type-command'];
const releaseType = releaseSelector
? getCustomSelection(releaseSelector)
: await getBuiltInSelection(relaseConfig);
if (!_.includes(releaseType, [MAJOR, MINOR, PATCH, NOOP]))
throw makeError(`Invalid release type ${releaseType}`);
return releaseType;
};
const main = async config => {
if (!(await headClean())) throw makeError('Not a clean state', {exitCode: 4});
const autoBumpConfig = config['auto-bump'];
if (_.isBoolean(autoBumpConfig)) {
if (!autoBumpConfig) {
process.stdout.write(c.bold.yellow('Auto-bump is deactivated in config'));
return;
}
} else if (_.isEmpty(autoBumpConfig)) throw makeError('No Config for autobump', {exitCode: 3});
const releaseType = await getReleaseType(autoBumpConfig);
if (releaseType === NOOP) return process.stdout.write(`Won't make a release\n`);
process.stdout.write(c.bold.yellow(`About to make a ${c.bold.blue(releaseType)} release\n`));
const bumpVersionCommand = autoBumpConfig['bump-command'] || 'npm version -m "v%s"';
await executeScript([`${bumpVersionCommand} ${releaseType}`]);
if (!config.local) await pushFiles('master', config.token, config.repoSlug, true);
process.stdout.write(c.bold.green(`Successfully made a ${releaseType} release\n`));
if (autoBumpConfig.publish || autoBumpConfig['publish-command']) {
await executeScript([autoBumpConfig['publish-command'] || 'npm publish']);
process.stdout.write(c.bold.green(`Successfully publish the ${releaseType} release\n`));
}
if (autoBumpConfig['sync-branch']) {
const branch = autoBumpConfig['sync-branch'];
await executeScript([
`git config remote.gh.url >/dev/null || git remote add gh https://${config.token}@github.com/${config.repoSlug}.git`,
`git checkout -B ${branch} master`,
`git push gh ${branch}:refs/heads/${branch} --force || (git remote remove gh && exit 12)`,
'git remote remove gh'
]);
process.stdout.write(c.bold.green(`Successfully sync branch ${branch}\n`));
}
if (autoBumpConfig['merge-branch']) {
const branch = autoBumpConfig['merge-branch'];
await executeScript([
`git config remote.gh.url >/dev/null || git remote add gh https://${config.token}@github.com/${config.repoSlug}.git`,
`git fetch gh && git checkout -B ${branch} gh/${branch} && git merge master`,
`git push gh ${branch}:refs/heads/${branch} || (git remote remove gh && exit 12)`,
'git remote remove gh'
]);
process.stdout.write(c.bold.green(`Successfully merged branch ${branch}\n`));
}
};
module.exports = {
main,
builtInSelectReleaseType,
getReleaseType,
getBuiltInSelection,
getCustomSelection,
mergeCustomKeywordsWithDefault
};
|
// const $ = document;
// const banner = $.querySelector('#js-banner');
// const headerContainer = $.querySelector('#header-container');
// $.addEventListener("DOMContentLoaded", () => {
// window.addEventListener("resize", () => {
// if (window.innerWidth > 768) {
// // console.log('bigger than 768px', window.innerWidth);
// headerContainer.classList.add('container-fluid');
// banner.classList.add('d-flex', 'align-items-center');
// } else {
// // console.log('smaller than 768px', window.innerWidth);
// headerContainer.classList.remove('container-fluid');
// banner.classList.remove('d-flex', 'align-items-center');
// }
// });
// });
|
country = [{id:"al",name:"Albania"},
{id:"dz",name:"Algeria"},
{id:"ar",name:"Argentina"},
{id:"am",name:"Armenia"},
{id:"au",name:"Australia"},
{id:"at",name:"Austria"},
{id:"bh",name:"Bahrain"},
{id:"bd",name:"Bangladesh"},
{id:"by",name:"Belarus"},
{id:"be",name:"Belgium"},
{id:"bj",name:"Benin"},
{id:"bo",name:"Bolivia"},
{id:"bw",name:"Botswana"},
{id:"br",name:"Brazil"},
{id:"bn",name:"Brunei Darussalam"},
{id:"bg",name:"Bulgaria"},
{id:"bf",name:"Burkina Faso"},
{id:"kh",name:"Cambodia"},
{id:"cm",name:"Cameroon"},
{id:"ca",name:"Canada"},
{id:"td",name:"Chad"},
{id:"cl",name:"Chile"},
{id:"cn",name:"China"},
{id:"co",name:"Colombia"},
{id:"cg",name:"Congo"},
{id:"cd",name:"Congo DRC"},
{id:"cr",name:"Costa Rica"},
{id:"ci",name:"Cote d'Ivoire"},
{id:"hr",name:"Croatia"},
{id:"cz",name:"Czech Republic"},
{id:"dk",name:"Denmark"},
{id:"do",name:"Dominican Republic"},
{id:"ec",name:"Ecuador"},
{id:"eg",name:"Egypt"},
{id:"ee",name:"Estonia"},
{id:"et",name:"Ethiopia"},
{id:"fi",name:"Finland"},
{id:"fr",name:"France"},
{id:"ga",name:"Gabon"},
{id:"ge",name:"Georgia"},
{id:"de",name:"Germany"},
{id:"gh",name:"Ghana"},
{id:"gr",name:"Greece"},
{id:"gt",name:"Guatemala"},
{id:"hu",name:"Hungary"},
{id:"in",name:"India"},
{id:"id",name:"Indonesia"},
{id:"iq",name:"Iraq"},
{id:"ie",name:"Ireland"},
{id:"il",name:"Israel"},
{id:"it",name:"Italy"},
{id:"jp",name:"Japan"},
{id:"jo",name:"Jordan"},
{id:"kz",name:"Kazakhstan"},
{id:"ke",name:"Kenya"},
{id:"kw",name:"Kuwait"},
{id:"kg",name:"Kyrgyzstan"},
{id:"la",name:"Laos"},
{id:"lv",name:"Latvia"},
{id:"lt",name:"Lithuania"},
{id:"my",name:"Malaysia"},
{id:"ml",name:"Mali"},
{id:"mt",name:"Malta"},
{id:"mr",name:"Mauritania"},
{id:"mu",name:"Mauritius"},
{id:"mx",name:"Mexico"},
{id:"md",name:"Moldova"},
{id:"mn",name:"Mongolia"},
{id:"ma",name:"Morocco"},
{id:"mz",name:"Mozambique"},
{id:"mm",name:"Myanmar"},
{id:"na",name:"Namibia"},
{id:"np",name:"Nepal"},
{id:"nl",name:"Netherlands"},
{id:"nz",name:"New Zealand"},
{id:"ni",name:"Nicaragua"},
{id:"ne",name:"Niger"},
{id:"ng",name:"Nigeria"},
{id:"no",name:"Norway"},
{id:"pk",name:"Pakistan"},
{id:"ps",name:"Palestine"},
{id:"pa",name:"Panama"},
{id:"pg",name:"Papua New Guinea"},
{id:"py",name:"Paraguay"},
{id:"pe",name:"Peru"},
{id:"ph",name:"Philippines"},
{id:"pl",name:"Poland"},
{id:"pt",name:"Portugal"},
{id:"qa",name:"Qatar"},
{id:"ro",name:"Romania"},
{id:"ru",name:"Russia"},
{id:"rw",name:"Rwanda"},
{id:"sa",name:"Saudi Arabia"},
{id:"sn",name:"Senegal"},
{id:"rs",name:"Serbia"},
{id:"sl",name:"Sierra Leone"},
{id:"sg",name:"Singapore"},
{id:"sk",name:"Slovakia"},
{id:"za",name:"South Africa"},
{id:"kr",name:"South Korea"},
{id:"es",name:"Spain"},
{id:"lk",name:"Sri Lanka"},
{id:"se",name:"Sweden"},
{id:"ch",name:"Switzerland"},
{id:"tw",name:"Taiwan"},
{id:"tz",name:"Tanzania"},
{id:"th",name:"Thailand"},
{id:"gm",name:"The Gambia"},
{id:"tg",name:"Togo"},
{id:"tn",name:"Tunisia"},
{id:"tr",name:"Turkey"},
{id:"ug",name:"Uganda"},
{id:"ua",name:"Ukraine"},
{id:"ae",name:"United Arab Emirates"},
{id:"gb",name:"United Kingdom"},
{id:"us",name:"United States"},
{id:"uy",name:"Uruguay"},
{id:"ve",name:"Venezuela"},
{id:"vn",name:"Vietnam"},
{id:"ye",name:"Yemen"},
{id:"zm",name:"Zambia"},
{id:"zw",name:"Zimbabwe"}];
|
import React from "react";
import { HomeContainer } from "./home.styles";
import HomeMenu from "../../components/home-menu/home-menu.component";
const Home = () => (
<HomeContainer>
<HomeMenu />
</HomeContainer>
);
export default Home;
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
angular.module('actorFinderApp', ['ngResource'],
function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
}).factory('Resource', ['$resource',
function ($resource) {
return {
actors: $resource('api/actor/:id', {id: '@id'}),
movies: $resource('api/movie/:id', {id: '@id'}),
tvShow: $resource('api/tv/:id', {id: '@id'}),
search: $resource('api/search', {}, {find: {method: 'POST', params: {data: 0}}})
};
}])
//do another factory to sync data through all controllers
|
import ItemsOption from './diagram.items_option';
class NodesOption extends ItemsOption {
_getKeyExpr() {
return this._diagramWidget._createOptionGetter('nodes.keyExpr');
}
_getItemsExpr() {
return this._diagramWidget._createOptionGetter('nodes.itemsExpr');
}
_getContainerChildrenExpr() {
return this._diagramWidget._createOptionGetter('nodes.containerChildrenExpr');
}
}
export default NodesOption; |
var express = require("express");
var router = express.Router();
var mongo = require("../../connection");
var md5 = require('md5');
router.post("/", async function (req, res) {
const db1 = mongo.get().collection("user");
var result = {
status:'',
role:'',
uname:''
};
var ar = await db1.find({ _id: req.body.USER_ID, PASSWORD: md5(req.body.PASSWORD) }).toArray();
console.log(ar)
if (ar.length > 0) {
result.status = 1;
result.role = ar[0].ROLE;
result.uname=ar[0].FIRST_NAME+" "+ar[0].LAST_NAME;
console.log(result);
res.send(result);
}
else {
result.status = 2;
console.log(result);
res.send(result);
}
});
// router.get("/facultyCheck", async function (req, res) {
// console.log(req.body)
// const db1 = mongo.get().collection("user");
// db1.find({}).toArray(function (err, result) {
// if (err) console.log(err);
// else res.send(result);
// });
// });
module.exports = router;
|
import React, { Component } from 'react';
import styles from '../public/index.sass';
import styles2 from '../public/carousel.css';
import { Link } from 'react-router-dom';
import emblem_iphone from '../public/img/emblem_iphone_mobile.jpg';
import menuIcon from '../public/img/menuIcon.jpg';
import emblemIcon from '../public/img/emblemIcon.jpg';
import wireframeTed from '../public/img/wireframeTed.jpg';
import coach_carter from '../public/img/coach_carter.jpg';
import hot_model from '../public/img/hot_model.jpg';
import scholasticKid from '../public/img/scholasticKid.jpg';
import pharamIpads from '../public/img/pharamIpads.jpg';
import imac from '../public/img/imac.jpg';
import slide1 from '../public/img/slide1.jpg';
import slide2 from '../public/img/slide2.jpg';
import slide3 from '../public/img/slide3.jpg';
import slide4 from '../public/img/slide4.jpg';
import slide5 from '../public/img/slide5.jpg';
import { Carousel } from 'react-responsive-carousel';
class DemoCarousel extends React.Component {
render() {
return (
<Carousel centerMode centerSlidePercentage={50} emulateTouch
showStatus={false} showThumbs={false} infiniteLoop={true} >
<div>
<img src={wireframeTed} />
<Link to="/accenture" className=""><p className="legend"><i class="zmdi zmdi-time-interval zmdi-hc-2x"></i></p></Link>
</div>
<div>
<img src={coach_carter} />
<Link to="/hilfiger" className=""><p className="legend"><i class="zmdi zmdi-time-interval zmdi-hc-2x"></i></p></Link>
</div>
<div>
<img src={hot_model} />
<Link to="/magnetique" className=""><p className="legend"><i class="zmdi zmdi-time-interval zmdi-hc-2x"></i></p></Link>
</div>
<div>
<img src={scholasticKid} />
<Link to="/scholastic" className=""><p className="legend"><i class="zmdi zmdi-time-interval zmdi-hc-2x"></i></p></Link>
</div>
<div>
<img src={pharamIpads} />
<Link to="/precision" className=""><p className="legend"><i class="zmdi zmdi-time-interval zmdi-hc-2x"></i></p></Link>
</div>
<div>
<img src={imac} />
<Link to="/real" className=""><p className="legend"><i class="zmdi zmdi-time-interval zmdi-hc-2x"></i></p></Link>
</div>
</Carousel>
);
}
};
class Slideshow extends React.Component {
render() {
return (
<Carousel showThumbs={false} infiniteLoop={true}>
<div>
<img src={slide1} />
<p className="legend"></p>
</div>
<div>
<img src={slide2} />
<p className="legend"></p>
</div>
<div>
<img src={slide3} />
<p className="legend"></p>
</div>
<div>
<img src={slide4} />
<p className="legend"></p>
</div>
<div>
<img src={slide5} />
<p className="legend"></p>
</div>
</Carousel>
);
}
};
class Home extends React.PureComponent {
constructor(props) {
super(props);
}
render() {
return(
<div className="home">
<div className="landingImg">
<div className="landingTxt">
<h2>I Design & Build Digital Experience to Help Brands Grow</h2>
<p> My name is Todd Crawford, I'm UI/UX Designer and Entrepreneur with more than 7+
years of Experience. I specialized with Web and Mobile Projects</p>
</div>
</div>
<div className="myStory">
<div className="storyContainer">
<h1>A GUY TO WATCH</h1>
<p>Comprehensive experience in designing within the digital space, working
with high-profile clients to increase engagement & build revenue.</p>
</div>
<div className="storyButton">
<button>MY STORY</button>
</div>
</div>
<div className="carAdjust"><DemoCarousel /></div>
<div className="carAdjust2"><Slideshow /></div>
<div className="contactReviews">
<li className="contactMe pure-u-md-1-2">
<Link to="/contact" className=""><h2>CONTACT ME</h2></Link>
<Link to="/contact" className=""><h3>Tell me about your next big idea!</h3></Link>
<Link to="/contact" className=""><i className="arrowButton zmdi zmdi-arrow-right"></i></Link>
</li>
<li className="kindWords pure-u-md-1-2">
<Link to="/testimonials" className=""><h2>KIND WORDS FROM</h2></Link>
<Link to="/testimonials" className=""><h2>PAST CLIENTS</h2></Link>
<Link to="/testimonials" className=""><i className="arrowButton zmdi zmdi-arrow-right"></i></Link>
</li>
</div>
<div className="socialFooter">
<span>© TODD DAVID CRAWFORD. ALL RIGHTS RESERVED.</span>
<ul className="socialIcons">
<a href="https://www.facebook.com/TdcGraphicDesign/" className=""><i className="zmdi zmdi-facebook"></i></a>
<a href="https://www.linkedin.com/in/todd-crawford-a706814/" className=""><i className="zmdi zmdi-linkedin"></i></a>
<a href="https://www.behance.net/ToddCrawford" className=""><i className="zmdi zmdi-behance"></i></a>
</ul>
</div>
</div>
);
}
}
export default Home;
|
export const TOGGLE_GRID = 'TOGGLE_GRID';
export const TOGGLE_POINT = 'TOGGLE_POINT';
|
import Rx from 'rxjs/Rx'
import { createSubscriber } from '../utils'
/* -- Part 1 --
const
simple$ = new Rx.Observable(observer => {
console.log('Generating observable...')
setTimeout(() => {
observer.next('An Item!')
setTimeout(() => {
observer.next('Another Item!')
observer.complete()
}, 1000)
}, 1000)
}),
error$ = new Rx.Observable(observer => {
observer.error(new Error('Boom!!'))
})
error$.subscribe(
item => console.log('One', item),
err => console.log('ERROR one:', err),
() => console.log('DONE one')
)
setTimeout(() => {
simple$.subscribe({
'next': item => console.log('Two', item),
'error': err => console.log('ERROR tow:', err),
'complete': () => console.log('DONE two')
})
}, 3000)
*/
const
createInterval$ = time => new Rx.Observable(observer => {
let
index = 0
const
interval = setInterval(() => {
index += 1
console.log('Generating', index)
observer.next(index)
}, time)
return () => clearInterval(interval)
}),
take$ = (sourceObservable$, amount) => new Rx.Observable(observer => {
let
count = 0
const
innerSubscription = sourceObservable$.subscribe(
item => {
observer.next(item)
count += 1
if(count >= amount) {
observer.complete()
}
},
observer.error,
observer.complete
)
return () => innerSubscription.unsubscribe()
}),
everySecond = createInterval$(1000),
firstFiveSeconds = take$(everySecond, 5),
subscription = firstFiveSeconds.subscribe(createSubscriber('one'))
// setTimeout(() => {
// subscription.unsubscribe()
// }, 3500)
|
import React, { Component } from 'react';
import './SettingsForm.css';
export default class SettingsForm extends Component {
state = {
label: ''
};
onLabelChange = (e) => {
this.setState({
label: e.target.value
});
};
onSubmit = (e) => {
e.preventDefault();
this.props.onItemAdded(this.state.label);
this.setState({
label: ''
});
};
render() {
return (
<form className="settings-form d-flex"
onSubmit={this.onSubmit}>
<label>
PROGRAMME
<select className="form-control"
onChange={this.onLabelChange}
value={this.state.value}>
<option value="cotton">Cotton</option>
<option value="easy-care">Easy-care</option>
<option value="mixed">Mixed farics</option>
<option value="delicates">Delicates</option>
<option value="woollens">Woollens</option>
</select>
</label>
<label>
TIMER
<select className="form-control"
onChange={this.onLabelChange}
value={this.state.value}>
<option value="30m">30 min</option>
<option value="45m">45 min</option>
<option value="60m">60 min</option>
<option value="90m ">90 min</option>
</select>
</label>
<label>
TEMPERATURE
<select className="form-control"
onChange={this.onLabelChange}
value={this.state.value}>
<option value="20c">20°C</option>
<option value="30c">30°C</option>
<option value="45c">40°C</option>
<option value="60c">60°C</option>
<option value="90c">90°C</option>
</select>
</label>
<button className="btn btn-outline-secondary">
Save
</button>
</form>
)
}
} |
import axios from 'axios'
export const fetchTeams = (campaigns) => (dispatch) => {
dispatch({
type: 'FETCH_TEAMS'
})
let endpoint = `${process.env.SUPPORTER_URL}/search/pages_totals.json`
let params = {
campaign_id: campaigns,
group_by: 'teams',
limit: 5
}
return axios
.get(endpoint, { params })
.then(response => response.data.results)
.then(data => dispatch(fetchTeamsSuccess(data)))
.catch(error => dispatch(fetchTeamsError(error)))
}
export const clearTeams = () => (dispatch) => {
dispatch({
type: 'CLEAR_TEAMS'
})
}
const fetchTeamsSuccess = data => ({
type: 'FETCH_TEAMS_SUCCESS',
payload: {
data
}
})
const fetchTeamsError = error => ({
type: 'FETCH_TEAMS_ERROR',
payload: {
error
}
})
|
export default [ '$locationProvider', function( $locationProvider ) {
$locationProvider.html5Mode( true );
}];
|
function concat (arrOne, arrTwo) {
var arr = [];
for (i = 0; i < arrOne.length; i++) {
arr.push(arrOne[i]);
}
for (x = 0; x < arrTwo.length; x++) {
arr.push(arrTwo[x]);
}
return arr;
} |
import React from 'react';
import './BuzzerPopup.css';
const buzzerPopup = (props) => (
props.can_buzz ? null
:
<div className={'buzzer'} style={{
color: props.buzzer_side === 'red' ? 'white' : 'black',
background: props.buzzer_side === 'red' ? 'lightgreen' : 'lightskyblue'}}>
<h1>TEAM {props.buzzer_side === 'red' ? 'GREEN' : 'BLUE'}</h1>
</div>
);
export default buzzerPopup; |
import Router from "koa-router";
import config from "../../config";
const { modules } = config;
export default function initModules(app) {
const modulesDirs = modules.map(name => `${__dirname}/${name}`);
modulesDirs.forEach(mod => {
const router = require(`${mod}/router`); // eslint-disable-line import/no-dynamic-require
const routes = router.default;
const baseUrl = router.baseUrl;
const instance = new Router({ prefix: baseUrl });
routes.forEach(config => {
const { method = "", route = "", handlers = [] } = config;
const lastHandler = handlers.pop();
instance[method.toLowerCase()](route, ...handlers, async ctx => {
const result = await lastHandler(ctx);
return result;
});
app.use(instance.routes()).use(instance.allowedMethods());
});
});
}
|
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path:'/',
redirect:'/home',
},
{
path:'/home',
name:'home',
component:()=>import("../views/home/home.vue"),
},
{
path:'/category',
name:'category',
component:()=>import("../views/category/category.vue")
},
{
path:'/shopping',
name:'shopping',
component:()=>import("../views/shopping/shopping.vue")
},
{
path:'/profile',
name:'profile',
component:()=>import("../views/profile/profile.vue")
},
{
path:'/detail/:id',
name:'detail',
component:()=>import("../views/detail/detail.vue")
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
|
function initMap () {
var location = {lat: 38.871857, lng: -77.056267};
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 14,
center: location
});
}
$(window).scroll(function(){
if($(this).scrollTop() > 100){
$('#scroll').fadeIn();
}else{
$('#scroll').fadeOut();
}
});
$('#scroll').click(function(){
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
});
$(document).ready(function(){
$(window).scroll(function(){
if($(this).scrollTop() > 100){
$('#scroll').fadeIn();
}else{
$('#scroll').fadeOut();
}
});
$('#scroll').click(function(){
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
});
}); |
isc.TabSet.create({
ID: "SearchTabSet",
// width: "100%",
// height: "30%",
tabs: [{
id: "search",
title: "search",
pane: crmMainSearchForm
},{
id: "DailyReportTabset",
title: "Daily Report",
pane: dailyReport ,
}]
}); |
const _ = function (obj) {
if (Object.getPrototypeOf(obj) === _) { return obj }
if (!(this instanceof _)) { return new _(obj) }
var o = Object.create(_)
o._wrapped = obj
return o
}
// Current version.
_.version = '0.0.1'
module.exports = _
// 常用函数
_.noop = function () {}
_.identity = function (x) { return x }
_.constant = function (val) { return function () { return val } }
// TODO: _.times
_.times = function (t) {}
_.random = function (min, max) {
if (max == null) {
max = min
min = 0
}
return min + Math.floor(Math.random() * (max - min + 1))
}
// TODO: _.mixin
let idCounter = 0
_.uniqueId = function (prefix) {
var id = ++idCounter + ''
return prefix ? prefix + id : id
}
const toString = ({}).toString
// TODO: to support OO-style
// TODO: to support array-like object
// 类型判断
_.isType = type => val => toString.call(val) === '[object ' + type + ']'
_.isObject = _.isType('Object')
_.isFunc = _.isType('Function')
_.isArray = _.isType('Array')
_.isNumber = _.isType('Number')
_.isString = _.isType('String')
_.isBoolean = _.isType('Boolean')
_.isNull = _.isType('Null')
_.isUndefined = _.isType('Undefined')
_.first = _.head = _.take = function (arr, n = null) {
if (arr === null || arr.length < 0) { return void 0 }
if (n === null) { return arr[0] }
if (n <= 0) { return [] }
return arr.slice(0, n)
}
_.rest = _.tail = _.drop = function (arr, n = 1) {
return arr.slice(n)
}
_.map = function (arr, fn = _.identity, cxt) {
if (arr === null) return []
let result = []
for (let i = 0; i < arr.length; i++) {
result[i] = fn.bind(cxt)(arr[i])
}
return result
}
_.initial = function (arr, n = arr.length - 1) {
return n <= arr.length ? arr.slice(0, n) : []
}
_.last = function (arr, n) {
if (arr === null || arr.length === 0) { return void 0 }
const len = arr.length
if (n === undefined) { return arr[len - 1] }
if (n <= 0) { return [] }
if (n > len) { return arr.slice() }
return arr.slice(n - 1, len)
}
_.compact = function (arr) {
const result = []
for (let i = 0, n = arr.length; i < n; i++) {
if (arr[i]) { result.push(arr[i]) }
}
return result
}
_.flatten = function flatten (input, shallow = false, output = []) {
input = input || []
for (let i = 0, n = input.length; i < n; i++) {
if (_.isArray(input[i])) {
shallow ? output.push(...input[i]) : flatten(input[i], shallow, output)
} else {
output.push(input[i])
}
}
return output
}
_.without = function (arr, ...args) {
const result = []
for (var i = 0, n = arr.length; i < n; i++) {
if (!_.contains(args, arr[i])) {
result.push(arr[i])
}
}
return result
}
_.contains = function (arr, val, cb = _.identity) {
for (var i = 0, n = arr.length; i < n; i++) {
if (cb(arr[i]) === cb(val)) {
return true
}
}
return false
}
// TODO: support large-scale array
_.sortedIndex = function (arr, val, it = _.identity, cxt) {
const fn = _.isFunc(it) ? it : x => (x[it])
for (var i = 0, n = arr.length; i < n; i++) {
if (fn.call(cxt, arr[i]) >= fn.call(cxt, val)) { return i }
}
return -1
}
_.uniq = function (arr, isSorted, it, cxt) {
// 重载
if (!_.isBoolean(isSorted)) {
cxt = it
it = isSorted
isSorted = false
}
const _it = _.isString(it) ? x => x[it] : it
const result = []
for (let i = 0, n = arr.length; i < n; i++) {
if (!_.contains(result, arr[i], _it)) {
result.push(arr[i])
}
}
return result
}
_.intersection = function (arr1, arr2) {
arr1 = arr1 || []
arr2 = arr2 || []
const result = []
for (let i = 0, n = arr1.length; i < n; i++) {
if (_.contains(arr2, arr1[i]) && !_.contains(result, arr1[i])) {
result.push(arr1[i])
}
}
return result
}
_.union = function (...args) {
const result = []
for (let i = 0, n = args.length; i < n; i++) {
for (let j = 0, m = args[i].length; j < m; j++) {
if (!_.contains(result, args[i][j])) {
result.push(args[i][j])
}
}
}
return result
}
_.difference = function (arr, ...args) {
const result = []
for (let i = 0, n = arr.length; i < n; i++) {
if (!_.contains(result, arr[i]) && args.every(function (item) { return !_.contains(item, arr[i]) })) {
result.push(arr[i])
}
}
return result
}
_.zip = function (...args) {
if (args.length === 1 && args[0] === null) return []
const result = []
const len = Math.max(...args.map(x => x.length))
for (let i = 0; i < len; i++) {
result.push(args.map(x => x[i]))
}
return result
}
_.unzip = function (arr) {
arr = arr || []
const result = []
const len = Math.max(...arr.map(x => x.length))
for (let i = 0; i < len; i++) {
result[i] = arr.map(x => x[i])
}
return result
}
_.object = function (arr1, arr2) {
const result = {}
if (arr2) {
arr1.forEach(function (item, index) { result[item] = arr2[index] })
} else {
arr1.forEach(function (item, index) { result[item[0]] = item[1] })
}
return result
}
_.indexOf = function (arr, val, fromIndex = false) {
return _.isBoolean(fromIndex)
? (fromIndex ? bSearch(arr, val, 0, arr.length - 1) : search(arr, val))
: (search(arr, val, fromIndex))
}
function bSearch (arr, val, sm, lg) {
if (sm > lg) { return -1 }
if (lg === sm) { return arr[sm] === val ? sm : -1 }
const md = Math.floor((sm + lg) / 2)
return arr[md] >= val ? bSearch(arr, val, sm, md) : bSearch(arr, val, md + 1, lg)
}
function search (arr, val, fromIndex = 0) {
if (fromIndex < 0) { fromIndex = arr.length + fromIndex }
for (let i = fromIndex, n = arr.length; i < n; i++) {
// 需要检查NaN,NaN !== NaN
if (arr[i] === val || (arr[i] !== arr[i] && val !== val)) { return i } // eslint-disable-line
}
return -1
}
_.lastIndexOf = function (arr, val, fromIndex) {
if (fromIndex === 0) { return arr[0] === val ? 0 : -1 }
const falsy = [void 0, '', 0, false, NaN, null, void 0]
if (_.contains(falsy, fromIndex)) { fromIndex = arr.length }
if (!_.isNumber(fromIndex)) { fromIndex = arr.length }
if (fromIndex < 0) { fromIndex = arr.length + fromIndex }
for (let i = fromIndex; i >= 0; i--) {
if (arr[i] === val || (arr[i] !== arr[i] && val !== val)) { // eslint-disable-line
return i
}
}
return -1
}
_.findLastIndex = function (objects, fn, cxt) {
objects = objects || []
let _fn = fn
if (_.isString(fn)) { _fn = x => x[fn] }
for (var i = objects.length - 1; i >= 0; i--) {
if (_fn.call(cxt, objects[i], i, objects)) {
return i
}
}
return -1
}
_.range = function (...args) {
const result = []
let start, end, step
if (args.length === 1) { start = 0; end = args[0]; step = start <= end ? 1 : -1 }
if (args.length > 1) { start = args[0]; end = args[1]; step = args[2] || (start <= end ? 1 : -1) }
let fn = (start <= end) ? (s, e) => (s < e) : (s, e) => (s > e)
for (let i = start; fn(i, end); i += step) {
result.push(i)
}
return result
}
_.chunk = function (arr, cnt) {
const result = []
if (cnt == null || cnt < 1) return result
for (let i = 0, n = arr.length; i < n; i += cnt) {
result.push(arr.slice(i, i + cnt))
}
return result
}
// functions def:
_.bind = function (fn, cxt, ...args) {
// if (!_.isFunc(fn)) { throw new TypeError('Bind must be called on a function') }
function bound (..._args) {
const _cxt = typeof new.target !== 'undefined' ? this : cxt
return fn.apply(_cxt, args.concat(_args))
}
bound.prototype = Object.create(fn.prototype)
return bound
}
_.partial = function (fn, ...args) {
function _partial (..._args) {
const result = []
const m = args.length
let n = _args.length
for (let i = 0, j = 0, k = 0; i < m || i < m + n - k; i++) {
if (args[i] === _.partial.placeholder) {
result[i] = _args[j++]
k++
} else if (i >= m) {
result[i] = j < n ? _args[j++] : void 0
} else {
result[i] = args[i]
}
}
return fn.apply(this, result)
}
_partial.prototype = Object.create(fn.prototype)
return _partial
}
// set default placeholder to _
_.partial.placeholder = _
_.bindAll = function (obj, ...args) {
args.forEach(function (key) {
obj[key] = _.bind(obj[key], obj)
})
}
_.memoize = function (fn, h) {
function memoize (...args) {
const key = h && h(...args) || args.join()
const cached = key in memoize.cache && memoize.cache.hasOwnProperty(key)
/* eslint no-return-assign: 0 */
return cached ? memoize.cache[key] : memoize.cache[key] = fn.apply(null, args)
}
memoize.cache = {}
return memoize
}
_.delay = function (fn, timeout, ...args) {
return setTimeout(() => { fn(...args) }, timeout)
}
_.defer = function (fn, ...args) {
return _.delay(fn, 0, ...args)
}
_.now = Date.now
// TODO: fix throttle
// _.throttle = function (fn, wait) {
// let previous = 0
// let timeout = null
// let result
// return function _throttle (...args) {
// if (!previous) { previous = _.now(); return fn(...args) }
// const now = _.now()
// const left = wait - (now - previous)
// if (left <= 0 || left > wait) {
// timeout && clearTimeout(timeout)
// timeout = null
// previous = _.now()
// result = fn(...args)
// } else if (!timeout) {
// timeout = _.delay(fn, left, ...args)
// }
// return result
// }
// }
_.throttle = function (func, wait, options) {
var context, args, result
var timeout = null
// 上次执行时间点
var previous = 0
if (!options) options = {}
// 延迟执行函数
var later = function () {
// 若设定了开始边界不执行选项,上次执行时间始终为0
previous = options.leading === false ? 0 : _.now()
timeout = null
result = func.apply(context, args)
if (!timeout) context = args = null
}
function throttled () {
var now = _.now()
// 首次执行时,如果设定了开始边界不执行选项,将上次执行时间设定为当前时间。
if (!previous && options.leading === false) previous = now
// 延迟执行时间间隔
var remaining = wait - (now - previous)
context = this
args = arguments
// 延迟时间间隔remaining小于等于0,表示上次执行至此所间隔时间已经超过一个时间窗口
// remaining大于时间窗口wait,表示客户端系统时间被调整过
if (remaining <= 0 || remaining > wait) {
clearTimeout(timeout)
timeout = null
previous = now
result = func.apply(context, args)
if (!timeout) context = args = null
// 如果延迟执行不存在,且没有设定结尾边界不执行选项
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining)
}
return result
}
throttled.cancel = function () {
clearTimeout(timeout)
previous = 0
timeout = context = args = null
}
return throttled
}
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function (func, wait, immediate) {
var timeout, result
var later = function (context, args) {
timeout = null
if (args) result = func.apply(context, args)
}
var debounced = _.restArgs(function (args) {
if (timeout) clearTimeout(timeout)
if (immediate) {
var callNow = !timeout
timeout = setTimeout(later, wait)
if (callNow) result = func.apply(this, args)
} else {
timeout = _.delay(later, wait, this, args)
}
return result
})
debounced.cancel = function () {
clearTimeout(timeout)
timeout = null
}
return debounced
}
_.restArgs = function (func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex
return function () {
var length = Math.max(arguments.length - startIndex, 0)
var rest = Array(length)
var index = 0
for (; index < length; index++) {
rest[index] = arguments[index + startIndex]
}
switch (startIndex) {
case 0: return func.call(this, rest)
case 1: return func.call(this, arguments[0], rest)
case 2: return func.call(this, arguments[0], arguments[1], rest)
}
var args = Array(startIndex + 1)
for (index = 0; index < startIndex; index++) {
args[index] = arguments[index]
}
args[startIndex] = rest
return func.apply(this, args)
}
}
_.once = function (fn) {
let result
let ret = function () {
if (!ret.__called) {
ret.__called = true
return result = fn()
}
return result
}
return ret
}
_.wrap = function (func, wrapper) {
return _.partial(wrapper, func)
}
_.negate = function (predicate) {
return function () {
return !predicate.apply(this, arguments)
}
}
_.compose = function () {
var args = arguments
var start = args.length - 1
return function () {
var i = start
var result = args[start].apply(this, arguments)
while (i--) result = args[i].call(this, result)
return result
}
}
// Returns a function that will only be executed on and after the Nth call.
_.after = function (times, func) {
return function () {
if (--times < 1) {
return func.apply(this, arguments)
}
}
}
// Returns a function that will only be executed up to (but not including) the Nth call.
_.before = function (times, func) {
var memo
return function () {
if (--times > 0) {
memo = func.apply(this, arguments)
}
if (times <= 1) func = null
return memo
}
}
// TODO: _.iteratee
// _.iteratee = builtinIteratee = function(value, context) {
// return cb(value, context, Infinity)
// }
|
var myMoney = 10;
if (myMoney > 9) {
var taxHaven = myMoney * myMoney;
}
console.log(taxHaven); |
import React, { Fragment } from 'react';
import { ActivityIndicator } from 'react-native';
import { Camera as ExpoCamera, Permissions, ImageManipulator } from 'expo';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { DropDownHelper } from '../../utils/helpers/dropdown';
import {
CameraButtonsContainer,
CloseButton,
FlipButton,
TakeButton,
LoadingContainer
} from './styles';
import { Container } from '../container';
export class Camera extends React.Component {
state = {
hasCameraPermission: null,
type: ExpoCamera.Constants.Type.back,
loading: true
};
async componentDidMount() {
const { status: status_camera_roll } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
const { status: status_camera } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasCameraPermission: status_camera === 'granted' && status_camera_roll === 'granted' });
}
render() {
const { hasCameraPermission, type, loading } = this.state;
const { onCloseButton, onTakeButton } = this.props;
// if (hasCameraPermission === null) {
// DropDownHelper.alert(
// 'error',
// 'Error',
// 'Ocurrió un error al intentar iniciar la cámara. Comprobá que los permisos estén activados.'
// );
// }
if (hasCameraPermission === false) {
DropDownHelper.alert(
'error',
'Error',
'Ocurrió un error al intentar iniciar la cámara. Comprobá que los permisos estén activados.'
);
}
return (
<Container>
<ExpoCamera
ref={(ref) => { this.camera = ref; }}
style={{ flex: 1 }}
type={type}
onCameraReady={() => this.setState({ loading: false })}
>
<CameraButtonsContainer>
<FlipButton
onPress={() => {
this.setState({
type:
type === ExpoCamera.Constants.Type.back
? ExpoCamera.Constants.Type.front
: ExpoCamera.Constants.Type.back
});
}}
>
<MaterialCommunityIcons name="reload" color="white" size={40} />
</FlipButton>
<TakeButton
onPress={async () => {
if (this.camera) {
this.setState({ loading: true });
const photo = await this.camera.takePictureAsync();
const resizedPhoto = await ImageManipulator.manipulateAsync(
photo.uri,
[{ resize: { width: 700 } }],
{ compress: 0.6, format: 'jpg', base64: false }
);
this.setState({ loading: false });
onTakeButton(resizedPhoto);
}
}}
>
<MaterialCommunityIcons
name="circle-slice-8"
color="white"
size={80}
/>
</TakeButton>
<CloseButton onPress={onCloseButton}>
<MaterialCommunityIcons name="close" color="white" size={40} />
</CloseButton>
</CameraButtonsContainer>
</ExpoCamera>
</Container>
);
}
}
|
const TasksModels = require('../models/tasks');
const middlewares = require('./middlewares');
const getAll = async () => {
const tasks = await TasksModels.getAll();
return tasks;
};
const getAllAlphabetic = async () => {
const tasks = await TasksModels.getAllAlphabetic();
return tasks;
};
const getAllStatus = async () => {
const tasks = await TasksModels.getAllStatus();
return tasks;
};
const create = async (newTask) => {
const { task, status } = newTask;
const isValid = middlewares.validateEntries(task, status);
if (isValid) return isValid;
const createdTask = await TasksModels.create(newTask);
const taskFromId = await TasksModels.getById(createdTask.insertedId);
return taskFromId;
};
const exclude = async (id) => {
const isValid = middlewares.validateId(id);
if (isValid) return isValid;
const task = await TasksModels.exclude(id);
if (!task) {
return {
code: 404,
message: 'There is no match with this ID',
};
}
return task;
};
const update = async (id, task, status) => {
const isValid = middlewares.validateId(id);
if (isValid) return isValid;
const entries = middlewares.validateEntries(task, status);
if (entries) return entries;
const updatedTask = await TasksModels.update(id, task, status);
if (!updatedTask) {
return {
code: 404,
message: 'There is no match with this ID',
};
}
return updatedTask;
};
module.exports = {
getAll,
getAllAlphabetic,
getAllStatus,
exclude,
create,
update,
};
|
var app = getApp()
// pages/stepThird/stepThird.js
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
nextStep: function() {
wx.navigateTo({
url: '../stepFourth/stepFourth',
success: function(res) {},
})
// var labor = app.globalData.labor;
// console.log(labor)
},
changeColor: function () {
app.globalData.labor = 1;
var Color = this.data.style1 == '#addf89' ? 'background-color: #fff;' : 'background-color: #addf89';
var Color1 = this.data.style1x == '#addf89' ? 'color: #595959;' : 'color: #fff;';
var Color2 = this.data.style1y == '#addf89' ? 'color: #999;' : 'color: #fff;';
var Colora = this.data.style1 == '#addf89' ? 'background-color: #addf89 ;': 'background-color: #fff';
var Colorb = this.data.style1x == '#addf89' ? 'color: #fff;' : 'color: #595959;';
var Colorc = this.data.style1y == '#addf89' ? 'color: #fff;' : 'color: #999;';
// 设置背景颜色数据
this.setData({
style1: Color,
style1x: Color1,
style1y: Color2,
style2: Colora,
style2x: Colorb,
style2y: Colorc,
style3: Colora,
style3x: Colorb,
style3y: Colorc,
});
},
changeColor1: function () {
app.globalData.labor = 2;
var Color = this.data.style2 == '#addf89' ? 'background-color: #fff;' : 'background-color: #addf89';
var Color1 = this.data.style2x == '#addf89' ? 'color: #595959;' : 'color: #fff;';
var Color2 = this.data.style2y == '#addf89' ? 'color: #999;' : 'color: #fff;';
var Colora = this.data.style1 == '#addf89' ? 'background-color: #addf89 ;' : 'background-color: #fff';
var Colorb = this.data.style1x == '#addf89' ? 'color: #fff;' : 'color: #595959;';
var Colorc = this.data.style1y == '#addf89' ? 'color: #fff;' : 'color: #999;';
// 设置背景颜色数据
this.setData({
style2: Color,
style2x: Color1,
style2y: Color2,
style1: Colora,
style1x: Colorb,
style1y: Colorc,
style3: Colora,
style3x: Colorb,
style3y: Colorc,
});
},
changeColor2: function () {
app.globalData.labor = 3;
var Color = this.data.style3 == '#addf89' ? 'background-color: #fff;' : 'background-color: #addf89';
var Color1 = this.data.style3x == '#addf89' ? 'color: #595959;' : 'color: #fff;';
var Color2 = this.data.style3y == '#addf89' ? 'color: #999;' : 'color: #fff;';
var Colora = this.data.style1 == '#addf89' ? 'background-color: #addf89 ;' : 'background-color: #fff';
var Colorb = this.data.style1x == '#addf89' ? 'color: #fff;' : 'color: #595959;';
var Colorc = this.data.style1y == '#addf89' ? 'color: #fff;' : 'color: #999;';
// 设置背景颜色数据
this.setData({
style3: Color,
style3x: Color1,
style3y: Color2,
style1: Colora,
style1x: Colorb,
style1y: Colorc,
style2: Colora,
style2x: Colorb,
style2y: Colorc,
});
},
}) |
import React from "react";
import firebase from "firebase/app";
import "firebase/auth";
import { Link } from "react-router-dom";
import "../scss/signIn.scss";
import "../scss/mediaSignIn.scss";
function SignIn({ email, password, onPassword, onEmail, onLine }) {
let [errors, setErrors] = React.useState(null);
const handleChange = ({ target: { value, name } }) => {
name === "email" ? onEmail(value) : onPassword(value);
};
const signAccount = (e) => {
e.preventDefault();
firebase
.auth()
.signInWithEmailAndPassword(email.toString().trim(), password)
.then(() => {
onLine(true);
})
.catch(({ message }) => setErrors(message));
};
switch (errors) {
case "Access to this account has been temporarily disabled due to many failed login attempts. You can immediately restore it by resetting your password or you can try again later.":
errors =
"Доступ к этой учетной записи был временно отключен. Вы можете немедленно восстановить его, сбросив пароль, или можете повторить попытку позже.";
break;
case "There is no user record corresponding to this identifier. The user may have been deleted.":
errors = "Данного аккаунта не существует";
break;
case "The password is invalid or the user does not have a password.":
errors = "Вы ввели не правильный пароль";
break;
default:
}
return (
<main className="wrap">
<div className="login">
<form
action=""
className="login__form"
onSubmit={("return", signAccount)}
>
<p className="login__p">Авторизация на сайте</p>
{errors === null ? null : <p className="login__error"> {errors}</p>}
<label className="login__label">Email</label>
<input
type="email"
className="login__email"
placeholder="faruq123@example.com"
required
onChange={handleChange}
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"
name="email"
/>
<label className="login__label">Пароль</label>
<input
autoComplete="on"
type="password"
className="login__password"
placeholder="password"
required
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
onChange={handleChange}
name="password"
/>
<button type="submit" className="login__submit">
Войти на сайт
</button>
<Link to="/react-login/" className="login__register" onClick={onLine}>
Если у вас нету аккаунта нажмите здесь
</Link>
</form>
</div>
</main>
);
}
export default SignIn;
|
const {MongoClient}=require('mongodb')
const MONGO_URL='mongodb://localhost:27017';
const DB_NAME='tododb';
async function writeTasks(){
const client= await MongoClient.connect(MONGO_URL)
const tododb=client.db(DB_NAME)
const todos=tododb.collection('todos')
const result=await todos.insertMany([
{
task:'another task',
owner:'security'
},
{
task:'more tasks',
owner:'CEO'
},
{
task:'task will be done later',
owner:'manager'
},
{
task:'bonus tasks',
owner:'executive'
}
])
console.log(result)
}
writeTasks() |
import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { AtIcon } from 'taro-ui'
import PropTypes from 'prop-types'
import Item from './Item'
import './index.scss';
class OrderCell extends Component {
static propTypes = {
item: PropTypes.object,
handleClick: PropTypes.func
}
static defaultProps = {
item: {
qty: 0,
giftQty: 0,
MaterialPrice: 0,
DefaultPrice: 0,
amount: 0,
defaultAmount: 0,
remark: ''
}
}
handleClick = index => {
const { onHanleClick } = this.props
onHanleClick(index)
}
render() {
const { item, hasIcon = false, index, isShared = false } = this.props;
return (
<View className='order-cell'>
<View className='title'>
<Text>{item.MaterialName + ' '}</Text>
<Text style='font-size: 28rpx;'>{item.MaterialModel}</Text>
</View>
<View className='box'>
<View className='at-row'>
<View className='at-col at-col-12'>数 量:{Number(item.qty).toFixed(2)}公斤</View>
<View className='at-col at-col-12'>开单价:¥{Number(item.DefaultPrice).toFixed(4)}</View>
{/* <View className='at-col at-col-12'>结算价:¥{Number(item.MaterialPrice).toFixed(4)}</View> */}
<Item isShow={!isShared} title='结算价' num={item.MaterialPrice}></Item>
</View>
<View className='at-row at-row--wrap'>
<View className='at-col at-col-12'>其中赠品:{Number(item.giftQty).toFixed(2)}公斤</View>
<View className='at-col at-col-12'>开单金额:¥{Number(item.defaultAmount).toFixed(4)}</View>
{/* <View className='at-col at-col-12'>结算金额{Number(item.amount).toFixed(4)}</View> */}
<Item isShow={!isShared} title='结算金额' num={item.amount}></Item>
</View>
{hasIcon ? (
<View className='item-icon'>
<AtIcon onClick={this.handleClick.bind(this, index)} value='subtract-circle' size='30' color='#F00'></AtIcon>
</View>
) : null}
</View>
{item.remark ? (
<View className='at-row' style={{ marginTop: 10}}>
<View className='at-col at-col-24'>备 注:{item.remark}</View>
</View>
) : null
}
</View>
)
}
}
export default OrderCell
|
import React from 'react';
import MatchListItem from './match_list_item';
class MatchList extends React.Component {
constructor(props) {
super(props);
this.state = { matches: [] };
this.paginationInit();
}
paginationInit() {
this.offset = 0;
this.limit = 20;
}
componentDidMount() {
this.setState({matches: this.props.matches});
}
// Ensures component updates state when revisiting.
componentWillMount() {
if (this.props.matches.entries) {
// const entries = this.throttleEntries(this.props.matches.entries);
// this.updateMatches(entries);
}
}
componentWillReceiveProps(newProps) {
if (newProps.matches) {
}
}
updateMatches(entries) {
this.setState({matches: this.state.matches.concat(entries)});
}
//
// // Handles pagination. No need to hit DB for new summoners. All are retrieved
// // in initial call so pagination logic can be handled locally
// throttleEntries(entries){
// const offset = this.offset;
// const limit = this.limit;
// this.offset += 20;
// this.limit += 20;
// // return entries.slice(offset, limit);
// }
renderMatchListItems() {
if (!this.props.matches) {
return <div> spinner</div>;
} else {
return this.props.matches.map((match, idx) => {
const currentSummoner = match.participants[this.props.summoner.summoner_id];
return (
<MatchListItem
key={idx}
match={match}
summoner={this.props.summoner}/>
);
});
}
}
handleMoreButton() {
console.log("loading");
const summonerName = this.props.summoner.name;
this.offset += 20;
this.limit += 20;
this.props.fetchMatches(summonerName, this.offset, this.limit);
}
render () {
return (
<div className="match-wrapper">
{
this.renderMatchListItems()
}
<div className="next-button">
<button onClick={() => this.handleMoreButton()}>Show More</button>
</div>
</div>
);
}
}
export default MatchList;
|
function renderStudents(students) {
let studentsHTML = `
<div style="display: flex; flex-direction: column; align-items: center;">
<h1>Roll Call!</h1>
</div>
`
for (let i = 0; i < students.length; i++) {
if (students[i].isPresent) {
studentsHTML += `
<div style="display: flex; flex-direction: column; align-items: center;">
<div style="background-color: lightgreen; border: 1px solid black;margin: 10px; width: 250px;text-align: center;">
<h3>${students[i].name}</h3>
<div>Present</div>
</div>
</div>
`
} else {
studentsHTML += `
<div style="display: flex; flex-direction: column; align-items: center;">
<div style="background-color: orangered; border: 1px solid black;margin: 10px; width: 250px;text-align: center;">
<h3>${students[i].name}</h3>
<div>Absent</div>
</div>
</div>
`
}
}
return studentsHTML;
}
function students() {
var studentsAbstraction = [
{
name: "Kamilah",
isPresent: true
},
{
name: "Kim",
isPresent: true
},
{
name: "Stuart",
isPresent: false
},
{
name: "Ron",
isPresent: true
},
{
name: "Krissy",
isPresent: false
},
]
var contentEl = document.getElementById('content');
contentEl.innerHTML = renderStudents(studentsAbstraction);
} |
const msgerForm = get(".msger-inputarea");
const msgerInput = get(".msger-input");
const msgerChat = get(".msger-chat");
function Message(from, message) {
this.from = from;
this.message = message;
}
function Position(from, X, Y) {
this.from = from;
this.X = X;
this.Y = Y;
}
const BOT_IMG = "assets/player/bot/bot_50x50.png";
const BOT_NAME = "BOT";
const PERSON_NAME = "Player 1";
$(msgerForm).submit(function(event){
event.preventDefault();
const msgText = msgerInput.value;
if (!msgText) return;
websocketGame.socket.emit('chatMessage', new Message(myself, msgText));
console.log("Send message: " + msgText);
msgerInput.value = "";
});
function appendMessage(name, img, side, text) {
const msgHTML = `
<div class="msg ${side}-msg">
<div class="msg-img" style="background-image: url(${img})"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">${name}</div>
<div class="msg-info-time">${formatDate(new Date())}</div>
</div>
<div class="msg-text">${text}</div>
</div>
</div>
`;
msgerChat.insertAdjacentHTML("beforeend", msgHTML);
msgerChat.scrollTop += 500;
}
function botResponse(message) {
appendMessage(BOT_NAME, BOT_IMG, "bot", message, true);
}
// Utils
function get(selector, root = document) {
return root.querySelector(selector);
}
function formatDate(date) {
const h = "0" + date.getHours();
const m = "0" + date.getMinutes();
return `${h.slice(-2)}:${m.slice(-2)}`;
} |
// canvasエレメントの取得
let canvasElement = document.getElementById( 'canvas' );
// WebGL, glCubicの初期化
gl3.initGL( canvasElement );
if( !gl3.ready ) { console.log( 'initialize error' ); return; }
let gl = gl3.gl;
// バッファ長の決定,小さければ小さいほど高レスポンス
let bufferSize = 2048;
let canvasWidth = bufferSize;
let canvasHeight = 1;
canvasElement.width = canvasWidth;
canvasElement.height = canvasHeight;
canvasElement.style.width = '512px';
canvasElement.style.height = '512px';
// オーディオ関連の初期化
let audio = new AudioContext();
let scriptProcessor = audio.createScriptProcessor( bufferSize );
scriptProcessor.connect( audio.destination );
// 正方形ポリゴンの生成
let quadVert = [-1,1,0,-1,-1,0,1,1,0,1,-1,0];
let quadVbo = [ gl3.create_vbo( quadVert ) ];
// シェーダプログラムの作成
let prg = gl3.program.create_from_source(
WE.vs,
WE.fs,
[ 'position' ],
[ 3 ],
[ 'bufferSize', 'sampleStart', 'bspsr', 'textureRandom', 'textureAmen' ],
[ '1f', '1f', '1f', '1i', '1i' ]
);
if ( !prg ) { return; }
// テクスチャのロード
let textureNumAmen = 0;
gl3.create_texture_fromsource( WE.images[ 'amen.png' ], textureNumAmen );
gl.activeTexture( gl.TEXTURE0 );
gl.bindTexture( gl.TEXTURE_2D, gl3.textures[ textureNumAmen ].texture );
// サンプル関連の変数の初期化
let sampleStart = 0;
let sampleRate = audio.sampleRate; // サンプルレート
let bspsr = bufferSize / sampleRate;
// シェーダ出力結果をscriptProcessorに渡すための配列
let pixels = new Uint8Array( bufferSize * 4 );
// なぜかWE.runがうまく動かない……
let stop = false;
// ループ
scriptProcessor.onaudioprocess = ( _event ) => {
// バッファ配列の取得
let outL = _event.outputBuffer.getChannelData( 0 );
let outR = _event.outputBuffer.getChannelData( 1 );
// runして無ければ止める
if ( !WE.run ) { stop = true; }
if ( stop ) {
for ( let i = 0; i < bufferSize; i ++ ) {
outL[ i ] = 0.0;
outR[ i ] = 0.0;
}
return;
}
// 描画
gl.bindFramebuffer( gl.FRAMEBUFFER, null );
gl.blendFunc( gl.ONE, gl.ONE );
gl3.scene_clear( [ 0.0, 0.0, 0.0, 0.0 ] );
gl3.scene_view( null, 0, 0, bufferSize, 1 );
prg.set_program();
prg.set_attribute( quadVbo );
prg.push_shader( [ bufferSize, sampleStart, bspsr, textureNumAmen ] );
gl3.draw_arrays( gl.TRIANGLE_STRIP, 4 );
gl.flush();
// シェーダ出力結果をscriptProcessorに渡す
gl.readPixels( 0, 0, bufferSize, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels );
for ( let i = 0; i < bufferSize; i ++ ) {
outL[ i ] = ( ( pixels[ i * 4 + 0 ] - 128 ) * 256 + pixels[ i * 4 + 1 ] ) / 32768.0;
outR[ i ] = ( ( pixels[ i * 4 + 2 ] - 128 ) * 256 + pixels[ i * 4 + 3 ] ) / 32768.0;
}
// サンプル位置を1増やす
sampleStart ++;
};
WE.run = true;
|
/*!
* Copyright (c) 2016 Nanchao Inc.
* All rights reserved.
*/
'use strict';
var Modbus = require('./modbus');
function ModbusRtuMaster(port, timeout) {
this._option = {
mode: 'ascii',
timeout: timeout
};
this._master = new Modbus(port, this._option);
}
// read status common handler
ModbusRtuMaster.prototype._readStatus = function (slaveAddress, functionCode, startAddress, quantity, requestHandler, parseHandler, callback) {
var that = this;
requestHandler(slaveAddress, startAddress, quantity, function (error) {
if (error) {
callback(error);
return;
}
that._master.read(function (error, data) {
if (error) {
callback(error);
return;
}
console.log('master receive is ', data);
var response = parseHandler(quantity, data);
if (response.slaveAddress === slaveAddress) {
if (response.functionCode === functionCode) {
callback(undefined, response.status);
} else if (response.functionCode === (functionCode | 0x80)) {
callback(new Error('Exception code: ' + response.exceptionCode));
} else {
callback(new Error('Invalid function code: ' + response.functionCode));
}
}
});
});
};
// Modbus "Read Coil Status" (FC=0x01)
ModbusRtuMaster.prototype.readCoils = function (slaveAddress, startAddress, quantity, callback) {
var master = this._master;
this._readStatus(
slaveAddress,
0x01,
startAddress,
quantity,
master.requestReadCoils.bind(master),
master.parseReadCoilsResponse.bind(master),
callback
);
};
// Modbus "Read Input Status" (FC=0x02)
ModbusRtuMaster.prototype.readDiscreteInputs = function (slaveAddress, startAddress, quantity, callback) {
var master = this._master;
this._readStatus(
slaveAddress,
0x02,
startAddress,
quantity,
master.requestReadDiscreteInputs.bind(master),
master.parseReadDiscreteInputsResponse.bind(master),
callback
);
};
// Modbus "Read Holding Registers" (FC=0x03)
ModbusRtuMaster.prototype.readHoldingRegisters = function (slaveAddress, startAddress, quantity, callback) {
var master = this._master;
this._readStatus(
slaveAddress,
0x03,
startAddress,
quantity,
master.requestReadHoldingRegisters.bind(master),
master.parseReadHoldingRegistersResponse.bind(master),
callback
);
};
// Modbus "Read Input Registers" (FC=0x04)
ModbusRtuMaster.prototype.readInputRegisters = function (slaveAddress, startAddress, quantity, callback) {
var master = this._master;
this._readStatus(
slaveAddress,
0x04,
startAddress,
quantity,
master.requestReadInputRegisters.bind(master),
master.parseReadInputRegistersResponse.bind(master),
callback
);
};
// Modbus "Write Single Coil" (FC=0x05)
ModbusRtuMaster.prototype.writeSingleCoil = function (slaveAddress, address, state, callback) {
var that = this;
this._master.requestWriteSingleCoil(slaveAddress, address, state, function (error) {
if (error) {
callback(error);
return;
}
that._master.read(function (error, data) {
if (error) {
callback(error);
return;
}
var response = that._master.parseWriteSingleCoilResponse(data);
if (response.slaveAddress === slaveAddress) {
if (response.functionCode === 0x05) {
callback(undefined, response.state);
} else if (response.functionCode === (0x05 | 0x80)) {
callback(new Error('Exception code: ' + response.exceptionCode));
} else {
callback(new Error('Invalid function code: ' + response.functionCode));
}
}
});
});
};
// Modbus "Write Single Register" (FC=0x06)
ModbusRtuMaster.prototype.writeSingleRegister = function (slaveAddress, address, value, callback) {
var that = this;
this._master.requestWriteSingleRegister(slaveAddress, address, value, function (error) {
if (error) {
callback(error);
return;
}
that._master.read(function (error, data) {
if (error) {
callback(error);
return;
}
var response = that._master.parseWriteSingleRegisterResponse(data);
if (response.slaveAddress === slaveAddress) {
if (response.functionCode === 0x06) {
callback(undefined, response.value);
} else if (response.functionCode === (0x06 | 0x80)) {
callback(new Error('Exception code: ' + response.exceptionCode));
} else {
callback(new Error('Invalid function code: ' + response.functionCode));
}
}
});
});
};
// write multiple common handler
ModbusRtuMaster.prototype._writeMultiple = function (slaveAddress, functionCode, startAddress, values, requestHandler, parseHandler, callback) {
var that = this;
requestHandler(slaveAddress, startAddress, values, function (error) {
if (error) {
callback(error);
return;
}
that._master.read(function (error, data) {
if (error) {
callback(error);
return;
}
var response = parseHandler(data);
if (response.slaveAddress === slaveAddress) {
if (response.functionCode === functionCode) {
callback();
} else if (response.functionCode === (functionCode | 0x80)) {
callback(new Error('Exception code: ' + response.exceptionCode));
} else {
callback(new Error('Invalid function code: ' + response.functionCode));
}
}
});
});
};
// Modbus "Write Multiple Coils" (FC=0x0F)
ModbusRtuMaster.prototype.writeMultipleCoils = function (slaveAddress, startAddress, values, callback) {
var master = this._master;
this._writeMultiple(
slaveAddress,
0x0F,
startAddress,
values,
master.requestWriteMultipleCoils.bind(master),
master.parseWriteMultipleCoilsResponse.bind(master),
callback
);
};
// Modbus "Write Multiple Registers" (FC=0x10)
ModbusRtuMaster.prototype.writeMultipleRegisters = function (slaveAddress, startAddress, values, callback) {
var master = this._master;
this._writeMultiple(
slaveAddress,
0x10,
startAddress,
values,
master.requestWriteMultipleRegisters.bind(master),
master.parseWriteMultipleRegistersResponse.bind(master),
callback
);
};
module.exports = ModbusRtuMaster;
// ModbusMaster.prototype.readCoils = function (slaveAddress, startAddress, quantity, callback) {
// var that = this;
// this._master.requestReadCoils(slaveAddress, startAddress, quantity, function (error) {
// if (error) {
// callback(error);
// return;
// }
// that._master.read(function (error, data) {
// if (error) {
// callback(error);
// return;
// }
// console.log('master receive is ', data);
// var response = that._master.parseReadCoilsResponse(quantity, data);
// if (response.slaveAddress === slaveAddress) {
// if (response.functionCode === 0x01) {
// callback(undefined, response.coilStatus);
// } else if (response.functionCode === 0x81) {
// callback(new Error('Exception code: ' + response.exceptionCode));
// } else {
// callback(new Error('Invalid function code: ' + response.functionCode));
// }
// }
// });
// });
// };
// ModbusMaster.prototyoe.readDiscreteInputs = function (slaveAddress, startAddress, quantity, callback) {
// var that = this;
// this._master.requestReadDiscreteInputs(slaveAddress, startAddress, quantity, function (error) {
// if (error) {
// callback(error);
// return;
// }
// that._master.read(function (error, data) {
// if (error) {
// callback(error);
// return;
// }
// var response = that._master.parseReadDiscreteInputsResponse(data);
// if (response.slaveAddress === slaveAddress) {
// if (response.functionCode === 0x02) {
// callback(undefined, response.inputsStatus);
// } else if (response.function === 0x82) {
// callback(new Error('Exception code: ' + response.exceptionCode));
// } else {
// callback(new Error('Invalid function code: ' + response.functionCode));
// }
// }
// });
// });
// };
/*
// *******************
var port;
var master;
$.ready(function (error) {
if (error) {
console.log(error);
return;
}
var option = {
mode: 'rtu',
address: 1,
timeout: 200
};
port = $('#rs485');
// var master = new Modbus(port, 'rtu');
master = new ModbusRtuMaster(port, 200);
setInterval(function () {
master.readCoils(1, 10, 19, function (error, data) {
if (error) {
console.log('error ', error);
}
console.log(data);
});
}, 3000);
$('#led-r').turnOn();
});
$.end(function () {
$('#led-r').turnOff();
});
*/
|
import { API_ROUTES } from 'api/config';
import { CALL_API } from 'constants';
/**
*
* Fetch employee data from server
*
*/
export const FETCH_EMPLOYEE_RECORDS = '@@employees/FETCH_EMPLOYEE_RECORDS';
export const FETCH_EMPLOYEE_SUCCESS = '@@employees/FETCH_EMPLOYEE_SUCCESS';
export const fetchEmployees = () => (dispatch, getState) => {
const { ids } = getState().employees;
if (ids.length > 0) {
return;
}
return dispatch({
type: FETCH_EMPLOYEE_RECORDS,
[CALL_API]: {
actionType: FETCH_EMPLOYEE_SUCCESS,
shouldNormalize: true,
url: API_ROUTES.employees
}
});
};
/**
*
* Fetch map data from server
*
*/
export const FETCH_MAP_DATA = '@@employees/FETCH_MAP_DATA';
export const FETCH_MAP_SUCCESS = '@@employees/FETCH_MAP_SUCCESS';
export const fetchMapData = () => (dispatch, getState) => {
const { mapData } = getState();
if (mapData) {
return;
}
return dispatch({
type: FETCH_MAP_DATA,
[CALL_API]: {
actionType: FETCH_MAP_SUCCESS,
shouldNormalize: false,
url: API_ROUTES.maps
}
});
};
/**
*
* Set active id for employee location hub
*
*/
export const SET_ACTIVE_EMPLOYEE_SET_ID = '@@employees/SET_ACTIVE_EMPLOYEE_SET_ID';
export const setActiveEmployeeSetId = id => {
return {
type: SET_ACTIVE_EMPLOYEE_SET_ID,
payload: id
};
};
/**
*
* Toggles lock on employee location hub
*
*/
export const TOGGLE_EMPLOYEE_ID_LOCK = '@@employees/TOGGLE_EMPLOYEE_ID_LOCK';
export const toggleEmployeeIdLock = () => (dispatch, getState) => {
return dispatch({
type: TOGGLE_EMPLOYEE_ID_LOCK,
payload: !getState().employees.isLocked
});
};
|
function mash(){
return `You will live in a ${getHome()}, and you will have ${getKidCount()} kids, you'll drive a ${getCar()}, and your salary will be ${getCash()}!`;
}
function getHome(){
if (process.argv[2]){
let homes = ["Mansion", process.argv[2], "Shack", "House", "North Korea"];
return homes[Math.floor(Math.random()*homes.length)];
} else {
let homes = ["Mansion", "Shack", "House", "North Korea"];
return homes[Math.floor(Math.random()*homes.length)];
}
}
function getKidCount(){
if ((Math.random()>.5) || !process.argv[3]){
return Math.floor(Math.random()*101);
} else {
return process.argv[3];
}
}
function getCar(){
if (process.argv[4]){
let cars = ["Tesla", "Lambo", "Horse", process.argv[4]];
return cars[Math.floor(Math.random()*cars.length)];
} else {
let cars = ["Tesla", "Lambo", "Horse"];
return cars[Math.floor(Math.random()*cars.length)];
}
}
function getCash(){
if (process.argv[5]){
let cash = ["$100 Billion", "$1 Million", "$14,000", "$-43", process.argv[5]]
return cash[Math.floor(Math.random()*cash.length)];
} else {
let cash = ["$100 Billion", "$1 Million", "$14,000", "$-43"];
return cash[Math.floor(Math.random()*cash.length)];
}
}
console.log(mash()) |
import React, { Component } from 'react';
import { Shortcuts } from 'react-shortcuts';
import { toInteger, toArray, last, map, includes } from 'lodash';
import axios from 'axios';
import AlbumCardsContainer from '../components/AlbumCardsContainer';
import StarMusiqAlbumsFetcher from '../lib/CORSEnabledStarMusiqAlbumFetcher';
import AlbumsStorageManager from '../lib/AlbumsStorageManager';
import Header from '../components/Header';
import albumsFilter from '../lib/albumsFilter';
import * as Sentry from '@sentry/browser';
class AlbumsFetcher extends Component {
constructor(props) {
super(props);
Sentry.init({ dsn: 'https://4b2c2e33e6a84b98960862f89d996947@sentry.io/1296781' });
this.starMusiqAlbumsRetriever = new StarMusiqAlbumsFetcher();
this.loadingErrorMessage = "Error! Please Try Again";
this.prevButtonRef = null;
this.nextButtonRef = null;
this.streamButtonRef = [];
this.individualSongsButtonRef = [];
this.normalDownloadButtonRef = [];
this.hqDownloadButtonRef = [];
this.getAlbumsEndpoint = (process.env.BACKEND_API_BASE_URL) + '/api/get_albums';
this.state = {
albums: [],
loading: false,
loadingError: false,
searchString: '',
};
}
fetchAlbums = async () => {
const response = await axios.get(this.getAlbumsEndpoint);
return response.data;
};
highlightNewAlbums = (albums = []) => {
let highlightedAlbums = albums;
if (AlbumsStorageManager.isVisitedAlbumsPresent()) {
const visitedAlbumIds = AlbumsStorageManager.getVisitedAlbumIds();
highlightedAlbums = map(albums, (album) => ({
...album,
unvisited: !includes(visitedAlbumIds, album['movieId']),
}));
}
AlbumsStorageManager.setVisitedAlbumIds(map(albums, 'movieId'));
return highlightedAlbums;
}
displayAlbumsOfPage = async () => {
this.setState({
loading: true,
});
const responseObject = await this.fetchAlbums();
if (responseObject.status === 'success') {
const { albums } = responseObject;
const highlightedAlbums = this.highlightNewAlbums(albums);
this.setState({
albums: highlightedAlbums,
loading: false
});
} else {
console.log(responseObject.errorMessage);
Sentry.captureException(responseObject);
this.setState(prevState => {
return {
loadingError: !prevState.loadingError,
loading: false
};
});
}
};
_handleShortcuts = (action, event) => {
const getAlbumIndex = (keyBoardEvent) => (
/* using event.code since keyCode and which properties are deprecated
and charCode is not required here
Physical Key value is required */
toInteger(last(toArray(keyBoardEvent.code))) - 1
);
switch (action) {
case "GO_TO_PREVIOUS_PAGE":
this.prevButtonRef.click();
console.log("Navigating to previous page");
break;
case "GO_TO_NEXT_PAGE":
this.nextButtonRef.click();
console.log("Navigating to next page");
break;
case "CLICK_ALBUM_STREAM_LINK":
console.log("Album Card Stream Link Shortcut Triggered");
this.streamButtonRef[getAlbumIndex(event)].click();
break;
case "CLICK_ALBUM_IS_LINK":
console.log("Album Card Individual Songs Link Shortcut Triggered");
this.individualSongsButtonRef[getAlbumIndex(event)].click();
break;
case "CLICK_ALBUM_ND_LINK":
console.log("Album Card Normal Quality Download Link Shortcut Triggered");
this.normalDownloadButtonRef[getAlbumIndex(event)].click();
break;
case "CLICK_ALBUM_HD_LINK":
console.log("Album Card High Quality Link Shortcut Triggered");
this.hqDownloadButtonRef[getAlbumIndex(event)].click();
break;
}
};
componentDidMount = () => {
this.displayAlbumsOfPage();
};
handleSearchStringChange = (event) => {
const userInputSearchString = _.trim(event.target.value);
const regexSafeSearchString = userInputSearchString.replace(/[^\w\s]/gi, '');
_.debounce(
() => {
this.setState({
...this.state,
searchString: regexSafeSearchString,
});
}, 500
)();
}
render() {
const { searchString, albums } = this.state;
const filteredAlbums = _.isEmpty(searchString) ? albums : albumsFilter({ searchString, albumsPayload: albums });
return (
<Shortcuts
name="ALBUMS_CONTAINER"
handler={this._handleShortcuts}
targetNodeSelector={'body'}
>
<Header
onSearchStringChange={this.handleSearchStringChange}
/>
<AlbumCardsContainer
{...this.state}
albums={filteredAlbums}
loadingErrorMessage={this.loadingErrorMessage}
streamButtonRef={el => this.streamButtonRef.push(el)}
individualSongsButtonRef={el =>
this.individualSongsButtonRef.push(el)
}
normalDownloadButtonRef={el => this.normalDownloadButtonRef.push(el)}
hqDownloadButtonRef={el => this.hqDownloadButtonRef.push(el)}
/>
</Shortcuts>
);
}
}
export default AlbumsFetcher;
|
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(A) {
// write your code in JavaScript (Node.js 4.0.0)
var hash = {}, counter = 0, i;
for ( i = 0; i < A.length; i++ ){
if ( hash[ A[i] ] === undefined ){
hash[ A[i] ] = 0;
counter++;
}
}
return counter;
} |
var startTime = 0;
var indexToDir = {
'0': 'left',
'1': 'down',
'2': 'up',
'3': 'right'
};
var keysPressed = {
up: false,
right: false,
down: false,
left: false
}
var chart = {
right: {
list: [],
pointer: 0
},
left: {
list: [],
pointer: 0
},
up: {
list: [],
pointer: 0
},
down: {
list: [],
pointer: 0
}
};
var timeouts = [];
var TIMING_WINDOW;
var getStopTime = function(thisBeat, stops) {
return stops.reduce(function(time, stop) {
if (thisBeat > stop.beat) {
time += stop.duration;
}
return time;
}, 0);
};
var getBPMTime = function(thisBeat, bpms) {
var addedTime = 0;
for (var i = 1; i < bpms.length && thisBeat > bpms[i].beat; i++) {
var oldBeatTime = 60 / bpms[i - 1].bpm;
var newBeatTime = 60 / bpms[i].bpm;
var timeAtBeatWithOldBPM = (thisBeat - bpms[i].beat) * oldBeatTime;
var timeAtBeatWithNewBPM = (thisBeat - bpms[i].beat) * newBeatTime;
addedTime += timeAtBeatWithNewBPM - timeAtBeatWithOldBPM;
}
return addedTime;
}
var inFreeze = {
left: {
freeze: false,
fromArrow: null,
},
down: {
freeze: false,
fromArrow: null,
},
up: {
freeze: false,
fromArrow: null,
},
right: {
freeze: false,
fromArrow: null,
}
}
var checkArrow = function(arrowTime, last) {
if(last) {
postMessage({
endSong: true
});
}
// !arrowTime.hit = arrow is missed
// !arrowTime.freezeUp = there actually is an arrow
if (!arrowTime.hit && !arrowTime.freezeUp) {
postMessage({
hit: false,
index: arrowTime.index,
dir: arrowTime.dir
});
} else if (arrowTime.animate) {
postMessage({
freezeUp: true,
dir: arrowTime.dir,
index: arrowTime.index
});
}
// at the end of a freeze (regardless of good or bad)
else if (arrowTime.freezeUp) {
inFreeze[arrowTime.dir].freeze = false;
}
}
var preChart = function(stepChart, bpm, arrowOffset, songOffset, timing, bpms, stops) {
TIMING_WINDOW = timing;
var measureTime = 1 / (bpm / 60 / 4); // number of seconds per measure
stepChart.forEach(function(measure, measureIndex) {
var notes = measure.length;
var noteTime = measureTime / measure.length;
measure.forEach(function(line, lineIndex) {
var timeStamp = measureTime * measureIndex + noteTime * lineIndex + arrowOffset;
var thisBeat = measureIndex * 4 + (lineIndex / notes) * 4;
var stopTime = getStopTime(thisBeat, stops);
var extraBPMTime = getBPMTime(thisBeat, bpms);
timeStamp += stopTime + extraBPMTime;
line.forEach(function(maybeArrow, index) {
var arrowTime,
thisTimeout;
if (maybeArrow === "1" || maybeArrow === "2") {
arrowTime = {
dir: indexToDir[index],
time: timeStamp,
attempted: false,
hit: false,
// this 'freeze' property is used to turn on the freeze eater (fader opaque) on a successful keypress
// at the top of a freeze arrow
freeze: maybeArrow === "2" ? true : false,
};
var arrowIndex = chart[indexToDir[index]].list.push(arrowTime) - 1;
arrowTime.index = arrowIndex;
// this stores a reference to the arrow with the additional freeze div, used at number 3 to signal freeze div removal
if (maybeArrow === "2") inFreeze[indexToDir[index]].fromArrow = arrowIndex;
thisTimeout = function(last) {
setTimeout(function() {
checkArrow(arrowTime, last);
}, (timeStamp + TIMING_WINDOW - songOffset) * 1000)
};
timeouts.push(thisTimeout);
} else if (maybeArrow === "3") {
arrowTime = {
dir: indexToDir[index],
time: timeStamp,
freezeUp: true,
// signal to checkArrow to specify which arrow to remove freeze from
index: inFreeze[indexToDir[index]].fromArrow,
};
var holdingFreezeTimeout = function(last) {
setTimeout(function() {
checkArrow(arrowTime, last);
}, (timeStamp - TIMING_WINDOW - songOffset) * 1000)
};
var animationFreezeTimeout = function(last) {
setTimeout(function() {
arrowTime.animate = true;
checkArrow(arrowTime, last);
}, (timeStamp + TIMING_WINDOW - songOffset) * 1000)
};
timeouts.push(holdingFreezeTimeout);
timeouts.push(animationFreezeTimeout);
}
});
});
});
// if song is too complicated, may bug when starting song before this is done
};
// checks on keyup whether we were in a freeze at that dir or not
var checkIfFreeze = function (dir) {
if (inFreeze[dir].freeze) {
postMessage({
dir,
brokeFreeze: true
})
}
}
var respondToKey = function(time, dir) {
var thisChart = chart[dir];
if (thisChart.pointer > thisChart.list.length) return;
var nextOne = thisChart.list[thisChart.pointer];
if (time > nextOne.time + TIMING_WINDOW )
while (nextOne.time < time - TIMING_WINDOW) { // timingwindow | press(time) | arrow(nextOne)
thisChart.pointer++;
nextOne = thisChart.list[thisChart.pointer];
}
var diffWithSign = nextOne.time - time;
var diff = Math.abs(diffWithSign);
if (diff < TIMING_WINDOW) {
nextOne.hit = true;
postMessage({
dir,
index: thisChart.pointer,
hit: true,
freeze: nextOne.freeze,
diff: diff
});
if (nextOne.freeze) inFreeze[dir].freeze = true;
}
}
self.onmessage = function(e) {
if (e.data.type === 'preChart') {
preChart(e.data.chart, e.data.bpm, e.data.arrowOffset, e.data.songOffset, e.data.timing, e.data.bpms, e.data.stops);
} else if (e.data.type === 'keyDown') {
respondToKey(e.data.timeStamp, e.data.dir);
keysPressed[e.data.dir] = true;
} else if (e.data.type === 'startTime') {
startTime = e.data.startTime;
//tagging the last timeout so we can end the song
timeouts[timeouts.length-1].last = true;
timeouts.forEach(function(func) {
if(func.last) {
func(true)
}
else func();
})
} else if (e.data.type === 'keyUp') {
checkIfFreeze(e.data.dir);
}
};
|
import React from "react";
export const Wrapper = ({ props, children }) => {
return (
<>
<style jsx>{`
.Wrapper {
width: calc(100% - 10vw);
margin: 0 auto;
position: relative;
z-index: 2;
}
@media only screen and (max-width: 1024px) {
.Wrapper {
width: calc(100% - 40px);
}
}
`}</style>
<div className={"Wrapper"}>{children}</div>
</>
);
};
export const Row = ({ props, children }) => {
return (
<>
<style jsx>{`
.Row {
padding-bottom: 8vh;
&:nth-child(even) {
}
}
`}</style>
<div className={"Row"}>{children}</div>
</>
);
};
|
const frontEndLogos = [
{
img: './public/assets/images/icons/html5.svg',
name: 'HTML5'
},
{
img: './public/assets/images/icons/css-3.svg',
name: 'CSS3'
},
{
img: './public/assets/images/icons/javascript.svg',
name: 'Javascript'
},
{
img: './public/assets/images/icons/jquery-1.svg',
name: 'jQuery'
},
{
img: './public/assets/images/icons/bootstrap-4.svg',
name: 'Bootstrap'
},
{
img: './public/assets/images/icons/reactjs.png',
name: 'ReactJS'
},
]; |
/**
* This is my custom i18n component. It lets me
* handle with precision the behavior of a switch
* in the user's language preference.
* In all cases, when the user changes the language,
* texts and links in the navigation will do the same,
* based on the routes defined here. And it navigate to
* the translated page.
* Blog posts, will have the same behavior if there is
* a translation. Otherwise, it will pass the control
* to an other component to let the user choose if he
* wants to keep reading or go to the home page (or
* edit the translation).
* Same about further sections that will be available
* only in french (eg, courses, education)
*/
import React, { useContext } from 'react';
import { Link, navigate } from 'gatsby';
import { LanguageContext } from '../store/language'
// We can feed this routes array during build time,
// with gatsby-node.js
const routes = [
{
from: '/',
to: '/fr',
},
{
from: '/fr',
to: '/',
},
{// trailing slashes for paths that expect to be completed
from: '/blog/fr/',
to: '/blog/en/',
},
{
from: '/blog/en/',
to: '/blog/fr/',
},
{
from: '/blog/en/global-state-with-gatsby/',
to: '/blog/fr/global-state-avec-gatsby/',
},
{
from: '/blog/fr/global-state-avec-gatsby/',
to: '/blog/en/global-state-with-gatsby/',
},
{
from: '/blog/en/add-a-custom-typeface-to-theme-ui',
to: '/blog/fr/ajouter-nouvelle-police-avec-theme-ui',
},
{
from: '/blog/fr/ajouter-nouvelle-police-avec-theme-ui',
to: '/blog/en/add-a-custom-typeface-to-theme-ui',
}
];
/**
* Navigation function that let you define
* custom routes when user switch from one
* language to another, and prevent undefined
* issues on server side rendering
* @param {Array} routes an array of routes
* from: the destination location
* to: the destination location
* @return {Function} navigate(to) -> @reach/router function
*/
const navigation = routes => {
routes.map(route => {
if (
typeof window !== 'undefined' &&
window.location.pathname === route.from
)
navigate(route.to);
});
};
/**
* A switch that set the language
* and handle the navigation
* @param {boolean} isNavigation by default, a language switch
* will trigger a navigation to a translated page. But you
* can imagine a page with inline traduction that change
* the text based on a translate() function (cd. utils).
* @param {}
*/
const LanguageSwitch = ({
children,
isNavigation = true,
...props
}) => {
const { language, setLanguage } = useContext(LanguageContext);
return (
<div
onClick={() => {
language === 'en' ? setLanguage('fr') : setLanguage('en');
if (isNavigation) navigation(routes);
}}
{...props}
>
{children}
</div>
);
};
export default LanguageSwitch;
|
test('class02', () => {
function myClass (initial) {
this.test = initial
}
const instance = new myClass(false)
console.log(instance.test)
}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.