text
stringlengths 7
3.69M
|
|---|
/*---
comment: 123
*/
function fn_name() { }
/*---
trying: something
*/
var x
|
var canvas;
var context;
var circleSize;
var canvasSize;
var fade;
function drawCircle(x,y,size,color) {
//draws a circle
context.beginPath();
context.arc(x,y,size,0,2*Math.PI);
context.fillStyle = color;
context.fill();
context.closePath();
}
function randomNum(num) {return Math.floor(Math.random()*num) + 1;}
function misc() {
//does some stuff with the inputs
if (circleSize != document.getElementById("circleSize").value && fade) {fadeInit();}
circleSize = Number(document.getElementById("circleSize").value);
canvasSize = Number(document.getElementById("canvasSize").value);
document.getElementById("circleSize").max = (canvasSize-circleSize)
if (canvas.width != canvasSize) {
if (fade) {fadeInit();}
canvas.width = canvasSize;
canvas.height = canvasSize;
}
}
function randomColor() {
//generate a random color
const hexChars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];
var color = '#';
for (var i = 0; i != 6; i++) {
color += hexChars[randomNum(16)-1];
} return color;
}
function randomCircle() {
//draws a random circle
var size = randomNum(circleSize)
drawCircle(
randomNum((canvas.width-size)-size)+size, //randomly generated x coord
randomNum((canvas.height-size)-size)+size, //randomly generated y coord
size, //randomly generated circle size
randomColor() //random color
);
}
function clearCanvas(){context.clearRect(0, 0, canvas.width, canvas.height);}
function isNumberKey(evt){ //definitely didn't steal this from stack overflow
//makes sure the inputted text is number
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
function distanceFormula(x,y) {return Math.floor(((x[0]-x[1])**2) + ((y[0]-y[1])**2)**.5)} //Distance formula
function fadeMode() {
var maxDistance = distanceFormula([0, 0], [canvas.width/2, canvas.height/2]);
var size = randomNum(circleSize)
var position = [randomNum((canvas.width-size)-size)+size, randomNum((canvas.height-size)-size)+size]
// var distance = Math.abs(distanceFormula(position, [canvas.width/2, canvas.height/2]));
var alpha = Math.floor(randomNum(255)).toString(16);
drawCircle(
position[0], //x coord
position[1], //y coord
size, //size var
randomColor()+alpha //random color + transparency value
);
}
function fadeInit() {drawCircle(canvas.width/2, canvas.height/2, circleSize, randomColor())}
function actionDelegator() {
misc(); //dynamic var code
if (document.getElementById("fade").checked != fade) {
clearCanvas()
if (document.getElementById("fade").checked == true) {fadeInit();}
}
fade = document.getElementById("fade").checked;
//var fade = false;
if (fade) {fadeMode();}
else {randomCircle();}
}
canvas = document.getElementById("canvas"); //the canvas in the html
context = canvas.getContext("2d") //the 2d drawing context
circleSize = document.getElementById("circleSize") //the circle size input
canvasSize = document.getElementById("canvasSize") //the canvas size input
setInterval(actionDelegator,50); //every 50 milisecs draw a random circle
|
const Discord = require("discord.js");
const { Database } = require("npm.db");
const db = new Database("database");
const moment = require("moment");
exports.run = async (client, message, args) => {
if(message.author.id !== '699597747657113653') if(message.author.id !== '548145246983159808') return;
const bakımaldıkabooooo = args[0];
const sebep = args.slice(1).join(" ");
if (bakımaldıkabooooo == "al") {
if (!sebep) return message.channel.send("Sebep Belirtin.");
db.set(`bakımsüre_`, Date.now());
db.set(`bakımalan_`, message.author.id);
db.set(`bakım_`, sebep);
return message.channel
.send(
`Bakım açıldı ab.`
)
} else if (bakımaldıkabooooo == "çıkar") {
let aylartoplam = {
"01": "Ocak",
"02": "Şubat",
"03": "Mart",
"04": "Nisan",
"05": "Mayıs",
"06": "Haziran",
"07": "Temmuz",
"08": "Ağustos",
"09": "Eylül",
"10": "Ekim",
"11": "Kasım",
"12": "Aralık"
};
let aylar = aylartoplam;
let rol = "";
require("moment-duration-format");
let wensj = db.get(`bakımsüre_`);
const duration = moment
.duration(Date.now() - wensj)
.format(" D [gün], H [saat], m [dakika], s [saniye]");
return embed(`
**:question: | Bakımdan çıkartmak istediğinize emin misiniz**
> Sebep: \`${db.get(`bakım_`)}\`
> Bakıma Alan: \`${db.get(`bakımalan_`)}\`
> Bakıma Alınma Tarihi: \`${moment(wensj).format("DD")} ${
aylar[moment(wensj).format("MM")]
} ${moment(wensj).format("YYYY HH:mm:ss")}\`
> Kara Listede Geçen Süre: \`${duration}\`
`).then(async wenbayrak => {
await wenbayrak.react("✅");
await wenbayrak.react("❌");
const filter = (reaction, user) => {
return (
["✅", "❌"].includes(reaction.emoji.name) &&
user.id === message.author.id
);
};
wenbayrak
.awaitReactions(filter, { max: 1, time: 60000, errors: ["time"] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === "✅") {
db.delete(`bakımsüre_`);
db.delete(`bakımalan_`);
db.delete(`bakım_`);
let bayrakwenqwe = new Discord.MessageEmbed()
.setColor("RANDOM")
.setAuthor(message.author.tag)
.setThumbnail(client.user.avatarURL())
.setDescription(`Bakım Kapandı!`);
wenbayrak.edit(bayrakwenqwe);
} else {
let bayrakwenqwe = new Discord.MessageEmbed()
.setColor("RANDOM")
.setAuthor(message.author.tag)
.setThumbnail(client.user.avatarURL())
.setDescription(`İşlem iptal edildi!`);
wenbayrak.edit(bayrakwenqwe);
}
})
.catch(err => {
let bayrakwenqwe = new Discord.MessageEmbed()
.setColor("RANDOM")
.setAuthor(message.author.tag)
.setThumbnail(client.user.avatarURL())
.setDescription(`İşlem iptal edildi!`);
wenbayrak.edit(bayrakwenqwe);
});
});
} else {
return message.reply("Geçersiz argüman! Argümanlar: `al` `çıkar`");
}
async function embed(text) {
//Bayrak & WenSamita Neiva
const embed = new Discord.MessageEmbed() //Bayrak & WenSamita Neiva
.setColor("BLUE") //Bayrak & WenSamita Neiva
.setThumbnail(message.author.avatarURL({ dynamic: true }))
.setAuthor(
//Bayrak & WenSamita Neiva
message.author.tag, //Bayrak & WenSamita Neiva
message.author.avatarURL({ dynamic: true }) //Bayrak & WenSamita Neiva
) //Bayrak & WenSamita Neiva
.setDescription(`${text}`) //Bayrak & WenSamita Neiva
.setTimestamp() //Bayrak & WenSamita Neiva
.setFooter(client.user.username, client.user.avatarURL()); //Bayrak & WenSamita Neiva
let msg = await message.channel.send(embed); //Bayrak & WenSamita Neiva
return msg; //Bayrak & WenSamita Neiva
}
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: ["bakım"],
permLevel: "BOT_OWNER"
};
exports.help = {
name: "bakım",
desciption: "WenSamita Neiva",
usage: "Bayrak & WenSamita Neiva"
};
|
import gql from 'graphql-tag';
export const PAGINATION_CARS = gql`
query paginationCars($limit:Int,$offset:Int){
paginationCars(limit:$limit,offset:$offset){
placa
modelo
tipo
marca
propietario
documento
detalle
fecha
imageUrl
}
totalCars
}
`;
|
// document.addEventListener('DOMContentLoaded', () => {
/* マイルストーン1 */
// alertで'You got 5 guesses. Guess 1 to 5'と言うメッセージを表示させ、1から5までの数値を当てるよう指示する。
alert('You got 5 guesses. Guess 1 to 5');
// 答えの数値を2で用意
const answer = 2;
// promptで'What do you guess?'と言うメッセージとともに、記入欄を表示させる
let guess = prompt('What do you guess?');
// forループで1から5までの数値で、答えの2が当たるまで推測を促すpromptを表示させる。
// ヒント1:if文とも組み合わせて、推測が当たった場合はalertで'Good job! See what happens next :)'を表示。当たったらゲーム終了にする。
// ヒント2:外れたらpromptで'Ops! Maybe, another try?'のメッセージとともに記入欄を表示。
for (let i = 0; i < 5; i++) {
if (guess == answer) {
alert('Good job! See what happens next :)');
break;
}
guess = prompt('Ops! Maybe, another try?');
}
/* マイルストーン2 */
// for文で完成したら、for文箇所をコメントアウトし、while文で書き換えてみましょう。
// });
|
function solve(arr, sort) {
class Ticket {
constructor(destination, price, status) {
this.destination = destination;
this.price = price;
this.status = status;
}
}
let tickets = [];
for (let element of arr) {
var [destination, price, status] = element.split('|');
price = Number(price);
tickets.push(new Ticket(destination, price, status));
}
switch (sort) {
case 'destination':
tickets.sort((a, b) => a.destination > b.destination);
break;
case 'price':
tickets.sort((a, b) => a.price > b.price);
break;
case 'status':
tickets.sort((a, b) => a.status > b.status);
break;
}
return tickets;
}
console.log(solve(['Philadelphia|94.20|available',
'New York City|95.99|available',
'New York City|95.99|sold',
'Boston|126.20|departed'],
'destination'));
|
const React = require("react");
const NoteList = require("./note-list");
const NoteForm = require("./note-form");
const App = React.createClass({
// componentDidMount() {
// document.body.addEventListener("click", this.handleClick);
// },
// componentWillUnmout() {
// document.body.removeEventListener("click", this.handleClick);
// },
handleClick(event) {
this.props.store.dispatch({
type: "EXIT_NOTE_EDITING",
});
},
toRainbowChar(char, key) {
return (
<span key={key} className="rainbow-char">
{char}
</span>
);
},
render() {
return (
<div>
<p className="notes-lede" onClick={this.handleClick}>
{"Shorts".split("").map(this.toRainbowChar)}
<span className="notes-sub">
A delightful little way to leave yourself short notes.
</span>
</p>
<NoteList store={this.props.store} />
<NoteForm onClick={this.handleClick} store={this.props.store}/>
</div>
);
},
});
module.exports = App;
|
/**
* @license
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview
* Registers a language handler for Lua.
*
*
* To use, include prettify.js and this file in your HTML page.
* Then put your code in an HTML tag like
* <pre class="prettyprint lang-lua">(my Lua code)</pre>
*
*
* I used http://www.lua.org/manual/5.1/manual.html#2.1
* Because of the long-bracket concept used in strings and comments, Lua does
* not have a regular lexical grammar, but luckily it fits within the space
* of irregular grammars supported by javascript regular expressions.
*
* @author mikesamuel@gmail.com
*/
PR['registerLangHandler'](
PR['createSimpleLexer'](
[
// Whitespace
[PR['PR_PLAIN'], /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'],
// A double or single quoted, possibly multi-line, string.
[PR['PR_STRING'], /^(?:\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)|\'(?:[^\'\\]|\\[\s\S])*(?:\'|$))/, null, '"\'']
],
[
// A comment is either a line comment that starts with two dashes, or
// two dashes preceding a long bracketed block.
[PR['PR_COMMENT'], /^--(?:\[(=*)\[[\s\S]*?(?:\]\1\]|$)|[^\r\n]*)/],
// A long bracketed block not preceded by -- is a string.
[PR['PR_STRING'], /^\[(=*)\[[\s\S]*?(?:\]\1\]|$)/],
[PR['PR_KEYWORD'], /^(?:and|break|do|else|elseif|end|false|for|function|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/, null],
// A number is a hex integer literal, a decimal real literal, or in
// scientific notation.
[PR['PR_LITERAL'],
/^[+-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i],
// An identifier
[PR['PR_PLAIN'], /^[a-z_]\w*/i],
// A run of punctuation
[PR['PR_PUNCTUATION'], /^[^\w\t\n\r \xA0][^\w\t\n\r \xA0\"\'\-\+=]*/]
]),
['lua']);
|
import * as actionType from '../../redux/actions/actionTypes'
const initialState = {
users: [
{
firstName: 'demo',
lastName: 'demo',
email: 'demo@gmail.com',
password: 'demo'
},
{
emaill: 'demo@gmail.com',
passwordd: 'demo',
}
],
isLogged: false
}
const signUpReducer = (state = initialState, action) => {
switch (action.type) {
case actionType.SIGNUP:
return {
users: [
...state.users,
action.payload
],
}
case actionType.LOGIN:
for (let user of state.users) {
if (user.emaill === action.payload.email && user.passwordd === action.payload.password) {
return {
...state,
isLogged: true
}
}
}
default: return state
}
return state;
}
export default signUpReducer;
|
$(document).on('click', '.messenger-trigger', function(e) {
e.preventDefault();
$('.messenger').addClass('open')
})
$(document).on('click', '#btn-close', function(e) {
$('.messenger').removeClass('open')
})
$(document).on('click', '.video-trigger', function(e) {
e.preventDefault();
$('.video').addClass('open')
})
$(document).on('click', '#close-video', function(e) {
$('.video').removeClass('open')
})
|
export const USER_SUCCESS = "USER_SUCCESS"
export const USER_FAILURE = "USER_FAILURE"
export const USER_REQUEST = "USER_REQUEST"
|
import { h, createContext, render } from 'preact';
import { useContext, forwardRef } from 'preact/compat';
import { setup, css, styled, keyframes } from '../index';
import { extractCss } from '../core/update';
describe('integrations', () => {
it('preact', () => {
const ThemeContext = createContext();
const useTheme = () => useContext(ThemeContext);
setup(h, null, useTheme);
const target = document.createElement('div');
const Span = styled('span', forwardRef)`
color: red;
`;
const SpanWrapper = styled('div')`
color: cyan;
${Span} {
border: 1px solid red;
}
`;
const BoxWithColor = styled('div')`
color: ${(props) => props.color};
`;
const BoxWithColorFn = styled('div')(
(props) => `
color: ${props.color};
`
);
const BoxWithThemeColor = styled('div')`
color: ${(props) => props.theme.color};
`;
const BoxWithThemeColorFn = styled('div')(
(props) => `
color: ${props.theme.color};
`
);
const fadeAnimation = keyframes`
0% {
opacity: 0;
}
99% {
opacity: 1;
color: dodgerblue;
}
`;
const BoxWithAnimation = styled('span')`
opacity: 0;
animation: ${fadeAnimation} 500ms ease-in-out;
`;
const BoxWithConditionals = styled('div')([
{ foo: 1 },
(props) => ({ color: props.isActive ? 'red' : 'tomato' }),
null,
{ baz: 0 },
false,
{ baz: 0 }
]);
const shared = { opacity: 0 };
const BoxWithShared = styled('div')(shared);
const BoxWithSharedAndConditional = styled('div')([shared, { baz: 0 }]);
const refSpy = jest.fn();
render(
<ThemeContext.Provider value={{ color: 'blue' }}>
<div>
<Span ref={refSpy} />
<Span as={'div'} />
<SpanWrapper>
<Span />
</SpanWrapper>
<BoxWithColor color={'red'} />
<BoxWithColorFn color={'red'} />
<BoxWithThemeColor />
<BoxWithThemeColorFn />
<BoxWithThemeColor theme={{ color: 'green' }} />
<BoxWithThemeColorFn theme={{ color: 'orange' }} />
<BoxWithAnimation />
<BoxWithConditionals isActive />
<BoxWithShared />
<BoxWithSharedAndConditional />
<div className={css([shared, { background: 'cyan' }])} />
</div>
</ThemeContext.Provider>,
target
);
expect(extractCss()).toMatchInlineSnapshot(
[
'"',
' ', // Empty white space that holds the textNode that the styles are appended
'@keyframes go384228713{0%{opacity:0;}99%{opacity:1;color:dodgerblue;}}',
'.go1127809067{opacity:0;background:cyan;}',
'.go3865451590{color:red;}',
'.go3991234422{color:cyan;}',
'.go3991234422 .go3865451590{border:1px solid red;}',
'.go1925576363{color:blue;}',
'.go3206651468{color:green;}',
'.go4276997079{color:orange;}',
'.go2069586824{opacity:0;animation:go384228713 500ms ease-in-out;}',
'.go631307347{foo:1;color:red;baz:0;}',
'.go3865943372{opacity:0;}',
'.go1162430001{opacity:0;baz:0;}',
'"'
].join('')
);
expect(refSpy).toHaveBeenCalledWith(
expect.objectContaining({
tagName: 'SPAN'
})
);
});
it('support extending with as', () => {
const list = ['p', 'm', 'as', 'bg'];
setup(h, undefined, undefined, (props) => {
for (let prop in props) {
if (list.indexOf(prop) !== -1) {
delete props[prop];
}
}
});
const target = document.createElement('div');
const Base = styled('div')(({ p = 0, m }) => [
{
color: 'white',
padding: p + 'em'
},
m != null && { margin: m + 'em' }
]);
const Super = styled(Base)`
background: ${(p) => p.bg || 'none'};
`;
render(
<div>
<Base />
<Base p={2} />
<Base m={1} p={3} as={'span'} />
<Super m={1} bg={'dodgerblue'} as={'button'} />
</div>,
target
);
// Makes sure the resulting DOM does not contain any props
expect(target.innerHTML).toEqual(
[
'<div>',
'<div class="go103173764"></div>',
'<div class="go103194166"></div>',
'<span class="go2081835032"></span>',
'<button class="go1969245729 go1824201605"></button>',
'</div>'
].join('')
);
expect(extractCss()).toMatchInlineSnapshot(
[
'"',
'.go1969245729{color:white;padding:0em;margin:1em;}',
'.go103173764{color:white;padding:0em;}',
'.go103194166{color:white;padding:2em;}',
'.go2081835032{color:white;padding:3em;margin:1em;}',
'.go1824201605{background:dodgerblue;}',
'"'
].join('')
);
});
it('shouldForwardProps', () => {
const list = ['p', 'm', 'as'];
setup(h, undefined, undefined, (props) => {
for (let prop in props) {
if (list.indexOf(prop) !== -1) {
delete props[prop];
}
}
});
const target = document.createElement('div');
const Base = styled('div')(({ p = 0, m }) => [
{
color: 'white',
padding: p + 'em'
},
m != null && { margin: m + 'em' }
]);
render(
<div>
<Base />
<Base p={2} />
<Base m={1} p={3} as={'span'} />
</div>,
target
);
// Makes sure the resulting DOM does not contain any props
expect(target.innerHTML).toEqual(
[
'<div>',
'<div class="go103173764"></div>',
'<div class="go103194166"></div>',
'<span class="go2081835032"></span>',
'</div>'
].join(''),
`"<div><div class=\\"go103173764\\"></div><div class=\\"go103194166\\"></div><span class=\\"go2081835032\\"></span></div>"`
);
expect(extractCss()).toMatchInlineSnapshot(
[
'"',
'.go103173764{color:white;padding:0em;}',
'.go103194166{color:white;padding:2em;}',
'.go2081835032{color:white;padding:3em;margin:1em;}',
'"'
].join('')
);
});
});
|
var gulp = requre('gulp')
gulp.task('copy', function(){
gulp.src('./src/*.html')
.pipe('./build')
})
|
import firebaseInstance from '../../middleware/firebase'
import {LocalStorage} from 'quasar'
import usersActions from '../store/users/actions'
const state = {
loggedIn: false
}
const mutations = {
setLoggedIn(state, value) {
state.loggedIn = value
}
}
const actions = {
registerUser({}, payload) {
return firebaseInstance.firebase.auth().createUserWithEmailAndPassword(payload.email, payload.password)
.then(response => {
window.user = response.user;
firebaseInstance.uploadProfilePictureToStorage(payload.profilePic, response.user.uid, payload)
return response.user.uid
}).catch(error => {
console.log('error', error)
})
},
loginUser({}, payload) {
return firebaseInstance.firebase.auth().signInWithEmailAndPassword(payload.email, payload.password)
.then(response => {
window.user = response.user;
console.log("response", response)
return response.user.uid
}).catch(error => {
console.log('error', error)
})
},
logoutUser() {
return firebaseInstance.firebase.auth().signOut().then(() => {
console.log('User Signed out')
}).catch(err => {
console.log(err)
})
},
handleAuthStateChange({commit}) {
firebaseInstance.firebase.auth().onAuthStateChanged(user => {
if (user) {
commit('setLoggedIn', true)
LocalStorage.set('loggedIn', true)
window.user = user
this.$router.push('/').catch(err => {
})
} else {
commit('setLoggedIn', false)
LocalStorage.set('loggedIn', false)
window.user = null
this.$router.replace('/auth')
}
})
}
}
const getters = {}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
|
const { RichEmbed } = require("discord.js");
module.exports = async (client, message, args, prefix) => {
message.delete();
if (args.length < 1) {
return message.channel.send(setEmbed(client, message));
}
let length = args[0].length;
// Emoji generico
// <a:nome:123456789987654321>
// <:nome:123456789987654321>
// Em ambos o ID termina no `length - 1` e comeca no `length - 19`
let emojiID = args[0].slice(length - 19, length - 1);
let emoji = message.guild.emojis.get(emojiID);
if (!emoji) {
return message.channel.send(setEmbed(client, message, prefix));
}
let embed = new RichEmbed()
.setTitle(`ID = \`${emoji.id}\``)
.setImage(emoji.url)
.setTimestamp();
message.channel.send(embed);
};
/**
* Função para fazer a embed caso um emoji não seja especificado
*/
var setEmbed = (client, message, prefix) => {
let url = message.author.avatarURL || message.author.defaultAvatarURL;
let embed = new RichEmbed()
.setAuthor(message.author.tag, url)
.setTitle(`Modo de uso: ${client.getEmoji("igorpicapica")}`)
.addField(`Exemplo de como usar o comando`, `s.emoji ${client.getEmoji("pipoca")}`)
.setFooter(`Comando executado por: ${message.author.username}`)
.setThumbnail("https://cdn.discordapp.com/emojis/502972742631424002.gif")
.setColor("#8e04cf")
.setTimestamp();
return embed;
};
|
var passport = require('passport');
var mongoose = require('mongoose');
LocalStrategy = require('passport-local').Strategy;
var User= mongoose.model('User');
module.exports = function() {
passport.use(new LocalStrategy(
(username,password,done)=> {
User.findOne({username:username}).exec((err,user)=> {
if(user && user.authenticate(password)){
return done(null,user);
}else{
return done(null,false);
}
})
}
));
passport.serializeUser((user,done)=> {
if(user){
return done(null,user._id);
}
});
passport.deserializeUser((id,done)=> {
User.findOne({_id:id}).exec((err,user)=> {
if(user){
return done(null,user);
} else{
return done(null,false);
}
})
});
};
|
define([
], function (namespace) {
'use strict';
/*
Sepacial for group and topic management
*/
return 'group';
});
|
//rewrite JS code to have something easier to parse
//the JS code is no more an AST, but a sequence of intructions (where some instructions can be sequence too)
//the main function is rewriteJS(fileName)
var esprima = require('esprima');
var fs = require('fs');
var fileName = process.argv[2];
var abst = {};
var tmp_var_id = 0;
//main function
//parse a JS file and returns an abstraction (not a complete CFG)
module.exports.rewriteJS = rewriteJS;
function rewriteJS(fileName) {
//Parse all.js
var data = fs.readFileSync(fileName, 'utf-8');
//console.log(data);
var ast = esprima.parse(data, {
loc: true
});
//init variables
abst = {};
tmp_var_id = 0;
visitNode(ast, abst);
return abst;
};
function visitNode(node, abst) {
switch (node.type) {
case 'Program':
visitProgram(node, abst);
break;
case 'VariableDeclaration':
visitVariableDeclaration(node, abst);
break;
case 'ExpressionStatement':
visitExpressionStatement(node, abst);
break;
case 'UpdateExpression':
visitUpdateExpression(node, abst);
break;
case 'IfStatement':
visitIfStatement(node, abst);
break;
case 'WhileStatement':
visitWhileStatement(node, abst);
break;
case 'ForStatement':
visitForStatement(node, abst);
break;
case 'FunctionDeclaration':
visitFunctionDeclaration(node, abst);
break;
default:
break;
};
};
function visitProgram(node, abst) {
abst.instructions = [];
for (var i = 0; i < node.body.length; i++) {
visitNode(node.body[i], abst);
};
};
function visitVariableDeclaration(node, abst) {
for (var i = 0; i < node.declarations.length; i++) {
var decl = {};
decl.type = 'declare-variable';
decl.x = node.declarations[i].id.name;
abst.instructions.push(decl);
if (node.declarations[i].init) visitVariableInit(node.declarations[i], abst);
};
};
function visitVariableInit(node, abst) {
var write = {};
write.type = 'write-variable';
write.x = node.id.name;
switch (node.init.type) {
case 'Literal':
write.v = node.init.value;
write.jstype = 'Literal';
break;
case 'Identifier':
var read = {};
read.type = 'read-variable';
read.x = node.init.name;
read.v = '__v_' + tmp_var_id;
tmp_var_id++;
abst.instructions.push(read);
write.v = read.v;
write.jstype = 'Identifier';
break;
case 'BinaryExpression':
visitBinaryExpression(node.init, abst);
write.v = abst.instructions[abst.instructions.length - 1].r;
write.jstype = 'Identifier';
break;
case 'UnaryExpression':
visitUnaryExpression(node.init, abst);
write.v = abst.instructions[abst.instructions.length - 1].r;
write.jstype = 'Identifier';
break;
case 'FunctionExpression':
visitFunctionExpression(node.init, abst);
write.v = abst.instructions[abst.instructions.length - 1].id;
write.jstype = 'Identifier';
break;
case 'MemberExpression':
visitMemberExpression(node.init, abst);
write.v = abst.instructions[abst.instructions.length - 1].v;
write.jstype = 'Property';
default:
break;
};
abst.instructions.push(write);
};
function visitArgument(node, abst) {
var arg_v = {};
switch (node.type) {
case 'Literal': //create a new variable for the argument
//create a new variable for the argument
var write = {};
write.type = 'write-variable';
write.x = '__v_' + tmp_var_id;
tmp_var_id++;
write.v = node.value;
write.jstype = 'Literal';
arg_v.name = write.x;
arg_v.type = 'Literal';
abst.instructions.push(write);
break;
case 'Identifier': //nothing to do
arg_v.name = node.name;
arg_v.type = 'Identifier';
break;
case 'BinaryExpression': //create a new variable for the argument
//create a new variable for the argument
var write = {};
write.type = 'write-variable';
write.x = '__v_' + tmp_var_id;
tmp_var_id++;
visitBinaryExpression(node, abst);
write.v = abst.instructions[abst.instructions.length - 1].r;
write.jstype = 'Identifier';
arg_v.name = write.x;
arg_v.type = 'Identifier';
abst.instructions.push(write);
break;
case 'UnaryExpression':
//create a new variable for the argument
var write = {};
write.type = 'write-variable';
write.x = '__v_' + tmp_var_id;
tmp_var_id++;
visitUnaryExpression(node, abst);
write.v = abst.instructions[abst.instructions.length - 1].r;
write.jstype = 'Identifier';
arg_v.name = write.x;
arg_v.type = 'Identifier';
abst.instructions.push(write);
break;
case 'FunctionExpression':
visitFunctionExpression(node, abst);
arg_v.name = abst.instructions[abst.instructions.length - 1].id;
arg_v.type = 'Identifier';
break;
case 'MemberExpression':
visitMemberExpression(node.init, abst);
arg_v.name = abst.instructions[abst.instructions.length - 1].v;
arg_v.type = 'Property';
break;
default:
break;
};
return arg_v;
};
function visitMemberExpression(node, abst) {
var me = {};
me.type = 'read-property';
if (node.object.type === 'Identifier') {
me.object = node.object.name;
} else {
visitMemberExpression(node.object, abst);
me.object = abst.instructions[abst.instructions.length - 1].v;
}
me.property = node.property.name;
me.v = '__p_' + tmp_var_id;
tmp_var_id++;
abst.instructions.push(me);
};
function visitBinaryExpression(node, abst) {
var op = {};
op.type = 'operation';
op.operator = node.operator;
op.arity = 'binary';
switch (node.left.type) {
case 'Literal':
op.x = node.left.value;
op.xjstype = 'Literal';
break;
case 'Identifier':
var read = {};
read.type = 'read-variable';
read.x = node.left.name;
read.v = '__v_' + tmp_var_id;
tmp_var_id++;
abst.instructions.push(read);
op.x = read.v;
op.xjstype = 'Identifier';
break;
case 'BinaryExpression':
visitBinaryExpression(node.left, abst);
op.x = abst.instructions[abst.instructions.length - 1].r;
op.xjstype = 'Identifier';
break;
case 'UnaryExpression':
visitUnaryExpression(node.left, abst);
op.x = abst.instructions[abst.instructions.length - 1].r;
op.xjstype = 'Identifier';
break;
case 'MemberExpression':
visitMemberExpression(node.left, abst);
op.x = abst.instructions[abst.instructions.length - 1].v;
op.xjstype = 'Property';
default:
break;
};
switch (node.right.type) {
case 'Literal':
op.y = node.right.value;
op.yjstype = 'Literal';
break;
case 'Identifier':
var read = {};
read.type = 'read-variable';
read.x = node.right.name;
read.v = '__v_' + tmp_var_id;
tmp_var_id++;
abst.instructions.push(read);
op.y = read.v;
op.yjstype = 'Identifier';
break;
case 'BinaryExpression':
visitBinaryExpression(node.right, abst);
op.y = abst.instructions[abst.instructions.length - 1].r;
op.yjstype = 'Identifier';
break;
case 'UnaryExpression':
visitUnaryExpression(node.right, abst);
op.y = abst.instructions[abst.instructions.length - 1].r;
op.yjstype = 'Identifier';
break;
case 'MemberExpression':
visitMemberExpression(node.right, abst);
op.y = abst.instructions[abst.instructions.length - 1].v;
op.yjstype = 'Property';
default:
break;
};
op.r = '__v_' + tmp_var_id;
tmp_var_id++;
abst.instructions.push(op);
};
function visitUnaryExpression(node, abst) {
var op = {};
op.type = 'operation';
op.arity = 'unary';
op.operator = node.operator;
switch (node.argument.type) {
case 'Literal':
op.x = node.argument.value;
op.xjstype = 'Literal';
break;
case 'Identifier':
var read = {};
read.type = 'read-variable';
read.x = node.argument.name;
read.v = '__v_' + tmp_var_id;
tmp_var_id++;
abst.instructions.push(read);
op.x = read.v;
op.xjstype = 'Identifier';
break;
case 'BinaryExpression':
visitBinaryExpression(node.argument, abst);
op.x = abst.instructions[abst.instructions.length - 1].r;
op.xjstype = 'Identifier';
break;
case 'UnaryExpression':
visitUnaryExpression(node.argument, abst);
op.x = abst.instructions[abst.instructions.length - 1].r;
op.xjstype = 'Identifier';
break;
case 'MemberExpression':
visitMemberExpression(node.argument, abst);
op.x = abst.instructions[abst.instructions.length - 1].v;
op.xjstype = 'Property';
default:
break;
};
op.r = '__v_' + tmp_var_id;
tmp_var_id++;
abst.instructions.push(op);
};
function visitExpressionStatement(node, abst) {
switch (node.expression.type) {
case 'AssignmentExpression':
var write = {};
switch (node.expression.left.type) {
case 'Identifier':
write.type = 'write-variable';
write.x = node.expression.left.name;
break;
case 'MemberExpression':
write.type = 'write-property';
visitMemberExpression(node.expression.left, abst);
write.property = abst.instructions[abst.instructions.length - 1].v;
write.object = abst.instructions[abst.instructions.length - 1].property;
break;
};
switch (node.expression.right.type) {
case 'Literal':
write.v = node.expression.right.value;
write.jstype = 'Literal';
break;
case 'Identifier':
var read = {};
read.type = 'read-variable';
read.x = node.expression.right.name;
read.v = '__v_' + tmp_var_id;
tmp_var_id++;
abst.instructions.push(read);
write.v = read.v;
write.jstype = 'Identifier';
break;
case 'BinaryExpression':
visitBinaryExpression(node.expression.right, abst);
write.v = abst.instructions[abst.instructions.length - 1].r;
write.jstype = 'Identifier';
break;
case 'UnaryExpression':
visitUnaryExpression(node.expression.right, abst);
write.v = abst.instructions[abst.instructions.length - 1].r;
write.jstype = 'Identifier';
break;
case 'FunctionExpression':
visitFunctionExpression(node.expression.right, abst);
write.v = abst.instructions[abst.instructions.length - 1].id;
write.jstype = 'Identifier';
break;
case 'MemberExpression':
visitMemberExpression(node.expression.right, abst);
write.v = abst.instructions[abst.instructions.length - 1].v;
write.jstype = 'Property';
break;
default:
break;
};
abst.instructions.push(write);
break;
case 'CallExpression':
var call = {};
call.type = 'call-expression';
switch (node.expression.callee.type) {
case 'Identifier':
call.callee = node.expression.callee.name;
break;
case 'FunctionExpression':
visitFunctionExpression(node.expression.callee, abst);
call.callee = abst.instructions[abst.instructions.length - 1].id;
break;
case 'MemberExpression':
visitMemberExpression(node.expression.callee, abst);
call.callee = abst.instructions[abst.instructions.length - 1].v;
break;
};
if (node.expression.arguments) {
call.args = [];
for (var i = 0; i < node.expression.arguments.length; i++) {
call.args.push(visitArgument(node.expression.arguments[i], abst));
};
};
abst.instructions.push(call);
break;
default:
break;
};
};
function visitUpdateExpression(node, abst) {
if (node.argument.type == 'Identifier') {
var read = {};
read.type = 'read-variable';
read.x = node.argument.name;
read.v = '__v_' + tmp_var_id;
tmp_var_id++;
abst.instructions.push(read);
var op = {};
op.type = 'operation';
op.operator = node.operator.substring(0, 1);
op.arity = 'binary';
op.x = read.v;
op.xjstype = 'Identifier';
op.y = 1;
op.yjstype = 'Literal';
op.r = '__v_' + tmp_var_id;
tmp_var_id++;
abst.instructions.push(op);
var write = {};
write.type = 'write-variable';
write.x = node.argument.name;
write.v = op.r;
write.jstype = 'Identifier';
abst.instructions.push(write);
} else { //Literal?
};
};
function visitTest(node, abst) {
switch (node.type) {
case 'Identifier':
var read = {};
read.type = 'read-variable';
read.x = node.name;
read.v = '__v_' + tmp_var_id;
tmp_var_id++;
abst.instructions.push(read);
break;
case 'BinaryExpression':
visitBinaryExpression(node, abst);
break;
case 'UnaryExpression':
visitUnaryExpression(node, abst);
break;
default:
break;
};
};
function visitIfStatement(node, abst) {
var ifi = {};
ifi.type = 'if';
//test
ifi.test = {};
ifi.test.instructions = [];
visitTest(node.test, ifi.test);
//consequent
ifi.consequent = {};
ifi.consequent.instructions = [];
switch (node.consequent.type) {
case 'ExpressionStatement':
visitExpressionStatement(node.consequent, ifi.consequent);
break;
case 'BlockStatement':
for (var i = 0; i < node.consequent.body.length; i++) {
visitNode(node.consequent.body[i], ifi.consequent);
};
break;
};
//alternate
if (node.alternate) {
ifi.alternate = {};
ifi.alternate.instructions = [];
switch (node.alternate.type) {
case 'ExpressionStatement':
visitExpressionStatement(node.alternate, ifi.alternate);
break;
case 'BlockStatement':
for (var i = 0; i < node.alternate.body.length; i++) {
visitNode(node.alternate.body[i], ifi.alternate);
};
break;
};
};
abst.instructions.push(ifi);
};
function visitWhileStatement(node, abst) {
var we = {};
we.type = 'while';
//test
we.test = {};
we.test.instructions = [];
visitTest(node.test, we.test);
//body
we.body = {};
we.body.instructions = [];
if (node.body.type === 'BlockStatement') {
for (var i = 0; i < node.body.body.length; i++) {
visitNode(node.body.body[i], we.body);
};
} else visitNode(node.body, we.body);
abst.instructions.push(we);
};
function visitInit(node, abst) {
switch (node.type) {
case 'VariableDeclaration':
visitVariableDeclaration(node, abst);
break;
case 'AssignmentExpression':
var write = {};
write.type = 'write-variable';
write.x = node.left.name;
switch (node.right.type) {
case 'Literal':
write.v = node.right.value;
write.jstype = 'Literal';
break;
case 'Identifier':
var read = {};
read.type = 'read-variable';
read.x = node.right.name;
read.v = '__v_' + tmp_var_id;
tmp_var_id++;
abst.instructions.push(read);
write.v = read.v;
write.jstype = "Identifier";
break;
case 'BinaryExpression':
visitBinaryExpression(node.right, abst);
write.v = abst.instructions[abst.instructions.length - 1].r;
write.jstype = "Identifier";
break;
case 'UnaryExpression':
visitUnaryExpression(node.right, abst);
write.v = abst.instructions[abst.instructions.length - 1].r;
write.jstype = "Identifier";
break;
default:
break;
};
abst.instructions.push(write);
break;
case 'UnaryExpression':
visitUnaryExpression(node, abst);
break;
default:
break;
};
};
function visitForStatement(node, abst) {
var fo = {};
fo.type = 'for';
fo.init = {};
fo.init.instructions = [];
visitInit(node.init, fo.init);
fo.update = {};
fo.update.instructions = [];
visitNode(node.update, fo.update);
fo.body = {};
fo.body.instructions = [];
if (node.body.type === 'BlockStatement') {
for (var i = 0; i < node.body.body.length; i++) {
visitNode(node.body.body[i], fo.body);
};
} else visitNode(node.body, fo.body);
abst.instructions.push(fo);
};
function visitFunctionDeclaration(node, abst) {
var fun = {};
fun.type = 'function-declaration';
fun.body = {};
fun.body.instructions = [];
fun.id = node.id.name;
//params
fun.params = [];
if (node.params) {
for (var i = 0; i < node.params.length; i++) {
var type = node.params[i].type;
var iden = node.params[i].name;
if (type === 'Identifier') fun.params.push(iden);
};
}
//body
if (node.body.type === 'BlockStatement') {
for (var i = 0; i < node.body.body.length; i++) {
visitNode(node.body.body[i], fun.body);
};
} else visitNode(node.body, fun.body);
abst.instructions.push(fun);
};
function visitFunctionExpression(node, abst) {
var fun = {};
fun.type = 'function-expression';
fun.body = {};
fun.body.instructions = [];
fun.id = '__f_' + tmp_var_id;
tmp_var_id++;
//params
fun.params = [];
if (node.params) {
for (var i = 0; i < node.params.length; i++) {
var type = node.params[i].type;
var iden = node.params[i].name;
if (type === 'Identifier') fun.params.push(iden);
};
}
if (node.body.type === 'BlockStatement') {
for (var i = 0; i < node.body.body.length; i++) {
visitNode(node.body.body[i], fun.body);
};
} else visitNode(node.body, fun.body);
abst.instructions.push(fun);
}
|
import React, { useEffect, useState } from "react";
import CircularProgress from "@material-ui/core/CircularProgress";
import Footer from "../components/Footer";
import { useParams, NavLink } from "react-router-dom";
import axios from "axios";
import "./styles/bookdetail.css";
import ArrowBackIcon from "@material-ui/icons/ArrowBack";
import BookIcon from "@material-ui/icons/Book";
// import FavoriteIcon from "@material-ui/icons/Favorite";
import Tooltip from "@material-ui/core/Tooltip";
import Snackbar from "@material-ui/core/Snackbar";
import FavoriteIcon from "@material-ui/icons/Favorite";
import { db } from "../firebase";
function BookDetails() {
const { id, uid } = useParams();
const apiKey = "AIzaSyBJe4Z5KP2Hhg5s_vFDCbe8stRDNCeUoE4";
const [book, setBook] = useState({});
const [bookimg, setBookimg] = useState("");
const [wishlist, setWishlist] = useState({});
const [loading, setLoading] = useState(false);
const [alert, setAlert] = useState({ showSnackbar: false, message: "" });
const closeSnack = () => {
setAlert({
showSnackbar: false,
});
};
const addtoWishlist = () => {
db.collection("wishlist")
.add({
user_id: uid,
wish_id: wishlist.id,
title: wishlist.volumeInfo.title,
author: wishlist.volumeInfo.authors,
image: wishlist.volumeInfo.imageLinks.thumbnail,
})
.then((res) => {
setAlert({
showSnackbar: true,
message: "Item added successfully",
});
});
};
useEffect(() => {
setLoading(true);
axios
.get(`https://www.googleapis.com/books/v1/volumes/${id}?key=${apiKey}`)
.then((response) => {
setBook(response.data.volumeInfo);
setBookimg(response.data.volumeInfo.imageLinks);
setWishlist(response.data);
setLoading(false);
})
.catch((error) => {
console.log(error);
});
}, []);
if (loading) {
return (
<CircularProgress
color="secondary"
size="5rem"
style={{ marginTop: "20vh", marginLeft: "48vw" }}
/>
);
} else {
return (
<>
<div className="book_details">
<div className="book_details_desc" key={book.id}>
<p>Publisher : {book.publisher}</p>
<p>Published Date : {book.publishedDate}</p>
<p className="category">Category : {book.categories}</p>
<p>Total Page : {book.printedPageCount}</p>
<p>
Preview :
<a href={book.previewLink} target="_blank" rel="noreferrer">
{book.previewLink}
</a>
</p>
<div className="buttons">
<NavLink
to={`/library/${uid}`}
style={{ textDecoration: "none" }}
>
<Tooltip title="back to previous" aria-label="SearchBooks">
<ArrowBackIcon style={{ fontSize: "2rem", color: "black" }} />
</Tooltip>
</NavLink>
<Tooltip title="Add to Favourite" aria-label="SearchBooks">
<FavoriteIcon
style={{ fontSize: "2rem", color: "red" }}
onClick={addtoWishlist}
/>
</Tooltip>
<a href={book.previewLink} target="_blank" rel="noreferrer">
<Tooltip title="read the book" aria-label="SearchBooks">
<BookIcon style={{ fontSize: "2rem", color: "black" }} />
</Tooltip>
</a>
</div>
</div>
<div className="book_img">
<img src={bookimg.thumbnail} alt="Book" />
<p>Title : {book.title}</p>
<p>Author : {book.authors}</p>
</div>
</div>
<Snackbar
anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
open={alert.showSnackbar}
message={alert.message}
autoHideDuration={3000}
onClose={closeSnack}
/>
<Footer />
</>
);
}
}
export default BookDetails;
|
import React from "react";
function SystemSelectionMenu(){
return(
<div>
<h1>SystemSelectionMenu</h1>
</div>
);
}
export default SystemSelectionMenu;
|
export {default as AppNavigation} from './AppNavigation';
export {default as AppContainer} from './AppContainer';
|
import React from 'react';
import { shallow } from 'enzyme';
import Field from '../Field';
describe('Field Component Tests', () => {
const component = shallow(<Field/>);
const mockOnChange = jest.fn();
test('Check if component renders without failure', () => {
expect(component.find('input').length).toBe(1);
});
test('Check if component works with value prop', () => {
component.setProps({ value: 'Hello' });
expect(component.find('input').props().value).toBe('Hello');
});
test('Check if component triggers onCHange', () => {
component.setProps({ onChange: mockOnChange });
component.find('input').simulate('change', { value: 'Talk' });
expect(mockOnChange).toHaveBeenCalled();
expect(mockOnChange).toHaveBeenCalledTimes(1);
});
});
|
#!/usr/bin/env node
'use strict';
process.title = 'arc-changelog';
const colors = require('colors/safe');
const gulp = require('gulp');
const conventionalChangelog = require('gulp-conventional-changelog');
function makeChangelog() {
console.log('Creating changelog...');
return new Promise((resolve, reject) => {
gulp.src('CHANGELOG.md', {
buffer: false
})
.pipe(conventionalChangelog({
preset: 'eslint' // Or to any other commit message convention you use.
}))
.pipe(gulp.dest('./'))
.on('data', function() {})
.on('end', function() {
resolve();
})
.on('error', function(e) {
reject(new Error('Can not create changelog. ' + e.message));
});
});
}
try {
makeChangelog().then(() => {
process.exit(0);
}).catch((err) => {
console.log(err);
process.exit(1);
});
} catch (e) {
console.log(colors.red(' ' + e.message));
process.exit(1);
}
|
// generated by Neptune Namespaces v4.x.x
// file: tests/Art.EryExtensions.Aws/DynamoDbPipeline/index.js
(module.exports = require('./namespace'))
.addModules({
Basics: require('./Basics'),
CrossPipelineEvents: require('./CrossPipelineEvents'),
Indexes: require('./Indexes')
});
|
import { connect } from 'react-redux';
import dictList from './dictList';
import { removeDictionary, toggleWordCreator } from '../../../../actions/actions';
import { getDictionaries } from '../../../../reducers/getState';
const mapStateToProps = (state) => {
return {
dictionaries: getDictionaries(state.dictionaries, state.selectedGroup),
groupId: state.selectedGroup
}
};
const mapDispatchToProps = (dispatch) => {
return {
onRemoveDict: (id, gropuId) => {
dispatch(removeDictionary(id, gropuId));
},
onDictChange: (id, change, name, repeat, list) => {
dispatch(toggleWordCreator(id, change, name, repeat, list));
}
};
};
const Dictionaries = connect(
mapStateToProps,
mapDispatchToProps
)(dictList);
export default Dictionaries;
|
import React from 'react';
import './ImageLinkForm.css'
const ImageLinkForm = ({onInputChange, onButtonSubmit}) =>{
return(
<div>
<p className="f3" style={{color:"blue"}}>
{'This Application will detect faces in your uploaded images. Have fun!'}
</p>
<div className="center">
<div className="form center pa4 br1 shadow-3 w-50">
<input className="f3 pa2 w-70" type="text" onChange={onInputChange} placeholder="Insert Image URL" />
<button className="w-30 grow f3 link pv3 dib white bg-black" onClick={onButtonSubmit}>Detect</button>
</div>
</div>
</div>
);
}
export default ImageLinkForm;
|
const edfFrontBoxStyle = {
height: '100%',
padding: '25px 0 5px 2px',
borderRadius: '4px',
boxShadow: '2px 2px 8px -3px rgba(0, 0, 0, 0.5)',
backgroundColor: '#eef1f6',
display: 'flex',
flexDirection: 'column'
}
const edfBackBoxStyle = {
...edfFrontBoxStyle,
padding: '0 0 5px 2px',
}
const edfImgWrapStyle = {
flex: 1,
paddingRop: '25px'
}
const edfFrontTitleStyle = {
width: '100%',
height: '40px',
fontFamily: 'Avenir',
fontSize: '13px',
lineHeight: '40px',
fontWeight: '900',
letterSpacing: '0.12px',
textAlign: 'center',
color: '#706f6f'
}
const edfBackTitleStyle = edfFrontTitleStyle
const edfBackConntentStyle = {
width: '100%',
flex: 1,
fontFamily: 'Avenir',
fontSize: '13px',
lineHeight: '40px',
fontWeight: '900',
letterSpacing: '0.12px',
textAlign: 'center',
color: '#706f6f'
}
const imgStyle = {
width: '100%',
height: '100%',
objectFit: 'cover'
}
export var EDFCard2 = (props) => {
let render = (
<div style={edfFrontBoxStyle}>
<div style={edfImgWrapStyle}>
<img style={imgStyle} src={props.coverImage}/>
</div>
<div style={edfFrontTitleStyle}>
{props.title}
</div>
</div>
)
if (props.type === 'back') {
render = (
<div className='back-container' style={edfBackBoxStyle}>
<div className='back-title' style={edfBackTitleStyle}>
{props.title}
</div>
<div style={edfBackConntentStyle}>
{props.content}
</div>
</div>
)
}
return (render)
}
|
/*changePanel
* Used to swap divs that are of the same container type (css class)
* panel - the id of the panel to display
* containers - the class that is associated with the group of divs
*/
function changePanel(CollectionName,TabName)
{
jQuery('.'+CollectionName).hide();
jQuery('#'+TabName).fadeIn();
return false;
}
|
import React, { Component } from 'react';
import 'react-bootstrap';
class Blog extends Component{
render() {
return (
<div>
<section className="engine">
<a rel="external" href="https://mobirise.com">https://mobirise.com/
</a></section>
<section className="mbr-section article mbr-parallax-background mbr-after-navbar blog-background" id="msg-box8-8">
<div className="mbr-overlay blog-overlay-custom">
</div>
<div className="container">
<div className="row">
<div className="col-md-8 col-md-offset-2 text-xs-center">
<h3 className="mbr-section-title display-2">Blog</h3>
<div className="lead"><p>Article header with background image and parallax effect.</p></div>
</div>
</div>
</div>
</section>
<section className="mbr-section mbr-section__container article blog-article-container-custom" id="header3-9">
<div className="container">
<div className="row">
<div className="col-xs-12">
<h3 className="mbr-section-title display-2">Colors and shades</h3>
<small className="mbr-section-subtitle">By Deborah Lazar on 12.54.15</small>
</div>
</div>
</div>
</section>
<section className="mbr-section article mbr-section__container blog-content-custom" id="content7-a">
<div className="container">
<div className="row">
<div className="col-xs-12 col-md-4 lead"><p>Make your own website in a few clicks! Mobirise helps you cut down development time by providing you with a flexible website editor with a drag and drop interface. MobiRise Website Builder creates responsive, retina and mobile friendly websites in a few clicks. Mobirise is one of the easiest website development tools available today. It also gives you the freedom to develop as many websites as you like given the fact that it is a desktop app.</p></div>
<div className="col-xs-12 col-md-4 lead"><p>Make your own website in a few clicks! Mobirise helps you cut down development time by providing you with a flexible website editor with a drag and drop interface. MobiRise Website Builder creates responsive, retina and mobile friendly websites in a few clicks. Mobirise is one of the easiest website development tools available today. It also gives you the freedom to develop as many websites as you like given the fact that it is a desktop app.</p></div>
<div className="col-xs-12 col-md-4 lead"><p>Make your own website in a few clicks! Mobirise helps you cut down development time by providing you with a flexible website editor with a drag and drop interface. MobiRise Website Builder creates responsive, retina and mobile friendly websites in a few clicks. Mobirise is one of the easiest website development tools available today. It also gives you the freedom to develop as many websites as you like given the fact that it is a desktop app.</p></div>
</div>
</div>
</section>
<section className="mbr-section mbr-section__container blog-section-container-custom" id="buttons1-b">
<div className="container">
<div className="row">
<div className="col-xs-12">
<div className="text-xs-center"><a className="btn btn-primary" href="https://mobirise.com/mobirise-free-win.zip">Comment</a> </div>
</div>
</div>
</div>
</section>
<section className="mbr-section article mbr-section__container blog-section-container-custom" id="content2-c">
<div className="container">
<div className="row">
<div className="col-xs-12 lead"><blockquote><p>comment by jflkaj;ean anwe on </p><p>Make your own website in a few clicks! Mobirise helps you cut down development time by providing you with a flexible website editor with a drag and drop interface. MobiRise Website Builder creates responsive, retina and mobile friendly websites in a few clicks. Mobirise is one of the easiest website development tools available today. It also gives you the freedom to develop as many websites as you like given the fact that it is a desktop app.</p></blockquote></div>
</div>
</div>
</section>
<footer className="mbr-small-footer mbr-section mbr-section-nopadding blog-footer-color" id="footer1-7">
<div className="container">
<p className="text-xs-center">Copyright (c) 2016 Artworking</p>
</div>
</footer>
</div>
)
}
}
export default Blog
|
$(function () {
$(document).on("click", ".sig_btn", function () {
var phoneid = $.trim($("#sig_mobile").find(".sig_input").val());
var username = $.trim($("#sig_name").find(".sig_input").val());
// alert(username);
var userpwd = $.trim($("#sig_pwd").find(".sig_input").val());
var againpwd = $.trim($("#sig_confirmpwd").find(".sig_input").val());
var regphoneid = /^[1][358]\d{9}$/;
var regname = /^[a-zA-Z0-9_]{3,19}$/;
var regpwd = /^[a-zA-Z0-9_]{6,16}$/;
if (phoneid == "") {
$("#sig_mobile").find(".sig_erro").html(" x 手机号不能为空");
} else {
if (!regphoneid.test(phoneid)) {
$("#sig_mobile").find(".sig_erro").html(" x 手机号格式不正确");
} else {
$("#sig_mobile").find(".sig_erro").html("");
}
}
if (username == "") {
$("#sig_name").find(".sig_erro").html(" x 用户名不能为空");
} else {
$("#sig_name").find(".sig_erro").html();
if (!regname.test(username)) {
$("#sig_name").find(".sig_erro").html(" x 用户名不符合要求");
} else {
$("#sig_name").find(".sig_erro").html("");
}
}
if (userpwd == "") {
$("#sig_pwd").find(".sig_erro").html(" x 密码不能为空");
} else {
if (!regpwd.test(userpwd)) {
$("#sig_pwd").find(".sig_erro").html(" x 密码不符合要求");
} else {
$("#sig_pwd").find(".sig_erro").html("");
}
}
if (againpwd == "") {
$("#sig_confirmpwd").find(".sig_erro").html(" x 请确认密码");
} else {
if (userpwd != againpwd) {
$("#sig_confirmpwd").find(".sig_erro").html(" x 密码输入不一致");
} else {
$("#sig_confirmpwd").find(".sig_erro").html("");
}
}
var phoneerro = $("#sig_mobile").find(".sig_erro").html();
var nameerro = $("#sig_name").find(".sig_erro").html();
var pwderro = $("#sig_pwd").find(".sig_erro").html();
var againerro = $("#sig_confirmpwd").find(".sig_erro").html();
if (phoneerro == "" && nameerro == "" && pwderro == "" && againerro == "") {
window.location.href = "login.html";
}
});
//手机号获得与失去焦点
$("#sig_mobile").find(".sig_input").focus(function () {
$(this).parent().parent().find(".sig_erro").html("");
});
$("#sig_mobile").find(".sig_input").blur(function () {
//查看此号码是否已被注册
//var val = $(this).val();
// $.ajax({
// type:"POST",
// url:"http://api.iwd.hk:81",
// dataType:"json",
// // contentType:"application/json",
// data:{json:'{"class":"login","table":"person","phone":"+86' + val + '","password":"cc880108"}'},
// //type: 'json',
// success:function(res){
// if(res.phone != "");
// $("#sig_mobile").find(".sig_erro").html(" ! 该手机号已被注册");
// }
// });
});
//用户名获得焦点
$("#sig_name").find(".sig_input").focus(function () {
$(this).parent().parent().find(".sig_erro").html("");
});
//密码获得焦点
$("#sig_pwd").find(".sig_input").focus(function () {
$(this).parent().parent().find(".sig_erro").html("");
});
//确认密码框获得焦点
$("#sig_confirmpwd").find(".sig_input").focus(function () {
$(this).parent().parent().find(".sig_erro").html("");
});
});
|
export * from './MyCustomAdapter';
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, hashHistory, IndexRoute } from 'react-router'
import { authCheck } from './services/auth';
// Styles
import 'bootstrap/dist/css/bootstrap.css';
import './index.css';
// Components
import App from './App';
import NotFound from './components/NotFound';
import Main from './components/Main';
import LoginForm from './components/auth/LoginForm';
import PasswordReset from './components/auth/PasswordReset';
import NewUserByEmail from './components/auth/NewUserByEmail';
const routing = (
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Main} onEnter={authCheck}/>
<Route path="/home" component={Main} onEnter={authCheck}/>
<Route path="/register" component={NewUserByEmail}/>
<Route path="/login" component={LoginForm}/>
<Route path="/reset-pwd" component={PasswordReset}/>
<Route path="*" component={NotFound}/>
</Route>
</Router>
)
ReactDOM.render(
routing, document.getElementById('root')
)
|
import { use, assert, expect } from "chai";
import assertArrays from "chai-arrays";
import mocha from "mocha";
import getMovies from "../movie";
use(assertArrays);
var moviesResult = null;
//get the first movie as the sample test with
var movieResult = null;
function resetResults() {
moviesResult = movieResult = null;
}
describe("Movie", () => {
describe("App-getMOvies", () => {
it("Movies object shouldnt be null", done => {
getMovies(moviesResult => {
assert.isNotNull(moviesResult);
done();
});
});
it("Movies should be an array", (done)=> {
getMovies((moviesResult)=> {
expect(moviesResult).to.be.array();
done();
});
});
it("Movies arrays should have atleast one movie exists in the datasource", (done)=> {
getMovies((moviesResult)=> {
expect(moviesResult).not.to.be.ofSize(0);
done();
});
});
it("movie has key properties if at least one movie exists in the datasource", (done) => {
getMovies((moviesResult)=> {
movieResult = moviesResult[0];
assert.property(
movieResult,
"title",
"movie doesnt have a title property"
);
assert.property(movieResult, "id", "movie doesnt have an id property");
assert.property(
movieResult,
"sessions",
"movie doesnt have the sessions property"
);
// this doesnt work chai.assert.deepProperty(movieResult, "sessions.location");
done();
});
});
});
});
|
jQuery(document).ready(function () {
jQuery('form.repeater').repeater({
// (Optional)
// "defaultValues" sets the values of added items. The keys of
// defaultValues refer to the value of the input's name attribute.
// If a default value is not specified for an input, then it will
// have its value cleared.
defaultValues: {
'text-input': 'foo'
},
// (Optional)
// "show" is called just after an item is added. The item is hidden
// at this point. If a show callback is not given the item will
// have $(this).show() called on it.
show: function () {
jQuery(this).slideDown();
},
// (Optional)
// "hide" is called when a user clicks on a data-repeater-delete
// element. The item is still visible. "hide" is passed a function
// as its first argument which will properly remove the item.
// "hide" allows for a confirmation step, to send a delete request
// to the server, etc. If a hide callback is not given the item
// will be deleted.
hide: function (deleteElement) {
if(confirm('Are you sure you want to delete this element?')) {
jQuery(this).slideUp(deleteElement);
}
},
repeaters: [{
// (Required)
// Specify the jQuery selector for this nested repeater
selector: '.repeater-item div.mfef-field-repeater:not([data-repeater-list])'
}]
});
jQuery('#mfef_btn_cancel').bind('click', confirm_cancel);
});
function confirm_cancel() {
return confirm( 'Are you sure you want to cancel?' );
}
|
import React from 'react'
import { Text, View, StyleSheet } from 'react-native'
const styles = StyleSheet.create({
title: {
fontSize: 100
}
})
const TestScreen = () => {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text style={styles.title}>Test</Text>
</View>
)
}
export default TestScreen
|
// Project : Drug Approval Analytics
// Version : 0.1.0
// File : \src\utils\scrapers.js
// Language : Python 3.9.5
// -----------------------------------------------------------------------------
// Author : John James
// Company : nov8.ai
// Email : john.james@nov8.ai
// URL : https://github.com/john-james-sf/drug-approval-analytics
// -----------------------------------------------------------------------------
// Created : Sunday, July 18th 2021, 7:33:27 am
// Modified : Sunday, July 18th 2021, 7:38:11 am
// Modifier : John James (john.james@nov8.ai)
// -----------------------------------------------------------------------------
// License : BSD 3-clause "New" or "Revised" License
// Copyright: (c) 2021 nov8.ai
const puppeteer = require('puppeteer');
const express = require('express');
const app = express();
const port = 3000;
app.get('/', async (req, res) => {
const {url} = req.query;
if(!url) {
res.status(400).send("Bad request: 'url' param is missing!");
return;
}
try {
const html = await getPageHTML(url);
res.status(200).send(html);
} catch (error) {
res.status(500).send(error);
}
});
const getPageHTML = async (pageUrl) => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(pageUrl);
const pageHTML = await page.evaluate('new XMLSerializer().serializeToString(document.doctype) + document.documentElement.outerHTML');
await browser.close();
return pageHTML;
}
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
|
const express=require('express')
const route=express.Router();
const theauth=require('../middelware/check')
const order=require('../model/ordercol')
const product=require('../model/productcol')
route.get('/',async(req,res)=>{
const find=await order.find()
.then((data)=>{
const ans={
count:data.length,
order:data
}
res.status(200).json({ message:ans});
})
.catch((err)=>{res.status(404).json({ message:err});})
})
route.post('/',theauth,async(req,res)=>{
product.findById(req.body.productid)
.then((products)=>{
if(!products){
return res.json({message:"id not found"})
}
const obj={
quentity:req.body.quentity,
product:req.body.productid
}
const insert=new order(obj)
return insert.save()
}).then(data=>{
const ans={
count:data.length,
product:data,
details:{
url:'http://localhost:4000/order/'+data.id
}
}
res.status(200).json({ message:ans});
})
.catch((err)=>{res.status(404).json({ message:err});});
})
route.get('/:id',async(req,res)=>{
var id=req.params.id;
const find=await order.findById(id,' quentity product')
.then((data)=>{
if(data){
res.status(200).json({ message:data});
}
else{
res.status(404).json({ message:"not valid id"});
}
})
.catch((err)=>{res.status(404).json({ message:err});})
})
route.delete('/:id',theauth,async(req,res)=>{
var id=req.params.id;
console.log("delete")
const del=await order.findByIdAndDelete(id)
res.status(200).json({ message:"product delete byid",delete:del});
})
module.exports=route;
|
import {useState, useEffect} from "react";
import {Link} from "react-router-dom";
import axios from "axios";
import AvatarImg from "../../assets/img/main1.jpg";
import PostImgCarousel from "../../components/sub/PostImgCarousel";
import CommentCard from "../../components/card/CommentCard";
import PostFooter from "../../components/navigation/PostFooter";
import PostTextData from "../../components/misc/PostTextData";
import NotFoundDiv from "../../components/misc/NotFoundDiv";
import LoadingDiv from "../../components/misc/LoadingDiv";
import Moment from 'react-moment';
import * as AiIcons from "react-icons/ai";
const SinglePostSection = ({devApi, devURL, token, current_user,
reloadPost, setCurrentComponent}) => {
const [post, setPost] = useState({});
const [body, setBody] = useState(null);
const [notFound, setNotFound] = useState(false);
const [loading, setLoading] = useState(true);
const _id = window.location.pathname.split("/")[2];
useEffect(() => {
setCurrentComponent("single_post");
axios({
method: 'GET',
url: `${devApi}post/${_id}/get/`,
headers: {
'Authorization': token
}
}).then((res) => {
if (res.data.message !== false){
setPost(res.data.post);
var __data = res.data.post.body;
__data = __data.replace(/(^|\W)(#[a-z\d][\w-]*)/ig,
'$1<a class="hightlight_text" href="/tags/$2">$2</a>');
__data = __data.replace(/(^|\W)(@[a-z\d][\w-]*)/ig,
'$1<a class="hightlight_text" href="/profile/$2">$2</a>');
setBody(__data);
}else{
setNotFound(true)
}
setLoading(false);
});
}, [devApi, token, _id, setCurrentComponent]);
return (
<>
{
loading?
<div className={`col-xl-5 col-lg-5
col-md-7 col-sm-10 col-12`}
id="content_col">
<LoadingDiv />
</div>
:
<>
{
notFound === true?
<NotFoundDiv
text="This Page is Not Available, Post Was Deleted"
style={{
color: "lightgrey",
fontFamily: "var(--arima)",
fontSize: "23px",
paddingLeft: "20px",
paddingRight: "20px",
paddingTop: "10px"
}}
/>
:
<>
<div className={`col-xl-5 col-lg-5
col-md-7 col-sm-7 col-12`}
id="content_col">
<div className="card post_card" id="singlepost_card">
<div className="header">
<Link to={`/user/${post.author_data.username}/`}>
<img
src={AvatarImg}
alt="postAuthorImg"
/>
<span className="username">
@{post.author_data.username}
{
post.author_data.verified === true?
<AiIcons.AiFillCheckCircle
className="verified"
/>:''
}
</span>
</Link>
<i id="upload_time">
<Moment fromNow>{post.date_added}</Moment>
</i>
</div>
<div className="body">
{
post.image.length > 0 ?
<PostImgCarousel
imageData={post.image}
devURL={devURL}
/>
:''
}
{
post.body.length > 0?
<PostTextData
body={body !== null?body:''}
toggle={false}
style={{
marginTop:"5px",
marginBottom:"0px"
}}
/>
:''
}
</div>
<PostFooter
post={post}
current_user={current_user}
token={token}
devApi={devApi}
devURL={devURL}
nullComment={true}
reloadPost={reloadPost}
/>
</div>
</div>
<div className="col-xl-4 col-lg-4"
id="rightbar_col">
<CommentCard
token={token}
devApi={devApi}
__id={window.location.pathname.split("/")[2]}
current_user={current_user}
/>
</div>
</>
}
</>
}
</>
)
}
export default SinglePostSection;
|
function myFizzBuzz(num) {
if (typeof num !== 'number') return false;
if (num % 3 === 0 && num % 5 === 0) return 'fizzbuzz';
if (num % 3 === 0) return 'fizz';
if (num % 5 === 0) return 'buzz';
return num;
}
const expected = myFizzBuzz(7)
test('Check that it is not divisible 5 and 3' , () => {
expect(expected).toBe(7);
})
|
const { bindActionCreators } = require('redux')
module.exports = function wrapActionCreators(actionCreators) {
return dispatch => bindActionCreators(actionCreators, dispatch)
}
|
const User = require('../models/user.model');
module.exports = function(async, Group){
return{
SetRouting : function(router){
router.get('/results', this.getResults);
router.post('/results', this.postResults);
},
getResults: function(req, res){
res.redirect('/home');
},
postResults : function(req, res){
async.parallel([
function (callback) {
const Regex = new RegExp((req.body.name), 'gi');
Group.find({'$or': [{'name': Regex}, {'title': Regex}]}, (err, result) => {
callback(err, result);
})
},
function (callback) {
User.findOne({ 'username': req.user.username })
.populate('request.userId')
.exec((err, result) => {
callback(err, result);
})
}
], (err, results) => {
const res1 = results[0];
const res2 = results[1];
const dataChunk =[];
const chunksize = 4;
for(let i =0; i < res1.length; i+= chunksize)
{
dataChunk.push(res1.slice(i, i + chunksize));
}
res.render('results', { title: 'ALTP | Home', chunks: dataChunk , user: req.user,data: res2});
})
}
}
}
|
import React from 'react';
import { PieChart, Pie, Sector, Cell, Tooltip } from 'recharts';
import {observer, inject} from 'mobx-react';
const COLORS = ['#0088FE', '#00C49F', '#FF8042'];
@inject("ViewStore", "ApiStore") @observer class PollChart extends React.Component{
constructor(props) {
super(props);
this.state = {
active: -1
}
}
resize = () => this.forceUpdate()
componentDidMount() {
window.addEventListener('resize', this.resize)
this.resize();
}
componentWillUnmount() {
window.removeEventListener('resize', this.resize)
}
render() {
if (!this.props.ApiStore.voted.get()) {
let store = this.props.ViewStore;
let poll = store.getProperty("currentPoll");
let colorMap = store.getProperty("colorMap")
let opts = [...poll.options];
opts.forEach((el, ind) => {el.id = ind})
let colorPick = (ind) => {
let color = colorMap[ind];
if (store.activeOptionIndex == ind) {
color = "rgba(0, 0, 0, 0.4)";
}
return color;
}
let height = 0;
let width = 0;
let parent = document.getElementById('chart-container');
if (parent) {height = parent.clientHeight
width = parent.clientWidth;
}
return(<div className = "flex-item">
<PieChart width={width*0.99} height= {height*0.99}>
<Pie data={opts} dataKey="votes" nameKey="name"
cx="50%" cy="50%" innerRadius={height*0.28} outerRadius={height*0.4} fill="#82ca9d"
onMouseOver = {(e) => {store.activeOptionIndex.set(e.payload.id); }}
onClick = {(e) => {store.chosenOptionIndex.set(e.payload.id);
this.props.ApiStore.newOption.set("")}}
onMouseLeave = {(e) => {/*store.activeOptionIndex.set(-1);*/}}
activeIndex={store.activeOptionIndex.get()}
activeShape = {(e) => (<g>
<text className = "chosen-sector" x={e.cx} y={e.cy} dy={8} textAnchor="middle" fill={"white"}>{(e.percent*100).toFixed(2) + "%"}</text>
<Sector
className = "option-cell"
cx={e.cx}
cy={e.cy}
startAngle={e.startAngle}
endAngle={e.endAngle}
innerRadius={height*0.28}
outerRadius={height*0.4}
stroke = "#FF5960" stroke-width = {5}
fill={e.payload.fill}
/>
</g>)}>
{
opts.map((entry, index) =>
<Cell className = "option-cell" fill = {colorPick(index)} stroke = "black"/>)
}
</Pie>
</PieChart>
</div>
)
} else {this.props.ApiStore.voted.set(false); return null }
}
}
export default PollChart;
|
"use strict";
var bcrypt = require('bcrypt-nodejs');
var SALT_WORK_FACTOR = 10;
var crypto = require('crypto');
module.exports.createRandomHash = function () {
var currentDate = (new Date()).valueOf().toString();
var random = Math.random().toString();
return crypto.createHash('sha1').update(currentDate + random).digest('hex');
};
module.exports.hash = function (password) {
var salt = bcrypt.genSaltSync();
return bcrypt.hashSync(password, salt);
};
module.exports.compare = function (password, hash) {
return bcrypt.compareSync(password, hash);
};
|
var $window = $(window);
var $up = $('#up');
function checkScroll(event){
var scrollTop = $window.scrollTop();
var 업버튼_보여질_포지션 = 100;
if(scrollTop > 업버튼_보여질_포지션) {
$up.fadeIn();
}
}
function goTop(){
$('html, body').animate({scrollTop:0}, 400);
}
$window.on('scroll', checkScroll);
$up.click(goTop);
|
class SymbolTable {
constructor(parent) {
this.parent = parent;
this.symbols = {};
this.symbolCnt = 0;
}
addSymbol(declNode) {
this.symbolCnt += 1;
this.symbols[declNode.symbol.raw] = { idx: this.symbolCnt, declNode };
}
symbolDefined(raw) {
return this.symbols[raw];
}
getSymbol(raw) {
for (let table = this; table; table = table.parent) {
if (table.symbols[raw]) {
return table.symbols[raw];
}
}
return null;
}
}
exports.SymbolTable = SymbolTable;
|
const autoprefixer = require('autoprefixer')
//后处理css css编译完成后(stylus -> css) 通过autoprefixer优化-->css属性加前缀(兼容浏览器)
module.exports = {
plugins: [
autoprefixer()
]
}
|
//Number
//Prototype
// IF, IFELSE, ELSE
Number.prototype.entre = function (inicio, fim) {
return this >= inicio && this <= fim
}
const imprimirResultado = function (nota ) {
if(nota.entre(9, 10)) {
console.log(nota + ' Quadro de honra')
} else if (nota.entre(7, 8.99)) {
console.log(nota + ' Aprovado')
} else if (nota.entre(4, 6.99)) {
console.log(nota + ' Recuperação')
} else if (nota.entre(0, 3.99)) {
console.log(nota + ' Reprovado')
} else {
console.log(nota + ' Nota indisponivel')
}
console.log('-----------------------')
}
imprimirResultado(2)
imprimirResultado(5.99)
imprimirResultado(7.5)
imprimirResultado(9.9)
imprimirResultado(100)
|
// Filename: ScriptEventsPumpHouse.js
// Author: Leonard Daly and Don Brutzman
// Identifier: http://X3dGraphics.com/examples/X3dForWebAuthors/Chapter09-EventUtilitiesScripting/ScriptEventsPumpHouse.js
// Created: 8 October 2007
// Revised: 14 April 2008
// Reference: http://www.web3d.org/x3d/content/examples/X3dSceneAuthoringHints.html#Scripts
// License: http://X3dGraphics.com/examples/X3dForWebAuthors/license.html
function angle (value) {
positionRed = new SFVec3f (Math.cos (value), 1.5 * Math.sin(value), .5);
positionGreen = new SFVec3f (Math.cos (value+2.094), 1.5 * Math.sin(value+2.094), 0);
positionTurquoise = new SFVec3f (Math.cos (value+4.189), 1.5 * Math.sin(value+4.189), -.5);
orientationRed = new SFRotation (0, 0, 1, -2*value);
orientationGreen = new SFRotation (0, 0, 1, -2*(value+2.094));
orientationTurquoise = new SFRotation (0, 0, 1, -2*(value+4.189));
}
|
initMap = function() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 37.3382, lng: -121.8863}, // Initialize map view to Mountain View
// styles: gray_mode, // Night mode,
});
};
/*global OHE _config*/
var OHE = window.OHE || {};
OHE.map = OHE.map || {};
(function OHEScopeWrapper($) {
var authToken;
OHE.authToken.then(function setAuthToken(token) {
if (token) {
authToken = token;
} else {
window.location.href = '/signin.html'; // GO BACK TO LOGIN PAGE IF NOT AUTHENTICATED
}
}).catch(function handleTokenError(error) {
alert(error);
window.location.href = '/signin.html'; // GO BACK TO LOGIN PAGE IF NOT AUTHENTICATED
});
// Register click handler for #request button
$(function onDocReady() {
OHE.authToken.then(function updateAuthMessage(token) {
if (token) {
displayUpdate('You are authenticated. Click to see your <a href="#authTokenModal" data-toggle="modal">auth token</a>.');
$('.authToken').text(token);
}
});
if (!_config.api.invokeUrl) {
$('#noApiMessage').show();
}
});
function displayUpdate(text) {
$('#updates').append($('<li>' + text + '</li>'));
}
}(jQuery));
|
var config = require('./cfg');
var _ = require('lodash');
var Promise = require('bluebird');
var slack = require('slack');
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
app.use(bodyParser.json());
app.post('/', function(req, res){
// Verify token
if (req.headers['x-buildkite-token'] != config.BUILDKITE_WEBHOOK_TOKEN) {
console.log("Invalid webhook token");
return res.status(401).send('Invalid token');
}
res.send('AOK'); // ACK buildkite. We can handle the rest after the response
var buildEvent = req.body;
var build = buildEvent.build;
var pipeline = buildEvent.pipeline;
// lookup every time. ensures any new users are included. less intensive API
// usage would be to setup a daily lookup interval instead, but leaves gaps.
getSlackUsers()
.then(function (slackProfiles) {
var details = {};
details.SLACK_USER_ID = _.find(slackProfiles, { email: build.creator.email }).id;
details.GITHUB_REPO = pipeline.repository.split('@').pop().replace(':','/').slice(0,-4);
details.GITHUB_LINK = 'https://' + details.GITHUB_REPO + '/commit/' + build.commit;
var text = `
:warning: A build you initiated for *${pipeline.name}* has *${build.state}* on branch *${build.branch}*!!
Build message: \`${build.message}\`
See more detail here:
${build.web_url}
The changes made since last build are avialable here:
${details.GITHUB_LINK}
`;
// message users directly only on failures
// if (build.state === 'failed') {
slack.chat.postMessage({
token: config.SLACK_TOKEN,
channel: details.SLACK_USER_ID,
text: text
}, function (err, data) {
if (err) {
throw err;
}
});
// }
})
.catch((e) => {
console.log(e);
});
});
app.listen(process.env.PORT || 3000, function() {
console.log('Express listening on port', this.address().port);
});
function getSlackUsers() {
return new Promise(function (resolve, reject) {
slack.users.list({token:config.SLACK_TOKEN}, (err, data)=>{
if (err) {
return reject(err);
}
// get user profiles for users' Slack DM channel lookup
var users = data.members;
var profiles = _.map(users, (user) => { return {
id: user.id,
name: user.name,
email: user.profile.email
}; });
return resolve(profiles);
});
});
}
|
const config = require('./db/config.json')
const util = require('util')
const discord = require('discord.js')
const client = new discord.Client({ fetchAllMembers: false, disableEveryone: true});
const { Client, Communicator, FriendStatus } = require('fortnite-basic-api');
const fs = require('fs').promises;
const path = require('path')
const mongoose = require('mongoose')
const guildConfig = require('./db/models/guilds')
const userConfig = require('./db/models/users')
require('dotenv').config();
client.commands = new discord.Collection()
client.aliases = new discord.Collection()
client.timers = new discord.Collection()
client.descriptions = new discord.Collection()
client.cmdPermissions = new discord.Collection()
const fnClient = new Client({
email: process.env.FORTNITE_EMAIL,
useDeviceAuth: true,
removeOldDeviceAuths: true,
deviceAuthPath: './fbadeviceauths.json',
// These tokens are static.
launcherToken: 'MzRhMDJjZjhmNDQxNGUyOWIxNTkyMTg3NmRhMzZmOWE6ZGFhZmJjY2M3Mzc3NDUwMzlkZmZlNTNkOTRmYzc2Y2Y=',
fortniteToken: 'ZWM2ODRiOGM2ODdmNDc5ZmFkZWEzY2IyYWQ4M2Y1YzY6ZTFmMzFjMjExZjI4NDEzMTg2MjYyZDM3YTEzZmM4NGQ=',
autokill: true,
seasonStartTime: '1606867200'
});
// const communicator = new Communicator(fnClient);
// (async () => {
// // EMAIL should be same as the account logging in with exchange!
// // The reason is that the deviceauth will be saved under "client.email"
// // In the JSON file on disk
// // This is where the magic happen
// console.log('Success creation of device auth',
// await fnClient.createDeviceAuthFromExchangeCode());
// // Perform the login process of the "client"
// console.log('Success login with created device auth',
// await fnClient.authenticator.login());
// const parallel = await Promise.all([
// fnClient.lookup.accountLookup('iXyles'),
// fnClient.authenticator.accountId,
// ]);
// (parallel).forEach((result) => {
// console.log(result);
// });
// // Node will die and print that the session has been killed if login was successful
// })();
client.login(process.env.DISCORD_TOKEN);
let retryCount = 0;
(async function loginFn() {
await fnClient.authenticator.login()
.then(async function(fn){
if(fn.error && retryCount < 10){
setTimeout(() => {
retryCount++
console.log(`error on login, retrying, count: ${retryCount}`)
return loginFn()
}, 10000)
}
})
})()
fs.readdir(path.join(__dirname, 'events'))
.then(files => {
files.forEach(f => {
let eventName = f.substring(0, f.indexOf('.js'));
let eventModule = require(path.join(__dirname, 'events', eventName))
console.log(`${eventName} event Loaded.`)
client.on(eventName, eventModule.bind(null, client))
})
console.log(`-All events Loaded-\n`)
})
.catch(e => console.log(e))
fs.readdir(path.join(__dirname, 'commands'))
.then(files => {
files.forEach(f => {
let commandName = f.substring(0, f.indexOf('.js'));
let file = require(path.join(__dirname, 'commands', commandName))
console.log(`${commandName} command Loaded.`)
if(!file.config) return;
client.commands.set(file.config.name, file)
file.config.aliases.forEach(a => {
client.aliases.set(a, file)
})
client.descriptions.set(file.config.description, file)
file.config.permission.forEach(a => {
client.cmdPermissions.set(a, file)
})
})
console.log(`-All commands Loaded-\n`)
})
mongoose.set('useUnifiedTopology', true);
mongoose.connect(process.env.DB_URI, { useNewUrlParser: true });
exports.fnClient = fnClient;
exports.userConfig = userConfig;
exports.guildConfig = guildConfig;
exports.config = config;
|
const TMDB_ENDPOINT = "https://api.themoviedb.org/3";
const APIKEY = "087d40cd76f8efab563b10d15f9a6ae2";
const IMG_PREFIX = "https://image.tmdb.org/t/p/w500";
let xhr;
let xhr2;
carregaFilmesLancamentos();
carregaFilmesPopulares();
// filmes - Populares - Início //
function carregaFilmesPopulares() {
xhr = new XMLHttpRequest();
xhr.open(
"GET", TMDB_ENDPOINT + "/movie/popular" + "?api_key=" + APIKEY + "&language=pt-BR",
true
);
xhr.onload = exibeFilmesPopulares;
xhr.send();
}
function exibeFilmesPopulares() {
let data = JSON.parse(xhr.responseText);
let textoHTML = "";
for (let i = 0; i < 3; i++) {
let nomeFilme = data.results[i].title;
let sinopse = data.results[i].overview;
let imagem = IMG_PREFIX + data.results[i].poster_path;
let id = data.results[i].id;
let estreia = data.results[i].release_date;
let nota = data.results[i].vote_average;
textoHTML += `
<div id="cartao" class="card col-md-4 ">
<img src="${imagem}" class="card-img-top" alt="...">
<div class="card-body">
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal${id}">Visualizar mais</button>
</div>
</div>
<div class="modal fade" id="exampleModal${id}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">${nomeFilme}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<strong>Resumo: </strong>${sinopse}<br>
<strong>Estreia: </strong>${estreia}<br>
<strong>Nota: </strong>${nota}<br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fechar</button>
</div>
</div>
</div>
</div>
`;
}
document.getElementById("popular").innerHTML = textoHTML;
}
// filmes - Populares - Fim //
// filmes - Pesquisa - Início //
function pesquisa1 (){
query = document.getElementById('pesquisaF').value;
localStorage.setItem('pesquisa',JSON.stringify(query))
}
// filmes - Pesquisa - Fim //
// filmes - Lançamentos - Início //
function carregaFilmesLancamentos() {
xhr2 = new XMLHttpRequest();
xhr2.open("GET", TMDB_ENDPOINT + "/movie/upcoming" + "?api_key=" + APIKEY + "&language=pt-BR", true);
xhr2.onload = exibeFilmesLancamentos;
xhr2.send();
}
function exibeFilmesLancamentos() {
console.log(this.responseText)
let data = JSON.parse(xhr2.responseText);
let textoHTML = "";
for (let i = 0; i < 3; i++) {
let imagem = IMG_PREFIX + data.results[i].poster_path;
let titulo = data.results[i].title;
let resumo = data.results[i].overview;
let estreia = data.results[i].release_date;
let nota = data.results[i].vote_average;
textoHTML = `
<div class="row">
<div class="col-xs-12 col-md-6 col-lg-6 imagem_lancamentos">
<img src="${imagem}" id="ftc" alt="...">
</div>
<div class="col-xs-12 col-md-6 col-lg-6 texto_lancamentos">
<h2>${titulo}</h2>
<p>${resumo}</p>
<strong><h4>Estreia</h4></strong>
<p>${estreia}</p>
<strong><h4>Avaliação</h4></strong>
<p>${nota}</p>
</div>
`
let elemento = document.getElementById(`car${i}`)
elemento.innerHTML = textoHTML;
console.log(elemento)
}
}
// filmes - Lançamentos - Fim //
|
import React from 'react';
import {Switch, Route} from 'react-router-dom';
import About from './components/About_us';
import Home from './components/Home';
import Gallery from './components/Gallery';
import Reviews from './components/Reviews';
import Blogs from './components/Blogs';
import Order from './components/Order';
import Footer from './components/Footer';
export default (
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/gallery" component={Gallery} />
<Route path="/review" component={Reviews} />
<Route path="/blog" component={Blogs} />
<Route path="/orders" component={Order} />
<Route path="https://www.instagram.com" components={Footer} />
</Switch>
</div>
)
|
// eslint-disable-next-line
import React from "react";
function Footer(){
return(<div>
<footer>
<div className="ftr-bar">
<div className="In-ftr">
<ul>
<li className="ftr-li"><span><h3>All Programs</h3></span>
<span><a href="#">Refferal Program</a></span>
<span><a href="#">Zero investment</a></span>
<span><a href="#">Small Investment</a></span>
<span><a href="#">Medium Investment</a></span>
</li>
<li className="ftr-li"><span><h3>Support</h3></span>
<span><a href="#">Terms & Condition</a></span>
<span><a href="#">Affiliate Disclouser</a></span>
<span><a href="#">Privacy & Policy</a></span>
</li>
<li className="ftr-li"><span><h3>About Us</h3></span>
<span><a href="#">Founder</a></span>
<span><a href="#">Mission</a></span>
</li>
<li className="ftr-li"><span><h3>Contact Us</h3></span>
<span><a href="#"> Shubhamvora05@gmail.com</a></span>
</li>
</ul>
</div>
</div>
</footer>
</div>);
}
export default Footer;
|
'use strict';
const RequestedCheck = require('./requested.check');
const DocScanConstants = require('../../../doc.scan.constants');
const Validation = require('../../../../yoti_common/validation');
const RequestedWatchlistScreeningConfig = require('./requested.watchlist.screening.config');
/**
* @class RequestedWatchlistScreeningCheck
*/
class RequestedWatchlistScreeningCheck extends RequestedCheck {
/**
* @param {RequestedWatchlistScreeningConfig} config
*/
constructor(config) {
Validation.instanceOf(config, RequestedWatchlistScreeningConfig, 'config');
super(DocScanConstants.WATCHLIST_SCREENING, config);
}
}
module.exports = RequestedWatchlistScreeningCheck;
|
import SudokuGridView from "./sudoku_grid_view.js" ;
class SudokuHintView extends SudokuGridView {
constructor(game){
super(game);
this.$displayHint = $(".display-hint");
this.$displayHint.on("click", this.displayHint.bind(this));
}
updateHint(){
const check = $(".display-hint").children().html();
if(check === "Hide Hint"){
let $ul = $(".hint");
$ul.remove();
this.buildHint();
}
}
buildHint(){
const $sudokuGrid = $(".sudoku-grid");
let $ul = $("<ul></ul>");
$ul.addClass("hint");
for(let i = 1; i < 10; i++){
let $li = $("<li></li>");
$li.addClass("sudoku-grid-tile");
let num = this.game.inputsVal[i];
$li.html(`num${i} ${num}`)
$ul.append($li);
}
$sudokuGrid.append($ul);
}
displayHint(event){
const $a = $(event.currentTarget).children();
this.handleHint($a.html());
if($a.html() === "Display Hint"){
$a.html("Hide Hint");
} else {
$a.html("Display Hint");
}
}
handleHint(value){
if(value === "Display Hint"){
this.buildHint();
this.buildCheckValuesButton();
} else {
let $ul = $(".hint");
let $button =$(".check-values");
$button.remove();
$ul.remove()
}
}
// check value button methods:
// ( update the backgoung color tile in red if false input value)
buildCheckValuesButton(){
const $footer = $(".footer");
let $button = $("<button></button>")
$button.html("Check values");
$button.addClass("check-values");
$button.on("click", this.checkValues.bind(this));
$footer.append($button);
}
checkValues(event){
this.updateConflictValues();
setTimeout(function(){
let $liConflict = $(".conflict-value");
$liConflict.removeClass("conflict-value");
}, 3000);
}
updateConflictValues(){
this.game.solution.forEach((line, row)=>{
line.forEach((value, col)=> {
let pos = [row, col];
let boardVal= this.game.board.getTile(pos).val;
if( boardVal !== 0 && boardVal !== value ){
let $li = $(`.li-${row}-${col}`);
$li.addClass("conflict-value");
}
});
});
}
//method to update tile color backgroung (green) when an input is selected
// buildSelectTileButton(){
// let $button = $("<button> </button>");
// $button.html("Viewer helper");
// $button.addClass("viewer-helper");
// $button.on("click", () => {
// let allInputs = $(":input");
// allInputs.on("click", this.handleSelect.bind(this)) ;
// });
// const $footer = $(".footer");
// $footer.append($button);
// }
handleSelect(event){
this.removeSelectedLis();
const $li = $(event.currentTarget).parent();
const col = $li.attr("class")[5];
const $ul = $li.parent();
const $liLines = $ul.children();
$liLines.addClass("tile-selected");
for(let index=0; index < 9; index++){
const $li = $(".sudoku-grid").find(`.li-${index}-${col}`)
$li.addClass("tile-selected");
}
}
removeSelectedLis(){
const $selectedLi = $(".tile-selected");
if($selectedLi.length !== 0){
$selectedLi.removeClass("tile-selected");
}
}
}
export default SudokuHintView;
|
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/quotes_revisited');
var quoteSchema = new mongoose.Schema({
name : String,
quote : String,
created_at : Date
})
var Quote = mongoose.model('quote', quoteSchema);
// var date = new Date();
// var time = new Date().toLocaleTimeString();
// console.log(date);
app.use(express.static(__dirname + '/static'));
app.use(bodyParser.urlencoded({extended: true}));
app.set('views', (__dirname + '/views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('index');
})
app.post('/quotes', function(req, res){
var add_quote = new Quote({name: req.body.name, quote : req.body.quote, created_at : new Date()});
add_quote.save(function(err){
if (err){
console.log('Entry error');
res.redirect('/');
} else {
console.log('Quote added');
res.redirect('/quotes');
}
})
})
app.get('/quotes', function(req, res){
var quote_list = [];
Quote.find({}, function(err, quotes){
if(err){
console.log('Load error');
res.redirect('/');
} else {
for (var i = 0; i < quotes.length; i++) {
quote_list.push({name : quotes[i].name, quote : quotes[i].quote, date : quotes[i].created_at.toLocaleString() });
}
res.render('quotes', { quotes : quote_list});
}
})
})
app.listen(3456, function(){
console.log('listening on port 3456');
})
|
const rp = require('request-promise');
const $ = require('cheerio');
const fs = require('fs');
exports.execute = function () {
const url = 'https://en.wikipedia.org/wiki/List_of_Presidents_of_the_United_States';
return rp(url)
.then(function(html){
//success!
const dom = $.load(html);
const wikiUrls = [];
for (let i = 0; i < dom('big > a').length; i++) {
wikiUrls.push(dom('big > a')[i].attribs.href);
}
console.log(wikiUrls);
resolve(wikiUrls);
})
.catch(function(err) {
//handle error
});
};
exports.toJSON = function (data) {
var json = JSON.stringify(data);
fs.writeFile('output.json', json, 'utf8', catchToJSON);
};
function catchToJSON(err) {
if (err) throw err;
console.log('complete');
}
|
import request from '@/utils/request'
import basicErrorHandler from './errorHandler'
import md5 from 'blueimp-md5/js/md5'
export async function post(title, text) {
const parseType = 'draft-0.0.1' // 解析方式版本
const hash = md5(title + text) // 用于防止重复提交
return request('/article', {
method: 'post',
requestType: 'form',
data: {
id: null,
parseType: parseType,
title: title,
text: text,
hash: hash,
},
errorHandler: basicErrorHandler,
})
}
export async function list(id) {
return request(`/public/articleComment?id=${ id }`, {
headers: {
accept: 'application/json',
},
errorHandler: basicErrorHandler,
})
}
export async function comments(id, page, size) {
return request(`/public/articleComment?id=${ id }&page=${ page }&size=${ size }`, {
headers: {
accept: 'application/json',
},
errorHandler: basicErrorHandler,
})
}
|
import Ember from "ember";
import { test } from 'ember-qunit';
import startApp from '../helpers/start-app';
import Validation from 'furnace-validation';
import PropertyValidator from 'furnace-validation/property';
import ObjectValidator from 'furnace-validation/object';
var App;
module('Validator module tests', {
setup: function() {
App = startApp();
},
teardown: function() {
Ember.run(App, App.destroy);
}
});
test("Interface", function( ) {
ok(typeof Validation==='object',"Module interface not properly exported");
equal(Validation.Object,ObjectValidator,"Expected ObjectValidator class");
equal(Validation.Property,PropertyValidator,"Expected PropertyValidator class");
ok(typeof Validation.val==='function',"Expected val function");
ok(typeof Validation.enum==='function',"Expected list function");
});
test("Validator generation", function( ) {
var validators=Validation.val({property : true,
object: true});
ok(validators instanceof Ember.ComputedProperty,'Check if validators register');
});
|
import {Controller} from "stimulus";
export default class extends Controller {
/**
*
* @type {string[]}
*/
static targets = [
"title"
];
/**
*
* @param options
*/
open(options) {
if (typeof options.title !== "undefined") {
this.titleTarget.textContent = options.title;
}
this.element.querySelector('form').action = options.submit;
if (this.data.get('async')) {
this.asyncLoadData(JSON.parse(options.params));
}
$(this.element).modal('toggle');
}
/**
*
* @param params
*/
asyncLoadData(params) {
let name = this.data.get('url') + '/' + this.data.get('slug') + '/' + this.data.get('method');
axios.post(name, params).then((response) => {
this.element.querySelector('[data-async]').innerHTML = response.data;
});
}
}
|
import React from "react"
import { Link } from "gatsby"
import { useFeatured } from "../queries/useFeatured"
import mainBlogStyles from "../styles/mainBlogStyles"
const Featured = () => {
const posts = useFeatured()
const classes = mainBlogStyles()
return (
<div className={classes.container}>
<h2 className={classes.title}>Featured</h2>
{posts.map(({ node }) => {
const title = node.frontmatter.title || node.fields.slug
return (
<div key={node.fields.slug}>
<h4>
<Link
className={classes.link}
to={`${node.fields.slug}`}
>
{title}
</Link>
</h4>
<small>{node.frontmatter.date}</small>
<p>{node.frontmatter.description}</p>
</div>
)
})}
</div>
)
}
export default Featured
|
var pluralizer = function (noun, number) {
if (number === 1) {
console.log (number + " " + noun);
} else if (number > 1) {
console.log (number + " " + noun + "s");
}
}
pluralizer ("cat", 3);
|
const EventEmitter = require("events");
class Emitter extends EventEmitter{
}
let emitter = new Emitter();
emitter.setMaxListeners(11);
emitter.on("test",()=>{
console.log("1::hello");
})
emitter.on("test",()=>{
console.log("2::hello");
})
emitter.on("test",()=>{
console.log("3::hello");
})
emitter.on("test",()=>{
console.log("4::hello");
})
emitter.on("test",()=>{
console.log("5::hello");
})
emitter.on("test",()=>{
console.log("6::hello");
})
emitter.on("test",()=>{
console.log("7::hello");
})
emitter.on("test",()=>{
console.log("8::hello");
})
emitter.on("test",()=>{
console.log("9::hello");
})
emitter.on("test",()=>{
console.log("10::hello");
})
emitter.on("test",()=>{
console.log("11::hello");
})
emitter.emit("test")
|
import styled from "styled-components"
import {Content} from "../Styled"
export const HomeContentWrapper = styled.div`
display: flex;
flex-grow: 1;
`
export const HomeStyledContent = styled(Content)`
display: flex;
margin-top: 33px;
margin-bottom: 33px;
`
|
import React, {useState} from 'react';
function Portfolio() {
// const [project, setProject] = useState(0);
const [projects] = useState([
{
title: 'wordUp',
github: 'https://github.com/njderenne/wordUp',
deploy: 'https://fast-shelf-56121.herokuapp.com/',
file: 'wordUp'
},
{
title: '24-Chains',
github: 'https://github.com/MarynaPR/24-chains',
deploy: 'https://dry-mesa-09626.herokuapp.com/',
file: '24chains'
},
{
title: 'One Stop Job',
github: 'https://github.com/frostyausty/OneStopJob',
deploy: 'https://frostyausty.github.io/OneStopJob/',
file: 'onestopjob'
},
{
title: 'Social Network API',
github: 'https://github.com/frostyausty/SocialNetworkAPI',
deploy: 'https://drive.google.com/file/d/1DSmmW3wcOSMIHGgTM-hmHJlOLBEVSFz_/view',
file: 'socialnetworkapi'
},
{
title: 'Budget Tracker',
github: 'https://github.com/frostyausty/BudgetTracker',
deploy: 'https://pure-thicket-17207.herokuapp.com/',
file: 'budgettracker'
},
{
title: 'Work Day Scheduler',
github: 'https://github.com/frostyausty/WorkDayScheduler',
deploy: 'https://frostyausty.github.io/WorkDayScheduler/',
file: 'workdayscheduler'
}
])
return (
<section>
<h2>Projects</h2>
<div className = "project-container">
{projects.map((project, i) => (
<div className={`project project-${i+1}`} key={project.title}>
<h3>{project.title}</h3>
<a className ="gitlink" target="_blank" href={project.github}>GitHub Repo</a>
<a className ="applink" target="_blank" href={project.deploy}>Live application</a>
<img src={require(`../../assets/projectPhotos/${project.file}.jpg`).default}
alt={project.title}
className="project-img"
key={i} />
</div>
))}
</div>
</section>
);
}
export default Portfolio;
|
routerApp
.controller(
'schoolDataControllerHome',
[
'$scope',
'$http',
function($scope, $http) {
$scope.$on('LastRepeaterElement', function() {
console.log('LastRepeaterElement');
setTimeout(function() {
loaded123($scope);
}, 250);
});
getData($scope, $http);
$scope.split = function(dayNo, lessonNo, index) {
var newLesson = angular
.copy($scope.school.timeTableDays[dayNo].lessons[index]);
newLesson.lessonLength = 1;
newLessons = [ {} ];
newLessons.length = 0;
for (i = 0; i < index; i++) {
newLessons
.push($scope.school.timeTableDays[dayNo].lessons[i]);
}
// make the last one 1 lesson shorter
lesson = $scope.school.timeTableDays[dayNo].lessons[i];
lesson.lessonLength = lesson.lessonLength - 1;
newLessons.push(lesson);
// add the new one
newLessons.push(newLesson);
for (i = index + 1; i < $scope.school.timeTableDays[dayNo].lessons.length; i++) {
newLessons
.push($scope.school.timeTableDays[dayNo].lessons[i]);
}
x = 0;
for (i = 0; i < newLessons.length; i++) {
newLessons[i].lessonNo = x;
newLessons[i].lessonName = "Lesson:"
+ (x + 1);
x = x + newLessons[i].lessonLength;
}
$scope.school.timeTableDays[dayNo].lessons = newLessons;
}
$scope.merge = function(dayNo, lessonNo, index) {
$scope.school.timeTableDays[dayNo].lessons[index - 1].lessonLength = $scope.school.timeTableDays[dayNo].lessons[index - 1].lessonLength
+ $scope.school.timeTableDays[dayNo].lessons[index].lessonLength;
$scope.school.timeTableDays[dayNo].lessons
.splice(index, 1);
}
$scope.save = function(school) {
putData(school, $http);
}
} ]);
routerApp.controller('schoolDataControllerAbout', function($scope, $http) {
getData($scope, $http);
});
var getData = function($scope, $http) {
if ($scope.school == null) {
$http({
method : 'GET',
url : 'json/school.json',
headers : {
'Content-Type' : 'application/json'
}
}).success(function(data, status) {
$scope.school = data.school;
}).error(function(data, status) {
});
}
}
var putData = function(school, $http) {
$http({
url : '/demo/school/save',
method : "POST",
data : {
school : school
},
headers : {
'Content-Type' : 'application/json'
}
}).success(function(data, status, headers, config) {
status = status + ' ' + headers;
}).error(function(data, status, headers, config) {
status = status + ' ' + headers;
});
}
var setRoom = function($scope, day, lesson, newRoom) {
$scope.school.timeTableDays[day], lessons[lesson].room = newRoom;
}
|
module.exports = {
rules: {
// Enforce “for” loop update clause moving the counter in the right direction
// https://github.com/eslint/eslint/blob/master/docs/rules/for-direction.md
'for-direction': 'error',
// Enforces that a return statement is present in property getters
// https://github.com/eslint/eslint/blob/master/docs/rules/getter-return.md
'getter-return': ['error', { allowImplicit: true }],
// Require using Error objects as Promise rejection reasons
// https://github.com/eslint/eslint/blob/master/docs/rules/prefer-promise-reject-errors.md
'prefer-promise-reject-errors': ['error', { allowEmptyReject: true }],
// Disallow await inside of loops
// https://github.com/eslint/eslint/blob/master/docs/rules/no-await-in-loop.md
'no-await-in-loop': 'error',
// Disallows ambiguous assignment operators in test conditions of if, for, while, and do...while statements.
// https://github.com/eslint/eslint/blob/master/docs/rules/no-cond-assign.md
'no-cond-assign': ['error', 'always'],
// Disallows calls to methods of the console object
// https://github.com/eslint/eslint/blob/master/docs/rules/no-console.md
'no-console': 'error',
// This rule disallows constant expressions in the test condition of if, for, while, or do...while statement and ternary expression
// https://github.com/eslint/eslint/blob/master/docs/rules/no-constant-condition.md
'no-constant-condition': 'error',
// disallow control characters in regular expressions
// https://github.com/eslint/eslint/blob/master/docs/rules/no-control-regex.md
'no-control-regex': 'error',
// Disallows debugger statements.
// https://github.com/eslint/eslint/blob/master/docs/rules/no-debugger.md
'no-debugger': 'error',
// Disallows duplicate parameter names in function declarations or expressions
// https://github.com/eslint/eslint/blob/master/docs/rules/no-dupe-args.md
'no-dupe-args': 'error',
// Disallows duplicate keys in object literals
// https://github.com/eslint/eslint/blob/master/docs/rules/no-dupe-keys.md
'no-dupe-keys': 'error',
// Disallows duplicate test expressions in case clauses of switch statements
// https://github.com/eslint/eslint/blob/master/docs/rules/no-duplicate-case.md
'no-duplicate-case': 'error',
// Disallows empty block statements
// https://github.com/eslint/eslint/blob/master/docs/rules/no-empty.md
'no-empty': 'error',
// disallow the use of empty character classes in regular expressions
// https://github.com/eslint/eslint/blob/master/docs/rules/no-empty-character-class.md
'no-empty-character-class': 'error',
// Disallows unnecessary boolean casts
// https://github.com/eslint/eslint/blob/master/docs/rules/no-extra-boolean-cast.md
'no-extra-boolean-cast': 'error',
// Disallow overwriting functions written as function declarations
// https://github.com/eslint/eslint/blob/master/docs/rules/no-func-assign.md
'no-func-assign': 'error',
// Disallow invalid regular expression strings in the RegExp constructor
// https://github.com/eslint/eslint/blob/master/docs/rules/no-invalid-regexp.md
'no-invalid-regexp': 'error',
// Disallows invalid whitespace that is not a normal tab and space
// https://github.com/eslint/eslint/blob/master/docs/rules/no-irregular-whitespace.md
'no-irregular-whitespace': 'error',
// Disallows negating the left operand
// https://github.com/eslint/eslint/blob/master/docs/rules/no-unsafe-negation.md
'no-obj-calls': 'error',
// Disallow use of Object.prototypes builtins directly
// https://github.com/eslint/eslint/blob/master/docs/rules/no-prototype-builtins.md
'no-prototype-builtins': 'error',
// Disallow multiple spaces in a regular expression literal
// https://github.com/eslint/eslint/blob/master/docs/rules/no-regex-spaces.md
'no-regex-spaces': 'error',
// Avoid code that looks like two expressions but is actually one
// https://github.com/eslint/eslint/blob/master/docs/rules/no-unexpected-multiline.md
'no-unexpected-multiline': 'error',
// Disallow return/throw/break/continue inside finally blocks
// https://github.com/eslint/eslint/blob/master/docs/rules/no-unsafe-finally.md
'no-unsafe-finally': 'error',
// Disallows invalid whitespace that is not a normal tab and space
// https://github.com/eslint/eslint/blob/master/docs/rules/no-unsafe-negation.md
'no-unsafe-negation': 'error',
// Disallows unreachable code
// https://github.com/eslint/eslint/blob/master/docs/rules/no-unreachable.md
'no-unreachable': 'error',
// Disallows comparisons to 'NaN'
// https://github.com/eslint/eslint/blob/master/docs/rules/use-isnan.md
'use-isnan': 'error',
// Enforces comparing typeof expressions to valid string literals
// https://github.com/eslint/eslint/blob/master/docs/rules/valid-typeof.md
'valid-typeof': 'error'
}
}
|
import React from 'react';
import { Link, useHistory } from 'react-router-dom';
const HamburgerMenu = () => {
return (
<Link to='/mobile-nav-links'>
<div className='hamburger-container'>
<div className='line line-1'></div>
<div className='line line-2'></div>
<div className='line line-3'></div>
</div>
</Link>
);
};
export default HamburgerMenu;
|
import { render } from 'react-dom'
import React, { useState } from 'react'
import { useSprings, animated, interpolate } from 'react-spring'
import { useGesture } from 'react-use-gesture'
import './App.css'
import cardBack from './images/cardback.png';
import cardAH from './cards/AH.jpg';
import card2H from './cards/2H.jpg';
import card3H from './cards/3H.jpg';
import card4H from './cards/4H.jpg';
import card5H from './cards/5H.jpg';
import card6H from './cards/6H.jpg';
import card7H from './cards/7H.jpg';
import card8H from './cards/8H.jpg';
import card9H from './cards/9H.jpg';
import card10H from './cards/10H.jpg';
import cardJH from './cards/JH.jpg';
import cardQH from './cards/QH.jpg';
import cardKH from './cards/KH.jpg';
import cardAS from './cards/AS.jpg';
import card2S from './cards/2S.jpg';
import card3S from './cards/3S.jpg';
import card4S from './cards/4S.jpg';
import card5S from './cards/5S.jpg';
import card6S from './cards/6S.jpg';
import card7S from './cards/7S.jpg';
import card8S from './cards/8S.jpg';
import card9S from './cards/9S.jpg';
import card10S from './cards/10S.jpg';
import cardJS from './cards/JS.jpg';
import cardQS from './cards/QS.jpg';
import cardKS from './cards/KS.jpg';
import cardAC from './cards/AC.jpg';
import card2C from './cards/2C.jpg';
import card3C from './cards/3C.jpg';
import card4C from './cards/4C.jpg';
import card5C from './cards/5C.jpg';
import card6C from './cards/6C.jpg';
import card7C from './cards/7C.jpg';
import card8C from './cards/8C.jpg';
import card9C from './cards/9C.jpg';
import card10C from './cards/10C.jpg';
import cardJC from './cards/JC.jpg';
import cardQC from './cards/QC.jpg';
import cardKC from './cards/KC.jpg';
import cardAD from './cards/AD.jpg';
import card2D from './cards/2D.jpg';
import card3D from './cards/3D.jpg';
import card4D from './cards/4D.jpg';
import card5D from './cards/5D.jpg';
import card6D from './cards/6D.jpg';
import card7D from './cards/7D.jpg';
import card8D from './cards/8D.jpg';
import card9D from './cards/9D.jpg';
import card10D from './cards/10D.jpg';
import cardJD from './cards/JD.jpg';
import cardQD from './cards/QD.jpg';
import cardKD from './cards/KD.jpg';
const textElement = <h1>Cryptic Cards</h1>;
const cards = [
(cardAD),
(card2D),
(card3D),
(card4D),
(card5D),
(card6D),
(card7D),
(card8D),
(card9D),
(card10D),
(cardJD),
(cardQD),
(cardKD),
(cardAH),
(card2H),
(card3H),
(card4H),
(card5H),
(card6H),
(card7H),
(card8H),
(card9H),
(card10H),
(cardJH),
(cardQH),
(cardKH),
(cardAC),
(card2C),
(card3C),
(card4C),
(card5C),
(card6C),
(card7C),
(card8C),
(card9C),
(card10C),
(cardJC),
(cardQC),
(cardKC),
(cardAS),
(card2S),
(card3S),
(card4S),
(card5S),
(card6S),
(card7S),
(card8S),
(card9S),
(card10S),
(cardJS),
(cardQS),
(cardKS)
]
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
//The maximum is exclusive and the minimum is inclusive
}
var kort=[1,2,3,4,5,6,7,8,9,10,11,12,13,
14,15,16,17,18,19,20,21,22,23,
24,25,26,27,28,28,30,31,32,33,
34,35,36,37,38,39,40,41,42,43,
44,45,46,47,48,49,50,51,52];
function OncePlease () {
var i=0;
var temp = getRandomInt(0,kort.length );
// console.log(temp);
while(i < kort.length) {
if(kort[temp] === kort[i]){
var retKort = kort[temp];
kort.splice(i,1);
i++;
return retKort;
}
i++;
}
}
// These two are just helpers, they curate spring data, values that are later being interpolated into css
const to = i => ({ x: 0, y: 0, scale: 1.0, rot: 0, delay: i * 5 })
const from = i => ({ x: 0, rot: 0, scale: 1.0, y: 10000 })
// This is being used down there in the view, it interpolates rotation and scale into a css transform
const trans = (r, s) => `perspective(15000px) rotateX(30deg) rotateY(${r / 10}deg) rotateZ(${r}deg) scale(${s})`
const Deck = () => {
const [gone] = useState(() => new Set()) // The set flags all the cards that are flicked out
const [props, set] = useSprings(cards.length, i => ({ ...to(i), from: from(i) })) // Create a bunch of springs using the helpers above
// Create a gesture, we're interested in down-state, delta (current-pos - click-pos), direction and velocity
const bind = useGesture(({ args: [index], down, delta: [xDelta], distance, direction: [xDir], velocity }) => {
const trigger = velocity > 0.2 // If you flick hard enough it should trigger the card to fly out
const dir = xDir < 0 ? -1 : 1 // Direction should either point left or right
if (!down && trigger) gone.add(index) // If button/finger's up and trigger velocity is reached, we flag the card ready to fly out
set(i => {
if (index !== i) return // We're only interested in changing spring-data for the current spring
const isGone = gone.has(index)
const x = isGone ? (window.innerWidth) * dir : down ? xDelta : 0 // When a card is gone it flys out left or right, otherwise goes back to zero
const rot = 0//xDelta / 100 + (isGone ? dir * 1 * velocity : 0) // How much the card tilts, flicking it harder makes it rotate faster
const scale = down ? 1.0 : 1 // Active cards lift up a bit
return { x, rot, scale, delay: undefined, config: { friction: 50, tension: down ? 800 : isGone ? 200 : 500 } }
})
if (!down && gone.size === cards.length) setTimeout(() => gone.clear() || set(i => to(i)), 600)
})
// Now we're just mapping the animated values to our view, that's it. Btw, this component only renders once. :-)
function refreshPage() {
window.location.reload(false);
}
return <div id="cardholder">
<div id="cards">
<h1 id="headText" >Cryptic Cards</h1>
<span className="clickText" >Click Card! Then Swipe Away! </span>
{ props.map(({ x, y, rot, scale}, i) => (
<animated.div key={i} style={{ transform: interpolate([x, y], (x, y) => `translate3d(${x}px,${y}px,0)`) }}>
{/* This is the card itself, we're binding our gesture to it (and inject its index so we know which is which) */}
<animated.div class="flip-card" {...bind(i)} style={{ transform: interpolate([rot, scale,], trans), backgroundImage: `url(${cardBack})` }}>
{/*<img src={card} class="cardImages" alt="tarotCard" unselectable="on" />
<img src={tess} class="cardImages" alt="Tess" unselectable="on" />*/}
<div className="flip-card-inner">
<div className="flip-card-front">
<img className="cardImages" src={cardBack} alt="cardbackside" />
</div>
<div className="flip-card-back">
<img src={cards[OncePlease()-1]} className="cardImages" alt="tarotCard" unselectable="on" />
</div>
</div>
{/*<img src={card} alt="Alps" />*/}
{/*console.log("hello")*/}
{/*backgroundImage: `url(${cards[i]})` */}
{/*</animated.div>*/}
</animated.div>
</animated.div>
))
}
<div className="Refresh">
<button className="REText" onClick={refreshPage}>SHUFFLE</button>
</div>
</div>
</div>
}
export default Deck;
|
/*
Let d(n) be defined as the sum of proper divisors of n
(numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable
pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55
and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71
and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
*/
var cache = {},
helper = require('./helper.js'),
i = 1,
result = [],
temp;
function amicable(a) {
var b;
function d(num) {
return sum(divisors(num));
}
b = d(a);
return b !== a && d(b) === a ? [a, b] : false;
}
function divisors(num) {
var i = 2,
list = [];
function push(n) {
if (!~list.indexOf(n)) {
list.push(n);
}
}
push(1);
while (i < num / 2) {
if (num % i === 0) {
push(i);
push(num / i);
}
i = i + 1;
}
return list
.sort(function (a, b) {
return a - b;
});
}
function sum(list) {
/*jshint evil:true*/
return eval(list.join('+'));
}
while (i < 10000) {
temp = !cache[i] ? amicable(i) : false;
if (temp) {
cache[temp[0]] = true;
cache[temp[1]] = true;
result = result
.concat(temp);
}
i = i + 1;
}
result = sum(result);
helper(result);
|
chrome.extension.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
console.log(msg);
displayCSS(msg.sURL, msg.aEmbeddedCSS, msg.aExternalCSS);
port.disconnect();
});
});
function displayCSS(sURL, aEmbeddedCSS, aExternalCSS) {
document.title = 'CSS - ' + sURL;
getElem('collapse-all').onclick = function() {toggleAll('collapse')};
getElem('expand-all').onclick = function() {toggleAll('expand')};
getElem('beautify-css').onclick = beautifyCSS;
var l = aEmbeddedCSS.length;
if (l > 0) {
for (var i = 0, sContent = ''; i < l; i++) {
sContent += aEmbeddedCSS[i] + (i+1 !== l? '\n': '');
}
addStyles('Embedded CSS', sContent);
}
for (i = 0; i < aExternalCSS.length; ++i) {
var oRequest = new XMLHttpRequest();
oRequest.open('get', aExternalCSS[i], false);
oRequest.send(null);
addStyles(aExternalCSS[i], oRequest.responseText, true);
}
}
function addStyles(sTitle, sContent, bExternal) {
var oDiv1 = document.createElement('div'),
oLink = document.createElement('a'),
oSpan = document.createElement('span'),
oDiv2 = document.createElement('div'),
oPre = document.createElement('pre');
if (bExternal) {
var oLink2 = document.createElement('a');
oLink2.href = sTitle;
oLink2.target = '_blank';
oLink2.appendChild(document.createTextNode(sTitle));
oSpan.appendChild(oLink2);
} else {
oSpan.innerText = sTitle;
}
oDiv1.className = 'styles';
oLink.onclick = toggle;
oSpan.className = 'title';
oDiv2.className = 'source';
oDiv2.style.display = 'block';
oDiv1.appendChild(oLink);
oDiv1.appendChild(oSpan);
oPre.className = 'prettyprint lang-css';
oPre.appendChild(document.createTextNode(sContent));
oDiv2.appendChild(oPre);
oDiv1.appendChild(oDiv2);
getElem('main-content').appendChild(oDiv1);
}
function toggle(oEvent) {
var oLink = oEvent.target,
oSource = oEvent.target.nextSibling;
while (oSource.className !== 'source') {
if (!oSource) return false;
oSource = oSource.nextSibling;
}
if (oSource.style && oSource.style.display === 'block') {
oSource.style.display = 'none';
oLink.style.backgroundImage = 'url(../img/tools/toggle-expand.png)';
} else {
oSource.style.display = 'block';
oLink.style.backgroundImage = 'url(../img/tools/toggle-collapse.png)';
}
return false;
}
function toggleAll(s) {
var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
if (!a[i].href)
a[i].style.backgroundImage = 'url(../img/tools/toggle-' + ((s === 'collapse') ? 'expand' : 'collapse') + '.png)';
}
var p = document.getElementsByClassName('source');
for (i = 0; i < p.length; i++) {
p[i].style.display = (s === 'collapse') ? 'none' : 'block';
}
}
function reindentCSS() {
var s = null;
var p = document.getElementsByTagName('pre');
for (var i = 0, l = p.length; i < l; i++) {
s = p[i].innerText;
// remove all tabs
s = s.replace(/\t+/ig,'');
// a single space before the opening curly bracket
s = s.replace(/(\S)\s*\{/ig,'$1 {');
// a new line and a tab between each declaration block
s = s.replace(/;\s*([a-z\-\*\_])/ig,';\n\t$1');
// a new line and a tab between each declaration block (keep the comment next to the declaration block)
s = s.replace(/;.*(\/\*.*\*\/)\s*([a-z\-\*\_])/ig,'; $1\n\t$2');
// a new line after the closing curly bracket
s = s.replace(/\}\s*(\S)/ig,'\}\n$1');
// a new line before the closing curly bracket
s = s.replace(/(\S)\s*\}/ig,'$1\n\}');
// a new line and a tab after the opening curly bracket
s = s.replace(/\{\s*([a-z\-\*\_])/ig,'\{\n\t$1');
// a new line and a tab after the opening curly bracket (keep the comment next to selector(s))
s = s.replace(/\{.*(\/\*.*\*\/)\s*([a-z\-])/ig,'\{ $1\n\t$2');
// a single space between the colon and the value
s = s.replace(/\t([a-z\-\*\_]+): */ig,'\t$1: ');
p[i].innerText = s;
}
}
function beautifyCSS(oEvent) {
reindentCSS(); // reindent
prettyPrint(); // syntax highlighting
oEvent.target.disabled = true;
}
function getElem(o) {
return document.getElementById(o);
}
|
var level = require('level-test')()
, sublevel = require('level-sublevel/bytewise')
, index = require('../../index')
, search = require('../../search')
, db = sublevel(level('level-scout'), { valueEncoding: 'json' })
, num = 0
require('./tape-debug')
module.exports = function (installIndex, installSearch) {
var sdb = db.sublevel(++num)
if (installIndex) index.install(sdb)
if (installSearch) search.install(sdb)
return sdb
}
|
/**
* 说明:
* 1、添加公式先按照../公式添加简要.txt,在函数弹出框注册;
* 2、公式还要在使用的时候进行全局js注册;
*/
window.SyswinVal = {
getEditFormula: function getEditFormula(spread) {
return null;
},
isValidFormula: function isValidFormula(sheet, formula) {
return true;
},
clearFormula: function clearFormula(spread) {},
clearTplCache: function clearTplCache() {
return true;
}
};
//获取单元格中的公式
window.SyswinVal.getEditFormula = function (spread) {
var tmpSpread;
var formula;
if (Tools.isNullOrEmpty(spread)) {
tmpSpread = GC.Spread.Sheets.findControl(document.getElementById('ss'));
} else {
tmpSpread = spread;
}
if (!Tools.isNullOrEmpty(tmpSpread)) {
var sheet = tmpSpread.getActiveSheet();
formula = sheet.getFormula(sheet.getActiveRowIndex(), sheet.getActiveColumnIndex());
}
return formula;
};
//是否合法公式
window.SyswinVal.isValidFormula = function (sheet, formula) {
try {
var parser = new GC.Spread.CalcEngine.CalcError.parse(formula);
} catch (ex) {
return false;
}
return true;
};
window.SyswinVal.clearTplCache = function () {
return true;
};
window.SyswinVal.getTplObjCache = function (tpl_name) {
if (Tools.isNullOrEmpty(tpl_name)) return '';
var tpl_str = '';
var tpl_obj;
try {
tpl_str = localStorage.getItem(tpl_name);
} catch (ex) {}
if (Tools.isNullOrEmpty(tpl_str)) return '';
try {
//模板json对象
tpl_obj = JSON.parse($.trim(tpl_str));
} catch (ex) {
throw new Error('实例化模板失败: ' + file_name);
}
return tpl_obj;
};
//清除页面所有公式
window.SyswinVal.clearFormula = function (spread) {
if (Tools.isNullOrEmpty(spread)) {
return;
}
var sheetCount = spread.getSheetCount();
for (var i = 0; i < sheetCount; i++) {
var sheet = spread.getSheet(i);
var sheetRowCount = sheet.getRowCount();
var sheetColCount = sheet.getColumnCount();
for (var x = 0; x < sheetRowCount; x++) {
for (var y = 0; y < sheetColCount; y++) {
if (!Tools.isNullOrEmpty(sheet.getFormula(x, y))) {
var cellVal = sheet.getValue(x, y, GC.Spread.Sheets.SheetArea.viewport);
sheet.setFormula(x, y, '');
sheet.setValue(x, y, cellVal);
}
}
}
}
};
//js注册全局函数
var SYSUM = function SYSUM() {};
SYSUM.prototype = new GC.Spread.CalcEngine.Functions.AsyncFunction("SYSUM", 2, 2, { name: 'SYSUM', description: '返回模板单元格的合计值。' });
SYSUM.prototype.defaultValue = function () {
return 'Loading...';
};
SYSUM.prototype.evaluateAsync = function (context) {
//汇总页面
var spread = GC.Spread.Sheets.findControl($('#ss')[0]);
var value;
var tpl;
var tpl_obj;
var sheets = spread.getSheetCount();
//遍历Workbook所有的Sheet
for (var i = 0; i < sheets; i++) {
var sheet = spread.getSheet(i);
//得到当前面签上下文对应的函数
var formula = sheet.getFormula(context.row, context.col);
if (!Tools.isNullOrEmpty(formula)) {
//得到要远程获取模板的名称
var file_name = sheet.name();
//从缓存中获取模板
tpl_obj = ''; //window.SyswinVal.getTplObjCache(file_name);
//缓存中没有模板
if (Tools.isNullOrEmpty(tpl_obj)) {
//根据模板名称获取文件磁盘存储id
var file_id = Tools.getTemplateFileId($.trim(file_name));
if (!Tools.isNullOrEmpty(file_id)) {
//获取模板ssjson
tpl = Tools.getTemplate(file_id);
try {
//模板json对象
tpl_obj = JSON.parse($.trim(tpl));
} catch (ex) {
throw new Error('实例化模板失败: ' + file_name);
} /*
try {
localStorage.setItem(file_name, tpl);
} catch (ex) {
throw new Error('缓存模板失败:' + file_name);
}*/
}
}
if (!Tools.isNullOrEmpty(tpl_obj)) {
//从ssjson实例化一个非host的Workbook对象
var spread0 = new GC.Spread.Sheets.Workbook();
spread0.fromJSON(tpl_obj);
var sheet0 = spread0.getSheet(0); //??只支持引入Workbook的第一个页面
try {
//将自定义函数替换为内置函数
formula = formula.replace('SYSUM', 'SUM');
//计算引擎等到值
value = GC.Spread.Sheets.CalcEngine.evaluateFormula(sheet0, formula, 0, 0, false);
} catch (o) {
value = '#VALUE!';
}
//为当前上下文的单元格赋值
context.setAsyncResult(value);
//刷新当前上下文对应的Sheet面签
spread.repaint();
}
}
}
};
GC.Spread.CalcEngine.Functions.AsyncFunctionEvaluateMode.onRecalculation;
var sysum = new SYSUM();
GC.Spread.CalcEngine.Functions.defineGlobalCustomFunction("SYSUM", sysum);
|
var api_url = "http://localhost:8080/";
jQuery.ajaxSetup({async:false});
function update() {
var f = $("#from").val();
var t = $("#to").val();
if(f && t) {
dt = {
t1: Math.floor(new Date(f)/1000),
t2: Math.floor(new Date(t)/1000)+86399
};
$.post(api_url+"getStats",dt,function(data) {
data = JSON.parse(data);
var data2 = [];
for (d in data.proTime) {
data2.push({ x: new Date(data.proTime[d].dt*1000), y:data.proTime[d].profit });
}
var chart = new CanvasJS.Chart("statsTime",{
zoomEnabled: true,
animationEnabled: true,
title:{
text: "Profit By day"
},
data: [
{
type: "line",
dataPoints: data2
}
]
});
chart.render();
var chart = new CanvasJS.Chart("byBrand",{
animationEnabled: true,
theme: "theme2",
title:{
text: "Profit By Brand"
},
data: [
{
type: "pie",
toolTipContent: "{y} - #percent %",
yValueFormatString: "Tk #",
dataPoints: data.byBrand
}
]
});
chart.render();
var chart = new CanvasJS.Chart("byType",{
animationEnabled: true,
theme: "theme2",
title:{
text: "Profit By Type"
},
data: [
{
type: "pie",
toolTipContent: "{y} - #percent %",
yValueFormatString: "Tk #",
dataPoints: data.byType
}
]
});
chart.render();
});
}
}
$(document).ready(function() {
$("#from").datepicker({
firstDay : 6,
onSelect: update
});
$("#to").datepicker({
firstDay : 6,
onSelect: update
});
});
|
(function (window, document, tplUtils) {
'use strict';
var isInitial = true,
name = '';
// id is a string with iframe's id
window.runSarineYoutubePlayer = function (id) {
var player,
tag = document.createElement('script'),
devLog = tplUtils.devLog;;
if (isInitial) {
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
devLog('youtube isInitial', isInitial, id);
isInitial = false;
}
window.onYouTubeIframeAPIReady = function () {
player = new YT.Player(id, {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
};
document.addEventListener('playSarineYoutube', function (e) {
console.log('***playSarineYoutube');
name = e.detail || '';
if (player && player.playVideo) {
player.playVideo();
}
}, false);
document.addEventListener('stopSarineYoutube', function (e) {
if (player && player.stopVideo && player.seekTo) {
player.seekTo(0, true);
player.stopVideo();
}
}, false);
function onPlayerReady(event) {
devLog('youtube ready');
if (name) {
tplUtils.fire(document, 'playSarineYoutube');
}
};
function onPlayerStateChange(event) {
devLog('youtube change state');
};
};
})(window, window.document, window.tplUtils);
|
module.exports = (sequelize, Sequelize) => {
const Product = sequelize.define("product", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
brand_id: {
type: Sequelize.INTEGER,
references: {
model: 'brands',
key: 'id'
}
},
name: {
type: Sequelize.STRING
},
price: {
type: Sequelize.DOUBLE
},
description: {
type: Sequelize.STRING
},
stock: {
type: Sequelize.INTEGER
},
published: {
type: Sequelize.BOOLEAN
},
color: {
type: Sequelize.STRING
}
}, {
tableName: "products",
timestamps: false
}
);
return Product;
};
|
export const getCookieValue = (cookieName) => {
const name = cookieName + '='
const ca = document.cookie.split(' ')
.filter(c => c.startsWith(name))
if (ca.length >= 1) {
const values = ca[0].split('=')
return decodeURIComponent(values[1])
}
return null
}
export const setCookieValue = (cookieName, value, expire = null) => {
let date = null
if (expire === null) {
date = null
} else if (typeof expire === 'string') {
date = expire
} else if (typeof expire === 'object' && typeof expire.format === 'function') {
date = expire.format('ddd, D MMM YYYY HH:mm:ss UTC')
} else if (typeof expire === 'object' && typeof expire.toGMTString === 'function') {
date = expire.toGMTString()
} else {
throw new Error('unknown expire type')
}
const baseCookie = `${cookieName}=${encodeURIComponent(value)} path=/`
document.cookie = date ? `${baseCookie} expires=${date}` : `${baseCookie}`
}
|
export {
// ACESFilmicToneMapping,
// AddEquation,
// AddOperation,
// AdditiveBlending,
// AlphaFormat,
// AlwaysDepth,
// AlwaysStencilFunc,
AmbientLight,
AmbientLightProbe,
// AnimationClip,
// AnimationLoader,
// AnimationMixer,
// AnimationObjectGroup,
// AnimationUtils,
// ArcCurve,
// ArrayCamera,
// ArrowHelper,
// Audio,
// AudioAnalyser,
// AudioContext,
// AudioListener,
// AudioLoader,
// AxesHelper,
// AxisHelper,
// BackSide,
// BasicDepthPacking,
// BasicShadowMap,
// BinaryTextureLoader,
// Bone,
// BooleanKeyframeTrack,
// BoundingBoxHelper,
// Box2,
// Box3,
// Box3Helper,
// BoxBufferGeometry,
// BoxGeometry,
// BoxHelper,
BufferAttribute,
BufferGeometry,
// BufferGeometryLoader,
// ByteType,
Cache,
Camera,
// CameraHelper,
// CanvasRenderer,
// CanvasTexture,
// CatmullRomCurve3,
// CineonToneMapping,
// CircleBufferGeometry,
// CircleGeometry,
// ClampToEdgeWrapping,
Clock,
// ClosedSplineCurve3,
// Color,
// ColorKeyframeTrack,
// CompressedTexture,
// CompressedTextureLoader,
// ConeBufferGeometry,
// ConeGeometry,
// CubeCamera,
// // BoxGeometry as CubeGeometry,
// CubeGeometry,
// CubeReflectionMapping,
// CubeRefractionMapping,
// CubeTexture,
// CubeTextureLoader,
// CubeUVReflectionMapping,
// CubeUVRefractionMapping,
// CubicBezierCurve,
// CubicBezierCurve3,
// CubicInterpolant,
// CullFaceBack,
// CullFaceFront,
// CullFaceFrontBack,
// CullFaceNone,
// Curve,
// CurvePath,
// CustomBlending,
// CylinderBufferGeometry,
// CylinderGeometry,
// Cylindrical,
// DataTexture,
// DataTexture2DArray,
// DataTexture3D,
// DataTextureLoader,
// DecrementStencilOp,
// DecrementWrapStencilOp,
// DefaultLoadingManager,
// DepthFormat,
// DepthStencilFormat,
// DepthTexture,
// DirectionalLight,
// DirectionalLightHelper,
// DirectionalLightShadow,
// DiscreteInterpolant,
// DodecahedronBufferGeometry,
// DodecahedronGeometry,
// DoubleSide,
// DstAlphaFactor,
// DstColorFactor,
// DynamicBufferAttribute,
// DynamicCopyUsage,
// DynamicDrawUsage,
// DynamicReadUsage,
// EdgesGeometry,
// EdgesHelper,
// EllipseCurve,
// EqualDepth,
// EqualStencilFunc,
// EquirectangularReflectionMapping,
// EquirectangularRefractionMapping,
// Euler,
// EventDispatcher,
// ExtrudeBufferGeometry,
// ExtrudeGeometry,
// Face3,
// Face4,
// FaceColors,
// FaceNormalsHelper,
// FileLoader,
// FlatShading,
// Float32Attribute,
// Float32BufferAttribute,
// Float64Attribute,
// Float64BufferAttribute,
// FloatType,
// Fog,
// FogExp2,
// Font,
// FontLoader,
// FrontFaceDirectionCCW,
// FrontFaceDirectionCW,
// FrontSide,
// Frustum,
// GammaEncoding,
Geometry,
GeometryUtils,
// GreaterDepth,
// GreaterEqualDepth,
// GreaterEqualStencilFunc,
// GreaterStencilFunc,
// GridHelper,
Group,
// HalfFloatType,
// HemisphereLight,
// HemisphereLightHelper,
// HemisphereLightProbe,
// IcosahedronBufferGeometry,
// IcosahedronGeometry,
// ImageBitmapLoader,
// ImageLoader,
// ImageUtils,
// ImmediateRenderObject,
// IncrementStencilOp,
// IncrementWrapStencilOp,
// InstancedBufferAttribute,
// InstancedBufferGeometry,
// InstancedInterleavedBuffer,
// InstancedMesh,
// Int16Attribute,
// Int16BufferAttribute,
// Int32Attribute,
// Int32BufferAttribute,
// Int8Attribute,
// Int8BufferAttribute,
// IntType,
// InterleavedBuffer,
// InterleavedBufferAttribute,
// Interpolant,
// InterpolateDiscrete,
// InterpolateLinear,
// InterpolateSmooth,
// InvertStencilOp,
// JSONLoader,
// KeepStencilOp,
// KeyframeTrack,
// LOD,
// LatheBufferGeometry,
// LatheGeometry,
Layers,
// LensFlare,
// LessDepth,
// LessEqualDepth,
// LessEqualStencilFunc,
// LessStencilFunc,
// Light,
// LightProbe,
// LightProbeHelper,
// LightShadow,
// Line,
// Line3,
// LineBasicMaterial,
// LineCurve,
// LineCurve3,
// LineDashedMaterial,
// LineLoop,
// LinePieces,
// LineSegments,
// LineStrip,
// LinearEncoding,
LinearFilter,
// LinearInterpolant,
// LinearMipMapLinearFilter,
// LinearMipMapNearestFilter,
// LinearMipmapLinearFilter,
// LinearMipmapNearestFilter,
// LinearToneMapping,
// Loader,
// LoaderUtils,
// LoadingManager,
// LogLuvEncoding,
// LoopOnce,
// LoopPingPong,
// LoopRepeat,
// LuminanceAlphaFormat,
// LuminanceFormat,
MOUSE,
Material,
// MaterialLoader,
Math,
// Matrix3,
// Matrix4,
// MaxEquation,
Mesh,
MeshBasicMaterial,
// MeshDepthMaterial,
// MeshDistanceMaterial,
// MeshFaceMaterial,
// MeshLambertMaterial,
// MeshMatcapMaterial,
MeshNormalMaterial,
MeshPhongMaterial,
// MeshPhysicalMaterial,
// MeshStandardMaterial,
// MeshToonMaterial,
// MinEquation,
// MirroredRepeatWrapping,
// MixOperation,
// MultiMaterial,
// MultiplyBlending,
// MultiplyOperation,
// NearestFilter,
// NearestMipMapLinearFilter,
// NearestMipMapNearestFilter,
// NearestMipmapLinearFilter,
// NearestMipmapNearestFilter,
// NeverDepth,
// NeverStencilFunc,
// NoBlending,
// NoColors,
// NoToneMapping,
// NormalBlending,
// NotEqualDepth,
// NotEqualStencilFunc,
// NumberKeyframeTrack,
// Object3D,
// ObjectLoader,
// ObjectSpaceNormalMap,
// OctahedronBufferGeometry,
// OctahedronGeometry,
// OneFactor,
// OneMinusDstAlphaFactor,
// OneMinusDstColorFactor,
// OneMinusSrcAlphaFactor,
// OneMinusSrcColorFactor,
OrthographicCamera,
PCFShadowMap,
PCFSoftShadowMap,
ParametricBufferGeometry,
ParametricGeometry,
// Particle,
// ParticleBasicMaterial,
// ParticleSystem,
// ParticleSystemMaterial,
// Path,
PerspectiveCamera,
Plane,
PlaneBufferGeometry,
PlaneGeometry,
PlaneHelper,
// PointCloud,
// PointCloudMaterial,
// PointLight,
// PointLightHelper,
// Points,
// PointsMaterial,
// PolarGridHelper,
// PolyhedronBufferGeometry,
// PolyhedronGeometry,
// PositionalAudio,
// PositionalAudioHelper,
// PropertyBinding,
// PropertyMixer,
// QuadraticBezierCurve,
// QuadraticBezierCurve3,
// Quaternion,
// QuaternionKeyframeTrack,
// QuaternionLinearInterpolant,
REVISION,
// RGBADepthPacking,
RGBAFormat,
RGBA_ASTC_10x10_Format,
RGBA_ASTC_10x5_Format,
RGBA_ASTC_10x6_Format,
RGBA_ASTC_10x8_Format,
RGBA_ASTC_12x10_Format,
RGBA_ASTC_12x12_Format,
RGBA_ASTC_4x4_Format,
RGBA_ASTC_5x4_Format,
RGBA_ASTC_5x5_Format,
RGBA_ASTC_6x5_Format,
RGBA_ASTC_6x6_Format,
RGBA_ASTC_8x5_Format,
RGBA_ASTC_8x6_Format,
RGBA_ASTC_8x8_Format,
RGBA_PVRTC_2BPPV1_Format,
RGBA_PVRTC_4BPPV1_Format,
RGBA_S3TC_DXT1_Format,
RGBA_S3TC_DXT3_Format,
RGBA_S3TC_DXT5_Format,
RGBDEncoding,
RGBEEncoding,
RGBEFormat,
RGBFormat,
RGBM16Encoding,
RGBM7Encoding,
RGB_ETC1_Format,
RGB_PVRTC_2BPPV1_Format,
RGB_PVRTC_4BPPV1_Format,
RGB_S3TC_DXT1_Format,
// RawShaderMaterial,
Ray,
Raycaster,
// RectAreaLight,
// RectAreaLightHelper,
// RedFormat,
// ReinhardToneMapping,
// RepeatWrapping,
// ReplaceStencilOp,
// ReverseSubtractEquation,
// RingBufferGeometry,
// RingGeometry,
Scene,
// SceneUtils,
// ShaderChunk,
// ShaderLib,
ShaderMaterial,
// ShadowMaterial,
// Shape,
// ShapeBufferGeometry,
// ShapeGeometry,
// ShapePath,
// ShapeUtils,
// ShortType,
// Skeleton,
// SkeletonHelper,
// SkinnedMesh,
// SmoothShading,
// Sphere,
// SphereBufferGeometry,
// SphereGeometry,
// Spherical,
// SphericalHarmonics3,
// SphericalReflectionMapping,
// Spline,
// SplineCurve,
// SplineCurve3,
// SpotLight,
// SpotLightHelper,
// SpotLightShadow,
// Sprite,
// SpriteMaterial,
// SrcAlphaFactor,
// SrcAlphaSaturateFactor,
// SrcColorFactor,
// StaticCopyUsage,
// StaticDrawUsage,
// StaticReadUsage,
// StereoCamera,
// StreamCopyUsage,
// StreamDrawUsage,
// StreamReadUsage,
// StringKeyframeTrack,
// SubtractEquation,
// SubtractiveBlending,
// TOUCH,
// TangentSpaceNormalMap,
// TetrahedronBufferGeometry,
// TetrahedronGeometry,
// TextBufferGeometry,
// TextGeometry,
// Texture,
// TextureLoader,
// TorusBufferGeometry,
// TorusGeometry,
// TorusKnotBufferGeometry,
// TorusKnotGeometry,
// Triangle,
// TriangleFanDrawMode,
// TriangleStripDrawMode,
// TrianglesDrawMode,
// TubeBufferGeometry,
// TubeGeometry,
UVMapping,
Uint16Attribute,
Uint16BufferAttribute,
Uint32Attribute,
Uint32BufferAttribute,
Uint8Attribute,
Uint8BufferAttribute,
Uint8ClampedAttribute,
Uint8ClampedBufferAttribute,
Uncharted2ToneMapping,
Uniform,
UniformsLib,
UniformsUtils,
UnsignedByteType,
UnsignedInt248Type,
UnsignedIntType,
UnsignedShort4444Type,
UnsignedShort5551Type,
UnsignedShort565Type,
UnsignedShortType,
VSMShadowMap,
Vector2,
Vector3,
Vector4,
VectorKeyframeTrack,
Vertex,
VertexColors,
VertexNormalsHelper,
// VideoTexture,
// WebGLMultisampleRenderTarget,
WebGLRenderTarget,
// WebGLRenderTargetCube,
WebGLRenderer,
WebGLUtils,
WireframeGeometry,
WireframeHelper,
WrapAroundEnding,
// XHRLoader,
// ZeroCurvatureEnding,
// ZeroFactor,
// ZeroSlopeEnding,
// ZeroStencilOp,
sRGBEncoding
} from '../../../node_modules/three/build/three.module.js'
|
import React from 'react';
import { Row, Col, Form, FormControl } from 'react-bootstrap';
import '../../App.css';
const SortBy = (props) => {
return (
<div>
<Row>
<Col md={3}>
<div id='search-div'>
<p id='small-search-text'>Search {props.pageName}:</p>
{/* <Form inline>
<FormControl
id='small-search'
type='text'
placeholder='ENTER KEYWORDS'
className='mr-sm-2'
></FormControl>
<i class='fas fa-search'></i>
</Form> */}
<input
id='small-search-field'
type='text'
placeholder='ENTER KEYWORDS'
/>
<i id='searchsubmit' className='fa fa-search'></i>
</div>
</Col>
<Col md={6}>
<h2 className='page-title'>
<strong>{props.pageTitle}</strong>
</h2>
{/* <p>
Newly Arrived
<i className='fas fa-minus'> </i>
<i className='fas fa-minus'> </i>
<i className='fas fa-minus'> </i>
<i className='fas fa-minus'> </i>
<i className='fas fa-minus'> </i>
<i className='fas fa-minus'> </i>
<i className='fas fa-minus'> </i>
<i className='fas fa-minus'> </i>
<i className='fas fa-minus'> </i>
<i className='fas fa-minus'> </i>
<i className='fas fa-minus'> </i>
<i className='fas fa-minus'> </i>
<i className='fas fa-minus'> </i>
Sort by: DEFAULT
<i class='fas fa-caret-down'></i>
</p> */}
<div class='textdiv'>
<div class='texttitle'>
{props.horizLineTextLeft}
</div>
<div class='divider'></div>
<span id='sort-by'>Sort by: DEFAULT</span>
<i class='fas fa-caret-down'></i>
</div>
</Col>
</Row>
</div>
);
};
export default SortBy;
|
import initMiddlewares from './middlewares';
import initReducers from './reducers';
const stacks = [
initMiddlewares,
initReducers,
];
export default stacks;
|
$(function() {
$(".showUploadTrainingResultsModal").click(function(e) {
$.tinybox.show($("#modalUploadTrainingResultsCsv"), {
overlayClose: false,
opacity: 0
});
});
$("#doUploadTrainingResultsCsv").mupload({
buttonText: "Upload spreadsheet",
url: "../trainingResults.csv",
useJsonPut: false,
oncomplete: function(data, name, href) {
log("oncomplete:", data.result.data, name, href);
if( data.result.status ) {
alert("Upload completed. Updated " + data.result.data.numUpdated + " rows");
} else {
if( data.result.data.unmatched.length > 0 ) {
alert(data.result.data.unmatched.length + " records could not be matched. Please review errors and update your spreadsheet.");
} else {
alert("There was an error uploading");
}
}
$(".results .numUpdated").text(data.result.data.numUpdated);
$(".results .numUnmatched").text(data.result.data.unmatched.length);
showUnmatched(data.result.data.unmatched);
$(".results").show();
}
});
});
|
import { connect } from 'react-redux';
import Example from '../screens/Example';
import { getExampleState } from '../redux/reducers';
import {EXAMPLE_USER_ACTION} from '../actions'
const mapStateToProps = (state) => ({
value: getExampleState(state) // uses selector to get state
});
const mapDispatchToProps = (dispatch) => ({
onClick: () => {
dispatch({ type: EXAMPLE_USER_ACTION }) // broadcast that user clicked
},
});
export default connect(mapStateToProps, mapDispatchToProps)(Example);
|
const express = require('express')
const hbs = require('hbs')
require('./db/mongoose')
const User = require('./models/user')
const auth = require('./middleware/auth')
const bodyParser = require('body-parser')
const path = require('path')
const app = express()
const PORT = process.env.PORT || 3000
// paths for express config
const publicDirectory = path.join(__dirname, './public')
const pagePath = path.join(__dirname, './views/pages')
const templatePath = path.join(__dirname, './views/pages')
app.set('view engine', 'hbs')
app.set('views', pagePath)
hbs.registerPartials(templatePath)
app.use(express.static(publicDirectory))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.get('', (req, res) => {
res.render('index')
})
app.get('/signup', (req, res) => {
res.render('signup')
})
//
app.post('/signup', async (req, res) => {
let { username, email, password } = req.body
const errors = []
if (!username) { errors.push('username') }
if (!email) { errors.push(' email') }
if (!password) { errors.push(' password') }
console.log(errors)
if(errors.length > 0){
res.render('signup', {
body: 'You did not enter: ' + errors
})
return
}
const user = new User(req.body)
try {
await user.save()
const token = await user.generateAuthToken()
res.status(201).send('index', { user, token })
} catch (e) {
res.status(400)
}
res.redirect('/memePage')
})
app.post('', async (req, res) => {
try {
const user = await User.findByCredentials(req.body.username, req.body.password)
const token = await user.generateAuthToken()
res.status(201).send({ user, token })
} catch (e) {
res.status(400)
}
res.redirect('/memePage')
})
app.get('/memePage', auth, async (req, res) => {
res.render('memePage')
})
app.listen(PORT, () => {
console.log(`Server is running on PORT: ${PORT}`)
})
|
const Doctor = require('./doctor');
const Pantient = require('./pantient');
const Schedule = require('./schedule');
const User = require('./user');
const Visit = require('./visit');
module.exports = { Doctor, Pantient, Schedule, User, Visit };
|
alert('어서오세요 사이퍼즈 세계에!!');
|
import Chart from "../Chart/Chart";
const ExpensesChart = (props) => {
return <Chart data={props.filteredData} />;
};
export default ExpensesChart;
|
'use strict';
angular.module('demoAppApp')
.controller('ResultDetailController', function ($scope, $rootScope, $stateParams, entity, Result, Investigation) {
$scope.result = entity;
$scope.load = function (id) {
Result.get({id: id}, function(result) {
$scope.result = result;
});
};
var unsubscribe = $rootScope.$on('demoAppApp:resultUpdate', function(event, result) {
$scope.result = result;
});
$scope.$on('$destroy', unsubscribe);
});
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "941f0f0fa7438a5cbaf0bb0783f50439",
"url": "/index.html"
},
{
"revision": "90ac4a614d5e4488bd64",
"url": "/static/css/main.d848d16b.chunk.css"
},
{
"revision": "4faf76328267412a5f1c",
"url": "/static/js/2.d5c10175.chunk.js"
},
{
"revision": "90ac4a614d5e4488bd64",
"url": "/static/js/main.20da7839.chunk.js"
},
{
"revision": "42ac5946195a7306e2a5",
"url": "/static/js/runtime~main.a8a9905a.js"
}
]);
|
import * as glext from "./../../GLExt/GLExt.js"
import * as sys from "./../../System/sys.js"
import * as vMath from "./../../glMatrix/gl-matrix.js";
import * as ui from "./ui.js"
import * as command from "./command.js"
import * as brushInterpolator from "./brushInterpolator.js"
import { CLayer, CRasterLayer, CVectorLayer } from "./layer.js";
class CLayerRenderer extends command.ICommandExecute{
/*
*/
constructor(){
super();
this.setType("CLayerRenderer");
this.framebuffer = new glext.CFramebuffer(false); this.framebuffer.Create();
this.quad_model = new glext.CModel(-1);
glext.GenQuadModel(this.quad_model);
}
RenderLayer(shader){
}
}
class CCursor extends command.ICommandExecute{
constructor(w, h){
super();
this.setType("CCursor");
this.width = w;
this.height = h;
this.X = 0.0;
this.Y = 0.0;
this.x = 0.0;
this.y = 0.0;
this.Pos = [0.0,0.0];
this.pos = [0.0,0.0];
let bBtnLeft = false;
let bLeftDown = false;
let bLeftUp = false;
}
set(posX, posY, bBtnLeft, bLeftDown, bLeftUp){
this.X = posX;
this.Y = posY;
this.x = this.X / this.width;
this.y = this.Y / this.height;
this.Pos = [this.X, this.Y];
this.pos = [this.x, this.y];
this.bBtnLeft = bBtnLeft;
this.bLeftDown = bLeftDown;
this.bLeftUp = bLeftUp;
}
}
export class CDocument extends ui.CGUIElement{
constructor(docId){
super();
this.setType("CDocument");
++CDocument.createdCount;
if(docId != null){
this.htmlObj = document.getElementById(docId);
this.docId = docId;
//ToDo: init width/height from htmlObj
this.width = 0;
this.height = 0;
}
else{
this.htmlObj = null;
this.docId = "document_file_" + CDocument.createdCount.toString();
this.width = 0;
this.height = 0;
}
this.layers = [];
// this.canvas = CanvasHandler.CreateHandle();
this.editingID = 0; //id layera u listi layers koji se trenutno editira
this.paintCanvas = null;
// this.parentCDocument = null;
this.activeLayerID = 0;
this.brush = null;
this.cursor = null;
this.interpolator = new brushInterpolator.CBrushInterpolator();
}
setBrush(brsh){
this.brush = brsh;
}
clearBrush(){
this.brush = null;
}
CreateFromDOM(dom, caller){
let _this = (caller == null || caller == undefined)? this : caller;
super.CreateFromDOM(dom, _this);
this.setZIndex( ui.CGUIElement.zIndex_Document );
}
CollapseForDisplay(){
//collapsat layere od 0 - editingID-1 u donju teksturu, a editingID+1 do layers.length-1 u gornju.
}
CreateLayerExt(type, w, h){
if(type == "raster"){ this.layers[this.layers.length] = new CRasterLayer(w, h); } else
if(type == "vector"){ this.layers[this.layers.length] = new CVectorLayer(w, h); }
}
CreateLayer(type){
this.CreateLayerExt(type, this.width, this.height); }
getDOM(){ return this.htmlObj; }
//----------------------------------------------------------------------
// set size
//----------------------------------------------------------------------
setSize(w, h){
let sizeobj = sys.utils.getGrandchild(this.htmlObj, CDocument.ids_to_size);
sizeobj.style.width = (w + 32).toString() + "px";
sizeobj.style.height = (h + 32).toString() + "px";
this.width = w;
this.height = h;
this.cursor = new CCursor(w, h);
}
/*resizes the document and every layer in it. */
ResizeInPixels(dleft, dright, dup, ddown){
for(let i = 0; i < this.layers.length; ++i){
this.layers[i].ResizeCanvas(dleft, dright, dup, ddown); }
let dw = dleft + dright; let dh = dup + ddown;
this.setSize(this.width+dw, this.height+dh);
this.UpdatePaintCanvasSize();
}
RescaleInPixels(dleft, dright, dup, ddown){
for(let i = 0; i < this.layers.length; ++i){
this.layers[i].ScaleCanvas(dleft, dright, dup, ddown); }
let dw = dleft + dright; let dh = dup + ddown;
this.setSize(this.width+dw, this.height+dh);
this.UpdatePaintCanvasSize();
}
ResizeInPercentage(pleft, pright, pup, pdown){
let dleft = pleft * this.width;
let dright = pright * this.width;
let dup = pup * this.height;
let ddown = pdown * this.height;
this.ResizeInPixels(dleft, dright, dup, ddown);
}
RescaleInPercentage(pleft, pright, pup, pdown){
let dleft = pleft * this.width;
let dright = pright * this.width;
let dup = pup * this.height;
let ddown = pdown * this.height;
this.RescaleInPixels(dleft, dright, dup, ddown);
}
Resize(){
let func = (arguments[0] == "percent")? this.ResizeInPercentage.bind(this) : this.ResizeInPixels.bind(this);
if(arguments.length > 3)
func(arguments[1],arguments[2],arguments[3],arguments[4]);
else{
let dw = arguments[1]/2.0; let dh = arguments[2]/2.0;
func( dw, dw, dh, dh );
}
}
Rescale(){
let func = (arguments[0] == "percent")? this.RescaleInPercentage.bind(this) : this.RescaleInPixels.bind(this);
if(arguments.length > 3)
func(arguments[1],arguments[2],arguments[3],arguments[4]);
else{
let dw = arguments[1]/2.0; let dh = arguments[2]/2.0;
func( dw, dw, dh, dh );
}
}
//----------------------------------------------------------------------
CreateNew(w, h){
this.width = w;
this.height = h;
//load html file and create dom elements from it (callback function)
sys.html.CreateDOMFromHTMLFile(this, "./windows/document.html", function(_this, obj){
_this.htmlObj = document.createElement('div');
_this.htmlObj.docId = _this.docId;
_this.htmlObj.appendChild(obj);
_this.CreateFromDOM(_this.htmlObj, _this);
_this.htmlObj.uiObj = _this;
_this.setSize(w, h);
document.body.appendChild(_this.htmlObj);
_this.htmlObj.style.position = "absolute";
// _this.htmlObj.onclick = document.window.document_onclick(_this.docId);
_this.htmlObj.AttachGLCanvas = _this.AttachGLCanvas;
// _this.htmlObj.onclick = _this.AttachGLCanvas;
_this.addOnClick(_this);
sys.html.MakeElementMovable(_this.htmlObj, "data-movable-element-handle");
});
}
getActivePaintLayer(){ return this.layers[this.activeLayerID].getPaintLayer(); }
BringToFront(){
this.uiObj.setZIndex( ui.CGUIElement.zIndex_Document+1 );
}
onClick(){
this.htmlObj.AttachGLCanvas();
}
RenderVisibleLayersToCanvas(){
let shader = glext.NDCQuadModel.mainDisplayShader;
glext.CFramebuffer.BindMainFB();
glext.gl.viewport(0, 0, glext.gl.viewportWidth, glext.gl.viewportHeight);
glext.gl.clearColor(0.0,0.0,0.0,1.0);
glext.gl.clear(glext.gl.COLOR_BUFFER_BIT | glext.gl.DEPTH_BUFFER_BIT);
shader.Bind();
this.getActivePaintLayer().texture.Bind(0, shader.ULTextureD);
glext.NDCQuadModel.RenderIndexedTriangles(shader);
this.getActivePaintLayer().texture.Unbind();
}
getHMTLImageFromCanvas(){
this.RenderVisibleLayersToCanvas();
let img = document.createElement('img');
img.src = glext.gl.canvasObject.toDataURL();
return img;
}
AddHTMLImage(htmlImg){
htmlImg.id = this.docId + "_img";
// htmlImg.style.position = "absolute";
htmlImg.style = glext.gl.canvasObject.style;
let obj = sys.utils.getGrandchild(this.htmlObj, CDocument.ids_to_paint_area);
obj.appendChild(htmlImg);
}
RemoveHTMLImage(){
let obj = sys.utils.getGrandchild(this.htmlObj, CDocument.ids_to_paint_area);
let i = sys.utils.getChildPosition(obj, this.docId + "_img");
if(i != -1)
obj.removeChild(obj.childNodes[i]);
}
//updates the OpenGL paint canvas, if this is active document
UpdatePaintCanvasSize(){
if(this.paintCanvas == null) return;
if(this.paintCanvas.width != this.width || this.paintCanvas.height != this.height){
this.paintCanvas.width = this.width;
this.paintCanvas.height = this.height;
glext.ResizeCanvas(this.width, this.height);
let dw = this.width - this.getActivePaintLayer().width;
let dh = this.height - this.getActivePaintLayer().height;
this.getActivePaintLayer().ResizeCanvas(Math.floor(dw/2.0), Math.floor(dw/2.0), Math.ceil(dh/2.0), Math.ceil(dh/2.0));
}
}
AttachGLCanvas(){
//this function operates on htmlObj from CDocument (this ptr is htmlObj)
let gl = glext.gl;
if(gl == null) return;
// assert(CDocuments.Count() != 0);
if(CDocuments.getActive() === this.uiObj) return;
if(CDocuments.Count() > 1){
let obj = sys.utils.getGrandchild(this, CDocument.ids_to_paint_area);
let objtwo = gl.canvasObject.parentNode;
let objtwoChildPos = sys.utils.getChildPosition(objtwo, CDocument.id_paint_canvas);
let oldCanvasObject = sys.utils.getChild(obj, CDocument.id_paint_canvas);
let doctwo = sys.utils.getGrandparent(gl.canvasObject, CDocument.ids_to_paint_area_reversed).parentNode;
let htmlImg = doctwo.uiObj.getHMTLImageFromCanvas();
doctwo.uiObj.AddHTMLImage(htmlImg);
//replaceChild( new, old );
obj.replaceChild(gl.canvasObject, oldCanvasObject);
if(objtwoChildPos != -1) objtwo.insertBefore(oldCanvasObject, objtwo.children[objtwoChildPos]);
//add mous functions to paint document object
this.baseWindowOffset = [gl.canvasObject.offsetLeft, gl.canvasObject.offsetTop];
this.transformMouseCoords = function(pos){
pos[0] = pos[0] - this.baseWindowOffset[0];
pos[1] = pos[1] - this.baseWindowOffset[1];
}
// gl.activeDoc = this;
CDocuments.setActive(this.uiObj);
this.uiObj.paintCanvas = gl.canvasObject;
doctwo.uiObj.paintCanvas = null;
this.uiObj.UpdatePaintCanvasSize();
this.uiObj.RenderVisibleLayersToCanvas();
this.uiObj.RemoveHTMLImage();
//set to front
this.uiObj.setZIndex( ui.CGUIElement.zIndex_Document );
//set to back
doctwo.uiObj.setZIndex( ui.CGUIElement.zIndex_ToBack );
}
else if(CDocuments.Count() == 1){
let obj = sys.utils.getGrandchild(this, CDocument.ids_to_paint_area);
let oldCanvasObject = sys.utils.getChild(obj, CDocument.id_paint_canvas);
obj.replaceChild(gl.canvasObject, oldCanvasObject);
this.baseWindowOffset = [gl.canvasObject.offsetLeft, gl.canvasObject.offsetTop];
this.transformMouseCoords = function(pos){
pos[0] = pos[0] - this.baseWindowOffset[0];
pos[1] = pos[1] - this.baseWindowOffset[1];
}
CDocuments.setActive(this.uiObj);
this.uiObj.paintCanvas = gl.canvasObject;
this.uiObj.setZIndex( ui.CGUIElement.zIndex_Document );
}
}
getPaintCanvas(){ return this.paintCanvas; }
//----------------------------------------------------------------------
// Update()
//----------------------------------------------------------------------
updateCursor(X, Y, bBtnLeft, bLeftDown, bLeftUp){
if(this.cursor == null) return;
this.cursor.set(X, Y, bBtnLeft, bLeftDown, bLeftUp);
}
updateBrush(){
if(this.brush == null) return;
if(this.cursor == null) return;
/*
brush has only position update here,
because other params are state of the brush and should be updated elsewhere
document only cares about position where to draw with brush,
and brush gets it color/size/type from other places (i.e. palette...)
*/
if(this.cursor.bBtnLeft == false){
this.brush.setColor(0.0,0.0,0.0); } //ToDo: make brush disabling with other option, color value should be kept by the brush
else{
this.brush.setPosition( this.cursor.pos ); }
let pos = [this.cursor.pos[0],1.0-this.cursor.pos[1]];
if(this.cursor.bLeftDown == true)
this.interpolator.Start(pos);
else if(this.cursor.bLeftUp == true)
this.interpolator.End(pos);
else
this.interpolator.Next(pos);
//initialDeltaT, minimalDeltaT, maxAngle, maxDistance, minDistance
// 0.02, 0.0002, 2.5, 0.05, 0.02
let PointsI = this.interpolator.Interpolate(0.2, 0.02, 2.5, 0.1, 0.05);
if(PointsI != undefined && PointsI.length > 0){
this.brush.setStrokeStart();
this.brush.setStrokeEnd();
this.brush.UploadPointListToShader(PointsI);
}
else{
this.brush.setStrokeEnd(false);
this.brush.setStrokeStart(false);
this.brush.ClearShaderPointList();
}
glext.CBlendMode.Bind(glext.CBlendMode.None);
this.brush.Update();
}
updateLayers(){
//updating of all layers
for(let i = 0; i < this.layers.length; ++i){
let layer = this.layers[i].getPaintLayer();
if(layer != null){
layer.Begin(this.brush.shader);
layer.Draw();
layer.End();
}
}
}
Update(cmd){ //X, W, bPressed
if(cmd != undefined && cmd != null){
this.exec(cmd);
}
}
//----------------------------------------------------------------------
execMouseEvent(cmd){
let cmdP = cmd.commandParams;
//cmd.set(doc.objectId, "CDocument", "mouseEvent", "absoluteMousePos", mousePos, bBtnLeft, sys.mouse.get().bLeftDown, sys.mouse.get().bLeftUp);
let pos = cmdP.params[1].value;
if(cmdP.params[0].value == "absoluteMousePos"){
this.uiObj.paintCanvas.transformMouseCoords(pos);
cmdP.params[0].value = "relativeMousePos";
}
let bBtnLeft = cmdP.params[2].value;
let bLeftDown = cmdP.params[3].value;
let bLeftUp = cmdP.params[4].value;
this.updateCursor(pos[0], pos[1], bBtnLeft, bLeftDown, bLeftUp);
this.updateBrush();
this.updateLayers();
}
exec(cmd){
if(cmd.objectType != "CDocument")
return;
if(cmd.command == "mouseEvent")
this.execMouseEvent(cmd);
}
//----------------------------------------------------------------------
Delete(){
for(let i = 0; i < this.layers.length; ++i){
this.layers[i].Delete();
this.layers[i] = null;
}
this.layers = [];
}
}
CDocument.createdCount = 0;
CDocument.ids_to_paint_area = ["panelmain","document_size","document_display_grid","document_paint_area"];
CDocument.ids_to_paint_area_reversed = ["document_paint_area","document_display_grid","document_size","panelmain"];
CDocument.id_paint_canvas = "document_paint_canvas";
CDocument.ids_to_size = ["panelmain","document_size"];
export class CDocuments extends command.ICommandExecute{
constructor(){
super();
this.setType("CDocuments");
}
static CreateDocument(w,h){
let doc = new CDocument(null);
CDocuments.documents[CDocuments.documents.length] = doc;
doc.CreateNew(w,h);
return doc;
}
static setActive(doc){
CDocuments.activeDoc = doc;
}
static Count(){ return CDocuments.documents.length; }
static getActive(){ return CDocuments.activeDoc; }
}
CDocuments.documents = [];
CDocuments.activeDoc = null;
|
"use strict";
let camera = null;
let defaultEaseTime = 20000000000000000000000000;
function createCamera(x, y, z, rx, ry, rz, viewangle) {
camera = mp.cameras.new("Cam", {x: x, y: y, z: z}, {x: rx, y: ry, z: rz}, viewangle);
camera.setActive(true);
mp.game.cam.renderScriptCams(true, true, defaultEaseTime, false, false);
}
exports.createCamera = createCamera;
function destroyCamera() {
if (!camera) return;
camera.setActive(false);
mp.game.cam.renderScriptCams(false, true, 0, true, true);
camera.destroy();
camera = null;
}
exports.destroyCamera = destroyCamera;
mp.events.add(
{
"cameraDestroyed" : () => {
destroyCamera();
},
});
|
import React from 'react'
import './Hero.css'
import PlusSign from '../../images/plus-sign.png'
import bracketImg from '../../images/brackets.png'
class BracketsList extends React.Component {
constructor(props) {
super(props)
console.log('THIS.PROPS', this.props)
this.state = {
show: true
}
this.showBrackets = this.showBrackets.bind(this)
}
showBrackets() {
this.setState((prevState, props) => ({
show: !this.state.show
}))
}
render() {
const display = this.state.show ? { visibility: 'visible' } : { visibility: 'hidden' }
const brackets = [
{
text: 'Templates optimized for load-speed, compatible with all ad networks.'
},
{
text: 'Open-source components, makes authoring & customization easy.'
},
{
text: 'Compiled builds, saves k-weight for your creative.'
},
{
text: 'Flexible tools, fits your process & enable automation.'
}
]
return (
<div className="bracket-container">
<div className="bracket-row">
<div style={display} className="brackets-list">
<div className="bracket-text">{brackets[0].text}</div>
<img src={bracketImg} className="bracket-img" alt="bracket img" />
</div>
<div style={display} className="brackets-list">
<div className="bracket-text">{brackets[1].text}</div>
<img src={bracketImg} className="bracket-img" alt="bracket img" />
</div>
</div>
<div className="bracket-row">
<img src={PlusSign} onClick={this.showBrackets} className="plus-sign" alt="plus-sign" />
</div>
<div className="bracket-row">
<div style={display} className="brackets-list">
<div className="bracket-text">{brackets[2].text}</div>
<img src={bracketImg} className="bracket-img" alt="bracket img" />
</div>
<div style={display} className="brackets-list">
<div className="bracket-text">{brackets[3].text}</div>
<img src={bracketImg} className="bracket-img" alt="bracket img" />
</div>
</div>
</div>
)
}
}
export default BracketsList
|
import chai from 'chai';
import Deck from '../../lib/deck/Deck';
const SUITS = require('../../lib/deck/suits.json');
const VALUES = require('../../lib/deck/values.json');
import Card from '../../lib/deck/Card';
import _ from 'lodash';
const assert = chai.assert;
describe('Deck', () => {
let deck;
beforeEach(() => {
deck = new Deck(index => {
const value = VALUES[index * 2 % VALUES.length];
const suit = SUITS[index % SUITS.length];
return new Card(value, suit);
});
});
it('.card', () => {
let card = deck.card();
assert.equal(card.value, 'A');
assert.equal(card.suit, SUITS[0]);
});
describe('.cards', () => {
let cards;
beforeEach(() => {
cards = deck.cards(3);
});
it('should provide the requested count of cards', () => {
assert.equal(cards.length, 3);
});
it('should provide the predicted cards', () => {
let card = cards[0];
assert.equal(card.value, 'A');
assert.equal(card.suit, SUITS[0]);
card = cards[2];
assert.equal(card.value, 5);
assert.equal(card.suit, SUITS[2]);
});
it('should always return cards in the expected range', () => {
var count = 100;
while (count-- > 0) {
let card = deck.card();
assert.ok(_.includes(SUITS, card.suit));
assert.ok(_.includes(VALUES, card.value));
}
});
});
describe('random deck', () => {
beforeEach(() => {
deck = new Deck();
});
it('should always return cards in the expected range', () => {
var count = 100;
while (count-- > 0) {
let card = deck.card();
assert.ok(_.includes(SUITS, card.suit));
assert.ok(_.includes(VALUES, card.value));
}
});
});
});
|
import {Form, Input, Icon, Select, DatePicker, Row, Col, Checkbox, Button, AutoComplete} from 'antd';
import React, {Component} from 'react';
import moment from 'moment';
import 'moment/locale/zh-cn';
import SearchModal from '../../components/modal/SearchModal.js'
import {articleTypeGetAll} from '../../requests/http-req.js'
moment.locale('zh-cn');
const FormItem = Form.Item;
const MonthPicker = DatePicker.MonthPicker;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;
class ArticleListSearch extends Component {
state = {
type: []
};
selectUserId = ''
handleSearch = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
if (this.props.handleSearch) {
this.props.handleSearch(values)
}
}
});
}
componentWillMount() {
}
componentDidMount() {
//获取币种类型 //获取提现类型的接口
articleTypeGetAll().then(((req) => {
console.log(req)
this.setState({
type: req.data.data
})
}))
}
render() {
const {getFieldDecorator} = this.props.form;
return (
<Form
style={{
flexDirection: 'row', display: 'flex', minHeight: '60px', height: '60px', width: '100%'
, paddingRight: '15px', paddingLeft: '15px'
}}
className="ant-advanced-search-form"
onSubmit={this.handleSearch}
>
<div style={{width: '100%', display: 'flex', flexDirection: 'row'}}>
<FormItem style={{margin: 'auto', flex: 1, paddingRight: '15px'}} label={'关键字'}>
{getFieldDecorator('keyWords', {
rules: [{
message: '关键字',
}],
})(
<Input/>
)}
</FormItem>
<FormItem style={{margin: 'auto', flex: 1, paddingRight: '15px'}} label={`文章类型`}>
{getFieldDecorator(`type`, {})(
<Select
placeholder="文章类型"
>
<Option key={1232} value={null}>全部</Option>
{
this.state.type && this.state.type.map((item, index) => {
return <Option key={index} value={item.typeName}>{item.typeName}</Option>
})
}
</Select>
)}
</FormItem>
<FormItem style={{margin: 'auto', flex: 1, paddingRight: '15px'}} label={`显示客户端`}>
{getFieldDecorator(`showClient`, {})(
<Select
placeholder="选择"
// onChange={this.handleSelectChange}
>
<Option key={3} value={null}>全部</Option>
<Option key={1} value={1}>手机端</Option>
<Option key={2} value={2}>电脑端</Option>
</Select>
)}
</FormItem>
<div style={{flex: 1}}/>
</div>
<Button htmlType="submit" type="primary" icon="search" style={{
margin: 'auto'
}}>搜索
</Button>
</Form>
);
}
}
const NewArticleListSearch = Form.create()(ArticleListSearch);
export default NewArticleListSearch;
|
import Rx from 'rxjs/Rx'
import { createSubscriber } from '../utils'
// Rx.Observable.interval(500)
// .take(5)
// .subscribe(createSubscriber('interval'))
// Rx.Observable.timer(1000, 500)
// .take(3)
// .subscribe(createSubscriber('timer'))
Rx.Observable.of('Hello!', 42, 'wow')
.subscribe(createSubscriber('of'))
Rx.Observable.of([ 'Hello!', 42, 'wow' ])
.subscribe(createSubscriber('of Array'))
Rx.Observable.from('yo')
.subscribe(createSubscriber('from'))
Rx.Observable.from([ 'Hello!', 42, new Error('hmm'), 'wow' ])
.subscribe(createSubscriber('from Array'))
// function * generate() {
// yield 1
// yield 5
// yield 'HEY!!'
// }
//
// Rx.Observable.from(generate())
// .subscribe(createSubscriber('from generator'))
Rx.Observable.throw(123)
.subscribe(createSubscriber('throw'))
Rx.Observable.throw(new Error('Argh!'))
.subscribe(createSubscriber('throw Error'))
Rx.Observable.empty()
.subscribe(createSubscriber('empty'))
let sideEffect = 0
const defer$ = Rx.Observable.defer(() => {
sideEffect += 1
return Rx.Observable.of(sideEffect)
})
defer$.subscribe(createSubscriber('defer$.one'))
defer$.subscribe(createSubscriber('defer$.two'))
defer$.subscribe(createSubscriber('defer$.three'))
Rx.Observable.never()
.subscribe(createSubscriber('never'))
Rx.Observable.range(10, 30)
.subscribe(createSubscriber('range'))
|
const pwd = process.env.PWD
module.exports = function() {
return pwd;
}
|
var level = require('levelup'),
levelMultiply = require('level-multiply'),
indexPeek = require('./indexing/indexPeek.js'),
matcher = require('./matchers/matcher.js'),
calibrater = require('./indexing/calibrater.js'),
indexer = require('./indexing/indexer.js'),
deleter = require('./indexing/deleter.js'),
replicator = require('./indexing/replicator.js'),
searcher = require('./search/searcher.js'),
docGetter = require('./search/docGetter.js'),
rmdir = require('rimraf'),
_ = require('lodash')
searchIndexLogger = require('./logger/searchIndexLogger'),
winston = require('winston');
var indexes = null, indexesMultiply = null;
var defaults = {
indexPath: 'si',
logLevel: 'info',
logSilent: false
};
var SearchIndex = module.exports = function (options) {
//initialize defaults options
options = _.defaults(options || {}, defaults);
//for further use
this.options = options;
indexes = (options && options.db)
? level(options.indexPath, {valueEncoding: 'json', db: options.db})
: level(options.indexPath, {valueEncoding: 'json'});
indexesMultiply = levelMultiply(indexes);
searchIndexLogger.remove(winston.transports.Console);
searchIndexLogger.add(winston.transports.Console, {silent: options.logSilent, level: options.logLevel});
calibrater.getTotalDocs(indexes, function(err, totalDocs) {
searcher.setTotalDocs(totalDocs);
});
return SearchIndex;
};
SearchIndex.del = function(docID, callback) {
if (!indexes) SearchIndex();
deleter.deleteDoc(docID, indexes, indexesMultiply, function(err) {
callback(err);
});
};
SearchIndex.get = function(docID, callback) {
if (!indexes) SearchIndex();
docGetter.getDoc(indexes, docID, function(err, doc) {
callback(err, doc);
});
};
SearchIndex.add = function(options, batch, callback) {
if (!indexes) SearchIndex();
indexer.addDocToIndex(indexes,
indexesMultiply,
batch,
options.batchName,
options.filters,
function(err) {
callback(err);
});
};
SearchIndex.empty = function( callback) {
var self = this;
if (!indexes) SearchIndex();
var err = false;
indexes.close(function(){
rmdir(self.options.indexPath, function(err){
indexes = level(self.options.indexPath, {valueEncoding: 'json'});
indexesMultiply = levelMultiply(indexes);
callback(err);
});
});
};
SearchIndex.search = function (q, callback) {
if (!indexes) SearchIndex();
searcher.search(indexes, indexesMultiply, q, function(results){
//TODO: make error throwing real
callback(false, results);
});
};
SearchIndex.match = function(beginsWith, callback) {
if (!indexes) SearchIndex();
matcher.matcher(indexes, beginsWith, function(err, match) {
callback(err, match);
});
};
SearchIndex.tellMeAboutMySearchIndex = function(callback) {
if (!indexes) SearchIndex();
calibrater.getTotalDocs(indexes, function(err, totalDocs) {
var metadata = {};
metadata['totalDocs'] = totalDocs;
callback(metadata);
});
};
SearchIndex.replicate = function(readStream, callback) {
if (!indexes) SearchIndex();
replicator.replicateFromSnapShot(readStream, indexes, function(err) {
callback(err);
});
};
SearchIndex.snapShot = function(callback) {
if (!indexes) SearchIndex();
replicator.createSnapShot(indexes, function(msg) {
callback(msg);
});
};
//utility methods for testing and devlopment
//******************************************
SearchIndex.indexRange = function(options, callback) {
if (!indexes) SearchIndex();
indexPeek.indexRange(options.start, options.stop, indexes, function(err, dump) {
callback(err, dump);
});
};
SearchIndex.indexValue = function(options, callback) {
if (!indexes) SearchIndex();
indexPeek.indexValue(options.key, indexes, function(err, value) {
callback(err, value);
});
};
//do a full recalibration of the index
SearchIndex.calibrate = function(callback) {
if (!indexes) SearchIndex();
calibrater.calibrate(indexes, function(err, msg) {
callback(err, msg);
});
};
|
// Setup a host to map to an externally facing IP via NAT-PMP
// https://tools.ietf.org/html/draft-cheshire-nat-pmp-03
const natpmp = require('nat-pmp');
const netroute = require('netroute');
exports.getExternalIp = function(port) {
console.log('hello')
const gateway = netroute.getGateway();
const client = new natpmp.Client(gateway);
client.portMapping({ public: port, private: port, ttl: 0 }, (err, info) => {
console.log('goodbye')
if (err) { console.log('error', err); }
else { console.log('info', info); }
})
}
|
'use strict';
const byteArrayToString = (byteArray) => {
const pad2 = x => x && x.length == 1 ? '0' + x : x;
const bytes = Array.from(byteArray || [])
.map(x => x !== undefined ? pad2(x.toString(16)) : '?');
return `[${bytes.join(', ')}]`;
};
/**
* @class Buffer
* @param {Object} options
* @param {Object} options.isMessageStart
* @param {Object} options.recognizeMessage Function that recognize a message from an array of bytes, it must return false or an Object with a property 'type'
* @param {Number} [readMessageTimeout] The value of Buffer.readMessageTimeout
* @property {Number} readMessageTimeout Time (in milliseconds) after which readMessage will throw an error if no data is received
*/
class Buffer {
constructor(options = {}) {
// Check isMessageStart
if (!options.isMessageStart)
throw new Error('Invalid isMessageStart funciton');
// TODO: check if it's a funciton
this._isMessageStart = options.isMessageStart;
// Check recognizeMessage
if (!options.recognizeMessage)
throw new Error('Invalid recognizeMessage funciton');
// TODO: check if it's a funciton
this._recognizeMessage = options.recognizeMessage;
// Init support variables
this._byteBuffer = [];
this._messageBuffer = [];
this._messageBufferMaxLenght = 10;
this._subscriptions = [];
this._isReadingMessage = false;
this.readMessageTimeout = options.readMessageTimeout || 60 * 1000;
}
/**
* Functions that receive chunks of data and recognize the messages
* @param {Number[]} data
*/
handleData(data) {
// Convert data to an array if needed
if (false === Array.isArray(data))
data = Array.from(data);
if (!this._isReadingMessage) {
while (data.length > 0) {
const isStart = this._isMessageStart(data);
if (isStart) {
this._isReadingMessage = true;
break;
}
// We don't know what this means, we just ignore the byte
// Ideally this should never happen 😅
const byteString = byteArrayToString([data[0]]);
console.warn(this._name, `*** Ignored ${byteString}`);
data.shift();
}
}
for (const byte of data) {
this._byteBuffer.push(byte);
const message = this._recognizeMessage(this._byteBuffer);
if (message) {
// Remove the message from the byteBuffer
this._removeFromByteBuffer(message.bytes.length);
// Add the message to the messageBuffer
if (this._messageBuffer.length + 1 > this._messageBufferMaxLenght)
this._messageBuffer.shift();
message.received = new Date();
this._messageBuffer.push(message);
// Notify subscriptions
this._subscriptions.forEach((subscription, index, subscriptions) => {
if (subscription.all !== true && subscription.msg.name !== message.type)
return;
if (typeof subscription.callback === 'function')
subscription.callback(message);
if (subscription.once)
subscriptions.splice(index, 1); // Remove subscription
});
}
}
}
/**
* Removes N bytes from the buffer
* @param {Number} n Number of bytes to be removed. With n=-1 it emptys the buffer
*/
_removeFromByteBuffer(n) {
if (n == -1)
n = this._byteBuffer.length;
for (let i = 0; i < n && this._byteBuffer.length > 0; i++)
this._byteBuffer.shift();
}
/**
* Subscribe to a message
* @param {Object} options
* @param {Message} options.msg Message
* @param {Boolean} [options.once=true]
* @param {Boolean} [options.all=false]
* @param {Function} options.callback
* @returns {Function} unsubscribe callback
*/
subscribe(options) {
const { msg, once = true, all = false, callback } = options;
const subscription = { msg, once, all, callback };
this._subscriptions.push(subscription);
return _ => {
const index = this._subscriptions.indexOf(subscription);
if (index !== -1) this._subscriptions.splice(index, 1);
};
}
/**
* Read a message from the serialport
* @param {String} msg Message
* @param {Object} options
* @param {Number} [options.timeout] If not set it uses the readMessageTimeout that was passed to the constructor
* @returns {Message} message
* @async
*/
async readMessage(msg, options = {}) {
let resolve, reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
const { timeout = this.readMessageTimeout } = options;
const timeoutId = setTimeout(_ => {
const msgBuffer = this._messageBuffer.map(m => m.type);
const error = new Error(`Timeout waiting for "${msg.name}", current buffers: ${JSON.stringify(this._byteBuffer)}, ${JSON.stringify(msgBuffer)}`);
error.byteBuffer = this._byteBuffer;
error.msgBuffer = this._messageBuffer.map(m => ({
type: m.type,
data: m.bytes
}));
reject(error);
}, timeout);
const callback = msg => {
clearTimeout(timeoutId);
resolve(msg);
}
this.subscribe({ msg, once: true, callback });
return promise;
}
}
module.exports = Buffer;
|
module.exports = class Book {
constructor(name, author, genre, id) {
this.name = name;
this.author = author;
this.genre = genre;
this.id = id;
}
static create({ name, author, genre, id }) {
return new Book(name, author, genre, id);
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.