text stringlengths 7 3.69M |
|---|
import React from "react";
import { NavLink } from "react-router-dom";
const Header = props => {
return (
<div>
<div>
<NavLink to="/patient/profile">
<button className="btn btn-primary">profile</button>
</NavLink>
<NavLink to="/patient/appointment">
<button className="btn btn-primary">Appointment</button>
</NavLink>
</div>
<button className="btn btn-danger" onClick={props.handleLogout}>
Logout
</button>
</div>
);
};
export default Header;
|
const path = require('path')
module.exports = {
client: 'pg',
connection:{
host:'localhost',
user: 'shiva',
password: 'shiva',
database:'fee_mgmt'
},
migrations:{
tableName:'migrations',
directory: path.resolve(__dirname, './migrations'),
},
useNullAsDefault:true
}; |
module.exports = {
Scan: require("./scan"),
Vendor:require("./vendors"),
Attendee:require("./attendee"),
Lead: require("./leads")
};
|
function cambionav(){
var navBarNuevo = document.getElementById("nav-bar"); // llamo el nav que esta oculto
var logo= document.getElementById('logo-white');
var distscroll= window.pageYOffset || document.documentElement.scrollTop;
if (distscroll > 100 ){ // al hacer scroll se debe eliminar la clase hide del nav que esta oculto
document.getElementById('nav-bar').classList.add('hide');
document.getElementById('navDos').classList.remove('hide');
}else{
document.getElementById('navDos').classList.add('hide');
document.getElementById('nav-bar').classList.remove('hide');
}
};
window.addEventListener('scroll' , cambionav)
/* VALIDACION FORMULARIO */
var phone = document.getElementById("phone");
phone.onclick = function(){
var span = document.getElementById("inputnuevo");
var inputFirstName = document.createElement("input");
inputFirstName.setAttribute("id", "firstName");
inputFirstName.setAttribute("placeholder", "First Name");
}
var boton = document.getElementById("become-driver");
boton.onclick = function(){
function phone(){
var phone = document.getElementById("phone").value;
if( !(/^\d{9}$/.test(phone)) ) { //Validación para ingresar 9 numeros
alert("Please enter a valid phone number");
}
}
phone();
}
|
/**
*
*/
jQuery(function($){
var jcrop_api;
$('#target').Jcrop({
onChange: showCoords,
onSelect: showCoords,
aspectRatio:4/3
},function(){
jcrop_api = this;
});
$('#coords').on('change','input',function(e){
var x1 = $('#x1').val(),
x2 = $('#x2').val(),
y1 = $('#y1').val(),
y2 = $('#y2').val();
jcrop_api.setSelect([x1,y1,x2,y2]);
});
});
// Simple event handler, called from onChange and onSelect
// event handlers, as per the Jcrop invocation above
function showCoords(c)
{
$('#x1').val(c.x);
$('#y1').val(c.y);
$('#x2').val(c.x2);
$('#y2').val(c.y2);
$('#w').val(c.w);
$('#h').val(c.h);
};
function submit(pos){
if($("#h").val()){//输入高度不为空则都不为空
$(pos).parent().submit();
}
else{//未选择图片
$("#error").html("未选择裁剪区域");
}
} |
const assert = require('assert');
const alunos = ['Pedro Henrique', 'Miguel', 'Maria Clara'];
const notas = [[9, 8, 10, 7, 5], [10, 9, 9, 10, 8], [10, 7, 10, 8, 9]];
function studentAverage() {
const avarage = notas.map((notes , index )=> ({ //Ultilizei a HOF map para criar outro array com os objetos
name:alunos[index],//Como no exercício fala que a posição das notas é a mesma do aluno !
average: notes.reduce((notesSum , note )=>notesSum + note) / notes.length //Utilizei a HOF reduce para somar todas as notas e dividir pelo quantidade de notas para achar o média
}));
return avarage;
}
const expected = [
{ name: 'Pedro Henrique', average: 7.8 },
{ name: 'Miguel', average: 9.2 },
{ name: 'Maria Clara', average: 8.8 },
];
assert.deepEqual(studentAverage(), expected); |
const BITBOXSDK = require('bitbox-sdk');
const jwt = require('jsonwebtoken');
const DEFAULT_REST_API = "https://rest.bitcoin.com/v2/";
class BlockOTP {
constructor(config) {
if (config && config.restURL && config.restURL !== "") {
this.restURL = config.restURL;
} else if (process.env.RESTURL && process.env.RESTURL !== "") {
this.restURL = process.env.RESTURL;
} else {
this.restURL = DEFAULT_REST_API;
}
this.BITBOX = new BITBOXSDK.BITBOX({ restURL: this.restURL });
}
async getBlockchainData() {
let blockCount = await this.BITBOX.Blockchain.getBlockCount();
let blockHash = await this.BITBOX.Blockchain.getBestBlockHash();
return {
bkc: blockCount,
mkr: blockHash
};
}
async signPayloadWithKey(privKeyWIF, payload = null) {
if (payload === null) {
payload = await this.getBlockchainData();
}
return await {
payload: payload,
signedMsg: this.BITBOX.BitcoinCash.signMessageWithPrivKey(
privKeyWIF,
JSON.stringify(payload)
)
};
}
verifySignedPayload(address, signedMsg, payload) {
return this.BITBOX.BitcoinCash.verifyMessage(
address,
signedMsg,
JSON.stringify(payload)
);
}
async createJWT(address, signedMsg) {
let payload = await this.getBlockchainData();
let verifyMessage = await this.verifySignedPayload(address, signedMsg, payload);
if (verifyMessage === true) {
return jwt.sign(payload, signedMsg, {
algorithm: 'HS256',
noTimestamp: true
});
} else {
throw "Did not validate private-key signed message";
}
}
async verifyJWT(address, signedMsg, token) {
let payload = jwt.decode(token);
let verifyMessage = this.verifySignedPayload(address, signedMsg, payload);
if (verifyMessage === true) {
try {
let cert = jwt.verify(token, signedMsg, {ignoreExpiration: true});
return {
payload: cert,
address: address
};
} catch (err) {
throw "Did not validate JWT payload data";
}
} else {
throw "Did not validate private-key signed message";
}
}
}
module.exports = BlockOTP;
|
'use strict';
angular.module('homebrewApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main',
controller: 'MainCtrl'
})
.when('/blog', {
templateUrl: 'partials/blog',
controller: 'BlogCtrl'
})
.when('/brew-fitness', {
templateUrl: 'partials/brew-fitness',
controller: 'Brew-FitnessCtrl'
})
.when('/about', {
templateUrl: 'partials/about',
controller: 'AboutCtrl'
})
.when('/contact', {
templateUrl: 'partials/contact',
controller: 'partials/controller'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}); |
import Vue from "vue";
import moment from "moment"; // 时间过滤器
// 用法 {{时间 | dateFmt("YYYY-MM-DD HH:mm:ss") }}
Vue.filter("dateFmt", (input, formatStr = 'YY-MM-DD HH:mm:ss') => {
// let input = input * 1000
if (!input) {
return (input = "暂无时间");
}
return moment(input * 1000).format(formatStr);
});
//字符串截取
Vue.filter('m_substr', function (value, start = 0, len = 6, affix = false) {
if (!value) return '';
if (value.length > len) {
if (affix == false) {
return value.slice(start, len);
} else {
return value.slice(start, len) + '...';
}
}
return value;
})
// 过滤时间秒 分钟 小数 天数
Vue.filter("filterDataFormat", timeStamp => {
// 时间戳
let differ = (new Date().getTime() / 1000 - timeStamp);
// let differ = new Date().getTime() / 1000 - (Date.parse(new Date(timeStamp)) / 1000)
if (differ < 60) {
return Math.floor(differ) + "秒前";
}
if (differ < 3600) {
return Math.floor(differ / 60) + "分钟前";
}
if (differ < 86400) {
return Math.floor(differ / 3600) + "小时前";
}
if (differ < 2592000) {
return Math.floor(differ / 86400) + "天前";
}
return "30天前";
});
// 过滤离预定时间剩余多少秒
Vue.filter("countDownTime", time => {
if (time < 1) {
return "00分00秒";
}
if (time <= 60) {
return time + "秒";
}
if (time <= 3600) {
return (Math.floor(time / 60) + "分" + (Math.ceil(time % 60) < 10 ? '0' + Math.ceil(time % 60) + '秒' : Math.ceil(time % 60) + '秒'));
}
if (time <= 7200) {
return (
Math.floor(time / 3600) +
"时" +
Math.floor((time % 3600) / 60) +
"分" +
Math.ceil((time % 60) / 1000) +
"秒"
);
}
});
|
function EventsService($http, $state) {
this.getEvent = function(params) {
return $http.get('api/v1/events/' + params.eventId + '.json')
.then(handleSuccess)
.catch(handleError)
};
this.newEvent = function(cause, eventData) {
return $http.post('api/v1/causes/' + cause.id + '/events.json', eventData)
.then(showEvent)
};
function showEvent(cause) {
var params = {};
params.causeId = cause.data.data.relationships.cause.data.id;
params.eventId = cause.data.data.id;
$state.go('causes.event', { causeId: params.causeId, eventId: params.eventId });
};
function handleSuccess(response) {
console.log(response);
return response.data;
};
function handleError(error) {
console.log(error);
};
};
EventsService.$inject = ['$http', '$state'];
angular
.module('uponnyc')
.service('EventsService', EventsService)
|
// Created by Vince Chang
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from '@reach/router';
import pf from 'petfinder-client';
import { Provider } from './SearchContext';
import Results from './Results';
import Details from './Details';
import SearchParams from './SearchParams';
const petfinder = pf({});
class App extends React.Component {
/* =========================================================================
* Function Name: constructor
* Task: This function will bind the state
* Every time you call .bind will create a new function, so that's why do it
* in the constructor, but good thing it will only happen once
* In newer JS, you no longer need to write the constructor if you write
* functions using the arrow function, it will automatically do the binding
* refer to transform-class-properties
========================================================================= */
constructor(props) {
super(props);
this.state = {
location: 'San Francisco, CA',
animal: '',
breed: '',
breeds: [],
handleAnimalChange: this.handleAnimalChange.bind(this),
handleBreedChange: this.handleBreedChange.bind(this),
handleLocationChange: this.handleLocationChange.bind(this),
getBreeds: this.getBreeds
};
}
/* =========================================================================
* Function Name: handleLocationChange
* Task: This function will update the location based off what the user types
* into the location field on the homepage
======================================================================== */
handleLocationChange(event) {
this.setState({
location: event.target.value
});
}
/* =========================================================================
* Function Name: handleAnimalChange
* Task: This function will set the state the the animal based off what the
* user selects from the list of selection
======================================================================== */
handleAnimalChange(event) {
this.setState(
{
animal: event.target.value,
breed: '' // Resets breed to empty string
},
this.getBreeds // then automatically called getBreeds once animal changed
);
}
/* =========================================================================
* Function Name: handleBreedChange
* Task: This function will update the state with breed selected from the list
* of selections
======================================================================== */
handleBreedChange(event) {
this.setState({
breed: event.target.value
});
}
/* =========================================================================
* Function Name: getBreeds
* Task: This function will retrieve the breeds for different animals by using
* the petfinder API. This will populate the breeds[] in state.
======================================================================== */
getBreeds() {
// CASE: Animal has been selected, so get breeds for this animal
if (this.state.animal) {
petfinder.breed.list({ animal: this.state.animal }).then(data => {
if (
data.petfinder &&
data.petfinder.breeds &&
Array.isArray(data.petfinder.breeds.breed)
) {
this.setState({
breeds: data.petfinder.breeds.breed
});
} else {
this.setState({ breeds: [] });
}
});
} else {
// CASE: Animal hasn't yet been selected, just have breeds as empty
this.setState({ breeds: [] });
}
}
/* =========================================================================
* Function Name: render
* Task: This function will render the show's markup for a pet. It handles
* logic for photos because the API will return different sizes of photos.
* The output will be the photo of the pet with its breed and location.
*
* Since Provider is wrapping everything, wherever I instantiate a Context obj
* I will have the state that Provider is making accessible which is App's
* state.
*
* Provider defines where I am going to get the resources from, in this case it
* is this file App.js 's state. Note you can have multiple Providers
========================================================================= */
render() {
return (
<div>
<header>
<div className="logo">
<Link to="/">Pet Adoption !</Link>
</div>
<Link to="/search-params">
<span aria-label="search" role="img">
🔍
</span>
</Link>
</header>
<Provider value={this.state}>
<Router>
<Results path="/" />
<Details path="/details/:id" />
<SearchParams path="/search-params" />
</Router>
</Provider>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
|
// Export some events
|
(function () {
angular
.module(APP.NAME).factory("contactService", ContactService);
ContactService.$inject = ["$log", "$http"];
function ContactService($log, $http) {
var vm = this;
var svc = {};
svc.addContact = _addContact;
svc.getContact = _getContact;
svc.deleteContact = _deleteContact;
return svc;
function _addContact(data, onSuccess, onError) {
var settings = {
url: '/api/messages',
method: 'POST',
headers: {},
cache: false,
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify(data),
withCredentials: true,
};
return $http(settings)
.then(onSuccess, onError)
}
function _getContact(onSuccess, onError) {
var settings = {
url: 'api/messages',
method: 'GET',
headers: {},
cache: false,
contentType: 'application/json; charset=UTF-8',
withCredentials: true,
};
return $http(settings)
.then(onSuccess, onError)
}
function _deleteContact(id, onSuccess, onError) {
var settings = {
url: 'api/messages/' + id,
method: 'DELETE',
headers: {},
cache: false,
contentType: 'application/json; charset=UTF-8',
withCredentials: true,
};
return $http(settings)
.then(function (response) {
onSuccess(response, id);
}, onError)
}
}
})();
|
//META{"name":"p_quoter"}*//
/*@cc_on
@if (@_jscript)
// Offer to self-install for clueless users that try to run this directly.
var shell = WScript.CreateObject("WScript.Shell");
var fs = new ActiveXObject("Scripting.FileSystemObject");
var pathPlugins = shell.ExpandEnvironmentStrings("%APPDATA%\\BetterDiscord\\plugins");
var pathSelf = WScript.ScriptFullName;
// Put the user at ease by addressing them in the first person
shell.Popup("It looks like you tried to run me directly. This is not desired behavior! It will work now, but likely will not work with other plugins. Even worse, with other untrusted plugins it may lead computer virus infection!", 0, "I'm a plugin for BetterDiscord", 0x30);
if (fs.GetParentFolderName(pathSelf) === fs.GetAbsolutePathName(pathPlugins)) {
shell.Popup("I'm in the correct folder already.\nJust reload Discord with Ctrl+R.", 0, "I'm already installed", 0x40);
} else if (!fs.FolderExists(pathPlugins)) {
shell.Popup("I can't find the BetterDiscord plugins folder.\nAre you sure it's even installed?", 0, "Can't install myself", 0x10);
} else if (shell.Popup("Should I copy myself to BetterDiscord's plugins folder for you?", 0, "Do you need some help?", 0x34) === 6) {
fs.CopyFile(pathSelf, fs.BuildPath(pathPlugins, fs.GetFileName(pathSelf)), true);
// Show the user where to put plugins in the future
shell.Exec("explorer " + pathPlugins);
shell.Popup("I'm installed!\nJust reload Discord with Ctrl+R.", 0, "Successfully installed", 0x40);
}
WScript.Quit();
@else @*/
var p_quoter =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(18);
/***/ }),
/* 1 */,
/* 2 */,
/* 3 */
/***/ (function(module, exports) {
/**
* BetterDiscord Plugin Base Class
* Copyright (c) 2015-present Jiiks - https://jiiks.net
* All rights reserved.
* https://github.com/Jiiks/BetterDiscordApp - https://betterdiscord.net
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
class Plugin {
constructor(props) {
this.props = props;
}
get authors() {
return this.props.authors;
}
get version() {
return this.props.version;
}
get name() {
return this.props.name;
}
get description() {
return this.props.description;
}
get reloadable() {
return this.props.reloadable;
}
get permissions() {
return this.props.permissions;
}
get storage() {
return this.internal.storage;
}
get settings() {
return this.storage.settings;
}
saveSettings() {
this.storage.save();
this.onSave(this.settings);
}
getSetting(id) {
let setting = this.storage.settings.find(setting => { return setting.id === id; });
if (setting && setting.value !== undefined) return setting.value;
}
get enabled() {
return this.getSetting("enabled");
}
}
module.exports = Plugin;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
/**
* BetterDiscord Plugin Api
* Copyright (c) 2015-present Jiiks - https://jiiks.net
* All rights reserved.
* https://github.com/Jiiks/BetterDiscordApp - https://betterdiscord.net
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const Logger = __webpack_require__(5);
const Api = __webpack_require__(6);
class PluginApi {
constructor(props) {
this.props = props;
}
log(message, level) {
Logger.log(this.props.name, message, level);
}
injectStyle(id, css) {
Api.injectStyle(id, css);
}
removeStyle(id) {
Api.removeStyle(id);
}
injectScript(id, script) {
Api.injectScript(id, script);
}
removeScript(id) {
Api.removeScript(id);
}
}
module.exports = PluginApi;
/***/ }),
/* 5 */
/***/ (function(module, exports) {
/**
* BetterDiscord Logger Module
* Copyright (c) 2015-present Jiiks - https://jiiks.net
* All rights reserved.
* https://github.com/Jiiks/BetterDiscordApp - https://betterdiscord.net
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
class Logger {
static log(moduleName, message, level = 'log') {
level = this.parseLevel(level);
console[level]('[%cBetter%cDiscord:%s] %s', 'color: #3E82E5', '', `${moduleName}${level === 'debug' ? '|DBG' : ''}`, message);
}
static logObject(moduleName, message, object, level) {
if (message) this.log(moduleName, message, level);
console.log(object);
}
static debug(moduleName, message, level, force) {
if (!force) { if (!window.BetterDiscord || !window.BetterDiscord.debug) return; }
this.log(moduleName, message, 'debug', true);
}
static debugObject(moduleName, message, object, level, force) {
if (!force) { if (!window.BetterDiscord || !window.BetterDiscord.debug) return; }
if (message) this.debug(moduleName, message, level, force);
console.debug(object);
}
static parseLevel(level) {
return {
'log': 'log',
'warn': 'warn',
'err': 'error',
'error': 'error',
'debug': 'debug',
'dbg': 'debug',
'info': 'info'
}[level];
}
}
module.exports = Logger;
/***/ }),
/* 6 */
/***/ (function(module, exports) {
module.exports = {};
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
/**
* BetterDiscord Plugin Storage
* Copyright (c) 2015-present Jiiks - https://jiiks.net
* All rights reserved.
* https://github.com/Jiiks/BetterDiscordApp - https://betterdiscord.net
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const Utils = __webpack_require__(6);
class PluginStorage {
constructor(path, defaults) {
this.path = `${path}/settings.json`;
this.defaultConfig = defaults;
this.load();
}
load() {
this.settings = JSON.parse(JSON.stringify(this.defaultConfig));
const loadSettings = Utils.tryParse(Utils.readFileSync(this.path));
if (loadSettings) {
Object.keys(loadSettings).map(key => {
this.setSetting(key, loadSettings[key]);
});
}
if (!this.getSetting('enabled')) this.setSetting('enabled', false);
}
save() {
const reduced = this.settings.reduce((result, item) => { result[item.id] = item.value; return result; }, {});
Utils.writeFileSync(this.path, JSON.stringify(reduced));
}
getSetting(id) {
const setting = this.settings.find(setting => setting.id === id);
if (!setting) return null;
return setting.value;
}
setSetting(id, value) {
const setting = this.settings.find(setting => setting.id === id);
if (!setting) {
this.settings.push({ id, value });
} else {
setting.value = value;
}
this.save();
}
setSettings(settings) {
this.settings = settings;
}
}
module.exports = PluginStorage;
/***/ }),
/* 8 */,
/* 9 */,
/* 10 */,
/* 11 */,
/* 12 */,
/* 13 */,
/* 14 */,
/* 15 */,
/* 16 */,
/* 17 */,
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
const v1transpile_version = 5;
module.exports = class {
constructor() {
const config = __webpack_require__(19);
if (!window.v1transpile || window.v1transpile.version < v1transpile_version) {
window.v1transpile = window.v1transpile || {};
window.v1transpile.version = v1transpile_version;
window.v1transpile.Plugin = window.v1transpile.Plugin || __webpack_require__(3);
window.v1transpile.PluginApi = window.v1transpile.PluginApi || __webpack_require__(4);
window.v1transpile.PluginStorage = window.v1transpile.PluginStorage || __webpack_require__(7);
window.v1transpile.Settings = window.v1transpile.Settings || {
/**
* Create and return a new top-level settings panel
* @author noodlebox
* @return {jQuery}
*/
topPanel() {
return $("<form>").addClass("form").css("width", "100%");
},
/**
* Create and return a container for control groups
* @author noodlebox
* @return {jQuery}
*/
controlGroups() {
return $("<div>").addClass("control-groups");
},
/**
* Create and return a flexible control group
* @author noodlebox
* @param {object} settings Settings object
* @param {Element|jQuery|string} settings.label an element or something JQuery-ish or, if string, use as plain text
* @return {jQuery}
*/
controlGroup(settings) {
const group = $("<div>").addClass("control-group");
if (typeof settings.label === "string") {
group.append($("<label>").text(settings.label));
} else if (settings.label !== undefined) {
group.append($("<label>").append(settings.label));
}
return group;
},
/**
* Create and return a group of checkboxes
* @author noodlebox
* @param {object} settings Settings object
* @param {object[]} settings.items an array of settings objects to be passed to checkbox()
* @param {function(state)} settings.callback called with the current state, when it changes state is an array of boolean values
* @return {jQuery}
*/
checkboxGroup(settings) {
settings = $.extend({
items: [],
callback: $.noop,
}, settings);
const state = settings.items.map(item => item.checked === true);
function onClick(i, itemState) {
if (settings.items[i].callback !== undefined) {
settings.items[i].callback(itemState);
}
state[i] = itemState;
settings.callback(state);
}
const group = $("<ul>").addClass("checkbox-group");
group.append(settings.items.map(function(item, i) {
return checkbox($.extend({}, item, {
callback: onClick.bind(undefined, i),
}));
}));
return group;
},
/**
* Create and return a checkbox
* @author noodlebox
* @param {object} settings Settings object
* @param {Element|jQuery|string} settings.label an element or something JQuery-ish or, if string, use as plain text
* @param {Element|jQuery|string} settings.help an element or something JQuery-ish or, if string, use as plain text
* @param {boolean} settings.checked
* @param {boolean} settings.disabled
* @param {function(state)} settings.callback called with the current state, when it changes state is a boolean
* @return {jQuery}
*/
checkbox(settings) {
settings = $.extend({
checked: false,
disabled: false,
callback: $.noop,
}, settings);
const input = $("<input>").attr("type", "checkbox")
.prop("checked", settings.checked)
.prop("disabled", settings.disabled);
const inner = $("<div>").addClass("checkbox-inner")
.append(input)
.append($("<span>"));
const outer = $("<div>").addClass("checkbox").append(inner);
if (settings.disabled) {
outer.addClass("disabled");
}
if (typeof settings.label === "string") {
outer.append($("<span>").text(settings.label));
} else if (settings.label !== undefined) {
outer.append($("<span>").append(settings.label));
}
outer.on("click.kawaiiSettings", function() {
if (!input.prop("disabled")) {
const checked = !input.prop("checked");
input.prop("checked", checked);
settings.callback(checked);
}
});
const item = $("<li>").append(outer);
let help;
if (typeof settings.help === "string") {
help = $("<div>").text(settings.help);
} else if (settings.help !== undefined) {
help = $("<div>").append(settings.help);
}
if (help !== undefined) {
help.appendTo(item)
.addClass("help-text")
.css("margin-top", "-3px")
.css("margin-left", "27px");
}
return item;
},
/**
* Create and return an input
* @author samogot
* @param {object} settings Settings object
* @param {Element|jQuery|string} settings.label an element or something JQuery-ish or, if string, use as plain text
* @param {Element|jQuery|string} settings.help an element or something JQuery-ish or, if string, use as plain text
* @param {boolean} settings.value
* @param {boolean} settings.disabled
* @param {function(state)} settings.callback called with the current state, when it changes. state is a string
* @return {jQuery}
*/
input(settings) {
settings = $.extend({
value: '',
disabled: false,
callback: $.noop,
}, settings);
const input = $("<input>").attr("type", "text")
.prop("value", settings.value)
.prop("disabled", settings.disabled);
const inner = $("<div>").addClass("input-inner")
.append(input)
.append($("<span>"));
const outer = $("<div>").addClass("input").append(inner);
if (settings.disabled) {
outer.addClass("disabled");
}
if (typeof settings.label === "string") {
outer.append($("<span>").text(settings.label));
} else if (settings.label !== undefined) {
outer.append($("<span>").append(settings.label));
}
input.on("change.kawaiiSettings", function() {
if (!input.prop("disabled")) {
const value = input.val();
settings.callback(value);
}
});
const item = $("<li>").append(outer);
let help;
if (typeof settings.help === "string") {
help = $("<div>").text(settings.help);
} else if (settings.help !== undefined) {
help = $("<div>").append(settings.help);
}
if (help !== undefined) {
help.appendTo(item)
.addClass("help-text")
.css("margin-top", "-3px")
.css("margin-left", "27px");
}
return item;
}
};
window.v1transpile.PluginApi.prototype.injectStyle = (id, css) => BdApi.injectCSS(id, css);
window.v1transpile.PluginApi.prototype.removeStyle = (id) => BdApi.clearCSS(id);
window.v1transpile.PluginStorage.prototype.load = function() {
this.settings = JSON.parse(JSON.stringify(this.defaultConfig));
this.path = this.path.replace('/settings.json', '');
if (!window.bdPluginStorage) {
return;
}
try {
const loadSettings = bdPluginStorage.get(this.path, "settings");
if (loadSettings) {
Object.keys(loadSettings).map(key => {
this.setSetting(key, loadSettings[key]);
});
}
} catch (err) {
console.warn(this.path, ":", "unable to load settings:", err);
}
};
window.v1transpile.PluginStorage.prototype.save = function() {
const reduced = this.settings.reduce((result, item) => {
result[item.id] = item.value;
return result;
}, {});
try {
bdPluginStorage.set(this.path, "settings", reduced);
} catch (err) {
console.warn(this.path, ":", "unable to save settings:", err);
}
};
window.v1transpile.Vendor = window.v1transpile.Vendor || {
get jQuery() {
return window.jQuery;
},
get $() {
return window.jQuery;
},
get React() {
return window.BDV2.react;
},
get ReactDOM() {
return window.BDV2.reactDom;
},
moment: {}
};
}
const storage = new window.v1transpile.PluginStorage(config.info.name.replace(/\s+/g, '_').toLowerCase(), config.defaultSettings);
const BD = {
Api: new window.v1transpile.PluginApi(config.info),
Storage: storage,
Events: {},
Renderer: {}
};
const plugin = __webpack_require__(20)(window.v1transpile.Plugin, BD, window.v1transpile.Vendor, true);
this.pluginInstance = new plugin(config.info);
this.pluginInstance.internal = {
storage,
path: ''
};
}
start() {
this.pluginInstance.onStart();
this.pluginInstance.storage.load();
}
stop() {
this.pluginInstance.onStop();
}
load() {
}
unload() {
}
getName() {
return this.pluginInstance.name
}
getDescription() {
return this.pluginInstance.description
}
getVersion() {
return this.pluginInstance.version
}
getAuthor() {
return this.pluginInstance.authors.join(', ')
}
getSettingsPanel() {
if (this.pluginInstance.storage.settings.length === 0)
return '';
const Settings = window.v1transpile.Settings;
const panel = Settings.topPanel();
const filterControls = Settings.controlGroups().appendTo(panel);
const Control = Settings.controlGroup({label: this.pluginInstance.name + " settings"})
.appendTo(filterControls);
const saveAndReload = () => {
this.pluginInstance.storage.save();
if (window.pluginCookie && window.pluginCookie[this.pluginInstance.name]) {
this.pluginInstance.onStop();
Promise.resolve().then(() => {
}).then(() => {
this.pluginInstance.onStart();
});
}
};
for (let item of this.pluginInstance.storage.settings) {
let input;
switch (item.type) {
case 'bool':
input = Settings.checkbox({
label: item.text,
help: item.description,
checked: item.value,
callback: state => {
this.pluginInstance.storage.setSetting(item.id, state);
saveAndReload();
},
});
break;
case 'text':
input = Settings.input({
label: item.text,
help: item.description,
value: item.value,
callback: state => {
this.pluginInstance.storage.setSetting(item.id, state);
saveAndReload();
},
});
break;
}
if (input)
Control.append(input)
}
return panel[0];
}
};
/***/ }),
/* 19 */
/***/ (function(module, exports) {
module.exports = {
"info": {
"name": "Quoter",
"authors": [
"Samogot"
],
"version": "3.4",
"description": "Add citation using embeds",
"repository": "https://github.com/samogot/betterdiscord-plugins.git",
"homepage": "https://github.com/samogot/betterdiscord-plugins/tree/master/v2/Quoter",
"reloadable": true
},
"defaultSettings": [
{
"id": "embeds",
"type": "bool",
"text": "Use embeds for quoting",
"description": "Use embeds if possible and fallback to markdown-formated quotes otherwise. Uncheck if you want to always use fallback mode",
"value": true
},
{
"id": "noEmbedsServers",
"type": "text",
"multiline": false,
"text": "Don't use embeds on this servers",
"description": "Some servers disallow self-botting. Despite this plugin isn't a bot, it's hard to approve it. So if on some server users not allowed to use embeds, you can add that server ID to this space separated black list. To get server id see this instructions: https://goo.gl/w77phg",
"value": ""
},
{
"id": "utc",
"type": "bool",
"text": "Use UTC TimeZone",
"description": "Use UTC TimeZone to display time in fallback mode",
"value": false
},
{
"id": "mention",
"type": "bool",
"text": "Mention cited users",
"description": "Automatically add mention of users, whose messages are cited",
"value": false
},
{
"id": "citeFull",
"type": "bool",
"text": "Cite full message group",
"description": "Clicking on quote icon cause citing full message group instead of one message. Use Alt+Click to quote single message.",
"value": true
}
],
"permissions": []
};
/***/ }),
/* 20 */
/***/ (function(module, exports) {
module.exports = (Plugin, BD, Vendor, v1) => {
const {Api, Storage} = BD;
let {$} = Vendor;
const minDIVersion = '1.3';
if (!window.DiscordInternals || !window.DiscordInternals.version ||
window.DiscordInternals.versionCompare(window.DiscordInternals.version, minDIVersion) < 0) {
const message = `Lib Discord Internals v${minDIVersion} or higher not found! Please install or upgrade that utility plugin. See install instructions here https://goo.gl/kQ7UMV`;
Api.log(message, 'warn');
return (class EmptyStubPlugin extends Plugin {
onStart() {
Api.log(message, 'warn');
alert(message);
return false;
}
onStop() {
return true;
}
});
}
const {monkeyPatch, WebpackModules, ReactComponents, getOwnerInstance, React, Renderer} = window.DiscordInternals;
const moment = WebpackModules.findByUniqueProperties(['parseZone']);
const Constants = WebpackModules.findByUniqueProperties(['Routes', 'ChannelTypes']);
const GuildsStore = WebpackModules.findByUniqueProperties(['getGuild']);
const UsersStore = WebpackModules.findByUniqueProperties(['getUser', 'getCurrentUser']);
const MembersStore = WebpackModules.findByUniqueProperties(['getNick']);
const UserSettingsStore = WebpackModules.findByUniqueProperties(['developerMode', 'locale']);
const MessageActions = WebpackModules.findByUniqueProperties(['jumpToMessage', '_sendMessage']);
const MessageQueue = WebpackModules.findByUniqueProperties(['enqueue']);
const MessageParser = WebpackModules.findByUniqueProperties(['createMessage', 'parse', 'unparse']);
const HistoryUtils = WebpackModules.findByUniqueProperties(['transitionTo', 'replaceWith', 'getHistory']);
const PermissionUtils = WebpackModules.findByUniqueProperties(['getChannelPermissions', 'can']);
const ModalsStack = WebpackModules.findByUniqueProperties(['push', 'update', 'pop', 'popWithKey']);
const ContextMenuItemsGroup = WebpackModules.find(m => typeof m === "function" && m.length === 1 && m.toString().search(/className\s*:\s*["']item-group["']/) !== -1);
ContextMenuItemsGroup.displayName = 'ContextMenuItemsGroup';
const ContextMenuItem = WebpackModules.find(m => typeof m === "function" && m.length === 1 && m.toString().search(/\.label\b.*\.hint\b.*\.action\b/) !== -1);
ContextMenuItem.displayName = 'ContextMenuItem';
const ExternalLink = WebpackModules.find(m => typeof m === "function" && m.length === 1 && m.prototype && m.prototype.onClick && m.prototype.onClick.toString().search(/\.trusted\b/) !== -1);
ExternalLink.displayName = 'ExternalLink';
const ConfirmModal = WebpackModules.find(m => typeof m === "function" && m.length === 1 && m.prototype && m.prototype.handleCancel && m.prototype.handleSubmit && m.prototype.handleMinorConfirm);
ConfirmModal.displayName = 'ConfirmModal';
const BASE_JUMP_URL = 'https://github.com/samogot/betterdiscord-plugins/blob/master/v2/Quoter/link-stub.md';
class QuoterPlugin extends Plugin {
// Life cycle
constructor(props) {
super(props);
this.cancelPatches = [];
this.quotes = [];
this.copyKeyPressed = false;
this.onCopyKeyPressed = this.onCopyKeyPressed.bind(this);
this.onCopy = this.onCopy.bind(this);
}
onStart() {
if (v1) {
$ = Vendor.$;
}
Api.injectStyle(QuoterPlugin.styleId, QuoterPlugin.style);
$(document).on("keydown.quoter", this.onCopyKeyPressed);
$(document).on("copy.quoter", this.onCopy);
// Embeds engine
this.patchSendMessageWithEmbed();
this.patchRetrySendMessageFromOptionPopout();
this.patchRetrySendMessageFromContextMenu();
// Main extension point
this.patchSendMessageForSplitAndPassEmbeds();
// UI
this.patchJumpLinkClick();
this.patchEmbedDate();
this.patchMessageContextMenuRender();
this.patchMessageRender();
return true;
}
onStop() {
Api.removeStyle(QuoterPlugin.styleId);
$(document).off("keydown.quoter", this.onCopyKeyPressed);
$(document).off("copy.quoter", this.onCopy);
this.cancelAllPatches();
return true;
}
cancelAllPatches() {
for (let cancel of this.cancelPatches) {
cancel();
}
}
// Helpers
static getCurrentChannel() {
return getOwnerInstance($('.chat')[0], {include: ["Channel"]}).state.channel;
}
static getIdsFromLink(href) {
const regex = new RegExp('^' + BASE_JUMP_URL + '\\?guild_id=([^&]+)&channel_id=([^&]+)&message_id=([^&]+)(?:&author_id=([^&]+))?$');
const match = regex.exec(href);
if (!match) return null;
return {
guild_id: match[1],
channel_id: match[2],
message_id: match[3],
author_id: match[4],
};
}
// Embeds engine
patchSendMessageWithEmbed() {
const cancel = monkeyPatch(MessageActions, '_sendMessage', {
before: ({methodArguments: [channel, message]}) => {
if (message.embed && message.embed.quoter) {
monkeyPatch(MessageQueue, 'enqueue', {
once: true,
before: ({methodArguments: [action]}) => {
if (action.type === 'send') {
action.message.embed = message.embed;
}
}
});
monkeyPatch(MessageParser, 'createMessage', {
once: true,
after: ({returnValue}) => {
if (returnValue) {
returnValue.embeds.push(message.embed);
}
}
});
}
}
});
this.cancelPatches.push(cancel);
}
patchRetrySendMessageFromOptionPopout() {
ReactComponents.get('OptionPopout', OptionPopout => {
const cancel = monkeyPatch(OptionPopout.prototype, 'handleRetry', {
before: this.patchCallbackPassEmbedFromPropsToSendMessage
});
this.cancelPatches.push(cancel);
this.cancelPatches.push(Renderer.rebindMethods(OptionPopout, ['handleRetry']));
});
}
patchRetrySendMessageFromContextMenu() {
const MessageResendItem = WebpackModules.findByDisplayName('MessageResendItem');
moment.locale(UserSettingsStore.locale);
const cancel = monkeyPatch(MessageResendItem.prototype, 'handleResendMessage', {
before: this.patchCallbackPassEmbedFromPropsToSendMessage
});
this.cancelPatches.push(cancel);
this.cancelPatches.push(Renderer.rebindMethods(MessageResendItem, ['handleResendMessage']));
}
patchCallbackPassEmbedFromPropsToSendMessage({thisObject}) {
if (thisObject.props.message && thisObject.props.message.embeds) {
const embed = thisObject.props.message.embeds.find(embed => embed.quoter);
if (embed) {
monkeyPatch(MessageActions, '_sendMessage', {
once: true,
before: ({methodArguments: [channel, message]}) => {
message.embed = embed;
}
});
}
}
}
// Main extension point
patchSendMessageForSplitAndPassEmbeds() {
const cancel = monkeyPatch(MessageActions, 'sendMessage', {
instead: ({methodArguments: [channelId, message], originalMethod, thisObject}) => {
const sendMessageDirrect = originalMethod.bind(thisObject, channelId);
const currentChannel = QuoterPlugin.getCurrentChannel();
const serverIDs = this.getSetting('noEmbedsServers').split(/\D+/);
if (this.getSetting('embeds') && !serverIDs.includes(currentChannel.guild_id) && (currentChannel.isPrivate() || PermissionUtils.can(0x4800, {channelId}))) {
this.splitMessageAndPassEmbeds(message, sendMessageDirrect);
}
else {
const sendMessageFallback = QuoterPlugin.sendWithFallback.bind(null, sendMessageDirrect, channelId);
this.splitMessageAndPassEmbeds(message, sendMessageFallback);
}
}
});
this.cancelPatches.push(cancel);
}
// Send Logic
static sendWithFallback(sendMessage, channelId, message) {
if (message.embed) {
const timestamp = moment(message.embed.timestamp);
if (Storage.getSetting('utc')) timestamp.utc();
const author = Storage.getSetting('mention') ? `<@${message.embed.author.id}>` : message.embed.author.name;
message.content += `\n*${author} - ${timestamp.format('YYYY-MM-DD HH:mm Z')}${message.embed.footer.text ? ' | ' + message.embed.footer.text : ''}*`;
message.content += `\n${'```'}\n${MessageParser.unparse(message.embed.description, channelId).replace(/\n?(```((\w+)?\n)?)+/g, '\n').trim()}\n${'```'}`;
message.content = message.content.trim();
message.embed = null;
}
sendMessage(message);
}
splitMessageAndPassEmbeds(message, sendMessage) {
const regex = /([\S\s]*?)(::(?:re:)?quote(\d+)(?:-(\d+))?::)/g;
let match, lastIndex = 0;
const currChannel = QuoterPlugin.getCurrentChannel();
while (match = regex.exec(message.content)) {
lastIndex = match.index + match[0].length;
let text = match[1];
const embeds = [];
const from_i = +match[3];
const to_i = +match[4] || from_i;
if (to_i <= this.quotes.length) {
for (let i = from_i; i <= to_i; ++i) {
const quote = this.quotes[i - 1];
if (embeds.length > 0 && embeds[embeds.length - 1].author.id === quote.message.author.id
&& (!embeds[embeds.length - 1].image || !quote.message.attachments.some(att => att.width))) {
this.appendToEmbed(embeds[embeds.length - 1], quote);
}
else {
embeds.push(this.parseNewEmbed(quote, currChannel));
}
}
}
else {
text += match[2];
}
text = text.trim() || ' ';
if (embeds.length > 0) {
for (let embed of embeds) {
sendMessage(Object.assign({}, message, {content: text, embed}));
text = ' ';
}
}
else {
sendMessage(Object.assign({}, message, {content: text}));
}
}
if (lastIndex < message.content.length) {
sendMessage(Object.assign({}, message, {content: message.content.substr(lastIndex)}));
}
for (let quote of this.quotes) {
quote.message.quotedContent = undefined;
}
this.quotes = [];
}
appendToEmbed(embed, quote) {
if (!embed.description)
embed.description = quote.text.trim();
else
embed.description += '\n' + quote.text.trim();
for (let attachment of quote.message.attachments) {
if (attachment.width) {
embed.image = attachment;
}
else {
let emoji = '📁';
if (/(.apk|.appx|.pkg|.deb)$/.test(attachment.filename)) {
emoji = '📦';
}
if (/(.jpg|.png|.gif)$/.test(attachment.filename)) {
emoji = '🖼';
}
if (/(.zip|.rar|.tar.gz)$/.test(attachment.filename)) {
emoji = '📚';
}
if (/(.txt)$/.test(attachment.filename)) {
attachment.filename = '📄';
}
embed.fields.push({
name: `${this.L.attachment} #${embed.fields.length + 1}`,
value: `${emoji} [${attachment.filename}](${attachment.url})`
});
}
}
}
parseNewEmbed(quote, currChannel) {
const embed = {
author: {
id: quote.message.author.id,
name: quote.message.nick || quote.message.author.username,
icon_url: quote.message.author.avatar_url || new URL(quote.message.author.getAvatarURL(), location.href).href,
},
footer: {},
timestamp: quote.message.timestamp.toISOString(),
fields: [],
color: quote.message.colorString && Number(quote.message.colorString.replace('#', '0x')),
url: `${BASE_JUMP_URL}?guild_id=${quote.channel.guild_id || '@me'}&channel_id=${quote.channel.id}&message_id=${quote.message.id}&author_id=${quote.message.author.id}`,
quoter: true
};
if (currChannel.id !== quote.channel.id) {
if (quote.channel.guild_id && quote.channel.guild_id !== '@me') {
embed.footer.text = '#' + quote.channel.name;
if (currChannel.guild_id !== quote.channel.guild_id) {
embed.footer.text += ' | ' + GuildsStore.getGuild(quote.channel.guild_id).name
}
}
else if (quote.channel.footer_text) {
embed.footer.text = quote.channel.footer_text;
}
else {
embed.footer.text = quote.channel.recipients
.slice(0, 5)
.map(id => currChannel.guild_id && MembersStore.getNick(currChannel.guild_id, id) || UsersStore.getUser(id).username)
.concat(quote.channel.recipients.length > 5 ? '...' : [])
.join(', ');
if (quote.channel.name) {
embed.footer.text = `${quote.channel.name} (${embed.footer.text})`;
}
else if (quote.channel.recipients.length === 1) {
embed.footer.text = '@' + embed.footer.text;
}
}
}
this.appendToEmbed(embed, quote);
return embed;
}
// UI
patchEmbedDate() {
ReactComponents.get('Embed', Embed => {
const cancel = Renderer.patchRender(Embed, [
{
selector: {
className: 'embed-footer',
child: {
text: true,
nthChild: -1
}
},
method: 'replace',
content: thisObject => moment(thisObject.props.timestamp).locale(UserSettingsStore.locale).calendar()
}
]);
this.cancelPatches.push(cancel);
});
}
patchJumpLinkClick() {
const cancel = monkeyPatch(ExternalLink.prototype, 'onClick', {
instead: ({thisObject, callOriginalMethod, methodArguments: [e]}) => {
let ids;
if (thisObject.props.href && (ids = QuoterPlugin.getIdsFromLink(thisObject.props.href))) {
HistoryUtils.transitionTo(Constants.Routes.MESSAGE(ids.guild_id, ids.channel_id, ids.message_id));
e.preventDefault();
}
else callOriginalMethod();
}
});
this.cancelPatches.push(cancel);
this.cancelPatches.push(Renderer.rebindMethods(ExternalLink, ['onClick']));
}
patchMessageRender() {
ReactComponents.get('Message', Message => {
const Tooltip = WebpackModules.findByDisplayName('Tooltip');
const cancel = Renderer.patchRender(Message, [
{
selector: {
className: 'markup',
},
method: 'before',
content: thisObject => React.createElement(Tooltip, {text: this.L.quoteTooltip}, React.createElement("div", {
className: "btn-quote",
onClick: this.onQuoteMessageClick.bind(this, thisObject.props.channel, thisObject.props.message),
onMouseDown: e => {
e.preventDefault();
e.stopPropagation();
}
}))
}
]);
this.cancelPatches.push(cancel);
});
}
patchMessageContextMenuRender() {
ReactComponents.get('MessageContextMenu', MessageContextMenu => {
const cancel = Renderer.patchRender(MessageContextMenu, [
{
selector: {
type: ContextMenuItemsGroup,
},
method: 'append',
content: thisObject => React.createElement(ContextMenuItem, {
label: this.L.quoteContextMenuItem,
hint: 'Ctrl+Shift+C',
action: this.onQuoteMessageClick.bind(this, thisObject.props.channel, thisObject.props.message)
})
}
]);
this.cancelPatches.push(cancel);
});
}
// Listeners
onCopyKeyPressed(e) {
if (e.which === 67 && e.ctrlKey && e.shiftKey) {
e.preventDefault();
const channel = QuoterPlugin.getCurrentChannel();
let text = this.quoteSelection(channel);
text += this.getMentions(channel);
if (text) {
this.copyKeyPressed = text;
document.execCommand('copy');
}
}
}
onCopy(e) {
if (!this.copyKeyPressed) {
return;
}
e.originalEvent.clipboardData.setData('Text', this.copyKeyPressed);
this.copyKeyPressed = false;
e.preventDefault();
}
onQuoteMessageClick(channel, message, e) {
e.preventDefault();
e.stopPropagation();
const {$channelTextarea, oldText} = this.tryClearQuotes();
const citeFull = this.getSetting('citeFull');
let newText;
if (QuoterPlugin.isMessageInSelection(message)) {
newText = this.quoteSelection(channel);
}
else if (e.ctrlKey || e.shiftKey || citeFull && !e.altKey) {
const group = QuoterPlugin.getMessageGroup(message);
if (e.shiftKey) {
newText = this.quoteMessageGroup(channel, group);
}
else {
newText = this.quoteMessageGroup(channel, group.slice(group.indexOf(message)));
}
}
else {
newText = this.quoteMessageGroup(channel, [message]);
}
newText += this.getMentions(channel, oldText);
if (newText) {
if (!$channelTextarea.prop('disabled')) {
const text = !oldText ? newText : /\n\s*$/.test(oldText) ? oldText + newText : oldText + '\n' + newText;
$channelTextarea.val(text).focus()[0].dispatchEvent(new Event('input', {bubbles: true}));
}
else {
const L = this.L;
this.copyKeyPressed = newText;
document.execCommand('copy');
ModalsStack.push(function(props) { // Can't use arrow function here
return React.createElement(ConfirmModal, Object.assign({
title: L.canNotQuoteHeader,
body: L.canNotQuoteBody,
// confirmText: Constants.Messages.OKAY
}, props));
})
}
}
}
// Quote Logic
tryClearQuotes() {
const $channelTextarea = $('.content textarea');
const oldText = $channelTextarea.val();
if (!/::(?:re:)?quote\d+(?:-\d+)?::/.test(oldText)) {
this.quotes = [];
}
return {$channelTextarea, oldText};
}
static isMessageInSelection(message) {
const selection = window.getSelection();
if (selection.isCollapsed) return false;
const range = selection.getRangeAt(0);
return !range.collapsed && $('.message').is((i, element) => range.intersectsNode(element)
&& getOwnerInstance(element, {include: ["Message"]}).props.message.id === message.id);
}
static getMessageGroup(message) {
const $messageGroups = $('.message-group').toArray();
for (let element of $messageGroups) {
const messages = getOwnerInstance(element, {include: ["MessageGroup"]}).props.messages;
if (messages.includes(message)) {
return messages;
}
}
return [message];
}
getMentions(channel, oldText) {
let mentions = '';
if (this.getSetting('embeds') && this.getSetting('mention')) {
for (let quote of this.quotes) {
const mention = MessageParser.unparse(`<@${quote.message.author.id}>`, channel.id);
if (!mentions.includes(mention) && (!oldText || !oldText.includes(mention))) {
mentions += mention + ' ';
}
}
}
return mentions
}
quoteMessageGroup(channel, messages) {
let count = 0;
for (let message of messages) {
if ((message.quotedContent || message.content).trim() || message.attachments.length > 0) {
++count;
this.quotes.push({text: message.quotedContent || message.content, message, channel});
}
}
if (count > 1) {
return `::quote${this.quotes.length - count + 1}-${this.quotes.length}::\n`;
}
else if (count === 1) {
return `::quote${this.quotes.length}::\n`;
}
return '';
}
quoteSelection(channel) {
const range = getSelection().getRangeAt(0);
const $clone = $(range.cloneContents());
const $markupsAndAttachments = $('.markup:not(.embed-field-value),.attachment-image,.embed-thumbnail-rich').filter((i, element) => range.intersectsNode(element));
const $markups = $markupsAndAttachments.filter('.markup');
if ($markups.length === 0 && $markupsAndAttachments.length === 0) {
return '';
}
const quotes = [];
const $clonedMarkups = $clone.children().find('.markup:not(.embed-field-value)');
if ($markups.length === 0) {
const quote = QuoterPlugin.getQuoteFromMarkupElement(channel, $markupsAndAttachments[0]);
if (quote) {
quote.message.quotedContent = quote.text = '';
quotes.push(quote);
}
}
else if ($markups.length === 1) {
const quote = QuoterPlugin.getQuoteFromMarkupElement(channel, $markups[0]);
if (quote) {
quote.message.quotedContent = quote.text = QuoterPlugin.parseSelection(channel, $clonedMarkups.add($('<div>').append($clone)).first());
quotes.push(quote);
}
}
else {
$markups.each((i, e) => {
const quote = QuoterPlugin.getQuoteFromMarkupElement(channel, e);
if (quote) {
quotes.push(quote);
}
});
quotes[0].message.quotedContent = quotes[0].text = QuoterPlugin.parseSelection(channel, $clonedMarkups.first());
quotes[quotes.length - 1].message.quotedContent = quotes[quotes.length - 1].text = QuoterPlugin.parseSelection(channel, $clonedMarkups.last());
}
let string = '';
const group = [];
const processGroup = () => {
if (group[0].re) {
this.quotes.push(group[0]);
string += `::re:quote${this.quotes.length}::\n`;
} else {
string += this.quoteMessageGroup(channel, group.map(g => g.message));
}
};
for (let quote of quotes) {
if (quote.text.trim() || quote.message.attachments.length > 0) {
if (group.length === 0 || !group[0].re && !quote.re && $(quote.markup).closest('.message-group').is($(group[0].markup).closest('.message-group'))) {
group.push(quote);
}
else {
processGroup();
group.length = 0;
group.push(quote);
}
}
}
if (group.length > 0) {
processGroup();
}
return string;
}
static parseSelection(channel, $markup) {
$markup.find('a').each((i, e) => {
const $e = $(e);
$(e).html(`[${$e.text()}](${$e.attr('href')})`);
});
$markup.find('pre').each((i, e) => {
const $e = $(e);
$e.html(`${$e.find('code').attr('class').split(' ')[1] || ''}\n${$e.find('code').text()}`);
});
$markup.find('.emotewrapper').each((i, e) => {
const $e = $(e);
$e.html($e.find('img').attr('alt'));
});
$markup.find('.emoji').each((i, e) => {
const $e = $(e);
if ($e.attr('src').includes('assets/')) {
$e.html($e.attr('alt'));
}
if ($e.attr('src').includes('emojis/')) {
$e.html(`<${$e.attr('alt')}${$e.attr('src').split('/').pop().replace('.png', '')}>`);
}
});
$markup.find('.edited,.timestamp,.username-wrapper').detach();
$markup.html($markup.html().replace(/<\/?pre>/g, "```"));
$markup.html($markup.html().replace(/<\/?code( class="inline")?>/g, "`"));
$markup.html($markup.html().replace(/<\/?strong>/g, "**"));
$markup.html($markup.html().replace(/<\/?em>/g, "*"));
$markup.html($markup.html().replace(/<\/?s>/g, "~~"));
$markup.html($markup.html().replace(/<\/?u>/g, "__"));
return MessageParser.parse(channel, $markup.text()).content
}
static getQuoteFromMarkupElement(channel, markup) {
if ($(markup).closest('.embed').length > 0) {
const $embed = $(markup).closest('.embed-rich');
const $embedAuthorName = $embed.find('.embed-author-name');
if ($embed.length > 0 && $embedAuthorName.attr('href').indexOf(BASE_JUMP_URL) === 0) {
const ids = QuoterPlugin.getIdsFromLink($embedAuthorName.attr('href'));
const embed = getOwnerInstance($embed[0], {include: ["Embed"]}).props;
const attachments = $embed.find('.embed-field-value a').map((i, e) => ({
url: $(e).attr('href'),
filename: $(e).text()
}));
if (embed.image) attachments.push(embed.image);
return {
re: true,
message: {
id: ids.message_id,
author: {
id: ids.author_id,
username: '> ' + embed.author.name,
avatar_url: embed.author.icon_url
},
timestamp: moment(embed.timestamp),
colorString: embed.color && '#' + embed.color.toString(16),
attachments: attachments,
content: embed.description,
},
channel: {
guild_id: ids.guild_id,
id: ids.channel_id,
footer_text: embed.footer && embed.footer.text,
name: embed.footer && embed.footer.text ? embed.footer.text.substr(1).split(' | ')[0] : channel.name
},
text: embed.description,
markup
}
}
}
else {
const props = getOwnerInstance(markup, {include: ["Message"]}).props;
return {
message: props.message,
channel: props.channel,
text: props.message.content,
markup
}
}
}
// Resources
static get style() {
// language=CSS
return `
.message-group .btn-quote {
opacity: 0;
-webkit-transition: opacity .2s ease;
transition: opacity .2s ease;
float: right;
width: 16px;
height: 16px;
background-size: 16px 16px;
cursor: pointer;
user-select: none;
background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 33 25"><path fill="#99AAB5" d="M18 6.5c0-2 .7-3.5 2-4.7C21.3.6 23 0 25 0c2.5 0 4.4.8 6 2.4C32.2 4 33 6 33 8.8s-.4 5-1.3 7c-.8 1.8-1.8 3.4-3 4.7-1.2 1.2-2.5 2.2-3.8 3L21.4 25l-3.3-5.5c1.4-.6 2.5-1.4 3.5-2.6 1-1.4 1.5-2.7 1.6-4-1.3 0-2.6-.6-3.7-1.8-1-1.2-1.7-2.8-1.7-4.8zM.4 6.5c0-2 .6-3.5 2-4.7C3.6.6 5.4 0 7.4 0c2.3 0 4.3.8 5.7 2.4C14.7 4 15.5 6 15.5 8.8s-.5 5-1.3 7c-.7 1.8-1.7 3.4-3 4.7-1 1.2-2.3 2.2-3.6 3C6 24 5 24.5 4 25L.6 19.5C2 19 3.2 18 4 17c1-1.3 1.6-2.6 1.8-4-1.4 0-2.6-.5-3.8-1.7C1 10 .4 8.5.4 6.5z"/></svg>') 50% no-repeat;
margin-right: 4px
}
.message-group .btn-quote:hover {
opacity: 1 !important
}
.theme-dark .btn-quote {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 33 25"><path fill="#FFF" d="M18 6.5c0-2 .7-3.5 2-4.7C21.3.6 23 0 25 0c2.5 0 4.4.8 6 2.4C32.2 4 33 6 33 8.8s-.4 5-1.3 7c-.8 1.8-1.8 3.4-3 4.7-1.2 1.2-2.5 2.2-3.8 3L21.4 25l-3.3-5.5c1.4-.6 2.5-1.4 3.5-2.6 1-1.4 1.5-2.7 1.6-4-1.3 0-2.6-.6-3.7-1.8-1-1.2-1.7-2.8-1.7-4.8zM.4 6.5c0-2 .6-3.5 2-4.7C3.6.6 5.4 0 7.4 0c2.3 0 4.3.8 5.7 2.4C14.7 4 15.5 6 15.5 8.8s-.5 5-1.3 7c-.7 1.8-1.7 3.4-3 4.7-1 1.2-2.3 2.2-3.6 3C6 24 5 24.5 4 25L.6 19.5C2 19 3.2 18 4 17c1-1.3 1.6-2.6 1.8-4-1.4 0-2.6-.5-3.8-1.7C1 10 .4 8.5.4 6.5z"/></svg>')
}
.message-group .comment > div:hover .btn-quote, .message-group .system-message > div:hover .btn-quote {
opacity: .4
}
`;
}
static get styleId() {
return "Quoter-plugin-style";
}
get locales() {
return {
'pt-BR': {
quoteContextMenuItem: "Citar",
quoteTooltip: "Citar",
attachment: "Anexo",
},
'ru': {
quoteContextMenuItem: "Цитировать",
quoteTooltip: "Цитировать",
attachment: "Вложение",
canNotQuoteHeader: "Вы не можете цитировать в этот канал",
canNotQuoteBody: "Код цитаты помещен в буфер обмена, Вы можете использовать его в другом канале. Также Вы можете воспользоватся комбинацией клавиш Ctrl+Shift+C, чтобы скопировать цытату выделеного текста.",
},
'uk': {
quoteContextMenuItem: "Цитувати",
quoteTooltip: "Цитувати",
attachment: "Додаток",
canNotQuoteHeader: "Ви не можете цитувати в цей канал",
canNotQuoteBody: "Код цитити поміщений до буферу обміну, Ви можете використати його в іншому каналі. Також ви можете скористатися комбінацію клавиш Ctrl+Shift+C, щоб скопіювати цитату виділеного тексту.",
},
'en-US': {
quoteContextMenuItem: "Quote",
quoteTooltip: "Quote",
attachment: "Attachment",
canNotQuoteHeader: "You can not quote into this channel",
canNotQuoteBody: "Quotation code placed into clipboard, you can use it in other channel. Also you can use Ctrl+Shift+C shortcut to copy quote of selected text.",
}
}
}
get L() {
return new Proxy(this.locales, {
get(locales, property) {
return locales[UserSettingsStore.locale] && locales[UserSettingsStore.locale][property] || locales['en-US'][property]
}
});
}
}
window.jQuery = $;
return QuoterPlugin;
};
/***/ })
/******/ ]);
/*@end @*/
|
import Ember from 'ember';
export default Ember.Component.extend({
actions: {
submitAnswer(params) {
this.sendAction('submitAnswer', params);
},
update(question, params) {
Object.keys(params).forEach(function(key) {
if(params[key] !==undefined && params[key] !=="") {
question.set(key,params[key]);
}
});
question.save();
this.transitionTo('index');
},
delete(question) {
if(confirm('You said you wanted help!')){
this.sendAction('destroyQuestion', question);
}
}
}
});
|
// https://www.hackerrank.com/challenges/picking-numbers/problem
// more explicit
const pickingNumbers = nums => {
const validNumSeqs = nums.map((num, numIdx) => {
const validNumSeq = [num];
nums.forEach((otherNum, otherNumIdx) => {
if (numIdx === otherNumIdx) return;
const isValidNum = validNumSeq.every(validNum => {
const difference = Math.abs(validNum - otherNum);
return difference <= 1;
});
if (isValidNum) validNumSeq.push(otherNum);
});
return validNumSeq;
});
const longest = validNumSeqs.reduce((longest, validNumSeq) => {
const { length } = validNumSeq;
const isLongest = length > longest;
return isLongest ? length : longest;
}, 0);
return longest;
};
// minimal code
const pickingNumbers = nums =>
nums
// returns array of `validNums` arrays
.map((num, numIdx) =>
nums.reduce(
(validNums, otherNum, otherNumIdx) => {
if (numIdx === otherNumIdx) return validNums; // skip same member in `nums`
const isValidNum = validNums.every(
validNum => Math.abs(validNum - otherNum) <= 1
);
return isValidNum ? validNums.concat(otherNum) : validNums;
},
[num] // start each validNums array with `num`
)
)
// returns the longest of all the `validNums` arrays
.reduce(
(longest, validNums) =>
validNums.length > longest ? validNums.length : longest,
0
);
|
function timeStamp() {
var response = document.getElementById("g-recaptcha-response");
if (response == null || response.value.trim() == "") {
var elems = JSON.parse(document.getElementsByName("captcha_settings")[0].value);
elems["ts"] = JSON.stringify(new Date().getTime());
document.getElementsByName("captcha_settings")[0].value = JSON.stringify(elems);
}
}
setInterval(timeStamp, 500);
function checkRecaptcha() {
document.getElementById("qwerty").addEventListener("submit", function(evt) {
var response = grecaptcha.getResponse();
if(response.length == 0) {
alert("Please, complete captcha validation!");
evt.preventDefault();
return false;
}
});
}
setTimeout(checkRecaptcha, 0);
function setMaxDate() {
var date = new Date();
var dayOfMonth = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
document.getElementById('date-field').max = (date.getFullYear() - 18) + '-' + (date.getMonth()+1) + '-' + dayOfMonth;
}
setTimeout(setMaxDate, 0);
function checkInputValidity(elem) {
var isValid = true;
if (elem.id === 'url') {
if (elem.value.trim()) {
if (!isValidUrl(elem.value)) {
elem.classList.add('has-error');
isValid = false;
} else {
elem.classList.remove('has-error');
}
} else {
elem.classList.remove('has-error');
}
} else if (!elem.value.trim()) {
elem.classList.add('has-error');
isValid = false;
} else if (elem.id === 'email' && !isValidEmail(elem.value)) {
elem.classList.add('has-error');
isValid = false;
} else {
elem.classList.remove('has-error');
}
return isValid;
}
function isValidEmail(email) {
return /^([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,6}$/.test(email);
}
/* function isValidDate(date) {
var a = String(new Date().getFullYear() - 18).slice(-1);
var regExpDate = new RegExp("^(0?[1-9]{1}|1[012])\\/(0?[1-9]|1[0-9]|2[0-9]|3[01])\\/(19\\d\\d|200[0-" + a + "]{1})$");
return regExpDate.test(date);
} */
function isValidUrl(url) {
return /^((https?|ftp)\:\/\/)?([a-z0-9]{1})((\.[a-z0-9-])|([a-z0-9-]))*\.([a-z]{2,6})(\/?)$/.test(url);
}
function isChecked(elem) {
var section = document.getElementById("shipping-address");
if (elem.checked) {
section.style.display = 'flex';
} else {
section.style.display = 'none';
}
}
function clickPage(button) {
var firstSection = document.getElementById("company-info");
var secondSection = document.getElementById("billing-address");
var thirdSection = document.getElementById("summary-info");
var isValid = true;
if (button.value === 'Next') {
if (firstSection.style.display === 'none') {
for (var elem of secondSection.querySelectorAll('.web-form-section-field.important')) {
validity = checkInputValidity(elem);
isValid = validity ? isValid : validity;
}
if (isValid) {
secondSection.style.display = 'none';
thirdSection.style.display = 'flex';
setSummaryinfo();
}
} else {
for (var elem of firstSection.querySelectorAll('.web-form-section-field.important')) {
validity = checkInputValidity(elem);
isValid = validity ? isValid : validity;
}
if (isValid) {
firstSection.style.display = 'none';
secondSection.style.display = 'flex';
}
}
} else {
if (secondSection.style.display === 'none') {
secondSection.style.display = 'flex';
thirdSection.style.display = 'none';
} else {
firstSection.style.display = 'flex';
secondSection.style.display = 'none';
}
}
}
function setSummaryinfo() {
var fields = document.querySelectorAll('.web-form-field');
var summarydivs = document.querySelectorAll('.web-form-section-summary-field');
for (var i = 0; i < fields.length; i++) {
var label = fields[i].children[0].innerHTML;
var input = fields[i].children[1];
var value;
if (input.children.length) {
value = input.children[0].value + ' ' + input.children[1].value;
} else {
value = input.value;
}
if (value) {
summarydivs[i].innerHTML = '<span>' + label + '</span><span>' + value + '</span>';
summarydivs[i].style.margin = '6px 0px 8px 6px';
}
}
}
function setDateValue(elem) {
document.getElementById('00N5g000000iJhE').value = new Date(elem.value).toLocaleDateString("en-US");
} |
import { createContext, useReducer } from "react";
import userReducer from "../reducers/userReducer";
export const UserContext = createContext();
const UserProvider = ({ children }) => {
const initial = {
isAuthenticated: false,
};
// an initial state to initialise the reducer. if a user object doesn't already exist, set it to initial.
const initialState = JSON.parse(
localStorage.getItem("user") || JSON.stringify(initial)
);
const [state, dispatch] = useReducer(userReducer, initialState);
return (
<UserContext.Provider value={{ state, dispatch }}>
{children}
</UserContext.Provider>
);
};
export default UserProvider |
import axios from 'axios'
let config;
const api = {
animals(params) { // many animals
const url = generateUrl(`https://api.petfinder.com/v2/animals`, params);
return get(url)
},
animal(params) { // single animal
if (!params.id) throw new Error("Enter an id!! Or use animals..");
return this.animals(params);
},
types(params, breedsOnly = false) { // many types
const url = generateUrl(`https://api.petfinder.com/v2/types`, params, breedsOnly);
return get(url)
},
breeds(params) { // types -> type -> breeds
if (!params.type) throw new Error("Enter a type!!");
return this.types(params, true);
},
orgs(params) { // many shelters
const url = generateUrl(`https://api.petfinder.com/v2/organizations`, params);
return get(url)
},
org(params) { // single shelter
if (!params.id) throw new Error("Enter an id!! Or use orgs..");
return this.orgs(params);
},
};
function generateUrl(base, params, breedsOnly = false) {
let url = base;
// id
if (params.id) {
return url += `/${params.id}`;
}
// breeds
if (breedsOnly) {
return url += `/${params.type}/breeds`
}
// add params
Object.getOwnPropertyNames(params).forEach( (param, i) => {
if (i === 0) {
url += '?';
} else {
url += '&';
}
// url += i ? '&' : '?'
url += `${param}=${params[param]}`
})
return url;
}
// wrapper around get - decides whether to retrive token
function get(url) {
if (config) return axios.get(url, {headers: config});
else return authToken() // promise -> then -> return promise
.then( ({data}) => {
config = { Authorization: `Bearer ${data.access_token}` };
return axios.get(url, {headers: config});
});
}
function authToken() {
// Returns a promise with bearer token. data.access_token
// Called once per session. Lasts one hour.
return axios.post("https://api.petfinder.com/v2/oauth2/token", {
grant_type: "client_credentials",
client_id: process.env.REACT_APP_API_KEY,
client_secret: process.env.REACT_APP_API_SECRET
});
}
export default api; |
var searchData=
[
['swap_75',['swap',['../flip_8cpp.html#a8ce0bb1f866912fff8f7e080edb7f8a5',1,'flip.cpp']]]
];
|
var Time = Class.extend({
init: function(options) {
if(!options) options = {};
this.time = new Date().getTime() * 0.001;
this.delta = 0;
this.factor = 1;
if('time' in options)
this.time = options.time;
},
set: function(time) {
if(!time) time = new Date().getTime() * 0.001;
this.add(time - this.time);
},
add: function(delta) {
delta *= this.factor;
this.time += delta;
this.delta = delta;
}
});
var TIME = new Module();
TIME.start = new Time();
TIME.bind('ready', function() {
TIME.ready = new Time();
TIME.time = new Time();
console.log('startup: ' + Math.round((TIME.ready.time - TIME.start.time) * 1000) + 'ms');
});
TIME.bind('tick', function() {
TIME.time.set();
return TIME.time.delta;
});
|
import React from 'react';
import SearchDataResultComponent from "./SearchDataResultComponent";
import {API,AUTH} from "../config";
class SearchFetchDataComponent extends React.Component {
constructor(props) {
super(props);
this.state = { isFetching : false, data: []};
//this.fetchData = this.fetchDataMocked;
this.fetchData = this.fetchRemoteData;
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
///comprobamos que se ha elejido correctamente el hotel
let error = [];
if( !this.props.hotel || this.props.hotel == -1)
error.push("Se debe elejir un hotel para poder realizar la búsqueda");
///comprobamos el número máximo de noches de hotel
if( !this.props.nights || this.props.nights < 1 || this.props.nights > 30)
error.push("El rango de estancia válido es entre 1-30 noches");
///comprobamos que la fecha sea correcta
if( !this.props.date )
error.push("Fecha introducida no válida");
///Si los datos a procesar no son correctos, mostramos los errores
if( error.length > 0 )
{
this.setState({ isFetching : false, data: []});
alert(error.join("\n"));
return;
}
///Si todo ha ido bien obtenemos los datos
this.setState({ isFetching : true, data: []});
this.fetchData(this.props.hotel, this.props.date, this.props.nights);
}
render = () => {
return (
<div className="search-content">
<button className="btn btn-primary mb-2" onClick={this.handleClick}>SEARCH</button>
<SearchDataResultComponent result = {this.state} />
</div>
);
};
fetchDataMocked = (hotel, date, nights) => {
this.setState({ isFetching : false,
data : [
{
"hotelId": 10030559,
"rateCode": "19867|120570b0|0",
"roomTypeId": 19867,
"roomName": "Habitación Twin",
"boardCode": "RO",
"boardName": "Sólo alojamiento",
"occupancy": {
"numAdults": 2,
"numChilds": 0,
"numBabies": 0
},
"occupationDescription": "2 personas",
"currency": "EUR",
"netPrice": "205.46",
"tax": "20.54",
"cityTax": "0.00",
"creditCardRequired": true,
"promoRate": false,
"cancellable": true,
"cancellationDeadLine": "2019/12/30 12:00:00 CET",
"payment": {
"paymentType": "DIRECT_PAYMENT_AT_CHECKOUT",
"paymentMethods": [
"CARD"
]
}
},
{
"hotelId": 10030559,
"rateCode": "19867|120570b0|1|41836",
"roomTypeId": 19867,
"roomName": "Habitación Twin",
"offerId": "41836",
"offerName": "20% DESCUENTO EN EL DESAYUNO BUFFET",
"boardCode": "BB",
"boardName": "Desayuno incluido",
"occupancy": {
"numAdults": 2,
"numChilds": 0,
"numBabies": 0
},
"occupationDescription": "2 personas",
"currency": "EUR",
"netPrice": "243.28",
"tax": "24.32",
"cityTax": "0.00",
"creditCardRequired": true,
"promoRate": false,
"cancellable": true,
"cancellationDeadLine": "2019/12/30 12:00:00 CET",
"payment": {
"paymentType": "DIRECT_PAYMENT_AT_CHECKOUT",
"paymentMethods": [
"CARD"
]
}
}
]
});
};
fetchRemoteData = (hotel, date, nights) => {
const parameters = `?hotelId=${hotel}&checkin=${date.toLocaleDateString('es-ES')}&nights=${nights}&lang=es`;
fetch(API + parameters, {
headers: new Headers({"Authorization": `Basic ${AUTH}`})
}).then(response => {
if (!response.ok) throw new Error(response.status);
return response.json();
}).then(data => {
if( data.hasOwnProperty('availableRates') && data.availableRates.hasOwnProperty(hotel) )
this.setState({isFetching : false, data : data.availableRates[hotel]});
else this.setState({isFetching : false, data : []});
}).catch(error => {
this.setState({isFetching : false, data : []});
alert(error);
});
};
}
export default SearchFetchDataComponent;
|
// news class, stores news information from the Guardian API
// converts headline, picture and article into HTML objects
function News(headline, fullStory, image){
this.headline = headline
this.fullStory = fullStory
this.image = image
}
News.prototype = {
displayHeadline: function() {
headlineDisplay = document.createElement('h2');
headlineDisplay.textContent = this.headline;
return headlineDisplay;
},
displayStory: function() {
storyDisplay = document.createElement('p');
storyDisplay.textContent = this.fullStory;
return storyDisplay;
},
displayImage: function() {
imageDisplay = document.createElement('img');
imageDisplay.setAttribute('src', this.image);
return imageDisplay
},
displayLink: function(index) {
linkDisplay = document.createElement('a');
linkDisplay.setAttribute('id', index)
linkDisplay.addEventListener('click', function() {
showArticle(index)
})
linkDisplay.textContent = this.headline;
return linkDisplay;
},
} |
//StateGameEnded
StateGameEnded.prototype = Object.create(State.prototype);
StateGameEnded.prototype.constructor = StateGameEnded;
StateGameEnded.animState = {
STARTING: 0,
IDLE: 1,
ENDING: 2,
ENDED: 3
}
function StateGameEnded(modx) {
this.init(modx);
this.anim_state = StateGameEnded.animState.STARTING;
this.animTime = -1;
this.animDuration = 2;
this.animEndDuration = 1;
this.endAnimTime = -1;
this.hudPlane = new Plane(this.modx.scene, 10);
this.hudAppearance = new CGFappearance(modx.scene);
this.hudAppearance.setAmbient(1, 1, 1, 1);
this.hudAppearance.setDiffuse(1, 1, 1, 1);
this.hudAppearance.setSpecular(0.3, 0.3, 0.3, 1);
this.hudAppearance.setShininess(120);
switch(this.modx.getEndReason()) {
case Modx.endGameReason.P1_WIN_SCORE:
this.hudAppearance.setTexture(new CGFtexture(modx.scene, "game/resources/player1wins_score.png"));
break;
case Modx.endGameReason.P2_WIN_SCORE:
this.hudAppearance.setTexture(new CGFtexture(modx.scene, "game/resources/player2wins_score.png"));
break;
case Modx.endGameReason.P1_WIN_TIME:
this.hudAppearance.setTexture(new CGFtexture(modx.scene, "game/resources/player1wins_timeout.png"));
break;
case Modx.endGameReason.P2_WIN_TIME:
this.hudAppearance.setTexture(new CGFtexture(modx.scene, "game/resources/player2wins_timeout.png"));
break;
case Modx.endGameReason.CONNECTION_ERR:
this.hudAppearance.setTexture(new CGFtexture(modx.scene, "game/resources/connect_error.png"));
break;
case Modx.endGameReason.ERROR:
this.hudAppearance.setTexture(new CGFtexture(modx.scene, "game/resources/error.png"));
break;
case Modx.endGameReason.TIE_GAME:
this.hudAppearance.setTexture(new CGFtexture(modx.scene, "game/resources/tie_game.png"));
break;
default:
this.hudAppearance.setTexture(new CGFtexture(modx.scene, "game/resources/player2wins_timeout.png"));
break;
}
this.modx.scene.lights[5].setPosition(2, 2, 1, 0);
this.modx.scene.lights[5].setAmbient(1, 1, 1, 1);
this.modx.scene.lights[5].setDiffuse(1, 1, 1, 1);
this.modx.scene.lights[5].setSpecular(1, 1, 1, 1);
this.modx.scene.lights[5].setVisible(false);
this.modx.scene.endGame();
this.modx.pieces[Modx.pieceTypes.HOVER_JOKER][0].setVisible(false);
this.modx.pieces[Modx.pieceTypes.HOVER_P1][0].setVisible(false);
this.modx.pieces[Modx.pieceTypes.HOVER_P2][0].setVisible(false);
}
StateGameEnded.prototype.displayHUD = function(t) {
if(this.anim_state != StateGameEnded.animState.ENDING) {
this.modx.scene.lights[5].enable();
this.modx.scene.lights[5].update();
if(this.animTime == -1 || t < this.animTime) {
this.animTime = t;
return;
}
this.modx.scene.pushMatrix();
this.hudAppearance.apply();
this.modx.scene.translate(1.3, -2.3, 0);
if(t > this.animTime + this.animDuration) {
this.anim_state = StateGameEnded.animState.IDLE;
this.modx.scene.scale(4, 2.5, 1);
} else {
anim_prop = (t-this.animTime)/this.animDuration;
this.modx.scene.scale(4*anim_prop, 2.5*anim_prop,1);
}
this.modx.scene.translate(0.5, 0.5, 0);
this.hudPlane.display();
this.modx.scene.popMatrix();
} else {
this.modx.scene.lights[5].enable();
this.modx.scene.lights[5].update();
if(this.animTime == -1 || t < this.animTime) {
this.animTime = t;
return;
}
this.modx.scene.pushMatrix();
this.hudAppearance.apply();
this.modx.scene.translate(1.3, -2.3, 0);
if(t > this.animTime + this.animEndDuration) {
this.anim_state = StateGameEnded.animState.ENDED;
this.modx.scene.scale(0, 0, 1);
this.modx.restart();
this.modx.start(this.newGame);
this.modx.scene.lights[5].disable();
this.modx.scene.lights[5].update();
} else {
anim_prop = (t-this.animTime)/this.animEndDuration;
this.modx.scene.scale(4*(1 - anim_prop), 2.5*(1 - anim_prop),1);
}
this.modx.scene.translate(0.5, 0.5, 0);
this.hudPlane.display();
this.modx.scene.popMatrix();
}
this.modx.displayHUDprimitives(t, false);
}
StateGameEnded.prototype.display = function(t) {
this.modx.displayBoard();
this.modx.displayXPieceBoxes();
this.modx.displayPieces(t);
}
StateGameEnded.prototype.isFinished = function(t) {
return this.anim_state == StateGameEnded.animState.ENDED;
}
StateGameEnded.prototype.terminate = function(newGame) {
this.anim_state = StateGameEnded.animState.ENDING;
this.animTime = -1;
this.newGame = newGame;
} |
/**
* @license
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('shaka.offline.DBEngine');
goog.require('goog.asserts');
goog.require('shaka.log');
goog.require('shaka.offline.IStorageEngine');
goog.require('shaka.util.Error');
goog.require('shaka.util.Functional');
goog.require('shaka.util.PublicPromise');
/**
* This manages all operations on an IndexedDB. This wraps all operations
* in Promises. All Promises will resolve once the transaction has completed.
* Depending on the browser, this may or may not be after the data is flushed
* to disk. https://goo.gl/zMOeJc
*
* @struct
* @constructor
* @implements {shaka.offline.IStorageEngine}
*/
shaka.offline.DBEngine = function() {
goog.asserts.assert(
shaka.offline.DBEngine.isSupported(),
'DBEngine should not be called when DBEngine is not supported');
/** @private {IDBDatabase} */
this.db_ = null;
/** @private {!Array.<shaka.offline.DBEngine.Operation>} */
this.operations_ = [];
/** @private {!Object.<string, number>} */
this.currentIdMap_ = {};
};
/**
* @typedef {{
* transaction: !IDBTransaction,
* promise: !shaka.util.PublicPromise
* }}
*
* @property {!IDBTransaction} transaction
* The transaction that this operation is using.
* @property {!shaka.util.PublicPromise} promise
* The promise associated with the operation.
*/
shaka.offline.DBEngine.Operation;
/** @private {string} */
shaka.offline.DBEngine.DB_NAME_ = 'shaka_offline_db';
/** @private @const {number} */
shaka.offline.DBEngine.DB_VERSION_ = 1;
/**
* Determines if the browsers supports IndexedDB.
* @return {boolean}
*/
shaka.offline.DBEngine.isSupported = function() {
return window.indexedDB != null;
};
/**
* Delete the database. There must be no open connections to the database.
* @return {!Promise}
*/
shaka.offline.DBEngine.deleteDatabase = function() {
if (!window.indexedDB)
return Promise.resolve();
var request =
window.indexedDB.deleteDatabase(shaka.offline.DBEngine.DB_NAME_);
var p = new shaka.util.PublicPromise();
request.onsuccess = function(event) {
goog.asserts.assert(event.newVersion == null, 'Unexpected database update');
p.resolve();
};
request.onerror = shaka.offline.DBEngine.onError_.bind(null, request, p);
return p;
};
/** @override */
shaka.offline.DBEngine.prototype.initialized = function() {
return this.db_ != null;
};
/** @override */
shaka.offline.DBEngine.prototype.init = function(storeMap, opt_retryCount) {
goog.asserts.assert(!this.db_, 'Already initialized');
return this.createConnection_(storeMap, opt_retryCount).then(function() {
// For each store, get the next ID and store in the map.
var stores = Object.keys(storeMap);
return Promise.all(stores.map(function(store) {
return this.getNextId_(store).then(function(id) {
this.currentIdMap_[store] = id;
}.bind(this));
}.bind(this)));
}.bind(this));
};
/** @override */
shaka.offline.DBEngine.prototype.destroy = function() {
return Promise.all(this.operations_.map(function(op) {
try {
// If the transaction is considered finished but has not called the
// callbacks yet, it will still be in the list and this call will fail.
// Simply ignore errors.
op.transaction.abort();
} catch (e) {}
var Functional = shaka.util.Functional;
return op.promise.catch(Functional.noop);
})).then(function() {
goog.asserts.assert(this.operations_.length == 0,
'All operations should have been closed');
if (this.db_) {
this.db_.close();
this.db_ = null;
}
}.bind(this));
};
/** @override */
shaka.offline.DBEngine.prototype.get = function(storeName, key) {
var request;
return this.createTransaction_(storeName, 'readonly', function(store) {
request = store.get(key);
}).then(function() { return request.result; });
};
/** @override */
shaka.offline.DBEngine.prototype.forEach = function(storeName, callback) {
return this.createTransaction_(storeName, 'readonly', function(store) {
var request = store.openCursor();
request.onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
callback(cursor.value);
cursor.continue();
}
};
});
};
/** @override */
shaka.offline.DBEngine.prototype.insert = function(storeName, value) {
return this.createTransaction_(storeName, 'readwrite', function(store) {
store.put(value);
});
};
/** @override */
shaka.offline.DBEngine.prototype.remove = function(storeName, key) {
return this.createTransaction_(storeName, 'readwrite', function(store) {
store.delete(key);
});
};
/** @override */
shaka.offline.DBEngine.prototype.removeKeys = function(storeName,
keys,
opt_onKeyRemoved) {
return this.createTransaction_(storeName, 'readwrite', function(store) {
for (var i = 0; i < keys.length; i++) {
var request = store.delete(keys[i]);
request.onsuccess = opt_onKeyRemoved || function(event) { };
}
});
};
/** @override */
shaka.offline.DBEngine.prototype.reserveId = function(storeName) {
goog.asserts.assert(storeName in this.currentIdMap_,
'Store name must be passed to init()');
return this.currentIdMap_[storeName]++;
};
/**
* Gets the ID to start at.
*
* @param {string} storeName
* @return {!Promise.<number>}
* @private
*/
shaka.offline.DBEngine.prototype.getNextId_ = function(storeName) {
var id = 0;
return this.createTransaction_(storeName, 'readonly', function(store) {
var request = store.openCursor(null, 'prev');
request.onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
id = cursor.key + 1;
}
};
}).then(function() { return id; });
};
/**
* Creates a new transaction for the given store name and calls |action| to
* modify the store. The transaction will resolve or reject the promise
* returned by this function.
*
* @param {string} storeName
* @param {string} type
* @param {!function(IDBObjectStore)} action
*
* @return {!Promise}
* @private
*/
shaka.offline.DBEngine.prototype.createTransaction_ = function(storeName,
type,
action) {
goog.asserts.assert(this.db_, 'Must not be destroyed');
goog.asserts.assert(type == 'readonly' || type == 'readwrite',
'Type must be "readonly" or "readwrite"');
var op = {
transaction: this.db_.transaction([storeName], type),
promise: new shaka.util.PublicPromise()
};
op.transaction.oncomplete = (function(event) {
this.closeOperation_(op);
op.promise.resolve();
}.bind(this));
// We will see an onabort call via:
// 1. request error -> transaction error -> transaction abort
// 2. transaction commit fail -> transaction abort
// As any transaction error will result in an abort, it is better to listen
// for an abort so that we will catch all failed transaction operations.
op.transaction.onabort = (function(event) {
this.closeOperation_(op);
shaka.offline.DBEngine.onError_(op.transaction, op.promise, event);
}.bind(this));
// We need to prevent default on the onerror event or else Firefox will
// raise an error which will cause a karma failure. This will not stop the
// onabort callback from firing.
op.transaction.onerror = (function(event) {
event.preventDefault();
}.bind(this));
var store = op.transaction.objectStore(storeName);
action(store);
this.operations_.push(op);
return op.promise;
};
/**
* Close an open operation.
*
* @param {!shaka.offline.DBEngine.Operation} op
* @private
*/
shaka.offline.DBEngine.prototype.closeOperation_ = function(op) {
var i = this.operations_.indexOf(op);
goog.asserts.assert(i >= 0, 'Operation must be in the list.');
this.operations_.splice(i, 1);
};
/**
* Creates a new connection to the database.
*
* On IE/Edge, it is possible for the database to not be deleted when the
* success callback is fired. This means that when we delete the database and
* immediately create a new connection, we will connect to the old database.
* If this happens, we need to close the connection and retry.
*
* @see https://goo.gl/hOYJvN
*
* @param {!Object.<string, string>} storeMap
* @param {number=} opt_retryCount
* @return {!Promise}
* @private
*/
shaka.offline.DBEngine.prototype.createConnection_ = function(
storeMap, opt_retryCount) {
var DBEngine = shaka.offline.DBEngine;
var indexedDB = window.indexedDB;
var request = indexedDB.open(DBEngine.DB_NAME_, DBEngine.DB_VERSION_);
var upgraded = false;
var createPromise = new shaka.util.PublicPromise();
request.onupgradeneeded = function(event) {
upgraded = true;
var db = event.target.result;
goog.asserts.assert(event.oldVersion == 0,
'Must be upgrading from version 0');
goog.asserts.assert(db.objectStoreNames.length == 0,
'Version 0 database should be empty');
for (var name in storeMap) {
db.createObjectStore(name, {keyPath: storeMap[name]});
}
};
request.onsuccess = (function(event) {
if (opt_retryCount && !upgraded) {
event.target.result.close();
shaka.log.info('Didn\'t get an upgrade event... trying again.');
setTimeout(function() {
var p = this.createConnection_(storeMap, opt_retryCount - 1);
p.then(createPromise.resolve, createPromise.reject);
}.bind(this), 1000);
return;
}
goog.asserts.assert(opt_retryCount == undefined || upgraded,
'Should get upgrade event');
this.db_ = event.target.result;
createPromise.resolve();
}.bind(this));
request.onerror = DBEngine.onError_.bind(null, request, createPromise);
return createPromise;
};
/**
* Rejects the given Promise using the error fromt the transaction.
*
* @param {!IDBTransaction|!IDBRequest} errorSource
* @param {!shaka.util.PublicPromise} promise
* @param {Event} event
* @private
*/
shaka.offline.DBEngine.onError_ = function(errorSource, promise, event) {
if (errorSource.error) {
promise.reject(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.INDEXED_DB_ERROR, errorSource.error));
} else {
promise.reject(new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.OPERATION_ABORTED));
}
// Firefox will raise an error which will cause a karma failure.
event.preventDefault();
};
|
import { getByTitle } from "@testing-library/react";
class NoteModel {
constructor() {
getByTitle,
content
}
} |
"use strict";
import swPrecache from 'sw-precache';
export default (config) => {
return function generate_sw_task (done) {
const rootDir = config.dest;
const connect = config.connect;
swPrecache.write(`${rootDir}/sw.js`, {
staticFileGlobs: [rootDir + '/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff,woff2,otf}'],
stripPrefix: rootDir,
maximumFileSizeToCacheInBytes: 8097152
}, () => {
if(connect){
connect.reload();
}
done();
});
};
};
|
import {combineReducers} from 'redux';
import {GET_ITEMS_SUCCESS, SAVE_ITEM_SUCCESS, EDIT_ITEM_SUCCESS, DELETE_ITEM_SUCCESS} from "../../actions/plantaAlimentos/itemsActions";
const list = (state = [], action) => {
switch(action.type){
case GET_ITEMS_SUCCESS:
return action.items;
case SAVE_ITEM_SUCCESS:
return [...state, action.item];
case EDIT_ITEM_SUCCESS:
return [ ...state.map ( item => {
if (item.id === action.item.id) {
return action.item;
}
return item;
})];
case DELETE_ITEM_SUCCESS:
return [ ...state.filter( item => item.id !== action.itemId)];
default:
return state;
}
};
const itemsReducer = combineReducers({
list:list,
});
export default itemsReducer; |
RecordMode = Mode.extend({
init: function(options) {
this.strokeHandler = new StrokeHandler();
},
activate: function() {
_writer.clearDisplay();
}
}); |
/***
PlotKit Autoload Javascript Module.
This file was adapted from MochiKit.
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito. All rights Reserved.
Modified by Alastair Tse, 2006, for PlotKit.
***/
if (typeof(PlotKit) == 'undefined') {
PlotKit = {};
}
if (typeof(PlotKit.PlotKit) == 'undefined') {
PlotKit.PlotKit = {};
}
PlotKit.PlotKit.NAME = "PlotKit.PlotKit";
PlotKit.PlotKit.VERSION = "0.9.2";
PlotKit.PlotKit.__repr__ = function () {
return "[" + this.NAME + " " + this.VERSION + "]";
};
PlotKit.PlotKit.toString = function () {
return this.__repr__();
};
PlotKit.PlotKit.SUBMODULES = [
"Base",
"Layout",
"Canvas",
"SVG",
"SweetCanvas",
"SweetSVG",
"EasyPlot"
];
if (typeof(PlotKit.__compat__) == 'undefined') {
PlotKit.__compat__ = true;
}
(function () {
if (typeof(document) == "undefined") {
return;
}
var scripts = document.getElementsByTagName("script");
var kXULNSURI = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
var base = null;
var baseElem = null;
var allScripts = {};
var i;
for (i = 0; i < scripts.length; i++) {
var src = scripts[i].getAttribute("src");
if (!src) {
continue;
}
allScripts[src] = true;
if (src.match(/PlotKit.js$/)) {
base = src.substring(0, src.lastIndexOf('PlotKit.js'));
baseElem = scripts[i];
}
}
if (base === null) {
return;
}
var modules = PlotKit.PlotKit.SUBMODULES;
for (var i = 0; i < modules.length; i++) {
if (PlotKit[modules[i]]) {
continue;
}
var uri = base + modules[i] + '.js';
if (uri in allScripts) {
continue;
}
if (document.documentElement &&
document.documentElement.namespaceURI == kXULNSURI) {
// XUL
var s = document.createElementNS(kXULNSURI, 'script');
s.setAttribute("id", "PlotKit_" + base + modules[i]);
s.setAttribute("src", uri);
s.setAttribute("type", "application/x-javascript");
baseElem.parentNode.appendChild(s);
} else {
// HTML
/*
DOM can not be used here because Safari does
deferred loading of scripts unless they are
in the document or inserted with document.write
This is not XHTML compliant. If you want XHTML
compliance then you must use the packed version of PlotKit
or include each script individually (basically unroll
these document.write calls into your XHTML source)
*/
document.write('<script src="' + uri +
'" type="text/javascript"></script>');
}
};
})();
|
import VueRouter from 'vue-router' // eslint-disable-line import/no-extraneous-dependencies
import VueI18n from 'vue-i18n'
import VueModal from 'vue-js-modal'
import SubscribeModal from './SubscribeModal.vue'
describe.skip('Component | SubscribeModal.vue', () => {
let wrapper
const email = 'pierre@recontact.me'
let localVue
beforeEach(() => {
console.warn = jest.fn()
localVue = createLocalVue()
localVue.use(VueI18n)
localVue.use(VueRouter)
localVue.use(VueModal)
wrapper = shallowMount(SubscribeModal, {
localVue,
data() {
return {
email,
}
},
})
})
describe('template', () => {
it('should match snapshot', () => {
expect(wrapper).toMatchSnapshot()
})
})
})
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
View,
ScrollView,
Animated,
VirtualizedList,
InteractionManager,
} from 'react-native';
import moment from 'moment';
import memoizeOne from 'memoize-one';
import Events from '../Events/Events';
import Header from '../Header/Header';
import Title from '../Title/Title';
import Times from '../Times/Times';
import styles from './WeekView.styles';
import {
TIME_LABELS_IN_DISPLAY,
CONTAINER_HEIGHT,
DATE_STR_FORMAT,
availableNumberOfDays,
setLocale,
CONTAINER_WIDTH,
} from '../utils';
const MINUTES_IN_DAY = 60 * 24;
export default class WeekView extends Component {
constructor(props) {
super(props);
this.eventsGrid = null;
this.verticalAgenda = null;
this.header = null;
this.pageOffset = 2;
this.currentPageIndex = this.pageOffset;
this.eventsGridScrollX = new Animated.Value(0);
this.state = {
currentMoment: props.selectedDate,
initialDates: this.calculatePagesDates(
props.selectedDate,
props.numberOfDays,
props.prependMostRecent,
),
};
setLocale(props.locale);
}
componentDidMount() {
requestAnimationFrame(() => {
this.scrollToVerticalStart();
});
this.eventsGridScrollX.addListener((position) => {
this.header.scrollToOffset({ offset: position.value, animated: false });
});
}
componentDidUpdate(prevprops) {
if (this.props.locale !== prevprops.locale) {
setLocale(this.props.locale);
}
}
componentWillUnmount() {
this.eventsGridScrollX.removeAllListeners();
}
calculateTimes = memoizeOne((hoursInDisplay) => {
const times = [];
const timeLabelsPerHour = TIME_LABELS_IN_DISPLAY / hoursInDisplay;
const minutesStep = 60 / timeLabelsPerHour;
for (let timer = 0; timer < MINUTES_IN_DAY; timer += minutesStep) {
let minutes = timer % 60;
if (minutes < 10) minutes = `0${minutes}`;
const hour = Math.floor(timer / 60) % 12 || 12;
const ampm = timer < 720 ? 'am' : 'pm'
const timeString = `${hour}:${minutes}${ampm}`;
times.push(timeString);
}
return times;
});
scrollToVerticalStart = () => {
if (this.verticalAgenda) {
const { startHour, hoursInDisplay } = this.props;
const startHeight = (startHour * CONTAINER_HEIGHT) / hoursInDisplay;
this.verticalAgenda.scrollTo({ y: startHeight, x: 0, animated: false });
}
};
scrollEnded = (event) => {
const {
nativeEvent: { contentOffset, contentSize },
} = event;
const { x: position } = contentOffset;
const { width: innerWidth } = contentSize;
const {
onSwipePrev,
onSwipeNext,
numberOfDays,
prependMostRecent,
} = this.props;
const { currentMoment, initialDates } = this.state;
const newPage = Math.round((position / innerWidth) * initialDates.length);
const movedPages = newPage - this.currentPageIndex;
this.currentPageIndex = newPage;
if (movedPages === 0) {
return;
}
InteractionManager.runAfterInteractions(() => {
const daySignToTheFuture = prependMostRecent ? -1 : 1;
const newMoment = moment(currentMoment)
.add(movedPages * numberOfDays * daySignToTheFuture, 'd')
.toDate();
const newState = {
currentMoment: newMoment,
};
if (movedPages < 0 && newPage < this.pageOffset) {
const first = initialDates[0];
const daySignToThePast = daySignToTheFuture * -1;
const addDays = numberOfDays * daySignToThePast;
const initialDate = moment(first).add(addDays, 'd');
initialDates.unshift(initialDate.format(DATE_STR_FORMAT));
this.currentPageIndex += 1;
this.eventsGrid.scrollToIndex({
index: this.currentPageIndex,
animated: false,
});
newState.initialDates = [...initialDates];
} else if (
movedPages > 0 &&
newPage > this.state.initialDates.length - this.pageOffset
) {
const latest = initialDates[initialDates.length - 1];
const addDays = numberOfDays * daySignToTheFuture;
const initialDate = moment(latest).add(addDays, 'd');
initialDates.push(initialDate.format(DATE_STR_FORMAT));
newState.initialDates = [...initialDates];
}
this.setState(newState);
if (movedPages < 0) {
onSwipePrev && onSwipePrev(newMoment);
} else {
onSwipeNext && onSwipeNext(newMoment);
}
});
};
eventsGridRef = (ref) => {
this.eventsGrid = ref;
};
verticalAgendaRef = (ref) => {
this.verticalAgenda = ref;
};
headerRef = (ref) => {
this.header = ref;
};
calculatePagesDates = (currentMoment, numberOfDays, prependMostRecent) => {
const initialDates = [];
for (let i = -this.pageOffset; i <= this.pageOffset; i += 1) {
const initialDate = moment(currentMoment).add(numberOfDays * i, 'd');
initialDates.push(initialDate.format(DATE_STR_FORMAT));
}
return prependMostRecent ? initialDates.reverse() : initialDates;
};
getListItemLayout = (index) => ({
length: CONTAINER_WIDTH,
offset: CONTAINER_WIDTH * index,
index,
});
render() {
const {
showTitle,
numberOfDays,
headerStyle,
headerTextStyle,
hourTextStyle,
eventContainerStyle,
formatDateHeader,
onEventPress,
events,
hoursInDisplay,
onGridClick,
EventComponent,
prependMostRecent,
rightToLeft,
} = this.props;
const { currentMoment, initialDates } = this.state;
const times = this.calculateTimes(hoursInDisplay);
const horizontalInverted =
(prependMostRecent && !rightToLeft) ||
(!prependMostRecent && rightToLeft);
return (
<View style={styles.container}>
<View style={styles.headerContainer}>
<Title
showTitle={showTitle}
style={headerStyle}
textStyle={headerTextStyle}
selectedDate={currentMoment}
/>
<VirtualizedList
horizontal
pagingEnabled
inverted={horizontalInverted}
showsHorizontalScrollIndicator={false}
scrollEnabled={false}
ref={this.headerRef}
data={initialDates}
getItem={(data, index) => data[index]}
getItemCount={(data) => data.length}
getItemLayout={(_, index) => this.getListItemLayout(index)}
keyExtractor={(item) => item}
initialScrollIndex={this.pageOffset}
renderItem={({ item }) => {
return (
<View key={item} style={styles.header}>
<Header
style={headerStyle}
textStyle={headerTextStyle}
formatDate={formatDateHeader}
initialDate={item}
numberOfDays={numberOfDays}
rightToLeft={rightToLeft}
/>
</View>
);
}}
/>
</View>
<ScrollView ref={this.verticalAgendaRef}>
<View style={styles.scrollViewContent}>
<Times times={times} textStyle={hourTextStyle} />
<VirtualizedList
data={initialDates}
getItem={(data, index) => data[index]}
getItemCount={(data) => data.length}
getItemLayout={(_, index) => this.getListItemLayout(index)}
keyExtractor={(item) => item}
initialScrollIndex={this.pageOffset}
renderItem={({ item }) => {
return (
<Events
times={times}
eventsByDate={events}
initialDate={item}
numberOfDays={numberOfDays}
onEventPress={onEventPress}
onGridClick={onGridClick}
hoursInDisplay={hoursInDisplay}
EventComponent={EventComponent}
eventContainerStyle={eventContainerStyle}
rightToLeft={rightToLeft}
/>
);
}}
horizontal
pagingEnabled
inverted={horizontalInverted}
onMomentumScrollEnd={this.scrollEnded}
scrollEventThrottle={32}
onScroll={Animated.event(
[
{
nativeEvent: {
contentOffset: {
x: this.eventsGridScrollX,
},
},
},
],
{ useNativeDriver: false },
)}
ref={this.eventsGridRef}
/>
</View>
</ScrollView>
</View>
);
}
}
WeekView.propTypes = {
events: PropTypes.object,
formatDateHeader: PropTypes.string,
numberOfDays: PropTypes.oneOf(availableNumberOfDays).isRequired,
onSwipeNext: PropTypes.func,
onSwipePrev: PropTypes.func,
onEventPress: PropTypes.func,
onGridClick: PropTypes.func,
headerStyle: PropTypes.object,
headerTextStyle: PropTypes.object,
hourTextStyle: PropTypes.object,
eventContainerStyle: PropTypes.object,
selectedDate: PropTypes.instanceOf(Date).isRequired,
locale: PropTypes.string,
hoursInDisplay: PropTypes.number,
startHour: PropTypes.number,
EventComponent: PropTypes.elementType,
showTitle: PropTypes.bool,
rightToLeft: PropTypes.bool,
prependMostRecent: PropTypes.bool,
};
WeekView.defaultProps = {
events: [],
locale: 'en',
hoursInDisplay: 6,
startHour: 0,
showTitle: true,
rightToLeft: false,
prependMostRecent: false,
};
|
import React, { Component } from 'react';
import './../style/gayaku.css';
import { Link } from 'react-router-dom';
import Header from './Header';
import Jumbotron from './Jumbotron';
import Footer from './Footer';
class About extends Component
{
render()
{
return (
<div>
<Header/>
{/* Container (About Section) */}
<div style={{marginTop: 150 }}>
<center><h1><b>ABOUT US</b></h1></center>
</div>
<div className="container bg-grey apaaja" style={{marginTop: 50, borderRadius: 15, padding: 20}}>
<div className="row">
<div className="col-sm-4 text-center">
<img src="images/me.jpg" className="img-circle border" width={220} height={204} alt="COFFEES" />
</div>
<div className="col-sm-8" style={{marginTop: 40, fontSize: 16, textAlign: 'justify'}}>
<p>
FanMartin's Coffe didirikan oleh Nur Inna Alfianinda pada tahun 2018,
merupakan sebuah perusahaan yang memproduksi biji dan bubuk kopi arabika kualitas terbaik
dengan variasi tipe roasting dan grinding, serta cita rasa dan aromanya, dimana kopi yang diproduksi berasal
dari wilayah perkebunan kopi kayumas Jawa Timur-Indonesia yang citarasa kopinya telah dikenal dan mendunia.
</p>
</div>
</div>
</div>
<div style={{marginTop: 70}}>
<Jumbotron/>
</div>
<Footer/>
</div>
);
}
} export default About; |
"use strict";
$(document)
.ready(function() {
// Product Delete
$(".delete_product")
.click(function(e) {
e.preventDefault();
const id = $(this).attr("id");
$.ajax({
type: "post",
url: `/Product/DeleteProduct/${id}`,
ajaxasync: true,
success: function() {
console.log(`Delete product${id}`);
$(`tr[id^='${id}']`).remove();
},
error: function(data) {
console.log(data.x);
}
});
});
}); |
function mostrar()
{
var mesDelAño =txtIdMes.value;
switch (mesDelAño){
case ("Febrero"):
alert ("este mes tiene 28");
break;
case ("Abril"):
case ("Junio"):
case ("Septiembre"):
case ("Noviembre"):
alert ("este mes tiene 30");
break;
default:
alert ("este mes tiene 31");
break;
}
} |
import React from "react";
import { Container, Row, Col, Fade } from "react-bootstrap";
import { Link } from "react-router-dom";
import Header from "../components/Header";
import Footer from "../components/Footer";
class Home extends React.Component {
render() {
return (
<Fade in={true} appear={true}>
<div className="Home vh-100">
<Header pos="fixed" />
<Container className="h-100 d-flex flex-column align-items-center justify-content-center">
<Row className="justify-content-center align-items-center w-100">
<Col
xs={12}
md={6}
className="p-5 translucent-black d-flex flex-column justify-content-center align-items-center"
>
<h1 className="text-center text-white pri-font">
<b>Life is an uphill battle</b>
</h1>
<h3 className="text-center text-white sec-font my-3">
Start your climb with us today
</h3>
<Link
className="btn btn-outline-light sec-font my-3"
to="/contact"
>
Find out more
</Link>
</Col>
</Row>
</Container>
<Footer />
</div>
</Fade>
);
}
}
export default Home;
|
const del = require('del')
const eslint = require('gulp-eslint')
const gulp = require('gulp')
const gutil = require('gulp-util')
const relativeSourcemapsSource = require('gulp-relative-sourcemaps-source')
const rollup = require('rollup-stream')
const rename = require('gulp-rename')
const buffer = require('vinyl-buffer')
const source = require('vinyl-source-stream')
const sourcemaps = require('gulp-sourcemaps')
const terser = require('gulp-terser')
gulp.task('clean', function () {
return del(['dist'])
})
gulp.task('check', function () {
return gulp.src(['src/**/*.js', 'gulpfile.js'])
.pipe(eslint())
.pipe(eslint.format('node_modules/eslint-friendly-formatter'))
.pipe(eslint.failAfterError())
})
gulp.task('dist', function () {
return rollup({
input: 'src/main.js',
format: 'es',
sourcemap: true
})
.pipe(source('main.js', './src'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(terser().on('error', gutil.log))
// sources[] would be relative to the output directory root
// without the relativeSourcemapsSource plugin
.pipe(rename('bundle.js'))
.pipe(relativeSourcemapsSource({ dest: 'dist' }))
.pipe(sourcemaps.write('.', {
includeContent: false,
// sources[] will be set to the relative paths to the source
// files - relative from the directory of every built file,
// that is why sourceRoot in map files should be always '.'
sourceRoot: '.'
}))
.pipe(gulp.dest('dist'))
})
gulp.task('default', gulp.series('check', 'dist'))
|
import { useEffect, useState } from 'react';
const getStatus = () =>
typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean'
? navigator.onLine
: true;
export const useOnline = () => {
const [status, setStatus] = useState(getStatus());
const setOnline = () => setStatus(true);
const setOffline = () => setStatus(false);
useEffect(() => {
window.addEventListener('online', setOnline);
window.addEventListener('offline', setOffline);
return () => {
window.removeEventListener('online', setOnline);
window.removeEventListener('offline', setOffline);
};
}, []);
return status;
};
export default useOnline;
|
import { action, computed, observable, runInAction } from 'mobx';
import axios from './../../helpers/axios';
import jwt_decode from 'jwt-decode';
// Note that we have deliberately avoided the use of arrow-functions to define the action.
// This is because arrow-functions capture the lexical this at the time the action is defined.
// However, the observable() API returns a new object, which is of course different from the lexical this that is captured in the action() call.
// This means, the this that you are mutating would not be the object that is returned from observable().
export const authState = observable({
token: null,
user: null,
registration_error: null,
login_error: null,
registered_email: null,
loading: false,
authRedirectPath: '/',
setAuthRedirectPath: action(function(path) {
this.authRedirectPath = path;
}),
authLogout: action(function() {
localStorage.removeItem('token');
localStorage.removeItem('expirationDate');
localStorage.removeItem('user');
this.token = null;
this.user = null;
}),
authCheckState: action(function() {
const token = localStorage.getItem('token');
if (!token) {
this.authLogout();
return;
}
const expirationDate = new Date(localStorage.getItem('expirationDate'));
if (expirationDate <= new Date()) {
this.authLogout();
return;
}
const user = JSON.parse(localStorage.getItem('user'));
this.token = token;
this.user = user;
}),
auth: action(function(email, password) {
this.loading = true;
this.login_error = null;
let data = {
"username": email,
"password": password
};
axios.post("/login_check", data)
.then(response => {
const decoded = jwt_decode(response.data.token);
let user = {
id: decoded.user_id,
email: decoded.username
};
const expirationDate = new Date(decoded.exp*1000);
localStorage.setItem('token', response.data.token);
localStorage.setItem('expirationDate', expirationDate.toISOString());
localStorage.setItem('user', JSON.stringify(user));
runInAction(() => {
this.token = response.data.token;
this.user = user;
this.loading = false;
this.login_error = null;
});
})
.catch(err => {
runInAction(() => {
this.loading = false;
this.login_error = err.response.data.errorMessage;
});
});
}),
register: action(function(data) {
this.loading = true;
this.registration_error = null;
this.registered_email = null;
data = {
"email": data.email,
"name": data.name,
"companyName": data.companyName,
"password": data.password,
"addresses": [
{
"street": data.billingAddress,
"city": data.billingCity,
"postalCode": data.billingPostalCode,
"countryCode": data.billingCountry
}
]
};
const config = {
"headers": {
'Accept': 'application/ld+json',
'Content-Type': 'application/ld+json'
}
};
axios.post("/users", data, config)
.then(response => {
runInAction(() => {
this.loading = false;
this.registration_error = null;
this.registered_email = response.data.email;
});
})
.catch(err => {
runInAction(() => {
this.loading = false;
this.registration_error = err.response.data.errorMessage;
this.registered_email = null;
});
});
}),
registerCleanup: action(function(email) {
localStorage.setItem('lastRegisteredEmail', email);
this.loading = false;
this.registration_error = null;
this.registered_email = null;
}),
});
|
const THREE = require('three');
export function Agent(pos) {
this.position = pos;//[pos.x,pos.y,pos.z];
this.forward = new THREE.Vector3(1,0,0);
this.velocity = new THREE.Vector3(0,0,0);
this.orientation = [1,1,1];
this.size = [1,1,1];
this.goal = new THREE.Vector3(0,0,0);
this.color = 0xFFFFFF;
this.markers = [];
this.mesh = null;
this.updatePosition = function(agents) {
var x = Math.floor(this.position.x);
var z = Math.floor(this.position.z);
var tile_agents = agents[x][z];
var index = tile_agents.indexOf(this);
if (index > -1) {
tile_agents.splice(index, 1);
} else {
console.log("WARNING: Agent index should always exist.")
}
this.position.x += this.velocity.x;
this.position.y += this.velocity.y;
this.position.z += this.velocity.z;
if (this.mesh) {
this.mesh.scale.set(0.3,0.3,0.3);
this.mesh.position.x = this.position.x;
this.mesh.position.z = this.position.z;
}
var new_x = Math.floor(this.position.x);
var new_z = Math.floor(this.position.z);
if (typeof agents[new_x] == 'undefined') {
agents[new_x] = [];
}
if (typeof agents[new_x][new_z] == 'undefined') {
agents[new_x][new_z] = [];
}
agents[new_x][new_z].push(this);
}
}
function createAgent(pos) {
var agent = new Agent(pos);
// var triangleGeometry = new THREE.Geometry();
// triangleGeometry.vertices.push(new THREE.Vector3(0.0, 0, 0.4));
// triangleGeometry.vertices.push(new THREE.Vector3(1.0, 0, 0.0));
// triangleGeometry.vertices.push(new THREE.Vector3( 0.0, 0, -0.4));
// triangleGeometry.vertices.push(new THREE.Vector3(0.0, 0.4, 0.0));
//
// triangleGeometry.faces.push(new THREE.Face3(0, 1, 2));
// triangleGeometry.faces.push(new THREE.Face3(0, 3, 1));
// triangleGeometry.faces.push(new THREE.Face3(1, 3, 2));
// triangleGeometry.faces.push(new THREE.Face3(2, 3, 0));
var cylinder = new THREE.CylinderGeometry(0.4, 0.4, 2);
var material = new THREE.MeshBasicMaterial({
color:0xFF0000,
side:THREE.DoubleSide
});
var mesh = new THREE.Mesh(cylinder, material);
mesh.position.set(pos.x, pos.y+0.21, pos.z);
mesh.scale.set(0.3,0.3,0.3);
agent.mesh = mesh;
return agent;
}
export default function Crowd(agent_density, grid_length) {
this.agentsData = [];
//this.spacing = Math.sqrt(grid_length * grid_length / num_agents);
this.spacing = 1.0/agent_density;
this.gridWidth = grid_length;
this.scenario = 1;
this.createAgents = function() {
var spacing_ceil = Math.ceil(this.spacing);
switch (this.scenario) {
case 1:
for (var i = 0; i < this.gridWidth/2; i+=spacing_ceil) {
var row = Math.floor(i);
for (var j = 0; j < this.gridWidth/2-row; j+=spacing_ceil) {
var col = Math.floor(j);
var x = i+Math.random()*this.spacing;
var z = j+Math.random()*this.spacing;
var agent = createAgent(new THREE.Vector3(x,0,z));
agent.goal.x = this.gridWidth-1;
agent.goal.z = this.gridWidth-1;
var floor_x = Math.floor(x);
var floor_z = Math.floor(z);
if (!this.agentsData[floor_x]) {
this.agentsData[floor_x] = [];
}
if (!this.agentsData[floor_x][floor_z]) {
this.agentsData[floor_x][floor_z] = [];
}
this.agentsData[floor_x][floor_z].push(agent);
}
}
for (var i = this.gridWidth-spacing_ceil; i >= this.gridWidth/2; i-=spacing_ceil) {
var row = Math.floor(i);
for (var j = this.gridWidth-spacing_ceil; j >= this.gridWidth/2+(this.gridWidth-spacing_ceil-row); j-=spacing_ceil) {
var col = Math.floor(j);
var x = i+Math.random()*this.spacing;
var z = j+Math.random()*this.spacing;
var agent = createAgent(new THREE.Vector3(x,0,z));
agent.goal.x = 0;
agent.goal.z = 0;
var floor_x = Math.floor(x);
var floor_z = Math.floor(z);
if (!this.agentsData[floor_x]) {
this.agentsData[floor_x] = [];
}
if (!this.agentsData[floor_x][floor_z]) {
this.agentsData[floor_x][floor_z] = [];
}
this.agentsData[floor_x][floor_z].push(agent);
}
}
break;
case 2:
for (var i = 0; i < this.gridWidth; i+=spacing_ceil) {
var row = Math.floor(i);
for (var j = 0; j < 3; j+=spacing_ceil) {
var col = Math.floor(j);
var x = i+Math.random()*this.spacing;
var z = j+Math.random()*this.spacing;
var agent = createAgent(new THREE.Vector3(x,0,z));
agent.goal.x = x;
agent.goal.z = this.gridWidth;
var floor_x = Math.floor(x);
var floor_z = Math.floor(z);
if (!this.agentsData[floor_x]) {
this.agentsData[floor_x] = [];
}
if (!this.agentsData[floor_x][floor_z]) {
this.agentsData[floor_x][floor_z] = [];
}
this.agentsData[floor_x][floor_z].push(agent);
}
}
for (var i = this.gridWidth-spacing_ceil; i >= 0; i-=spacing_ceil) {
var row = Math.floor(i);
for (var j = this.gridWidth-spacing_ceil; j >= this.gridWidth-spacing_ceil-2; j-=spacing_ceil) {
var col = Math.floor(j);
var x = i+Math.random()*this.spacing;
var z = j+Math.random()*this.spacing;
var agent = createAgent(new THREE.Vector3(x,0,z));
agent.goal.x = x;
agent.goal.z = 0;
var floor_x = Math.floor(x);
var floor_z = Math.floor(z);
if (!this.agentsData[floor_x]) {
this.agentsData[floor_x] = [];
}
if (!this.agentsData[floor_x][floor_z]) {
this.agentsData[floor_x][floor_z] = [];
}
this.agentsData[floor_x][floor_z].push(agent);
}
}
break;
case 3:
for (var i = 0; i < this.gridWidth; i+=spacing_ceil) {
var row = Math.floor(i);
for (var j = 0; j < this.gridWidth; j+=spacing_ceil) {
var col = Math.floor(j);
var x = i+Math.random()*this.spacing;
var z = j+Math.random()*this.spacing;
var agent = createAgent(new THREE.Vector3(x,0,z));
var floor_x = Math.floor(x);
var floor_z = Math.floor(z);
if (typeof this.agentsData[floor_x] == 'undefined') {
this.agentsData[floor_x] = [];
}
if (typeof this.agentsData[floor_x][floor_z] == 'undefined') {
this.agentsData[floor_x][floor_z] = [];
}
this.agentsData[floor_x][floor_z].push(agent);
}
}
break;
default:
console.log('Not an existing scenario.');
break;
}
return this.agentsData;
}
} |
import React from 'react'
import { storiesOf } from '@storybook/react'
import { text, boolean, number, select } from '@storybook/addon-knobs/react'
import { withInfo } from '@storybook/addon-info'
import {
Form,
Input,
Label,
Search,
TextInput,
TextareaInput,
CheckboxInput,
Select,
Option
} from '../forms'
const labelProps = () => ({
bold: boolean('bold', false),
light: boolean('light', false),
uppercase: boolean('uppercase', false),
lowercase: boolean('lowercase', false)
})
storiesOf('Form', module)
.add(
'Label',
withInfo(`
something here
`)(() => <Label {...labelProps()}>{text('label', 'Some Input')}</Label>)
)
.add(
'Search',
withInfo(`
something here
`)(() => <Search focus={boolean('focus', true)} />)
)
.add(
'TextInput',
withInfo(`
something here
`)(() => (
<TextInput
label={text('label', 'Email')}
placeholder={text('placeholder', 'Email Address')}
/>
))
)
.add(
'TextareaInput',
withInfo(`
something here
`)(() => (
<TextareaInput
label={text('label', 'About You')}
placeholder={text('placeholder', 'Tell us about yourself ')}
minHeight={text('minHeight', '')}
width={text('width', '')}
/>
))
)
.add(
'CheckboxInput',
withInfo(`
something here
`)(() => (
<Form>
<CheckboxInput label={'Hello'} placeholder={text('label', 'Vegan')} />
<CheckboxInput
label={'Hello'}
placeholder={text('label', 'Gluten Free')}
/>
</Form>
))
)
.add(
'Select and Options',
withInfo(`
something here
`)(() => (
<Form>
<Label>{text('label', 'Select with Options')}</Label>
<Select>
<Option value={1}>{text('Option 1', 'One')}</Option>
<Option value={2}>{text('Option 1', 'Two')}</Option>
</Select>
</Form>
))
)
|
import React from 'react';
import { Link } from "react-router-dom";
import './main.css';
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink,
UncontrolledDropdown,
DropdownToggle,
DropdownMenu,
DropdownItem} from 'reactstrap';
import AuthService from "../AuthService";
import withAuth from "../withAuth";
const Auth = new AuthService();
class Header extends React.Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false,
userAuthorities: []
};
}
componentWillMount() {
this.setState({
userAuthorities: this.props.user.authorities
})
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
handleLogout(){
Auth.logout()
this.props.history.replace('/login');
}
render() {
return (
<div>
<Navbar color="light" light expand="md">
<NavbarBrand href="/">
<img src="/logo-fiuba.svg" width="30" height="30" alt=""/>
</NavbarBrand>
<NavbarToggler onClick={this.toggle} />
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto" navbar>
<UncontrolledDropdown nav inNavbar>
<DropdownToggle nav caret>
Acciones
</DropdownToggle>
<DropdownMenu right>
<DropdownItem>
<Link to="/cursos">Cursos</Link>
</DropdownItem>
<div className={this.state.userAuthorities.includes('ROLE_ADMIN') ? '' : 'd-none'}>
<DropdownItem divider />
<DropdownItem>
<Link to="/periodos">Periodos</Link>
</DropdownItem>
<DropdownItem divider />
<DropdownItem>
<Link to="/alumnos/cargaMasiva">Importar Alumnos</Link>
</DropdownItem>
</div>
<DropdownItem divider />
<DropdownItem>
<Link to="/profesores/cargaMasiva">Importar Profesores</Link>
</DropdownItem>
<DropdownItem divider />
<DropdownItem>
<Link to="/reportes">Reporte</Link>
</DropdownItem>
</DropdownMenu>
</UncontrolledDropdown>
<NavItem>
<NavLink href="#" onClick={this.handleLogout.bind(this)}>
Salir
</NavLink>
</NavItem>
</Nav>
</Collapse>
</Navbar>
</div>
);
}
}
export default withAuth(Header);
|
const name = 'move'
function onInstall() {}
function dir(direction) {
let move = false
switch(direction) {
case 0: move = this.up(); break;
case 1: move = this.left(); break;
case 2: move = this.down(); break;
case 3: move = this.right(); break;
}
const port = lab.mode.port1.inFocus(this.__)
if (move) {
switch(port) {
case 1: this.__.fsfx('step1'); break;
case 2: this.__.fsfx('step2'); break;
case 3: this.__.fsfx('step2'); break;
case 4: this.__.fsfx('step2'); break;
}
} else {
if (port) this.__.fsfx('misStep')
}
return move
}
function up() {
const w = this.__._
const x = this.__.x
const y = this.__.y - 1
const obstacle = w.isSolid(x, y)
if (!obstacle) {
w.touch(x, y, this.__)
this.__.y = y
return true
} else {
if (this.__.push) this.__.push(obstacle, 0)
if (obstacle.pushedBy) obstacle.pushedBy(this.__, 0)
return false
}
}
function left() {
const w = this.__._
const x = this.__.x - 1
const y = this.__.y
const obstacle = w.isSolid(x, y)
if (!obstacle) {
w.touch(x, y, this.__)
this.__.x = x
return true
} else {
if (this.__.push) this.__.push(obstacle, 1)
if (obstacle.pushedBy) obstacle.pushedBy(this.__, 1)
return false
}
}
function down() {
const w = this.__._
const x = this.__.x
const y = this.__.y + 1
const obstacle = w.isSolid(x, y)
if (!obstacle) {
w.touch(x, y, this.__)
this.__.y = y
return true
} else {
if (this.__.push) this.__.push(obstacle, 2)
if (obstacle.pushedBy) obstacle.pushedBy(this.__, 2)
return false
}
}
function right() {
const w = this.__._
const x = this.__.x + 1
const y = this.__.y
const obstacle = w.isSolid(x, y)
if (!obstacle) {
w.touch(x, y, this.__)
this.__.x = x
return true
} else {
if (this.__.push) this.__.push(obstacle, 3)
if (obstacle.pushedBy) obstacle.pushedBy(this.__, 3)
return false
}
}
function onRemove() {}
|
const express = require("express");
const app = express();
const {
checkErr,
correctPath,
borrarImagen,
borrarArchivo,
deleteDir,
findData,
} = require("../funts");
const { verificaToken, verificaTokenImg } = require("../middelwares/authentication");
const Dir = require("../models/dir");
const File = require("../models/file");
const User = require("../models/user");
const fs = require("fs");
const path = require("path");
app.get("/getMediaFile/:id", verificaTokenImg, (req, res) => {
let id = req.params.id;
File.findById(id, (err, filedb) => {
if (err) {
return res.status(400).json({
ok: false,
err,
});
}
if (!filedb) {
return res.status(500).json({
ok: false,
err: { message: "no existe el archivo solicitado" },
});
}
let pathFile = filedb.path;
if (fs.existsSync(pathFile)) {
res.sendFile(pathFile + "/" + filedb.nombre);
}
});
});
app.get("/getTextFile/:id", verificaToken, (req, res) => {
let id = req.params.id;
File.findById(id, (err, filedb) => {
if (err) {
return res.status(400).json({
ok: false,
err,
});
}
let pathFile = filedb.path;
if (fs.existsSync(pathFile)) {
fs.readFile(pathFile + "/" + filedb.nombre, "utf8", (err, data) => {
if (err) {
return res.status(500).json({
ok: false,
err,
});
} else {
res.send({
data: data,
});
}
});
}
});
});
app.get('/getDataFile/:id', verificaToken, (req, res) => {
let id = req.params.id
File.findById(id, (err, filedb) => {
if (err) {return res.status(500).json({ok:false, err})}
return res.json({
ok: true,
filedb
})
})
})
module.exports = app;
|
// // @flow
// import React from 'react';
// import { Platform, StyleSheet, View } from 'react-native';
// import { reaction } from 'mobx';
// import { observer } from 'mobx-react';
//
// import type { ViewStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet';
//
// import {
// UIButton,
// UIColor,
// UITextButton,
// UIConstant,
// UILocalized,
// UIStyle,
// } from '../../services/UIKit/UIKit';
//
// import TONAssets from '../../assets/TONAssets';
//
// import { ModalController, ModalPath } from '../../TONRootNavigator/modal';
//
// import TONLocalized from '../../TONLocalized';
//
// import { TONAsync } from '../../TONUtility';
//
// import { TONKeystore } from '../../TONWallet';
//
// import { securityCardManager } from '../../TONSecurityCard';
//
// import WelcomeHelper from '../helpers/WelcomeHelper';
//
// import WalletWelcomeView from '../components/WalletWelcomeView';
//
// import WalletSetupScreenBase, { WalletSetupScreens } from './WalletSetupTypes';
//
// import type { WelcomeItem } from '../helpers/WelcomeHelper';
//
// import type { NavigationProps } from '../../services/UIKit/UIKit';
//
// type Props = NavigationProps;
//
// type State = {
// welcomeItems: ?WelcomeItem,
// welcomeIndex: number,
// generatingMasterKey: boolean,
// };
//
// const styleProperties = {
// container: {
// flex: 1,
// padding: UIConstant.contentOffset(),
// backgroundColor: UIColor.white(),
// },
// spaceSeparator: {
// width: UIConstant.contentOffset(),
// },
// };
//
// const styles = StyleSheet.create(styleProperties);
//
// let legalNotesConfirmed;
//
// @observer
// export default class WalletSetupMainScreen extends WalletSetupScreenBase<Props, State> {
// static navigationOptions = WalletSetupScreenBase.createNavigationOptions(
// '',
// null, // set logo if needed,
// Platform.OS === 'web', // shrink the navigation bar for web to help the modal screen
// );
//
// static defaultProps = {};
//
// // constructor
// constructor(props: Props) {
// super(props);
//
// this.state = {
// welcomeItems: [],
// welcomeIndex: 0,
// generatingSeedPhrase: false,
// };
// }
//
// componentDidMount() {
// super.componentDidMount();
// this.loadWelcomeItems();
// this.welcomeItemsReloader = reaction(
// () => securityCardManager.securityCardActivating,
// () => this.loadWelcomeItems(),
// );
// }
//
// componentWillFocus() {
// super.componentWillFocus();
// legalNotesConfirmed = false;
// }
//
// componentWillUnmount() {
// super.componentWillUnmount();
// if (this.welcomeItemsReloader) this.welcomeItemsReloader();
// }
//
// // Events
// onButtonPress = () => {
// const welcomeIndex = this.getWelcomeIndex();
// const startIndex = this.getStartIndex();
// if (welcomeIndex === startIndex) {
// WelcomeHelper.rememberAsShown();
// this.guardedAsyncNavigation(() => {
// ModalController.show(ModalPath.LegalNotes, {
// shouldConfirm: true,
// onConfirm: this.onConfirmLegalNotes,
// onDidHide: this.onLegalNotesHide,
// });
// });
// } else {
// this.setWelcomeIndex(welcomeIndex + 1);
// }
// };
//
// onTextButtonPress = () => {
// const welcomeIndex = this.getWelcomeIndex();
// const startIndex = this.getStartIndex();
// if (welcomeIndex === startIndex) {
// WelcomeHelper.rememberAsShown();
// this.guardedAsyncNavigation(() => {
// this.navigateToRestoreScreen();
// });
// } else {
// this.setWelcomeIndex(startIndex);
// }
// };
//
// /* eslint-disable class-methods-use-this */
// onConfirmLegalNotes = () => {
// legalNotesConfirmed = true;
// ModalController.hide(ModalPath.LegalNotes);
// };
//
// onLegalNotesHide = () => {
// if (legalNotesConfirmed) {
// this.startGenerateSeedPhrase();
// }
// };
//
// // Setters
// setGeneratingSeedPhrase(generatingSeedPhrase: boolean) {
// this.setStateSafely({ generatingSeedPhrase });
// }
//
// setWelcomeItems(welcomeItems: WelcomeItem[]) {
// this.setStateSafely({ welcomeItems });
// }
//
// setWelcomeIndex(welcomeIndex: number) {
// if (this.welcomeView) {
// this.welcomeView.changeIndex(welcomeIndex);
// }
// this.setStateSafely({ welcomeIndex });
// }
//
// // Getters
// isGeneratingSeedPhrase(): boolean {
// return this.state.generatingSeedPhrase;
// }
//
// getWelcomeItems(): WelcomeItem[] {
// return this.state.welcomeItems;
// }
//
// getWelcomeIndex(): number {
// return this.state.welcomeIndex;
// }
//
// getStartIndex(): number {
// return this.getWelcomeItems().length - 1;
// }
//
// getButtonTitle(): string {
// if (securityCardManager.securityCardActivating) {
// return TONLocalized.setup.main.securityCard.create;
// }
// const welcomeIndex = this.getWelcomeIndex();
// if (welcomeIndex === this.getStartIndex()) {
// return TONLocalized.setup.main.wallet.create;
// }
// return UILocalized.Next;
// }
//
// getTextButtonTitle(): string {
// if (securityCardManager.securityCardActivating) {
// return TONLocalized.setup.main.securityCard.restore;
// }
// const welcomeIndex = this.getWelcomeIndex();
// if (welcomeIndex === this.getStartIndex()) {
// return TONLocalized.setup.main.wallet.restore;
// }
// return UILocalized.Skip;
// }
//
// getTextButtonStyle(): ViewStyleProp {
// if (securityCardManager.securityCardActivating) {
// return [UIStyle.margin.topDefault(), UIStyle.margin.bottomHuge()];
// }
// return UIStyle.common.flex();
// }
//
// getButtonStyle(): ViewStyleProp {
// if (securityCardManager.securityCardActivating) {
// return {};
// }
// const welcomeIndex = this.getWelcomeIndex();
// if (welcomeIndex === this.getStartIndex()) {
// return UIStyle.common.flex3();
// }
// return UIStyle.common.flex();
// }
//
// getButtonTestID(): string {
// const welcomeIndex = this.getWelcomeIndex();
// if (welcomeIndex === this.getStartIndex()) {
// return 'create_wallet_button';
// }
// return 'next_welcome_button';
// }
//
// getTextButtonTestID(): string {
// const welcomeIndex = this.getWelcomeIndex();
// if (welcomeIndex === this.getStartIndex()) {
// return 'restore_wallet_button';
// }
// return 'skip_welcome_button';
// }
//
// areButtonsDisabled(): boolean {
// return !securityCardManager.securityCardActivating && !this.getWelcomeItems().length;
// }
//
// // Actions
// loadWelcomeItems() {
// (async () => {
// const welcomeItems = securityCardManager.securityCardActivating
// ? [
// {
// icon: TONAssets.icoStartItem(),
// ...TONLocalized.setup.start.securityCard,
// content: this.renderRestoreButton(UITextButton.Align.Left),
// },
// ]
// : [
// // ...(await WelcomeHelper.getWelcomeItems()),
// {
// icon: TONAssets.icoStartItem(),
// ...TONLocalized.setup.start.wallet,
// },
// ];
// this.setWelcomeItems(welcomeItems);
// })();
// }
//
// async startGenerateSeedPhrase() {
// this.setGeneratingSeedPhrase(true);
// await TONAsync.timeout(1);
// const seedPhrase = await TONKeystore.generateRandomSeed();
// this.setGeneratingSeedPhrase(false);
// this.navigateToCreateNewScreen(seedPhrase);
// }
//
// navigateToCreateNewScreen(seedPhrase: string) {
// this.navigateToNextScreen(WalletSetupScreens.SetLocalPassword, {
// seedPhrase,
// isNewWallet: true,
// });
// /* this.navigateToNextScreen('WalletSetupNewKeyView', {
// seedPhrase,
// isNewWallet: true,
// }); */
// }
//
// navigateToRestoreScreen() {
// this.navigateToNextScreen(WalletSetupScreens.RestorePhrase);
// }
//
// // render
// renderWelcomeView() {
// const welcomeItems = this.getWelcomeItems();
// return (<WalletWelcomeView
// ref={component => { this.welcomeView = component; }}
// items={welcomeItems}
// onIndexChange={index => this.setWelcomeIndex(index)}
// />);
// }
//
// renderCreateButton() {
// return (
// <UIButton
// testID={this.getButtonTestID()}
// title={this.getButtonTitle()}
// buttonSize={UIButton.ButtonSize.Large}
// buttonShape={UIButton.ButtonShape.Radius}
// style={this.getButtonStyle()}
// disabled={this.areButtonsDisabled()}
// showIndicator={this.isGeneratingSeedPhrase()}
// onPress={this.onButtonPress}
// />
// );
// }
//
// renderRestoreButton(align: string) {
// return (
// <UITextButton
// testID={this.getTextButtonTestID()}
// title={this.getTextButtonTitle()}
// align={align}
// buttonStyle={this.getTextButtonStyle()}
// disabled={this.areButtonsDisabled()}
// onPress={this.onTextButtonPress}
// />
// );
// }
//
// renderButtonsView() {
// if (securityCardManager.securityCardActivating) {
// return this.renderCreateButton();
// }
// return (
// <View style={UIStyle.Common.centerLeftContainer()}>
// {this.renderCreateButton()}
// <View style={styles.spaceSeparator} />
// {this.renderRestoreButton(UITextButton.Align.Center)}
// </View>
// );
// }
//
// renderSafely() {
// return (
// <View style={styles.container}>
// {this.renderWelcomeView()}
// {this.renderButtonsView()}
// </View>
// );
// }
// }
|
// const nodemailer = require("nodemailer");
import nodemailer from "nodemailer";
import { google } from "googleapis";
// const transporter = nodemailer.createTransport({
// service: "gmail",
// auth: {
// user: "sherbazkhan1408@gmail.com", //[process.env.FROM_EMAIL].toString(),
// pass: "********", //[process.env.FROM_EMAIL_PASS].toString(), // naturally, replace both with your real credentials or an application-specific password
// },
// });
export const sendMailToAdmin = async (orderDetails) => {
try {
const oAuth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
process.env.GOOGLE_REDIRECT_URI
);
oAuth2Client.setCredentials({
refresh_token: process.env.GOOGLE_REFRESH_TOKEN,
});
const accessToken = await oAuth2Client.getAccessToken();
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
type: "OAuth2",
user: process.env.FROM_EMAIL,
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
refreshToken: process.env.GOOGLE_REFRESH_TOKEN,
accessToken,
},
});
const {
user,
order,
orderItems,
shippingAddress,
itemsPrice,
taxPrice,
shippingPrice,
totalPrice,
} = orderDetails;
const mailOptionsAdmin = {
from: `${process.env.FROM_EMAIL_NAME} <${process.env.FROM_EMAIL}>`,
to: process.env.FROM_EMAIL, //, enemiesofenron@gmail.com",
subject: "New Order",
html: "",
};
mailOptionsAdmin.html = `<div>
<div>Customer: <b>${user.name} <b></div> <br/>
<div>Order Id: <b>${order._id}<b></div> <br/>
<div>
<h2>Order Items:</h2>
<table style="width:100%">
<thead>
<tr>
<th style="text-align: left;">Item Name</th><th style="text-align: left;">Quantity</th><th style="text-align: left;">Price</th>
</tr>
</thead>
<tbody>
${
orderItems &&
orderItems?.map(
(item) =>
`<tr>
<td style="text-align: left;">${item.name}</td><td style="text-align: center;">${item.qty}</td><td style="text-align: right;">${item.price}</td>
</tr>`
)
}
</tbody>
</table>
</div> <br/>
<div>Items Price: <b>${itemsPrice}<b></div> <br/>
<div>Shipping Price: <b>${shippingPrice}<b></div> <br/>
<div>Tax Price: <b>${taxPrice}<b></div> <br/>
<div>Shipping Address: <b>${shippingAddress.address} ${
shippingAddress.city
} ${shippingAddress.postalCode} ${
shippingAddress.country
}<b></div> <br/>
<h2>Total Price: <b>${totalPrice}<b></h2>
</div>`;
transporter.sendMail(mailOptionsAdmin, (error, info) => {
if (error) {
console.log("Error in Sending Email To Admin: " + error);
return "Error in Sending Email To Admin: " + error;
} else {
console.log("Email sent to Admin: " + info.response);
return "Email sent to Admin: " + info.response;
}
});
} catch (error) {
console.log("Catch: " + error);
return "Catch: " + error;
}
};
export const sendMailToCustomer = async (orderDetails) => {
try {
const oAuth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
process.env.GOOGLE_REDIRECT_URI
);
oAuth2Client.setCredentials({
refresh_token: process.env.GOOGLE_REFRESH_TOKEN,
});
const accessToken = await oAuth2Client.getAccessToken();
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
type: "OAuth2",
user: process.env.FROM_EMAIL,
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
refreshToken: process.env.GOOGLE_REFRESH_TOKEN,
accessToken,
},
});
const {
user,
order,
orderItems,
shippingAddress,
itemsPrice,
taxPrice,
shippingPrice,
totalPrice,
} = orderDetails;
const mailOptionsCustomer = {
from: `${process.env.FROM_EMAIL_NAME} <${process.env.FROM_EMAIL}>`,
to: user.email, //, enemiesofenron@gmail.com",
subject: "Thankyou For Your Order",
html: "",
};
mailOptionsCustomer.html = `<h1>Dear ${user.name}, Your Order Id is: ${
order._id
}</h1><br/>
<div>
<h2>Order Items:</h2>
<table style="width:100%">
<thead>
<tr>
<th style="text-align: left;">Item Name</th><th style="text-align: left;">Quantity</th><th style="text-align: left;">Price</th>
</tr>
</thead>
<tbody>
${
orderItems &&
orderItems?.map(
(item) =>
`<tr>
<td style="text-align: left;">${item.name}</td><td style="text-align: center;">${item.qty}</td><td style="text-align: right;">${item.price}</td>
</tr>`
)
}
</tbody>
</table>
<div>
<div>Items Price: <b>${itemsPrice}<b></div> <br/>
<div>Shipping Price: <b>${shippingPrice}<b></div> <br/>
<div>Tax Price: <b>${taxPrice}<b></div> <br/>
<div>Shipping Address: <b>${shippingAddress.address} ${
shippingAddress.city
} ${shippingAddress.postalCode} ${
shippingAddress.country
} <b></div> <br/>
<h2>Total Price: <b>${totalPrice}<b></h2> `;
transporter.sendMail(mailOptionsCustomer, (error, info) => {
if (error) {
console.log("Error in Sending Email To Customer: " + error);
} else {
console.log("Email sent to Customer: " + info.response);
}
});
} catch (error) {
console.log("Catch:" + error);
}
};
|
'use strict';
module.exports = {
async getFunctionsAndService() {
this.fcService = undefined;
this.fcFunctions = [];
await this.getService();
await this.getFunctions();
},
async getService() {
const serviceName = this.provider.getServiceName();
this.fcService = await this.provider.getService(serviceName);
},
async getFunctions() {
if (!this.fcService) {
return;
}
const serviceName = this.fcService.serviceName;
this.fcFunctions = await this.provider.getFunctions(serviceName);
}
};
|
import React, { Component } from 'react';
import { Menu, Container } from 'semantic-ui-react';
export default class WritingNav extends Component {
state = {}
handleItemClick = (e, { name }) => this.setState({ activeItem: name })
render() {
const { activeItem } = this.state
return (
<Menu pointing secondary vertical>
<Container>
<Menu.Item href="#WebsiteIntroduction" name='intro' active={activeItem === 'intro'} onClick={this.handleItemClick}>
Website Introduction
</Menu.Item>
<Menu.Item href="#Post2" name='post2' active={activeItem === 'post2'} onClick={this.handleItemClick}>
Post 2
</Menu.Item>
</Container>
</Menu>
)
}
}
|
import firebase from 'firebase'
import createCollection from '../util/create-collection'
const Games = createCollection(firebase, '/games')
const Players = createCollection(firebase, '/players')
const Guesses = createCollection(firebase, '/guesses')
// {
// games: {
// test: {
// words: [],
// maxUsers: 5,
// drawingTurn: 'ronaldo',
// sketch: {
// status: 'sketch_IDLE',
// position: { x: 0, y: 0 },
// color: 'black',
// thickness: 1
// }
// }
// },
//
// players: {
// test: {
// ronaldo: {
// points: 5
// },
// cleyson: {
// points: 10
// },
// },
// 'other-room': {
//
// }
// },
//
// guesses: {
// test: {
// g1: {
// message: 'monkey',
// sentAt: 1442536987
// },
// g2: {
// message: 'donkey',
// sentAt: 1442536999
// }
// }
// }
// }
export {
Games,
Players,
Guesses,
}
|
module.exports = {
root: true,
reportUnusedDisableDirectives: true,
env: {
node: true,
jest: true,
},
plugins: [
'@typescript-eslint',
],
extends: [
'airbnb-base',
'plugin:@typescript-eslint/recommended',
'@bessonovs/eslint-config',
'@bessonovs/eslint-config/typescript',
],
parser: '@typescript-eslint/parser',
parserOptions: {
project: [
'./tsconfig.json',
],
},
ignorePatterns: [
'.eslintrc.js',
],
rules: {
'arrow-body-style': 'off',
'lines-between-class-members': 'off',
'implicit-arrow-linebreak': 'off',
'no-restricted-syntax': 'off',
'object-curly-newline': [
'error',
{
ImportDeclaration: {
minProperties: 1,
multiline: true,
},
},
],
'@typescript-eslint/indent': [
'error',
'tab',
],
'import/no-useless-path-segments': 'error',
'import/no-cycle': 'error',
// doesn't work for central devDependencies
'import/no-extraneous-dependencies': 'off',
'import/extensions': [
'error',
'ignorePackages',
{
ts: 'never',
tsx: 'never',
},
],
},
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
},
},
},
overrides: [
{
files: ['**/*.js'],
rules: {
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
},
},
{
files: ['**/__tests__/**'],
rules: {
'@typescript-eslint/explicit-function-return-type': 'off',
},
},
{
files: ['**/*.ts', '**/*.d.ts'],
rules: {
indent: 'off', // ts has own rule: @typescript-eslint/indent
'no-useless-constructor': 'off',
},
},
],
}
|
/**
* @fileoverview Hook that runs a callback on unMount
* @author Gabriel Womble
*/
import { useEffect } from 'react';
function useUnmount(callback) {
useEffect(() => callback, []);
}
export { useUnmount };
|
var AWS = require('aws-sdk');
AWS.config.update({region: 'eu-central-1'});
const createTopic = async (topicName) => {
var createTopicPromise = new AWS.SNS({apiVersion: '2010-03-31'}).createTopic({Name: topicName}).promise();
// Handle promise's fulfilled/rejected states
createTopicPromise.then(
function(data) {
}).catch(
function(err) {
console.error(err, err.stack);
});
};
exports.createTopic = createTopic; |
import React, { useEffect, useState } from 'react';
import styles from './index.module.scss';
import cx from 'classnames';
import { Link } from 'dva/router';
// import { asideMenuConfig } from '@/config/menu';
function PageTab(props) {
const tab = [
{code: 'a', name: 'a'},
{code: 'b', name: 'b'}
]
const val = 'a'
useEffect(() => {
// console.log(1)
});
if(!tab)return null;
return (
<div className={styles.wrap}>
{
tab.map((item,index)=>{
return(
<Link
className={`${val === item.code ? styles.tabActive : ''}`}
key={index}
to={`/${item.code}`}
onClick={()=>{}}
>{item.name}</Link>
)
})
}
</div>
);
}
export default PageTab; |
import { all, fork } from 'redux-saga/effects';
import homeRoot from './home';
import es6promise from 'es6-promise';
es6promise.polyfill();
export default function* rootSaga() {
yield all([fork(homeRoot)]);
}
|
'use strict';
const OperationSurvey = require('entity/check_before_operation');
const Project = require('entity/project');
module.exports = function (req, res, next) {
if (req.params.project_id === Project.id) {
res.send([Object.assign({}, OperationSurvey, {project_id: Project.id})]);
} else {
res.send(404);
}
next();
};
|
import React, { Component } from "react";
import axios from "axios";
const APP_ID = "70f92be2ff3cdd0a4cc712e9fac9f1c0";
export default class Weather extends Component {
state = {
city: "",
weather: null
};
CancelToken = axios.CancelToken;
cancel = null;
cancelRequest = () => {
if (this.cancel) this.cancel();
this.cancel = null;
};
componentWillUnmount() {
this.cancelRequest();
}
getWeather = place => {
this.cancelRequest();
const lang = "pl";
const url = encodeURI(
`http://api.openweathermap.org/data/2.5/weather?q=${place}&appid=${APP_ID}&lang=${lang}&units=metric`
);
axios
.get(url, {
cancelToken: new axios.CancelToken(c => {
this.cancel = c;
})
})
.then(result => {
if (result.status === 200) {
const weather = { ...result.data };
console.log(weather);
this.setState({ weather, city: place });
}
})
.catch(err => {
console.error(
"Error while getting weather for ",
place,
". Error: ",
err
);
this.setState({ weather: null });
});
};
getIconUrl = icon => {
return `http://openweathermap.org/img/w/${icon}.png`;
};
render() {
if (this.props.place !== this.state.city) this.getWeather(this.props.place);
if (this.state.weather) {
console.log(
"Display weather for ",
this.state.city,
"\n",
this.state.weather
);
return (
<div id="wetherMainFrame">
<h6 className="badge m-2 badge-primary">{this.state.city}</h6>
<div>{this.state.weather.weather[0].description}</div>
<img
src={this.getIconUrl(this.state.weather.weather[0].icon)}
alt={this.state.weather.weather[0].main}
/>
<div>Temperature: {this.state.weather.main.temp}</div>
<div>Pressure: {this.state.weather.main.pressure}</div>
<div>Humidity: {this.state.weather.main.humidity}</div>
<div>Wind speed: {this.state.weather.wind.speed}</div>
</div>
);
}
return <div>Place no selected!</div>;
}
}
|
import {Grid} from "@material-ui/core";
const ContainerConfigurator = function ({component, form, setForm, resetForm, updateForm, ...props}) {
return (
<div>
<Grid container>
<Grid item xs={12}>
Hallo!
</Grid>
</Grid>
</div>
);
};
export default ContainerConfigurator;
|
// @flow
import { date, number } from "@lingui/core"
import I18nProvider from "./I18nProvider"
import Trans from "./Trans"
import { Plural, Select, SelectOrdinal } from "./Select"
import createFormat from "./createFormat"
import withI18n from "./withI18n"
const DateFormat = withI18n()(createFormat(date))
const NumberFormat = withI18n()(createFormat(number))
const i18nMark = (id: string) => id
export {
i18nMark,
withI18n,
I18nProvider,
Trans,
Plural,
Select,
SelectOrdinal,
DateFormat,
NumberFormat
}
|
import React from "react";
import Shifumi from "./cardsprojects/Shifumi";
import Memory from "./cardsprojects/Memory";
import Hangman from "./cardsprojects/Hangman";
import Terredegeek from "./cardsprojects/Terredegeek";
//i call the data.json file which is based on projetsFolder
//i map it, it means for every id inside the data.json, it will create div elements
//datajson structure : id-titre-contenu, to reach it : post.titre etc.
//post is a free parameter for data function, necessary to reach content of data.json
class Projets extends React.Component {
constructor (props) {
super (props);
}
render () {
return (
<div className="container-fluid d-flex flex-column py-4" id="projet">
<section id="mesprojets" className="container-fluid w-75 mx-auto">
<h2 className="text-center text-white pb-1 pt-4 w-75 mx-auto">Mes Projets</h2><hr className="hr w-100"></hr>
<div className="row py-4">
<Shifumi />
<Hangman />
<Terredegeek />
<Memory />
</div>
</section>
</div>
);
}
}
export default Projets;
// function Projets (){
// return (
// <div id="projet" className="project_list">
// <h2 id="mesprojets" className="text-center text-white pt-5">Mes projets<hr className="hr w-100"></hr></h2>
// {Data.map(post => {
// return (
// <div className="d-flex justify-content-center flex-row pt-5 text-center w-100">
// <div className="col-sm-6">
// <div className="card bg-secondary text-white">
// <div className="card-body">
// <h3 className="card-title">{post.titre}</h3>
// <p className="card-text">{post.contenu}</p>
// </div>
// </div>
// </div>
// </div>
// );
// })}
// </div>
// )
// }
// export default Projets;
|
function AddProduct() {
$.ajax({
type: "POST",
url: "/products/add",
data: $('#formAddProduct').serialize(),
success: function(msg){
$("#_successAlert").show().delay(5000).fadeOut();
$("#formAddProduct").trigger('reset');
},
error: function(jqXHR, textStatus, errorThrown) {
$("#_failAlert").html(jqXHR.responseText);
$("#_failAlert").show().delay(5000).fadeOut();
}
});
$('#modal').modal('hide');
}
|
$(document).ready(function(){
//create data
$('#create-task').submit(function(event){
event.preventDefault();
var form = $(this);
var formData = form.serialize();
$.ajax({
url : "create.php",
method : "POST",
data : formData,
success: function(data){
$("#ajax_msg").css("display","block").delay(3000).slideUp(300).html(data);
$("#name").val("");
$("#description").val("");
}
});
});
//read data
$("#task-list").load('read.php');
});
//editable both name and description in tasks.php
function editElement(div){
div.style.border = "1px solid lavender";
div.style.padding = "5px";
div.style.background = "white";
div.contentEditable = true;
}
//update name to db
function updateName(target,id){
var data = target.textContent;
target.style.border = "none";
target.style.padding = "0px;"
target.style.background = "#ececec";
target.contentEditable = false;
$.ajax({
url : "update.php",
method : "POST",
data : {
name:data,
id:id
},
success: function(data){
$("#ajax_msg").css("display","block").delay(3000).slideUp(300).html(data);
}
});
}
//update description to db
function updateDescription(target,id){
var data = target.textContent;
target.style.border = "none";
target.style.padding = "0px;"
target.style.background = "#ececec";
target.contentEditable = false;
$.ajax({
url : "update.php",
method : "POST",
data : {
description:data,
id:id
},
success: function(data){
$("#ajax_msg").css("display","block").delay(3000).slideUp(300).html(data);
}
});
}
//update Status
function updateStatus(target,id){
var data = target.textContent;
target.style.border = "none";
target.style.padding = "0px;"
target.style.background = "#ececec";
target.contentEditable = false;
$.ajax({
url : "update.php",
method : "POST",
data : {
status:data,
id:id
},
success: function(data){
$("#ajax_msg").css("display","block").delay(3000).slideUp(300).html(data);
}
});
}
//delete Element
function deleteElement(id,name){
if(confirm("Are you sure you want to delete " + name +" ?") ){
$.ajax({
url : "delete.php",
method : "POST",
data : {
id:id
},
success: function(data){
$("#ajax_msg").css("display","block").delay(3000).slideUp(300).html(data);
$("#task-list").load('read.php');
}
});
}
return false;
} |
import React, { PureComponent } from 'react';
import { Form, Input, Select, Cascader } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
class OpenCityForm extends PureComponent{
render(){
const { getFieldDecorator } = this.props.form;
const modalFormItemLayout = {
labelCol:{
span:5
},
wrapperCol:{
span:19
}
};
const residences = [
{
value: '浙江',
label: '浙江',
children: [{
value: '杭州',
label: '杭州'
}],
},{
value: '江苏',
label: '江苏',
children: [{
value: '南京',
label: '南京'
},{
value: '苏州',
label: '苏州'
}],
},{
value: '安徽',
label: '安徽',
children: [{
value: '合肥',
label: '合肥'
}],
}
];
return (
<Form layout="horizontal">
<FormItem label="选择城市" {...modalFormItemLayout}>
{
getFieldDecorator('city_name')(
<Cascader options={residences} style={{ width: 200 }}/>
)
}
</FormItem>
<FormItem label="用车模式" {...modalFormItemLayout}>
{
getFieldDecorator('mode',{
initialValue:'1'
})(
<Select style={{ width: 150 }}>
<Option value="0">全部</Option>
<Option value="1">指定停车点</Option>
<Option value="2">禁停区</Option>
</Select>
)
}
</FormItem>
<FormItem label="营运模式" {...modalFormItemLayout}>
{
getFieldDecorator('op_mode',{
initialValue:'1'
})(
<Select style={{ width: 100 }}>
<Option value="1">自营</Option>
<Option value="2">加盟</Option>
</Select>
)
}
</FormItem>
<FormItem label="城市管理员" {...modalFormItemLayout}>
{
getFieldDecorator('city_admin',{
initialValue:''
})(
<Input placeholder="请输入名称" style={{ width: 200 }}/>
)
}
</FormItem>
<FormItem label="城市管理员ID" {...modalFormItemLayout}>
{
getFieldDecorator('city_admin_id',{
initialValue:''
})(
<Input placeholder="请输入id" style={{ width: 200 }}/>
)
}
</FormItem>
</Form>
)
}
};
OpenCityForm = Form.create({})(OpenCityForm);
export default OpenCityForm; |
module.exports.PortfolioTransaction = class PortfolioTransaction {
constructor(
{
id, // (primary key) id of transaction
portfolioId, // (foreign key) id of portfolio the transaction belongs too
transactionType, // Type of transaction "BUY" || "SELL"
cryptoCurrencyId, // id of cryptocurrency
numberOfUnits, // quantity of the cryptocurrency
transactionValue, // total value of the cryptocurrency at time of transaction
transactionCost, // total transaction cost/price
transactionDate // date/time of transaction
}) {
this.id = `${id}`; // string
this.portfolioId = `${portfolioId}`; // string
this.transactionType = `${transactionType}`; // 'BUY' || 'SELL'
this.cryptoCurrencyId = `${cryptoCurrencyId}`; // string
this.numberOfUnits = (numberOfUnits + 0); // number
this.transactionValue = (transactionValue + 0); // number
this.transactionCost = (transactionCost + 0); // number
this.transactionDate = new Date(transactionDate); // date
}
};
|
<!doctype <!DOCTYPE html>
<html lang="en" ng-app="myLanguageApp">
<head>
<title>Angular JS Welcomoe!</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
</head>
<body>
<div ng-controller = "languages">
Select your Favourite Language
<button ng-click= "php()">php</button>
<button ng-click= "javascript()">Javascript</button>
<button ng-click= "cplus()">C++</button>
<button ng-click= "java()">Java</button>
<p>You have selected: {{myFavLanguage}}</p>
</div>
<script>
var application = angular.module('myLanguageApp', []);
application.controller("languages", function($scope) {
$scope.myFavLanguage = "none";
$scope.php = function(){
$scope.myFavLanguage = "Php";
};
$scope.javascript = function(){
$scope.myFavLanguage = "Javascript";
};
$scope.java = function(){
$scope.myFavLanguage = "Java";
};
$scope.cplus = function(){
$scope.myFavLanguage = "C++";
};
});
</script>
</body>
</html>
|
const nb1 = 1;
let nb2 = nb1;
nb2 = 2;
console.log(nb1); // 1
// const nb1 = 1 -> alloc (adresse mémoire 1234) [1]
// const nb2 = nb1 -> alloc (adresse mémoire 3456) [1]
// nb2 = 2; -> (adresse mémoire 3456) [2]
// console.log(nb1); // read (adresse mémoire 1234) [1]
const obj1 = { nb: 1 };
// const obj1 -> alloc (adresse mémoire 5432) [6543]
// { nb: 1 } -> alloc (adresse mémoire 6543) [{ nb: 1 }]
const obj2 = obj1; // -> alloc (adresse mémoire 9087) [6543]
obj2.nb = 2; // read (adresse mémoire 9087) [6543] -> [{ nb: 2 }]
console.log(obj1.nb); // 2 // read (adresse mémoire 9087) [6543] -> [{ nb: 2 }]
const array1 = [1];
const array2 = array1;
array2[0] = 2;
console.log(array1[0]); // 2
|
export class User {
id;
name;
email;
profilePath;
constructor(id, name, email, profilePath) {
this.id = id;
this.name = name;
this.email = email;
this.profilePath = profilePath;
}
} |
var EmployeeController = require('../controllers/EmployeeController');
module.exports = function (app) {
app.post('/employee/getLogin', function (req, res) { // Not Controller
EmployeeController.getLogin(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
app.post('/employee/getEmployeeBy', function (req, res) {
EmployeeController.getEmployeeBy(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
app.post('/employee/getEmployeeByEmployeeCode', function (req, res) {
EmployeeController.getEmployeeByEmployeeCode(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
app.post('/employee/insertEmployee', function (req, res) {
EmployeeController.insertEmployee(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
app.post('/employee/updateEmployeeByEmployeeCode', function (req, res) {
EmployeeController.updateEmployeeByEmployeeCode(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
app.post('/employee/deleteEmployeeByEmployeeCode', function (req, res) {
EmployeeController.deleteEmployeeByEmployeeCode(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
} |
const targetElement = document.querySelector('.cardSelectionButtons')
const eventHub = document.querySelector('.container')
export const CardSelect = () => {
targetElement.innerHTML = `
<button id="criminalsButton">Display All Criminals</button>
<button id="witnessesButton">Display All Witnesses</button>
<button id="facilitiesButton">Display All Facilities</button>`
}
eventHub.addEventListener("click", e => {
if (e.target.id === "criminalsButton") {
const cE = new CustomEvent("criminalsSelected")
eventHub.dispatchEvent(cE)
}
if (e.target.id === "witnessesButton") {
const cE = new CustomEvent("witnessesSelected")
eventHub.dispatchEvent(cE)
}
if (e.target.id === "facilitiesButton") {
const cE = new CustomEvent("facilitiesSelected")
eventHub.dispatchEvent(cE)
}
}) |
// # Задача 4
// Создайте класс `Countries` который при создании своего экземпляра принимает один параметр в с типом строка. Этот параметр будет служить API эндпоинтом.
// У класса `Countries` должен быть один метод `send` который должен возвращать промис.
// А принимает метод `send` один параметр который должен быть по типу `number` и который потом будет использоваться как значение для `GET` query-параметра `size`.
// **Обратите внимание**:
// 1. Метод `send` должен возвращать промис.
// 2. Использование `async & await` внутри класса **запрещено**.
// 3. Использование посторонних библиотек кроме библиотеки `fetch` **запрещено**
// 4. Если сервер ответил статус кодом `200` промис **должен** возвращать массив который содержит список объектов-стран.
// 5. В том случае если сервер ответил статус кодом не `200` промис **должен** генерировать ошибку с текстом `We have error, status code: ${statusCode}`
// 6. Генерировать ошибку если `url` по типу не строка.
// 7. Генерировать ошибку если методу `send` передать по типу не число.
// **В результате такой код должен работать**:
// ```javascript
// const get = require("fetch").fetchUrl;
// const url = "https://lab.lectrum.io/geo/api/countries";
// const countries = new Countries(url);
// (async () => {
// try {
// const data = await countries.send(2);
// console.log(data); // массив стран
// } catch (error) {
// console.log(error);
// }
// })();
// ```
// --------------------------------------- SOLUTION ---------------------------------------------------------
class Countries {
constructor(url) {
if (typeof url !== "string") {
throw new Error(`TypeError: ${url} should be a string`);
}
this.url = url;
}
send = number => {
if (typeof number !== "number") {
throw new Error(`TypeError: ${number} should be a number`);
}
const url = `${this.url}?size=${number}`;
const result = get(url).then(response => {
if (response.status !== 200) {
throw new Error(`We have error, status code: ${response.status}`);
}
const data = response.json();
return data;
});
return result;
};
}
|
function (doc) {
if (doc._id.substr(0,7) === "groups:") {
emit(doc._id.substr(7), {
"koolPet_Groups": doc.petGroups,
"koolPet_Name": doc.petName,
"gender": doc.genderVal,
"favorite_KoolPet": doc.favePet,
"koolness": doc.koolness,
"comments": doc.comments
});
}
}; |
import React, { Component } from "react";
import { Button, Card, TextField } from "@material-ui/core";
import { withSnackbar } from 'notistack';
const axios = require("axios");
class Login extends Component {
state = {
UNAME: "",
PASSWORD: "",
status: 0
};
componentDidMount() {
}
login = e => {
e.preventDefault();
var data = {
USER_ID: this.state.UNAME,
PASSWORD: this.state.PASSWORD
};
axios
.post("http://localhost:5000/project/loginCheck", data)
.then(res => {
if (res.data.status === 2) {
//alert("Enter correct crendentials");
this.props.enqueueSnackbar("Incorrecnt Credentials", {
variant: 'error',
});
} else {
if (res.data.role === 'A') {
this.props.enqueueSnackbar("Login Successfull", {
variant: 'success',
});
localStorage.setItem('user', this.state.UNAME);
localStorage.setItem('fullname', res.data.uname);
this.props.history.push("/coordinatorHome");
}
else {
this.props.enqueueSnackbar("Login Successfull", {
variant: 'success',
});
localStorage.setItem('user', this.state.UNAME);
localStorage.setItem('fullname', res.data.uname);
this.props.history.push("/facultyHome");
}
}
})
.catch(err => console.log(err));
};
UNAME = e => {
this.setState({ UNAME: e.currentTarget.value });
};
PASSWORD = e => {
this.setState({ PASSWORD: e.currentTarget.value });
};
render() {
console.log(localStorage.getItem('myValueInLocalStorage'));
return (
<div>
<Card style={{ width: "40%", marginLeft: "30%", marginTop: "10%" }}>
<TextField
label="User - ID"
variant="outlined"
onChange={e => this.UNAME(e)}
style={{ width: "80%", marginLeft: "10%", marginTop: 20 }}
/>
<br />
<TextField
type="password"
label="Password"
variant="outlined"
onChange={e => this.PASSWORD(e)}
style={{ width: "80%", marginLeft: "10%", marginTop: 20 }}
/>
<br />
<Button
variant="outlined"
style={{
marginTop: 20,
width: "30%",
marginLeft: "35%",
marginBottom: 20
}}
color="primary"
onClick={e => this.login(e)}
>
Login
</Button>
</Card>
</div>
);
}
}
export default withSnackbar(Login);
|
/**
* @author Mikael Emtinger
*/
ROME = {};
// animal
ROME.Animal = function(geometry, parseMorphTargetsNames) {
var result = ROME.AnimalAnimationData.init(geometry, parseMorphTargetsNames);
var that = {};
that.morph = 0.0;
that.animalA = {
frames: undefined,
currentFrame: 0,
lengthInFrames: 0,
currentTime: 0,
lengthInMS: 0,
timeScale: 1.0,
name: ""
};
that.animalB = {
frames: undefined,
currentFrame: 0,
lengthInFrames: 0,
currentTime: 0,
lengthInMS: 0,
timeScale: 1.0,
name: ""
};
that.availableAnimals = result.availableAnimals;
that.mesh = new THREE.MorphAnimMesh(geometry, result.material);
var isPlaying = false;
var morphTargetOrder = that.mesh.morphTargetForcedOrder;
var material = result.material;
//--- play ---
that.play = function(animalA, animalB, morph, startTimeAnimalA, startTimeAnimalB) {
if (!isPlaying) {
isPlaying = true;
that.morph = 0;
THREE.AnimationHandler.add(that);
}
animalB = animalB !== undefined ? animalB : animalA;
morph = morph !== undefined ? morph : 0;
setAnimalData(animalA, that.animalA);
setAnimalData(animalB, that.animalB);
that.animalA.currentTime = startTimeAnimalA ? startTimeAnimalA : 0;
that.animalB.currentTime = startTimeAnimalB ? startTimeAnimalB : 0;
that.update(0);
};
//--- update ---
that.update = function(deltaTimeMS) {
if (that.mesh._modelViewMatrix) {
var data, dataNames = ["animalA", "animalB"];
var d, dl;
var f, fl;
var frame, nextFrame;
var time, nextTime;
var unloopedTime;
var lengthInMS;
var lenghtInFrames;
var morphTarget;
var scale;
for (d = 0, dl = dataNames.length, morphTarget = 0; d < dl; d++) {
data = that[dataNames[d]];
unloopedTime = data.currentTime;
data.currentTime = (data.currentTime + deltaTimeMS * data.timeScale) % data.lengthInMS;
// did we loop?
if (unloopedTime > data.currentTime) {
data.currentFrame = 0;
}
// find frame/nextFrame
frame = 0;
for (f = data.currentFrame, fl = data.lengthInFrames - 1; f < fl; f++) {
if (data.currentTime >= data.frames[f].time && data.currentTime < data.frames[f + 1].time) {
frame = f;
break;
}
}
data.currentFrame = frame;
nextFrame = frame + 1 < fl ? frame + 1 : 0;
morphTargetOrder[morphTarget++] = data.frames[frame].index;
morphTargetOrder[morphTarget++] = data.frames[nextFrame].index;
time = data.frames[frame].time;
nextTime = data.frames[nextFrame].time > time ? data.frames[nextFrame].time : data.frames[nextFrame].time + data.lengthInMS;
scale = (data.currentTime - time) / (nextTime - time);
material.uniforms[dataNames[d] + "Interpolation"].value = scale;
}
material.uniforms.animalMorphValue.value = that.morph;
if (material.attributes[that.animalA.name] !== undefined) {
material.attributes.colorAnimalA.buffer = material.attributes[that.animalA.name].buffer;
}
if (material.attributes[that.animalB.name] !== undefined) {
material.attributes.colorAnimalB.buffer = material.attributes[that.animalB.name].buffer;
}
}
};
//--- set new target animal ---
that.setNewTargetAnimal = function(animal, startTimeAnimalB) {
if (that.morph === 1) {
// switch so B -> A
for (var property in that.animalA) {
that.animalA[property] = that.animalB[property];
}
// set new B and change morph
that.animalB.currentTime = startTimeAnimalB ? startTimeAnimalB : 0;
setAnimalData(animal, that.animalB);
setFrame(that.animalB);
that.morph = 0;
} else {
console.log("Error: Cannot change animal target if morph != 1. Skipping.");
}
};
//--- set animal data ---
var setAnimalData = function(name, data) {
if (ROME.AnimalAnimationData[name] !== undefined) {
data.frames = ROME.AnimalAnimationData[name];
data.lengthInFrames = data.frames.length;
data.lengthInMS = data.frames[data.lengthInFrames - 1].time;
data.name = name.toLowerCase();
data.normalsOffset = Math.floor(data.frames.length * 0.5, 10);
} else {
console.log("Error: Couldn't find data for animal " + name);
}
};
//--- set frame ---
var setFrame = function(data) {
var f, fl;
var currentTime = data.currentTime;
var frames = data.frames;
for (f = 0, fl < frames.length; f < fl; f++) {
if (currentTime >= frames[f].time) {
data.currentFrame = f;
return;
}
}
};
//--- set current frame ---
var setCurrentFrame = function(data) {
};
//--- return public ---
return that;
};
// shader
ROME.AnimalShader = {
uniforms: function() {
return THREE.UniformsUtils.merge([THREE.UniformsLib["common"],
THREE.UniformsLib["lights"], {
"animalAInterpolation": {
type: "f",
value: 0.0
},
"animalBInterpolation": {
type: "f",
value: 0.0
},
"animalMorphValue": {
type: "f",
value: 0.0
},
"scale": {
type: "f",
value: 1.0
},
"lightScale": {
type: "f",
value: 0.0
},
"lightOffset": {
type: "v3",
value: new THREE.Vector3(0.0, 0.0, 0.0)
},
}
]);
},
attributes: function() {
return {
"colorAnimalA": {
type: "c",
boundTo: "faces",
value: []
},
"colorAnimalB": {
type: "c",
boundTo: "faces",
value: []
}
}
},
vertexShader: [
"uniform float animalAInterpolation;",
"uniform float animalBInterpolation;",
"uniform float animalMorphValue;",
"attribute vec3 colorAnimalA;",
"attribute vec3 colorAnimalB;",
"varying vec3 vColor;",
"varying vec3 vLightWeighting;",
THREE.ShaderChunk["lights_pars_vertex"],
"uniform float lightScale;",
"uniform vec3 lightOffset;",
"void main() {",
"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
"vColor = mix( colorAnimalA, colorAnimalB, animalMorphValue );",
"vec3 animalA = mix( morphTarget0, morphTarget1, animalAInterpolation );",
"vec3 animalB = mix( morphTarget2, morphTarget3, animalBInterpolation );",
"vec3 morphed = mix( animalA, animalB, animalMorphValue );",
"vec3 transformedNormal = normalize( normalMatrix * normal );",
//THREE.ShaderChunk[ "lights_vertex" ],
// separate lights for animals
// ( ambient + one directional )
"vLightWeighting = vec3( 0.1 );",
"vec4 lDirection = viewMatrix * vec4( vec3( 1.0, -1.0, 0.0 ), 0.0 );",
"float directionalLightWeighting = dot( transformedNormal, normalize( lDirection.xyz ) ) * 0.5 + 0.5;",
"vLightWeighting += vec3( 1.0 ) * directionalLightWeighting;",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( morphed, 1.0 );",
"}"
].join("\n"),
fragmentShader: [
"uniform vec3 diffuse;",
"uniform float opacity;",
THREE.ShaderChunk["fog_pars_fragment"],
THREE.ShaderChunk["lights_pars_fragment"],
"varying vec3 vLightWeighting;",
"varying vec3 vColor;",
"void main() {",
"gl_FragColor = vec4( vLightWeighting, 1.0 );",
"gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
//"gl_FragColor = vec4( diffuse, 1.0 );",
//"gl_FragColor = gl_FragColor * vec4( diffuse, 1.0 );",
//"gl_FragColor = gl_FragColor * gl_FragColor;",
//"gl_FragColor = vec4( vColor, 1.0 );",
/*
"vec3 lightWeighting = vLightWeighting;",
"vec3 uBaseColor = vec3( 0.0 );",
"vec3 uLineColor1 = vColor;",
"vec3 uLineColor2 = 0.7 * vColor;",
"vec3 uLineColor3 = 0.5 * vColor;",
"vec3 uLineColor4 = 0.2 * vColor;",
"gl_FragColor = vec4( uBaseColor, 1.0 );",
"if ( length(lightWeighting) < 1.00 ) {",
"if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) {",
"gl_FragColor = vec4( uLineColor1, 1.0 );",
"}",
"}",
"if ( length(lightWeighting) < 0.75 ) {",
"if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) {",
"gl_FragColor = vec4( uLineColor2, 1.0 );",
"}",
"}",
"if ( length(lightWeighting) < 0.50 ) {",
"if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) {",
"gl_FragColor = vec4( uLineColor3, 1.0 );",
"}",
"}",
"if ( length(lightWeighting) < 0.3465 ) {",
"if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) {",
"gl_FragColor = vec4( uLineColor4, 1.0 );",
"}",
"}",
*/
THREE.ShaderChunk["fog_fragment"],
"}"
].join("\n")
}
// animation data
ROME.AnimalAnimationData = {
// static animal names (please fill in as it's faster than parsing through the geometry.morphTargets
animalNames: ["scorp", "tarbuffalo", "horse", "bear", "mountainlion", "deer", "fox", "goldenRetreiver", "seal", "chow", "raccoon", "bunny", "frog", "elk", "moose", "fishA", "fishB", "fishC", "fish", "sockPuppet", "shdw2", "blackWidow", "crab", "goat", "gator", "tarbuffalo_runB", "tarbuffalo", "wolf", "toad", "parrot", "eagle", "owl", "hummingBird", "flamingo", "stork", "butterflyA", "butterflyB", "butterflyC", "butterflyD", "butterflyLowA", "butterflyLowB", "butterflyLowC", "butterflyLowD", "vulture", "raven", "bison", "sickle"],
colorVariations: {
"armhand": {
hRange: 0.02,
sRange: 0.10,
vRange: 0.05,
hOffset: 0.00,
sOffset: 0.0,
vOffset: -0.1
},
"bearBlack": {
hRange: 0.00,
sRange: 0.10,
vRange: 0.075,
hOffset: 0.00,
sOffset: 0.00,
vOffset: -0.10
},
"bearBrown": {
hRange: 0.02,
sRange: 0.15,
vRange: 0.15,
hOffset: -0.01,
sOffset: 0.05,
vOffset: -0.15
},
"blackWidow": {
hRange: 0.02,
sRange: 0.10,
vRange: 0.05,
hOffset: 0.00,
sOffset: 0.0,
vOffset: -0.1
},
"bunny": {
hRange: 0.05,
sRange: 0.125,
vRange: 0.20,
hOffset: 0.00,
sOffset: -0.05,
vOffset: 0.00
},
"butterflyA": {
hRange: 0.02,
sRange: 0.10,
vRange: 0.15,
hOffset: 0.00,
sOffset: 0.00,
vOffset: 0.0
},
"butterflyB": {
hRange: 0.02,
sRange: 0.10,
vRange: 0.15,
hOffset: 0.00,
sOffset: 0.00,
vOffset: 0.0
},
"butterflyC": {
hRange: 0.02,
sRange: 0.10,
vRange: 0.15,
hOffset: 0.00,
sOffset: 0.00,
vOffset: 0.0
},
"butterflyD": {
hRange: 0.02,
sRange: 0.10,
vRange: 0.15,
hOffset: 0.00,
sOffset: 0.00,
vOffset: 0.0
},
"centipede": {
hRange: 0.05,
sRange: 0.00,
vRange: 0.55,
hOffset: 0.00,
sOffset: 0.10,
vOffset: -0.45
},
"chow": {
hRange: 0.025,
sRange: 0.15,
vRange: 0.10,
hOffset: 0.00,
sOffset: -0.1,
vOffset: -0.1
},
"cow": {
hRange: 0.00,
sRange: 0.00,
vRange: 0.20,
hOffset: 0.00,
sOffset: 0.05,
vOffset: -0.25
},
"cowCarcass": {
hRange: 0.00,
sRange: 0.00,
vRange: 0.00,
hOffset: 0.00,
sOffset: -0.10,
vOffset: 0.00
},
"crab": {
hRange: 0.07,
sRange: 0.00,
vRange: 0.15,
hOffset: -0.025,
sOffset: 0.15,
vOffset: -0.16
},
"deer": {
hRange: 0.03,
sRange: 0.15,
vRange: 0.25,
hOffset: -0.012,
sOffset: 0.05,
vOffset: 0.00
},
"eagle": {
hRange: 0.075,
sRange: 0.10,
vRange: 0.25,
hOffset: 0.00,
sOffset: 0.1,
vOffset: -0.05
},
"elk": {
hRange: 0.03,
sRange: 0.10,
vRange: 0.30,
hOffset: -0.0075,
sOffset: 0.00,
vOffset: -0.2
},
"fish": {
hRange: 0.00,
sRange: 0.00,
vRange: 0.20,
hOffset: 0.00,
sOffset: 0.00,
vOffset: 0.00
},
"flamingo": {
hRange: 0.1,
sRange: 0.15,
vRange: 0.25,
hOffset: -0.03,
sOffset: 0.1,
vOffset: -0.15
},
"fox": {
hRange: 0.03,
sRange: 0.15,
vRange: 0.25,
hOffset: -0.012,
sOffset: 0.05,
vOffset: 0.00
},
"frog": {
hRange: 0.05,
sRange: 0.10,
vRange: 0.25,
hOffset: 0.01,
sOffset: 0.05,
vOffset: -0.10
},
"gator": {
hRange: 0.05,
sRange: 0.00,
vRange: 0.20,
hOffset: -0.05,
sOffset: 0.00,
vOffset: -0.26
},
"goat": {
hRange: 0.02,
sRange: 0.07,
vRange: 0.1,
hOffset: 0.00,
sOffset: 0.00,
vOffset: -0.20
},
"goldenRetreiver": {
hRange: 0.025,
sRange: 0.2,
vRange: 0.05,
hOffset: 0.00,
sOffset: -0.1,
vOffset: 0.015
},
"horse": {
hRange: 0.025,
sRange: 0.1,
vRange: 0.25,
hOffset: -0.005,
sOffset: 0.00,
vOffset: -0.10
},
"hummingbird": {
hRange: 0.05,
sRange: 0.10,
vRange: 0.3,
hOffset: -0.02,
sOffset: 0.1,
vOffset: -0.30
},
"moose": {
hRange: 0.07,
sRange: 0.05,
vRange: 0.1,
hOffset: 0.00,
sOffset: -0.0,
vOffset: -0.2
},
"mountainlion": {
hRange: 0.02,
sRange: 0.10,
vRange: 0.15,
hOffset: 0.00,
sOffset: 0.10,
vOffset: -0.05
},
"owl": {
hRange: 0.025,
sRange: 0.4,
vRange: 0.15,
hOffset: -0.005,
sOffset: -0.3,
vOffset: -0.10
},
"panther": {
hRange: 0.00,
sRange: 0.10,
vRange: 0.075,
hOffset: 0.00,
sOffset: 0.00,
vOffset: -0.16
},
"parrot": {
hRange: 0.05,
sRange: 0.10,
vRange: 0.3,
hOffset: -0.025,
sOffset: 0.1,
vOffset: -0.10
},
"raccoon": {
hRange: 0.00,
sRange: 0.10,
vRange: 0.25,
hOffset: 0.6,
sOffset: -0.10,
vOffset: -0.2
},
"raven": {
hRange: 0.02,
sRange: 0.10,
vRange: 0.1,
hOffset: 0.00,
sOffset: 0.0,
vOffset: -0.1
},
"scorp": {
hRange: 0.00,
sRange: 0.10,
vRange: 0.075,
hOffset: 0.00,
sOffset: 0.00,
vOffset: -0.15
},
"seal": {
hRange: 0.00,
sRange: 0.00,
vRange: 0.05,
hOffset: 0.00,
sOffset: 0.05,
vOffset: -0.10
},
"shdw2": {
hRange: 0.0,
sRange: 0.10,
vRange: 0.0195,
hOffset: 0.0,
sOffset: -0.05,
vOffset: -0.112
},
// "shdw2": { hRange: 0.00, sRange: 0.10, vRange: 0.06,
// hOffset: 0.00, sOffset: -0.05, vOffset: -0.15 },
"sickle": {
hRange: 0.04,
sRange: 0.00,
vRange: 0.1,
hOffset: 0.00,
sOffset: -0.20,
vOffset: -0.30
},
"stork": {
hRange: 0.00,
sRange: 0.10,
vRange: 0.20,
hOffset: 0.02,
sOffset: -0.05,
vOffset: -0.05
},
"tarbuffalo": {
hRange: 0.04,
sRange: 0.10,
vRange: 0.1,
hOffset: -0.015,
sOffset: 0.0,
vOffset: -0.175
},
"toad": {
hRange: 0.07,
sRange: 0.00,
vRange: 0.1,
hOffset: -0.02,
sOffset: 0.0,
vOffset: -0.25
},
"vulture": {
hRange: 0.01,
sRange: 0.25,
vRange: 0.08,
hOffset: 0.0,
sOffset: -0.10,
vOffset: -0.16
},
"wolf": {
hRange: 0.00,
sRange: 0.2,
vRange: 0.06,
hOffset: -0.05,
sOffset: -0.15,
vOffset: -0.10
},
"zero": {
hRange: 0.00,
sRange: 0.00,
vRange: 0.00,
hOffset: 0.00,
sOffset: 0.00,
vOffset: 0.00
}
},
animalVariationMap: {
"armhand": "armhand",
"bearbrown": "bearBrown",
"bearblack": "bearBlack",
"blackwidow": "blackWidow",
"bunny": "bunny",
"butterflya": "butterflyA",
"butterflyb": "butterflyB",
"butterflyc": "butterflyC",
"butterflyd": "butterflyD",
"centipede": "centipede",
"chow": "chow",
"cow": "cow",
"cowcarcass": "cowCarcass",
"crab": "crab",
"deer": "deer",
"eagle": "eagle",
"elk": "elk",
"fisha": "fish",
"fishb": "fish",
"fishc": "fish",
"fishd": "fish",
"flamingo": "flamingo",
"fox": "fox",
"frog": "frog",
"gator": "gator",
"goat": "goat",
"goldenretreiver": "goldenRetreiver",
"horse": "horse",
"hummingbird": "hummingbird",
"moose": "moose",
"mountainlion": "mountainlion",
"mountainlionblack": "panther",
"owl": "owl",
"parrot": "parrot",
"raccoon": "raccoon",
"raven": "raven",
"scorpion": "scorp",
"seal": "seal",
"shdw": "shdw2",
"sickle": "sickle",
"stork": "stork",
"tarbuffalo": "tarbuffalo",
"toad": "toad",
"vulture": "vulture",
"wolf": "wolf",
"bison": "tarbuffalo"
},
// init frame times and indices
init: function(geometry, parseMorphTargetNames) {
if (!geometry.initialized) {
geometry.initialized = true;
var availableAnimals = [];
var animal, animalName;
var charCode, morphTargetName, morphTarget, morphTargets = geometry.morphTargets;
var a, al, m, ml, currentTime;
// add animal names to static list?
if (parseMorphTargetNames) {
for (m = 0, ml = morphTargets.length; m < ml; m++) {
// check so not already exists
for (a = 0, al = this.animalNames.length; a < al; a++) {
animalName = this.animalNames[a];
if (morphTargets[m].name.indexOf(animalName) !== -1) {
break;
}
}
// did not exist?
if (a === al) {
morphTargetName = morphTargets[m].name;
for (a = 0; a < morphTargetName.length; a++) {
charCode = morphTargetName.charCodeAt(a);
if (!((charCode >= 65 && charCode <= 90) ||
(charCode >= 97 && charCode <= 122))) {
break;
}
}
this.animalNames.push(morphTargetName.slice(0, a));
}
}
}
// parse out the names
for (a = 0, al = this.animalNames.length; a < al; a++) {
animalName = this.animalNames[a];
animal = this[animalName];
currentTime = 0;
if (animal === undefined || animal.length === 0) {
animal = this[animalName] = [];
for (m = 0, ml = morphTargets.length; m < ml; m++) {
if (morphTargets[m].name.indexOf(animalName) !== -1) {
animal.push({
index: m,
time: currentTime
});
currentTime += parseInt(1000 / 24, 10); // 24 fps
if (availableAnimals.indexOf(animalName) === -1) {
availableAnimals.push(animalName);
}
}
}
} else {
for (m = 0, ml = morphTargets.length; m < ml; m++) {
if (availableAnimals.indexOf(animalName) === -1 && morphTargets[m].name.indexOf(animalName) !== -1) {
availableAnimals.push(animalName);
}
}
}
}
// create material
var material = new THREE.MeshPhongMaterial({
color: 0xffffff,
specular: 0xffffff,
shininess: 20,
morphTargets: true,
morphNormals: true,
vertexColors: THREE.FaceColors,
shading: THREE.FlatShading
});
// set animal-specific light params
//console.log( attributes.colorAnimalA.value );
//console.log( availableAnimals );
// init custom attributes
//randomizeColors( attributes.colorAnimalA.value, variations );
//randomizeColors( attributes.colorAnimalB.value, variations );
// set return values
geometry.availableAnimals = availableAnimals;
geometry.customAttributes = material.attributes;
} else {
// create material
var material = new THREE.MeshShaderMaterial({
uniforms: ROME.AnimalShader.uniforms(),
attributes: {},
vertexShader: ROME.AnimalShader.vertexShader,
fragmentShader: ROME.AnimalShader.fragmentShader,
fog: true,
lights: true,
morphTargets: true
});
// copy custom attributes
for (var a in geometry.customAttributes) {
var srcAttribute = geometry.customAttributes[a];
if (a === "colorAnimalA" || a === "colorAnimalB") {
material.attributes[a] = {
type: "c",
size: 3,
boundTo: srcAttribute.boundTo,
value: srcAttribute.value,
array: undefined,
buffer: undefined,
needsUpdate: false,
__webglInitialized: true,
};
} else {
material.attributes[a] = srcAttribute;
}
}
}
return {
availableAnimals: geometry.availableAnimals,
material: material
};
}
};
function randomizeColors(colors, variations) {
var i, il, c, hd, sd, vd;
for (i = 0, il = colors.length; i < il; i++) {
c = colors[i];
hd = variations.hRange * Math.random() + variations.hOffset;
sd = variations.sRange * Math.random() + variations.sOffset;
vd = variations.vRange * Math.random() + variations.vOffset;
// THREE.ColorUtils.adjustHSV( c, hd, sd, vd );
}
}
function morphColorsToFaceColors(geometry) {
if (geometry.morphColors && geometry.morphColors.length) {
var colorMap = geometry.morphColors[0];
for (var i = 0; i < colorMap.colors.length; i++) {
geometry.faces[i].color = colorMap.colors[i];
}
}
}
|
const Main = require('./index')
test('すぬけ君は最大で何回操作を行うことができるかを求めてください.', () => {
expect(Main('3\n8 12 40')).toBe(2)
})
test('すぬけ君は最大で何回操作を行うことができるかを求めてください.', () => {
expect(Main('4\n5 6 8 10')).toBe(0)
})
test('すぬけ君は最大で何回操作を行うことができるかを求めてください.', () => {
expect(Main('6\n382253568 723152896 37802240 379425024 404894720 471526144')).toBe(8)
})
|
var elements = ["Characters: ", "Setting: ", "Theme: "];
//title
document.getElementById("title").innerHTML = "<h2>A Title You Think Better Suits the Story</h2";
//date
var d = new Date();
document.getElementById("date").innerHTML = "Date Posted: " + d.toDateString();
//names
var str = document.getElementById("names").innerHTML;
var txt = str.replace("Nino","Alonzo");
var txt2 = txt.replace("Taylor Swift","Katy Perry");
document.getElementById("names").innerHTML = txt2;
//upper
var text = document.getElementById("upper").innerHTML;
document.getElementById("upper").innerHTML = text.toUpperCase();
//parts
document.getElementById("characters").innerHTML = "<strong>" + elements[0] + "</strong>A waitress and a boy";
document.getElementById("setting").innerHTML = "<strong>" + elements[1] + "</strong>In a coffee shop";
document.getElementById("theme").innerHTML = "<strong>" + elements[2] + "</strong>Write your own theme of the story!";
|
// JavaScript Document
var elem_origin;
var elem_destino;
function comenzar(){
elem_origin = document.getElementById("imagen");
elem_origin.addEventListener("dragstart",comenzamos_arrastrar,false);
elem_destino= document.getElementById("zonadestino");
//elem_destino.addEventListener("gragenter",function(e){e.preventDefault();},false);
elem_destino.addEventListener("dragover",function(e){e.preventDefault();},false);
elem_destino.addEventListener("drop",soltado,false);
elem_origin.addEventListener("dragend",terminado,false); //cuando terminas jalar el evento sirve esto
elem_destino.addEventListener("dragenter",entrando,false);
elem_destino.addEventListener("dragleave",saliendo,false);
}
function comenzamos_arrastrar(e){
var codigo= "<img src='"+ elem_origin.getAttribute("src")+ "'>" ;
e.dataTransfer.setData("Text",codigo);
}
//sona destino
function soltado(e){
e.preventDefault();
elem_destino.innerHTML=e.dataTransfer.getData("Text");
}
function terminado(e){
var elemento= e.target;
elemento.style.visibility="hidden";
}
function entrando (e){
e.preventDefault();
elem_destino.style.background="red";
}
function saliendo(e){
e.preventDefault();
//elem_destino.style.background="#fff";
elem_destino.style.visibility="hidden";
}
window.addEventListener("load",comenzar,false);
/*
//var comienzo=elem_origin.addEventListener("dragstart",function(){alert("comenzo el evento");},false);
//var final=elem_origin.addEventListener("dragend",function(){alert("comenzo el evento");},false);
//var arrastrando = elem_origin.addEventListener("drag",function(){alert("tiempo de arrastrado");},false)
*/ |
'use strict'
////////////////////////////////////////////////////////////////////////////////
// Modules
////////////////////////////////////////////////////////////////////////////////
var gulp = require('gulp'); // Gulp.
var gutil = require('gulp-util'); // Gulp utilities.
var uglify = require('gulp-uglify'); // Uglify for JS.
var connect = require('gulp-connect'); // Webserver.
var sass = require('gulp-sass'); // SASS.
var webpack = require('webpack-stream'); // Webpack.
var minifycss = require('gulp-clean-css'); // Minify css.
var path = require('path');
////////////////////////////////////////////////////////////////////////////////
// Paths
////////////////////////////////////////////////////////////////////////////////
var srcPath = './src/';
var destPath = './dist/';
var modulesPath = './node_modules/';
////////////////////////////////////////////////////////////////////////////////
// Production/Development wrapper functions.
////////////////////////////////////////////////////////////////////////////////
var production = function(f) {
return gutil.env.env == 'production' ? f : gutil.noop()
};
var development = function(f) {
return gutil.env.env == 'development' ? f : gutil.noop()
};
////////////////////////////////////////////////////////////////////////////////
// Tasks.
////////////////////////////////////////////////////////////////////////////////
// JSX
gulp.task('jsx', function() {
gulp.src(srcPath + 'js/index.jsx')
.pipe(webpack({
resolve: {
root: [
path.resolve('./src/data')
]
},
module: {
loaders: [
{
test: /\.jsx$/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
},
output: {
filename: 'app.js'
}
}))
.pipe(production(uglify())) // Uglify in production only.
.pipe(gulp.dest(destPath + 'js/'))
.pipe(connect.reload());
});
// Compile .scss and move.
gulp.task('stylesheets', function() {
gulp.src(srcPath + 'css/**/*')
.pipe(sass().on('error', sass.logError))
.pipe(production(minifycss())) // Minify in production only.
.pipe(gulp.dest(destPath + 'css/'))
.pipe(connect.reload());
});
// Move .html.
gulp.task('html', function() {
gulp.src(srcPath + '*.html')
.pipe(gulp.dest(destPath))
.pipe(connect.reload());
});
////////////////////////////////////////////////////////////////////////////////
// Webserver
////////////////////////////////////////////////////////////////////////////////
gulp.task("webserver", function() {
connect.server({
root: 'dist',
livereload: true,
port: 8080
});
});
////////////////////////////////////////////////////////////////////////////////
// Watch task
////////////////////////////////////////////////////////////////////////////////
gulp.task('watch', function() {
gulp.watch(srcPath + 'js/**/*.jsx', ['jsx']); // JSX files.
gulp.watch(srcPath + 'css/**/*.scss', ['stylesheets']); // SASS Main.
gulp.watch(srcPath + 'css/**/_*.scss', ['stylesheets']); // SASS Partials.
gulp.watch(srcPath + '*.html', ['html']); // HTML
});
////////////////////////////////////////////////////////////////////////////////
// Default task
////////////////////////////////////////////////////////////////////////////////
gulp.task('default', ['watch', 'jsx', 'stylesheets', 'html','webserver']);
////////////////////////////////////////////////////////////////////////////////
// Build only task, no webserver or watch tasks.
////////////////////////////////////////////////////////////////////////////////
gulp.task('build', ['jsx', 'stylesheets', 'html']);
|
/* *****************************************************************************
* Name: Una Rúnarsdóttir
*
* Description: All the endpoints that are called in the front end.
* This is the query, what is called
* All the functionality is in the controller and is called in the endpoints.
*
* Written: 9/12/2020
* Last updated: 3/1/2021
*
*
**************************************************************************** */
let express = require('express');
let router = express.Router();
let upload = require('../config/multer.config.js');
const fileWorker = require('../controllers/file.controller.js');
/*
* get home
*/
router.get('/', fileWorker.home);
/*
* FILE pictures
* post photo in map with selected mapId
*/
router.post('/api/file/upload/:id', upload.single("file"), fileWorker.uploadFile);
/*
* FILE pictures
* get all photos in map with selected mapId
*/
router.get('/api/file/info/:mapId', fileWorker.listAllFiles);
/*
* FILE pictures
* post photo with selected id in map with selected mapId
*/
router.get('/api/file/:mapId/:id', fileWorker.downloadFile);
/*
* FILE pictures
* delete photo with selected id in map with selected mapId
*/
router.delete('/api/file/:mapId/:id', fileWorker.deleteFile)
/*
* FILE DESCRIPTION - one to one to every image
* creates photo description
*/
router.post('/api/file/description/upload', upload.single("file"), fileWorker.setFileDescription)
/*
* FILE DESCRIPTION - one to one to every image
* gets photo description with selected photoId and mapId
*/
router.get('/api/file/description/:mapId/:photoId', fileWorker.getFileDescription);
/*
* FILE DESCRIPTION - one to one to every image
* get all photo descriptions with selected mapId
*/
router.get('/api/files/getAllDescription/:mapId', fileWorker.listAllFileDescription);
/*
* FILE DESCRIPTION - one to one to every image
* updates photo description with selected photoId and mapId
*/
router.put('/api/files/update/:mapId/:photoId', fileWorker.updateFileDescription)
/*
* FILE DESCRIPTION - one to one to every image
* deletes photo description with selected photoId and mapId
*/
router.delete('/api/file/descriptions/delete/:mapId/:photoId', fileWorker.deleteFileDescription)
/*
* MAP - map with shows and every show has many photos
* create map
*/
router.post('/api/map/upload', upload.single("file"), fileWorker.uploadMap)
/*
* MAP - map with shows and every show has many photos
* get all maps in array
*/
router.get('/api/map/info', fileWorker.listAllMaps);
/*
* MAP - map with shows and every show has many photos
* delete map with the mapId
*/
router.delete('/api/map/:mapId', fileWorker.deleteMap)
/*
* MAP - map with shows and every show has many photos
* update map with the mapId
*/
router.put('/api/update/map/:mapId', fileWorker.updateMap)
/*
* USER
* create user
*/
router.post('/api/users', upload.single("file"), fileWorker.createUser);
/*
* USER
* post user
*/
router.post('/api/login', upload.single("file"), fileWorker.login);
/*
* CV
* create cv
*/
router.post('/api/cv/upload', upload.single("file"),upload.single("file"), fileWorker.uploadCV);
/*
* CV
* update cv
*/
router.put('/api/cv/update', upload.single("file"), upload.single("file"), fileWorker.updateCV);
/*
* CV
* get cv
*/
router.get('/api/cv', fileWorker.getCv);
/*
* COVER
* upload cover photo
*/
router.post('/api/cover/upload', upload.single("file"),upload.single("file"), fileWorker.uploadCover);
/*
* COVER
* update cover photo
*/
router.put('/api/cover/update', upload.single("file"), upload.single("file"), fileWorker.updateCover);
/*
* COVER
* get cover photo
*/
router.get('/api/cover', fileWorker.getCover);
/*
* SHOW COVER
* post show cover photo
*/
router.post('/api/showcover/upload', upload.single("file"),upload.single("file"), fileWorker.uploadShowCover);
/*
* SHOW COVER
* update show cover photo
*/
router.put('/api/showcover/update', upload.single("file"), upload.single("file"), fileWorker.updateShowCover);
/*
* SHOW COVER
* get show cover photo
*/
router.get('/api/showcover', fileWorker.getShowCover);
module.exports = router; |
/**
* Created by Administrator on 2018/5/19.
*/
$(function(){
//注册表单
$('#btt').click(function(){
var name=$('#uname').val(); //获得注册账号的值
var pas1=$('#pas1').val();//获得密码值
var pas2=$('#pas2').val();
//正则表达式
var reg= /^[A-Za-z0-9]+$/;
if( name===''||pas1===''||pas2===''){
alert('错误')
}else{
if(reg.test(name)&&name.length>=6){
if(reg.test(pas1)&&pas1.length>=6&&pas1.length<=12){
if(pas1===pas2){
localStorage.setItem('name',name);
localStorage.setItem('pas1',pas1);
$('#uname').val('');
$('#pas1').val('');
$('#pas2').val('');
}else{
alert('密码不一致')
}
}else{
alert('密码需大于6位小于12位')
}
}else{
alert('请输入正确6位以上账号名')
}
}
})
}) |
const chai = require('chai')
const chaiHttp = require('chai-http')
const assert = chai.assert
const server = require('../server.js')
chai.use(chaiHttp)
test('Server Test', function(done) {
chai.request(server)
.get('/spotify-auth')
.redirects(0)
.end(function(err, res) {
assert.equal(res.status, 302);
assert.isTrue(res.redirect)
done()
})
}) |
var exampleSocket;
var lastMsg;
var game;
function connect() {
if(exampleSocket != undefined && exampleSocket.readyState == 1) {
console.log("Already Connected");
return;
}
game = new Game();
exampleSocket = new WebSocket("ws://localhost:443");
exampleSocket.onmessage = function(event) {
if(processingUpdate) { return; }
//Recieve MSG and Update STAMP
lastMsg = JSON.parse(event.data).msg;
updateDate = new Date();
date.value = (updateDate.getHours() % 12) + ':' + updateDate.getMinutes() + ':' + updateDate.getSeconds();
};
exampleSocket.onclose = function(event) {
stopGame();
}
}
function disconnect() {
exampleSocket.close();
}
function eatFood() {
console.log("Ate Food");
sendMsg(encodeMsg(1, "Eating Food"));
}
function antHill() {
console.log("Attacking Anthill");
sendMsg(encodeMsg(2, "Attacking Hill"));
}
function encodeMsg(id, msg) {
var encodedMsg = {};
encodedMsg.id = id;
encodedMsg.msg = msg;
return JSON.stringify(encodedMsg);
}
function joinGame() {
console.log("Joined Game");
var names = ["Joe", "Jamie", "Johnathan", "Jesabel", "Jasmine", "Jack", "JoJo", "Jill", "Jabby", "Jessie", "TIM"];
sendMsg(encodeMsg(0, names[(Math.floor((Math.random() * 10) + 1))]));
}
function sendMsg(msg) {
exampleSocket.send(msg);
}
function updateFood(food) {
foods = food;
}
|
class UI {
constructor() {
this.humidity = document.getElementById('w-humidity');
this.feelsLike = document.getElementById('w-feels-like');
this.dewpoint = document.getElementById('w-dewpoint');
this.wind = document.getElementById('w-wind');
this.icon = document.getElementById('w-icon');
}
paint(weather) {
this.icon.setAttribute('src', 'https://www.metaweather.com/static/img/weather/s.svg');
this.humidity.textContent = weather.title;
this.feelsLike.textContent = weather.location_type;
this.dewpoint.textContent = weather.woeid;
this.wind.textContent = weather.latt_long;
}
} |
/**
* Created by wen on 2016/8/16.
*/
import React from 'react';
import SearchResult from './searchResult';
import {serverFetch} from '../../../utils/clientFetch';
export default {
path: '/searchResult',
async action({cookie,query,state}) {
let result = (state && state.list && {code:200,data:{list:state.list}}) || await serverFetch(cookie,'/articles/search',{page: 1,text: query.keywords,pagesize: 5});
if(result.code !== 200) result = {code:200,data: {list:[]}};
return <SearchResult query={query}
data={{...((state && state.defalultData ) || result)}}
state={state}
list = {result.data.list}/>;
}
};
|
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
VueRouter.prototype.animate = 0;
const Index = () => import(/* webpackChunkName: "index-test" */ '../pages/index.vue');
const Index_home = () => import(/* webpackChunkName: "index-test" */ '../component/layout/index.vue');
const Activity = () => import(/* webpackChunkName: "index-test" */ '../pages/activity.vue');
const My = () => import(/* webpackChunkName: "index-test" */ '../pages/my.vue');
const Info = () => import(/* webpackChunkName: "index-test" */ '../pages/info.vue');
const Setting = () => import(/* webpackChunkName: "index-test" */ '../pages/setting.vue');
const Find = () => import(/* webpackChunkName: "index-test" */ '../pages/find.vue');
const routerList = [
{
path: '/',
name: '首页',
meta: {iconType: 'icon-shouyefill'},
component: Index_home,
redirect: '/index',
children: [
{ path: 'index', component: Index, name: '首页' }
]
},
{
path: '/activity',
meta: {iconType: 'icon-gouwuche1'},
component: Index_home,
redirect: '/',
children: [
{ path: '/', component: Activity, name: '活动' }
]
},
{
path: '/find',
meta: {iconType: 'icon-zanfill'},
component: Index_home,
redirect: '/',
children: [
{ path: '/', component: Find, name: '发现' }
]
},
{
path: '/my',
meta: {iconType: 'icon-geren2'},
component: Index_home,
redirect: '/',
children: [
{ path: '/', component: My, name: '我的' }
]
},
{path: '/info', name: 'info', component: Info, meta: {slide: 1}},
{path: '/setting', name: 'setting', component: Setting, meta: {slide: 1}}
];
const router = new VueRouter({
routes: routerList
});
router.beforeEach((to, from, next)=>{
next();
})
router.afterEach((to, from)=>{
if (to.path === '/index' || to.path === '/my' || to.path === '/activity'){
return;
}
})
export default router;
|
import firebase from 'firebase/app';
import apiKeys from './helpers/apiKeys.json';
import authData from './helpers/data/authData';
import home from './components/home/home';
import login from './components/login/login';
import 'bootstrap';
import '../styles/main.scss';
const init = () => {
firebase.initializeApp(apiKeys.firebaseKeys);
authData.checkLoginStatus();
login.loginButton();
home.logoutEvent();
home.buildHomePage();
};
init();
|
import { createStackNavigator } from "@react-navigation/stack";
const RankingStack = createStackNavigator();
export default RankingStack;
|
var firebase = require('firebase');
require('firebase/auth');
require('firebase/firestore');
var db = require('./firebase'); //get reference to firebase config file
var express = require('express');
var router = express.Router();
var database = firebase.firestore(db.app); //declare database using app initialization in firebase.js
//DEPRECATED - MOVED TO reviews-controller, 3/31/2020
function createNewReview(date, rating, reviewBody, reviewedAsHost, reviewee, reviewer) {
console.log("createNewReview called");
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var newReviewRef = database.collection("reviews").doc();
var newReviewId = newReviewRef.id;
let setDoc = database.collection("reviews").doc(newReviewId).set({
date: date,
rating: rating,
reviewBody: reviewBody,
reviewedAsHost: reviewedAsHost,
reviewee: reviewee,
reviewer: reviewer
});
return setDoc.then(function() {
console.log("Document successfully written for review!");
});
} else {
// User is signed out.
// ...
}
});
}
router.post('/', function(req, res, next) {
console.log("API working for review page");
createNewReview(req.body.date, req.body.rating, req.body.reviewBody,
req.body.reviewedAsHost, req.body.reviewee, req.body.reviewer);
res.send("Review created!");
});
module.exports = router; |
function monitorArticleDetails_document(data, sectionTitle) {
$("#articleDetails .container").html(processing)
var articleInfo = data.data.results[0];
var articleTitle = (articleInfo.title) ? (articleInfo.title) : ""
var articleID = (articleInfo.id) ? (articleInfo.id) : ""
var itemID = (articleInfo.itemId)
var isBookMarked = (articleInfo.isBookmarked) ? (articleInfo.isBookmarked) : ""
var articleBookMarkInfo = ""
var articleUrl = (articleInfo.url) ? (articleInfo.url) : ""
var articleSource = (articleInfo.source) ? (articleInfo.source) : ""
var articleDate = (articleInfo.timestamp) ? (articleInfo.timestamp) : ""
articleDate = articleDate.split(201, 1)
var articleImage = (articleInfo.image) ? (articleInfo.image) : ""
var articleFavIcon = (articleInfo.favicon) ? (articleInfo.favicon) : ""
var articleSummary = (articleInfo.summary) ? (articleInfo.summary) : ""
var articleTweet = (articleInfo.extra.tweetList) ? (articleInfo.extra.tweetList) : ""
var articleTweetsTotal = articleTweet.length
var articleMatchedContent = (articleInfo.extra.matchedContentTypes) ? (articleInfo.extra.matchedContentTypes) : ""
var articleMatchedContentTypesTotal = articleMatchedContent.length
var articleMatchedCompany = (articleInfo.matchedCompanies) ? (articleInfo.matchedCompanies) : ""
var articleMatchedCompaniesTotal = articleMatchedCompany.length
var articleMatchedTopic = (articleInfo.matchedTopics) ? (articleInfo.matchedTopics) : ""
var articleMatchedTopicsTotal = articleMatchedTopic.length
var tweetArea = ""
var frContent = ""
if (String(sectionTitle) == "undefined") {
frContent += '<div class="item_header red"><span class="itemcounter"></span><span>FirstReads</span></div>'
}
else {
frContent += '<div class="item_header blue"><span class="itemcounter"></span><span>' + sectionTitle + '</span></div>'
}
frContent += '<div class="outer">'
frContent += '<div class="doc_content" >'
frContent += '<div class="doc_title">'
articleBookMarkInfo = (isBookMarked) ? "bookmark_active bookmark_common_h" : "bookmark bookmark_common_h"
frContent += '<div class="' + articleBookMarkInfo + '"calledFrom = "detailSection" docID = "' + articleID + '" itemID = "' + itemID + '"> </div>'
frContent += '<div class="titlearea">'
frContent += '<div class="title">' + articleTitle + '</div>'
frContent += '<div class="source"><span class="favicon"><img src="' + articleFavIcon + '" alt=""></span><span class="favicon_name">' + articleSource + '</span><span class="date">' + articleDate + '</span></div>'
frContent += '</div>'
frContent += '</div>'
frContent += '<div class="doc_summery">'
if (articleImage != "") {
frContent += '<span><img src="' + articleImage + '"/></span>'
}
frContent += articleSummary
frContent += '</div>'
if (articleTweetsTotal > 0) {
var tweetImg
var tweetTitle
frContent += '<div class="relatedtweet">'
frContent += '<div class="title">Related Tweet:</div>'
for (var i = 0; i < articleTweetsTotal; i++) {
tweetImg = (articleTweet[i].extra.userImage) ? (articleTweet[i].extra.userImage) : ""
tweetTitle = (articleTweet[i].title) ? (articleTweet[i].title) : ""
frContent += '<div class="tweet margin10 floatleft" onclick=\'callChildBrowser({url:"www.google.com"})\'>'
frContent += '<span class="tweet_img"><img src="' + tweetImg + '"></span>'
frContent += '<span>'
frContent += tweetTitle
frContent += '</span>'
frContent += '</div>'
}
frContent += '</div>'
}
frContent = articleMatchedCompanyInfo(articleMatchedTopicsTotal, frContent, articleMatchedTopic, "matchedTopic");
frContent = articleMatchedCompanyInfo(articleMatchedContentTypesTotal, frContent, articleMatchedContent, "matchedContent");
frContent = articleMatchedCompanyInfo(articleMatchedCompaniesTotal, frContent, articleMatchedCompany, "matchedCompany");
frContent += '</div>'
frContent += '<div class="documentActionButtons">'
frContent += '<span><input type="button" class="btn grey document" value="Email"></span>'
frContent += '<span><input type="button" class="btn grey document" value="Open"></span>'
frContent += '</div>'
//scrollDocumentDetails(".articleContainer", "#articleDetailsWrapper", "#articleDetailsScroller");
$("#articleDetails .container").addClass("margin37")
$("#articleDetails .container").html(frContent)
checkBookMarkItem("detailSection")
}
function callChildBrowser(url) {
PG_childBrowser(url)
}
function articleMatchedCompanyInfo(articleMatchedCompaniesTotal, frContent, articleMatchedCompany, calledFrom) {
if (articleMatchedCompaniesTotal > 0) {
var linkName = ""
var linkID = ""
var articleTitle = ""
switch (calledFrom) {
case 'matchedTopic':
articleTitle = "Topics MENTIONED:"
break;
case 'matchedContent':
articleTitle = "RELATED CONTENT:"
break;
case 'matchedCompany':
articleTitle = " COMPANIES:"
break;
default :
console.log("No operation for this event :(")
}
frContent += '<div class="relatedCompanies">'
frContent += '<div class="title">' + articleTitle + '</div>'
for (var articleMatchedCompanyType = 0; articleMatchedCompanyType < articleMatchedCompaniesTotal; articleMatchedCompanyType++) {
linkName = (calledFrom == "matchedContent") ? articleMatchedCompany[articleMatchedCompanyType].name : articleMatchedCompany[articleMatchedCompanyType].title
linkID = articleMatchedCompany[articleMatchedCompanyType].id
frContent += '<div class="company" onclick=\'search_keyword("' + linkName + '")\'>'
frContent += linkName
frContent += '</div>'
}
frContent += '</div>'
}
return frContent;
}
function monitorArticleDetails_tweet(data) {
var tweetInfo = data.data.results[0]
var relatedDoc = (tweetInfo.relatedDocs) ? (tweetInfo.relatedDocs) : ""
var relatedDocsTotal = (relatedDoc != "") ? relatedDoc.length : 0
var tweetTitle = (tweetInfo.title) ? (tweetInfo.title) : ""
var includedLink = (tweetInfo.url) ? (tweetInfo.url) : ""
var userImage = (tweetInfo.extra.userImage) ? (tweetInfo.extra.userImage) : ""
var tweetedBy = (tweetInfo.extra.description) ? (tweetInfo.extra.description) : ""
var screenName = (tweetInfo.extra.screenName) ? (tweetInfo.extra.screenName) : ""
var tweeterName = (tweetInfo.extra.name) ? (tweetInfo.extra.name) : ""
var timeLabel = (tweetInfo.extra.timeLabel) ? (tweetInfo.extra.timeLabel) : ""
var documentInfo = (tweetInfo.extra.document) ? (tweetInfo.extra.document) : ""
var documentTitle = (documentInfo.title) ? (documentInfo.title) : ""
var documentSource = (documentInfo.source) ? (documentInfo.source) : ""
var documentFavIcon = (documentInfo.favicon) ? (documentInfo.favicon) : ""
var documentFavImage = (documentInfo.image) ? (documentInfo.image) : ""
var documentFavSummary = (documentInfo.summary) ? (documentInfo.summary) : ""
var tweetedBy = (tweetInfo.extra.description) ? (tweetInfo.extra.description) : ""
var frContent = ""
frContent += '<div class="item_header tweet"><span class="itemcounter"></span><span>FirstTweets</span></div>';
frContent += '<div class="outer">';
frContent += '<div class="doc_content">';
frContent += '<div class="search_item_tweet no_bg">';
frContent += '<div>';
frContent += '<div class="tweet_img"><img src="' + userImage + '"></div>';
frContent += '<div>';
frContent += tweetTitle;
frContent += '</div>';
frContent += '</div>';
frContent += '<div class="source">';
frContent += '<span class="floatright"><span class="favicon"></span>'
frContent += '<span class="favicon_name">' + screenName + '</span>'
frContent += '</span>'
frContent += '<span class="floatleft date">' + timeLabel + '</span>';
frContent += '</div>';
frContent += '</div>';
if (includedLink != "") {
frContent += '<div class="includedlink">';
frContent += '<div class="title">included link:</div>';
frContent += '<div><a href="' + includedLink + '">' + includedLink + '</a></div>';
frContent += '</div>';
}
if (documentInfo != "") {
frContent += '<div class="doc_summery">'
frContent += '<div class="title">' + documentTitle + '</div>'
frContent += '<div class="source">'
frContent += '<span class="favicon"><img width="16" height="16" src="' + documentFavIcon + '" alt="source" /></span>'
frContent += '<span class="favicon_name">' + documentSource + '</span>'
frContent += '</div>'
frContent += '<div>'
frContent += documentFavSummary
frContent += '</div>'
frContent += '</div>'
}
frContent += '<div class="tweetedby">'
frContent += '<div class="title">tweetedby:</div>'
frContent += '<div>'
frContent += tweeterName + '<span class="socialmedia"> @' + screenName + '</span>'
frContent += '<span class="lightGrey">' + tweetedBy + '</span>'
frContent += '</div>'
frContent += '</div>'
if (relatedDocsTotal > 0) {
frContent += '<div class="relateddocuments ">'
frContent += '<div class="title">related documents:</div>'
for (var relatedDoc = 0; relatedDoc < relatedDocsTotal; relatedDoc++) {
frContent += '<div>'
frContent += '<div class="bold"><a href="#">Windows 7 and Google Android: The Safer OS</a></div>'
frContent += '<div> <img src=""> <span class="attribution">A little about</span></div>'
frContent += '</div>'
frContent += '</div>'
}
}
frContent += '</div>'
frContent += '<div class="documentActionButtons">'
frContent += '<span><input type="button" class="btn grey document" value="Email"></span>'
frContent += '<span><input type="button" class="btn grey document" value="Open"></span>'
frContent += '</div>'
frContent += '</div>'
$("#articleDetails .container").addClass("margin37")
$("#articleDetails .container").html(frContent)
}
function monitorArticleDetails_MT(data) {
var mtInfo = data.data.results[0];
var mtTitle = (mtInfo.title) ? (mtInfo.title) : "";
var mtRelatedCompaniesInfo = (mtInfo.matchedCompanies) ? (mtInfo.matchedCompanies) : "";
var mtRelatedCompaniesTotal = (mtRelatedCompaniesInfo != "") ? mtRelatedCompaniesInfo.length : 0
var mtRelatedCompanyTitle = ""
var mtTimeStamp = (mtInfo.timestamp) ? (mtInfo.timestamp) : "";
var mtDocSummary = "";
var mtDocTitle = "";
var mtDocSource = "";
var frContent = ""
if (mtTimeStamp != "") {
mtTimeStamp = mtTimeStamp.split(201, 1)
}
frContent += '<div class="item_header green"><span class="itemcounter"></span><span>Management Changes</span></div>'
frContent += '<div class="outer">'
frContent += '<div class="doc_content">'
frContent += '<div class="search_item no_bg pb5">'
frContent += '<div>'
frContent += '<div class="mt_img mtHireImage"></div>'
frContent += '<div>'
frContent += mtTitle
frContent += '</div>'
frContent += '</div>'
frContent += '<div class="cb10"></div>'
frContent += '<div class="source"><span class="date">' + mtTimeStamp + '</span></div>'
frContent += '</div>'
if (mtDocSummary != "") {
frContent += '<div class="doc_summery">'
frContent += '<div class="title">' + mtDocTitle + '</div>'
frContent += '<div class="source"><span class="favicon"></span>' + mtDocSource + '</div>'
frContent += '<div>'
frContent += mtDocSummary
frContent += '</div>'
frContent += '</div>'
}
if (mtRelatedCompaniesTotal > 0) {
frContent += '<div class="relatedCompanies">'
frContent += '<div class="title">related Companies</div>'
for (var mtRelatedCompany = 0; mtRelatedCompany < mtRelatedCompaniesTotal; mtRelatedCompany++) {
mtRelatedCompanyTitle = mtRelatedCompaniesInfo[mtRelatedCompany].title
frContent += '<div class="company">'
frContent += mtRelatedCompanyTitle
frContent += '</div>'
}
frContent += '</div>'
}
frContent += '</div>'
frContent += '<div class="documentActionButtons">'
frContent += '<span><input type="button" class="btn grey document" value="Email"></span>'
frContent += '<span><input type="button" class="btn grey document" value="Open"></span>'
frContent += '</div>'
frContent += '</div>'
$("#articleDetails .container").addClass("margin37")
$("#articleDetails .container").html(frContent)
}
function monitorArticleDetails_events(data) {
var eventInfo = data.data.results[0]
var eventTitle = eventInfo.title
var eventDate = eventInfo.timestamp
eventDate = eventDate.split(201, 1)
var eventClosingPrice = eventInfo.extra.closingPrice
var eventPrevClosingPrice = eventInfo.extra.previousClosingPrice
var eventTradingVolume = eventInfo.extra.tradingVolume
var eventPercentChange = eventInfo.extra.percentChange
var eventMV52Week = eventInfo.extra.avg52Week
var eventMV200Day = eventInfo.extra.avg200Day
var eventMV100Day = eventInfo.extra.avg100Day
var eventMV50Day = eventInfo.extra.avg50Day
var frContent = ""
frContent += '<div class="item_header green"><span class="itemcounter"></span><span>Major Stock and Financial Events</span></div>'
frContent += '<div class="outer">'
frContent += '<div class="doc_content">'
frContent += '<div class="search_item no_bg pb5">'
frContent += '<div>'
frContent += '<div class="mt_img mtstockup_Image"></div>'
frContent += '<div>'
frContent += eventTitle
frContent += '</div>'
frContent += '</div>'
frContent += '<div class="cb10"></div>'
frContent += '<div class="source"><span class="date">' + eventDate + '</span></div>'
frContent += '</div>'
frContent += '<div class="doc_relateditem_con">'
frContent += '<div class="title_red">Moving Averages:</div>'
frContent += '<div class="Averages_con">'
frContent += '<table CELLPADDING="4" CELLSPACING="0">'
frContent += '<tr class="bottomborder">'
frContent += '<td class="bottomborder">52 Week</td>'
frContent += '<td class="bottomborder">200 day</td>'
frContent += '<td class="bottomborder">100 day</td>'
frContent += '<td class="bottomborder">50 day</td>'
frContent += '</tr>'
frContent += '<tr>'
frContent += '<td><b>$' + eventMV52Week + '</b></td>'
frContent += '<td><b>$' + eventMV200Day + '</b></td>'
frContent += '<td><b>$' + eventMV100Day + '</b></td>'
frContent += '<td><b>$' + eventMV50Day + '</b></td>'
frContent += '</tr>'
frContent += '</table>'
frContent += '</div>'
frContent += '</div>'
frContent += '</div>'
frContent += '<div class="documentActionButtons">'
frContent += '<span><input type="button" class="btn grey document" value="Email"></span>'
frContent += '<span><input type="button" class="btn grey document" value="Open"></span>'
frContent += '</div>'
frContent += '</div>'
$("#articleDetails .container").addClass("margin37")
$("#articleDetails .container").html(frContent)
}
|
// Add parents to the data
// D3's stratify needs the parent directories, and sorted
function parentify(apiData){
parents = { '/' : ''}; // init with root directory
apiData.forEach(function(entry) {
filepath = entry.filepath;
while(filepath.indexOf('/') > 0) {
filepath = filepath.substring(0, filepath.lastIndexOf('/'));
parents[filepath] = parents[filepath] || ''; // Ruby ||=
}
});
for(parent in parents) {
apiData.push({
'filepath' : parent,
'id' : null,
'num_fixes' : null
});
}
apiData.sort(function(a,b){
return (a.filepath > b.filepath) ? 1 : ((b.filepath > a.filepath) ? -1 : 0);
});
return apiData;
}
// Given filepath data with parents, generate a cluster hierarchy
// Also: add up the values of each parent
function clusterify(data){
stratify = d3.stratify()
.parentId(function (d) {
if(d.filepath == '/') return null;
if(d.filepath.indexOf('/') > 0) { // non-root file
return d.filepath.substring(0, d.filepath.lastIndexOf('/'));
} else { //root file
return '/';
}
})
.id(function (d) {
return d.filepath;
});
root = stratify(data);
root.sum(function(d) { return d.num_fixes });
return root;
}
$( document ).ready( function() {
$.ajax({
url: "/api/filepaths?offenders=true",
dataType: 'json',
success: function(apiData) {
parentedData = parentify(apiData);
root = clusterify(parentedData);
console.log(root);
//Init SVG
var width = 700,
height = 700,
radius = Math.min(width, height) / 2;
var svg = d3.select("#offenders_map")
.append("svg:svg")
// svg width and height NOT set for responsiveness here!!
// viewBox is the internal coordinate system and then this
// scales to fit its container
.attr("viewBox", "0 0 " + width + " " + height)
.attr("preserveAspectRatio", "xMidYMid meet")
var g = svg.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
// Init scales for zooming
var x = d3.scaleLinear()
.range([0, 2 * Math.PI]);
var y = d3.scaleSqrt()
.range([0, radius]);
//Size the arcs
var partition = d3.partition()
partition(root)
var arc = d3.arc()
.startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x0))); })
.endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x1))); })
.innerRadius(function(d) { return Math.max(0, y(d.y0)); })
.outerRadius(function(d) { return Math.max(0, y(d.y1)); });
// Create color scheme
purpleScale = d3.interpolateRgb('#774b70','#ce6dbd')
var color = d3.scaleSequential(purpleScale)
.domain([0,root.height])
;
// Put it all together
$('#loading_map').remove();
g.selectAll('path')
.data(root.descendants())
.enter().append('path')
.attr("d", arc)
.style('stroke', '#de9ed6')
.style('stroke-width', '0.25px')
.style("fill", d => color(d.depth))
.on("click", clicked)
.on("mouseover", mouseovered)
;
// When we click on a particular path, we zoom in
function clicked(d) {
svg.transition()
.duration(750)
.tween("scale", function() {
var xd = d3.interpolate(x.domain(), [d.x0, d.x1]),
yd = d3.interpolate(y.domain(), [d.y0, 1]),
yr = d3.interpolate(y.range(), [d.y0 ? 20 : 0, radius]);
return function(t) { x.domain(xd(t)); y.domain(yd(t)).range(yr(t)); };
})
.selectAll("path")
.attrTween("d", function(d) { return function() { return arc(d); }; });
}
function mouseovered(d){
if(d.data.id) {
d3.select("#offenders_path")
.html("<a href=\"/filepaths/" +
d.data.id +
"\">" +
d.data.filepath +
"</a>"
);
} else {
d3.select("#offenders_path").html(d.data.filepath);
}
}
}
});
});
|
let txt = document.getElementById("txt");
let lastMassage = document.getElementById("last-massage");
let warn = document.getElementById("warn");
function send() {
lastMassage.innerHTML = txt.value;
if (txt.value === "") {
warn.style.display = "block";
} else {
warn.style.display = "none";
}
}
|
const Sequelize = require('sequelize');
const databaseManager = require('../user_modules/database-manager');
const userPhotoMap = require('./maps/user-photo.map');
module.exports = {};
const UserPhoto = databaseManager.context.define('userPhoto', {
Id: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
UserId: {
allowNull: false,
type: Sequelize.INTEGER
},
Data: {
type: Sequelize.BLOB('long')
},
Filename: {
allowNull: false,
type: Sequelize.STRING
},
MimeType: {
allowNull: false,
type: Sequelize.STRING
}
},{
instanceMethods: {
getMap: function() {
return UserPhoto.getMap();
}
},
});
/**
* Figures out how to serialize and deserialize this model
* @returns {Object}
*/
UserPhoto.getMap = function () {
return userPhotoMap;
};
module.exports = UserPhoto;
|
/*
* @Descripttion: 接口调用demo
* @Author: 王月
* @Date: 2020-09-16 13:46:58
* @LastEditors: Please set LastEditors
* @LastEditTime: 2020-11-18 15:32:13
*/
import service from './api';
// 获取AppId
export function GetWXAppId(data) {
return service({
url: `${baseApi}/Activity/GetWXAppId`,
method: 'GET',
data
});
}
// 服务器当前时间
export function GetServerTime(data) {
return service({
url: `${baseApi}/activity/GetServerTime`,
method: 'GET',
data
});
}
// 获取短网址
export function ShortUrl(data) {
return service({
url: `${baseApi}/activity/ShortUrl`,
method: 'GET',
data
});
}
// 获取jssdk
export function GetJSSDK(data) {
return service({
url: `${baseApi}/Activity/GetJSSDK`,
method: 'GET',
data
});
} |
'use strict'
const fs = require('fs')
// const employeeArray = require('?')
// employeeArray.forEach(emp =>
// {
//
// new employee
// })
class Employee {
constructor (name, title, salary) {
// TODO
this.name = name
this.title = title
this.salary = salary
}
static parseFromFilePath(filePath) //fileStream with JSON
{
let x = (JSON.parse(fs.readFileSync(filePath)))
return x.map(x => new Employee(x.name, x.title, x.salary))
}
promote(title, salary)
{
this.title = title
this.salary = salary
}
// TODO ???
}
// TODO ???
module.exports = {
Employee
}
|
const app = require('./server/server')
const Port = 5500
const carRoutes = require('./data/carRoutes')
app.use('/api/cars', carRoutes)
app.listen(Port, ()=>console.log('now running on ' + Port)) |
var stack;
var maxTake = Math.floor(stack/2);
var mode;
document.addEventListener("keyup", function(e){
if(e.keyCode == 13){
var playerInput = parseInt(Math.floor(document.getElementById("playerInput").value
));
if(mode == "Impossible"){
removeFromStackImpossible(playerInput);
}else if(mode == "Hard"){
removeFromStackHard(playerInput);
}else if(mode == "Medium"){
removeFromStackMedium(playerInput);
}else if(mode == "Easy"){
removeFromStackEasy(playerInput);
}else{
document.getElementById("playerNum").innerHTML = "Choose a mode first!";
}
console.log(stack);
document.getElementById("playerInput").value = "";
}
})
function startGameImpossible(){
stack = Math.ceil(Math.random()* 100);
maxTake = Math.floor(stack/2);
mode = "Impossible";
document.getElementById("maxTake").innerHTML = "The max you can take is: " + maxTake;
document.getElementById("stack").innerHTML = "Stack: " + stack;
}
function startGameHard(){
stack = Math.ceil(Math.random()* 100);
maxTake = Math.floor(stack/2);
mode = "Hard";
document.getElementById("maxTake").innerHTML = "The max you can take is: " + maxTake;
document.getElementById("stack").innerHTML = "Stack: " + stack;
}
function startGameMedium(){
stack = Math.ceil(Math.random()* 100);
maxTake = Math.floor(stack/2);
mode = "Medium";
document.getElementById("maxTake").innerHTML = "The max you can take is: " + maxTake;
document.getElementById("stack").innerHTML = "Stack: " + stack;
}
function startGameEasy(){
stack = Math.ceil(Math.random()* 100);
maxTake = Math.floor(stack/2);
mode = "Easy";
document.getElementById("maxTake").innerHTML = "The max you can take is: " + maxTake;
document.getElementById("stack").innerHTML = "Stack: " + stack;
}
function removeFromStackImpossible(playerNum){
if(playerNum > maxTake){
document.getElementById("compNum").innerHTML = "Enter a number that is less than or equal to " + maxTake;
}else{
stack -= playerNum;
if(2**6 < stack){
var numToGetTo = 63;
var compNum = stack - numToGetTo;
}else if (2**5 < stack){
var numToGetTo = 31;
var compNum = stack - numToGetTo;
}else if(2**4 < stack){
var numToGetTo = 15;
var compNum = stack - numToGetTo;
}else if(2**3 < stack){
var numToGetTo = 6;
var compNum = stack - numToGetTo;
}else if(2**2 < stack){
var numToGetTo = 3;
var compNum = stack - numToGetTo;
}else if(2**1 < stack){
var numToGetTo = 1;
var compNum = stack - numToGetTo;
}else{
maxTake = 0;
endGame();
return null;
}
stack -= compNum;
maxTake = Math.floor(stack/2);
display(compNum, playerNum);
}
}
function removeFromStackEasy(playerNum){
stack -= playerNum;
if(maxTake > 0){
var compNum = Math.ceil(Math.random()*maxTake);
stack -= compNum;
maxTake = Math.floor(stack/2);
}else{
maxTake = 0;
endGame();
return null;
}
display(compNum, playerNum);
}
function removeFromStackHard(playerNum){
}
function removeFromStackMedium(playerNum){
}
function display(compNum, playerNum){
document.getElementById("maxTake").innerHTML = "The max you can take is: " + maxTake;
document.getElementById("playerNum").innerHTML = "You took out: " + playerNum;
document.getElementById("compNum").innerHTML = "Computer took out: " + compNum;
document.getElementById("stack").innerHTML = "Stack: " + stack;
}
function endGame(){
if(maxTake == 0){
document.getElementById("maxTake").innerHTML = " ";
document.getElementById("playerNum").innerHTML = " ";
document.getElementById("compNum").innerHTML = " ";
document.getElementById("stack").innerHTML = "You lost! Start a New Game!";
}
} |
'use strict';
describe('Budget Demo App', function() {
var goButton = element(by.id('login'));
var submitLoginBtn = element(by.css('.bnt-submit-login'));
var loginView = element(by.css('.login-container'));
var email = element(by.model('vm.email'));
var pass = element(by.model('vm.pass'));
beforeEach(function() {
browser.get('http://localhost:8000/app/#/authentication');
expect(loginView.isPresent()).toBe(false);
goButton.click();
});
it('should have a title', function() {
expect(browser.getTitle()).toEqual('Budget Buddy');
});
it('should should open login page', function() {
expect(loginView.isPresent()).toBe(true);
});
it('should display invalid email error message if user enter invalid email address', function() {
email.sendKeys("wrong email");
pass.click();
var invalidEmail = element(by.id('valid-email'));
expect(invalidEmail.getText()).toEqual('Enter valid email address.');
});
it('it should dispaly required email message if email field is empty', function() {
email.sendKeys("");
pass.click();
var invalidEmail = element(by.id('required-email'));
expect(invalidEmail.getText()).toEqual('Email is required.');
});
it('it should dispaly required password message if pass field is empty', function() {
pass.sendKeys("");
email.click();
var invalidPass = element(by.id('required-pass'));
expect(invalidPass.getText()).toEqual('Password is required.');
});
});
|
'use-strict';
var rootPath = require('rfr');
var AppPath = rootPath('/app/appConfig');
var Exception = AppPath('/exceptions/baseException').Exception;
var mongoose = require('mongoose');
mongoose.Promise = require('q').Promise;
var opts = {
server: {
auto_reconnect: true
}
};
var command = null;
var createConnection = function(connectionString){
command = mongoose.connect(connectionString,opts);
return command;
};
var open = function(){
if(command){
command.open();
return true;
}
else{
var error = new Error('Connection is not created');
throw Exception(0,'connection',error,'-1000');
}
};
var close = function(){
if(command){
command.close();
return true;
}
else{
var error = new Error('Connection is not created');
throw Exception(0,'connection',error,'-1000');
}
};
var setCommand = function(db){
command = db;
}
var getCommand = function(){
return command
}
module.exports = {
CreateConnection : createConnection,
Open : open,
Close : close,
SetCommand : setCommand,
GetCommand : getCommand
} |
export { default } from "./UserEditForm";
|
import React from 'react'
import Header from '../components/Header'
import Footer from '../components/Footer'
import Head from '../components/Head'
import RegisterPanel from '../components/PersonalPage/Register'
const App = () => {
return (
<>
<Head title="General page" />
<Header />
<RegisterPanel />
<Footer />
</>
)
}
export default App
|
/**
* View Cart Page
*/
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Table, Input } from 'reactstrap';
import IconButton from '@material-ui/core/IconButton';
import Button from '@material-ui/core/Button';
import { Link } from 'react-router-dom';
// Card Component
import { RctCard, RctCardContent } from 'Components/RctCard';
//Actions
import { deleteItemFromCart, onChangeProductQuantity } from "Actions";
//Helper
import { textTruncate } from "Helpers/helpers";
// intl messages
import IntlMessages from 'Util/IntlMessages';
// page title bar
import PageTitleBar from 'Components/PageTitleBar/PageTitleBar';
class Carts extends Component {
onChangeQuantity(quantity, cartItem) {
if (quantity > 0) {
this.props.onChangeProductQuantity(quantity, cartItem);
}
}
//Get Total Price
getTotalPrice() {
const { cart } = this.props;
let totalPrice = 0;
for (const item of cart) {
totalPrice += item.totalPrice
}
return totalPrice.toFixed(2);
}
//Is Cart Empty
isCartEmpty() {
const { cart } = this.props;
if (cart.length === 0) {
return true;
}
}
render() {
const { cart, deleteItemFromCart, match } = this.props;
return (
<div className="cart-wrapper">
<PageTitleBar title={<IntlMessages id="sidebar.cart" />} match={match} />
<RctCard>
<RctCardContent noPadding>
<Table hover responsive className="mb-0">
<thead>
<tr>
<th className="w-10"></th>
<th className="w-50"><IntlMessages id="components.product" /></th>
<th className="w-10 text-center"><IntlMessages id="components.quantity" /></th>
<th className="w-10 text-center"><IntlMessages id="widgets.price" /></th>
<th className="w-10 text-center"><IntlMessages id="components.totalPrice" /></th>
<th className="w-10 text-center"><IntlMessages id="components.removeProduct" /></th>
</tr>
</thead>
<tbody>
{!this.isCartEmpty() ? cart.map((cart, key) => (
<tr key={key}>
<td className="w-10 text-center"><img src={cart.image} alt="products" className="media-object" width="100" height="100" /></td>
<td className="w-50">
<h3>{textTruncate(cart.name, 40)}</h3>
<span className="fs-14 d-block text-muted">{textTruncate(cart.description, 80)}</span>
<span className="fs-14 d-block text-muted">{cart.brand}</span>
</td>
<td>
<Input
type="number"
value={cart.productQuantity}
onChange={(e) => this.onChangeQuantity(e.target.value, cart)}
/>
</td>
<td className="text-danger text-center">$ {cart.price}</td>
<td className="text-bold text-center">$ {cart.totalPrice.toFixed(2)}</td>
<td className="text-center">
<IconButton onClick={() => deleteItemFromCart(cart)}>
<i className="zmdi zmdi-close"></i>
</IconButton>
</td>
</tr>
)) :
<tr>
<td colSpan="6" className="text-center h-25">
<span className="d-block font-5x mb-30 text-danger"><i className="zmdi zmdi-shopping-cart"></i></span>
<span className="mb-20 font-3x"><IntlMessages id="components.CartEmptyText" /></span>
</td>
</tr>
}
</tbody>
<tfoot>
<tr className="text-center">
<td colSpan="2"><Input type="text" placeholder="Enter Promo Code" /></td>
<td><Button variant="raised" color="secondary" className="text-white"><IntlMessages id="widgets.apply" /></Button></td>
<td><span className="font-weight-bold"><IntlMessages id="widgets.total" /></span></td>
<td><span className="font-weight-bold">$ {this.getTotalPrice()}</span></td>
<td>
<Button variant="raised" size="large" color="primary" className="text-white" component={Link} to="/app/ecommerce/checkout">
<IntlMessages id="components.checkout" />
</Button>
</td>
</tr>
</tfoot>
</Table>
</RctCardContent>
</RctCard>
</div>
)
}
}
const mapStateToProps = ({ ecommerce }) => {
const { cart } = ecommerce;
return { cart };
}
export default connect(mapStateToProps, {
deleteItemFromCart,
onChangeProductQuantity
})(Carts); |
/**
* Defines the material properties of some object: color, diffuse reflectance,
* specular reflectance, reflectivity, refractiveness, etc.
*/
function Material(cfg) {
this.color = new Color(cfg.color).mult(1 / 255);
this.diffuse = cfg.diffuse === undefined ? 0 : cfg.diffuse;
this.reflection = cfg.reflection === undefined ? 0 : cfg.reflection;
this.specular = cfg.specular === undefined ? 0 : cfg.specular;
this.specular_exp = cfg.specular_exp === undefined ? 0 : cfg.specular_exp;
this.ambient = cfg.ambient === undefined ? 0 : cfg.ambient;
// optional
if (cfg.checkerboard) {
this.checkerboard = new Color(cfg.checkerboard).mult(1 / 255);
}
if (cfg.refraction && cfg.refraction_index) {
this.refraction = cfg.refraction;
this.refraction_index = cfg.refraction_index;
}
};
/**
* Returns the color of the paterial at a specific point.
* Using this instead of directly accessing the color attribute allows for
* procedural textures etc to be generated
*/
Material.prototype.get_color = function(p) {
if (this.checkerboard) {
return (((Math.floor(p.x) + Math.floor(p.z)) % 2)
? this.checkerboard
: this.color);
}
return this.color;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.