text stringlengths 7 3.69M |
|---|
var searchData=
[
['filehandling_2ecpp_61',['fileHandling.cpp',['../file_handling_8cpp.html',1,'']]],
['filehandling_2eh_62',['fileHandling.h',['../file_handling_8h.html',1,'']]],
['flip_2ecpp_63',['flip.cpp',['../flip_8cpp.html',1,'']]],
['flip_2eh_64',['flip.h',['../flip_8h.html',1,'']]]
];
|
import React from "react";
class Header extends React.Component {
render() {
return (
<>
<h1 className="header text-xl bg-gradient-dark pb-8 pt-5 pt-md-8">
Header Dashboard
</h1>
</>
);
}
}
export default Header;
|
document.addEventListener("DOMContentLoaded",function (){
new WOW().init();
var set = document.getElementsByClassName("set")
set[0].classList.add("current_set");
set[2].classList.add("current_set");
},false) |
const fillTable = () => {
const tasks = JSON.parse(window.localStorage.getItem('tasks'));
for (i = 0; i < tasks.length; i++) {
const task = tasks[i];
const taskNumberFunc = task.taskNumber;
const taskStatus = document.createTextNode(task.taskStatus);
const taskText = document.createTextNode(task.taskText);
const taskTime = document.createTextNode(task.taskTime);
const newStatus = document.createElement('td');
const newTask = document.createElement('td');
const newTimeStamp = document.createElement('td');
const newDeleteButton = document.createElement('td');
const row = document.createElement("tr");
newStatus.appendChild(taskStatus);
newTask.appendChild(taskText);
newTimeStamp.appendChild(taskTime);
newDeleteButton.innerHTML = '<button class="button is-danger is-outlined is-small" onclick = "deleteTask(' + taskNumberFunc + ')"><span class="icon"></span></button>';
row.appendChild(newStatus);
row.appendChild(newTask);
row.appendChild(newTimeStamp);
row.appendChild(newDeleteButton);
row.setAttribute('id', taskNumberFunc);
document.getElementById("todotablebody").appendChild(row);
};
}
const deleteTask = (id) => {
// if (window.confirm("Are you sure?") === true) {
document.getElementById(id).remove();
var tasks = JSON.parse(window.localStorage.getItem('tasks'));
for (i = 0; i < tasks.length; i++) {
const task = tasks[i];
if (task.taskNumber === id) {
tasks.splice(i, 1);
window.localStorage.setItem('tasks', JSON.stringify(tasks));
break;
};
};
// }
}
const buttonScript = () => {
window.localStorage.clear();
window.localStorage.setItem('createdTasks', 0);
window.localStorage.removeItem('tasks');
}
const twoNumberDate = (date) => {
const string = new String(date);
if (string.length === 1) {
return '0' + date;
}
else {
return date;
}
}
const appendTextnode = (id, node) => {
let textnode = document.createTextNode(node);
document.getElementById(id).appendChild(textnode);
}
const convertMonthToName = (month) => {
if (month === 1) {
return "January";
} else if (month === 2) {
return "February";
} else if (month === 3) {
return "March";
} else if (month === 4) {
return "April";
} else if (month === 5) {
return "May";
} else if (month === 6) {
return "June";
} else if (month === 7) {
return "July";
} else if (month === 8) {
return "August";
} else if (month === 9) {
return "September";
} else if (month === 10) {
return "October";
} else if (month === 11) {
return "November";
} else if (month === 12) {
return "December";
} else {
return "error1"
}
}
const timeNow = () => {
const today = new Date();
const date = twoNumberDate(today.getDate()) + '-' + convertMonthToName((today.getMonth() + 1)) + '-' + today.getFullYear();
const time = twoNumberDate(today.getHours()) + ":" + twoNumberDate(today.getMinutes()) + ":" + twoNumberDate(today.getSeconds());
const dateTime = time + ' ' + date;
return dateTime;
}
const addTask = () => {
if (inputBox.value !== "") {
const inputBox = document.getElementById("inputBox");
const taskText = document.createTextNode(inputBox.value);
const row = document.createElement("tr");
const newStatus = document.createElement('td');
const newTask = document.createElement("td");
const newTimeStamp = document.createElement("td");
const newDeleteButton = document.createElement("td");
var text = window.localStorage.getItem('createdTasks');
var createdTasks = parseInt(text, 10);
createdTasks++;
window.localStorage.setItem('createdTasks', createdTasks);
const statusValue = document.createTextNode('Not Completed');
newStatus.appendChild(statusValue);
newDeleteButton.innerHTML = '<button class="button is-danger is-outlined is-small" onclick = "deleteTask(' + createdTasks + ')"><span class="icon"></span></button>';
newTask.appendChild(taskText);
const timeStampValue = document.createTextNode(timeNow());
newTimeStamp.appendChild(timeStampValue);
row.appendChild(newStatus);
row.appendChild(newTask);
row.appendChild(newTimeStamp);
row.appendChild(newDeleteButton);
row.setAttribute('id', createdTasks);
document.getElementById("todotablebody").appendChild(row);
const task = {
'taskNumber': createdTasks,
'taskStatus': 'Not Completed',
'taskText': inputBox.value,
'taskTime': timeNow()
};
addTaskToLocalStorage(task);
inputBox.value = "";
}
}
const addTaskToLocalStorage = (task) => {
var tasks = JSON.parse(window.localStorage.getItem('tasks'));
if (tasks === null) {
var tasks = [];
};
tasks.push(task);
window.localStorage.setItem('tasks', JSON.stringify(tasks));
//window.alert(tasks);
}
|
import React from 'react';
class PokemonComparator extends React.Component {
constructor(props) {
super(props);
this.state = {
currentPokemon: 0,
pokemonData: [],
isLoaded: false,
isError: false,
};
}
// Get pokemon stat
getPokemonStats() {
const firstPokemonStats = this.props.data[0].stats;
const secondPokemonStats = this.props.data[1].stats;
for (let i = 0; i < firstPokemonStats.length; i++) {
getRowStat(i)
}
function getRowStat(i) {
// console.log(secondPokemonStats[i])
}
let data = this.props.data;
return firstPokemonStats.map((statItem, index) => (
<li key={index}>
<span className="stat_name">{statItem.stat.name}</span>
<div className="stat_data__wrapper">
{/* <span className="stat_data_compare">+5%</span> */}
<span className="stat_data active">{statItem.base_stat}</span>
<span className="stat_data active">{statItem.base_stat}</span>
{/* <span className="stat_data_compare">-3%</span> */}
</div>
</li>
));
}
compareStats() {
const firstPokemonStats = this.props.data[0].stats;
const secondPokemonStats = this.props.data[1].stats;
}
render() {
const { isLoaded } = this.state;
return (
<div className="pokemon_card__stats">
{this.getPokemonStats()}
</div>
);
}
}
export default PokemonComparator;
|
'use strict'
const assertPromise = require('../../dd-trace/test/plugins/promise')
assertPromise('promise-js')
|
const expect = chai.expect
import Vue from 'vue'
import Popover from "../src/popover/Popover"
import Button from "../src/button/Button"
Vue.config.productionTip = false
Vue.config.devtools = false
describe('Popover', () => {
it('存在.', () => {
expect(Popover).to.be.ok
})
it('可以设置position', (done) => {
Vue.component('s-popover', Popover)
Vue.component('s-button', Button)
const div = document.createElement('div')
document.body.appendChild(div)
div.innerHTML = `
<s-popover ref="pop">
<template v-slot:content>
弹出内容
</template>
<template v-slot:default>
<s-button>点我</s-button>
</template>
</s-popover>
`
const vm = new Vue({
el: div
})
const popover = vm.$refs.pop
vm.$el.querySelector('button').click()
vm.$nextTick(() => {
expect(vm.$refs.pop.$refs.contentWrapper.classList.contains('position-top')).to.eq(true)
done()
})
})
it('可以设置trigger', (done) => {
Vue.component('s-popover', Popover)
Vue.component('s-button', Button)
const div = document.createElement('div')
document.body.appendChild(div)
div.innerHTML = `
<s-popover ref="pop" trigger="hover">
<template v-slot:content>
弹出内容
</template>
<template v-slot:default>
<s-button>点我</s-button>
</template>
</s-popover>
`
const vm = new Vue({
el: div
})
const popover = vm.$refs.pop
const event = new Event('mouseenter')
popover.$refs.popover.dispatchEvent(event)
popover.$nextTick(() => {
expect(popover.$refs.contentWrapper).to.exist
done()
})
})
})
|
/* global describe setTimeout it */
/* eslint-disable no-unused-vars */
const assert = require('assert');
const IntersectionRenderer = require('../src/IntersectionRenderer.js');
const TrafficLight = require('../src/TrafficLight');
const TrafficLightRenderer = require('../src/TrafficLightRenderer');
describe('IntersectionRenderer', () => {
const canvasMock = {
getContext: function(){
return {
clearRect: function(){}
}
}
};
describe('#constructor', () => {
it('should throw an exception with the wrong lights', () => {
let wasExceptionThrown = false;
const wrongLights = [new TrafficLight(), new TrafficLight(),new TrafficLight(),
{} // wrong object passed
];
try {
let intersection = new IntersectionRenderer(canvasMock, wrongLights);
} catch (ex) {
wasExceptionThrown = true;
}
assert.ok(wasExceptionThrown);
});
it('should throw an exception with the wrong renderer for traffic lights', () => {
let wasExceptionThrown = false;
const lights = [new TrafficLight(), new TrafficLight(),new TrafficLight(), new TrafficLight()];
const wrongRenderer = {}; // wrong object passed
try {
let intersection = new IntersectionRenderer(canvasMock, lights, wrongRenderer);
} catch (ex) {
wasExceptionThrown = true;
}
assert.ok(wasExceptionThrown);
});
it('should throw an exception when there are no 4 lights', () => {
let wasExceptionThrown = false;
// Missing one light
const wrongLights = [new TrafficLight(), new TrafficLight(), new TrafficLight()];
try {
let intersection = new IntersectionRenderer(canvasMock, wrongLights);
} catch (ex) {
wasExceptionThrown = true;
}
assert.ok(wasExceptionThrown);
});
});
describe('#render', () => {
it('should call "render" method on all lights', () => {
let counter = 0;
let called = [false, false, false, false];
let origRender = TrafficLightRenderer.prototype.render;
// We mock the function to count the number of times called
TrafficLightRenderer.prototype.render = function() {
called[counter++] = true;
};
let renderer = new TrafficLightRenderer();
const lights = [new TrafficLight(), new TrafficLight(), new TrafficLight(), new TrafficLight()];
const intersection = new IntersectionRenderer(canvasMock, lights, renderer);
intersection.render();
const wereAllLightsCalled = called.every(item => item);
assert.ok(wereAllLightsCalled);
TrafficLightRenderer.prototype.render = origRender;
});
});
});
|
const colors = {
primary: '#FF6C00',
secondary: '#D45A00',
greyDark: '#999',
grey:'#CCC',
greyLigth: '#E0E7EE',
ligth: '#E7E7E7',
warning: '#F30',
alert: '#A43287',
dark: '#212121',
darkest: '#000',
}
const breakpoints = {
smallest: 320,
small: 768,
medium: 900,
large: 1248
}
const container = {
small: 656,
medium: 760,
large: 1104
}
const typography = {
body: '"Helvetica", sans-serif',
base: '87.5%',
baseDesktop: '100%',
}
export default { colors, breakpoints, typography, container } |
const BaseController = require("./base-controller");
const ApiWrapper = require("../services/api-wrapper");
const ValidationParser = require("../services/validation-parser");
let apiWrapper = new ApiWrapper();
module.exports = class P45InstructionController extends BaseController {
async postNewInstruction(ctx) {
let employerId = ctx.params.employerId;
let employeeId = ctx.params.employeeId;
let body = ctx.request.body;
let apiRoute = `Employer/${employerId}/Employee/${employeeId}/PayInstructions`;
let response = await apiWrapper.post(apiRoute, { P45PayInstruction: body });
if (ValidationParser.containsErrors(response)) {
return;
}
await ctx.redirect(`/employer/${employerId}/employee/${employeeId}?status=P45 instruction saved&statusType=success#p45-instruction`);
}
async postExistingInstruction(ctx) {
let employerId = ctx.params.employerId;
let employeeId = ctx.params.employeeId;
let id = ctx.params.id;
let body = ctx.request.body;
let apiRoute = `Employer/${employerId}/Employee/${employeeId}/PayInstruction/${id}`;
let response = await apiWrapper.put(apiRoute, { P45PayInstruction: body });
if (ValidationParser.containsErrors(response)) {
console.log(ValidationParser.extractErrors(response));
return;
}
await ctx.redirect(`/employer/${employerId}/employee/${employeeId}?status=P45 instruction saved&statusType=success#p45-instruction`);
}
}; |
import React from 'react';
import styled from 'styled-components';
const Container = styled.div`
display: flex;
justify-content: center;
`;
const TurnElement = styled.div`
padding: 8px 16px;
font-size: 1.2rem;
font-weight: bold;
border-bottom: ${({isTurn}) => (isTurn ? '3px solid black' : '0')};
`;
const Turn = ({turns, turn}) => {
return (
<Container>
{turns.map(item => {
const isTurn = item === turn;
return (
<TurnElement key={item} isTurn={isTurn}>
{item}
</TurnElement>
);
})}
</Container>
);
};
export default Turn; |
import React from 'react'
import './StoryReel.css'
import Story from './Story'
function StoryReel() {
return (
<div className="storyReel">
<Story image="https://upload.wikimedia.org/wikipedia/commons/e/ee/Anirban_Bhattacharjee.jpg"
profileSrc="https://i2.cinestaan.com/image-bank/1500-1500/150001-151000/150881.jpg"
title="Anirban Bhatta"/>
</div>
)
}
export default StoryReel
|
let names = document.getElementById('name');
let email = document.getElementById('email');
let show = document.getElementsByTagName('span');
let input = document.getElementsByTagName('input');
names.onkeydown = function () {
const regExp = /^[a-zA-Z0-9]{2,10}$/;
if (regExp.test(names.value)) {
show[0].innerText = "Name is Valid";
show[0].style.color = "#00ff00";
input[0].style.boxShadow = "0px 0px 4px #00ff00";
}
else {
show[0].innerText = "Name is not Valid";
show[0].style.color = "#ff0000";
input[0].style.boxShadow = "0px 0px 4px #ff0000";
}
}
email.onkeydown = function () {
const regExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (regExp.test(email.value)) {
show[1].innerText = "Email is Valid";
show[1].style.color = "#00ff00";
input[1].style.boxShadow = "0px 0px 4px #00ff00";
}
else {
show[1].innerText = "Email is not Valid";
show[1].style.color = "#ff0000";
input[1].style.boxShadow = "0px 0px 4px #ff0000";
}
}
const form = document.querySelector('form');
const tbody = document.querySelector('tbody');
const table = document.querySelector('table');
function addingUsers(e) {
e.preventDefault();
tbody.innerHTML += `
<tr>
<td>${names.value}</td>
<td>${email.value}</td>
<td><button class="delBtn">X</button></td>
</tr>
`;
}
function deletingUsers(e) {
if (!e.target.classList.contains("delBtn")) {
return;
}
let btn = e.target;
btn.closest("tr").remove();
}
form.addEventListener('submit', addingUsers);
table.addEventListener('click', deletingUsers); |
import React from 'react';
import ReactDOM from 'react-dom';
import { expect } from 'chai';
import { StatusTable } from '../../src/components/status-table';
import makeDummyRow from '../../src/dummy/factory-paperboy-rows';
import * as action from '../../src/action-creators';
import {
Simulate,
renderIntoDocument,
scryRenderedDOMComponentsWithTag,
findRenderedDOMComponentWithTag
} from 'react-addons-test-utils';
describe('Component: StatusTable', () => {
let getCalledAction = {};
let dispatched = [];
for (let prop in action) {
if (typeof action[prop] === 'function') {
getCalledAction[prop] = (data) => dispatched.push(action[prop](data).type);
}
}
beforeEach(() => dispatched = []);
it(`수정 button => dispatch 'OPEN_MODAL_MODIFY_DRAFT'`, () => {
let head = [];
let rows = [];
const countRows = 10;
for (let i = 0;i < countRows; i++) {
head.push(i);
rows.push(makeDummyRow());
}
const props = { head, rows };
const component = renderIntoDocument(<StatusTable {...props} {...getCalledAction} />);
const button = scryRenderedDOMComponentsWithTag(component, 'button')[0];
Simulate.click(button);
expect(dispatched.pop()).to.equal('OPEN_MODAL_MODIFY_DRAFT');
});
}); |
import React from 'react';
import propTypes from 'prop-types';
import classNames from 'classnames';
import * as styles from './index.module.scss';
const Row = ({ id, children, className, wrap, padded, noMargin}) => (
<div className={classNames(styles.row, className, {[styles.row__padded]: padded}, {[styles.row__no_margin]: noMargin}, {[styles.row__wrap]: wrap})} id={id}>
{children}
</div>
)
Row.propTypes = {
id: propTypes.string,
children: propTypes.node.isRequired,
padded: propTypes.bool,
noMargin: propTypes.bool,
}
export default Row |
const { app, BrowserWindow } = require('electron');
const { join } = require('path');
const { format } = require('url');
let win;
const createWindow = () => {
win = new BrowserWindow({ width: 1200, height: 800 });
win.loadURL(format({
pathname: join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
win.on('closed', () => win = null);
};
// start
app.on('ready', createWindow);
// close
app.on('windows-all-closed', () => process.platform !== 'darwin' && app.quit());
// some mac shit
app.on('activate', () => win === null && createWindow());
|
import React from "react";
import { Col, Row, Alert } from "antd";
const Error = ({ description }) => {
return (
<Row align="middle" justify="center">
<Col>
<Alert
message="Error fetching recipes"
description={description}
type="error"
/>
</Col>
</Row>
);
};
export default Error;
|
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var app = express();
var parseServer = new ParseServer({
databaseURI: 'mongodb://localhost:27017/dev',
appId: 'CHECKERS_2',
masterKey: 'MASTER_KEY', // Keep this key secret!
serverURL: 'http://localhost:1337/parse',
liveQuery: {
classNames: ['Game']
}
});
app.use('/parse', parseServer);
app.post('/parse/classes/Game', function (req, res, next) {
console.log('Creating a game ...');
next(); // pass control to the next handler
});
var httpServer = require('http').createServer(app);
httpServer.listen(1337, function () {
console.log('parse-server-example running on port 1337.');
});
var parseLiveQueryServer = ParseServer.createLiveQueryServer(httpServer); |
define([
'common/views/visualisations/completion_rate',
'client/views/visualisations/percentage-graph',
'lodash'
], function (View, GraphView, _) {
return View.extend({
views: function () {
var views = View.prototype.views.apply(this, arguments);
return _.extend(views, {
'.volumetrics-completion': {
view: GraphView,
options: {
valueAttr: this.valueAttr
}
}
});
}
});
});
|
describe('LoginCtrl : ', function () {
var controller;
var execFacebookLogin;
var mockAccount;
var $scope = {};
beforeEach(module('app.LoginCtrl', function ($provide) {
mockAccount = testApi.mockAccount($provide);
$provide.value('facebook', {
login: function (callback) {
execFacebookLogin = callback;
}
});
$provide.value('$state', {
go: function () {
}
});
}));
beforeEach(function () {
inject(function ($controller) {
controller = $controller('LoginCtrl', {$scope: $scope});
})
});
describe('scope.loginWithFacebook', function () {
it('Reacts to successful facebook login.', inject(function ($state) {
//ARRANGE
var stateStub = sinon.stub($state);
// ACT
$scope.loginWithFacebook();
execFacebookLogin();
// ASSERT
expect(stateStub.go.calledWith('home')).toEqual(true);
}));
});
describe('scope.login', function () {
it('Reacts to successful login.', inject(function ($state, $q, $rootScope) {
//ARRANGE
var stateStub = sinon.stub($state);
// ACT
$scope.login('email', 'password');
mockAccount.login.resolve();
// ASSERT
expect(stateStub.go.calledWith('home')).toEqual(true);
}));
it('Reacts to failed login.', inject(function ($state, $timeout) {
// ACT
$scope.login();
mockAccount.login.reject({
message: 'account failed to login'
});
$timeout.flush();
// ASSERT
expect($scope.error).toEqual('account failed to login');
}));
});
}); |
var sys = require('pex-sys');
var glu = require('pex-glu');
var geom = require('pex-geom');
var color = require('pex-color');
var Window = sys.Window;
var Color = color.Color;
var OrthographicCamera = glu.OrthographicCamera;
var Vec2 = geom.Vec2;
var Vec3 = geom.Vec3;
var typo = require('pex-typo');
var TextBox = typo.TextBox;
Window.create({
settings: {
width: 1280,
height: 800
},
init: function() {
var textboxPresets = this.textboxPresets = [];
textboxPresets['default'] = {
maxLines: 1,
background: Color.DarkGrey
};
textboxPresets['defined-width'] = {
width: 600,
maxLines: 1,
background: Color.DarkGrey
};
textboxPresets['defined-width-limit'] = {
width: 600,
overflow: TextBox.Overflow.Limit,
maxLines: 1,
background: Color.DarkGrey
};
textboxPresets['defined-width-and-height'] = {
width: 600,
height: 100,
maxLines: 3,
background: Color.DarkGrey
};
textboxPresets['defined-width-and-height-scale-text'] = {
width: 1220,
height: 180,
overflow: TextBox.Overflow.ScaleText,
background: Color.DarkGrey,
fontSize: 180
};
textboxPresets['defined-width-break'] = {
width: 580,
lineHeight: 1.25,
overflow: TextBox.Overflow.BreakText,
background: Color.DarkGrey,
marginTop: 10,
marginLeft: 10,
marginRight: 10,
fontSize: 18
};
this.textboxes = [];
for(textboxPresetName in textboxPresets) {
textboxPreset = textboxPresets[textboxPresetName];
var textbox = new TextBox("Lorem ipsum", "Verdana", textboxPreset.fontSize ? textboxPreset.fontSize : 20, textboxPreset);
this.textboxes[textboxPresetName] = textbox;
}
// Layout
var y = 70;
this.textboxes['default'].setPosition(20, y); y += this.textboxes['default'].height + 10;
this.textboxes['defined-width'].setPosition(20, y); y += this.textboxes['defined-width'].height + 10;
this.textboxes['defined-width-limit'].setPosition(20, y); y += this.textboxes['defined-width-limit'].height + 10;
this.textboxes['defined-width-and-height'].setPosition(20, y); y += this.textboxes['defined-width-and-height'].height + 10;
this.textboxes['defined-width-and-height-scale-text'].setPosition(20, y); y += this.textboxes['defined-width-and-height-scale-text'].height + 10;
this.textboxes['defined-width-break'].setPosition(20, y);
// Info text
this.desc = new TextBox("Type your text and watch different behaviors. Press `CMD + d` to toggle debug info drawing.", 'Arial', 14, { color: Color.LightGrey });
this.desc.setPosition(20, 20);
// Camera
this.camera = new OrthographicCamera(0,0, this.width, this.height, 0.1, 100, null, Vec3.create(0, 0, 0), Vec3.create(0, 1, 0));
// Keybinding
this.on('keyDown', function(e) {
if(e.keyCode == 51) { // BACKSPACE to clear
for(textboxPresetName in this.textboxes) {
var text = this.textboxes[textboxPresetName].text;
if(text.length > 0) {
text = text.substr(0, text.length-1);
this.textboxes[textboxPresetName].update( text );
}
}
} else if(e.cmd && e.str == 'd') { // CMD + d to toggle debug info drawing
for(textboxPresetName in this.textboxes) {
this.textboxes[textboxPresetName].options.drawDebug = !this.textboxes[textboxPresetName].options.drawDebug;
this.textboxes[textboxPresetName].update( this.textboxes[textboxPresetName].text );
}
} else {
for(textboxPresetName in this.textboxes) {
this.textboxes[textboxPresetName].text += e.str;
this.textboxes[textboxPresetName].update( this.textboxes[textboxPresetName].text );
}
}
}.bind(this));
},
draw: function() {
glu.viewport(0, 0, this.width, this.height);
glu.enableAlphaBlending();
glu.clearColorAndDepth(Color.Black);
this.desc.draw(this.camera);
for(textboxPresetName in this.textboxes) {
this.textboxes[textboxPresetName].draw(this.camera);
}
}
}); |
import React from "react";
import { createStore } from "redux";
import { Provider } from "react-redux";
import { expect } from "chai";
import { configure, mount } from "enzyme";
import Adapter from "@wojtekmaj/enzyme-adapter-react-17";
import App from "../App";
import restaurantsReducer from "../features/restaurant/restaurantsSlice";
configure({ adapter: new Adapter() });
describe("RestaurantsInput", () => {
let wrapper;
let store;
beforeEach(() => {
store = createStore(restaurantsReducer);
wrapper = mount(
<Provider store={store}>
<App />
</Provider>
);
});
it("updates the store when the form is submitted", () => {
expect(store.getState().restaurants.length).to.equal(0);
let form = wrapper.find("form").first();
form.simulate("submit", { preventDefault() {} });
expect(store.getState().restaurants.length).to.equal(1);
});
it("uses the values from the form to update the store", () => {
expect(store.getState().restaurants.length).to.equal(0);
let restaurantNameInput = wrapper.find("input").first();
restaurantNameInput.simulate("change", { target: { value: "chilis" } });
let locationInput = wrapper.find({ type: "text" }).last();
locationInput.simulate("change", { target: { value: "philly" } });
let form = wrapper.find("form").first();
form.simulate("submit", { preventDefault() {} });
expect(store.getState().restaurants[0]).to.deep.include({
name: "chilis",
location: "philly",
});
expect(store.getState().restaurants.length).to.equal(1);
});
});
|
import $ from 'jquery'
const StudentForm = (($) => {
const NAME = 'student-form'
const DATA_KEY = `bs.${NAME}`
const EVENT_KEY = `.${DATA_KEY}`
const DATA_API_KEY = '.data-api'
const Event = {
LOAD_DATA_API: `load${EVENT_KEY}${DATA_API_KEY}`,
CLICK_DATA_API: `click${EVENT_KEY}${DATA_API_KEY}`
}
const Default = {
}
const ClassName = { // eslint-disable-line
}
const Selector = {
DATA_MODULE: `[data-module="${NAME}"]`
}
class StudentForm {
constructor (element, config) {
this._element = $(element)
this._config = this._getConfig(config)
this.$submitbtn = $('#submit-btn')
this._addEventListener()
}
// public api
static get Default () {
return Default
}
// private api
_addEventListener () {
var database = firebase.database()
var $name = $('.student-form input[name="name"]')
var $university = $('.student-form input[name="university"]')
var $program = $('.student-form input[name="program"]')
var $year = $('.student-form input[name="year"]')
var $description = $('.student-form textarea[name="description"]')
var $submitbtn = this.$submitbtn
var uid
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
uid = user.uid
database.ref(`users/${uid}`).once('value').then((snapshot) => {
var currole = snapshot.val().role
if (currole == 'recruiter') window.location.assign('/')
else {
$submitbtn.click((e) => {
database = database.ref(`users/${uid}`)
var json = {}
json["name"] = $name.val()
json["university"] = $university.val()
json["program"] = $program.val()
json["year"] = $year.val()
json["description"] = $description.val()
database.update(json)
alert('Update successful')
window.location.assign('/facial-reg.html')
})
}
})
} else {
window.location.assign('/')
}
})
}
_getConfig (config) {
config = $.extend({}, Default, config)
return config
}
static _jQueryInterface (config) {
return this.each(function () {
const $element = $(this)
const _config = $.extend(
{},
Default,
$element.data(),
typeof config === 'object' && config
)
let data = $element.data(DATA_KEY)
if (!data) {
data = new StudentForm(this, _config)
$element.data(DATA_KEY, data)
}
})
}
}
/**
* Data Api implement
*/
$(window).on(Event.LOAD_DATA_API, () => {
StudentForm._jQueryInterface.call($(Selector.DATA_MODULE))
})
/**
* jQuery
*/
$.fn[NAME] = StudentForm._jQueryInterface
$.fn[NAME].Constructor = StudentForm
return StudentForm
})($)
export default StudentForm
|
import React from 'react'
import { Link } from 'react-router-dom';
const AboutApp = () => {
return (
<section className="h-100 w-100 main-resume">
<div className="d-flex justify-content-center align-items-center h-100 ">
<div className="jumbotron p-5 rounded resume w-50 font-weight-bolder" >
<h5 className="display-6">Dear user ,hi</h5>
<p className="lead ">this responsive application made with React Js and some other libraries like Bootstrap and react-Toastify</p>
<p className="lead mb-0">thank you for using my app. </p>
<p className="lead mt-0">Best Regards, "Mostafa.es".</p>
<a href="mailto:e.mostafa021@gmail.com?subject=about_todo_app" className=" mt-3 text-danger text-decoration-none"><h4>click for email to me!</h4></a>
<hr className="my-4" />
<Link className="btn btn-primary btn-lg" to={"/"} role="button">Back to App</Link>
</div>
</div>
</section>
);
}
export default AboutApp; |
import { takeLatest, put, call, select } from "redux-saga/effects";
import { actionTypes, actions as propertyActions } from "./actions";
import { actions as uiActions } from "../ui/actions";
import { actions as mapActions } from "../map/actions";
import { getMetros, getMetroProperties } from "../../api/msrApi";
function getZoom(state) { return state.map.zoom };
function* watchClearMetroProperties() {
yield put(uiActions.setShowInfoPanel(false));
}
function* watchGetMetros() {
yield put(uiActions.setLoading(true));
const metros = yield call(getMetros);
yield put(propertyActions.getMetrosComplete(metros));
yield put(uiActions.setLoading(false));
}
function* watchSelectMetro({ payload: metro }) {
const { latitude: lat, longitude: lng, name } = metro;
yield put(uiActions.setLoading(true));
yield put(mapActions.setCenter({ lat, lng }));
yield put(mapActions.setZoom(10));
const properties = yield call(getMetroProperties, name);
yield put(propertyActions.getMetroPropertiesComplete(properties));
yield put(uiActions.setShowInfoPanel(true));
yield put(uiActions.setLoading(false));
}
function* watchSelectProperty({ payload: property }) {
const { latitude: lat, longitude: lng } = property;
yield put(uiActions.setShowInfoPanel(true));
yield put(mapActions.setCenter({ lat, lng }));
const currentZoom = yield select(getZoom);
if (currentZoom < 12) {
yield put(mapActions.setZoom(13));
}
}
export default function* propertiesSaga() {
yield takeLatest(actionTypes.getMetros, watchGetMetros);
yield takeLatest(actionTypes.selectMetro, watchSelectMetro);
yield takeLatest(actionTypes.clearMetroProperties, watchClearMetroProperties);
yield takeLatest(actionTypes.selectProperty, watchSelectProperty);
} |
import React, { useState } from 'react';
const Toggle= () =>{
const[count,setcount]=useState(1);
const dark=()=>{
if(count==="1"){
setco("#e4e6eb")
setcount("2")
}
else{
setco("black")
setcount("1")
}
}
return(<>
<label className="switch" style={{backgroundColor: bg}} index={count}>
<input type="checkbox" onClick={dark}/>
<span className="slider round"></span>
</label>
</>)
}
export default Toggle; |
const mongoose = require('mongoose');
const Joigoose = require('joigoose')(mongoose, null, {
_id: true,
timestamps: true,
});
const Joi = require('joi');
const UserSchema = Joi.object().keys({
username: Joi.string().required(),
password: Joi.string().required(),
email: Joi.string().required(),
firstName: Joi.string().required(),
lastName: Joi.string().required(),
region: Joi.string().optional(),
configurations: Joi.object()
.keys({
features: Joi.object()
.keys({
daily_questions: Joi.boolean().required(),
habit_tracker: Joi.boolean().required(),
time_tracker: Joi.boolean().required(),
})
.required(),
})
.optional(),
});
const schema = Joigoose.convert(UserSchema);
schema.updatedAt = { type: Date, default: Date.now };
schema.createdAt = { type: Date, default: Date.now };
module.exports = mongoose.model('User', schema);
|
const LIST_TYPES = {
Bullet: 1,
Ordered: 2,
}
module.exports = LIST_TYPES
|
window.onload = function(){
var id = $.cookie('id');
var totalNmbuer,currentPage,sta;
//权限判断
if(id==null){
$("#room_add").css("display","none");
$("#room_delete_all").css("display","none");
$("#room_daochu_all").css("display","none");
selectRoom(id,1,sta);
}else {
selectSat(id);
}
//记录价格
var price;
//导出数据
$("#room_daochu_all").click(function () {
$(".table2excel").table2excel({
exclude: ".noExl",
name: "Excel Document Name",
filename: "房间信息管理",
exclude_img: true,
exclude_links: true,
exclude_inputs: true
});
});
//跳转管理页面
$("#a_href").click(function () {
if(data != "undefined"){
window.location.href="index.html?"+data;
}else{
window.location.href="index.html";
}
});
//重置信息
$("#chongzhi_but").click(function () {
$("#page_nav").empty();
$("#room_table tbody").empty();
$("#page_info").empty();
$("#selectPrice").val("");
$("#price_but").attr("disabled","disabled");
$("#baobiao").empty();
$("#baobiao").css("display","block");
$("#p_but").text("");
$("#selectPrice").parent().removeClass("has-error");
selectRoom(id,1,sta);
});
//点击新增按钮弹出框
$("#room_add").click(function(){
$("#number_input").val("");
$("#introduce_input").val("");
$("#floor_input").val("");
$("#price_input").val("");
$("#price_input").val("");
$("#path_input").val("");
$("#p_input").text("");
$("#path_input").parent().removeClass("has-error");
$("#p1_input").text("");
$("#img_input").attr("src","img/mangement/img.jpg");
$("#addRoom").modal({
backdrop:"static"
});
});
//检查房间名是否存在
$("#number_input").change(function () {
$("#number_input").parent().removeClass("has-success has-error");
$("#number_span").text("");
var number=$(this).val();
number=number.trim();
if(number==""||number==null){
savaBut( $("#save_room_but"));
return false;
}
$.ajax({
url:"/hotelonlinereservation/ManagementController/selectNumber",
data:"number="+number,
dataType:"json",
type:"GET",
success:function (data) {
if(data==false){
$("#number_input").parent().addClass("has-error");
$("#number_span").text("房间名已存在");
$("#number_span").css("color","red");
$("#save_room_but").attr("msg","error");
savaBut( $("#save_room_but"));
}else{
$("#save_room_but").attr("msg","success");
savaBut( $("#save_room_but"));
}
},
error:function () {
layer_alert('获取错误', "error");
},
});
});
//介绍
$("#introduce_input").change(function(){
$(this).parent().removeClass("has-error");
$("#introduce_span").text("");
var introduce=$(this).val();
introduce=introduce.trim();
if(introduce==""||introduce==null){
savaBut( $("#save_room_but"));
return false;
}
if(introduce.length>5){
$(this).parent().addClass("has-error");
$("#introduce_span").text("介绍不要超过5个字");
$("#introduce_span").css("color","red");
$("#save_room_but").attr("msg-1","error");
savaBut( $("#save_room_but"));
return false;
}else{;
$("#save_room_but").attr("msg-1","success");
savaBut( $("#save_room_but"));
}
});
//完成全选/全不选
$("#check_all").click(function(){
//prop(选中复选框就是ture 没选中就是false)
$(".check_item").prop("checked",$(this).prop("checked"));
});
//.check_item为单个全选添加点击事件
$(document).on("click",".check_item",function(){
//判断当前元素是否选择完成,全部选满是ture 否则是fals
var flag=$(".check_item:checked").length==$(".check_item").length;
//alert($(".check_item:checked").length);
$("#check_all").prop("checked",flag);
});
//多选删除 批量删除
$("#room_delete_all").click(function(){
var number="";
var dele_idstr="";
//便利选中的单选框
$.each($(".check_item:checked"),function(){
//获取其父元素tr下边的第三个td元素的值(员工的姓名)
number+=$(this).parents("tr").find("td:eq(1)").text()+",";
//组装员工的id
dele_idstr+=$(this).parents("tr").find("td:eq(6)").find(".delete_btn").attr("room-id")+"-";
});
if(!$.trim(number)){
layer_alert('请选择删除的房间', "warn");
}else{
//去除多余的逗号
number=number.substring(0, number.length-1);
//去除多余的-
dele_idstr=dele_idstr.substring(0, dele_idstr.length-1);
if(confirm("确认删除"+number+"这些房间吗?")){
//发送ajax请求
$.ajax({
url:"/hotelonlinereservation/ManagementController/deleteAll/"+dele_idstr,
type:"DELETE",
dataType:"json",
success:function(result){
if(result.msg=="处理失败"){
layer_alert(number+'其中某个房间已被预订无法批量删除', "warn");
}else{
layer_alert('房间删除成功', "success");
//回到当前页面
selectRoom(id,currentPage,sta);
}
},
error:function () {
layer_alert('删除失败联系管理员', "error");
}
});
}
}
});
//点击编辑按钮弹出模态框
$(document).on("click",".update_btn",function(){
//在模态框弹出之前查出房间信息
getRoom($(this).attr("room-id"));
$("#p_update").text("");
$("#update_room_but").attr("disabled",false);
$("#update_room_but").attr("room-id",$(this).attr("room-id"));
$("#span1_update").text("");
$("#path_update").parent().removeClass("has-error");
//弹出模态框
$("#updateRoom").modal({
backdrop:"static"
});
});
//检查价格是否正确
$("#selectPrice").change(function () {
$("#selectPrice").parent().removeClass("has-error");
$("#p_but").text("");
var price=$(this).val();
price=price.trim();
if(price==null||price==""){
$("#price_but").attr("disabled","disabled");
return false;
}
var r = /^\+?[1-9][0-9]*$/; //判断是否为正整数
if(!r.test(price)){
$("#selectPrice").parent().addClass("has-error");
$("#p_but").text("价钱只为正整数");
$("#p_but").css("color","red");
$("#price_but").attr("disabled","disabled");
return false;
}else{
$("#price_but").attr("disabled",false);
}
});
//价格查询房间
$("#price_but").click(function () {
price=$("#selectPrice").val();
selectRoomByPrice(id,price,1,sta);
});
//更新图片预览
$("#path_update").change(function () {
var preview = document.querySelector('#img_update');
var file = document.querySelector('#path_update').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
$("#span1_update").text("");
$("#path_update").parent().removeClass("has-error");
reader.readAsDataURL(file);
}
});
//新增图片预览
$("#path_input").change(function () {
var preview = document.querySelector('#img_input');
var file = document.querySelector('#path_input').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
$("#path_input").parent().removeClass("has-error");
$("#p1_input").text("");
reader.readAsDataURL(file);
}
});
//给后面单个删除按钮添加事件
$(document).on("click",".delete_btn",function () {
var roomIds= $(this).attr("room-id");
var room=$(this).parents("tr").find("td:eq(1)").text();
if(confirm("确认删除"+room+"房间吗?")){
$.ajax({
url:"/hotelonlinereservation/ManagementController/deleteAll/"+roomIds,
type:"DELETE",
dataType:"json",
success:function (data) {
if(data.msg=="处理失败"){
layer_alert('此房间已被预订无法删除', "warn");
}else{
layer_alert('房间删除成功', "success");
//回到当前页面
selectRoom(id,currentPage,sta);
}
},
error:function () {
layer_alert('删除失败联系管理员', "error");
}
});
}
});
//悬浮事件
$("#room_table").on("mouseover mouseout","img",function(event){
$("#pic").remove();
$("#room_table").append("<div id='pic' style='position:absolute;'><img src='"+$(this).attr("src")+"' style='width: 300px; height:300px; border-radius: 5px;-webkit-box-shadow: 5px 5px 5px 5px hsla(0,0%,5%,1.00); box-shadow: 5px 5px 5px 0px hsla(0,0%,5%,0.3); '></div>");
if(event.type == "mouseover"){
//鼠标悬浮
$(this).mousemove(function(e){
$("#pic").css({
"top":40+"px",
"right":-20+"px"
}).fadeIn("fast");
});
}else if(event.type == "mouseout"){
$("#pic").remove();
}
});
//根据价格查房间
function selectRoomByPrice(id,price,pn,sta) {
$.ajax({
url:"/hotelonlinereservation/ManagementController/selectRoomByPrice",
type:"GET",
dataType:"json",
data:{"price":price,"pn":pn},
success:function (data) {
var room = data.extend.pageInfo.list;
//解析房间信息
roomAjaxByPic(id,room,sta);
//解析分页条信息
pageByprice(id,price,data,sta);
//解析分页信息
build_pag_navByPic(data);
$("#baobiao").empty();
baobiaoByPic(room);
},
error:function () {
layer_alert('查询错误联系管理员', "error");
}
});
}
//解析分页条(价格)
function pageByprice(id,price,data,sta) {
//清空数据
$("#page_nav").empty();
var ul=$("<ul></ul>").addClass("pagination");
//构造控件
var firstPage=$("<li></li>").append($("<a></a>").append("首页").attr("href","javascript:void(0);"));
var perPage=$("<li></li>").append($("<a></a>").append("«"));
//当前为第一页,那首页和上一页无法点击
//alert(result.extend.pageInfo.hasPreviousPage);
//是否有上一页
if(data.extend.pageInfo.hasPreviousPage==false){
firstPage.addClass("disabled");
perPage.addClass("disabled");
}else{
//为控件添加点击事件(点击首页跳转第一页)
firstPage.click(function(){
selectRoomByPrice(id,price,1,sta);
});
// 点击上一页,跳转到当前页面减一
perPage.click(function(){
selectRoomByPrice(id,price,data.extend.pageInfo.pageNum-1,sta)
});
}
//构造控件(下一页)
var nextPage=$("<li></li>").append($("<a></a>").append("»"));
//尾页
var lastPage=$("<li></li>").append($("<a></a>").append("尾页").attr("href","javascript:void(0);"));
//如果当前是最后一页,就无法点击下一页后尾页
if(data.extend.pageInfo.hasNextPage==false){
nextPage.addClass("disabled");
lastPage.addClass("disabled");
}else{
//为控件添加点击事件(当前页面加一)
nextPage.click(function(){
selectRoomByPrice(id,price,data.extend.pageInfo.pageNum+1,sta)
});
lastPage.click(function(){
//跳到最后一页
selectRoomByPrice(id,price,data.extend.pageInfo.pages,sta)
});
}
//添加首页跟前一页
ul.append(firstPage).append(perPage);
//便利页码号result.extend.pageInfo.navigatepageNums==1,2,3.4,5
//所有页码
//alert(result.extend.pageInfo.navigatepageNums);
$.each(data.extend.pageInfo.navigatepageNums,function(index,item){
//item是依次被便利出来的1,2,3,4,5页码
var numli=$("<li></li>").append($("<a></a>").append(item));
//如果当前被便利出来的页码等于被点击页数,加一个蓝色标记
if(data.extend.pageInfo.pageNum==item){
numli.addClass("active");
}
numli.click(function(){
selectRoomByPrice(id,price,item,sta)
});
ul.append(numli);
});
//便利完了添加下一页和尾页
ul.append(nextPage).append(lastPage);
//将ul添加到nav中
var nav=$("<nav></nav>").append(ul);
//将nav添加到id为page_nav的div中
nav.appendTo("#page_nav");
}
//更新之前查出信息
function getRoom(id) {
$.ajax({
url:"/hotelonlinereservation/ManagementController/getRoom/"+id,
type:"GET",
dataType:"json",
success:function (data) {
var room=data.extend.room;
var path=room.path;
$("#number_update").text(room.number);
$("#floor_update").val(room.floor);
$("#introduce_update").val(room.introduce);
$("#price_update").val(room.price);
//$("#path_update").val(path);
//alert( $("#path_update").value(room.path));
$("#img_update").attr("src",room.path);
},
error:function () {
layer_alert('获取失败', "error");
},
});
}
//判断按钮
function savaBut(msg) {
if(msg.attr("msg")=="success"&&msg.attr("msg-1")=="success"){
msg.attr("disabled",false);
}else {
msg.attr("disabled","disabled");
}
}
//按楼层获取所有房间信息
function selectRoom(id,pn,sta){
$.ajax({
url:"/hotelonlinereservation/ManagementController/selectRoom",
type:"GET",
dataType:"json",
data:"pn="+pn,
beforeSend:function(XMLHttpRequest){
$("#loading").html("<p style=\"display: block;font-size: 25px;margin-top: 200px;margin-left:45%;\">\n" +
" <svg >\n" +
" <path fill=\"#0000FF\" d=\"M73,50c0-12.7-10.3-23-23-23S27,37.3,27,50 M30.9,50c0-10.5,8.5-19.1,19.1-19.1S69.1,39.5,69.1,50\">\n" +
" <animateTransform\n" +
" attributeName=\"transform\"\n" +
" attributeType=\"XML\"\n" +
" type=\"rotate\"\n" +
" dur=\"1s\"\n" +
" from=\"0 50 50\"\n" +
" to=\"360 50 50\"\n" +
" repeatCount=\"indefinite\" />\n" +
" </path>\n" +
" </svg>\n"+
" </p>");
},
success:function (data) {
$("#loading").css("display","none");
var room = JSON.parse(data.extend.pageInfo);
//解析房间信息
roomAjax(id,room,sta);
//解析分页条信息
page(id,room,sta);
//解析分页信息
build_pag_nav(room);
baobiao(room);
},
error:function () {
$("#loading").css("display","none");
layer_alert('获取错误', "error");
},
});
}
function baobiaoByPic(room) {
var y_label = "价格"; //Y轴标题
var x_label = "房间号"; //X轴标题
//var line_title =new Array(data.extend.list.length); //曲线名称
var x =[];
var data1=[];
var circle =new Array;
for(var a=0;a<room.length;a++){
circle[a]=room[a].price;
x[a]=room[a].number;
}
data1.push(circle);
var data_max =600; //Y轴最大刻度
var title = "这是标题"; //统计图标标题
j.jqplot.diagram.base("baobiao", data1, "A", "房间价格统计表", x, x_label, y_label, data_max, 2);
}
function baobiao(room) {
var y_label = "价格"; //Y轴标题
var x_label = "房间号"; //X轴标题
//var line_title =new Array(data.extend.list.length); //曲线名称
var x =[];
var data1=[];
var circle =new Array;
for(var a=0;a<room[0].list.length;a++){
circle[a]=room[0].list[a].price;
x[a]=room[0].list[a].number;
}
data1.push(circle);
var data_max =600; //Y轴最大刻度
var title = "这是标题"; //统计图标标题
j.jqplot.diagram.base("baobiao", data1, "A", "房间价格统计表", x, x_label, y_label, data_max, 2);
}
function selectSat(id){
$.ajax({
url: "/hotelonlinereservation/RegistrationController/getName",
type: "GET",
data: {"id": id},
dataType: "json",
success: function (data) {
var user = data.extend.list;
$.each(user, function (index, item) {
sta=user.sta;
if(user.sta==1){
$("#room_add").text("");
$("#room_delete_all").text("");
$("#room_add").text("新增");
$("#room_add").attr("disabled",false);
$("#room_delete_all").text("删除");
$("#room_delete_all").attr("disabled",false);
$("#room_daochu_all").attr("disabled",false);
}else {
$("#room_add").text("");
$("#room_delete_all").text("");
$("#room_add").text("无权限");
$("#room_add").css("display","none");
$("#room_delete_all").text("无权限");
$("#room_delete_all").css("display","none");
$("#room_daochu_all").css("display","none");
}
});
//按楼层获取所有房间信息
selectRoom(id,1,sta);
},
error: function () {
layer_alert('服务器异常', "error");
},
});
}
//解析房间信息(全部获取)
function roomAjax(id,room,sta){
$("#room_table tbody").empty();
if(room==null){
$("#room_table tbody").append("<div style='height: 200px;width: 500px;margin-top: 100px;margin-left: 30%;'><span class=\"glyphicon glyphicon-exclamation-sign\" aria-hidden=\"true\" style='font-size:100px;color: #c0c0c0;margin-left: 35%;'></span><p style='font-size: 30px;'>客官,目前所有房间正在整改中</p></div>");
$("#baobiao").css("display","none");
}else{
for(var i=0;i<room[0].list.length;i++){
var checkBoxId=$("<td style=' vertical-align: middle;'><input type='checkbox' class='check_item'/></td>");
var roomname=$("<td style=' vertical-align: middle;'></td>").append(room[0].list[i].number);
var roomfloor=$("<td style=' vertical-align: middle;'></td>").append(room[0].list[i].floor);
var roomintroduce=$("<td style=' vertical-align: middle;'></td>").append(room[0].list[i].introduce);
var roomprice=$("<td style=' vertical-align: middle;'></td>").append(room[0].list[i].price+"元/日");
var roompath=$("<td style=' vertical-align: middle;' ></td>").append($("<div class='img_d"+i+"' style='width:50px;height:50px;'><img src='"+room[0].list[i].path+"' width='50px'height='50px' style='cursor: pointer;' class='img_a'/></div>"));
//添加编辑按钮
if(sta!=1){
var edibtn=$($("<span></span>").addClass("glyphicon glyphicon-ban-circle"));
}else{
var edibtn=$("<button></button>").addClass("btn btn-primary btn-sm update_btn")
.append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑");
//为编辑按钮添加一个自定义属性来记录id
edibtn.attr("room-id",room[0].list[i].roomId);
//添加删除按钮
var delbtn=$("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
.append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
//为删除按钮添加id
delbtn.attr("room-id",room[0].list[i].roomId);
}
var btntd=$("<td style=' vertical-align: middle;'></td>").append(edibtn).append(" ").append(delbtn);
$("<tr></tr>").append(checkBoxId).append(roomname).append(roomfloor).append(roomintroduce).append(roomprice)
.append(roompath).append(btntd)
.appendTo("#room_table tbody");
//图片加载完成
loadImg($(".img_d"+i+""));
}
}
}
//图片加载完成
function loadImg(img_d) {
img_d.find("img").hide();
img_d.append("<p style='display: block;position: relative;bottom: 25px;right: 25px;'><svg ><path fill=\"#0000FF\" d=\"M73,50c0-12.7-10.3-23-23-23S27,37.3,27,50 M30.9,50c0-10.5,8.5-19.1,19.1-19.1S69.1,39.5,69.1,50\">\n" +
" <animateTransform\n" +
" attributeName=\"transform\"\n" +
" attributeType=\"XML\"\n" +
" type=\"rotate\"\n" +
" dur=\"1s\"\n" +
" from=\"0 50 50\"\n" +
" to=\"360 50 50\"\n" +
" repeatCount=\"indefinite\" />\n" +
" </path>\n" +
" </svg></p>");
img_d.find("img").load(function(e){
img_d.find("p").empty();
img_d.find("img").show();
});
}
//解析房间信息(价格获取)
function roomAjaxByPic(id,room,sta){
$("#room_table tbody").empty();
if(room.length==0){
$("#room_table tbody").append("<div style='height: 200px;width: 500px;margin-top: 100px;margin-left: 30%;'><span class=\"glyphicon glyphicon-exclamation-sign\" aria-hidden=\"true\" style='font-size:100px;color: #c0c0c0;margin-left: 35%;'></span><p style='font-size: 30px;'>客官,目前没有这么便宜的房间</p></div>");
$("#baobiao").css("display","none");
}else{
$.each(room,function(index,item){
var checkBoxId=$("<td style=' vertical-align: middle;'><input type='checkbox' class='check_item'/></td>");
var roomname=$("<td style=' vertical-align: middle;'></td>").append(item.number);
var roomfloor=$("<td style=' vertical-align: middle;'></td>").append(item.floor);
var roomintroduce=$("<td style=' vertical-align: middle;'></td>").append(item.introduce);
var roomprice=$("<td style=' vertical-align: middle;'></td>").append(item.price+"元/日");
var roompath=$("<td style=' vertical-align: middle;' ></td>").append($("<img src='"+item.path+"' width='50px'height='50px' style='cursor: pointer;' class='img_a'/>"));
//添加编辑按钮
if(sta!=1){
var edibtn=$($("<span></span>").addClass("glyphicon glyphicon-ban-circle"));
/* //添加删除按钮glyphicon glyphicon-ban-circle
var delbtn=$("<button disabled='disabled'></button>").addClass("btn btn-danger btn-sm delete_btn")
.append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("无权限");
//为删除按钮添加id
delbtn.attr("room-id",item.roomId);*/
}else{
var edibtn=$("<button></button>").addClass("btn btn-primary btn-sm update_btn")
.append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑");
//为编辑按钮添加一个自定义属性来记录id
edibtn.attr("room-id",item.roomId);
//添加删除按钮
var delbtn=$("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
.append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
//为删除按钮添加id
delbtn.attr("room-id",item.roomId);
}
var btntd=$("<td style=' vertical-align: middle;'></td>").append(edibtn).append(" ").append(delbtn);
$("<tr></tr>").append(checkBoxId).append(roomname).append(roomfloor).append(roomintroduce).append(roomprice)
.append(roompath).append(btntd)
.appendTo("#room_table tbody");
});
}
}
//解析分页条信息
function page(id,data,sta) {
//清空数据
$("#page_nav").empty();
var ul=$("<ul></ul>").addClass("pagination");
//构造控件
var firstPage=$("<li></li>").append($("<a></a>").append("首页").attr("href","javascript:void(0);"));
var perPage=$("<li></li>").append($("<a></a>").append("«"));
//当前为第一页,那首页和上一页无法点击
//alert(result.extend.pageInfo.hasPreviousPage);
//是否有上一页
if(data[0].hasPreviousPage==false){
firstPage.addClass("disabled");
perPage.addClass("disabled");
}else{
//为控件添加点击事件(点击首页跳转第一页)
firstPage.click(function(){
selectRoom(id,1,sta)
$("#baobiao").empty();
});
// 点击上一页,跳转到当前页面减一
perPage.click(function(){
selectRoom(id,data[0].pageNum-1,sta)
$("#baobiao").empty();
});
}
//构造控件(下一页)
var nextPage=$("<li></li>").append($("<a></a>").append("»"));
//尾页
var lastPage=$("<li></li>").append($("<a></a>").append("尾页").attr("href","javascript:void(0);"));
//如果当前是最后一页,就无法点击下一页后尾页
if(data[0].hasNextPage==false){
nextPage.addClass("disabled");
lastPage.addClass("disabled");
}else{
//为控件添加点击事件(当前页面加一)
nextPage.click(function(){
selectRoom(id,data[0].pageNum+1,sta)
$("#baobiao").empty();
});
lastPage.click(function(){
//跳到最后一页
selectRoom(id,data[0].pages,sta);
$("#baobiao").empty();
});
}
//添加首页跟前一页
ul.append(firstPage).append(perPage);
//便利页码号result.extend.pageInfo.navigatepageNums==1,2,3.4,5
//所有页码
//alert(result.extend.pageInfo.navigatepageNums);
$.each(data[0].navigatepageNums,function(index,item){
//item是依次被便利出来的1,2,3,4,5页码
var numli=$("<li></li>").append($("<a></a>").append(item));
//如果当前被便利出来的页码等于被点击页数,加一个蓝色标记
if(data[0].pageNum==item){
numli.addClass("active");
}
numli.click(function(){
selectRoom(id,item,sta);
$("#baobiao").empty();
});
ul.append(numli);
});
//个数
// var number=$("<select style='width: 80px;height: 34px;'><option value='5'>5</option><option value='10'>10</option><option value='15'>15</option><option value='20'>20</option></select>");
//便利完了添加下一页和尾页
ul.append(nextPage).append(lastPage);
//将ul添加到nav中
var nav=$("<nav></nav>").append(ul)
//将nav添加到id为page_nav的div中
nav.appendTo("#page_nav");
}
//解析分页信息
function build_pag_nav(data){
//清空数据
$("#page_info").empty();
$("#page_info").append("当前"+data[0].pageNum +"页,总"+data[0].pages +"共页,总"+data[0].total+"记录");
//记录总数
totalNmbuer=data[0].pages;
//记录当前页数
currentPage=data[0].pageNum;
}
//解析分页信息
function build_pag_navByPic(data){
//清空数据
$("#page_info").empty();
$("#page_info").append("当前"+data.extend.pageInfo.pageNum +"页,总"+data.extend.pageInfo.pages +"共页,总"+data.extend.pageInfo.total+"记录");
/*//记录总数
totalNmbuer=data.extend.pageInfo.pages;
//记录当前页数
currentPage=data.extend.pageInfo.pageNum;*/
}
/** 弹出层 **/
function layer_alert(msg, type) {
if (type == "success") {
layer.alert(msg, {
icon : 1
});
return;
}
if (type == "error") {
layer.alert(msg, {
icon : 2
});
return;
}
if (type == "ask") {
layer.alert(msg, {
icon : 3
});
return;
}
if (type == "warn") {
layer.alert(msg, {
icon : 7
});
return;
}
}
function layer_post(data) {
if (data.code === 0) {
layer.alert(data.message, {
icon : 1
});
return;
}
if (data.code === 1 || data.code === 999) {
layer.alert(data.message, {
icon : 2
});
return;
}
if (data.code === 2) {
layer.alert(data.message, {
icon : 7
});
return;
}
if (data.code === 3) {
layer.alert(data.message, {
icon : 7
});
return;
}
}
function appLoading() {
return layer.load(1, {
shade : false
});
}
function clearLoading(index) {
layer.close(index);
}
}
|
const max_score=10;
const max_ques=3;
let questionnaire=document.getElementById("question");
let choice=Array.from(document.getElementsByClassName("choice-text"));
let selectques=document.getElementById("question_counter");
let selectscore=document.getElementById("score");
console.log("q",questionnaire);
console.log("choice",choice);
let current_ques ={};
let copy_ques=[];
let questions=[
{
ques:"Do you think eating ginger can prevent corona??",
choice1:"Yes",
choice2:"No",
answer:"2"
},
{
ques:"Do you think hot weather can prevent corona??",
choice1:"Yes",
choice2:"No",
answer:"2"
},
{
ques:"Do you think lock-down is a good decision??",
choice1:"Yes",
choice2:"No",
answer:"1"
}
]
console.log(questions);
let question_counter=0;
let score=0;
copy_ques=[...questions];
start_game = () =>
{
score=0;
copy_ques=[];
question_counter=0;
set_new_ques();
};
set_new_ques = () =>
{
if (question_counter >= max_ques || questions.length ===0 ) {
return window.location.assign("end.html");
}
current_ques=questions[question_counter];
questionnaire.innerText=current_ques.ques;
question_counter++;
selectques.innerText=`${question_counter}/${max_ques}`;
choice.forEach(i =>
{
const number=i.dataset["number"];
i.innerText=current_ques["choice"+number];
});
};
choice.forEach(i => {
i.addEventListener("click",e =>{
const selectchoice=e.target;
const selectanswer=selectchoice.dataset["number"];
let newclass="incorrect";
const ans=selectanswer===current_ques.answer;
if(ans)
{
newclass="correct";
increment_score(max_score);
}
selectchoice.parentElement.classList.add(newclass);
setTimeout(() =>
{
selectchoice.parentElement.classList.remove(newclass);
set_new_ques();
},1000);
});
});
increment_score =(num) =>
{
score=score+num;
selectscore.innerText=score;
}
start_game(); |
class ComputerPaddle extends Paddle {
constructor() {
super(c.height*0.33);
}
ai() {
if(ball.posY > this.posY + this.height*0.6) {
this.move(5);
} else if(ball.posY < this.posY + this.height*0.4) {
this.move(-5);
}
}
}
|
function MyAlert() {
// Used https://www.youtube.com/watch?v=-RLE2Q7OzME as guide
var result = false;
var inputText = null;
var isPaused = false;
// Function that shows the overlay and the dialog
this.render = function(){
var pageHeight = window.innerHeight;
var dialogOverlay = document.getElementById("dialogOverlay");
var dialogBox = document.getElementById("dialogBox");
dialogOverlay.style.display = "block";
dialogOverlay.style.height = pageHeight + "px";
dialogBox.style.margin = "auto";
dialogBox.style.position = "absolute";
dialogBox.style.left = "0px";
dialogBox.style.top = "100px";
dialogBox.style.right = "0px";
dialogBox.style.display = "block";
}
// Function that alerts the user with paramter txt
this.alert = function (txt) {
this.render();
document.getElementById('dialogHead').innerHTML = "Alert!";
document.getElementById('dialogBody').innerHTML = txt;
var button = '<button onclick="Alert.hide()">OK</button>';
document.getElementById('dialogFoot').innerHTML = button;
}
// Hides the dialog from the user
this.hide = function () {
var dialogOverlay = document.getElementById("dialogOverlay");
var dialogBox = document.getElementById("dialogBox");
dialogBox.style.display = "none";
dialogOverlay.style.display = "none";
}
// Function that asks user for confirmation
this.confirmation = function(txt, yesCallback, noCallBack){
this.render();
document.getElementById('dialogHead').innerHTML = "Confirmation";
document.getElementById('dialogBody').innerHTML = txt;
var button = '<button id="buttonYes" ">Confirm</button>';
button = button + '<button id="buttonNo">Deny</button>';
document.getElementById('dialogFoot').innerHTML = button;
document.getElementById('buttonYes').onclick = function() {
new MyAlert().hide();
yesCallback();
}
document.getElementById('buttonNo').onclick = function () {
new MyAlert().hide();
noCallBack();
}
}
this.prompt = function(txt, def, yesCallBack){
this.render();
document.getElementById('dialogHead').innerHTML = txt;
if (def == null){
def = '';
}
var input = '<input id="prompt_value" value="'+def+'">';
document.getElementById('dialogBody').innerHTML = input;
var button = '<button id = "prompt_confirm">Confirm</button>';
button = button + '<button id = "prompt_deny">Deny</button>';
document.getElementById('dialogFoot').innerHTML = button;
document.getElementById('prompt_confirm').onclick = function () {
new MyAlert().hide();
yesCallBack();
}
document.getElementById('prompt_deny').onclick = function () {
new MyAlert().hide();
document.getElementById('prompt_value').value = null;
yesCallBack();
}
if(result){
inputText = document.getElementById('prompt_value').innerHTML;
return inputText;
}
return null;
}
} |
import {applyMiddleware, createStore} from 'redux'
import {createEpicMiddleware} from 'redux-observable'
import {ajax} from 'rxjs/observable/dom/ajax'
import 'rxjs/add/operator/catch'
import {Observable} from 'rxjs/Observable'
import 'rxjs/add/observable/of'
import epics from './epic'
import reducers from './reducer'
import {resetGoogleAccessToken} from './actions'
const errorHandler = (error, stream) => {
if (error.status === 401) {
return Observable.of(resetGoogleAccessToken())
}
return stream
}
export const epicAdapter = {
input: action$ => action$,
output: action$ => action$.catch(errorHandler)
}
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8'
}
const epicMiddleware = createEpicMiddleware(epics, {
dependencies: {
get: (url, customHeaders) =>
ajax({
url,
headers: Object.assign({}, headers, customHeaders),
crossDomain: true
}),
post: (url, body, customHeaders, responseType) =>
ajax({
method: 'POST',
url,
body,
headers: Object.assign({}, headers, customHeaders),
responseType: responseType || 'json',
crossDomain: true
}),
put: (url, body, customHeaders, responseType) =>
ajax({
method: 'PUT',
url,
body,
headers: Object.assign({}, headers, customHeaders),
responseType: responseType || 'json',
crossDomain: true
})
},
epicAdapter
})
export default createStore(reducers, {}, applyMiddleware(epicMiddleware))
|
/* eslint-disable no-console */
/* eslint-disable prefer-rest-params */
/* eslint-disable func-names */
import { __DEV__ } from '../constants/env';
const emptyFn = () => {};
export default {
info: __DEV__
? function() {
console.info(...arguments);
}
: emptyFn,
debug: __DEV__
? function() {
console.debug(...arguments);
}
: emptyFn,
error: __DEV__
? function() {
console.error(...arguments);
}
: emptyFn,
warn: __DEV__
? function() {
console.warn(...arguments);
}
: emptyFn,
}; |
/* Create a new Express HTTP server */
const fs = require( 'fs' );
const express = require( 'express' );
const app = express();
const cors = require( 'cors' );
app.use( cors());
/* Listen on port 2224 */
app.listen( 2224, () => console.log( 'Layout cache public server listening on port 2224!' ));
/* Create a public endpoint */
app.get( '/public', ( req, res ) => {
/* Depending whether or not a repo url was provided define the base path */
let basePath = '/tmp/layouts';
if ( req.query.url ) {
basePath = process.env.DEV
? `/tmp/layouts/${req.query.url.split( '/' )[1].split( '.git' )[0]}`
: `/tmp/${req.query.url.split( '/' )[1].split( '.git' )[0]}`;
}
if ( req.query.directory ) {
basePath = `/tmp/${req.query.directory}`;
}
/* Attempt to read the public routing file */
fs.readFile( `${basePath}/routing.public.json`, ( err, data ) => {
/* If an error occured then return it */
if ( err ) {
res.status( 500 );
res.json({
error: 'An unexpected error occured loading the public routing configuration for this repository.'
});
return;
}
let parsed = null;
try {
/* Convert the data to a string and JSON parse it */
parsed = JSON.parse( data.toString());
} catch ( e ) {
console.error( e );
res.status( 500 );
res.json({
error: 'An unexpected error occured loading the public routing configuration for this repository.'
});
return;
}
/* Loop over each file in the parsed file */
const files = parsed.map( entry => readJSONFile( `${basePath}/${entry.path}` ));
Promise.all( files ).then( result => {
res.json( parsed.map(( entry, index ) => {
entry.data = result[index];
return entry;
}));
});
});
});
/* Returns a promise that resolves when the file is loaded */
function readJSONFile( path ) {
return new Promise(( resolve, reject ) => {
/* Read the file */
fs.readFile( path, ( err, data ) => {
if ( err ) {
return reject( err );
}
try {
const parsed = JSON.parse( data.toString());
return resolve( parsed );
} catch ( e ) {
return reject( e );
}
});
});
}
|
import { createStyles, makeStyles } from "@material-ui/core/styles";
const useStyles = () =>
makeStyles(() =>
createStyles({
root: {
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
marginBottom: "60px",
},
title: {
textAlign: "center",
fontFamily: "Caveat",
fontWeight: "bold",
fontSize: "80px",
color: "#3F454A",
width: "100%",
"@media (max-width: 960px)": {
fontSize: "48px",
},
},
headingShape: {
position: "absolute",
marginTop: "42px",
paddingRight: "30px",
zIndex: -1,
opacity: 0.3,
"@media (max-width: 960px)": {
maxWidth: "90vw",
},
},
})
)();
export default useStyles;
|
import React, {Fragment, Component}from 'react';
import HomeNav from '../nav/homenav';
import Par from '../UI/paragraphs';
import one from '../../images/one.png';
import two from '../../images/two.png';
import three from '../../images/three.png';
import four from '../../images/four.png';
import Image from '../UI/image';
import GadgetPhone from '../../images/iphone.jpg';
import Lcd from '../../images/lcdScreen.jpg';
import shoe from '../../images/Nikeshoe_2.jpg';
import Form from '../../containers/formHolder'
import LoginForm from '../../components/forms/login'
import RequestForm from '../../components/forms/submitsign'
import SignForm from '../../components/forms/signUp'
import axios from 'axios'
import Footer from '../../components/UI/footer'
import About from '../../components/landing/about'
import ProBox from '../../components/holders/productBox'
import Loader from '../../components/UI/preloader'
import WinerBox from '../../components/holders/winnerBox'
import Slider from '../../components/holders/slider'
import Counter from '../../components/holders/counter'
import VendPolicy from '../../documents/vendors'
import RefunfPolicy from '../../documents/refund'
import TermsAndCond from '../../documents/document'
import AboutCo from '../../documents/aboutCompany'
import PrivacyPolicy from '../../documents/privacy'
import ModalTerms from 'react-modal'
import Modal from 'react-modal'
import WhatsApp from '../../images/iconfinder_whatsapp_287520.png'
import Ig from '../../images/6225234-download-instagram-logo-icon-free-png-transparent-image-and-clipart-instagram-symbol-transparent-400_400_preview.png'
import Tel from '../../images/iconfinder_telegram_3069742.png'
import Fb from '../../images/facbook.png'
import PayMentOpt from '../../images/PaymentOptions3.png'
import AboutCustoms from '../../documents/aboutVendN'
Modal.setAppElement('#root')
ModalTerms.setAppElement('#root')
class Landing extends Component {
state={
login: false,
sign: false,
request: false,
terms: {
},
timming: "3000",
products: null,
winners: null,
openedModal : false,
forms: false,
openAbout: false,
aboutType: null
}
componentDidMount() {
this.getFrontPro()
this.getFrontWin()
}
openAbout = () => {
let newState = {...this.state}
this.setState({
openedModal : !newState.openedModal,
showInfo: <AboutCustoms openForm={() => {
this.openAbout()
this.openRequest()
}} />,
})
}
getFrontPro = () => {
axios.get(localStorage.address + "/api/v1/frontpro")
.then(response => {
let newArray = [...response.data.data]
this.setState({
products: newArray
})
})
.catch(error => {
})
}
getFrontWin = () => {
axios.get(localStorage.address + "/api/v1/frontwin")
.then(response => {
let newArray = [...response.data.data]
this.setState({
winners: newArray
})
})
.catch(error => {
})
}
openSHare = () => {
this.setState({
modalShare: true
})
}
openLogin = () => {
let newState = {...this.state}
this.setState({
login: !newState.login,
forms: !newState.forms
})
}
openModalTimer = () => {
this.setState({
timming: "900000"
})
}
closeModalHanlder = () => {
this.setState({
timming: "3000"
})
}
openLogin21= () => {
}
openSign = () => {
let newState = {...this.state}
this.setState({
sign: !newState.sign,
forms: !newState.forms
})
}
openRequest = () => {
let newState = {...this.state}
this.setState({
request: !newState.request,
forms: !newState.forms
})
setTimeout(() => {
location.href="#topz"
}, 10);
}
loginSign = () => {
let newState = {...this.state}
this.setState({
login: !newState.login,
sign: !newState.sign
})
}
openTerms = () => {
this.setState({
openedModal : true,
showInfo: <TermsAndCond />
})
}
openRef = () => {
this.setState({
openedModal : true,
showInfo: <RefunfPolicy />
})
}
openVend = () => {
this.setState({
openedModal : true,
showInfo: <VendPolicy />
})
}
openAbout2 = () => {
this.setState({
openedModal : true,
showInfo: <AboutCo />
})
}
openPrivacy = () => {
this.setState({
openedModal : true,
showInfo: <PrivacyPolicy />
})
}
render() {
let CurrentForm = null
let func = null
let func2 = null
if(this.state.login) {
CurrentForm =( <LoginForm sign={this.loginSign} login={this.props.onLogin}/>)
func = this.openLogin
}
if(this.state.sign) {
CurrentForm =( <SignForm openTerms={ () => {
this.openRequest()
this.openTerms()
}} openPrivacy={() => {
this.openSign()
this.openPrivacy()
}}
login={this.props.onLogin}/>)
func = this.openSign
}
if (this.state.request) {
CurrentForm = (<RequestForm login={this.props.onLogin} openTerms={ () => {
this.openRequest()
this.openTerms()
}} openPrivacy={() => {
this.openRequest()
this.openPrivacy()
}}
openCharges12={() => {
this.openRequest()
this.openAbout()
}}
openVendor12={() => {
this.openRequest()
this.openVend()
}}
/>)
func = this.openRequest
}
return (
<React.Fragment>
{ !this.state.openAbout ?<React.Fragment>
{!this.state.forms ? <React.Fragment>
<HomeNav click1={this.openLogin} click2={this.openSign} />
{/* <div className="introPage">
<Par
info={{
type:"homeText padds2", //homeText homePara
text:" DO YOU BELIEVE YOU ARE A LUCKY PERSON? "
}}
/>
<Par
info={{
type:"homePara padds2", //homeText homePara
text:"Today, You Stand A Chance to Own A Valuable Item You Desire For A Minimum of $1"
}}
/>
<a href="#how" className="linkBtn2">Learn More</a>
</div>
*/}
<div id="how" className="introPage5">
<p className="homePara">
We Auction Valuable Items as the Winning Prize For One of You With the Lucky Fortune Number to Claim It. Our Winner Items are Sponsored through Tickets Sales.
</p>
<div className="gridBtn">
<a href="#how1" className="linkBtn21">How It Work </a>
<a href="https://www.youtube.com/watch?v=FteTrkjdb-0" target="_blank" className="blue darken-3">Watch Demo</a>
</div>
</div>
<div id="how1" className="introPage2">
<h5>How It Works </h5>
<div className="grid-flex padds2">
<div>
{/* <img width="180px" height="110px" src={one} alt=""/> */}
<p>Vendors Auction Brand New or Used items on the platform</p>
</div>
<div>
{/* <img width="180px" height="110px" src={two} alt=""/> */}
<p> You Choose an item you like, Then, Select and Buy one or more Lucky Tickets you Wish to Stand a Chance to Win </p>
</div>
<div>
{/* <img width="180px" height="110px" src={three} alt=""/> */}
<p> You Confirm if your ticket(s) Are the Winning Ticket(s) </p>
</div>
<div>
{/* <img width="180px" height="110px" src={four} alt=""/> */}
<p> We Ship your Won Item to your Location Even Globally </p>
</div>
</div>
<a href="#how3" className="linkBtn2">What We Do</a>
</div>
<div id="how3" className="introPage4 padds2">
<h3 style={{textTransform: "capitalize", paddingBottom:"10px"}} >
Fortune Auction is a Digital Product-Lottery Platform that Uses Unbais Technology that Select Winners Through Pure Luck
</h3>
<a className="linkBtn2" onClick={() => this.openAbout2()}>Learn More</a>
</div>
<div className="introPage3">
<h5 className="padds2">YOUR NEXT WISH COULD BE $1</h5>
<a href="#products" className="linkBtn11">View Auction</a>
<div className="bottomAligned grid-three">
<div>
<img width="250px" height="200px"src={GadgetPhone} alt=""/>
<p>Gadgets</p>
</div>
<div>
<img width="250px" height="200px"src={shoe} alt=""/>
<p>Fashion</p>
</div>
<div>
<img width="250px" height="200px"src={Lcd} alt=""/>
<p>Electronics</p>
</div>
</div>
</div>
<div className="imageSlider">
<Fragment>
<div className="w3-content w3-section" >
<Slider
timer="1000"
displayIn={ [
<div className="mySlides">
<img src={GadgetPhone} alt="" width="250px" height="200px" />
<p>Gadgets</p>
</div>,
<div className="mySlides">
<img src={shoe} alt="" width="250px" height="200px" />
<p>Fashion</p>
</div>,
<div className="mySlides">
<img src={Lcd} alt="" width="250px" height="200px" />
<p>Electronics</p>
</div>
]}
/>
</div>
</Fragment>
</div>
{/* About Appears here */}
<div className="about lastFron padds2">
<h3>Think of Affordable, Fast & Secure way to get your Wishes. Think Fortune Auction! </h3>
<div className="grid-three">
<div className="blackBokx">
<h5>RETURN & REFUND</h5>
<p className=""> We refund your money Immediately when the bid target is not reached after the bid deadline. So share to win!
</p>
<a className="linkBtn2" onClick={this.openRef}>Learn More</a>
</div>
<div className="blackBokx">
<h5> VENDORS </h5>
<p className=""> We partner with vendors globally with legal new or used items to auction.
</p>
<a className="linkBtn2" onClick={this.openAbout} >Learn More</a>
<br/>
<p className="">Do you have item(s) to auction? </p>
<a className="linkBtn2" onClick={this.openRequest} >Request Now</a>
</div>
<div className="blackBokx">
<h5>SECURITY</h5>
<p className="">We encrypt your password & payment information with safe technology. Your privacy is highly important to us.
</p>
<a className="linkBtn2" onClick={this.openPrivacy}>Learn More</a>
</div>
</div>
</div>
{/* display about us 2 end */}
{this.state.products ? <div id="products" className="">
<h3 className="center-align">AUCTION</h3>
<a className="viewMore" onClick={this.openLogin}>view more</a>
<div className="hideSmall ProductsHere">
{this.state.products.map(n => (
<ProBox
key={n.id}
info={{
name: n.name,
winners: n.winners,
price: n.price,
fortunes: n.tickets,
image: n.picture,
date: n.date,
hour: n.hour,
sold: n.sold,
type: n.type
}}
login={this.openLogin}
check={true}
onFinish={this.openLogin21}
openModl={this.openModalTimer}
closeMdl={this.closeModalHanlder}
/>
))}
</div>
<div className="hideBig">
<Slider
timer={this.state.timming}
displayIn={this.state.products.map(n => (
<ProBox
key={n.id}
info={{
name: n.name,
winners: n.winners,
price: n.price,
fortunes: n.tickets,
image: n.picture,
date: n.date,
hour: n.hour,
sold: n.sold,
type: n.type
}}
openModalaSec={this.openSHare}
login={this.openLogin}
check={true}
onFinish={this.openLogin21}
openModl={this.openModalTimer}
closeMdl={this.closeModalHanlder}
/>
))}
/>
</div>
</div> : <Loader type="circle" style="preloader-wrapper large active"/>}
{this.state.winners ? <div className="winners">
<h3 className="center-align">WINNERS</h3>
<a className="viewMore" onClick={this.openLogin}>view more</a>
<div className="hideSmall ProductsHere">
{this.state.winners.map(n => (
<WinerBox
key={n.id}
info={{
winners: n.id,
names: n.name,
wonfor : n.product,
image: n.picture,
location: n.location,
description: n.quote,
price: n.price,
audio: n.audion,
video: n.video
}}
openModl={this.openModalTimer}
closeMdl={this.closeModalHanlder}
/>
))}
</div>
<div className="hideBig">
<Slider
timer={this.state.timming}
displayIn={this.state.winners.map(n => (
<WinerBox
key={n.id}
info={{
winners: n.id,
names: n.name,
wonfor : n.product,
image: n.picture,
location: n.location,
description: n.quote,
price: n.price,
audio: n.audion,
video: n.video
}}
openModl={this.openModalTimer}
closeMdl={this.closeModalHanlder}
/>
))}
/>
</div>
</div> : <Loader type="circle" style="preloader-wrapper large active"/>}
{/* <img src={PayMentOpt} width="100%" alt=""/> */}
<Footer
openTerms={this.openTerms}
openRef={this.openRef}
openAbout={this.openAbout2}
openPrivacy={this.openPrivacy}
openVend1={this.openAbout}
openVend={this.openVend}
/>
<ModalTerms
style={{
overlay: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0, 0, 0, 0.404)'
},
content: {
position: 'absolute',
top: '5%',
left: '2%',
right: '2%',
bottom: '5%',
border: '1px solid #fff',
background: '#fff',
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
borderRadius: '5px',
outline: 'none',
padding: '20px'
}
}}
isOpen={this.state.openedModal} onRequestClose={() => this.setState({openedModal : false})}
>
<div>
<div className="fixed-action-btn">
<a className="btn-floating black" onClick={() => this.setState({openedModal : false})}>
<i className="material-icons">clear</i>
</a>
</div>
{this.state.showInfo}
</div>
</ModalTerms>
<Modal
style={{
overlay: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0, 0, 0, 0.304)'
},
content: {
position: 'absolute',
top: '20%',
left: '10%',
right: '10%',
height: "100px",
border: '1px solid #fff',
background: '#fff',
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
borderRadius: '10px',
outline: 'none',
padding: '30px'
}
}}
isOpen={this.state.modalShare} onRequestClose={() => {
this.setState({ modalShare: false})
if(typeof this.props.closeMdl == "function") {
this.props.closeMdl()
}
}
}>
<div className="fixed-action-btn">
<a className="btn-floating black" onClick={
() => {
this.setState({ modalShare: false})
}
}>
<i className="material-icons">clear</i>
</a>
</div>
{/* https://telegram.me/share/url?url=<URL><TEXT></TEXT> */}
<div className="picturesShare">
<a href="#" target="_blank"
onClick={() => {
window.open(
'https://telegram.me/share/url?url='+location.href + "&text=" + " Never has such a global guarantee platform been made that enables you to have the opportunity to get your heart wishes for as low as $1.Don’t Miss out! Check it out now!" + " " )
return false;}}>
<img src={Tel} width="35px" height="35px" alt=""/>
</a>
<a href="#" target="_blank"
onClick={() => {
window.open(
'whatsapp://send?text='+ " Never has such a global guarantee platform been made that enables you to have the opportunity to get your heart wishes for as low as $1.Don’t Miss out! Check it out now!" + " " + encodeURIComponent(location.href))
return false;}}>
<img src={WhatsApp} width="35px" height="35px" alt=""/>
</a>
<a href="#" target="_blank"
onClick={() => {
window.open(
'https://www.facebook.com/sharer/sharer.php?u='+" Never has such a global guarantee platform been made that enables you to have the opportunity to get your heart wishes for as low as $1.Don’t Miss out! Check it out now!" + " " + comencodeURIComponent(location.href),
'facebook-share-dialog',
'width=626,height=436')
return false;}}>
<img src={Fb} width="35px" height="35px" alt=""/>
</a>
<a href="#" target="_blank"
onClick={() => {
window.open(
'https://www.instagram.com/?url='+ " Never has such a global guarantee platform been made that enables you to have the opportunity to get your heart wishes for as low as $1.Don’t Miss out! Check it out now!" + " " +encodeURIComponent(location.href))
return false;}}
>
<img src={Ig} width="35px" height="35px" alt=""/>
</a>
</div>
</Modal>
</React.Fragment> : <div className="homeform">
<Form
clecked={func} sign={func2}
>
{CurrentForm}
</Form>
</div>
}
</React.Fragment>
: <About type={this.state.aboutType} click={() => this.openAbout(null)} openRequest={this.openRequest}/>} </React.Fragment>)
}
}
export default Landing; |
//Módulo para modelo './palpite-megasena.model'
module.exports.modelo = {
PalpiteMegasena: require('./palpite-megasena.model'),
} |
'use strict';
/**
* @ngdoc function
* @name newCard1App.controller:HeaderCtrl
* @description
* # HeaderCtrl
* Controller of the newCard1App
*/
angular.module('newCart').controller('HeaderCtrl', function($window,$scope, authToken) {
$scope.isAuthenticated = authToken.isAuthenticated;
});
|
export class PortMapping {
constructor(externalPort, internalPort) {
if (internalPort === undefined && typeof externalPort === 'string') {
const splittedPorts = externalPort.split(':');
if (splittedPorts.length === 2) {
this._externalPort = String(splittedPorts[0] || "");
this._internalPort = String(splittedPorts[1] || "");
} else if (splittedPorts.length === 1) {
this._externalPort = "";
this._internalPort = String(splittedPorts[0] || "");
}
} else {
this._externalPort = String(externalPort || "");
this._internalPort = String(internalPort || "");
}
const isExternalPortRange = (this.getExternalPort() || "").indexOf('-') !== -1;
const isInternalPortRange = (this.getInternalPort() || "").indexOf('-') !== -1;
if (this.getInternalPort() && this.getExternalPort() && (isExternalPortRange && !isInternalPortRange || !isExternalPortRange && isInternalPortRange)) {
throw new Error();
}
if (isExternalPortRange) {
const split = this.getExternalPort().split("-");
if (+split[0] >= +split[1]) {
throw new Error(`External port range is malformed! ${this.getExternalPort()}`);
}
}
if (isInternalPortRange) {
const split = this.getInternalPort().split("-");
if (+split[0] >= +split[1]) {
throw new Error(`External port range is malformed! ${this.getInternalPort()}`);
}
}
}
getExternalPort() {
return this._externalPort;
}
setExternalPort(port) {
this._externalPort = port;
}
getInternalPort() {
return this._internalPort;
}
setInternalPort(port) {
this._internalPort = port;
}
toString() {
return [this.getExternalPort(), this.getInternalPort()].filter(p => p.length > 0).join(':');
}
static fromJSON(json) {
return Object.assign(new PortMapping(), json);
}
}
|
import React from 'react';
const ButtonStyles = () => (
<div>
<div className="header">
<h4 className="title">Styles</h4>
</div>
<div className="content buttons-with-margin">
<button className="btn btn-wd">Default</button>
<button className="btn btn-fill btn-wd">Fill</button>
<button className="btn btn-fill btn-rectangle btn-wd">Fill + Rectangle</button>
<button className="btn btn-rectangle btn-wd">Rectangle</button>
<button className="btn btn-simple btn-wd">Simple</button>
</div>
</div>
);
export default ButtonStyles; |
"use strict";
import React from "react";
import Input from "./common/textInput";
import Homepage from "./homePage";
export default class savePlaylist extends React.Component {
constructor(props) {
super(props);
this.state = {
userInput: null
};
this._onChange = this._onChange.bind(this);
this._onClick = this._onClick.bind(this);
}
_onChange(event){
const userInput = event.target.value;
this.setState({userInput: userInput});
}
_onClick(){
if(this.state.userInput){
this.props.handler(this.state.userInput);
}
}
resetHandler(){
// this.input.click
location.reload();
}
render() {
return (
<div id="playlist">
<Input label="Playlist Name" width="480" name="playlistName" onChange={this._onChange.bind(this)} value={this.state.userInput}/>
<a href="#" onClick={this._onClick} className="button" style={{backgroundColor: "#5cb85c"}}>Save Playlist to Your Spotify Account</a>
<br></br>
<a href="#" onClick={this.resetHandler} className="button" style={{backgroundColor: "#5cb85c"}}>Make a New Playlist!</a>
</div>
);
}
}
|
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Gallery from './Gallery'
function App() {
return (
<Router>
<Switch>
<Route exact path='/'>
<Home />
</Route>
<Route path='/about'>
<About />
</Route>
{/* <Route path='*'>
<Error />
</Route> */}
<Route path='/gallery'>
<Gallery />
</Route>
</Switch>
</Router>
);
}
export default App;
|
import React, {Component} from 'react';
import {NavLink} from 'react-router-dom';
import axios from 'axios';
class Task extends Component {
updateStatus(id, status, index) {
const TASKS_URL = 'http://localhost:8000/api/v1/tasks/';
let new_status;
if (status === "backlog") {
new_status = "in progress"
}
else if (status === "in progress" && index === 1) {
new_status = "done"
}
else if (status === "in progress" && index === -1) {
new_status = "backlog"
}
else if (status === "done") {
new_status = "in progress"
}
axios
.patch(TASKS_URL + id + "/", {
'status': new_status
})
.then(response => {
console.log(response.data);
this.props.updateBoard();
return response.data;
})
.catch(error => console.log(error));
}
deleteTask(id) {
const TASKS_URL = 'http://localhost:8000/api/v1/tasks/';
axios.delete(TASKS_URL + id, {}).then(response => {
console.log(response.data);
this.props.updateBoard();
return response.data;
}).catch(error => console.log(error));
}
render() {
const link = "/task/" + this.props.task.id;
const link_edit = '/tasks/edit/' + this.props.task.id;
return (
<div className="card mb-1">
<div className="card-body">
<h5 className="card-title">{this.props.task.summary}</h5>
<h6 className="card-subtitle mb-2 text-muted">{this.props.task.status_display}</h6>
<p className="card-text">{this.props.task.description}</p>
<NavLink className="nav-link" to={link}>Подробнее</NavLink>
<NavLink className="nav-link" to={link_edit}>Редактировать</NavLink>
{this.props.task.status === "backlog" && <i className="fas fa-arrow-right m-1"
onClick={() => (this.updateStatus(this.props.task.id, this.props.task.status, 1))}/>}
{this.props.task.status === "in progress" &&
<div>
<i className="fas fa-arrow-left m-1"
onClick={() => (this.updateStatus(this.props.task.id, this.props.task.status, -1))}/>
<i className="fas fa-arrow-right m-1"
onClick={() => (this.updateStatus(this.props.task.id, this.props.task.status, 1))}/>
</div>}
{this.props.task.status === "done" && <i className="fas fa-arrow-left"
onClick={() => (this.updateStatus(this.props.task.id, this.props.task.status, -1))}/>}
<i className="fas fa-trash-alt m-1" onClick={() => (this.deleteTask(this.props.task.id))}></i>
</div>
</div>
)
}
}
export default Task; |
/*global Harpy, $harpy*/
Harpy.harpify = function($harpy) {
function createStatConfig() {
var stats = {
time : {
blocked : 0,
dns : 0,
connect : 0,
send : 0,
wait : 0,
receive : 0
},
type : {
image : 0,
html : 0,
js : 0,
css : 0,
text : 0,
other : 0
},
uncached : {
image : 0,
html : 0,
js : 0,
css : 0,
text : 0,
other : 0
},
size : {
cache : 0,
download : 0
},
requests : {
cached : 0,
uncached : 0
},
timing : {
onContentLoad : 0,
onLoad : 0,
total : 0
}
};
return stats;
}
function harpify(har) {
var entryCache = {};
var stats = createStatConfig();
var time = har.log.pages[0].pageTimings;
stats.timing.onLoad = time.onLoad;
stats.timing.total = time.onLoad;
stats.timing.onContentLoad = time.onContentLoad || time.onLoad;
var startTime = new Date(har.log.pages[0].startedDateTime);
var i, entry, url, type, endTime, x, domain, source, urlDomain, redirect;
for(i=0; i<har.log.entries.length; i++) {
entry = har.log.entries[i];
url = entry.request.url;
try {
urlDomain = url.split("://")[1].split("/")[0];
} catch (e) {
urlDomain = "";
}
redirect = (Number(entry.response.status) === 301 || Number(entry.response.status) === 302);
if(!domain && !redirect) {
domain = urlDomain;
}
if(urlDomain === domain) {
source = "identical";
} else if(redirect || (domain && urlDomain.indexOf(domain.substr(domain.indexOf("."))) !== -1)) {
source = "internal";
} else {
source = "external";
}
entry.harpy_info = {};
entryCache[i] = entry;
entry.harpy_info.source = source;
if(i>0) {
url = url.replace(har.log.entries[0].request.url,"");
}
type = $harpy.util.getMimetype(entry.response.content.mimeType);
endTime = new Date(entry.startedDateTime).getTime() + entry.time;
if(endTime > startTime.getTime() + time.total) {
stats.timing.total = endTime - startTime;
}
for(x in entry.timings) {
if(entry.timings.hasOwnProperty(x)) {
if( entry.timings[x] > 0) {
stats.time[x] += entry.timings[x];
}
}
}
stats.type[type] += entry.response.bodySize;
stats.uncached[type] += entry.response.bodySize;
stats.size.download += entry.response.bodySize;
entry.harpy_info.index = i+1;
entry.harpy_info.url = url;
entry.harpy_info.mimetype = type;
if(entry.response.status === '(cache)') {
entry.harpy_info.cache = "cache";
stats.requests.cached += 1;
} else {
stats.requests.uncached += 1;
if(Number(entry.response.status) > 399) {
entry.harpy_info.error = 'error';
} else if(Number(entry.response.status) === 304) {
entry.harpy_info.cache = "cache";
}
}
if(entry.cache.hasOwnProperty('afterRequest')) {
stats.size.cache += entry.response.content.size;
stats.type[type] += entry.response.content.size;
entry.harpy_info.size = entry.response.content.size;
} else {
entry.harpy_info.size = entry.response.bodySize;
}
entry.harpy_info.startTime = new Date(entry.startedDateTime) - startTime;
entry.harpy_info.endTime = entry.harpy_info.startTime + entry.time;
}
var harpy_info = {};
harpy_info.time = stats.timing;
harpy_info.size = stats.size;
har.log.pages[0].harpy_info = harpy_info;
return {
har : har,
stats : stats,
entryCache : entryCache
};
}
return harpify;
}; |
import Vue from 'vue'
import RightSideMenuPanel from './RightSideMenuPanel.vue';
function open(propsData) {
const DialogComponent = Vue.extend(RightSideMenuPanel);
return new DialogComponent({
el: document.createElement('div'), propsData
});
}
export default {
View(data){
let propData = {
selectedAccount: data.selectedAccount,
selectedItems: data.selectedItems
}
return open(propData)
}
} |
const passport = require("passport");
class UserController {
constructor(userService) {
this.userService = userService;
}
async getUser(req, res) {
const { limit } = req.query;
const limitToNumber = parseInt(limit);
const query = await this.userService.getUser(limitToNumber);
res.send(query);
}
async getUserById(req, res) {
const { id } = req.params;
const query = await this.userService.getUserById(id);
res.send(query);
}
async addUser(req, res) {
const { body } = req;
const { name, password, isAdmin } = body;
const checkUser = await this.userService.checkUser(name);
if (name && password) {
if (checkUser != true) {
try {
const query = await this.userService.addUser(body);
res.status(200).send("Registro cargado con éxito");
} catch (error) {
res.status(500).send("Error al agregar");
}
} else {
res.status(400).send("El usuario ya existe");
}
} else {
res.status(400).send("Faltan ingresar campos obligatorios");
}
}
async editUser(req, res) {
const { body } = req;
const { id } = req.params;
if (id.length === 24) {
const checkUserId = await this.userService.checkUserId(id);
if (checkUserId === true) {
if (body) {
try {
const query = await this.userService.editUser(id, body);
res.status(200).send("Usuario actualizado exitosamente");
} catch (error) {
res.status(500).send("Error al actualizar");
}
} else {
res.status(400).send("Ingrese algún dato para modificar");
}
}
}
return res.status(400).send("No existe el id");
}
async deleteUser(req, res) {
const { id } = req.params;
if (id.length === 24) {
const checkUserId = await this.userService.checkUserId(id);
if (checkUserId === true) {
try {
const query = await this.userService.deleteUser(id);
res.status(200).send("Registro borrado exitosamente");
} catch (error) {
res.status(500).send("Error al borrar el registro");
}
} else {
res.status(400).send("El id ingresado no existe");
}
} else {
res.status(400).send("El id ingresado no existe");
}
}
}
module.exports = UserController;
|
import React from 'react';
import { setup } from 'goober';
import { prefix } from 'goober/prefixer';
setup(React.createElement, prefix);
|
let f_to_c_button = document.getElementById("conversionbutton")
let current_temp_display = document.getElementById("current_temp_degrees")
let f_temp = Number(current_temp_display.textContent)
let convert_f_to_c = function(number) {
return Math.round(((number - 32) * 5) / 9)
}
conversionbutton.addEventListener("click", function() {
current_temp_display.textContent = convert_f_to_c(f_temp) }
)
let r = new XMLHttpRequest()
r.open("GET","http://api.wunderground.com/api/ba5b9bfd895f0fd1/forecast/q/NJ/Union_City.json")
r.send()
r.addEventListener("load", function(){
let p = JSON.parse(r.responseText)
document.getElementById("todays_high").textContent = p.forecast.simpleforecast.forecastday[0].high.fahrenheit
document.getElementById("todays_low").textContent = p.forecast.simpleforecast.forecastday[0].low.fahrenheit
let r2 = new XMLHttpRequest()
r2.open("GET","http://api.wunderground.com/api/ba5b9bfd895f0fd1/conditions/q/NJ/Union_City.json")
r2.send()
r2.addEventListener("load", function(){
let p2 = JSON.parse(r2.responseText)
document.getElementById("current_temp_degrees").textContent = r2.conditions.current_observation.temp_f
})
}
)
|
import React from 'react';
import { Link } from 'react-router-dom';
import styles from './Header.css';
const Header = () => (
<header className={styles.header}>
<div className={styles.container}>
<Link className={styles.logo} to="/dashboard">
<h1>Tournament</h1>
</Link>
<button className={styles.btn}>Logout</button>
</div>
</header>
);
export default Header; |
function startMap() {
const ironhackSAO = {
lat: -23.5617375,
lng: -46.6623218
};
// Centralizar o mapa
const map = new google.maps.Map(
document.getElementById('map'),
{
zoom: 8,
center: ironhackSAO
}
);
// Marcações no mapa
const myMarker = new google.maps.Marker({
position: ironhackSAO,
map: map,
title: "I'm here"
});
if (navigator.geolocation) {
// Get current position
// The permissions dialog will pop up
navigator.geolocation.getCurrentPosition(function (position) {
// Create an object to match Google's Lat-Lng object format
const myNotebookPosition = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
new google.maps.Marker({
position: myNotebookPosition,
map: map,
title: "I'm here"
});
// User granted permission
// Center the map in the position we got
}, function () {
// If something goes wrong
console.log('Error in the geolocation service.');
});
const directionsService = new google.maps.DirectionsService;
const directionsDisplay = new google.maps.DirectionsRenderer;
const directionRequest = {
origin: ironhackSAO,
destination: 'Rua dom bosco, 206, Mooca',
travelMode: 'WALKING'
};
directionsService.route(
directionRequest,
function(response, status) {
if (status === 'OK') {
// everything is ok
directionsDisplay.setDirections(response);
} else {
// something went wrong
window.alert('Directions request failed due to ' + status);
}
}
);
directionsDisplay.setMap(map);
} else {
// Browser says: Nah! I do not support this.
console.log('Browser does not support geolocation.');
}
}
startMap(); |
const formReceta = document.getElementById('formReceta');
formReceta.addEventListener('submit', submit);
async function submit(evt) {
const path = (location.pathname + location.search).substr(1);
evt.preventDefault();
let seleccionados = document.querySelectorAll('input');
const medicamentos = [];
for (const medicamento of seleccionados) {
if (medicamento.checked)
medicamentos.push(medicamento.id);
}
const response = await fetch(`/${path}`,
{
method: 'POST',
body: JSON.stringify({
medicamentos
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}
);
const data = await response.json();
console.log(data['status'])
if (data['status'] == 201)
location.href = '/lista_pacientes'
} |
var POPULATION = []
var RANKS = []
var BEST = []
function generate(){
var new_population = []
var sum = 0
var max = 0
var min = 1
//first iteration
if(POPULATION.length == 1){
for(var i = 0; i < M - 1; i++){
var blank_child = new Chromosome(true)
for (var j = 0; j < N; j++) {
blank_child.schedule_numbers.push(INIT_SOLN.schedule_numbers[j].map((sched_no) => sched_no))
}
blank_child.refreshLifetimeAndCoverage()
blank_child.applyMutation()
blank_child.refreshLifetimeAndCoverage()
blank_child.calculateFitness()
new_population.push(blank_child)
sum += blank_child.fitness
if (blank_child.fitness > max) {
max = blank_child.fitness
}
if (blank_child.fitness < min) {
min = blank_child.fitness
}
}
}else{
//all other iterations
for(var i = 0; i < M - M*0.2; i++){
var parentA = RANKS[getRandomInt(0, (RANKS.length / 1.5) - 1)]
var parentB = RANKS[getRandomInt(0, (RANKS.length / 1.5) - 1)]
var a_rank = RANKS.length - RANKS.indexOf(parentA)
var b_rank = RANKS.length - RANKS.indexOf(parentB)
var blank_child = new Chromosome(true)
var parentAThreshold = a_rank / (a_rank + b_rank)
for (var j = 0; j < N; j++){
if(Math.random() < parentAThreshold){
blank_child.schedule_numbers.push( parentA.schedule_numbers[j].map((sched_no) => sched_no) )
}else{
blank_child.schedule_numbers.push( parentB.schedule_numbers[j].map((sched_no) => sched_no) )
}
}
blank_child.refreshLifetimeAndCoverage()
blank_child.applyMutation()
blank_child.refreshLifetimeAndCoverage()
blank_child.calculateFitness()
new_population.push(blank_child)
sum += blank_child.fitness
if (blank_child.fitness > max){
max = blank_child.fitness
}
if (blank_child.fitness < min){
min = blank_child.fitness
}
}
}
POPULATION = new_population
calculateRank()
console.warn("AVG: "+ sum/M)
console.warn("MAX: "+ max)
console.warn("MIN: "+ min)
}
function calculateRank(){
//first iteration mein skip
if(BEST.length > 0){
POPULATION.push( ...BEST )
}
RANKS = POPULATION.map( (val)=>val )
RANKS.sort( (a, b)=>a.fitness>b.fitness )
RANKS.splice(M, RANKS.length - M)
POPULATION.splice(M, POPULATION.length - M)
BEST = []
for(var i = 0; i < M*0.2; i++){
BEST.push(RANKS[i])
}
}
function generation_controller(){
generate()
// stats nikalo population ke in future
}
|
// Redux
import { applyMiddleware, combineReducers, createStore } from 'redux'
import { createLogger } from 'redux-logger'
// Navigation
import { PilotTab } from './screens/Pilot/navigationConfig';
import { PilotsTab } from './screens/Pilots/navigationConfig';
import { TabBar, tabBarReducer } from './screens/TabBar/TabBar';
// Middleware
const middleware = () => {
return applyMiddleware(createLogger())
}
export default createStore(
combineReducers({
tabBar: tabBarReducer,
pilotTab: (state,action) => PilotTab.router.getStateForAction(action,state),
pilotsTab: (state,action) => PilotsTab.router.getStateForAction(action,state),
pilotActive: (state = false, action) => {
if(action.type === 'PILOT_STATUS') {
return ! state;
}
return state;
},
airSpace: (state = true, action) => {
if(action.type === 'AIR_SPACE_STATUS') {
return ! state;
}
return state;
},
loggedIn: (state = false, action) => {
if(action.type === 'LOG_IN_USER') {
return true;
}
if(action.type === 'LOG_OUT_USER') {
return false;
}
return state;
},
}),
middleware(),
)
|
(function () {
'use strict';
angular.module('products', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/products', {
templateUrl: 'modules/products/views/products.list.html',
controller: 'ProductsCtrl',
controllerAs: 'vm'
}).when('/products/new', {
templateUrl: 'modules/products/views/product.new.html',
controller: 'ProductsCtrl',
controllerAs: 'vm'
});
}])
}()); |
const path = require('path');
const webpack = require('webpack');
module.exports = function (config) {
var confBuilder = require('./webpack.config.template');
confBuilder.module.loaders.push({
test: /\.jsx$/,
loader: 'isparta',
include: path.resolve('src'),
});
confBuilder.devtool = 'inline-source-map';
config.set({
browsers: ['Chrome'],
singleRun: true,
frameworks: ['mocha', 'chai-spies', 'chai'],
files: [
'tests.webpack.js',
],
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap'],
},
reporters: ['mocha', 'coverage', 'jenkins'],
plugins: [
require('karma-webpack'),
require('karma-mocha'),
require('karma-chai'),
require('karma-chai-spies'),
require('karma-mocha-reporter'),
require('karma-jenkins-reporter'),
require('karma-chrome-launcher'),
require('karma-sourcemap-loader'),
require('karma-coverage'),
],
webpack: confBuilder,
webpackServer: {
noInfo: true,
},
coverageReporter: {
check: {
global: {
statements: 86,
branches: 80,
functions: 95,
lines: 40,
},
},
}
});
};
|
// if (2==3) {
// document.write("I love hot pockets!");
// }else {
// document.write("I love strawberries!");
// }
//
//
// function hiLowGame() {
// var randomNumber = Math.floor((Math.random()*100)+1);
// var guessedNumber = prompt("Enter Your Guess...if you Dare...");
// return [guessedNumber, randomNumber];
// }
//
//
// function hiLowGame() {
// var randomNumber = function() {
// return Math.floor((Math.random()*100)+1);
// }
// var guessedNumber = function() {
// return prompt ("Enter Your Guess...");
// }
// }
v------------Real Code------------v
//Declares Name, Random#, and Guessed# Variables
var name = "0";
var randomNumber = 0;
var guessedNumber = 0;
//function that asks for user name and generates random number between 1-100
function hiLowGame() {
name = prompt("Enter Your Name:");
randomNumber = Math.floor((Math.random()*100)+1);
//prompts user for a guess and stores guess as a string
guessedNumber = prompt("Alright " + name + " enter your guess...if you dare...");
//returns name, randomNumber and guessNumber as [string, string, number]
//return [name, randomNumber, guessedNumber];
while (randomNumber){
if (randomNumber == guessedNumber) {
prompt ("Congragulations " + name + " You Won!!! The Secret Number was " + randomNumber + "!!!");
break;
}
else if (randomNumber > guessedNumber) {
guessedNumber = prompt ("Too Low...Try Again...");
}
else if (randomNumber < guessedNumber) {
guessedNumber = prompt ("Too High...Try Again...");
}
else {
guessedNumber = prompt ("Im Sorry, You Can Only Input Numbers...Try Again...");
}
}
}
^----------Real Code--------------^
Hi/Lo Game Challenge
Create a function that plays the following game:
* The computer picks a secret random integer between 1 and 100 (both inclusive), and
* repeatedly asks the user for guesses.
* the computer notifies them If the users guess is too high or too low, ; and
* if the user guesses the secret number correctly, the computer displays a winning message and the game is over.
* Stretch goal 1: If the user has not guessed the secret number in seven tries, the user loses.
* Stretch goal 2: Validate the users input. If the user puts a anything other than a number, tell the user they can only use numbers,
* Stretch goal 3: Allow the user to put there name in before the game starts. When the user has won the game, let the user know they have won, using their name.
|
import Vue from 'vue'
import Vuex from 'vuex'
import Http from '../utils/Http'
import api from '../utils/api'
import moments from './moments'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
isLogin: false,
userInfo: {},
starUsers: []
},
mutations: {
setLogin(state, payload){
state.isLogin = payload;
},
setStarUsers(state, payload){
state.starUsers = payload;
},
setUserInfo(state,userinfo){
state.userInfo = userinfo
}
},
actions: {
async requestStars(context){
try {
var result = await Http.get(api.STAR_USERS);
if (result.data.status==0) {
// 假设是请求成功的数据
var data = result.data.data;
context.commit('setStarUsers', data);
}
} catch (error) {
throw new Error(error);
}
},
// 获取用户名
async requestUserInfo(context){
try {
var result = await Http.get(api.REQUEST_USERINFO);
// console.log("获得用户",result);
if (result.data.status==0) {
var data = result.data.data;
// console.log(data);
context.commit('setUserInfo', data);
}
} catch (error) {
throw new Error(error);
}
},
},
modules: {
moments
}
})
|
var document = window.document;
function signupCheck() {
var username = document.getElementById("usernameInput").value;
var email = document.getElementById("emailInput").value;
var password = document.getElementById("passwordInput").value;
var conPass = document.getElementById("confirmPass").value;
if(password === conPass) {
signupPost(username, email, password);
}
else {
alert("Passwords do not match!")
}
}
function signupPost(username, email, password) {
var url = "http://fa19server.appspot.com/api/Users";
var okay = true;
var userBody = '';
userBody = userBody.concat("username=", username);
var emailBody = '';
emailBody = emailBody.concat("email=", email);
var passBody = '';
passBody = passBody.concat("password=", password);
var data = '';
data = data.concat(userBody, "&", emailBody, "&", passBody);
//Refrenced primarily from developers.google.com
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: data
})
.then(function(response) {
if (!response.ok) {
console.log("NOT OKAY");
okay = false;
}
return response.json();
})
.then(function(myJson) {
if (!okay) {
var errTexts = '';
var alMessages = myJson.error.details.messages;
for(var i in alMessages) {
errTexts = errTexts.concat(i, ": ", alMessages[i], "\n")
}
alert(errTexts);
}
else {
window.location.href = '../public/login.html';
}
//console.log(myJson);
});
} |
import React from 'react'
import Modal from "react-bootstrap/Modal";
import Button from "react-bootstrap/Button";
export default function ModalEmail({ show, onHandleClose, chosenEmail }) {
return (
<div>
<Modal show={show} onHide={onHandleClose} animation={false}>
<Modal.Header closeButton>
<Modal.Title>Gravatar Modal</Modal.Title>
</Modal.Header>
<Modal.Body>{chosenEmail}</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={onHandleClose}>
Close
</Button>
</Modal.Footer>
</Modal>
</div>
)
}
|
import { gql } from "apollo-server";
export const typeDef = gql`
extend type Query {
getRoles: [Role!]
}
extend type Mutation {
addRole(rolType: String!): Role
}
type Role {
id: ID!
rolType: String!
}
`;
|
// 初始化一个 WebSocket 对象
var ws = new WebSocket("ws://s.hackcoll.com:3334/ctf_channels");
// 建立 web socket 连接成功触发事件
ws.onopen = function () {
// 使用 send() 方法发送数据
ws.send("发送数据");
$('body').append('<div class="msg-tip-box" id="msg-tip-box">');
console.log("数据发送中...");
};
// 接收服务端数据时触发事件
ws.onmessage = function (e) {
// var received_msg = e.data;
console.log("数据已接收...");
try {
var message = JSON.parse(e['data']);
if ('event' in message && message['event'] in events_functions) {
events_functions[message['event']](message);
}
}catch (e) {
}
};
// 断开 web socket 连接成功触发事件
ws.onclose = function () {
console.log("连接已关闭...");
};
/**
* 不同的事件不同的处理
* @type {{CHALLENGE_SOLVED: events_functions.CHALLENGE_SOLVED, JOIN_REQUEST: events_functions.JOIN_REQUEST, JOIN_REQUEST_APPROVED: events_functions.JOIN_REQUEST_APPROVED, JOIN_REQUEST_REJECTED: events_functions.JOIN_REQUEST_REJECTED, JOIN_REQUEST_DELETED: events_functions.JOIN_REQUEST_DELETED, GAME_START: events_functions.GAME_START, GAME_PAUSE: events_functions.GAME_PAUSE, GAME_RESUME: events_functions.GAME_RESUME, GAME_END: events_functions.GAME_END}}
*/
var events_functions = {
ROUTINE_NOTICE: function(message){ //普通信息
createNewNotification(
message.message
);
},
ROUTINE_NOTICE_WARNING : function(message){ //警告
createNewNotification(
message.message,
'warning'
);
},
JOIN_REQUEST_APPROVED: function(message){ //有队友加入
createNewNotification(
message.message
);
}
};
/**
* 弹框
* @param title 标题
* @param text 内容
* @param type 类型 1.success:成功 2.warning: 警告 3. error 错误
*/
function createNewNotification(text, type='success'){
creatTip(text, type);
}
/**
* 创建弹窗
* @param text
* @param type
*/
function creatTip(text, type) {
var content = '';
switch (type) {
case "success":
content = ' <div style="display: block !important;" class="msg-con1 effect-hidden j-msg-con j-msg-putong">\n' +
' <p class="tip-title"><em></em>成功通知</p>\n' +
' <div class="cont">'+text+'</div>\n' +
' <div class="end">我知道了</div>\n' +
'</div>';
break;
case "warning":
content = ' <div style="display: block !important;" class="msg-con1 effect-hidden j-msg-con j-msg-warning">\n' +
' <p class="tip-title"><em></em>警告通知</p>\n' +
' <div class="cont">'+text+'</div>\n' +
' <div class="end">我知道了</div>\n' +
'</div>';
break;
case "error":
content = ' <div style="display: block !important;" class="msg-con1 effect-hidden j-msg-con j-msg-putong">\n' +
' <p class="tip-title"><em></em>错误通知</p>\n' +
' <div class="cont">'+text+'</div>\n' +
' <div class="end">我知道了</div>\n' +
'</div>';
break;
}
if($('#msg-tip-box').length == 0){
$('body').append('<div class="msg-tip-box" id="msg-tip-box">');
}
$('div#msg-tip-box').append(content);
window.setTimeout(function () {
$('div#msg-tip-box .j-msg-putong:first-child').remove();
}, 1000)
}
/**
* 关闭右上角信息框
*/
$(function () {
$("body").on('click', '.j-msg-con .end', function(event) {
$(this).parent('.j-msg-con').remove();
if($('body #msg-tip-box').find('.msg-con1').length == 0){
$('body #msg-tip-box').remove();
}
});
})
var removeTime = window.setInterval(function () {
try {
$('div#msg-tip-box').find('.j-msg-putong')[0].remove();
}catch (e) {
window.clearInterval(removeTime);
}
if($('body #msg-tip-box').find('.msg-con1').length == 0){
$('body #msg-tip-box').remove();
}
}, 2000)
|
function passSelected(listFrom, listTo, clone, notDuplicate) {
if (!listIsEmpty(listFrom)) { return false; }
listSelected(listFrom);
if(!listFrom.disabled && !listTo.disabled) {
for (i=0; i < listFrom.options.length; i++) {
if (listFrom.options[i].selected) {
if (notDuplicate) {
if (searchText(listTo, listFrom.options[i].text)) {
alert('A lista de destino não pode ter ítens repetidos.');
return false;
}
}
var op = document.createElement("OPTION");
op.text = listFrom.options[i].text;
op.value = listFrom.options[i].value;
listTo.options.add(op);
if (!clone) {
listFrom.options[i] = null;
i--;
}
}
}
}
}
function passAll(listFrom, listTo, clone, notDuplicate) {
listIsEmpty(listFrom);
if(!listFrom.disabled && !listTo.disabled){
for(i=0; i < listFrom.options.length; i++) {
if (notDuplicate) {
if (searchText(listTo, listFrom.options[i].text)) {
alert('A lista de destino não pode ter ítens repetidos.');
return false;
}
}
var op = document.createElement("OPTION");
op.text = listFrom.options[i].text;
op.value = listFrom.options[i].value;
listTo.options.add(op);
if (!clone) {
listFrom.options[i] = null;
i--;
}
}
}
}
function deleteList(list) {
if (!listIsEmpty(list)) { return false; }
arraySelected = listSelected(list);
for(i=arraySelected.length-1; i >= 0; i--) {
list.options.remove(arraySelected[i]);
}
}
function listIsEmpty(list) {
if (!list.length) {
return alert("A lista está vazia.");
}
return true;
}
function listSelected(list) {
var listSelected = new Array();
for(i=0; i < list.options.length; i++) {
if (list.options[i].selected) {
listSelected.push(i);
}
}
return listSelected;
}
function addOption(objSelect, objOption){
objSelect.options[objSelect.options.length] = objOption;
}
function searchText(list, string) {
var encontrou = false;
for(sL=0; sL < list.options.length; sL++) {
if (list.options[sL].text == string) {
encontrou = true;
break;
}
}
return encontrou;
} |
var app = getApp();
Component({
properties: {
top: {
type: String,
value: app.globalData.navigationCustomStatusHeight + app.globalData.navigationCustomCapsuleHeight
},
type: {
type: String,
value: ""
}
},
data: {
bgOpacity: 0,
top: app.globalData.navigationCustomStatusHeight + app.globalData.navigationCustomCapsuleHeight + 100
},
methods: {
showMenu: function showMenu() {
this.setData({
flag: true,
wrapAnimate: "wrapAnimate",
menuAnimate: "menuAnimate"
});
},
hideMenu: function hideMenu(e) {
var that = this;
that.setData({
wrapAnimate: "wrapAnimateOut",
menuAnimate: "menuAnimateOut"
});
setTimeout(function() {
that.setData({
flag: false
});
}, 400);
},
catchNone: function catchNone() {
//阻止冒泡
},
_hideEvent: function _hideEvent(e) {
this.triggerEvent("hideEvent", e.currentTarget.dataset.type);
}
}
}); |
// declare variables
var firstName;
var lastName;
var massiveArray = [];
function getRandom(min,max){
var random = Math.floor(Math.random() * (max - min)) + min;
return random;
}
// function for first names
function getFirstName(num){
var firstNames = ["Joe","Mary","Sue","Jose","Brad","John","Kate","Malik","Bianca","Jason"];
return firstNames[num];
}
// function for last names
function getLastName(num){
var lastNames = ["Brown","Garcia","Smith","Jackson","Lee","Chang","Jones","Young","Reed","Chavez"];
return lastNames[num];
}
// constructor for name objects
function NameObject(first,last){
this.firstName = first;
this.lastName = last;
}
// nested loop to create multi-dimensional array
for(var i = 0; i < 4; i++){
massiveArray[i] = [];
for(var j = 0; j < 250; j++){
firstName = getFirstName(getRandom(0,9));
lastName = getLastName(getRandom(0,9));
massiveArray[i].push(new NameObject(firstName,lastName));
}
}
|
import PostRepository from 'models/repositories/PostRepository'
import { UserServiceFactory } from 'models/services'
import { setCollectionOwner, getSimpleOwner } from 'helpers/utils'
export default class PostService {
constructor({ postRepository, userService }) {
this.postRepository = postRepository
this.userService = userService
}
getPost = async postId => {
return await this.postRepository.getPost(postId)
}
getPostByGroupId = async (groupId, { lastId, recordCount }) => {
let query = { groupId: groupId }
if (lastId) {
query = Object.assign(query, { _id: { $lt: lastId } })
}
try {
const posts = await this.postRepository.getPostsByGroupId(
query,
recordCount
)
return await setCollectionOwner.call(this, posts)
} catch (error) {
throw error
}
}
deletePost(postId) {
return this.postRepository.deletePost(postId)
}
postUserPost = async (userId, groupId, payload) => {
try {
const post = await this.postRepository.insertPost(payload)
const postObj = post.toObject()
postObj.owner = await getSimpleOwner.call(this, post)
return postObj
} catch (error) {
throw error
}
}
deleteUserPost(userId, postId) {
try {
return Promise.all([this.postRepository.deletePost(postId)])
} catch (error) {
throw error
}
}
}
export const PostServiceFactory = () => {
const postRepository = new PostRepository()
return new PostService({ postRepository, userService: UserServiceFactory() })
}
|
function addPromise(a, b) {
return new Promise(function(resolve, reject) {
if (typeof a === 'number' && typeof b === 'number') {
resolve(a + b);
}
else {
reject('Invalid numbers');
}
});
}
function success(num) {
console.log('success', num);
}
function errMsg(err) {
console.log('error', err);
}
addPromise(71, 29).then(success, errMsg);
addPromise(66, 'foo').then(success, errMsg);
|
import React, { Component } from 'react'
import { formateDate } from '../../utils/dataUnlis'
import memoryUntils from '../../utils/memoryUntils'
import { withRouter } from 'react-router-dom';
import storageUntils from '../../utils/storageUntils';
import { message, Modal } from 'antd';
import LinkButton from '../../components/link-button';
import './index.less';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import menuList from '../../config/menuConfig'
//头部导航组件
class Header extends Component {
state = {//初始化时间数据
currentTime: formateDate(Date.now())
}
//退出登录
logout = ()=> {
//从内存中获取username
const username = memoryUntils.user.username
const { confirm } = Modal;
confirm({
title: '确定要退出吗',
icon: <ExclamationCircleOutlined />,
okText:"确定",
cancelText: "取消",
onOk : () => {
//删除location中的数据
storageUntils.removeUser(username)
//删除内存中的数据
memoryUntils.user = {}
//跳转路由到登录界面
this.props.history.push("/login")
message.success("退成成功")
}
});
}
//创建更新时间数据函数
getTime = () => {
//创建定时器
this.timer = setInterval(() => {
const time = formateDate(Date.now())
this.setState({ currentTime: time })
}, 1000)
}
//得到title
getTitle = () => {
//得到当前的路径
const path = this.props.location.pathname
//创建接收的title
let title
//便利所有路径
menuList.forEach(item => {
//判断是否有相同的路径
if (path.indexOf(item.key) === 0) {
title = item.title
} else if (item.children) {
const citem = item.children.find(citem => path.indexOf(citem.key) === 0)
if (citem) {
//如果有citem 取出citem
title = citem.title
}
}
})
//返回title
return title
}
//启动定时器每秒更新时间数据
componentDidMount() {
this.getTime()
}
//组件销毁前 销毁定时器
componentWillUnmount() {
clearInterval(this.timer)
}
render() {
const { currentTime } = this.state
const username = memoryUntils.user.username
const title = this.getTitle()
return (
<div className='header'>
<div className="header-top">
<span>欢迎,{username}</span>
<LinkButton onClick={this.logout}>退出</LinkButton>
</div>
<div className="header-bottom">
<div className="header-bottom-left">
<h1>{title}</h1>
</div>
<div className="header-bottom-center">
{/* 调用和风天气完成天气 */}
<div id="he-plugin-simple" className="header-bottom-right-weather">
</div>
</div>
<div className="header-bottom-right">
<span>{currentTime}</span>
</div>
</div>
</div>
)
}
}
export default withRouter(Header) |
// JavaScript source code
var decP = prompt("To how many decimal places do you wish to see Pi rounded?");
if (decP > 20 || decP === 20) {
decP = 20;
}
var pi = Math.PI.toFixed(20);
var intem = pi * (Math.pow(10,decP));
var rounded = Math.round(intem);
var resultnum = rounded / (Math.pow(10, decP));
var result = String(resultnum);
alert(result);
|
module.exports = {
"extends": [
"airbnb"
],
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 2018,
"ecmaFeatures": {
"impliedStrict": true,
"classes": true
}
},
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"jest": true,
"node": true,
},
"rules": {
"import/no-extraneous-dependencies": 0,
"import/prefer-default-export": 0,
"import/no-named-as-default": 0,
"import/extensions": 0,
"import/order": [ 2, {
"groups": [ "builtin", "external", "parent", "sibling" ],
"newlines-between": "ignore",
} ],
"import/no-absolute-path": 0,
"import/no-unresolved": [ 2, { "ignore": [ "/" ] } ],
"react/sort-comp": 0,
"react/jsx-curly-spacing": [ 2, "always" ],
"react/jsx-first-prop-new-line": 0,
"react/jsx-indent": [ 2, 2 ],
"react/jsx-indent-props": 0,
"react/jsx-filename-extension": 0,
"react/no-did-mount-set-state": 0,
"react/forbid-prop-types": 0,
"react/jsx-tag-spacing": [ 2, { "beforeSelfClosing": "always" } ],
"react/no-danger": 0,
"react/no-find-dom-node": 0,
"jsx-a11y/no-static-element-interactions": 0,
"jsx-a11y/anchor-has-content": 2,
"jsx-a11y/label-has-for": 0,
"jsx-a11y/click-events-have-key-events": 0,
"new-cap": 0,
"arrow-parens": [ "error", "always" ],
"arrow-body-style": 0,
"comma-dangle": [ "error", "always-multiline" ],
"no-unused-expressions": [ "error", { "allowTernary": true } ],
"no-confusing-arrow": 0,
"no-console": [ "error", { "allow": [ "warn", "error", "info" ] } ],
"radix": [ "error", "as-needed" ],
"no-trailing-spaces": [ "error", { "skipBlankLines": true, "ignoreComments": true } ],
"no-multi-spaces": 0,
"object-curly-spacing": [ "error", "always" ],
"global-require": 0,
"linebreak-style": 0,
"class-methods-use-this": 0,
"newline-after-var": [ "error" ],
"newline-before-return": [ "error" ],
"no-underscore-dangle": 0,
"no-plusplus": 0,
"function-paren-newline": 0,
"no-param-reassign": 0,
},
"plugins": [ 'react-hooks' ],
}
|
#! /usr/bin/env node
const inquirer = require('inquirer');
// Helpers
const utils = require('./utils/utils.js');
const helpers = require('./helpers/helpers.js');
// helper pointers
const questions = utils.questions;
const sample_service_worker_config = helpers.service_worker_config;
const sample_manifest = helpers.manifest;
inquirer.prompt(questions).then(answers => {
if(answers.framework == 'angular'){
sample_manifest.name = answers.appname;
sample_manifest.short_name = answers.appname;
sample_manifest.theme_color = answers.theme_color;
sample_manifest.background_color = answers.background_color;
sample_manifest.display = answers.display;
console.log('Your manifest file \n ----------------------------- \n', sample_manifest);
}
else {
console.log('currently supporting Angular 2+')
}
});
|
/*preloader*/
$(document).ready(function($) {
var Body = $('body');
Body.addClass('preloader-site');
});
$(window).load(function() {
$('.preloader-wrapper').fadeOut();
$('body').removeClass('preloader-site');
});
/*parallax scrolling*/
$(window).scroll(function(){
let scrollTop = $(this).scrollTop();
console.log(scrollTop);
$(".hero").css("background-position-y", -(scrollTop*2) + "px");
}); |
import React from 'react'
import { reset } from 'redux-form'
import axios from 'axios'
import classNames from 'classnames'
import { Field, reduxForm } from 'redux-form'
import WidgetGrid from '../../../../components/widgets/WidgetGrid'
import Datatable from '../../../../components/tables/Datatable'
import {RFField, RFRadioButtonList, RFTextArea } from '../../../../components/ui'
import {required, email, number} from '../../../../components/forms/validation/CustomValidation'
import AlertMessage from '../../../../components/common/AlertMessage'
import {submitStudentSpecialSevices, removeStudentSpecialSevices} from './submit'
import {mapForRadioList} from '../../../../components/utils/functions'
import { upper } from '../../../../components/utils/normalize'
import Msg from '../../../../components/i18n/Msg'
class SpecialServicesForm extends React.Component {
constructor(props){
super(props);
this.state = {
studentId: 0,
yesNoOptions: [],
activeTab: "add",
disabledDetails: true
}
this.handleHasReceivedServiceChange = this.handleHasReceivedServiceChange.bind(this);
}
componentDidMount(){
axios.get('assets/api/common/YesNo.json')
.then(res=>{
const yesNoOptions = mapForRadioList(res.data);
this.setState({yesNoOptions});
});
this.setState({studentId: this.props.studentId});
this.props.change('studentId', this.props.studentId); // function provided by redux-form
$('#specialServicesGrid').on('click', 'td', function(event) {
if ($(this).find('#dele').length > 0) {
//alert( $(this).find('#dele').data('tid'));
var id = $(this).find('#dele').data('tid');
removeStudentSpecialSevices(id, $(this));
}
});
}
handleHasReceivedServiceChange(obj, value){
if(value=="Yes"){
this.setState({disabledDetails:true});
}
else{
this.setState({disabledDetails:false});
}
}
//
render() {
const { handleSubmit, pristine, reset, submitting, touched, error, warning } = this.props
const { studentId, activeTab, disabledDetails, yesNoOptions } = this.state;
return (
<WidgetGrid>
<div className="tabbable tabs">
<ul className="nav nav-tabs">
<li id="tabAddLink" className="active">
<a id="tabAddSpecialService" data-toggle="tab" href="#A11A2"><Msg phrase="AddText" /></a>
</li>
<li id="tabListLink">
<a id="tabListSpecialService" data-toggle="tab" href="#B11B2"><Msg phrase="ListText" /></a>
</li>
</ul>
<div className="tab-content">
<div className="tab-pane active" id="A11A2">
<form id="form-special-services" className="smart-form"
onSubmit={handleSubmit((values)=>{submitStudentSpecialSevices(values, studentId)})}>
<fieldset>
<div className="row">
<section className="remove-col-padding col-sm-12 col-md-12 col-lg-12">
<Field name="specialServiceName" labelClassName="input"
labelIconClassName="icon-append fa fa-book"
component={RFTextArea}
maxLength="500" type="text"
label="SpecialServiceNameText"
placeholder="Please enter special service that your child ever evaluated. e.g: Speech/Language therapy, counseling, wears hearing aids or others"/>
</section>
</div>
<div className="row">
<section className="remove-col-padding col-sm-6 col-md-6 col-lg-6">
<Field component={RFRadioButtonList} name="hasReceivedService"
required={true}
label="ChooseYesIfReceivedSpeicalServiceText"
onChange={this.handleHasReceivedServiceChange}
options={yesNoOptions} />
</section>
<section className="remove-col-padding col-sm-6 col-md-6 col-lg-6">
</section>
</div>
<div className="row">
<section className="remove-col-padding col-sm-12 col-md-12 col-lg-12">
<Field name="details" labelClassName="input"
labelIconClassName="icon-append fa fa-book"
component={RFTextArea}
maxLength="500" type="text"
label="DetailsText"
placeholder="Please enter details about the special service"/>
</section>
</div>
{(error!==undefined && <AlertMessage type="w" icon="alert-danger" message={error} />)}
<Field component="input" type="hidden" name="studentId" />
<footer>
<button type="button" disabled={pristine || submitting} onClick={reset} className="btn btn-primary">
<Msg phrase="ResetText"/>
</button>
<button type="submit" disabled={pristine || submitting} className="btn btn-primary">
<Msg phrase="SaveText"/>
</button>
</footer>
</fieldset>
</form>
</div>
<div className="tab-pane table-responsive" id="B11B2">
<Datatable id="specialServicesGrid"
options={{
ajax: {"url": getWebApiRootUrl() +'/api/StudentSiblings/' + studentId, "dataSrc": ""},
columnDefs: [
{
"render": function ( data, type, row ) {
return '<a id="dele" data-tid="' + data + '"><i class=\"glyphicon glyphicon-trash\"></i><span class=\"sr-only\">Edit</span></a>';
}.bind(self),
"className": "dt-center",
"sorting": false,
"targets": 6
}
],
columns: [
{data: "SpecialServiceName"},
{data: "Details"},
{data: "StudentSpecialServiceID"}
],
buttons: [
'copy', 'excel', 'pdf'
]
}}
paginationLength={true}
className="table table-striped table-bordered table-hover"
width="100%">
<thead>
<tr>
<th data-hide="mobile-p"><Msg phrase="SpecialServiceNameText"/></th>
<th data-class="expand"><Msg phrase="DetailsText"/></th>
<th data-hide="mobile-p"></th>
</tr>
</thead>
</Datatable>
</div>
</div>
</div>
</WidgetGrid>
)
}
}
const afterSubmit = function(result, dispatch) {
dispatch(reset('SpecialServicesForm'));
}
export default reduxForm({
form: 'SpecialServicesForm', // a unique identifier for this form
onSubmitSuccess: afterSubmit,
keepDirtyOnReinitialize: false
})(SpecialServicesForm) |
class _Node {
constructor(value, next) {
this.value = value;
this.next = next;
}
}
class LinkedList {
constructor() {
this.head = null;
}
insertBefore(key, item) {
// Start at the head
let currNode = this.head;
// If the list is empty
if (!this.head) {
return null;
}
// Check for the item
while (currNode.value !== key) {
if (currNode.next === null) {
return null;
} else {
// Otherwise, keep looking
currNode = currNode.next;
}
}
let newNode = new _Node(item, currNode.next);
currNode.next = newNode;
}
insertAfter(key, item) {
// Start at the head
let currNode = this.head;
// If the list is empty
if (!this.head) {
return null;
}
// Check for the item
while (currNode.value !== key) {
if (currNode.next === null) {
return null;
} else {
// Otherwise, keep looking
currNode = currNode.next;
}
}
let newNode = new _Node(item, currNode.next);
currNode.next = newNode;
}
insertFirst(item) {
this.head = new _Node(item, this.head);
}
insertLast(item) {
if (this.head === null) {
this.insertFirst(item);
} else {
let tempNode = this.head;
while (tempNode.next !== null) {
tempNode = tempNode.next;
}
tempNode.next = new _Node(item, null);
}
}
findLast() {
let currNode = this.head;
// If the list is empty
if (!this.head) {
return null;
}
// Check for the item
while (currNode.next !== null) {
if (currNode.next === null) {
return currentNode;
} else {
// Otherwise, keep looking
currNode = currNode.next;
}
}
}
find(item) {
// Start at the head
let currNode = this.head;
// If the list is empty
if (!this.head) {
return null;
}
// Check for the item
while (currNode.value !== item) {
/* Return null if it's the end of the list
and the item is not on the list */
if (currNode.next === null) {
return null;
} else {
// Otherwise, keep looking
currNode = currNode.next;
}
}
// Found it
return currNode;
}
remove(item) {
// If the list is empty
if (!this.head) {
return null;
}
// If the node to be removed is head, make the next node head
if (this.head.value === item) {
this.head = this.head.next;
return;
}
// Start at the head
let currNode = this.head;
// Keep track of previous
let previousNode = this.head;
while (currNode !== null && currNode.value !== item) {
// Save the previous node
previousNode = currNode;
currNode = currNode.next;
}
if (currNode === null) {
console.log("Item not found");
return;
}
previousNode.next = currNode.next;
}
}
const display = linkedList => {
console.log(linkedList);
};
const size = linkedList => {
let currentNode = linkedList.head;
let count = 0;
while (currentNode.next !== null) {
currentNode = currentNode.next;
count++;
}
return count;
};
const isEmpty = linkedList => {
if (linkedList.head === null) {
return false;
} else {
return true;
}
};
const main = () => {
const SLL = new LinkedList();
SLL.insertFirst("Apollo");
SLL.insertFirst("Boomer");
SLL.insertLast("Helo");
SLL.insertLast("Husker");
SLL.insertLast("Starbuck");
SLL.insertLast("Tauhida");
SLL.remove("Boomer");
SLL.find("Helo");
SLL.insertBefore("Boomer", "Athena");
display(SLL);
console.log(isEmpty(SLL));
console.log(size(SLL));
};
// main();
// Mystery Program:
function WhatDoesThisProgramDo(lst) {
let current = lst.head;
while (current !== null) {
let newNode = current;
while (newNode.next !== null) {
if (newNode.next.value === current.value) {
newNode.next = newNode.next.next;
} else {
newNode = newNode.next;
}
}
current = current.next;
}
}
// Reverse a Linked List
// Recursive
const reverse = head => {
// If list is one node long
if (!head || !head.next) {
return head;
}
let temp = reverse(head.next);
head.next.next = head;
head.next = undefined;
return temp;
};
// 3rd from the end
const findN = list => {
// Start at the head
let currNode = this.head;
// If the list is empty
if (!this.head) {
return null;
}
// Check for the item
while (currNode.value !== null) {
/* Return null if it's the end of the list
and the item is not on the list */
if (currNode.next.next === null) {
return currNode;
} else {
// Otherwise, keep looking
currNode = currNode.next;
}
}
};
// Middle of a list
const middle = list => {
let fastPoint = list.head;
let slowPoint = list.head;
while ((fastPoint.next !== null) & (fastPoint.next.next !== null)) {
fastPoint = fastPoint.next.next;
slowPoint = slowPoint.next;
}
return slowPoint;
};
// Cycle in a List
const testList = new LinkedList();
testList.insertFirst("Hey");
testList.insertLast("Woa");
testList.insertLast("Wowo");
console.log(testList);
const cycleList = list => {
let currNode = list.head;
// If the list is empty
if (!head) {
return null;
}
while (currNode.next !== null) {
if (currNode.next === null) {
return false;
} else {
// Otherwise, keep looking
currNode = currNode.next;
}
}
};
// Sorting a list
const sort = list => {
if (list.head === null || list.head.next === null) {
return head;
}
};
|
// @flow
function checkStatus(response: Response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
const error = new Error(`HTTP Error ${response.statusText}`);
throw error;
}
function parseJSON(response: Response) {
return response.json();
}
export { checkStatus, parseJSON };
|
const jwt = require('jsonwebtoken');
const secret = "wayoBoi"; // verifies that the server reconnizes this token
const expiration = '2h';
module.exports = {
signToken: function ({ username, email, _id}) {
const payload = { username, email, _id }; // this sign token function expects a user object and will add thats users username email and id properties to the token
return jwt.sign({data: payload}, secret, { expiresIn: expiration})
},
authMiddleware: function ({ reg }) {
// allows token to be sent via req.body req query or headeres
let token = req.body.token || req.query.token || req.headers.authorization;
// seperate bearer from token valuie
if (req.headers.authorization) {
token = token.split(' ').pop().trim();
}
// if no token return request obeject as is
if(!token) {
return req;
}
try {
// decode and attach user data to reqst object
const { data } = jwt.verify(token,secret, {maxAge: expiration});
req.user = data
} catch {
console.log('invalid token ')
}
// return updatec request object
return req;
}
} |
"use strict";
const assert = require("assert");
const d = require("dotty");
const h = require("highland");
const proxyquire = require("proxyquire").noPreserveCache();
const r = require("ramda");
const sinon = require("sinon");
describe("transitland", () => {
let msg, robot, stubs, transitland;
beforeEach(function() {
msg = {
"robot": robot,
"reply": sinon.spy(),
};
robot = {
"commands": [],
"respond": (expression, fn) => {
robot.commands.push([expression, fn]);
},
"tell": sinon.spy((string, msg) => {
const out = r.find(r.compose(
r.flip(r.test)(string),
r.head), robot.commands);
return r.last(out)(msg);
}),
};
stubs = {
"request": {
"get": (endpoint, cb) => {
cb(null, {}, JSON.stringify({
"schedule_stop_pairs": [{
"trip_headsign": "Lindenwold",
"origin_departure_time": "22:22:00",
}, {
"trip_headsign": "Lindenwold",
"origin_departure_time": "22:42:00",
}, {
"trip_headsign": "Lindenwold",
"origin_departure_time": "23:02:00",
}]
}));
},
},
"./operators": {
"findOperator": sinon.spy(r.always(h([{
"name": "Port Authority Transit Corporation",
"short_name": "PATCO",
"onestop_id": "o-dr4e-portauthoritytransitcorporation",
"timezone": "America/New_York",
}]))),
},
"./stops": {
"findStop": sinon.spy(r.always(h([{
"onestop_id": "s-dr4e382mxm-15~16thandlocust",
"name": "15-16th and Locust",
}]))),
},
};
transitland = proxyquire("../lib/index", stubs);
transitland(robot);
});
describe( "find next times for requested stop", () => {
it( "should respond with the upcoming times until EOD", done => {
msg = r.merge(msg, {
"reply": sinon.spy(message => {
assert.equal(r.path(["reply", "calledOnce"], msg), true);
assert.equal("The next trains from 15-16th and Locust are 10:22pm to Lindenwold, 10:42pm to Lindenwold, 11:02pm to Lindenwold", message);
done();
}),
"match": [
"next train on patco from 15-16th and Locust",
"patco",
"15-16th and Locust",
],
});
robot.tell("next train on patco from 15-16th and Locust", msg);
});
});
describe("forget transit stops and lines", () => {
beforeEach(() => {
d.put(robot, "brain.data.transitland.operators.patco", "o-dr4e-portauthoritytransitcorporation");
d.put(robot, "brain.data.transitland.stops.15th 16th and locust", "s-dr4e382mxm-15~16thandlocust");
});
it("should remove any remembered operators", done => {
msg = r.merge(msg, {
"reply": sinon.spy(message => {
assert.equal(r.path(["reply", "calledOnce"], msg), true);
assert.equal("Oh shit! I forgot all the transit operators!", message);
assert.equal(r.path(["brain", "data", "transitland", "operators", "patco"], robot), undefined);
done();
}),
"match": [
"forget all transit operators",
"operator",
],
});
robot.tell("forget all transit operators", msg);
});
it("should remove any remembered stops", done => {
msg = r.merge(msg, {
"reply": sinon.spy(message => {
assert.equal(r.path(["reply", "calledOnce"], msg), true);
assert.equal("Oh shit! I forgot all the transit stops!", message);
assert.equal(r.path(["brain", "data", "transitland", "stops", "15th 16th and locust"], robot), undefined);
done();
}),
"match": [
"forget all transit stops",
"stop",
],
});
robot.tell("forget all transit stops", msg);
});
});
});
|
const hr = require("../models/hr");
module.exports = {
//GET: /hr/employees
getAllEmployees(req, res, next) {
hr.getAllEmployees((hrEmployees) => {
res.status(200).json(hrEmployees);
});
},
//GET: /hr/employee/:employeeId
getEmployee(req, res, next) {
const employeeId = req.params.employeeId;
hr.getEmployee(employeeId, (hrEmployee) => {
res.status(200).json(hrEmployee);
});
},
//POST: /hr/new-employee
addNewEmployee(req, res, next) {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const middleInitial = req.body.middleInitial;
const address1 = req.body.address1;
const address2 = req.body.address2;
const city = req.body.city;
const state = req.body.state;
const zip = req.body.zip;
const email = req.body.email;
const socialSecurityNumber = req.body.socialSecurityNumber;
const phoneNumber = req.body.phoneNumber;
const gender = req.body.gender;
const driversLicense = req.body.driversLicense;
const maritalStatus = req.body.maritalStatus;
const shareholderStatus = req.body.shareholderStatus;
const benefitPlans = req.body.benefitPlans;
const ethnicity = req.body.ethnicity;
hr.addNewEmployee(
{
firstName,
lastName,
middleInitial,
address1,
address2,
city,
state,
zip,
email,
socialSecurityNumber,
phoneNumber,
gender,
driversLicense,
maritalStatus,
shareholderStatus,
benefitPlans,
ethnicity,
},
(result) => {
res.status(200).json(result);
}
);
},
//POST: /hr/update-employee
updateEmployee(req, res, next) {
const employeeId = req.body.id;
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const middleInitial = req.body.middleInitial;
const address1 = req.body.address1;
const address2 = req.body.address2;
const city = req.body.city;
const state = req.body.state;
const zip = req.body.zip;
const email = req.body.email;
const socialSecurityNumber = req.body.socialSecurityNumber;
const phoneNumber = req.body.phoneNumber;
const gender = req.body.gender;
const driversLicense = req.body.driversLicense;
const maritalStatus = req.body.maritalStatus;
const shareholderStatus = req.body.shareholderStatus;
const benefitPlans = req.body.benefitPlans;
const ethnicity = req.body.ethnicity;
hr.updateEmployee(
{
employeeId,
firstName,
lastName,
middleInitial,
address1,
address2,
city,
state,
zip,
email,
socialSecurityNumber,
phoneNumber,
gender,
driversLicense,
maritalStatus,
shareholderStatus,
benefitPlans,
ethnicity,
},
(result) => {
res.status(200).json(result);
}
);
},
//GET: /hr/delete-employee
deleteEmployee(req, res, next) {
const employeeId = req.body.id;
hr.deleteEmployee(employeeId, (result) => {
res.status(200).json(result);
});
},
};
|
import PropTypes from 'prop-types'
import { css } from '@emotion/core'
import styled from '@emotion/styled'
import { containedSplit } from '../../../traits'
import { grid } from '../../../macros'
const Thirds = styled.div(
...grid.styles(),
containedSplit.styles,
({ reversed }) => css`
grid-template-columns: ${reversed ? '2fr 1fr' : '1fr 2fr'};
grid-template-areas: 'left right';
> :nth-child(odd) {
grid-area: left;
}
> :nth-child(even) {
grid-area: right;
}
`
)
Thirds.propTypes = {
...grid.propTypes(),
reversed: PropTypes.bool,
}
Thirds.defaultProps = {
...grid.defaultProps(),
reversed: false,
}
export default Thirds
|
const mongoose = require('../common/connection');
var Schema = mongoose.Schema;
var adminschema = new Schema({
email: String,
password: String
});
var adminmodel = mongoose.model('adminmodels',adminschema);
module.exports= adminmodel; |
import React, { Component } from 'react';
import { View, Text, SafeAreaView, ScrollView, Animated, TouchableOpacity, TextInput, ActivityIndicator, StatusBar } from 'react-native';
import colors from '../../../constants/Colors';
import styles from '../../../styles/customer/Style_ExploreScreen';
import CategoriesList from './CategoriesList';
import SearchBar from './SearchBar';
import ResultsList from './ResultsList';
import { connect } from "react-redux";
import * as Location from 'expo-location';
import { Overlay, Slider, Button, Rating } from 'react-native-elements';
import route from '../../../routeConfig';
class ExploreScreen extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
searchQuery: '',
searchResults: [],
currentLocation: {},
distance: null,
isDistanceOverylayVisible: false,
minPrice: '0',
maxPrice: null,
isPriceOverylayVisible: false,
rating: 0,
isRatingOverylayVisible: false,
category: 'All',
};
this.initAnimation = this.initAnimation.bind(this);
this.renderDistancePickerOverlay = this.renderDistancePickerOverlay.bind(this);
this.renderRatingPickerOverlay = this.renderRatingPickerOverlay.bind(this);
this.renderPricePickerOverlay = this.renderPricePickerOverlay.bind(this);
this.handleCategoryChange = this.handleCategoryChange.bind(this);
this.updateSearch = this.updateSearch.bind(this);
this.fetchSearch = this.fetchSearch.bind(this);
}
async componentDidMount() {
this.fetchSearch();
}
componentWillMount() {
this.initAnimation();
}
async initAnimation() {
this.scrollY = new Animated.Value(0);
this.startHeaderHeight = 120;
this.endHeaderHeight = 80;
this.animatedHeaderHeight = this.scrollY.interpolate({
inputRange: [0, 80],
outputRange: [this.startHeaderHeight, this.endHeaderHeight],
extrapolate: 'clamp'
})
this.animatedOpacity = this.animatedHeaderHeight.interpolate({
inputRange: [this.endHeaderHeight, this.startHeaderHeight],
outputRange: [0, 1],
extrapolate: 'clamp'
})
this.animatedTagTop = this.animatedHeaderHeight.interpolate({
inputRange: [this.endHeaderHeight, this.startHeaderHeight],
outputRange: [-30, 10],
extrapolate: 'clamp'
})
this.startHeaderHeight = this.scrollY.interpolate({
inputRange: [0, 40],
outputRange: [this.startHeaderHeight, this.endHeaderHeight],
extrapolate: 'clamp'
})
this.searchBarHeight = this.scrollY.interpolate({
inputRange: [0, 10],
outputRange: [0, 10],
extrapolate: 'clamp'
})
}
async handleCategoryChange(chosen) {
await this.setState({category: chosen});
this.fetchSearch();
}
updateSearch(text) {
this.setState({ searchQuery: text});
}
async fetchSearch() {
await this.setState({isLoading: true});
const url = `${route}/search/search`;
const options = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
searchQuery: this.state.searchQuery,
radius: this.state.distance,
lon: this.props.currentLocation.coords.longitude,
lat: this.props.currentLocation.coords.latitude,
category: this.state.category,
rating: this.state.rating,
minPrice: this.state.minPrice,
maxPrice: this.state.maxPrice,
})
};
const request = new Request(url, options)
await fetch(request)
.then(response => response.json())
.then(data => {
// console.log(data)
this.setState({searchResults: data});
})
.catch(error => console.log(error))
await this.setState({isLoading: false});
}
renderDistancePickerOverlay() {
return(
<Overlay
isVisible={this.state.isDistanceOverylayVisible}
onBackdropPress={() => this.setState({ isDistanceOverylayVisible: false })}
overlayStyle={{height: '30%', width: '90%'}}
>
<View style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center'}}>
<Text>Search by distance:</Text>
<Text style={{fontSize: 18, fontWeight: '600', marginTop: 10}}>{this.state.distance}km</Text>
<Slider
value={this.state.distance}
onValueChange={value => this.setState({ distance: value })}
maximumValue={100}
minimumTrackTintColor={colors.green03}
minimumValue={1}
step={1}
value={this.state.distance}
style={{width: '80%'}}
thumbTintColor={colors.green03}
/>
<Button
buttonStyle={{
borderRadius: 10,
borderColor: colors.green03,
borderWidth: 1.5,
}}
titleStyle={{
color: colors.green03,
fontWeight: '400',
fontSize: 14
}}
containerStyle={{ width: '40%', height: 40, marginTop: 20 }}
type="outline"
title="Apply"
onPress={() => {
this.setState({ isDistanceOverylayVisible: false});
this.fetchSearch();
}}
/>
</View>
</Overlay>
);
}
renderRatingPickerOverlay() {
return(
<Overlay
isVisible={this.state.isRatingOverylayVisible}
onBackdropPress={() => this.setState({ isRatingOverylayVisible: false })}
overlayStyle={{height: '30%', width: '90%'}}
>
<View style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center'}}>
<Rating
ratingCount={4}
imageSize={35}
startingValue={1}
onFinishRating={(value) => this.setState({ rating: value })}
type={'custom'}
/>
<Text style={{fontSize: 18, fontWeight: '600', marginTop: 10}}>& Up</Text>
<Button
buttonStyle={{
borderRadius: 10,
borderColor: colors.green03,
borderWidth: 1.5,
}}
titleStyle={{
color: colors.green03,
fontWeight: '400',
fontSize: 14
}}
containerStyle={{ width: '40%', height: 40, marginTop: 30 }}
type="outline"
title="Apply"
onPress={() => {
this.setState({ isRatingOverylayVisible: false});
this.fetchSearch();
}}
/>
</View>
</Overlay>
);
}
renderPricePickerOverlay() {
return(
<Overlay
isVisible={this.state.isPriceOverylayVisible}
onBackdropPress={() => this.setState({ isPriceOverylayVisible: false })}
overlayStyle={{height: '30%', width: '90%'}}
>
<View style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center'}}>
<Text>Price range:</Text>
<View style={{flexDirection: 'row', marginTop: 15, justifyContent: 'center', alignItems: 'center'}}>
<Text style={{fontSize: 14, fontWeight: '400', marginRight: 10, marginLeft: 10}}>min</Text>
<TextInput
style={{borderWidth: 1, borderRadius: 8, paddingVertical: 10, paddingHorizontal: 20, fontSize: 16, fontWeight: '500',}}
returnKeyType={'done'}
selectTextOnFocus={true}
defaultValue={'0'}
placeholderTextColor={colors.gray04}
onChangeText={(value) => this.setState({ minPrice: value })}
keyboardType="numeric"
/>
<Text style={{fontSize: 18, fontWeight: '500', marginRight: 10, marginLeft: 10}}>-</Text>
<TextInput
style={{borderWidth: 1, borderRadius: 8, paddingVertical: 10, paddingHorizontal: 20, fontSize: 16, fontWeight: '500',}}
returnKeyType={'done'}
selectTextOnFocus={true}
defaultValue={'0'}
placeholderTextColor={colors.gray04}
onChangeText={(value) => this.setState({ maxPrice: value })}
keyboardType="numeric"
/>
<Text style={{fontSize: 14, fontWeight: '400', marginRight: 10, marginLeft: 10}}>max</Text>
</View>
<Button
buttonStyle={{
borderRadius: 10,
borderColor: colors.green03,
borderWidth: 1.5,
}}
titleStyle={{
color: colors.green03,
fontWeight: '400',
fontSize: 14
}}
containerStyle={{ width: '40%', height: 40, marginTop: 30 }}
type="outline"
title="Apply"
onPress={() => {
this.setState({ isPriceOverylayVisible: false });
this.fetchSearch();
}}
/>
</View>
</Overlay>
);
}
render() {
return (
<SafeAreaView style={styles.flexContainer}>
<StatusBar barStyle="dark-content"/>
<View style={styles.flexContainer}>
<Animated.View style={{
height: this.startHeaderHeight,
backgroundColor: 'white',
justifyContent: 'center',
}}>
<Animated.View style={{ top: this.searchBarHeight, zIndex: 1 }}>
<SearchBar updateSearch={this.updateSearch} fetchSearch={this.fetchSearch}/>
</Animated.View>
<Animated.View style={{
flexDirection: 'row',
marginHorizontal: 24,
position: 'relative',
top: this.animatedTagTop,
opacity: this.animatedOpacity,
}}
>
<TouchableOpacity style={{
minHeight: 20,
minWidth: 40,
padding: 5,
marginRight: 5,
backgroundColor: 'white',
borderColor: colors.gray03,
borderWidth: 1,
borderRadius: 25,
}}
onPress={() => this.setState({isDistanceOverylayVisible: true})}
>
<Text style={{
fontSize: 10,
fontWeight: '600',
color: colors.gray04,
padding: 5,
}}
>
Distance
</Text>
</TouchableOpacity>
<TouchableOpacity style={{
minHeight: 20,
minWidth: 40,
padding: 5,
marginRight: 5,
backgroundColor: 'white',
borderColor: colors.gray03,
borderWidth: 1,
borderRadius: 25,
}}
onPress={() => this.setState({isPriceOverylayVisible: true})}
>
<Text style={{
fontSize: 10,
fontWeight: '600',
color: colors.gray04,
padding: 5,
}}
>
Price Range
</Text>
</TouchableOpacity>
<TouchableOpacity style={{
minHeight: 20,
minWidth: 40,
padding: 5,
marginRight: 5,
backgroundColor: 'white',
borderColor: colors.gray03,
borderWidth: 1,
borderRadius: 25
}}
onPress={() => this.setState({isRatingOverylayVisible: true})}
>
<Text style={{
fontSize: 10,
fontWeight: '600',
color: colors.gray04,
padding: 5,
}}
>
Rating
</Text>
</TouchableOpacity>
</Animated.View>
</Animated.View>
{this.renderDistancePickerOverlay()}
{this.renderRatingPickerOverlay()}
{this.renderPricePickerOverlay()}
<ScrollView scrollEventThrottle={16} showsVerticalScrollIndicator={false} onScroll={Animated.event(
[
{nativeEvent: { contentOffset: {y: this.scrollY} }}
]
)}
>
<CategoriesList
categoriesList={this.props.categoriesList}
changeCategory={this.handleCategoryChange}
chosenCategory={this.state.category}
/>
{
this.state.isLoading ?
<View style={{ flex: 1, justifyContent: 'center', alignContent: 'center', backgroundColor: colors.white, marginTop: 120}}>
<ActivityIndicator size="large" color={colors.red}/>
</View>
:
<ResultsList
resultList={this.state.searchResults}
navigation={this.props.navigation}
/>
}
</ScrollView>
</View>
</SafeAreaView>
)
}
}
const mapStateToProps = ({ App, User, Customer, Business }) => {
return {
hasBusiness: User.hasBusiness,
currentUser: User.currentUser,
favoritesList: Customer.favoritesList,
view: User.view,
categoriesList: App.categoriesList,
currentLocation: User.currentLocation,
}
}
export default connect(mapStateToProps)(ExploreScreen);
|
//= require jquery
//= require jquery_ujs
//= require lodash
//= require materialize
//= require d3
//= require select2
//= require_tree ./d3_assets
//= require_tree ./visualisations
//= require main_helpers
|
export default function(value) {
if (!value) return true;
const regex = /^\d{5}(?:[-\s]\d{4})?$/;
return regex.test(value);
} |
app.controller('fhome',['$scope','$state','$localStorage',function($scope,$state,$localStorage){
//console.log($localStorage.login);
if($localStorage.flogin===undefined || $localStorage.flogin==="undefined"){
alert("username and password is incorrect");
$state.go('flogin');
}
else{
$state.go('home');
}
}]); |
define(["jquery", "knockout", "durandal/app", "durandal/system", "plugins/router", "services/data", "komapping"], function ($, ko, app, system, router, data, mapper) {
var
// Properties
cfg = mapper.fromJS({
ID: '',
CheckInterval: 0,
CheckRunning: false,
NotificationInterval: 15,
Password: '',
Port: 26,
Recepient: '',
SendEmail: false,
SendSms: false,
Sender: '',
Smtp: '',
Ssl: false,
Username: ''
}),
isBusy = ko.observable(false),
// Handlers
save = function() {
isBusy(true);
data.updateConfiguration(cfg).done(function(){
}).fail(function(){
}).always(function(){
isBusy(false);
})
},
// Lifecycle
activate = function () {
return data.getConfiguration().done(function (configuration) {
mapper.fromJS(configuration, cfg);
})
},
deactivate = function () {};
return {
// Place your public properties here
isBusy: isBusy,
cfg: cfg,
save: save,
activate: activate,
deactivate: deactivate
};
}); |
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import AppBar from '@material-ui/core/AppBar';
import Snackbar from '@material-ui/core/Snackbar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import Grid from '@material-ui/core/Grid';
import { BasicProfile, Timings, Services, Prices } from '../components';
import UserIcon from '@material-ui/icons/Person';
import BackendService from '../services/backendServices';
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
},
menuButton: {
marginRight: 36,
},
menuButtonHidden: {
display: 'none',
},
title: {
flexGrow: 1,
cursor: 'pointer'
},
content: {
flexGrow: 1,
height: '100vh',
overflow: 'auto',
marginTop: theme.spacing(5),
padding: theme.spacing(10),
}
}));
export default function Profile() {
const classes = useStyles();
const [anchorEl, setAnchorEl] = React.useState(null);
const [state, setState] = React.useState({
open: false,
message: '',
vertical: 'top',
horizontal: 'right',
});
const { vertical, horizontal, open, message } = state;
const handleSnackClose = () => {
setState({ ...state, open: false });
};
const handleClick = event => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const home = async () => {
try {
const practiceId = localStorage.getItem('userId');
if (practiceId) {
let response = await BackendService.getServices(practiceId);
if (response.data.data.length > 0) {
window.location.pathname = '/home';
} else {
setState({ ...state, open: true, message: 'Register atleast one service!' });
}
} else {
window.location.pathname = '/signin';
}
} catch (error) {
setState({ ...state, open: true, message: 'Something went wrong!' });
}
}
const logout = () => {
localStorage.removeItem('token');
localStorage.removeItem('email');
localStorage.removeItem('userId');
localStorage.removeItem('serviceId');
window.location.pathname = '/signin'
};
return (
<div className={classes.root}>
<CssBaseline />
<AppBar color='secondary'>
<Toolbar >
<Typography component="h1" variant="h6" color="inherit" noWrap onClick={home} className={classes.title}>
MeetMe
</Typography>
<IconButton style={{color: 'white'}} aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick}>
<UserIcon />
</IconButton>
<Menu
id="simple-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={logout}>Logout</MenuItem>
</Menu>
</Toolbar>
</AppBar>
<Snackbar
anchorOrigin={{ vertical, horizontal }}
key={`${vertical},${horizontal}`}
open={open}
onClose={handleSnackClose}
ContentProps={{
'aria-describedby': 'message-id',
}}
message={<span id="message-id">{message}</span>}
/>
<main className={classes.content}>
<div className={classes.appBarSpacer} />
<Grid container spacing={3}>
<Grid item xs={6} container spacing={3}>
<Grid item xs={12}>
<BasicProfile />
</Grid>
<Grid item xs={12}>
<Prices />
</Grid>
</Grid>
<Grid item xs={6} container spacing={3}>
<Grid item xs={12}>
<Services />
</Grid>
<Grid item xs={12}>
<Timings />
</Grid>
</Grid>
</Grid>
</main>
</div>
);
} |
#!/usr/bin/env node
/* Copyright (c) 2015 Intel Corporation. All rights reserved.
* Use of this source code is governed by a MIT-style license that can be
* found in the LICENSE file.
*/
'use strict';
require('../src/index').run(process.argv.slice(2)); |
'use strict';
(function(root, factory){
if (typeof define === 'function' && define.amd) {
define([], function() { return factory( root ); });
} else if (typeof exports !== 'undefined') {
module.exports = factory( root );
} else {
var previousSparkup = root.sparkup, sparkup = factory( root );
sparkup.noConflict = function(){
root.sparkup = previousRequest;
return sparkup;
}
root.sparkup = sparkup;
}
})( window, function( root ){
return (function sparky(){
var parents = [], pos = 0;
return {
previousParent: function(){
pos--;
},
addParent: function( element ) {
parents.splice( pos, 0, element );
pos++;
},
getParent: function(){
var _pos = pos - 1;
if ( _pos < 0 ) _pos = 0;
return parents[_pos];
},
build: function( string ) {
var html = document.createDocumentFragment(), parentEL;
// reset
parents = []; pos = 0;
this.addParent(html);
var doc = string.split('>'), elements, idx, line;
for( var i = 0, l = doc.length; i < l; i++ )
{
// remove extra white space
line = doc[i].toString().trim().replace(/\s{2,}/,'');
idx = line.indexOf('<');
if ( idx !== false && idx !== -1 )
{
elements = line.split('<');
// process element with current parent
this.processDepth( elements[0] );
for( var j = 1, len = elements.length; j < len; j++ ){
this.previousParent();
this.processDepth( elements[j] );
}
}
else
{
this.processDepth( line );
}
}
return html;
},
processDepth: function( group ) {
group = group.trim();
if ( !group || group == '' ) return;
var siblings = group.match(/[^\s]*{[^}]*}[^\s]*|[^\s^{^}]+/g);
var parentEL = this.getParent();
var elem, sibling;
for( var j = 0, len = siblings.length; j < len; j++ ){
sibling = siblings[j].trim();
if ( sibling == '' ) continue;
elem = this.createElement( sibling );
parentEL.appendChild( elem );
}
this.addParent( elem );
},
createElement: function( elem ) {
var id, classes, attributes, element, text;
if ( !(element = this.getElement( elem )) ){
return false;
}
element = document.createElement( element );
if ( (id = this.getID( elem )) ){
element.id = id;
}
if ( (classes = this.getClasses( elem )) ){
element.className = classes.join(' ');
}
if ( (attributes = this.getAttributes( elem )) ){
for( var attribute in attributes ){
element.setAttribute( attribute, attributes[attribute] );
}
}
if ( (text = this.getText( elem )) ){
if ( element.textContent !== undefined ) element.textContent = text;
else if ( element.innerText !== undefined ) element.innerText = text;
else element.innerHTML = text;
}
return element;
},
getElement: function( elem ){
var m;
if ( ( m = elem.match(/#|\.|\[|\{/) ) ){
return elem.substring(0,m.index);
} else {
return elem;
}
},
getID: function( elem ) {
var matches;
if ( (matches = elem.match(/#([\w_-]+)/)) ){
return matches[1];
}
return false;
},
getClasses: function( elem ) {
var matches;
if ( (matches = elem.match(/\.[\w_-]+/g)) ){
for( var i = 0, l = matches.length; i < l; i++ ){
matches[i] = matches[i].substring(1);
}
return matches;
}
return false;
},
getText: function( elem ) {
var matches;
if ( (matches = elem.match(/\{([\W\w]+)\}/)) ){
return matches[1];
}
return false;
},
getAttributes: function( elem ) {
var matches, attributes = {}, pair, match;
if ( (matches = elem.match(/\[[\w\W]+\]/g)) ){
for( var i = 0, l = matches.length; i<l; i++ ){
match = matches[i];
pair = match.substring(1,match.length-1);
pair = pair.split('=');
attributes[pair[0]] = pair[1];
}
return attributes;
}
return false;
}
}
})();
});
|
var windowPos : Rect;
var imgPos : Rect[];
var customSkin : GUISkin;
var windowOpen : boolean = false;
var messageBox : String;
var messageBoxGuide : String;
var extinguisherImages : Texture2D[];
var extinguisherType : String;
var typeLetters : Texture2D[];
function Start()
{
typeLetters = new Texture2D[6];
typeLetters[0] = Resources.Load("A",typeof(Texture2D)) as Texture2D;
typeLetters[1] = Resources.Load("B",typeof(Texture2D)) as Texture2D;
typeLetters[2] = Resources.Load("C",typeof(Texture2D)) as Texture2D;
typeLetters[3] = Resources.Load("D",typeof(Texture2D)) as Texture2D;
typeLetters[4] = Resources.Load("E",typeof(Texture2D)) as Texture2D;
typeLetters[5] = Resources.Load("F",typeof(Texture2D)) as Texture2D;
}
function OnGUI()
{
GUI.skin = customSkin;
if (windowOpen) {
//extinguisher properties
GUI.Box(windowPos, messageBox);
//extinguisher types textures
var i: int = 0;
for (i = 0; i < extinguisherImages.Length; i++) {
GUI.DrawTexture(imgPos[i],extinguisherImages[i],ScaleMode.ScaleAndCrop);
}
if (extinguisherImages.Length > 1) {
var guidePos = Rect(imgPos[0].left, imgPos[i-1].bottom + 36, imgPos[1].right - imgPos[0].left - 10, imgPos[i-1].bottom + 100);
//extinguisher guide
GUI.Label(guidePos, messageBoxGuide);
}
}
}
function getTypeResource( resource: String){
switch (resource) {
case "A":
return typeLetters[0];
break;
case "B":
return typeLetters[1];
break;
case "C":
return typeLetters[2];
break;
case "D":
return typeLetters[3];
break;
case "E":
return typeLetters[4];
break;
case "F":
return typeLetters[5];
break;
default: break;
}
}
// hide function for close the window (boolean=false)
function Hide() {
windowOpen = false;
return;
}
function Show() {
var imgWidth : int = Screen.width/6 - Screen.width/20;
var imgTop : int = Screen.height/25+5;
var imgLeft : int = Screen.width/20+5;
Debug.Log(extinguisherType);
switch (extinguisherType)
{
case "Powder":
Debug.Log("powder");
extinguisherImages = new Texture2D[3];
imgPos = new Rect[3];
extinguisherImages[0] = getTypeResource("A");
imgPos[0] = Rect (imgLeft, imgTop, imgWidth, imgWidth);
imgLeft += imgWidth+(Screen.width/20);
extinguisherImages[1] = getTypeResource("B");
imgPos[1] = Rect (imgLeft, imgTop, imgWidth, imgWidth);
imgLeft -= imgWidth+(Screen.width/20);
imgTop += imgWidth+(Screen.width/20);
extinguisherImages[2] = getTypeResource("C");
imgPos[2] = Rect (imgLeft, imgTop, imgWidth, imgWidth);
messageBoxGuide = "L'estintore a polvere chimica polivalente ABC è il più diffuso, è efficiente con tutti i tipi di fuochi escluso D. Sporca. Rimuovere l'anello (premere [E] dopo aver equipaggiato l'estintore e rimuoverlo) dirigere poi il getto sulla base del fuoco.";
break;
case "CO2":
Debug.Log("co2");
extinguisherImages = new Texture2D[2];
imgPos = new Rect[2];
extinguisherImages[0] = getTypeResource("B");
imgPos[0] = Rect (imgLeft, imgTop, imgWidth, imgWidth);
imgLeft += imgWidth+(Screen.width/20);
extinguisherImages[1] = getTypeResource("C");
imgPos[1] = Rect (imgLeft, imgTop, imgWidth, imgWidth);
messageBoxGuide = "L'estintore ad anidride carbonica è meno sporcante e usato per apparecchiature in tensione. Non efficiente all'esterno, con incendi di tipo A, modesto rischio di ustione congelante e asfissia per l'utilizzatore. Rimuovere l'anello (premere [E] dopo aver equipaggiato l'estintore e rimuoverlo) dirigere poi il getto sulla base del fuoco.";
break;
default:
Debug.Log("default");
extinguisherImages = new Texture2D[1];
imgPos = new Rect[1];
imgWidth = Screen.width/3 - Screen.width/10;
extinguisherImages[0] = getTypeResource(extinguisherType);;
imgPos[0] = Rect (imgLeft, imgTop, imgWidth, imgWidth);
break;
}
windowPos = Rect (Screen.width/20, Screen.height/25, Screen.width/3 - Screen.width/20, Screen.height - Screen.height/10);
windowOpen = true;
return;
} |
import React from 'react';
import Header from './Header';
import Footer from './Footer';
import Container from './Container';
import $ from 'jquery';
class AppComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
screenWidth: $(window).width()
}
}
render() {
return (
<div>
<Header />
<div id = 'grey-overlay'></div>
<Container url={this.props.location} screenWidth={this.state.screenWidth}/>
</div>
)
}
updateDimensions() {
this.setState({screenWidth: $(window).width()});
}
componentDidMount() {
window.addEventListener("resize", this.updateDimensions.bind(this));
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions.bind(this));
}
}
export default AppComponent;
|
import {useQuery} from "react-query";
import axios from "axios";
import {useSelector} from "react-redux";
import {useEffect, useState} from "react";
import './grade.css'
function Grades() {
const state = useSelector(state => state)
const {isLoading, error, data} = useQuery('fetchGradesStudent', () =>
axios(`http://127.0.0.1:8000/gradebook/student`, {
headers: {
"Authorization": "JWT " + state.auth.token.access,
}
}))
const handleExpandClick = (e) => {
let display = e.target.nextSibling.style.display;
e.target.nextSibling.style.display = display === 'block' ? 'none' : 'block'
}
if (isLoading) {
return <div>Loading...</div>
}
if (!isLoading) {
console.log(data)
return (
<div className="grades_wrapper">
<div className="grades_list">
{data.data.map((el, i) => {
return <div className="grade_element" key={el.id}>
<div className="grade_title" onClick={(e) => handleExpandClick(e)}>{el.lesson.name}</div>
<div className="expand_details">
<table>
<tr>
{el.gradebook ? <th>Студенти</th> : <th>Пусто</th>}
{el.gradebook && el.gradebook.columns.map((el, i) => {
return <th>{el.date}</th>
})}
{/*<th>Company</th>*/}
{/*<th>Contact</th>*/}
{/*<th>Country</th>*/}
</tr>
{el.gradebook && [...new Array(el.gradebook.columns[0].grades.length)].map((item, i) => {
return <tr>
<td>{el.gradebook.columns[0].grades[i].user.first_name} {el.gradebook.columns[0].grades[i].user.middle_name}</td>
{el.gradebook && el.gradebook.columns.map((element, grade_index) => {
// {console.log(el.gradebook)}
return <td>{el.gradebook.columns[grade_index].grades[i].value}</td>
})}
</tr>
})}
</table>
</div>
</div>
})}
</div>
</div>
)
}
}
export default Grades; |
const amqp = require('amqplib/callback_api')
const wretch = require('wretch')
global.fetch = require("node-fetch")
global.FormData = require("form-data")
global.URLSearchParams = require("url").URLSearchParams
const QUEUE = "alert"
amqp.connect('amqp://guest:Romain01@app.updatr.tech', function(error0, connection) {
if (error0) throw error0
connection.createChannel(function(error1, channel) {
channel.assertQueue(QUEUE, { durable: true })
// channel.sendToQueue(queue, Buffer.from(JSON.stringify(sample)))
channel.consume(QUEUE, msg => {
const message = JSON.parse(msg.content.toString())
const headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
if (message.DiscordAlert) {
const payload = JSON.stringify({
content: "```md\n" + Object.keys(message.report).map(key => {
dep = message.report[key]
return `${key} used : ${dep.packageVersion} latest : ${dep.lastVersion}`
}).join("\n") + "\n```"
})
wretch().url(message.DiscordWebHook).headers(headers).body(payload).post()
}
if (message.SlackAlert) {
const payload = JSON.stringify({
text: Object.keys(message.report).map(key => {
dep = message.report[key]
return `${key} used : ${dep.packageVersion} latest : ${dep.lastVersion}\n`
}).join("\n")
})
wretch().url(message.SlackWebHook).headers(headers).body(payload).post()
}
}, {
noAck: true
})
})
}) |
var archy = require('archy');
var chalk = require('chalk');
function listPage(){
var Page = this.model('Page');
var nodes = Page.map(function(page){
var title = page.title || '(no title)';
return title + '\n' + chalk.gray(page.path);
});
var s = archy({
label: 'Total: ' + Page.length,
nodes: nodes
});
console.log(s);
}
module.exports = listPage; |
// Copyright (C) 2008 Intershop Communications AG, all rights reserved.
// This file requires: ObjectGlue, CodeBlueprint.
// We need the function constructor to avoid leaking references in older browser versions, hence the evil bit.
// This file is not supposed to use any undeclared variables, because that would pollute global namespace.
// See also: http://code.google.com/p/jslint4java/ and http://www.jslint.com/lint.html
/*jslint evil: true, undef: true */
/*global ActiveXObject, alert, document, top, window, ObjectGlue, CodeBlueprint, tinyMCE, windowFor */
/**
* Constructor for the server browser
*/
function ServerBrowser(uri, media, links) {
this.browserTemplate = uri;
this.mediaBrowserURI = media;
this.linksBrowserURI = links;
// Groups: 1-base url, 2-session id, 3-parameters
var re = /(.*)\/HtmlEditor-\w+(;sid=[^\/?]*)?(?:\?(.*))?/;
var match = re.exec(this.mediaBrowserURI);
if (match) {
var sid = match[2] ? match[2] : "";
this.searchQueryURI = match[1] + "/ServerBrowser-SearchStaticContent" + sid;
this.lightboxURI = match[1] + "/ServerBrowser-Lightbox" + sid;
this.uriParameters = this.parseURIParameters(match[3]);
} else {
this.searchQueryURI = "ServerBrowser-SearchStaticContent";
this.lightboxURI = "ServerBrowser-Lightbox";
}
}
/* prototype */
ServerBrowser.extend(null, {
///// Instance properties
/**
* Encapsulates control functions
*/
controls: {
ID_UPLOAD_BUTTON: 'uploadButton',
ID_NEW_FOLDER_BUTTON: 'newFolderButton',
ID_RENAME_BUTTON: 'renameButton',
ID_DELETE_BUTTON: 'deleteButton',
/**
* Enables or disables the given control
*
* @param win The window
* @param node The element to change state
* @param state The new state, true for disabled, false for enabled
*/
setEnabled: function(win, node, state) {
if (typeof node === "string") {
node = win.document.getElementById(node);
}
if (node) {
if (state === false) {
node.disabled = true;
} else {
node.disabled = false;
node.removeAttribute("disabled");
}
}
},
/**
* Enables or disables the leaf dependent controls
*
* @param win The window
* @param state true|false
*/
setEnabledForLeaf: function(win, state)
{
this.setEnabled(win, this.ID_RENAME_BUTTON, state);
this.setEnabled(win, this.ID_DELETE_BUTTON, state);
},
/**
* Enables or disables the control dependent controls
*
* @param win The window
* @param state true|false
*/
setEnabledForNode: function(win, state)
{
this.setEnabled(win, this.ID_NEW_FOLDER_BUTTON, state);
this.setEnabled(win, this.ID_UPLOAD_BUTTON, state);
this.setEnabled(win, this.ID_RENAME_BUTTON, state);
this.setEnabled(win, this.ID_DELETE_BUTTON, state);
}
},
/**
* Encapsulates treeView functions
*/
treeView: {
ID_FOLDERTREE: "folder_tree",
CLASS_SUBFOLDERLIST: "subfolder_list",
CLASS_SELECTED: "selected",
CLASS_NODETITLE: "node_title",
/**
* returns the div inside the node with the class "subfolder_list"
*
* @param win The window
* @param node The node to get the subfolder div for
*
* @return the subfolder div element or null in case there is none.
*/
getSubfolderDiv: function(win, node)
{
var tags = node.childNodes;
for (var i = 0; i<tags.length; i++) {
if (tags[i].className.indexOf(this.CLASS_SUBFOLDERLIST)>=0)
{
return tags[i];
}
}
return;
},
/**
* checks and returns whether the given node is the selected node
*
* @param win The window
* @param node The node to check selection for
*
* @return true|false
*/
isSelected: function(win, node)
{
var tags = node.childNodes;
for (var i = 0; i<tags.length; i++) {
if (tags[i].className.indexOf(this.CLASS_NODETITLE)>=0)
{
return tags[i].className.indexOf("selected")>=0;
}
}
return false;
},
/**
* returns the id of the selected element in the node tree
*
* @param win The window
* @param node The node to get the selection for
*
* @return the id of the selected element or null in case the
* selection is not in the node's subtree
*/
getSelectedIdFor: function(win, node)
{
var tags;
// handle root separate
if (node.id == this.ID_FOLDERTREE) {
tags = node.childNodes;
} else {
var subfolderDiv = this.getSubfolderDiv(win, node);
// check if it is the selected node
if (node && (this.isSelected(win, node))) {
return subfolderDiv.id;
} else if (subfolderDiv) {
tags = subfolderDiv.childNodes;
} else {
return;
}
}
// Walk through the tree.
for (var i = 0; i<tags.length; i++) {
var sel = this.getSelectedIdFor(win, tags[i]);
if (sel) {
return sel;
}
}
return;
},
/**
* returns the id of the selected element
*
* @param win The window
* @return returns the id of the selected element inside the tree view
* or null in case there is no selection
*/
getSelectedId: function(win) {
var folderTree = win.document.getElementById(this.ID_FOLDERTREE);
return this.getSelectedIdFor(win, folderTree);
}
},
createCallback: function() {
return this.openBrowser.closureFor(this);
},
command: function(ev, name) {
var f = this["command" + name];
if (typeof f === "function") {
f.apply(this, arguments);
} else {
alert("Not implemented: " + name);
}
ObjectGlue.stopPropagation(ev);
},
commandDelete: function(ev, cmd, win) {
var selectedUri = win.serverBrowserSelectedURI;
var url = win.document.getElementById("params.server_browser");
if (!url || !selectedUri) {
return;
}
if (selectedUri.lastIndexOf("/") + 1 == selectedUri.length) {
url = url.getAttribute("deleteFolderPipeline");
} else {
url = url.getAttribute("deleteImagePipeline");
}
if (!url) {
return;
}
var name = this.getBasename(selectedUri);
tinyMCE.activeEditor.windowManager.open({
url: url + "?" + this.encodePostData({
ContextURI: selectedUri,
OldName: name
}),
width: 440,
height: 145,
inline: true,
resizable: false
}, {
server_browser: this,
refresh: this.refreshParent.closureFor(this, win)
});
},
commandRefresh: function(ev, cmd, win) {
this.refresh(win);
},
commandRename: function(ev, cmd, win) {
var contextUri = win.serverBrowserContextURI;
var selectedUri = win.serverBrowserSelectedURI;
var url = win.document.getElementById("params.server_browser");
if (!url || !contextUri || !selectedUri) {
return;
}
if (selectedUri.lastIndexOf("/") + 1 == selectedUri.length) {
url = url.getAttribute("renameFolderPipeline");
contextUri = this.getParentID(selectedUri);
} else {
url = url.getAttribute("renameImagePipeline");
}
if (!url) {
return;
}
var name = this.getBasename(selectedUri);
tinyMCE.activeEditor.windowManager.open({
url: url + "?" + this.encodePostData({
ContextURI: contextUri,
NewName: name,
OldName: name
}),
width: 470,
height: 200,
inline: true,
resizable: false
}, {
server_browser: this,
refresh: this.refreshParent.closureFor(this, win)
});
},
refresh: function(win) {
var state = win.refresh_state;
if (!(state && state.src)) {
return;
}
win.document.getElementById("busy_shield").style.display = "block";
this.sendRequest(state.src, this._reload.closureFor(this), {
src: state.src,
win: win
}, state.arg);
},
getParentID: function(uri) {
if (uri) {
var slash = uri.lastIndexOf('/', uri.length - 2);
if (slash != -1) {
return uri.substring(0, slash + 1);
}
}
},
getBasename: function(uri) {
if (uri) {
var end = uri.length;
var slash = uri.lastIndexOf('/');
if (slash + 1 == end) {
end = slash;
slash = uri.lastIndexOf('/', slash - 1);
}
if (slash != -1) {
return uri.substring(slash + 1, end);
}
}
},
refreshParent: function(win) {
var parentID = this.getParentID(win.serverBrowserSelectedURI);
if (!parentID) {
return;
}
var node = win.document.getElementById(parentID);
if (node) {
node = node.parentNode;
}
if (!node) {
return;
}
var src = node.getAttribute("src");
if (!src) {
return;
}
win.serverBrowserSelectedURI = parentID;
win.document.getElementById("selected_uri").value = "";
win.document.getElementById("selected_alt").value = "";
win.document.getElementById("selected_alt").title = "";
win.document.getElementById("selected_lb").value = "";
win.document.getElementById("busy_shield").style.display = "block";
this.sendRequest(src, this._reload.closureFor(this), {
src: src,
win: win
});
},
commandSearch: function(event, cmd, query, type) {
var src = this.searchQueryURI;
var node = ObjectGlue.getTarget(event);
var win = windowFor(node);
var selectedId = this.treeView.getSelectedId(win);
if (win && src) {
win.refresh_state = {
src: src + "?" + this.encodePostData({
OrganizationDomainId: this.uriParameters.OrganizationDomainId,
LocaleId: this.uriParameters.LocaleId,
Query: query,
Type: type
//Selection: selectedId
}),
arg: this.createParameters({
Query: query,
Version: 2
})
};
this.refresh(win);
}
},
commandNewFolder: function(event, cmd, win) {
var url = win.document.getElementById("params.server_browser");
url = url ? url.getAttribute("folderPipeline") : null;
if (!url) {
return;
}
tinyMCE.activeEditor.windowManager.open({
url: url + "?" + this.encodePostData({
OrganizationDomainId: this.uriParameters.OrganizationDomainId,
LocaleId: this.uriParameters.LocaleId,
ContextURI: win.serverBrowserContextURI
}),
width: 520,
height: 180,
inline: true,
resizable: false
}, {
server_browser: this,
refresh: this.refresh.closureFor(this, win)
});
},
commandUpload: function(event, cmd, win) {
var url = win.document.getElementById("params.server_browser");
url = url ? url.getAttribute("uploadPipeline") : null;
if (!url) {
return;
}
tinyMCE.activeEditor.windowManager.open({
url: url + "?" + this.encodePostData({ ContextURI: win.serverBrowserContextURI }),
width: 560,
height: 255,
inline: true,
resizable: false
}, {
server_browser: this,
refresh: this.refresh.closureFor(this, win)
});
},
openBrowser: function(field_name, url, type, win) {
tinyMCE.activeEditor.windowManager.open({
url: this.browserTemplate,
width: 740,
height: 520,
inline: true,
resizable: false
}, {
server_browser: this,
target_window: win,
target_name: field_name,
target_type: type
});
},
createParameters: function(o) {
var n, result = {};
if (this.uriParameters) {
for (n in this.uriParameters) {
if (this.uriParameters.hasOwnProperty(n)) {
result[n] = this.uriParameters[n];
}
}
}
if (o) {
for (n in o) {
if (o.hasOwnProperty(n)) {
result[n] = o[n];
}
}
}
return result;
},
encodePostData: function(data) {
if (!data) {
return "";
} else if (typeof data === "string") {
return data;
} else {
var result = [];
for (var n in data) {
if (data.hasOwnProperty(n)) {
result.push(String(n) + "=" + encodeURIComponent(data[n]));
}
}
result = result.join("&");
return result;
}
},
sendRequest: function(url, fun, opt, data) {
var request = this.createXMLHttpRequest();
var showError = this.showError.closureFor(this);
request.open(data ? "POST" : "GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = new Function(); // allow GC
if (request.status == 200) {
fun(request, opt);
} else {
showError(request.responseText);
}
}
};
var content = this.encodePostData(data);
if (content) {
request.setRequestHeader("Content-Length", content.length);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
request.send(content);
},
/**
* loads the serverproser for a specified xml content
*
* @param win The window
* @param xml The xml content containing the serverbrowser content
* @param src ?
*/
_onload: function (win, xml, src) {
if (!xml) {
win.server_browser = this;
var node, notifyClosure = this.notifyChange.closureFor(this);
if (win.document.body.addEventListener) {
win.document.body.addEventListener("DOMMouseScroll", notifyClosure, false);
win.document.body.addEventListener("mousewheel", notifyClosure, false);
node = win.document.getElementById("entry_list");
node.addEventListener("scroll", notifyClosure, false);
node.addEventListener("resize", notifyClosure, false);
} else if (win.document.body.attachEvent) {
win.document.body.attachEvent("onmousewheel", notifyClosure);
node = win.document.getElementById("entry_list");
node.attachEvent("onscroll", notifyClosure);
// Trident does not service resize event, user is bound to enter after drag.
win.document.documentElement.attachEvent("onmouseenter", notifyClosure);
} else {
win.document.body.onmousewheel = notifyClosure;
node = win.document.getElementById("entry_list");
node.onscroll = notifyClosure;
// Trident does not service resize event, user is bound to enter after drag.
win.document.documentElement.onmousenter = notifyClosure;
}
var type = win.tinyMCEPopup.getWindowArg('target_type');
var title = win.document.getElementById("title."+type);
// if (title) {
// tinyMCE.activeEditor.windowManager.setTitle(title.innerHTML, win.tinyMCEPopup.id);
// }
this.sendRequest(type == "file" ? this.linksBrowserURI : this.mediaBrowserURI,
this._reload.closureFor(this), { win: win });
return;
}
for (var n = xml.firstChild; n; n = n.nextSibling) {
if (n.nodeName == "collection") {
this.addItems(win, n, src);
} else if (n.nodeName == "libraries") {
this.addChildren(win, n, src);
}
}
win.document.getElementById("busy_shield").style.display = "none";
},
_reload: function(xhr, opt) {
if (xhr.responseXML && xhr.responseXML.nodeType == 9) {
this._onload(opt.win, xhr.responseXML, opt.src);
} else {
this.showError(xhr.responseText);
}
},
addItems: function(win, xml, src) {
for (var n = xml.firstChild; n; n = n.nextSibling) {
if (n.nodeName == "items") {
this.addChildren(win, n, src);
return;
}
}
},
/**
* Adds elements in the tree and content view
*
* @param win The window
* @param xml The xml containing the content to add
* @param src ?
*/
addChildren: function(win, xml, src) {
var parent = null;
var folders = [];
var resources = [];
var selected = null;
var searchfolder = win.document.getElementById("folder_searchresult");
var disconnected_searchfolder = false;
for (var n = xml.firstChild; n; n = n.nextSibling) {
var o = this.parseNode(n);
if (n.nodeName == "collection" || n.nodeName == "library") {
var folderBluePrint = new CodeBlueprint(win, "blueprint.folder");
if (!parent) {
if (src && src.indexOf(this.searchQueryURI)>=0)
{
// in case of the elements added are result of a search
parent = win.document.getElementById("folder_searchresult"); //searchfolder;
parent = this.findFolderNode(parent, src, n.id);
if (parent.id=="folder_searchresult")
{
parent = win.document.getElementById("folder_searchresult_sublist"); //searchfolder;
}
selected = parent;
if (o.id && parent.id == o.id) {
// Already present.
continue;
} else
{
if (o)
{
selected = o.id;
}
folders.push(folderBluePrint.getInnerHTML(parent));
}
}
else
{
parent = win.document.getElementById("folder_tree");
// Try to find the parent library or folder.
parent = this.findFolderNode(parent, src, n.id);
selected = parent;
if (o.title == "[..]") {
// Skip the synthetic parent node.
continue;
}
if (parent.id == "folder_tree") {
// Append new libraries.
parent.removeChild(searchfolder);
disconnected_searchfolder = true;
folders.push(folderBluePrint.getInnerHTML(parent));
selected = src ? o.id : null;
} else if (o.id && parent.id == o.id) {
// Already present.
continue;
}
}
}
folderBluePrint.append(folders, o);
} else if (n.nodeName == "resource") {
var resourceBluePrint = new CodeBlueprint(win, "blueprint.leaf");
resourceBluePrint.append(resources, this.adjustLeaf(o));
} else if (n.nodeName == "paging") {
this.addPaging(win, o, n);
break;
}
}
// Force redraw to take place in JS thread, otherwise Trident will corrupt the tree display.
folders = folders.join("");
resources = resources.join("");
var that = this;
win.setTimeout(function(){
if (parent && (src || folders)) {
if (folders.length > 0) {
parent.style.display = "";
}
parent.innerHTML = folders;
if (parent && (parent.id == "folder_tree") && disconnected_searchfolder) {
parent.appendChild(searchfolder);
}
if (parent && (parent.id == "folder_searchresult_sublist")) {
if (searchfolder.className.indexOf("closed") != -1) {
searchfolder.className = "server_browser_node opened";
}
}
if (folders.length === 0) {
/*
* Trident re-flows the div with text-height, even when empty.
* This is ugly, so we hide empty sub-trees.
*/
parent.style.display = "none";
}
}
var list = win.document.getElementById("entry_list");
list.scrollTop = 0;
list.scrollState = "";
if ((resources.length === 0) && src && (src.indexOf(that.searchQueryURI)>=0)) {
list.innerHTML = "<div class=\"server_browser_leaf\">No items found for your search</div>";
}
else {
list.innerHTML = resources;
}
win.setTimeout(function(){
if (typeof selected === "string") {
selected = win.document.getElementById(selected);
}
if (!selected) {
that.selectFolder(null, parent.firstChild, true);
}
if (selected && selected.id != "folder_tree") {
that.changeFolderSelection(win, selected.parentNode);
}
that.afterChange(win);
}, 40);
}, 10);
},
subfolderRe: /\bsubfolder_list\b/,
findFolderNode: function(node, uri, id) {
if (!uri) {
return node;
}
if (id) {
var idNode = node.ownerDocument.getElementById(id);
if (idNode && this.subfolderRe.test(idNode.className)) {
return idNode;
}
}
var tags = node.getElementsByTagName("DIV");
for (var i = tags.length; --i >= 0;) {
if (tags[i].getAttribute("src") == uri) {
tags = tags[i].childNodes;
for (var j = tags.length; --j >= 0;) {
if (tags[j].nodeName == "DIV" && this.subfolderRe.test(tags[j].className)) {
node = tags[j];
break;
}
}
break;
}
}
return node;
},
addPaging: function(win, paging, xml) {
win.document.getElementById("paging_title").innerHTML = paging.title;
// The document loaded from the XHR is not indexed by ID, so we have to use our own indexing.
var buttons = {};
buttons[paging.firstPageId] = this.setPagingIcon(win, "iconFirst", paging.iconFirst);
buttons[paging.previousPageId] = this.setPagingIcon(win, "iconPrevious", paging.iconPrevious);
buttons[paging.nextPageId] = this.setPagingIcon(win, "iconNext", paging.iconNext);
buttons[paging.lastPageId] = this.setPagingIcon(win, "iconLast", paging.iconLast);
for (var n = xml.nextSibling; n; n = n.nextSibling) {
if (n.nodeName == "collection") {
var id = n.getAttribute("id");
if (id && buttons[id]) {
buttons[id].setAttribute("uri", this.parseNode(n).uri);
buttons[id].disabled = "";
}
}
}
},
setPagingIcon: function(win, iconId, src) {
if (!iconId) {
return;
}
var icon = win.document.getElementById(iconId);
if (icon) {
icon.src = src ? src : icon.getAttribute("src");
return icon;
}
},
disablePageButtons: function(win) {
win.document.getElementById("paging_title").innerHTML = "";
this.setPagingIcon(win, "iconFirst").disabled = "disabled";
this.setPagingIcon(win, "iconPrevious").disabled = "disabled";
this.setPagingIcon(win, "iconNext").disabled = "disabled";
this.setPagingIcon(win, "iconLast").disabled = "disabled";
},
/**
* Returns an object with properties for all attributes and child elements of the given xml node.
*
* @param xml The xml node to parse.
* @return An object with properties set from the xml node.
*/
parseNode: function(xml) {
var result = {};
if (xml.attributes) {
for (var i = xml.attributes.length; --i >= 0;) {
var name = xml.attributes[i].nodeName;
result[name] = xml.getAttribute(name);
}
}
for (var n = xml.firstChild; n; n = n.nextSibling) {
if (n.firstChild && n.firstChild.nodeType == 3) {
result[n.nodeName] = n.firstChild.nodeValue;
}
}
return result;
},
parseURIParameters: function(s) {
var result = {};
var re = /&?([^=]+)(?:=([^&]+)?)?/g;
for (var match; !!(match = re.exec(s));) {
result[match[1]] = match[2] ? match[2] : 1;
}
return result;
},
adjustLeaf: function(o) {
o.src = this.findFallback(o.src, o.uri);
o.preview = this.findFallback(o.preview, o.icon);
o.encoded = this.findFallback(o.encodeduri, o.uri, o.src);
o.description = this.findFallback(o.description, o.title);
return o;
},
switchPage: function(win, node) {
if (node.disabled) {
return;
}
var src = node ? node.getAttribute("uri") : null;
if (win && src) {
win.document.getElementById("busy_shield").style.display = "block";
this.sendRequest(src, this._reload.closureFor(this), {
win: win
});
}
},
nodeTitleRe: /\bnode_title\b/,
changeFolderSelection: function(win, node) {
var divs = win.document.getElementById("folder_tree").getElementsByTagName("DIV");
for (var i = divs.length; --i >= 0;) {
var scan = divs[i];
if (scan.className) {
var k = scan.className.indexOf(" selected");
if (k != -1 && scan.parentNode != node) {
scan.className = scan.className.substring(0, k);
} else if (k == -1 && scan.parentNode == node && this.nodeTitleRe.test(scan.className)) {
scan.className = scan.className + " selected";
}
}
}
var readonly = node.getAttribute("readonly");
if (readonly=="true")
{
this.controls.setEnabledForNode(win, false);
}
else
{
var contextUri = this.getFolderURI(node);
if (contextUri) {
win.serverBrowserContextURI = contextUri;
this.controls.setEnabled(win, this.controls.ID_UPLOAD_BUTTON);
this.controls.setEnabled(win, this.controls.ID_NEW_FOLDER_BUTTON);
var parent = this.getParentID(contextUri);
if (parent) {
parent = win.document.getElementById(parent);
}
// a root navigation element in the tree view can not be deleted or renamed
this.controls.setEnabled(win, this.controls.ID_RENAME_BUTTON, parent ? true : false);
this.controls.setEnabled(win, this.controls.ID_DELETE_BUTTON, parent ? true : false);
} else {
// elements without context uri cannot be changed
win.serverBrowserContextURI = null;
this.controls.setEnabledForNode(win, false);
}
}
},
decodeURIParameter: function(s) {
if (s) {
// decodeURIComponent does not interpret + as per specification.
s = s.replace(/[+]/g, " ");
s = decodeURIComponent(s);
}
return s;
},
getContextURI: function(src) {
var q = src.indexOf('?');
if (q != -1) {
src = this.parseURIParameters(src.substring(q + 1));
if (src) {
if (src.ContextURI) {
return this.decodeURIParameter(src.ContextURI);
}
if (src.URI) {
return this.decodeURIParameter(src.URI);
}
}
}
},
getFolderURI: function(node) {
var result;
for (var scan = node.firstChild; scan && !result; scan = scan.nextSibling) {
if (scan.tagName == "DIV" && scan.className == "subfolder_list") {
result = scan.getAttribute("id");
}
}
if (!result) {
result = this.getContextURI(node.getAttribute("src"));
}
return result;
},
selectFolder: function(ev, node, open) {
ObjectGlue.stopProcessing(ev);
if (!node || node.disabled) {
return;
}
var src = node.getAttribute("src");
var win = windowFor(node);
win.document.getElementById("selected_lb").innerHTML = "";
if (win && src) {
var uri = node.getAttribute("uri");
if (uri && uri != src) {
// Folder with its own resource URI.
win.document.getElementById("selected_uri").value = uri;
var selected_alt = win.document.getElementById("selected_alt");
selected_alt.value = node.getAttribute("description");
selected_alt.title = selected_alt.value;
var desc = node.getAttribute("description2");
if (desc) {
var elem = win.document.getElementById("selected_lb");
elem.innerHTML = "(" + desc + ")";
}
}
var contextUri = this.getFolderURI(node);
if (contextUri) {
win.serverBrowserSelectedURI = contextUri;
}
if (open && node.className.indexOf("closed") != -1) {
node.className = "server_browser_node opened";
}
win.refresh_state = {
src: src
};
this.refresh(win);
}
},
toggleFolder: function(ev, node) {
ObjectGlue.stopProcessing(ev);
if (!node || node.disabled) {
return;
}
if (node.className.indexOf("opened") != -1) {
node.className = "server_browser_node closed";
var subs = node.getElementsByTagName("DIV");
for (var i = subs.length; --i >= 0;) {
var className = subs[i].className;
if (className.indexOf("selected") != -1) {
this.selectFolder(ev, node);
break;
}
}
} else if (node.className.indexOf("closed") != -1) {
node.className = "server_browser_node opened";
// Cannot determine if sub-folders are recent, refresh.
this.selectFolder(ev, node);
}
},
openLeaf: function(ev, win, node) {
ObjectGlue.stopProcessing(ev);
ObjectGlue.getTarget(ev).blur();
if (ev && (ev.detail >= 2 || ev.type == "dblclick")) {
return;
}
this.selectLeaf(ev, win, node);
var src = node.getAttribute("src");
var aTagContent = node.lastChild.innerHTML;
var add = "";
if(src.indexOf("?") == -1) {
// in case url rewrite is enabled the '?' doesn't exist
if(aTagContent.indexOf(".link") > -1) {
add = "&MimeType=text/html";
}
}
else {
add = "&MimeType=text/html";
}
var w = win.open(this.lightboxURI + "?URI=" + encodeURIComponent(src) + add,
"ServerBrowser_Lightbox", "height=100,left=" + ev.screenX +
",location=yes,menubar=no,status=no,toolbar=no,top=" + ev.screenY +
",width=100,resizable=yes,scrollbars=yes", true);
// Help finding window location.
win.lightBoxPosition = { x: ev.screenX, y: ev.screenY };
},
selectLeaf: function(ev, win, node) {
if (ev && (ev.detail >= 2 || ev.type == "dblclick")) {
var selected_uri = win.document.getElementById("selected_uri");
var selected_alt = win.document.getElementById("selected_alt");
this.applyValue(win, selected_uri.value, selected_alt.value);
return;
}
for (var scan = node.parentNode.firstChild; scan; scan = scan.nextSibling) {
if (scan.className) {
var i = scan.className.indexOf(" selected");
if (i != -1) {
scan.className = scan.className.substring(0, i);
}
}
}
if (win) {
node.className = node.className + " selected";
win.serverBrowserSelectedURI = this.getContextURI(node.getAttribute("img"));
win.document.getElementById("selected_uri").value = node.getAttribute("encoded");
win.document.getElementById("selected_alt").value = node.getAttribute("description");
win.document.getElementById("selected_alt").title = node.getAttribute("description");
var desc = node.getAttribute("description2");
if (desc) {
var elem = win.document.getElementById("selected_lb");
elem.innerHTML = "(" + desc + ")";
}
var readonly = node.getAttribute("readonly");
this.controls.setEnabledForLeaf(win, (readonly=='true')? false: true);
}
else
{
this.controls.setEnabledForLeaf(win, false);
}
},
applyValue: function(win, uri, alt, ssl) {
if (uri) {
var target = win.tinyMCEPopup.getWindowArg('target_window');
var id = win.tinyMCEPopup.getWindowArg('target_name');
if (ssl) {
var end = uri.lastIndexOf("[/ismediaobject]");
if (end == -1) {
end = uri.lastIndexOf("[/islink]");
}
if (end > 0) {
end = uri.lastIndexOf("|", end);
if (end > 0) {
uri = uri.substring(0, end) + "|kupussl|true" + uri.substring(end);
}
} else {
// for storefront links append the ssl-parameter
uri = uri + "?ssl=true";
}
}
target = target.document.getElementById(id);
target.value = uri;
if (typeof target.onchange === "function") {
target.onchange();
}
if (alt && target.form && target.form.alt) {
target.form.alt.value = alt;
}
}
win.tinyMCEPopup.close();
},
notifyChange: function(ev) {
this.queueChange(windowFor(ObjectGlue.getTarget(ev)));
},
queueChange: function(win) {
if (!win.notifyTimeout) {
var t = this;
win.notifyTimeout = win.setTimeout(function() {
win.notifyTimeout = null;
t.afterChange(win);
}, 200);
}
},
afterChange: function(win) {
var doc = win.document;
if (!doc) {
// Originating document not found.
return;
}
var list = doc.getElementById("entry_list");
if (!list) {
// No list to update.
return;
}
var state = String(doc.body.clientWidth) + "x" + String(doc.body.clientHeight);
if (win.bodyState != state) {
win.bodyState = state;
var n = doc.getElementById("toolbar_area").clientWidth - 210; // ori: 208
if (n != list.clientWidth) {
list.style.width = n + "px";
var box = doc.getElementById("control_area");
n = doc.getElementById("toolbar_area").clientWidth;
if (n != box.clientWidth) {
box.style.width = n + "px";
}
state = "dirty";
}
n = doc.documentElement.clientHeight - 95;
if (n != list.clientHeight) {
list.style.height = n + "px";
var tree = doc.getElementById("folder_tree");
n = doc.documentElement.clientHeight - 99;
if (n != tree.clientHeight) {
tree.style.height = n + "px";
}
state = "dirty";
}
if (state == "dirty") {
this.queueChange(win);
return;
}
}
var top = list.scrollTop - 100;
var bottom = list.scrollTop + list.clientHeight;
state = "top:" + top + ",bottom:" + bottom + ",width:" + list.clientWidth;
if (list.scrollState == state) {
return;
} else {
list.scrollState = state;
}
for (var node = list.firstChild; node; node = node.nextSibling) {
if (node.nodeType != 1 || node.tagName != "DIV") {
continue;
}
var pos = node.offsetTop;
if (pos < top) {
continue;
} else if (pos > bottom) {
break;
} else {
for (var child = node.firstChild; child; child = child.nextSibling) {
if (child.className == "leaf_frame") {
if (!child.style.backgroundImage) {
child.style.backgroundImage = "url(" + node.getAttribute("img") + ")";
}
break;
}
}
}
}
},
showError: function(text) {
if (typeof text === "string" && /<\s*body/i.test(text)) {
top.document.documentElement.innerHTML = text;
} else {
alert("Error: " + text);
}
},
/**
* Find the first non-null and non-undefined value in the list of parameters.
* @param value... variable list of value parameters.
*/
findFallback: function(/* value... */) {
for (var i = 0; i < arguments.length; i++) {
var v = this.trimString(arguments[i]);
if (v) {
return v;
}
}
},
/**
* Trim a string, removing all leading and trailing white space.
* @param s string to trim.
* @return trimmed string.
*/
trimString: function(s) {
return (typeof s === "string") ? s.replace(/^\s+|\s+$/g, "") : s;
}
});
////////////////////////////////////////////////////////////
// Decide on a DOM and XmlHTTPRequest implementation to use.
do {
if (window.XMLHttpRequest && window.DOMParser &&
document.implementation && document.implementation.createDocument) {
ServerBrowser.prototype.createXMLHttpRequest = new Function(
"return new XMLHttpRequest();");
ServerBrowser.prototype.parseXMLString = new Function("text",
"return new DOMParser().parseFromString(text, \"text/xml\");");
break;
}
try {
var http = new ActiveXObject("MSXML2.XmlHttp");
var dom2 = new ActiveXObject("MSXML2.DOMDocument");
ServerBrowser.prototype.createXMLHttpRequest = new Function(
"return new ActiveXObject(\"MSXML2.XmlHttp\");");
ServerBrowser.prototype.parseXMLString = new Function("text",
"var result = new ActiveXObject(\"MSXML2.DOMDocument\");" +
"result.async = \"false\";" +
"result.loadXML(text);" +
"return result;");
break;
} catch (e) {}
try {
var http = new ActiveXObject("Microsoft.XmlHttp");
var dom2 = new ActiveXObject("Microsoft.DOMDocument");
ServerBrowser.prototype.createXMLHttpRequest = new Function(
"return new ActiveXObject(\"Microsoft.XmlHttp\");");
ServerBrowser.prototype.parseXMLString = new Function("text",
"var result = new ActiveXObject(\"Microsoft.DOMDocument\");" +
"result.async = \"false\";" +
"result.loadXML(text);" +
"return result;");
break;
} catch (e) {}
try {
var http = new ActiveXObject("MSXML.XmlHttp");
var dom2 = new ActiveXObject("MSXML.DOMDocument");
ServerBrowser.prototype.createXMLHttpRequest = new Function(
"return new ActiveXObject(\"MSXML.XmlHttp\");");
ServerBrowser.prototype.parseXMLString = new Function("text",
"var result = new ActiveXObject(\"MSXML.DOMDocument\");" +
"result.async = \"false\";" +
"result.loadXML(text);" +
"return result;");
break;
} catch (e) {}
try {
var http = new ActiveXObject("MSXML3.XmlHttp");
var dom2 = new ActiveXObject("MSXML3.DOMDocument");
ServerBrowser.prototype.createXMLHttpRequest = new Function(
"return new ActiveXObject(\"MSXML3.XmlHttp\");");
ServerBrowser.prototype.parseXMLString = new Function("text",
"var result = new ActiveXObject(\"MSXML3.DOMDocument\");" +
"result.async = \"false\";" +
"result.loadXML(text);" +
"return result;");
break;
} catch (e) {}
} while (false); |
#!/usr/bin/env node
const program = require('commander');
program
.name('pos-cli env')
.command(
'add [environment]',
'Add new environment. Example: pos-cli env add staging --email user@example.com --url https://example.com'
)
.command('list', 'list all environments')
.parse(process.argv); |
import React from 'react'
import { shallow } from 'enzyme'
import RemoveFromWatchlist from './RemoveFromWatchlist'
describe('RemoveFromWatchlist Component', () => {
it('should only render the Remove from Watchlist button for Movies or TV Shows on the watchlist', () => {
let propsMock = {
isInWatchList: true,
type: 'Movie',
}
let component = shallow(<RemoveFromWatchlist {...propsMock} />)
expect(component.find('.c-remove-from-watchlist-button').exists()).toBe(true)
propsMock = {
isInWatchList: true,
type: 'TV',
}
component = shallow(<RemoveFromWatchlist {...propsMock} />)
expect(component.find('.c-remove-from-watchlist-button').exists()).toBe(true)
propsMock = {
isInWatchList: true,
type: 'Episode',
}
component = shallow(<RemoveFromWatchlist {...propsMock} />)
expect(component.find('.c-remove-from-watchlist-button').exists()).toBe(false)
propsMock = {
isInWatchList: false,
type: 'Movie',
}
component = shallow(<RemoveFromWatchlist {...propsMock} />)
expect(component.find('.c-remove-from-watchlist-button').exists()).toBe(false)
})
it('should remove the item from the watchlist when the button is clicked', () => {
const removeItemMock = jest.fn().mockResolvedValue()
const propsMock = {
isInWatchList: true,
remove: removeItemMock,
type: 'Movie',
}
const component = shallow(<RemoveFromWatchlist {...propsMock} />)
const mockedEvent = { target: {}, preventDefault: () => {} }
component.find('.c-remove-from-watchlist-button').simulate('click', mockedEvent)
expect(removeItemMock.mock.calls).toHaveLength(1)
})
})
|
import React from 'react';
import PropTypes from 'prop-types';
import MaterialUIForm from 'react-material-ui-form';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import withStyles from '@material-ui/styles/withStyles';
import { styles } from '../theme';
class UserInfoForm extends React.Component {
state = { error: undefined };
submit = (values, pristineValues) => {
if (values.password !== values.password2) {
this.setState({ error: 'Passwords must match' });
} else {
this.props.onSubmit(values, pristineValues);
}
};
render() {
const { onSubmit, classes, error } = this.props;
const formClass = [classes.form, classes.container].join(' ');
return (
<MaterialUIForm onSubmit={onSubmit} className={formClass}>
<Typography variant="subtitle1">Enter Account Details</Typography>
<TextField
label="Username"
name="username"
type="text"
value=""
variant="outlined"
data-validator="isRequired"
className={classes.textField}
/>
<TextField
label="Real Name"
name="realName"
type="text"
value=""
variant="outlined"
className={classes.textField}
/>
<TextField
label="Password"
name="password"
type="password"
value=""
variant="outlined"
data-validator="isRequired"
className={classes.textField}
/>
<TextField
label="Password (confirm)"
name="password2"
type="password"
value=""
variant="outlined"
data-validator="isRequired"
className={classes.textField}
/>
<Typography color="error" align="center" className={classes.textField}>
{error || this.state.error}
</Typography>
<Button
type="submit"
variant="contained"
color="primary"
className={classes.submit}
>
Sign Up
</Button>
</MaterialUIForm>
);
}
}
export default withStyles(styles)(UserInfoForm);
UserInfoForm.propTypes = {
onSubmit: PropTypes.func.isRequired,
classes: PropTypes.object.isRequired,
error: PropTypes.node
};
UserInfoForm.defaultProps = {
error: undefined
};
|
let action_type = ['ADD_TODO', 'TOGGLE_TODO', 'REMOVE_TODO', 'EDIT_TODO', 'CHANGE_COLOR'];
export function addTodo(text = '', completed = false) {
return {
type: 'ADD_TODO',
text,
completed
}
}
export function toggleTodo(index) {
return {
type: 'TOGGLE_TODO',
index
}
}
export function editTodo(index, text) {
return {
type: 'EDIT_TODO',
index,
text
}
}
export let test = 10;
export let todos = function (state = [{
text: 'Initial Content',
completed: false
}], action) {
let stat;
switch (action.type) {
case 'ADD_TODO':
//console.log('stat', state)
return state.concat([{ text: action.text, completed: false }])
case 'TOGGLE_TODO':
stat = [...state];
let comp = stat[action.index].completed;
stat[action.index].completed = !comp;
return stat
case 'EDIT_TODO':
stat = [...state];
stat[action.index].text = action.text;
return stat
default:
return state
}
}
export let color = function (state = 'default', action) {
switch (action.type) {
case 'CHANGE_COLOR':
return action.color;
default:
return state;
}
} |
import React from 'react'
import { Menu , Button} from 'semantic-ui-react'
export default class NavBar extends React.Component {
state = {}
handleItemClick = (e, { name }) => this.setState({ activeItem: name })
render() {
const { activeItem } = this.state
return (
<Menu >
<Menu.Item>
<img src='https://cdn3.vectorstock.com/i/1000x1000/61/97/lunch-box-icon-flat-style-vector-20186197.jpg' />
</Menu.Item>
<Menu.Item header>LUNCHBOX</Menu.Item>
<Menu.Item position='right'>
<Button>Log-in</Button>
</Menu.Item>
</Menu>
)
}
}
//
// <Menu.Item
// name='New Grocery'
// active={activeItem === 'reviews'}
// onClick={this.handleItemClick}
// />
|
import React, {Component} from 'react';
import SearchPage from './SearchPage.js';
import '../../../../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './HeaderSections.css'
import Image from 'react-bootstrap/Image'
class HeaderSections extends Component {
render(){
const categoryId=this.props.categoryId
return (
<div className={"container-fluid display"}>
<div className={"row "}>
<div className={"col-2 "}>
<img className="img-icon" src={this.props.categories[categoryId].backgroundUrl}/>
</div>
<div className={"col pt-3"}>
<h1 className={"font-weight-bold justify-content-flex-start text-left "}>{this.props.categories[categoryId].title}</h1>
</div>
</div>
<div className="row pt-5 justify-content-end ">
<div className={"col-4"}>
</div>
</div>
</div>
);
}
}
export default HeaderSections; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.