text
stringlengths 7
3.69M
|
|---|
function solve(array, n)
{
let rotations=array.length<n?n%array.length:n;
for (let i = 0; i < rotations; i++) {
array.unshift(array.pop());
}
console.log(`${array.join(' ')}`);
}
solve(
['1',
'2',
'3',
'4'], 2)
solve(['Banana',
'Orange',
'Coconut',
'Apple'],
15
)
|
import React, { Component } from 'react'
import HeaderTitle from './HeaderTitle'
import HeaderNav from './HeaderNav'
import './css/mainSectionHeader.css'
export default class MainSectionHeader extends Component {
state = {
headerTitle: 'Browse Available Books',
navLinks: [
{
title: 'All Books',
id: '1',
},
{
title: 'Most Recent',
id: '2',
},
{
title: 'Most Popular',
id: '3',
},
{
title: 'Free Books',
id: '4',
},
]
}
render() {
return (
<div className='main-section-header' >
<HeaderTitle title={this.state.headerTitle} />
<HeaderNav links={this.state.navLinks}/>
</div>
)
}
}
|
'use strict';
class Locator {
/**
* @param {config} config
* @param {{}} locatableConfig
* @param {string} relativePathModifierToRoot eg '../../' if the locator is one folder deep from the root
*/
constructor(config, locatableConfig, relativePathModifierToRoot) {
this._config = config;
this._locatableConfig = locatableConfig;
this._relativePathModifierToRoot = relativePathModifierToRoot || '../../';
this._locatable = {};
this._reservedCharacters = ['%', '@', '~'];
}
/**
* @param {string} name
* @returns {object}
*/
get(name) {
//there is already an instance
if (this._locatable[name] !== undefined) {
return this._locatable[name];
}
//there is no locatable config, throw an error
if (this._locatableConfig[name] === undefined) {
throw new Error('Could not retrieve an instance for ' + name);
}
//it's an alias, return the referenced object
if (typeof this._locatableConfig[name] === 'string') {
this._locatable[name] = this.get(this._locatableConfig[name]);
return this._locatable[name];
}
//create an instance based on the configuration
this._locatable[name] = this._createInstance(this._locatableConfig[name]);
return this._locatable[name];
}
/**
* @param {string} requirable
* @returns {object}
* @private
*/
_require(requirable) {
const originalRequirable = requirable;
if (requirable[0] === '.' && requirable[1] === '/') {
requirable = this._relativePathModifierToRoot + requirable.substr(2);
}
if (requirable.indexOf('[') === -1) {
return require(requirable);
}
const splittedRequirable = requirable.split('[');
requirable = splittedRequirable[0];
let result = require(requirable);
splittedRequirable.shift();
while(splittedRequirable.length > 0) {
const subRequirable = splittedRequirable.shift().replace(']', '');
if (result[subRequirable] === undefined) {
throw new Error('Could not require ' + originalRequirable);
}
result = result[subRequirable];
}
return result;
}
/**
* @param {{Array}|{string}} locatableConfig
* @return {object}
* @private
*/
_createInstance(locatableConfig) {
//the config is a factory method, call and return it
if (typeof locatableConfig === 'function') {
return locatableConfig(this, this._config);
}
const c = this._require(locatableConfig[0]);
//if the second argument is a function, use it as factory method
if (typeof locatableConfig[1] === 'function') {
return locatableConfig[1](this, c, this._config);
}
//if c is not constructable, return c
if (c.prototype === undefined || c.prototype.constructor === undefined) {
return c;
}
const dependencyConfigs = locatableConfig[1] || [];
const dependencies = [];
for (const dependencyConfig of dependencyConfigs) {
dependencies.push(this._getDependency(dependencyConfig));
}
return new c(...dependencies);
}
/**
* @param {string|*} dependencyConfig
* @returns {object|*}
* @private
*/
_getDependency(dependencyConfig) {
if (typeof dependencyConfig !== 'string') {
return dependencyConfig;
}
const firstChar = dependencyConfig[0];
const secondChar = dependencyConfig[1];
if (this._dependencyConfigIsEscaped(firstChar, secondChar)) {
return dependencyConfig.substr(1);
}
//config parameter
if (firstChar === '%') {
const configName = dependencyConfig.substr(1, dependencyConfig.length - 2);
return this._config.get(configName);
}
//another service
if (firstChar === '@') {
const name = dependencyConfig.substr(1);
return this.get(name);
}
//require
if (firstChar === '~') {
const requirable = dependencyConfig.substr(1);
return this._require(requirable);
}
return dependencyConfig;
}
/**
* @param {string} firstChar
* @param {string} secondChar
* @returns {boolean}
* @private
*/
_dependencyConfigIsEscaped(firstChar, secondChar) {
if (this._reservedCharacters.indexOf(firstChar) === -1) {
return false;
}
return firstChar === secondChar;
}
}
module.exports = Locator;
|
'use strict';
// import the mountebank helper library
const mb_helper = require('../src/mb_helper');
// create the skeleton for the imposter (does not post to MB)
const firstImposter = new mb_helper.Imposter({ 'imposterPort' : 3000 });
// construct sample responses and conditions on which to send it
const sampleResponse = {
'uri' : '/hello',
'verb' : 'GET',
'res' : {
'statusCode': 200,
'responseHeaders' : { 'Content-Type' : 'application/json' },
'responseBody' : JSON.stringify({ 'hello' : 'world' })
}
};
const anotherResponse = {
'uri' : '/pets/123',
'verb' : 'PUT',
'res' : {
'statusCode': 200,
'responseHeaders' : { 'Content-Type' : 'application/json' },
'responseBody' : JSON.stringify({ 'somePetAttribute' : 'somePetValue' })
}
};
// add our responses to our imposter
firstImposter.addRoute(sampleResponse);
firstImposter.addRoute(anotherResponse);
firstImposter.postToMountebank()
.then(response => {
console.log('response: ');
console.log(response);
})
.catch(error => {
console.log('error: ');
console.log(error);
})
.then( () => {
firstImposter.updateResponseBody(JSON.stringify({ 'WHAT' : 'UP' }), { 'verb' : 'GET', 'uri' : '/hello' });
})
.catch(error => {
console.log('second error: ');
console.log(error);
});
|
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function() {
return gulp.src(['./scss/**/*.scss', '!./scss/**/_*.scss', '!./scss/**/_tmp/**/*'])
.pipe(sass())
.pipe(gulp.dest(function(file) {
var base = file.base;
return base.replace('scss', 'src');
}));
});
gulp.task('default', ['sass']);
|
import RoleDelete from "./RoleDelete";
export {RoleDelete}
export default RoleDelete
|
import React, { useEffect, useState } from "react";
import { useParams } from "react-router";
import "../styles/profile.css";
// import logo from "../assests/logo.png";
import axios from "axios";
import Button from "@material-ui/core/Button";
import Tooltip from "@material-ui/core/Tooltip";
import Dialog from "@material-ui/core/Dialog";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import CircularProgress from "@material-ui/core/CircularProgress";
function Profile() {
const [user, setUser] = useState({});
const [dialog, setDialoag] = useState(false);
const { id } = useParams();
const logoutUser = () => {
setDialoag(true);
axios
.get("/user/logout")
.then((response) => {
console.log(response);
localStorage.removeItem("user_credientials");
window.location.replace("/login");
setDialoag(true);
})
.catch((err) => {
console.log(err);
});
};
const closeDialog = () => {
setDialoag(false);
};
useEffect(() => {
axios
.get(`/user/getUser/${id}`)
.then((res) => {
console.log(res.data);
setUser(res.data);
})
.catch((err) => {
console.log(err);
});
}, []);
return (
<div className="profile">
<img src={user.image} alt={user.username} className="user_image" />
<div className="user_data">
<p>Username : {user.username}</p>
<p>Name : {user.fullname}</p>
<p>Email : {user.email}</p>
<p>Phone number : {user.phone}</p>
<Tooltip title="want to logout?" aria-label="Profile">
<Button variant="contained" color="secondary" onClick={logoutUser}>
Logout
</Button>
</Tooltip>
</div>
<Dialog open={dialog} onClose={closeDialog}>
<DialogContent>
<DialogContentText id="alert-dialog-description">
<CircularProgress color="secondary" size="3rem" />
</DialogContentText>
</DialogContent>
</Dialog>
</div>
);
}
export default Profile;
|
const supertest = require('supertest');
const app = require('../../app');
const factory = require('../factory/users');
const { UNPROCESSABLE_ENTITY_ERROR, UNAUTHORIZED_ERROR } = require('../../app/errors');
const server = supertest(app);
let data = {};
let userTest = {};
describe('Signin suite tests', () => {
beforeAll(async () => {
data = { email: 'test@wolox.co', password: 'test1234' };
userTest = await factory.attributes({ ...data, last_name: 'test' });
});
beforeEach(async () => {
await server.post('/users').send(userTest);
});
test('Token created OK', async done => {
const result = await server.post('/users/sessions').send(data);
expect(result.statusCode).toBe(200);
expect(result.body).toHaveProperty('token');
done();
});
test('Email domain not allowed', async done => {
const result = await server.post('/users/sessions').send({ ...data, email: 'test@gmail.com' });
expect(result.statusCode).toBe(422);
expect(result.body.internal_code).toBe(UNPROCESSABLE_ENTITY_ERROR);
done();
});
test('Wrong password', async done => {
const result = await server.post('/users/sessions').send({ ...data, password: 'wrong123' });
expect(result.statusCode).toBe(401);
expect(result.body.internal_code).toBe(UNAUTHORIZED_ERROR);
done();
});
test('No mandatory fields', async done => {
const result = await server.post('/users/sessions').send({});
expect(result.statusCode).toBe(422);
expect(result.body.internal_code).toBe(UNPROCESSABLE_ENTITY_ERROR);
expect(result.body.message).toHaveProperty('email');
expect(result.body.message).toHaveProperty('password');
done();
});
});
|
import React from 'react';
import { describe, add } from '@sparkpost/libby-react';
import { DatePicker, useBreakpoint } from '@sparkpost/matchbox';
import { DateUtils } from 'react-day-picker';
// @example
// const breakpoint = useBreakpoint();
// const months = React.useMemo(() => {
// return ['default', 'xs', 'sm'].includes(breakpoint) ? 1 : 2;
// }, [breakpoint]);
// const to = new Date();
// const from = new Date(new Date().setDate(new Date().getDate() - 15));
// const initial = ['default', 'xs', 'sm'].includes(breakpoint)
// ? new Date()
// : new Date(new Date().setDate(new Date().getDate() - 30));
// const selectedDays = {
// to,
// from,
// };
// const modifiers = {
// firstSelected: day => {
// return DateUtils.isSameDay(day, selectedDays.from);
// },
// lastSelected: day => DateUtils.isSameDay(day, selectedDays.to),
// inBetween: day => DateUtils.isDayBetween(day, selectedDays.from, selectedDays.to),
// };
// return (
// <DatePicker
// modifiers={modifiers}
// initialMonth={initial}
// numberOfMonths={months}
// disabledDays={{ after: new Date() }}
// toMonth={new Date()}
// selectedDays={selectedDays}
// onDayClick={d => console.log('click', d)}
// m="400"
// />
// );
const to = new Date();
const from = new Date(new Date().setDate(new Date().getDate() - 15));
const selectedDays = {
to,
from,
};
const modifiers = {
firstSelected: day => {
return DateUtils.isSameDay(day, selectedDays.from);
},
lastSelected: day => DateUtils.isSameDay(day, selectedDays.to),
inBetween: day => DateUtils.isDayBetween(day, selectedDays.from, selectedDays.to),
};
describe('DatePicker', () => {
add('basic usage', () => {
const breakpoint = useBreakpoint();
const months = React.useMemo(() => {
return ['default', 'xs', 'sm'].includes(breakpoint) ? 1 : 2;
}, [breakpoint]);
const initial = ['default', 'xs', 'sm'].includes(breakpoint)
? new Date()
: new Date(new Date().setDate(new Date().getDate() - 30));
return (
<DatePicker
modifiers={modifiers}
initialMonth={initial}
numberOfMonths={months}
disabledDays={{ after: new Date() }}
toMonth={new Date()}
selectedDays={selectedDays}
onDayClick={d => console.log('click', d)}
m="400"
/>
);
});
});
|
const User = require("../models/user");
module.exports = function(app, passport){
app.get("/", function(res, req){
res.send("Welcome to hitchAlong! app Root Page");
});
app.post("/login", passport.authenticate("local-login"), function(req, res){
console.log("sending..." + req.body);
res.send(req.body);
});
app.post("/signup", passport.authenticate("local-signup"), function(req, res){
console.log("sending..." + req.body);
console.log("Result: " + res);
res.send(req.body);
});
};
|
function showUser( id ) {
$.getJSON('/api/users/'+id, function (response) {
$('#users-form-modal .modal-title').html('Exibindo usuário <b><i>' + response.name + '</i></b>');
$('#users-form-modal').modal('show');
console.log( response );
});
// Limpeza ao final
$('#users-form-modal .modal-title').html(' ');
$('#users-form-modal .modal-body').html(' ');
}
|
import React, { useState } from "react";
import './SearchEngine.css';
import Results from "./Results";
import Photos from "./Photos";
import axios from "axios";
export default function SearchEngine () {
let [keyword, setKeyword] = useState("");
let [results, setResults] = useState (null);
let [photos, setPhotos] = useState(null);
function handleDicitonaryResponse (response) {
setResults(response.data[0]);
}
function handlePexelsResponse (response) {
setPhotos(response.data.photos);
}
function search(event){
event.preventDefault ();
let apiUrl = `https://api.dictionaryapi.dev/api/v2/entries/en/${keyword}` ;
axios.get(apiUrl).then(handleDicitonaryResponse);
let apiKeyPhotos="563492ad6f917000010000016f0115c6c86644c18a14defcaba701cf";
let apiUrlPhotos= `https://api.pexels.com/v1/search?query=${keyword}&per_page=8`;
axios.get(apiUrlPhotos, {headers: {"Authorization": `Bearer ${apiKeyPhotos}`}}).then(handlePexelsResponse);
}
function handleKeywordChange(event) {
setKeyword(event.target.value);
}
return(
<div className="SearchEngine">
<div className="input-title"><strong>What word do you want to look up?</strong></div>
<form onSubmit={search}>
<input type="search" placeholder="Search a word ..." autoFocus={true} onChange={handleKeywordChange} className="col search-bar"/>
<input type="submit" className="btn btn-info btn-lg" value="Search"/>
</form>
<Results results={results}/>
<Photos photos={photos}/>
</div>
);
}
|
import React, { Component } from 'react';
import './../Css/App.css';
import Header from './Header';
import Search from './Search';
import TableData from './TableData';
import AddUser from './AddUser';
import EditUser from './EditUser';
import DataUser from './../Database/Data';
import { v4 as uuidv4 } from 'uuid';
class App extends Component {
constructor(props) {
super(props);
this.state = {
addFormStatus: false,
data: [],
textSearch:"",
editFormStatus: false,
userEditObject:{}
}
}
componentWillMount() {
if(localStorage.getItem("userData") === null){
localStorage.setItem("userData", JSON.stringify(DataUser));
} else{
let tempData = JSON.parse(localStorage.getItem("userData"));
this.setState({
data: tempData
});
}
}
deleteUser = (id) => {
let dataAfterDelete = this.state.data.filter(item => item.id !== id);
this.setState({
data: dataAfterDelete
});
localStorage.setItem("userData", JSON.stringify(dataAfterDelete));
}
getUserEditInfo = (info) => {
this.state.data.forEach((value) => {
if(value.id === info.id){
value.id = info.id;
value.name = info.name;
value.phone = info.phone;
value.level = info.level
}
})
localStorage.setItem("userData", JSON.stringify(this.state.data));
}
changeEditStatus = () => {
this.setState({
editFormStatus: !this.state.editFormStatus
});
}
showEditForm = () => {
if(this.state.editFormStatus === true){
return <EditUser getUserEditInfo={(info) => this.getUserEditInfo(info)} userEditObject={this.state.userEditObject} changeEditStatus={() => this.changeEditStatus()}/>
}
}
editUser = (user) => {
this.setState({
userEditObject: user
});
}
getNewUserData = (name, phone, level) => {
let item = {};
item.id = uuidv4();
item.name = name;
item.phone = phone;
item.level = level;
let newData = this.state.data;
newData.push(item);
this.setState({
data: newData
});
localStorage.setItem("userData", JSON.stringify(newData));
}
showAddForm = () => {
if(this.state.addFormStatus === true){
return <AddUser add={(name, phone, level) => this.getNewUserData(name, phone, level)}/>
}
}
changeAddFormStatus = () => {
this.setState({
addFormStatus : !this.state.addFormStatus
});
}
getTextSearch = (text) => {
this.setState({
textSearch: text
});
}
render() {
let resultSearch = [];
let data = this.state.data;
data.forEach((item) => {
if(item.name.toLowerCase().indexOf(this.state.textSearch.toLowerCase()) !== -1 || item.phone.indexOf(this.state.textSearch) !== -1){
if(this.state.textSearch.length >= 2){
resultSearch.push(item);
}else{
resultSearch = this.state.data;
}
}
});
return (
<div>
<Header/>
<Search
getTextSearch={(text) => this.getTextSearch(text)}
addFormStatus={this.state.addFormStatus}
changeAddFormStatus={() => this.changeAddFormStatus()}
/>
<div className="container">
<div className="row">
{this.showEditForm()}
</div>
</div>
<div className="content">
<div className="container">
<div className="row">
<TableData
deleteUser={(id) => this.deleteUser(id)}
changeEditStatus={() => this.changeEditStatus()}
editUser={(user) => this.editUser(user)}
data={resultSearch}
/>
{this.showAddForm()}
</div>
</div>
</div>
</div>
);
}
}
export default App;
|
let n = parseInt(prompt('Введіть будь ласка число'));
let m = parseInt(prompt('Введіть будь ласка число'));
if(!Number.isInteger(n) || !Number.isInteger(m)){
alert('Спробуйте ще раз');
}else{
const skipPairs = confirm('Пропускати парні?');
let result = null;
for(let i = n; i <= m; ++i){
if(skipPairs && !(i % 2)){
continue;
}
result += i;
};
alert(result);
}
|
import { baseUrl } from '@/config/application'
export default {
/* 分类相关 */
// 获取大分类别
async getTypeList ({commit}) {
let json = await (await fetch(`${baseUrl}/cla/list`)).json()
commit('getTypeList', json)
},
// 根据大分类id,获取小分类别
async getTypeItem ({commit}, arg) {
let json = await (await fetch(`${baseUrl}/cla/detail?id=${arg}`)).json()
commit('getTypeItem', json)
},
/* 购物车相关 */
// 设置购物车总价
async setSumPrice ({commit, state}) {
let sum = 0
state.carList.forEach(el => (sum += (el.checked ? (el.price * el.total) : 0)))
commit('setSumPrice', sum)
},
// 设置购物车
async setCatList ({commit, state}) {
let json = await (await fetch(`${baseUrl}/car/list?id=1`)).json()
commit('setCatList', json)
let sum = 0
state.carList.forEach(el => (sum += (el.checked ? (el.price * el.total) : 0)))
commit('setSumPrice', sum) // 计算总价
},
// 勾选商品
async choseTotal ({commit, state}, arg) {
commit('choseTotal', arg)
},
// 勾选商品
async choseGoods ({commit, state}, arg) {
commit('choseGoods', arg)
},
// 勾选全部
async checkAll ({commit}, arg) {
commit('checkAll', arg)
},
// 获取订单列表
async getAllOrder ({commit}, arg) {
let json = await (await fetch(`${baseUrl}/order/list?id=1`)).json()
commit('getAllOrder', json)
}
}
|
import React from 'react';
import { Redirect } from "react-router-dom";
import {getRequest} from './api';
import { ROUTES } from 'utils/RoutePaths';
const TokenExpired = (props) => {
async function deleteToken() {
await getRequest('/error');
localStorage.clear();
}
deleteToken();
return (
<Redirect to={{pathname: ROUTES.LOGIN,state:{ from: props.location}}} />
);
}
export default TokenExpired;
|
const mongoose = require("mongoose");
const { Activity } = require("./activity");
const { Food } = require("./food");
const { Meal } = require("./meal");
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
firstName: {
type: String,
required: false,
},
lastName: {
type: String,
required: false,
},
goalDailyCalories: {
type: Number,
required: false,
},
goalDailyProtein: {
type: Number,
required: false,
},
goalDailyCarbohydrates: {
type: Number,
required: false,
},
goalDailyFat: {
type: Number,
required: false,
},
goalDailyActivity: {
type: Number,
required: false,
},
activities: {
type: [Activity.schema],
required: true,
},
meals: {
type: [Meal.schema],
required: true,
},
foods: {
type: [Food.schema],
required: true,
},
});
module.exports = {
User: mongoose.model("User", userSchema),
};
|
const puppeteer = require("puppeteer");
const fbPage = "https://www.facebook.com/";
const targetPage =
"https://www.facebook.com/psantosfitt/posts/3058604314253749";
function startComment(page) {
const iterator = async (resolve, reject, iteration = 0) => {
try {
const comment = "Up";
const inputQuery = "div.notranslate";
if ((await page.url()) === targetPage) {
if (iteration === 0) {
await page.waitFor(inputQuery);
}
await page.type(inputQuery, comment);
await page.waitFor(1000 * 10); // 10s
await page.keyboard.press(String.fromCharCode(13));
}
if (iteration >= 10000) {
resolve();
} else {
return iterator(resolve, reject, iterator + 1);
}
} catch (e) {
reject(e);
}
};
return new Promise((resolve, reject) => iterator(resolve, reject));
}
async function main() {
try {
const email = "your email goes here";
const pass = "your password goes here";
const browser = await puppeteer.launch({ headless: false, timeout: 30000 });
const page = await browser.newPage();
// set user agent (override the default headless User Agent)
await page.setUserAgent(
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
);
await page.goto(fbPage);
await page.waitFor("input#email");
await page.waitFor("input#pass");
await page.type("input#email", email);
await page.type("input#pass", pass);
await page.tap("input[type=submit]");
await page.waitFor(2500);
await page.goto(targetPage);
await startComment(page);
await browser.close();
} catch (e) {
console.log({ e });
}
}
main();
|
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
return this.get('store').findRecord('cocktail', params.id);
},
actions: {
saveCocktail(country) {
let confirmation = confirm('Are you sure?');
if (confirmation) {
country.save();
}
}
}
});
|
var app=angular.module('app',['ui.bootstrap','ui.router','employees','app.data','category','project','entities']);
app.config(function($stateProvider,$urlRouterProvider,$httpProvider){
//For unmatched url, redirect to /state1
$urlRouterProvider.otherwise('/');
$stateProvider
.state('root',{
url:'',
abstract:true,
views:{
'header':{
templateUrl:'partials/Home/header.html',
controller:'HeaderCtrl',
controllerAs:'hdc'
},
'leftmenu':{
templateUrl:'partials/Home/leftmenu.html',
// controller:'LeftCtrl',
// controllerAs:'leftCtrl'
},
'footer':{
templateUrl:'partials/Home/footer.html',
// controller:'FooterCtrl',
// controllerAs:'footerCtrl'
}
}
})
.state('login',{
url:'/',
views:{
'login':{
templateUrl:'partials/Accounts/login.html',
controller:'LoginCtrl',
controllerAs:'lgc'
}
}
})
.state('root.dashboard',{
url:'/dashboard',
views:{
'content@':{
templateUrl:'partials/Employees/employeeList.html',
controller:'EmployeeListCtrl',
controllerAs:'elc',
resolve:{
employees:function(dataService){
return dataService.getData('http://localhost/advanced/api/web/index.php/v1/employees').then(function(result){
return result;
});
},
categories:function(dataService){
return dataService.getData('http://localhost/advanced/api/web/index.php/v1/categories').then(function(result){
return result;
})
}
}
}
}
})
})
|
var loading = {
// 单位rpx
X: 410,
//宽
Y: 410,
//高
color: "#E9302D"
};
var app = getApp();
Page({
data: {},
onLoad: function onLoad(options) {
this.init();
},
// 初始化
init: function init() {
var screenWidth = app.globalData.screenWidth;
loading.X = loading.X / 750 * wx.getSystemInfoSync().windowWidth;
loading.Y = loading.Y / 750 * wx.getSystemInfoSync().windowWidth;
this.drawLoading();
},
drawLoading: function drawLoading() {
var ctx = wx.createCanvasContext("loading");
ctx.arc(loading.X / 2, loading.Y / 2, loading.X / 2, 0, 2 * Math.PI);
ctx.stroke();
ctx.draw();
}
});
|
import React, { Component } from 'react';
import './league.css';
// import { Button } from 'reactstrap';
import { Link } from 'react-router-dom';
// import { Wrapper } from '../../Wrappers/wrapbut.js';
const text = [
{ name: 'RPL', fullname: 'SERIE A',
txt: '' },
{ name: 'EPL', fullname: 'ENGLISH PREMIER LEAGUE',
txt: '' },
{ name: 'LL', fullname: 'LA LIGA',
txt: '' },
{ name: 'Bundesliga', fullname: 'BUNDESLIGA',
txt: '' }
];
export default class Leaguepage extends Component {
constructor(props) {
super(props);
}
render() {
const link = this.props.link;
const content = ' consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
// console.log(link);
return (
<div className = 'container pl-0 pr-0 pb-0'>
<div className = 'row align-items-center justify-content-center'>
{text.map((item) => {
if (link === item.name) {
return (
<div className='col-10 col-md-10 mr-1 pt-4' key = {item.name}
style = {{ paddingTop: '1%' }}
>
<div className = 'container m-0 p-2'>
<div className = 'row justify-content-center'
style = {{ height: '88%' }}
>
<div className = 'col pl-4 pr-4 pb-4 anim'
style = {{ width: '50%', marginTop: '4%' }}
>
<Link to = {`/table/${link}`} key = {item.name}
className='btn btn-primary'
style = {{ borderRadius: '50%', display: 'block', height: '363.56px' }}
>
<h3 className = 'p-1 display-4'
style = {{ marginTop: '110px' }}
>TABLE GRAPH</h3>
<p
style = {{ fontSize: '20pt' }}
>
Кликни на кружок
</p>
</Link>
</div>
<div className = 'col pl-4 pr-4 pb-4 anim'
style = {{ width: '50%', marginTop: '4%' }}
>
<Link to = {`/scores/${link}`}
className='btn btn-primary'
style = {{ borderRadius: '50%', display: 'block', height: '363.56px' }}
>
<h3 className = 'p-1 display-4'
style = {{ marginTop: '110px' }}
>SIMPLE TABLE</h3>
<p
style = {{ fontSize: '20pt' }}
>
Кликни на кружок
</p>
</Link>
</div>
</div>
</div>
</div>
);
}
// console.log('false');
})
}
</div>
</div>
);
}
}
|
const http = require('http');
const url = require('url');
const DEFAULT_TIMEOUT = 0;
const DEFAULT_VAR_TIMEOUT = 0;
const DEFAULT_STATUS_CODE = 200;
const requestHandler = async (req, res) => {
const { query } = url.parse(req.url, true);
let timeout = parseInt(query.wait || DEFAULT_TIMEOUT, 10);
timeout += Math.round(Math.random() * parseInt(query.varWait || DEFAULT_VAR_TIMEOUT, 10));
let statusCode = parseInt(query.statusCode, 10) || DEFAULT_STATUS_CODE;
if (query.error > Math.round(Math.random() * 100)) statusCode = 500;
res.statusCode = statusCode;
setTimeout(() => res.end(), timeout);
};
const host = 'localhost';
const port = 4343;
const server = http.createServer(requestHandler);
server.listen({ host, port }, () => {
const address = server.address();
console.log(`Server is listening on ${address.address}:${address.port}`);
});
|
import { combineReducers } from 'redux'
import search from './search'
import cart from './cart'
import orders from './orders'
import order from './order'
import stat from './stat'
export default combineReducers({
search,
cart,
orders,
order,
stat,
})
|
/*
Program Table Definition
Input: getting cylinder information
Processing: calculate the volume
Output: show the result of the calculation
*/
function volume(){
let radius = parseFloat(document.getElementById("radius").value);
let height = parseFloat(document.getElementById("height").value);
//calculation
let volume = parseFloat(Math.PI * radius*radius * height);
//showing the final result in the HTML
document.getElementById("output").innerHTML = volume.toFixed(2) + " liters";
}
|
app.filter('findAttr', function () {
return function (jsonTest,attrName) {
try{
var json = JSON.parse(jsonTest);
if(json["content"]){
if(json["content"][attrName]){
return json["content"][attrName] ;
}else{
if(attrName=='code'){
attrName = 'responseCode'
}
else if(attrName=='message'){
attrName = 'responseMessage'
}
return json[attrName] ;
}
return json["content"][attrName];
}else{
return json[attrName];
}
}catch(e) {
return "";
}
};
});
|
'use strict';
var positionData = {};
function getLocation() {
return new Promise(function(resolve, reject) {
navigator.geolocation.getCurrentPosition(function(position) {
positionData.latitude = position.coords.latitude;
positionData.longitude = position.coords.longitude;
resolve(position);
});
});
}
function searchLocation() {
return new Promise(function(resolve, reject) {
var geocoder = new google.maps.Geocoder();
var searchTerms = $('#searchVal').val();
geocoder.geocode( { 'address': searchTerms}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
positionData.latitude = results[0].geometry.location.lat();
positionData.longitude = results[0].geometry.location.lng();
resolve(positionData);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
});
}
function showPosition() {
return new Promise(function(resolve, reject) {
var cityName;
var countryCode;
var latitude = positionData.latitude;
var longitude = positionData.longitude;
var geolocUrl = 'https://maps.googleapis.com/maps/api/geocode/json?&language=en&latlng=' + latitude + ',' + longitude;
$.get(geolocUrl, function(response) {
var results = response.results;
var country = results[results.length-1].address_components[0].long_name;
if (country === 'United Kingdom') {
for (var result = 0; result < results.length; result++) {
for (var component = 0; component < results[result].address_components.length; component++) {
if(results[result].address_components[component].types.includes('postal_town')) {
cityName = convToParam(results[result].address_components[component].long_name);
}
if (results[result].address_components[component].types.includes('administrative_area_level_1')) {
country = convToParam(results[result].address_components[component].long_name);
}
}
}
} else {
for (var result = 0; result < results.length; result++) {
for (var component = 0; component < results[result].address_components.length; component++) {
if(results[result].address_components[component].types.includes('locality')) {
cityName = convToParam(results[result].address_components[component].long_name);
}
}
}
country = convToParam(results[results.length-1].address_components[0].long_name);
}
countryCode = results[results.length-1].address_components[0].short_name;
positionData.cityName = cityName;
positionData.country = country;
positionData.countryCode = countryCode;
positionData.latitude = latitude;
positionData.longitude = longitude;
resolve(positionData);
});
});
}
function convToParam(words) {
var result = words.split(' ');
result = result.join('+');
return result;
}
|
import React from 'react';
import { Link } from "react-router-dom"
import Input from "../Utility/Input"
import Button from '../Utility/Button';
import Heading from '../Utility/Heading';
function Form({ heading, noteText }) {
return (
<form>
<Heading size="2rem" text={heading} />
<Input type="email" placeholder="Email" />
<Input type="password" placeholder="Password" />
<p> { noteText } <Link to="/register">here</Link></p>
<Button> Login </Button>
</form>
)
}
export default Form;
|
/*
* Copyright (C) 2021 Radix IoT LLC. All rights reserved.
*/
/**
* @ngdoc directive
* @name ngMango.directive:maTileMapPolyline
* @restrict 'E'
* @scope
*
* @description Adds a polyline to a <a ui-sref="ui.docs.ngMango.maTileMap">maTileMap</a>. If content is supplied, it will be added to the map
* as a popup that is opened when the polyline is clicked. Local scope variables that are available inside the polyline popup are
* <code>$leaflet</code>, <code>$map</code>, <code>$mapCtrl</code>, <code>$polyline</code>, and <code>$polylineCtrl</code>.
*
* @param {LatLng[]|string[]|number[][]} coordinates Coordinates (array of latitudes/longitudes) of the polyline, do not close the polyline as it will be
* closed automatically
* e.g. <code>[{lat: lat1, lng: lng1}, {lat: lat2, lng: lng2}, {lat: lat3, lng: lng3}]</code> or <code>[[lat1, lng2], [lat2, lng2], [lat3, lng3]]</code>
* @param {string=} tooltip Text to display in the polyline tooltip
* @param {expression=} on-click Expression is evaluated when the polyline is clicked.
* Available locals are <code>$leaflet</code>, <code>$map</code>, <code>$polyline</code>, <code>$event</code>, and <code>$coordinates</code>.
* @param {object=} options Options for the Leaflet polyline instance,
* see <a href="https://leafletjs.com/reference-1.5.0.html#polyline-option" target="_blank">documentation</a>
*/
class TileMapPolylineController {
static get $$ngIsClass() { return true; }
static get $inject() { return ['$scope', '$element', '$transclude']; }
constructor($scope, $element, $transclude) {
this.$scope = $scope;
this.$element = $element;
this.$transclude = $transclude;
this.mapCtrl = $scope.$mapCtrl;
}
$onChanges(changes) {
if (!this.polyline) return;
if (changes.coordinates && this.coordinates) {
this.polyline.setLatLngs(this.getCoordinates());
}
if (changes.options && this.options) {
this.polyline.setStyle(this.options);
}
if (changes.tooltip && this.tooltip) {
this.polyline.bindTooltip(this.tooltip);
}
}
$onInit() {
this.polyline = this.mapCtrl.leaflet.polyline(this.getCoordinates(), this.options)
.addTo(this.$scope.$layer);
if (this.tooltip) {
this.polyline.bindTooltip(this.tooltip);
}
if (typeof this.onClick === 'function') {
this.polyline.on('click', event => {
const locals = {$polyline: this.polyline, $event: event, $coordinates: this.polyline.getLatLngs()};
this.$scope.$apply(() => {
this.onClick(locals);
});
});
}
this.$transclude(($clone, $scope) => {
if ($clone.contents().length) {
$scope.$polyline = this.polyline;
$scope.$polylineCtrl = this;
this.polyline.bindPopup($clone[0]);
} else {
$clone.remove();
$scope.$destroy();
}
});
}
$onDestroy() {
this.polyline.remove();
}
getCoordinates() {
let coordinates = this.coordinates;
if (Array.isArray(this.coordinates)) {
coordinates = this.coordinates.map(latLng => this.mapCtrl.parseLatLong(latLng));
}
return coordinates;
}
}
function tileMapPolylineDirective() {
return {
scope: false,
bindToController: {
coordinates: '<',
options: '<?',
tooltip: '@?',
onClick: '&?'
},
transclude: 'element',
controller: TileMapPolylineController
};
}
export default tileMapPolylineDirective;
|
export default /* glsl */`
vec4 encodeLinear(vec3 source) {
return vec4(source, 1.0);
}
vec4 encodeGamma(vec3 source) {
return vec4(pow(source + 0.0000001, vec3(1.0 / 2.2)), 1.0);
}
vec4 encodeRGBM(vec3 source) { // modified RGBM
vec4 result;
result.rgb = pow(source.rgb, vec3(0.5));
result.rgb *= 1.0 / 8.0;
result.a = saturate( max( max( result.r, result.g ), max( result.b, 1.0 / 255.0 ) ) );
result.a = ceil(result.a * 255.0) / 255.0;
result.rgb /= result.a;
return result;
}
vec4 encodeRGBP(vec3 source) {
// convert incoming linear to gamma(ish)
vec3 gamma = pow(source, vec3(0.5));
// calculate the maximum component clamped to 1..8
float maxVal = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z))));
// calculate storage factor
float v = 1.0 - ((maxVal - 1.0) / 7.0);
// round the value for storage in 8bit channel
v = ceil(v * 255.0) / 255.0;
return vec4(gamma / (-v * 7.0 + 8.0), v);
}
vec4 encodeRGBE(vec3 source) {
float maxVal = max(source.x, max(source.y, source.z));
if (maxVal < 1e-32) {
return vec4(0, 0, 0, 0);
} else {
float e = ceil(log2(maxVal));
return vec4(source / pow(2.0, e), (e + 128.0) / 255.0);
}
}
`;
|
//var termoApp = angular.module('termoApp');
var reportServices = angular.module('FilesService', ['ngResource']);
reportServices.factory('Files', ['$resource',
function($resource){
return $resource('/termodva/rest/files/file', {}, {
query: { method: 'GET', isArray: true },
});
}]);
|
import React, { Component } from 'react';
import Token from './services/token';
import Storage from './services/storage';
import {redirectIfNotAuthenticated} from './services/auth';
class Settings extends Component {
handleSignOut () {
Token.remove();
Storage.remove('currentUsername');
this.props.removeUser();
this.props.history.push('/home');
}
componentWillMount () {
redirectIfNotAuthenticated(this.props.history.push, '/login');
}
render() {
const {user} = this.props;
if (!user) return null;
return (
<div className="settings-page">
<div className="container page">
<div className="row">
<div className="col-md-6 offset-md-3 col-xs-12">
<h1 className="text-xs-center">Your Settings</h1>
<form>
<fieldset>
<fieldset className="form-group">
<input className="form-control" type="text" placeholder="URL of profile picture" value={user.image}/>
</fieldset>
<fieldset className="form-group">
<input className="form-control form-control-lg" type="text" placeholder="Your Name" value={user.username}/>
</fieldset>
<fieldset className="form-group">
<textarea className="form-control form-control-lg" rows="8" placeholder="Short bio about you" value={user.bio}></textarea>
</fieldset>
<fieldset className="form-group">
<input className="form-control form-control-lg" type="text" placeholder="Email" value={user.email}/>
</fieldset>
<fieldset className="form-group">
<input className="form-control form-control-lg" type="password" placeholder="Password" value={user.password}/>
</fieldset>
<button className="btn btn-lg btn-primary pull-xs-right">
Update Settings
</button>
</fieldset>
</form>
<hr/>
<button className="btn btn-outline-danger" onClick={this.handleSignOut.bind(this)}>
Or click here to logout.
</button>
</div>
</div>
</div>
</div>
);
}
}
export default Settings;
|
import Frisbee from './Frisbee'
window.Frisbee = Frisbee
|
import Phaser from "phaser";
import PuzzleElement from "./puzzle-element";
class Heart extends PuzzleElement{
constructor({scene, xn, yn, s, direction}){
super({scene, xn, yn, s, key: 'heart'});
this.type = 'heart';
this.direction = direction;
this.setInteractive();
}
get direction(){
return this._direction;
}
set direction(value){
this._direction = value % 4;
this.angle = 90 * this._direction;
}
rotate({rotation, duration, delay}){
return new Promise((resolve, reject) => {
this.scene.tweens.add({
targets: this,
props: {
direction: this.direction + rotation
},
delay,
duration,
onComplete: resolve
});
});
}
smile(){
this.setFrame(1);
}
calm(){
this.setFrame(0);
}
}
Heart.register('heart');
export default Heart;
|
import Validators from 'validators';
import assert from 'assert';
describe('Validators', function() {
describe('#isArray()', function() {
it('should return true when received an array in params otherwhise false', function() {
assert.equal(Validators.isArray([]), true);
assert.equal(Validators.isArray(new Date()), false);
assert.equal(Validators.isArray(true), false);
assert.equal(Validators.isArray(1), false);
assert.equal(Validators.isArray('1'), false);
assert.equal(Validators.isArray({}), false);
assert.equal(Validators.isArray(() => {}), false);
});
});
describe('#isNotArray()', function() {
it('should return false when received an array in params otherwhise true', function() {
assert.equal(Validators.isNotArray([]), false);
assert.equal(Validators.isNotArray(new Date()), true);
assert.equal(Validators.isNotArray(true), true);
assert.equal(Validators.isNotArray(1), true);
assert.equal(Validators.isNotArray('1'), true);
assert.equal(Validators.isNotArray({}), true);
assert.equal(Validators.isNotArray(() => {}), true);
});
});
describe('#isArrayFiled()', function() {
it('should return true when received a filed array in params otherwhise false', function() {
assert.equal(Validators.isArrayFiled([1]), true);
assert.equal(Validators.isArrayFiled(new Date()), false);
assert.equal(Validators.isArrayFiled([]), false);
assert.equal(Validators.isArrayFiled(true), false);
assert.equal(Validators.isArrayFiled(1), false);
assert.equal(Validators.isArrayFiled('1'), false);
assert.equal(Validators.isArrayFiled({}), false);
assert.equal(Validators.isArrayFiled(() => {}), false);
});
});
describe('#isArrayLike()', function() {
it('should return true when received an array or object with length properties in params otherwhise false', function() {
assert.equal(Validators.isArrayLike([]), true);
assert.equal(Validators.isArrayLike({lenght: 0}), true);
assert.equal(Validators.isArrayLike(new Date()), false);
assert.equal(Validators.isArrayLike({}), false);
assert.equal(Validators.isArrayLike(true), false);
assert.equal(Validators.isArrayLike(1), false);
assert.equal(Validators.isArrayLike('1'), false);
assert.equal(Validators.isArrayLike({}), false);
assert.equal(Validators.isArrayLike(() => {}), false);
});
});
describe('#isBool()', function() {
it('should return true when received a boolean object otherwhise false', function() {
assert.equal(Validators.isBool(true), true);
assert.equal(Validators.isBool(false), true);
assert.equal(Validators.isBool(new Date()), false);
assert.equal(Validators.isBool([]), false);
assert.equal(Validators.isBool({}), false);
assert.equal(Validators.isBool(1), false);
assert.equal(Validators.isBool('1'), false);
assert.equal(Validators.isBool({}), false);
assert.equal(Validators.isBool(() => {}), false);
});
});
describe('#isDate()', function() {
it('should return true when received a date object otherwhise false', function() {
assert.equal(Validators.isDate(new Date()), true);
assert.equal(Validators.isDate(true), false);
assert.equal(Validators.isDate([]), false);
assert.equal(Validators.isDate({}), false);
assert.equal(Validators.isDate(1), false);
assert.equal(Validators.isDate('1'), false);
assert.equal(Validators.isDate({}), false);
assert.equal(Validators.isDate(() => {}), false);
});
});
describe('#isDefined()', function() {
it('should return true when received a defined value otherwhise false', function() {
assert.equal(Validators.isDefined(new Date()), true);
assert.equal(Validators.isDefined(true), true);
assert.equal(Validators.isDefined([]), true);
assert.equal(Validators.isDefined({}), true);
assert.equal(Validators.isDefined(1), true);
assert.equal(Validators.isDefined('1'), true);
assert.equal(Validators.isDefined({}), true);
assert.equal(Validators.isDefined(() => {}), true);
assert.equal(Validators.isDefined(null), true);
assert.equal(Validators.isDefined(), false);
assert.equal(Validators.isDefined(undefined), false);
});
});
describe('#isEmpty()', function() {
it('should return true when received a empty string or array', function() {
assert.equal(Validators.isEmpty(''), true);
assert.equal(Validators.isEmpty([]), true);
assert.equal(Validators.isEmpty('1'), false);
assert.equal(Validators.isEmpty([1]), false);
assert.equal(Validators.isEmpty({}), false);
assert.equal(Validators.isEmpty(new Date()), false);
assert.equal(Validators.isEmpty({}), false);
assert.equal(Validators.isEmpty(() => {}), false);
assert.equal(Validators.isEmpty(1), false);
assert.equal(Validators.isEmpty(new Date()), false);
});
});
describe('#isFloat()', function() {
it('should return true when received a float number', function() {
assert.equal(Validators.isFloat(1.5), true);
assert.equal(Validators.isFloat(1), false);
assert.equal(Validators.isFloat([]), false);
assert.equal(Validators.isFloat({}), false);
assert.equal(Validators.isFloat('1.5'), false);
assert.equal(Validators.isFloat(true), false);
assert.equal(Validators.isFloat(new Date()), false);
assert.equal(Validators.isFloat(() => {}), false);
});
});
describe('#isFunc()', function() {
it('should return true when received a function', function() {
assert.equal(Validators.isFunc(() => {}), true);
assert.equal(Validators.isFunc(1.5), false);
assert.equal(Validators.isFunc(1), false);
assert.equal(Validators.isFunc([]), false);
assert.equal(Validators.isFunc({}), false);
assert.equal(Validators.isFunc('1.5'), false);
assert.equal(Validators.isFunc(true), false);
assert.equal(Validators.isFunc(new Date()), false);
});
});
describe('#isInt()', function() {
it('should return true when received a integer number', function() {
assert.equal(Validators.isInt(1), true);
assert.equal(Validators.isInt(1.5), false);
assert.equal(Validators.isInt([]), false);
assert.equal(Validators.isInt({}), false);
assert.equal(Validators.isInt('1.5'), false);
assert.equal(Validators.isInt(true), false);
assert.equal(Validators.isInt(new Date()), false);
assert.equal(Validators.isInt(() => {}), false);
});
});
describe('#isNotNull()', function() {
it('should return true when received a not null object', function() {
assert.equal(Validators.isNotNull(1), true);
assert.equal(Validators.isNotNull([]), true);
assert.equal(Validators.isNotNull({}), true);
assert.equal(Validators.isNotNull('1.5'), true);
assert.equal(Validators.isNotNull(true), true);
assert.equal(Validators.isNotNull(new Date()), true);
assert.equal(Validators.isNotNull(() => {}), true);
assert.equal(Validators.isNotNull(), true);
assert.equal(Validators.isNotNull(undefined), true);
assert.equal(Validators.isNotNull(null), false);
});
});
describe('#isNull()', function() {
it('should return true when received a not null object', function() {
assert.equal(Validators.isNull(null), true);
assert.equal(Validators.isNull(1), false);
assert.equal(Validators.isNull([]), false);
assert.equal(Validators.isNull({}), false);
assert.equal(Validators.isNull('1.5'), false);
assert.equal(Validators.isNull(false), false);
assert.equal(Validators.isNull(new Date()), false);
assert.equal(Validators.isNull(() => {}), false);
assert.equal(Validators.isNull(), false);
assert.equal(Validators.isNull(undefined), false);
});
});
describe('#isNumber()', function() {
it('should return true when received a number', function() {
assert.equal(Validators.isNumber(1), true);
assert.equal(Validators.isNumber(1.5), true);
assert.equal(Validators.isNumber([]), false);
assert.equal(Validators.isNumber({}), false);
assert.equal(Validators.isNumber('1.5'), false);
assert.equal(Validators.isNumber(false), false);
assert.equal(Validators.isNumber(new Date()), false);
assert.equal(Validators.isNumber(() => {}), false);
assert.equal(Validators.isNumber(), false);
assert.equal(Validators.isNumber(undefined), false);
});
});
describe('#isObject()', function() {
it('should return true when received an object', function() {
assert.equal(Validators.isObject({}), true);
assert.equal(Validators.isObject(1), false);
assert.equal(Validators.isObject(1.5), false);
assert.equal(Validators.isObject([]), false);
assert.equal(Validators.isObject('1.5'), false);
assert.equal(Validators.isObject(false), false);
assert.equal(Validators.isObject(new Date()), false);
assert.equal(Validators.isObject(() => {}), false);
assert.equal(Validators.isObject(), false);
assert.equal(Validators.isObject(undefined), false);
});
});
describe('#isString()', function() {
it('should return true when received a string object', function() {
assert.equal(Validators.isString('1.5'), true);
assert.equal(Validators.isString({}), false);
assert.equal(Validators.isString(1), false);
assert.equal(Validators.isString(1.5), false);
assert.equal(Validators.isString([]), false);
assert.equal(Validators.isString(false), false);
assert.equal(Validators.isString(new Date()), false);
assert.equal(Validators.isString(() => {}), false);
assert.equal(Validators.isString(), false);
assert.equal(Validators.isString(undefined), false);
});
});
describe('#isUndefined()', function() {
it('should return true when received an undefined object', function() {
assert.equal(Validators.isUndefined(), true);
assert.equal(Validators.isUndefined(undefined), true);
assert.equal(Validators.isUndefined('1.5'), false);
assert.equal(Validators.isUndefined({}), false);
assert.equal(Validators.isUndefined(1), false);
assert.equal(Validators.isUndefined(1.5), false);
assert.equal(Validators.isUndefined([]), false);
assert.equal(Validators.isUndefined(false), false);
assert.equal(Validators.isUndefined(new Date()), false);
assert.equal(Validators.isUndefined(() => {}), false);
});
});
describe('#exists()', function() {
it('should return true when a valid value (!null, !undefined)', function() {
assert.equal(Validators.exists(), false);
assert.equal(Validators.exists(undefined), false);
assert.equal(Validators.exists(null), false);
assert.equal(Validators.exists('1.5'), true);
assert.equal(Validators.exists({}), true);
assert.equal(Validators.exists(1), true);
assert.equal(Validators.exists(1.5), true);
assert.equal(Validators.exists([]), true);
assert.equal(Validators.exists(true), true);
assert.equal(Validators.exists(new Date()), true);
assert.equal(Validators.exists(() => {}), true);
});
});
describe('#isNil()', function() {
it('should return true when a value is null or undefined', function() {
assert.equal(Validators.isNil(), true);
assert.equal(Validators.isNil(undefined), true);
assert.equal(Validators.isNil(null), true);
assert.equal(Validators.isNil('1.5'), false);
assert.equal(Validators.isNil({}), false);
assert.equal(Validators.isNil(1), false);
assert.equal(Validators.isNil(1.5), false);
assert.equal(Validators.isNil([]), false);
assert.equal(Validators.isNil(false), false);
assert.equal(Validators.isNil(new Date()), false);
assert.equal(Validators.isNil(() => {}), false);
});
});
});
|
18 gid=1329781531
17 uid=183816338
20 ctime=1441138963
20 atime=1441138963
23 SCHILY.dev=16777221
23 SCHILY.ino=32545633
18 SCHILY.nlink=1
|
import { fork } from 'redux-saga/effects';
import application from './application';
export default function* saga() {
yield fork(application);
}
|
import { Radio } from 'antd';
import ReactEcharts from 'echarts-for-react';
import React from 'react';
import { currenMonth } from './arguments';
const Group = Radio.Group
const RadioButton = Radio.Button;
class Line extends React.Component {
componentDidUpdate() {
currenMonth.series[0].data = this.props.data.monthCount
currenMonth.series[1].data = this.props.data.monthSum
let line = this.echarts_react.getEchartsInstance();
line.setOption(currenMonth)
}
currenMonthClick = () => {
let line = this.echarts_react.getEchartsInstance();
line.setOption(currenMonth)
}
yearToYearClick = () => {
let line = this.echarts_react.getEchartsInstance();
let option = {
series: [
{
data: this.props.data.anMonthCount
},
{
data: this.props.data.anMonthSum
}
]
};
line.setOption(option)
}
chainClick = () => {
let line = this.echarts_react.getEchartsInstance();
let option = {
series: [
{
data: this.props.data.momMonthCount
},
{
data: this.props.data.momMonthSum
}
]
};
line.setOption(option)
}
render() {
return (
<div>
<div className="chart-title1">当月交易情况</div>
<Group defaultValue="a" >
<RadioButton value="a" onClick={this.currenMonthClick}>当月交易情况</RadioButton>
<RadioButton value="b" onClick={this.yearToYearClick}>同比</RadioButton>
<RadioButton value="c" onClick={this.chainClick}>环比</RadioButton>
</Group>
<ReactEcharts
ref={(e) => { this.echarts_react = e; }}
option={currenMonth}
style={this.props.style}
/>
</div>
)
}
}
export default Line
|
import React from 'react';
import { Modal, Button, InputGroup, FormControl, Alert } from 'react-bootstrap';
const { Header, Body, Footer, Title } = Modal;
const { Prepend, Text, Append } = InputGroup;
const CustomModal = (props) => {
const { handleClose, isShow, vehicleDetail, isError } = props;
const formatDate = (date) => {
const time = new Date(date);
const month = time.getMonth() + 1;
const day = time.getDate();
const year = time.getFullYear();
return month + "/" + day + "/" + year;
};
return(
<Modal show={isShow} size= "lg" onHide={handleClose}>
<Header closeButton>
<Title>Vehicles Detail</Title>
</Header>
<Body>
{
!isError ?
(vehicleDetail && (
<>
<InputGroup size="sm" className="mb-3 pr-1 w-50 f-left">
<Prepend>
<Text id="inputGroup-sizing-sm-1">Name</Text>
</Prepend>
<FormControl
readOnly
aria-label="Small"
aria-describedby="inputGroup-sizing-sm"
value = { vehicleDetail.name }
/>
</InputGroup>
<InputGroup size="sm" className="mb-3 pl-1 w-50 f-left">
<Prepend>
<Text id="inputGroup-sizing-sm-2">Vehicle Class</Text>
</Prepend>
<FormControl
readOnly
aria-label="Small"
aria-describedby="inputGroup-sizing-sm"
value = { vehicleDetail.vehicle_class }
/>
</InputGroup>
<InputGroup size="sm" className="mb-3 pr-1 w-50 f-left">
<Prepend>
<Text id="inputGroup-sizing-sm-3">Model</Text>
</Prepend>
<FormControl
readOnly
aria-label="Small"
aria-describedby="inputGroup-sizing-sm"
value = { vehicleDetail.model }
/>
</InputGroup>
<InputGroup size="sm" className="mb-3 pl-1 w-50 f-left">
<Prepend>
<Text id="inputGroup-sizing-sm-4">Manufacturer</Text>
</Prepend>
<FormControl
readOnly
aria-label="Small"
aria-describedby="inputGroup-sizing-sm"
value = { vehicleDetail.manufacturer }
/>
</InputGroup>
<InputGroup size="sm" className="mb-3 pr-1 w-50 f-left">
<Prepend>
<Text id="inputGroup-sizing-sm-5">Max Atmosphering Speed</Text>
</Prepend>
<FormControl
readOnly
aria-label="Small"
aria-describedby="inputGroup-sizing-sm"
value = { vehicleDetail.max_atmosphering_speed }
/>
<Append>
<Text>mph</Text>
</Append>
</InputGroup>
<InputGroup size="sm" className="mb-3 pl-1 w-50 f-left">
<Prepend>
<Text id="inputGroup-sizing-sm-6">Consumables</Text>
</Prepend>
<FormControl
readOnly
aria-label="Small"
aria-describedby="inputGroup-sizing-sm"
value = { vehicleDetail.consumables }
/>
</InputGroup>
<InputGroup size="sm" className="mb-3 pr-1 w-50 f-left">
<Prepend>
<Text id="inputGroup-sizing-sm-7">Crew</Text>
</Prepend>
<FormControl
readOnly
aria-label="Small"
aria-describedby="inputGroup-sizing-sm"
value = { vehicleDetail.crew }
/>
</InputGroup>
<InputGroup size="sm" className="mb-3 pl-1 w-50 f-left">
<Prepend>
<Text id="inputGroup-sizing-sm-8">Length</Text>
</Prepend>
<FormControl
readOnly
aria-label="Small"
aria-describedby="inputGroup-sizing-sm"
value = { vehicleDetail.length }
/>
<Append>
<Text>ft</Text>
</Append>
</InputGroup>
<InputGroup size="sm" className="mb-3 pr-1 w-50 f-left">
<Prepend>
<Text id="inputGroup-sizing-sm-9">Passengers</Text>
</Prepend>
<FormControl
readOnly
aria-label="Small"
aria-describedby="inputGroup-sizing-sm"
value = { vehicleDetail.passengers }
/>
</InputGroup>
<InputGroup size="sm" className="mb-3 pl-1 w-50 f-left">
<Prepend>
<Text id="inputGroup-sizing-sm-10">Cargo capacity</Text>
</Prepend>
<FormControl
readOnly
aria-label="Small"
aria-describedby="inputGroup-sizing-sm"
value = {vehicleDetail.cargo_capacity}
/>
</InputGroup>
<InputGroup size="sm" className="mb-3 pr-1 w-50 f-left">
<Prepend>
<Text id="inputGroup-sizing-sm-11">Cost in credits</Text>
</Prepend>
<FormControl
readOnly
aria-label="Small"
aria-describedby="inputGroup-sizing-sm"
value = { vehicleDetail.cost_in_credits }
/>
<Append>
<Text>$</Text>
</Append>
</InputGroup>
<InputGroup size="sm" className="mb-3 pl-1 w-50 f-left">
<Prepend>
<Text id="inputGroup-sizing-sm-12">Created</Text>
</Prepend>
<FormControl
readOnly
aria-label="Small"
aria-describedby="inputGroup-sizing-sm"
value = { formatDate(vehicleDetail.created) }
/>
</InputGroup>
</>
))
:
<Alert variant="warning">Have issues from sever!</Alert>
}
</Body>
<Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
</Footer>
</Modal>
);
}
export default CustomModal;
|
import React from 'react';
import Note from '../Note';
import toJSON from 'enzyme-to-json';
import { shallow } from 'enzyme';
describe('Note', () => {
it('renders note correctly.', () => {
const wrapper = shallow(<Note />);
expect(toJSON(wrapper)).toMatchSnapshot();
});
it('calls delete function when delete button is clicked.', () => {
const deleteFunc = jest.fn();
const wrapper = shallow(<Note deleteNote={deleteFunc} />);
wrapper
.find('.delete')
.simulate('click');
expect(deleteFunc).toHaveBeenCalledTimes(1);
});
it('calls updateView function and view is updated.', () => {
const wrapper = shallow(<Note
id="1"
title='This is a title'
body='This is the body.'
/>);
const updateView = jest.spyOn(wrapper.instance(), 'updateView');
expect(wrapper.state()).toEqual({ // State of component before click.
id: '1',
title: 'This is a title',
body: 'This is the body.',
isUpdating: false,
});
wrapper.find('.update-view').simulate('click');
expect(updateView).toHaveBeenCalledTimes(1);
expect(wrapper.state()).toEqual({ // State of component after click.
id: '1',
title: 'This is a title',
body: 'This is the body.',
isUpdating: true,
});
expect(toJSON(wrapper)).toMatchSnapshot();
});
it('calls on api to update note when submit is called.', (done) => {
const mockSuccessResponse = {id: '1', title: 'This is the updated title', body: 'This is the updated body.'};
const mockJsonPromise = Promise.resolve(mockSuccessResponse);
const mockFetchPromise = Promise.resolve({
json: () => mockJsonPromise,
});
jest.spyOn(global, 'fetch').mockImplementation(() => mockFetchPromise);
const wrapper = shallow(<Note id='1'/>);
var submitEvent = new Event('submit');
wrapper.instance().handleSubmit(submitEvent);
expect(global.fetch).toHaveBeenCalledTimes(1);
expect(global.fetch).toHaveBeenCalledWith("https://5ec581652a4ba000163d2084.mockapi.io/api/v1/notes/1", {"body": "{}", "headers": {"Content-Type": "application/json"}, "method": "PUT"});
process.nextTick(() => {
expect(wrapper.state()).toEqual({
id: '1',
title: 'This is the updated title',
body: 'This is the updated body.',
isUpdating: true
});
});
global.fetch.mockClear();
done();
});
});
|
/* eslint-disable no-param-reassign */
import Joi from 'react-native-joi'
import uid from 'uid-safe'
// TODO
// import * as loaderActions from '../Loader/LoaderActions'
export function getAllMessages(groupId) {
return {
type: 'GET_ALL_MESSAGES_FROM_GROUP',
groupId,
}
}
export function addMessage(message) {
return {
type: 'ADD_NEW_MESSAGE_TO_GROUP',
message,
}
}
export function removeAllMessages(groupId) {
return {
type: 'REMOVE_ALL_MESSAGE_FROM_GROUP',
groupId,
}
}
export function createNewGroupMessages(groupId) {
return {
type: 'CREATE_NEW_GROUP_MESSAGES',
groupId,
}
}
// DEBUG
export function setGroupMessages(store) {
return {
type: 'SET_ALL_GROUP_MESSAGES',
store,
}
}
// ====== HANDLERS ======= //
export function getAllMessagesHandler(groupId) {
return (dispatch) => {
dispatch(getAllMessages(groupId))
}
}
const messageschema = {
_type: Joi.string().insensitive(),
id: Joi.string(),
createdAt: Joi.string().isoDate(),
body: {
text: Joi.string().insensitive(),
},
from: {
_type: Joi.string().insensitive(),
id: Joi.string(),
userName: Joi.string().insensitive(),
userPicture: Joi.string().insensitive(),
},
to: {
_type: 'Group',
id: Joi.string().alphanum(),
},
}
export function addMessageHandler(message) {
return (dispatch) => {
// dispatch(loaderActions.startLoadingAction())
message.id = uid.sync(18)
message.createdAt = new Date().toISOString()
Joi.validate(message, messageschema, (err) => {
// dispatch(loaderActions.stopLoadingAction())
if (err) return (new Error('Error')) // TODO: error logic after validation
return dispatch(addMessage(message))
})
}
}
|
import classes from "./Input.module.css";
const Input = (props) => {
const { label, elementType, elementConfig, value, changeFn } = props;
const inputClasses = [classes.InputElement];
if (props.invalid && props.shouldValidate && props.touched) {
inputClasses.push(classes.Invalid);
}
let inputElement;
switch (elementType) {
case "input":
inputElement = (
<input
className={inputClasses.join(" ")}
{...elementConfig}
onChange={changeFn}
value={value}
/>
);
break;
case "textarea":
inputElement = (
<textarea
className={inputClasses.join(" ")}
{...elementConfig}
onChange={changeFn}
value={value}
/>
);
break;
case "select":
inputElement = (
<select
className={inputClasses.join(" ")}
placeholder={elementConfig.placeholder}
onChange={changeFn}
defaultValue={"DEFAULT"}
>
<option value="DEFAULT" disabled>
{elementConfig.placeholder}
</option>
{elementConfig.options.map((el) => (
<option key={el.value} value={el.value}>
{el.displayValue}
</option>
))}
</select>
);
break;
default:
inputElement = (
<input
className={inputClasses.join(" ")}
{...elementConfig}
value={value}
onChange={changeFn}
/>
);
break;
}
return (
<div className={classes.Input}>
<label className={classes.Label}>{label}</label>
{inputElement}
</div>
);
};
export default Input;
|
const input = require("fs").readFileSync("/dev/stdin", "utf8")
let cin = input.split(/ |\n/), cid = 0
const next = () => cin[cid++]
const nexts = (n) => cin.slice(cid, cid+=n).map(i=>parseInt(i))
const [A, B, H, M] = nexts(4)
const long = M * 6.0
const short = (H + M / 60) * 30.0
let angle = Math.abs(long - short)
// console.log(long, short, angle)
// console.log(long, short, angle)
const result = Math.sqrt(A**2 + B**2 - 2 * A * B * Math.cos(angle * (Math.PI / 180)))
console.log(result)
|
const app = require("../server/server.js");
const knex = require("../server/db");
var request = require("supertest");
const chai = require("chai");
const chaiHttp = require("chai-http");
const expect = chai.expect;
chai.use(chaiHttp);
const moment = require("moment");
const userTuple = {
id: "1",
name: "Ambra",
surname: "Ferri",
password_hash: "$2b$10$A9KmnEEAF6fOvKqpUYbxk.1Ye6WLHUMFgN7XCSO/VF5z4sspJW1o.",
email: "s274930@studenti.polito.it",
role: "student",
city: "Poggio Ferro",
birthday: "1996-11-04",
ssn: "MK97060783",
};
const teacherTuple = {
id: "2",
name: "John",
surname: "Doe",
password_hash: "$2b$10$A9KmnEEAF6fOvKqpUYbxk.1Ye6WLHUMFgN7XCSO/VF5z4sspJW1o.",
email: "john.doe@polito.it",
role: "teacher",
city: "Milano",
birthday: "1971-11-04",
ssn: "MR17121943",
};
const officerTuple = {
id: "3",
name: "Enrico",
surname: "Carraro",
password_hash: "$2b$10$A9KmnEEAF6fOvKqpUYbxk.1Ye6WLHUMFgN7XCSO/VF5z4sspJW1o.",
email: "s280113@studenti.polito.it",
role: "supportOfficer",
city: "Torino",
birthday: "1991-11-04",
ssn: "152",
};
const userCredentials = {
email: "s274930@studenti.polito.it",
password: "password",
};
const teacherCredentials = {
email: "john.doe@polito.it",
password: "password",
};
const officerCredentials = {
email: "s280113@studenti.polito.it",
password: "password",
};
const courseTuple = {
id: "1",
name: "Software Engineering II",
main_prof: teacherTuple.id,
year: 1,
semester: 1,
};
const lectureTuple = {
id: "1",
course: courseTuple.id,
lecturer: teacherTuple.id,
start: moment()
.subtract(1, "days")
.subtract(1, "hours")
.format("YYYY-MM-DD HH:mm:ss"),
end: moment().subtract(1, "days").format("YYYY-MM-DD HH:mm:ss"),
capacity: 125,
status: "presence",
room: 1,
};
const semesterTuple = {
sid: 5,
name: "s1",
start: moment().add(2, "days").format("YYYY-MM-DD"),
end: moment().add(2, "days").add(1, "hours").format("YYYY-MM-DD"),
inserted_lectures: 1,
};
const futureLectureTuple = {
id: 1,
course: courseTuple.id,
lecturer: teacherTuple.id,
start: moment().add(2, "days").format("YYYY-MM-DD HH:mm:ss"),
end: moment().add(2, "days").add(1, "hours").format("YYYY-MM-DD HH:mm:ss"),
capacity: 25,
status: "presence",
room: 1,
};
describe("Semester test", async function () {
const authenticatedUser = request.agent(app);
this.timeout(100000);
before(async () => {
await knex("user").del();
await knex("semester").del();
await knex("lecture").del();
await knex("user").insert(userTuple);
await knex("user").insert(teacherTuple);
await knex("user").insert(officerTuple);
await knex("semester").insert(semesterTuple);
await knex("lecture").insert(lectureTuple);
});
describe("Get Semester Details ", async () => {
//now let's login the user before we run any tests
const authenticatedUser = request.agent(app);
before(async () => {
await knex("user").del();
await knex("semester").del();
await knex("lecture").del();
await knex("user").insert(userTuple);
await knex("user").insert(teacherTuple);
await knex("user").insert(officerTuple);
await knex("semester").insert(semesterTuple);
await knex("lecture").insert(lectureTuple);
const res = await authenticatedUser
.post("/api/auth/login")
.send(userCredentials);
expect(res.status).to.equal(200);
});
it("should return with status 200", async () => {
const res = await authenticatedUser.get(`/api/semesters`);
expect(res).to.be.json;
expect(res.status).to.equal(200);
});
it("should return the body ", async () => {
const res = await authenticatedUser.get(`/api/semesters/`);
expect(res.body).to.have.deep.members([
{
sid: semesterTuple.sid,
name: semesterTuple.name,
start: semesterTuple.start,
end: semesterTuple.end,
inserted_lectures: semesterTuple.inserted_lectures,
},
]);
});
after(async () => {
await knex("user").del();
await knex("semester").del();
await knex("lecture").del();
});
});
});
describe("Retrieves semesters when not logged as support officer", async () => {
const authenticatedUser = request.agent(app);
before(async () => {
await knex("user").del();
await knex("lecture").del();
await knex("course").del();
await knex("user").insert(teacherTuple);
const res = await authenticatedUser
.post("/api/auth/login")
.send(teacherCredentials);
expect(res.status).to.equal(200);
});
it("Should return 401, Unauthorized access, only support officers can access this data.", async () => {
await authenticatedUser.get(`/api/semesters/future`).expect(401, {message: "Unauthorized access, only support officers can access this data."});
})
after(async () => {
await knex("user").del();
});
})
describe("Future Semester ", async function () {
this.timeout(5000);
//now let's login the user before we run any tests
const authenticatedUser = request.agent(app);
before(async () => {
await knex("user").del();
await knex("lecture").del();
await knex("course").del();
await knex("user").insert(teacherTuple);
await knex("user").insert(officerTuple);
await knex("semester").insert(semesterTuple);
await knex("course").insert(courseTuple);
await knex("lecture").insert(futureLectureTuple);
const res = await authenticatedUser
.post("/api/auth/login")
.send(officerCredentials);
expect(res.status).to.equal(200);
});
it("should return with status 200", async () => {
const res = await authenticatedUser.get(`/api/semesters/future`);
expect(res.status).to.equal(200);
});
it("should return one future semester", async () => {
const res = await authenticatedUser.get(`/api/semesters/future`);
expect(res.body.length).to.equal(1);
expect(res.body).to.have.deep.members([
{
id: semesterTuple.sid,
name:semesterTuple.name,
start:semesterTuple.start,
end:semesterTuple.end
},
]);
});
after(async () => {
await knex("user").del();
await knex("lecture").del();
await knex("lecture_booking").del();
await knex("course").del();
await knex("semester").del();
});
});
|
"use strict";
exports.unsubscribeNodesDisposing = exports.subscribeNodesDisposing = void 0;
var _events_engine = _interopRequireDefault(require("../core/events_engine"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var REMOVE_EVENT_NAME = 'dxremove';
function nodesByEvent(event) {
return event && [event.target, event.delegateTarget, event.relatedTarget, event.currentTarget].filter(function (node) {
return !!node;
});
}
var subscribeNodesDisposing = function subscribeNodesDisposing(event, callback) {
_events_engine.default.one(nodesByEvent(event), REMOVE_EVENT_NAME, callback);
};
exports.subscribeNodesDisposing = subscribeNodesDisposing;
var unsubscribeNodesDisposing = function unsubscribeNodesDisposing(event, callback) {
_events_engine.default.off(nodesByEvent(event), REMOVE_EVENT_NAME, callback);
};
exports.unsubscribeNodesDisposing = unsubscribeNodesDisposing;
|
const test = require('tape');
const isRegExp = require('./isRegExp.js');
test('Testing isRegExp', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof isRegExp === 'function', 'isRegExp is a Function');
//t.deepEqual(isRegExp(args..), 'Expected');
//t.equal(isRegExp(args..), 'Expected');
//t.false(isRegExp(args..), 'Expected');
//t.throws(isRegExp(args..), 'Expected');
t.end();
});
|
function $(obj){
if(typeof obj=="function"){
window.onload=obj;
}else if(typeof obj=="string"){
return document.getElementById(obj);
}else if( typeof obj=="object" ){
return obj;
}
}
function getStyle(obj,attr){
return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle( obj )[attr];
}
function doMove(obj,attr,dir,target,endFn){ //endFn 回调函数
clearInterval( obj.timer );
dir=parseInt( getStyle( obj,attr ) )<target?dir:-dir;
obj.timer=setInterval( function (){
var speed=parseInt(getStyle(obj,attr))+dir;
if( speed>target&&dir>0||speed<target&&dir<0 ){
speed=target;
}
obj.style[attr]=speed+"px";
if( speed==target ){
clearInterval( obj.timer );
if( endFn ){
endFn();
}
}
},200 );
}
function opacity(obj,step,target,endFn){
clearInterval(obj.timer1);
step=parseFloat( getStyle( obj,"opacity" ) )*100<target?step:-step;
//alert(step);
obj.timer1=setInterval( function (){
var speed=parseFloat(getStyle(obj,"opacity"))*100+step;
if(speed>target&&step>0||speed<target&&step<0){
speed=target;
}
obj.style.opacity=speed/100;
if( speed==target ){
clearInterval( obj.timer1 );
if( endFn ){
endFn();
}
}
},60 )
}
function shake( obj,dir,endFn ){
if( obj.onOff ){return;}
obj.onOff=true;
var _this=obj;
var arr=[];
var num=0;
var len=20;
for( var i=20;i>0;i-=2 ){
arr.push( i,-i );
}
arr.push(0);
var pos =parseInt( getStyle( _this,dir ));
clearInterval( _this.shake );
_this.shake=setInterval(function (){
_this.style[dir]=pos+arr[num]+"px";
num++;
if( num==len ){
clearInterval( _this.shake );
endFn&&endFn();
obj.onOff=false;
}
},100);
}
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Header extends Component{
static propTypes={
items:PropTypes.array.isRequired,
isLoading:PropTypes.bool//должна быть булевого типа но не обязательно быть
};
render(){
console.log('items',this.props.items);
return(
<div>
{this.props.items.map((item,index)=>
<a href={item.link} key={index}>{item.label}</a>
)}
</div>
);
}
}
export default Header;
|
const Order = require('../models/Order')
// find my orders
exports.myOrders = async (req, res) => {
const orders = await Order.find({ user: req.user._id }).populate({ path: "orderItems", populate: { path: "product" } })
// console.log('orders:', orders);
res.json(orders);
}
// shipping
exports.shipping = (req, res) =>{
console.log(req.body)
}
// create a new order
exports.createOrder = async (req, res) => {
if (req.body.orderItems.length === 0) {
return res.status(400).json({ message: 'Cart is empty' });
}
const order = new Order({
orderItems: req.body.orderItems,
shippingAddress: req.body.shippingAddress,
paymentMethod: req.body.paymentMethod,
itemsPrice: req.body.itemsPrice,
shippingPrice: req.body.shippingPrice,
taxPrice: req.body.taxPrice,
totalPrice: req.body.totalPrice,
user: req.user._id
});
console.log('req.user', req.user);
const createdOrder = await order.save();
res.status(201).json({ message: 'New Order Created', order: createdOrder });
}
// get order details by users
exports.orderDetails = async (req, res) => {
const order = await Order.findById(req.params.id);
if (order) {
res.json(order);
} else {
res.status(404).json({ message: 'Order Not Found' });
}
}
// payment process
exports.paymentProcess = async (req, res) => {
// get the order via orderId in params
const order = await Order.findById(req.params.id);
// update order if exists
if (order) {
order.isPaid = true;
order.paidAt = Date.now();
// add paymentResult field in orderModel
order.paymentResult = {
id: req.body.id,
status: req.body.status,
update_time: req.body.update_time,
email_address: req.body.payer.email_address,
};
//save updated order in db
const updatedOrder = await order.save();
// send back updated order
res.json({ message: 'Payment processed successfully', order: updatedOrder });
} else {
res.status(401).json({ message: 'Order Not Found' });
}
}
|
import React from 'react'
import { useStoreState } from 'easy-peasy'
import { yupResolver } from '@hookform/resolvers/yup'
import { useForm } from 'react-hook-form'
import InputField from 'Components/Form-control/InputField'
import { Button, Col, Row } from 'Components/UI-Library'
import schema from './Contact.Yup'
import './ContactForm.Style.less'
const ContactForm = () => {
const user = useStoreState((state) => state.auth.user)
const defaultValues = {
defaultValues: {
firstName: user ? user.firstName : '',
lastName: user ? user.lastName : '',
email: user ? user.email : '',
subject: '',
message: '',
},
resolver: yupResolver(schema),
}
const form = useForm(defaultValues)
const handleSubmit = (value) => {
console.log(`value`, value)
}
return (
<form onSubmit={form.handleSubmit(handleSubmit)} className="contact-form-wrapper">
<Row gutter={[48, 6]}>
<Col xs={24} md={12} lg={10}>
<InputField
label="First Name"
name="firstName"
form={form}
isRequired
/>
</Col>
<Col xs={24} md={12} lg={10}>
<InputField
label="Last Name"
name="lastName"
form={form}
isRequired
/>
</Col>
<Col xs={24} md={12} lg={10}>
<InputField label="Email" name="email" form={form} isRequired />
</Col>
<Col xs={24} md={12} lg={10}>
<InputField label="Subject" name="subject" form={form} />
</Col>
<Col xs={24} md={24} lg={20}>
<InputField
label="Leave us a message..."
name="message"
form={form}
textArea
/>
</Col>
<Col xs={12} md={10} lg={10}>
<Button block htmlType="submit" className="btn-submit">Submit</Button>
</Col>
</Row>
</form>
)
}
export default ContactForm
|
import React from 'react'
import { Chip as MuiChip } from '@material-ui/core'
export default function Chip(props) {
const { label, size, color, backgroundColor, ...other} = props
return (
<MuiChip
label={label}
size={size || "small"}
color="primary"
{...other}
/>
)
}
|
import {
SAVE_RANDOM_CUSTOMER_ID,
SAVE_RANDOM_CUSTOMER_ID_EXIT
} from '../types';
export function saveRandomCustomerIdAction(newId){
return async (dispatch)=>{
dispatch(saveRandomCustomerId());
try{
//Si todo sale bien
console.log("Se asigna el id al usuario, solo la primera vez",newId);
dispatch(saveRandomCustomerIdExit(newId))
}catch (error){
console.log(error);
}
}
}
const saveRandomCustomerId=()=>({
type:SAVE_RANDOM_CUSTOMER_ID,
payload:false
});
const saveRandomCustomerIdExit = (randomId)=>({
type:SAVE_RANDOM_CUSTOMER_ID_EXIT,
payload:randomId
});
|
/*!
* News - Hacker news and reddit in the CLI.
*
* Veselin Todorov <hi@vesln.com>
* MIT License.
*/
/**
* Module dependencies.
*/
var request = require('request');
/**
* Reader constructor.
*/
function Reader() {};
/**
* Returns the popular items.
*
* @param {Function} Callback.
* @api public
*/
Reader.prototype.get = function(fn) {
var self = this;
request.get(this.url, function (err, res, body) {
if (err) return fn(err);
self.parse(body, function(err, data) {
if (err) return fn(err);
fn(null, data);
})
});
};
/**
* Expose `Reader`.
*/
module.exports = Reader;
|
import { Permissions, Notifications } from 'expo';
import * as firebase from 'firebase';
import { store } from '../redux/store';
export async function registerForPushNotificationsAsync() {
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
if (finalStatus !== 'granted') {
return;
}
const token = await Notifications.getExpoPushTokenAsync();
const uid = store.getState().globalReducer.user.uid;
if (uid != null) {
const updates = {};
updates['/push_notification_token'] = token;
firebase
.database()
.ref(`users/${uid}`)
.update(updates);
}
console.log(`Token: ${token}`);
}
export async function getTokenPushNotificationUser(user) {
let token;
await firebase
.database()
.ref(`users/${user}`)
.once('value', (snapshot) => {
token = snapshot.val().push_notification_token;
});
return token;
}
export async function sendPushNotification(request) {
savePushNotification({
uid: request.uid,
data: request.body.data
});
return fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(request.body)
})
.then(response => response.json())
.catch((error) => {
console.error(error);
});
}
export async function savePushNotification(notification) {
notification.data.timestamp = Date.now();
return await firebase
.database()
.ref(`notifications/${notification.uid}`)
.push(notification.data);
}
export async function getNotifications(uid) {
let notifications = [];
await firebase
.database()
.ref(`notifications/${uid}`)
.limitToFirst(10)
.orderByChild('timestamp')
.once('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
const notification = childSnapshot.val();
notification.key = childSnapshot.key;
notifications.push(notification);
});
});
return notifications.reverse();
}
export async function getNotificationsRef(uid) {
return await firebase
.database()
.ref(`notifications/${uid}`);
}
export async function toggleReadNotification(request) {
let updates = {};
updates['/read'] = true;
await firebase
.database()
.ref(`notifications/${request.uid}/${request.notificationKey}`)
.update(updates);
}
export async function deleteNotification(request) {
return await firebase
.database()
.ref(`notifications/${request.uid}/${request.notification_id}`)
.update(null);
}
|
module.exports = {
name: 'stop',
description: 'Use this in a voice channel as a command to stop playing music',
execute(message) {
if (message.guild.voiceConnection) {
// Empty the queue
songQueueGroups[message.guild.id] = {queue: []};
var targetServer = servers.get(message.guild.id);
if (targetServer.timerId) {
clearTimeout(servers.get(message.guild.id).timerId);
}
if (targetServer.dispatcher) {
targetServer.dispatcher.destroy();
}
servers.delete(message.guild.id);
songQueueGroups.delete(message.guild.id);
message.member.voiceChannel.leave();
} else {
return message.channel.send("You need to be in a voice channel to be able to use this command");
}
},
};
|
'use strict';
var React = require('react');
var Scoreboard = require('./scoreboard');
// var PauseMenu = require('./pause-menu');
var Gameboard = require('./gameboard');
var GameStore = require('../stores/game-store');
var HeldPiece = require('./held-piece');
var PieceQueue = require('./piece-queue');
var Tetris = React.createClass({
displayName: 'Tetris',
render: function render() {
return React.createElement(
'div',
{ className: 'row' },
React.createElement(
'div',
{ className: 'col-md-2' },
React.createElement(Scoreboard, null)
),
React.createElement(
'div',
{ className: 'col-md-4' },
React.createElement(Gameboard, null)
),
React.createElement(
'div',
{ className: 'col-md-4' },
React.createElement(PieceQueue, null)
)
);
}
});
module.exports = Tetris;
|
module.exports = global.server ? global.server.workflowMgmt.main_db : {
url: "mongodb://localhost",
port: "27017",
user: "",
password: "",
dbname: "workflow-management",
authdb: ""
}
|
const initialState = {
openProjectPending: false,
openProjectError: null,
closeProjectPending: false,
closeProjectError: null,
studios: [],
studioById: {},
getInitialStatePending: false,
getInitialStateError: null,
initializing: true,
getMainStatePending: false,
getMainStateError: null,
newProjectDialogVisible: false,
welcomePageVisible: false,
};
export default initialState;
|
import React from 'react';
import { Grid, Typography } from '@material-ui/core';
import GameHeader from './../../components/GameHeader';
const Wavelength = () => (
<Grid>
<GameHeader title="Wavelength" />
<Typography align="center">Coming Soon!</Typography>
</Grid>
);
export default Wavelength;
|
import Page from './Page'
class CheckPage extends Page {
setFormat(format) {
browser.element('.SrcUiInputInput').setValue(format)
}
setCardFormat(format) {
browser.element('.SrcUiContentEditableContentEditable').setValue(format)
}
saveFormat() {
browser.element('.SrcUiLayoutLayout div .SrcUiLayoutLayout:nth-Child(1) .SrcUiLinkLink').click()
}
loadFormat() {
browser.element('.SrcUiLayoutLayout div .SrcUiLayoutLayout:nth-Child(2) .SrcUiLinkLink').click()
}
selectFormat(format) {
browser.element(`//*[text()='${format}']`).click()
}
showPreview() {
browser.element('.SrcPagesCheckComponentsCheckBlock .SrcUiButtonButton').click()
}
getPreviewCardNumber() {
return browser.element('table tbody td:nth-Child(2)').getText()
}
}
export default CheckPage
|
/*
Write a program that checks if the entered number is a prime number (i.e. divisible only by 1 and by itself).
Input: 17 | 15
Output: true | false
*/
function isPrime(number){
for(var i = 2;i < number; i++){
if(number % i === 0){
return false;
}
}
return number > 1;
}
console.log(isPrime(15));
|
import React from "react";
const Card = (props) => {
return (
<div className="display-card">
<div className="card">
<img className="card-img" src={props.img.proy} alt="Avatar" />
<div className="card-container">
<h4>
<b>{props.titulo}</b>
</h4>
<p>{props.descripcion} & Engineer</p>
<button className="button"><a className="enlaces" href={props.buton} target="_blank">Go to the project</a></button>
</div>
</div>
</div>
);
};
export default Card;
|
var searchData=
[
['q4',['Q4',['../db/df8/classBALL_1_1HMOFile.html#a9f25b113d2b7abc0b0853b72e5f9c5c4a0c94860378723ebae3ecada72b739353',1,'BALL::HMOFile']]],
['q8',['Q8',['../db/df8/classBALL_1_1HMOFile.html#a9f25b113d2b7abc0b0853b72e5f9c5c4a3cb5ff36d4d773fe5c2f74558f4849f4',1,'BALL::HMOFile']]]
];
|
window.onload = function(){
plusPrice();
/* 재고를 확인하는 function을 생성 */
check_amount();
}
function check_amount(){
var cnolist = document.getElementsByClassName("cnolist");
var list_checkbox = document.getElementsByClassName("list_checkbox");
var cartlist = document.getElementsByClassName("cartlist");
var arrCno = [];
for(var i = 0 ; i < cnolist.length; i++){
arrCno.push(cnolist[i].value);
}
var tempdata = {"arr":arrCno};
console.log(tempdata);
jQuery.ajaxSettings.traditional = true;
$.ajax({
url : "/checkAmount" ,
data : tempdata,
dataType : 'json',
contentType: "application/json;charset=utf-8",
success : function(result){
for(var j = 0 ; j < result.length; j++){
var pamount = result[j]*1;
if(pamount <= 0){
//console.log("pamount :" +pamount);
alert("재고가 소진된 제품은 결제가 불가합니다.");
list_checkbox[j].disabled = true;
/*cartlist[j].remove();*/
}
}
},error : function(error){
alert("결제할 제품이 없습니다.");
}
}); // end ajax
}
/* 주문 상품을 선택하지 않고 상품 주문을 선택할 시 오류를 막는 코드 */
function check_submit(){
var orderdata = document.getElementById("orderdata");
var first_cno = orderdata.firstChild;
if(first_cno == null)
{
alert("결제할 제품을 선택해주세요.")
return ;
}
var paysubmit = document.getElementById("paysubmit");
paysubmit.submit();
}
/* 전체 checkbox on , off 기능 구현 코드 */
function checkAll() {
var list_checkbox = document.getElementsByClassName("list_checkbox");
if(main_checkbox.checked == true){
for(var j = 0 ; j < list_checkbox.length ; j++){
if(list_checkbox[j].disabled==false){
list_checkbox[j].checked = true ;
}
}
}else{
for(var j = 0 ; j < list_checkbox.length ; j++){
if(list_checkbox[j].disabled==false){
list_checkbox[j].checked = false ;
}
}
}
}
/* checkbox가 onclick이 되면 실행이 되는 기능이다. */
function plusPrice(){
/* 클릭된 cno들은 class를 가지게 된다.
*
* 클릭된 cno는 checked = true 이다.
*
* 그래서 아래서 훑는 것이 checked = true 인지를 훑는 것이다.
*
*
*
* */
/*먼저 클릭된 cno가 몇번째 cno인지 확인을 해야하므로 총 갯수를 가지고 훑는다.*/
var list_checkbox = document.getElementsByClassName("list_checkbox");
var cnolist = document.getElementsByClassName("cnolist");
var price = document.getElementsByClassName("price");
var orderdata = document.getElementById("orderdata");
var hiddencno_list = document.getElementsByClassName("temp");
/* hiddencno_list 초기화 */
$("#orderdata *").remove();
/* 체크된 checkbox의 갯수를 세기 위함 */
/*var chcknum = 0;*/
var plusprice = 0;
var deliveryprice = 0;
var i = 0;
for(i = 0 ; i < list_checkbox.length ; i ++){
if(list_checkbox[i].checked == true){
var hiddencno = document.createElement("input");
/*chcknum += 1*1;*/
plusprice += price[i].value*1;
/* input type = hidden name = cnolist2 value = cnolist */
hiddencno.type = 'hidden';
hiddencno.value = cnolist[i].value;
hiddencno.name = "cnolist2" ;
orderdata.appendChild(hiddencno);
}
}
//test
/*console.log("선택된 값의 갯수" + chcknum);*/
/*console.log("plus price : " + plusprice);*/
/* 페이지에 보여지는 가격들을 위한 코드 */
/*var span = document.createElement('span');
span.innerText = plusprice;
span.classList.add("format-money");
document.getElementById("price_text").appendChild(span);
*/
document.getElementById("price_text").innerText = plusprice + "원";
/*document.getElementById("price_text").classList.add(".format-money");*/
if(plusprice*1 >= 50000){
deliveryprice = 0;
}else if(plusprice == 0 ){
deliveryprice = 0;
}else{
deliveryprice = 3000;
}
document.getElementById("delivery_price_text").innerText = deliveryprice+ "원";
document.getElementById("total_price_text").innerText = plusprice + deliveryprice + "원";
document.getElementById("total_price").value = plusprice + deliveryprice ;
}
/* 부분 선택 삭제 구현 중 배열로 ajax값을 날리는데 문제가 있음 */
function delete_cno(){
var userid = document.getElementById('userid');
var list_checkbox = document.getElementsByClassName("list_checkbox");
var cnolist = document.getElementsByClassName("cnolist");
var arrCno = [];
for(var i = 0 ; i < list_checkbox.length; i++){
if(list_checkbox[i].checked == true){
console.log(cnolist[i].value);
/*arrCno.push(cnolist[i].value);*/
arrCno.push(cnolist[i].value);
}
}
var tempdata = {"arr":arrCno, "userid":userid.value};
console.log(tempdata);
jQuery.ajaxSettings.traditional = true;
$.ajax({
url : "/deleteCno" ,
data : tempdata,
dataType : 'json',
contentType: "application/json;charset=utf-8",
success : function(result){
alert("삭제되었습니다.");
window.location.href = '/cart_list/'+result;
},error : function(error){
alert("삭제할 상품을 선택해주세요.");
}
}); // end ajax
}
function delete_ALL(){
var userid = document.getElementById('userid');
var temp = {"userid":userid.value};
$.ajax({
url : '/deleteAll',
data : temp ,
dataType : 'json',
contentType: "application/json;charset=utf-8",
success : function(result){
alert("장바구니를 비웠습니다.");
window.location.href = '/cart_list/'+result;
},error : function(data) {
alert("에러 : 관리자에게 문의하세요");
}
});
}
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
user_login: { type: String, unique: true, required: true },
user_firstname: { type: String, required: true },
user_lastname: { type: String, required: true },
user_pass: { type: String, required: true },
user_nikname: { type: String, required: false },
user_email: { type: String, required: false },
user_url: { type: String, required: false },
user_registered: { type: Date, default: Date.now },
user_activation_key: { type: String, required: false },
user_status: { type: String, required: false },
display_name: { type: String, required: false }
});
// schema.set('toJSON', {
// virtuals: true,
// versionKey: false,
// transform: function (doc, ret) {
// delete ret._id;
// delete ret.hash;
// }
// });
module.exports = mongoose.model('User', schema);
|
var hexagonboard = function(map) {
let sceneObject = new THREE.Object3D();
sceneObject.name = 'hexagons';
const radius = 20;
const hexWidth = radius * 2;
const hexHeight = Math.sqrt(3) / 2 * hexWidth;
const hexGeometry = new THREE.CylinderGeometry( radius, radius-3, 10, 6 );
function createHexWire( radius ){
const material = new THREE.LineBasicMaterial({ color: 0x00ff00 });
const geometry = new THREE.Geometry();
for( let i = 0; i <= 6; i += 1 ){
const angle = i / 6.0 * (Math.PI * 2.0);
const vertex = new THREE.Vector3(Math.sin(angle) * radius, 0.0, Math.cos(angle) * radius);
geometry.vertices.push( vertex );
}
let line = new THREE.Line( geometry, material );
line.name = 'hexWire';
return line;
}
const hexWire = createHexWire(17);
function createHex(posX, posY, type) {
let color = '#111111';
if( type == 1 ) color = '#6688dd';
else if( type == 2 ) color = '#efde8d';
else if( type == 3 ) color = '#af8e2d';
const hexMaterial = new THREE.MeshPhongMaterial( { color: color, wireframe: false, shininess: 1.0} );
let hexMesh = new THREE.Mesh( hexGeometry, hexMaterial );
hexMesh.rotation.set( 1.57, 1.57, 0);
hexMesh.position.set( posX * (hexWidth / 4 * 3), posY * hexHeight, 0 );
if( (posX % 2) == 1 )
hexMesh.position.y += hexHeight / 2;
hexMesh.updateMatrix();
return hexMesh;
}
map.data.forEach( tile => {
let hexObject = createHex(tile.x, tile.y, tile.type);
hexObject.userData.x = tile.x;
hexObject.userData.y = tile.y;
hexObject.userData.type = tile.type;
sceneObject.add( hexObject );
if( tile.move !== undefined ) {
let tileObject = planeGenerator.tile(tile.move);
tileObject.name = 'move';
hexObject.add(tileObject);
hexObject.material.color.setHex(tile.move.color);
hexObject.userData.hexColor = tile.move.color;
hexObject.userData.move = tile.move;
}
if( tile.type == 3 ) {
hexObject.add( planeGenerator.city(tile.city) );
hexObject.userData.city = tile.city;
}
});
return {
sceneObject: sceneObject,
hexWire: hexWire
};
};
var planeGenerator = (function() {
var cityTextures = {
textures: [
{name: "religion", map: THREE.ImageUtils.loadTexture('/img/religion64.png')},
{name: "trade", map: THREE.ImageUtils.loadTexture('/img/trade64.png')},
{name: "politics", map: THREE.ImageUtils.loadTexture('/img/politics64.png')},
{name: "samurai", map: THREE.ImageUtils.loadTexture('/img/samurai64.png')},
{name: "1", map: THREE.ImageUtils.loadTexture('/img/1.png')},
{name: "2", map: THREE.ImageUtils.loadTexture('/img/2.png')},
{name: "3", map: THREE.ImageUtils.loadTexture('/img/3.png')},
{name: "4", map: THREE.ImageUtils.loadTexture('/img/4.png')},
{name: "ronin", map: THREE.ImageUtils.loadTexture('/img/ronin64.png')},
{name: "boat", map: THREE.ImageUtils.loadTexture('/img/boat64.png')}
],
get: function(name){return this.textures.find( function(tex){return tex.name==name;} ); }
};
function getCityProperties(count){
if( count == 1 ) return { properties: [ {radius: 13, x: 0, y: 0} ] };
if( count == 2 ) return { properties: [ {radius: 13, x: -0, y: -6}, {radius: 13, x: 0, y: 6} ] };
return { properties: [ {radius: 11, x: 6, y: 0}, {radius: 11, x: -5, y: 6}, {radius: 11, x: -5, y: -6} ] };
}
function addSingleObject(name, map, xTranslate, zTranslate, radius, radiusY){
const planeMaterial = new THREE.MeshPhongMaterial({color: 0xFFFFFF, shininess: 1.0, map: map, transparent: true});
const planeGeometry = new THREE.BoxGeometry(radius, radiusY || radius, 0.1, 1, 1, 1);
let planeMesh = new THREE.Mesh(planeGeometry, planeMaterial);
planeMesh.position.y += 50;
planeMesh.position.x += xTranslate;
planeMesh.position.z += zTranslate;
planeMesh.rotation.x = Math.PI/2;
planeMesh.rotation.z = Math.PI/2;
planeMesh.name = name;
return planeMesh;
}
function city(properties) {
let count = 0;
let cities = [];
for( key in properties ) {
if( !properties.hasOwnProperty(key) )
continue;
count ++;
var textureObject = cityTextures.get(key);
if( textureObject === undefined ){
console.log('invalid city type', key);
continue;
}
cities.push(textureObject);
}
let cityObject = new THREE.Object3D();
cityObject.name = 'city';
let cityProperties = getCityProperties(count);
for( let i = 0; i < cities.length; i += 1 ){
const property = cityProperties.properties[i];
cityObject.add( addSingleObject(cities[i].name, cities[i].map, property.x, property.y, property.radius) );
}
return cityObject;
}
function tile(card){
const numberTexture = cityTextures.get(card.size);
const typeTexture = cityTextures.get(card.suite);
const properties = getCityProperties(2);
let tileObject = new THREE.Object3D();
tileObject.name = 'tempTurn';
tileObject.userData.card = card;
tileObject.add( addSingleObject(card.suite, typeTexture.map, properties.properties[0].x, properties.properties[0].y, properties.properties[0].radius) );
tileObject.add( addSingleObject(card.size, numberTexture.map, properties.properties[1].x, properties.properties[1].y, properties.properties[1].radius - 3) );
return tileObject;
}
return {
city: city,
tile: tile
};
})();
var boardHelper = ( function() {
function findSurroundingTiles(tile, mapObject) {
const tileOffsets = [{x: 0, y: 1}, {x: 0, y: -1}, {x: 1, y: 0}, {x: -1, y: 0}];
const specialOffsets = [
[{x: 1, y: -1}, {x: -1, y: -1}], //%2 == 0
[{x: 1, y: 1}, {x: -1, y: 1}] //%2 == 1
];
let surroundingTiles = [];
function findTilesFor(offset) {
let t = mapObject.children.find(
maptile =>
(offset.x + tile.userData.x) == maptile.userData.x &&
(offset.y + tile.userData.y) == maptile.userData.y
);
if (t)
surroundingTiles.push(t);
}
let specialOffset = specialOffsets[tile.userData.x % 2];
specialOffset.forEach(findTilesFor);
tileOffsets.forEach(findTilesFor);
return surroundingTiles;
}
return {
findTilesAround: findSurroundingTiles
};
})();
|
import { format, parseISO } from 'date-fns';
import pt from 'date-fns/locale/pt';
import Mail from '../../lib/Mail';
class SubscriptionMail {
get key() {
return 'SubscriptionMail';
}
async handle({ date }) {
const { user, data, name, titulo, email } = date;
await Mail.sendMail({
to: `${name}, <${email}>`,
subject: 'Nova inscrição na sua MeetUp!',
template: 'subscriptions',
context: {
name,
titulo,
user: user.name,
email: user.email,
data: format(parseISO(data), "'dia' dd 'de' MMMM', às' H:mm'hs'", {
locale: pt,
}),
},
});
}
}
export default new SubscriptionMail();
|
#!/usr/bin/env node
/* jshint node:true, esversion:6 */
'use strict';
/*!
* MIDI WebSocket Bridge Client.
* Hugo Hromic - http://github.com/hhromic
*
* Copyright 2016 Hugo Hromic
*
* 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.
*/
// required modules
const log4js = require('log4js');
const argparse = require('argparse');
const ws = require('ws');
const midi = require('midi');
const utils = require('../lib/utils.js');
const _package = require('../package');
// initialize loggers
const loggers = {
midi: log4js.getLogger('midi:' + process.pid),
websocket: log4js.getLogger('websocket:' + process.pid),
};
// process command-line arguments
const argParser = argparse.ArgumentParser({
version: _package.version,
description: _package.description,
});
argParser.addArgument(['-l', '--list-midi-devices'], {
type: Boolean, action: 'storeTrue', dest: 'listMidiDevices',
help: 'List available local MIDI devices and exit',
});
argParser.addArgument(['-u', '--ws-url'], {
type: String, defaultValue: 'ws://localhost:5000', metavar: 'URL', dest: 'wsUrl',
help: 'WebSocket server URL to connect (default: ws://localhost:5000)',
});
argParser.addArgument(['-d', '--midi-devices'], {
type: String, metavar: 'DEVICES', dest: 'midiDevices',
help: 'Local MIDI devices to bridge (default: none)',
});
const options = argParser.parseArgs();
// list local MIDI devices and exit?
if (options.listMidiDevices) {
utils.showPorts(new midi.input(), 'Current local MIDI input port indexes');
utils.showPorts(new midi.output(), 'Current local MIDI output port indexes');
process.exit(0);
}
// initialize WebSocket client
const midiDevices = [];
var wsClient = new ws(options.wsUrl);
wsClient.on('error', err => {
loggers.websocket.error('client error: %s', err.toString());
});
wsClient.on('open', () => {
const midiDevicesIndexes = utils.parseMidiDevicesIndexes(options.midiDevices);
midiDevicesIndexes.forEach(indexes => {
const newMidiDevice = {input: undefined, output: undefined};
if (indexes.input !== undefined) {
const midiInput = new midi.input();
midiInput.ignoreTypes(true, true, true);
midiInput.on('message', (deltaTime, message) => {
midiDevices.forEach(midiDevice => {
if (midiDevice !== newMidiDevice && midiDevice.output !== undefined) {
midiDevice.output.sendMessage(message);
}
});
wsClient.send(Buffer.from(message));
});
midiInput.openPort(indexes.input);
newMidiDevice.input = midiInput;
loggers.midi.info('using local MIDI input: %s', midiInput.getPortName(indexes.input));
}
if (indexes.output !== undefined) {
const midiOutput = new midi.output();
midiOutput.openPort(indexes.output);
newMidiDevice.output = midiOutput;
loggers.midi.info('using local MIDI output: %s', midiOutput.getPortName(indexes.output));
}
midiDevices.push(newMidiDevice);
});
loggers.websocket.info('client connected to %s', options.wsUrl);
});
wsClient.on('close', () => {
loggers.websocket.debug('client disconnected');
});
wsClient.on('message', (data, flags) => {
if (flags.binary) {
const midiMessage = Array.from(data);
midiDevices.forEach(midiDevice => {
if (midiDevice.output !== undefined) {
midiDevice.output.sendMessage(midiMessage);
}
});
}
});
|
$(document).ready(function(){
VK.Widgets.Group("vk_groups", {mode: 3, width: "550", height: "220"}, 148426161);
});
|
/**
* @license
* Copyright 2014 Google Inc. All Rights Reserved.
*
* 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('lf.proc.Runner');
goog.require('goog.structs.Set');
goog.require('lf.TransactionType');
goog.forwardDeclare('lf.proc.Task');
/**
* Query/Transaction runner which actually runs the query in a transaction
* (either implicit or explict) on the back store.
* @constructor
* @struct
* @final
*/
lf.proc.Runner = function() {
/**
* The scopes that are currently used by an in-flight query execution
* operation. Any other queries with overlapping scopes will be queued until
* their scopes are free.
* @private {!goog.structs.Set.<!lf.schema.Table>}
*/
this.usedScopes_ = new goog.structs.Set();
/** @private {!Array.<!lf.proc.Task>} */
this.queue_ = [];
};
/**
* Schedules a task for this runner.
* @param {!lf.proc.Task} task The task to be scheduled.
* @param {boolean=} opt_prioritize Whether the task should be added at the
* front of the queue, defaults to false.
* @return {!IThenable.<!Array.<!lf.proc.Relation>>}
*/
lf.proc.Runner.prototype.scheduleTask = function(task, opt_prioritize) {
var prioritize = opt_prioritize || false;
prioritize ? this.queue_.unshift(task) : this.queue_.push(task);
this.consumePending_();
return task.getResolver().promise;
};
/**
* Examines the queue and executes as many tasks as possible taking into account
* the scope of each task and the currently occupied scopes.
* @private
*/
lf.proc.Runner.prototype.consumePending_ = function() {
var queue = this.queue_.slice();
for (var i = 0; i < queue.length; i++) {
// Note: Iterating on a shallow copy of this.queue_, because this.queue_
// will be modified during iteration and therefore it is not correct
// iterating on this.queue_, as it can't guarantee that every task in the
// queue will be traversed.
var task = queue[i];
if (this.usedScopes_.intersection(task.getScope()).isEmpty()) {
// Removing from this.queue_, not queue which is a copy used for
// iteration.
this.queue_.splice(i, /* howMany */ 1);
this.execTask_(task);
}
}
};
/**
* Executes a QueryTask. Callers of this method should have already checked
* that no other running task is using any table within the combined scope of
* this task.
* @param {!lf.proc.Task} task
* @private
*/
lf.proc.Runner.prototype.execTask_ = function(task) {
this.acquireScope_(task);
task.exec().then(
goog.bind(this.onTaskSuccess_, this, task),
goog.bind(
/** @type {function(*)} */ (this.onTaskError_), this, task));
};
/**
* Acquires the necessary scope for the given task.
* @param {!lf.proc.Task} task
* @private
*/
lf.proc.Runner.prototype.acquireScope_ = function(task) {
if (task.getType() == lf.TransactionType.READ_WRITE) {
this.usedScopes_.addAll(task.getScope());
}
};
/**
* Releases the scope that was held by the given task.
* @param {!lf.proc.Task} task
* @private
*/
lf.proc.Runner.prototype.releaseScope_ = function(task) {
if (task.getType() == lf.TransactionType.READ_WRITE) {
this.usedScopes_.removeAll(task.getScope());
}
};
/**
* Executes when a task finishes successfully.
* @param {!lf.proc.Task} task The task that finished.
* @param {!Array.<!lf.proc.Relation>} results The result produced by the task.
* @private
*/
lf.proc.Runner.prototype.onTaskSuccess_ = function(task, results) {
this.releaseScope_(task);
task.getResolver().resolve(results);
this.consumePending_();
};
/**
* Executes when a task finishes with an error.
* @param {!lf.proc.Task} task The task that finished.
* @param {!Error} error The error that caused the failure.
* @private
*/
lf.proc.Runner.prototype.onTaskError_ = function(task, error) {
this.releaseScope_(task);
task.getResolver().reject(error);
this.consumePending_();
};
|
Ext.JpdlPanel = Ext.extend(Ext.Panel, {
initComponent: function() {
this.on('bodyresize', function(p, w, h) {
var b = p.getBox();
this.jpdlCanvas.setX(b.x);
this.jpdlCanvas.setWidth(b.width - 200);
this.jpdlCanvas.setHeight(b.height);
this.jpdlPalette.setX(b.x + this.jpdlCanvas.getWidth());
this.jpdlPalette.setHeight(b.height);
this.jpdlModel.resize(b.x, b.y, b.width - 200, b.height);
});
},
afterRender: function() {
Ext.JpdlPanel.superclass.afterRender.call(this);
var box = this.getBox();
Ext.DomHelper.append(this.body, [{
id: '_jpdl_canvas',
tag: 'div',
cls: 'jpdlcanvas'
}, {
id: '_jpdl_palette',
tag: 'div',
cls: 'jpdlpalette',
html: this.createPalette()
}]);
this.jpdlCanvas = Ext.get('_jpdl_canvas');
this.jpdlPalette = Ext.get('_jpdl_palette');
this.jpdlModel = new Jpdl.Model({
id: '_jpdl_canvas'
});
},
createPalette: function() {
// header
var html = '<div class="dragHandle move">'
+'<span class="move" unselectable="on">palette</span>'
+'</div>';
html += '<ul>'
// part1
html += this.createPart('Operations',['select','marquee']);
// part2
html += this.createPart('Components',['transition-straight','transition-broken','start','end','cancel','error',
'state','hql','sql','java','script','esb','task','decision','fork','join']);
html += '</ul>'
return html;
},
createPart: function(title, items) {
var html = '<li class="paletteBar"><div unselectable="on">' + title+ '</div><ul>';
for (var i = 0; i < items.length; i++) {
var t = items[i];
html += '<li id="' + t + '" class="paletteItem ' + t + '">'
+ '<span class="paletteItem-' + t + '" unselectable="on">' + t + '</span>'
+ '</li>';
}
html += '</ul></li>';
return html;
}
});
Ext.reg('jpdlpanel', Ext.JpdlPanel);
/*
Ext.onReady(function() {
var viewport = new Ext.Viewport({
layout: 'fit',
items: [{
tbar: new Ext.Toolbar([
'Open', '-', 'Save'
]),
bbar: new Ext.Toolbar([
'->', 'Position'
]),
layout: 'border',
items: [{
region: 'west',
title: 'menu',
width: 150,
layout: 'accordion',
items: [{
title: 'attributes'
}, {
title: 'elements'
}, {
title: 'forms'
}]
}, {
region: 'center',
xtype: 'jpdlpanel'
}]
}]
});
});
*/
/*
Jpdl.onReady(function(){
var model = new Jpdl.Model({
id: 'canvas'
});
});
*/
|
import Message from './message.jsx';
import Route from '../../js/route';
import messagesActions from '../../actions/messagesActions';
class MessageRoute extends Route {
constructor() {
super();
this.name = "message";
this.component = Message;
}
fetch(nextState) {
var id = nextState.params.id;
return messagesActions.getById(id);
}
}
export default new MessageRoute();
|
const Task = require('./Task')
const CalenderTaskRunner = require('./runners/CalenderTaskRunner')
const CronTaskRunner = require('./runners/CronTaskRunner')
const IntervalTaskRunner = require('./runners/IntervalTaskRunner')
const PeriodTaskRunner = require('./runners/PeriodTaskRunner')
let i = 0
const tasks = []
function getNextId() {
return `Task ${++i}`
}
function stopAll() {
for (const task of tasks) {
task.stop()
}
}
function stop(taskId) {
const task = tasks.find(t => t.getId() === taskId)
task.stop()
}
function reschedule(taskId, timing) {
const task = tasks.find(t => t.getId() === taskId)
task.reschedule(timing)
}
function doAfter(fn, period) {
const task = new Task(fn, period)
task.setTaskRunner(new PeriodTaskRunner())
task.setId(getNextId())
tasks.push(task)
task.run()
return task.getId()
}
function doAt(fn, date) {
if (!(date instanceof Date)) {
throw new Error('date should be Date object')
}
if (date - Date.now() < 0) {
throw new Error('date should be in the future')
}
const task = new Task(fn, date)
task.setTaskRunner(new CalenderTaskRunner())
task.setId(getNextId())
tasks.push(task)
task.run()
return task.getId()
}
function doRecurrent(fn, period) {
const task = new Task(fn, period)
task.setTaskRunner(new IntervalTaskRunner())
task.setId(getNextId())
tasks.push(task)
task.run()
return task.getId()
}
function doRecurrentCron(fn, cron) {
const task = new Task(fn, cron)
task.setTaskRunner(new CronTaskRunner())
task.setId(getNextId())
tasks.push(task)
task.run()
return task.getId()
}
module.exports = {
stopAll,
stop,
reschedule,
doAfter,
doAt,
doRecurrent,
doRecurrentCron
}
|
import React from "react";
import { Link } from "react-router-dom";
function Footer(props) {
return (
<nav className="navbar fixed-bottom footer">
<span>
Made with
<Link className="footer-link" to="https://reactjs.org/">
ReactJs
</Link>
by
<Link className="footer-link" to="https://github.com/Eugene4277">
Eugene
</Link>
</span>
</nav>
);
}
export default Footer;
|
const gulp = require('gulp')
const rename = require('gulp-rename')
const sass = require('gulp-sass')
const cleanCss = require('gulp-clean-css')
const concat = require('gulp-concat')
function styles () {
return gulp.src('./public/src/scss/**/init.scss')
.pipe(sass()).on('error', sass.logError)
.pipe(rename({
basename: 'style'
}))
.pipe(cleanCss({compatibility: 'ie8'}))
.pipe(gulp.dest('./public/dist/css/'))
}
function watch () {
gulp.watch('./public/src/scss/**/*.scss', styles)
gulp.watch('./public/src/img/**/*', img)
gulp.watch('./public/src/js/**/*.js', js)
gulp.watch('./public/src/pdf/**/*.pdf', pdf)
}
function js () {
const customJs = './public/src/js/**/*.js'
return gulp.src([customJs])
.pipe(concat('script.js'))
.pipe(rename({
basename: 'script',
extname: '.js'
}))
.pipe(gulp.dest('./public/dist/js/'))
}
function img () {
const images = './public/src/img/**/*'
return gulp.src([images])
.pipe(gulp.dest('./public/dist/img/'))
}
function pdf () {
const pdfs = './public/src/pdf/**/*'
return gulp.src([pdfs])
.pipe(gulp.dest('./public/dist/pdf/'))
}
exports.watch = watch
exports.styles = styles
exports.js = js
exports.img = img
exports.pdf = pdf
const build = gulp.series(gulp.parallel(styles, img, js, pdf))
gulp.task('default', build)
|
import React from 'react';
import Layout from "../components/Layout";
import NavOne from "../components/NavOne";
import SliderOne from "../components/SliderOne";
import Footer from "../components/Footer";
import Topbar from "../components/Topbar";
import CalendarioDigital from "../components/CalendarioDigital";
const CalendarioPage = () => {
return (
<Layout pageTitle="Santa Cruz Educa">
<Topbar />
<NavOne />
{/* <SliderOne /> */}
<CalendarioDigital titulo='Cursos Actuales'/>
<CalendarioDigital titulo='Proximos Cursos'/>
<CalendarioDigital titulo= 'Anteriores Cursos'/>
<Footer />
</Layout>
);
};
export default CalendarioPage;
|
const { userModel, tokenModel } = require("../../models/index");
const { getBalance } = require("../../helpers/index");
const { preparedUser } = require("../../helpers/index");
const jwt = require("jsonwebtoken");
module.exports = async (req, res, next) => {
let error = null;
try {
const { email, password } = res.locals.user;
const user = await userModel.findUserByEmail(email);
if (!user || user.status !== true) {
error = "SIGNINERROR";
res.locals.errorMessage = "user doesnt exist or verified";
next(error);
return;
}
if (password !== user.password) {
error = "SIGNINERROR";
res.locals.errorMessage = "wrong password";
next(error);
return;
}
const token = await jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
expiresIn: 1 * 24 * 60 * 60,
});
await tokenModel.create({
userId: user._id,
token,
lastModifiedDate: Date.now(),
});
const balance = await getBalance(user.walletId);
return res.status(200).json({
token: token,
balance,
...preparedUser(user),
});
} catch (err) {
res.locals.errorMessage = "Oops something went wrong try it later";
error = "SIGNINERROR";
next(error);
}
};
|
import { faBook, faBookMedical, faBookReader, faBorderAll, faUserCog, faUsers } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import React from 'react';
import { NavLink } from 'react-router-dom';
const AdminDashboardSidebar = ({ url }) => {
// Active link style
const activeLinkStyle = {
fontWeight: "bold",
}
return (
<div className="container mt-5 ">
<div className="">
<div className="h3">Dashboard</div>
<ul className="list-unstyled mt-3 adm-sidebar">
<li className="mt-3">
<NavLink exact
className="nav-link text-dark text-nowrap"
activeStyle={activeLinkStyle}
to={`${url}/profile`}>
<FontAwesomeIcon icon={faUserCog} /> Profile
</NavLink>
</li>
<li className="mt-3">
<button className="btn btn-link shadow-none text-nowrap text-dark text-decoration-none border-0" type="button" data-bs-toggle="collapse" data-bs-target="#collapseBooks" >
<FontAwesomeIcon icon={faBook} /> Books
</button>
</li>
<div className="collapse ms-4" id="collapseBooks">
<NavLink exact
className="nav-link text-dark text-nowrap"
activeStyle={activeLinkStyle}
to={`${url}/addBook`}>
<FontAwesomeIcon icon={faBookMedical} /> Add Book
</NavLink>
<NavLink exact
className="nav-link text-dark text-nowrap"
activeStyle={activeLinkStyle}
to={`${url}/viewBooks`}>
<FontAwesomeIcon icon={faBookReader} /> View Books
</NavLink>
</div>
<li className="mt-3">
<NavLink exact
className="nav-link text-dark text-nowrap"
activeStyle={activeLinkStyle}
to={`${url}/category`}>
<span className="position-relative pt-2">
<FontAwesomeIcon icon={faBorderAll} /> Categories
</span>
</NavLink>
</li>
<li className="mt-3">
<NavLink exact
className="nav-link text-dark text-nowrap"
activeStyle={activeLinkStyle}
to={`${url}/users`}>
<span className="position-relative pt-2">
<FontAwesomeIcon icon={faUsers} /> Users
</span>
</NavLink>
</li>
</ul>
</div>
<hr />
</div>
);
}
export default AdminDashboardSidebar;
|
import DS from "ember-data";
export default DS.Model.extend({
email: DS.attr('string'),
firstName: DS.attr('string'),
lastName: DS.attr('string'),
screenName: DS.attr('string'),
fullName: function () {
var firstName = this.get('firstName'),
lastName = this.get('lastName'),
parts = [];
if (firstName) {
parts.push(firstName);
}
if (lastName) {
parts.push(lastName);
}
return parts.join(' ');
}.property('firstName', 'lastName'),
displayName: function () {
var screenName = this.get('screenName'),
fullName = '';
if (screenName) {
return screenName;
} else {
fullName = this.get('fullName');
if (fullName) {
return fullName;
} else {
return this.get('email');
}
}
}.property('screenName', 'fullName', 'email')
});
|
import {
HANDLE_BACKWARD,
HANDLE_FORWARD,
HANDLE_HELP_RESET
} from '../constants/help';
import sections from '../data/static/howItWorks';
const stepIndex = (state = 1, action) => {
switch (action.type) {
case HANDLE_FORWARD:
return state + 1;
case HANDLE_BACKWARD:
return state - 1;
default:
return state;
}
};
const help = (state = {
stepIndex: 1,
sections
}, action) => {
switch (action.type) {
case HANDLE_FORWARD:
return Object.assign({}, state, {
stepIndex: stepIndex(state.stepIndex, action)
});
case HANDLE_BACKWARD:
return Object.assign({}, state, {
stepIndex: stepIndex(state.stepIndex, action)
});
case HANDLE_HELP_RESET:
return Object.assign({}, state, {
stepIndex: 1
});
default:
return state;
}
};
export default help;
|
var todo = new Object();
todo.isActive = true;
var draggableExist = false;
var newDraggable;
var $todoList;
var $calCells;
var helperClone;
var todoItemTemplate;
var quickAddInput;
$(function(){
$todoList = $('#todoList');
$bodyTag = $('body');
todoItemTemplate = $('#todoItemTemplate');
quickAddInput = $('#quickAddInput');
todo.setupToDoList();
todo.setupQuickAddForm();
todo.getAllToDos();
});
//function calCreateNewEventFunct(event, ui){
// var eventText = ui.draggable.children(".todoTitle").html();
// var eventID = 'calEvent_'+ui.draggable.attr('id');
// var calNewEvent = $('<div id="'+eventID+'" class="calEvent">'+eventText+'</div>')
//
// $('#'+eventID).remove();
//
// $(this).append(calNewEvent);
// $('#'+eventID).ellipsis();
//}
//function calCellHoverEffectFunct(e){
// $(this).toggleClass('calCellActive');
//}
// START OF TRANSITION TO OBJECT NOTATION
todo.details = null; //Info on current todo. To get id, todo.details.id
todo.detailsDivHeight = 0;
todo.allToDos = new Array(0);
todo.setupToDoList = function(){
$todoList
.sortable({
axis: 'y',
tolerance: 'pointer',
sort: todo.todoListSortingFunct,
update: todo.reorderToDos,
stop: function(event, ui){
ui.item.show();
if(draggableExist){
newDraggable.remove();helperClone.remove();
}
draggableExists = false;
}
});
$('.todoCheckBox').live('click', todo.toggleCompleteStatus);
$('.todoCheckBox').live("mouseover", function(){
if ($(this).parent().data("complete")==0)
$(this).children('.todoCheckOff').addClass('todoCheckHover');
});
$('.todoCheckBox').live("mouseout", function(){
if ($(this).parent().data("complete")==0)
$(this).children('.todoCheckOff').removeClass('todoCheckHover');
});
$('.todo').live('click', todo.showToDoDetails);
$('.calEvent').live('click', todo.showToDoDetails);
$('#todoDetailsClose').click(todo.hideToDoDetails)
}
todo.setupQuickAddForm = function(){
$("#addTodoForm")
.submit(todo.quickAddSend);
}
todo.quickAddSend = function(){
var data;
var todoTitle = quickAddInput.val();
if(jQuery.trim(todoTitle)=="")
return false;
data = {
site: site.siteID(),
title: todoTitle
};
gen.json(
window.location.pathname + '/todos/',
data,
function(data){
todo.addNewToDoItem(data, false);
quickAddInput.val("").focus();
todo.toggleToDoListTut("hide");
}
);
return false;
}
todo.createNewToDoItem = function(data){
var newToDo = todoItemTemplate.clone();
var pretty_time = '';
var members = ' ';
(data.pretty_time != '') ? pretty_time=data.pretty_time + ' ' : pretty_time='';
if(data.members.length != 0){
members = 'Assigned To: ';
$.each(data.members, function(i, item){
members = members + item;
if((i+1) != data.members.length)
members = members + ", ";
});
}
newToDo
.attr('id', 'todo_'+data.id)
.removeClass('hidden')
.children('.todoTitle')
.attr('id', 'todoTitle_'+data.id)
.html('<span>'+data.title+'</span>')
.end()
.children('.todoBottom')
.children('.todoAssignedMembers')
.attr('id', 'todoAssignedMembers_'+data.id)
.html(members)
.end()
.children('.todoDueDate')
.attr('id', 'todoDueDate_'+data.id)
.html(pretty_time + data.pretty_date);
return newToDo;
}
todo.configureToDoItem = function(data){
$('#todoTitle_'+data.id).ellipsis();
$('#todo_'+data.id).data("id", data.id);
$('#todo_'+data.id+' .todoExpand').data("id", data.id);
todo.toggleToDoCheckmark(data);
}
todo.updateToDoItem = function(data){
$('#todo_'+data.id).replaceWith(todo.createNewToDoItem(data));
if(todo.details != null)
$('#todo_'+data.id).addClass('droppableHover');
todo.configureToDoItem(data);
todo['id_'+data.id] = data;
}
todo.addNewToDoItem = function(data, scrollTop){
var scrollPos = 0;
if(!scrollTop)
scrollPos = $todoList.attr("scrollHeight");
$todoList
.append(todo.createNewToDoItem(data))
.attr({
scrollTop: scrollPos
});
todo['id_'+data.id] = data;
todo.allToDos.push('id_'+data.id);
cal.updateCalEvent(data.id);
todo.configureToDoItem(data);
}
todo.todoListSortingFunct = function(e, ui){
if(e.pageX > 328){
if(!draggableExist){
draggableExist = true;
newDraggable = $('<div>'+ui.item.children(".todoTitle").html()+'</div>')
.addClass("todoDraggable")
.addClass("ui-state-hover")
.appendTo($bodyTag)
.ellipsis()
.css({
'top': e.pageY,
'left': e.pageX
});
helperClone = ui.item
.clone()
.appendTo($bodyTag)
.css({
'top': ui.offset.top,
'left': 11
})
.animate({
'top': ui.placeholder.offset().top
}, 500);
ui.item.hide();
}else{
newDraggable.css({
'top': e.pageY,
'left': e.pageX
});
}
}else{
if(draggableExist){
draggableExist = false;
newDraggable.remove();
helperClone.remove();
ui.item.show();
}
}
}
todo.getAllToDos = function(){
data = {
site: null //site.siteID() //This should be modified in the future when site.siteID() uses listeners
}
gen.json(
window.location.pathname + '/todos/getAllToDos/',
data,
function(data){
$.each(data, function(i, item){
todo.addNewToDoItem(item, true);
});
cal.createAllEvents();
todo.toggleToDoListTut("show");
},
'Loading ToDo List...'
);
}
todo.toggleToDoListTut = function(action){
if(action == "show" && !site.settingsBoxDisplayed && todo.allToDos.length == 0){
$('#todoListTut').fadeIn();
}else{
$('#todoListTut').hide();
}
}
todo.reorderToDos = function(){
var serial = $todoList.sortable('serialize');
data = {
site: site.siteID(),
order: 'serial'
};
gen.json(
window.location.pathname + '/todos/reorderToDos/?' + serial,
data,
function(data){}
);
}
todo.toggleCompleteStatus = function(){
var todoItem = $(this).parent();
var todo_id = todoItem.data("id");
data = {
site: site.siteID(),
id: todo_id,
complete: todoItem.data("complete")
};
gen.json(
window.location.pathname + '/todos/toggleCompleteStatus/',
data,
todo.toggleToDoCheckmark
);
return false;
}
todo.toggleToDoCheckmark = function(data){
var todoItem = $('#todo_'+data.id);
var checkMark = todoItem.children('.todoCheckBox').children('span');
if(data.complete==0){
todoItem.removeClass('todoComplete');
checkMark.removeClass('todoCheckOn');
checkMark.addClass('todoCheckOff');
}else{
todoItem.addClass('todoComplete');
checkMark.addClass('todoCheckOn');
checkMark.removeClass('todoCheckOff');
}
checkMark.removeClass('todoCheckHover');
todoItem.data("complete", data.complete);
if(todo.details && todo.details.id == data.id){
todo.details.complete = data.complete;
if(data.complete == 1){
$('#todoDetailsCompleteStatus_'+data.id).html('Yes');
$('#id_complete').attr('checked', true);
}else if (data.complete == 0){
$('#todoDetailsCompleteStatus_'+data.id).html('No');
$('#id_complete').attr('checked', false);
}
}
}
todo.showToDoDetails = function(event, ui){
var todoItem = $(this);
var todoID = todoItem.data('id');
if(!todo.isActive){
return false;
}
todo.loadToDoDetails(todoID);
$('#todoList div').removeClass('droppableHover');
$('#todo_'+todoID).addClass('droppableHover');
return false;
}
todo.hideToDoDetails = function(){
$('#todoDetails').hide();
todo.details = null;
$('#tabs').show();
$('#todoList div').removeClass('droppableHover');
return false;
}
todo.loadToDoDetails = function(todo_id){
data = {
site: site.siteID(),
id: todo_id
};
gen.json(
window.location.pathname + '/todos/viewmodifyToDoDetails/',
data,
function(data){
// $('#todoDetailsHeader').html(data.title);
todo.details = data;
$('#todoDetails').show();
$('#tabs').hide();
$('#todoDetailsTable').html(data.table).attr('scrollTop', 0);
$('#modifyToDoDetailsFormContent').html(data.form);
todo.createViewToDoDetailsTable();
},
'Loading...'
);
}
todo.sendModifyToDoDetailsForm = function(){
var data = $('#modifyToDoDetailsForm').serialize();
gen.jsonPost(
window.location.pathname + '/todos/viewmodifyToDoDetails/',
data,
function(data){
var scrollPos = $('#todoDetailsForm').attr('scrollTop');
todo.details = data;
if(data.form_success){
$('#todoDetailsTable').html(data.table);
$('#modifyToDoDetailsFormContent').html(data.form);
todo.createViewToDoDetailsTable();
$('#todoDetailsTable').attr('scrollTop', (scrollPos+10));
todo.updateToDoItem(data);
cal.updateCalEvent(data.id);
}else{
$('#modifyToDoDetailsFormContent').html(data.form);
todo.createModifyToDoDetailsForm();
todo.restyleModifyToDoDetailsForm();
$('#todoDetailsForm').attr('scrollTop', ($('#modifyToDoDetailsFormContent ul.errorlist:first').position().top - 10));
}
}
);
return false;
}
todo.createViewToDoDetailsTable = function(){
var data = todo.details;
var detailsTable = $('#todoDetailsTable')
var detailsForm = $('#todoDetailsForm');
var scrollPos = detailsForm.attr('scrollTop');
$('#todoDetailsHeader').html('ToDo Details: ' + data.title);
detailsForm.hide();
detailsTable.show().attr('scrollTop', scrollPos);
$('#todoDetailsActionButton')
.html('Edit')
// .addClass('ui-state-hover')
// .focus()
// .blur(function(){
// $(this).removeClass('ui-state-hover');
// })
.unbind('click')
.click(todo.createModifyToDoDetailsForm);
$('#todoDetailsCancelButton')
.html('Close')
.unbind('click')
.click(todo.hideToDoDetails);
todo.configureRelatedTopicsTable();
todo.configureRelatedFilesTable();
}
todo.createModifyToDoDetailsForm = function(){
var data = todo.details;
var detailsTable = $('#todoDetailsTable')
var detailsForm = $('#todoDetailsForm');
var scrollPos = detailsTable.attr('scrollTop');
$('#todoDetailsHeader').html('Edit: ' + data.title);
detailsTable.hide();
detailsForm.show();
$('#id_id').val(data.id);
$('#modifyToDoDetailsForm').submit(todo.sendModifyToDoDetailsForm);
$('#todoDetailsActionButton')
.html('Save')
// .addClass('ui-state-hover')
// .focus()
// .blur(function(){
// $(this).removeClass('ui-state-hover');
// })
.unbind('click')
.click(todo.sendModifyToDoDetailsForm);
$('#todoDetailsCancelButton')
.html('Cancel')
.unbind('click')
.click(todo.createViewToDoDetailsTable);
$('#id_description').elastic({onResize: function(){
var detailsForm = $('#todoDetailsForm');
var oldHeight = todo.detailsDivHeight;
var newHeight = detailsForm.attr('scrollHeight');
var heightDiff = (newHeight-oldHeight);
var scrollPos = detailsForm.attr('scrollTop');
todo.detailsDivHeight = detailsForm.attr('scrollHeight');
detailsForm.attr('scrollTop', (scrollPos+heightDiff));
}});
todo.detailsDivHeight = detailsForm.attr('scrollHeight');
detailsForm.attr('scrollTop', scrollPos);
todo.configureRelatedTopicsTable();
todo.configureRelatedFilesTable();
}
todo.restyleModifyToDoDetailsForm = function(){
var data = todo.details;
$.each(data.error_keys, function(i, item){
$('#id_'+item)
.css({
'margin-top':'0',
'border': '1px solid red'
});
});
}
todo.removeRelatedTopic = function(topic_id, todo_id){
var data = {
site: site.siteID(),
item: topic_id,
todo: todo_id
};
gen.jsonPost(
window.location.pathname + '/todos/removeRelatedTopic/',
data,
function(data){
$('#relatedTopicsView').html(data.topics_table);
$('#relatedTopicsModify').html(data.topics_table);
todo.configureRelatedTopicsTable();
}
);
}
todo.configureRelatedTopicsTable = function(){
$('#relatedTopicsTable .relatedTopicLink').each(function(){
var link = $(this);
var id = link.attr('id').split('_')[1];
link.click(function(){
todo.hideToDoDetails();
site.tabs.tabs('select', 1);
discuss.displayCurrentDiscussion(id);
return false;
});
});
$('#relatedTopicsView .relatedTopicRemoveLink').each(function(){
var link = $(this);
var id = link.attr('id').split('_')[1];
link.click(function(){todo.removeRelatedTopic(id, todo.details.id);return false;});
});
$('#relatedTopicsModify .relatedTopicRemoveLink').each(function(){
var link = $(this);
var id = link.attr('id').split('_')[1];
link.click(function(){todo.removeRelatedTopic(id, todo.details.id);return false;});
});
}
todo.removeRelatedFile = function(file_id, todo_id){
var data = {
site: site.siteID(),
item: file_id,
todo: todo_id
};
gen.jsonPost(
window.location.pathname + '/todos/removeRelatedFile/',
data,
function(data){
$('#relatedFilesView').html(data.files_table);
$('#relatedFilesModify').html(data.files_table);
todo.configureRelatedFilesTable();
}
);
}
todo.configureRelatedFilesTable = function(){
$('#relatedFilesTable .relatedFileLink').each(function(){
var link = $(this);
var currHref = link.attr('href');
link.attr('href', site.media_url+'/storage/'+site.url+'/'+currHref);
});
$('#relatedFilesView .relatedFileRemoveLink').each(function(){
var link = $(this);
var id = link.attr('id').split('_')[1];
link.click(function(){todo.removeRelatedFile(id, todo.details.id);return false;});
});
$('#relatedFilesModify .relatedFileRemoveLink').each(function(){
var link = $(this);
var id = link.attr('id').split('_')[1];
link.click(function(){todo.removeRelatedFile(id, todo.details.id);return false;});
});
}
//function asdf(){
// var detailsTable = $('#todoDetailsTable')
// var detailsForm = $('#todoDetailsForm');
// var scrollPos = detailsTable.attr('scrollTop');
//
// console.log('Table ScrollPos: ' + scrollPos);
// console.log('Table ScrollHeight: ' + detailsTable.attr('scrollHeight'));
// console.log('Table ScrollTop: ' + detailsTable.attr('scrollTop'));
// console.log('Form ScrollHeight: ' + detailsForm.attr('scrollHeight'));
// console.log('Form ScrollTop: ' + detailsForm.attr('scrollTop'));
//}
//END OF ToDoList////////////////////////////////////////////////////////////////////////////////
|
import React from 'react';
import { Route } from 'react-router-dom';
import PrivateRoutes from './PrivateRoutes';
import Login from '../views/Login';
const Routes = () => (
<div>
<Route component={PrivateRoutes} />
<Route exact path="/login" component={Login} />
</div>
);
export default Routes;
|
import {
MANAGE_PINCODE_REQUEST,
MANAGE_PINCODE_SUCCESS,
MANAGE_PINCODE_FAILURE,
} from './manage-pincode-constants';
const initialState = {
error: false,
isFetching: false,
pincodeDetails: [],
totalRecords: '',
};
const managePincode = (state = initialState, action) => {
switch (action.type) {
case MANAGE_PINCODE_REQUEST:
return {
...state,
isFetching: true,
pincodeDetails: [],
};
case MANAGE_PINCODE_FAILURE:
return {
...state,
error: true,
isFetching: false,
pincodeDetails: [],
};
case MANAGE_PINCODE_SUCCESS:
return {
...state,
error: false,
isFetching: false,
pincodeDetails: action.data,
totalRecords: action.totalRecords,
};
default:
return state;
}
};
export default managePincode;
|
class VersionValidator {
constructor() { }
validate(value) {
return {
isValid: /^\d+(\.\d+(\.\d+)?)?$/.test(value.trim()),
message: 'Layout must follow version standards (e.g., 9 or 9.9 or 9.9.9).'
};
}
}
export default (new VersionValidator());
|
window.onload = function() {
var info = {
timeOpened: new Date(),
timezone: (new Date()).getTimezoneOffset() / 60,
pageon: window.location.pathname,
referrer: document.referrer,
previousSites: history.length,
browserName: navigator.appName,
browserEngine: navigator.product,
browserVersion1a: navigator.appVersion,
browserVersion1b: navigator.userAgent,
browserLanguage: navigator.language,
browserOnline: navigator.onLine,
browserPlatform: navigator.platform,
javaEnabled: navigator.javaEnabled(),
dataCookiesEnabled: navigator.cookieEnabled,
dataCookies1: document.cookie,
dataCookies2: decodeURIComponent(document.cookie.split(";")),
dataStorage: localStorage,
sizeScreenW: screen.width,
sizeScreenH: screen.height,
sizeDocW: document.width,
sizeDocH: document.height,
sizeInW: innerWidth,
sizeInH: innerHeight,
sizeAvailW: screen.availWidth,
sizeAvailH: screen.availHeight,
scrColorDepth: screen.colorDepth,
scrPixelDepth: screen.pixelDepth,
}
if (Object.keys(navigator.geolocation).length !== 0) {
info = {
...info, ...{
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy,
altitude: position.coords.altitude,
altitudeAccuracy: position.coords.altitudeAccuracy,
heading: position.coords.heading,
speed: position.coords.speed,
timestamp: position.timestamp,
}
}
}
}
|
var COMB_TYPE_NONE = 0 // 0点
var COMB_TYPE_OX1 = 1 // 1点
var COMB_TYPE_OX2 = 2 // 2点
var COMB_TYPE_OX3 = 3 // 3点
var COMB_TYPE_OX4 = 4 // 4点
var COMB_TYPE_OX5 = 5 // 5点
var COMB_TYPE_OX6 = 6 // 6点
var COMB_TYPE_OX7 = 7 // 7点
var COMB_TYPE_OX8 = 8 // 8点
var COMB_TYPE_OX9 = 9 // 9点
var COMB_TYPE_SAN_GONG = 10 // 三公
var COMB_TYPE_SAN_TIAO = 11 // 三条
var COMB_TYPE_BAO_SAN = 12 // 爆三
//获取牌型
module.exports.getType = function(handCard) {
var result = {
"type" : 0,
"card" : {},
"award": 1
}
//先找出最大的单张牌
result.card = handCard[0]
for(var i = 1;i < 3;i++){
if(handCard[i].num > result.card.num || (handCard[i].num == result.card.num && handCard[i].type > result.card.type)){
result.card = handCard[i]
}
}
var GongNum = 0
//计算公数量
for(var i = 0;i < 3;i++){
if(handCard[i].num < 14 && handCard[i].num > 10){
GongNum++
}
}
//爆三
if(handCard[0].num == 3 && handCard[1].num == 3 && handCard[2].num == 3){
result.type = COMB_TYPE_BAO_SAN
result.award = 9
return result
}
//三条
if(handCard[0].num == handCard[1].num && handCard[1].num == handCard[2].num){
result.type = COMB_TYPE_SAN_TIAO
result.award = 5
return result
}
//三公
if(GongNum == 3){
result.type = COMB_TYPE_SAN_GONG
result.award = 4
return result
}
var pointNum = 0
//普通牌型,计算点数
for(var i = 0; i < 3;i++){
if(handCard[i].num < 10){
pointNum += handCard[i].num
}
}
pointNum = pointNum % 10
if(pointNum == 9){
result.type = COMB_TYPE_OX9
result.award = 3
return result
}else if(pointNum == 8){
result.type = COMB_TYPE_OX8
result.award = 2
return result
}else{
result.type = pointNum
result.award = 1
return result
}
}
//对比手牌 返回true为第一个玩家赢,false为第二个玩家赢
module.exports.compare = function(result1,result2) {
if(result1.type > result2.type){
return true
}
if(result1.type == result2.type && result1.card.num > result2.card.num){
return true
}
if(result1.type == result2.type && result1.card.num == result2.card.num && result1.card.type > result2.card.type){
return true
}
return false
}
//换牌
module.exports.changeHandCard = function(handCard,cards,endCount,flag) {
var tmpResult = {}
tmpResult = module.exports.getType(handCard)
if(flag == true){
//换好牌
var value = 6
var tmpRand = Math.random()
var times = 5
if(tmpRand < 0.4){
value = 7
times = 10
}else if(tmpRand < 0.1){
value = 8
times = 20
}
if(tmpResult.type < value){
for(var z = 0;z < 3;z++){
cards[endCount++] = deepCopy(handCard[z])
}
var randTimes = 0
var dealFlag = false
do{
randTimes++
dealFlag = false
//洗牌
for(var i = 0;i < endCount;i++){
var tmpIndex = Math.floor(Math.random() * (endCount - 0.000001))
var tmpCard = cards[i]
cards[i] = cards[tmpIndex]
cards[tmpIndex] = tmpCard
}
//发牌
for(var i = 0; i < 3; i++){
handCard[i] = cards[endCount - 3 + i]
}
tmpResult = module.exports.getType(handCard)
if(tmpResult.type < value){
dealFlag = true
}
}while(dealFlag && randTimes < times)
}
}else{
//换差牌
var value = 5
var tmpRand = Math.random()
var times = 3
if(tmpRand < 0.4){
value = 4
times = 4
}else if(tmpRand < 0.1){
value = 3
times = 5
}
if(tmpResult.type > value){
for(var z = 0;z < 3;z++){
cards[endCount++] = deepCopy(handCard[z])
}
var randTimes = 0
var dealFlag = false
do{
randTimes++
dealFlag = false
//洗牌
for(var i = 0;i < endCount;i++){
var tmpIndex = Math.floor(Math.random() * (endCount - 0.000001))
var tmpCard = cards[i]
cards[i] = cards[tmpIndex]
cards[tmpIndex] = tmpCard
}
//发牌
for(var i = 0; i < 3; i++){
handCard[i] = cards[endCount - 3 + i]
}
tmpResult = module.exports.getType(handCard)
if(tmpResult.type > value){
dealFlag = true
}
}while(dealFlag && randTimes < times)
}
}
}
var deepCopy = function(source) {
var result={}
for (var key in source) {
result[key] = typeof source[key]==="object"? deepCopy(source[key]): source[key]
}
return result;
}
|
/**
* Created by zhualex on 16/3/7.
*/
$(function(){
initsearch();
function initsearch(){
$('.tagtype').each(function(){
if($(this).data().check==1){
var key=$(this).data().key;
var value=$(this).data().v;
$('#tag_'+key).show();
$('#tag_'+key).find('li').each(function(){
if($(this).children('a').data().v==value){
$(this).addClass('tag-hover');
}
})
}
})
}
//普通搜索聚合
$('.tagtype').click(function(){
var key=$(this).data().key;
$('.tag_value_ul').hide();
$('#tag_'+key).show();
})
})
|
var router = require('express').Router()
router.use(require('./cert_info'))
// api 추가 후 npm 재시작 필요!
module.exports = router
|
import _extends from "@babel/runtime/helpers/esm/extends";
import { GroupPanelProps } from "./group_panel_props";
export var GroupPanelLayoutProps = _extends({}, GroupPanelProps, {
groupsRenderData: []
});
|
import fetchMock from 'fetch-mock';
import App from "../App";
describe('repro', () => {
let app;
let response;
beforeEach(() => {
app = new App({});
spyOn(app, 'setState');
});
afterEach(() => {
fetchMock.restore();
});
describe('Without overriding config', () => {
describe('Setting status only in new Response init', () => {
beforeEach(() => {
response = new Response(null, {status: 500});
fetchMock.get('https://www.example.com/', response);
});
it('Should set state with expected error message', (done) => {
app.handleSubmit();
expectAsync(() =>
expect(app.setState).toBeCalledWith({error: response.statusText}),
done
);
});
});
describe('Setting status and statusText in new Response init', () => {
beforeEach(() => {
response = new Response(null, {status: 500, statusText: 'I failed'});
fetchMock.get('https://www.example.com/', response);
});
it('Should set state with expected error message', (done) => {
app.handleSubmit();
expectAsync(() =>
expect(app.setState).toBeCalledWith({error: response.statusText}),
done
);
});
});
describe('Using status as the response', () => {
beforeEach(() => {
response = 500;
fetchMock.get('https://www.example.com/', response);
});
it('Should set state with expected error message', (done) => {
app.handleSubmit();
expectAsync(() =>
expect(app.setState).toBeCalledWith({error: 'Internal Server Error'}),
done
);
});
});
describe('Using a response configuration object with only status set', () => {
beforeEach(() => {
response = {status: 500};
fetchMock.get('https://www.example.com/', response);
});
it('Should set state with expected error message', (done) => {
app.handleSubmit();
expectAsync(() =>
expect(app.setState).toBeCalledWith({error: 'Internal Server Error'}),
done
);
});
});
describe('Using a response configuration object with status and statusText set', () => {
beforeEach(() => {
response = {status: 500, statusText: 'I failed!'};
fetchMock.get('https://www.example.com/', response);
});
it('Should set state with result and response configuration on the body of the result response', (done) => {
app.handleSubmit();
expectAsync(() =>
expect(app.setState).toBeCalledWith({result: response}),
done
);
});
});
});
describe('Override config', () => {
beforeAll(() => {
fetchMock.config.Response = Response;
});
describe('Setting status only in new Response init', () => {
beforeEach(() => {
response = new Response(null, {status: 500});
fetchMock.get('https://www.example.com/', response);
});
it('Should set state with expected error message', (done) => {
app.handleSubmit();
expectAsync(() =>
expect(app.setState).toBeCalledWith({error: response.statusText}),
done
);
});
});
describe('Setting status and statusText in new Response init', () => {
beforeEach(() => {
response = new Response(null, {status: 500, statusText: 'I failed'});
fetchMock.get('https://www.example.com/', response);
});
it('Should set state with expected error message', (done) => {
app.handleSubmit();
expectAsync(() =>
expect(app.setState).toBeCalledWith({error: response.statusText}),
done
);
});
});
describe('Using status as the response', () => {
beforeEach(() => {
response = 500;
fetchMock.get('https://www.example.com/', response);
});
it('Should set state with expected error message', (done) => {
app.handleSubmit();
expectAsync(() =>
expect(app.setState).toBeCalledWith({error: 'Internal Server Error'}),
done
);
});
});
describe('Using a response configuration object with only status set', () => {
beforeEach(() => {
response = {status: 500};
fetchMock.get('https://www.example.com/', response);
});
it('Should set state with expected error message', (done) => {
app.handleSubmit();
expectAsync(() =>
expect(app.setState).toBeCalledWith({error: 'Internal Server Error'}),
done
);
});
});
describe('Using a response configuration object with status and statusText set', () => {
beforeEach(() => {
response = {status: 500, statusText: 'I failed!'};
fetchMock.get('https://www.example.com/', response);
});
it('Should set state with result and response configuration on the body of the result response', (done) => {
app.handleSubmit();
expectAsync(() =>
expect(app.setState).toBeCalledWith({result: response}),
done
);
});
});
});
});
const expectAsync = (expectation, done) => {
setTimeout(() => {
try{
expectation();
done();
} catch(e) {
done.fail(e);
}
})
};
|
import { reduce } from "../reduce/reduce"
/**
* Performs left-to-right function composition. The leftmost function may have
* any arity, the remaining functions must be unary.
*
* Functions can return a Promise, behaving like Promise.sequence.
*
* @name pipeP
* @tag Promise
* @signature (...fn) => (...input): any
* @see {@link pipe}
*
* @param {Function} first First function in chain
* @param {Function[]} rest Remaining bottom functions
* @param {Array} source First function arguments
*
* @returns {Promise<any>}
*
* @example
* const inc = input => input + 1
* const incP = input => Promise.resolve(input + 1)
*
* pipeP(incP, inc)(2).then(result => {
* // => result = 4
* })
*/
const pipeP = (first, ...rest) => (...input) =>
reduce(
(acc, item) => acc.then(result => item(result)),
Promise.resolve(first.apply(null, input))
)(rest)
export { pipeP }
|
class ActionSettings {
constructor() {
this.polling = true;
}
setPolling(status) {
this.polling = status;
}
}
export default ActionSettings;
|
import * as utils from '../src/utils';
describe('add', () => {
it('should work', () => {
expect(
utils.add(1, 1)
).toEqual(2);
});
});
|
//<img src={process.env.PUBLIC_URL + "/GitHub-Mark.png"} alt="lien_GitHub"/> is the way to LOAD images from public file (not src file) on the site
//mail-to is html method to send a mail box to user in the goal to contact you
function Footer(){
return(
<footer id="footer" className="text-center text-white text-lg-start">
<h2 className="text-center pb-2 pt-5 w-75 mx-auto">Pour me contacter :<hr className="hr w-100"></hr></h2>
<div className="blabla text-center w-75 mx-auto">
<h5 className="text-uppercase pb-2">Pour finir :</h5>
<p>Dans le cadre de ma formation à l'Afpa de Rouen, je suis à la recherche
d'un stage non rémunéré pour 9 semaines à partir du 16 août 2021.
Si mon profil vous intéresse, vous pouvez directement me contacter
en cliquant sur le lien ci-joint : <a className="mailto" href="mailto:julien.coart@gmail.com">julien.coart@gmail.com.</a>
</p>
</div>
<div className="container_footer d-flex justify-content-center w-50 mx-auto p-4">
<div className="row">
<div className="col-lg-6 col-md-6 mb-4 mx-auto">
<ul className="list-unstyled mb-5">
<li>
<a href="https://www.linkedin.com/in/julien-coart-86142a147/" target="_blank" rel=" noreferrer noopener">
<img className="logofooter" src={process.env.PUBLIC_URL + "/linkedinlogo.png"} alt="lien_linkedin"/>
</a>
</li>
</ul>
</div>
<div className="col-lg-6 col-md-6 mx-auto">
<ul className="list-unstyled">
<li>
<a href="https://github.com/JulienDev76-75" target="_blank" rel=" noreferrer noopener">
<img className="logofooter" src={process.env.PUBLIC_URL + "/github.png"} alt="lien_GitHub"/>
</a>
</li>
</ul>
</div>
</div>
</div>
<div className="copyright text-center text-white mt-5">© 2021 Copyright: Julien Coart.<br />Projet réalisé avec la technologie React.</div>
</footer>
);
}
export default Footer;
{/* <div id="music" className="spotify w-100"><iframe src="https:open.spotify.com/embed/playlist/1PKYiQbbX3Fak5c9SiYpFQ" allowTransparency="true" allow="encrypted-media"></iframe></div> */}
|
import React, { Component } from 'react';
import { Button } from 'react-onsenui';
import Webcam from 'react-webcam';
import DefaultPage from "./Default";
class TakePicture extends Component {
constructor (props) {
super(props)
this.state = {
enableVideo: false,
imageSrc: null
}
this.buttonStyle = {
marginTop: '30px',
padding: '25px',
fontSize: '18px'
}
}
setRef = (webcam) => {
this.webcam = webcam;
}
capture = () => {
const imageSrc = this.webcam.getScreenshot();
this.setState({imageSrc: imageSrc});
};
renderWebcam () {
if (this.state.enableVideo) {
return <div>
<Webcam
audio={false}
height={350}
ref={this.setRef}
screenshotFormat="image/jpeg"
width='100%'/>
<img alt="capture" width='100%' height='350' src={this.state.imageSrc}/>
<Button style={{margin: '10px'}} onClick={this.capture}>Capture photo</Button>
<Button style={{margin: '10px'}} onClick={() => {
this.setState({enableVideo: false})
}}>Disable Webcam</Button>
</div>
} else {
return <p style={{textAlign: 'center'}}>
<Button modifier='large' style={this.buttonStyle} onClick={() => {
this.setState({enableVideo: true})
}}>Enable Webcam</Button>
</p>
}
}
render () {
return (
<section style={{margin: '16px'}}>
{this.renderWebcam()}
</section>
)
}
}
export default DefaultPage(TakePicture);
|
import model from './model';
import isEmpty from '../../utility/isEmpty';
const startGame = async ({ body }, res) => {
const { name = 'anonymous' } = body;
let response = {
success: false,
code: 400,
data: {}
};
try {
const { success, code, result } = await model.getInitialGame({ name });
if (success) {
response = {
success,
code,
data: !isEmpty(result) ? result : {}
};
}
return res.status(response.code).json(response);
} catch (error) {
response.result = error;
return res.status(response.code).json(response);
}
};
const callCard = async ({ body }, res) => {
let response = {
success: false,
code: 400,
data: {}
};
const { userId, bets } = body;
try {
const { success, code, result } = await model.callNewRound({ userId, bets });
if (success) {
response = {
success,
code,
data: !isEmpty(result) ? result : {}
};
}
return res.status(response.code).json(response);
} catch (error) {
return res.status(response.code).json(response);
}
};
const hitCard = async ({ body }, res) => {
let response = {
success: false,
code: 400,
data: {}
};
const { userId } = body;
try {
const { success, code, result } = await model.callHitCard({ userId });
if (success) {
response = {
success,
code,
data: !isEmpty(result) ? result : {}
};
}
return res.status(response.code).json(response);
} catch (error) {
return res.status(response.code).json(response);
}
};
const standCard = async ({ body }, res) => {
let response = {
success: false,
code: 400,
data: {}
};
const { userId, bets } = body;
try {
const { success, code, result } = await model.standCard({ userId, bets });
if (success) {
response = {
success,
code,
data: !isEmpty(result) ? result : {}
};
}
return res.status(response.code).json(response);
} catch (error) {
return res.status(response.code).json(response);
}
};
const scoreTable = async (req, res) => {
let response = {
success: false,
code: 400,
data: {}
};
try {
const { success, code, result } = await model.getScoreTable();
if (success) {
response = {
success,
code,
data: !isEmpty(result) ? result : {}
};
}
return res.status(response.code).json(response);
} catch (error) {
return res.status(response.code).json(response);
}
};
export default { startGame, callCard, hitCard, standCard, scoreTable };
|
define(function (require) {
let Vue = require('vue');
let Store = require('store/appstore')
let registerNodeType = require('litegraph/lg_nodefactory');
Vue.component('Graph', {
data: function () {
return {
nodeTypes: Store.state.nodeTypes
}
},
mounted: function() {
canvas = new LGraphCanvas(this.$refs.graphCanvas, Store.getGraph(), {autoresize: true});
canvas.show_info = false;
// Put hooks on pos (to set dirty flag)
Object.defineProperty( canvas, "node_dragged", {
set: function(v) {
this._node_dragged = v;
Store.setDirty(true);
},
get: function() { return this._node_dragged; },
enumerable: true
});
// Overload LGraphCanvas because the heigh is not exacty equals!
// When the canvas grow, the di grow too :(
LGraphCanvas.prototype.resize = function(width, height)
{
if(!width && !height)
{
var parent = this.canvas.parentNode;
width = parent.offsetWidth;
height = parent.offsetHeight;
}
if(this.canvas.width > width && Math.abs(this.canvas.height - height) < 10)
return;
this.canvas.width = width;
this.canvas.height = height;
this.bgcanvas.width = this.canvas.width;
this.bgcanvas.height = this.canvas.height;
this.setDirty(true,true);
}
canvas.resize();
canvas.getMenuOptions = function(){ return [ { content:"Audio node", has_submenu: true, callback: LGraphCanvas.onMenuAdd } ] };
window.addEventListener("resize", function() {
canvas.resize(10,10);
canvas.resize();
} );
},
watch: {
nodeTypes: function(nodeTypes){
nodeTypes.forEach(nt => registerNodeType(nt,
Store.sendCommand.bind(Store),
() => Store.setDirty(true)
));
}
},
template: `
<div class= "flex-grow-1" style='height:100%;background-color: #8b0000;overflow:hidden '>
<canvas style="" ref="graphCanvas"></canvas>
</div>`,
});
});
|
/**
* Card Masonary
*/
import React, { Component } from 'react';
import {
Card,
CardImg,
CardTitle,
CardText,
CardColumns,
CardSubtitle,
CardBody,
CardImgOverlay
} from 'reactstrap';
import Button from '@material-ui/core/Button';
// page title bar
import PageTitleBar from 'Components/PageTitleBar/PageTitleBar';
// intl messages
import IntlMessages from 'Util/IntlMessages';
export default class CardsMasonry extends Component {
render() {
return (
<div className="cardsmasonry-wrapper">
<PageTitleBar title={<IntlMessages id="sidebar.cardsMasonry" />} match={this.props.match} />
<CardColumns>
<Card inverse color="danger">
<CardBody>
<CardTitle>Card title</CardTitle>
<CardSubtitle>Card subtitle</CardSubtitle>
<CardText>This card has supporting text below as a natural lead-in to additional content.</CardText>
<Button variant="raised" color="default">Button</Button>
</CardBody>
</Card>
<Card>
<CardImg top width="100%" src={require('Assets/img/gallery-7.jpg')} className="img-fluid" alt="Card image cap" />
<CardBody>
<CardTitle>Card title</CardTitle>
<CardSubtitle>Card subtitle</CardSubtitle>
<CardText>This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</CardText>
<Button variant="raised" color="primary" className="text-white">Button</Button>
</CardBody>
</Card>
<Card inverse color="success">
<CardBody>
<CardTitle>Card title</CardTitle>
<CardSubtitle>Card subtitle</CardSubtitle>
<CardText>This card has supporting text below as a natural lead-in to additional content.</CardText>
<Button variant="raised" color="default">Button</Button>
</CardBody>
</Card>
<Card>
<CardImg width="100%" src={require('Assets/img/gallery-10.jpg')} className="img-fluid" alt="Card image cap" />
<CardImgOverlay className="gradient-warning">
<CardTitle>Card Title</CardTitle>
<CardText>This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</CardText>
<CardText>
<small>Last updated 3 mins ago</small>
</CardText>
</CardImgOverlay>
</Card>
<Card>
<CardImg top width="100%" src={require('Assets/img/gallery-8.jpg')} className="img-fluid" alt="Card image cap" />
</Card>
<Card body style={{ borderColor: '#333' }}>
<CardTitle>Special Title Treatment</CardTitle>
<CardText>With supporting text below as a natural lead-in to additional content.</CardText>
<Button variant="raised" className="btn-dark text-white">Button</Button>
</Card>
<Card body inverse color="primary">
<CardTitle>Special Title Treatment</CardTitle>
<CardText>With supporting text below as a natural lead-in to additional content.</CardText>
<Button variant="raised" color="default">Button</Button>
</Card>
<Card>
<CardBody>
<CardTitle>Card title</CardTitle>
<CardSubtitle>Card subtitle</CardSubtitle>
<CardText>This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</CardText>
<Button variant="raised" color="primary" className="text-white">Button</Button>
</CardBody>
<CardImg bottom width="100%" src={require('Assets/img/gallery-9.jpg')} className="img-fluid" alt="Card image cap" />
</Card>
</CardColumns>
</div>
);
}
}
|
// @flow
import * as React from 'react';
import { View, ScrollView } from 'react-native';
import { Translation } from '@kiwicom/mobile-localization';
import { TextButton, StyleSheet } from '@kiwicom/mobile-shared';
import { defaultTokens } from '@kiwicom/mobile-orbit';
import { getCard } from '@kiwicom/rnmodules';
import OrderSummary from '../insuranceOverviewScene/orderSummary/OrderSummary';
import PaymentFormTitle from './PaymentFormTitle';
import CardOptions from './CardOptions';
import PaymentForm from './PaymentForm';
import InsurancePaymentContext from './InsurancePaymentContext';
const noop = () => {};
type CardType = {|
+cardholder: string,
+expiryMonth: string,
+expiryYear: string,
+number: string,
|};
type State = {|
card: ?CardType,
active: 'SAVED_CARD' | 'ANOTHER_CARD',
|};
export default class PaymentScene extends React.Component<{||}, State> {
state = {
card: null,
active: 'ANOTHER_CARD',
};
async componentDidMount() {
const card = await getCard();
if (card != null) {
this.setState({ card, active: 'SAVED_CARD' });
}
}
onPressPaymentButton = () => {
console.warn('TODO');
};
setActiveCard = (pressed: 'SAVED_CARD' | 'ANOTHER_CARD') => {
if (this.state.active !== pressed) {
this.setState({
active: pressed,
});
}
};
render() {
const isAnotherCardActive = this.state.active === 'ANOTHER_CARD';
const cardDigits =
this.state.card != null ? this.state.card.number.slice(-4) : '';
return (
<React.Fragment>
<InsurancePaymentContext.Provider>
<ScrollView>
<View style={styles.container}>
<View style={styles.formRow}>
<PaymentFormTitle />
</View>
{this.state.card != null && (
<CardOptions
active={this.state.active}
setActiveCard={this.setActiveCard}
onSavedCardSecurityCodeChange={noop}
cardDigits={cardDigits}
/>
)}
{isAnotherCardActive && <PaymentForm />}
</View>
<View style={[styles.container, styles.buttonContainer]}>
<TextButton
title={
<Translation id="mmb.trip_services.insurance.payment.pay_now" />
}
onPress={this.onPressPaymentButton}
// TODO
disabled={true}
/>
</View>
</ScrollView>
</InsurancePaymentContext.Provider>
<OrderSummary />
</React.Fragment>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: defaultTokens.paletteWhite,
padding: 10,
},
formRow: {
paddingTop: 15,
paddingBottom: 5,
},
buttonContainer: {
marginTop: 10,
},
});
|
import * as actions from '../lib/actions'
import {showModal, SHOW_MODAL} from '../lib/actions'
describe('provided actions', () => {
it('can access via restack-core/actions', () => {
expect(actions).not.toBeNull();
expect(actions.SHOW_MODAL).toBe("SHOW_MODAL")
})
it('can access individual action / action creator via import', () => {
expect(typeof showModal).toBe('function')
expect(SHOW_MODAL).toBe("SHOW_MODAL")
})
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.