text stringlengths 7 3.69M |
|---|
'use strict'
module.exports = () => {
const rum = window.DD_RUM
const context = rum && rum.getInternalContext && rum.getInternalContext()
return { ...context }
}
|
const db = require("../db.js");
const S = require("sequelize");
class Favorites extends S.Model {}
Favorites.init(
{
Title: {
type: S.STRING,
},
Year: {
type: S.INTEGER,
},
imdbID: {
type: S.STRING,
},
Type: {
type: S.STRING,
},
Poster: {
type: S.STRING,
},
},
{ sequelize: db, modelName: "favorite" }
);
module.exports = Favorites;
|
import React from "react";
const Comment = (props) => {
const strip = (html) => {
let tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
return (
<div className="comment">
<p>{props.value.by}</p>
<p>{strip(props.value.text)}</p>
</div>
)
}
export default Comment; |
import React from 'react';
import Layout from "../components/layout"
import SEO from "../components/seo"
import PageLayout from "../components/pageLayout/pageLayout"
import { semejnueSporu } from "../contants"
const Sporu = () => (
<Layout>
<SEO title="Семейные споры"/>
<PageLayout page={semejnueSporu}/>
</Layout>
)
export default Sporu;
|
var Counter = React.createClass({
getInitialState: function () {
return { count: 0 };
},
increment: function () {
this.setState({ count: this.state.count + 1 });
},
render: function () {
return (
<div>
<h1>Counter</h1>
<p>{ this.state.count }</p>
<button onClick={ this.increment }>Increment</button>
</div>
);
}
});
React.renderComponent(
<Counter />,
document.body
); |
import React from "react";
import Card from "react-bootstrap/Card";
import Button from "react-bootstrap/Button";
const courseItem = (props) => {
let { course, loadCourseData } = props;
return (
<div className="mx-3 my-3 ">
<Card
bg={"Light"}
text={"dark"}
border={"secondary"}
style={{ width: "20rem" }}
>
<Card.Header style={{ background: `${course.color}` }}>
{" "}
Course ID: {course.id}{" "}
</Card.Header>
<Card.Body>
<Card.Title>{course.name}</Card.Title>
<Card.Text>
Year {course.year} Semester {course.semester}
</Card.Text>
<Button
variant="primary"
onClick={() => {
loadCourseData(course);
}}
>
Select the Course
</Button>
</Card.Body>
</Card>
</div>
);
};
export default courseItem;
|
/* global G7 */
$(function() {
'use strict';
(function($, window, undefined) {
/**
* @name Header
* @memberof G7.Modules
* @description Displays a page header with optional logo, headline, text and stretching background image.
*/
G7.Modules.Header = (function() {
/**
* @scope G7.Modules.Header
* @description Exposed methods from the G7.Modules.Header Module.
*/
return {
/**
* @name init
* @description G7.Modules.Header Module Constructor.
*/
init: (function() {
/**
* @description Selects the header element that is not a carousel.
*/
var $header = $('.header').not('.carousel');
if ($header.length > 0) {
/**
* @description Displays a streched background image in the header
*/
$header.backstretch($header.data('header-bg'));
}
})()
};
}());
})(jQuery, window);
}); |
import {combineReducers} from 'redux';
import {GET_CLIENTES_SUCCESS, SAVE_CLIENTE_SUCCESS, EDIT_CLIENTE_SUCCESS, DELETE_CLIENTE_SUCCESS, GET_CLIENTES_DATA_SUCCESS, GET_CLSEARCH_SUCCESS} from "../../actions/administracion/clientesActions";
function list(state=[], action){
switch(action.type){
case GET_CLIENTES_SUCCESS:
return action.clientes;
case SAVE_CLIENTE_SUCCESS:
return [action.cliente, ...state ];
case EDIT_CLIENTE_SUCCESS:
let newL = state.filter(a=>{
return a.id!=action.cliente.id
});
return [...newL, action.cliente];
case DELETE_CLIENTE_SUCCESS:
let acualL = state.filter(a=>{
return a.id!=action.clienteId;
});
return acualL;
default:
return state;
}
}
function allData(state={}, action) {
switch (action.type){
case GET_CLIENTES_DATA_SUCCESS:
return action.dataClient;
default:
return state;
}
}
function clienteSearch(state = {}, action) {
switch (action.type){
case GET_CLSEARCH_SUCCESS:
return action.clienteS;
default:
return state;
}
}
const clientesReducer = combineReducers({
list:list,
allData:allData,
clienteSearch:clienteSearch
});
export default clientesReducer; |
export default ({
state: {
histories: []
},
getters: {
getHistories: state => state.histories
},
mutations: {
setHistory (state, history) {
state.histories.push(history)
},
},
actions: {
addHistory (context, history) {
context.commit('setHistory', history)
}
}
})
|
// BASE Setup
// ===================================================
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, './client')));
// require('./server/config/mongoose.js');
// require('./server/config/routes.js')(app);
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
//API prefixes
app.use('/api', router);
app.listen(1337, function(){
console.log("Server is running at 1337");
}) |
export const menuData = [
{
title: 'Basic',
subMenu: [
{
title: 'Layout布局',
router: '/views/ui/layouts'
},
{
title: 'Color色彩',
router: '/views/ui/colors'
},
{
title: 'Icon图标',
router: '/views/ui/icons'
},
{
title: 'Button 按钮',
router: '/views/ui/buttons'
}
]
},
{
title: 'Form',
subMenu: [
{
title: 'Radio 单选框',
router: '/views/ui/radios'
},
{
title: 'Checkbox 多选款',
router: '/views/ui/checkboxs'
},
{
title: 'Input 输入框',
router: '/views/ui/inputs'
},
{
title: 'Input Number 计数器',
router: '/views/ui/inputnumbers'
},
{
title: 'Select 选择器',
router: '/views/ui/selects'
},
{
title: 'Cascader 级联选择器',
router: '/views/ui/cascaders'
},
{
title: 'Switch 开关',
router: '/views/ui/switch'
},
{
title: 'Slider 滑块',
router: '/views/ui/sliders'
},
{
title: 'Form 表单',
router: '/views/ui/forms'
}
]
},
{
title: 'Data',
subMenu: [
{
title: 'Table 表格',
router: '/views/ui/tables'
}
]
}
] |
require('dotenv').config();
const Pool = require('pg').Pool;
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const tokenController = require('../tokencontroller');
const secretKey = process.env.SECRET_KEY;
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: 'memedb',
password: process.env.DB_PASS,
port: 5432,
});
const saltRounnds = 10;
const createUser = (request, response) => {
const {first_name, last_name, email, pass} = request.body;
if (first_name === "" || last_name === "" || email === "" || pass === "") {
response.status(400).send("Missing information");
return
}
if (validateEmail(email)) {
bcrypt.hash(pass, saltRounnds, (err, hash) => {
checkEmailInUse(email)
.then((result) => {
if (result >= 1) {
response.status(400).send("Email already in use")
} else {
pool.query('INSERT INTO users (first_name, last_name, email, password) VALUES ($1,$2,$3,$4)', [first_name, last_name, email, hash], (error, results) => {
if (error) {
response.sendStatus(500);
return
}
tokenController.createToken({first_name: first_name, last_name: last_name, email: email})
.then((token) => response.status(201).json({token}));
});
}
});
});
} else {
response.status(400).send("Please enter a valid email address")
}
};
const login = (request, response) => {
const {email, pass} = request.body;
pool.query('SELECT * FROM USERS WHERE email = $1', [email], (error, results) => {
if (error) {
throw error
}
bcrypt.compare(pass, results.rows[0].password, (error, resp) => {
if (resp) {
const data = results.rows[0];
tokenController.createToken({first_name: data.first_name, last_name: data.last_name, email: data.email})
.then((token) => response.status(200).cookie("auth_token", token, {
maxAge: 3600,
httpOnly: true
}).send("login successful"));
} else {
response.status(400).send("Incorrect password")
}
});
});
};
async function checkEmailInUse (email) {
return new Promise((resolve, reject) => {
pool.query("SELECT * FROM users WHERE email = ($1)", [email], (error, results) => {
if (error) {
reject(0)
}
resolve(results.rowCount)
})
});
}
function validateEmail(email) {
let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
module.exports = {
createUser,
login
};
|
const express = require('express');
const router = express.Router();
module.exports = ({getUserByEmail}) => {
router.post("/login", (req, res) => {
const { email, password }=req.body;
getUserByEmail(email)
.then(user => {
req.session["userId"] = user.id;
res.status(200)
})
.then(user => {
res.redirect("/portfolio")
})
.catch(err => res.status(err.status).send(err.message))
});
return router;
} |
db.movies.updateMany({},{$set:{sequels:0}}); |
import endpoint from './endpoint';
export const getSongList = async (data) => {
await endpoint.get("/rest/v1/song")
.then(resp => {
console.log("Fetched songs");
data.setSongList(resp.data.songs);
})
.catch(e => console.log("Error:", e));
}
export const getSingleSong = async (data, id) => {
await endpoint.get(`/rest/v1/song/${id}`)
.then(resp => {
console.log(`Fetched song ${id}`);
data.setSingleSong(resp.data);
})
.catch(e => console.log("Error:", e));
}
export const editThenUpdateSong = async (data, song) => {
console.log("edit then update song");
await endpoint.post(`/rest/v1/song/edit`, song)
.then(resp => {
console.log(`Updated song ${song.id}`);
data.setSingleSong(resp.data);
})
.catch(e => console.log("Error:", e));
} |
$(document).ready(function (){
$('#btnHome').on('click', function (){
window.location = 'http://www.roguesensei.com/';
});
$('#btnWilson').on('click', function (){
window.location = 'http://www.roguesensei.com/wilson/index.html';
});
$('btnBack').on('click', function(){
history.back();
});
});
|
/**
* Created by gemini on 2017/5/18.
*/
import Vue from 'vue'
import filters from '~filters'
// use fiters
// sconsole.log(Object)
Object.keys(filters).forEach(key => Vue.filter(key, filters[key]))
|
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
window.$ = window.jQuery = require('jquery');
require('materialize-css/dist/js/materialize');
import Vue from 'vue'
import App from './components/layouts/App'
import axios from 'axios';
import VueAxios from 'vue-axios';
import router from './router'
Vue.use(VueAxios,axios);
Vue.axios.defaults.baseURL= 'http://tapcheck.oo/api';
Vue.config.productionTip = false;
Vue.router = router;
Vue.use(require('@websanova/vue-auth'),{
auth: require('@websanova/vue-auth/drivers/auth/bearer.js'),
http: require('@websanova/vue-auth/drivers/http/axios.1.x'),
router: require('@websanova/vue-auth/drivers/router/vue-router.2.x')
});
App.router = Vue.router;
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
});
|
import UpdateUserAvatarService from '../services/UpdateUserAvatarService';
import DiscStorageRepository from '../providers/multerProvider/DiscStorageProvider';
import BCriptHashProvider from '../providers/bcryptjsProvider/BCriptHashProvider';
import Repository from '../repository/Repository';
class AvatarController {
async update(req, res) {
const { id } = req.userId;
console.log(id);
const UpdateUserAvatar = new UpdateUserAvatarService({
BCriptHashProvider,
Repository,
DiscStorageRepository,
});
const newAvatar = await UpdateUserAvatar.execute({
id: id,
avatar: req.file.filename,
});
return res.status(200).json(newAvatar);
}
}
export default new AvatarController();
|
import React from 'react'
import Route1 from './Route1'
import Route2 from './Route2'
import Route3 from './Route3'
const App = (props) => (
<div>
<Route1 />
<Route2 />
<Route3 />
</div>
)
export default App |
const express = require("express");
const {db} = require('../../db/models/index');
const sequelize = require ("sequelize")
const router = express.Router()
const {User} = require("../../db/models/index")
module.exports=router; |
var ball = {
x: 100,
y: 100,
velocityX: 2,
velocityY: 2,
update: function () {
noFill();
stroke(255, 238, 130);
circle(this.x, this.y, 10);
this.x += this.velocityX;
this.y += this.velocityY;
},
};
//this portion of the code is the ball start off by setting var to ball and its position with x and y.
//velocity x is the speed of the ball going horizontal and velocity y is the speed vertically
//in the game the ball isnt filled because in the code noFill(); doesnt fill.
//in the next portion the function is updated to the ball moving 10 y instead of 2.
var paddle = {
x: 100,
y: 350,
w: 150,
h: 20,
update: function () {
noFill();
stroke(143, 251, 255);
rect(this.x, this.y, this.w, this.h);
if (keyIsDown(LEFT_ARROW)) {
this.x -= 2;
}
if (keyIsDown(RIGHT_ARROW)) {
this.x += 2;
}
},
};
// in this portion of the code this is the properties of the paddle
// giving it a width of 150px and height of 20px and its starting position (x 100,y 350)
// paddle doesnt have a fill in game becuase of noFill is which doesnt fill the paddle var.
// the rect or the shape of the paddle on this line were giving it the properties we defined eariler for the paddle
//using if statements to get the user input on the paddle and way its going to move when the button is pressed (arrow keys) -= meaning left and the += meaning right
var blocks = [];
for (var i = 0; i < 6; i++) {
blocks[i] = { x: i * 60, y: 10 };
}
// this part of the code is the array for the block that the ball hits during the game
// for loop is running to display how many blocks there are which is 6
function setup() {
createCanvas(400, 400);
}
function draw() {
background(70);
ball.update();
paddle.update();
//assuming these update the propertes of ball and paddle as the game goes on.
if (ball.x > 400) {
ball.x = 400;
ball.velocityX *= -1;
}
if (ball.x < 0) {
ball.x = 0;
ball.velocityX *= -1;
}
if (ball.y < 0) {
ball.y = 0;
ball.velocityY *= -1;
}
// somewhere it this if the ball goes off the canvas of the game the values representing the canvas and the position of the ball depending on this position of the ball will determine if it will either bounce off the side of the wall or if it hits the bottom of the canvas goes off the page.
if (hitTestPoint(ball.x, ball.y, paddle.x, paddle.y, paddle.w, paddle.h)) {
ball.velocityY *= -1;
}
//here guessing that if the ball hits the paddle during the game the Y velocity of the ball is decreased by 1 briefly
for (var i = 0; i < blocks.length; i++) {
var b = blocks[i];
rect(b.x, b.y, 60, 20);
//displaying the blocks during the game getting the information from the array blocks[];
if (hitTestPoint(ball.x, ball.y, b.x, b.y, 60, 20)) {
ball.velocityY *= -1;
// this code is similar to the one above but still shows the ball velocity Y speed is being drecreased to 1 briefly when coming into contact with the blocks that are being displayed.
//remove block from array
blocks.splice(i, 1);
}
}
}
function hitTestPoint(px, py, bx, by, bw, bh) {
if (px > bx && px < bx + bw) {
if (py > by && py < by + bh) {
return true;
}
}
return false;
}
//px and py are the paddles bx and by is the ball and bw and bh is the block its running a if statement to verify the positions of each.
|
'use strict'
module.exports = (sequelize, Sequelize) => {
const Round = sequelize.define('Round', {
round: {
type: Sequelize.INTEGER,
allowNull: false
}
},
{
freezeTableName: true,
timestamps: false,
paranoid: true,
underscored: true,
classMethods: {
associate: (models) => {
Round.hasMany(models.Game, {
foreignKey: 'round',
as: 'games'
})
}
}
});
return Round;
}; |
import React from 'react';
import { Route,Switch } from 'react-router-dom';
import Fullscreen from './Fullscreen';
import Instructions from './Instructions';
const App = () =>{
return(
<Switch>
<Route path="/" component={Fullscreen} exact/>
<Route path="/instructions" component={Instructions}/>
</Switch>
);
}
export default App; |
import LocalizedStrings from 'react-localization';
export const strings = {
en: {
next: 'Next',
},
fr: {
next: 'Prochain',
},
};
export default new LocalizedStrings(strings);
|
// init page
$(document).ready(function() {
// Materialize init
// ******************************
// init Modals
$('.modal').modal();
// init timepicker
$('.timepicker').timepicker();
// For adding seconds (00)
$('.timepicker').on('change', function() {
let receivedVal = $(this).val();
$(this).val(receivedVal + ":00");
});
// init datepicker
$('.datepicker').datepicker({
format: 'yyyy-mm-dd'
});
$('select').formSelect();
// ******************************
// Sign up script
$('#sign-up').click(event => {
event.preventDefault();
const username = $('#user-name').val().trim();
const password = $('#user-password').val().trim();
const email = $('#email').val().trim();
const phone = $('#phone-number').val().trim();
const validEmail = email.includes("@");
const validPhone = parseInt(phone);
if (!username || !password || !email) {
alert("Need to fill in")
} else if (!validEmail) {
alert("Not valid email")
} else if (phone.length === 0) {
const newSignUp = {
username: username,
password: password,
email: email,
phone: phone
};
$.ajax("/signup", {
type: "POST",
data: newSignUp,
}).then(newSignUpData => {});
} else if (phone.length > 0) {
if (phone.length != 10 || validPhone === NaN) {
alert("Not a valid phone number. Only include numbers (no dashes) and provide a 10 digit phone number (includes area code)");
}
else {
const newSignUp = {
username: username,
password: password,
email: email,
phone: phone
};
$.ajax("/signup", {
type: "POST",
data: newSignUp,
}).then(newSignUpData => {
// Create a default schedule for User once they sign up
const signupsched = [];
makeWeekendSchedule(signupsched);
makeWeekdaySchedule(signupsched);
makeWeekendSchedule(signupsched);
$.ajax("/api/weeks", {
type: "POST",
data: {
days: JSON.stringify(signupsched),
UserId: newSignUpData.id
}
})
});
}
}
});
// login script
$('#login').click(event => {
event.preventDefault();
const username = $('#username').val().trim();
const password = $('#password').val().trim();
if (!username || !password) {
alert("Please enter both a username and password")
} else {
const loginUser = {
username: username,
password: password,
};
$.ajax("/login", {
type: "POST",
data: loginUser,
}).then(loginUserData => {
location.replace("/dashboard");
});
}
});
// Update User
$('#update-user').click(event => {
event.preventDefault();
let id = $('#update-user').attr("data-id")
const username = $('#user-name1').val().trim();
const password = $('#user-password1').val().trim();
const email = $('#email1').val().trim();
const phone = $('#phone-number1').val().trim();
const validEmail = email.includes("@");
const validPhone = parseInt(phone);
if (!username || !email) {
alert("Need to provide both a username and an email.. Did not update")
location.reload();
} else if (!validEmail) {
alert("Not valid email. Did not update")
location.reload();
} else if (phone.length === 0) {
const updatedUser = {
username: username,
password: password,
email: email,
phone: phone
};
$.ajax("/users/" + id, {
type: "PUT",
data: updatedUser,
}).then(updatedUseData => { location.reload() });
} else if (phone.length > 0) {
if (phone.length != 10 || validPhone === NaN) {
alert("Not a valid phone. Did not update");
location.reload();
} else {
const updatedUser = {
username: username,
password: password,
email: email,
phone: phone
};
$.ajax("/users/" + id, {
type: "PUT",
data: updatedUser,
}).then(updatedUseData => { location.reload() });
}
}
});
// delete user script
$('#delete-user').click(event => {
event.preventDefault();
alert("Are you Sure?");
let id = $('#delete-user').attr("data-id");
$.ajax("/users/" + id, {
type: "DELETE",
}).then((deletedUserData) => { location.replace("/logout") });
});
// add task script
$('#add-task').click(event => {
event.preventDefault();
// Convert checkboxes to true/false
let is_reoccurring = ($('#reoccurring').val() === "on");
let is_autoSchedule = ($('#auto-schedule').val() === "on");
const title = $('#task-title').val().trim();
const startDate = $('#datepicker').val();
const endDate = $('#duedatepicker').val();
const startTime = $('#timepicker').val();
const endTime = $('#timeduepicker').val();
if (!title) {
alert("Need to give your task a title");
} else if (!startDate || !startTime) {
alert("Need to specify when the task starts")
} else if (startDate > endDate) {
alert("Your start date cannot be later than end date");
} else if (startDate === endDate && startTime > endTime) {
alert("Start time must be before end time");
} else {
const newTask = {
title: title,
description: $('#details').val().trim(),
endDate: endDate,
endTime: endTime,
startDate: startDate,
startTime: startTime,
timeToComplete: $('#length').val(),
is_autoSchedule: is_autoSchedule,
is_reoccurring: is_reoccurring,
UserId: $("#add-task").attr("data-id"),
userName: $("#add-task").attr("data-name"),
userEmail: $("#add-task").attr("data-email")
}
$.ajax("/api/tasks", {
type: "POST",
data: newTask
}).then(newTaskData => {
location.reload();
});
}
});
$(".update-task").click(function(event) {
event.preventDefault();
let taskId = $(this).attr("data-id");
// Convert checkboxes to true/false
let is_reoccurring = ($('#reoccurring').val() === "on");
let is_autoSchedule = ($('#auto-schedule').val() === "on");
const title = $('#task-title').val().trim();
const startDate = $('#datepicker').val();
const endDate = $('#duedatepicker').val();
const startTime = $('#timepicker').val();
const endTime = $('#timeduepicker').val();
if (!title) {
alert("Need to give your task a title");
} else if (!startDate || !startTime) {
alert("Need to specify when the task starts")
} else if (startDate > endDate) {
alert("Your start date cannot be later than end date");
} else if (startDate === endDate && startTime > endTime) {
alert("Start time must be before end time");
}
const updatedTaskObj = {
title: title,
description: $('#details').val().trim(),
endDate: endDate,
endTime: endTime,
startDate: startDate,
startTime: startTime,
timeToComplete: $('#length').val(),
is_autoSchedule: is_autoSchedule,
is_reoccurring: is_reoccurring,
}
$.ajax("/api/tasks/" + taskId, {
type: "PUT",
data: updatedTaskObj
}).then(() => {
location.reload();
})
})
// delete task script
$(".delete-task").click(function(event) {
event.preventDefault()
// Get the ID from the button.
let taskId = $(this).attr("data-id");
// Send the DELETE request.
$.ajax("/api/tasks/" + taskId, {
type: "DELETE"
}).then(
function() {
// Reload the page to get the updated list
location.reload();
}
);
});
// Schedule population
$("#open-schedule").click(event => {
let weekId = $("#open-schedule").attr("data-id");
$.ajax(`/api/weeks/${weekId}`, {
type: "GET"
}).then(weekRaw => {
let week = JSON.parse(weekRaw.days);
console.log(week);
// Set up calendar on weekly schedule
const weekcolumns = ["sun", "mon", "tues", "wed", "thur", "fri", "sat"];
// Create time labels
// Start with a column
const timeCol = $("<div>");
// add it to the calendar block
$(".week-cal").empty();
$(".week-cal").append(timeCol);
// Add header cell
const headerCell = $("<div>");
headerCell.text("time");
timeCol.append(headerCell);
timeCol.append($("<br>"));
// Add 24 cells
for (let i = 0; i < 24; i++) {
// Make cell
const newCell = $("<div>");
// Create hour
let label;
if (i === 0) {
label = 12;
} else if (i > 12) {
label = i - 12;
} else {
label = i;
}
// THIS CODE SUPPORTS HALF-HOUR TIME BLOCKS
// We're not using that right now but I'm leaving it in for future development
// if (i === 0 || i === 24 ) {
// label = '12';
// } else if (i === 1 || 1 === 25) {
// label = '12.5';
// } else if (i > 25 ) {
// label = `${(i - 24)/2}`;
// } else {
// label = `${i/2}`;
// }
// // translate number to time
// // first check if there's a decimal
// if (label[label.length-2] === ".") {
// // These are our half-hour times
// label = label.replace(".5", ":30");;
// } else {
// // the rest just get some zeroes
// label+=":00";
// }
// Add am/pm designation
if (i < 12) {
label += " am";
} else {
label += " pm";
}
// Set text
newCell.text(label);
// append to column
timeCol.append(newCell);
}
// for each day of the week,
for (let sched = 0; sched < 7; sched++) {
// make a column
const thisCol = $("<div>")
.addClass(`${weekcolumns[sched]} col center-align`);
// add it to the calendar block
$(".week-cal").append(thisCol);
// Add header cell
const headerCell = $("<div>");
headerCell.text(weekcolumns[sched]);
thisCol.append(headerCell);
thisCol.append($("<br>"));
// Add 24 cells
for (let i = 0; i < 24; i++) {
// Make cell
const newCell = $("<div>");
// Give it a unique identifier
newCell.data("ref", `${weekcolumns[sched]}${i}`);
// Set text equal to schedule of that day
newCell.text(week[sched][i]);
// Store it in data
newCell.data("category",week[sched][i]);
// Identify it as a cell for styling
newCell.addClass("week-cell");
// Append to col
thisCol.append(newCell);
}
}
// Clear categories
$(".category-list").empty();
// Add list of categories
const timeCategories = ["sleep", "work", "meal", "personal", "chores", "~"];
// For each category of time...
timeCategories.forEach(thisCat => {
// make a new div
const newCat = $("<div>");
newCat.data("category", thisCat);
newCat.text(thisCat);
// The first statement is selected, the rest are not
if (thisCat === "sleep") {
newCat.addClass(`sched-cat sched-cat-sel`);
} else {
newCat.addClass(`sched-cat sched-cat-unsel`);
}
// Append to list
$(".category-list").append(newCat);
});
// Script to set time as active
$(".category-list").click(event => {
const selected = event.target;
// first remove selected class from everything
if (selected.className.includes("sched-cat")) {
// get everything on the list
const divList = $(".category-list").children();
// Set to unselected
for (let divEl = 0; divEl < divList.length; divEl++) {
divList[divEl].classList.remove("sched-cat-sel");
divList[divEl].classList.add("sched-cat-unsel");
}
// Remove unsel from selected div and add sel
selected.classList.remove("sched-cat-unsel");
selected.classList.add("sched-cat-sel");
}
})
// Once calendar is populated, add calendar behavior
$(".week-cal").click(event => {
event.preventDefault();
// Get selected element
const timeEl = event.target
// Once they click on a week cell
if (timeEl.className === "week-cell") {
// Get the selected time category
const active = $(".category-list .sched-cat-sel").text();
// Replace the text in the cell
timeEl.innerText = active;
}
})
})
})
// schedule creation functions
function makeWeekendSchedule(schedArray) {
let day = [];
for (let weekend = 0; weekend < 24; weekend++) {
if (weekend < 10) {
day.push("sleep");
} else if (weekend < 12) {
day.push("chores");
} else if (weekend === 12 || weekend === 18) {
day.push("meal");
} else if (weekend < 22) {
day.push("personal");
} else {
day.push("sleep");
}
}
schedArray.push(day);
}
function makeWeekdaySchedule(schedArray) {
// We make five weekdays
for (let weekDay = 0; weekDay < 5; weekDay++) {
// Create the day
let day = [];
for (let time = 0; time < 24; time++) {
if (time < 8) {
day.push("sleep");
} else if (time === 8) {
day.push("~");
} else if (time < 12) {
day.push("work");
} else if (time === 12 || time === 18) {
day.push("meal");
} else if (time < 18) {
day.push("work");
} else if (time < 22) {
day.push("personal");
} else {
day.push("sleep");
}
}
schedArray.push(day);
}
}
// ===============================================
// AUTOSCHEDULER FUNCTIONALITY
// ===============================================
// Given a week object (seven arrays of 24 hours), an object
// The returned object has two child arrays, "personal" and "work", which contain day,hour references to a week
// today is the day of the week, and thisHour is the current hour. We won't get references past those points
function findAvailableTimes(weekObj, today, thisHour) {
// set up output object
// This list will contain paired values representing week and hour indices
const outputObj = {
work: [],
personal: []
};
// iterate through days, starting with today
for (let day = today; day < weekObj.length; day++) {
// Start at hour 0
let startHour = 0;
// If this is the first day we're considering, we start with the next available hour instead
if (day === today) {
startHour += thisHour + 1;
}
// iterate through hours
for (let hour = startHour; hour < weekObj[day].length; hour ++) {
// If the hour stores "work", store the ref
if (weekObj[day][hour] === "work") {
outputArr.work.push([day,hour]);
}
// If the hour stores "personal", store the ref
if (weekObj[day][hour] === "personal") {
outputArr.personal.push([day,hour]);
}
}
}
return outputObj;
}
function setStartTimes(userId) {
// A bit hacky, but this is the one place on the page where the week id is stored
const weekId = $("#open-schedule").attr("data-id");;
// Get tasks
$.ajax("/api/tasks", {
type: "GET"
}).then(taskArr => {
// Get week
$.ajax(`/api/week/${weekId}`, {
type: "GET"
}).then(week=> {
console.log(taskArr);
console.log(week);
})
})
}
});
|
(() => {
angular.module('kemia-app').config(chartConfig)
chartConfig.$inject = ['ChartJsProvider']
function chartConfig(ChartJsProvider) {
ChartJsProvider.setOptions({
colors: ['#803690', '#00ADF9', '#DCDCDC', '#46BFBD', '#FDB45C', '#949FB1', '#4D5360']
})
}
// RUN BLOCK
angular.module('kemia-app').run(kemiaRunBlock)
kemiaRunBlock.$inject = ['$rootScope', '$state', 'authenticationFactory']
function kemiaRunBlock($rootScope, $state, authenticationFactory) {
$rootScope.$on('$stateChangeStart', (event, toState) => {
if (toState.authenticate) {
authenticationFactory.checkAuth().then((response) => {
if (response.status === 'unauthenticated') {
// User isn’t authenticated
$state.go('login')
event.preventDefault()
}
})
}
})
}
})() |
var fs = require('fs')
// 异步读取
fs.readFile('../file/file.txt', 'utf-8', function(err, data) {
if (err) {
console.error(err)
} else {
console.log('readFile', data)
console.log('readFile end..')
}
})
var readFileSyncData = fs.readFileSync('../file/file.txt', 'utf-8')
console.log('readFileSyncData: ', readFileSyncData)
console.log('readFileSyncData end..') |
import React from "react";
import { Grid, Row, Col } from "react-bootstrap";
const Starship = ({ starship, isFetching }) => {
if (isFetching) {
return (
<Grid>
<Row>
<Col md={12}>
<span className="img-loader" />
</Col>
</Row>
</Grid>
);
}
return (
<Grid>
<h1>Starship: {starship.name}</h1>
<Row>
<Col md={12}>
<h3>Model: {starship.model}</h3>
<h3>Manufacturer: {starship.manufacturer}</h3>
<h3>Cost (in Credits): {starship.cost_in_credits}</h3>
</Col>
</Row>
</Grid>
);
};
export default Starship;
|
const http = require("http");
const bodyParser = require("body-parser");
const connect = require("connect");
const app = connect();
let isLogin = false;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.setHeader("Content-Type", "text/plain");
res.write("you posted:\n");
res.end(JSON.stringify(req.body, null, 2));
});
/*
app.use((req, res, next) => {
if (req.url.indexOf("favicon.ico") > 0) {
return;
}
next();
});
app.use((req, res, next) => {
if (isLogin) return next();
else {
console.log("No estás logado");
res.end("No estas logado");
}
});
app.use((request, response, next) => {
response.setHeader("Content-Type", "text/html");
response.end("Hello <strong>HTTP</strong>!");
});
*/
app.listen(4000);
http.createServer(app);
|
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import axios from './axios-backend/http-common'
import VueAxios from 'vue-axios'
import router from './router'
import store from './store'
import BootstrapVue from 'bootstrap-vue'
import Vuelidate from 'vuelidate'
import VueMoment from 'vue-moment'
import CxltToastr from 'cxlt-vue2-toastr'
import Multiselect from 'vue-multiselect'
Vue.config.productionTip = false
Vue.config.devtools = true
/* eslint-disable */
// Bootstrap
Vue.use(BootstrapVue)
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
//Serve para fazer o binding do axios (preconfigurado) na instancia do Vue
//(não precisa mais fazer o import do axios nos components)
Vue.use(VueAxios, axios)
Vue.use(Vuelidate)
Vue.use(VueMoment)
Vue.use(CxltToastr)
import 'cxlt-vue2-toastr/dist/css/cxlt-vue2-toastr.css'
Vue.component('multiselect', Multiselect)
new Vue({
el: '#app',
axios,
store,
router,
components: { App },
template: '<App/>'
})
|
import React,{useState} from 'react';
import {View, Text, TouchableOpacity} from 'react-native';
import styles from '../styles/ToastStyles';
// This is outside your function. It is supposed to be inside and before return
/* It also seems like you are using an old method. Maybe try going about it using
const method and useState. */
/*state = {
textValue: 'Toast'
}
//when you press the button it should alternate from Youve moved the Toast up! to Youve moved the Toast down!
onPress = () => {
this.setState({
textValue: 'Youve moved the Toast up!'
})
}
onPress = () => {
this.setState({
textValue: 'Youve moved the Toast down!'
})
}*/
function Toast(){
const [count, setCount] = useState(0);
var upToast = "You've moved toast up";
var downToast = "You've moved toast down";
var up = -500;
var box = null;
if (count === 0) {
box = (<TouchableOpacity
onPress={()=>{setCount(!count)}}
>
<Text>{upToast}</Text>
</TouchableOpacity>
)
}
if (count === 1) {
box = (<TouchableOpacity
style={{marginBottom: up}}
onPress={()=>{setCount(!count)}}
>
<Text>{downToast}</Text>
</TouchableOpacity>
)
}
else {
box = <Text>Toast</Text>
}
return (
<View style={styles.toast}>
<Text>{box}</Text>
</View>
)}
export default Toast;
//<Text onPress={this.onPress}>Toast</Text>
//<Button title="Toast" onPress={this.onPress} />
/*export default class App extends Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
onPress = () => {
this.setState({
count: this.state.count+1
})
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.button}
onPress={this.onPress}
>
<Text> Toast </Text>
</TouchableOpacity>
<View style={[styles.countContainer]}>
<Text style={[styles.countText]}>
{ this.state.count !== 0 ? this.state.count: null}
</Text>
</View>
</View>
)
}
}*/ |
const container = document.querySelector(".container");
const h2 = document.querySelector("#hex");
function changeBg() {
randomColor = "#000000".replace(/0/g, function() {
return (~~(Math.random() * 16)).toString(16);
});
container.style.background = randomColor;
h2.innerHTML = `Hex Color: ${randomColor}`;
} |
// Borrowed from https://gist.github.com/hoschi/6538249ad079116840825e20c48f1690
// Note that reloading sagas has several issues/caveats to be aware of.
// See https://github.com/yelouafi/redux-saga/issues/22#issuecomment-218737951 for discussion.
import { take, fork, cancel } from 'redux-saga/effects'
import rootSaga from './root-saga'
export const CANCEL_SAGAS_HMR = 'CANCEL_SAGAS_HMR'
function createAbortableSaga (saga) {
if (__DEV__) {
return function * main () {
const sagaTask = yield fork(saga)
yield take(CANCEL_SAGAS_HMR)
yield cancel(sagaTask)
}
} else {
return saga
}
}
export const SagaManager = {
startSagas (sagaMiddleware) {
sagaMiddleware.run(createAbortableSaga(rootSaga))
},
cancelSagas (store) {
store.dispatch({
type: CANCEL_SAGAS_HMR
})
}
}
|
import qs from 'qs'
// const wxBaseUrl = 'http://localhost:8080'
const wxApiUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize'
// const wxAppSecret = '0e71b8c395ff717c11815a5d6680b501'
export default class {
// 换取微信code
static wxCode () {
let params = {
appid: 'wx0e7778296caadc9a',
redirect_uri: 'http://www.zhimalivip.com/auth',
response_type: 'code',
scope: 'snsapi_userinfo',
state: 'zhimali'
}
let gourl = wxApiUrl + '?' + qs.stringify(params) + '#wechat_redirect'
// console.log(gourl)
window.location.href = gourl
}
}
// qs.stringify 序列化url形式 gourl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx47e4a904266b9c84....#wechat_redirect'
//默认导出一个构造方法,只能直接调用,实例对象无此方法 |
// pages/home/home.js
Page({
/**
* 页面的初始数据
*/
data: {
goods: {
id: 1,
image: '/images/goods1.png',
title: '新鲜梨花带雨',
price: 0.01,
stock: '有货',
detail: '这里是梨花带雨详情。',
parameter: '125g/个',
service: '不支持退货'
},
num: 0,
totalNum: 0,
hasCarts: false,
curIndex: 0,
show: false,
scaleCart: false
},
addCount() {
let num = this.data.num;
num++;
this.setData({
num: num
})
const self = this;
// const num = this.data.num;
//let total = this.data.totalNum;
self.setData({
show: true
})
setTimeout(function () {
self.setData({
show: false,
scaleCart: true
})
setTimeout(function () {
self.setData({
scaleCart: false,
hasCarts: true,
//totalNum: num + total
num: num
})
}, 200)
}, 300)
},
minusCount() {
let num = this.data.num;
if(num === 0){
self.setData({
hasCarts: false
});
return;
}
num--;
this.setData({
num: num
})
},
addToCart:function(e) {
console.log("加入购物车");
wx.switchTab({
url: '../cart/cart',
})
},
bindTap:function(e) {
const index = parseInt(e.currentTarget.dataset.index);
this.setData({
curIndex: index
})
}
}) |
'use strict';
const serializerPath = require('jest-serializer-path');
const cloneDeep = require('lodash.clonedeep');
const rewireExternalSvgLoader = require('..');
expect.addSnapshotSerializer(serializerPath);
const mockConfig = {
module: {
rules: [
{
test: /\.(js|jsx|mjs)$/,
enforce: 'pre',
use: [
{ options: {}, loader: 'path/to/eslint-loader/index.js' },
],
include: 'path/to/src',
},
{
oneOf: [
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: 'path/to/url-loader/index.js',
options: {},
},
{
test: /\.(js|jsx|mjs)$/,
include: 'path/to/src',
loader: 'path/to/babel-loader/lib/index.js',
options: {},
},
{
test: /\.css$/,
use: [
'path/to/style-loader/index.js',
{
loader: 'path/to/css-loader/index.js',
options: { importLoaders: 1 },
},
{
loader: 'path/to/postcss-loader/lib/index.js',
options: {},
},
],
},
{
exclude: [/\.js$/, /\.html$/, /\.json$/],
loader: 'path/to/file-loader/dist/cjs.js',
options: { name: 'static/media/[name].[hash:8].[ext]' },
},
],
},
],
},
plugins: [],
};
it('should modify the webpack config correctly for development', () => {
const result = rewireExternalSvgLoader(cloneDeep(mockConfig), 'development');
expect(result).toMatchSnapshot();
});
it('should modify the webpack config correctly for production', () => {
const result = rewireExternalSvgLoader(cloneDeep(mockConfig), 'production');
expect(result).toMatchSnapshot();
});
it('should override the default test / include / exclude', () => {
const result = rewireExternalSvgLoader(cloneDeep(mockConfig), 'development', {
test: 'svg',
include: 'foo',
exclude: 'bar',
});
expect(result).toMatchSnapshot();
});
it('should pass options to the loader', () => {
const result = rewireExternalSvgLoader(cloneDeep(mockConfig), 'development', {
loaderOptions: { name: 'foo.svg' },
});
expect(result).toMatchSnapshot();
});
it('should pass options to the plugin', () => {
const result = rewireExternalSvgLoader(cloneDeep(mockConfig), 'development', {
pluginOptions: { emit: false },
});
expect(result).toMatchSnapshot();
});
it('should allow usage with compose', () => {
expect(rewireExternalSvgLoader(cloneDeep(mockConfig), 'development'))
.toEqual(rewireExternalSvgLoader()(cloneDeep(mockConfig), 'development'));
expect(rewireExternalSvgLoader(cloneDeep(mockConfig), 'development', { include: 'foo' }))
.toEqual(rewireExternalSvgLoader({ include: 'foo' })(cloneDeep(mockConfig), 'development'));
});
|
'use strict';
$.ajax({url: "https://mangahost4.com", success: function(result){
$("#mural").html(result);
}});
var aux = new Object();
//Variavel usada para obter uma resposta
//file:///android_asset/index.html
aux.call_result = null;
aux.Screen = new Array();
(aux.Screen).push('lancamentos');
try {
aux.Pasta = WebApp.DiretorioDownload()+'/Otaku Host';
}
catch(err) {
console.log("IsNotApp");
}
aux.Type = 'Anime';
aux.AniManGenero = "";
aux.AniManIndex_Fav = null;
aux.Pag = 0;
aux.WebPlayer = false;
aux.FireBase = null;
//Fontes de animes e mangás
aux.Fonts = new Object();
aux.AniManSource = new Object();
//Fontes de videos
aux.FontsVids = new Object();
//Lançamentos
aux.inicial = new Object();
aux.inicial['Manga'] = new Array();
aux.inicial['Anime'] = new Array();
aux.BibliotecaIdioma = new Object();
//Anuncios
aux.InterstitialTime = 0;
aux.InterstitialHtml = "";
//Configuração de idiomas
aux.Bandeiras = {
"PT-Br":"🇧🇷",
"En-US":"🇱🇷"
};
aux.Generos = {
"PT-Br":['Aventura','Escolar','Ecchi','Esporte','Comedia','Drama','Fantasia','Harem','Mecha','Shoujo','Seinen','Shounen','Romance','Terror'],
"En-US":['Adventure', 'School', 'Ecchi', 'Sport', 'Comedy', 'Drama', 'Fantasy', 'Harem', 'Mecha', 'Shoujo', 'Seinen', 'Shounen' , 'Romance ','Horror']
};
//inject
aux.Biblioteca = null;
aux.EpTratamento = [' ', ':','-'];
/*
- CONTROLADORES DE CHAMADA AO SISTEMA
*/
//1 - Caso estejamos esperando uma chamada async do sistema, devemos esperar que ela termine para que possamos entrar.
aux.android_sinaleiro = true;
//Quais elementos de chamada devemos exibir modal de loading?
aux.android_callModal = ['ajax'];
//Chamada não Async, save_file_manga ira chamar outra função que se tornara 'recursiva'
aux.android_callIgnore = ['save_file_manga','assistir','open_link','exit','download','ads','analytics','interstitial_show','interstitial_close','inject'];
//bloqueador de paginação, ele vira true somente em 'generos' e 'pesquisa'
aux.PaginacaoDetectCheck = false;
//Controles de download
aux.DownloadsConfig = new Object();
//Usuario pode pausar todos downloads
aux.DownloadsConfig.Farol = true;
//Controle sobre requisição de download
aux.DownloadsConfig.Request = false;
//File, (Nome,Capitulo,Sources)
aux.DownloadsConfig.Fila = new Array();
aux.Data = new Date();
aux.Data = (aux.Data).getFullYear()+'-'+String((aux.Data).getMonth() + 1).padStart(2, '0')+'-'+String((aux.Data).getDate()).padStart(2, '0');
$(document).ready(async function(){
M.AutoInit();
$('#loading').modal('open');
$('#progress').modal({ending_top: '50%'});
$('#SlideDownload').sidenav({edge:'right'});
$('#loading').modal({
dismissible: false
});
$("#login").modal({
onCloseEnd : function(){
aux.CodUserQuerest = undefined;
}
});
$("#epcap").modal({
onCloseEnd : function(){
$("#fontsopc").html("");
}
});
$('#progress').modal({
dismissible: false
});
$( "#list_epcap" ).change(function() {
$("#fontsopc").html("");
});
$( "#nome_pesquisa" ).keypress(function( event ) {
if ( event.which == 13 ) {
$('#pesquisa ul').html("");
pesquisa(1);
}
});
$('#temporada input[type="checkbox"]').on('change', function() {
$('#temporada input[type="checkbox"]').not(this).prop('checked', false);
});
$(document).on('click', '#toast-container .toast', function() {
$(this).fadeOut(function(){
$(this).remove();
});
});
//Carregar Fontes
load_fonts_Mangas();
load_fonts_Animes();
screen('lancamentos');
favoritos('update');
if(await WebApp.DirExist(aux.Pasta)==false){
await WebApp.CreateDir(aux.Pasta);
await WebApp.CreateDir(aux.Pasta+'/capas');
await WebApp.CreateDir(aux.Pasta+'/mangas');
if(await WebApp.DirExist(aux.Pasta)==false){
alert(908);
return null;
}
}
//Carregar dados de Download, caso usuario tenha fechado app sem terminar todos download'
if(WebApp.GetBD("DownloadsFila",0)!=0){
aux.DownloadsConfig.Fila = JSON.parse(WebApp.GetBD("DownloadsFila",0));
}
//Controlador de rolagem de paginas generos
$("#genero").scroll(async function() {
if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
await generos_pesquisa(aux.Pag+1);
}
});
$("#genero").on('click', 'input[type="checkbox"]', function() {
$('input[type="checkbox"]').not(this).prop('checked', false);
});
//Controlador de rolagem de paginas pesquisa
$("#pesquisa").scroll(async function() {
if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight-1) {
await pesquisa(aux.Pag+1);
}
});
//Capturar erros
$.Deferred.exceptionHook = function (err, stackTrace) {
// 'err' is what you throw in your deferred's catch.
//$('.modal').modal('close');
//alert('J'+err);
}
//Exibir fontes para selecionar. Manga
$("#list_MangaSources").html(`<option value="null" selected>Mangá</option>`);
for(let cont=0;cont<(aux.Fonts['Manga']).length;cont++){
$("#list_MangaSources").append(`
<option value="${cont}">${aux.Bandeiras[aux.Fonts['Manga'][cont].Idioma]} ${aux.Fonts['Manga'][cont].Nome}</option>
`);
}
//Exibir fontes para selecionar. Anime
$("#list_AnimesSources").html(`<option value="null" selected>Anime</option>`);
for(let cont=0;cont<(aux.Fonts['Anime']).length;cont++){
$("#list_AnimesSources").append(`
<option value="${cont}">${aux.Bandeiras[aux.Fonts['Anime'][cont].Idioma]} ${aux.Fonts['Anime'][cont].Nome}</option>
`);
}
if(WebApp.GetBD("AniManSource_Manga",0)==0){
aux.AniManSource['Manga'] = WebApp.GetBD("AniManSource_Manga",0);
$("#list_MangaSources").val(aux.AniManSource['Manga']).attr("selected", "selected");
}else{
$("#Fontes_Config").modal('open');
}
if(WebApp.GetBD("AniManSource_Anime",0)==0){
aux.AniManSource['Anime'] = WebApp.GetBD("AniManSource_Anime",0);
$("#list_AnimesSources").val(aux.AniManSource['Anime']).attr("selected", "selected");
}else{
$("#Fontes_Config").modal('open');
}
console.log("Html: Iniciado atts");
WebApp.Ajax('https://otakuhost.github.io/WebApp/version.json',''+function(Code,Result){
Result = JSON.parse(htmlDecode(Result));
if(WebApp.AppVersion()+0<Result['versionApk']){
//Aviso APK atualizar
M.toast("AttApk...");
console.log("Html: Att apk necessario");
return null;
$("#nova_versao h5").text("Otaku Host V"+Result.find('#versao').text());
$("#nova_versao .desc").html(Result.find('#info').html());
$("#nova_versao .link").attr('href',Result.find('#link').text());
$("#nova_versao").modal("open");
}else if(WebApp.GetBD("WebAppVersion",0)<Result.versionWebApp){
//Atualizar AppOffline
M.toast("AttWApp...");
WebApp.SetBD("WebAppVersion",Result.versionWebApp);
console.log("Html: Iniciado atts html");
WebApp.Ajax('https://otakuhost.github.io/WebApp/index.html',''+function(Code,Result){
WebApp.SetBD("servidorHtml",htmlDecode(Result));
WebApp.ReloadScreem();
});
}
});
//WebPlayer email
if(WebApp.GetBD("Email",0)==0){
$("#email_webPlayer").val(WebApp.GetBD("Email",0));
$("#web_PlayerModal p").html(`<b>Codigo</b>: `+WebApp.GetBD("Codigo",0));
aux.FireBase = new Firebase('https://otakuhostapp-d36e8.firebaseio.com/user/'+md5(WebApp.GetBD("Email",0))+'-'+ WebApp.GetBD("Codigo",0));
}
await historico(null);
await update_biblioteca();
await update_download_view();
await process_downloads_mangas(null,null);
});
async function email_set(){
if(($("#email_webPlayer").val()).length>5){
WebApp.SetBD('Email',$("#email_webPlayer").val());
WebApp.SetBD('Codigo',Math.floor(Math.random() * 999)+1);
$("#web_PlayerModal p").html(`<b>Codigo</b>: `+WebApp.GetBD("Codigo",0));
aux.FireBase = new Firebase('https://otakuhostapp-d36e8.firebaseio.com/user/'+md5(WebApp.GetBD("Email",0))+'-'+WebApp.GetBD("Codigo",0));
}
}
async function configurar_fontes(){
if($("#list_AnimesSources").val()=="null" || $("#list_MangaSources").val()=="null"){
alert("Selecione uma fonte!");
}else{
WebApp.SetBD('AniManSource_Manga',$("#list_MangaSources").val());
WebApp.SetBD('AniManSource_Anime',$("#list_AnimesSources").val());
aux.AniManSource['Manga'] = WebApp.GetBD("AniManSource_Manga",0);
aux.AniManSource['Anime'] = WebApp.GetBD("AniManSource_Anime",0);
aux.inicial['Manga'] = new Array();
aux.inicial['Anime'] = new Array();
$("#Fontes_Config").modal('close');
}
}
async function noticias(){
loading(true);
WebApp.Ajax('https://ptanime.com/feed/',''+function(Code,Result){
if(Code==200){
aux.Noticias = htmlDecode(Result);
$("#noticias").html("");
aux.Noticias = (aux.Noticias).split("<item>");
let titulo="",
img="",
text="";
console.log("tamanho: "+ console.log("Hello World"));
for(let cont=1;cont<(aux.Noticias).length;cont++){
titulo = (aux.Noticias[cont]).split("<title>")[1];
titulo = titulo.split("</title>")[0];
text = (aux.Noticias[cont]).split("<content:encoded>")[1];
text = text.split("</content:encoded>")[0];
text = text.split("href=").join("href=");
text = text.split("width=").join("w=");
text = text.split("height=").join("h=");
text = text.split("style=").join("s=");
img = text.split('src="')[1];
img = img.split('"')[0];
$("#noticias").append(`
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="${img}">
</div>
<div class="card-content grey darken-3">
<span class="card-title activator white-text">${titulo}<i class="material-icons right">more_vert</i></span>
</div>
<div class="card-reveal black-text">
<span class="card-title grey-text text-darken-4">${titulo}<i class="material-icons right">close</i></span>
<div class="corpo">${text}</div>
</div>
</div>
`);
}
screen('noticias');
}
loading(false);
});
}
//Controlador de anuncio full screen
async function interstitialShow(){
console.log("Call intensival");
WebApp.Ads_Intensival();
}
//Atualiza o sistema de visualização de download
async function update_download_view(){
$("#SlideDownload").html("");
for(let cont=0;cont<(aux.DownloadsConfig.Fila).length;cont++){
$("#SlideDownload").append(`
<li class="collection-item">
<div class="row">
<div class="col s3 l3 m3">
<img class="cover" src="${aux.DownloadsConfig.Fila[cont].Img}">
</div>
<div class="col s9 l9 m9">
<b>${aux.DownloadsConfig.Fila[cont].Nome} - ${aux.DownloadsConfig.Fila[cont].Capitulo}</b><br>
<div class="chip">
<img src="download_icon.png" alt="Contact Person">
<i class="porcent">0</i>%
<i onclick="process_downloads_mangas('delet',aux.DownloadsConfig.Fila[${cont}]);" class="right material-icons">close</i>
</div>
</div>
</div>
</li>
`);
}
}
//Le ou deleta capituloda biblioteca
async function biblioteca_cap(Acao){
if(Acao=='read'){
aux.MangasSources = await WebApp.GetFiles(`${aux.Pasta}/mangas/${aux.AniMan}/${$("#biblioteca_caps select").val()}`);
aux.MangasSources = (aux.MangasSources).split('[#]');
(aux.MangasSources).sort();
$("#leitor").html("");
$(".modal").modal('close');
screen('leitor');
for(let cont=0;cont<(aux.MangasSources).length;cont++){
$("#leitor").append(`<img src="${aux.MangasSources[cont]}">`);
}
//WebApp.StatusBar('false');
}else{
let check = await WebApp.DeleteDir(`${aux.Pasta}/mangas/${aux.AniMan}/${$("#biblioteca_caps select").val()}/`);
biblioteca_caps(aux.AniMan);
}
}
//Exibe capitulos existentes na biblioteca
async function biblioteca_caps(Manga){
let caps = await WebApp.GetFiles(aux.Pasta+'/mangas/'+Manga);
$("#biblioteca_caps select .cap").html("");
if(caps!=""){
caps = caps.split("/storage/emulated/0/Otaku Host/mangas/"+Manga+"/").join("");
caps = caps.split('[#]');
caps.sort();
for(let cont=0;cont<caps.length;cont++){
if(!(caps[cont]).includes(".jpg")){
$("#biblioteca_caps select .cap").append(`
<option value="${caps[cont]}">${caps[cont]}</option>
`);
}
}
$('#biblioteca_caps').modal('open');
}else{
$('#biblioteca_caps').modal('close');
await WebApp.DeleteDir(`${aux.Pasta}/mangas/${Manga}/`);
await update_biblioteca();
await biblioteca();
}
}
//Exibe a biblioteca de mangás
async function biblioteca(){
$("#biblioteca ul").html("");
for(let cont=0;cont<(aux.Biblioteca).length;cont++){
$("#biblioteca ul").append(`
<li class="col s4 m3 l2" value="${aux.Biblioteca[cont]}">
<div class="card-image">
<img src="${decodeURI(`/storage/emulated/0/Otaku Host/mangas/${aux.Biblioteca[cont]}/capa.jpg`)}"/>
<span class="titulo">${aux.Biblioteca[cont]}</span>
</div>
</li>
`);
}
$("#biblioteca ul li").on("click", function() {
aux.AniMan = $(this).attr("value");
biblioteca_caps(aux.AniMan);
});
screen('biblioteca');
cover_height();
}
//Atualiza biblioteca
async function update_biblioteca(){
aux.Biblioteca = await WebApp.GetFiles(aux.Pasta+'/mangas');
console.log(aux.Biblioteca);
if(aux.Biblioteca==""){
aux.Biblioteca = new Array();
}else{
aux.Biblioteca = (aux.Biblioteca).split("/storage/emulated/0/Otaku Host/mangas/").join("");
aux.Biblioteca = (aux.Biblioteca).split('[#]');
}
return true;
}
function android_process_downloads_mangas(){
aux.DownloadsConfig.Request = false;
process_downloads_mangas(null,null);
}
//Sistema de processamento de download.
/*
add - Adiciona capitulo a fila de download,(Nome,CAP01,Sources)
devar - Deleta da pagina de download, (Nome,CAP01)
null - Processa download, (null)
*/
async function process_downloads_mangas(Acao,Dado){
if(Acao=='add'){
for(let cont=0;cont<(aux.DownloadsConfig.Fila).length;cont++){
if(aux.DownloadsConfig.Fila[cont].Nome==Dado.Nome && aux.DownloadsConfig.Fila[cont].Capitulo==Dado.Capitulo){
M.toast({html:'Capitulo ja existe na fila de download! '});
return false;
}
}
(aux.DownloadsConfig.Fila).push(Dado);
M.toast({html:'Adicionado a fila!'});
await update_download_view();
//Não existe downlod's sendo processado
if(aux.DownloadsConfig.Request==false){
process_downloads_mangas(null,null);
}
WebApp.SetBD("DownloadsFila",JSON.stringify(aux.DownloadsConfig.Fila))
return true;
}else if(Acao=='delet'){
for(let cont=0;cont<(aux.DownloadsConfig.Fila).length;cont++){
if(aux.DownloadsConfig.Fila[cont].Nome==Dado.Nome && aux.DownloadsConfig.Fila[cont].Capitulo==Dado.Capitulo){
(aux.DownloadsConfig.Fila).splice(cont, 1);
WebApp.SetBD("DownloadsFila",JSON.stringify(aux.DownloadsConfig.Fila));
await update_download_view();
return true;
}
}
return false;
}else{
//(Farol= Controle do usuario, Fila de Download, Processando)
if(aux.DownloadsConfig.Farol && (aux.DownloadsConfig.Fila).length>0 && aux.DownloadsConfig.Request==false){
//Visamos que um download esta sendo feito.
aux.DownloadsConfig.Request = true;
//Verificar se a capa e a pasta ja existem
if(!(aux.Biblioteca).includes(aux.DownloadsConfig.Fila[0].Nome)){
await WebApp.CreateDir(aux.Pasta+'/mangas/'+aux.DownloadsConfig.Fila[0].Nome);
await WebApp.SaveFile(`${aux.Pasta}/mangas/${aux.DownloadsConfig.Fila[0].Nome}/capa.jpg`,aux.DownloadsConfig.Fila[0].Img);
await update_biblioteca();
}
for(let cont=0;cont<(aux.DownloadsConfig.Fila[0].Sources).length;cont++){
if(aux.DownloadsConfig.Fila[0].Sources[cont]!=null){
if(cont==0){
//if(await BrasilSenpai.DirExist(aux.Pasta)==false){}
await WebApp.CreateDir(`${aux.Pasta}/mangas/${aux.DownloadsConfig.Fila[0].Nome}/${aux.DownloadsConfig.Fila[0].Capitulo}`);
console.log("Pasta capitlo OK");
}
//save_file_manga
WebApp.SaveManga(`${cont}.jpg`,aux.DownloadsConfig.Fila[0].Sources[cont],`${aux.Pasta}/mangas/${aux.DownloadsConfig.Fila[0].Nome}/${aux.DownloadsConfig.Fila[0].Capitulo}/`);
aux.DownloadsConfig.Fila[0].Sources[cont] = null;
$("#SlideDownload .porcent").first().text(await porcentagem(cont+1,(aux.DownloadsConfig.Fila[0].Sources).length));
console.log("Pagº"+cont);
return true;
}
}
console.log("Cap OK");
//Download concluido, vamos remover da lita
aux.DownloadsConfig.Request=false;
await process_downloads_mangas('delet',aux.DownloadsConfig.Fila[0]);
return await process_downloads_mangas(null,null);
}
}
}
async function loading(Check){
if(Check){
await $('#loading').modal('open');
await sleep(1000)
return true;
}else{
await $('#loading').modal('close');
}
}
function GenFilter(Element){
if($(Element).is(":checked")){
aux.Generos[aux.Fonts[aux.Type][aux.AniManSource[aux.Type]].Idioma];
aux.AniManGenero = aux.Generos[aux.Fonts[aux.Type][aux.AniManSource[aux.Type]].Idioma][$(Element).attr("value")];
$('#SlideGenero input[type="checkbox"]').not(Element).prop('checked', false);
}else{
aux.AniManGenero="";
}
}
async function generos_pesquisa(pag){
if(aux.AniManGenero!=""){
//aux.PaginacaoDetectCheck = false;
if(pag==1){
$('#genero ul').html("");
}
aux.Pag = pag;
loading(true);
await aux.Fonts[aux.Type][aux.AniManSource[aux.Type]].Generos(aux.Pag);
}else{
M.toast({html:'Você precisa selecionar um genero!'});
}
}
//Pesquis de animes/Mangas
async function pesquisa(pag){
aux.Pag = pag;
if(pag==1){
screen('pesquisa');
$("#pesquisa ul").html("");
}
await aux.Fonts[aux.Type][aux.AniManSource[aux.Type]].Pesquisa(aux.Pag);
//Na parte de pequisa, todo fluxo vai para sinopse.
}
//Exibir alertas de erros
function alert(code){
if(code.length>3){
$('#alert .modal-content').html(`
<i class="large material-icons">sentiment_neutral</i><br>
Erro inexperado...<br>
Codigo: ${code}
`);
}else{
$('#alert .modal-content').html(biblioteca_alerts[code]);
}
$('#alert').modal('open');
}
//Puxar fontes
async function fontes(){
aux.FontSelect = null;
WebApp.SetBD('Hist-'+aux.AniMan.Nome+'-'+aux.AniMan.Type,$("#list_epcap").val());
$("#fontsopc").html("");
historico($("#list_epcap").val());
//Parte para extração de paginas.
if(aux.AniMan.Type=='Manga'){
aux.Fonts['Manga'][aux.AniMan['IndexSource']].Sources($("#list_epcap").val());
}else{
//Carrega todos links de video.
loading(true);
let HD,Strick;
WebApp.Ajax($("#list_epcap").val(),''+async function(Code,Result){
aux.FontsVids = HtmlToVideo(htmlDecode(Result));
for(let cont=0;cont<(aux.FontsVids).length;cont++){
if(aux.FontsVids[cont][1]){
HD = "";
}else{
HD = "HD";
}
$("#fontsopc").append(`<a value="${cont}" onclick="font_set(${cont})" class="waves-effect waves-light btn">Fonte ${cont} ${HD}</a>`);
}
loading(false);
})
}
interstitialShow()
}
async function blogger_extrair(html){
html = html.split(`[{"play_url":"`);
if(html.length<=1){
alert(2);
return null;
}
html = html[1];
html = html.split(`","f`);
html = JSON.parse('"'+html[0]+'"');
return html;
}
//Exibir episodio ou manga, online ou download
async function font_set(index){
$(`#fontsopc a`).removeClass("deep-orange accent-4");
$(`#fontsopc a[value='${index}']`).addClass("deep-orange accent-4");
aux.FontSelect = index;
if(aux.Type=='Anime'){
//Verificar se existe algum tratamento para fonte.
await aux.Fonts[aux.Type][aux.AniManSource[aux.Type]].TFontes(aux.FontsVids[index]);
if(aux.FontsVids[index][0]==null){
alert(2);
return null;
}
//Definir se e uma subfonte ou não.
if(aux.FontsVids[index][1]){
//loading(true);
aux.FontsIndex = index;
WebApp.Ajax(aux.FontsVids[index][0],''+async function(Code,Result){
let temp = null;
if(Code==200){
temp = await HtmlToVideo(await htmlDecode(Result));
if(temp=="" || temp==null || temp.length<=0){
aux.FontsVids[aux.FontSelect][0]=null;
console.log("FALHA");
}else{
for(let cont=0;cont<temp.length;cont++){
if(cont<=0){
aux.FontsVids[aux.FontsIndex][0] = temp[cont][0];
aux.FontsVids[aux.FontsIndex][1] = temp[cont][1];
}else{
(aux.FontsVids).push([temp[cont][0],temp[cont][1]]);
}
}
$("#fontsopc").html("");
for(let cont=0;cont<(aux.FontsVids).length;cont++){
if(aux.FontsVids[cont][1]){
HD = "";
}else{
HD = "HD";
}
console.log("click..");
$("#fontsopc").append(`<a value="${cont}" onclick="font_set(${cont})" class="waves-effect waves-light btn">Fonte ${cont} ${HD}</a>`);
}
}
font_set(aux.FontsIndex);
}
loading(false);
console.log(Code);
});
}else{
if($("#sinopse nav .downplay").attr("value")=="false"){
await WebApp.Download(aux.AniMan.Nome+' - '+$("#list_epcap option:selected").html()+'.mp4',aux.FontsVids[index][0]);
M.toast({html: `Download adicionado, você pode ver na barra de statos.`});
}else{
if($('#check_webplayer').is(":checked") && aux.FireBase!==null){
aux.FireBase.push({name:"video_play",text:aux.FontsVids[index][0]});
setTimeout(function(){
aux.FireBase.remove(function(error){
//do stuff after removal
});
}, 3000);
}else{
await WebApp.Assistir(aux.FontsVids[index][0]);
}
}
}
}else{
await manga_source_imgs(aux.FontsMangas[index].Link,aux.AniMan.Nome,aux.EpCapSelect,aux.FontsMangas[index].Replace,aux.FontsMangas[index].Nome);
}
}
function Make_Url_Manga(index,Nome,Cap){
Nome = Nome.toLowerCase();
for(let cont=0;cont<(aux.FontsMangas[index].Replace).length;cont++){
Nome = Nome.split((aux.FontsMangas[index].Replace)[cont][0]).join((aux.FontsMangas[index].Replace)[cont][1]);
}
Nome = ((aux.FontsMangas[index].Link)).split('#nome#').join(Nome);
Nome = Nome.split('#cap#').join(Cap);
return Nome;
}
//Processamento de mangás
async function Ler_Baixar_Mangas(Sorces){
if($("#sinopse nav .downplay").attr("value")=="false"){
var temp = new Object();
temp.Nome = aux.AniMan.Nome;
temp.Capitulo = aux.EpCapSelect;
temp.Sources = Sorces;
temp.Img = aux.AniMan.Img;
await process_downloads_mangas('add',temp);
M.toast({html: `Download adicionado, clique no icone de download no topo!`});
}else{
$("#leitor").html("");
$(".modal").modal('close');
screen('leitor');
aux.MangasSources = Sorces;
for(let cont=0;cont<(Sorces).length;cont++){
$("#leitor").append(`<img src="${Sorces[cont]}">`);
}
}
}
/*
action: exist,add_delet,update
*/
async function favoritos(Action){
if(Action=="update"){
if(WebApp.GetBD("Favoritos",0)==0){
aux.Favoritos = new Array();
console.log("Favoritos vazio");
}else{
aux.Favoritos = JSON.parse(WebApp.GetBD("Favoritos",0));
}
aux.FavCheck = new Array();
for(let cont=0;cont<(aux.Favoritos).length;cont++){
(aux.FavCheck).push(`${aux.Favoritos[cont].Nome}-${aux.Favoritos[cont].Type}`);
}
return null;
}else if(Action=="add_delet"){
let index = null;
for(let cont=0;cont<(aux.Favoritos).length;cont++){
if(aux.Favoritos[cont].Nome==aux.AniMan.Nome && aux.Favoritos[cont].Type==aux.AniMan.Type){
index=cont;
}
}
if(index==null){
(aux.FavCheck).push(`${aux.AniMan.Nome}-${aux.AniMan.Type}`);
(aux.Favoritos).push(aux.AniMan);
$("#sinopse nav .fav i").text('favorite');
await WebApp.SaveFile(`${aux.Pasta}/capas/${md5(aux.AniMan.Nome+'-'+aux.AniMan.Type)}.jpg`,aux.AniMan.Img);
index=1;
M.toast({html: `Adicionado!`});
}else{
(aux.FavCheck).splice(index, 1);
(aux.Favoritos).splice(index, 1);
$("#sinopse nav .fav i").text('favorite_border');
await WebApp.DeleteFile(`${aux.Pasta}/capas/${md5(aux.AniMan.Nome+'-'+aux.AniMan.Type)}.jpg`);
index=0;
M.toast({html: `Removido!`});
}
WebApp.SetBD('Favoritos',JSON.stringify(aux.Favoritos));
return null;
}else{
let check = false;
for(let cont=0;cont<(aux.Favoritos).length;cont++){
if(aux.Favoritos[cont].Nome==aux.AniMan.Nome && aux.Favoritos[cont].Type==aux.AniMan.Type){
check=true;
}
}
return check;
}
}
function cover_height(){
if(aux.Screen[(aux.Screen).length-1]=="lancamentos" && aux.Type=="Anime"){
$(`.page-content li`).height($(`#${aux.Screen[(aux.Screen).length-1]} .page-content li`).width()*0.7);
}else{
$(`.page-content li`).height($(`#${aux.Screen[(aux.Screen).length-1]} .page-content li`).width()*1.5);
if(aux.Type=="Anime"){
$(`#anime_manga_lac .page-content li`).height($(`#${aux.Screen[(aux.Screen).length-1]} .page-content li`).width()*0.7);
}
}
if(aux.Screen[(aux.Screen).length-1]=="pesquisa"){
$("#pesquisa li").unbind();
$("#pesquisa li").on("click", function() {
aux.Fonts[aux.Type][aux.AniManSource[aux.Type]].Sinopse($(this).attr('value'));
});
}else if(aux.Screen[(aux.Screen).length-1]=="genero"){
$("#genero .page-content li").on( "click", function() {
aux.Fonts[aux.Type][aux.AniManSource[aux.Type]].Sinopse($(this).attr('value'));
});
}
}
//Processar favoritos
async function swap_fav(Type){
$('#anime_manga_fav ul').html('');
aux.Type = Type;
screen('favoritos');
await sleep(300);
$('.swap').text(Type);
for(let cont=0;cont<(aux.Favoritos).length;cont++){
if(aux.Favoritos[cont].Type==Type){
$('#anime_manga_fav ul').append(`
<li class="col s4 m3 l2 AniMan_Sinopse" value="${cont}">
<div class="card-image">
<img src="file://${aux.Pasta}/capas/${md5(aux.Favoritos[cont].Nome+'-'+aux.Favoritos[cont].Type)}.jpg">
<span class="titulo">${aux.Favoritos[cont].Nome}</span>
</div>
</li>
`);
}
}
await cover_height();
$(".page-content .AniMan_Sinopse").on( "click", function() {
let cont = $(this).attr('value');
aux.AniManIndex_Fav = aux.Favoritos[cont].IndexSource;
aux.Fonts[aux.Favoritos[cont].Type][aux.Favoritos[cont].IndexSource].Sinopse(aux.Favoritos[cont].Link);
});
}
//Controlador de telas
async function screen(x){
M.Toast.dismissAll();
$('.sidenav').sidenav('close');
$(".screen").hide();
$(".screen_"+x).show();
$("#"+x).show();
if((aux.Screen).length==0 || aux.Screen[(aux.Screen).length-1]!=x){
(aux.Screen).push(x);
}
aux.PaginacaoDetectCheck = false;
await WebApp.Analytics(x+"V6.1");
}
function voltar(){
if((aux.Screen).length>1){
if(aux.Screen[(aux.Screen).length-1]=='leitor'){
//WebApp.StatusBar('true');
}
(aux.Screen).splice((aux.Screen).length-1, 1);
}else{
WebApp.Exit();
}
$('.modal').modal('close');
screen(aux.Screen[(aux.Screen).length-1]);
}
//Carregar Historico
async function historico(link){
if(link==null){
if(WebApp.GetBD("LinkHistorico",0)==0){
aux.LinkHistorico = (WebApp.GetBD("LinkHistorico",0)).split(",");
}else{
aux.LinkHistorico = new Array();
}
}else{
if(!(aux.LinkHistorico).includes(link)){
(aux.LinkHistorico).push(link);
WebApp.SetBD('LinkHistorico',(aux.LinkHistorico).join(","));
}
}
}
async function load_cap_ep(CapEp){
aux.FontSelect = null;
aux.EpCapSelect = $(CapEp).text();
$("#fontsopc").html("");
$(CapEp).addClass("visited");
historico($(CapEp).attr("value"));
//Parte para extração de paginas.
if(aux.AniMan.Type=='Manga'){
aux.Fonts['Manga'][aux.AniMan['IndexSource']].Sources($(CapEp).attr("value"));
}else{
//Carrega todos links de video.
loading(true);
let HD,Strick;
WebApp.Ajax($(CapEp).attr("value"),''+async function(Code,Result){
aux.FontsVids = HtmlToVideo(htmlDecode(Result));
for(let cont=0;cont<(aux.FontsVids).length;cont++){
if(aux.FontsVids[cont][1]){
HD = "";
}else{
HD = "HD";
}
$("#fontsopc").append(`<a value="${cont}" onclick="font_set(${cont})" class="waves-effect waves-light btn">Fonte ${cont} ${HD}</a>`);
}
$("#epcap").modal("open");
loading(false);
})
}
interstitialShow()
}
//Carregar sinopse anime/manga
async function sinopse(){
//Registramos o index da fonte.
if(aux.AniManIndex_Fav!==null){
aux.AniMan['IndexSource'] = aux.AniManIndex_Fav;
aux.AniManIndex_Fav = null;
}else{
aux.AniMan['IndexSource'] = aux.AniManSource[aux.AniMan.Type];
}
$("#epcap .episodio").html("");
$("#epcap .cap").html("");
$("#sinopse h5").text(aux.AniMan.Nome);
$("#sinopse .inf").html(`
<p><b>Tipo</b>: ${aux.AniMan.Type}</p>
<p><b>Fonte:</b> ${aux.Fonts[aux.AniMan.Type][aux.AniMan['IndexSource']].Nome}</p>
${aux.AniMan['inf']}
`);
$("#sinopse img").attr('src', aux.AniMan.Img);
$("#sinopse .generos").html("");
for(let cont=0;cont<(aux.AniMan.Generos).length;cont++){
$("#sinopse .generos").append(`<span class="chip">${aux.AniMan.Generos[cont]}</span>`);
}
let episodio = new Object();
episodio.ep = false;
episodio.cap = false;
$("#epcap .ep").html("");
$("#epcap .cap").html("");
$("#Cap_Ep_Ova").html("");
for(let cont=0;cont<(aux.AniMan.Episodios).length;cont++){
console.log(aux.AniMan.Episodios[cont].Link);
episodio.ep = true;
$("#epcap .ep").append(`<option value="${aux.AniMan.Episodios[cont].Link}">${aux.AniMan.Episodios[cont].Ep}</option>`);
if((aux.LinkHistorico).includes(aux.AniMan.Episodios[cont].Link)){
$("#Cap_Ep_Ova").append(`<a onclick="load_cap_ep($(this))" class="btn-small btn-CapEp visited" value="${aux.AniMan.Episodios[cont].Link}">${aux.AniMan.Episodios[cont].Ep}</a>`);
}else{
$("#Cap_Ep_Ova").append(`<a onclick="load_cap_ep($(this))" class="btn-small btn-CapEp" value="${aux.AniMan.Episodios[cont].Link}">${aux.AniMan.Episodios[cont].Ep}</a>`);
}
}
for(let cont=0;cont<(aux.AniMan.Capitulos).length;cont++){
episodio.cap = true;
$("#epcap .cap").append(`<option value="${aux.AniMan.Capitulos[cont].Link}">${aux.AniMan.Capitulos[cont].Cap}</option>`);
if((aux.LinkHistorico).includes(aux.AniMan.Capitulos[cont].Link)){
$("#Cap_Ep_Ova").append(`<a onclick="load_cap_ep($(this))" class="btn-small btn-CapEp visited" value="${aux.AniMan.Capitulos[cont].Link}">${aux.AniMan.Capitulos[cont].Cap}</a>`);
}else{
$("#Cap_Ep_Ova").append(`<a onclick="load_cap_ep($(this))" class="btn-small btn-CapEp" value="${aux.AniMan.Capitulos[cont].Link}">${aux.AniMan.Capitulos[cont].Cap}</a>`);
}
}
if(episodio.ep){
$("#epcap .ep").show();
}else{
$("#epcap .ep").hide();
}
if(episodio.cap || aux.AniMan.Type=="Manga"){
$("#epcap .cap").show();
//$("#sinopse .type_ep").text("Capitulos.");
}else{
$("#epcap .cap").hide();
//$("#sinopse .type_ep").text("Episodios/Ovas.");
}
$("#sinopse .descricao").text(aux.AniMan.Descricao);
if(await favoritos('exist')){
$("#sinopse nav .fav i").text('favorite');
}else{
$("#sinopse nav .fav i").text('favorite_border');
}
if(WebApp.GetBD('Hist-'+aux.AniMan.Nome+'-'+aux.AniMan.Type,0)==0){
$("#list_epcap").val(WebApp.GetBD('Hist-'+aux.AniMan.Nome+'-'+aux.AniMan.Type,0)).attr("selected", "selected");
}
$("#mode_epcap").prop("checked",false);
screen('sinopse');
}
async function mode_downloadassistir(){
if($("#sinopse nav .downplay").attr("value")=="true"){
$("#sinopse nav .downplay").attr("value",false)
$("#sinopse nav .downplay i").text("cloud_download")
M.toast({html:'Modo download ativado!'});
}else{
$("#sinopse nav .downplay").attr("value",true)
$("#sinopse nav .downplay i").text("play_arrow")
M.toast({html:'Modo assistir ativado!'});
}
}
//Carregar capitulos da fonte selecionada
async function FontCaps(index){
let cap = 1;
loading(true);
if((aux.AniMan.Capitulos).length>0){
cap = aux.AniMan.Capitulos[(aux.AniMan.Capitulos).length-1]['Episodio'];
}
aux.FontMangaindex = index;
WebApp.Ajax(await Make_Url_Manga(index,aux.AniMan.Nome,cap),''+async function(Code,Result){
if(Code==200){
Result = htmlDecode(Result);
Result = Result.split("viewerChapter chapters")[1];
Result = Result.split(" - #");
$("#epcap .cap").html(" ");
for(let cont=1,temp;cont<Result.length;cont++){
temp = (Result[cont]).split('</')[0];
$("#epcap .cap").html(`<option value="${temp}">${temp}</option>${$("#epcap .cap").html()}`);
}
}
$("#list_epcap").show();
loading(false);
});
}
//Troca de sistema de Animes/Manga
async function swap(Type){
$('#anime_manga_lac .page-content').html('');
aux.Type = Type;
await sleep(300);
$('.swap').text(Type);
if((aux.inicial[Type]).length<=0){
aux.Fonts[Type][aux.AniManSource[Type]].Lancamentos();
return false;
}else{
let temp = aux.inicial[Type];
console.log(aux.FavCheck);
for(let cont=0,css='';cont<temp.length;cont++){
if((aux.FavCheck).includes(`${temp[cont].nome}-${Type}`)){
css = "isFav";
}else{
css = "";
}
$('#anime_manga_lac .page-content').append(`
<li class="col s4 m3 l2 AniMan_Sinopse" value="${temp[cont].link}">
<div class="card-image">
<img src="${temp[cont].img}" class="${css}">
<span class="titulo">${temp[cont].nome}</span>
<span class="stat light-blue darken-2">${temp[cont].ep}</span>
</div>
</li>
`);
}
$("#anime_manga_lac .page-content li").unbind();
$("#anime_manga_lac .page-content li").on( "click", function() {
aux.Fonts[aux.Type][aux.AniManSource[aux.Type]].Lancamentos_Action($(this).attr('value'));
});
cover_height();
}
return true;
}
/*
ajax = Requisitar dados de uma url. (url)
apk_version = Versão do APK. (null)
save_file = Salva arquivo. (/diretorio/nome.png,LINK)
exit = Fecha app. (null)
arquivo_devar = Deleta um arquivo. (Diretorio/arquivos.png)
arquivo_liste = Retorna lista de todos arquivos, (extensão (*),diretorio)
dir_liste = Listar aquivos. (Diretorio)
dir_exist = Exist diretorio,Diretorio
dir_creat = Cria diretorio,Diretorio
dir_devar = Deletar pasta,Diretorio
status_bar = FullScreenn,null
open_link = Abre um link,url
save_file_manga = Salva arquivo. (/diretorio/nome.png,LINK)
download = adiciona download ao status bar,(/xx/xx/nome.png,link)
ads = mostra anuncio, (interstial,offerwall,rewarded,specialoffer)
analytics = info, (inicio,sinopse,animexx)
*/
//Somente android pode chamar essa função
function android_set(Dado){
aux.call_result = Dado;
}
//Calcular porcentagem
async function porcentagem(partialValue, totalValue) {
return ((100 * partialValue) / totalValue ) | 0;
}
//Modal de progresso
async function progress(Procent){
$('#progress .determinate').width(Procent+'%');
if(Procent<100){
if(!$('#progress').hasClass('open')){
$('#progress').modal('open');
}
}else{
if($('#progress').hasClass('open')){
$('#progress').modal('close');
}
}
}
function photoswip_open(){
let items = new Array();
for(let cont=0;cont<(aux.MangasSources).length;cont++){
items.push(
{
src: aux.MangasSources[cont],
w: 0,
h: 0
}
);
}
let pswpElement = document.querySelectorAll('.pswp')[0];
let options = {
history: false,
focus: false,
showAnimationDuration: 0,
hideAnimationDuration: 0
};
aux.PhotoSwipe_gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
aux.PhotoSwipe_gallery.listen('gettingData', function(index, item) {
if (item.w < 1 || item.h < 1) { // unknown size
var img = new Image();
img.onload = function() { // will get size after load
item.w = this.width; // set image width
item.h = this.height; // set image height
aux.PhotoSwipe_gallery.invalidateCurrItems(); // reinit Items
aux.PhotoSwipe_gallery.updateSize(true); // reinit Items
}
img.src = item.src; // let's download image
}
});
aux.PhotoSwipe_gallery.init();
aux.PhotoSwipe_gallery.options.closeOnVerticalDrag = false;
aux.PhotoSwipe_gallery.options.pinchToClose = false;
}
//Dormi
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
//Decodifica para UTF8
function htmlDecode(value) {
return $('<div/>').html(value).text();
}
function HtmlToVideo(html){
let Video =[
['playerx?php=',false],
['noticia.php?token=',false],
['/0/bg.mp4',false],
['bg.mp4',true],
['?contentId=',true],
['video.g?token=',true],
['videoplayback',false],
['.mp4',false],
['.MP4',false]
];
let pilha_src= new Array(),
pilha_src_final = new Array(),
temp,
parametro,
temp2,
check=true,j,k;
html = html.split('http');
for(j=1;j<html.length;j++){
temp = (html[j]).split("'")[0];
temp = (temp).split('"')[0];
temp = 'http'+temp;
pilha_src.push(temp);
}
//Pesquisar quais são as fontes de video
for(j=0;j<pilha_src.length;j++){
for(k=0;k<Video.length;k++){
if((pilha_src[j]).includes(Video[k][0])){
pilha_src_final.push([pilha_src[j],Video[k][1]]);
break;
}
}
}
console.log("Videos:");
console.log(pilha_src_final);
return pilha_src_final;
}
//Transforma texto em dados
//One Piece,OVA,5
function tratamento(txt,biblioteca){
var EpTratamento = [' ', ':','-']
,nome
,ep
,tipo;
for(var j=0; j<biblioteca.length;j++){
for(var i=0; i<(biblioteca[j].par).length;i++){
if(txt.includes(biblioteca[j].par[i])){
tipo = biblioteca[j].tipo;
nome = txt.split(biblioteca[j].par[i])[0];
ep = txt.split(biblioteca[j].par[i])[1];
ep = ep.trim();
for(var k=0;k<EpTratamento.length;k++){
ep = ep.split(EpTratamento[k])[0];
}
ep = parseInt(ep);
nome = nome.trim();
return [nome,ep,tipo];
}
}
}
return null;
}
async function torrentStream(Hash){
WebApp.StreamTorrent(Hash,''+async function(FileList){
console.log("Torrent "+FileList);
aux.AniMan.Episodios = FileList.split(",");
$("#Cap_Ep_Ova").html("");
for(let cont=0;cont<(aux.AniMan.Episodios).length;cont++){
if((aux.LinkHistorico).includes(aux.AniMan.Episodios[cont])){
$("#Cap_Ep_Ova").append(`<a onclick="WebApp.StreamTorrentPlay('${cont}')" class="btn-small btn-CapEp visited">${aux.AniMan.Episodios[cont]}</a>`);
}else{
$("#Cap_Ep_Ova").append(`<a onclick="WebApp.StreamTorrentPlay('${cont}')" class="btn-small btn-CapEp">${aux.AniMan.Episodios[cont]}</a>`);
}
}
});
}
|
/* Copyright (c) 2017 Red Hat, Inc. */
var inherits = require('inherits');
var fsm = require('../fsm.js');
var messages = require('./messages.js');
function _State () {
}
inherits(_State, fsm._State);
function _Ready () {
this.name = 'Ready';
}
inherits(_Ready, _State);
var Ready = new _Ready();
exports.Ready = Ready;
function _Disabled () {
this.name = 'Disabled';
}
inherits(_Disabled, _State);
var Disabled = new _Disabled();
exports.Disabled = Disabled;
function _Start () {
this.name = 'Start';
}
inherits(_Start, _State);
var Start = new _Start();
exports.Start = Start;
function _Selected1 () {
this.name = 'Selected1';
}
inherits(_Selected1, _State);
var Selected1 = new _Selected1();
exports.Selected1 = Selected1;
function _Selected2 () {
this.name = 'Selected2';
}
inherits(_Selected2, _State);
var Selected2 = new _Selected2();
exports.Selected2 = Selected2;
function _Selected3 () {
this.name = 'Selected3';
}
inherits(_Selected3, _State);
var Selected3 = new _Selected3();
exports.Selected3 = Selected3;
function _EditLabel () {
this.name = 'EditLabel';
}
inherits(_EditLabel, _State);
var EditLabel = new _EditLabel();
exports.EditLabel = EditLabel;
function _Move () {
this.name = 'Move';
}
inherits(_Move, _State);
var Move = new _Move();
exports.Move = Move;
_Start.prototype.start = function (controller) {
controller.changeState(Ready);
};
_Start.prototype.start.transitions = ['Ready'];
_Selected1.prototype.onMouseUp = function (controller) {
controller.changeState(Selected2);
};
_Selected1.prototype.onMouseUp.transitions = ['Selected2'];
_Selected1.prototype.onMouseMove = function (controller) {
controller.changeState(Move);
};
_Selected1.prototype.onMouseMove.transitions = ['Move'];
_Selected2.prototype.onKeyDown = function (controller, msg_type, $event) {
//controller.changeState(Ready);
controller.delegate_channel.send(msg_type, $event);
};
_Selected2.prototype.onKeyDown.transitions = ['Ready'];
_Selected2.prototype.onMouseDown = function (controller, msg_type, $event) {
controller.scope.pressedScaledX = controller.scope.scaledX;
controller.scope.pressedScaledY = controller.scope.scaledY;
var groups = controller.scope.selected_groups;
var i = 0;
var selected = false;
controller.scope.selected_groups = [];
for (i = 0; i < groups.length; i++) {
if (groups[i].type !== "fsm") {
continue;
}
if (groups[i].is_icon_selected(controller.scope.scaledX, controller.scope.scaledY)) {
groups[i].selected = true;
selected = true;
controller.scope.selected_groups.push(groups[i]);
}
}
if (selected) {
controller.changeState(Selected3);
} else {
for (i = 0; i < groups.length; i++) {
groups[i].selected = false;
}
controller.changeState(Ready);
controller.handle_message(msg_type, $event);
}
};
_Selected2.prototype.onMouseDown.transitions = ['Selected3', 'Ready'];
_Selected3.prototype.onMouseUp = function (controller) {
controller.changeState(EditLabel);
};
_Selected3.prototype.onMouseUp.transitions = ['EditLabel'];
_Selected3.prototype.onMouseMove = function (controller) {
controller.changeState(Move);
};
_Selected3.prototype.onMouseMove.transitions = ['Move'];
_EditLabel.prototype.start = function (controller) {
controller.scope.selected_groups[0].edit_label = true;
};
_EditLabel.prototype.end = function (controller) {
controller.scope.selected_groups[0].edit_label = false;
};
_EditLabel.prototype.onMouseDown = function (controller, msg_type, $event) {
controller.changeState(Ready);
controller.handle_message(msg_type, $event);
};
_EditLabel.prototype.onMouseDown.transitions = ['Ready'];
_EditLabel.prototype.onKeyDown = function (controller, msg_type, $event) {
//Key codes found here:
//https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
var item = controller.scope.selected_groups[0];
var previous_name = item.name;
if ($event.keyCode === 8 || $event.keyCode === 46) { //Delete
item.name = item.name.slice(0, -1);
} else if ($event.keyCode >= 48 && $event.keyCode <=90) { //Alphanumeric
item.name += $event.key;
} else if ($event.keyCode >= 186 && $event.keyCode <=222) { //Punctuation
item.name += $event.key;
} else if ($event.keyCode === 13) { //Enter
controller.changeState(Selected2);
} else if ($event.keyCode === 32) { //Space
item.name += " ";
} else {
console.log($event.keyCode);
}
controller.scope.send_control_message(new messages.GroupLabelEdit(controller.scope.client_id,
item.id,
item.name,
previous_name));
};
_EditLabel.prototype.onKeyDown.transitions = ['Selected2'];
_Ready.prototype.onMouseDown = function (controller, msg_type, $event) {
controller.scope.pressedScaledX = controller.scope.scaledX;
controller.scope.pressedScaledY = controller.scope.scaledY;
var groups = controller.scope.groups;
var i = 0;
var selected = false;
controller.scope.clear_selections();
for (i = 0; i < groups.length; i++) {
if (groups[i].type !== "fsm") {
continue;
}
if (groups[i].is_icon_selected(controller.scope.scaledX, controller.scope.scaledY)) {
groups[i].selected = true;
selected = true;
controller.scope.selected_groups.push(groups[i]);
}
}
if (selected) {
controller.changeState(Selected1);
} else {
controller.delegate_channel.send(msg_type, $event);
}
};
_Ready.prototype.onMouseDown.transitions = ['Selected1'];
_Move.prototype.start = function (controller) {
var groups = controller.scope.selected_groups;
var i = 0;
for (i = 0; i < groups.length; i++) {
groups[i].moving = true;
}
};
_Move.prototype.end = function (controller) {
var groups = controller.scope.selected_groups;
var i = 0;
var j = 0;
for (i = 0; i < groups.length; i++) {
for(j = 0; j < groups[i].states.length; j++) {
groups[i].states[j].selected = false;
}
}
for (i = 0; i < groups.length; i++) {
groups[i].moving = false;
}
};
_Move.prototype.onMouseUp = function (controller) {
controller.changeState(Selected2);
};
_Move.prototype.onMouseUp.transitions = ['Selected2'];
_Move.prototype.onMouseMove = function (controller) {
var groups = controller.scope.selected_groups;
var states = null;
console.log(groups);
var diffX = controller.scope.scaledX - controller.scope.pressedScaledX;
var diffY = controller.scope.scaledY - controller.scope.pressedScaledY;
var i = 0;
var j = 0;
var previous_x1, previous_y1, previous_x2, previous_y2, previous_x, previous_y;
var c_messages = [];
for (i = 0; i < groups.length; i++) {
c_messages = [];
previous_x1 = groups[i].x1;
previous_y1 = groups[i].y1;
previous_x2 = groups[i].x2;
previous_y2 = groups[i].y2;
groups[i].x1 = groups[i].x1 + diffX;
groups[i].y1 = groups[i].y1 + diffY;
groups[i].x2 = groups[i].x2 + diffX;
groups[i].y2 = groups[i].y2 + diffY;
groups[i].update_xy();
c_messages.push(new messages.GroupMove(controller.scope.client_id,
groups[i].id,
groups[i].x1,
groups[i].y1,
groups[i].x2,
groups[i].y2,
previous_x1,
previous_y1,
previous_x2,
previous_y2));
states = groups[i].states;
for (j = 0; j < states.length; j++) {
previous_x = states[j].x;
previous_y = states[j].y;
states[j].x = states[j].x + diffX;
states[j].y = states[j].y + diffY;
c_messages.push(new messages.StateMove(controller.scope.client_id,
states[j].id,
states[j].x,
states[j].y,
previous_x,
previous_y));
}
controller.scope.send_control_message(new messages.MultipleMessage(controller.scope.client_id, c_messages));
}
controller.scope.pressedScaledX = controller.scope.scaledX;
controller.scope.pressedScaledY = controller.scope.scaledY;
};
_Move.prototype.onTouchMove = _Move.prototype.onMouseMove;
|
import React, { Component } from 'react';
import axios from 'axios';
import Admins from './Admins';
import {Link} from 'react-router-dom';
//const passport = require('passport');
import {BrowserRouter as Router,Route} from 'react-router-dom';
//import './';
//import Popup from 'reactjs-popup'
//import { useAlert } from 'react-alert'
class AdminApp extends Component {
state={
_id:'',
full_name:'',
email:'',
password:'',
username:'',
super:''
}
constructor(props){
super(props)
this.state={
admins:[],
error:false,
loading:true,
updatedadmin:null
}
}
componentDidMount() {
const tokenB= localStorage.getItem('jwtToken');
axios
.get('http://localhost:5000/api/admins/')
.then(res=> this.setState({admins:res.data.data,loading:false}))
.catch(error=> this.ERROR.bind(error))
}
// getAdmin = (e) => {
// e.preventDefault();
// const admin = e.target.elements.id.value;
// if(admin){
// axios.get(`http://localhost:5000/api/admins/${admin}`).then((res) =>{
// const email = res.data.email;
// const username = res.data.username;
// const full_name = res.data.full_name
// const password = res.data.password
// this.setState({email})
// this.setState({full_name})
// this.setState({password})
// this.setState({username})
// })
// } else return;
// }
getAdmins= async () => {
//const tokenB= localStorage.getItem('jwtToken');
return await axios.get("http://localhost:5000/api/admins/"
);
}
// addadmin=(full_name,email,password,username)=>{
// axios.post("http://localhost:5000/api/admins/",{
// full_name:full_name,email:email,password:password,username:username
// }
// ).then(res => {this.setState({admin:[...this.state.AdminApp,res.data]})})
// .catch(e=> "error")
// alert('Admin was created succesfully')
// window.location = '/admin';
// // <Redirect to="/HomePage" />
// // <Popup>
// // <div>
// // Admincouldn't be created, you did not meet validations, try again
// // </div>
// // </Popup>
// // )
// }
showadmin = (id) => {
const tokenB= localStorage.getItem('jwtToken');
window.location = `http://localhost:5000/api/admins/${id}`
}
deleteadmin = (id) => {
const tokenB= localStorage.getItem('jwtToken');
axios.delete(`http://localhost:5000/api/admins/${id}`,{
Authorization: tokenB
})
.then(res =>this.setState({ admins: [...this.state.admins.filter(admin => admin._id !== id)] }));
}
updateadmin = (id) => {
this.setState({updatedadmin:id})
window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
}
updateadminreal=(id,full_name,email,password,username)=>{
const tokenB= localStorage.getItem('jwtToken');
axios.put(`http://localhost:5000/api/admins/${id}`,{
full_name:full_name,email:email,password:password,username:username},{
Authorization: tokenB}
).then(res => {this.setState({admin:[...this.state.AdminApp,res.data]})})
.catch(e=> "error")
alert('Admin was updated succesfully')
for(var i=0;i<2;i++){
window.location = '/admin';}
//window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
}
onSubmitUpdate= async(e)=>{
e.preventDefault();
var f=true;
if (this.state.password && this.state.password.length<8){
f = false;
alert('password cannot be less than 8 characters')
}
const adminsdb = await this.getAdmins()
for(var i=0;i<adminsdb.data.data.length;i++){
if(this.state.email && adminsdb.data.data[i].email===this.state.email){
alert('this email already exists or is your old email,please enter another one')
f =false;
}
if(this.state.username && adminsdb.data.data[i].username===this.state.username){
alert('this username already exists or your old username,please enter another one')
f =false;
}
if(this.state.super==='yes' && adminsdb.data.data[i].super===this.state.super){
alert('there is already a super admin')
f =false;
}
}
if(f===true)
this.updateadminreal(this.state.updatedadmin,this.state.full_name,this.state.email,this.state.password,this.state.username);
}
// onSubmit= async(e)=>{
// e.preventDefault();
// var f=true;
// if(!this.state.full_name){
// f = false;
// alert('full name cannot be empty')
// }
// else if (!this.state.password || this.state.password.length<8){
// f= false;
// alert('password cannot be empty or less than 8 characters')
// }
// else if (!this.state.username){
// f = false;
// alert('username cannot be empty')
// }
// else if (!this.state.email){
// f = false;
// alert('email cannot be empty')
// }
// //const adminsdb
// const adminsdb = await this.getAdmins()
// // to check that username and email do not exist before when creating
// for(var i=0;i<adminsdb.data.data.length;i++){
// if(adminsdb.data.data[i].email===this.state.email){
// alert('this email already exists,please enter another one')
// f =false;
// }
// if(adminsdb.data.data[i].username===this.state.username){
// alert('this username already exists,please enter another one')
// f =false;
// }
// }
// if(f===true){
// // alert(''+adminsdb.data.data.length)
// this.addadmin(this.state.full_name,this.state.email,this.state.password,this.state.username);
// }
// }
onChange=(e)=>this.setState({[e.target.name]:e.target.value});
render() {
return this.state.error?<h1>process could not be complete</h1>:this.state.loading?
<h1>loading please be patient</h1>
:(
<div className="Admins">
<h1>Admins</h1>
<Link to="/admin/pendingjobs">View Pending Jobs </Link>
<Link to="/admin/pendingpartners">View Pending Partners </Link>
<Link to="/admin/pendingmembers">View Pending Members </Link>
<Link to="/admin/pendingeduorgs">View Pending EduOrgs </Link>
<Link to="/admin/pendingadmins">View Pending Admins </Link>
<Admins admins = {this.state.admins} deleteadmin={this.deleteadmin} updateadmin={this.updateadmin} showadmin={this.showadmin}/>
<br />
{/* <div>
<AdminIdComponentForm getAdmin={this.getAdmin}/>
<center>
{ this.state.email ? <p><h4>Email:</h4> {this.state.email}</p>:<p></p>}
{ this.state.full_name ? <p><h4>Name:</h4> {this.state.full_name}</p>:<p></p>}
{ this.state.username ? <p><h4>User Name:</h4> {this.state.username}</p>:<p></p>}
</center>
</div> */}
{/* <label> Admin Register</label>
<br/>
<br />
<form onSubmit={this.onSubmit}>
<label>
Full Name:
<input
name="full_name"
type="text"
value={this.state.full_name}
onChange={this.onChange}
/>
</label>
<br />
<br />
<label>
Email:
<input
name="email"
type="email"
value={this.state.email}
onChange={this.onChange}
/>
</label>
<br />
<br />
<label>
Password:
<input
name="password"
type="text"
value={this.state.password}
onChange={this.onChange}
/>
</label>
<br />
<br />
<label>
Username:
<input
name="username"
type="text"
value={this.state.username}
onChange={this.onChange}
/>
</label>
<br />
<br />
{/* <button onClick={this.addjob.bind(this)} style={btnStyle}> Submit</button> */}
{/* <input
type="submit"
value="Submit"
//className="btn"
// style={{flex: '1'}}
/>
</form>
<br/>
<br/> */}
{/* <form onSubmit={this.onSubmitget}>
<label> Get an Admin</label>
<br/>
ID (just for now use id until we log in):
<input
name="id"
type="text"
value={this.state._id}
onChange={this.onChange}
/>
<input
type="submit"
value="Submit"
//className="btn"
// style={{flex: '1'}}
/>
<br />
<br /> */}
{/* </form> */}
<label> Update Profile</label>
<br/>
<br />
<form onSubmit={this.onSubmitUpdate}>
<label>
Full Name:
<input
name="full_name"
type="text"
value={this.state.full_name}
onChange={this.onChange}
/>
</label>
<br />
<br />
<label>
Email:
<input
name="email"
type="email"
value={this.state.email}
onChange={this.onChange}
/>
</label>
<br />
<br />
<label>
Password:
<input
name="password"
type="text"
value={this.state.password}
onChange={this.onChange}
/>
</label>
<br />
<br />
<label>
Username:
<input
name="username"
type="text"
value={this.state.username}
onChange={this.onChange}
/>
</label>
<br />
<br />
<label>
Super:
<input
name="super"
type="text"
value={this.state.super}
onChange={this.onChange}
/>
</label>
<br />
<br />
{/* <button onClick={this.addjob.bind(this)} style={btnStyle}> Submit</button> */}
<input
type="submit"
value="Submit"
//className="btn"
// style={{flex: '1'}}
/>
</form>
</div>
);
}
ERROR=(error)=>{
console.log(error)
this.setState({error:true})
}
}
const btnStyle={
background:'#000000',
color:'#fff'
}
export default AdminApp;
|
const { Post,User } = require('../models')
const DataLoader = require('dataloader')
const { PubSub , withFilter } = require('graphql-subscriptions')
const pubsub = new PubSub()
// const resolvers = {
// Post: {
// id: post => post._id,
// author: (post) => User.findById(post.authorId)
// },
// User: {
// id: user => user._id,
// posts: (user) => Post.find({ authorId: user._id })
// },
// Query:{
// posts: () => Post.find(),
// post: (obj,{id}) => Post.findOne({_id : args.id}),
// users: () => User.find() ,
// }
// }
const resolvers = {
Tag:{
posts: async (tag) =>{
const posts = await Post.find({ tags : tag.name })
return posts
}
},
Post: {
id: (post) => { return post._id},
author: async (post , args ,context) =>{
//const user = await User.findById(post.authorId)
const user = await context.loaders.userLoader.load(`${post.authorId}`)//post.authorId
return user
},
tags: (post) => {
return post.tags.map((tag) =>{
return { name:tag }
})
}
},
User: {
id: (user) => { return user._id },
posts: async (user , args ,context) =>{
//const posts = await Post.find({ authorId: user._id })
const posts = await context.loaders.postsByUserIdLoader.load(user._id)//user._id
return posts
}
},
Query:{
posts: async (obj, {tag , tags} ) => {
if(tags) {
const post = await Post.find({tags : { $in : tags }})
return post
}
if(tag) {
const post = await Post.find({tags : tag})
return post
}
const post = await Post.find()
return post
} ,
post: async (obj,{id}) =>{
const post = await Post.findOne({_id : id})
return post
},
users: async () => {
const users = await User.find()
return users
} ,
me: async (obj, args, context) => {
return context.user
},
hello: () =>{
pubsub.publish
('HELLO_QUERIED')
return 'Hello World'
}
},
Mutation: {
login: async (obj , { username, password}) =>{
const token = await User.createAccessToken(username, password)
return token
},
signup: async (obj , { username, password}) =>{
const user = await User.signup(username, password)
return user
},
createPost: async(obj , { data } ,context) =>{
//const res = context.user
const res = await Post.createPost( data ,context.user)
//console.log(res)
pubsub.publish('POST_CREATED',{
id: res.id,
tags: res.tags
})
return res
},
// createPost :
// args.data.
},
Subscription: {
helloQueried: {
subscribe: () => {
return pubsub.asyncIterator
('HELLO_QUERIED')
},
resolve: () => {
return `${new Date()}`
}
},
postCreated : {
// subscribe: () => {
// return pubsub.asyncIterator
// ('POST_CREATED')
// },
subscribe: withFilter(() => pubsub.asyncIterator('POST_CREATED')
, (payload, args) => {
if(!args.tag) {
return true
}
return payload.tags.includes(args.tag)
}),
resolve: async (payload) => {
const post = await Post.findById(payload.id)
return post
}
}
}
}
module.exports = resolvers |
var moto_1 = {
color : 'black',
speed : 0,
accelerate : function()
{
this.speed += 1;
}
};
localStorage.moto_1 = JSON.stringify(moto_1); |
function tab_switch(event, post_type) {
var i, tab_content, tab_links;
tab_content = document.getElementsByClassName("tab_content");
for (i = 0; i < tab_content.length; i++) {
tab_content[i].style.display = "none";
}
tab_links = document.getElementsByClassName("tab_links");
for (i = 0; i < tab_links.length; i++) {
tab_links[i].className = tab_links[i].className.replace(" active", "");
}
document.getElementById(post_type).style.display = "block";
event.currentTarget.className += "active";
}
|
function getColor(color, theme) {
const [name, variant] = color.split(' ');
if (variant) return theme.colors[name][variant];
return theme.colors[name];
}
export default getColor;
|
import React from 'react';
import { Container, Row, Grid, Icon, Col } from 'native-base';
import { StyleSheet, Text, ScrollView, TouchableOpacity, Image } from 'react-native';
import { UserHeader, Card, ContainerWithLoading } from '../../../components';
import { Option, ArrowNavigator } from '../components';
import { connect } from 'react-redux';
import { withCameraModal, withImagePicker } from '../../../hocs';
import { bindActionCreators } from 'redux';
import { previousQuestion, nextQuestion, selectOption, finishQuiz, fetchQuestions } from '../actions';
class Question extends React.Component {
componentDidMount() {
this.props.fetchQuestions();
}
padStart = (expression) => {
return (expression + "").padStart(2, '0');
};
_renderOptions = () => {
const userChoice = this.props.userChoices.find(
choice => choice.questionIndex === this.props.currentQuestion
);
let options = null;
if (this.props.questions.length > 0) {
options = this.props.question.options.map((option, index) => (
<Option
key={index} text={option}
onPress={() => (!userChoice) ? this.props.selectOption(index) : null}
enableGreen={
userChoice &&
(
(userChoice.choiceIndex === index &&
userChoice.choiceIndex === this.props.question.rightAnswerIndex) ||
index === this.props.question.rightAnswerIndex
)
}
enableRed={
userChoice &&
userChoice.choiceIndex === index &&
userChoice.choiceIndex !== this.props.question.rightAnswerIndex
}
/>
))
}
return options;
};
isFirstQuestion = () => {
return this.props.currentQuestion === 0;
};
isLastQuestion = () => {
return this.props.currentQuestion + 1 === this.props.questions.length;
};
render() {
return (
<ContainerWithLoading
style={styles.container}
loading={this.props.loading}>
{/* Cabeçalho */}
<UserHeader
size={10}
user={this.props.loggedUser}
uri={this.props.pictureUri}
onPressIcon={this.props.openCameraModal}
/>
{/* Card */}
<Card size={90}>
<Grid>
<Row size={10}>
<Text style={styles.questionHeaderBig}>Perguntas {this.padStart(this.props.currentQuestion + 1)}/</Text>
<Text style={styles.questionHeaderSmall}>{this.padStart(this.props.questions.length)}</Text>
</Row>
<Row size={20} style={styles.questionTextContainer}>
<Text style={styles.questionText}>{this.props.question.name}</Text>
</Row>
<Row size={60}>
<ScrollView contentContainerStyle={styles.scrollViewContainer}>
{this._renderOptions()}
</ScrollView>
</Row>
<ArrowNavigator
size={10}
onPressPrev={this.props.previousQuestion}
onPressNext={this.props.nextQuestion}
leftDisabled={this.isFirstQuestion()}
rightDisabled={this.isLastQuestion()}
showFinishButton={this.props.userChoices.length === this.props.questions.length}
onPressFinish={this.props.finishQuiz}
/>
</Grid>
</Card>
</ContainerWithLoading>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#412DB5'
},
questionHeaderBig: {
fontSize: 24,
color: '#412DB5',
fontWeight: 'bold',
alignSelf: 'center'
},
questionHeaderSmall: {
fontSize: 16,
color: '#412DB5',
fontWeight: 'bold',
alignSelf: 'center'
},
questionTextContainer: {
justifyContent: 'center',
alignItems: 'center',
paddingLeft: 20,
paddingRight: 20
},
questionText: {
fontSize: 24,
color: '#412DB5',
textAlign: 'center'
},
scrollViewContainer: {
padding: 5
},
});
const mapStateToProps = (state) => {
const { loggedUser } = state.loginReducer;
const { questions, currentQuestion, userChoices, loading } = state.questionReducer;
return {
loggedUser,
questions,
currentQuestion,
userChoices,
question: questions.length > 0 ? questions[currentQuestion] : {},
loading
};
};
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
previousQuestion,
nextQuestion,
selectOption,
finishQuiz,
fetchQuestions
},
dispatch
);
export default connect(mapStateToProps, mapDispatchToProps)(withCameraModal(withImagePicker(Question))); |
const chrome = require('selenium-webdriver/chrome');
const {webdriver, Builder, By, until } = require('selenium-webdriver');
const screen = {
width: 1278,
height: 1024
};
const chromeOptions = new chrome.Options()
// .addArguments("--disable-gpu", "--no-sandbox",'start-maximized')
.addArguments("--disable-gpu", "--no-sandbox")
.windowSize(screen)
const driver = new Builder()
.forBrowser("chrome")
.setChromeOptions(chromeOptions)
.build();
module.exports = () => {
return driver;
}
|
const memberIDInputEl = document.querySelector('#memberID');
const checkIfMemberExistFormEl = document.querySelector('#checkIfMemberExistForm');
const updateMemberFormEl = document.querySelector('#updateMemberForm');
const messagePlaceHolderEl = document.querySelector('.messagePlaceHolder');
const newNameInputEl = document.querySelector('#newName');
const newAgeInputEl = document.querySelector('#newAge');
const newCommentsInputEl = document.querySelector('#newComments');
const newExpirationDateInputEl = document.querySelector('#newExpirationDate');
const hasPrivateBoatCheckboxEl = document.querySelector('#hasPrivateBoat');
const privateBoatSerialNumberInputEl = document.querySelector('#privateBoatSerialNumber');
const newPhoneInputEl = document.querySelector('#newPhone');
const newEmailInputEl = document.querySelector('#newEmail');
const newPasswordInputEl = document.querySelector('#newPassword');
const isManagerCheckboxEl = document.querySelector('#isManager');
let memberID;
function submitMemberID(event) {
console.log("in submitMemberID()");
memberID = memberIDInputEl.value;
submitMemberAsync();
event.preventDefault();
}
async function submitMemberAsync() {
try {
let response = await fetch('/BMSWebApp/updateMember?' + "memberID=" + memberID);
let text = await response.text();
console.log("text is: --" + text);
if (text === "false") {
updateSubmitMessage("Member didn't found", 0);
updateMemberFormEl.style.display = "none"
} else if (response.status == 200) {
updateSubmitMessage("Member found", 200);
updateMemberFormEl.style.display = "block"
}
} catch (e) {
console.log(e.message);
}
}
checkIfMemberExistFormEl.addEventListener('submit', submitMemberID)
async function updateMember(event) {
event.preventDefault();
let newName = newNameInputEl.value;
let newAge = newAgeInputEl.value;
let newComments = newCommentsInputEl.value;
let newExpirationDate = newExpirationDateInputEl.value;
let hasPrivateBoat = hasPrivateBoatCheckboxEl.checked;
let privateBoatSerialNumber = privateBoatSerialNumberInputEl.checked;
let newPhone = newPhoneInputEl.checked;
let newEmail = newEmailInputEl.checked;
let newPassword = newPasswordInputEl.checked;
let isManager = isManagerCheckboxEl.checked;
const data = {
memberID: memberID,
newName: newName,
newAge: newAge,
newComments: newComments,
newExpirationDate: newExpirationDate,
hasPrivateBoat: hasPrivateBoat,
privateBoatSerialNumber: privateBoatSerialNumber,
newPhone: newPhone,
newEmail: newEmail,
newPassword: newPassword,
isManager: isManager
}
const response = await fetch('/BMSWebApp/updateMember', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json;charset=utf-8'
}),
body: JSON.stringify(data)
});
updateSubmitMessage(await response.text(), response.status);
}
updateBoatFormEl.addEventListener('submit', updateMember)
function updateSubmitMessage(message, responseStatus) {
let HttpCodes = {
success : 200,
needToRemoveOther : 409
}
messagePlaceHolderEl.innerHTML=message;
if (responseStatus === HttpCodes.success){
messagePlaceHolderEl.setAttribute("style", "color:black;")
}
else{
messagePlaceHolderEl.setAttribute("style", "color:red;")
}
} |
const chalk = require('chalk'),
lo = require('lodash');
module.exports = {
test: test,
genResultStr: genResultStr
};
function test(vm, test, criteria, exercise, submission) {
return new Promise((resolve, reject) => {
let result = vm.run(test.input);
const passed = lo.isEqual(test.expected, result);
resolve({
input: test.input,
result: result,
pass: passed,
expected: test.expected,
type: 'equals'
});
});
}
function genResultStr(results, testIdx) {
if (results.pass) {
console.log(
chalk.green(`TEST ${testIdx + 1}: PASSED! (${results.input} === ${JSON.stringify(results.expected)})`)
);
} else {
console.log(
chalk.red(
`TEST ${testIdx + 1}: FAILED! ${results.input}
Expected (${JSON.stringify(results.expected)})<${typeof results.expected}>, but got (${JSON.stringify(
results.result
)})<${typeof results.result}> instead`
)
);
}
}
|
(function() {
'use strict';
angular
.module('template.Home')
.value('AdValue', ['app/images/ad1.jpg',
'app/images/ad2.jpg',
'app/images/ad3.jpg',
'app/images/ad4.jpg',
'app/images/ad5.jpg'
])
.value('GalleryValue', ['app/images/godofwar.jpg',
'app/images/gta.jpg',
'app/images/harleyquinn.jpg',
'app/images/legomovie.jpg',
'app/images/lou.jpg',
'app/images/marioandfriends.jpg'
])
})(); |
import request from 'superagent'
export const SUBMIT_RANKINGS = 'SUBMIT_RANKINGS'
export const SUBMIT_RANKINGS_ERROR = 'SUBMIT_RANKINGS_ERROR'
export const SUBMIT_RANKINGS_SUCCESS = 'SUBMIT_RANKINGS_SUCCESS'
export const GET_RANKINGS = 'GET_RANKINGS'
export const GET_RANKINGS_ERROR = 'GET_RANKINGS_ERROR'
export const GET_RANKINGS_SUCCESS = 'GET_RANKINGS_SUCCESS'
export const GET_RANKINGS_DOESNT_EXIST = 'GET_RANKINGS_DOESNT_EXIST'
export function submitRankings (value) {
return {
type: SUBMIT_RANKINGS,
payload: value
}
}
export function getRankings (value) {
return {
type: GET_RANKINGS,
payload: value
}
}
const rankingsService = store => next => action => {
next(action)
switch (action.type) {
case SUBMIT_RANKINGS: {
const flavors = action.payload.flavors
const userId = action.payload.userId
const hasRankedBefore = action.payload.hasRankedBefore
let flavorsPostData = flavors.map((flavor) => (
{
id: flavor.id,
rank: flavor.rank
})
)
if (!hasRankedBefore) {
request.post('/api/rankings')
.set('Content-Type', 'application/json')
.send({ userId: userId, flavors: flavorsPostData })
.end((err, res) => {
if (err) {
return next({
type: SUBMIT_RANKINGS_ERROR,
payload: err
})
}
const data = JSON.parse(res.text)
next({
type: SUBMIT_RANKINGS_SUCCESS,
payload: data
})
})
} else {
request.put('/api/rankings')
.set('Content-Type', 'application/json')
.send({ userId: userId, flavors: flavorsPostData })
.end((err, res) => {
if (err) {
return next({
type: SUBMIT_RANKINGS_ERROR,
payload: err
})
}
const data = JSON.parse(res.text)
next({
type: SUBMIT_RANKINGS_SUCCESS,
payload: data
})
})
}
break
}
case GET_RANKINGS: {
const userId = action.payload
request.get(`/api/rankings/${userId}`)
.end((err, res) => {
if (res.notFound) {
return next({
type: GET_RANKINGS_DOESNT_EXIST
})
} else if (err) {
return next({
type: GET_RANKINGS_ERROR,
payload: err
})
} else {
const data = JSON.parse(res.text)
next({
type: GET_RANKINGS_SUCCESS,
payload: data
})
}
})
break
}
default:
break
}
}
export default rankingsService
|
import React, {Component} from 'react';
import {Modal, Form, Spin, Table, Icon, Row, Col} from 'antd';
import config from '@/commons/config-hoc';
import {FormElement} from '@/library/components';
import localMenus from "@/menus";
import {convertToTree, getGenerationKeys} from "@/library/utils/tree-utils";
import {arrayRemove, arrayPush} from '@/library/utils';
@config({
ajax: true,
})
@Form.create()
export default class RoleEdit extends Component {
state = {
loading: false,
data: {},
selectedRowKeys: [],
halfSelectedRowKeys: [],
menuTreeData: [],
};
columns = [
{
title: '名称', dataIndex: 'text', key: 'text', width: 250,
render: (value, record) => {
const {icon} = record;
if (icon) return <span><Icon type={icon}/> {value}</span>;
return value;
}
},
{
title: '类型', dataIndex: 'type', key: 'type', width: 80,
render: value => {
if (value === '1') return '菜单';
if (value === '2') return '功能';
// 默认都为菜单
return '菜单';
}
},
{title: 'path', dataIndex: 'path', key: 'path', width: 150},
{title: 'url', dataIndex: 'url', key: 'url'},
{title: 'target', dataIndex: 'target', key: 'target', width: 100},
];
componentDidMount() {
this.fetchMenus();
this.windowHeight = document.body.clientHeight;
}
componentDidUpdate(prevProps) {
const {visible, form: {resetFields}} = this.props;
// 打开弹框
if (!prevProps.visible && visible) {
// 重置表单,接下来填充新的数据
resetFields();
// 重新获取数据
this.fetchData();
}
}
fetchData() {
const {roleId} = this.props;
if (!roleId) {
// 添加操作
this.setState({data: {}, selectedRowKeys: []});
} else {
// 修改操作
// TODO 根据id 发送ajax请求获取数据
this.setState({loading: true});
setTimeout(() => {
const data = {
id: roleId,
name: `角色名称${roleId}`,
description: `角色描述${roleId}`,
permissions: ['ajax', 'user', 'component', '/example/antd/async-select'],
};
const selectedRowKeys = data.permissions;
this.setState({data, selectedRowKeys});
// 如果不是所有的子级都选中,删除父级的key,父级为半选状态
this.setSelectedRowKeys(selectedRowKeys);
this.setState({loading: false});
}, 500);
}
}
fetchMenus() {
localMenus().then(menus => {
// 菜单根据order 排序
const orderedData = [...menus].sort((a, b) => {
const aOrder = a.order || 0;
const bOrder = b.order || 0;
// 如果order都不存在,根据 text 排序
if (!aOrder && !bOrder) {
return a.text > b.text ? 1 : -1;
}
return bOrder - aOrder;
});
const menuTreeData = convertToTree(orderedData);
this.setState({menuTreeData});
});
/*
// TODO 获取所有的菜单,不区分用户
this.setState({loading: true});
this.props.ajax
.get('/menus')
.then(res => {
this.setState({menus: res});
})
.finally(() => this.setState({loading: false}));
*/
}
handleOk = () => {
const {loading, selectedRowKeys, halfSelectedRowKeys} = this.state;
if (loading) return;
const {onOk, form: {validateFieldsAndScroll}} = this.props;
validateFieldsAndScroll((err, values) => {
if (!err) {
// 半选、全选都要提交给后端保存
const keys = selectedRowKeys.concat(halfSelectedRowKeys);
const params = {...values, keys};
const {id} = values;
console.log(params);
// TODO ajax 提交数据
// id存在未修改,不存在未添加
const ajax = id ? this.props.ajax.put : this.props.ajax.post;
this.setState({loading: true});
ajax('/roles', params)
.then(() => {
if (onOk) onOk();
})
.finally(() => this.setState({loading: false}));
}
});
};
handleCancel = () => {
const {onCancel} = this.props;
if (onCancel) onCancel();
};
// 处理选中状态:区分全选、半选
setSelectedRowKeys = (srk) => {
let selectedRowKeys = [...srk];
let halfSelectedRowKeys = [...this.state.halfSelectedRowKeys];
const {menuTreeData} = this.state;
const loop = (dataSource) => {
dataSource.forEach(item => {
const {children, key} = item;
if (children?.length) {
// 所有后代节点
const keys = getGenerationKeys(dataSource, key);
// 未选中节点
const unSelectedKeys = keys.filter(it => !selectedRowKeys.find(sk => sk === it));
// 一个也未选中
if (unSelectedKeys.length && unSelectedKeys.length === keys.length) {
halfSelectedRowKeys = arrayRemove(halfSelectedRowKeys, key);
selectedRowKeys = arrayRemove(selectedRowKeys, key);
}
// 部分选中
if (unSelectedKeys.length && unSelectedKeys.length < keys.length) {
halfSelectedRowKeys = arrayPush(halfSelectedRowKeys, key);
selectedRowKeys = arrayRemove(selectedRowKeys, key);
}
// 全部选中了
if (!unSelectedKeys.length && keys.length) {
halfSelectedRowKeys = arrayRemove(halfSelectedRowKeys, key);
selectedRowKeys = arrayPush(selectedRowKeys, key);
}
loop(children);
}
});
};
loop(menuTreeData);
this.setState({halfSelectedRowKeys, selectedRowKeys});
};
getCheckboxProps = (record) => {
const {halfSelectedRowKeys, selectedRowKeys} = this.state;
const {key} = record;
// 半选
if (halfSelectedRowKeys.includes(key)) return {checked: false, indeterminate: true};
// 全选
if (selectedRowKeys.includes(key)) return {checked: true, indeterminate: false};
return {};
};
onSelect = (record, selected) => {
const {key} = record;
let selectedRowKeys = [...this.state.selectedRowKeys];
// 选中、反选所有的子节点
const keys = getGenerationKeys(this.state.menuTreeData, key);
keys.push(key);
keys.forEach(k => {
if (selected) {
selectedRowKeys = arrayPush(selectedRowKeys, k);
} else {
selectedRowKeys = arrayRemove(selectedRowKeys, k);
}
this.setSelectedRowKeys(selectedRowKeys);
})
};
FormElement = (props) => <FormElement form={this.props.form} labelWidth={100} {...props}/>;
render() {
const {visible} = this.props;
const {loading, data, menuTreeData, selectedRowKeys} = this.state;
const FormElement = this.FormElement;
return (
<Modal
destroyOnClose
width="70%"
confirmLoading={loading}
visible={visible}
title={data.id ? '编辑角色' : '添加角色'}
onOk={this.handleOk}
onCancel={this.handleCancel}
>
<Spin spinning={loading}>
<Form>
{data.id ? (<FormElement type="hidden" field="id" decorator={{initialValue: data.id}}/>) : null}
<Row>
<Col span={10}>
<FormElement
label="角色名称"
field="name"
decorator={{
initialValue: data.name,
rules: [
{required: true, message: '请输入角色名称!'}
],
}}
/>
</Col>
<Col span={14}>
<FormElement
label="角色描述"
type="textarea"
field="description"
rows={1}
decorator={{
initialValue: data.description,
}}
/>
</Col>
</Row>
</Form>
<Table
size="small"
defaultExpandAllRows
columns={this.columns}
rowSelection={{
selectedRowKeys,
onChange: this.setSelectedRowKeys,
getCheckboxProps: this.getCheckboxProps,
onSelect: this.onSelect
}}
dataSource={menuTreeData}
pagination={false}
scroll={{y: this.windowHeight ? this.windowHeight - 390 : 400}}
/>
</Spin>
</Modal>
);
}
}
|
'use strict';
/**
* @ngdoc service
* @name dssiFrontApp.KeyLoanStatus
* @description
* # KeyLoanStatus
* Factory in the dssiFrontApp.
*/
angular.module('dssiFrontApp')
.factory('KeyLoanStatus', function () {
var service = {
key_loan_statuses: [
{
id: 0,
name: 'No prestada'
},
{
id: 1,
name: 'Prestada'
}
]
};
return service;
});
|
import search from './script/search';
import virtualkeyboard from './script/keyboard/keyboard';
|
import createState from '../state'
export default ( state, mapper = null ) => {
return ( fn ) => {
if ( mapper ) {
const newState = createState( mapper( state ) )
newState.__subscribe( fn )
state.__subscribe( store => {
Object.assign( newState, mapper( state ) )
} )
return fn( mapper( state ) )
} else {
state.__subscribe( fn )
return fn( state )
}
}
}
|
// Auth
export { default as Auth } from './Auth';
// Connect Twitter
export { default as TwitterConnect } from './TwitterConnect';
// App bar
export { default as AppBar } from './AppBar';
// HelpDesk
export { default as HelpDesk } from './HelpDesk'; |
module.exports = express => {
return express.use((request, response, next) => {
response.header("Access-Control-Allow-Origin", "*");
response.header(
"Access-Control-Allow-Methods",
"GET,PUT,POST,DELETE,OPTIONS"
);
response.header(
"Access-Control-Allow-Headers",
"Content-type,Accept,Authorization"
);
if (request.method === "OPTIONS") {
return response.status(200).end();
}
return next();
});
};
|
#!/usr/bin/env node
'use strict';
const path = require('path');
const connect = require('connect');
const proxy = require('proxy-middleware');
const url = require('url');
const webpack = require('webpack');
const bodyParser = require('body-parser');
const api = require('./server/api');
const contentBase = path.resolve(__dirname);
const port = getSetting('PORT', 9999);
const bridgeHost = getSetting('BRIDGE_HOST', 'http://bridgelearning.dev:3000');
const bridgeBase = getSetting('BRIDGE_ROOT', function() {
return require('./server/resolveBridgeRoot')();
});
const app = connect();
const compiler = webpack(loadAndMonkeyPatchWebpackConfig({
port: port,
bridgeBase: bridgeBase
}));
// Forward all /api requests to Bridge Rails:
app.use('/api', proxy(url.parse(`${bridgeHost}/api`)));
app.use('/auth', proxy(url.parse(`${bridgeHost}/auth`)));
// We'll need body parsing for the activation API, see server/api.js
app.use(bodyParser.json());
// Mirage API endpoints:
api(app, { bridgeBase: bridgeBase });
app.use(require('webpack-dev-middleware')(compiler, {
contentBase: contentBase,
publicPath: compiler.options.output.publicPath,
hot: false,
quiet: false,
noInfo: process.env.PROFILE !== '1',
lazy: false,
inline: false,
profile: process.env.PROFILE === '1',
historyApiFallback: false,
watchOptions: {
aggregateTimeout: 300,
},
stats: {
colors: true,
hash: true,
version: true,
timings: process.env.PROFILE === '1',
assets: process.env.PROFILE === '1',
chunks: true,
modules: process.env.PROFILE === '1',
reasons: process.env.PROFILE === '1',
children: process.env.PROFILE === '1',
source: false,
errors: true,
errorDetails: true,
warnings: true,
publicPath: process.env.PROFILE === '1',
},
}));
app.use(require('webpack-hot-middleware')(compiler));
// serve Mirage index.html:
app.use(require('serve-static')(contentBase));
// forward to bridge's public/ directory for static assets like fonts/,
// locales/, etc.:
app.use(require('serve-static')(path.join(bridgeBase, 'public')));
console.log(Array(80).join('='));
console.log('Mirage [Bridge]');
console.log(Array(80).join('-'));
console.log('Mirage: Running initial Webpack build, hold your horses...');
compiler.plugin('done', fnOnce(function() {
console.log('Mirage: OK, all set for play.');
}));
app.listen(port, function() {
console.log('Mirage: HTTP server listening at %d', port);
});
function fnOnce(fn) {
let called = false;
return function() {
if (!called) {
called = true;
fn.apply(null, arguments);
}
}
}
function getSetting(key, defaultValue) {
let userConfig;
try {
userConfig = require('./config');
}
catch(e) {
userConfig = {};
}
return process.env[key] || userConfig[key] || lazy(defaultValue);
function lazy(x) {
if (typeof x === 'function') {
return x();
}
else {
return x;
}
}
}
function loadAndMonkeyPatchWebpackConfig(settings) {
const config = require('./webpack.config')({
bridgeBase: settings.bridgeBase,
happy: getSetting('HAPPY'),
withDLLs: getSetting('WEBPACK_DLLS'),
});
const apiToken = getSetting('BRIDGE_API_TOKEN');
if (!apiToken || String(apiToken).length === 0) {
console.error("Mirage: BRIDGE_API_TOKEN must be configured!");
process.exit(1);
}
config.entry.bundle = [
`webpack-hot-middleware/client?path=http://localhost:${settings.port}/__webpack_hmr`
].concat( config.entry.bundle );
config.output.publicPath = '/build/';
config.plugins = (config.plugins || []).concat([
new webpack.DefinePlugin({
// 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.BRIDGE_API_TOKEN': JSON.stringify(apiToken)
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
]);
return config;
}
|
import $ from '../../core/renderer';
import Action from '../../core/action';
import DOMComponent from '../../core/dom_component';
import { active, focus, hover, keyboard } from '../../events/short';
import { deferRender, deferRenderer, noop } from '../../core/utils/common';
import { each } from '../../core/utils/iterator';
import { extend } from '../../core/utils/extend';
import { focusable as focusableSelector } from './selectors';
import { inArray } from '../../core/utils/array';
import { isPlainObject, isDefined } from '../../core/utils/type';
import '../../events/click';
import '../../events/core/emitter.feedback';
import '../../events/hover';
function setAttribute(name, value, target) {
name = name === 'role' || name === 'id' ? name : "aria-".concat(name);
value = isDefined(value) ? value.toString() : null;
target.attr(name, value);
}
var Widget = DOMComponent.inherit({
_feedbackHideTimeout: 400,
_feedbackShowTimeout: 30,
_supportedKeys() {
return {};
},
_getDefaultOptions() {
return extend(this.callBase(), {
hoveredElement: null,
isActive: false,
disabled: false,
visible: true,
hint: undefined,
activeStateEnabled: false,
onContentReady: null,
hoverStateEnabled: false,
focusStateEnabled: false,
tabIndex: 0,
accessKey: undefined,
/**
* @section Utils
* @type function
* @default null
* @type_function_param1 e:object
* @type_function_param1_field1 component:this
* @type_function_param1_field2 element:DxElement
* @type_function_param1_field3 model:object
* @name WidgetOptions.onFocusIn
* @action
* @hidden
*/
onFocusIn: null,
/**
* @section Utils
* @type function
* @default null
* @type_function_param1 e:object
* @type_function_param1_field1 component:this
* @type_function_param1_field2 element:DxElement
* @type_function_param1_field3 model:object
* @name WidgetOptions.onFocusOut
* @action
* @hidden
*/
onFocusOut: null,
onKeyboardHandled: null,
ignoreParentReadOnly: false
});
},
_init() {
this.callBase();
this._initContentReadyAction();
},
_innerWidgetOptionChanged: function _innerWidgetOptionChanged(innerWidget, args) {
var options = Widget.getOptionsFromContainer(args);
innerWidget && innerWidget.option(options);
this._options.cache(args.name, options);
},
_bindInnerWidgetOptions(innerWidget, optionsContainer) {
var syncOptions = () => this._options.silent(optionsContainer, extend({}, innerWidget.option()));
syncOptions();
innerWidget.on('optionChanged', syncOptions);
},
_getAriaTarget() {
return this._focusTarget();
},
_initContentReadyAction() {
this._contentReadyAction = this._createActionByOption('onContentReady', {
excludeValidators: ['disabled', 'readOnly']
});
},
_initMarkup() {
var {
disabled,
visible
} = this.option();
this.$element().addClass('dx-widget');
this._toggleDisabledState(disabled);
this._toggleVisibility(visible);
this._renderHint();
this._isFocusable() && this._renderFocusTarget();
this.callBase();
},
_render() {
this.callBase();
this._renderContent();
this._renderFocusState();
this._attachFeedbackEvents();
this._attachHoverEvents();
this._toggleIndependentState();
},
_renderHint() {
var {
hint
} = this.option();
this.$element().attr('title', hint || null);
},
_renderContent() {
deferRender(() => !this._disposed ? this._renderContentImpl() : void 0).done(() => !this._disposed ? this._fireContentReadyAction() : void 0);
},
_renderContentImpl: noop,
_fireContentReadyAction: deferRenderer(function () {
return this._contentReadyAction();
}),
_dispose() {
this._contentReadyAction = null;
this._detachKeyboardEvents();
this.callBase();
},
_resetActiveState() {
this._toggleActiveState(this._eventBindingTarget(), false);
},
_clean() {
this._cleanFocusState();
this._resetActiveState();
this.callBase();
this.$element().empty();
},
_toggleVisibility(visible) {
this.$element().toggleClass('dx-state-invisible', !visible);
this.setAria('hidden', !visible || void 0);
},
_renderFocusState() {
this._attachKeyboardEvents();
if (this._isFocusable()) {
this._renderFocusTarget();
this._attachFocusEvents();
this._renderAccessKey();
}
},
_renderAccessKey() {
var $el = this._focusTarget();
var {
accessKey
} = this.option();
$el.attr('accesskey', accessKey);
},
_isFocusable() {
var {
focusStateEnabled,
disabled
} = this.option();
return focusStateEnabled && !disabled;
},
_eventBindingTarget() {
return this.$element();
},
_focusTarget() {
return this._getActiveElement();
},
_getActiveElement() {
var activeElement = this._eventBindingTarget();
if (this._activeStateUnit) {
return activeElement.find(this._activeStateUnit).not('.dx-state-disabled');
}
return activeElement;
},
_renderFocusTarget() {
var {
tabIndex
} = this.option();
this._focusTarget().attr('tabIndex', tabIndex);
},
_keyboardEventBindingTarget() {
return this._eventBindingTarget();
},
_refreshFocusEvent() {
this._detachFocusEvents();
this._attachFocusEvents();
},
_focusEventTarget() {
return this._focusTarget();
},
_focusInHandler(event) {
if (!event.isDefaultPrevented()) {
this._createActionByOption('onFocusIn', {
beforeExecute: () => this._updateFocusState(event, true),
excludeValidators: ['readOnly']
})({
event
});
}
},
_focusOutHandler(event) {
if (!event.isDefaultPrevented()) {
this._createActionByOption('onFocusOut', {
beforeExecute: () => this._updateFocusState(event, false),
excludeValidators: ['readOnly', 'disabled']
})({
event
});
}
},
_updateFocusState(_ref, isFocused) {
var {
target
} = _ref;
if (inArray(target, this._focusTarget()) !== -1) {
this._toggleFocusClass(isFocused, $(target));
}
},
_toggleFocusClass(isFocused, $element) {
var $focusTarget = $element && $element.length ? $element : this._focusTarget();
$focusTarget.toggleClass('dx-state-focused', isFocused);
},
_hasFocusClass(element) {
var $focusTarget = $(element || this._focusTarget());
return $focusTarget.hasClass('dx-state-focused');
},
_isFocused() {
return this._hasFocusClass();
},
_getKeyboardListeners() {
return [];
},
_attachKeyboardEvents() {
this._detachKeyboardEvents();
var {
focusStateEnabled,
onKeyboardHandled
} = this.option();
var hasChildListeners = this._getKeyboardListeners().length;
var hasKeyboardEventHandler = !!onKeyboardHandled;
var shouldAttach = focusStateEnabled || hasChildListeners || hasKeyboardEventHandler;
if (shouldAttach) {
this._keyboardListenerId = keyboard.on(this._keyboardEventBindingTarget(), this._focusTarget(), opts => this._keyboardHandler(opts));
}
},
_keyboardHandler(options, onlyChildProcessing) {
if (!onlyChildProcessing) {
var {
originalEvent,
keyName,
which
} = options;
var keys = this._supportedKeys(originalEvent);
var func = keys[keyName] || keys[which];
if (func !== undefined) {
var handler = func.bind(this);
var result = handler(originalEvent, options);
if (!result) {
return false;
}
}
}
var keyboardListeners = this._getKeyboardListeners();
var {
onKeyboardHandled
} = this.option();
keyboardListeners.forEach(listener => listener && listener._keyboardHandler(options));
onKeyboardHandled && onKeyboardHandled(options);
return true;
},
_refreshFocusState() {
this._cleanFocusState();
this._renderFocusState();
},
_cleanFocusState() {
var $element = this._focusTarget();
$element.removeAttr('tabIndex');
this._toggleFocusClass(false);
this._detachFocusEvents();
this._detachKeyboardEvents();
},
_detachKeyboardEvents() {
keyboard.off(this._keyboardListenerId);
this._keyboardListenerId = null;
},
_attachHoverEvents() {
var {
hoverStateEnabled
} = this.option();
var selector = this._activeStateUnit;
var namespace = 'UIFeedback';
var $el = this._eventBindingTarget();
hover.off($el, {
selector,
namespace
});
if (hoverStateEnabled) {
hover.on($el, new Action(_ref2 => {
var {
event,
element
} = _ref2;
this._hoverStartHandler(event);
this.option('hoveredElement', $(element));
}, {
excludeValidators: ['readOnly']
}), event => {
this.option('hoveredElement', null);
this._hoverEndHandler(event);
}, {
selector,
namespace
});
}
},
_attachFeedbackEvents() {
var {
activeStateEnabled
} = this.option();
var selector = this._activeStateUnit;
var namespace = 'UIFeedback';
var $el = this._eventBindingTarget();
active.off($el, {
namespace,
selector
});
if (activeStateEnabled) {
active.on($el, new Action(_ref3 => {
var {
event,
element
} = _ref3;
return this._toggleActiveState($(element), true, event);
}), new Action(_ref4 => {
var {
event,
element
} = _ref4;
return this._toggleActiveState($(element), false, event);
}, {
excludeValidators: ['disabled', 'readOnly']
}), {
showTimeout: this._feedbackShowTimeout,
hideTimeout: this._feedbackHideTimeout,
selector,
namespace
});
}
},
_detachFocusEvents() {
var $el = this._focusEventTarget();
focus.off($el, {
namespace: "".concat(this.NAME, "Focus")
});
},
_attachFocusEvents() {
var $el = this._focusEventTarget();
focus.on($el, e => this._focusInHandler(e), e => this._focusOutHandler(e), {
namespace: "".concat(this.NAME, "Focus"),
isFocusable: (index, el) => $(el).is(focusableSelector)
});
},
_hoverStartHandler: noop,
_hoverEndHandler: noop,
_toggleActiveState($element, value) {
this.option('isActive', value);
$element.toggleClass('dx-state-active', value);
},
_updatedHover() {
var hoveredElement = this._options.silent('hoveredElement');
this._hover(hoveredElement, hoveredElement);
},
_findHoverTarget($el) {
return $el && $el.closest(this._activeStateUnit || this._eventBindingTarget());
},
_hover($el, $previous) {
var {
hoverStateEnabled,
disabled,
isActive
} = this.option();
$previous = this._findHoverTarget($previous);
$previous && $previous.toggleClass('dx-state-hover', false);
if ($el && hoverStateEnabled && !disabled && !isActive) {
var newHoveredElement = this._findHoverTarget($el);
newHoveredElement && newHoveredElement.toggleClass('dx-state-hover', true);
}
},
_toggleDisabledState(value) {
this.$element().toggleClass('dx-state-disabled', Boolean(value));
this.setAria('disabled', value || undefined);
},
_toggleIndependentState() {
this.$element().toggleClass('dx-state-independent', this.option('ignoreParentReadOnly'));
},
_setWidgetOption(widgetName, args) {
if (!this[widgetName]) {
return;
}
if (isPlainObject(args[0])) {
each(args[0], (option, value) => this._setWidgetOption(widgetName, [option, value]));
return;
}
var optionName = args[0];
var value = args[1];
if (args.length === 1) {
value = this.option(optionName);
}
var widgetOptionMap = this["".concat(widgetName, "OptionMap")];
this[widgetName].option(widgetOptionMap ? widgetOptionMap(optionName) : optionName, value);
},
_optionChanged(args) {
var {
name,
value,
previousValue
} = args;
switch (name) {
case 'disabled':
this._toggleDisabledState(value);
this._updatedHover();
this._refreshFocusState();
break;
case 'hint':
this._renderHint();
break;
case 'ignoreParentReadOnly':
this._toggleIndependentState();
break;
case 'activeStateEnabled':
this._attachFeedbackEvents();
break;
case 'hoverStateEnabled':
this._attachHoverEvents();
this._updatedHover();
break;
case 'tabIndex':
case 'focusStateEnabled':
this._refreshFocusState();
break;
case 'onFocusIn':
case 'onFocusOut':
break;
case 'accessKey':
this._renderAccessKey();
break;
case 'hoveredElement':
this._hover(value, previousValue);
break;
case 'isActive':
this._updatedHover();
break;
case 'visible':
this._toggleVisibility(value);
if (this._isVisibilityChangeSupported()) {
// TODO hiding works wrong
this._checkVisibilityChanged(value ? 'shown' : 'hiding');
}
break;
case 'onKeyboardHandled':
this._attachKeyboardEvents();
break;
case 'onContentReady':
this._initContentReadyAction();
break;
default:
this.callBase(args);
}
},
_isVisible() {
var {
visible
} = this.option();
return this.callBase() && visible;
},
beginUpdate() {
this._ready(false);
this.callBase();
},
endUpdate() {
this.callBase();
if (this._initialized) {
this._ready(true);
}
},
_ready(value) {
if (arguments.length === 0) {
return this._isReady;
}
this._isReady = value;
},
setAria() {
if (!isPlainObject(arguments.length <= 0 ? undefined : arguments[0])) {
setAttribute(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], (arguments.length <= 2 ? undefined : arguments[2]) || this._getAriaTarget());
} else {
var target = (arguments.length <= 1 ? undefined : arguments[1]) || this._getAriaTarget();
each(arguments.length <= 0 ? undefined : arguments[0], (name, value) => setAttribute(name, value, target));
}
},
isReady() {
return this._ready();
},
repaint() {
this._refresh();
},
focus() {
focus.trigger(this._focusTarget());
},
registerKeyHandler(key, handler) {
var currentKeys = this._supportedKeys();
this._supportedKeys = () => extend(currentKeys, {
[key]: handler
});
}
});
Widget.getOptionsFromContainer = _ref5 => {
var {
name,
fullName,
value
} = _ref5;
var options = {};
if (name === fullName) {
options = value;
} else {
var option = fullName.split('.').pop();
options[option] = value;
}
return options;
};
export default Widget; |
const { intersect } = require("../utils");
const solve = (data) => {
const ingredientCount = new Map();
const allergenFoods = new Map();
data.forEach((line) => {
const [first, second] = line.split(" (contains ");
const ingredients = first.split(" ");
const allergens = second.slice(0, -1).split(", ");
ingredients.forEach((x) => ingredientCount.set(x, (ingredientCount.get(x) || 0) + 1));
allergens.forEach((x) => allergenFoods.set(x, (allergenFoods.get(x) || []).concat(new Set(ingredients))));
});
const dangerousIngredients = new Map();
const queue = [...allergenFoods].map(([allergen, v]) => [allergen, v.reduce(intersect)]);
while (queue.length > 0) {
const [allergen, ingredients] = queue.pop();
if (ingredients.size === 1) {
const ingredient = [...ingredients][0];
dangerousIngredients.set(ingredient, allergen);
queue.forEach(([, value]) => value.delete(ingredient));
} else {
queue.unshift([allergen, ingredients]);
}
}
return [dangerousIngredients, ingredientCount];
};
module.exports = {
part1: (data) => {
const [dangerousIngredients, ingredientCount] = solve(data);
return [...ingredientCount].reduce((acc, [k, v]) => (dangerousIngredients.has(k) ? acc : acc + v), 0);
},
part2: (data) => {
const [dangerousIngredients] = solve(data);
return [...dangerousIngredients]
.sort((a, b) => (a[1] > b[1] ? 1 : -1))
.map((x) => x[0])
.join(",");
},
};
|
import React from 'react';
const Form = () => {
const [name,setName] = React.useState("");
const [email,setEmail] = React.useState("");
const [password,setPassword] = React.useState("");
const [people,setPeople] = React.useState([]);
const handleSubmit = (e) => {
e.preventDefault();
if( name && email ){
const person = { id:new Date().getTime().toString() ,name,email}
setPeople( (people) => {
return [...people, person];
} );
setName("");
setEmail("");
setPassword("");
// console.log(people);
}
};
const changeName = (value) => {
setName( value );
}
const changeEmail = (value) => {
setEmail( value );
}
const changePassword = (value) => {
setPassword( value );
}
return (
<React.Fragment>
<article>
<form action="" className="form" onSubmit={ handleSubmit }>
<div className="form-control">
<label
htmlFor="userName">Enter Name: </label>
<input
type="text"
name="userName"
id="userName"
onChange = { (e) => { changeName(e.target.value) } }
value={name}
/>
</div>
<div className="form-control">
<label htmlFor="userEmail">Email</label>
<input
type="email"
name="userEmail"
id="userEmail"
value={email}
onChange = { (e) => changeEmail( e.target.value ) }
/>
</div>
<div className="form-control">
<label htmlFor="userPassword">Password</label>
<input
type="password"
name="userPassword"
id="userPassword"
value={password}
onChange = { (e) => changePassword( e.target.value ) }
/>
</div>
<button type="submit" className="btn">Submit</button>
</form>
{
people.map( (person) => {
const { id,name,email } = person;
return (
<div className="personList item" key={id}>
<h4>{name}</h4>
<p>{email}</p>
</div>
)
})
}
</article>
</React.Fragment>
)
}
export default Form; |
(function() {
'use strict'
angular
.module('customer')
.config(routerConfig);
routerConfig.$inject = ['$stateProvider', '$urlRouterProvider'];
function routerConfig($stateProvider, $urlRouterProvider) {
$stateProvider
.state('customers', {
url: '/customers',
templateUrl: 'src/app/manager.customer/customers.html',
controller: 'customerController',
controllerAs: 'customer'
})
.state('customers.search', {
url: '/search',
templateUrl: 'src/app/manager.customer/customers.search.html'
})
.state('customers.edit', {
url: '/edit',
templateUrl: 'src/app/manager.customer/customers.edit.html'
})
$urlRouterProvider.otherwise('/');
}
})() |
(function(){
//--------------------------------------
//--------------------------------------
//Ура, счетчик, нормааааас. Замыкания))))
let func = function(){
let count = 1;
return function(){
//count++;
console.log(++count);
}
};
//var timerId = setInterval(func(), 2000);
//---------------------------------------
//---------------------------------------
// 1. Создаём новый объект XMLHttpRequest
var xhr = new XMLHttpRequest();
// 2. Конфигурируем его: GET-запрос на URL 'phones.json'
xhr.open('POST', ' test.txt', false);
// 3. Отсылаем запрос
xhr.send();
// 4. Если код ответа сервера не 200, то это ошибка
if (xhr.status != 200) {
// обработать ошибку
alert( xhr.status + ': ' + xhr.statusText ); // пример вывода: 404: Not Found
} else {
// вывести результат
console.log( xhr.responseText ); // responseText -- текст ответа.
}
var app = new Vue({
el: '#test',
data: {
message: 'Hello Vue.js!',
seen: true,
}
});
var para = new Vue({
el: "#paraid",
data: {
para: "Text",
},
methods: {
ReverseMessage: function(){
this.para = this.para.split('').reverse().join('');
},
}
});
var inp = new Vue({
el:"#test_input",
data: {
message: "Hello Vue!"
},
});
var testfor = new Vue({
el:"#new",
data: {
myarray: [
{text: "Oleg"},
{text: "Nastenka"},
{text: "Slastenka"},
],
},
});
var a = document.getElementById("pp");
a.addEventListener("mouseover", function(){
app.seen = false;
a.style.backgroundColor="blue";
});
//a.addEventListener("mouseout", function(){
// app.seen = true;
// a.style.backgroundColor="red";
//});
})();
|
$(document).ready(function() {
$('.settings-link').click(function(event) {
event.preventDefault();
var link = $(this).attr('href');
$.ajax({
url: link,
type: 'GET',
dataType: 'html',
beforeSend: function()
{
showBusy();
},
success: function(html)
{
updateSettingsPage(html);
}
});
});
try {
var domains = JSON.parse(localStorage.getItem('domains'));
var categories = JSON.parse(localStorage.getItem('categories'));
} catch (e) {
return true;
}
// Set the Domain menus.
if (domains !== null) {
$('#settings-front').before('<ul class="accordion" id="front-accordion"></ul>');
for (i = 0; i < domains.length; i++) {
$('#study-links').append('<li class="has-dropdown domain-link" domainid="' +
domains[i].id + '"><a href="#">' + domains[i].name +
'</a><ul class="dropdown" id="domain-' + domains[i].id +
'"></ul></li><li class="divider"></li>');
$('#front-accordion').append('<li><div class="title"><h5>' +
domains[i].name + '</h5></div><div class="content"><ul id="front-domain-' +
domains[i].id + '"></ul></div></li>');
};
}
// Set the Category menus.
if (categories !== null) {
for (i = 0; i < categories.length; i++) {
var UlDomain = $('#domain-' + categories[i].domainId);
$(UlDomain).append('<li><a href="pages/questions.html" class="question-link" categoryid="' +
categories[i].id + '" categoryname="' + categories[i].name + '">' +
categories[i].name + '</a></li><li class="divider"></li>');
var frontDomain = document.getElementById('front-domain-' + categories[i].domainId);
$(frontDomain).append('<li><a href="pages/questions.html" class="question-link" categoryid="'+
categories[i].id + '" categoryname="' +
categories[i].name+'">' + categories[i].name + '</a></li>');
}
}
});
$(document).on('click', '.question-link', function(event) {
event.preventDefault();
var link = $(this).attr('href');
var categoryId = parseInt($(this).attr('categoryid'));
var categoryName = $(this).attr('categoryname');
$.ajax({
url: link,
type: 'GET',
dataType: 'html',
beforeSend: function()
{
showBusy();
},
success: function(html)
{
updateQuestionsPage(html, categoryId, categoryName);
}
});
});
$(document).on('click', '.marked-link', function(event) {
event.preventDefault();
var link = $(this).attr('href');
$.ajax({
url: link,
type: 'GET',
dataType: 'html',
beforeSend: function()
{
showBusy();
},
success: function(html)
{
var marked = localStorage.getItem('marked');
if (marked) {
var categoryId, categoryName;
updateQuestionsPage(html, categoryId, categoryName);
}
else {
$('#ajax-content').html('<h2>Bookmarked Questions</h2><p>You have no bookmarked questions.</p>');
}
}
});
});
$(document).on('submit', '#login-form', function(event) {
event.preventDefault();
var ajaxHtml = $('#ajax-content').html();
var username = $('#input-username').val();
var apiKey = $('#input-apikey').val();
// Saveusername and password.
if (typeof(localStorage) === 'undefined' )
{
alert('Your browser does not support HTML5 localStorage. Try upgrading.');
}
else
{
try
{
localStorage.setItem('username', username);
localStorage.setItem('apiKey', apiKey);
updateSettingsPage(ajaxHtml);
$('#messages').html('Username and api key saved successfully.<a href="" class="close">×</a>');
$('#messages').removeClass('alert');
$('#messages').addClass('alert-box success');
}
catch (e)
{
alert(e);
updateSettingsPage(ajaxHtml);
$('#messages').html('There was a problem saving the username and api key.<a href="" class="close">×</a>');
$('#messages').removeClass('success');
$('#messages').addClass('alert-box alert');
}
}
});
$(document).on('click', '#sync-button', function(event) {
event.preventDefault();
document.addEventListener("deviceready", syncNow, false);
function syncNow() {
var connectionType = navigator.connection.type;
if (connectionType == Connection.NONE) {
alert('It seems you are not connected to a network.');
}
else {
var ajaxHtml = $('#ajax-content').html();
var username = localStorage.getItem('username');
var apiKey = localStorage.getItem('apiKey');
var data = {username:username, apiKey:apiKey};
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://9etraining.laughinghost.com/study-rest',
data: data,
beforeSend: function()
{
showBusy();
},
success: function(data)
{
if (data.data === 'user') {
updateSettingsPage(ajaxHtml);
$('#messages').html('Username was not found.<a href="" class="close">×</a>');
$('#messages').removeClass('success');
$('#messages').addClass('alert-box alert');
}
else if (data.data === 'key') {
updateSettingsPage(ajaxHtml);
$('#messages').html('Api key was not found.<a href="" class="close">×</a>');
$('#messages').removeClass('success');
$('#messages').addClass('alert-box alert');
}
else {
localStorage.setItem('domains', JSON.stringify(data.data.domains));
localStorage.setItem('categories', JSON.stringify(data.data.categories));
localStorage.setItem('questions', JSON.stringify(data.data.questions));
try {
var domains = JSON.parse(localStorage.getItem('domains'));
var categories = JSON.parse(localStorage.getItem('categories'));
var questions = JSON.parse(localStorage.getItem('questions'));
} catch (e) {
showFail();
}
// Remove menus.
$('#study-links li').remove();
$('#study-links').append('<li class="divider"></li>');
// Set the domain menus.
for (i = 0; i < domains.length; i++) {
$('#study-links').append('<li class="has-dropdown domain-link" domainid="' +
domains[i].id + '"><a href="#">' + domains[i].name +
'</a><ul class="dropdown" id="domain-' + domains[i].id +
'"></ul></li><li class="divider"></li>');
};
// Set the Category menus.
for (i = 0; i < categories.length; i++) {
var UlDomain = $('#domain-' + categories[i].domainId);
$(UlDomain).append('<li><a href="pages/questions.html" class="question-link" categoryid="' +
categories[i].id + '" categoryname="' + categories[i].name + '">' +
categories[i].name + '</a></li><li class="divider"></li>');
}
updateSettingsPage(ajaxHtml);
if (domains.length > 0 && categories.length > 0 && questions.length > 0) {
$("#sync-modal").reveal();
}
}
}
});
}
}
});
$(document).on('click', '#sync-refresh-button', function() {
window.location.reload();
});
|
/*
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
*/
var lengthOfLIS = function(nums) {
if (!nums.length) {
return 0;
}
var result = 1;
var dpArr = [];
for (var k = 0; k < nums.length; k++) {
dpArr.push(1);
}
for (var i = 1; i < nums.length; i++) {
for (var j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dpArr[i] = Math.max(dpArr[i], dpArr[j] + 1);
}
}
result = Math.max(result, dpArr[i]);
}
return result;
};
console.log(lengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18]));
console.log(lengthOfLIS([4, 8, 7, 9, 6, 10]));
console.log(lengthOfLIS([4,10,4,3,8,9])); |
var $faqSearch = $('.faqs-page #faq_search_input');
var $accordion = $(".faqs-page #faqs_accordion");
var $originalData = $accordion.html();
var timer;
var interval = 500;
$faqSearch.focus();
// Do the ajax request with a delay
$faqSearch.on('input', function (e) {
clearTimeout(timer);
// Third argument passes the input to the function
timer = setTimeout(ajaxCall, interval, $(this));
// if ($faqSearch.val()) {
// }
});
function ajaxCall(input) {
var search = input.val();
if (search) {
$.ajax({
url: 'api/search-faq/' + search,
type: 'POST',
headers: {
'Authorization': 'Bearer mBu7IB6nuxh8RVzJ61f4',
},
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {},
success: function (data) {
// var json_obj = $.parseJSON(data);//parse JSON
$('.alert').slideUp(); // Hide alert if previously shown
var ajaxBox = $(".faqs-page #faqs_accordion");
ajaxBox.empty(); // remove old content
//Check if we have at least one result in our data
// console.log(data.data.faqs);
if (!$.isEmptyObject(data.data.faqs)) {
$.each(data.data.faqs, function (key, obj) { //$.parseJSON() method is needed unless chrome is throwing error.
// var regex = new RegExp(search, 'gi');
// Replace the search term within the results with a highlighted span
// result = result.replace(regex, `<span class="hl">${search}</span>`);
ajaxBox.append('<div class="card"><div class="card-header" id="heading'+key+'">\n' +
' <h2 class="mb-0">\n' +
' <button class="btn btn-link collapsed text-left" type="button"\n' +
' data-toggle="collapse"\n' +
' data-target="#collapse'+key+'" aria-expanded="false"\n' +
' aria-controls="collapse'+key+'">' + obj.question + "</button>\n" +
" </h2>\n" +
' </div><div id="collapse'+key+'" class="collapse" aria-labelledby="heading'+key+'" data-parent="#faqs_accordion">\n' +
'<div class="card-body">\n' +
'<p>' + obj.answer + '</button>\n' +
' </p>\n' +
'</div>\n' +
'</div></div>');
});
ajaxBox.highlight(search); // Use the highlight API to search for keyword, not including HTML tags
} else {
ajaxBox.append('<h3>No FAQs found! Please refine the search.</h3>');
}
},
error: function (data) {
showAlert('Something went wrong! Please try again.', false);
},
});
} else {
// Show the full list when the search is empty, or deleted
$accordion.html($originalData);
}
};
|
import React, { Component, Fragment } from 'react';
import { Route, Switch } from 'react-router-dom';
import Layout from './components/Layout/Layout';
import ProductsList from './containers/ProductsList/ProductsList'
import Cart from './containers/Cart/cart'
import Details from './containers/Details/Details';
import Default from './containers/Defaults/Default'
class App extends Component {
render() {
return (
<Fragment>
<Layout>
<Switch>
<Route path='/' exact component={ProductsList}/>
<Route path='/cart' component={Cart}/>
<Route path='/detail' component={Details}/>
<Route component={Default}/>
</Switch>
</Layout>
</Fragment>
);
}
}
export default App;
|
/*
* @Description:
* @Author: yamanashi12
* @Date: 2019-05-10 10:17:53
* @LastEditTime: 2021-01-19 16:37:02
* @LastEditors: Please set LastEditors
*/
import { Message } from 'element-ui'
import { httpError302 } from './plubs/preivew302'
const isDev = process.env.NODE_ENV === 'development'
const loginLink = '/login.index'
/**
* response 过滤器
*
* @export
* @param {*} res
* @returns
*/
export default function filterResponse(config = {}, res = {}) {
const { options = {} } = config
if (options.noCheck) {
// 忽略过滤器
return {
data: res.data,
response: res
}
}
if (res.code === 400) {
if (options.preview302) {
httpError302()
} else if (options.noAuth) {
// 开发环境登录鉴权
Message({
message: '请先到特定系统登录',
type: 'error',
duration: 2 * 1000
})
// eslint-disable-next-line no-throw-literal
throw {
response: res,
status: res.status,
request: res.request,
responseText: res.data && (res.data.errorMessage || res.data.msg) ? res.data.errorMessage || res.data.msg : '网络错误',
errorCode: res.data && (res.data.errorCode || res.data.code) !== undefined ? res.data.errorCode || res.data.code : 1
}
} else if (!isDev) {
Message({
message: '请先登录',
type: 'error',
duration: 2 * 1000,
onClose() {
window.location.href = loginLink
}
})
// 正式环境未登录跳转
window.location.href = loginLink
}
} else if (res.data && res.data.code === 2 && !isDev && !options.noAuth) {
Message({
message: '无权限',
type: 'error',
duration: 2 * 1000,
onClose() {
window.location.href = loginLink
}
})
} else if (!res.data || (res.data.errorCode !== 0 && res.data.code !== 0) || res.status !== 200) {
// eslint-disable-next-line
throw {
response: res,
status: res.status,
request: res.request,
responseText: res.data && (res.data.errorMessage || res.data.msg) ? res.data.errorMessage || res.data.msg : '网络错误',
errorCode: res.data && (res.data.errorCode || res.data.code) !== undefined ? res.data.errorCode || res.data.code : 1
}
}
return {
data: res.data.data,
response: res
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import {Alert, Container, Row, Col, Modal, ModalBody, ModalFooter, ModalHeader, Button,Table} from 'reactstrap';
import { Badge } from 'reactstrap';
import {connect} from 'react-redux';
import {cancelWeather} from 'api/open-weather-map.js';
import {getWeather, weatherToggle} from 'states/weather-actions.js';
import {listPosts, createPost, createVote} from 'api/posts.js';
import ReminderForm_en from 'components/ReminderForm_en.jsx'
import './Mood.css';
import moment from 'moment';
import PostList_en from 'components/PostList_en.jsx';
import {getStartSleepTime, getEndSleepTime, getStartPhoneTime, getEndPhoneTime, sleepToggle, phoneToggle, breakFastToggle} from 'states/actions.js';
import {listSleepTime, createSleepTime, listSleepTimeServer, createSleepTimeServer} from 'api/sleep.js';
import {listPhoneTime, createPhoneTime, listPhoneTimeServer, createPhoneTimeServer} from 'api/phone.js'
var FontAwesome = require('react-fontawesome');
import GymStats from 'components/GymStats.jsx';
import {listGymTimeServer, createGymTime, listGymTime} from 'api/gym.js';
export default class Test extends React.Component {
constructor(props){
super(props);
this.state = {
sleep: false,
data: [],
postLoading: false,
muscleList: [],
muscle: '二頭肌',
text: '',
};
this.sleepTime = new Date();
this.diff = 0;
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.getStartSleepTime = this.getStartSleepTime.bind(this);
this.getEndSleepTime = this.getEndSleepTime.bind(this);
this.listSleepTime = this.listSleepTime.bind(this);
}
render() {
// console.log('data', this.state.data);
const {startSleepTime, endSleepTime} = this.props;
return (
<div>
<MuscleList muscleList={this.state.muscleList}/>
<form onSubmit={this.handleSubmit}>
<input
onChange={this.handleChange}
value={this.state.text}
/>
<button>
Add #{this.state.muscleList.length + 1}
</button>
</form>
<div>
<Button color="warning" id="icon4" onClick = {this.getStartSleepTime}><img src="images/icon2.png" id="image4"/></Button>
<Button color="warning" id="icon4" onClick = {this.getEndSleepTime}><img src="images/icon3.png" id="image3"/></Button>
<div>
<GymStats/>
</div>
</div>
</div>
);
}
handleChange(e) {
this.setState({ text: e.target.value });
console.log("handleChange",this.state.text);
}
handleSubmit(e) {
e.preventDefault();
if (!this.state.text.length) {
return;
}
const newItem = {
text: this.state.text,
id: Date.now()
};
this.setState(prevState => ({
muscleList: prevState.muscleList.concat(newItem),
text: ''
}));
}
getStartSleepTime() {
// console.log('dddata', this.state.data);
if(this.state.sleep === false){
this.state.sleep = true;
let startSleepTime = new Date();
this.sleepTime = new Date();
let unixSleepTime = moment.utc(moment(startSleepTime,"DD/MM/YYYY HH:mm:ss")).format("x");
console.log('unixSleepTime', unixSleepTime);
//this.props.dispatch(getStartSleepTime(startSleepTime));
}else {
let endSleepTime = new Date();
//this.diff = moment.utc(moment(endSleepTime,"DD/MM/YYYY HH:mm:ss").diff(moment(this.sleepTime,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss");
let unixEndSleepTime = moment.utc(moment(endSleepTime,"DD/MM/YYYY HH:mm:ss")).format("x");
console.log('unixEndSleepTime', unixEndSleepTime);
//console.log(moment(endSleepTime,"DD/MM/YYYY HH:mm:ss"));
var diff = moment.utc(moment(endSleepTime,"DD/MM/YYYY HH:mm:ss").diff(moment(this.sleepTime,"DD/MM/YYYY HH:mm:ss"))).format("X");
//this.props.dispatch(getEndSleepTime(endSleepTime,diff));
//this.props.dispatch(sleepToggle());
// var x = moment(this.sleepTime,"DD/MM");
// console.log(x);
//this.handleCreateSleep(this.sleepTime, endSleepTime, diff);
let start = '1514906850989';
let end = '1514906860989'; /// 先寫死!!!
let key = 'test';
this.listSleepTime(start, end, key);
// console.log('data', this.state.data);
}
}
listSleepTime(start, end, key) {
// console.log('hi');
this.setState({
postLoading: true
}, () => {
listGymTimeServer(start, end).then(data => {
console.log('datttta', data);
// this.setState({
// data: data,
// postLoading: false
// });
createGymTime(key, data);
}).catch(err => {
console.error('Error listing GymTime', err);
this.setState({
data: [],
postLoading: false
});
});
});
}
// handleCreateSleep(start, end, diff) {
// //console.log(diff);
// createSleepTime(start, end, diff).then(() => {
// this.listSleepTime();
// }).catch(err => {
// console.error('Error creating SleepTime', err);
// });
// createSleepTimeServer(start, end, diff).then(() => {
// listSleepTimeServer();
// }).catch(err => {
// console.error('Error creating SleepTime', err);
// });
// }
getEndSleepTime() {
let key = 'test';
this.setState({
// postLoading: true
}, () => {
listGymTime(key).then(data => {
console.log('all data array', data);
this.setState({
data: data,
postLoading: false
});
}).catch(err => {
console.error('Error listing GymTime', err);
this.setState({
data: [],
// postLoading: false
});
});
});
}
}
// export default connect((state) => {
// return {
// ...state.sleep,
// ...state.phone,
// ...state.weather,
// ...state.breakFast,
// unit: state.unit
// };
// })(Test);
class MuscleList extends React.Component {
render() {
console.log("hello",this.props.muscleList);
return (
<ul>
{this.props.muscleList.map(item => (
<li key={item.id}>
<button>{item.text}</button>
</li>
))}
</ul>
);
}
} |
// Jsnack 2 - Updated
// Creare un array di oggetti:
// Ogni oggetto descriverà una bici da corsa con le seguenti proprietà: nome e peso.
// Stampare a schermo la bici con peso minore utilizzando destructuring e template literal
const bikes = [
{
nome : 'giant',
peso : 8
},
{
nome : 'cannondale',
peso : 2
},
{
nome : 'merida',
peso : 3
}
];
let lightBike = bikes[0].peso;
for (let i = 0; i < bikes.length; i++) {
if (bikes[i].peso < lightBike) {
lightBike = bikes[i];
}
}
// ho 3 variabili di oggetti bici
const [giant, cannondale, merida] = bikes;
console.log(giant, cannondale, merida);
const biciLeggera = `La bici più leggera è: ${lightBike.nome}`;
console.log(biciLeggera);
document.getElementById('bici').innerHTML = `
<li>Nome: ${lightBike.nome}</li>
<li>Peso: ${lightBike.peso}</li>
`
|
dashboard.controller("hduserhome", ['$rootScope', '$scope', '$state', '$location', 'dashboardService', 'Flash','createTicketService','assignticketService','userHomeService', '$localStorage',
function ($rootScope, $scope, $state, $location, dashboardService, Flash,createTicketService,assignticketService,userHomeService, $localStorage) {
var vm = this;
var userdetails;
$scope.ticketsOpened = {};
$scope.ticketsInprogress = {};
$scope.querytickets = {};
$scope.closedTickets = {};
$scope.raisedTickets = {};
$scope.cancelTickets = {};
$scope.GroupallocatedTickets = {};
$scope.GroupticketsInprogress = {};
$scope.Groupquerytickets = {};
$scope.GroupclosedTickets = {};
$scope.GroupticketsOpened = {};
$scope.Groupcanceltickets = {};
$scope.IndvcancelTickets ={};
$scope.myValue = true;
$scope.GroupValue = false;
$scope.IndvValue = false;
$scope.HeadValue = false;
$scope.IndividualValue = false;
$scope.BUValue = true;
$scope.IndBUValue = true;
vm.emailid = {};
vm.userrole = {};
var userfilteredticks = {};
var indvfilteredticks = {};
var headfilteredticks = {};
$scope.init=function(){
// userdetails = $localStorage.User;
userdetails = JSON.parse(window.localStorage.getItem("User"));
// vm.emailid = $localStorage.User.emailid;
if (userdetails != null) {
vm.emailid = userdetails.emailid;
}
vm.userrole = "User";
if (JSON.parse(window.localStorage.getItem("hduserrole")) != null) {
// if ($localStorage.hduserrole.role.includes("BUGroupIndividual")) {
if (JSON.parse(window.localStorage.getItem("hduserrole")).role.indexOf("BUGroupIndividual") != -1) {
vm.userrole = "BUGroupIndividual"
}
// else if ($localStorage.hduserrole.role.includes("BUGroupHead")) {
else if (JSON.parse(window.localStorage.getItem("hduserrole")).role.indexOf("BUGroupHead") != -1) {
vm.userrole = "BUGroupHead"
};
}
userHomeService.getRaisedTickets( [vm.emailid , vm.userrole] ).then(function(response){
var inprogressTicks = [];
var queryTicks = [];
var completedTicks = [];
var closedTicks = [];
var openedTicks = [];
var cancelTicks = [];
var indvinprogressTicks = [];
var indvqueryTicks = [];
var indvclosedTicks = [];
var indvcompletedTicks = [];
var indvassignedTicks = [];
var indvcancelTicks = [];
var headinprogressTicks = [];
var headqueryTicks = [];
var headclosedTicks = [];
var headopenedTicks = [];
var headAssignedTicks = [];
var headcompletedTicks = [];
var headcancelTicks =[];
var jresonse = JSON.stringify(response);
userfilteredticks = JSON.parse(jresonse).filter( function(entry) {
if (entry.owneremail == vm.emailid) {
if(entry.status == "In-Progress") {
inprogressTicks.push(entry); }
else if(entry.status == "Query") {
queryTicks.push(entry); }
else if(entry.status == "Completed") {
completedTicks.push(entry); }
else if(entry.status == "Closed") {
closedTicks.push(entry); }
else if(entry.status == "Open"||entry.status == "Assigned") {
openedTicks.push(entry); }
else if(entry.status == "Cancel") {
cancelTicks.push(entry); }
return true;
}
else
{ return false;}
// return entry.owneremail == vm.emailid;
});
indvfilteredticks = JSON.parse(jresonse).filter( function(entry) {
if (entry.Assigned_to == vm.emailid) {
if(entry.status == "In-Progress") {
indvinprogressTicks.push(entry); }
else if(entry.status == "Query") {
indvqueryTicks.push(entry); }
else if(entry.status == "Completed") {
indvcompletedTicks.push(entry); }
else if(entry.status == "Assigned") {
indvassignedTicks.push(entry); }
else if(entry.status == "Closed") {
indvclosedTicks.push(entry); }
else if(entry.status == "Cancel") {
indvcancelTicks.push(entry); }
return true;
}
else
{ return false;}
//return entry.Assigned_to == vm.emailid;
});
headfilteredticks = JSON.parse(jresonse).filter( function(entry) {
if (entry.categoryhead == vm.emailid) {
if(entry.status == "In-Progress") {
headinprogressTicks.push(entry); }
else if(entry.status == "Query") {
headqueryTicks.push(entry); }
else if(entry.status == "Completed") {
headcompletedTicks.push(entry); }
else if(entry.status == "Closed") {
headclosedTicks.push(entry); }
else if(entry.status == "Assigned") {
headAssignedTicks.push(entry); }
else if(entry.status == "Open") {
headopenedTicks.push(entry); }
else if(entry.status == "Cancel") {
headcancelTicks.push(entry); }
return true;
}
else
{ return false;}
//return entry.categoryhead == vm.emailid;
});
$scope.raisedTickets = userfilteredticks.length;
$scope.ticketsOpened = openedTicks.length;
$scope.ticketsInprogress = inprogressTicks.length;
$scope.ticketsCompleted = completedTicks.length;
$scope.querytickets = queryTicks.length;
$scope.closedTickets = closedTicks.length;
$scope.cancelTickets = cancelTicks.length;
if ($scope.raisedTickets == 0 ) { $scope.myValue = false;};
if ( JSON.parse(window.localStorage.getItem("hduserrole")) != null){
// if ( $localStorage.hduserrole.role.includes("BUGroupIndividual") ) {
if ( JSON.parse(window.localStorage.getItem("hduserrole")).role.indexOf("BUGroupIndividual") != -1 ) {
$scope.IndvValue = true;
$scope.IndvassignedTickets = indvfilteredticks.length;
$scope.IndvticketsAssigned = indvassignedTicks.length;
$scope.IndvticketsInprogress = indvinprogressTicks.length;
$scope.Indvquerytickets = indvqueryTicks.length;
$scope.IndvcompletedTickets = indvcompletedTicks.length;
$scope.IndvclosedTickets = indvclosedTicks.length;
$scope.IndvcancelTickets = indvcancelTicks.length;
}
// if ($localStorage.hduserrole.role.includes("BUGroupHead") ) {
if (JSON.parse(window.localStorage.getItem("hduserrole")).role.indexOf("BUGroupHead") != -1) {
$scope.GroupValue = true;
$scope.HeadValue = true;
$scope.GroupallocatedTickets = headfilteredticks.length;
$scope.GroupticketsOpened = headopenedTicks.length;
$scope.GroupticketsAssigned = headAssignedTicks.length;
$scope.GroupticketsInprogress = headinprogressTicks.length;
$scope.Groupquerytickets = headqueryTicks.length;
$scope.GroupcompletedTickets = headcompletedTicks.length;
$scope.GroupclosedTickets = headclosedTicks.length;
$scope.Groupcanceltickets = headcancelTicks.length;
};
}
if ($scope.GroupallocatedTickets == 0 ) { $scope.BUValue = false;};
if ($scope.IndvassignedTickets == 0 ) { $scope.IndBUValue = false;};
setTimeout(function(){
$scope.$apply(function(){
$scope.options = {
data: [
{
Opened : $scope.ticketsOpened,
Inprogress: $scope.ticketsInprogress,
Query : $scope.querytickets,
Completed : $scope.ticketsCompleted,
Closed : $scope.closedTickets,
Cancel : $scope.cancelTickets
}
],
dimensions: {
Opened: { type : 'pie'},
Inprogress: { type : 'pie'},
Query: { type : 'pie'},
Completed: { type : 'pie'},
Closed: { type : 'pie'},
Cancel: { type : 'pie'}
}
}
$scope.groupoptions = {
data: [
{
ActionRequired : $scope.GroupticketsOpened,
Assigned : $scope.GroupticketsAssigned,
Inprogress: $scope.GroupticketsInprogress,
Query : $scope.Groupquerytickets,
Completed : $scope.GroupcompletedTickets,
Closed : $scope.GroupclosedTickets,
Cancel : $scope.Groupcanceltickets
}
],
dimensions: {
ActionRequired: { type : 'pie'},
Assigned: { type : 'pie'},
Inprogress: { type : 'pie'},
Query: { type : 'pie'},
Completed: { type : 'pie'},
Closed: { type : 'pie'},
Cancel: { type : 'pie'}
}
}
$scope.indvoptions = {
data: [
{
ActionRequired : $scope.IndvticketsAssigned,
Inprogress : $scope.IndvticketsInprogress,
Query : $scope.Indvquerytickets,
Completed : $scope.IndvcompletedTickets,
Closed : $scope.IndvclosedTickets,
Cancel : $scope.IndvcancelTickets
}
],
dimensions: {
ActionRequired: { type : 'pie'},
Inprogress : { type : 'pie'},
Query : { type : 'pie'},
Completed : { type : 'pie'},
Closed : { type : 'pie'},
Cancel : { type : 'pie'}
}
}
});});
}); // service Get call end
};// Init call end
$scope.init();
$scope.go = function(ai) {
window.location.replace('#/app/mytickets');
};
}
]);
|
const {MongoClient, ObjectID} = require('mongodb');
MongoClient.connect(`mongodb://localhost:27017/TodoApp`, (err, db) => {
if (err) {
return console.log("Unable to connect to mongodb server", err);
}
console.log("Connected to mongodb server");
//deleteMany
// db.collection('Todos').deleteMany({text:"eat lunch"}).then((result)=>{
// console.log(result);
// });
//deleteOne -> deltes the first match
// db.collection('Todos').deleteOne({text: 'eat lunch'}).then((result)=>{
// console.log(result);
// });
//findOneandDelete -> deletes the first match doc and return it
db.collection('Todos').findOneAndDelete({completed:false}).then((result)=>{
console.log(result);
})
//db.close();
}); //amazon webservices or heroku url or localhost url |
appModule.service('fileServices', ["fileUploadQueue", function ( fileUploadQueue) {
this.uploadFileToUrl = function (file, uploadUrl, progressCallback, successCallback, errorCallback) {
var fd = new FormData();
fd.append('file', file);
var request = new window.XMLHttpRequest();
var progressObj = fileUploadQueue.queueUpload(file);
request.upload.addEventListener('progress', progressObj.progressFunc);
if (progressCallback) request.upload.addEventListener('progress', progressCallback);
if (errorCallback) request.upload.addEventListener('error', errorCallback);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
successCallback(request.response.substr(1, request.response.length - 2));
fileUploadQueue.completeUpload(progressObj);
}
};
request.open("POST", uploadUrl);
request.send(fd);
};
}
]).service('multipleFileServices', ["fileUploadQueue", function ( fileUploadQueue) {
this.uploadFileToUrl = function (file, uploadUrl) {
return new window.Promise(function (resolve, reject) {
var fd = new FormData();
fd.append('file', file);
var request = new window.XMLHttpRequest();
var progressObj = fileUploadQueue.queueUpload(file);
request.upload.addEventListener('progress', progressObj.progressFunc);
request.onload = function () {
if (request.status === 200) {
resolve(request.response.substr(1, request.response.length - 2));
fileUploadQueue.completeUpload(progressObj);
}
else {
reject(Error(request.statusText));
}
};
request.onerror = function () {
reject(Error(Arguments));
};
request.open("POST", uploadUrl);
request.send(fd);
});
};
}
]);
appModule.service("fileUploadQueue", ["$rootScope", "$timeout",
function ($rootScope, $timeout) {
this.queueUpload = function (file) {
var progressObj = {
fileName: file.name,
fileSize: file.size
};
var progressFunc = function (progress) {
$timeout(function () {
progressObj.uploadedPercent = (progress.loaded / progress.total).toFixed(2) * 100;
if (progressObj.uploadedPercent > 98) progressObj.uploadedPercent = 98;
});
};
progressObj.progressFunc = progressFunc;
if (!$rootScope.uploadQueue) $rootScope.uploadQueue = [];
$rootScope.uploadQueue.push(progressObj);
$rootScope.showingUploadQueue = true;
return progressObj;
}
this.completeUpload = function (progressObj) {
$timeout(function () {
$rootScope.uploadQueue.splice($rootScope.uploadQueue.indexOf(progressObj), 1);
if ($rootScope.uploadQueue.length === 0) {
$rootScope.showingUploadQueue = false;
}
});
}
}
]); |
window.addEventListener("load", function () {
handleAddHtmlOnClick();
});
function handleAddHtmlOnClick(){
let btns = document.querySelectorAll(".oocss-html-adder");
for (let index = 0; index < btns.length; index++) {
let btn = btns[index];
let target = document.querySelector(btn.dataset.targetSelector);
let path = btn.dataset.path;
let callback = function(response) {
let htmlNode = document.createElement("template");
htmlNode = response.trim();
target.insertAdjacentHTML('beforeend', htmlNode);
}
btn.addEventListener("click", function(){
ajaxGet(path, callback);
});
}
}
|
export const getDateId = (date) => {
if (date && date.getTime()) {
return date.getFullYear().toString().padStart(4,'0')
+ (date.getMonth()+1).toString().padStart(2,'0')
+ date.getDate().toString().padStart(2,'0')
} else return ''
}
export const filterOfDate = (date) => {
if (date && date.getTime()) {
const hour = date.getHours()
return hour >= 5 && hour < 11? 'BREAKFAST'
: hour >= 11 && hour < 16? 'LUNCH'
: hour >= 16 && hour < 23? 'DINNER'
: 'SNACK';
} else return '';
}
|
'use strict';
angular.module('podcasts')
.component('podcasts', {
templateUrl: 'podcasts/podcasts.template.html',
controller: ['podcastsFactory', function(podcastsFactory) {
var feeds = [];
podcastsFactory.getFeeds(function(data) {
this.feeds = data['feeds'];
}.bind(this));
this.feeds = feeds;
}]
});
|
import styled from "styled-components";
const Button = styled.button`
font-size: 21px;
color: ${props => props.type === "cancel" ? "#52B6FF" : "#FFFFFF"};
border: none;
background: ${props => props.type === "cancel" ? "#FFFFFF" : "#52B6FF"};
border-radius: 4.63636px;
width: ${props => props.width}px;
height: ${props => props.height}px;
`
export default Button
|
function ResponseError(status, data, message) {
this.name = 'ResponseError'
this.message = message
Error.call(this, message)
Error.captureStackTrace(this, this.constructor)
this.status = status
this.data = data
}
ResponseError.prototype = Object.create(Error.prototype)
ResponseError.prototype.constructor = ResponseError
export default ResponseError
|
import React from 'react';
import { View, Text, Image, Alert, TouchableOpacity } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { signOut } from '~/store/modules/auth/actions';
import Background from '~/components/Background';
import Header from '~/components/Header';
import { Container, Title, RowClosure, InfoClosure, TitleClosure, ValueClosure,
RowCurrentCapital, InfoCurrentCapital, TitleCurrentCapital, ValueCurrentCapital,
DetailingCurrentCapital, DetailingCurrentCapitalRight, DetailingCurrentCapitalLeft,
DetailingRowCurrentCapital, TitleDetailing, SubTitleDetailing, ResultSubTitleDetailing } from './styles';
export default function ServicosItens() {
const dispatch = useDispatch();
function Logout(){
dispatch(signOut());
}
return (
<Background>
<Header />
<Container>
<RowClosure>
<InfoClosure>
<TouchableOpacity onPress={Logout}>
<TitleClosure>Sair</TitleClosure>
</TouchableOpacity>
</InfoClosure>
</RowClosure>
</Container>
</Background>
);
}
|
import { message } from 'antd';
import { find, create, detail, update } from '../services/client';
export default {
namespace: 'client',
state: {
isLoading: false,
listData: {
list: [],
pagination: {
currentPage: 1,
pageSize: 10,
},
},
detail: {},
},
effects: {
*find({ payload }, { call, put }) {
yield put({
type: 'setLoading',
payload: true,
});
const response = yield call(find, payload);
if (response.success) {
yield put({
type: 'setListData',
payload: response.data,
});
} else {
message.error(response.data);
}
},
*create({ payload, callback }, { call, put }) {
const response = yield call(create, payload);
if (response.success) {
yield put({
type: 'addListData',
payload: response.data,
});
callback && callback();
message.success('创建成功');
} else {
message.error(response.data);
}
},
*detail({ payload, callback }, { call, put }) {
const response = yield call(detail, payload);
if (response.success) {
yield put({
type: 'setDetail',
payload: response.data,
});
callback && callback(response.data);
} else {
message.error(response.data);
}
},
*clearDetail(_, { put }) {
yield put({
type: 'setDetail',
payload: {},
});
},
*update({ payload, callback }, { call }) {
const response = yield call(update, payload);
if (response.success) {
callback && callback(response.data);
message.success('更新成功');
} else {
message.error(response.data);
}
},
},
reducers: {
setLoading(state, { payload }) {
return {
...state,
isLoading: !!payload,
};
},
setListData(state, { payload }) {
return {
...state,
listData: { ...payload },
isLoading: false,
};
},
addListData(state, { payload }) {
return {
...state,
listData: {
...state.listData,
list: [payload, ...state.listData.list],
},
};
},
setDetail(state, { payload }) {
return {
...state,
detail: payload,
};
},
},
};
|
const {Router} = require('express');
const router = Router();
const {auth} = require('../controller/auth')
const {addBook,getBook,getTitle,getArticle,getReaded} = require('../controller/book')
router.post('/',addBook);
router.get('/',getBook);
router.post('/title',getTitle)
router.post('/article',auth,getReaded,getArticle)
module.exports = router;
|
function adds() {
var li = document.createElement("LI");
document.getElementById("ssss").appendChild(li);
li.innerHTML=document.getElementById("textt").value;
};
function remove() {
document.getElementById("ssss").innerHTML="";
};
|
import { trackingApi } from "@sitecore-jss/sitecore-jss-tracking";
import { dataFetcher } from "./../utils/dataFetcher";
const config = {
"sitecoreApiKey": "{5339D3FA-E63B-4FFF-9349-CC2C76413C47}",
"sitecoreApiHost": "http://spotify.wenneker.local",
"jssAppName": "spotitube",
"defaultLanguage": "en",
"graphQLEndpointPath": "/api/spotitube",
"graphQLEndpoint": "http://localhost:3000/api/spotitube?sc_apikey={5339D3FA-E63B-4FFF-9349-CC2C76413C47}"
};
const trackingApiOptions = {
host: config.sitecoreApiHost,
querystringParams: {
sc_apikey: config.sitecoreApiKey
},
fetcher: dataFetcher
};
export function trackEventSubscribe(eventId) {
return trackGoal("Subscribe to Event");
}
export function trackEventUnsubscription(eventId) {
return trackGoal("Unsubscribe to Event");
}
export function trackEventFavorite(eventId) {
return trackGoal("Favorite Event");
}
export function trackEventUnfavorite(eventId) {
return trackGoal("Unfavorite Event");
}
export function trackCompleteRegistration() {
return trackGoal("Complete Registration");
}
export function trackCompleteFavoriteSports() {
return trackGoal("Complete Favorite Sports");
}
export function trackCompleteDemographics() {
return trackGoal("Complete Demographics");
}
export function trackGoal(goalId) {
return trackingApi
.trackEvent([{ goalId }], trackingApiOptions)
.then(() => console.log("Goal pushed to JSS tracker API"))
.catch(error => console.error(error));
}
|
function heapSort(arr) {
if (Object.prototype.toString.call(arr) !== '[object Array]') {
console.log('param is not an array');
return;
}
function swap(i ,j){
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
function heapify(start,end) {
let dad = start;
let son = dad * 2 + 1;
if(son >= end){
return;
}
if(son + 1 < end && arr[son] < arr[son+1]){
son++;
}
if(arr[dad] <= arr[son]){
swap(dad , son);
heapify(son, end);
}
}
let len = arr.length;
for (let i = Math.floor(len/2) -1; i >= 0;i--){
heapify(i,len);
}
for (let i = len-1; i > 0;i--){
swap(0,i);
heapify(0,i);
console.log(arr)
}
return arr;
}
module.exports ={
sort: heapSort
}
|
import axios from 'axios';
const header = (token) => ({
headers: {
Authorization: `Bearer ${token}`,
},
});
export const signInGamePost = (token, gameId) => {
const url = '/api/game/signin/' + (gameId ? gameId : '');
return axios.post(url, null, header(token));
};
export const startGamePost = (token, gameId) => {
return axios.post('/api/game/startgame/' + gameId, null, header(token));
};
export const getGame = (token, gameId) =>
axios.get('/api/game/' + gameId, header(token));
export const askPost = (token, gameId, question) =>
axios.post('/api/game/ask/' + gameId, question, header(token));
export const guessPost = (token, gameId, guess) =>
axios.post('/api/game/guess/' + gameId, { guess: guess }, header(token));
export const betPost = (token, gameId, betValue) =>
axios.post('/api/game/bet/' + gameId, { betValue }, header(token));
export const foldPost = (token, gameId) =>
axios.post('/api/game/fold/' + gameId, null, header(token));
|
var Monster = require("Monster");
var Hero = require("Hero");
var Menu = require("menu");
cc.Class({
extends: cc.Component,
properties: {
menuList:{
default:null,
type:cc.Node
},
monster:{
default:null,
type:Monster,
visible: true, // optional, default is true
displayName: '怪兽', // optional
readonly: true
},
hero:{
default:null,
type:Hero,
visible: true, // optional, default is true
displayName: '英雄', // optional
readonly: true
},
menu : {
default:null,
type:Menu,
viaible:true
}
},
// use this for initialization
onLoad: function () {
var menulist = this.menuList.getComponent('menulist');
var self = this;
this.node.on(cc.Node.EventType.TOUCH_END, function (event) {
//如果列表弹出则收回
if(menulist.menuState == 'UP'){
//发射列表弹出事件
menulist.node.emit('move-down');
}
//播放monster别打击动画
self.monster.beHit(10);
//主角动画
self.hero.heroAction();
//复位按钮
self.menu.setButtonsNaomal();
}, this);
},
// called every frame, uncomment this function to activate update callback
// update: function (dt) {
// },
});
|
import './createDiagramme'
import './createGraphs' |
/*
* @Author: huangyuhui
* @since: 2020-07-07 16:29:19
* @LastAuthor: huangyuhui
* @lastTime: 2020-07-23 10:54:55
* @message:
* @FilePath: \supply-chain-system\webpack\webpack.prod.js
*/
const baseConf = require('./webpack.base');
const { merge } = require('webpack-merge');
var MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const path = require('path');
const webpack = require('webpack');
const {
development: isDevelopment,
local: isLocal,
production: isProduction,
volume: isShowVolume
} = require('yargs').argv;
module.exports = merge(baseConf, {
mode: 'production',
devtool: 'nosources-source-map',
output: {
filename: `js/[name].[chunkhash].js`,
path: path.join(process.cwd(), 'dist'),
chunkFilename: `js/[name].[chunkhash].js`,
publicPath: isProduction && isLocal ? './' : '/',
},
plugins: [
new CompressionPlugin({
algorithm: 'gzip',
threshold: 8192,
test: /\.(js|css|html|svg)$/,
}),
new MiniCssExtractPlugin({
filename: 'style/[name].[contenthash].css',
chunkFilename: 'style/[name].[contenthash].css',
}),
/* 添加 dll 插件 */
new webpack.DllReferencePlugin({
context: '.',
manifest: require(path.resolve(process.cwd(), 'dll/vendor-manifest.json'))
}),
new AddAssetHtmlPlugin({
filepath: path.resolve(process.cwd(), "dll/*.dll.js")
}),
/* 打包进度条 */
new ProgressBarPlugin(),
/* 体积可视化 */
isShowVolume && new BundleAnalyzerPlugin()
].filter(Boolean),
});
|
const segments = require('./bike_paths.json');
const turf = require('@turf/turf');
const fs = require('fs');
let collection = turf.featureCollection(segments.features);
let features = [];
const radius = 100; // feet
const mileConversionConstant = 0.000189394; // feet to miles
const statusMap = {
'ACTIVE': 'active',
'PLANNED': 'planned',
'RECOMM': 'recommended'
}
collection.features.forEach((feature) => {
// only keep those bike paths that are either existing or possible in the future
if (['ACTIVE', 'PLANNED', 'RECOMM'].includes(feature.properties.Status)) {
const length = turf.length(feature.geometry, { units: 'meters' });
const midpoint = turf.along(feature.geometry, length / 2, { units: 'meters' });
const buffer = turf.circle(midpoint.geometry.coordinates, radius * mileConversionConstant, { steps: 8, units: 'miles' });
features.push(
turf.feature(
buffer.geometry,
{
name: feature.properties.SegmentName,
status: statusMap[feature.properties.Status],
type: feature.properties.Facility,
objectId: feature.properties.OBJECTID,
tranPlanID: feature.properties.TranPlanID,
}
)
);
}
});
collection = turf.featureCollection(features);
fs.writeFileSync('bike_path_midpoints.json', JSON.stringify(collection));
|
const express = require('express');
const userDb = require('../data/helpers/userDb');
const postDb = require('../data/helpers/postDb');
const router = express.Router();
// GET /api/user/:id
router.get('/:id', (req, res) => {
const { id } = req.params;
console.log(id);
userDb
.get(id)
.then(user => {
if (user) {
res.send(user);
} else {
res.status(404).json({message: 'user does not exist'});
}
})
.catch(err => {
res.status(500)
.json({ message: 'unable to fullfill request' });
});
});
// GET /api/users/:userId
router.get('/:userId/posts', (req, res) => {
const { userId } = req.params;
console.log(userId);
userDb
.getUserPosts(userId)
.then(posts => {
res.send(posts);
})
.catch(err => {
res.status(500)
.json({ message: 'unable to get user posts' });
});
});
// CREATE /api/users/create
router.post('/create', (req, res) => {
const user = req.body;
if (user.name) {
userDb
.insert(user)
.then(idInfo => {
userDb.get(idInfo.id)
.then(user => {
res.status(201).json(idInfo);
});
})
.catch(err => {
res.status(500)
.json({ message: 'failed to insert user into db'});
});
}
});
// DELETE /api/users/:id
router.delete('/:id', (req, res) => {
const { id } = req.params;
userDb
.remove(id)
.then(count => {
if (count) {
res.json({ message: 'user successfully deleted' });
} else {
res
.status(404)
.json({ message: 'the user with the specified id does not exist' });
}
})
.catch(err => {
res
.status(500)
.json({ error: 'user could not be deleted' });
});
});
// UPDATE /api/users/:id
router.put('/:id', (req, res) => {
const user = req.body;
const { id } = req.params;
if (user.name) {
userDb.update(id, user)
.then(count => {
userDb.get(id)
.then(user => {
res
.json(user);
})
})
.catch(err => {
res
.status(400)
.json({ message: 'please provide new name for user' });
});
} else {
res
.status(500)
.json({ error: 'user information could not be modified.' });
}
});
module.exports = router;
|
import React from "react";
import Router from "next/router";
import io from "socket.io-client";
import withAuth from "../libs/withAuth";
class IOTester extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { permisions } = this.props;
// if (!permisions.includes("io-tester")) {
// Router.push("/dashboard");
// }
const username = "testadm1";
// this.socket = io.connect("/tester");
// this.emit(username, "this message from io-tester");
}
emitMessage = () => {
// this.socket.emit("success", "Hello B2P");
};
render() {
return (
<div className="container">
<h1>IO - Tester - Page </h1>
<button onClick={this.emitMessage} className="btn">
Notifition after 10 second
</button>
</div>
);
}
}
export default withAuth(IOTester);
|
import {
SUPPLIER_FETCHING,
SUPPLIER_SUCCESS,
SUPPLIER_FAILED,
SUPPLIER_CLEAR,
} from "../constants";
const initialState = {
isFetching: false,
isError: false,
result: null,
};
export default (state = initialState, { type, payload }) => {
switch (type) {
case SUPPLIER_FETCHING:
return { ...state, isFetching: true, isError: false, result: null };
case SUPPLIER_FAILED:
return { ...state, isFetching: false, isError: true, result: null };
case SUPPLIER_SUCCESS:
return { ...state, isFetching: false, isError: false, result: payload };
case SUPPLIER_CLEAR:
return { ...state, result: null, isFetching: false, isError: false };
default:
return state;
}
};
|
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
const createaccounttoken = (data) => {
console.log(data)
try {
var token = jwt.sign({_id: data}, 'freelancer-ke-122220928283829');
return token;
} catch (err) {
return err;
}
}
module.exports.createaccounttoken = createaccounttoken; |
var languageTypeRadio = document.querySelector("languageTypeRadio");
var textArea = document.querySelector(".textArea");
var greetAmount = document.querySelector(".greetAmount");
var greetBtn = document.querySelector(".greetBtn");
var greetNameElement = document.querySelector(".greetName");
var resetBtn = document.querySelector(".resetBtn");
var final = "";
var existing = JSON.parse(localStorage.getItem("Name"))
var greetInstance = GreetingsManager(existing);
window.onload = function () {
displayCount();
}
resetBtn.addEventListener('click', function () {
localStorage.clear();
displayCount();
location.reload();
})
greetBtn.addEventListener('click', function () {
var checkedRadioBtn = document.querySelector("input[name='languageType']:checked");
if (checkedRadioBtn) {
var languageType = checkedRadioBtn.value;
}
greetInstance.add(textArea.value);
localStorage.setItem("Name", JSON.stringify(greetInstance.records()));
displayCount();
greetNameElement.innerHTML = greetInstance.greet(languageType);
})
function displayCount() {
document.getElementById("total").innerHTML = greetInstance.count();
}
|
function drawCircle(x,y,circleRad,index){
ctx.lineWidth="5"
ctx.beginPath();
ctx.moveTo(x+circleRad, y);
ctx.arc(x, y, circleRad, 0 * Math.PI / 180, 360 * Math.PI / 180, false );
ctx.stroke();
circleList.push({x:x,y:y,circleRad:circleRad,index:index})
}
function getStartPoint(startCircle,endx,endy){
let rad = Math.atan2(endy - startCircle.y,endx - startCircle.x);
let y = Math.sin(rad) * startCircle.circleRad + startCircle.y;
let x = Math.cos(rad) * startCircle.circleRad + startCircle.x;
return {x,y}
}
function createCircle1(){
let startWidth = 490;
let circleRad = 50;
let x = canvas.width;
let y = canvas.height;
x = canvas.width;
// start & end
ctx.font = "56px serif";
ctx.fillText("S", startWidth-16, y/2+24);
ctx.fillText("E", x-startWidth-16, y/2+24);
drawCircle(startWidth,y/2,circleRad,0);
drawCircle(x-startWidth, y/2,circleRad,4);
// others
drawCircle(x/2, y/4,circleRad,1);
drawCircle(x/2, y/2,circleRad,2);
drawCircle(x/2, y*3/4,circleRad,3);
}
function mousedown(event){
const point = {
x: event.offsetX,
y: event.offsetY
};
preImage = ctx.getImageData(0,0,canvas.width,canvas.height);
for(let circle of circleList){
if(Math.pow(point.x-circle.x,2) + Math.pow(point.y-circle.y,2) <= Math.pow(circle.circleRad,2)){
startCircle = circle
draw = true;
}
}
preImageMove = ctx.getImageData(0,0,canvas.width,canvas.height);
}
function mousemove(event){
let endx = event.offsetX;
let endy = event.offsetY;
if(!endCircle || Math.pow(endx-endCircle.x,2) + Math.pow(endy-endCircle.y,2) > Math.pow(endCircle.circleRad,2)){
endCircle = null;
for(let circle of circleList){
if(Math.pow(endx-circle.x,2) + Math.pow(endy-circle.y,2) <= Math.pow(circle.circleRad,2)){
endCircle = circle
break;
}
}
}
if(draw && Math.pow(endx-startCircle.x,2) + Math.pow(endy-startCircle.y,2) > Math.pow(startCircle.circleRad,2)){
let startPoint = getStartPoint(startCircle,endx,endy);
if(endCircle && Math.pow(endx-endCircle.x,2) + Math.pow(endy-endCircle.y,2) <= Math.pow(endCircle.circleRad,2)){
endx = getStartPoint(endCircle,startCircle.x,startCircle.y).x;
endy = getStartPoint(endCircle,startCircle.x,startCircle.y).y;
startPoint = getStartPoint(startCircle,endx,endy);
}
ctx.putImageData(preImageMove,0,0);
ctx.beginPath();
ctx.moveTo(startPoint.x,startPoint.y);
ctx.lineTo(endx,endy);
ctx.stroke();
}
}
function mouseup(){
draw = false;
if(endCircle){
preImage = ctx.getImageData(0,0,canvas.width,canvas.height);
movable[startCircle.index].push(endCircle.index);
console.log(movable);
}
ctx.putImageData(preImage,0,0);
}
function touchstart(event){
startx = event.offsetX;
starty = event.offsetY;
draw = true;
}
function touchmove(event){
if(draw){
//ctx.save();
ctx.beginPath();
ctx.moveTo(startx, starty);
ctx.lineTo(event.offsetX,event.offsetY);
ctx.stroke();
}
}
function touchend(){
draw = false;
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
circleList = [];
createCircle1();
var startCircle;
var endCircle;
var draw = false;
var preImage;
var preImageMove;
var movable = new Array(5);
movable[0]
for(node of movable){
node = new Array(0);
}
var rate = 1/canvas.width
canvas.addEventListener("mousedown",mousedown,false);
canvas.addEventListener("mousemove",mousemove,false);
canvas.addEventListener("mouseup",mouseup,false);
canvas.addEventListener("touchstart",touchstart,false);
canvas.addEventListener("touchmove",touchmove,false);
canvas.addEventListener("touchend",touchend,false);
|
/**
* Created by Phani on 7/23/2016.
*/
import {FlowRouter} from "meteor/kadira:flow-router";
import {BlazeLayout} from "meteor/kadira:blaze-layout";
import "../../ui/layouts/app_body.js";
import "../../ui/layouts/app_body_fluid.js";
import "../../ui/pages/home.js";
import "../../ui/pages/about/about.js";
import "../../ui/pages/account/account.js";
import "../../ui/pages/account/logout.js";
import "/imports/ui/pages/chart/chart.js";
import {DATA_CHART_ID, DATA_READ_ONLY} from "/imports/ui/components/graph_view/graph_view.js";
import {DATA_SHOW_GRAPH} from "/imports/ui/pages/chart/chart.js"
import "/imports/ui/pages/graph_guide/graph_guide.js";
import {incrementChartDownload} from "/imports/api/charts/methods.js";
//Routes
FlowRouter.route("/", {
name: "App.home",
action() {
BlazeLayout.render("app_body", {main: "home"});
},
});
FlowRouter.route("/about", {
name: "App.about",
action() {
BlazeLayout.render("app_body", {main: "about"});
},
});
FlowRouter.route("/account", {
name: "App.account",
action() {
BlazeLayout.render("app_body", {main: "account"});
},
});
FlowRouter.route("/logout", {
name: "App.account",
action() {
BlazeLayout.render("app_body", {main: "logout"});
},
});
FlowRouter.route("/chart/:chartId", {
name: "App.chart",
action(params) {
let context = {};
context[DATA_CHART_ID] = params.chartId;
context[DATA_READ_ONLY] = true;
context[DATA_SHOW_GRAPH] = false;
BlazeLayout.render("app_body_fluid",
{
main: "chart",
dataContext: context
}
);
},
});
FlowRouter.route("/chart/:chartId/edit", {
name: "App.chart",
action(params) {
incrementChartDownload.call(params.chartId);
let context = {};
context[DATA_CHART_ID] = params.chartId;
context[DATA_READ_ONLY] = false;
context[DATA_SHOW_GRAPH] = true;
BlazeLayout.render("app_body_fluid",
{
main: "chart",
dataContext: context
}
);
},
});
FlowRouter.route("/chart/:chartId/view", {
name: "App.chart",
action(params) {
incrementChartDownload.call(params.chartId);
let context = {};
context[DATA_CHART_ID] = params.chartId;
context[DATA_READ_ONLY] = true;
context[DATA_SHOW_GRAPH] = true;
BlazeLayout.render("app_body_fluid",
{
main: "chart",
dataContext: context
}
);
},
}); |
import {
FETCH_BY_ID_SUCCESS,
FETCH_BY_ID_REQUEST,
FETCH_BY_ID_FAILURE,
} from "./getByIdTypes";
const initialState = {
loading: false,
appDataByIdStats: null,
error: "",
};
const appByIdReducer = (state = initialState, actions) => {
switch (actions.type) {
case FETCH_BY_ID_REQUEST:
return {
...state,
loading: true,
};
case FETCH_BY_ID_SUCCESS:
return {
...state,
loading: false,
appDataByIdStats: actions.payload,
};
case FETCH_BY_ID_FAILURE:
return {
...state,
loading: false,
error: actions.payload,
};
default:
return state;
}
};
export default appByIdReducer;
|
// @flow
import { API3 } from "./api"
import Restrictor from "./restrictor"
function timeout(time: number) {
return new Promise(resolve => setTimeout(resolve, time))
}
declare var NodeFilter: any
export class NodeReplacer {
_api: API3
_idRegex: RegExp = /[235]\d{8}/gi // GE SSO format: d{9}
_restrictor: Restrictor = new Restrictor
constructor(api: API3) {
this._api = api
}
async watch(element: Element) {
await this.replace(element)
const observer = new window.MutationObserver(this._getChangeHandler())
observer.observe(element, {
childList: true,
characterData: true,
subtree: true
})
return this
}
_getChangeHandler() {
return (mutations: Array<MutationRecord>, _observer: MutationObserver) => {
for(const { target } of mutations) {
this.replace(target)
}
}
}
async replace(element: Node) {
console.info("start replacing")
const start = Date.now()
const walker = document.createTreeWalker(element, window.NodeFilter.SHOW_TEXT)
const pending = []
let x = 0
while(walker.nextNode()) {
if(++x === 500) {
x = 0
await timeout(0)
}
const { currentNode } = walker
pending.push(this._replaceNode(currentNode))
}
await Promise.all(pending)
console.info(`finished replacing in ${ Date.now() - start } milliseconds`)
}
_blurNode({ parentElement }: Node) {
if(parentElement instanceof window.HTMLElement) {
parentElement.style.filter = "blur(0.8px)"
}
}
_unblurNode({ parentElement }: Node) {
if(parentElement instanceof window.HTMLElement) {
parentElement.style.filter = ""
}
}
async _replaceNode(node: Node) {
if(!node.nodeValue) {
return
}
const ids = node.nodeValue.match(this._idRegex) || []
if(ids.length <= 0 || !this._restrictor.check(node.parentElement)) {
return
}
const pending = []
for(const id of ids) {
pending.push(this._replaceId(id, node))
}
this._blurNode(node)
await Promise.all(pending)
this._unblurNode(node)
}
async _replaceId(id: string, node: Node) {
const user = await this._api.getUser(id)
node.nodeValue = node.nodeValue.replace(id, user.getName())
}
}
|
import React, { Component } from 'react';
import EditBookEntryInline from './EditBookEntryInline';
class BookEntry extends Component {
constructor(){
super();
this.toggleEditMode = this.toggleEditMode.bind(this);
this.state = {
editMode: false
};
}
toggleEditMode(){
this.setState({
editMode: !this.state.editMode
});
}
render(){
const btnText = this.state.editMode ? "Lukk" : "Endre";
return (
<div className="book-entry">
<p>{this.props.data.text}</p>
<p>Skrevet av: {this.props.data.name}</p>
<button onClick={(e)=>this.props.deleteEntry(this.props.index)}>×</button>
<button onClick={this.toggleEditMode}>{btnText}</button>
<EditBookEntryInline editMode={this.state.editMode} data={this.props.data} index={this.props.index} editEntry={this.props.editEntry} />
</div>
)
}
}
export default BookEntry; |
export default /* glsl */`
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
vec3 unpack3NFloats(float src) {
float r = fract(src);
float g = fract(src * 256.0);
float b = fract(src * 65536.0);
return vec3(r, g, b);
}
vec3 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {
vec4 a = texture2D(tex, tc);
vec4 b = texture2D(tex, tc + graphSampleSize);
float c = fract(tc.x * graphNumSamples);
vec3 unpackedA = unpack3NFloats(a.w);
vec3 unpackedB = unpack3NFloats(b.w);
w = mix(unpackedA, unpackedB, c);
return mix(a.xyz, b.xyz, c);
}
#define HASHSCALE4 vec4(1031, .1030, .0973, .1099)
vec4 hash41(float p) {
vec4 p4 = fract(vec4(p) * HASHSCALE4);
p4 += dot(p4, p4.wzxy+19.19);
return fract(vec4((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x));
}
void main(void) {
if (gl_FragCoord.x > numParticles) discard;
readInput(vUv0.x);
visMode = inShow? 1.0 : -1.0;
vec4 rndFactor = hash41(gl_FragCoord.x + seed);
float particleRate = rate + rateDiv * rndFactor.x;
outLife = inLife + delta;
float nlife = clamp(outLife / lifetime, 0.0, 1.0);
vec3 localVelocityDiv;
vec3 velocityDiv;
vec3 paramDiv;
vec3 localVelocity = tex1Dlod_lerp(internalTex0, vec2(nlife, 0), localVelocityDiv);
vec3 velocity = tex1Dlod_lerp(internalTex1, vec2(nlife, 0), velocityDiv);
vec3 params = tex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);
float rotSpeed = params.x;
float rotSpeedDiv = paramDiv.y;
vec3 radialParams = tex1Dlod_lerp(internalTex3, vec2(nlife, 0), paramDiv);
float radialSpeed = radialParams.x;
float radialSpeedDiv = radialParams.y;
bool respawn = inLife <= 0.0 || outLife >= lifetime;
inPos = respawn ? calcSpawnPosition(rndFactor.xyz, rndFactor.x) : inPos;
inAngle = respawn ? mix(startAngle, startAngle2, rndFactor.x) : inAngle;
#ifndef LOCAL_SPACE
vec3 radialVel = inPos - emitterPos;
#else
vec3 radialVel = inPos;
#endif
radialVel = (dot(radialVel, radialVel) > 1.0E-8) ? radialSpeed * normalize(radialVel) : vec3(0.0);
radialVel += (radialSpeedDiv * vec3(2.0) - vec3(1.0)) * radialSpeedDivMult * rndFactor.xyz;
localVelocity += (localVelocityDiv * vec3(2.0) - vec3(1.0)) * localVelocityDivMult * rndFactor.xyz;
velocity += (velocityDiv * vec3(2.0) - vec3(1.0)) * velocityDivMult * rndFactor.xyz;
rotSpeed += (rotSpeedDiv * 2.0 - 1.0) * rotSpeedDivMult * rndFactor.y;
addInitialVelocity(localVelocity, rndFactor.xyz);
#ifndef LOCAL_SPACE
outVel = emitterMatrix * localVelocity + (radialVel + velocity) * emitterScale;
#else
outVel = (localVelocity + radialVel) / emitterScale + emitterMatrixInv * velocity;
#endif
outPos = inPos + outVel * delta;
outAngle = inAngle + rotSpeed * delta;
`;
|
const yaml = require('js-yaml');
const fs = require('fs');
const { isArray } = require('lodash');
const JSBIN_YAML_PATH = 'data/jsbins.yaml';
const jsbin = yaml.load(fs.readFileSync(JSBIN_YAML_PATH, 'utf-8'));
const JSBIN_CLIENT_OPTIONS = {
ssl: true,
host: 'jsbin.ably.com',
port: 443,
};
const jsbinClient = {
url_for: (id, options = JSBIN_CLIENT_OPTIONS) => {
const maybePanels = isArray(options.panels) ? options.panels.join(',') : options.panels;
const panels =
maybePanels && (options.embed || !options.preview)
? options.embed
? `/embed?${maybePanels}`
: `/edit#${panels}`
: '';
const url = `${options.ssl ? 'https' : 'http'}://${options.host}:${options.port}/${id}${
options.revision ? `/${options.revision}` : `/latest`
}${panels}`;
return url;
},
};
module.exports = {
jsbin,
jsbinClient,
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.