text
stringlengths 7
3.69M
|
|---|
import React, { Component } from 'react';
import { withRouter, Link } from 'react-router-dom'
import { Layout, Menu , Avatar, Icon, Button, message } from 'antd';
import { Query, Mutation } from 'react-apollo';
// Queries
import GET_USER from '../../queries/GET_USER';
import QUERY_USER from '../../queries/QUERY_USER';
import REMOVE_USER from '../../queries/REMOVE_USER';
// constants
import routesCode from '../../constants/routes';
// Ant.design
const { Header } = Layout;
const { REACT_APP_CLIENT_ID, REACT_APP_REDIRECT_URI } = process.env;
const Login = () => (
<a href={`https://github.com/login/oauth/authorize?client_id=${REACT_APP_CLIENT_ID}&scope=user%20public_repo%20gist&redirect_uri=${REACT_APP_REDIRECT_URI}`}>
<Icon type="login" />
Login
</a>
);
class CustomHeader extends Component {
renderLink = () => {
if (localStorage.getItem("github_token")) {
return (
<Query query={ GET_USER }>
{({ data, client }) => {
// If local user
const { name, avatarUrl } = data.user;
if (name) {
return (
<Mutation mutation={ REMOVE_USER }>
{(removeUser) => (
<div>
<Avatar className="hideMobile" size="large" src={avatarUrl} />
<span className="hideMobile"> { name } </span>
<Button
onClick={e => {
e.preventDefault();
localStorage.removeItem("github_token");
removeUser();
message.success('logged out');
this.props.history.push('/login');
}}
style={{ marginLeft: 10 }}
ghost
>
Log out
<Icon type="logout" />
</Button>
</div>
)}
</Mutation>
);
}
// If not local user, query
return (
<Query query={ QUERY_USER } onCompleted={(params) => {
client.writeData({ data: { user: params.viewer} });
}}>
{({ loading, error }) => {
if (loading) return <div>loading...</div>;
if (error) return <div>Error</div>;
return <Login />;
}}
</Query>
);
}}
</Query>
);
}
// If not logged
return <Login />;
}
checkifLogged = () => {
if (!localStorage.getItem("github_token")) {
message.warning('You need to login first');
}
}
selectedKey = () => {
const { history } = this.props
switch (history.location.pathname) {
case routesCode.AUTH.DASHBOARD:
return '1';
case routesCode.AUTH.STARED:
return '2';
case routesCode.PUBLIC.LOGIN:
return '4';
default:
// Return the default for add fedback / routes / etc
return '3'
}
}
render() {
return (
<Header>
<div className="logo" />
<Menu
theme="dark"
mode="horizontal"
defaultSelectedKeys={[ this.selectedKey() ]}
style={{ lineHeight: '64px' }}
>
<Menu.Item key="1">
<Link onClick={this.checkifLogged} to="/">Search</Link>
</Menu.Item>
<Menu.Item key="2">
<Link onClick={this.checkifLogged} to="/stared">Stared</Link>
</Menu.Item>
<Menu.Item className="hideMobile" key="3">
<Link to="/bacon">404 page</Link>
</Menu.Item>
<Menu.Item style={{float: 'right'}} key="4">
{ this.renderLink() }
</Menu.Item>
</Menu>
</Header>
);
}
}
export default withRouter(CustomHeader);
|
//循环添加不同行业标准的item
$(function(){
$.ajax({
url : "/BZCX/icstype/showTypeByTree",
type : "post",
async : true,
success : function(res) {
var classfiy_item=$('.classfiy_modules')
classfiy_items=eval("("+res.data+")");
var classfiy=''
for(var i=0;i<classfiy_items.length;i++){
classfiy+=`<div class='classfiy_title'>${classfiy_items[i].icsName}</div>
<div class='classfiy_content'>
<ul>
</ul>
</div>`
}
var first=classfiy_items[0].children,second=classfiy_items[1].children,third=classfiy_items[2].children;
classfiy_item.append(classfiy)
var classfiy_li=$('.classfiy_content>ul')
var path=''
for(var j=0;j<first.length;j++){
if(first[j].type==0){
path='country_standard.html'
}else if(first[j].type==1){
path='classify_law.html'
}
classfiy_li[0].innerHTML+=`<li class='classfiy_item'>
<a href="${path}?icsCode=${first[j].icsCode}&moudle='4003'&typeName=${first[j].type}">
<img src="${first[j].img}" />
<span>${first[j].icsName}</span>
</a>
</li>`
}
for(var d=0;d<second.length;d++){
if(second[d].type==0){
path='country_standard.html'
}else if(second[d].type==1){
path='classify_law.html'
}
classfiy_li[1].innerHTML+=`<li>
<a href="${path}?icsCode=${second[d].icsCode}&moudle='4003'&typeName=${second[d].type}">
<img src="${second[d].img}" />
<span>${second[d].icsName}</span>
</a>
</li>`
}
for(var h=0;h<third.length;h++){
if(third[h].type==0){
path='country_standard.html'
}else if(third[h].type==1){
path='classify_law.html'
}
classfiy_li[2].innerHTML+=`<li>
<a href="${path}?icsCode=${third[h].icsCode}&moudle='4003'&typeName=${third[h].type}">
<img src="${third[h].img}" />
<span>${third[h].icsName}</span>
</a>
</li>`
}
}
})
})
|
const opencage_apikey = '42463996dd094ffd8cc8fbebe5b5d09d'
module.exports = opencage_apikey;
|
angular.module("EcommerceModule").factory("MainpageService", function($http){
var returnValue = {};
var BASEURL = "http://localhost:8080/";
var httpGetData = function(URL){
return $http.get(URL);
}
var httpGetDataWithParam = function(URL, config){
return $http.get(URL, config);
}
var httpPost = function(URL, data){
return $http.post(URL, data);
}
returnValue.httpGetCategory = function(){
return httpGetData(BASEURL + "GetCategoryList");
}
returnValue.httpGetSubCategory = function(){
return httpGetData(BASEURL + "GetSubCategoryList");
}
returnValue.httpGetProduct = function(){
return httpGetData(BASEURL + "GetProductList");
}
returnValue.httpGetProductCount = function(){
return httpGetData(BASEURL + "GetProductCount");
}
returnValue.httpGetnewProduct = function(index, maxResult){
var param = {index: index, maxResult: maxResult};
return httpGetDataWithParam(BASEURL + "Product/GetNewProduct", {params: param});
}
returnValue.httpGetMostViewProduct = function(index, maxResult){
var param = {index: index, maxResult: maxResult};
return httpGetDataWithParam(BASEURL + "Product/GetTheMostViewedProduct", {params: param});
}
returnValue.OpenCart = function(token){
var URL = {
url: BASEURL + "Cart/Purchase",
headers: {
'token': token
}
};
return httpGetData(URL);
}
returnValue.logOut = function(token){
var URL = BASEURL + "User/Logout?token=" + token;
return $http.post(URL, {});
}
return returnValue;
})
|
import {createStore, combineReducers} from 'redux';
import ChatReducer from './reducers/chat';
import UserReducer from './reducers/user';
import BrowserReducer from './reducers/browser';
var reducers = combineReducers({
ChatReducer: ChatReducer,
UserReducer: UserReducer,
BrowserReducer: BrowserReducer
});
var store = createStore(reducers);
export default store;
|
const status = {
}
|
'use strict';
var gulp = require('gulp'),
browserify = require('browserify'),
fs = require('fs');
gulp.task("jsDist", function() {
return browserify('./test/index.src.js', { debug: true})
.bundle().pipe(fs.createWriteStream('./test/index.js'));
});
//Serveur local
gulp.task('devServer', function() {
// Lancement du serveur local
var connect = require('connect');
var serveStatic = require('serve-static');
var http = require('http');
var app = connect();
/*app.use(require('connect-livereload')({
port: 35729
}));*/
app.use(serveStatic('./test'));
http.createServer(app).listen(8080);
var opn = require('opn');
opn('http://localhost:8080/');
});
gulp.task("dev", ["devServer"], function() {
});
gulp.task('default', function() {
// place code for your default task here
});
|
var async = require('async')
, config = require('./config')
, exec = require('child_process').exec
, fs = require('fs')
, nitrogen = require('nitrogen');
var user = new nitrogen.User({
nickname: 'user',
email: process.env.NITROGEN_EMAIL,
password: process.env.NITROGEN_PASSWORD
});
var service = new nitrogen.Service(config);
service.authenticate(user, function(err, session, user) {
if (err) return console.log('failed to connect user: ' + err);
// search for all sunset images from camera, sorted in oldest to newest
nitrogen.Message.find(session, { from: "52c33da4b77d9aac07000025", type: 'image', tags: 'sunset-1' }, {}, function(err, images) {
if (err) return console.log('finding images to stitch failed: ' + err);
async.eachLimit(images, 10, function(image, callback) {
var filename = 'images/' + image.ts.getTime() + '.jpg';
if (!fs.existsSync(filename)) {
nitrogen.Blob.get(session, image.body.url, function(err, resp, blob) {
if (err) return callback(err);
fs.writeFile(filename, blob, 'binary', function(err) {
if (err) return console.log('saving image failed');
console.log(filename + ' downloaded.');
callback();
});
});
} else {
console.log(filename + ' already downloaded.');
callback();
}
}, function (err) {
if (err) return console.log('failed to download all images, bailing.');
console.log('images downloaded successfully.');
var createVideoCommand = "ffmpeg -f image2 -r 20 -pattern_type glob -i 'images/*.jpg' -c:v libx264 timelapse.mp4";
exec(createVideoCommand, function (err, stdout, stderr) {
if (err) return console.log('failed to build video.');
console.log('created video');
});
});
});
});
|
import Vue from 'vue'
import VueEventBus from 'vue-event-bus'
import Footer from '@/components/Footer'
describe('Footer.vue', () => {
it('should render correct contents', () => {
Vue.use(VueEventBus)
const Constructor = Vue.extend(Footer)
const vm = new Constructor().$mount()
expect(vm.$el.querySelector('p').textContent)
.to.contain('Copyright 2016.')
})
it('starts with the attribution as an empty object', () => {
Vue.use(VueEventBus)
const Constructor = Vue.extend(Footer)
const vm = new Constructor().$mount()
expect(vm.attribution).to.deep.equal({})
})
it('updates the attribution when the search event happens', () => {
Vue.use(VueEventBus)
const Constructor = Vue.extend(Footer)
const vm = new Constructor().$mount()
vm.$bus.$emit('search', {
attribution: {
html: '<a></a>',
url: 'imageurl',
logo: 'apilogo'
}
})
expect(vm.attribution.url).to.equal('imageurl')
})
})
|
import React from "react";
import {ScrollView, Text, View} from "react-native";
export default class array_api extends React.Component {
render() {
return (<ScrollView>
<Text>length</Text>
</ScrollView>)
}
}
|
import FlightSegments from './FlightSegments';
export default FlightSegments;
|
import styled, { keyframes } from 'styled-components'
import { theme } from '@styles'
const { flat, fonts, borderRadius, fontSizes } = theme
export const StyledToast = styled.div`
border: 2px solid transparent;
background-color: ${flat.dark.background};
border-radius: ${borderRadius};
width: 100%;
box-shadow: 0 1px 10px 0 rgba(0, 0, 0, 0.1), 0 2px 15px 0 rgba(0, 0, 0, 0.05);
margin: 1.5rem 0 1rem;
padding: 1rem;
display: flex;
position: relative;
top: 4rem;
right: 1rem;
cursor: pointer;
flex: 1;
cursor: pointer;
font-family: ${fonts.Montserrat};
overflow: hidden;
justify-content: space-between;
`
// box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
export const StyledToastText = styled.div`
padding: 0.5rem 1rem;
line-height: 1.4;
`
export const StyledToastCloseBtn = styled.button`
border: none;
background-color: transparent;
margin: 0;
color: ${flat.dark.button};
font-weight: bold;
font-size: ${fontSizes.xl};
background: transparent;
outline: none;
padding: 0;
cursor: pointer;
opacity: 0.7;
transition: 0.3s ease;
align-self: flex-start;
display: inline-block;
position: absolute;
top: 4px;
right: 4px;
&:hover,
&:focus {
opacity: 1;
}
`
const progressBarAnimation = keyframes`
0% {
transform: scaleX(1);
}
100% {
transform: scaleX(0);
}
`
export const StyledProgressBar = styled.div`
position: absolute;
bottom: 0;
left: ${props => (props.rtl ? `initial` : 0)};
width: 100%;
height: 5px;
z-index: $rt-z-index;
opacity: 0.7;
background-color: rgba(255, 255, 255, 0.7);
animation: ${props => (props.animate ? `${progressBarAnimation} 1s linear` : '')};
background: ${props => (props.color ? `${flat.dark.button}` : `transparent`)};
right: ${props => (props.rtl ? 0 : `unset`)};
transform-orign: ${props => (props.rtl ? `right` : `left`)};
`
|
import authService from "../../services/authService.js";
import furnitureService from "../../services/furnitureService.js";
import { allMyFurniture } from "./myFurnitureTemplate.js";
async function getView(context) {
let userId = authService.getUserId();
let items = await furnitureService.getMyFurniture(userId);
let templateResult = allMyFurniture(items);
context.renderView(templateResult);
}
export default {
getView
}
|
import Vue from 'vue';
import upperCamelCase from 'uppercamelcase';
import objectPath from 'object-path';
import A1 from './a1';
console.log('Vue in a.js', Vue);
upperCamelCase('foo-bar');
console.log('A1 in a.js', A1, objectPath);
export default {
name: 'A'
};
|
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import { ConnectedRouter } from 'react-router-redux';
import Users from '../components/users/list.component';
import AddUser from '../components/users/add.component';
/** Shared Elements */
import Header from "../components/shared/header/header.component";
import Footer from "../components/shared/footer/footer.component";
class AppRouter extends React.Component {
render() {
return (
<ConnectedRouter history={this.props.history}>
<div>
<Header />
<Switch>
<Route exact path="/" component={Users} />
<Route exact path="/users/" component={Users} />
<Route exact path="/users/add" component={AddUser} />
<Route exact path="/users/add/:id" component={AddUser} />
</Switch>
<Footer />
</div>
</ConnectedRouter>
);
}
}
export default AppRouter;
|
import * as actions from './actions'
import * as mutations from './mutations'
const moduloUsuario = {
state: () => ({
usuario: null,
idListaCreada: null,
listas: [],
listaSeleccionada: null,
}),
mutations,
actions,
};
export default moduloUsuario;
|
(function () {
'use strict';
/**
* @ngdoc object
* @name bienenFuerDasVolk.controller:BienenFuerDasVolkCtrl
*
* @description
*
*/
angular
.module('bienenFuerDasVolk')
.controller('BienenFuerDasVolkCtrl', BienenFuerDasVolkCtrl);
function BienenFuerDasVolkCtrl() {
var vm = this;
vm.ctrlName = 'BienenFuerDasVolkCtrl';
}
}());
|
import React, { useState } from 'react'
import { makeStyles } from '@material-ui/core/styles'
import TextField from '@material-ui/core/TextField'
import Button from '@material-ui/core/Button'
function LoginForm () {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const handleSubmit = e => {
e.preventDefault()
console.log('handle submit triggered')
// if (!email || !password) return
// console.log(email + ', ' + password)
// setEmail('')
// setPassword('')
}
const useStyles = makeStyles(theme => ({
container: {
display: 'flex',
flexWrap: 'wrap'
},
TextField: {
margin: theme.spacing(1)
}
}))
const classes = useStyles()
return (
<form className={classes.container} onSubmit={handleSubmit} noValidate>
<TextField
id="email"
placeholder="NOP Email"
className={classes.TextField}
inputProps={{
'aria-label': 'email'
}}
required
autoFocus
value={email}
onChange={e => setEmail(e.target.value)}
/>
<TextField
id="password"
placeholder="Password"
className={classes.TextField}
inputProps={{
'aria-label': 'password'
}}
required
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
/>
<Button
type="submit"
>
Sign In
</Button>
</form>
)
}
export default LoginForm
|
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
});
module.exports = {
plugins: [
{
resolve: "gatsby-plugin-tidio-chat",
options: {
tidioKey: process.env.TIDIO_PUBLIC_KEY,
enableDuringDevelop: false,
},
},
],
};
|
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Layout from './Layout';
import Landing from './Landing';
import Capture from './Capture';
const Routes = (
<Route path="/" component={Layout}>
<IndexRoute component={Landing} />
<Route path="sign-up" component={Capture} />
</Route>
);
export default Routes;
|
import home from '../view/home.html'
const config = ($routeProvider) => {
$routeProvider.
when('/home', {
templateUrl: home,
controller: 'testCtrl'
})
}
config.$inject = ['$routeProvider']
export default config
|
// @desc This is the filter on Admin Order Component filtering completed, processing and pending orders
// @author Sylvia Onwukwe
import React from "react";
import Paginations from "../../components/Pagination/Pagination";
class Filter extends React.Component{
render (){
return (
<Paginations
pages={[
{ text: "Completed" },
{ text: "Processing" },
{ text: "Pending"}
]}
color="info"
/>
);
}
}
export default Filter;
|
const { Event} = require('../event/schema');
const { SpeakerInputType } = require('../speaker/schema');
const { GraphQLObjectType, GraphQLList } = require('graphql');
const Event = require('../../controller/eventController');
const mutation = new GraphQLObjectType({
name: 'EventMutation',
description: 'Mutations for event schema',
fields: {
addEvent: {
type: EventType,
args: {
title: {type: GraphQLString},
datetime: {type: GraphQLDateTime},
address: {type: GraphQLString},
description: {type: GraphQLString},
hostid: {type: GraphQLString},
category: {type: GraphQLInt},
types: {type: new GraphQLList(GraphQLString)},
posterlink: {type: GraphQLString},
booklink: {type: GraphQLString},
speakers: {type: new GraphQLList(SpeakerInputType)},
},
resolve: async (parent, args, context) => {
const event = await Event.addEvent(args, context.user);
return event;
}
},
removeEvent: {
type: EventType,
args: {
id: {type: GraphQLString},
},
resolve(parent, args){
return Event.removeEvent(args.id);
}
}
}
});
module.exports = mutation;
|
function capitaliseFirstLetter(str) {
return str[0].toUpperCase() + str.slice(1);
}
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
function log(str) {
Ti.API.log("Logging " + str);
}
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function undef(param) {
if ( typeof param === 'undefined')
return true;
else {
if (isBlank(param))
return true;
else
return false;
}
}
function notifyOkDialog(message, title) {
var diag = Ti.UI.createAlertDialog({
message : message,
ok : 'Okay',
title : title
})
return diag;
}
|
module.exports = {
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected.
// In this repo, were are using it to EXCLUDE the helper file __jestSharedSetup.js
collectCoverageFrom: [
'src/**/{!(__jestSharedSetup),}.(js|ts|tsx)',
],
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// This will be used to configure minimum threshold enforcement for coverage results.
coverageThreshold: {
global: {
branches: 74,
functions: 92,
lines: 83,
statements: 83,
},
},
// The paths to modules that run some code to configure or set up the testing environment before
// each test
setupFiles: [
'jest-canvas-mock',
],
// The test environment that will be used for testing
testEnvironment: 'jsdom',
setupFilesAfterEnv: [
'<rootDir>/src/__tests__/setup.js',
],
// Define what files are included as tests
testRegex: '.*\\/.+\\.test.(js|ts|tsx)$',
};
|
import React from 'react';
const NotFound = () =>{
return(
<h1>Whoops .This page does'nt exist</h1>
)
}
export default NotFound;
|
// Your code here
//var Person = function (age, name) {
// this._age = age;
// this._name = name;
//};
//Person.prototype.introduce = function () {
// return "My name is " + this._name + ". I am " + this._age + " years old.";
//};
//var Student = function (age, name, Class) {
// Person.apply(this, arguments);
// this._Class = Class;
//};
//Student.prototype.introduce = function () {
// return "I am a Student.I am at Class " + this._Class + ".";
function Person(age,name){
this._age=age;
this._name=name;
};
Person.prototype.introduce=function(){
return this._name+","+this._age;
}
function Student(age,name,Class){
Person.call(this,age,name);
this._Class=Class;
};
Student.prototype=Object.create(Person.prototype);
Student.prototype.constructor=Student;
Student.prototype.introduce=function(){
return "Class"+this._Class;
}
|
import React, { Component } from 'react';
import AppItem from './AppItem';
import { Settings } from '../services/Settings';
class AppList extends Component {
settings = new Settings();
constructor(props) {
super(props);
this.state = {
apps: []
}
this.loadAppList();
}
async loadAppList() {
const localAppList = await this.settings.getLocalAppList();
const remoteAppList = await this.settings.getRemoteAppList();
const repoBaseUrl = await this.settings.getRepoBaseUrl();
let appList = localAppList.map(app => ({
key: app.key,
name: app.name,
repoUrl: undefined,
localVersion: app.version,
remoteVersion: undefined
}))
remoteAppList.forEach(remoteApp => {
remoteApp.repoUrl = `${repoBaseUrl}${remoteApp.key}/releases/download/v${remoteApp.version}/${remoteApp.key}.zip`;
const localAppIndex = appList.findIndex(localApp => remoteApp.key === localApp.key);
if (localAppIndex > -1) {
appList[localAppIndex].remoteVersion = remoteApp.version;
appList[localAppIndex].repoUrl = remoteApp.repoUrl;
} else {
appList.push({
key: remoteApp.key,
name: remoteApp.name,
repoUrl: remoteApp.repoUrl,
localVersion: undefined,
remoteVersion: remoteApp.version
})
}
});
this.setState({
apps: appList
});
}
render() {
return (
<div>
<h2>Installed applications</h2>
{this.state.apps.map( app => (
<div key={app.name}>
<AppItem app={app}/>
</div>
))}
</div>
)
}
}
export default AppList;
|
// object inheritance
var Vehicle = function (name)
{
this.name = name;
this.nameUpper = name.toUpperCase();
// this.start= function()
// {
// return this.name+" is starting";
// }
}
Vehicle.prototype.start= function()
{
return this.name+" is starting";
}
/*
When new Vehicle() is called, JavaScript does four things:
1. It creates a new object.
2. It sets the constructor property of the object to Vehicle.
3. It sets up the object to delegate to Vehicle.prototype.
4. It calls Vehicle() function in the context of the new object.-- constructor invocation happens here
The result of new Vehicle() is this new object.
*/
var veh1 = new Vehicle('Small SUV');
console.log("the constructor:"+veh1.constructor);// the Vehicle function
console.log(veh1.constructor == Vehicle); // true
console.log(veh1 instanceof Vehicle); // true
console.dir(veh1.__proto__); // Vehicle.prototype
var veh2 = new Vehicle('Large SUV');
console.log(veh1.start());
console.log(veh2.start());
var Car = function(name)
{
Vehicle.call(this,name);
console.dir(this.__proto__);
console.log(this.start()+'==>>');
}
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.start = function()
{
return this.nameUpper+" Car is starting";
}
var car1 = new Car('Small');
console.log(car1 instanceof Vehicle)
console.log(car1.start());
var car2 = new Car('Huge');
console.log(car2 instanceof Vehicle)
console.log(car2.start());
console.log(car1.start());
console.log((new Vehicle("truck")).start());
var Maruti = function(model,name)
{
Car.call(this,name);
this.model = model;
}
Maruti.prototype=Object.create(Car.prototype);
Maruti.prototype.start = function()
{
return "Maruti with model "+this.model+" and name " +this.nameUpper+" Car is starting";
}
var dZire = new Maruti('Dzire',"swift");
console.log(dZire.start());
function inherits(ctor, superCtor) {
if (ctor === undefined || ctor === null)
throw new TypeError('The constructor to `inherits` must not be ' +
'null or undefined.');
if (superCtor === undefined || superCtor === null)
throw new TypeError('The super constructor to `inherits` must not ' +
'be null or undefined.');
if (superCtor.prototype === undefined)
throw new TypeError('The super constructor to `inherits` must ' +
'have a prototype.');
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
|
import { REQUEST_CARS, RECEIVE_CARS } from '../actions/cars'
const initialState = { items: [], isFetching: false }
const cars = (state = initialState, action) => {
switch (action.type) {
case REQUEST_CARS:
return Object.assign({}, state, {isFetching: true})
case RECEIVE_CARS:
return Object.assign({}, state, {
items: action.cars,
isFetching: false,
receivedAt: action.receivedAt
})
default:
return state
}
}
export default cars
|
import React from 'react';
import './App.css';
import Game from './Game';
export const CELL_VALUE = 'X';
export const getRandom = (max, min) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
class App extends React.Component {
render() {
return <Game />;
}
}
export default App;
|
const express = require('express')
const router = express.Router()
const authController = require('../controllers/auth')
const route = '/auth'
module.exports = (server) => {
router.post('/register', authController.register)
router.get('/login', authController.login)
router.get('/logout', authController.logout)
router.get('/me/:id', authController.me)
server.use(route, router)
}
|
import { Button } from "react-bootstrap";
import "./NewPollButton.css";
import { Plus } from "react-bootstrap-icons";
function NewPollButton(props) {
return (
<Button
className="btn-newpoll-position btn btn-success rounded-circle"
style={{ width: "50px", height: "50px", font: "2em sans-serif" }}
onClick={() => {
props.setShowModal(true)
}}
>
<Plus size="25px" className="iconnewpoll" />
</Button>
);
}
export default NewPollButton;
|
import * as THREE from 'three'
import Tools from './Tools'
import { ConvexBufferGeometry } from './thirdparty/ConvexGeometry'
/**
* This is the base class for `MorphologyPolyline` and `MorphologyPolycylinder`.
* It handles the common features, mainly related to soma creation
*/
class MorphologyShapeBase extends THREE.Object3D {
/**
* @constructor
* Builds a moprho as a polyline
* @param {Object} morpho - raw object that describes a morphology (usually straight from a JSON file)
* @param {object} options - the option object
* @param {Number} options.color - the color of the polyline.
* If provided, the whole neurone will be of the given color, if not provided,
* the axon will be green, the basal dendrite will be red and the apical dendrite will be green
*/
constructor(morpho, options) {
super()
this.userData.morphologyName = options.name
this._pointToTarget = null
this._morpho = morpho
// fetch the optional color
const color = Tools.getOption(options, 'color', null)
// simple color lookup, so that every section type is shown in a different color
this._sectionColors = {
axon: color || 0x1111ff,
basal_dendrite: color || 0xff1111,
apical_dendrite: color || 0xf442ad,
}
}
/**
* @private
* The method to build a soma mesh using the 'default' way, aka using simply the
* data from the soma.
* @return {THREE.Mesh} the soma mesh
*/
_buildSomaDefault() {
const soma = this._morpho.getSoma()
const somaPoints = soma.getPoints()
// case when soma is a single point
if (somaPoints.length === 1) {
const somaSphere = new THREE.Mesh(
new THREE.SphereGeometry(soma.getRadius(), 32, 32),
new THREE.MeshPhongMaterial({ color: 0x000000, transparent: true, opacity: 0.3 }),
)
somaSphere.position.set(somaPoints[0][0], somaPoints[0][1], somaPoints[0][2])
return somaSphere
// this is a 3-point soma, probably colinear
} if (somaPoints.length === 3) {
/*
let radius = soma.getRadius()
let mat = new THREE.MeshPhongMaterial( {color: 0x000000, transparent: true, opacity:0.3} )
let c1 = Tools.makeCylinder(
new THREE.Vector3(...somaPoints[0]),
new THREE.Vector3(...somaPoints[1]),
radius,
radius,
false,
mat
)
let c2 = Tools.makeCylinder(
new THREE.Vector3(...somaPoints[1]),
new THREE.Vector3(...somaPoints[2]),
radius,
radius,
false,
mat
)
let somaCyl = new THREE.Object3D()
somaCyl.add(c1)
somaCyl.add(c2)
return somaCyl
*/
const somaSphere = new THREE.Mesh(
new THREE.SphereGeometry(soma.getRadius(), 32, 32),
new THREE.MeshPhongMaterial({ color: 0x000000, transparent: true, opacity: 0.3 }),
)
somaSphere.position.set(somaPoints[0][0], somaPoints[0][1], somaPoints[0][2])
return somaSphere
// when soma is multiple points
} if (somaPoints.length > 1) {
// compute the average of the points
const center = soma.getCenter()
const centerV = new THREE.Vector3(center[0], center[1], center[2])
const geometry = new THREE.Geometry()
for (let i = 0; i < somaPoints.length; i += 1) {
geometry.vertices.push(
new THREE.Vector3(somaPoints[i][0], somaPoints[i][1], somaPoints[i][2]),
new THREE.Vector3(
somaPoints[(i + 1) % somaPoints.length][0],
somaPoints[(i + 1) % somaPoints.length][1],
somaPoints[(i + 1) % somaPoints.length][2],
),
centerV,
)
geometry.faces.push(new THREE.Face3(3 * i, 3 * i + 1, 3 * i + 2))
}
const somaMesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
color: 0x000000,
transparent: true,
opacity: 0.3,
side: THREE.DoubleSide,
}))
return somaMesh
}
console.warn('No soma defined')
return null
}
/**
* @private
* Here we build a soma convex polygon based on the 1st points of the orphan
* sections + the points available in the soma description
* @return {THREE.Mesh} the soma mesh
*/
_buildSomaFromOrphanSections() {
const somaPoints = this._morpho.getSoma().getPoints()
let somaMesh = null
try {
// getting all the 1st points of orphan sections
const somaPolygonPoints = this._morpho.getOrphanSections().map((s) => {
const allPoints = s.getPoints()
const firstOne = allPoints[1]
return new THREE.Vector3(...firstOne)
})
// adding the points of the soma (adds values mostly if we a soma polygon)
for (let i = 0; i < somaPoints.length; i += 1) {
somaPolygonPoints.push(new THREE.Vector3(...somaPoints[i]))
}
const geometry = new ConvexBufferGeometry(somaPolygonPoints)
const material = new THREE.MeshPhongMaterial({
color: 0x555555,
transparent: true,
opacity: 0.7,
side: THREE.DoubleSide,
})
somaMesh = new THREE.Mesh(geometry, material)
return somaMesh
} catch (e) {
console.warn('Attempted to build a soma from orphan section points but failed. Back to the regular version.')
return this._buildSomaDefault()
}
}
/**
* @private
* Builds the soma. The type of soma depends on the option
* @param {Object} options - The option object
* @param {String|null} options.somaMode - "default" to display only the soma data or "fromOrphanSections" to build a soma using the orphan sections
*/
_buildSoma(options) {
this._pointToTarget = this._morpho.getSoma().getCenter()
// can be 'default' or 'fromOrphanSections'
const buildMode = Tools.getOption(options, 'somaMode', null)
let somaMesh = null
if (buildMode === 'fromOrphanSections') {
somaMesh = this._buildSomaFromOrphanSections()
} else {
somaMesh = this._buildSomaDefault()
}
return somaMesh
}
/**
* Get the point to target when using the method lookAt. If the soma is valid,
* this will be the center of the soma. If no soma is valid, it will be the
* center of the box
* @return {Array} center with the shape [x: Number, y: Number, z: Number]
*/
getTargetPoint() {
if (this._pointToTarget) {
// rotate this because Allen needs it (just like the sections)
const lookat = new THREE.Vector3(this._pointToTarget[0], this._pointToTarget[1], this._pointToTarget[2])
lookat.applyAxisAngle(new THREE.Vector3(1, 0, 0), Math.PI)
lookat.applyAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI)
return lookat
}
const center = new THREE.Vector3()
this.box.getCenter(center)
return center
}
/**
* Get the morphology object tied to _this_ mesh
* @return {morphologycorejs.Morphology}
*/
getMorphology() {
return this._morpho
}
}
export default MorphologyShapeBase
|
var arr=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
var counts = {};
for(i in arr){
if(!counts.hasOwnProperty(arr[i])) counts[arr[i]]={item:arr[i],count:1};
else {
var c = counts[arr[i]].count;
counts[arr[i]]={item:arr[i],count:c+1};
}
}
console.log(counts);
var large = 0;
var elm = {};
for(i in counts){
if(counts[i].count>large) elm = counts[i];
}
console.log(elm);
|
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { Container, Ul, Li } from "./style";
import PostCard from "../../../postCard";
import NewPostButton from "./NewPostButton";
import PostModal from "../../../postModal";
import LoadingScreenCard from "../../../loadingScreens/postCard";
import NoDataFoundMessage from "../../NoDataFoundMessage";
import ViewAllButton from "../../util/ViewAllButton";
const index = ({ preview }) => {
const isAuthenticated = useSelector((state) => state.auth.isAuthenticated);
const user = useSelector((state) => state.auth.user);
const [posts, setPosts] = useState([]);
const [isLoading, setLoading] = useState(true);
let loadingCards = [];
for (let i = 0; i < 20; ++i) {
loadingCards.push(<LoadingScreenCard key={i} />);
}
useEffect(() => {
if (isAuthenticated) {
setPosts(preview ? user.posts.slice(0, 5) : user.posts);
setLoading(false);
}
}, [isAuthenticated, user]);
return (
<Container>
{isLoading && loadingCards}
{!isLoading && posts.length > 0 && (
<Ul preview={preview}>
<PostModal quickData={posts} />
{!preview && (
<Li>
<NewPostButton />
</Li>
)}
{posts.map((post, index) => {
return (
<Li key={index}>
<PostCard
key={index}
postData={post}
isManagementView={true}
directToPostPage={true}
/>
</Li>
);
})}
{preview && (
<Li>
<ViewAllButton link="/account?view=posts" />
</Li>
)}
</Ul>
)}
{!isLoading && posts.length === 0 && (
<NoDataFoundMessage
title={"Looks like you haven't created any posts yet."}
subtitle={"That's okay, click the button below to create a new post!"}
buttonText={"Create Post"}
link={"/createpost"}
/>
)}
</Container>
);
};
export default index;
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
Dimensions,
ScrollView,
} from 'react-native';
const TILE_SIZE = 20;
const BOARD_WIDTH = (Dimensions.get('window').width - 20) - (Dimensions.get('window').width % TILE_SIZE);
const BOARD_HEIGHT = (Dimensions.get('window').height - 60) - (Dimensions.get('window').height % TILE_SIZE);
class Tile extends Component {
constructor(props) {
super(props);
this.onTileChange = this.onTileChange.bind(this);
}
shouldComponentUpdate(nextProps) {
// Update component only if cell's value changed
return (this.props.value !== nextProps.value);
}
onTileChange () {
this.props.handleTileTouch(this.props.x, this.props.y);
}
render () {
let style = this.props.value ? styles.tileActive : styles.tileUnactive;
return (
<TouchableOpacity onPress={this.onTileChange}>
<View style={style}></View>
</TouchableOpacity>
);
}
}
class Row extends Component {
render () {
return (
<View style={styles.row}>
{
this.props.rowArr.map( (element, index) =>
<Tile
key={index}
value={this.props.rowArr[index]}
x={this.props.x}
y={index}
handleTileTouch={this.props.handleTileTouch}
/>
)
}
</View>
);
}
}
class Board extends Component {
render() {
return (
<ScrollView maximumZoomScale={3} minimumZoomScale={1}>
<View style = {styles.board}>
{
this.props.grid.map((element, index) =>
<Row
rowArr={element}
key={index}
x={index}
handleTileTouch={this.props.handleTileTouch}
/>)
}
</View>
</ScrollView>
);
}
}
const Button = (props) => (
<TouchableOpacity onPress = {props.onPress}>
<View style={props.style}>
<Text style={props.textStyle}> {props.text} </Text>
</View>
</TouchableOpacity>
);
class ToolsBar extends Component {
render() {
return (
<View style = {styles.toolsBar}>
<Button onPress={this.props.handleReset} style={styles.tool} textStyle={styles.toolText} text={'Reset'} />
<Button onPress={this.props.handleRandom} style={styles.tool} textStyle={styles.toolText} text={'Random'} />
<Button onPress={this.props.handlePause} style={styles.tool} textStyle={styles.toolText} text={'Pause'} />
<Button onPress={this.props.handleRun} style={styles.tool} textStyle={styles.toolText} text={'Play'} />
</View>
)
}
}
export default class Conways extends Component {
constructor(props) {
super(props);
this.state = {
grid: this.getEmptyGrid(),
};
this.handleTileTouch = this.handleTileTouch.bind(this);
this.handleReset = this.handleReset.bind(this);
this.handleRun = this.handleRun.bind(this);
this.handlePause = this.handlePause.bind(this);
this.handleRandom = this.handleRandom.bind(this);
this.getEmptyGrid = this.getEmptyGrid.bind(this);
}
getEmptyGrid() {
let grid = [];
for (let x = 0; x < BOARD_HEIGHT / TILE_SIZE; x++) {
grid[x] = [];
for (let y = 0; y < BOARD_WIDTH / TILE_SIZE; y++) {
grid[x][y] = false;
}
}
return grid;
}
getNextGrid() {
let newArray = [];
for (let i = 0; i < BOARD_HEIGHT / TILE_SIZE; i++) {
let row = [];
for (let j = 0; j < BOARD_WIDTH / TILE_SIZE; j++) {
row.push(this.willCellSurvive(this.state.grid, i, j) ? 1 : 0);
}
newArray.push(row);
}
return newArray;
}
willCellSurvive(grid, x, y) {
let neighbors = 0;
/**
* count living cells arond the targeted cell
*/
if (grid[mod(x + 1, BOARD_HEIGHT / TILE_SIZE)][y]) neighbors++;
if (grid[mod(x + 1, BOARD_HEIGHT / TILE_SIZE)][mod(y + 1, BOARD_WIDTH / TILE_SIZE)]) neighbors++;
if (grid[x][mod(y + 1, BOARD_WIDTH / TILE_SIZE)]) neighbors++;
if (grid[x][mod(y - 1, BOARD_WIDTH / TILE_SIZE)]) neighbors++;
if (grid[mod(x + 1, BOARD_HEIGHT / TILE_SIZE)][mod(y - 1, BOARD_WIDTH / TILE_SIZE)]) neighbors++;
if (grid[mod(x - 1, BOARD_HEIGHT / TILE_SIZE)][y]) neighbors++;
if (grid[mod(x - 1, BOARD_HEIGHT / TILE_SIZE)][mod(y - 1, BOARD_WIDTH / TILE_SIZE)]) neighbors++;
if (grid[mod(x - 1, BOARD_HEIGHT / TILE_SIZE)][mod(y + 1, BOARD_WIDTH / TILE_SIZE)]) neighbors++;
return (grid[x][y] && neighbors == 2 || neighbors == 3);
function mod(x, m) {
m = Math.abs(m);
return (x % m + m) % m;
}
}
/*----------------------------HANDLERS--------------------------------------*/
handleTileTouch(x, y) {
let newArray = this.state.grid;
newArray[x][y] = !newArray[x][y];
this.setState({grid: newArray});
}
handleReset() {
this.setState({ grid: this.getEmptyGrid() });
}
handleRandom() {
let newArray = [];
for (let x = 0; x < BOARD_HEIGHT / TILE_SIZE; x++) {
newArray[x] = [];
for (let y = 0; y < BOARD_WIDTH / TILE_SIZE; y++) {
newArray[x][y] = (Math.random() >= 0.80);
}
}
this.setState({ grid: newArray });
}
handleRun() {
if (!this.timer) {
this.timer = setInterval(() => this.setState({grid: this.getNextGrid()}), 50);
}
}
handlePause() {
clearInterval(this.timer);
this.timer = null;
}
render() {
return (
<View style={styles.container}>
<Board
grid={this.state.grid}
handleTileTouch={this.handleTileTouch}
/>
<ToolsBar
grid={this.state.grid}
handleReset={this.handleReset}
handleRandom={this.handleRandom}
handleRun={this.handleRun}
handlePause={this.handlePause}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
board: {
marginTop: 20,
backgroundColor: '#333333',
width: BOARD_WIDTH,
height: BOARD_HEIGHT,
},
row: {
flexDirection: 'row',
width: BOARD_WIDTH,
height: BOARD_HEIGHT / (BOARD_HEIGHT / TILE_SIZE),
},
tileUnactive: {
backgroundColor: '#222222',
borderColor: "black",
borderWidth: 1,
width: TILE_SIZE,
height: TILE_SIZE,
},
tileActive: {
backgroundColor: 'white',
borderColor: "black",
borderWidth: 1,
width: TILE_SIZE,
height: TILE_SIZE,
},
toolsBar: {
justifyContent: 'space-around',
alignItems: 'center',
flexDirection: 'row',
width: BOARD_WIDTH,
height: 30,
marginTop: 5,
},
tool: {
justifyContent: 'center',
alignItems: 'center',
height: 25,
width: 60,
backgroundColor: '#222222',
},
toolText: {
color: 'white',
},
});
AppRegistry.registerComponent('Conways', () => Conways);
|
$(document).ready( function() {
$("#iSearchSecret").on('click', function(){
var recherche = $(this).val();
$('tbody#listeSecrets').html("");
$.ajax({
url: '../SM-home.php?action=R',
type: 'POST',
data: $.param({'Search_Secrets': recherche}),
success: function(reponse){
if(reponse){
$('tbody#listeSecrets').html(reponse);
var total = $('tbody#listeSecrets tr').attr('data-total');
$('#total').text( total );
}
},
error: function(reponse) {
alert('Erreur sur serveur : ' + reponse['responseText']);
}
});
});
$("#iSaveUseServer").click(function(){
var UseSecretServer = $('#Use_SecretServer').val();
$.ajax({
url: '../SM-preferences.php?action=SUX',
type: 'POST',
data: $.param({'UseSecretServer': UseSecretServer}),
dataType: 'json',
success: function(reponse){
if ( reponse['Status'] == 'success' || reponse['Status'] == 'error' ) {
showInfoMessage( reponse['Status'], reponse['Message'] ); // SecretManager.js
} else {
alert('Erreur sur serveur : ' + reponse);
}
},
error: function(reponse) {
alert('Erreur sur serveur : ' + reponse['responseText']);
}
});
});
$("#iSaveKeysProperties").click(function(){
var Operator_Key_Size = $('#Operator_Key_Size').val();
var Operator_Key_Complexity = $('#Operator_Key_Complexity').val();
var Mother_Key_Size = $('#Mother_Key_Size').val();
var Mother_Key_Complexity = $('#Mother_Key_Complexity').val();
$.ajax({
url: '../SM-preferences.php?action=SKX',
type: 'POST',
data: $.param({
'Operator_Key_Size': Operator_Key_Size,
'Operator_Key_Complexity' : Operator_Key_Complexity,
'Mother_Key_Size' : Mother_Key_Size,
'Mother_Key_Complexity' : Mother_Key_Complexity
}),
dataType: 'json',
success: function(reponse){
if ( reponse['Status'] == 'success' || reponse['Status'] == 'error' ) {
showInfoMessage( reponse['Status'], reponse['Message'] ); // SecretManager.js
} else {
alert('Erreur sur serveur : ' + reponse);
}
},
error: function(reponse) {
alert('Erreur interne sur serveur : ' + reponse['responseText']);
}
});
});
});
function setSecret( secret_id, action ) {
var action = action || '';
if ( action == 'D' ) {
var Delete_Mode = ' disabled';
} else {
var Delete_Mode = '';
}
cancel();
$.ajax({
url: '../SM-home.php?action=AJAX_LV',
type: 'POST',
data: $.param({'scr_id': secret_id}),
dataType: 'json', // le résultat est transmit dans un objet JSON
success: function(reponse){
if ( $('#' + secret_id + ' td p').length == 0 ) {
var group, group_id, type, type_id, environment, environment_id, application,
host, user, expiration, comment, right, dirname, L_Edit, L_Delete, L_View;
$('tr#' + secret_id + ' td').each( function( index ) {
if ( index == 0 ) {
group_id = $(this).attr('data-id');
$.each(reponse['listGroups'], function(attribut, valeur) {
if ( group_id == valeur['sgr_id'] ) {
var Selected = ' selected';
} else {
var Selected = '';
}
group = group + '<option value=' + valeur['sgr_id'] + Selected +
'>' + valeur['sgr_label'] + '</option>';
});
group_o = $(this).text();
} else if ( index == 1 ) {
type_id = $(this).attr('data-id');
$.each(reponse['listTypes'], function(attribut, valeur) {
if ( type_id == valeur['stp_id'] ) {
var Selected = ' selected';
} else {
var Selected = '';
}
type = type + '<option value=' + valeur['stp_id'] + Selected +
'>' + valeur['stp_name'] + '</option>';
});
type_o = $(this).text();
} else if ( index == 2 ) {
environment_id = $(this).attr('data-id');
$.each(reponse['listEnvironments'], function(attribut, valeur) {
if ( environment_id == valeur['env_id'] ) {
var Selected = ' selected';
} else {
var Selected = '';
}
environment = environment + '<option value=' + valeur['env_id'] +
Selected + '>' + valeur['env_name'] + '</option>';
});
environment_o = $(this).text();
} else if ( index == 3 ) {
application = $(this).text();
} else if ( index == 4 ) {
host = $(this).text();
} else if ( index == 5 ) {
user = $(this).text();
} else if ( index == 6 ) {
expiration = $(this).text();
expiration_color = $(this).attr('class');
} else if ( index == 7 ) {
comment = $(this).text();
}
} );
var currentClass = $('tr#' + secret_id).attr('class');
currentClass = currentClass.replace("surline", "");
var L_Cancel = $('tr#' + secret_id).attr('data-cancel');
var L_Modify = $('tr#' + secret_id).attr('data-modify');
var L_Delete = $('tr#' + secret_id).attr('data-delete');
if ( reponse['Password'] == null ) {
var password = '*********';
} else {
var password = reponse['Password'];
}
if ( reponse['alert'] == true ) {
var alert = 'checked';
} else {
var alert = '';
}
var newOcc = '<tr id="MOD_' + secret_id + '" class="' + currentClass + '" style="cursor: pointer;">' +
'<td colspan="9" style="margin:0;padding:0;border:2px solid #568EB6;">' +
'<div id="modification-zone">' +
'<label for="'+'group_'+secret_id+'">' + reponse['L_Group'] + '</label>' +
'<select id="'+'group_'+secret_id+'" class="input-xlarge"' + Delete_Mode + '>' +
group +
'</select>' +
'<label for="'+'type_'+secret_id+'">' + reponse['L_Type'] + '</label>' +
'<select id="'+'type_'+secret_id+'" class="input-medium"' + Delete_Mode + '>' +
type +
'</select>' +
'<label for="'+'environment_'+secret_id+'">' + reponse['L_Environment'] + '</label>' +
'<select id="'+'environment_'+secret_id+'"' + ' class="input-medium"' + Delete_Mode + '>' +
environment +
'</select><br/>' +
'<label for="'+'application_'+secret_id+'">' + reponse['L_Application'] + '</label>' +
'<input id="'+'application_'+secret_id+'" type="text" value="' + application +
'" class="input-medium"' + Delete_Mode + '>' +
'<label for="'+'host_'+secret_id+'">' + reponse['L_Host'] + '</label>' +
'<input id="'+'host_'+secret_id+'" type="text" value="' + host + '" class="input-medium"' +
Delete_Mode + '>' +
'<label for="'+'user_'+secret_id+'">' + reponse['L_User'] + '</label>' +
'<input id="'+'user_'+secret_id+'" type="text" value="' + user + '" class="input-medium"' +
Delete_Mode + '>' +
'<label for="'+'secret_'+secret_id+'">' + reponse['L_Password'] + '</label>';
if ( action == 'D' ) {
password = '************';
}
newOcc = newOcc + '<input id="'+'secret_'+secret_id+'" type="text" value="' + password +
'" class="input-medium"' + Delete_Mode + '><br/>' +
'<label for="'+'alert_'+secret_id+'">' + reponse['L_Alert'] + '</label>' +
'<input id="'+'alert_'+secret_id+'" type="checkbox" ' + alert + Delete_Mode + '>' +
'<label for="'+'expiration_'+secret_id+'">' + reponse['L_Expiration_Date'] + '</label>' +
'<input id="'+'expiration_'+secret_id+'" type="text" value="' + expiration + '" class="input-medium"' +
Delete_Mode + '>' +
'<label for="'+'comment_'+secret_id+'">' + reponse['L_Comment'] + '</label>' +
'<input id="'+'comment_'+secret_id+'" type="text" value="' + comment + '" class="input-xxlarge"' +
Delete_Mode + '>' +
'</div>' +
'<p style="margin-top: 6px;margin-bottom: 6px;padding:0">' +
'<span class="div-left"><a class="button" href="javascript:cancel();">' + L_Cancel + '</a></span>';
if ( action == 'D' ) {
newOcc = newOcc + '<span class="div-right"><a class="button" href="javascript:remove('+secret_id+')">' +
L_Delete + '</a></span>';
} else {
newOcc = newOcc + '<span class="div-right"><a class="button" href="javascript:save('+secret_id+')">' +
L_Modify + '</a></span>';
}
newOcc = newOcc + '</p>' +
'<p> </p>' +
'</td>' +
'</tr>';
$('tr#' + secret_id).hide();
$(newOcc).insertAfter('tr#' + secret_id);
}
},
error: function(reponse) {
alert('Erreur sur serveur : ' + reponse['responseText']);
}
});
}
function cancel() {
$('tbody#listeSecrets tr td div').each( function() {
var currentId = $(this).parent().parent().attr('id');
$('#' + currentId).remove();
var Tmp = currentId.split('_');
$('#'+Tmp[1]).show();
} );
}
function save( secret_id ) {
var sgr_id = $('#group_'+secret_id).val();
var stp_id = $('#type_'+secret_id).val();
var env_id = $('#environment_'+secret_id).val();
var scr_host = $('#host_'+secret_id).val();
var scr_user = $('#user_'+secret_id).val();
var scr_password = $('#secret_'+secret_id).val();
var scr_comment = $('#comment_'+secret_id).val();
var scr_alert = $('#alert_'+secret_id).is(':checked');
var scr_application = $('#application_'+secret_id).val();
var scr_expiration_date = $('#expiration_'+secret_id).val();
if ( scr_alert == true ) {
scr_alert = 1;
} else {
scr_alert = 0;
}
$.ajax({
url: '../SM-home.php?action=AJAX_S',
type: 'POST',
data: $.param({
'scr_id': secret_id,
'sgr_id' : sgr_id,
'stp_id' : stp_id,
'scr_host' : scr_host,
'scr_user' : scr_user,
'scr_password' : scr_password,
'scr_comment' : scr_comment,
'scr_alert' : scr_alert,
'env_id' : env_id,
'scr_application' : scr_application,
'scr_expiration_date' : scr_expiration_date
}),
dataType: 'json', // le résultat est transmit dans un objet JSON
success: function(reponse) {
showInfoMessage( reponse['status'], reponse['message'] ); // SecretManager.js
if ( reponse['status'] == 'success' ) {
$.ajax({
url: '../SM-home.php?action=AJAX_R',
type: 'POST',
success: function(reponse){
$('tbody#listeSecrets').html(reponse);
},
error: function(reponse) {
alert('Erreur sur serveur : ' + reponse['responseText']);
}
});
}
},
error: function(reponse) {
alert('Erreur sur serveur : ' + reponse['responseText']);
}
});
}
function remove( secret_id ) {
$.ajax({
url: '../SM-home.php?action=AJAX_D',
type: 'POST',
data: $.param({
'scr_id': secret_id
}),
dataType: 'json', // le résultat est transmit dans un objet JSON
success: function(reponse) {
showInfoMessage( reponse['status'], reponse['message'] ); // SecretManager.js
if ( reponse['status'] == 'success' ) {
$('#' + secret_id ).remove();
$('#MOD_' + secret_id ).remove();
}
},
error: function(reponse) {
alert('Erreur sur serveur : ' + reponse['responseText']);
}
});
}
|
import withSession from "plugins/next-session";
const ApiSession = async (req, res) => {
let user = req.session.get("user");
// console.log(user);
return user ? res.json({ loggedIn: true, ...user }) : res.json({ loggedIn: false });
};
export default withSession(ApiSession);
|
import React from 'react';
import ItemCmt from "@/components/itemCmt";
//创建评论组件
class ItemList extends React.Component{
constructor(){
super();
this.state = {
itemList:[
{id:1,name:"zhangsan",content:"一楼"},
{id:2,name:"lisi",content:"沙发"},
{id:3,name:"wangwu",content:"板凳"}
]
};
}
render(){
return <div>
<h1 style={{color:"red",textAlign:"center",fontWeight:200}}>这是评论列表组件</h1>
{this.state.itemList.map(item=><ItemCmt key={item.id} {...item}></ItemCmt>)}
{/*{this.state.itemList.map(item=>(<div key={item.id}><h1>评论人:{item.name}</h1><h3>评论内容:{item.content}</h3></div>))} */}
</div>
}
}
export default ItemList
|
/*
* deepspeechWrapper.js by Aaron Becker
* Manages real-time speech recognition for CarOS using Mozilla's DeepSpeech recognition engine
*
* Dedicated to Marc Perkel
*
* Copyright (C) 2018, Aaron Becker <aaron.becker.developer@gmail.com>
*
* I know that I could have made a stab at implementing this myself, but oh well lol
*/
const Fs = require('fs');
const mic = require('mic');
const Sox = require('sox-stream');
const Ds = require('deepspeech');
const path = require('path');
const argparse = require('argparse');
const MemoryStream = require('memory-stream');
function totalTime(hrtimeValue) {
return (hrtimeValue[0] + hrtimeValue[1] / 1000000000).toPrecision(4);
}
const deepspeechWrapper = {
debugMode: false,
model: {},
audio_max_sample_length: 30000, //time (in ms) to sample audio from the microphone
neuralConstants: {
// These constants control the beam search decoder
// Beam width used in the CTC decoder when building candidate transcriptions
beam_width: 500,
// The alpha hyperparameter of the CTC decoder. Language Model weight
lm_weight: 1.50,
// Valid word insertion weight. This is used to lessen the word insertion penalty
// when the inserted word is part of the vocabulary
valid_word_count_weight: 2.10,
// These constants are tied to the shape of the graph used (changing them changes
// the geometry of the first layer), so make sure you use the same constants that
// were used during training
// Number of MFCC features to use
n_features: 26,
// Size of the context window used for producing timesteps in the input vector
n_context: 9
},
init: (neuralSettings) => {
return new Promise( (resolve, reject) => {
if (deepspeechWrapper.debugMode) {
console.log("Initializing deepspeech; versions");
Ds.printVersions();
}
if (!neuralSettings) {
return reject("neuralSettings undefined in recognition network init");
}
let nsR = neuralSettings.recognition;
if (!nsR || !nsR.triePath || !nsR.dataBasePath || !nsR.LMpath || !nsR.modelPath || !nsR.alphabetPath) {
return reject("neuralSettings is missing an essential setting for network init");
}
let bp = nsR.dataBasePath;
let triePath = path.join(bp, nsR.triePath);
let LMpath = path.join(bp, nsR.LMpath);
let modelPath = path.join(bp, nsR.modelPath);
let alphabetPath = path.join(bp, nsR.alphabetPath);
if (deepspeechWrapper.debugMode) {
console.log("model pathing: alphabet@%s, model@%s, LM@%s trie@%s", alphabetPath, modelPath, LMpath, triePath);
}
//load model
if (deepspeechWrapper.debugMode) {
console.log('Loading model from file %s', nsR.modelPath);
}
const model_load_start = process.hrtime();
var model = new Ds.Model(modelPath, deepspeechWrapper.neuralConstants.n_features, deepspeechWrapper.neuralConstants.n_context, alphabetPath, deepspeechWrapper.neuralConstants.beam_width);
const model_load_end = process.hrtime(model_load_start);
console.log('Loaded model in %ds.', totalTime(model_load_end));
if (deepspeechWrapper.debugMode) {
console.log('Loading language model from files %s %s', LMpath, triePath);
}
const lm_load_start = process.hrtime();
model.enableDecoderWithLM(alphabetPath, LMpath, triePath, deepspeechWrapper.neuralConstants.lm_weight, deepspeechWrapper.neuralConstants.valid_word_count_weight);
const lm_load_end = process.hrtime(lm_load_start);
console.log('Loaded language model in %ds.', totalTime(lm_load_end));
deepspeechWrapper.model = model; //set var
var micInstance = mic({
sampleRate: 16000,
channels: 1,
debug: deepspeechWrapper.debugMode,
fileType: "wav",
bits: 16,
encoding: 'signed-integer',
endian: 'little',
compression: 0.0,
exitOnSilence: 6
});
var micInputStream = micInstance.getAudioStream();
deepspeechWrapper.micInstance = micInstance;
deepspeechWrapper.micInputStream = micInputStream;
return resolve(); //resolve
})
},
runInference: audioBuffer => {
return new Promise( (resolve, reject) => {
try {
if (deepspeechWrapper.debugMode) {
console.log('Running inference.');
}
const audioLength = (audioBuffer.length / 2) * ( 1 / 16000); //in seconds
// We take half of the buffer_size because buffer is a char* while
// LocalDsSTT() expected a short*
const inference_start = process.hrtime();
let inference = String(deepspeechWrapper.model.stt(audioBuffer.slice(0, audioBuffer.length / 2), 16000));
const inference_stop = process.hrtime(inference_start);
if (deepspeechWrapper.debugMode) {
console.log('Inference took %ds for %ds audio file.', totalTime(inference_stop), audioLength.toPrecision(4));
}
return resolve(inference);
} catch (e) {
return reject(e);
}
})
},
takeAudioSample: ms => {
if (!ms) {
ms = deepspeechWrapper.audio_max_sample_length;
}
return new Promise( (resolve, reject) => {
var audioStream = new MemoryStream(); //memory stream of audio coming in from microphone
var transform = Sox({ //transform stream to make data conistent in terms of formatting
global: {
'no-dither': true,
},
output: {
bits: 16,
rate: 16000,
channels: 1,
encoding: 'signed-integer',
endian: 'little',
compression: 0.0,
type: 'raw'
}
});
deepspeechWrapper.micInputStream.pipe(transform).pipe(audioStream); //pipe mic through transform stream and then to audio stream
deepspeechWrapper.micInstance.start(); //start recording
setTimeout( () => {
deepspeechWrapper.micInstance.stop();
},ms);
if (deepspeechWrapper.debugMode) {
console.log("stopping recording in %dms", ms);
}
audioStream.on('finish', () => {
if (deepspeechWrapper.debugMode) {
console.log("Recording audio sample finished; resolving");
}
deepspeechWrapper.micInputStream.unpipe(transform);
//transform.unpipe(audioStream);
audioBuffer = audioStream.toBuffer();
return resolve(audioBuffer);
});
})
},
loadAudioFile: fileName => {
return new Promise( (resolve, reject) => {
if (!fileName) {
return reject("FileName not defined");
}
try {
const buffer = Fs.readFileSync(fileName);
} catch(e) {
return reject("Error reading audio file: "+e);
}
function bufferToStream(buffer) {
var stream = new Duplex();
stream.push(buffer);
stream.push(null);
return stream;
}
var audioStream = new MemoryStream();
bufferToStream(buffer).
pipe(Sox({
global: {
'no-dither': true,
},
output: {
bits: 16,
rate: 16000,
channels: 1,
encoding: 'signed-integer',
endian: 'little',
compression: 0.0,
type: 'raw'
}
})).
pipe(audioStream);
audioStream.on('finish', () => {
audioBuffer = audioStream.toBuffer();
return resolve(audioBuffer);
});
})
}
}
module.exports = deepspeechWrapper;
|
var Sites, imgurAlbum, basicMatch, stripUrl, getUrls;
var urlArray = [];
Sites = {};
imgurAlbum = {
isAlbum: null,
id: null,
index: null,
cached: {},
images: function() {
if (this.id && this.isAlbum)
return this.cached[id].images;
},
captions: function() {
if (this.id && this.isAlbum)
return this.cached[id].captions;
},
getAlbum: function(id) {
if (!imgurAlbum.cached[id]) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.imgur.com/2/album/' + id.replace(/#.*/, '') + '.json', false);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var images = JSON.parse(xhr.responseText).album.images;
this.cached[id] = {};
this.cached[id].index = 0;
this.cached[id].images = [];
this.cached[id].captions = [];
for (var i = 0; i < images.length; i++) {
this.cached[id].images.push(images[i].links.original);
this.cached[id].captions.push(images[i].image.caption.trim());
}
}
}.bind(this);
xhr.send();
}
if (!this.cached[id]) {
return false;
}
this.id = id;
this.isAlbum = true;
imageZoom.albumIndex.innerText = this.cached[id].index + 1 + '/' + this.cached[id].images.length;
imageZoom.caption.innerText = this.cached[this.id].captions[this.cached[this.id].index];
if (imageZoom.caption.innerText.trim() !== '') {
imageZoom.caption.style.display = 'block';
}
return this.cached[id].images[this.cached[id].index];
},
getImage: function(next) {
var albumLength = this.cached[this.id].images.length;
var index = this.cached[this.id].index;
if (this.cached[this.id].images.length > 1) {
if (next) {
this.cached[this.id].index = (index + 1 < albumLength) ? index + 1 : 0;
} else {
this.cached[this.id].index = (index - 1 < 0) ? albumLength - 1 : index - 1;
}
imageZoom.albumIndex.innerText = this.cached[this.id].index + 1 + '/' + albumLength;
var img = new Image();
img.src = this.cached[this.id].images[this.cached[this.id].index];
if (this.isAlbum) {
imageZoom.caption.innerText = this.cached[this.id].captions[this.cached[this.id].index];
imageZoom.caption.style.display = 'block';
}
if (imageZoom.caption.innerHTML === '') {
imageZoom.caption.innerHTML = '';
imageZoom.caption.style.display = 'none';
}
imageZoom.appendImage(img.src, true);
}
}
};
basicMatch = function(url) {
return (/\.(png|jpeg|jpg|svg|gif|tif|tiff|bmp)((:large|((\\?[^?])+))$)?/i).test(url);
};
stripUrl = function(url) {
if (!url) {
return;
}
url = url.replace(/^http(s)?:\/\//, '');
url = '.' + url.replace(/\/.*/, '');
url = url.replace(/.*\.(([^\.]+)\.([^\.]+)$)/, '$1');
return url;
};
getUrls = function(elems) {
if (urlArray.length) {
return urlArray;
}
for (var i = 0, l = elems.length; i < l; i++) {
if (elems[i] && elems[i].href) {
urlArray.push(elems[i].href);
}
}
return urlArray;
};
Sites.github = function(elem, callback) {
var url = elem.src;
if (!url || !/avatars/.test(url) || !/githubusercontent\.com/.test(stripUrl(url))) {
return;
}
callback(url.replace(/\?.*/, ''));
};
Sites.gravatar = function(elem, callback) {
var url = elem.src;
if (!url || !/gravatar\.com/.test(stripUrl(url)) || !basicMatch(url)) {
return;
}
callback(url);
};
Sites.twitter = function(elem, callback) {
var img;
if (elem.className === 'media-overlay' && elem.previousElementSibling.src) {
img = elem.previousElementSibling.src;
} else if (/twimg.*_(normal|bigger)/.test(elem.src)) {
img = elem.src.replace(/(twimg.*)_(normal|bigger)/, '$1');
} else if (/twimg/.test(stripUrl(elem.src))) {
img = elem.src.replace(/:thumb/, '') + ':large';
} else if (elem.firstChild && /twimg/.test(elem.firstChild.src)) {
img = elem.firstChild.src + ':large';
} else if (elem.parentNode && /is-preview/.test(elem.parentNode.className)) {
img = elem.src;
}
if (img) {
callback(img);
}
};
Sites.livememe = function(elem, callback) {
var base = /livememe\.com/i;
if (base.test(stripUrl(elem.href)) || (elem.parentNode && base.test(stripUrl(elem.parentNode.href)))) {
base = /[a-zA-Z0-9]{7}/;
if (elem.href && base.test(elem.href)) {
callback(elem.href + '.jpg');
} else if (elem.parentNode.href && base.test(elem.parentNode.href)) {
callback(elem.parentNode.href + '.jpg');
}
}
};
Sites.imgur = function(elem, callback) {
getUrls([elem, elem.parentNode]).forEach(function(url) {
if (!/\/random/.test(url) && /imgur\.com/i.test(stripUrl(url))) {
imgurAlbum.isAlbum = false;
if (basicMatch(url)) {
return callback(url);
}
if (/\/a\//.test(url)) {
return callback(imgurAlbum.getAlbum(url.replace(/.*\/a\//, '')));
}
if (/\/gallery\/(([a-zA-Z0-9]){7})/.test(url)) {
return callback(url.replace('/gallery/', '/') + '.jpg');
}
if (/\/gallery\//.test(url)) {
return callback(imgurAlbum.getAlbum(url.replace(/.*gallery/, '')));
}
var suffix = url.replace(new RegExp('.*' + stripUrl(url) + '(\/)?', 'i'), '');
if (suffix.length === 7) {
return callback(url + '.jpg');
}
}
});
};
Sites.wikimedia = function(elem, callback) {
var url = elem.src;
if (/(wikipedia|wikimedia)\.org/i.test(stripUrl(url)) && !/\.ogv|\.ogg/.test(url) && basicMatch(url)) {
url = url.replace(/\/thumb/, '');
if (/.*\.(png|jpg|jpeg|gif|svg|tif).*\.(png|jpg|jpeg|gif|svg|tif)/i.test(url)) {
url = url.replace(/\/([^\/]+)$/, '');
}
callback(url);
}
};
Sites.facebook = function(elem, callback) {
if (!/facebook\.com/.test(document.URL) || /ContentWrapper/.test(elem.className) || /(fbexternal|_b\.([a-zA-Z]+)$)/.test(elem.src))
return false;
function trimUrl(url) {
if (url)
return url.replace(/\/[tc][0-9]+\.[^\/]+/g, '').replace(/\/[sp][0-9]+x[0-9]+\//, '/').replace(/_[a-z](\.[a-z]+$)/, '_o$1').replace(/\/[a-z]\//, '/');
}
if (/ImageContainer/.test(elem.className) && elem.firstChild && elem.firstChild.src)
callback(trimUrl(elem.firstChild.src));
else if (elem.nodeName === 'I' && elem.style.backgroundImage)
callback(trimUrl(elem.style.backgroundImage.replace(/^url\(/, '').replace(/\)$/, '')));
else {
var e = elem.firstChild;
if (e && e.firstChild && e.firstChild.src)
callback(trimUrl(e.firstChild.src));
else callback(trimUrl(elem.src));
}
};
Sites.deviantart = function(elem, callback) {
getUrls([elem, elem.parentNode]).forEach(function(url) {
if (/deviantart\.(com|net)/i.test(url)) {
if (/\/fs([0-9]+)\/[a-zA-Z]\//.test(url)) {
callback(url);
} else if (/\/art\//i.test(url)) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://backend.deviantart.com/oembed?url=' + url);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var parsed = JSON.parse(xhr.responseText);
return callback(parsed.url);
}
};
xhr.send();
}
}
});
};
Sites.googleUserContent = function(elem, callback) {
if (!/googleusercontent\.com/.test(stripUrl(elem.src)) || !basicMatch(elem.src)) {
return;
}
function trimUrl(url) {
return url.replace(/\/[a-z][0-9]([^\/]+)(\/([^\/]+)\.(jpg|svg|jpeg|png|gif|tif)$)/i, '/s0$2');
}
callback(trimUrl(elem.src));
};
Sites.normal = function(elem, callback) {
getUrls([elem, elem.parentNode, elem.parentNode.parentNode]).forEach(function(url) {
if (basicMatch(url)) {
return callback(url.replace(/.*url=/, '').replace(/.*moapi\.net\//, ''));
}
});
};
Sites.gfycat = function(elem, callback) {
function getGfySource(url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
imageZoom.isVideo = true;
imageZoom.videoSource.type = 'video/webm';
callback(xhr.responseText.match(/source id=["']webmsource["'] src=["']([^"']+)["']/i)[0].replace(/^.*src=["']/, '').replace(/["']$/, ''), xhr.responseText.match(/poster=["']([^["']+)["']/i)[0].replace(/^.*=["']/, '').replace(/["']$/, ''));
}
};
xhr.send();
}
getUrls([elem, elem.parentNode]).forEach(function(url) {
if (!/\.gif$/.test(url) && /gfycat\.com/.test(stripUrl(url))) {
getGfySource(url.replace(/[^a-zA-Z_-]+$/, ''));
if (imageZoom.isVideo) {
return;
}
}
});
};
Sites.video = function(elem, callback) {
getUrls([elem, elem.parentNode]).forEach(function(url) {
if (/\.webm(\?([^?]+))?$/.test(url)) {
imageZoom.isVideo = true;
imageZoom.videoSource.type = 'video/webm';
return callback(url);
} else if (/\.(mp4|m4v)(\?([^?]+))?$/.test(url)) {
imageZoom.videoSource.type = 'video/mp4';
imageZoom.isVideo = true;
return callback(url);
} else if (/\.ogv(\?([^?]+))?$/.test(url)) {
imageZoom.videoSource.type = 'video/ogg';
imageZoom.isVideo = true;
return callback(url);
}
});
};
Sites.xkcd = function(elem, callback) {
getUrls([elem, elem.parentNode]).forEach(function(url) {
if (/xkcd\.com/i.test(stripUrl(url)) && /xkcd\.com\/([0-9]+)(\/)?$/i.test(url)) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://xkcd.com/' + url.replace(/[^0-9]+/g, '') + '/info.0.json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
xhr = xhr.responseText;
var img = xhr.replace(/.*(http:\\\/\\\/([^"]+)\.(png|jpg|jpeg|svg|tif)).*/i, '$1');
img = unescape(decodeURIComponent(img.replace(/\\\//g, '/')));
if (img) {
callback(img);
}
}
};
xhr.send();
}
});
};
Sites.flickr = function(elem, callback) {
var flickrApiPath = 'https://www.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=b5fcc857586ba650aa946ffee502daf2&format=json&photo_id=';
getUrls([elem, elem.parentNode]).forEach(function(url) {
if (/flickr\.com/i.test(stripUrl(url)) && /\/([0-9]){10,11}(\/|$)/i.test(url)) {
var photo_id = url.match(/\/([0-9]){10,11}(\/|$)/)[0].replace(/\//g, '');
var xhr = new XMLHttpRequest();
xhr.open('GET', flickrApiPath + photo_id);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var parsed = JSON.parse(xhr.responseText.replace(/.*Api\(/, '').replace(/\)/, '')).sizes.size;
return callback(parsed[parsed.length - 1].source);
}
};
xhr.send();
return;
}
});
};
|
const config = require('./config/config')
const { initDb } = require('./config/database')
initDb(config.firebase_creds)
const express = require('express')
const passport = require('passport')
const app = express()
const bodyParser = require('body-parser')
const router = require('./routes/router')
const validateIdToken = require('./middleware/validateIdToken')
// Takes the raw requests and turns them into usable properties on req.body
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(passport.initialize())
// CORS HANDLING
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*') // * allows all origins to send request
res.header(
'Access-Control-Allow-Headers',
'Origin, X-requested-With, Content-Type, Accept, Authorization'
) // kinds of headers allowed
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE') // setting allowed http methods
return res.status(200).json({}) // empty success response just for the browser
}
next()
})
app.use(validateIdToken)
app.use('/', router)
app.listen(config.port, () => {
console.log(`App is running on port ${config.port}`)
})
module.exports = app
|
// RxJS v6+
import { interval } from "rxjs";
import { sample } from "rxjs/operators";
//emit value every 1s
const source = interval(1000);
//sample last emitted value from source every 2s
const example = source.pipe(sample(interval(2000)));
//output: 2..4..6..8..
const subscribe = example.subscribe(val => console.log(val));
|
import { message } from 'antd';
import {
find,
update,
} from '../services/category';
export default {
namespace: 'category',
state: {
isLoading: false,
list: [],
},
effects: {
*find(_, { call, put }) {
yield put({
type: 'setLoading',
payload: true,
});
const response = yield call(find);
if (response.success) {
yield put({
type: 'setListData',
payload: response.data,
});
} else {
message.error(response.data);
}
},
*update({ payload }, { call, put }) {
const response = yield call(update, payload);
if (response.success) {
yield put({
type: 'setListData',
payload: response.data,
});
message.success('修改成功');
} else {
message.error(response.data);
}
},
},
reducers: {
setLoading(state, { payload }) {
return {
...state,
isLoading: !!payload,
};
},
setListData(state, { payload }) {
return {
...state,
list: [...payload],
isLoading: false,
};
},
},
};
|
import Tarea from '../models/Tarea';
import Proyecto from '../models/Proyecto';
import { validationResult } from 'express-validator';
const crearTarea = async(req, res) => {
const errores = validationResult(req);
if(!errores.isEmpty()){
return res.status(400).json({errores: errores.array()});
}
try{
let tarea = new Tarea(req.body);
// Validar proyecto
let proyecto = await Proyecto.findById(tarea.proyecto);
console.log('proyecto', proyecto);
if(!proyecto){
return res.status(404).json({msg: 'Proyecto no encontrado.'});
}
if(proyecto.creador.toString() !== req.usuario.id){
return res.status(401).json({msg: 'No autorizado'});
}
tarea.save();
res.status(200).json(tarea);
}
catch(error){
console.log(error);
res.status(500).send('Hubo un error al guardar la tarea');
}
}
const obtenerTareas = async(req, res) => {
try {
// console.log('obtenerTareas', req.query);
// console.log(req.params.proyecto);
const {proyecto} = req.query;
let proyectoExiste = await Proyecto.findById(proyecto).sort({creado: -1});
if(!proyectoExiste){
return res.status(404).json({msg: 'Proyecto no encontrado'});
}
if(proyectoExiste.creador.toString() !== req.usuario.id){
return res.status(401).json({msg: 'No autorizado'});
}
const tareas = await Tarea.find({proyecto});
// console.log('resultado obenerTareas', tareas);
res.status(200).json({tareas});
} catch (error) {
console.log(error);
res.status(500).send('Hubo un error');
}
}
const actualizarTarea = async(req, res) => {
try {
const {nombre, estado, proyecto} = req.body;
let tarea = await Tarea.findOne({_id: req.params.id, proyecto});
if(!tarea){
return res.status(404).json({msg: 'Tarea no existe'});
}
let proyectoEncontrado = await Proyecto.findById(tarea.proyecto);
if(proyectoEncontrado.creador.toString() !== req.usuario.id){
return res.status(404).json({msg: 'No autorizado'});
}
let nuevaTarea = {};
if(nombre) nuevaTarea.nombre = nombre;
if(estado !== null && estado !== undefined) nuevaTarea.estado = estado;
tarea = await Tarea.findOneAndUpdate({_id: req.params.id},{
$set: nuevaTarea
}, {new: true});
res.status(200).json(tarea);
} catch (error) {
console.log(error);
res.status(500).send('Hubo un error');
}
}
const eliminarTarea = async(req, res) => {
try {
const {proyecto} = req.query;
// console.log('id, body', req.params.id, proyecto);
let tarea = await Tarea.findOne({_id: req.params.id, proyecto});
if(!tarea){
return res.status(404).json({msg: 'Tarea no encontrada'});
}
let proyectoEncontrado = await Proyecto.findById(proyecto);
if(proyectoEncontrado.creador.toString() !== req.usuario.id){
return res.status(401).json({msg: 'No autorizado'});
}
await Tarea.findOneAndDelete({_id: req.params.id});
res.status(200).json({msg: 'Tarea eliminada'});
} catch (error) {
console.log(error);
res.status(500).send('Hubo un error');
}
}
export {
crearTarea,
obtenerTareas,
actualizarTarea,
eliminarTarea
}
|
var router = require('express').Router();
var authMiddleware = require('../auth/middlewares/auth');
router.use(authMiddleware.hasAuthadmin);
router.use('/home', require('./home/routes'));
router.use('/hotlines', require('./hotlines/routes'));
router.use('/hotlines/addhotline', require('./hotlines/routes'));
router.use('/emergency', require('./emergency/routes'));
router.use('/emergency/deleted', require('./emergency/routes'));
router.use('/emergency/addemergencycat', require('./emergency/routes'));
router.use('/emergency/addemergencycat/category', require('./emergency/routes'));
router.use('/learn', require('./learn/routes'));
router.use('/learn/deleted', require('./emergency/routes'));
router.use('/learn/addlearncat', require('./learn/routes'));
router.use('/learn/addlearncat/category', require('./learn/routes'));
router.use('/map', require('./map/routes'));
router.use('/map/addhospital', require('./map/routes'));
router.use('/prepare', require('./prepare/routes'));
router.use('/prepare/deleted', require('./emergency/routes'));
router.use('/prepare/addpreparecat', require('./prepare/routes'));
router.use('/prepare/addpreparecat/category', require('./prepare/routes'));
exports.admin = router;
|
import React , { Component } from 'react';
import RightSidebar from './RightSidebar';
import AuthorBookLists from './AuthorBookLists';
import GenreBookLists from './GenreBookLists';
import { toggleElementClass } from 'Utils/toggle';
/**
* @class SortSidebar
* @extends { React.Component }
* @description renders the right sider bar components
* @param { object } props
* @returns { JSX }
*/
class SortSidebar extends Component {
constructor(props){
super(props);
this.state = {
sortOptions: 'authors'
}
this.sortByAuthors = this.sortByAuthors.bind(this);
this.sortByCategories = this.sortByCategories.bind(this);
}
/**
* @method componentDidMount
* @memberof SortSidebar
* @description Lifecycle method after component mounts
* @param { null }
* @returns { void }
*/
componentDidMount(){
toggleElementClass({
toggleType: 'double',
previous:'.nested-list .glyphicon-user',
next:'.glyphicon-tasks',
toggledClass: 'active-r'
});
}
/**
* @method sortByAuthors
* @memberof SortSidebar
* @description Display list of sorted book by author
* @param {event} event handler
*/
sortByAuthors(event){
event.preventDefault()
this.setState({
sortOptions:'authors'
})
}
/**
* @method sortByCategories
* @memberof SortSidebar
* @description Display list of sorted book by categories
* @param {event} event handler
*/
sortByCategories(event){
event.preventDefault()
this.setState({
sortOptions:'genres'
})
}
render(){
return(
<RightSidebar
rightSidebarClass = "sort-sidebar"
sortByAuthors={this.sortByAuthors}
sortByCategories = {this.sortByCategories}>
{
this.state.sortOptions === 'authors' &&
<AuthorBookLists/>
}{
this.state.sortOptions === 'genres' &&
<GenreBookLists/>
}
</RightSidebar>
)
}
}
export default SortSidebar
|
// as_jsfunclib.js: useful javascript function set,
// written / assembled by Alexander Selifonov <as-works@narod.ru>
// V 1.006.114 last change: 28.02.2008
var noajax = 'No XmlHttpRequest in Your browser !';
var postcont = 'application/x-www-form-urlencoded; charset=UTF-8';
var HttpRequestExist = true;
function NewXMLHttpRequest()
{
if(!HttpRequestExist) return false;
var xmlhttplocal;
try {
xmlhttplocal= new ActiveXObject("Msxml2.XMLHTTP")
} catch (e)
{
try {
xmlhttplocal= new ActiveXObject("Microsoft.XMLHTTP")
}
catch (E) {
xmlhttplocal=false;
}
}
if (!xmlhttplocal && typeof XMLHttpRequest!='undefined') {
try { var xmlhttplocal = new XMLHttpRequest(); }
catch (e) { xmlhttplocal = HttpRequestExist = false; }
}
return(xmlhttplocal);
}
function SetFormValue(felem,newval) {
var itmp;
if(typeof(felem)!='object') return;
switch(felem.type) {
case 'select-one':
for(itmp=0;itmp<felem.options.length;itmp++) {
if(felem.options[itmp].value==newval) {felem.selectedIndex=itmp; break; }
}
break;
case 'checkbox':
felem.checked = (newval>0);
break;
default:
felem.value = newval;
break;
}
}
function GetFormValue(felem) {
ret = '';
var itmp;
if(typeof(felem)!='object') return ret;
switch(felem.type) {
case 'select-one':
itmp=felem.selectedIndex;
if(itmp>=0) ret = felem.options[itmp].value;
break;
case 'checkbox':
ret = felem.checked;
break;
default:
ret = felem.value;
break;
}
return ret;
}
function ComputeParamString(frmname, skipempty, fldlist)
{ // compute param string with all "frmname" form values
var theForm;
if(isNaN(skipempty)) skipempty=false;
if(typeof(frmname)=='object') theForm=frmname;
else theForm=eval("window.document."+frmname);
var els = theForm.elements;
var retval = "";
for(i=0; i<els.length; i++)
{ //<2>
vname = els[i].name;
if(vname=='') continue;
if(typeof(fldlist)=='object' && !IsInArray(fldlist,vname)) continue;
oneval = "";
t = els[i].type;
switch(t)
{ //<3>
case "select-one" :
var selobj =els[i];
var nIndex = selobj.selectedIndex;
if (nIndex >=0) oneval = selobj.options[nIndex].value;
break;
case "text": case "button": case "textarea": case 'password': case "hidden": case 'submit':
if(els[i].value != "")
oneval = els[i].value;
break;
case "checkbox":
/* if(vname =='dago_limit') {
alert(vname+ ' type: '+ typeof(els[i]) );
alert('value: '+els[i].value + ' length: '+ els[i].length);
}
*/
oneval = (els[i].checked ? "1":"0");
break;
case "radio":
if(els[i].value != "" && els[i].checked)
oneval = els[i].value;
break;
default:
// alert(vname+': not supported control: '+els[i].type);
oneval = els[i].value;
break;
} //<3>
if((oneval!='' && oneval!=0) || (!skipempty)) {
if (retval != "") retval = retval + "&";
retval = retval+vname+'='+encodeURIComponent(oneval);
}
} //<2>
return retval;
} // ComputeParamString()
function SelectBoxSet(frm,objname, val){
var obj;
elems = '';
if(typeof frm=='string') eval("obj=document."+frm+"."+objname);
else eval('obj=frm.'+objname);
if(!isNaN(obj.selectedIndex)) //alert('SelectBoxSet error: '+frm+'.'+objname+" - not a selectbox !");
{
for(kk=0; kk<obj.options.length; kk++) {
if (obj.options[kk].value==val) { obj.selectedIndex = kk; return; }
}
}
}
function FindInSelectBox(frm,objname,val){
var obj;
if(typeof frm=='string') eval("obj=document."+frm+"."+objname);
else eval('obj=frm.'+objname);
if(isNaN(obj.selectedIndex)) return -1;
var kk; var vlow = val.toLowerCase();
for(kk=0; kk<obj.options.length; kk++) {
if (obj.options[kk].text.toLowerCase()==vlow) return kk;
}
return -1;
}
function DateRepair(sparam)
{ // make input date well formatted: dd.mm.yyyy
var sdate = (typeof sparam =='string' ? sparam : sparam.value);
if(sdate.length<1) return '';
var d_date = new Date();
if(sdate.length<3) sdate +='.'+d_date.getMonth()+'.'+d_date.getDay();
var syy='', smm='', sdd='';
var dp = 1;
if(sdate.charAt(dp)>=0 && sdate.charAt(dp)<='9' && sdate.length>2 )
dp=2;
sdd = sdate.substring(0,dp);
if(sdate.charAt(dp)>=0 && sdate.charAt(dp)<='9')
sdate = sdate.substring(dp);
else sdate = sdate.substring(dp+1);
dp = 1;
if(sdate.charAt(dp)>=0 && sdate.charAt(dp)<='9' && sdate.length>=2 ) dp=2;
smm = sdate.substring(0,dp);
if(sdate.charAt(dp)>=0 && sdate.charAt(dp)<='9')
sdate = sdate.substring(dp);
else sdate = sdate.substring(dp+1);
if(sdate == '') {
sdate = d_date.getFullYear();
}
syy = sdate;
if(syy.length<4) {
if(syy>20 && syy<=99) syy = '19'+syy;
else syy = (syy.length==2 ? '20' : 200) + syy;
}
if(sdd<=0 || smm<=0) return '';
if(sdd.length<2) sdd = '0'+sdd;
if(smm.length<2) smm = '0'+smm;
ret = sdd+'.'+smm+'.'+syy;
if(typeof(sparam)=='object') { sparam.value = ret; return false; }
delete d_date;
return ret;
}
function NumberRepair(sparam) {
var sdata = (typeof(sparam)=='string' ? sparam : sparam.value);
var ret = sdata.replace(',','.');
ret = parseFloat(ret);
if(isNaN(ret)) ret = '0';
if(typeof(sparam)=='object') { sparam.value = ret; return; }
return ret;
}
function AddToDate(sdate, years, months, days)
{ // sdate must be in 'dd.mm.yyyy' format !!!
var mlen = [0,31,28,31,30,31,30,31,31,30,31,30,31];
var delem = sdate.split('.');
if(delem.length<3) delem = sdate.split('/');
if(delem.length<3) return '';
var nday = (delem[0]-0);
var nmon = (delem[1]-0);
var nyear = (delem[2]-0);
if(months>12 || months<-12) {
years += Math.floor(months/12);
months = months % 12;
}
if(years!=0) nyear +=years;
if(months>0) {
nmon += months;
while(nmon >12) {
nyear++;
nmon -= 12;
}
}
else if(months<0) {
nmon += months;
while(nmon <-12) {
nyear--;
nmon += 12;
}
}
var nmlen = ((nyear % 4==0) && nmon==2) ? 29 : mlen[nmon];
if(days!=0) {
nday+=days;
if(nday > nmlen) {
nday -= nmlen;
nmon++;
if(nmon>12) { nmon=1; nyear++;};
}
else if(nday<=0) {
nmon--;
if(nmon<=0) { nmon=12; nyear--; }
}
nmlen = ((nyear % 4==0) && nmon==2) ? 29 : mlen[nmon];
if(nday<=0) nday += nmlen;
}
if(nday>nmlen) nday = nmlen;
if(nday<10) nday = '0'+nday;
if(nmon<10) nmon = '0'+nmon;
return (nday+'.'+nmon+'.'+nyear);
}
function IsInArray(arr, val)
{
for(lp=0; lp<arr.length;lp++){ if(arr[lp]==val) return true; }
return false;
}
function FormatInteger( integer )
{ // author:
var result = '';
var pattern = '###,###,###,###';
if(typeof(integer)!='string') integer = integer+'';
integerIndex = integer.length - 1;
patternIndex = pattern.length - 1;
while ( (integerIndex >= 0) && (patternIndex >= 0) )
{
var digit = integer.charAt( integerIndex );
integerIndex--;
// Skip non-digits from the source integer (eradicate current formatting).
if ( (digit < '0') || (digit > '9') ) continue;
// Got a digit from the integer, now plug it into the pattern.
while ( patternIndex >= 0 )
{
var patternChar = pattern.charAt( patternIndex );
patternIndex--;
// Substitute digits for '#' chars, treat other chars literally.
if ( patternChar == '#' )
{
result = digit + result;
break;
}
else { result = patternChar + result; }
}
}
return result;
}
// compares two 'dd.mm.yyyy' strings as dates
function CompareDates(dt1,dt2) {
var cd1=dt1.substring(6,10)+dt1.substring(3,5)+dt1.substring(0,2);
var cd2=dt2.substring(6,10)+dt2.substring(3,5)+dt2.substring(0,2);
if(cd1>cd2) return 1;
if(cd1<cd2) retun -1;
return 0;
}
/* useful functions from Dustin Diaz, http://www.dustindiaz.com/top-ten-javascript/
*/
/* grab Elements from the DOM by className */
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
/* get, set, and delete cookies */
function getCookie( name ) {
var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ";", len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}
function setCookie( name, value, expires, path, domain, secure ) {
var today = new Date();
today.setTime( today.getTime() );
if ( expires ) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );
document.cookie = name+"="+escape( value ) +
( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}
function deleteCookie( name, path, domain ) {
if ( getCookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
/* quick getElement reference */
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
function asGetObj(name)
{
if (document.getElementById) {
return document.getElementById(name);
}
else if (document.all) {
return document.all[name];
}
else if (document.layers)
{
if (document.layers[name]) {
return document.layers[name];
this.style = document.layers[name];
}
else { return document.layers.testP.layers[name]; }
}
return null;
}
|
class _Main {
static function main (args : string[]) : void {
// we cannot introduce "X -> Y" style type declaration, e.g.:
var add = (x : number, y : number) : number -> x -> y;
}
}
|
import React, { Component } from "react";
import MapContainer from "./EventMapContainer";
class EventMapComponent extends Component {
render() {
return (
<React.Fragment>
<MapContainer coords={this.props.coords} />
</React.Fragment>
);
}
}
export default EventMapComponent;
|
import React, {useEffect} from 'react';
import Loader from 'components/Loader/Loader';
import { useSelector, useDispatch } from 'react-redux';
import { Link, useParams } from 'react-router-dom';
import './MovieDetail.scss';
import { actFetchMovieDetail } from './module/actions';
export default function MovieDetail(props) {
const { movieId } = useParams(); // props.match.params
const dispatch = useDispatch(); // mapDispatchToProps
const { loading, movieDetail } = useSelector( state => state.movieDetailReducer); // mapStatetoProps
useEffect(() => {
dispatch(actFetchMovieDetail(movieId));
}, [])
if(loading) return <Loader />
return movieDetail && (
<div className="mt-5">
<div className="movieDetail container">
<div className="row">
<div className="col-5 col-sm-4 col-lg-3">
<img className="img-fluid" src={movieDetail.hinhAnh} alt="" />
</div>
<div className="col-7 col-sm-8 col-lg-9">
<h2>{movieDetail.tenPhim}</h2>
<h5>Premier on {new Date(movieDetail.ngayKhoiChieu).toLocaleDateString()}</h5>
<p>{movieDetail.moTa}</p>
<h5>Rating: {movieDetail.danhGia}*</h5>
<a className="btn btn-success" href={movieDetail.trailer}>Watch Trailer</a>
</div>
</div>
</div>
<div className="showTime mt-3 pt-3 pb-5">
<div className="container">
<h1 className="col-9 ml-auto">Show Time</h1>
<div className="row showTime__content">
<div className="col-3 content__left">
<div className="nav flex-column nav-pills text-left" id="v-pills-tab" role="tablist" aria-orientation="vertical">
{movieDetail.heThongRapChieu.map((heThongRap, idx) => {
return (
<a className={`left-logo nav-link mr-0 ${idx === 0 ? 'active' : ''}`} id="v-pills-home-tab" data-toggle="pill" href={`#${heThongRap.maHeThongRap}`} role="tab" aria-controls={heThongRap.maHeThongRap} key={idx} aria-selected="true">
<img src={heThongRap.logo} alt=""/>
<span className="cinemaName">{heThongRap.tenHeThongRap}</span>
</a>
)
})}
</div>
</div>
<div className="col-9 content__right">
<div className="tab-content" id="v-pills-tabContent">
{movieDetail.heThongRapChieu.map((heThongRap, idx) => {
return (
<div className={`tab-pane fade show ${idx === 0 ? 'active' : ''}`} id={heThongRap.maHeThongRap} role="tabpanel" aria-labelledby="v-pills-home-tab" key={idx}>
{heThongRap.cumRapChieu.map((cumRap, idx) => {
return (
<div className="text-left" key={idx}>
<img src={cumRap.hinhAnh} alt="" style={{width: '50px', marginRight: '6px'}} />
<span className="cinema__name">{cumRap.tenCumRap}</span>
<div className="my-2">
{cumRap.lichChieuPhim.map((lichChieu, idx) => {
return (
<Link to={`/seat-plan/${lichChieu.maLichChieu}`} className="btn btn-info mr-3 mb-3" key={idx}>{new Date(lichChieu.ngayChieuGioChieu).toLocaleTimeString()}</Link>
)
})}
</div>
</div>
);
})}
</div>
)
})}
</div>
</div>
</div>
</div>
</div>
</div>
)
}
|
describe('Cloud Functions', () => {
let storageFileToRTDB
let adminInitStub
let admin
before(() => {
admin = require('firebase-admin')
adminInitStub = sinon.stub(admin, 'initializeApp')
storageFileToRTDB = functionsTest.wrap(
require(`${__dirname}/../../index`).storageFileToRTDB
)
})
after(() => {
functionsTest.cleanup()
adminInitStub.restore()
})
describe('Storage File to RTDB', () => {
it('responds to fake event', async () => {
const snap = {
val: () => ({ displayName: 'some', filePath: 'some' })
}
const fakeContext = {
params: { filePath: 'testing', userId: 1 }
}
// Invoke webhook with our fake request and response objects. This will cause the
// assertions in the response object to be evaluated.
await storageFileToRTDB(snap, fakeContext)
})
})
})
|
'use strict';
/**/
/*
var config = {
host: '192.168.0.21',
port: 22,
username: 'iojs',
privateKey: fs.readFileSync('/Users/zensh/.ssh/id_rsa')
};
*/
var gulp = require('gulp'),
concatCss = require('gulp-concat-css'),
minifyCss = require('gulp-minify-css'),
rename = require("gulp-rename"),
notify = require("gulp-notify"),
through = require('gulp-through'),
sass = require('gulp-sass'),
uncss = require('gulp-uncss'),
autoprefixer= require('gulp-autoprefixer'),
jsdoc = require("gulp-jsdoc"),
uglify = require('gulp-uglifyjs'),
refresh = require('gulp-livereload'),
shell = require('gulp-shell'),
svgo = require('svgo'),
lr = require('tiny-lr'),
svgSprite = require("gulp-svg-sprites"),
jade = require('gulp-jade'),
GulpSSH = require('gulp-ssh'),
/*
gulpSSH = new GulpSSH({
ignoreErrors: false,
sshConfig: config
}),
*/
yaml = require('gulp-yaml'),
server = lr();
/**/
/*
var plugins = require("gulp-load-plugins")({
pattern: ['gulp-*', 'gulp.*'],
replaceString: /\bgulp[\-.]/
});
*/
/**/
gulp.task('default', ['min-css', 'min-js']);
/**/
gulp.task('lr-server', function() {
server.listen(35729, function(err) {
if(err) return console.log(err);
});
});
/**/
gulp.task('min-css', function () {
return gulp.src('scss/style.scss')
.pipe(sass())
.pipe(minifyCss({compatibility: 'ie8'}))
.pipe(rename("getiss.min.css"))
.pipe(notify({
message: "Generated file: <%= file.relative %> @ <%= options.date %>",
templateOptions: {
date: new Date()
}
}
))
.pipe(gulp.dest('cdn/'));
});
// delete not used css classes , ids, tags
/**/
gulp.task('uncss', function () {
return gulp.src('cdn/bundle.min.css')
.pipe(uncss({
//html: ['index.html', 'posts/**/*.html', 'http://example.com']
html: ['test.html']
}))
.pipe(notify({
message: "Delete not used css classes , ids, tagse: <%= file.relative %> @ <%= options.date %>",
templateOptions: {
date: new Date()
}
}
))
.pipe(gulp.dest('cdn/'));
});
/**/
gulp.task('jsdoc',function() {
gulp.src("js/app/*.js")
.pipe(jsdoc('./doc'))
.pipe(notify({
message: "Js documentations create : <%= file.relative %> @ <%= options.date %>",
templateOptions: {
date: new Date()
}
}
))
});
/**/
gulp.task('min-js', function() {
gulp.src([ 'js/bower_components/jquery/dist/jquery.js',
'js/bower_components/underscore/underscore.js',
'js/bower_components/backbone/backbone.js',
//'js/bower_components/backbone-localstorage/backbone-localstorage.js',
//'js/app/collections/*.js', // collections backbone
//'js/app/models/*.js', // models
//'js/app/views', // views
'js/bower_components/kjur/jsrsasign/jsrsasign-latest-all-min.js',
'js/app/app.js' // init
])
.pipe(uglify())
.pipe(rename("getiss.min.js"))
.pipe(gulp.dest('cdn/'))
.pipe(notify({
message: "Generated file: <%= file.relative %> @ <%= options.date %>",
templateOptions: {
date: new Date()
}
}
))
});
/**/
gulp.task('phpdoc', shell.task(['vendor/bin/phpdoc -d . -t docs/phpdoc -i vendor/,node_modules/,server.php']));
/**/
gulp.task('watch', function () {
gulp.watch(['min-css', 'min-js']);
});
gulp.task('sprites', function () {
return gulp.src('img/svg/*.svg')
.pipe(svgSprite({
cssFile: "../scss/includes/_sprite.scss",
layout: 'diagonal'
}))
.pipe(gulp.dest("cdn/"))
.pipe(notify({
message: "SVG sprite create : <%= file.relative %> @ <%= options.date %>",
templateOptions: {
date: new Date()
}
}
));
});
/**/
gulp.task('pngSprite', ['svgSprite'], function() {
return gulp.src(basePaths.dest + paths.sprite.svg)
.pipe(plugins.svg2png())
.pipe(gulp.dest(paths.images.dest));
});
/**/
gulp.task('sprite', ['pngSprite']);
/**/
gulp.task('exec', function () {
return gulpSSH
.exec(['uptime', 'ls -a', 'pwd'], {filePath: 'commands.log'})
.pipe(gulp.dest('logs'))
});
/**/
gulp.task('yml', function () {
return gulp.src('/var/www/phalcon/app/config/*.yml')
.pipe(yaml({ space: 2 }))
.pipe(gulp.dest('./json/'))
});
// Jade
gulp.task('jade', function(){
gulp.src('./template/*.jade')
.pipe(jade())
.pipe(gulp.dest('./dist/'))
});
// Watch
gulp.task('watch', function(){
gulp.watch('./template/*.jade',['jade']);
});
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Auth from '../../authenticate/containers/Auth'
const auth = new Auth();
class NavBar extends Component {
render() {
return (
<div>
<Link to={'/'}>Home</Link>
<Link to={'/about-us'}>About Us</Link>
<button type='button' onClick={auth.logout}>Logout</button>
</div>
)
}
}
export default NavBar;
|
KISSY.config('modules', {
'kg/xscroll/1.1.8/plugin/scrollbar': { requires: ['node', 'base', 'anim', 'kg/xscroll/1.1.8/util']}
});
|
function aegismarked(text)
{
//Example
text = text.replace(/<startexample>/g,'<div class="panel panel-default example"> \r\n \
<div class="panel-body" style="padding:0px;padding-top:15px;"><small style="padding-left:15px;" class="text-muted">EXAMPLE</small>\r\n<div style="padding-left:15px;">').replace(/<endexample>/g, '</div></div>\r\n</div>');
//Solution
text = text.replace(/<startsolution>/g,'</div><div class="panel panel-default solution" style="margin-bottom: 0px;"> \r\n \
<div class="panel-body"><small class="text-muted">SOLUTION</small>\r\n<div>').replace(/<endsolution>/g, '</div></div>\r\n</div>');
// Defintion
text = text.replace(/<startdefinition>/g,'<div class="panel panel-default definition"> \r\n \
<div class="panel-body"><small class="text-muted">DEFINITION</small>\r\n<div>').replace(/<enddefinition>/g, '</div></div>\r\n</div>');
// Proof
text = text.replace(/<startproof>/g,'</div><div class="panel panel-default proof" style="margin-bottom: 0px;"> \r\n \
<div class="panel-body"><small class="text-muted">PROOF</small>\r\n<div>').replace(/<endproof>/g, '</div></div>\r\n</div>');
// Question
text = text.replace(/<startquestion-(\d+)>/g,'<div class="slickQuiz" id="slickQuiz-$1" data-id="$1">\r\n \
<h1 class="quizName"></h1>\r\n \
<div class="quizArea">\r\n \
<div class="quizHeader"> \
<a class="startQuiz" href="">Get Started!</a> \
</div> \
</div> \
<div class="quizResults"> \
<h3 class="quizScore">You Scored: <span></span></h3> \
<h3 class="quizLevel"><strong>Ranking:</strong> <span></span></h3> \
<div class="quizResultsCopy"></div> \
</div>').replace(/<\/endquestion>/g, '</div>');
// Theory
text = text.replace(/<starttheorem>/g,'<div class="panel panel-default theorem"> \r\n \
<div class="panel-body" style="padding:0px;padding-top:15px;"><small class="text-muted" style="padding-left:15px;">THEOREM</small>\r\n<div style="padding-left:15px;">').replace(/<endtheorem>/g, '</div></div>\r\n</div>');
// Theory
text = text.replace(/<startbox>/g,'<div class="panel panel-default box"> \r\n \
<div class="panel-body">\r\n<div>').replace(/<endbox>/g, '</div></div>\r\n</div>');
text = text.replace(/<startcenter>/g,'<p class="text-center">').replace(/<endcenter>/g, '</p>');
text = text.replace(/<hr-(\d+)>/g, "<hr style=\"height:$1px;\"");
text = text.replace(/</g, '<').replace(/>/g, '>');
return text;
}
|
const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
router.get('/jwt', (req, res) => {
let username = process.env.JWT_USERNAME || 'iot'
let password = process.env.JWT_PASSWORD || 'iot1234'
let secretkey = process.env.SECRET_KEY
let iss = process.env.ISS;
let sub = process.env.SUB;
let aud = process.env.AUD;
let exp = process.env.EXP;
let algorithms = process.env.ALG_TOKEN;
let payload = {
issuer: iss,
subject: sub,
audience: aud,
expiresIn: exp,
algorithm: algorithms,
}
let p_username = req.body.username;
let p_password = req.body.password;
if(p_username == username && p_password == password) {
jwt.sign(payload, secretkey, (err, token) => {
res.json({
"status":true,
"message":"Login Successfull",
"type":"Bearer Token",
"token":token
})
})
} else {
res.send({
"status":false,
"message":"Wrong Username or Password",
})
}
})
module.exports = router
|
const express = require("express"),
cookieParser = require("cookie-parser"),
path = require("path"),
cluster = require("cluster"),
net = require("net"),
farmhash = require("farmhash"),
helmet = require("helmet"),
passport = require("passport"),
keys = require("./config/keys"),
log = require("./config/log")("SERVER", "blue"),
session = require("./session"),
authenticate = require("./middlewares/authenticate"),
PORT = process.env.PORT || 5050,
num_processes = require("os").cpus().length;
const app = express();
app.use(helmet());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser(keys.cookieKey));
app.use(session);
app.use(passport.initialize());
app.use(passport.session());
app.use("/api", authenticate);
require("./models/User");
require("./models/Invite");
require("./models/Game");
require("./services/passport");
require("./routes/apiRoutes")(app);
require("./routes/authRoutes")(app);
require("./routes/gameRoutes")(app);
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "frontend", "build")));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "frontend", "build", "index.html"));
});
}
const server = app.listen(0, "localhost");
require("./services/socketio")(server);
if (cluster.isMaster) {
log("master cluster is at work!");
const workers = [];
const spawn = i => {
workers[i] = cluster.fork();
workers[i].on("exit", (code, signal) => {
log("worker exited!", "code:", code, "\n", "signal:", signal);
log("respawning worker", i);
spawn(i);
});
};
for (let i = 0; i < num_processes; i++) {
spawn(i);
}
const worker_index = (ip, len) => {
return farmhash.fingerprint32(ip) % len;
};
net
.createServer({ pauseOnConnect: true }, socket => {
const worker = workers[worker_index(socket.remoteAddress, num_processes)];
worker.send("sticky-session:connection", socket);
})
.listen(PORT);
} else {
process.on("message", (message, connection) => {
if (message !== "sticky-session:connection") return;
server.emit("connection", connection);
connection.resume();
});
}
|
/*
get php fallback file for production
*/
var gulp = require('gulp');
var phpFallbackTask = function() {
return gulp.src([
'./index.php',
])
.pipe(gulp.dest('production/')); // place php fallback in root directory
};
gulp.task('phpFallbackTask', phpFallbackTask);
module.exports = phpFallbackTask;
|
function wikiAPI() {
var searchTerm = document.getElementById('searchTerm').value;
var xhr = new XMLHttpRequest();
var url = "https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&generator=search&gsrnamespace=0&gsrlimit=30&gsrsearch=" + searchTerm;
xhr.open('GET', url);
xhr.onload = function() {
var wikiObject = JSON.parse(this.response);
//console.log(wikiObject);
//console.log(wikiObject.query.pages);
var pages = wikiObject.query.pages;
var pageID = wikiObject.query.pages.pageid;
var pageURL = "https://en.wikipedia.org/?curid=" + pageID;
for (i in pages) {
var newDiv = document.createElement('div');
newDiv.setAttribute('class','row h4');
document.getElementById('wiki').appendChild(newDiv);
newDiv.innerText = pages[i].title;
//var newLink = document.createElement('a');
// document.getElementById('pageURL').appendChild(newLink);
//newLink.innerText = pages[i].title;
//newLink.href.innerText = pages[i].pageURL;
document.getElementById('pageURL').onclick = function() {
document.querySelector('a').setAttribute("href", pageURL);
}
}
}
xhr.send();
}
|
//Languages
//Dependencies
export default {
users : ["users","χρήστες"],
user : ["user","χρήστης"],
groups : ["groups","Ομάδες"],
cars : ["cars"],
category : ["category","Κατηγορία"],
categories : ["categories","sioth9eah"],
priceLists :["pricelists","sfopas",],
name : ["name","Κατηγορία"],
email : ["email","Όνομα"],
address : ["address","Διεύθυνση"],
zip : ["zip","T.K."],
phone : ["phone","Τηλέφωνο"],
prices : ["prices","Τιμές"],
pricelist : ["pricelist","Τιμοκατάλογος"],
signin : ["signin","Είσοδος"],
signout : ["signout","Αποσύνδεση"],
group : ["group","Ομάδες"],
car : ["car","Αυτοκίνητο"],
cars : ["cars","Αυτοκίνητα"],
access : ["access","Πρόσβαση"],
rentals : ["rentals","Ενοικιάσεις"],
booking : ["booking","Ολοκληρωμένη Κράτηση"],
bookings : ["bookings","Ολοκληρωμένες Κρατήσεις"],
reservations : ["reservations","Κρατήσεις"],
password : ["password","Κωδικός πρόσβασης"],
city : ["city", "Πόλη"],
tel : ["tel","Τηλέφωνο"],
surname : ["surname","Επίθετο"],
vatNumber :["vatNumber","ΑΦΜ"],
new :["new","νέος"],
updatedNow : ["updated now"," τώρα ΕΠΙΚΑΙΡΟΠΟΙΗΜΕΝΟ"],
dashboard : ["dashboard","ταμπλό"],
inactive : ["inactive","αδρανής"],
active : ["active","ενεργός"],
edit : ["edit","επεξεργασία"],
profile : ["profile","Προφίλ"],
first : ["first","πρώτα"],
home : ["home","Σπίτι"],
postalCode : ["postal code", "Ταχυδρομικός Κώδικας"],
create : ["create","δημιουργώ"],
read : ["read","ανάγνωση"],
update : ["update","εκσυγχρονίζω"],
delete : ["delete","διαγράφω"],
save : ["save","αποθηκεύσετε"],
by : ["by","με"],
members : ["members","μέλη"],
loading : ["loading","φόρτωση"],
add : ["add","προσθέτω"],
remove : ["remove","αφαιρώ"],
createUser : ["create user","δημιουργώ χρήστης"],
createGroup : ["create group","δημιουργώ Ομάδες"],
make : ["Make","φτιαχνω, κανω"]
}
|
const { Router: createRouter } = require('express');
const { checkAccess } = require('../middlewares');
const logoutRouter = createRouter();
logoutRouter.get('/', checkAccess, async (req, res) => {
const { session } = req;
await session.destroy();
res.json({
response: true
});
});
exports.logoutRouter = logoutRouter;
|
import React from "react";
import { usePromiseTracker } from "react-promise-tracker";
import Loader from "react-loader-spinner";
import "./spinner.css";
export const Spinner = (props) => {
const { promiseInProgress } = usePromiseTracker();
return (
promiseInProgress && (
<div className="lds-spinner"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>
)
);
};
export default Spinner;
|
var _ = require('lodash');
var React = require('react');
var ReactBootstrap = require('react-bootstrap');
var Input = ReactBootstrap.Input;
var ExternalOrderSelector = React.createClass({
propTypes: {
externalOrders: React.PropTypes.object,
},
getDefaultProps: function() {
return {
externalOrders: { },
};
},
render: function() {
var externalOrderOptions = _.map(this.props.externalOrders, function(externalOrder) {
return (<option value={ externalOrder.externalorderId } key={ externalOrder.externalorderId }>
{ externalOrder.externalorderCode } { externalOrder.supplierName }
</option>);
});
return (
<Input type="select" {...this.props}>
<option value="0">Valitse ulkoinen tilaus...</option>
{ externalOrderOptions }
</Input>
);
},
});
module.exports = ExternalOrderSelector;
|
function create(inputArray) {
let contentDiv = document.getElementById("content");
for (let i = 0; i < inputArray.length; i++) {
let div = document.createElement("div");
let p = document.createElement("p");
p.textContent = inputArray[i];
p.style.display = "none";
div.appendChild(p);
contentDiv.appendChild(div);
}
contentDiv.addEventListener("click", showParagraph);
function showParagraph(e) {
if (e.target.matches("#content div")) {
let p = e.target.children[0];
p.style.display = "block";
}
}
}
|
import percent from './../util/percent';
class Armor {
constructor(props) {
this._absorption = props.absorption || 0;
this._name = props.name;
}
/**
*
* @returns {number}
*/
get absorption() {
return this._absorption || 0;
}
/**
* @returns {String}
*/
get name() {
return this._name;
}
}
const armors = require('./../data/json/armor-Armor.json')
.map(params => {
const out = {};
for (let prop in params) {
if (params.hasOwnProperty(prop)) {
let lcProp = prop.toLowerCase();
out[lcProp] = percent(params[prop]);
}
}
return out;
})
.reduce((memo, params) => {
const a = new Armor(params);
memo[a.name] = a;
return memo;
}, {});
export {Armor, armors};
|
// JavaScript Document
// Carousel //
$('#myCarousel').carousel({
interval: 3000,
})
/*************** Mega menu slide down on hover with carousel ****************/
$(document).ready(function(){
$(".dropdown").hover(
function() {
$('.dropdown-menu', this).not('.in .dropdown-menu').stop(true,true).slideDown("400");
$(this).toggleClass('open');
},
function() {
$('.dropdown-menu', this).not('.in .dropdown-menu').stop(true,true).slideUp("400");
$(this).toggleClass('open');
}
);
});
/*************** Loop Thumbnail Image Product Page ****************/
// select all thumbnails
const galleryThumbnail = document.querySelectorAll(".thumbnails-list li");
// select featured
const galleryFeatured = document.querySelector(".product-gallery-featured img");
// loop all items
galleryThumbnail.forEach((item) => {
item.addEventListener("mouseover", function () {
let image = item.children[0].src;
galleryFeatured.src = image;
});
});
/*************** shopping Cart ****************/
$(document).ready(function() {
/* Set rates + misc */
var taxRate = 0.05;
var shippingRate = 15.00;
var fadeTime = 300;
/* Assign actions */
$('.product-quantity input').change( function() {
updateQuantity(this);
});
$('.product-removal button').click( function() {
removeItem(this);
});
/* Recalculate cart */
function recalculateCart()
{
var subtotal = 0;
/* Sum up row totals */
$('.product').each(function () {
subtotal += parseFloat($(this).children('.product-line-price').text());
});
/* Calculate totals */
var tax = subtotal * taxRate;
var shipping = (subtotal > 0 ? shippingRate : 0);
var total = subtotal + tax + shipping;
/* Update totals display */
$('.totals-value').fadeOut(fadeTime, function() {
$('#cart-subtotal').html(subtotal.toFixed(2));
$('#cart-tax').html(tax.toFixed(2));
$('#cart-shipping').html(shipping.toFixed(2));
$('#cart-total').html(total.toFixed(2));
if(total == 0){
$('.checkout').fadeOut(fadeTime);
}else{
$('.checkout').fadeIn(fadeTime);
}
$('.totals-value').fadeIn(fadeTime);
});
}
/* Update quantity */
function updateQuantity(quantityInput)
{
/* Calculate line price */
var productRow = $(quantityInput).parent().parent();
var price = parseFloat(productRow.children('.product-price').text());
var quantity = $(quantityInput).val();
var linePrice = price * quantity;
/* Update line price display and recalc cart totals */
productRow.children('.product-line-price').each(function () {
$(this).fadeOut(fadeTime, function() {
$(this).text(linePrice.toFixed(2));
recalculateCart();
$(this).fadeIn(fadeTime);
});
});
}
/* Remove item from cart */
function removeItem(removeButton)
{
/* Remove row from DOM and recalc cart total */
var productRow = $(removeButton).parent().parent();
productRow.slideUp(fadeTime, function() {
productRow.remove();
recalculateCart();
});
}
});
|
"use strict";
require("run-with-mocha");
const assert = require("assert");
const PlaybackStateType = require("../../src/types/PlaybackStateType");
describe("types/PlaybackStateType", () => {
it("Symbol.hasInstance", () => {
[
PlaybackStateType.UNSCHEDULED_STATE, "unscheduled",
PlaybackStateType.SCHEDULED_STATE, "scheduled",
PlaybackStateType.PLAYING_STATE, "playing",
PlaybackStateType.FINISHED_STATE, "finished",
].forEach((value) => {
assert(PlaybackStateType[Symbol.hasInstance](value));
});
});
});
|
/**
* @properties={type:12,typeid:36,uuid:"09E244B7-8DCB-4331-8ADF-CC47A08A05FD"}
*/
function datafesta_string()
{
return datafesta.substring(0, 2) + '/' + datafesta.substring(2, 4) + '/' + globals.TODAY.getFullYear();
}
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import './TextInput.scss';
const TextInput = React.forwardRef((props, ref) => {
const { id, name, type, value, label, rootClassName, error, disabled, onChange } = props;
return (
<div
className={classNames('text-input__component', {
error: !!error,
[rootClassName]: !!rootClassName,
})}
>
<div className="text-input__component__row">
{label && <label htmlFor={id}>{label}</label>}
<input
ref={ref}
id={id}
type={type}
name={name}
value={value}
onChange={onChange}
disabled={disabled}
/>
</div>
{error && <span>{error}</span>}
</div>
);
});
TextInput.propTypes = {
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
type: PropTypes.oneOf(['text', 'email', 'password', 'number']),
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
label: PropTypes.string,
rootClassName: PropTypes.string,
error: PropTypes.string,
disabled: PropTypes.bool,
onChange: PropTypes.func,
};
TextInput.defaultProps = {
value: undefined,
type: 'text',
label: null,
rootClassName: null,
error: null,
disabled: null,
onChange: null,
};
export default TextInput;
|
// // 1차풀이 (시간복잡도...)
// function solution(n) {
// if(n==2){
// return 1;
// }
// var j = 3;
// var result = 1;
// for(j; j<=n; j++){
// var count = 0;
// var i=3;
// for(i; i<j; i++){
// if(j%i == 0){
// break;
// }
// }
// result++;
// }
// return result;
// }
// function isPrime(n){
// if(n<=1){return false;}
// if(n%2==0){return (n==2);}
// var i=3;
// for(i; i<=Math.sqrt(n); i++){
// if(n%i==0){return false;}
// }
// return true;
// }
// function sol(num){
// if(num == 2){return 1;}
// var count = 0;
// for(var i=2; i<=num; i++){
// if(isPrime(i) == true){count++;}
// }
// return count;
// }
// function sol(num){
// if(num == 2){return 1;}
// var count = 0;
// for(var i=2; i<=num; i++){
// if(isPrime(i) == true){
// count++;
// }
// }
// return count;
// }
// function isPrime(n){
// var i=3;
// const length = Math.sqrt(n);
// if(n<=1){return false;}
// if(n%2==0){return (n==2);}
// for(i; i<=length; i++){
// if(n%i==0){return false;}
// }
// return true;
// }
function solution(num){
console.log("입력한 값은 : " + num + " 입니다");
var count = 1;
if(num == 2){return 1;}
console.log("일단 2보다 크므로 count에 소수 2를 포함합니다.");
console.log("현재 count의 값은 : " + count);
for(var i=3; i<=num; i+=2){
console.log(i+"에 대해 소수인지 검사를 시작합니다.");
for(var j=2; j<i; j++){
var isPrime = true;
if(i%j==0){
console.log(i+"를" + j + "로 나눌수 있으므로 " + i + "는 소수가 아닙니다. break 합니다");
isPrime = false;
break;
} else {
console.log(i+"를" + j + "로 나눌수 없습니다.");
}
}
if(isPrime){
console.log(i + "는 소수가 맞습니다. count에 1을 더합니다.");
count++;
};
console.log("현재 count의 값은 : " + count);
}
return count;
}
console.log(solution(5));
console.log(solution(10));
|
const fs = require('fs');
const path = require('path');
const connection = require('./connection');
const sorter = require('../common/sorter');
const _recordVersion = async (params, session) => {
await session.run('MATCH (v:__db_versions) DETACH DELETE (v)');
await session.run(`CREATE(:__db_versions $placeholder)`, {placeholder: {versions: params.versions}});
console.log(`VERSION APPLICATOR SAVED VERSION CHANGELOG`);
};
const _runQueries = async (params, queries, session) => {
for (const query of queries) {
try {
await session.run(query);
console.log(`VERSION APPLICATOR RAN: ${query}`);
} catch (error) {
console.log(`VERSION APPLICATOR ERROR: ${query} MESSAGE: ${JSON.stringify(error)}`);
}
}
};
const _getQueriesFromFiles = async (params, dir, files) => {
const queries = [];
for (const file of files) {
if (!params.versions.includes(file)) {
const content = await fs.readFileSync(path.join(dir, file), 'utf8');
const lines = content.split('\n');
params.versions.push(file);
for (const line of lines) {
if (line) {
queries.push(line);
}
}
console.log(`VERSION APPLICATOR APPLYING: ${file}`);
} else {
console.log(`VERSION APPLICATOR SKIPPED: ${file}`);
}
}
return queries;
};
exports.apply = async (params) => {
console.log('APPLYING VERSIONS');
const driver = await connection.getDriver(params.neo4jConfig);
const session = await driver.session();
const dir = path.join(process.cwd(), params.versionsDirectory);
const files = sorter.sortFiles(await fs.readdirSync(dir), '.txt');
const queries = await _getQueriesFromFiles(params, dir, files);
await _runQueries(params, queries, session);
await _recordVersion(params, session);
await session.close();
};
|
var Sky = require("./sky");
var Vector = require("./vector");
var extend = require("./utils").extend;
global.emojiBoids = emojiBoids;
/**
*
*/
function emojiBoids(selector, options) {
/**
* Options include
* - Emoji subset
* - Turns ... TODO
* - Interval (ms)
* - Pizza
*/
selector = selector || "body";
var container = document.querySelector(selector),
containerDims = container.getBoundingClientRect();
var sky,
defaults = {
emojis: ["🍕"],
boids: 120,
flockTo: new Vector(containerDims.width/2, containerDims.height/2),
interval: 210,
turns: null,
xMin: 0,
xMax: containerDims.width,
yMin: 0,
yMax: containerDims.height,
};
options = extend({}, defaults, options);
sky = new Sky(container, options);
if (options.turns) {
sky.moveBoids();
} else {
setInterval(function() {
sky.moveBoids();
}, options.interval);
}
return {
sky: sky,
};
}
|
/**
* @license
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('shaka.test.MemoryDBEngine');
/**
* An in-memory version of the DBEngine. This is used to test the behavior of
* Storage using a fake DBEngine.
*
* @constructor
* @struct
* @extends {shaka.offline.DBEngine}
*/
shaka.test.MemoryDBEngine = function() {
/** @private {Object.<string, !Object.<number, *>>} */
this.stores_ = null;
/** @private {Object.<string, number>} */
this.ids_ = null;
};
/**
* Returns the data for the given store name, synchronously.
*
* @param {string} storeName
* @return {!Object.<number, *>}
*/
shaka.test.MemoryDBEngine.prototype.getAllData = function(storeName) {
return this.getStore_(storeName);
};
/** @override */
shaka.test.MemoryDBEngine.prototype.initialized = function() {
return this.stores_ != null;
};
/** @override */
shaka.test.MemoryDBEngine.prototype.init = function(storeMap) {
this.stores_ = {};
this.ids_ = {};
for (var storeName in storeMap) {
goog.asserts.assert(storeMap[storeName] == 'key', 'Key path must be "key"');
this.stores_[storeName] = {};
this.ids_[storeName] = 0;
}
return Promise.resolve();
};
/** @override */
shaka.test.MemoryDBEngine.prototype.destroy = function() {
this.stores_ = null;
this.ids_ = null;
return Promise.resolve();
};
/** @override */
shaka.test.MemoryDBEngine.prototype.get = function(storeName, key) {
return Promise.resolve(this.getStore_(storeName)[key]);
};
/** @override */
shaka.test.MemoryDBEngine.prototype.forEach = function(storeName, callback) {
shaka.util.MapUtils.values(this.getStore_(storeName)).forEach(callback);
return Promise.resolve();
};
/** @override */
shaka.test.MemoryDBEngine.prototype.insert = function(storeName, value) {
var store = this.getStore_(storeName);
goog.asserts.assert(!store[value.key], 'Value must not already exist');
store[value.key] = value;
return Promise.resolve();
};
/** @override */
shaka.test.MemoryDBEngine.prototype.remove = function(storeName, key) {
var store = this.getStore_(storeName);
delete store[key];
return Promise.resolve();
};
/** @override */
shaka.test.MemoryDBEngine.prototype.removeKeys = function(storeName,
keys,
opt_onKeyRemoved) {
var store = this.getStore_(storeName);
for (var key in store) {
key = Number(key);
if (keys.indexOf(key) >= 0) {
delete store[key];
}
}
return Promise.resolve();
};
/** @override */
shaka.test.MemoryDBEngine.prototype.reserveId = function(storeName) {
goog.asserts.assert(this.ids_, 'Must not be destroyed');
goog.asserts.assert(storeName in this.ids_,
'Store ' + storeName + ' must appear in init()');
return this.ids_[storeName]++;
};
/**
* @param {string} storeName
* @return {!Object.<number, *>}
* @private
*/
shaka.test.MemoryDBEngine.prototype.getStore_ = function(storeName) {
goog.asserts.assert(this.stores_, 'Must not be destroyed');
goog.asserts.assert(storeName in this.stores_,
'Store ' + storeName + ' must appear in init()');
return this.stores_[storeName];
};
|
/**
* Created by zhualex on 16/2/8.
*/
$(function(){
$('#login_btn_submit').click(function(){
//提交登陆:
var account_id=$('#account_id').val();
var password=$('#password').val();
var img_verity=$('#img_verity').val();
if ($.trim(account_id).length<1 ){
alert('账号名、密码不能为空');
return false;
}else if($.trim(password).length<1){
alert('密码不能为空');
return false;
}
else if($.trim(img_verity).length<1){
alert('验证码不能为空');
return false;
}
else{
$('#login_form').submit();
return true;
}
})
})
|
import React, { useState, useEffect } from "react";
import hero from "../../assets/hero.jpg";
import { FcGoogle } from "react-icons/fc";
import axios from "axios";
import { createHashHistory } from "history";
import AddForm from '../Home/AddPaper';
import { BrowserRouter as Router, Redirect } from "react-router-dom";
const Register = () => {
const [username, setUsername] = useState();
const [email, setEmail] = useState();
const [error, setError] = useState();
const [password, setPassword] = useState();
const [_error, errRes] = useState("");
const history = createHashHistory();
const [isRegistered, setRegister] = useState(false);
const handleUsername = (e) => {
setUsername(e.target.value);
};
const handleEmail = (e) => {
setEmail(e.target.value);
};
const handlePassword = (e) => {
setPassword(e.target.value);
};
const handleSubmit = async (e) => {
e.preventDefault();
const data = {
username: username,
email: email,
password: password,
};
if (!username || !email || !password) {
errRes("Please fill in all the fields!");
} else {
const reg_URL = "http://127.0.0.1:8000/auth/register";
await axios
.post(reg_URL, data)
.then((response) => {
const login_result = response;
console.log(login_result.data);
history.go("/login");
setRegister(true)
})
.catch((error) => {
setError(error.response.data);
console.log(error.response.data);
if (error.response.data) {
errRes("Username or email already exist!");
}
})
.then(() => {
// always executed
});
}
};
return (
<div>
{isRegistered ?
<Redirect to="/login"/> :
<form id="add-form" onSubmit={handleSubmit}>
<img className="pull-right" src={hero} alt="" />
<h2>Welcome</h2>
<p>Register an Account</p>
<p className="error">{_error}</p>
<div id="add-form-group">
<input
type="text"
id="add-form-control"
placeholder="Enter name"
onChange={handleUsername}
/>
</div>
<div id="add-form-group">
<input
type="email"
id="add-form-control"
placeholder="Enter email"
onChange={handleEmail}
/>
</div>
<div id="add-form-group">
<input
type="password"
id="add-form-control"
placeholder="Enter password"
onChange={handlePassword}
/>
</div>
<button className="btn btn-primary" id="add-btn" type="submit">
Register
</button>
<div class="or"> OR </div>
<a href="#" id="add-btn-google">
<FcGoogle id="google-icon" />
Signup with google
</a>
</form>
}
</div>
);
};
export default Register;
|
// module untuk pairing clock-clock per orang per hari
let ClockPairing = (function() {
let telat5;
let telat15;
let tidakClockOut;
function _toMiliSeconds(time) {
let timeParts = time.split(":");
let h = timeParts[0] ? +timeParts[0] * 60 * 60 * 1000 : 0;
let m = timeParts[1] ? +timeParts[1] * 60 * 1000 : 0;
let s = timeParts[2] ? +timeParts[2] * 1000 : 0;
return h + m + s;
}
function _toHHMMSS(milliseconds) {
let h = Math.floor(milliseconds/(60*60*1000));
milliseconds %= (60*60*1000);
let m = Math.floor(milliseconds/(60*1000));
milliseconds %= (60*1000);
let s = Math.floor(milliseconds/(1000));
return `${h}:${m}:${s}`;
}
//clocks adalah array of moment object
function _getClockPairs(clocks) {
if (!clocks || clocks.length === 0) return null;
//sort ascending
clocks.sort((a, b) => a.valueOf() - b.valueOf());
let currentClock = clocks[0]; //clock valid pertama
let validClocks = [currentClock];
//cari semua clock valid
for (let i = 1; i < clocks.length; i++) {
//apabila selisih lebih dari 15 menit (dalam milliseconds), berarti valid
if (clocks[i].diff(currentClock) > 15 * 60 * 1000) {
currentClock = clocks[i];
validClocks.push(clocks[i]);
}
}
//pairing semua clock valid
let clockPairs = [];
for (let i = 0; i < validClocks.length; i += 2) {
if (!validClocks[i + 1]) { //kalau tidak punya pasangan sign out
clockPairs.push({
clockIn: validClocks[i],
clockOut: null,
duration: 0
});
} else { //kalo pasangan absensi lengkap/rapi
clockPairs.push({
clockIn: validClocks[i],
clockOut: validClocks[i + 1],
duration: moment.utc(validClocks[i + 1].diff(validClocks[i]))
});
}
}
return clockPairs;
}
function _getAttendancePairs(attendances) {
if (!attendances || attendances.length === 0) return null;
for (let i = 0; i < attendances.length; i++) attendances[i].date = moment(attendances[i].date);
//sort ascending
attendances.sort((a, b) => a.date.valueOf() - b.date.valueOf());
let currentAttendance = attendances[0]; //clock valid pertama
let validAttendances = [currentAttendance];
//cari semua clock valid
for (let i = 1; i < attendances.length; i++) {
//apabila selisih lebih dari 15 menit (dalam milliseconds), berarti valid
if (attendances[i].date.diff(currentAttendance.date) > 15 * 60 * 1000) {
currentAttendance = attendances[i];
validAttendances.push(attendances[i]);
}
}
//pairing semua clock valid
let attendancePairs = [];
for (let i = 0; i < validAttendances.length; i += 2) {
if (!validAttendances[i + 1]) { //kalau tidak punya pasangan sign out
attendancePairs.push({
attendanceIn: validAttendances[i],
attendanceOut: null,
duration: 0
});
} else { //kalo pasangan absensi lengkap/rapi
attendancePairs.push({
attendanceIn: validAttendances[i],
attendanceOut: validAttendances[i + 1],
duration: moment.utc(validAttendances[i + 1].date.diff(validAttendances[i].date))
});
}
}
return attendancePairs;
}
function _produceFlag(color, content, tooltipMsg) {
return `<span data-toggle="tooltip" data-placement="right" title="${tooltipMsg}" style="color:white; background:${color};">${content}</span>`;
}
function _clockValidatorFactory(pRanges, color, tooltipMsg) {
let newClockValidator = function (clock) {
let ranges = pRanges;
for (let range of ranges) {
// kalau ada yang match, return clock nya aja
if (_toMiliSeconds(range[0]) <= _toMiliSeconds(clock) && _toMiliSeconds(clock) <= _toMiliSeconds(range[1])) {
return clock;
}
}
return _produceFlag(color, clock, tooltipMsg);
}
return newClockValidator;
};
function _DTTFirstClockValidatorFactory(inClocks, tolerance, beforeColor, afterColor) {
return function(myClock) {
let myClockMs = _toMiliSeconds(myClock);
let inClocksMs = inClocks.map(clock => _toMiliSeconds(clock));
let toleranceMs = _toMiliSeconds(tolerance);
let closestClockMs = -1, closestGap = 48*60*60*1000;
for (let i = 0; i < inClocksMs.length; i++) {
let currentGap = Math.abs(myClockMs - inClocksMs[i]);
if (currentGap < closestGap) {
closestClockMs = inClocksMs[i];
closestGap = currentGap;
}
}
let clockInTime, telat5 = false;
if (closestClockMs - toleranceMs <= myClockMs && myClockMs <= closestClockMs + toleranceMs) {
clockInTime = myClock;
} else if (myClockMs < closestClockMs) {
clockInTime = _produceFlag(beforeColor, myClock, 'DTT sebelum 15 menit');
} else if (myClockMs > closestClockMs) {
clockInTime = _produceFlag(afterColor, myClock, 'DTT setelah 15 menit');
}
if (myClockMs > closestClockMs && closestClockMs - myClockMs > 5*60*1000) {
telat5 = true;
}
return {
clockInTime: clockInTime,
telat5: telat5
};
};
}
function _produceFlagManualClock(attendance) {
if (attendance.type && attendance.type === 'manual') {
return _produceFlag('orange', attendance.date.format('HH:mm:ss'), 'manual clock');
}
return null;
}
function _getFlaggedClockPairs(paramAttendancePairs, options) {
if (!paramAttendancePairs || !paramAttendancePairs.length) return '-';
let attendancePairs = paramAttendancePairs.slice();
let attendancePairsDisplay = '';
if (['Dosen Tidak Tetap'].includes(options.department.trim())) { // jika Dosen Tidak Tetap
// let validateClockInRange = _clockValidatorFactory([["08:45", "09:15"], ["17:15", "17:45"]], "rgb(244,72,66)");
let validateClockInRange = _DTTFirstClockValidatorFactory(['09:00', '17:30'], '00:15', 'rgb(44, 116, 232)', 'rgb(244,72,66)');
let validateClockOutRange = _clockValidatorFactory([["12:15", "12:45"], ["20:45", "21:15"]], "rgb(244,72,66)", "DTT ClockOut diluar Range");
let validateDurationRange = _clockValidatorFactory([[options.dosenTidakTetapMaxTime, "23:59"]], "rgb(173,244,66)", "DTT > 3.5 jam");
attendancePairsDisplay = attendancePairs.reduce((acc, cur) => {
let validationResult = validateClockInRange(cur.attendanceIn.date.format("HH:mm:ss"));
let clockInTime = _produceFlagManualClock(cur.attendanceIn) || validationResult.clockInTime;
telat5 = telat5 || validationResult.telat5;
let clockOutTime = cur.attendanceOut ?
(_produceFlagManualClock(cur.attendanceOut) || validateClockOutRange(cur.attendanceOut.date.format("HH:mm:ss"))) : _produceFlag('orange', '[empty]', 'incomplete clock');
let durationTime = cur.duration ? `(${ validateDurationRange(cur.duration.format("HH:mm:ss")) })` : '';
return acc + `${clockInTime} - ${clockOutTime} ${durationTime}<br><br>`
}, '');
} else if (options.jamMasuk) { // terdapat jam masuk
// let jamMasukToleransi = moment.utc(options.jamMasuk, 'HH:mm:ss').add(15,'minutes');
// let validateJamMasuk15 = _clockValidatorFactory([["00:00", jamMasukToleransi.format('HH:mm:ss')]], "rgb(244,72,66)");
let batasJamMasukToleransi5Ms = _toMiliSeconds(options.jamMasuk) + _toMiliSeconds('00:05:00');
let batasJamMasukToleransi15Ms = _toMiliSeconds(options.jamMasuk) + _toMiliSeconds('00:15:00');
let validateJamMasuk5 = _clockValidatorFactory([["00:00", _toHHMMSS(batasJamMasukToleransi5Ms)]], "rgb(244,72,66)", 'Telat 5 menit');
let validateJamMasuk15 = _clockValidatorFactory([["00:00", _toHHMMSS(batasJamMasukToleransi15Ms)]], "rgb(244,72,66)", 'Telat 15 menit');
attendancePairsDisplay = (cur => {
// assign status telat
if (!['Dosen Tidak Tetap', 'Mahasiswa Magang'].includes(options.department.trim())) {
if (validateJamMasuk5(cur.attendanceIn.date.format("HH:mm:ss")).length > 8) telat5 = true;
if (validateJamMasuk15(cur.attendanceIn.date.format("HH:mm:ss")).length > 8) telat15 = true;
}
let clockInTime =
_produceFlagManualClock(cur.attendanceIn) || validateJamMasuk15(cur.attendanceIn.date.format("HH:mm:ss"));
let clockOutTime = cur.attendanceOut ?
(_produceFlagManualClock(cur.attendanceOut) || cur.attendanceOut.date.format("HH:mm:ss")) : _produceFlag('orange', '[empty]', 'incomplete clock');
let durationTime = cur.duration ? `(${cur.duration.format("HH:mm:ss")})` : '';
return `${clockInTime} - ${clockOutTime} ${durationTime}<br><br>`
})(attendancePairs[0]);
attendancePairs.shift();
attendancePairsDisplay += attendancePairs.reduce((acc, cur) => {
let clockInTime = _produceFlagManualClock(cur.attendanceIn) || cur.attendanceIn.date.format("HH:mm:ss");
let clockOutTime = cur.attendanceOut ?
(_produceFlagManualClock(cur.attendanceOut) || cur.attendanceOut.date.format("HH:mm:ss")) : _produceFlag('orange', '[empty]', 'incomplete clock');
let durationTime = cur.duration ? `(${cur.duration.format("HH:mm:ss")})` : '';
return acc + `${clockInTime} - ${clockOutTime} ${durationTime}<br><br>`
}, '');
} else { // tidak ketentuan khusus
attendancePairsDisplay = attendancePairs.reduce((acc, cur) => {
let clockInTime = _produceFlagManualClock(cur.attendanceIn) || cur.attendanceIn.date.format("HH:mm:ss");
let clockOutTime = cur.attendanceOut ?
(_produceFlagManualClock(cur.attendanceOut) || cur.attendanceOut.date.format("HH:mm:ss")) : _produceFlag('orange', '[empty]', 'incomplete clock');
let durationTime = cur.duration ? `(${cur.duration.format("HH:mm:ss")})` : '';
return acc + `${clockInTime} - ${clockOutTime} ${durationTime}<br><br>`
}, '');
}
return attendancePairsDisplay;
}
function _getTotalWorkingTime(clockPairs, options) {
if (!clockPairs || !clockPairs.length) return '00:00:00';
let totalWorkingTime;
if (['Dosen Tidak Tetap'].includes(options.department.trim())) { // jika Dosen Tidak Tetap
totalWorkingTime = moment.utc(clockPairs.reduce(
(acc, cur) =>
acc + Math.min(_toMiliSeconds(options.dosenTidakTetapMaxTime), cur.duration.valueOf()), 0))
.format("HH:mm:ss");
} else {
totalWorkingTime = moment.utc(clockPairs.reduce(
(acc, cur) => acc + cur.duration.valueOf(), 0)).format("HH:mm:ss");
}
return totalWorkingTime;
}
function _getFlaggedTotalWorkingTime(clockPairs, options) {
if (!clockPairs || !clockPairs.length) return '00:00:00';
let totalWorkingTime = _getTotalWorkingTime(clockPairs, options);
let flaggedTotalWorkingTime = totalWorkingTime;
if (['Sunday', 'Saturday'].includes(clockPairs[0].clockIn.format('dddd'))) {
let validateDuration = _clockValidatorFactory([['02:00', '23:59']], 'rgb(173,244,66)', 'Weekend < 2 jam');
flaggedTotalWorkingTime = validateDuration(totalWorkingTime);
} else if (['Dosen Tidak Tetap', 'Mahasiswa Magang'].includes(options.department.trim())) { // jika Pegawai Tidak Tetap
flaggedTotalWorkingTime = totalWorkingTime;
} else { // jika Pegawai Tetap
if (clockPairs.length == 1) {
let validateDuration = _clockValidatorFactory([['09:00', '23:59']], 'rgb(173,244,66)', 'Karyawan Tetap < 9 jam');
flaggedTotalWorkingTime = validateDuration(totalWorkingTime);
} else if (clockPairs.length >= 2) {
let validateDuration = _clockValidatorFactory([['08:00', '23:59']], 'rgb(173,244,66)', 'Karyawan Tetap < 8 jam');
flaggedTotalWorkingTime = validateDuration(totalWorkingTime);
}
}
return flaggedTotalWorkingTime;
}
function process(attendances, options) {
telat5 = false;
telat15 = false;
tidakClockOut = false;
let clocks = attendances.map(att => moment(att.date));
let clockPairs = _getClockPairs(clocks);
let attendancePairs = _getAttendancePairs(attendances);
let flaggedClockPairs = _getFlaggedClockPairs(attendancePairs, options);
let totalWorkingTime = _getTotalWorkingTime(clockPairs, options);
let flaggedTotalWorkingTime = _getFlaggedTotalWorkingTime(clockPairs, options);
if (clockPairs && !clockPairs[clockPairs.length-1].clockOut) tidakClockOut = true;
let totalSesi = 0;
if (clockPairs) {
totalSesi = clockPairs.length;
if (tidakClockOut) totalSesi -= 1;
}
return {
clockPairs: clockPairs,
flaggedClockPairs: flaggedClockPairs,
totalWorkingTime: totalWorkingTime,
flaggedTotalWorkingTime: flaggedTotalWorkingTime,
telat5: telat5,
telat15: telat15,
tidakClockOut: tidakClockOut,
totalSesi: totalSesi
};
}
return {
process: process
};
})();
|
// web.js
var express = require("express");
logfmt = require("logfmt");
fs = require("fs");
hbs = require("express3-handlebars").create();
publications = require("./routes/publications.js");
var app = express();
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
app.use(function(error, req, res, next) { res.send('500: Internal Server Error', 500); });
});
app.use(logfmt.requestLogger());
app.configure(function(){
app.use(logfmt.requestLogger());
app.use(express.json());
app.use("/", express.static(__dirname+"/public"));
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
// add other things to serve here
});
app.get('/', function (req, res, next) { res.render('index',{}); });
app.get('/publications/', publications.getPapers);
app.use(function(req, res) { res.send('404: Page not Found', 404); });
var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
console.log("Listening on " + port);
});
|
const isProduction = process.env.NODE_ENV === 'production';
module.exports = Object.freeze({
PRODUCTION: isProduction,
AUTH_CODE_LIFE: 10 * 60 * 1000, // 10 min
ACCESS_TOKEN_LIFE: 60 * 60 * 1000, // 1h
REFRESH_TOKEN_LIFE: 24 * 60 * 60 * 1000, // 1d
SESSION_SECRET: isProduction ? process.env.SESSION_SECRET : 'secret',
COOKIE_SECRET: isProduction ? process.env.COOKIE_SECRET : 'cookie_secret'
});
|
var cheerio = require('cheerio');
exports.kuwo = {
searchUrl: 'http://sou.kuwo.cn/ws/NSearch',
songUrl: 'http://antiserver.kuwo.cn/anti.s?format=mp3|aac&type=convert_url&response=url',
parse: function(body, key, pn) {
var $ = cheerio.load(body),
$list = $('.m_list ul li'),
$page = $('.page'),
list = [];
$list.each(function(i, el) {
var $this = $(el);
list.push({
id: 'MUSIC_'+parseInt($this.find('input[name="musicNum"]').val()),
name: $this.find('.m_name a').attr('title'),
album: $this.find('.a_name a').attr('title'),
singer: $this.find('.s_name a').attr('title')
});
});
$page.find('a').each(function(i, el) {
var $this = $(el),
href = $this.attr('href');
if (href !== '#@') {
var num = href.split('=').reverse()[0];
$this.attr('data-option', JSON.stringify({
key: key,
pn: num
}));
}
$this.attr('href', 'javascript:;');
});
return {
page: $page.html(),
list: list
};
}
};
exports.list = {
LisUrl:'http://www.kuwo.cn/?catalog=yueku2016',
baseUrl:'http://www.kuwo.cn',
parse:function(body){
var $ = cheerio.load(body),
lis=$('#song ul li'),
list=[];
lis.each(function(i, el) {
var $this = $(el);
var src='http://www.kuwo.cn'+$this.find('.name a').attr('href')
list.push({
href:src,
id:src.split('?')[1].split('=')[1],
img:$this.find('.cover img').attr('data-src'),
num:$this.find('em').text(),
name:$this.find('.name a').text()
});
});
return {
list:list
}
}
}
exports.paihang={
url:'http://www.kuwo.cn/bang/index',
parse:function(body){
var $ = cheerio.load(body),
lis=$('#chartsContent .leftNav .classify ul li'),
list=[];
lis.each(function(index,item){
var $this = $(item);
list.push({
name:$this.attr('data-name'),
img:$this.find('img').attr('src')
})
})
return {
paihang:list
}
}
}
exports.bangs={
baseUrl:'http://www.kuwo.cn/bang/content?name=',
parse:function(body,count,start){
var $ = cheerio.load(body),
banner=$('.banner img').attr('src'),
lis=$('.listMusic li'),
result='',
banner='',
list=[];
lis.each(function(index,item){
var $this=$(item);
list.push({
num:$this.find('.num').text(),
name:$this.find('.name a').text(),
src:$this.find('.name a').attr('href'),
singer:$this.find('.artist a').text(),
album:JSON.parse($this.find('.tools').attr('data-music')).album,
id:JSON.parse($this.find('.tools').attr('data-music')).id
})
})
result=list.splice(start,count);
banner=$('.banner img').attr('src');
return {
list:result,
banner:banner
}
}
}
exports.tuijian={
baseUrl:'http://www.kuwo.cn/playlist/content?pid=',
parse:function(body,count,start,id){
var $=cheerio.load(body),
title='',
tits=$('.leftNav ul li'),
lis=$('.listMusic li'),
titles=[],
list=[];
tits.each(function(index,item){
var $this=$(item);
titles.push({
id:$this.find('.name').attr('data-id'),
title:$this.find('.name').text()
})
})
for(var i=0;i<titles.length;i++){
if(titles[i].id===id){
title=titles[i].title;
}
}
lis.each(function(index,item){
var $this=$(item);
list.push({
num:$this.find('.num').text(),
name:$this.find('.name a').text(),
singer:$this.find('.artist a').text(),
album:JSON.parse($this.find('.tools').attr('data-music')).album,
id:JSON.parse($this.find('.tools').attr('data-music')).id
})
})
result=list.splice(start,count);
return {
title:title,
list:result
}
}
}
|
import React from 'react';
import CartItem from '../cart-item/';
import {selectcartItems} from '../../store/cart/cart.selectors.js';
import {closecart} from '../../store/cart/cart.actions.js';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import {createStructuredSelector} from 'reselect';
import { bindActionCreators } from 'redux';
import {useOutsideClick} from '../../effects/';
import PropTypes from 'prop-types';
import {
CartDropdownContainer,
CartDropdownButton,
EmptyMessageContainer,
CartItemsContainer
} from './cart-dropdown.styles';
const MODAL_CLASS_NAME = 'modalContainer';
const CartDropdown = ({cartItems, history, closecart}) => {
const outsideClickEffect = useOutsideClick(MODAL_CLASS_NAME, closecart)
return (
<CartDropdownContainer className={MODAL_CLASS_NAME}>
<CartItemsContainer>
{
cartItems.length ?
cartItems.map(item => <CartItem key={item.id} item={item}/>)
:<EmptyMessageContainer>your cart is empty</EmptyMessageContainer>
}
</CartItemsContainer>
<CartDropdownButton
onClick={() => {
history.push('/checkout');
closecart();
}}
>
go to checkout
</CartDropdownButton>
</CartDropdownContainer>
)
}
const mapStateToProps = createStructuredSelector({
cartItems: selectcartItems
});
const mapDispatchToProps = dispatch => bindActionCreators({closecart}, dispatch)
CartDropdown.propTypes = {
cartItems: PropTypes.array,
history: PropTypes.object,
closecart: PropTypes.func.isRequired
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(CartDropdown));
|
/// <reference path="../../lib/jquery-1.11.3.js" />
/// <reference path="../../lib/Q.mini.js" />
/*
* Q.UI.adapter.jquery.js
* author:devin87@qq.com
* update:2017/12/25 13:44
*/
(function (undefined) {
"use strict";
var window = Q.G,
isFunc = Q.isFunc,
isObject = Q.isObject,
isArrayLike = Q.isArrayLike,
extend = Q.extend,
makeArray = Q.makeArray,
view = Q.view;
//---------------------- event.js ----------------------
function stop_event(event, isPreventDefault, isStopPropagation) {
var e = new jQuery.Event(event);
if (isPreventDefault !== false) e.preventDefault();
if (isStopPropagation !== false) e.stopPropagation();
}
jQuery.Event.prototype.stop = function () {
stop_event(this);
};
var SUPPORT_W3C_EVENT = !!document.addEventListener;
//添加DOM事件,未做任何封装
function addEvent(ele, type, fn) {
if (SUPPORT_W3C_EVENT) ele.addEventListener(type, fn, false);
else ele.attachEvent("on" + type, fn); //注意:fn的this并不指向ele
}
//移除DOM事件
function removeEvent(ele, type, fn) {
if (SUPPORT_W3C_EVENT) ele.removeEventListener(type, fn, false);
else ele.detachEvent("on" + type, fn);
}
//添加事件
function add_event(ele, type, selector, fn, once, stops) {
var handle = fn;
if (once) {
handle = function (e) {
fn.call(this, e);
$(ele).off(type, selector, handle);
};
}
$(ele).on(type, selector, handle);
if (!once) stops.push([ele, type, handle, selector]);
}
//批量添加事件
//types:事件类型,多个之间用空格分开;可以为对象
//selector:要代理的事件选择器或处理句柄
function add_events(elements, types, selector, handle, once) {
if (typeof types == "string") {
types = types.split(' ');
if (isFunc(selector)) {
once = once || handle;
handle = selector;
selector = undefined;
}
} else {
if (selector === true || handle === true) once = true;
if (selector === true) selector = undefined;
}
var stops = [];
makeArray(elements).forEach(function (ele) {
if (isArrayLike(types)) {
makeArray(types).forEach(function (type) {
add_event(ele, type, selector, handle, once, stops);
});
} else if (isObject(types)) {
Object.forEach(types, function (type, handle) {
add_event(ele, type, selector, handle, once, stops);
});
}
});
//返回移除事件api
return {
es: stops,
off: function (types, selector) {
remove_events(stops, types, selector);
}
};
}
//批量移除事件
//es:事件句柄对象列表 eg:es => [[ele, type, handle, selector],...]
function remove_events(es, types, selector) {
es.forEach(function (s) {
$(s[0]).off(s[1], s[3], s[2]);
});
}
//批量添加事件,执行一次后取消
function add_events_one(elements, types, selector, handle) {
return add_events(elements, types, selector, handler, true);
}
Q.event = {
fix: function (e) {
return new jQuery.Event(e);
},
stop: stop_event,
trigger: function (el, type) {
$(el).trigger(type);
},
//原生事件添加(建议使用add)
addEvent: addEvent,
//原生事件移除
removeEvent: removeEvent,
//添加事件,并返回操作api
add: add_events,
//注意:批量移除事件,与一般事件移除不同;移除事件请使用add返回的api
removeEs: remove_events,
one: add_events_one
};
//---------------------- dom.js ----------------------
//var _parseFloat = parseFloat;
//当元素的css值与要设置的css值不同时,设置css
function setCssIfNot(el, key, value) {
var $el = $(el);
if (el && $el.css(key) != value) $el.css(key, value);
}
//创建元素
function createEle(tagName, className, html) {
var el = document.createElement(tagName);
if (className) el.className = className;
if (html) el.innerHTML = html;
return el;
}
//动态创建样式
function createStyle(cssText) {
var style = document.createElement("style");
style.type = "text/css";
style.styleSheet && (style.styleSheet.cssText = cssText) || style.appendChild(document.createTextNode(cssText));
Q.head.appendChild(style);
return style;
}
//解析html为元素,默认返回第一个元素节点
//all:是否返回所有节点(childNodes)
function parseHTML(html, all) {
var _pNode = createEle("div", undefined, html);
return all ? _pNode.childNodes : Q.getFirst(_pNode);
}
//移除指定内联样式
function removeCss(el, key) {
var cssText = el.style.cssText;
if (cssText) el.style.cssText = cssText.drop(key + "(-[^:]+)?\\s*:[^;]*;?", "gi").trim();
}
//将输入框样式设为错误模式
//value:重置后输入框的值,默认为空字符串
function setInputError(input, hasBorder, value) {
if (hasBorder) input.style.borderColor = "red";
else input.style.border = "1px solid red";
input.value = value || "";
input.focus();
}
//恢复输入框默认样式
function setInputDefault(input) {
removeCss(input, "border");
}
var NODE_PREV = "previousSibling",
NODE_NEXT = "nextSibling",
NODE_FIRST = "firstChild",
NODE_LAST = "lastChild";
//遍历元素节点
function walk(el, walk, start, all) {
var el = el[start || walk];
var list = [];
while (el) {
if (el.nodeType == 1) {
if (!all) return el;
list.push(el);
}
el = el[walk];
}
return all ? list : null;
}
var DEF_OFFSET = { left: 0, top: 0 };
extend(Q, {
camelCase: $.camelCase,
attr: function (el, key, value) {
return $(el).attr(key, value);
},
prop: function (el, key, value) {
return $(el).prop(key, value);
},
width: function (el, w) {
return $(el).width(w);
},
height: function (el, h) {
return $(el).height(h);
},
getStyle: function (el, key) {
return $(el).css(key);
},
setStyle: function (el, key, value) {
if (value === null) return removeCss(el, key);
$(el).css(key, value);
},
setOpacity: function (el, value) {
return $(el).css("opacity", value);
},
removeCss: removeCss,
css: function (el, key, value) {
return $(el).css(key, value);
},
show: function (el) {
$(el).show();
},
hide: function (el) {
$(el).hide();
},
toggle: function (el) {
$(el).toggle();
},
isHidden: function (el) {
return $(el).is(":hidden");
},
offset: function (el, x, y) {
var $el = $(el);
if (x === undefined && y === undefined) {
var offset = $el.offset();
offset.width = $el.outerWidth();
offset.height = $el.outerHeight();
return offset;
}
setCssIfNot(el, "position", "absolute");
if (x !== undefined) $el.css("left", x);
if (y !== undefined) $el.css("top", y);
},
//getPos: function (el, pNode) {
// if (!pNode) pNode = el.offsetParent;
// var $el = $(el),
// $pl = $(pNode),
// offset = $el.offset(),
// poffset = $pl.offset();
// offset.left -= poffset.left + _parseFloat($pl.css("borderLeftWidth")) + _parseFloat($el.css("marginLeft"));
// offset.top -= poffset.top + _parseFloat($pl.css("borderTopWidth")) + _parseFloat($el.css("marginTop"));
// return offset;
//},
setCssIfNot: setCssIfNot,
setCenter: function (el, onlyPos) {
setCssIfNot(el, "position", "absolute");
var size = view.getSize(),
offset = $(el.offsetParent).offset() || DEF_OFFSET,
left = Math.round((size.width - $(el).outerWidth()) / 2) - offset.left + view.getScrollLeft(),
top = Math.round((size.height - $(el).outerHeight()) / 2) - offset.top + view.getScrollTop(),
pos = { left: Math.max(left, 0), top: Math.max(top, 0) };
return onlyPos ? pos : $(el).css(pos);
},
getFirst: function (el) {
return el.firstElementChild || walk(el, NODE_NEXT, NODE_FIRST, false);
},
getLast: function (el) {
return el.lastElementChild || walk(el, NODE_PREV, NODE_LAST, false);
},
getPrev: function (el) {
return el.previousElementSibling || walk(el, NODE_PREV, null, false);
},
getNext: function (el) {
return el.nextElementSibling || walk(el, NODE_NEXT, null, false);
},
getChilds: function (el) {
//walk方式性能要好于通过childNodes筛选
return el.children ? makeArray(el.children) : walk(el, NODE_NEXT, NODE_FIRST, true);
},
findTag: function (el, tagName) {
while (el && el.tagName != "BODY") {
if (el.tagName == tagName) return el;
el = el.parentNode;
}
},
createEle: createEle,
createStyle: createStyle,
parseHTML: parseHTML,
removeEle: function (el) {
$(el).remove();
},
hasClass: function (el, clsName) {
return $(el).hasClass(clsName);
},
addClass: function (el, clsName) {
$(el).addClass(clsName);
},
removeClass: function (el, clsName) {
$(el).removeClass(clsName);
},
replaceClass: function (el, oldName, clsName) {
$(el).removeClass(oldName).addClass(clsName);
},
toggleClass: function (el, clsName) {
$(el).toggleClass(clsName);
},
setInputError: setInputError,
setInputDefault: setInputDefault
});
window.$$ = Q.query = $.find;
})();
|
// BEGIN-SNIPPET dynamic-data-immutable.js
import Component from "@ember/component";
import { action } from "@ember/object";
export default class DynamicDataImmutableObjectsComponent extends Component {
tagName = "";
bars = [
{ id: 1, value: 100 },
{ id: 2, value: 50 },
{ id: 3, value: 70 },
];
@action updateBar(updatedIndex, inputEvent) {
const newValue = parseInt(inputEvent.target.value, 10);
this.set(
"bars",
this.bars.map((item, index) => {
if (updatedIndex === index) {
return { id: item.id, value: newValue };
} else {
return item;
}
})
);
}
}
// END-SNIPPET
|
import React, {Component} from 'react';
import { connect } from 'react-redux';
class Intro extends Component {
state = {
animateOut: false
}
intervals = [];
componentDidMount() {
this.intervals.push(setTimeout(() => {
this.setState({animateOut: true});
}, 4800));
if (this.props.isHost) {
this.intervals.push(setTimeout(() => {
this.props.nextScreen();
}, 5500));
}
}
componentWillUnmount() {
this.intervals.forEach(clearInterval);
}
render() {
return <div className="center-screen no-scroll">
<div className={`intro column${this.state.animateOut ? ' slide-down': ''}`}>
<div className="welcome slide-in-from-left">Welcome to</div>
<div className="title slide-in-from-right">Story Time!</div>
<div className="description fade-in">Players will take turns writing the next line of the story and voting for which line gets added.</div>
</div>
</div>
}
}
function mapStateToProps({ isHost }) {
return { isHost };
}
export default connect(mapStateToProps, null)(Intro);
|
/*
TeventDispatcher
_eventTypes: { type1:[listener1, listener2 ...], type2:[listener1, listener2 ...], ...}
*/
uses("panjs.core.events.Tevent");
__CLASSPATH__="panjs.core.events.TeventDispatcher";
defineClass("TeventDispatcher", "panjs.core.Tobject", {
_listeners: null,
constructor: function(args){
this._listeners = {};
},
free: function(){
this.removeAllListeners();
},
/* params event:Tevent
return Boolean
*/
_getListenerIndex: function(type, listener)
{
if (!this.hasEventListener(type))
return -1;
for (var i=0; i< this._listeners[type].length; i++)
{
if (this._listeners[type][i] != null)
if (this._listeners[type][i].listener == listener)
return i;
}
return -1;
},
dispatchEvent: function(mixed, eventData, bubbles, cancelable)
{
/*mixed = Tevent: {type, eventData, bubbles, cancelable}
or
mixed = {type, eventData, bubbles, cancelable}*/
var type = null;
var event = null;
if (typeof mixed == "object")
{
event = mixed;
type = mixed.type;
}
else{
type = arguments[0];
}
if (!this.hasEventListener(type))
return;
//un objet event n'est créé que si il y a des listeners
if (event == null)
event = new Tevent(type, eventData, bubbles, cancelable);
var listeners = this._listeners[event.type];
for (var i=0; i< listeners.length; i++)
{
if (listeners[i] != null)
{
var list = listeners[i];
if (event.currentTarget == null)
event.currentTarget = this;
event.bind = list.bind;
event.relatedData = list.data;
if (event.bind == null)
list.listener.call(this, event);
else
list.listener.call(event.bind,event);
if (event.cancelled)
break;
}
}
},
/* params type:String, listener:Function
return void
*/
on: function(type, listener, bind, data)
{
if (arguments.length <4 ) var data = null;
if (arguments.length <3 ) var bind = null;
var l = {"listener":listener, "data": data, "bind":bind};
if (!this.hasEventListener(type))
this._listeners[type] = [];
for (var i=0; i< this._listeners[type].length; i++)
{
if (this._listeners[type][i] == null)
{
this._listeners[type][i] = l;
return;
}
}
this._listeners[type].push(l);
},
offByCtx: function(ctx){
for (type in this._listeners)
{
var listeners = this._listeners[type];
for (var i=0; i< listeners.length; i++)
{
if ((listeners[i] != null)&&(listeners[i].bind == ctx))
{
listeners[i] = null;
}
}
}
},
off: function(type, listener)
{
var indx = this._getListenerIndex(type, listener);
if (indx >= 0)
{
this._listeners[type][indx] = null;
}
},
removeAllListeners: function()
{
for (type in this._listeners)
{
this._listeners[type].length = 0;
this._listeners[type] = null;
delete this._listeners[type];
}
},
/* params: type:String
return Boolean
*/
hasEventListener: function(evtType)
{
return (typeof this._listeners[evtType] != "undefined");
}
});
|
/**
* Created by Bram on 4/11/2014.
*/
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var CategorieSchema = new Schema({
naam: {type: String}
//,beginDatum: {type: Date}
//,eindDatum:{type: Date}
});
CategorieSchema.path('naam').required(true, 'Naam mag niet leeg zijn');
//CategorieSchema.path('beginDatum').required(true, 'Begindatum mag niet leeg zijn');
//CategorieSchema.path('eindDatum').required(true, 'Einddatum mag niet leeg zijn');
module.exports = mongoose.model('Categorie', CategorieSchema);
|
var app = angular.module('app', ["ngRoute", 'ngMaterial']);
/**
* Configure the Routes
*/
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
// Home
.when("/", {templateUrl: "vistas/home.html"})
.when("/contact", {templateUrl: "vistas/contact.html"})
// .when("/admin", {templateUrl: "/views/admin.html", controller:"admin"})
// else 404
// .otherwise("/404", {templateUrl: "/angularviews/partials/404.html", controller: "PageCtrl"});
}]);
|
function byId(id){
return typeof id === "string" ?document.getElementById(id):id
}
function byTagName(elem,obj) {
return (obj || document).getElementsByTagName(elem);
}
function byClass(sClass, oParent) {
var aClass = [];
var reClass = new RegExp("(^| )"+sClass+"( |$)");
var aElem = byTagName("*", oParent);
for (var i = 0; i < aElem.length; i++) {
reClass.test(aElem[i].className) && aClass.push(aElem[i]);
};
return aClass;
}
// 面向对象版
function Roll(){
this.initialize.apply(this,arguments)
}
Roll.prototype = {
initialize: function(obj) {
var _this = this;
this.obj = byId(obj);
this.oUp = byClass("up",this.obj)[0];
this.oDown = byClass("down",this.obj)[0];
this.oList = byClass("list",this.obj)[0];
this.aItem = byTagName("li",this.oList);
this.timer = null;
this.iHeight = this.aItem[0].offsetHeight;
this.oUp.onclick = function(){
_this.up()
};
this.oDown.onclick = function(){
_this.down()
}
},
up: function() {
this.oList.insertBefore(this.aItem[this.aItem.length-1],this.oList.firstChild);
this.oList.style.top = -this.iHeight+"px";
this.doMove(0);
},
down: function() {
this.doMove(-this.iHeight,function(){
this.oList.appendChild(this.aItem[0]);
this.oList.style.top = 0;
})
},
doMove: function(iTarget,callBack) {
var _this = this;
clearInterval(this.timer);
this.timer = setInterval(function(){
var iSpeed = (iTarget - _this.oList.offsetTop)/5;
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed):Math.floor(iSpeed);
_this.oList.offsetTop == iTarget ?
(clearInterval(_this.timer), callBack && callBack.apply(_this)):
_this.oList.style.top = iSpeed + _this.oList.offsetTop + "px"
},30)
}
}
window.onload = function(){
new Roll("box");
}
// window.onload = function() {
// var oBox = byId("box");
// var oPrev = byClass("up", oBox)[0];
// var oNext = byClass("down", oBox)[0];
// var oUl = byClass("list", oBox)[0];
// var aLi = byTagName("li", oUl);
// var timer = null;
// var iHeight = aLi[0].offsetHeight;
// oPrev.onclick = function() {
// oUl.insertBefore(aLi[aLi.length-1],oUl.firstChild);
// oUl.style.top = -iHeight + "px";
// doMove(0);
// }
// oNext.onclick = function() {
// doMove(-iHeight, function(){
// oUl.appendChild(aLi[0]);
// oUl.style.top = 0;
// })
// }
// function doMove(iTarget,callBack){
// clearInterval(timer);
// timer = setInterval(function(){
// var iSpeed = (iTarget - oUl.offsetTop) / 5;
// iSpeed = iSpeed > 0 ? Math.ceil(iSpeed):Math.floor(iSpeed);
// oUl.offsetTop == iTarget ?
// (clearInterval(timer),callBack && callBack.apply(this)):
// oUl.style.top = iSpeed + oUl.offsetTop + "px"
// },30)
// }
// }
|
function DashboardCtrl($scope, $rootScope, $http, $modal, $stateParams, SweetAlert, authService, timeAgo, Constants) {
$scope.ShowType = $stateParams.show;
$scope.getRandomInt = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
$rootScope.$on('logon', function (event, args) {
$scope.onload();
});
$rootScope.$on(Constants.Events.ProjectNewProjectAdded, function (event, data) {
$scope.onload();
});
$scope.Projects = [];
$scope.loadProjects = function (show) {
$scope.loading = true;
var projectFilter =
{
FilterBy: 0
};
if (show == 'list')
{
projectFilter.FilterBy = 1;
}
else if (show == 'share') {
projectFilter.FilterBy = 2;
}
else if (show == 'archived')
{
projectFilter.FilterBy = 3;
}
$http.post(Constants.WebApi.Project.GetProjects, projectFilter).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.Projects = response.data.Projects;
$scope.loading = false;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.loading = false;
SweetAlert.swal({
title: "Error!",
text: "Load Project Failed!",
type: "warning"
});
});
}
$scope.onload = function ()
{
if ($scope.ShowType == null)
{
$scope.ShowType = 'list';
}
if (authService.isAuthenticated()) {
$scope.loadProjects($scope.ShowType);
}
}
$scope.setHighlightColor = function (project, color) {
if (project != null) {
var projectDto = {
Id: project.Id,
HighlightColor: color
};
$http.post(Constants.WebApi.Project.SetProjectHighlightColor, projectDto).then(function (response) {
project.User.HighlightColor = color;
$rootScope.$broadcast(Constants.Events.ProjectHighlightColorChanged, projectDto);
}, function (response) {
$scope.loading = false;
SweetAlert.swal({
title: "Error!",
text: "Set project highlight color failed!",
type: "warning"
});
});
}
}
$scope.setFavorite = function (project, isFavorite) {
var projectDto = {
Id: project.Id,
ProjectTitle: project.ProjectTitle,
IsFavorite: isFavorite
};
$http.post(Constants.WebApi.Project.SetProjectFavorite, projectDto).then(function (response) {
project.IsFavorite = isFavorite;
project.User.IsFavorite = isFavorite;
$rootScope.$broadcast(Constants.Events.ProjectFavoriteChanged, projectDto);
}, function (response) {
$scope.loading = false;
SweetAlert.swal({
title: "Error!",
text: "Set project favorite failed!",
type: "warning"
});
});
}
$scope.setArchived = function (project, isArchived) {
var projectDto = {
Id: project.Id,
IsArchived: isArchived
};
$http.post(Constants.WebApi.Project.SetProjectArchived, projectDto).then(function (response) {
project.IsArchived = isArchived;
// remove
var index = $scope.Projects.indexOf(project);
$scope.Projects.splice(index, 1);
}, function (response) {
$scope.loading = false;
SweetAlert.swal({
title: "Error!",
text: "Set project archived failed!",
type: "warning"
});
});
}
$scope.openProperty = function (projId) {
var modalInstance = $modal.open({
templateUrl: 'views/modals/ProjectSetting.html',
controller: ProjectSettingCtrl,
resolve: {
ProjectId: function () {
return projId;
}
}
});
modalInstance.result.then(function () {
//on ok button press
$scope.onload();
$rootScope.$broadcast(Constants.Events.ProjectListChanged, { });
}, function () {
//on cancel button press
});
}
$scope.createNewProject = function()
{
$rootScope.$broadcast(Constants.Events.ProjectAddingNew, null);
}
}
|
const helper = require('./helper');
const lib = require('./lib');
const cors = require('cors');
const constants = require('./constants');
const Redis = require("ioredis");
const redisClient = new Redis();
function handleError(e, res) {
console.error(e);
res.status(500).json({
error: e.toString()
});
}
module.exports = (app, db) => {
const productInfo = {};
const leaderboards = [];
const init = new Promise(async (resolve, reject) => {
const bazaarProducts = await db
.collection('bazaar')
.find()
.toArray();
const itemInfo = await db
.collection('items')
.find({ id: { $in: bazaarProducts.map(a => a.productId) } })
.toArray();
for (const product of bazaarProducts) {
const info = itemInfo.filter(a => a.id == product.productId);
if (info.length > 0)
productInfo[product.productId] = info[0];
}
const keys = await redisClient.keys('lb_*');
for (const key of keys) {
const lb = constants.leaderboard(key);
if (lb.mappedBy == 'uuid' && !lb.key.startsWith('collection_enchanted'))
leaderboards.push(lb);
}
leaderboards.sort((a, b) => {
return a.key.localeCompare(b.key);
})
resolve();
});
app.use('/api/v2/*', async (req, res, next) => {
req.cacheOnly = true;
if (req.query.key) {
const doc = await db
.collection('apiKeys')
.findOne({ key: req.query.key });
if (doc != null)
req.cacheOnly = false;
}
next();
});
app.all('/api/v2/leaderboards', cors(), async (req, res) => {
res.json(leaderboards);
});
app.all('/api/v2/leaderboard/:lbName', cors(), async (req, res) => {
const count = Math.min(100, req.query.count || 20)
let page, startIndex, endIndex;
const lb = constants.leaderboard(`lb_${req.params.lbName}`);
const lbCount = await redisClient.zcount(`lb_${lb.key}`, "-Infinity", "+Infinity");
if (lbCount == 0) {
res.status(404).json({ error: "Leaderboard not found." });
return;
}
const output = {
positions: []
};
if (req.query.find) {
const uuid = (await helper.resolveUsernameOrUuid(req.query.find, db, true)).uuid;
const rank = lb.sortedBy > 0 ?
await redisClient.zrank(`lb_${lb.key}`, uuid) :
await redisClient.zrevrank(`lb_${lb.key}`, uuid);
if (rank == null) {
res.status(404).json({ error: "Specified user not found on leaderboard." });
return;
}
output.self = { rank: rank + 1 };
page = Math.floor(rank / count) + 1;
startIndex = (page - 1) * count;
endIndex = startIndex - 1 + count;
} else {
page = Math.max(1, req.query.page || 1);
startIndex = (page - 1) * count;
endIndex = startIndex - 1 + count;
}
page = Math.min(page, Math.floor(lbCount / count) + 1);
output.page = page;
startIndex = (page - 1) * count;
endIndex = startIndex - 1 + count;
let results = lb.sortedBy > 0 ?
await redisClient.zrange(`lb_${lb.key}`, startIndex, endIndex, 'WITHSCORES') :
await redisClient.zrevrange(`lb_${lb.key}`, startIndex, endIndex, 'WITHSCORES');
for (let i = 0; i < results.length; i += 2) {
const lbPosition = {
rank: i / 2 + startIndex + 1,
amount: lb.format(results[i + 1]),
raw: results[i + 1],
uuid: results[i],
username: (await helper.resolveUsernameOrUuid(results[i], db, true)).display_name
};
if ('self' in output && output.self.rank == lbPosition.rank)
output.self = lbPosition;
output.positions.push(lbPosition);
}
res.json(output);
});
app.all('/api/v2/bazaar', cors(), async (req, res) => {
await init;
try {
const output = {};
for await (const product of db.collection('bazaar').find()) {
const itemInfo = productInfo[product.productId];
const productName = itemInfo ? itemInfo.name : helper.titleCase(product.productId.replace(/(_+)/g, ' '));
output[product.productId] = {
id: product.productId,
name: productName,
buyPrice: product.buyPrice,
sellPrice: product.sellPrice,
buyVolume: product.buyVolume,
sellVolume: product.sellVolume,
tag: helper.hasPath(itemInfo, 'tag') ? itemInfo.tag : null,
price: (product.buyPrice + product.sellPrice) / 2
};
}
res.json(output);
} catch (e) {
handleError(e, res);
}
});
app.all('/api/v2/profile/:player', cors(), async (req, res) => {
try {
const { profile, allProfiles } = await lib.getProfile(db, req.params.player, null, { cacheOnly: req.cacheOnly });
const output = { profiles: {} };
for (const singleProfile of allProfiles) {
const userProfile = singleProfile.members[profile.uuid];
const items = await lib.getItems(userProfile, req.query.pack);
const data = await lib.getStats(db, singleProfile, allProfiles, items);
output.profiles[singleProfile.profile_id] = {
profile_id: singleProfile.profile_id,
cute_name: singleProfile.cute_name,
current: Math.max(...allProfiles.map(a => a.members[profile.uuid].last_save)) == userProfile.last_save,
last_save: userProfile.last_save,
raw: userProfile,
items,
data
};
}
res.json(output);
} catch (e) {
handleError(e, res);
}
});
app.all('/api/v2/coins/:player/:profile', cors(), async (req, res) => {
try {
const { profile, allProfiles } = await lib.getProfile(db, req.params.player, null, { cacheOnly: req.cacheOnly });
let output = {
error: "Invalid Profile Name!"
};
for (const singleProfile of allProfiles) {
const cute_name = singleProfile.cute_name;
if (cute_name.toLowerCase() != req.params.profile.toLowerCase())
continue;
const items = await lib.getItems(singleProfile.members[profile.uuid], req.query.pack);
const data = await lib.getStats(db, singleProfile, allProfiles, items);
output = {
profile_id: singleProfile.profile_id,
cute_name: cute_name,
purse: data.purse,
bank: data.bank
};
}
res.json(output);
} catch (e) {
handleError(e, res);
}
});
app.all('/api/v2/coins/:player', cors(), async (req, res) => {
try {
const { profile, allProfiles } = await lib.getProfile(db, req.params.player, null, { cacheOnly: req.cacheOnly });
const output = { profiles: {} };
for (const singleProfile of allProfiles) {
const cute_name = singleProfile.cute_name;
const items = await lib.getItems(singleProfile.members[profile.uuid], req.query.pack);
const data = await lib.getStats(db, singleProfile, allProfiles, items);
output.profiles[singleProfile.profile_id] = {
profile_id: singleProfile.profile_id,
cute_name: cute_name,
purse: data.purse,
bank: data.bank
};
}
res.json(output);
} catch (e) {
handleError(e, res);
}
});
app.all('/api/v2/talismans/:player/:profile', cors(), async (req, res) => {
try {
const { profile, allProfiles } = await lib.getProfile(db, req.params.player, null, { cacheOnly: req.cacheOnly });
let output = {
error: "Invalid Profile Name!"
};
for (const singleProfile of allProfiles) {
const cute_name = singleProfile.cute_name;
if (cute_name.toLowerCase() != req.params.profile.toLowerCase())
continue;
const items = await lib.getItems(singleProfile.members[profile.uuid], req.query.pack);
const talismans = items.talismans;
output = {
profile_id: singleProfile.profile_id,
cute_name: singleProfile.cute_name,
talismans
};
}
res.json(output);
} catch (e) {
handleError(e, res);
}
});
app.all('/api/v2/talismans/:player', cors(), async (req, res) => {
try {
const { profile, allProfiles } = await lib.getProfile(db, req.params.player, null, { cacheOnly: req.cacheOnly });
const output = { profiles: {} };
for (const singleProfile of allProfiles) {
const userProfile = singleProfile.members[profile.uuid];
const items = await lib.getItems(userProfile, req.query.pack);
const talismans = items.talismans;
output.profiles[singleProfile.profile_id] = {
profile_id: singleProfile.profile_id,
cute_name: singleProfile.cute_name,
talismans
};
}
res.json(output);
} catch (e) {
handleError(e, res);
}
});
app.all('/api/v2/slayers/:player/:profile', cors(), async (req, res) => {
try {
const { profile, allProfiles } = await lib.getProfile(db, req.params.player, null, { cacheOnly: req.cacheOnly });
let output = {
error: "Invalid Profile Name!"
};
for (const singleProfile of allProfiles) {
const cute_name = singleProfile.cute_name;
if (cute_name.toLowerCase() != req.params.profile.toLowerCase())
continue;
const items = await lib.getItems(singleProfile.members[profile.uuid], req.query.pack);
const data = await lib.getStats(db, singleProfile, allProfiles, items);
output = {
profile_id: singleProfile.profile_id,
cute_name: singleProfile.cute_name,
slayer_xp: data.slayer_xp,
slayers: data.slayers,
slayer_bonus: data.slayer_bonus,
slayer_coins_spent: data.slayer_coins_spent
};
}
res.json(output);
} catch (e) {
handleError(e, res);
}
});
app.all('/api/v2/slayers/:player', cors(), async (req, res) => {
try {
const { profile, allProfiles } = await lib.getProfile(db, req.params.player, null, { cacheOnly: req.cacheOnly });
const output = { profiles: {} };
for (const singleProfile of allProfiles) {
const userProfile = singleProfile.members[profile.uuid];
const items = await lib.getItems(userProfile, req.query.pack);
const data = await lib.getStats(db, singleProfile, allProfiles, items);
output.profiles[singleProfile.profile_id] = {
profile_id: singleProfile.profile_id,
cute_name: singleProfile.cute_name,
slayer_xp: data.slayer_xp,
slayers: data.slayers,
slayer_bonus: data.slayer_bonus,
slayer_coins_spent: data.slayer_coins_spent
};
}
res.json(output);
} catch (e) {
handleError(e, res);
}
});
app.all('/api/v2/dungeons/:player/:profile', cors(), async (req, res) => {
try {
const { profile, allProfiles } = await lib.getProfile(db, req.params.player, null, { cacheOnly: req.cacheOnly });
let output = {
error: "Invalid Profile Name!"
};
for (const singleProfile of allProfiles) {
const cute_name = singleProfile.cute_name;
if (cute_name.toLowerCase() != req.params.profile.toLowerCase())
continue;
const userProfile = singleProfile.members[profile.uuid];
const hypixelProfile = await helper.getRank(profile.uuid, db);
const dungeonData = await lib.getDungeons(userProfile, hypixelProfile);
output = {
profile_id: singleProfile.profile_id,
cute_name: singleProfile.cute_name,
dungeons: dungeonData
};
}
res.json(output);
} catch (e) {
handleError(e, res);
}
});
app.all('/api/v2/dungeons/:player', cors(), async (req, res) => {
try {
const { profile, allProfiles } = await lib.getProfile(db, req.params.player, null, { cacheOnly: req.cacheOnly });
const output = { profiles: {} };
for (const singleProfile of allProfiles) {
const userProfile = singleProfile.members[profile.uuid];
const hypixelProfile = await helper.getRank(profile.uuid, db);
const dungeonData = await lib.getDungeons(userProfile, hypixelProfile);
output.profiles[singleProfile.profile_id] = {
profile_id: singleProfile.profile_id,
cute_name: singleProfile.cute_name,
dungeons: dungeonData
};
}
res.json(output);
} catch (e) {
handleError(e, res);
}
});
};
|
import React, { Component } from "react";
import Router from "next/router";
import api from "./api";
import AuthService from "./AuthService";
import { getCookie, setCookie } from "./Cookies";
import cookie from "js-cookie";
import localStorage from "local-storage";
export default function withOutAuth(NoAuthComponent) {
const apis = new api(process.env.APP_DOMAIN).group("user");
const Auth = new AuthService(process.env.API_DOMAIN_URL_12000);
return class Authenticated extends Component {
static async getInitialProps(ctx) {
try {
const ctxx = { query: ctx.query, pathName: ctx.pathName };
const isServer = !!ctx.req;
// Ensures material-ui renders the correct css prefixes server-side
let userAgent;
let domain;
if (!isServer) {
userAgent = navigator.userAgent;
domain = ".";
} else {
userAgent = ctx.req.headers["user-agent"];
domain = process.env.APP_DOMAIN;
}
// Check if Page has a `getInitialProps`; if so, call it.
const pageProps =
NoAuthComponent.getInitialProps &&
(await NoAuthComponent.getInitialProps(ctx));
const url = { query: ctx.query, pathName: ctx.pathName };
// Return props.
return {
...pageProps,
userAgent,
url,
domain
};
} catch (err) {
const isServer = !!ctx.req;
if (isServer) {
ctx.res.send(err.message);
ctx.res.end();
} else {
throw new Error(err);
}
}
}
constructor(props) {
super(props);
}
async componentDidMount() {
try {
} catch (err) {
console.log(err);
//Router.push('/logout')
}
}
render() {
return (
<div>
<NoAuthComponent {...this.props} />
</div>
);
}
};
}
|
const getMood = (mood) => {
// eslint-disable-next-line default-case
switch (mood) {
case 1:
return "awful";
case 2:
return "bad";
case 3:
return "okay";
case 4:
return "good";
case 5:
return "awesome";
}
};
const locale = {
checkInHeading: () => "Check in with yourself",
checkInSubheading: () => "How are you feeling right now?",
hideCheckIns: () => "Hide previous check-ins",
showCheckIns: () => "Show previous check-ins",
noCheckInsYet: () => "You have no check-ins yet.",
averageMood: (mood) =>
`Your average mood during the past week was ${getMood(mood)}.`,
mood: getMood,
settings: () => "Settings",
darkMode: () => "Dark mode",
formattedDate: (time) => new Date(time).toLocaleDateString("en-gb"),
};
export default locale;
|
// Quinton Ashley
// https://www.youtube.com/watch?v=E7o1UpHH0c0
function setup() { //0 0:03
createCanvas(windowWidth, windowHeight);
example0();
}
function drawCaterpillar() { //1 0:08
// initialize variables
var radius = 50;
// draw line
ellipse(50, 50, radius, radius); //2 0:14 4
ellipse(i, i, radius, radius); //4
i += 10;
// repeat //2
ellipse(60, 60, radius, radius); //2 0:23
ellipse(70, 70, radius, radius);
ellipse(80, 80, radius, radius);
ellipse(90, 90, radius, radius);
ellipse(100, 100, radius, radius);
ellipse(110, 110, radius, radius);
ellipse(120, 120, radius, radius); //4 10
ellipse(130, 130, radius, radius); //4
ellipse(140, 140, radius, radius); //4 10
ellipse(140, 140, radius, radius);
ellipse(150, 150, radius, radius);
ellipse(160, 160, radius, radius); //10
ellipse(170, 170, radius, radius);
ellipse(180, 180, radius, radius); //4
ellipse(190, 190, radius, radius);
ellipse(200, 200, radius, radius);
ellipse(i, i, radius, radius);
i += 10;
ellipse(i, i, radius, radius);
i += 10;
ellipse(i, i, radius, radius);
i += 10;
ellipse(i, i, radius, radius);
i += 10;
ellipse(i, i, radius, radius);
i += 10;
} //1
function example1() {
// initialize variables //3 0:18
var radius = 50;
var i = 50;
// draw line
ellipse(i, i, radius, radius);
i += 10;
ellipse(i, i, radius, radius); //4
i += 10;
ellipse(i, i, radius, radius);
i += 10;
ellipse(i, i, radius, radius);
i += 10;
ellipse(i, i, radius, radius);
i += 10;
ellipse(i, i, radius, radius);
i += 10;
} //1
function example2() {
// initialize variables //5 1:40
var radius = 50;
// draw line
for (var i = 50; i < 200; i += 10) {
ellipse(i, i, radius, radius);
}
} //1
|
window.addEventListener('load', function(){
let forms = document.querySelector('.LoginForm');
let email = document.querySelector('#email');
let password = document.querySelector('#password');
let pEmail=document.querySelector('#errorEmail')
let pPassword=document.querySelector('#errorPassword')
const validarEmail = input =>{
const correo =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)+\.\S+/.test(input.value)
if(input.value === ''){
input.placeholder = "Correo Electronico obligatorio";
pEmail.classList.add("mostrar");
pEmail.innerHTML= "Correo Electronico Obligatorio"
input.style.backgroundColor = "orange";
errors[select.name] = `${select.name} is required`
}
else if(!correo) {
input.placeholder = "Escriba un correo electronico valido, por favor";
pEmail.classList.add("mostrar");
pEmail.innerHTML= "Correo Electronico Invalido"
input.style.backgroundColor = "orange";
input.value = "";
errors[select.name] = `${select.name} es invalido`
} else {
input.classList.remove('invalid');
input.style.backgroundColor = "white";
pEmail.classList.remove("mostrar");
pEmail.classList.add("ocultar");
}
}
const validarPassword = input => {
if(input.value === ''){
input.placeholder = "Contraseña Obligatoria";
pPassword.classList.add("mostrar");
pPassword.innerHTML= "Contraseña Obligatoria"
input.style.backgroundColor = "orange";
errors[select.name] = `${select.name} is required`
}else{
input.style.backgroundColor = "white";
pPassword.classList.remove("mostrar");
pPassword.classList.add("ocultar");
}
}
//el evento blur para detectar cuando el usuario haga clic fuera del input
email.addEventListener("blur", function(){ validarEmail(email); })
password.addEventListener("blur", function(){ validarPassword(password); })
function ValidacionForm() {
validarEmail()
validarPassword()
}
forms.addEventListener("submit", function(event) {
ValidacionForm()
if(Object.keys(errors).length) {
event.preventDefault();
event.stopPropagation();
console.log(errors)
}
console.log('Autenticación exitosa')
})
})
|
(function (cjs, an) {
var p; // shortcut to reference prototypes
var lib={};var ss={};var img={};
lib.ssMetadata = [
{name:"card cow_girl_atlas_1", frames: [[0,0,1954,1663]]},
{name:"card cow_girl_atlas_2", frames: [[0,0,1638,1417]]},
{name:"card cow_girl_atlas_3", frames: [[0,0,1450,1388]]},
{name:"card cow_girl_atlas_4", frames: [[0,0,1558,1250]]},
{name:"card cow_girl_atlas_5", frames: [[0,0,1546,1050]]},
{name:"card cow_girl_atlas_6", frames: [[0,0,1442,1117]]},
{name:"card cow_girl_atlas_7", frames: [[0,0,960,1000],[0,1002,960,1000],[962,0,960,1000],[962,1002,960,1000]]},
{name:"card cow_girl_atlas_8", frames: [[0,0,960,1000],[0,1002,960,1000],[962,0,960,1000],[962,1002,960,1000]]},
{name:"card cow_girl_atlas_9", frames: [[0,0,960,1000],[0,1002,960,1000],[962,0,960,1000],[962,1002,960,1000]]},
{name:"card cow_girl_atlas_10", frames: [[0,0,960,1000],[0,1002,960,1000],[962,0,960,1000],[962,1002,960,1000]]},
{name:"card cow_girl_atlas_11", frames: [[1281,555,614,553],[664,0,615,554],[0,0,662,690],[1281,0,615,553],[0,692,710,373]]}
];
(lib.AnMovieClip = function(){
this.actionFrames = [];
this.gotoAndPlay = function(positionOrLabel){
cjs.MovieClip.prototype.gotoAndPlay.call(this,positionOrLabel);
}
this.play = function(){
cjs.MovieClip.prototype.play.call(this);
}
this.gotoAndStop = function(positionOrLabel){
cjs.MovieClip.prototype.gotoAndStop.call(this,positionOrLabel);
}
this.stop = function(){
cjs.MovieClip.prototype.stop.call(this);
}
}).prototype = p = new cjs.MovieClip();
// symbols:
(lib._13BCEABB1447DE16 = function() {
this.initialize(ss["card cow_girl_atlas_5"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
(lib._6E33D36645D6A2F5 = function() {
this.initialize(ss["card cow_girl_atlas_4"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
(lib._925C5C11E60E1EED = function() {
this.initialize(ss["card cow_girl_atlas_6"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
(lib._925C5C11E60E1EF3 = function() {
this.initialize(ss["card cow_girl_atlas_3"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
(lib._925C5C11E60E1EF4 = function() {
this.initialize(ss["card cow_girl_atlas_1"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
(lib._925C5C11E60E1EF5 = function() {
this.initialize(ss["card cow_girl_atlas_2"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
(lib._925C5C11E60E1EF7 = function() {
this.initialize(img._925C5C11E60E1EF7);
}).prototype = p = new cjs.Bitmap();
p.nominalBounds = new cjs.Rectangle(0,0,2104,2079);
(lib.BackHair = function() {
this.initialize(ss["card cow_girl_atlas_7"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
(lib.Bang = function() {
this.initialize(ss["card cow_girl_atlas_7"]);
this.gotoAndStop(1);
}).prototype = p = new cjs.Sprite();
(lib.BMP_46ef3140_5063_4fb8_9237_27bf483f1f6f = function() {
this.initialize(ss["card cow_girl_atlas_11"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
(lib.BMP_70b26aa5_ce98_4332_bb18_12785532d81c = function() {
this.initialize(ss["card cow_girl_atlas_11"]);
this.gotoAndStop(1);
}).prototype = p = new cjs.Sprite();
(lib.BMP_bda309b1_26d3_4b79_9785_54c22542d9fe = function() {
this.initialize(ss["card cow_girl_atlas_11"]);
this.gotoAndStop(2);
}).prototype = p = new cjs.Sprite();
(lib.BMP_ee2513d0_0770_49fd_b09f_d6f15dd946af = function() {
this.initialize(ss["card cow_girl_atlas_11"]);
this.gotoAndStop(3);
}).prototype = p = new cjs.Sprite();
(lib.face = function() {
this.initialize(ss["card cow_girl_atlas_7"]);
this.gotoAndStop(2);
}).prototype = p = new cjs.Sprite();
(lib.leftblink = function() {
this.initialize(ss["card cow_girl_atlas_7"]);
this.gotoAndStop(3);
}).prototype = p = new cjs.Sprite();
(lib.leftear = function() {
this.initialize(ss["card cow_girl_atlas_8"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
(lib.lefteyewhite = function() {
this.initialize(ss["card cow_girl_atlas_8"]);
this.gotoAndStop(1);
}).prototype = p = new cjs.Sprite();
(lib.lefteyeball = function() {
this.initialize(ss["card cow_girl_atlas_8"]);
this.gotoAndStop(2);
}).prototype = p = new cjs.Sprite();
(lib.mouthE = function() {
this.initialize(ss["card cow_girl_atlas_8"]);
this.gotoAndStop(3);
}).prototype = p = new cjs.Sprite();
(lib.mouthneutral = function() {
this.initialize(ss["card cow_girl_atlas_9"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
(lib.mouthR = function() {
this.initialize(ss["card cow_girl_atlas_9"]);
this.gotoAndStop(1);
}).prototype = p = new cjs.Sprite();
(lib.mouthsmile = function() {
this.initialize(ss["card cow_girl_atlas_9"]);
this.gotoAndStop(2);
}).prototype = p = new cjs.Sprite();
(lib.nose = function() {
this.initialize(ss["card cow_girl_atlas_9"]);
this.gotoAndStop(3);
}).prototype = p = new cjs.Sprite();
(lib.rightblink = function() {
this.initialize(ss["card cow_girl_atlas_10"]);
this.gotoAndStop(0);
}).prototype = p = new cjs.Sprite();
(lib.rightear = function() {
this.initialize(ss["card cow_girl_atlas_10"]);
this.gotoAndStop(1);
}).prototype = p = new cjs.Sprite();
(lib.righteyeball = function() {
this.initialize(ss["card cow_girl_atlas_10"]);
this.gotoAndStop(2);
}).prototype = p = new cjs.Sprite();
(lib.righteyewhite = function() {
this.initialize(ss["card cow_girl_atlas_10"]);
this.gotoAndStop(3);
}).prototype = p = new cjs.Sprite();
(lib.ビットマップ1 = function() {
this.initialize(ss["card cow_girl_atlas_11"]);
this.gotoAndStop(4);
}).prototype = p = new cjs.Sprite();
(lib.トゥイーン42 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib._13BCEABB1447DE16();
this.instance.setTransform(-995.25,-14.65,1.1056,0.972,-29.9984);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-995.2,-869.2,1990.5,1738.4);
(lib.トゥイーン41 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib._925C5C11E60E1EED();
this.instance.setTransform(189.3,276.35,0.3346,0.3346,-120.0029);
this.instance_1 = new lib._925C5C11E60E1EED();
this.instance_1.setTransform(-668,-754,0.3346,0.3346);
this.instance_2 = new lib._925C5C11E60E1EF3();
this.instance_2.setTransform(-696,162,0.3346,0.3346);
this.instance_3 = new lib._925C5C11E60E1EF7();
this.instance_3.setTransform(-226,65,0.3346,0.3346);
this.instance_4 = new lib._925C5C11E60E1EF5();
this.instance_4.setTransform(-169,-705,0.3037,0.3037);
this.instance_5 = new lib._925C5C11E60E1EF4();
this.instance_5.setTransform(-490,-197,0.2002,0.2002);
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.instance_5},{t:this.instance_4},{t:this.instance_3},{t:this.instance_2},{t:this.instance_1},{t:this.instance}]}).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-696,-754,1209,1514.6);
(lib.トゥイーン38 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib._6E33D36645D6A2F5();
this.instance.setTransform(-16.5,-42.45,0.0456,0.0456,29.9612);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-45,-42.4,90.1,84.9);
(lib.トゥイーン36 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.rightear();
this.instance.setTransform(-284.9,-296.75,0.5935,0.5935);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-284.9,-296.7,569.8,593.5);
(lib.トゥイーン34 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.leftear();
this.instance.setTransform(-284.9,-296.75,0.5935,0.5935);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-284.9,-296.7,569.8,593.5);
(lib.トゥイーン32 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.rightblink();
this.instance.setTransform(-340.75,-354.95,0.7099,0.7099);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-340.7,-354.9,681.5,709.9);
(lib.トゥイーン30 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.righteyewhite();
this.instance.setTransform(-340.75,-354.95,0.7099,0.7099);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-340.7,-354.9,681.5,709.9);
(lib.トゥイーン29 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.righteyewhite();
this.instance.setTransform(-340.75,-354.95,0.7099,0.7099);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-340.7,-354.9,681.5,709.9);
(lib.トゥイーン28 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.righteyeball();
this.instance.setTransform(-340.75,-354.95,0.7099,0.7099);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-340.7,-354.9,681.5,709.9);
(lib.トゥイーン27 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.righteyeball();
this.instance.setTransform(-340.75,-354.95,0.7099,0.7099);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-340.7,-354.9,681.5,709.9);
(lib.トゥイーン26 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.leftblink();
this.instance.setTransform(-315.95,-329.1,0.6582,0.6582);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-315.9,-329.1,631.9,658.2);
(lib.トゥイーン24 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.lefteyewhite();
this.instance.setTransform(-315.95,-329.1,0.6582,0.6582);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-315.9,-329.1,631.9,658.2);
(lib.トゥイーン23 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.lefteyewhite();
this.instance.setTransform(-315.95,-329.1,0.6582,0.6582);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-315.9,-329.1,631.9,658.2);
(lib.トゥイーン22 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.lefteyeball();
this.instance.setTransform(-315.95,-329.1,0.6582,0.6582);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-315.9,-329.1,631.9,658.2);
(lib.トゥイーン21 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.lefteyeball();
this.instance.setTransform(-315.95,-329.1,0.6582,0.6582);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-315.9,-329.1,631.9,658.2);
(lib.トゥイーン20 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.mouthR();
this.instance.setTransform(-321.55,-334.95,0.6699,0.6699);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-321.5,-334.9,643.1,669.9);
(lib.トゥイーン18 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.mouthneutral();
this.instance.setTransform(-321.55,-334.95,0.6699,0.6699);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-321.5,-334.9,643.1,669.9);
(lib.トゥイーン17 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.mouthneutral();
this.instance.setTransform(-321.55,-334.95,0.6699,0.6699);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-321.5,-334.9,643.1,669.9);
(lib.トゥイーン16 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.mouthsmile();
this.instance.setTransform(-321.55,-334.95,0.6699,0.6699);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-321.5,-334.9,643.1,669.9);
(lib.トゥイーン14 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.mouthE();
this.instance.setTransform(-321.55,-334.95,0.6699,0.6699);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-321.5,-334.9,643.1,669.9);
(lib.トゥイーン12 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.ビットマップ1();
this.instance.setTransform(-231.35,-121.5,0.6517,0.6517);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-231.3,-121.5,462.70000000000005,243.1);
(lib.トゥイーン11 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.ビットマップ1();
this.instance.setTransform(-231.35,-121.5,0.6517,0.6517);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-231.3,-121.5,462.70000000000005,243.1);
(lib.トゥイーン10 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.BackHair();
this.instance.setTransform(-331.15,-344.95,0.6899,0.6899);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-331.1,-344.9,662.3,689.9);
(lib.トゥイーン9 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.BackHair();
this.instance.setTransform(-331.15,-344.95,0.6899,0.6899);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-331.1,-344.9,662.3,689.9);
(lib.トゥイーン8 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.nose();
this.instance.setTransform(-316.8,-330,0.66,0.66);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-316.8,-330,633.6,660);
(lib.トゥイーン7 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.nose();
this.instance.setTransform(-316.8,-330,0.66,0.66);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-316.8,-330,633.6,660);
(lib.トゥイーン6 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.Bang();
this.instance.setTransform(-333.2,-347.1,0.6942,0.6942);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-333.2,-347.1,666.5,694.2);
(lib.トゥイーン5 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.Bang();
this.instance.setTransform(-333.2,-347.1,0.6942,0.6942);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-333.2,-347.1,666.5,694.2);
(lib.トゥイーン4 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.text = new cjs.Text("おめでとうございます", "37px 'Wawati SC'", "#313131");
this.text.textAlign = "center";
this.text.lineHeight = 54;
this.text.lineWidth = 433;
this.text.parent = this;
this.text.setTransform(0,-38.65);
this.timeline.addTween(cjs.Tween.get(this.text).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-218.5,-40.6,437,81.30000000000001);
(lib.トゥイーン3 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.text = new cjs.Text("おめでとうございます", "37px 'Wawati SC'", "#313131");
this.text.textAlign = "center";
this.text.lineHeight = 54;
this.text.lineWidth = 433;
this.text.parent = this;
this.text.setTransform(0,-38.65);
this.timeline.addTween(cjs.Tween.get(this.text).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-218.5,-40.6,437,81.30000000000001);
(lib.トゥイーン2 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.text = new cjs.Text("あけまして", "37px 'Wawati SC'", "#313131");
this.text.textAlign = "center";
this.text.lineHeight = 54;
this.text.lineWidth = 285;
this.text.parent = this;
this.text.setTransform(0,-34.35);
this.timeline.addTween(cjs.Tween.get(this.text).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-144.3,-36.3,288.70000000000005,72.69999999999999);
(lib.トゥイーン1 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.text = new cjs.Text("あけまして", "37px 'Wawati SC'", "#313131");
this.text.textAlign = "center";
this.text.lineHeight = 54;
this.text.lineWidth = 285;
this.text.parent = this;
this.text.setTransform(0,-34.35);
this.timeline.addTween(cjs.Tween.get(this.text).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-144.3,-36.3,288.70000000000005,72.69999999999999);
(lib.シンボル1 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.face();
this.instance.setTransform(-324.05,-337.55,0.6751,0.6751);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-324,-337.5,648.1,675.1);
(lib.WarpedAsset_1 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.BMP_bda309b1_26d3_4b79_9785_54c22542d9fe();
this.timeline.addTween(cjs.Tween.get(this.instance).wait(1));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(0,0,662,690);
(lib.PuppetShape_1 = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
// レイヤー_1
this.instance = new lib.WarpedAsset_1("synched",0);
this.instance_1 = new lib.BMP_46ef3140_5063_4fb8_9237_27bf483f1f6f();
this.instance_1.setTransform(-4.95,99);
this.instance_2 = new lib.BMP_70b26aa5_ce98_4332_bb18_12785532d81c();
this.instance_2.setTransform(-5,98.05);
this.instance_3 = new lib.BMP_ee2513d0_0770_49fd_b09f_d6f15dd946af();
this.instance_3.setTransform(-5.05,99);
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.instance}]}).to({state:[{t:this.instance_1}]},195).to({state:[{t:this.instance_2}]},1).to({state:[{t:this.instance_3}]},1).wait(86));
this._renderFirstFrame();
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(-5,0,667,690);
// stage content:
(lib.cardcowgirl = function(mode,startPosition,loop,reversed) {
if (loop == null) { loop = true; }
if (reversed == null) { reversed = false; }
var props = new Object();
props.mode = mode;
props.startPosition = startPosition;
props.labels = {};
props.loop = loop;
props.reversed = reversed;
cjs.MovieClip.apply(this,[props]);
this.actionFrames = [46];
// timeline functions:
this.frame_46 = function() {
playSound("_20200829_110600wav");
}
// actions tween:
this.timeline.addTween(cjs.Tween.get(this).wait(46).call(this.frame_46).wait(236));
// おめでとうございます
this.instance = new lib.トゥイーン3("synched",0);
this.instance.setTransform(468.25,542.6);
this.instance.alpha = 0;
this.instance._off = true;
this.instance_1 = new lib.トゥイーン4("synched",0);
this.instance_1.setTransform(367.4,486.95,1.7134,3.457,0.7696,0,0,0.1,0.2);
this.timeline.addTween(cjs.Tween.get({}).to({state:[]}).to({state:[{t:this.instance}]},127).to({state:[{t:this.instance_1,p:{x:367.4,y:486.95}}]},60).to({state:[{t:this.instance_1,p:{x:362.35,y:487.95}}]},94).wait(1));
this.timeline.addTween(cjs.Tween.get(this.instance).wait(127).to({_off:false},0).to({_off:true,regX:0.1,regY:0.2,scaleX:1.7134,scaleY:3.457,rotation:0.7696,x:367.4,y:486.95,alpha:1},60).wait(95));
// あけまして
this.instance_2 = new lib.トゥイーン1("synched",0);
this.instance_2.setTransform(289.65,465.55);
this.instance_2.alpha = 0;
this.instance_2._off = true;
this.instance_3 = new lib.トゥイーン2("synched",0);
this.instance_3.setTransform(260.55,280.6,2.3246,3.3434,-9.9659,0,0,0.1,0.1);
this.timeline.addTween(cjs.Tween.get({}).to({state:[]}).to({state:[{t:this.instance_2}]},62).to({state:[{t:this.instance_3}]},46).wait(174));
this.timeline.addTween(cjs.Tween.get(this.instance_2).wait(62).to({_off:false},0).to({_off:true,regX:0.1,regY:0.1,scaleX:2.3246,scaleY:3.3434,rotation:-9.9659,x:260.55,y:280.6,alpha:1},46).wait(174));
// _2021年
this.instance_4 = new lib.トゥイーン42("synched",0);
this.instance_4.setTransform(358.95,347.75);
this.instance_4.alpha = 0;
this.instance_4._off = true;
this.timeline.addTween(cjs.Tween.get(this.instance_4).wait(32).to({_off:false},0).to({scaleX:0.7029,scaleY:0.7029,x:332.5,alpha:0.2695},8).wait(242));
// Bang
this.instance_5 = new lib.トゥイーン5("synched",0);
this.instance_5.setTransform(327.2,969.1);
this.instance_5.alpha = 0;
this.instance_6 = new lib.トゥイーン6("synched",0);
this.instance_6.setTransform(327.2,969.1);
this.instance_6._off = true;
this.timeline.addTween(cjs.Tween.get(this.instance_5).to({_off:true,alpha:1},20).wait(262));
this.timeline.addTween(cjs.Tween.get(this.instance_6).to({_off:false},20).wait(29).to({startPosition:0},0).wait(146).to({rotation:-2.4714,x:327.35,y:968.95},0).wait(1).to({rotation:-5.2117,x:325.85,y:968.75},0).wait(86));
// mouth_nuetral
this.instance_7 = new lib.トゥイーン17("synched",0);
this.instance_7.setTransform(315.55,970.95);
this.instance_7.alpha = 0;
this.instance_8 = new lib.トゥイーン18("synched",0);
this.instance_8.setTransform(315.55,970.95);
this.instance_8._off = true;
this.timeline.addTween(cjs.Tween.get(this.instance_7).to({_off:true,alpha:1},20).wait(262));
this.timeline.addTween(cjs.Tween.get(this.instance_8).to({_off:false},20).wait(29).to({startPosition:0},0).to({_off:true},13).wait(47).to({_off:false},0).to({_off:true},18).wait(6).to({_off:false},0).to({_off:true},1).wait(5).to({_off:false},0).to({_off:true},1).wait(35).to({_off:false},0).to({_off:true},1).wait(12).to({_off:false},0).wait(7).to({rotation:-2.4714,x:315.8,y:971.3},0).wait(1).to({rotation:-5.2117,x:314.4,y:971.65},0).wait(86));
// mouth_E
this.instance_9 = new lib.トゥイーン14("synched",0);
this.instance_9.setTransform(314.9,973.25);
this.instance_9._off = true;
this.timeline.addTween(cjs.Tween.get(this.instance_9).wait(89).to({_off:false},0).wait(8).to({startPosition:0},0).to({_off:true},1).wait(71).to({_off:false},0).wait(5).to({startPosition:0},0).to({_off:true},1).wait(107));
// mouth_smile
this.instance_10 = new lib.トゥイーン16("synched",0);
this.instance_10.setTransform(314.9,973.25);
this.instance_10._off = true;
this.timeline.addTween(cjs.Tween.get(this.instance_10).wait(71).to({_off:false},0).wait(8).to({startPosition:0},0).to({_off:true},1).wait(18).to({_off:false},0).wait(10).to({startPosition:0},0).to({_off:true},1).wait(25).to({_off:false},0).wait(4).to({startPosition:0},0).to({_off:true},1).wait(1).to({_off:false},0).wait(4).to({startPosition:0},0).to({_off:true},1).wait(11).to({_off:false},0).to({_off:true},1).wait(6).to({_off:false},0).wait(5).to({startPosition:0},0).to({_off:true},1).wait(7).to({_off:false},0).wait(4).to({startPosition:0},0).to({_off:true},1).wait(101));
// mouth_R
this.instance_11 = new lib.トゥイーン20("synched",0);
this.instance_11.setTransform(314.9,973.25);
this.instance_11._off = true;
this.timeline.addTween(cjs.Tween.get(this.instance_11).wait(62).to({_off:false},0).wait(8).to({startPosition:0},0).to({_off:true},1).wait(9).to({_off:false},0).wait(8).to({startPosition:0},0).to({_off:true},1).wait(38).to({_off:false},0).wait(5).to({startPosition:0},0).to({_off:true},1).wait(12).to({_off:false},0).wait(5).to({startPosition:0},0).wait(1).to({startPosition:0},0).wait(4).to({startPosition:0},0).to({_off:true},1).wait(1).to({_off:false},0).wait(5).to({startPosition:0},0).to({_off:true},1).wait(18).to({_off:false},0).wait(5).to({startPosition:0},0).to({_off:true},2).wait(94));
// right_eye_ball
this.instance_12 = new lib.トゥイーン27("synched",0);
this.instance_12.setTransform(317.75,959.95);
this.instance_12.alpha = 0;
this.instance_13 = new lib.トゥイーン28("synched",0);
this.instance_13.setTransform(317.75,959.95);
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.instance_12}]}).to({state:[{t:this.instance_13}]},20).to({state:[]},13).to({state:[{t:this.instance_13}]},5).to({state:[{t:this.instance_13}]},11).to({state:[]},146).wait(87));
this.timeline.addTween(cjs.Tween.get(this.instance_12).to({_off:true,alpha:1},20).wait(262));
// right_eye_white
this.instance_14 = new lib.トゥイーン29("synched",0);
this.instance_14.setTransform(317.75,959.95);
this.instance_14.alpha = 0;
this.instance_15 = new lib.トゥイーン30("synched",0);
this.instance_15.setTransform(317.75,959.95);
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.instance_14}]}).to({state:[{t:this.instance_15}]},20).to({state:[]},13).to({state:[{t:this.instance_15}]},5).to({state:[{t:this.instance_15}]},11).to({state:[]},146).wait(87));
this.timeline.addTween(cjs.Tween.get(this.instance_14).to({_off:true,alpha:1},20).wait(262));
// right_blink
this.instance_16 = new lib.トゥイーン32("synched",0);
this.instance_16.setTransform(323.75,961.7);
this.instance_16._off = true;
this.timeline.addTween(cjs.Tween.get(this.instance_16).wait(33).to({_off:false},0).wait(4).to({startPosition:0},0).to({_off:true},1).wait(157).to({_off:false,rotation:-2.4714,x:323.6},0).wait(1).to({rotation:-5.2117,x:321.75},0).wait(86));
// left_eye_ball
this.instance_17 = new lib.トゥイーン21("synched",0);
this.instance_17.setTransform(309.95,961.1);
this.instance_17.alpha = 0;
this.instance_18 = new lib.トゥイーン22("synched",0);
this.instance_18.setTransform(309.95,961.1);
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.instance_17}]}).to({state:[{t:this.instance_18}]},20).to({state:[]},13).to({state:[{t:this.instance_18}]},5).to({state:[{t:this.instance_18}]},11).to({state:[]},146).wait(87));
this.timeline.addTween(cjs.Tween.get(this.instance_17).to({_off:true,alpha:1},20).wait(262));
// left_eye_white
this.instance_19 = new lib.トゥイーン23("synched",0);
this.instance_19.setTransform(309.95,961.1);
this.instance_19.alpha = 0;
this.instance_20 = new lib.トゥイーン24("synched",0);
this.instance_20.setTransform(309.95,961.1);
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.instance_19}]}).to({state:[{t:this.instance_20}]},20).to({state:[]},13).to({state:[{t:this.instance_20}]},5).to({state:[{t:this.instance_20}]},11).to({state:[]},146).wait(87));
this.timeline.addTween(cjs.Tween.get(this.instance_19).to({_off:true,alpha:1},20).wait(262));
// left_blink
this.instance_21 = new lib.トゥイーン26("synched",0);
this.instance_21.setTransform(315.95,968.6);
this.instance_21._off = true;
this.timeline.addTween(cjs.Tween.get(this.instance_21).wait(33).to({_off:false},0).wait(4).to({startPosition:0},0).to({_off:true},1).wait(157).to({_off:false,rotation:-2.4714,x:316.1,y:968.95},0).wait(1).to({rotation:-5.2117,x:314.6,y:969.25},0).wait(86));
// nose
this.instance_22 = new lib.トゥイーン7("synched",0);
this.instance_22.setTransform(314.8,966);
this.instance_22.alpha = 0;
this.instance_23 = new lib.トゥイーン8("synched",0);
this.instance_23.setTransform(314.8,966);
this.instance_23._off = true;
this.timeline.addTween(cjs.Tween.get(this.instance_22).to({_off:true,alpha:1},20).wait(262));
this.timeline.addTween(cjs.Tween.get(this.instance_23).to({_off:false},20).wait(29).to({startPosition:0},0).wait(146).to({rotation:-2.4714,x:314.85,y:966.4},0).wait(1).to({rotation:-5.2117,x:313.25,y:966.8},0).wait(86));
// Face
this.instance_24 = new lib.シンボル1("synched",0);
this.instance_24.setTransform(317.75,960.15);
this.instance_24.alpha = 0;
this.timeline.addTween(cjs.Tween.get(this.instance_24).to({alpha:1},20).wait(29).to({startPosition:0},0).wait(146).to({rotation:-2.4714,x:317.55,y:960.45},0).wait(1).to({rotation:-5.2117,x:315.65,y:960.7},0).wait(86));
// left_ear
this.instance_25 = new lib.トゥイーン34("synched",0);
this.instance_25.setTransform(465.4,847.85,1,1,0,0,0,138.5,-99.9);
this.instance_25.alpha = 0;
this.timeline.addTween(cjs.Tween.get(this.instance_25).to({alpha:1},20).wait(15).to({startPosition:0},0).to({regX:138.6,rotation:18.9691,x:465.45,y:847.9},2).wait(1).to({regX:138.5,rotation:0,x:465.4,y:847.85},0).wait(11).to({regX:0,regY:0,x:326.9,y:947.75},0).wait(41).to({regX:138.5,regY:-99.9,x:465.4,y:847.85},0).to({regX:138.6,rotation:18.9691,x:465.45,y:847.9},2).wait(1).to({regX:138.5,rotation:0,x:465.4,y:847.85},0).wait(3).to({startPosition:0},0).to({regX:138.6,rotation:18.9691,x:465.45,y:847.9},2).wait(1).to({regX:138.5,rotation:0,x:465.4,y:847.85},0).wait(82).to({startPosition:0},0).to({regX:138.6,rotation:18.9691,x:465.45,y:847.9},2).wait(1).to({regX:138.5,rotation:0,x:465.4,y:847.85},0).wait(11).to({rotation:-2.4714,x:460.2,y:841.9},0).wait(1).to({regX:138.6,rotation:-5.2117,x:452.6,y:835.4},0).wait(26).to({startPosition:0},0).to({regY:-99.8,rotation:9.7872,y:835.5},13).wait(1).to({regY:-99.9,rotation:-5.2117,y:835.4},0).wait(46));
// right_ear
this.instance_26 = new lib.トゥイーン36("synched",0);
this.instance_26.setTransform(275.3,845.95,1,1,0,0,0,-51.6,-101.8);
this.instance_26.alpha = 0;
this.timeline.addTween(cjs.Tween.get(this.instance_26).to({alpha:1},20).wait(15).to({startPosition:0},0).to({rotation:-14.9992,x:275.25},2).wait(1).to({rotation:0,x:275.3},0).wait(11).to({regX:0,regY:0,x:326.9,y:947.75},0).wait(41).to({regX:-51.6,regY:-101.8,x:275.3,y:845.95},0).to({rotation:-14.9992,x:275.25},2).wait(1).to({rotation:0,x:275.3},0).wait(3).to({startPosition:0},0).to({rotation:-14.9992,x:275.25},2).wait(1).to({rotation:0,x:275.3},0).wait(82).to({startPosition:0},0).to({rotation:-14.9992,x:275.25},2).wait(1).to({rotation:0,x:275.3},0).wait(11).to({rotation:-2.4714,x:270.2,y:848.2},0).wait(1).to({rotation:-5.2117,x:262.95,y:850.8},0).wait(26).to({startPosition:0},0).to({regY:-101.7,rotation:-20.2105,y:850.9},13).wait(1).to({regY:-101.8,rotation:-5.2117,y:850.8},0).wait(46));
// body
this.instance_27 = new lib.トゥイーン11("synched",0);
this.instance_27.setTransform(344.35,1109.5);
this.instance_27.alpha = 0;
this.instance_28 = new lib.トゥイーン12("synched",0);
this.instance_28.setTransform(344.35,1109.5);
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.instance_27}]}).to({state:[{t:this.instance_28}]},20).to({state:[{t:this.instance_28}]},29).wait(233));
this.timeline.addTween(cjs.Tween.get(this.instance_27).to({_off:true,alpha:1},20).wait(262));
// ハート
this.instance_29 = new lib.トゥイーン38("synched",0);
this.instance_29.setTransform(634.2,947.45,1.3876,1.581,-19.9519,0,0,0.1,0.2);
this.instance_29._off = true;
this.timeline.addTween(cjs.Tween.get(this.instance_29).wait(198).to({_off:false},0).to({scaleX:5.3944,scaleY:5.9744,rotation:-49.9512,x:464.6,y:595.85},23,cjs.Ease.quintOut).wait(20).to({startPosition:0},0).wait(40).to({startPosition:0},0).wait(1));
// Back_hair
this.instance_30 = new lib.トゥイーン9("synched",0);
this.instance_30.setTransform(322.15,977.95);
this.instance_30.alpha = 0;
this.instance_31 = new lib.トゥイーン10("synched",0);
this.instance_31.setTransform(322.15,977.95);
this.instance_32 = new lib.PuppetShape_1("synched",195,false);
this.instance_32.setTransform(322,978,1,1,0,0,0,331,345);
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.instance_30}]}).to({state:[{t:this.instance_31}]},20).to({state:[{t:this.instance_31}]},29).to({state:[{t:this.instance_32,p:{startPosition:195}}]},145).to({state:[{t:this.instance_32,p:{startPosition:196}}]},1).to({state:[{t:this.instance_32,p:{startPosition:197}}]},1).wait(86));
this.timeline.addTween(cjs.Tween.get(this.instance_30).to({_off:true,alpha:1},20).wait(262));
// 背景
this.instance_33 = new lib.トゥイーン41("synched",0);
this.instance_33.setTransform(440.55,692.3);
this.instance_33.alpha = 0.2617;
this.timeline.addTween(cjs.Tween.get(this.instance_33).wait(282));
this._renderFirstFrame();
}).prototype = p = new lib.AnMovieClip();
p.nominalBounds = new cjs.Rectangle(-286.3,78.5,1640.6,1374.4);
// library properties:
lib.properties = {
id: 'BECA4F022B0146F68380A99859CD1618',
width: 700,
height: 1200,
fps: 30,
color: "#FFFFFF",
opacity: 1.00,
manifest: [
{src:"images/_925C5C11E60E1EF7.png?1598667105369", id:"_925C5C11E60E1EF7"},
{src:"images/card cow_girl_atlas_1.png?1598667105304", id:"card cow_girl_atlas_1"},
{src:"images/card cow_girl_atlas_2.png?1598667105304", id:"card cow_girl_atlas_2"},
{src:"images/card cow_girl_atlas_3.png?1598667105304", id:"card cow_girl_atlas_3"},
{src:"images/card cow_girl_atlas_4.png?1598667105304", id:"card cow_girl_atlas_4"},
{src:"images/card cow_girl_atlas_5.png?1598667105304", id:"card cow_girl_atlas_5"},
{src:"images/card cow_girl_atlas_6.png?1598667105304", id:"card cow_girl_atlas_6"},
{src:"images/card cow_girl_atlas_7.png?1598667105304", id:"card cow_girl_atlas_7"},
{src:"images/card cow_girl_atlas_8.png?1598667105304", id:"card cow_girl_atlas_8"},
{src:"images/card cow_girl_atlas_9.png?1598667105304", id:"card cow_girl_atlas_9"},
{src:"images/card cow_girl_atlas_10.png?1598667105304", id:"card cow_girl_atlas_10"},
{src:"images/card cow_girl_atlas_11.png?1598667105304", id:"card cow_girl_atlas_11"},
{src:"sounds/_20200829_110600wav.mp3?1598667105369", id:"_20200829_110600wav"}
],
preloads: []
};
// bootstrap callback support:
(lib.Stage = function(canvas) {
createjs.Stage.call(this, canvas);
}).prototype = p = new createjs.Stage();
p.setAutoPlay = function(autoPlay) {
this.tickEnabled = autoPlay;
}
p.play = function() { this.tickEnabled = true; this.getChildAt(0).gotoAndPlay(this.getTimelinePosition()) }
p.stop = function(ms) { if(ms) this.seek(ms); this.tickEnabled = false; }
p.seek = function(ms) { this.tickEnabled = true; this.getChildAt(0).gotoAndStop(lib.properties.fps * ms / 1000); }
p.getDuration = function() { return this.getChildAt(0).totalFrames / lib.properties.fps * 1000; }
p.getTimelinePosition = function() { return this.getChildAt(0).currentFrame / lib.properties.fps * 1000; }
an.bootcompsLoaded = an.bootcompsLoaded || [];
if(!an.bootstrapListeners) {
an.bootstrapListeners=[];
}
an.bootstrapCallback=function(fnCallback) {
an.bootstrapListeners.push(fnCallback);
if(an.bootcompsLoaded.length > 0) {
for(var i=0; i<an.bootcompsLoaded.length; ++i) {
fnCallback(an.bootcompsLoaded[i]);
}
}
};
an.compositions = an.compositions || {};
an.compositions['BECA4F022B0146F68380A99859CD1618'] = {
getStage: function() { return exportRoot.stage; },
getLibrary: function() { return lib; },
getSpriteSheet: function() { return ss; },
getImages: function() { return img; }
};
an.compositionLoaded = function(id) {
an.bootcompsLoaded.push(id);
for(var j=0; j<an.bootstrapListeners.length; j++) {
an.bootstrapListeners[j](id);
}
}
an.getComposition = function(id) {
return an.compositions[id];
}
an.makeResponsive = function(isResp, respDim, isScale, scaleType, domContainers) {
var lastW, lastH, lastS=1;
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
function resizeCanvas() {
var w = lib.properties.width, h = lib.properties.height;
var iw = window.innerWidth, ih=window.innerHeight;
var pRatio = window.devicePixelRatio || 1, xRatio=iw/w, yRatio=ih/h, sRatio=1;
if(isResp) {
if((respDim=='width'&&lastW==iw) || (respDim=='height'&&lastH==ih)) {
sRatio = lastS;
}
else if(!isScale) {
if(iw<w || ih<h)
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==1) {
sRatio = Math.min(xRatio, yRatio);
}
else if(scaleType==2) {
sRatio = Math.max(xRatio, yRatio);
}
}
domContainers[0].width = w * pRatio * sRatio;
domContainers[0].height = h * pRatio * sRatio;
domContainers.forEach(function(container) {
container.style.width = w * sRatio + 'px';
container.style.height = h * sRatio + 'px';
});
stage.scaleX = pRatio*sRatio;
stage.scaleY = pRatio*sRatio;
lastW = iw; lastH = ih; lastS = sRatio;
stage.tickOnUpdate = false;
stage.update();
stage.tickOnUpdate = true;
}
}
an.handleSoundStreamOnTick = function(event) {
if(!event.paused){
var stageChild = stage.getChildAt(0);
if(!stageChild.paused){
stageChild.syncStreamSounds();
}
}
}
})(createjs = createjs||{}, AdobeAn = AdobeAn||{});
var createjs, AdobeAn;
|
const mongoose = require('mongoose');
const db = mongoose.connection;
mongoose.connect("mongodb://localhost:27017/test",{
useNewUrlParser: true,
useUnifiedTopology: true
})
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', (success)=>{
console.log('connected db: test')
if(success){
success()
}
})
db.on('disconnected', function () {
console.log('MongoDB disconnected!');
mongoose.connect(config.mongodb, {
useNewUrlParser: true,
useUnifiedTopology: true
});
});
db.on('connecting', function () {
console.log('connecting to MongoDB...');
});
db.on('connected', function () {
console.log('MongoDB connected!');
});
db.on('reconnected', function () {
console.log('MongoDB reconnected!');
});
// 验证码
let checkcodeSchema = new mongoose.Schema({
token: String,
code: String
})
// 用户
let userSchema = new mongoose.Schema({
name: String,
userId: String,
pwd: String,
avatar: {
type: String,
default: ""
},
token: {
type: String,
default: ""
}
})
// 留言
let commentSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.ObjectId,
ref: 'User'
},
content: String,
create_time: {
type: String,
default: Date.now
}
})
exports.Checkcode = mongoose.model('Checkcode', checkcodeSchema);
exports.User = mongoose.model('User', userSchema);
exports.Comment = mongoose.model('Comment', commentSchema);
|
//load required modules
var esprima = require('esprima');
var estraverse = require('estraverse');
var traverseJS = require('./TraverseJS.js');
module.exports.build = function(data) {
//build the ast
var ast = esprima.parse(data, {
loc: true
});
//the abstraction that will contain all instructions
var abst = {}
//traverse the ast
estraverse.traverse(ast, {
enter: enterNode,
leave: leaveNode
});
return abst;
function enterNode(node, parent) {
switch (node.type) {
case 'Program':
traverseJS.enterProgram(node, parent);
break;
case 'VariableDeclaration':
traverseJS.enterVariableDeclaration(node, parent);
break;
case 'VariableDeclarator':
traverseJS.enterVariableDeclarator(node, parent);
break;
case 'UnaryExpression':
traverseJS.enterUnaryExpression(node, parent);
break;
case 'BinaryExpression':
traverseJS.enterBinaryExpression(node, parent);
break;
case 'UpdateExpression':
traverseJS.enterUpdateExpression(node, parent);
break;
case 'MemberExpression':
traverseJS.enterMemberExpression(node, parent, abst);
break;
case 'ExpressionStatement':
traverseJS.enterExpressionStatement(node, parent);
break;
case 'AssignmentExpression':
traverseJS.enterAssignmentExpression(node, parent);
break;
case 'CallExpression':
traverseJS.enterCallExpression(node, parent);
break;
case 'FunctionExpression':
traverseJS.enterFunctionExpression(node, parent);
break;
case 'FunctionDeclaration':
traverseJS.enterFunctionDeclaration(node, parent);
break;
case 'BlockStatement':
traverseJS.enterBlockStatement(node, parent);
break;
case 'IfStatement':
traverseJS.enterIfStatement(node, parent);
break;
};
};
function leaveNode(node, parent) {
switch (node.type) {
case 'Program':
abst = traverseJS.leaveProgram(node, parent);
break;
case 'VariableDeclaration':
traverseJS.leaveVariableDeclaration(node, parent);
break;
case 'VariableDeclarator':
traverseJS.leaveVariableDeclarator(node, parent);
break;
case 'UnaryExpression':
traverseJS.leaveUnaryExpression(node, parent);
break;
case 'BinaryExpression':
traverseJS.leaveBinaryExpression(node, parent);
break;
case 'UpdateExpression':
traverseJS.leaveUpdateExpression(node, parent);
break;
case 'MemberExpression':
traverseJS.leaveMemberExpression(node, parent, abst);
break;
case 'ExpressionStatement':
traverseJS.leaveExpressionStatement(node, parent);
break;
case 'AssignmentExpression':
traverseJS.leaveAssignmentExpression(node, parent);
break;
case 'CallExpression':
traverseJS.leaveCallExpression(node, parent);
break;
case 'FunctionExpression':
traverseJS.leaveFunctionExpression(node, parent);
break;
case 'FunctionDeclaration':
traverseJS.leaveFunctionDeclaration(node, parent);
break;
case 'BlockStatement':
traverseJS.leaveBlockStatement(node, parent);
break;
case 'IfStatement':
traverseJS.leaveIfStatement(node, parent);
break;
};
};
};
module.exports.prettyPrint = function(abst) {
for (var i = 0; i < abst.instructions.length; i++) {
console.log(abst.instructions[i].prettyPrint());
};
};
|
let heading = document.querySelector(".heading");
// let headingText = "Welcome to 30 days of JavaScript";
heading.innerText = "Welcome to 30 days of JavaScript";
let button = document.querySelector(".button");
button.innerText = "Learn Python";
button.addEventListener("click", replaceLanguage);
function replaceLanguage() {
if(button.innerText === "Learn Python") {
heading.innerText = "Welcome to 30 days of Python";
button.innerText = "Learn JavaScript";
} else {
heading.innerText = "Welcome to 30 days of JavaScript";
button.innerText = "Learn Python";
}
}
|
// all "require" better to include all at top
require('dotenv').config()
var express = require('express')
var morgan = require('morgan')
var app = express()
app.use(morgan('combined'))
app.use(express.json({
limit: '10mb',
extended: true
}));
var router = require('./routes/main-route')
//static folder (e.g. css files)
app.use('/public', express.static('public'))
//all your routes
app.use('/', router);
//templating engine
app.set('view engine', 'pug')
//setting port
var port = process.env.PORT || 8080;
//start listening at the configured port
app.listen(port, '0.0.0.0', "localhost", () => {
console.log("Listning at port: " + port)
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.