text stringlengths 7 3.69M |
|---|
const fs = require('fs');
const path = require('path');
const process = require('process');
class FileReader {
stdout = process.stdout;
constructor(fileName) {
this.file = path.join(__dirname, fileName);
}
readFile() {
const readableStream = fs.createReadStream(this.file, 'utf-8');
readableStream.on('data', (chunk) => {
this.stdout.write(chunk)
});
}
sayGoodBye() {
process.on('exit', () => this.stdout.write('Good luck!\n'));
}
}
const fileReader = new FileReader('text.txt');
fileReader.readFile();
fileReader.sayGoodBye();
|
const Stage = require('./stage.schema');
const Race = require('../race/race.schema');
class StageService {
async getAllStages() {
return Stage.find({});
}
async getStageById(stageId) {
return Stage.findById(stageId);
}
async createNewStage(newStageProps) {
let newStage = new Stage(newStageProps);
newStage.save();
return newStage;
}
async editStageById(stageId, newProps) {
await Stage.updateOne(
{ _id: stageId },
{
$set: {
title: newProps.title,
description: newProps.description,
geolocation: newProps.geolocation,
},
},
);
return await Stage.findById(stageId);
}
async deleteStageById(stageId) {
await Race.deleteMany({ stageId: stageId });
await Stage.deleteOne({ _id: stageId });
return `Stage with id: ${stageId} was successfully removed`;
}
async addLeagueToStage(stageId, leagueId) {
const stage = await Stage.findById(stageId);
stage.league = leagueId;
await stage.save();
return stage;
}
}
module.exports = StageService;
|
const fetch = require("node-fetch")
fetch("https://api.ibs.it/se-questo-uomo-libro-primo-levi/e/9788806219352")
.then( res => res.json())
.then( res => console.log(res)) |
import { useState, useEffect } from "react";
import { useParams } from "react-router";
import { fetchCastById } from '../../services/apiService';
import styles from './styles.module.scss';
const CastView = () => {
const [apiResponse, setApiResponse] = useState(null);
const { movieId } = useParams()
useEffect(() => {
fetchCastById(movieId).then(({ cast }) => {
setApiResponse(cast.filter(cast => !cast.profile_path === false));
});
}, [movieId]);
return (
<ul className={styles.list}>
{apiResponse && apiResponse.map(actor => {
return (
<li key={actor.id} className={styles.item}>
<div className={styles.actorInfo}>
<img
src={`https://image.tmdb.org/t/p/w500${actor.profile_path}`}
alt={actor.original_name}
className={styles.cardImg}
/>
<span>{actor.original_name}</span>
</div>
</li>)
})}
</ul>
);
}
export default CastView; |
import React from "react";
import PageTemplate from "../templates/PageTemplate";
import ContactTemplate from "../templates/ContactTemplate";
const Contact = () => (
<PageTemplate>
<ContactTemplate />
</PageTemplate>
);
export default Contact;
|
function runTest()
{
FBTest.openNewTab(basePath + "css/6582/issue6582-1.html", function(win)
{
FBTest.openFirebug(function()
{
var panel = FBTest.selectPanel("stylesheet");
var locationButtons = FW.Firebug.chrome.$("fbLocationButtons");
FBTest.ok(locationButtons.getAttribute("collapsed") != "true",
"Location button must be visible");
FBTest.selectPanelLocationByName(panel, "issue6582-iframe.html");
// Remove iframe with the stylesheet.
FBTest.click(win.document.getElementById("removeIFrame"));
var locations = panel.getLocationList();
if (FBTest.compare(1, locations.length, "There must be one CSS file"))
{
var description = panel.getObjectDescription(locations[0]);
FBTest.compare("testcase.css", description.name,
"The current CSS file name must be correct");
}
FBTest.testDone();
});
});
}
|
//Base
import React, { Component } from 'react';
import './index.css';
class Map extends Component {
constructor(props) {
super(props);
this.state = {
lat: this.props.mapLat,
lng: this.props.mapLng
}
}
componentDidMount() {
const google = window.google;
let map,
marker;
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: this.state.lat, lng: this.state.lng},
zoom: 16,
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
fullscreenControl: false
});
marker = new google.maps.Marker({
map: map,
position: {lat: this.state.lat, lng: this.state.lng}
});
}
render() {
return (
<div id="map"></div>
)
}
}
export default Map; |
angular.module('boosted')
.controller('homeCtrl', function($scope,service, $state, $timeout) {
$scope.fadeIn = false;
$timeout(function(){
$scope.fadeIn = true;
} , 200)
});
|
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var WebhookIdSchema = new Schema({
channelId: {
type: String,
required: true
},
tag: String,
username: {
type: String,
required: true
},
avatarURL: {
type: String,
required: true
}
});
module.exports = mongoose.model("WebhookId", WebhookIdSchema);
|
import { product_list } from './views/product-list';
import { product_edit } from './views/product-edit';
var menu_data = [
{id: "product", icon: "gift", value: "Products", data:[
{ id: "productList", icon:'list', value: "View Products"},
{ id: "productEdit", icon:'edit', value: "Edit Products"}
]}
];
webix.ui({
id: "fullView",
cols:[
{ id:"sidebar", view: "sidebar", data: menu_data, on:{
onAfterSelect: function(id){
showView(id);
}
}
},
product_edit,
product_list
]
});
export function showView(id){
$$('fullView').getChildViews().forEach(function(view){
if (view.name!=='sidebar') view.hide();
});
$$(id).show();
$$("sidebar").select(id);
}
|
module.exports = function(mongoose) {
//var Schema = mongoose.Schema;
var schema = mongoose.Schema({
githubId : String
});
return mongoose.model('UserLogin',schema);
}
|
/** @file: enginesis.js - JavaScript interface for Enginesis SDK
* @author: jf
* @date: 7/25/13
* @summary: A JavaScript interface to the Enginesis API. This is designed to be a singleton
* object, only one should ever exist. It represents the data model and service/event model
* to converse with the server.
*
* git $Header$
*
**/
"use strict";
var enginesis = function (siteId, gameId, gameGroupId, enginesisServerStage, authToken, developerKey, languageCode, callBackFunction) {
var VERSION = '2.2.17';
var debugging = true;
var disabled = false; // use this flag to turn off communicating with the server
var errorLevel = 15; // bitmask: 1=info, 2=warning, 4=error, 8=severe
var useHTTPS = false;
var serverStage = null;
var serverHost = null;
var submitToURL = null;
var siteId = siteId || 0;
var gameId = gameId || 0;
var gameGroupId = gameGroupId || 0;
var languageCode = languageCode || 'en';
var syncId = 0;
var lastCommand = null;
var callBackFunction = callBackFunction;
var authToken = authToken;
var developerKey = developerKey;
var loggedInUserId = 0;
var requestComplete = function (enginesisResponseData, overRideCallBackFunction) {
var enginesisResponseObject;
//debugLog("CORS request complete " + enginesisResponseData);
try {
enginesisResponseObject = JSON.parse(enginesisResponseData);
} catch (exception) {
enginesisResponseObject = {results:{status:{success:0,message:"Error: " + exception.message,extended_info:enginesisResponseData.toString()},passthru:{fn:"unknown",state_seq:"0"}}};
}
enginesisResponseObject.fn = enginesisResponseObject.results.passthru.fn;
if (overRideCallBackFunction != null) {
overRideCallBackFunction(enginesisResponseObject);
} else if (callBackFunction != null) {
callBackFunction(enginesisResponseObject);
}
};
var sendRequest = function (fn, parameters, overRideCallBackFunction) {
var enginesisParameters = serverParamObjectMake(fn, parameters),
crossOriginRequest = new XMLHttpRequest();
if (typeof crossOriginRequest.withCredentials == undefined) {
debugLog("CORS is not supported");
} else if ( ! disabled) {
crossOriginRequest.onload = function(e) {
requestComplete(this.responseText, overRideCallBackFunction);
}
crossOriginRequest.onerror = function(e) {
debugLog("CORS request error " + crossOriginRequest.status + " " + e.toString());
// TODO: Enginesis.requestError(errorMessage); generate a canned error response (see PHP code)
}
// TODO: Need "GET", "PUT", and "DELETE" methods
crossOriginRequest.open("POST", submitToURL, true);
crossOriginRequest.overrideMimeType("application/json");
crossOriginRequest.send(convertParamsToFormData(enginesisParameters));
lastCommand = fn;
}
};
var serverParamObjectMake = function (whichCommand, additionalParameters) {
var serverParams = {
fn: whichCommand,
language_code: languageCode,
site_id: siteId,
game_id: gameId,
state_seq: ++ syncId,
response: "json"
};
if (loggedInUserId != 0) {
serverParams.logged_in_user_id = loggedInUserId;
}
if (additionalParameters != null) {
for (var key in additionalParameters) {
if (additionalParameters.hasOwnProperty(key)) {
serverParams[key] = additionalParameters[key];
}
}
}
return serverParams;
};
var convertParamsToFormData = function (parameterObject)
{
var key;
var formDataObject = new FormData();
for (key in parameterObject) {
if (parameterObject.hasOwnProperty(key)) {
formDataObject.append(key, parameterObject[key]);
}
}
return formDataObject;
};
var qualifyAndSetServerStage = function (newServerStage) {
switch (newServerStage) {
case '':
case '-l':
case '-d':
case '-q':
case '-x':
serverStage = newServerStage;
break;
default:
serverStage = ''; // anything we do not expect goes to the live instance
break;
}
serverHost = 'www.enginesis' + serverStage + '.com';
submitToURL = (useHTTPS ? 'https://' : 'http://') + serverHost + '/index.php';
return serverStage;
};
var debugLog = function (message, level) {
if (debugging) {
if (level == null) {
level = 15;
}
if (errorLevel & level > 0) { // only show this message if the error level is on for the level we are watching
console.log(message);
}
if (level == 9) {
alert(message);
}
}
};
qualifyAndSetServerStage(enginesisServerStage);
// =====================================================================
// this is the public interface
//
return {
ShareHelper: ShareHelper,
versionGet: function () {
return VERSION;
},
serverStageSet: function (newServerStage) {
return qualifyAndSetServerStage(newServerStage);
},
serverStageGet: function () {
return serverStage;
},
gameIdGet: function () {
return gameId;
},
gameIdSet: function (newGameId) {
return gameId = newGameId;
},
gameGroupIdGet: function () {
return gameGroupId;
},
gameGroupIdSet: function (newGameGroupId) {
return gameGroupId = newGameGroupId;
},
siteIdGet: function () {
return siteId;
},
siteIdSet: function (newSiteId) {
return siteId = newSiteId;
},
sessionBegin: function(gameKey, overRideCallBackFunction) {
return sendRequest("SessionBegin", {gamekey: gameKey}, overRideCallBackFunction);
},
userLogin: function(userName, password, overRideCallBackFunction) {
return sendRequest("UserLogin", {user_name: userName, password: password}, overRideCallBackFunction);
},
userLoginCoreg: function (userName, siteUserId, gender, dob, city, state, countryCode, locale, networkId, overRideCallBackFunction) {
return sendRequest("UserLoginCoreg",
{
site_user_id: siteUserId,
user_name: userName,
network_id: networkId
}, overRideCallBackFunction);
},
registeredUserCreate: function (userName, password, email, realName, dateOfBirth, gender, city, state, zipcode, countryCode, mobileNumber, imId, tagline, siteUserId, networkId, agreement, securityQuestionId, securityAnswer, imgUrl, aboutMe, additionalInfo, sourceSiteId, captchaId, captchaResponse, overRideCallBackFunction) {
captchaId = '99999';
captchaResponse = 'DEADMAN';
sendRequest("RegisteredUserCreate",
{
site_id: this.site_id,
captcha_id: captchaId,
captcha_response: captchaResponse,
user_name: userName,
site_user_id: siteUserId,
network_id: networkId,
real_name: realName,
password: password,
dob: dateOfBirth,
gender: gender,
city: city,
state: state,
zipcode: zipcode,
email_address: email,
country_code: countryCode,
mobile_number: mobileNumber,
im_id: imId,
agreement: agreement,
security_question_id: 1,
security_answer: '',
img_url: '',
about_me: aboutMe,
tagline: tagline,
additional_info: additionalInfo,
source_site_id: sourceSiteId
}, overRideCallBackFunction);
},
registeredUserForgotPassword: function (userName, email, overRideCallBackFunction) {
// this function generates the email that is sent to the email address matching username or email address
// that email leads to the change password web page
return sendRequest("RegisteredUserForgotPassword", {user_name: userName, email: email}, overRideCallBackFunction);
},
gameFind: function(game_name_part, overRideCallBackFunction) {
return sendRequest("GameFind", {game_name_part: game_name_part}, overRideCallBackFunction);
},
gameList: function(firstItem, numItems, gameStatusId, overRideCallBackFunction) {
return sendRequest("GameList", {first_item: firstItem, num_items: numItems, game_status_id: gameStatusId}, overRideCallBackFunction);
},
gameDataCreate: function (referrer, fromAddress, fromName, toAddress, toName, userMessage, userFiles, gameData, nameTag, addToGallery, lastScore, overRideCallBackFunction) {
return sendRequest("GameDataCreate", {
referrer: referrer,
from_address: fromAddress,
from_name: fromName,
to_address: toAddress,
to_name: toName,
user_msg: userMessage,
user_files: userFiles,
game_data: gameData,
name_tag: nameTag,
add_to_gallery: addToGallery ? 1 : 0,
last_score: lastScore
}, overRideCallBackFunction);
},
gameDataGet: function(gameDataId, overRideCallBackFunction) {
return sendRequest("GameDataGet", {game_data_id: gameDataId}, overRideCallBackFunction);
},
gameTrackingRecord: function (category, action, label, hitData, overRideCallBackFunction) {
// category = what generated the event
// action = what happened (LOAD, PLAY, GAMEOVER, EVENT, ZONECHG)
// label = path in game where event occurred
// data = a value related to the action, quantifying the action, if any
if (window.ga != null) {
// use Google Analytics if it is there (send, event, category, action, label, value)
ga('send', 'event', category, action, label, hitData);
}
return sendRequest("GameTrackingRecord", {hit_type: 'REQUEST', hit_category: category, hit_action: action, hit_label: label, hit_data: hitData}, overRideCallBackFunction);
}
};
};
/*
EnginesisServices.prototype.addOrUpdateVoteByURI = function(voteGroupURI, voteURI, voteValue) {
var data = this._serverParamObjectMake("AddOrUpdateVoteByURI");
data.vote_group_uri = voteGroupURI;
data.uri = voteURI;
data.vote_value = voteValue;
return this._sendRequest(data);
}
EnginesisServices.prototype.getNumberOfVotesPerURIGroup = function(voteGroupURI) {
var data = { fn: "GetNumberOfVotesPerURIGroup",
vote_group_uri: voteGroupURI,
site_id: this.site_id };
return this._sendRequest(data);
}
'GameImgUrl' => array(0, 0, 'GameImgUrl', null, 'site_id', 'logged_in_user_id', 'game_id', 'width', 'height', 'num'),
'GameImgGet' => array(0, 0, 'GameImgGet', null, 'site_id', 'logged_in_user_id', 'game_id', 'width', 'height', 'num'),
'GameListByCategory' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'num_items_per_category', 'game_status_id'),
'GameDataCreate' => array(0, 0, 'GameDataCreate', null, 'site_id', 'logged_in_user_id', 'game_id', 'referrer', 'from_address', 'from_name', 'to_address', 'to_name', 'user_msg', 'user_files', 'game_data', 'name_tag', 'add_to_gallery', '-last_score'),
'GameGet' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_id'),
'GameGetByName' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_name'),
'GameFindByName' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_name'),
'GameListList' => array(0, 0, null, null, 'site_id', 'logged_in_user_id'),
'GameListListGames' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_list_id'),
'GameListListGamesByName' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_list_name'),
'GameListByMostPopular' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'start_date', 'end_date', 'first_item', 'num_items'),
'GameListCategoryList' => array(0, 0, null, null, 'site_id', 'logged_in_user_id'),
'RecommendedGameList' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_id'),
'GameListListRecommendedGames' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_list_id'),
'GameFeatureList' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_id'),
'GameFeatureGet' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_id', 'sort_order'),
'GameTipList' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_id'),
'GameTipGet' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_id', 'sort_order'),
'GamePlayEventListByMostPlayed' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'start_date', 'end_date', 'num_items'),
'GamePlayEventCountByMostPlayed' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_id', 'start_date', 'end_date'),
'GamePlayEventCountByMostPlayedForGameGroup' => array(0, 0, null, null, 'site_id', 'logged_in_user_id', 'game_group_id', 'start_date', 'end_date'),
*/
|
var gulp = require('gulp'),
sass = require('gulp-ruby-sass'),
autoprefixer = require('gulp-autoprefixer'),
browserSync = require('browser-sync').create();
gulp.task('styles', function() {
return sass('app/scss/*.scss', { style: 'expanded' })
.pipe(autoprefixer('last 2 version'))
.pipe(gulp.dest('app/css/'))
});
gulp.task('default', ['styles'], function() {
browserSync.init({
server: "./app"
});
gulp.watch("app/scss/*.scss",['styles']);
gulp.watch("app/css/*.css").on('change', browserSync.reload);
gulp.watch("app/*.html").on('change', browserSync.reload);
gulp.watch("app/js/*.js").on('change', browserSync.reload);
});
gulp.task('browser-sync', function() {
browserSync.init({
server: {
baseDir: "./app"
}
});
});
|
var pageSize = 25;
Ext.define('gigade.EmsDepRe', {
extend: 'Ext.data.Model',
fields: [
{ name: "relation_id", type: "int" },
{ name: "relation_type", type: "int" },
{ name: "relation_order_count", type: "int" },
{ name: "relation_order_cost", type: "int" },
{ name: "relation_dep", type: "int" },
{ name: "update_time", type: "string" },
{ name: "create_time", type: "string" },
{ name: "relation_create_type", type: "int" },
{ name: "create_user", type: "int" },
{ name: "update_user", type: "int" },
{ name: "relation_year", type: "int" },
{ name: "relation_month", type: "int" },
{ name: "relation_day", type: "int" },
{ name: "dep_name", type: "string" },
{ name: "user_username", type: "string" },
]
});
var EmsDepReStore = Ext.create('Ext.data.Store', {
pageSize: pageSize,
model: 'gigade.EmsDepRe',
proxy: {
type: 'ajax',
url: '/EmsDepRelation/EmsDepRelationList',
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
}
}
});
EmsDepReStore.on('beforeload', function () {
Ext.apply(EmsDepReStore.proxy.extraParams,
{
dep_code: Ext.getCmp('depart').getValue(),
datatype: Ext.getCmp('datatype').getValue(),
// serchDate: Ext.getCmp('serchDate').getValue(),
date: Ext.getCmp('date').getValue(),
relation_type: Ext.getCmp('re_type').getValue(),
});
});
var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 2
});
var type = 2;
//頁面載入
Ext.onReady(function () {
var EmsDepRe = Ext.create('Ext.grid.Panel', {
id: 'EmsDepRe',
store: EmsDepReStore,
plugins: [cellEditing],
width: document.documentElement.clientWidth,
columns: [
{ header: "編號", dataIndex: 'relation_id', width: 60, align: 'center' },
{ header: '部門', dataIndex: 'dep_name', width: 150, align: 'center' },
{
header: '公關單類型', dataIndex: 'relation_type', width: 100, align: 'center', renderer: function (value) {
if (value == 1) {
return "公關單";
}
else if (value == 2) {
return "報廢單";
}
}
},
{ header: '年', dataIndex: 'relation_year', width: 100, align: 'center' },
{ header: "月", dataIndex: 'relation_month', width: 100, align: 'center' },
{ header: "日", dataIndex: 'relation_day', width: 100, align: 'center' },
{ header: "訂單成本", dataIndex: 'relation_order_cost', width: 100, align: 'center', editor: { xtype: 'numberfield', allowBlank: false, minValue: 0, allowDecimals: false } },
{ header: "訂單筆數", dataIndex: 'relation_order_count', width: 100, align: 'center', editor: { xtype: 'numberfield', allowBlank: false, minValue: 0, allowDecimals: false } },
{
header: '類型', dataIndex: 'relation_create_type', width: 100, align: 'center', renderer: function (value) {
if (value == 1) {
return "系統生成";
}
else if (value == 2) {
return "人工keyin";
}
}
},
{ header: '創建時間', dataIndex: 'create_time', width: 150, align: 'center' },
{ header: '創建人', dataIndex: 'user_username', width: 100, align: 'center' },
],
tbar: [
{ xtype: 'button', text: "新增", id: 'add', hidden: false, iconCls: 'icon-user-add', handler: onAddClick },
'->',
{
xtype: 'combobox', fieldLabel: "部門", id: 'depart', hidden: false, labelWidth: 50, store: EmsDepStore, displayField: 'dep_name',
valueField: 'dep_code', emptyText: '請選擇...',editable:false,
},
{
xtype: 'combobox', fieldLabel: "公關單類型", id: 're_type', hidden: false, labelWidth: 80, store: reTypeStore, displayField: 'txt',
valueField: 'value', emptyText: '請選擇...', margin: '0 0 0 5', editable: false,
},
{
xtype: 'combobox', fieldLabel: "類型", id: 'datatype', labelWidth: 50, store: typeStore, displayField: 'datatxt', valueField: 'datavalue',
value: '0', margin: '0 0 0 5', editable: false,value:'2',
},
//{
// xtype: 'combobox', fieldLabel: '查詢日期', id: 'serchDate', store: dateStore, value: 0, displayField: 'txt', labelWidth: 65,
// valueField: 'value', margin: '0 0 0 5', editable: false,
//},
{ xtype: 'datefield', id: 'date', fieldLabel: '查詢日期', hidden: false, value: new Date(), format: 'Y-m-d', editable: false,labelWidth:60,margin:'0 0 0 10' },
{ xtype: 'button', text: "查詢", id: 'query', hidden: false, handler: onQuery, iconCls: 'icon-search', },
{
xtype: 'button', text: "重置", id: 'reset', hidden: false, iconCls: 'ui-icon ui-icon-reset',
handler: function () {
Ext.getCmp('depart').setValue('');
// Ext.getCmp('serchDate').setValue(0);
Ext.getCmp('date').setValue(new Date());
Ext.getCmp('datatype').setValue('2');
Ext.getCmp('re_type').setValue('0');
}
},
],
bbar: Ext.create('Ext.PagingToolbar', {
store: EmsDepReStore,
pageSize: pageSize,
displayInfo: true,
displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}',
emptyMsg: NOTHING_DISPLAY
}),
listeners: {
scrollershow: function (scroller) {
if (scroller && scroller.scrollEl) {
scroller.clearManagedListeners();
scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller);
}
},
edit: function (editor, e) {
if (e.record.data.relation_create_type == 1) {
Ext.Msg.alert("提示信息", "此爲系統自動生成,所做更改無效!");
EmsDepReStore.load();
}
else {
//如果編輯的是轉移數量
var relation_id = e.record.data.relation_id;
var EmsDep = e.field;
var value = e.value;
if (e.field == "relation_order_cost" || e.field == "relation_order_count") {
if (e.value != e.originalValue) {
Ext.Ajax.request({
url: '/EmsDepRelation/EditEmsDepR',
params: {
relation_id: relation_id,
emsDep: EmsDep,
value: value
},
success: function (response) {
var res = Ext.decode(response.responseText);
if (res.success) {
Ext.Msg.alert("提示信息", "保存成功!");
EmsDepReStore.load();
}
else {
Ext.Msg.alert("提示信息", "保存失敗!");
EmsDepReStore.load();
}
}
});
}
}
}
}
},
viewConfig: {
forceFit: true,
getRowClass: function (record, rowIndex, rowParams, store) {
if (record.data.relation_create_type == 1) {
return 'ems_actual_type';//注意这里返回的是定义好的css类;列如:(.ppp_ddd_sss div{background-color:red})定义到你页面访问到的css文件里。
}
}
}
});
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: [EmsDepRe],
renderTo: Ext.getBody(),
autoScroll: true,
listeners: {
resize: function () {
EmsDepRe.width = document.documentElement.clientWidth;
this.doLayout();
}
}
});
// EmsDepReStore.load({ params: { start: 0, limit: 25 } });
});
onAddClick = function () {
editFunction(null, EmsDepReStore);
}
onQuery = function () {
Ext.getCmp('EmsDepRe').store.loadPage(1, {
params: {
dep_code: Ext.getCmp('depart').getValue(),
datatype: Ext.getCmp('datatype').getValue(),
// serchDate: Ext.getCmp('serchDate').getValue(),
date: Ext.getCmp('date').getValue(),
relation_type: Ext.getCmp('re_type').getValue(),
}
});
}
|
import React from 'react'
import {Navbar, NavItem, NavLink, Nav, NavbarBrand} from 'reactstrap'
import Carro from './Carro'
class Navegacion extends React.Component {
render(){
return(
<Navbar color= 'light' light expand='sm'>
<NavbarBrand href='/'>{this.props.titulo}</NavbarBrand>
<Nav className='ml-auto' navbar>
<NavItem>
<Carro/>
</NavItem>
</Nav>
</Navbar>
);
}
}
export default Navegacion; |
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import lozad from 'lozad';
class LazyImage extends PureComponent {
observer;
componentDidMount() {
const { rootMargin } = this.props;
this.observer = lozad(this.img, {
rootMargin,
threshold: 0.01,
});
this.observer.observe();
}
componentDidUpdate() {
this.img.removeAttribute('data-loaded');
this.observer.triggerLoad(this.img);
}
applyRef = ref => {
this.img = ref;
};
onErrorEvent(event) {
event.target.classList.add('onError');
}
onLoadEvent(event) {
event.target.classList.add('onLoad');
}
render() {
const { data, alt, width, height } = this.props;
return (
<img
height={height || 'initial'}
width={width || 'initial'}
data-src={data}
data-iesrc={data}
alt={alt}
ref={this.applyRef}
onError={this.onErrorEvent}
onLoad={this.onLoadEvent}
/>
);
}
}
LazyImage.defaultProps = {
rootMargin: '0px 512px 0px 512px',
};
LazyImage.propTypes = {
width: PropTypes.string,
height: PropTypes.string,
data: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
srcset: PropTypes.string,
otherProps: PropTypes.shape({}),
rootMargin: PropTypes.string,
};
export default LazyImage;
|
export const DEFAULT_ORDER = 101; |
import React from 'react';
import {Link} from 'react-router-dom';
/**
* Cards to display businesses
* show business name and a button that links to
* view all business details
*
*/
const Cards = (props) =>{
const businesses = props.businesslist;
return(
<div className="row" style={{marginLeft:'25%'}}>
{businesses.map(business =>
<div className="card col-md-5" key={business.id} style={{ margin:"2%", display:"inline-block", backgroundColor:"#DCDCDC"}} >
<div className>
<div >
<div className="card-body" style={{}}>
<h4 className="card-title">{business.business_name}</h4>
<p className="card-text">{business.category}</p>
<Link to={`/businesses/${business.id}`} className="btn btn-secondary btn-sm">View Details</Link>
</div>
</div>
</div>
</div>
)}
</div>
);
}
export default Cards;
|
class Variavel {
constructor(val,peso){
this._valor=Number(val);
this._peso=Number(peso);
}
get valor(){
return this._valor;
}
set valor(val){
this._valor=Number(val);
}
get peso(){
return this._peso;
}
set peso(val){
this._peso=Number(val);
}
}
// function knapsack(tamanho,pesos,valores){
function knapsack(tamanho,vars){
n = Number(vars.length);
tamanho=Number(tamanho);
knap = Array();
// p = pesos.map(function(x){
// return Number(x);
// });
// v = valores.map(function(x){
// return Number(x);
// });
p = vars.map(function(x){
return Number(x.peso);
});
v = vars.map(function(x){
return Number(x.valor);
});
for(var i=0;i<n+1;i++){
var aux = Array();
for(var j=0;j<tamanho+1;j++){
aux.push(0);
}
knap.push(aux);
}
for(var i=0;i<n+1;i++){
for(var w=0;w<tamanho+1;w++){
if(i==0 || w==0){
knap[i][w]=0;
}
else if(p[i-1] <= w){
knap[i][w]=Math.max(v[i-1] + knap[i-1][w-p[i-1]],knap[i-1][w]);
//console.log(v[i-1],knap[i-1][w-p[i-1]],knap[i-1][w]);
//console.log(i-1,w-p[i-1],w,p[i-1]);
}
else{
knap[i][w]= knap[i-1][w];
}
}
}
// console.log(knap);
return {'r':knap[n][tamanho],'tb':knap};
}
|
import React from 'react';
import { Container, Title, Dados, Label, Line } from './styles';
function PersonDados (){
return (
<Container>
<Title>Seus Dados</Title>
<Label>Nome:</Label>
<Line>
<Dados>Jessica dos SantosLima</Dados>
</Line>
<Label>CPF:</Label>
<Line>
<Dados>***.***.***-*</Dados>
</Line>
<Label>Celular:</Label>
<Line>
<Dados>(11)9 58648-55647</Dados>
</Line>
<Label>E-Mail:</Label>
<Line>
<Dados>jessicadoslima@gmail.com</Dados>
</Line>
</Container>
);
};
export default PersonDados;
|
var inputs = document.getElementsByTagName("input");
var username = inputs[0];
var email = inputs[1];
var number = inputs[2];
username.pattern = "[a-zA-Z ]*";
email.pattern = "([a-zA-Z0-9\.]*)(@)([a-zA-Z]*)(\.)([a-zA-Z]*)";
number.pattern = "([0-9/(/)-]*)";
username.required = true;
email.required = true; |
import { useState } from 'react';
import { Card, CardList, Filters, LoadPage, Loader } from '../components';
import { formatNumber, paginateArray } from '../utils/functions';
export default function Countries({ countries }) {
const { data, status, error } = countries;
const [region, setRegion] = useState('all');
const [search, setSearch] = useState('');
const [page, setPage] = useState(1);
const limit = 8;
if (status === 'pending' || status === 'idle') {
return (
<>
<Filters>
<Filters.Search type='text' placeholder='Search for a country...' />
<Filters.Select label='Filter by Region' />
</Filters>
<CardList>
<LoaderCard />
</CardList>
</>
);
}
if (status === 'error') {
throw error;
}
const filtredResult = data.filter((country) => {
let filters = { region: true, search: true };
if (region !== 'all') {
filters.region = country.region === region;
}
if (search) {
filters.search = country.name
.toLowerCase()
.includes(search.toLowerCase());
}
return filters.region && filters.search;
});
const totalPages = Math.ceil(filtredResult.length / limit);
const paginatedResult = paginateArray(filtredResult, limit);
let finalResult = [];
for (let i = 0; i < page; i++) {
finalResult = [...finalResult, ...paginatedResult[i].data];
}
function handleRegion(region) {
setPage(1);
setRegion(region);
}
function handleSearch(event) {
setPage(1);
setSearch(event.target.value);
}
function loadMore() {
setPage(page + 1);
setTimeout(() => {
window.scrollBy({
top: window.innerHeight - 150,
behavior: 'smooth',
});
}, 200);
}
const options = [
{ value: 'all', label: 'All Regions' },
{ value: 'Africa', label: 'Africa' },
{ value: 'Americas', label: 'Americas' },
{ value: 'Asia', label: 'Asia' },
{ value: 'Europe', label: 'Europe' },
{ value: 'Oceania', label: 'Oceania' },
];
return (
<>
<Filters>
<Filters.Search
type='text'
value={search}
onChange={handleSearch}
placeholder='Search for a country...'
/>
<Filters.Select
options={options}
value={region}
setValue={handleRegion}
label='Filter by Region'
/>
</Filters>
{finalResult.length === 0 ? (
<h2 style={{ textAlign: 'center' }}>No Countries Found...</h2>
) : (
<CardList>
{finalResult.map((country) => (
<CardItem key={country.name} country={country} />
))}
</CardList>
)}
{page < totalPages && (
<LoadPage>
<LoadPage.Button onClick={loadMore}>Load More</LoadPage.Button>
</LoadPage>
)}
</>
);
}
function LoaderCard() {
return Array.from(Array(8).keys()).map((i) => <Loader.Card key={i} />);
}
function CardItem({ country }) {
const { name, flag, population, region, capital, alpha3Code } = country;
return (
<Card to={`/detail/${alpha3Code.toLowerCase()}`}>
<Card.Image src={flag} alt={`${name} country flag`} />
<Card.Body>
<Card.Title>{name}</Card.Title>
<Card.Description>
<Card.DescriptionTitle>Population: </Card.DescriptionTitle>
{formatNumber(population)}
</Card.Description>
<Card.Description>
<Card.DescriptionTitle>Region: </Card.DescriptionTitle>
{region}
</Card.Description>
<Card.Description>
<Card.DescriptionTitle>Capital: </Card.DescriptionTitle>
{capital}
</Card.Description>
</Card.Body>
</Card>
);
}
|
import Link from 'next/link';
import React from 'react';
import BlogSidebar from '../blog/blog-sidebar';
import BlogDetailsForm from '../forms/blog-details-form';
const post_comments = [
{
date:'3/05/2022, 3:53:39 PM',
img:'/assets/img/testimonial/testi-4.2.png',
name:'Kristin Watson',
desc:"Patient Comments are a collection of comments submitted by viewers in <br /> response to a question posed by a MedicineNet doctor."
},
{
children:true,
date:'5/09/2022, 3:59:39 PM',
img:'/assets/img/testimonial/testi-4.5.png',
name:'Farhan Firoz',
desc:"Include anecdotal examples of your experience, or things you took notice of that <br /> you feel others would find useful."
},
{
date:'8/10/2022, 5:59:39 PM',
img:'/assets/img/testimonial/testi-4.1.png',
name:'Salim rana',
desc:"Include anecdotal examples of your experience, or things you took notice of that <br /> you feel others would find useful."
},
]
const BlogDetailsArea = ({ blog }) => {
const { img, author, date, comment, views, title } = blog || {};
return (
<>
<div className="postbox__area pt-120 pb-120">
<div className="container">
<div className="row">
<div className="col-xxl-8 col-xl-8 col-lg-8 col-12">
<div className="postbox__wrapper">
<article className="postbox__item format-image transition-3">
<div className="postbox__content">
<p><img className="w-100" src={img} alt="" /></p>
<div className="postbox__meta">
<span><a href="#"><i className="fal fa-user-circle"></i>{author}</a></span>
<span><a href="#"><i className="fal fa-clock"></i>{date}</a></span>
<span><a href="#"><i className="fal fa-comment-alt-lines"></i>({comment}) Coments</a></span>
<span><a href="#"><i className="fal fa-eye"></i> {views} views</a></span>
</div>
<h3 className="postbox__title">
{title}
</h3>
<div className="postbox__text">
<p>One in four people in the world will be affected by mental or neurological disorders at some point in their lives, says the World Health Organization. Still, we spend more time brushing our teeth than taking care of our mental health, said Guy Winch in his TED talk.
</p>
<p>We tend to neglect our mental well-being because of the stigma of mental health care. But as societies become wiser and more self-aware, there is a greater need to redefine the meaning of mental health care. Naomi Hirabayashi and Marah Lidey do exactly that by drawing attention to the aspect of preventing mental health issues. The application they built makes mental self-care easy and accessible. of this year of the best law and his a part of this years.</p>
<p>We tend to neglect our mental well-being because of the stigma of mental health care. But as societies become wiser and more self-aware, there is a greater need to redefine the meaning of mental health care. Naomi Hirabayashi and Marah Lidey do exactly that by drawing attention to the aspect of preventing mental health issues. The application they built makes mental self-care easy and accessible. of this year of the best law and his a part of this years.</p>
</div>
<div className="postbox__thumb2">
<div className="row gx-50">
<div className="col-xl-6">
<p><img src="/assets/img/blog-details/blog-big-4.jpg" alt="" /></p>
</div>
<div className="col-xl-6">
<p><img src="/assets/img/blog-details/blog-sm-5.jpg" alt="" /></p>
</div>
</div>
</div>
<div className="postbox__social-wrapper">
<div className="row">
<div className="col-xl-6 col-lg-12">
<div className="postbox__tag tagcloud">
<span>Tag</span>
<Link href="/blog-details">
<a>Business</a>
</Link>
<Link href="/blog-details">
<a>Design</a>
</Link>
<Link href="/blog-details">
<a>apps</a>
</Link>
<Link href="/blog-details">
<a>data</a>
</Link>
</div>
</div>
<div className="col-xl-6 col-lg-12">
<div className="postbox__social text-xl-end text-start">
<span>Share</span>
<a href="https://www.linkedin.com/" target="_blank" rel="noreferrer">
<i className="fab fa-linkedin tp-linkedin"></i>
</a>
<a href="https://www.pinterest.com/" target="_blank" rel="noreferrer">
<i className="fab fa-pinterest tp-pinterest"></i>
</a>
<a href="https://www.facebook.com/" target="_blank" rel="noreferrer">
<i className="fab fa-facebook tp-facebook" ></i>
</a>
<a href="https://twitter.com/" target="_blank" rel="noreferrer">
<i className="fab fa-twitter tp-twitter"></i>
</a>
</div>
</div>
</div>
</div>
</div>
</article>
<div className="postbox__comment mb-65">
<h3 className="postbox__comment-title">(04) Comment</h3>
<ul>
{post_comments.map((comment,i) => {
const {date,desc,img,name,children} = comment;
return <li key={i} className={`${children ? 'children' : ''}`}>
<div className="postbox__comment-box d-flex">
<div className="postbox__comment-info ">
<div className="postbox__comment-avater mr-20">
<img src={img} alt="" />
</div>
</div>
<div className="postbox__comment-text">
<div className="postbox__comment-name">
<h5>{name}</h5>
<span className="post-meta">{date}</span>
</div>
<p>{desc}</p>
<div className="postbox__comment-reply">
<a href="#">Reply</a>
</div>
</div>
</div>
</li>
})}
</ul>
</div>
<div className="postbox__comment-form">
<h3 className="postbox__comment-form-title">Leave a Reply</h3>
{/* details form start */}
<BlogDetailsForm />
{/* details form end */}
</div>
</div>
</div>
<div className="col-xxl-4 col-xl-4 col-lg-4">
{/* blog sidebar start */}
<BlogSidebar />
{/* blog sidebar end */}
</div>
</div>
</div>
</div>
</>
);
};
export default BlogDetailsArea; |
const _ = require('underscore');
const config = require('./config');
const bsonUrlEncoding = require('./utils/bsonUrlEncoding');
/**
* Performs a search query on a Mongo collection and pages the results. This is different from
* find() in that the results are ordered by their relevancy, and as such, it does not take
* a paginatedField parameter. Note that this is less performant than find() because it must
* perform the full search on each call to this function.
*
* @param {MongoCollection} collection A collection object returned from the MongoDB library's
* or the mongoist package's `db.collection(<collectionName>)` method. This MUST have a Mongo
* $text index on it.
* See https://docs.mongodb.com/manual/core/index-text/.
* @param {String} searchString String to search on.
* @param {Object} params
* -query {Object} The find query.
* -limit {Number} The page size. Must be between 1 and `config.MAX_LIMIT`.
* -fields {Object} Fields to query in the Mongo object format, e.g. {title :1}.
* The default is to query ONLY _id (note this is a difference from `find()`).
* -next {String} The value to start querying the page. Defaults to start at the beginning of
* the results.
*/
module.exports = async function(collection, searchString, params) {
if (_.isString(params.limit)) params.limit = parseInt(params.limit, 10);
if (params.next) params.next = bsonUrlEncoding.decode(params.next);
params = _.defaults(params, {
query: {},
limit: config.MAX_LIMIT,
});
if (params.limit < 1) params.limit = 1;
if (params.limit > config.MAX_LIMIT) params.limit = config.MAX_LIMIT;
// We must perform an aggregate query since Mongo can't query a range when using $text search.
const aggregate = [
{
$match: _.extend({}, params.query, {
$text: {
$search: searchString,
},
}),
},
{
$project: _.extend({}, params.fields, {
_id: 1,
score: {
$meta: 'textScore',
},
}),
},
{
$sort: {
score: {
$meta: 'textScore',
},
_id: -1,
},
},
];
if (params.next) {
aggregate.push({
$match: {
$or: [
{
score: {
$lt: params.next[0],
},
},
{
score: {
$eq: params.next[0],
},
_id: {
$lt: params.next[1],
},
},
],
},
});
}
aggregate.push({
$limit: params.limit,
});
let response;
// Support both the native 'mongodb' driver and 'mongoist'. See:
// https://www.npmjs.com/package/mongoist#cursor-operations
const aggregateMethod = collection.aggregateAsCursor ? 'aggregateAsCursor' : 'aggregate';
const results = await collection[aggregateMethod](aggregate).toArray();
const fullPageOfResults = results.length === params.limit;
if (fullPageOfResults) {
response = {
results,
next: bsonUrlEncoding.encode([_.last(results).score, _.last(results)._id]),
};
} else {
response = {
results,
};
}
return response;
};
|
var express = require('express'),
app = express(),
baseServer = require('lc-baseServer'),
port = process.env.PORT || 5000
// router for the API
var routerApi = baseServer.routerApi
.dbUrlsPath('./server/dbUrls.json', 'prod')
.connect(function (err) {})
// base prod
var routerProd = baseServer.routerProd
// set up server app
app
.use(express.static('./clientBuild'))
.use('/api', routerApi)
.get(['/', '/*'], express.static('./clientBuild/index.html'))
.listen(port)
console.log('Server in '+ process.env.NODE_ENV +' mode, listening on port:' + port) |
"use strict";
odoo.define('pos_extended_interface.order', function (require) {
var utils = require('web.utils');
var round_pr = utils.round_precision;
var models = require('point_of_sale.models');
var core = require('web.core');
var qweb = core.qweb;
var _t = core._t;
var _super_Order = models.Order.prototype;
models.Order = models.Order.extend({
initialize: function (attributes, options) {
_super_Order.initialize.apply(this, arguments);
var self = this;
if (!this.note) {
this.note = '';
}
},
init_from_JSON: function (json) {
var res = _super_Order.init_from_JSON.apply(this, arguments);
if (json.note) {
this.note = json.note
}
return res;
},
export_as_JSON: function () {
var json = _super_Order.export_as_JSON.apply(this, arguments);
if (this.note) {
json.note = this.note;
}
return json;
},
export_for_printing: function () {
var receipt = _super_Order.export_for_printing.call(this);
receipt['note'] = this.note;
receipt['signature'] = this.signature;
return receipt;
},
set_note: function (note) {
this.note = note;
this.trigger('change', this);
},
get_note: function (note) {
return this.note;
},
});
var _super_Orderline = models.Orderline.prototype;
models.Orderline = models.Orderline.extend({
initialize: function (attributes, options) {
var res = _super_Orderline.initialize.apply(this, arguments);
this.note = this.note || "";
return res;
},
init_from_JSON: function (json) {
var res = _super_Orderline.init_from_JSON.apply(this, arguments);
if (json.note) {
this.note = this.set_line_note(json.note);
}
},
export_as_JSON: function () {
var json = _super_Orderline.export_as_JSON.apply(this, arguments);
if (this.note) {
json.note = this.get_line_note();
}
return json;
},
clone: function () {
var orderline = _super_Orderline.clone.call(this);
orderline.note = this.note;
return orderline;
},
export_for_printing: function () {
var receipt_line = _super_Orderline.export_for_printing.apply(this, arguments);
receipt_line['note'] = this.note || '';
return receipt_line;
},
set_line_note: function (note) {
this.note = note;
this.trigger('change', this);
},
get_line_note: function () {
return this.note;
},
});
}); |
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var WebpackStrip = require('strip-loader');
module.exports = {
context: path.resolve('src'),
entry: {
app: ['./assets/scripts/app'],
vendors: ['jquery', 'knockout']
},
output: {
path: path.resolve('public/assets/'),
publicPath: '/public/assets/',
filename: '[name].bundle.js',
libraryTarget: 'var',
library: 'App'
},
devServer: {
contentBase: './',
noInfo: true,
},
plugins: [
new ExtractTextPlugin('[name].css'),
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jQuery',
'windows.jQuery': 'jquery'
}),
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.bundle.js', Infinity),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false, },
output: { comments: false },
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin(),
],
module: {
preLoaders: [],
loaders: [{
test: /\.js$/,
include: getPath('src/assets/scrips'),
loader: WebpackStrip.loader('debug', 'console.log')
}, {
test: /\.es6$/,
//exclude: /node_modules/,
include: getPath('src/assets/scrips'),
loader: 'babel-loader',
}, {
test: /\.scss$/,
//exclude: /node_modules/,
include: getPath('src/assets/styles'),
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!autoprefixer-loader!sass-loader'),
}]
},
resolve: {
extensions: ['', '.js', '.es6', '.ts']
}
}
function getPath(relativePath) {
return path.join(__dirname, relativePath);
}
|
import React, { Component } from 'react';
import { Switch, Route } from 'react-router-dom';
import Navbar from './components/Navbar';
import MainPage from './containers/MainPage';
import LoginPage from './containers/LoginPage';
import LogoutPage from './containers/LogoutPage';
import SignUpPage from './containers/SignUpPage';
import CarsPage from './containers/CarsPage';
import AddCarPage from './containers/AddCarPage';
import FuelConsumptionPage from './containers/FuelConsumptionPage';
import AddFuelConsumptionPage from './containers/AddFuelConsumptionPage';
import RepairsPage from './containers/RepairsPage';
import AddRepairPage from './containers/AddRepairPage';
import UserDetailsPage from './containers/UserDetailsPage';
import EditUserDetailsPage from './containers/EditUserDetailsPage';
import PasswordEmailChangePage from './containers/PasswordEmailChangePage';
import EditCarDetailPage from './containers/EditCarDetailPage';
class App extends Component {
render() {
return (
<div>
<Navbar/>
<div className = 'ui container' style={{marginTop: '50px'}}>
<Switch>
<Route exact path = '/' component = {MainPage}/>
<Route exact path = '/cars' component = {CarsPage}/>
<Route exact path = '/cars/add' component = {AddCarPage}/>
<Route exact path = '/cars/:carId/edit' component = {EditCarDetailPage}/>
<Route exact path = '/cars/:carId/fuelConsumption' component = {FuelConsumptionPage}/>
<Route exact path = '/cars/:carId/fuelConsumption/add' component = {AddFuelConsumptionPage}/>
<Route exact path = '/cars/:carId/repairs' component = {RepairsPage}/>
<Route exact path = '/cars/:carId/repairs/add' component = {AddRepairPage}/>
<Route exact path = '/accountDetails' component = {UserDetailsPage}/>
<Route exact path = '/accountDetails/edit' component = {EditUserDetailsPage}/>
<Route exact path = '/accountDetails/changePasswordEmail' component = {PasswordEmailChangePage}/>
<Route exact path = '/login' component = {LoginPage}/>
<Route exact path = '/register' component = {SignUpPage}/>
<Route exact path = '/logout' component = {LogoutPage}/>
</Switch>
</div>
</div>
);
}
}
export default App; |
const Mustache = require('mustache');
const fs = require('fs');
const { promisify } = require('util');
const readFileAsync = promisify(fs.readFile);
const writeFileAsync = promisify(fs.writeFile);
const path = require('path');
const publicDir = path.join(__dirname, '../public');
class MainController {
static async main(req, res, next) {
try {
const htmlString = await readFileAsync(publicDir + '/views/template.html', 'utf8');
console.log('TCL: MainController -> main -> res', htmlString);
var view = {
testVar: 'Joe',
calc: function() {
return 2 + 4;
},
};
const output = Mustache.render(htmlString, view);
console.log('oopsie');
return res.status(200).send(output);
} catch (error) {
error.statusCode = 500;
next(error);
}
}
static async main2(req, res, next) {
try {
var view = {
title: 'Joe',
calc: function() {
return 2 + 4;
},
};
var output = Mustache.render('{{title}} spends {{calc}}', view);
return res.status(200).json(output);
} catch (error) {
error.statusCode = 500;
next(error);
}
}
}
module.exports = MainController;
|
// for es6
// import 'babel-polyfill';
import Sandbox from './Sandbox';
/* facade: DOM */
const DOMFacade = {
query: selector => document.querySelector(selector)
};
class Framework {
constructor (opt) {
this._ = new Sandbox(this, opt);
}
get DOM () {
return DOMFacade;
}
}
export default Framework; |
import Component from '../../component';
import Pairs from '../../../models/pairs';
import CalcTemplate from '../../../../templates/pages/currency/CalcTemplate.hbs';
import PairTemplate from '../../../../templates/partials/PairTemplate.hbs';
class Calculate extends Component{
constructor() {
super();
this.model = new Pairs();
}
getData() {
if (JSON.parse(sessionStorage.getItem('converseConfig')).length) {
this.pairs = JSON.parse(sessionStorage.getItem('converseConfig'));
return new Promise(resolve => resolve());
}
return this.model.getPairs(sessionStorage.getItem('currenciesToCalculate')).then(pairs => {
this.pairs = pairs;
sessionStorage.setItem('converseConfig', JSON.stringify(this.pairs));
}).catch(() => window.location.hash = '#/404');
}
render() {
return new Promise(resolve => resolve(CalcTemplate(this.pairs[0])));
}
afterRender() {
this.appendPairs();
this.setActions();
}
setActions() {
const pageContent = document.getElementsByClassName('calculation')[0],
amountInputs = pageContent.getElementsByTagName('input');
pageContent.addEventListener('keyup', event => {
if (event.target.classList.contains('original-value')) {
this.model.conversion(event.target);
} else if (event.target.classList.contains('target-value')) {
this.model.reverseConversion(event.target);
}
}
);
pageContent.addEventListener('click', event => {
if (event.target.classList.contains('back-to-list')) {
window.location.hash = '#/currencyList';
} else if (event.target.classList.contains('reset-values-btn')) {
this.clearAmounts(event.target);
}
});
for (let input in amountInputs) {
if (amountInputs.hasOwnProperty(input)) {
amountInputs[input].addEventListener('blur', event => {
this.setToZero(event.target);
});
}
}
}
appendPairs() {
const pairsContainer = document.getElementsByClassName('pairs-container')[0];
this.pairs.forEach(pair => {
pairsContainer.insertAdjacentHTML('beforeEnd', PairTemplate(pair));
});
}
clearAmounts(resetBtn) {
const pairContainer = resetBtn.parentElement.parentElement.parentElement,
original = pairContainer.getElementsByClassName('original-value')[0],
target = pairContainer.getElementsByClassName('target-value')[0],
converseConfig = JSON.parse(sessionStorage.getItem('converseConfig')),
currentPair = converseConfig.find(element => element.to === pairContainer.dataset.target);
original.value = '0.00';
target.value = '0.00';
currentPair.originalAmount = '0.00';
currentPair.targetAmount = '0.00';
sessionStorage.setItem('converseConfig', JSON.stringify(converseConfig));
}
setToZero(amountInput) {
/*
Formatting an input value to n:nn vue
*/
amountInput.value = amountInput.value.trim() == 0 ? '0.00' : Number(amountInput.value).toFixed(2);
}
}
export default Calculate; |
function Enemy() {
this.pos = createVector(random(width), random(height));
this.bearing = 0;
this.r = 20;
this.health = 100;
this.dead = false;
this.update = function() {
// Ai
this.targetX = player.pos.x;
this.targetY = player.pos.y;
this.bearing = PI / 2 + atan2(player.pos.y-this.pos.y, player.pos.x-this.pos.x);
}
this.show = function() {
// Main player
push();
stroke(0);
translate(this.pos.x, this.pos.y);
rotate(this.bearing);
if (debug.collider) {
noFill();
ellipse(0, 0, this.r) // Sphere Collider
}
fill(this.health, this.health, this.health);
triangle(0, -15, 15, 15, -15, 15); // Actuall enemy
pop();
}
}
|
import styled from 'styled-components'
import border from '@a/styles/border.js'
const BtnWrap =border(
styled.button`
width:.64rem;
height:.3rem;
background-color:#fff;
/* border:none; */
margin-right:0.1rem;
/* border:1px solid #ccc; */
border-radius:0.02rem;
font-size:.12rem;
color:#666;
`
)
const BtnBox = styled.div`
margin-top:0.08rem;
display:flex;
a{
width:.64rem;
height:.3rem;
background-color:#fff;
border:none;
margin-right:0.1rem;
border:1px solid;
border-color:#ccc;
border-radius:0.03rem;
font-size:.12rem;
color:#666;
line-height:.3rem;
}
a:last-child{
border:1px solid ${props =>{
return props.color === '' ? "rgb(204,204,204)" : props.color
}};
color:${props=> props.color === '' ? "#666" : props.color}
}
`
const OrderInfoWrap = styled.div`
margin-bottom:.15rem;
h1{
height:.44rem;
background-color:#fff;
font-weight:normal;
display:flex;
align-items:center;
padding-left:0.15rem;
color:#333;
font-size:.14rem;
border-bottom:1px solid #efefef;
}
ul{
li{
height:.44rem;
background-color:#fff;
display:flex;
align-items:center;
justify-content:space-between;
padding-left:.15rem;
padding-right:.1rem;
border-bottom:1px solid #efefef;
p{
font-size:0.13rem;
color:#999;
span{
width:.18rem;
height:.18rem;
font-size:.12rem;
color:#FF6666;
border:1px solid #FF6666;
margin-right:0.03rem;
border-radius:0.02rem;
}
}
.newUser{
color:#00CC99;
}
h3{
font-size:.13rem;
color:${props=> props.color === '' ? "#666" : props.color};
font-weight:normal;
}
}
h5{
height:.5rem;
display:flex;
justify-content:space-between;
align-items:center;
padding-left:.15rem;
padding-right:.1rem;
background-color:#fff;
span{
font-weight:normal;
font-size:.14rem;
color:#333;
}
em{
font-size:.18rem;
color:#FF6666;
}
}
}
`
const PayMethodWrap = styled.div`
background-color:#fff;
h1{
height:.44rem;
font-weight:normal;
font-size:.14rem;
color:#333;
line-height:.44rem;
border-bottom:1px solid #efefef;
padding-left:.15rem;
}
ul{
li{
height:.54rem;
display:flex;
align-items:center;
justify-content:space-between;
border-bottom:1px solid #efefef;
padding-left:.15rem;
padding-right:.15rem;
span{
padding-left:.15rem;
font-size:.14rem;
color:#999;
}
}
}
`
const OrderList = styled.div`
margin-bottom:.15rem;
h1{
height:.44rem;
background-color:#fff;
display:flex;
justify-content:space-between;
align-items:center;
font-weight:normal;
padding-left:.15rem;
padding-right:0.1rem;
border-bottom:1px solid #efefef;
span{
color:#999;
font-size:.14rem;
}
p{
em{
color:rgb(0,204,153);
}
font-size:.12rem;
color:#999
}
}
ul{
li{
height:.91rem;
border-bottom:1px solid #efefef;
background-color:#fff;
display:flex;
padding-left:.15rem;
align-items:center;
position: relative;
.imgbox{
height:.67rem;
width:.67rem;
background-color:pink;
img{
height:100%;
width:100%;
}
}
p{
padding-left:.15rem;
display:flex;
flex-direction:column;
font-size:.12rem;
span{
font-size:.14rem;
width:2.2rem;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
}
i{
font-size:.12rem;
color:#999;
}
em{
font-size:.12rem;
color:#00CC99;
}
}
h5{
font-weight:normal;
position:absolute;
right:.1rem;
top:0.15rem;
color:#666666;
}
}
}
footer{
height:.7rem;
background-color:#fff;
display:flex;
justify-content:center;
align-items:center;
}
`
const Buton = border(
styled.button`
width:1.14rem;
height:.35rem;
border:none;
font-size:.13rem;
color:#999;
/* border:1px solid #999; */
background-color:#fff;
line-height:.35rem;
svg{
margin-left:0.05rem;
}
`
)
const Coupon = styled.div`
height:.5rem;
background-color:#fff;
margin-bottom:.15rem;
display:flex;
justify-content:space-between;
align-items:center;
padding-left:.15rem;
padding-right:.2rem;
font-size:.14rem;
color:#999;
p{
position: relative;
span{
font-size:.12rem;
padding-right:.1rem;
}
svg{
position: absolute;
}
}
`
const NoSelectWrap = styled.div`
height:.5rem;
background-color:#fff;
margin-top:.06rem;
margin-bottom:.06rem;
padding-left:.15rem;
display:flex;
align-items:center;
span{
padding-left:.15rem;
color:#30CA96;
}
div{
flex:1;
text-align:right;
padding-right:.15rem;
}
`
export{
BtnWrap,
BtnBox,
OrderInfoWrap,
PayMethodWrap,
OrderList,
Coupon,
NoSelectWrap,
Buton
} |
window.onload = function () {
let _quantity, _price, orderItemNum, deltaQuantity, orderItemQuantity, deltaCost;
let quantityArr = [];
let priceArr = [];
let totalForms = parseInt($('input[name="orderitems-TOTAL_FORMS"]').val());
let orderTotalQuantity = parseInt($('.order_total_quantity').text()) || 0;
let orderTotalPrice = parseFloat($('.order_total_cost').text()) || 0;
console.log("order DOM ready");
for (let i = 0; i < totalForms; i++) {
_quantity = parseInt($('input[name=orderitems-' + i + '-quantity]').val());
_price = parseFloat($('.orderitems-' + i + '-price').text().replace(',', '.'));
quantityArr[i] = _quantity;
if (_price) {
priceArr[i] = _price;
} else {
priceArr[i] = 0;
}
}
$('.order_form').on('click', 'input[type=number]', function() {
let target = event.target
orderItemNum = parseInt(target.name.replace('orderitems-', '').replace('-quantity', ''));
if (priceArr[orderItemNum]) {
orderItemQuantity = parseInt(target.value);
deltaQuantity = orderItemQuantity - quantityArr[orderItemNum];
quantityArr[orderItemNum] = orderItemQuantity;
orderSummaryUpdate(priceArr[orderItemNum], deltaQuantity)
}
});
$('.order_form').on('click', 'input[type=checkbox]', function() {
let target = event.target
orderItemNum = parseInt(target.name.replace('orderitems-', '').replace('-DELETE', ''));
if (target.checked) {
deltaQuantity = -quantityArr[orderItemNum];
} else {
deltaQuantity = quantityArr[orderItemNum];
}
orderSummaryUpdate(priceArr[orderItemNum], deltaQuantity)
});
function orderSummaryRecalc () {
orderTotalQuantity = 0;
orderTotalPrice = 0;
for (let i = 0; i < totalForms; i++) {
orderTotalQuantity += quantityArr[i];
orderTotalPrice += priceArr[i];
}
$('.order_total_quantity').html(orderTotalQuantity.toString());
$('.order_total_cost').html(orderTotalPrice.toFixed(2).toString());
}
function orderSummaryUpdate (orderItemPrice, deltaQuantity) {
deltaCost = orderItemPrice * deltaQuantity;
orderTotalPrice = Number((orderTotalPrice + deltaCost).toFixed(2));
orderTotalQuantity = orderTotalQuantity + deltaQuantity;
$('.order_total_quantity').text(orderTotalQuantity.toString());
$('.order_total_cost').text(orderTotalPrice.toString());
}
$('.order_form select').change(function () {
let target = event.target;
orderItemNum = parseInt(target.name.replace('orderitems-', '').replace('-product', ''));
let orderItemProductPk = target.options[target.selectedIndex].value;
if (orderItemProductPk) {
$.ajax({
url: '/order/product/' + orderItemProductPk + '/price/',
success: function (data) {
if (data.price) {
priceArr[orderItemNum] = parseFloat(data.price);
if (isNaN(quantityArr[orderItemNum])) {
quantityArr[orderItemNum] = 0;
}
let priceHtml = '<span class="orderitems-' + orderItemNum + '-price">' + data.price.toString().replace('.', ',') + '</span> руб';
let curTr = $('.order_form table').find('tr:eq(' + (orderItemNum + 1) + ')');
curTr.find('td:eq(2)').html(priceHtml);
orderSummaryRecalc();
}
}
});
}
})
$('.formset_row').formset({
addText: 'Добавить продукт',
deleteText: 'Удалить',
prefix: 'orderitems',
removed: deleteOrderItem,
});
function deleteOrderItem(row) {
let target_name = row[0].querySelector('input[type=number]').name
orderItemNum = parseInt(target_name.replace('orderitems-', '').replace('-quantity', ''));
deltaQuantity = -quantityArr[orderItemNum];
orderSummaryUpdate(priceArr[orderItemNum], deltaQuantity)
}
} |
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import moment from "moment";
class DisplayQuestion extends Component {
static propTypes = {
question: PropTypes.object.isRequired,
showScale: PropTypes.bool
};
static defaultProps = {
showScale: true
};
render() {
const { question, showScale } = this.props;
return (
<div className="level has-background-light py-1 px-1 is-marginless border-bottom">
<div className="level-left">{question.title}</div>
{showScale && (
<div className="level-right field is-grouped is-grouped-multiline">
<div className="control">
<div className="tags has-addons">
<span className="tag is-dark">barème</span>
<span className="tag is-success">{question.scale}</span>
</div>
</div>
<div className="control">
<div className="tags has-addons">
<span className="tag is-dark">temps est.</span>
<span className="tag is-success">
{moment.utc(question.estimatedTime * 1000).format("mm:ss")}
</span>
</div>
</div>
</div>
)}
</div>
);
}
}
const mapStateToProps = state => {
return {
showScale: state.exams.exams.showScale
};
};
export default connect(mapStateToProps)(DisplayQuestion);
|
var morseTable = {
".-": "A",
"-...": "B",
"-.-.": "C",
"-..": "D",
".": "E",
"..-.": "F",
"--.": "G",
"....": "H",
"..": "I",
".---": "J",
"-.-": "K",
".-..": "L",
"--": "M",
"-.": "N",
"---": "O",
".--.": "P",
"--.-": "Q",
".-.": "R",
"...": "S",
"-": "T",
"..-": "U",
"...-": "V",
".--": "W",
"-..-": "X",
"-.--": "Y",
"--..": "Z",
".----": "1",
"..---": "2",
"...--": "3",
"....-": "4",
".....": "5",
"-....": "6",
"--...": "7",
"---..": "8",
"----.": "9",
"-----": "0"
};
var fs = require("fs");
fs.readFileSync("input.txt").toString().split("\n").forEach(function (line) {
if (line !== "") {
morseCode(line);
}
});
function morseCode(line) {
var words = [];
line.trim().split(" ").forEach(function (word) {
var letters = [];
word.split(" ").forEach(function (letter) {
letters.push(morseTable[letter]);
});
words.push(letters.join(""));
});
console.log(words.join(" "));
}
|
'use strict'
var Cookies = require('js-cookie')
var utils = require('string-utils')
var $body = $('body')
$body.append('<p>sub.js!</p>')
if (Cookies) {
$body.append('<p>js-cookie is loaded!</p>')
}
$body.append('<p>' + utils.randomString(100) + '</p>')
|
const express = require('express');
const router = express.Router();
const errs = require('../config/errors.js')
const fs = require('fs')
const { T_user, T_store } = require('../managers/model')
const {
tempAvatarDir,
avatarSize,
getUploadKey,
uploadUrl,
AccessKey,
SecretKey,
bucketName,
cdnHost
} = require('../config/upload.config')
const sizeOf = require('image-size')
const request = require('superagent')
const qiniuToken = require('qiniu-uptoken')
const validator = require('validator')
const { httpLogger, errorLogger } = require('../common/helper/logHelper')
const TOKEN = qiniuToken(AccessKey,SecretKey,bucketName)
/**
* 头像上传
* @param {String} avatar 头像 [base64]
* @return {msg:url}
*/
router.post('/avatar', (req, res, next) => {
existsSync(tempAvatarDir)
let { avatar="" } = req.body
try {
let base64Data = avatar.replace(/^data:image\/\w+;base64,/, "");
if(!avatar || !validator.isBase64(base64Data)) return next(JSON.stringify(errs.not_avatar))
const key = getUploadKey()
const type = avatar.match(/^data:image\/(\w*)/)[1] || "png"; //拿到当前是什么图片 jpeg/png
let imageData = Buffer.from(base64Data, 'base64'); //使用 Buffer转换成二进制
const filename = `${tempAvatarDir}/${Date.now()}.${type}`
fs.writeFileSync(filename,imageData,'binary')
const avatarSize = sizeOf(filename)
httpLogger.info("/avatar-tempAvatar-save-success:",avatarSize)
//长宽限制200
if (avatarSize.width === avatarSize.width && avatarSize.height === avatarSize.height) {
httpLogger.info('/avatar-start-upload')
request
.post(uploadUrl)
.field('key', key)
.field('name', key)
.field('token', TOKEN)
.attach('file', imageData, key)
.set('Accept', 'application/json')
.end((err, data) => {
if (err) {
errorLogger.info('/avatar-upload-faild:', err)
return next(JSON.stringify(errs.avatar_upload_faild))
}
httpLogger.info('/avatar-end-upload:', data)
res.resRawData = {
msg:cdnHost + key
}
next()
})
} else {
next(JSON.stringify(errs.avatar_size_error))
}
fs.unlinkSync(filename)
} catch (error) {
next(error)
}
})
const existsSync = (path) => {
const isExists = fs.existsSync(path)
if (!isExists) {
fs.mkdirSync(path)
}
}
module.exports = router
|
function input() {
inputDate = document.getElementById("taskExpDateInput").value;
var verifyDateFormat = /^(\d{1,2})-(\d{1,2})-(\d{4})$/;
var validDateValue = /(^(((0[1-9]|1[0-9]|2[0-8])[-](0[1-9]|1[012]))|((29|30|31)[-](0[13578]|1[02]))|((29|30)[-](0[4,6,9]|11)))[-](19|[2-9][0-9])\d\d$)|(^29[-]02[-](19|[2-9][0-9])(00|04|08|12|16|20|24|28|32|36|40|44|48|52|56|60|64|68|72|76|80|84|88|92|96)$)/;
var validYear = /(^(\d{1,2})-(\d{1,2})-(19[789]\d|20[012]\d|203[01234567])$)/;
if (!inputDate.match(verifyDateFormat)) {
document.getElementById("message").innerHTML = "Please enter a dd-mm-yyyy date";
document.getElementById("message").classList.remove('hidden');
document.getElementById("message").classList.add('error');
return false;
} else if (!inputDate.match(validDateValue)) {
document.getElementById("message").innerHTML = "Please enter a valid date";
document.getElementById("message").classList.remove('hidden');
document.getElementById("message").classList.add('error');
return false;
} else if (!inputDate.match(validYear)) {
document.getElementById("message").innerHTML = "Year must be at least 1970 and lower than 2038";
document.getElementById("message").classList.remove('hidden');
document.getElementById("message").classList.add('error');
return false;
} else
return true;
return false;
}
function editList(list) {
let editform = document.getElementById("editListForm");
document.getElementById("editListID").value = list.id.substr(4);
editform.submit();
}
function RequestAuthToken(tokenName, elementToChange, isHtml = true) {
let token = this.document.getElementById("ReqAuthToken");
if (token == null) {
console.log("Failed to find auth token");
return;
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText != -1) {
if (isHtml) {
elementToChange.value = this.responseText;
} else {
elementToChange.val = this.responseText;
}
} else if (this.responseText == -2) {
console.log("[ERROR]\tAuth Token Not Sent");
} else if (this.responseText == -3) {
console.log("[ERROR]\tFailed to validate Auth Token");
}
}
};
xhttp.open("POST", "../security/requestsToken.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("&tokenName=" + tokenName + "&AuthToken=" + token.value);
}
var deleteTaskAJAXAuthToken = {
val: 0
};
var deleteTaskAJAXTokenName = "deleteTaskAJAX";
var getListToScriptAJAXAuthToken = {
val: 0
};
var getListToScriptAJAXTokenName = "getListToScriptAJAX";
var getListDataAJAXAuthToken = {
val: 0
};
var getListDataAJAXTokenName = "getListDataAJAX";
var getListIndexAJAXAuthToken = {
val: 0
};
var getListIndexAJAXTokenName = "getListIndexAJAX";
window.onload = function(e) {
RequestAuthToken(deleteTaskAJAXTokenName, deleteTaskAJAXAuthToken, false);
RequestAuthToken(getListToScriptAJAXTokenName, getListToScriptAJAXAuthToken, false);
RequestAuthToken(getListDataAJAXTokenName, getListDataAJAXAuthToken, false);
RequestAuthToken(getListIndexAJAXTokenName, getListIndexAJAXAuthToken, false);
let searchToken = document.getElementById("searchAuthToken");
if (searchToken != null) {
let id = document.getElementById("searchID");
RequestAuthToken(id.value, searchToken);
}
let addListToken = document.getElementById("addListAuthToken");
if (addListToken != null) {
let id = document.getElementById("addListID");
RequestAuthToken(id.value, addListToken);
}
let editListToken = document.getElementById("editListAuthToken");
if (editListToken != null) {
let id = document.getElementById("editListFormID");
RequestAuthToken(id.value, editListToken);
}
let addTaskToken = document.getElementById("addTaskAuthToken");
if (addTaskToken != null) {
let id = document.getElementById("addTaskFormID");
RequestAuthToken(id.value, addTaskToken);
}
let delListToken = document.getElementById("delListAuthToken");
if (delListToken != null) {
let id = document.getElementById("delListID");
RequestAuthToken(id.value, delListToken);
}
let inviteUserToken = document.getElementById("inviteUserAuthToken");
if (inviteUserToken != null) {
let id = document.getElementById("inviteUserID");
RequestAuthToken(id.value, inviteUserToken);
}
let editTask = document.getElementById("editTaskAuthToken");
if (editTask != null) {
let id = document.getElementById("editTaskTokenName");
RequestAuthToken(id.value, editTask);
}
}
function XSS_Remove_Tags(string, elementToChange) {
var val = string;
elementToChange.value = val.replace(/<\/?[^>]+(>|$)/g, "");
}
var searchForm = document.querySelector("#searchForm");
if (searchForm != null) {
var searchInput = searchForm.querySelector("#searchImp");
if (searchInput != null) {
searchInput.oninput = function() {
let str = searchInput.value;
str = XSS_Remove_Tags(str, searchInput);
}
}
}
var listTable = document.querySelector("#listsTable");
var currList = 0;
function deleteTask(task) {
if (confirm("Are you sure you want to delete this task?") == true) {
var taskID = (task.id.substr(0, task.id.indexOf('/'))).substr(4);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == 0) {
location.reload();
}
}
};
xhttp.open("POST", "../task_management/deleteTask.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("&task_id=" + taskID + "&tokenName=" + deleteTaskAJAXTokenName + "&AuthToken=" + deleteTaskAJAXAuthToken.val);
}
}
function editTask(task) {
let editform = document.getElementById("editTaskForm");
document.getElementById("editTaskID").value = task.id.substr(4);
editform.submit();
}
var tasklist = [];
if (listTable != null) {
var listOwnerArray = [];
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
listOwnerArray = JSON.parse(this.responseText);
}
};
xhttp.open("POST", "../list_management/getListToScript.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("&tokenName=" + getListToScriptAJAXTokenName + "&AuthToken=" + getListToScriptAJAXAuthToken.val);
let listName = document.getElementById("taskNameid");
if (taskExpDateInput != null) {
listName.oninput = function() {
let str = listName.value;
str = XSS_Remove_Tags(str, listName);
};
}
let descBox = document.getElementById("descriptionBox");
if (descBox != null) {
descBox.oninput = function() {
let str = descBox.value;
str = XSS_Remove_Tags(str, descBox);
}
}
let dateBox = document.getElementById("taskExpDateInput");
if (dateBox != null) {
dateBox.oninput = function() {
let str = dateBox.value;
str = XSS_Remove_Tags(str, dateBox);
}
}
let listtableform = document.getElementById("addListForm");
let formInput = listtableform.querySelector("#listnameID");
formInput.oninput = function() {
let str = formInput.value;
str = XSS_Remove_Tags(str, formInput);
}
listTable.onclick = function(ev) {
if (ev.target.parentElement.querySelector('.id') != null) {
var clickedID = ev.target.parentElement.querySelector('.id').innerText;
var clickedName = ev.target.parentElement.querySelector('.name').innerText;
document.getElementById('idList2').value = clickedID;
document.getElementById('idList3').value = clickedID;
document.getElementById('idList4').value = clickedID;
document.getElementById('idListName').value = clickedName;
var clickedName = ev.target.parentElement.querySelector('.name').innerText;
document.getElementById('ListName').innerHTML = clickedName;
var index = ev.target.parentElement.rowIndex;
if (index == null) {
console.log("NULL row");
} else {
currList = index;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == -1 || this.responseText == -2 || this.responseText == -3) {
document.getElementById("message").innerHTML = "Error";
document.getElementById("message").classList.remove('hidden');
} else {
var tasks = JSON.parse(this.responseText);
for (let i = 0; i < tasks.length; ++i) {
tasklist.push(JSON.parse(tasks[i]));
}
}
}
let tableHTML = document.querySelector("#taskTable").querySelector("tbody");
var htmlString = '';
if (tasklist.length != 0) {
htmlString = `<tr>
<th class="id">ID</th>
<th class="status arrowCursor" ></th>
<th class="task arrowCursor">Task</th>
<th class="expDate arrowCursor">Expiration Date </th>
<th id="descriptionHead" class="task arrowCursor">Description </th>
<th class="deltete task"></th>
</tr>`;
for (let i = 0; i < tasklist.length; ++i) {
var taskRow = tasklist[i].id;
htmlString = htmlString + "\n" + "<tr>";
htmlString = htmlString + "\n" + '<td class="id verticalTop">' + tasklist[i].id + '</td>';
if (tasklist[i].completed == "true") {
var checkMark = "✔";
var htmlstring = '';
var editTaskString = '';
htmlString = htmlString + "\n" + '<td class="status verticalTop" >' +
editTaskString + htmlstring + checkMark + ' </td>';
} else {
var checkMark = "";
if (listOwnerArray[index].userID !== listOwnerArray.slice(-1).pop()) {
var htmlstring = '<input type="checkbox" class="status verticalTop" onclick="completeTask(this);" id="task' + taskRow + '/index' + currList + '"';
htmlString = htmlString + "\n" + '<td class="status verticalTop" style="text-align:right;" >' + htmlstring + checkMark + ' </td>';
} else {
let htmlstring = '<input style=" margin-left: -13px" onclick="completeTask(this);" id="task' + taskRow + '/index' + currList + '" type="checkbox"';
let editTaskString = '<a class = "buttonCursor left_align" onclick="editTask(this);" id="task' + taskRow + '"> ✎ </a> ';
htmlString = htmlString + "\n" + '<td class="status verticalTop" style="text-align:right;" >' +
editTaskString + htmlstring + checkMark + ' </td>';
}
}
if ((tasklist[i].title).length != 0 && (tasklist[i].title).length > 26)
htmlString = htmlString + "\n" + '<td id = "description"> <div class = "taskDiv">' + tasklist[i].title + ' </div></td>';
else
htmlString = htmlString + "\n" + '<td id = "description"><div class = "taskDivNotFilled">' + tasklist[i].title + '</div></td>';
let data = "";
if (tasklist[i].expiring != null) {
data = tasklist[i].expiring;
}
let taskDate = new Date(data * 1000);
let taskDateYear = taskDate.getYear();
let taskDateMonth = taskDate.getMonth() + 1;
let taskDateDay = taskDate.getDate();
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
let currentDate = new Date();
let currentDay = currentDate.getDate();
let currentMonth = currentDate.getMonth() + 1;
let currentYear = currentDate.getYear();
let diffData = (taskDate - currentDate);
let diffDay = taskDateDay - currentDay;
let diffMonth = taskDateMonth - currentMonth;
let diffYear = taskDateYear - currentYear;
if (diffData <= 259200000 && diffDay <= 2 && tasklist[i].completed != "true" || diffData <= 259200000 && tasklist[i].completed != "true")
htmlString = htmlString + "\n" + '<td class="expDate closeDate verticalTop"><b>' + pad(taskDateDay, 2) + "-" + pad(taskDateMonth, 2) + "-" + taskDate.getFullYear() + '</td>';
else
htmlString = htmlString + "\n" + '<td class="expDate verticalTop"><b>' + pad(taskDateDay, 2) + "-" + pad(taskDateMonth, 2) + "-" + taskDate.getFullYear() + '</td>';
if ((tasklist[i].description).length != 0 && (tasklist[i].description).length > 26)
htmlString = htmlString + "\n" + '<td id = "description"> <div class = "descriptionDiv">' + tasklist[i].description + ' </div></td>';
else
htmlString = htmlString + "\n" + '<td id = "description"><div class = "descriptionDivNotFilled">' + tasklist[i].description + '</div></td>';
if (listOwnerArray[index].userID !== listOwnerArray.slice(-1).pop()) {
htmlString = htmlString + "\n" + '<td class="delete verticalTop"> </td></tr>';
} else {
htmlString = htmlString + "\n" + `<td class="delete verticalTop">
<a class = "buttonCursor" onclick="deleteTask(this);" id="task` + taskRow + `/"> X </a>
</td>
</tr>`;
}
}
};
tableHTML.innerHTML = htmlString;
tasklist.length = 0;
}
};
xhttp.open("POST", "../list_management/getListData.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("index=" + currList + "&tokenName=" + getListDataAJAXTokenName + "&AuthToken=" + getListDataAJAXAuthToken.val);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == 0) {
document.getElementById("message").innerHTML = "Completed Task";
document.getElementById("message").classList.remove('hidden');
}
}
};
xhttp.open("POST", "../list_management/getListIndex.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("listID=" + clickedID + "&tokenName=" + getListIndexAJAXTokenName + "&AuthToken=" + getListIndexAJAXAuthToken.val);
}
}
}
var inviteUserForm = document.querySelector("#userInviteForm");
var userNameInput = inviteUserForm.querySelector("#usernameInput");
userNameInput.oninput = function() {
let str = userNameInput.value;
str = XSS_Remove_Tags(str, userNameInput);
}
|
(function (require) {
var
global,
MSGS,
stringifyAndPostFactory,
stringifyAndPost,
JSON,
Worker,
worker,
usingFakeIDB,
toEmscripten,
commandsToRun = [],
xxx;
function doNothing() {
}
function messageHandler(e) {
e = JSON.parse(e);
switch(e.messageType) {
case MSGS.IDB_STATUS: { //returns whether IndexedDB is available in the worker
WorkerIDBStatusRecieved(e.data);
} break;
case MSGS.FAKE_IDB_UPDATED: { //the copy of the indexedDB in the worker is now synchronized
workerIDBUpdated();
} break;
case MSGS.OUTPUT_TEXT: { //output to console
console.log(e.data);
} break;
case COMMAND_FINISHED: { //the command we asked the worker to run has completed. store any file contents returned into IndexedDB
commandFinished(e.data);
} break;
}
}
function fromEmscripten(create, remove) {
stringifyAndPost(MSGS.UPDATE_FAKE_IDB, {
create: create
remove: remove
});
}
function toEmscriptenReciever(a) {
toEmscripten = a;
}
function main(a, b, c) {
global = a;
JSON = global.JSON;
Worker = global.Worker;
MSGS = b;
stringifyAndPostFactory = c;
if(!Worker) {
console.log("web workers not available in this web browser");
return;
}
Module.FS.mkdir('/Documents');
Module.FS.mount(Module.FS.filesystems.IDBWFS, {
fromEmscripten: fromEmscripten,
toEmscriptenReciever: toEmscriptenReciever
}, '/Documents');
newWorker();
Module.FS.syncfs(true, doNothing); //indexeddb to local
}
function newWorker() {
worker = new Worker('worker.js');
stringifyAndPost = stringifyAndPostFactory(worker, JSON);
worker.addEventListener('message', messageHandler, false);
}
function runCommand(commandLine) {
commandsToRun.push(commandLine);
if(!!usingFakeIDB !== usingFakeIDB) { //only do this on page load. The worker might be terminated and replaced later though
stringifyAndPost(MSGS.TEST_FOR_IDB, null);
return;
}
continueRunCommand();
}
function workerIDBStatusRecieved(IDBAvailable) {
//serialise the indexedDB data then send it to the worker in a message
usingFakeIDB = IDBAvailable;
continueRunCommand();
}
function continueRunCommand() {
if (usingFakeIDB) {
Module.FS.syncfs(3, doNothing); //local to worker message
}
else {
workerIDBUpdated();
}
}
function workerIDBUpdated() {
stringifyAndPost(MSGS.RUN_COMMAND, commandsToRun.shift());
}
function commandFinished(data) {
if(usingFakeIDB) {
toEmscripten(false, data.created, data.removed);
Module.FS.syncfs(3, persistLocal); //web worker to local
}
}
function persistLocal() {
Module.FS.syncfs(false, doNothing); //local to indexeddb and web worker
}
function terminateWorker() {
worker.terminate();
newWorker();
if(usingFakeIDB) {
toEmscripten(true); //reset the cache of web worker files
}
}
require(['global','msgs', 'stringifyAndPost'], main);
})(require);
|
const express = require('express');
const router = express.Router();
const usersRoute = require('./usersRoute.js');
const tvRoute = require('./tvRoute.js');
const movieRoute = require('./movieRoute.js');
router.use('/movie', movieRoute);
router.use('/tv', tvRoute);
router.use('/users', usersRoute);
router.get('/', (req, res) => {
res.send('Halaman Utama');
})
module.exports = router; |
import Ember from 'ember';
import NewOrEdit from 'ui/mixins/new-or-edit';
export default Ember.Component.extend(NewOrEdit, {
service: null,
primaryResource: Ember.computed.alias('service'),
actions: {
done() {
this.sendAction('done');
},
cancel() {
this.sendAction('cancel');
},
},
didInsertElement() {
this.$('INPUT')[0].focus();
},
validate() {
var errors = [];
if ( !this.get('service.externalIpAddresses.length') && !this.get('service.hostname') )
{
errors.push('Choose one or more targets to send traffic to');
}
else
{
this._super();
errors = this.get('errors')||[];
}
if ( errors.length )
{
this.set('errors',errors.uniq());
return false;
}
return true;
},
willSave: function() {
this.set('service.launchConfig',{});
return this._super.apply(this,arguments);
},
doneSaving() {
this.send('done');
},
});
|
const express = require("express");
const db = require("../../models/index");
const { industries, countries, license, licenseRole, userLanguages } = require("../../constants");
const router = express.Router();
const User = db.user;
const Company = db.company;
const Department = db.department;
const DepartmentUserAccess = db.department_user_access;
// Get Static Data
router.get("/staticData", async (req, res) => {
try {
console.log("====================================");
console.log("req.body:", req.body);
console.log("====================================");
let industryList = industries.map((item) => {
return {
label:item,
value:item,
};
});
let countryList = countries.map((item) => {
return {
label:item.name,
value:item.name,
code:item.code,
};
});
let licenseList = license.map((item) => {
return {
label:item.name,
value:item.name,
amt:item.amt
};
});
let licenseRoleList = licenseRole.map((item) => {
return {
label:item,
value:item,
};
});
let userLanguageList = userLanguages.map((item) => {
return {
label:item.name,
value:item.name,
code:item.code,
};
});
return res
.status(200)
.json({ success: true, msg: "Data get done.", industryList, countryList, licenseList, licenseRoleList, userLanguageList });
} catch (error) {
return res.status(400).json({ success: false, msg: error.message });
}
});
module.exports = router;
|
// Poll handler
const _data = require("./data");
const helpers = require("./helpers");
const config = require("./config");
const { _tokens } = require("./tokensHandler");
const poll = (data, callback) => {
const acceptableMethods = ["post", "get", "put", "delete"];
if (acceptableMethods.indexOf(data.method) > -1) {
_poll[data.method](data, callback);
} else {
callback(405);
}
};
const _poll = {};
// Poll: post
// Required data: title, description
// Optional data: none
_poll.post = (data, callback) => {
const { payload, headers } = data;
// validate inputs
const pollTitle =
typeof payload.pollTitle == "string" && payload.pollTitle.trim().length > 0
? payload.pollTitle.trim()
: false;
const pollDescription =
typeof payload.pollDescription == "string" &&
payload.pollDescription.trim().length > 10
? payload.pollDescription.trim()
: false;
const members = ["vo4gsBmmNAvPfMNRwpoY", "pRfMUbJQPQeCvGrSQSgK"];
/* typeof payload.members == "object" &&
payload.members instanceof Array &&
payload.members.length >= 2
? payload.members
: false;*/
if (pollTitle && members) {
// get the token from headers
const token = typeof headers.token == "string" ? headers.token : false;
// Lookup the team by reading the token
_data.read("tokens", token, (err, tokenData) => {
if (!err && tokenData) {
const teamName = tokenData.name;
// Lookup team data
_data.read("teams", teamName, (err, teamData) => {
if (!err && teamData) {
const teamPoll =
typeof teamData.poll == "object" && teamData.poll instanceof Array
? teamData.poll
: [];
// verify that the team has less than the number of max-poll-per-team
if (teamPoll.length < config.maxPoll) {
// create a random id for the poll
const pollId = helpers.createRandomString(20);
// create the poll object, and include the team's name
const pollObject = {
id: pollId,
teamName,
title: pollTitle,
description: pollDescription || "",
members,
status: "open"
};
// save the object
_data.create("poll", pollId, pollObject, err => {
if (!err) {
// Add the poll id to the team's object
teamData.poll = teamPoll;
teamData.poll.push(pollId);
// save the new team data
_data.update("teams", teamName, teamData, err => {
if (!err) {
// Return the data about the new poll created
callback(200, pollObject);
} else {
callback(500, {
Error: "Could not update the team with new vote."
});
}
});
} else {
callback(500, { Error: "Could not create the new vote" });
}
});
} else {
callback(400, {
Error: `The team already has the maximum number of votes ${config.maxVotes}`
});
}
} else {
callback(403);
}
});
} else {
callback(403);
}
});
} else {
callback(400, { Error: "Missing required inputs, or inputs are invalid" });
}
};
// Poll - get
// Required data: id
// Optional: none
_poll.get = (data, callback) => {
// Check that the id is valid.
const { queryStringObject: qs } = data;
const id =
typeof qs.id == "string" && qs.id.trim().length == 20
? qs.id.trim()
: false;
if (id) {
// Lookup the check
_data.read("poll", id, (err, pollData) => {
if (!err && pollData) {
// Get the token from the headers
const token =
typeof data.headers.token == "string" ? data.headers.token : false;
// verify that the given token is valid for the and belongs to the team who created the member
_tokens.verifyToken(token, pollData.teamName, tokenIsValid => {
if (tokenIsValid) {
// Return the member data
callback(200, pollData);
} else {
callback(403);
}
});
} else {
callback(404);
}
});
} else {
callback(400, { Error: "Missing required field" });
}
};
// Poll: put
// Required data: id, memberId
// Optional data: title, description, status (one must be sent)
_poll.put = (data, callback) => {
// Check for the required field
const { payload } = data;
const pollId =
typeof payload.pollId == "string" && payload.pollId.trim().length == 20
? payload.pollId.trim()
: false;
/*const memberId =
typeof payload.memberId == "string" && payload.memberId.trim().length == 20
? payload.memberId.trim()
: false;
*/
// Check for the optional fields
// validate inputs
const pollTitle =
typeof payload.pollTitle == "string" && payload.pollTitle.trim().length > 0
? payload.pollTitle.trim()
: false;
const pollDescription =
typeof payload.pollDescription == "string" &&
payload.pollDescription.trim().length > 0
? payload.pollDescription.trim()
: false;
// TODO: Add email valisdation
/*const status =
typeof payload.status == "string" &&
(payload.status.trim() == "open" || payload.status.trim() == "closed")
? payload.status.trim()
: false;*/
// Check to make sure id is valid
if (pollId) {
// Lookup the poll
_data.read("poll", pollId, (err, pollData) => {
if (!err && pollData) {
// Get the token from the headers
const token =
typeof data.headers.token == "string" ? data.headers.token : false;
// verify that the given token is valid and belongs to the team who created the member
_tokens.verifyToken(token, pollData.teamName, tokenIsValid => {
if (tokenIsValid) {
// Update the poll where necessary
if (pollTitle) {
pollData.title = pollTitle;
}
if (pollDescription) {
pollData.description = pollDescription;
}
_data.update("poll", pollId, pollData, err => {
if (!err) {
callback(200);
} else {
callback(500, { Error: "Could not update the poll" });
}
});
/*if (status) {
pollData.status = status;
}*/
/*
const memberPosition = pollData.members.findIndex(
m => m.id == memberId
);
if (memberPosition > -1) {
const count = pollData.members[memberPosition].count + 1;
pollData.members[memberPosition] = { id: memberId, count };
// Store the new updates
_data.update("poll", id, pollData, err => {
if (!err) {
callback(200);
} else {
callback(500, { Error: "Could not update the poll" });
}
});
} else {
callback(400, { error: "Missing fields to update" });
}*/
} else {
callback(403);
}
});
} else {
callback(400, { Error: "poll ID did not exist" });
}
});
} else {
callback(400, { Error: "Missing required field" });
}
};
// Poll - delete
// Required data: id
// Optional data: none
_poll.delete = (data, callback) => {
// Check that the id is valid.
const { queryStringObject: qs } = data;
const id =
typeof qs.id == "string" && qs.id.trim().length == 20
? qs.id.trim()
: false;
// Lookup the team
if (id) {
// Lookup the poll
_data.read("poll", id, (err, pollData) => {
if (!err && pollData) {
// Get the token from the headers
const token =
typeof data.headers.token == "string" ? data.headers.token : false;
// verify that the given token is valid for the team
_tokens.verifyToken(token, pollData.teamName, tokenIsValid => {
if (tokenIsValid) {
// Delete the member data
_data.delete("poll", id, err => {
if (!err) {
// Lookup the team
_data.read("teams", pollData.teamName, (err, teamData) => {
if (!err && teamData) {
const teamPoll =
typeof teamData.poll == "object" &&
teamData.poll instanceof Array
? teamData.poll
: [];
// Remove the deleted poll from their list of poll
const pollPosition = teamPoll.indexOf(id);
if (pollPosition > -1) {
teamPoll.splice(pollPosition, 1);
// re-save the team's data
_data.update(
"teams",
pollData.teamName,
teamData,
err => {
if (!err) {
callback(200);
} else {
callback(500, {
Error: "Could not update the team"
});
}
}
);
} else {
callback(500, {
Error:
"Could not find the poll on the teams's object, so could not remove it."
});
}
} else {
callback(500, {
Error:
"Could not find the team who created the poll, so could not remove the poll from the list of polls on the team object"
});
}
});
} else {
callback(500, { Error: "Could not delete the poll data" });
}
});
} else {
callback(403);
}
});
} else {
callback(400, { Error: "The specified poll ID does not exist" });
}
});
} else {
callback(400, { Error: "Missing required field" });
}
};
module.exports = poll;
|
const test = require('ava');
let testFunc;
global.hexo = {
extend: {
helper: {
register: (_, f) => {
testFunc = f
}
}
}
};
require('./index');
let config;
let page;
test.beforeEach(() => {
config = { url: 'https://base-url.com' };
page = { canonical_path: 'canonical/PATH/' };
});
test('Canonical url is set properly if the page has a canonical_url property', t => {
page.canonical_url = 'https://canonical.com/URL/';
t.is(testFunc(config, page), '<link rel="canonical" href="https://canonical.com/URL/"/>');
});
test('Canonical url is set to base_url appended with canonical_path if no canonical_url is provided', t => {
console.log(config, page);
t.is(testFunc(config, page), '<link rel="canonical" href="https://base-url.com/canonical/PATH/"/>');
});
test('Canonical url is tolerant of trailing slash in config.url', t => {
config.url += '/';
t.is(testFunc(config, page), '<link rel="canonical" href="https://base-url.com/canonical/PATH/"/>');
}); |
import React, {Component} from 'react';
import UpdateInfoClientLayout from '../components/update-info-client-layout.js'
import axios from 'axios'
class UpdateInfoClient extends Component {
state = {
name: "Luisa",
lastName: "",
phoneNumber: "",
university: "valle",
universityCode: "",
country: "",
department: "",
city: "",
email: ""
}
handleNameChange = event => {
this.setState({
name: event.target.value
})
}
handleLastNameChange = event => {
this.setState({
lastName: event.target.value
})
}
handlePasswordChange = event => {
this.setState({
password: event.target.value
})
}
handleUniversityCodeChange = event => {
this.setState({
universityCode: event.target.value
})
}
handleUniversityChange = event => {
this.setState({
university: event.target.value
})
}
handleCountryChange = event => {
this.setState({
country: event.target.value
})
}
handleDepartmentChange = event => {
this.setState({
department: event.target.value
})
}
handleCityChange = event => {
this.setState({
city: event.target.value
})
}
handlePhoneNumberChange = event => {
this.setState({
phoneNumber: event.target.value
})
}
handleEmailChange = event => {
this.setState({
email: event.target.value
})
}
getUser = () => {
axios.get()
.then(response => {
})
.catch (function (error) {
});
}
handleClickEditName = event => {
this.arrowName.style.display = 'none';
this.guardarName.style.display = 'inline-block';
this.name.style.display = "inline-block";
this.nameLabel.style.display = "none";
}
handleGuardarClickName = event => {
this.arrowName.style.display = 'inline-block';
this.guardarName.style.display = 'none';
this.name.style.display = "none";
this.nameLabel.style.display = "inline-block";
}
setRefArrowName = element => {
this.arrowName = element;
}
setRefGuardarName = element => {
this.guardarName = element;
}
setRefName = element => {
this.name = element;
}
setRefNameLabel = element => {
this.nameLabel = element;
}
handleClickEditPassword = event => {
this.arrowPassword.style.display = 'none';
this.guardarPassword.style.display = 'inline-block';
this.password.style.display = "inline-block";
this.passwordLabel.style.display = "none";
}
handleGuardarClickPassword = event => {
this.arrowPassword.style.display = 'inline-block';
this.guardarPassword.style.display = 'none';
this.password.style.display = "none";
this.passwordLabel.style.display = "inline-block";
}
setRefArrowPassword = element => {
this.arrowPassword = element;
}
setRefGuardarPassword = element => {
this.guardarPassword = element;
}
setRefPassword = element => {
this.password = element;
}
setRefPasswordLabel = element => {
this.passwordLabel = element;
}
handleClickEditEmail = event => {
this.arrowEmail.style.display = 'none';
this.guardarEmail.style.display = 'inline-block';
this.email.style.display = "inline-block";
this.emailLabel.style.display = "none";
}
handleGuardarClickEmail = event => {
this.arrowEmail.style.display = 'inline-block';
this.guardarEmail.style.display = 'none';
this.email.style.display = "none";
this.emailLabel.style.display = "inline-block";
}
setRefArrowEmail = element => {
this.arrowEmail = element;
}
setRefGuardarEmail = element => {
this.guardarEmail = element;
}
setRefEmail = element => {
this.email = element;
}
setRefEmailLabel = element => {
this.emailLabel = element;
}
handleClickEditPhoneNumber = event => {
this.arrowPhoneNumber.style.display = 'none';
this.guardarPhoneNumber.style.display = 'inline-block';
this.phoneNumber.style.display = "inline-block";
this.phoneNumberLabel.style.display = "none";
}
handleGuardarClickPhoneNumber = event => {
this.arrowPhoneNumber.style.display = 'inline-block';
this.guardarPhoneNumber.style.display = 'none';
this.phoneNumber.style.display = "none";
this.phoneNumberLabel.style.display = "inline-block";
}
setRefArrowPhoneNumber = element => {
this.arrowPhoneNumber = element;
}
setRefGuardarPhoneNumber = element => {
this.guardarPhoneNumber = element;
}
setRefPhoneNumber = element => {
this.phoneNumber = element;
}
setRefPhoneNumberLabel = element => {
this.phoneNumberLabel = element;
}
handleClickEditUniversity = event => {
this.arrowUniversity.style.display = 'none';
this.guardarUniversity.style.display = 'inline-block';
this.university.style.display = "inline-block";
this.universityLabel.style.display = "none";
}
handleGuardarClickUniversity = event => {
this.arrowUniversity.style.display = 'inline-block';
this.guardarUniversity.style.display = 'none';
this.university.style.display = "none";
this.universityLabel.style.display = "inline-block";
}
setRefArrowUniversity = element => {
this.arrowUniversity = element;
}
setRefGuardarUniversity = element => {
this.guardarUniversity = element;
}
setRefUniversity = element => {
this.university = element;
}
setRefUniversityLabel = element => {
this.universityLabel = element;
}
handleClickEditUniversityCode = event => {
this.arrowUniversityCode.style.display = 'none';
this.guardarUniversityCode.style.display = 'inline-block';
this.universityCode.style.display = "inline-block";
this.universityCodeLabel.style.display = "none";
}
handleGuardarClickUniversityCode = event => {
this.arrowUniversityCode.style.display = 'inline-block';
this.guardarUniversityCode.style.display = 'none';
this.universityCode.style.display = "none";
this.universityCodeLabel.style.display = "inline-block";
}
setRefArrowUniversityCode = element => {
this.arrowUniversityCode = element;
}
setRefGuardarUniversityCode = element => {
this.guardarUniversityCode = element;
}
setRefUniversityCode = element => {
this.universityCode = element;
}
setRefUniversityCodeLabel = element => {
this.universityCodeLabel = element;
}
handleClickEditCountry = event => {
this.arrowCountry.style.display = 'none';
this.guardarCountry.style.display = 'inline-block';
this.country.style.display = "inline-block";
this.countryLabel.style.display = "none";
}
handleGuardarClickCountry = event => {
this.arrowCountry.style.display = 'inline-block';
this.guardarCountry.style.display = 'none';
this.country.style.display = "none";
this.countryLabel.style.display = "inline-block";
}
setRefArrowCountry = element => {
this.arrowCountry = element;
}
setRefGuardarCountry = element => {
this.guardarCountry = element;
}
setRefCountry = element => {
this.country = element;
}
setRefCountryLabel = element => {
this.countryLabel = element;
}
handleClickEditDepartment = event => {
this.arrowDepartment.style.display = 'none';
this.guardarDepartment.style.display = 'inline-block';
this.department.style.display = "inline-block";
this.departmentLabel.style.display = "none";
}
handleGuardarClickDepartment = event => {
this.arrowDepartment.style.display = 'inline-block';
this.guardarDepartment.style.display = 'none';
this.department.style.display = "none";
this.departmentLabel.style.display = "inline-block";
}
setRefArrowDepartment = element => {
this.arrowDepartment = element;
}
setRefGuardarDepartment = element => {
this.guardarDepartment = element;
}
setRefDepartment = element => {
this.department = element;
}
setRefDepartmentLabel = element => {
this.departmentLabel = element;
}
handleClickEditCity = event => {
this.arrowCity.style.display = 'none';
this.guardarCity.style.display = 'inline-block';
this.city.style.display = "inline-block";
this.cityLabel.style.display = "none";
}
handleGuardarClickCity = event => {
this.arrowCity.style.display = 'inline-block';
this.guardarCity.style.display = 'none';
this.city.style.display = "none";
this.cityLabel.style.display = "inline-block";
}
setRefArrowCity = element => {
this.arrowCity = element;
}
setRefGuardarCity = element => {
this.guardarCity = element;
}
setRefCity = element => {
this.city = element;
}
setRefCityLabel = element => {
this.cityLabel = element;
}
render() {
return (
<div style={{width: '100%'}}>
<UpdateInfoClientLayout
name = {this.state.name}
lastName = {this.state.lastName}
phoneNumber = {this.state.phoneNumber}
password = {this.state.password}
universityCode = {this.state.universityCode}
university = {this.state.university}
country = {this.state.country}
department = {this.state.department}
city = {this.state.city}
email = {this.state.email}
handleUniversityChange = {this.handleUniversityChange}
handleNameChange = {this.handleNameChange}
handleLastNameChange = {this.handleLastNameChange}
handleUniversityCodeChange = {this.handleUniversityCodeChange}
handlePasswordChange = {this.handlePasswordChange}
handleCountryChange = {this.handleCountryChange}
handleDepartmentChange = {this.handleDepartmentChange}
handleCityChange = {this.handleCityChange}
handlePhoneNumberChange = {this.handlePhoneNumberChange}
handleEmailChange = {this.handleEmailChange}
setRefArrowName = {this.setRefArrowName}
handleClickEditName = {this.handleClickEditName}
setRefGuardarName = {this.setRefGuardarName}
setRefName = {this.setRefName}
setRefNameLabel = {this.setRefNameLabel}
handleGuardarClickName = {this.handleGuardarClickName}
setRefArrowPassword = {this.setRefArrowPassword}
handleClickEditPassword = {this.handleClickEditPassword}
setRefGuardarPassword = {this.setRefGuardarPassword}
setRefPassword = {this.setRefPassword}
setRefPasswordLabel = {this.setRefPasswordLabel}
handleGuardarClickPassword = {this.handleGuardarClickPassword}
setRefArrowEmail = {this.setRefArrowEmail}
handleClickEditEmail = {this.handleClickEditEmail}
setRefGuardarEmail = {this.setRefGuardarEmail}
setRefEmail = {this.setRefEmail}
setRefEmailLabel = {this.setRefEmailLabel}
handleGuardarClickEmail = {this.handleGuardarClickEmail}
setRefArrowPhoneNumber = {this.setRefArrowPhoneNumber}
handleClickEditPhoneNumber = {this.handleClickEditPhoneNumber}
setRefGuardarPhoneNumber = {this.setRefGuardarPhoneNumber}
setRefPhoneNumber = {this.setRefPhoneNumber}
setRefPhoneNumberLabel = {this.setRefPhoneNumberLabel}
handleGuardarClickPhoneNumber = {this.handleGuardarClickPhoneNumber}
setRefArrowUniversity = {this.setRefArrowUniversity}
handleClickEditUniversity = {this.handleClickEditUniversity}
setRefGuardarUniversity = {this.setRefGuardarUniversity}
setRefUniversity = {this.setRefUniversity}
setRefUniversityLabel = {this.setRefUniversityLabel}
handleGuardarClickUniversity = {this.handleGuardarClickUniversity}
setRefArrowUniversityCode = {this.setRefArrowUniversityCode}
handleClickEditUniversityCode = {this.handleClickEditUniversityCode}
setRefGuardarUniversityCode = {this.setRefGuardarUniversityCode}
setRefUniversityCode = {this.setRefUniversityCode}
setRefUniversityCodeLabel = {this.setRefUniversityCodeLabel}
handleGuardarClickUniversityCode = {this.handleGuardarClickUniversityCode}
setRefArrowCountry = {this.setRefArrowCountry}
handleClickEditCountry = {this.handleClickEditCountry}
setRefGuardarCountry = {this.setRefGuardarCountry}
setRefCountry = {this.setRefCountry}
setRefCountryLabel = {this.setRefCountryLabel}
handleGuardarClickCountry = {this.handleGuardarClickCountry}
setRefArrowDepartment = {this.setRefArrowDepartment}
handleClickEditDepartment = {this.handleClickEditDepartment}
setRefGuardarDepartment = {this.setRefGuardarDepartment}
setRefDepartment = {this.setRefDepartment}
setRefDepartmentLabel = {this.setRefDepartmentLabel}
handleGuardarClickDepartment = {this.handleGuardarClickDepartment}
setRefArrowCity = {this.setRefArrowCity}
handleClickEditCity = {this.handleClickEditCity}
setRefGuardarCity = {this.setRefGuardarCity}
setRefCity = {this.setRefCity}
setRefCityLabel = {this.setRefCityLabel}
handleGuardarClickCity = {this.handleGuardarClickCity}
/>
</div>
)
}
}
export default UpdateInfoClient;
|
/**
* Created by hugo on 2018/9/3.
*/
module.exports.navTitle = [
{
name: '文章',
link: '/article'
},
{
name: '资源',
link: '/resource'
}
]
|
import React, { Component } from 'react';
import { Layout } from 'antd';
import { connect } from 'react-redux';
import {BrowserRouter} from "react-router-dom";
import AppContent from './app-content/index.js';
import AppHeader from './app-header/index.js';
import AppHeaderUser from './app-header/app-header-user/index.js';
import { doChangeLoginState } from '../redux/action/user';
import Cookies from 'js-cookie';
import './index.css';
const { Header, Content } = Layout;
class AppLayout extends Component {
componentWillMount(){
let userId = Cookies.get('userId');
let mobileNumber = Cookies.get('mobileNumber');
if(userId && mobileNumber){
fetch('/server/user/autoLogin',{
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'mobileNumber=' + encodeURIComponent(mobileNumber) + '&userId=' + encodeURIComponent(userId)
}).then(res => {
return res.json();
}).then(res => {
if(res.isCorrect){
this.props.onChangeLoginState(true);
}
})
}
}
render() {
return (
<BrowserRouter>
<Layout>
<Header className="app-layout-header">
<AppHeader/>
</Header>
<Content>
<AppContent/>
</Content>
</Layout>
</BrowserRouter>
);
}
}
const mapStateToProps = (state) => {
return {
}
}
const mapDispatchToProps = (dispatch) => {
return {
onChangeLoginState: (loginState) => dispatch(doChangeLoginState(loginState))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AppLayout); |
const Product = require('../models/Product')
module.exports = {
find: (req, res, next) => {
Product.find()
.then(products => {
res.status(200).json(products)
})
.catch(next)
},
add: (req, res, next) => {
const { name, description, price, stock, series, image } = req.body
Product.create({ name, description, price, stock, series, image })
.then(product => {
res.status(201).json(product)
})
.catch(next)
},
update: (req, res, next) => {
const { name, description, price, stock, series, image } = req.body
Product.findByIdAndUpdate(req.params.id, {
name, description, price, stock, series, image
}, {useFindAndModify: false, omitUndefined: true, runValidators: true})
.then(product => {
res.status(200).json(product)
})
.catch(next)
},
delete: (req, res, next) => {
Product.findByIdAndDelete(req.params.id)
.then(product => {
res.status(200).json(product)
})
.catch(next)
}
} |
const loggedOutLinks = document.querySelectorAll(".logged-out");
const loggedInLinks = document.querySelectorAll(".logged-in");
let admin=document.querySelectorAll(".admin");
const loginCheck = user => {
if (user){
loggedInLinks.forEach(link=>link.style.display="block");
loggedOutLinks.forEach(link=>link.style.display="none");
admin.forEach(element=>element.style.display="block");
}
else{
loggedInLinks.forEach(link=>link.style.display="none");
loggedOutLinks.forEach(link=>link.style.display="block");
admin.forEach(element=>element.style.display="none");
}
}
// ------------------------------ REGISTER A USER------------------------------------
document.querySelector("#signup-form").addEventListener(`submit`, (e)=>{
e.preventDefault();
let email=document.querySelector("#signup-email").value;
let password=document.querySelector("#signup-password").value;
auth
.createUserWithEmailAndPassword(email,password)
.then(userCredential=>{
document.querySelector("#signup-form").reset;
$(`#signupModal`).modal(`hide`);
})
.catch(error=>{
alert(error.message);
})
});
//------------------------------- AUTH USER------------------------------------------
document.querySelector("#login-form").addEventListener(`submit`, (e)=>{
e.preventDefault();
let email=document.querySelector("#login-email").value;
let password=document.querySelector("#login-password").value;
auth
.signInWithEmailAndPassword(email,password)
.then(userCredential=>{
document.querySelector("#login-form").reset;
})
.catch(error=>{
alert(error);
})
});
document.querySelector("#logout").addEventListener(`click`, (e)=> {
e.preventDefault();
auth.signOut().then(()=>{
})
});
//------------------------------- GOOGLE AUTH USER------------------------------------------
document.querySelector("#googleLogin").addEventListener(`click`,(e)=>{
e.preventDefault();
const provider = new firebase.auth.GoogleAuthProvider();
auth.signInWithPopup(provider)
.then(result => {
})
.catch(err => {
console.log(err);
})
});
auth.onAuthStateChanged(user =>{
if (user) {
loginCheck(user);
$(`#signinModal`).modal(`hide`);
}
else{
loginCheck(user);
}
});
const recipesContainer = document.getElementById("recipes-container");
const onGetRecipe = (callback) => db.collection("cooking-recipe").onSnapshot(callback);
window.addEventListener("DOMContentLoaded", async (e) => {
await onGetRecipe((querySnapshot) => {
recipesContainer.innerHTML = "";
let datosLength=querySnapshot.docs.length;
let textHTML=[""];
let counter=1;
let counter2=0;
let counter3=1;
querySnapshot.forEach((doc) => {
const recipe = doc.data();
textHTML[counter2]+=`<div class="col-sm container-card p-0 m-2"><a href="recipe.html?id=${doc.id}">
<img src="${recipe.imageURL}" class="card-img-top" alt="..."></a>
<button type="button" class="btn btn-danger admin delete" imagereference="${recipe.imageReference}" docid="${doc.id}" style="display:none;">Borrar</button>
<a href="update-recipe.html?id=${doc.id}&imageReference=${recipe.imageReference}"><button type="button" class="btn btn-primary admin edit" style="display:none;">Editar</button></a>
<div class="card-body"><a href="recipe.html?id=${doc.id}" id="card-text">${recipe.name}</a></div>
</div>`;
if(counter===3){
textHTML[counter2]=`<div class="row">${textHTML[counter2]}</div>`;
textHTML[counter2+1]="";
counter2=counter2+1;
counter=0;
}
else{
if(counter3===datosLength){
textHTML[counter2]=`<div class="row">${textHTML[counter2]}</div>`;
}
}
counter=counter+1;
counter3=counter3+1;
});
for(let i=0;i<textHTML.length;i++){
recipesContainer.innerHTML +=textHTML[i];
}
admin=document.querySelectorAll(".admin");
if(document.querySelector(".new-recipe").getAttribute("style")==="display: none;"){
admin.forEach(element=>element.style.display="none");
}
else if(document.querySelector(".new-recipe").getAttribute("style")==="display: block;"){
admin.forEach(element=>element.style.display="block");
}
document.querySelectorAll(".delete").forEach(element=>{
element.addEventListener(`click`,()=>{
borrar(element.getAttribute("docid"),element.getAttribute("imagereference"))
});
});
});
});
function borrar(docid,imagereference){
//Borrar imagen
let imgReference = storageRef.child(imagereference);
imgReference.delete().then(function() {
}).catch(function(error) {
console.log(error);
});
//Borrar datos
db.collection("cooking-recipe").doc(docid).delete().then(() => {
}).catch((error) => {
console.error("Error removing document: ", error);
});
}
const deleteTask = (id) => db.collection("tasks").doc(id).delete();
|
const validPerms = [
'CREATE_INSTANT_INVITE',
'KICK_MEMBERS',
'BAN_MEMBERS',
'ADMINISTRATOR',
'MANAGE_CHANNELS',
'MANAGE_GUILD',
'ADD_REACTIONS', // add reactions to messages
'READ_MESSAGES',
'SEND_MESSAGES',
'SEND_TTS_MESSAGES',
'MANAGE_MESSAGES',
'EMBED_LINKS',
'ATTACH_FILES',
'READ_MESSAGE_HISTORY',
'MENTION_EVERYONE',
'EXTERNAL_EMOJIS', // use external emojis
'CONNECT', // connect to voice
'SPEAK', // speak on voice
'MUTE_MEMBERS', // globally mute members on voice
'DEAFEN_MEMBERS', // globally deafen members on voice
'MOVE_MEMBERS', // move member's voice channels
'USE_VAD', // use voice activity detection
'CHANGE_NICKNAME',
'MANAGE_NICKNAMES', // change nicknames of others
'MANAGE_ROLES_OR_PERMISSIONS',
'MANAGE_WEBHOOKS',
'MANAGE_EMOJIS'
]
exports.bot = function (bot, message, permission) {
if (!permission || !validPerms.includes(permission)) return true
const channel = message.channel
const guild = bot.guilds.get(channel.guild.id)
const guildBot = guild.members.get(bot.user.id)
const hasPerm = guildBot.permissionsIn(channel).has(permission)
if (permission === 'MANAGE_ROLES_OR_PERMISSIONS' && !hasPerm) {
console.log(`Commands Warning: (${channel.guild.id}, ${channel.guild.name}) => Self subscription disabled due to missing permission.`)
message.channel.send('Function disabled due to missing `Manage Roles` permission.').then(m => m.delete(3000))
}
return hasPerm
}
exports.user = function (message, permission) {
if (!permission || !validPerms.includes(permission)) return true
const serverPerm = message.member.hasPermission(permission)
const channelPerm = message.member.permissionsIn(message.channel).has(permission)
if (serverPerm || channelPerm) return true
else return false
}
|
import {makeStyles} from "@material-ui/styles";
export const useStyles = makeStyles({
wrapper: {
display: "flex",
flexDirection: 'row',
justifyContent: 'space-between',
width: '50%',
flexWrap: 'wrap',
backgroundColor: 'white',
border: '1px solid lightgrey',
borderRadius: '4px',
rowGap: '30px',
padding: 20,
"& svg": {
cursor: 'pointer'
}
},
timeSlotsWrapper: {
minHeight:"25vh",
display: "flex",
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
columnGap: '10px',
},
timeSlot: {
width: '50px',
height: '30px',
backgroundColor: 'white',
border: '1px solid grey',
textAlign: "center",
lineHeight: '30px',
fontSize: '12px',
'&:hover': {
backgroundColor: 'dodgerblue',
color: 'white',
cursor: 'pointer'
}
},
timeSlotDisabled: {
color: 'lightgrey',
border: '1px solid lightgrey',
width: '50px',
height: '30px',
backgroundColor: 'white',
textAlign: "center",
lineHeight: '30px',
fontSize: '12px',
cursor: 'pointer',
"& hover": {
backgroundColor: 'white'
}
},
slots: {
display: "flex",
flexDirection: 'row',
alignItems: 'flex-start',
justifyContent: 'flex-start',
columnGap: '5px',
rowGap: '5px',
flexWrap: 'wrap',
},
imageWrapper: {
height: '100%',
width: '20%',
'& img': {
objectFit: 'contain'
}
},
slotsWrapper: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
rowGap: '10px',
},
movieInfo: {
height: '100%',
maxWidth: '70%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
rowGap: '10px',
'& p': {
color: 'grey',
fontSize: '12px'
},
"& > div": {
minHeight: '30%',
}
}
}) |
var roleBuilder = {
/** @param {Creep} creep **/
run: function(creep) {
if(creep.memory.building && creep.carry.energy == 0) {
creep.memory.building = false;
creep.say('-- harvest --');
}
if(!creep.memory.building && creep.carry.energy == creep.carryCapacity) {
var targets = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType == STRUCTURE_EXTENSION ||
structure.structureType == STRUCTURE_SPAWN ||
structure.structureType == STRUCTURE_TOWER
) && ((_.sum(structure.store) < structure.storeCapacity) || (structure.energy < structure.energyCapacity));
}
});
if(targets.length > 0) {
if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(targets[0], {visualizePathStyle: {stroke: '#ffffff'}});
}
}
creep.memory.building = true;
creep.say('-- build --');
}
if(creep.memory.building) {
var targets = creep.room.find(FIND_CONSTRUCTION_SITES);
if(targets.length) {
if(creep.build(targets[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(targets[0], {visualizePathStyle: {stroke: '#ffffff'}});
}
}else{
creep.memory.building = false;
}
}
else {
var sources = creep.room.find(FIND_DROPPED_ENERGY);
var x;
for(var i = 0; i < sources.length; i ++){
if(sources[x].energy > 0){
x = i;
}
}
if(creep.pickup(sources[x]) == ERR_NOT_IN_RANGE) {
creep.pickup(sources[x], {visualizePathStyle: {stroke: '#ffaa00'}});
}
}
}
};
module.exports = roleBuilder; |
import http from "./httpService";
async function getBookings(monthObj) {
try {
const { data: bookings } = await http.post(
`${http.baseUrl}/bookings/filterByMonth`,
monthObj
);
return bookings;
} catch (error) {
console.log(error);
}
}
async function getBookingsForWeek(date) {
try {
const { data: bookings } = await http.post(
`${http.baseUrl}/bookings/filterByWeek`,
{fromDate:date}
);
return bookings;
} catch (error) {
console.log(error);
}
}
async function addBooking(booking) {
try {
return await http.post(`${http.baseUrl}/bookings/insert`, booking);
} catch (error) {
console.log(error);
}
}//${http.baseUrl} //http://localhost:5000
async function getProofId(id) {
try {
return await http.get(`${http.baseUrl}/booking/idproof/${id}`);
} catch (error) {
console.log(error);
}
}
async function updateBooking(booking) {
try {
return await http.put(`${http.baseUrl}/bookings/update`, booking);
} catch (error) {
console.log(error);
}
}
async function getDayCheckin(date) {
try {
const { data: bills } = await http.get(`${http.baseUrl}/bookings/dayCheckin?date=${date}`);
return bills;
} catch (error) {
console.log(error);
}
}
async function searchGuest(param) {
try {
const { data: bills } = await http.get(`${http.baseUrl}/search/booking?search=${param}`);
return bills;
} catch (error) {
console.log(error);
}
}
async function searchGuestByDate(param) {
try {
const { data: bills } = await http.get(`${http.baseUrl}/search/booking?searchdate=${param}`);
return bills;
} catch (error) {
console.log(error);
}
}
async function getTodaysCheckin() {
try {
let date = new Date().toISOString().split("T")[0]
const { data: bills } = await http.get(`${http.baseUrl}/search/booking?checkin=${date}`);
return bills;
} catch (error) {
console.log(error);
}
}
async function getExpectedCheckouts() {
try {
const { data: bills } = await http.get(`${http.baseUrl}/expectedcheckouts`);
return bills;
} catch (error) {
console.log(error);
}
}
export default { getBookings, getBookingsForWeek, addBooking, updateBooking, getProofId, getDayCheckin, searchGuest, getTodaysCheckin, searchGuestByDate, getExpectedCheckouts };
|
angular.module('ucms.app.core')
.controller('coreCtrl', function ($scope, $xhttp, $localStorage, $rootScope, $sce,$modal, $q, $timeout, $folder, $contentType) {
// auto renew folder data
$scope.currentUser = {};
$scope.normalSidebarMenu = {
Items: [
{
Id: "dashboard",
Name: "Dashboard",
Url: "/",
Icon: "icon-home",
CheckPermission: false
}
]
};
$scope.setupSidebarMenu = {};
$scope.thumbAvatar = "";
$scope.selectedFields = {};
$scope.folders = [];
$scope.logout = function () {
delete $localStorage.authData;
window.location.href = '/login';
}
var folderId, ctypeId; // id of selected objects as Folder, Contenttype, Field
//==== START: ADVANCED SEARCH ==================================
// An object is representer of advanced search configuration
$scope.headerAdvSearchConfig = {
show: false,
selectedField: [],
libraries: [],
keyWord: '',
advSearchInFields: false,
selectedFolderNode: null,
selectedContentType: null,
advSearchInAttch: false
};
$scope.libraries = null;
function loadContentType(folderId) {
$contentType.getByFolderId(folderId).then(function (response) {
$scope.contentTypes = response.data;
if (ctypeId && ctypeId != '')
$scope.headerAdvSearchConfig.selectedContentType = _.find($scope.contentTypes, { 'Id': ctypeId });
});
}
// when selected library has changed in Advance Search panel
$scope.libChanged = function (target) {
if (target) {
$scope.headerAdvSearchConfig.selectedFolderNode = target;
// find root parent
var rootId = target.root;
loadContentType(rootId);
$scope.showFolderTree = false;
}
}
function convertFolderToNode(folder, parent) {
var node = {
"id": folder.Id,
"root": (parent) ? parent.Id : folder.Id,
"name": folder.Name,
"children": []
};
// check and set as selected folder
if ($scope.headerAdvSearchConfig.selectedFolderNode && $scope.headerAdvSearchConfig.selectedFolderNode.id == folder.Id) {
$scope.headerAdvSearchConfig.selectedFolderNode = node;
}
_.forEach(folder.SubFolders, function (subFolder) {
node.children.push(convertFolderToNode(subFolder, folder));
});
return node;
}
$scope.fieldsDialog = function (headerAdvSearchConfig) {
if (headerAdvSearchConfig.selectedContentType && headerAdvSearchConfig.selectedContentType.Id != '' && $scope.selectedFields) {
var listKey = Object.keys($scope.selectedFields);
var listValue = Object.values($scope.selectedFields);
for (var i = 0; i < listKey.length ; i++) {
var typeField = _.find(headerAdvSearchConfig.selectedContentType.Fields, { 'Name': listKey[i] });
if (typeField.DataType == 'Date')
typeField['Value'] = new Date(moment.utc(listValue[i]).format('YYYY-MM-DD'));
else if (typeField.DataType == 'DateTime')
typeField['Value'] = new Date(moment.utc(listValue[i]).format('YYYY-MM-DD HH:mm'));
else
typeField['Value'] = listValue[i];
}
}
$scope.selectedFields = {};
$modal.showFieldsDialog(headerAdvSearchConfig).then(function (res) {
if (!res.advSearchInAttch && res.selectedContentType)
_.forEach(res.selectedContentType.Fields, function (item) {
if ((item.DataType === "Date" || item.DataType === "DateTime") && item.Value) {
var datetimeFormat = (item.DataType === "Date") ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm';
item.Value = moment(item.Value).format(datetimeFormat);
}
if (item.DataType === "MultiSelect" && item.Value) {
item.Value = item.Value.join(' ');
}
if (item.Value) {
$scope.selectedFields[item.Name] = item.Value;
}
});
$scope.headerAdvSearchConfig = res;
$scope.searchClick();
});
}
$scope.loadLibraries = function () {
var libraries = [];
var defer = $q.defer();
$folder.getFolderTree().then(function (response) {
_.forEach(response, function (folder) {
var node = convertFolderToNode(folder);
libraries.push(node);
});
defer.resolve(libraries);
});
return defer.promise;
}
$scope.searchClick = function () {
if (!(($scope.headerAdvSearchConfig.keyWord && $scope.headerAdvSearchConfig.keyWord.length > 2) || ($scope.headerAdvSearchConfig.advSearchInFields && $scope.headerAdvSearchConfig.selectedContentType))) {
return;
}
$scope.selectedFields = $scope.headerAdvSearchConfig.advSearchInFields ? $scope.selectedFields : null;
var newLocation = '/search?query=' + ($scope.headerAdvSearchConfig.advSearchInFields ? "" : encodeURIComponent($scope.headerAdvSearchConfig.keyWord));
newLocation += ($scope.headerAdvSearchConfig.selectedFolderNode) ? "&folder=" + $scope.headerAdvSearchConfig.selectedFolderNode.id : "";
newLocation += ($scope.headerAdvSearchConfig.selectedContentType) ? "&ctype=" + $scope.headerAdvSearchConfig.selectedContentType.Id : "";
newLocation += $scope.selectedFields ? "&fields=" + JSON.stringify($scope.selectedFields) : '';
newLocation += ($scope.headerAdvSearchConfig.advSearchInAttch) ? "&inattch=" + $scope.headerAdvSearchConfig.advSearchInAttch : "";
newLocation += ($scope.headerAdvSearchConfig.advSearchInFields) ? "&infields=" + $scope.headerAdvSearchConfig.advSearchInFields : "";
window.location = newLocation;
}
// when user click to any positions is out of advanced search zone, hide the panel
window.onclick = function (e) {
/// check is target is inside advanced search form
var element = e.target;
var isInAdvSearch = false;
while (element != null) {
if (element.id == "header-advsearch-form" ||
element.className.indexOf("search-form-expanded") != -1 ||
element.className.indexOf("search-expand-btn") != -1) {
isInAdvSearch = true;
break;
}
element = element.parentElement;
}
if (!isInAdvSearch) {
$scope.headerAdvSearchConfig.show = false;
}
$timeout(function () {
$scope.$apply();
});
}
//==== END: ADVANCED SEARCH ==================================
$scope.init = function () {
$scope.loadLibraries().then(function (libraries) {
$scope.libraries = libraries;
$scope.headerAdvSearchConfig.libraries = libraries;
// set initialized values
$scope.headerAdvSearchConfig.keyWord = Utils.getParameterByName("query").trim();
folderId = (Utils.getParameterByName("folder").trim() != '') ? Utils.getParameterByName("folder").trim() : null;
ctypeId = (Utils.getParameterByName("ctype").trim() != '') ? Utils.getParameterByName("ctype").trim() : null;
$scope.selectedFields = (Utils.getParameterByName("fields").trim() != '') ? JSON.parse(Utils.getParameterByName("fields").trim()) : null;
$scope.headerAdvSearchConfig.advSearchInAttch = (Utils.getParameterByName("inattch").trim() != '') ? Utils.getParameterByName("inattch").trim() == true.toString() : false;
$scope.headerAdvSearchConfig.advSearchInFields = (Utils.getParameterByName("infields").trim() != '') ? Utils.getParameterByName("infields").trim() == true.toString() : false;
if (folderId && folderId != '') {
$scope.headerAdvSearchConfig.selectedFolderNode = _.find(libraries, { 'id': folderId });
loadContentType(folderId);
}
});
// get normal Setup sideBar menu items
$xhttp.get('/api/config/getsidebarmenu?isSetupMenu=true').then(function (response) {
$scope.setupSidebarMenu = response.data;
_.forEach($scope.setupSidebarMenu.Items, function (item) {
item.Description = $sce.trustAsHtml(item.Description);
})
}, function (err) {
});
//===== FOLDERS TREE ==========
var isContentPage = (window.location.toString().indexOf('/content/addedit') != -1) ||
(window.location.toString().indexOf('/workflow/status') != -1);
$folder.getFolderTree().then(function (data) {
$scope.folders = data;
});
$xhttp.get(WEBAPI_ENDPOINT + '/api/user/getmyprofile').then(function(response) {
$scope.currentUser = response.data;
});
}
}); |
var ws = new WebSocket('wss://soliturn.com:8080');
ws.onopen = function(evt) {
var jsonmessage = {'type':'key','message':tkey};
ws.send(JSON.stringify(jsonmessage));
}
ws.onmessage = function(evt){
var dm;
if (evt.data[0]=='{'){
dm = JSON.parse(evt.data);
}
if (dm.type && dm.type == 'saved'){
var el = document.getElementById('gameLink');
el.setAttribute('href','../'+username+'/'+dm.name);
el.style.display = 'inline-block';
}
else if (dm.puzzle){
document.getElementById("sudoku").value = dm.puzzle;
chgSudoku();
}
}
function chgIPT(evt) {
var el = evt.target;
var i = parseInt(el.id.split('-')[1]);
var iiminus1 = parseInt(el.id.split('-')[2]);
var val = parseInt(el.value);
console.log('Reset');
if (val > 0){
itemPerThing[i][iiminus1]=val;
spendPerThing[i][iiminus1]=0;
el.classList.add('positive');
el.classList.remove('negative');
el.classList.remove('zero');
}
else if (val <0){
itemPerThing[i][iiminus1]=0;
spendPerThing[i][iiminus1]=-1*val;
el.classList.add('negative');
el.classList.remove('positive');
el.classList.remove('zero');
}
else {
itemPerThing[i][iiminus1]=0;
spendPerThing[i][iiminus1]=0;
el.classList.add('zero');
el.classList.remove('negative');
el.classList.remove('positive');
}
resetGame();
}
function chgSPP(evt) {
var el = evt.target;
var i = parseInt(el.id.split('-')[1]);
var val = parseInt(el.value);
if (val < 0){
spendPerPerson[i]=-1*val;
}
else if (val >0){
spendPerPerson[i]=-1*val;//Is a negative spend possible?
}
else {
spendPerPerson[i]=0;
}
resetGame();
}
function chgResource(evt) {
var el = evt.target;
var id = parseInt(el.id.substr(8,9));
var ell = document.getElementById("emojiData");
var elll = ell.querySelectorAll("td")[id-1];
emojiList[id-1] = el.value;
elll.textContent = el.value;
document.getElementById("income"+id+"emoji").textContent = el.value;
}
function chgInitial(evt) {
var el = evt.target;
var id = parseInt(el.id.substr(8,9));
var ell = document.getElementById("initialData");
//var elll = ell.querySelectorAll("td")[id-1];
//elll.textContent = el.value;
if (id < 7){
totalsReset[id]=parseInt(el.value);
minTotalsReset[id]=parseInt(el.value);
ell = document.getElementById("minimum-"+id);
ell.textContent = el.value;
}
else {
nPeopleReset = parseInt(el.value);
}
resetGame();
}
document.getElementById("resource1emoji").addEventListener('change',chgResource);
document.getElementById("resource2emoji").addEventListener('change',chgResource);
document.getElementById("resource3emoji").addEventListener('change',chgResource);
document.getElementById("resource4emoji").addEventListener('change',chgResource);
document.getElementById("resource5emoji").addEventListener('change',chgResource);
document.getElementById("resource6emoji").addEventListener('change',chgResource);
document.getElementById("resource7emoji").addEventListener('change',chgResource);
document.getElementById("resource1initial").addEventListener('change',chgInitial);
document.getElementById("resource2initial").addEventListener('change',chgInitial);
document.getElementById("resource3initial").addEventListener('change',chgInitial);
document.getElementById("resource4initial").addEventListener('change',chgInitial);
document.getElementById("resource5initial").addEventListener('change',chgInitial);
document.getElementById("resource6initial").addEventListener('change',chgInitial);
document.getElementById("resource7initial").addEventListener('change',chgInitial);
function chgBPY(evt) {
var el = evt.target;
if (el.id == 'births'){
bpyReset[0]=parseInt(el.value);
}
else {
bpyReset[1]=parseInt(el.value);
}
resetGame();
}
document.getElementById("births").addEventListener('change',chgBPY);
document.getElementById("perYear").addEventListener('change',chgBPY);
function chgItem(evt) {
var el = evt.target;
var id = parseInt(el.id.substr(4,5));
imgList[id]=el.getAttribute('data-value');
var ell = document.getElementById('button-'+id);
ell.innerHTML = '';
var img = document.createElement('img');
img.setAttribute('src',"../sfarm/"+el.getAttribute('data-value')+".png");
ell.appendChild(img);
ell = document.getElementById('header-'+id).querySelector('img');
ell.setAttribute('src',"../sfarm/"+el.getAttribute('data-value')+".png");
ell = document.getElementById('item'+id+'img');
ell.setAttribute('src',"../sfarm/"+el.getAttribute('data-value')+".png");
resetGame();
}
document.getElementById("item1icon").addEventListener('awesomplete-selectcomplete',chgItem);
document.getElementById("item2icon").addEventListener('awesomplete-selectcomplete',chgItem);
document.getElementById("item3icon").addEventListener('awesomplete-selectcomplete',chgItem);
document.getElementById("item4icon").addEventListener('awesomplete-selectcomplete',chgItem);
document.getElementById("item5icon").addEventListener('awesomplete-selectcomplete',chgItem);
document.getElementById("item6icon").addEventListener('awesomplete-selectcomplete',chgItem);
document.getElementById("item7icon").addEventListener('awesomplete-selectcomplete',chgItem);
document.getElementById("item8icon").addEventListener('awesomplete-selectcomplete',chgItem);
document.getElementById("item9icon").addEventListener('awesomplete-selectcomplete',chgItem);
function chgSudoku() {
var el = document.getElementById("sudoku");
var puzzleRaw = el.value;
puzzleRaw = puzzleRaw.replace(/\s/g,'');
puzzleRaw = puzzleRaw.replace(/\t/g,'');
puzzleRaw = puzzleRaw.replace(/\n/g,'');
puzzleRaw = puzzleRaw.replace(/\|/g,'');
puzzleRaw = puzzleRaw.replace(/-/g,'');
puzzleRaw = puzzleRaw.replace(/\./g,'0');
var puzzles = [];
var puzzle = [];
var row = [];
for (var i=0;i<puzzleRaw.length;i++){
if ('0123456789'.indexOf(puzzleRaw[i])>-1){
row.push(puzzleRaw[i]);
}
if (row.length == 9){
puzzle.push(row);
row = [];
}
if (puzzle.length==9){
puzzles.push(puzzle);
puzzle = [];
}
}
if (puzzles.length > 0){
puzzleReset = [];
for (var i=0;i<puzzles[0].length;i++){
puzzleReset.push(puzzles[0][i].slice());
}
moves = [];
resetGame();
}
}
function randomSudoku(evt) {
var elid = evt.target.id;
var difficulty = 'easy';
if (elid == 'randomMedium'){
difficulty = 'medium';
}
else if (elid == 'randomHard'){
difficulty = 'hard';
}
var jsonmessage = {'type':'sudoku','difficulty':difficulty};
ws.send(JSON.stringify(jsonmessage));
}
document.getElementById("sudoku").addEventListener('change',chgSudoku);
document.getElementById("randomEasy").addEventListener('click',randomSudoku);
document.getElementById("randomMedium").addEventListener('click',randomSudoku);
document.getElementById("randomHard").addEventListener('click',randomSudoku);
function saveGame(evt) {
var jsonmessage = {'type':'save','game':{}};
jsonmessage.game['puzzle']=puzzleReset;//is updating on change
jsonmessage.game['totals']=totalsReset;//is updating on change
jsonmessage.game['nPeople']=nPeopleReset;//is updating on change
jsonmessage.game['bpy']=bpyReset;//is updating on change
jsonmessage.game['itemPerThing']=itemPerThing;//is updating on change
jsonmessage.game['spendPerThing']=spendPerThing;//is updating on change
jsonmessage.game['spendPerPerson']=spendPerPerson;//is updating on change
jsonmessage.game['imgList']=imgList;//is updating on change
jsonmessage.game['emojiList']=emojiList;//is updating on change
ws.send(JSON.stringify(jsonmessage));
}
document.getElementById("saveGame").addEventListener('click',saveGame);
|
import { FETCH_CHITS, ADD_CHIT, UPDATE_CHIT } from './types';
import { uri } from '../constants';
import axios from 'axios';
export const fetchChits = () => dispatch =>
axios.get(uri + 'chits').then(payload => {
dispatch({
type: FETCH_CHITS,
chits: payload.data,
});
});
export const addChit = value => dispatch =>
axios
.post(uri + 'chits', {
...value,
})
.then(response => {
dispatch({
type: ADD_CHIT,
newChit: response.data,
});
})
.catch(error => {
console.log(error);
});
export const updateChits = value => dispatch =>
axios
.patch(uri + 'chits/' + value._id, {
...value,
})
.then(response => {
dispatch({
type: UPDATE_CHIT,
updatedUser: response._id,
});
})
.catch(error => {
console.log(error);
});
|
import React from 'react';
import Todo from './Todo';
class TodoList extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
console.log('delete this task');
}
render() {
let that = this;
let list = this.props.toDoList.map(function(todo) {
return (
<Todo key={todo.id} todo={todo} />
);
});
return (
<div>
<h3>TodoList Component</h3>
<ul>
{list}
</ul>
</div>
);
}
}
export default TodoList; |
import React from "react";
const API = "https://api.wheretheiss.at/v1/satellites/25544";
export default function Refactored() {
return (
<div>
<p>Hello, world!</p>
</div>
);
}
function Counter() {
return (
<div>
<p>Counter: counter</p>
<p>Counter Updated: updatedCounter</p>
<p>Rendered: render</p>
</div>
);
}
|
import { NavLink, useRouteMatch } from "react-router-dom";
export default function TabTitle() {
const { url } = useRouteMatch();
return (
<div className="tab-title">
<NavLink exact to={`${url}`}>
Thông tin tài khoản
</NavLink>
<NavLink to={`${url}/your-course`}>Khóa học của bạn</NavLink>
<NavLink to={`${url}/project`}>Dự án đã làm</NavLink>
<NavLink to={`${url}/history-payment`}>Lịch sử thanh toán</NavLink>
<NavLink to={`${url}/coin-management`}>Quản lý COIN của tôi</NavLink>
</div>
);
}
|
define(['./module'], function(app){
'use strict';
app.directive('profileGenerator', ['config.paths', function(paths){
return {
restrict : 'A',
controller: 'GeneratorController',
templateUrl : paths.views + "generator.html",
replace : true,
link : function($scope, el){
// search an image inside the element and check if it's loaded
el.find("img").on("load", function(){
$scope.$apply(function(){
// on loaded image, stop preloading
$scope.loading = false;
})
});
}
}
}])
}); |
(global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/index/hot_ranking/_item" ], {
5308: function(n, e, t) {
var a = t("c859");
t.n(a).a;
},
"5dde": function(n, e, t) {
t.d(e, "b", function() {
return a;
}), t.d(e, "c", function() {
return i;
}), t.d(e, "a", function() {});
var a = function() {
var n = this;
n.$createElement;
n._self._c;
}, i = [];
},
"65e5": function(n, e, t) {
Object.defineProperty(e, "__esModule", {
value: !0
}), e.default = void 0;
var a = {
computed: {
top_img: function() {
return this.type ? "https://cdn.vip-wifi.com/hzfangchan/version-img/1.14.25/activity_a/building_rank/".concat(this.type, ".png") : "";
}
},
props: {
val: Array,
type: String
}
};
e.default = a;
},
c859: function(n, e, t) {},
c8df: function(n, e, t) {
t.r(e);
var a = t("5dde"), i = t("e106");
for (var o in i) [ "default" ].indexOf(o) < 0 && function(n) {
t.d(e, n, function() {
return i[n];
});
}(o);
t("5308");
var c = t("f0c5"), r = Object(c.a)(i.default, a.b, a.c, !1, null, "01ab3820", null, !1, a.a, void 0);
e.default = r.exports;
},
e106: function(n, e, t) {
t.r(e);
var a = t("65e5"), i = t.n(a);
for (var o in a) [ "default" ].indexOf(o) < 0 && function(n) {
t.d(e, n, function() {
return a[n];
});
}(o);
e.default = i.a;
}
} ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/index/hot_ranking/_item-create-component", {
"pages/index/hot_ranking/_item-create-component": function(n, e, t) {
t("543d").createComponent(t("c8df"));
}
}, [ [ "pages/index/hot_ranking/_item-create-component" ] ] ]); |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Middleware = void 0;
class Middleware {
express() {
return async (req, res, next) => {
const result = await this.handler(req, res);
if (result.statusCode >= 200 && result.statusCode <= 299) {
Object.assign(req.body, result.body);
next();
}
else if (result.statusCode > 499) { //500+
console.log("Interal Error:", result.body);
res.status(result.statusCode).json({ error: result.body.message });
}
else { // 400+
console.log("Client side Error:", result.body);
res.status(result.statusCode).json({ error: result.body.toReveal() });
}
};
}
}
exports.Middleware = Middleware;
|
var indexSectionsWithContent =
{
0: "_abcdehilmnoprstuvw",
1: "abchlmu",
2: "abhl",
3: "_amstuvw",
4: "_eiprs",
5: "abcdeilmnorstuvw"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "namespaces",
3: "files",
4: "functions",
5: "variables"
};
var indexSectionLabels =
{
0: "All",
1: "Classes",
2: "Namespaces",
3: "Files",
4: "Functions",
5: "Variables"
};
|
const express = require('express');
const request = require('supertest');
const deepEqual = require('deep-equal');
const registrantRouter = require('../../../server/routers/registrant.router');
const mockEventResults = require('../../expectation-objects/mockEventResults');
const mockRegistrantRouterResponse = require('../../expectation-objects/mockRegistrantRouterResponse2');
const mockAddWinnerList = require('../../expectation-objects/mockMatchUps/mockAddWinner');
jest.mock('../../../server/modules/event-authentication.middleware');
const { rejectUnauthenticated } = require('../../../server/modules/event-authentication.middleware');
jest.mock('../../../server/modules/pool');
const pool = require('../../../server/modules/pool');
const mockPoolResults = require('../../expectation-objects/mockPoolResults');
jest.mock('../../../server/modules/utils/determine-winner');
const determineWinner = require('../../../server/modules/utils/determine-winner');
const initRegistrantRouter = () => {
const app = express();
app.use(registrantRouter);
return app;
};
describe('GET /registrant', () => {
test('It should 200 if event authentication passes', async (done) => {
const app = initRegistrantRouter();
rejectUnauthenticated.mockImplementation(async (req, res, next) => {
[req.event] = mockEventResults.rows;
delete req.event.secret_key;
next();
});
pool.query.mockImplementation(async () => mockPoolResults);
determineWinner.mockImplementation((matchUpInput) => {
const theMockMatchUp = mockAddWinnerList
.filter(mockAddWinner => deepEqual(mockAddWinner.matchUpDetails, matchUpInput))[0];
if (!theMockMatchUp) {
return { display_name: ' ' };
}
return theMockMatchUp.winner;
});
const res = await request(app).get('/event');
expect(res).toHaveProperty('status', 200);
expect(res.body).toEqual(mockRegistrantRouterResponse);
done();
});
});
|
export function createVNode (vtype, type, props) {
return {vtype, type, props}
}
// vdom=》dom
export function conversionNode(vnode) {
const {vtype} = vnode;
if (!vtype) {
return document.createTextNode(vnode);
}
if (vtype === 1) {
return createElementTag(vnode);
} else if (vtype === 2) {
return createClassComp(vnode);
} else if (vtype === 3) {
return createFuncComp(vnode);
}
}
function createElementTag(vnode) {
const {type, props} = vnode;
const node = document.createElement(type);
// 处理特殊属性
const {key, children, ...rest} = props;
Object.keys(rest).forEach(i => {
if (i === 'className') {
return node.setAttribute('class', rest[i]);
} else if(i === 'style'&& typeof rest[i] === 'object') {
const style = Object.keys(rest[i]).map(n => n + ':' + rest[i][n]).join(';')
return node.setAttribute('style', style);
} else if(/on\w+/.test(i)) {
const event = i.toLowerCase();
return node[event] = rest[i];
} else {
return node.setAttribute(i, rest[i]);
}
})
children.forEach(dom => {
if (Array.isArray(dom)) {
dom.forEach(n => node.appendChild(conversionNode(n)))
} else {
const vnode = conversionNode(dom)
node.appendChild(vnode);
}
})
return node
}
function createClassComp(vnode) {
const {type, props} = vnode;
const dom = new type(props).render();
return conversionNode(dom)
}
function createFuncComp(vnode) {
const {type, props} = vnode;
const dom = type(props);
return conversionNode(dom)
} |
var http = require('http');
var express = require('express');
var router = express.Router();
var soap = require('soap');
var request = require('request');
/* GET order data */
router.get('/order', function(req, res) {
console.log("getting orders: ");
var req_balance = http.get({
host: 'web-order',
port: 80,
path: '/order'
}, function(response) {
var data = "";
console.log("get order successful: " + response);
response.on('data', function(chunk) {
data += chunk;
});
response.on('error', function(error) {
console.log("Response error on http get order" + error);
});
response.on('end', function() {
console.log("getting order complete: " + data);
if (data.length > 0) {
try {
var data_object = JSON.parse(data);
}
catch (e) {
console.log("getting order - error: " + e);
return;
}
console.log("order: " + data_object);
res.json(data_object);
}
});
});
req_balance.on('error', function(e) {
console.log("HTTP get request error retrieving order: " + e);
});
});
/* GET pending order data */
router.get('/pendingorder', function(req, res) {
console.log("getting pending orders: ");
var req_balance = http.get({
host: 'web-order',
port: 80,
path: '/pendingorder'
}, function(response) {
var data = "";
console.log("get pending order successful: " + response);
response.on('data', function(chunk) {
data += chunk;
});
response.on('error', function(error) {
console.log("Response error on http get pending order" + error);
});
response.on('end', function() {
console.log("getting pending order complete: " + data);
if (data.length > 0) {
try {
var data_object = JSON.parse(data);
}
catch (e) {
console.log("getting pending order - error: " + e);
return;
}
console.log("pending order: " + data_object);
res.json(data_object);
}
});
});
req_balance.on('error', function(e) {
console.log("HTTP get request error retrieving pending order: " + e);
});
});
/*
* POST to userorder.
*/
router.post('/addorder', function(req, res) {
console.log("posting order to Order service: %j ", req.body);
request({
url: "http://web-order:80/order",
method: "POST",
json: true, // <--Very important!!!
body: req.body
}, function (error, response, body){
console.log(response);
});
});
/*
* POST to pendingorder.
*/
router.post('/addpendingorder', function(req, res) {
console.log("posting pending order: ");
request({
url: "http://web-order:80/pendingorder",
method: "POST",
json: true, // <--Very important!!!
body: req.body
}, function (error, response, body){
console.log(response);
});
});
/*
* Delete pendingorder.
*/
router.post('/delpendingorder', function(req, res) {
console.log("del pending order: ");
request({
url: "http://web-order:80/pendingorder",
method: "DELETE",
json: true, // <--Very important!!!
body: req.body
}, function (error, response, body){
console.log(response);
});
});
module.exports = router;
|
'use strict';
const Controller = require('egg').Controller;
class PageController extends Controller {
async mobile() {
const { ctx } = this
const pageId = ctx.params.id;
const result = await ctx.service.pages.show(ctx.params);
if (result.ret == 0) {
let httpContent = await ctx.renderView('p/index.js', {pageData: result.data});
// 替换大小
httpContent = httpContent.replace('/*__page__size__*/', `window.__page_size = ${httpContent.length};`)
ctx.body = httpContent
}
else {
let message = '未知错误';
if (result.ret == -101) {
ctx.status = 404;
message = '页面找不到了';
}
else {
ctx.status = 500;
}
await ctx.render('error/error.js', {message: message});
}
}
}
module.exports = PageController; |
var column_num;
var row_num;
var environmentNameValue;
var dummy = "dummy";
var iTEST="";
var abacus="";
var stc="";
var cnt=1;
var generatoRowCount=0;
//var iTest = {'username':"", 'password':"", 'ipAddress':"", 'testServer':""};
//var abacus = {'username':"", 'password':"", 'ipAddress':"", 'testServer':""};
//var stc = {'username':"", 'password':"", 'ipAddress':"", 'testServer':""};
$(document).ready(function(){
$(".verifyLoader").hide();
$("#myTable td").click(function() {
//alert("iTEST:"+iTEST+"abacus:"+abacus+"stc:"+stc);
var select = document.getElementById('sel');
if(select.selectedIndex == -1){
$("#save").html("Please configure TestBed first in add TestBed page.")
displayHideBox('2');
return true;
}
// else if(iTEST == "" && abacus == "" && stc==""){
// $("#save").html("Please configure a test controller first!")
// displayHideBox('2');
// return false;
// }
$("#cpeModel").html("");
column_num = parseInt( $(this).index() ) + 1;
row_num = parseInt( $(this).parent().index() );
if(!(column_num == "1" || column_num == "3")){
if(column_num == "2"){
$.ajax({url: "getCmts/"+environmentNameValue+"/"+userNetworkId+"/"+column_num+"/"+row_num,
async: false,
success: function(result){
if(result.length!=0)
{
$( "#addCmtsErrorMsg" ).html("");
$('#cmtsId').val(result.cmtsId);
$('#userName').val(result.userName);
$('#password').val(result.password);
$('#ipAddress').val(result.ipAddress);
$("#cmtsDeleteButton").removeAttr("disabled");
$('#cmtsModal').modal('show');
}
else
{
if(iTEST == "" && abacus == "" && stc==""){
$("#save").html("Please configure a test controller first!")
displayHideBox('2');
}
else
{
$( "#addCmtsErrorMsg" ).html("");
$('#userName').val(result.userName);
$('#password').val(result.password);
$('#ipAddress').val(result.ipAddress);
$("#cmtsDeleteButton").attr('disabled',true);
$('#cmtsModal').modal('show');
}
}
}
});
}else{
$.ajax({url: "getCpe/"+environmentNameValue+"/"+userNetworkId+"/"+column_num+"/"+row_num,
async: false,
success: function(result){
if(result.length!=0)
{
$( "#addCpeErrorMsg" ).html("");
$('#cpeId').val(result.cpeId);
$('#cpeVendor').val(result.cpeVendor);
getCpeMOdels(result.cpeVendor,result.cpeModel);
$('#cpeModel').val(result.cpeModel);
$('#cmMac').val(result.cmMac);
$('#mtaMac').val(result.mtaMac);
$('#telephoneOne').val(result.telephoneOne);
$('#telephoneTwo').val(result.telephoneTwo);
getFirmwareVersions(result.cpeVendor,result.cpeVersion);
$('#cpeVersion').val(result.cpeVersion);
$("#cpeDeleteButton").removeAttr("disabled");
$('#deleteConfirmation').modal('show');
// $('#deleteConfirmation').on('show.bs.modal', function (e) {
// $("#cpeVendor").val(result.cpeVendor);
// $("#cpeModel").val(result.cpeModel);
// $("#cmMac").val(result.cmMac);
// $("#mtaMac").val(result.mtaMac);
// $("#telephoneOne").val(result.telephoneOne);
// $("#telephoneTwo").val(result.telephoneTwo);
// $('#cpeVersion').val(result.cpeVersion);
// })
}
else
{
if(iTEST == "" && abacus == "" && stc==""){
$("#save").html("Please configure a test controller first!")
displayHideBox('2');
}
else{
$( "#addCpeErrorMsg" ).html("");
$("#cpeDeleteButton").attr('disabled',true);
$('#cpeVendor').val(result.cpeVendor);
$('#cpeModel').val(result.cpeModel);
$('#cmMac').val(result.cmMac);
$('#mtaMac').val(result.mtaMac);
$('#telephoneOne').val(result.telephoneOne);
$('#telephoneTwo').val(result.telephoneTwo);
$('#cpeVersion').val(result.cpeVersion);
$('#deleteConfirmation').modal('show');
}
}
}
});
}
}
});
$.ajax({url: "getEnvDetails/"+dummy+"/"+userNetworkId,
success: function(result){
getEnvDetails(result);
environmentNameValue = $('#sel').val();
}
});
$('#cpeVendor').change(function() {
var vendor = $("#cpeVendor").val();
//alert(vendor)
getCpeMOdels(vendor,'null');
getFirmwareVersions(vendor,'null');
});
});
function getEnvDetails(result){
var selectData = "<label id=\"environmentName\" for=\"sel\" placeholder=\"Select TestBed\">TestBed:</label><select class=\"form-control\" id=\"sel\" name=\"sel\">";
if(result.environmentNames != null){
for(var i=0;i<result.environmentNames.length;i++){
selectData = selectData+"<option value="+result.environmentNames[i]+">"+result.environmentNames[i]+"</option>";
}
}
selectData = selectData+"</select>";
$( "#envNamesList" ).html(selectData);
$("#networkId").val(result.admin);
$("#location").val(result.location);
if(result.testServerModels != null){
iTEST = "";
abacus = "";
stc = "";
$("#iTESTstatus").attr("src","");
$("#iTESTstatus").css("display","none");
$("#ABACUSstatus").attr("src","");
$("#ABACUSstatus").css("display","none");
$("#STCstatus").attr("src","");
$("#STCstatus").css("display","none");
//alert(result.testServerModels.length);
for(var i=0;i<result.testServerModels.length;i++){
var testServer = result.testServerModels[i].testServer;
var status = result.testServerModels[i].testServerStatus;
if(status=="pass")
{
$("#"+testServer+"status").attr("src","images/green.png");
$("#"+testServer+"status").css("display","block");
}
else if(status=="fail")
{
$("#"+testServer+"status").attr("src","images/red.png");
$("#"+testServer+"status").css("display","block");
}
else
{
$("#"+testServer+"status").attr("src","");
$("#"+testServer+"status").css("display","none");
}
if(testServer=="iTEST")
{
//alert("iTEST");
iTEST = "1";
}
if(testServer=="ABACUS")
{
//alert("ABACUS");
abacus = "1";
}
if(testServer=="STC")
{
//alert("STC");
stc = "1";
}
}
if(result.testServerModels.length == 0)
{
$("#iTESTstatus").attr("src","");
$("#iTESTstatus").css("display","none");
$("#ABACUSstatus").attr("src","");
$("#ABACUSstatus").css("display","none");
$("#STCstatus").attr("src","");
$("#STCstatus").css("display","none");
iTEST = "";
abacus = "";
stc = "";
}
//
}
//
var test="";
for(var row=1;row<6;row++){
if(result.cmtsModels != null && result.cmtsModels != ""){
for(var i=0;i<result.cmtsModels.length;i++){
row_num = result.cmtsModels[i].rowNo;
column_num = result.cmtsModels[i].columnNo;
var cmtsStatus = result.cmtsModels[i].cmtsStatus;
var imgCmts = "<img src=\"images/cmts.jpg\"><img src=\"\" id=\"cmtsStatus"+row_num+column_num+"\" style=\"display:none;width:30px;height:30px;position: relative;top:-21px;left:21px;\">"
var imgCmtsStatus="";
if(cmtsStatus=='pass')
imgCmtsStatus="images/green.png"
else if(cmtsStatus=='fail')
imgCmtsStatus="images/red.png"
else if(cmtsStatus=='test' || cmtsStatus=='inprogress')
{
$( "#cmtsStatus"+row_num+column_num ).css("display", "none");
test="true";
}
else
$( "#cmtsStatus"+row_num+column_num ).css("display", "none");
if(row == row_num){
$( "#"+row+"2").html(imgCmts);
$( "#cmtsStatus"+row_num+column_num ).css("display", "block");
$( "#cmtsStatus"+row_num+column_num ).attr("src",imgCmtsStatus);
break;
}else{
$( "#"+row+"2" ).html("");
//$( "#b"+row+"1" ).removeClass('btn-success');
//$( "#b"+row+"1" ).removeClass('btn-danger');
}
}
} else{
$( "#"+row+"2" ).html("");
}
}
for(var col=4;col<16;col++){
for(var row=1;row<6;row++){
if(result.cpeModels != null && result.cpeModels != ""){
for(var i=0;i<result.cpeModels.length;i++){
var cpeImgData = result.cpeModels[i].cpeModel;
row_num = result.cpeModels[i].rowNo;
column_num = result.cpeModels[i].columnNo;
var imgData = "<img src=\"images/CPE_"+cpeImgData+".jpg\"><img src=\"\" id=\"status"+row_num+column_num+"\" style=\"display:none;width:30px;height:30px;position: relative;top:-21px;left:21px;\">"
var cpeStatus = result.cpeModels[i].cpeStatus;
var imgStatus="";
//var cpeOutput="<table style=\"background: transparent !important;\"><tr><td style=\"background: transparent !important;\">hello1: </td><td style=\"background: transparent !important;\">"+result.cpeModels[i].cpeOutput+"</td></tr><tr><td style=\"background: transparent !important;\">hello2:</td><td style=\"background: transparent !important;\"> "+result.cpeModels[i].cpeOutput+"</td></tr></table>";
var cpeOutput="";
var outArr = result.cpeModels[i].cpeOutput.split("$");
for(var k=0;k<outArr.length;k++)
{
cpeOutput=cpeOutput+outArr[k]+"<br>";
}
if(cpeStatus=='pass')
imgStatus="images/green.png"
else if(cpeStatus=='fail')
imgStatus="images/red.png"
else if(cpeStatus=='test' || cpeStatus=='inprogress')
{
$( "#status"+row_num+column_num ).css("display", "none");
test="true";
}
else
$( "#status"+row_num+column_num ).css("display", "none");
if(col == column_num && row == row_num){
if(cpeOutput!="<br>")
{
$( "#"+row_num+column_num ).data('bs.tooltip',false) // Delete the tooltip
.tooltip({ title: cpeOutput});
}
$( "#"+row_num+column_num ).html(imgData);
$( "#status"+row_num+column_num ).css("display", "block");
$( "#status"+row_num+column_num ).attr("src",imgStatus);
break;
}else{
$( "#"+row+col ).html("");
//$( "#b"+row+col ).removeClass('btn-success');
//$( "#b"+row+col ).removeClass('btn-danger');
}
}
}else{
$( "#"+row+col ).html("");
}
}
}
//alert(test);
if(test=="true")
{
$("#VerifyEnv").attr('disabled',true);
$("#SaveEnv").attr('disabled',true);
$("#DeleteEnv").attr('disabled',true);
$(".verifyLoader").show();
}
else
{
$("#VerifyEnv").removeAttr("disabled");
$("#SaveEnv").removeAttr("disabled");
$("#DeleteEnv").removeAttr("disabled");
$(".verifyLoader").hide();
}
$('#sel').change(function() {
environmentNameValue = $(this).val();
$.ajax({url: "getEnvDetails/"+environmentNameValue+"/"+userNetworkId,
success: function(data){
getEnvDetails(data);
}
});
});
// return true;
}
function validateEditEnv(){
var select = document.getElementById('sel');
if(select.selectedIndex == -1){
$( "#editEnvErrorMsg" ).html("Please configure TestBed first in add TestBed page.").css('color','red');
return true;
}
var environmentName = select.options[select.selectedIndex].value;
var networkId = $('#networkId').val().trim();
var location = $('#location').val().trim();
var json = {"environmentName" : environmentName,"ownerNetworkId" : userNetworkId,"adminNetworkId" : networkId,"location" : location};
if ((typeof environmentName == "undefined" || environmentName == null || environmentName=="") || (typeof networkId == "undefined" || networkId == null || networkId=="")
|| (typeof location == "undefined" || location == null || location=="")) {
$( "#editEnvErrorMsg" ).html("All the fields are mandatory").css('color','red');
}else{
$.ajax({
url: "user/editEnvironment",
type: 'POST',
data: JSON.stringify(json),
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "text/plain");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
if(response!=null){
if(response.search("updated") != -1){
$( "#editEnvErrorMsg" ).html(response).css('color','blue');
environmentNameValue = environmentName;
}else{
$( "#editEnvErrorMsg" ).html(response).css('color','red');
}
}else{
$( "#editEnvErrorMsg" ).html("Oops system under maintenance please try after sometime!").css('color','blue');
}
}
});
}
return true;
}
function verifyDetails(){
var select = document.getElementById('sel');
if(select.selectedIndex == -1){
$("#save").html("Please configure TestBed first in add TestBed page.")
displayHideBox('2');
return true;
}
else if(iTEST == "" && abacus == "" && stc==""){
$("#save").html("Please configure a test controller first!")
displayHideBox('2');
return false;
}
else
{
doVerify();
}
}
function doVerify()
{
$(".verifyLoader").show();
$("#VerifyEnv").attr('disabled',true);
$("#SaveEnv").attr('disabled',true);
$("#DeleteEnv").attr('disabled',true);
$.ajax({url: "doVerify/"+environmentNameValue+"/"+userNetworkId,
success: function(result){
if(result=="success")
{
verifyStatus();
}
else{
$("#VerifyEnv").removeAttr("disabled");
$("#SaveEnv").removeAttr("disabled");
$("#DeleteEnv").removeAttr("disabled");
}
},
});
}
function verifyStatus()
{
var test="";
var loop="";
$.ajax({url: "getEnvDetails/"+environmentNameValue+"/"+userNetworkId,
success: function(result){
if(result.testServerModels != null){
$("#iTESTstatus").attr("src","");
$("#iTESTstatus").css("display","none");
$("#ABACUSstatus").attr("src","");
$("#ABACUSstatus").css("display","none");
$("#STCstatus").attr("src","");
$("#STCstatus").css("display","none");
for(var i=0;i<result.testServerModels.length;i++){
var testServer = result.testServerModels[i].testServer;
var status = result.testServerModels[i].testServerStatus;
// alert(status);
if(status=="pass")
{
$("#"+testServer+"status").attr("src","images/green.png");
$("#"+testServer+"status").css("display","block");
}
else if(status=="fail")
{
$("#"+testServer+"status").attr("src","images/red.png");
$("#"+testServer+"status").css("display","block");
}
else
{
$("#"+testServer+"status").attr("src","");
$("#"+testServer+"status").css("display","none");
}
}
if(result.testServerModels.length == 0)
{
//alert("-->0");
$("#iTESTstatus").attr("src","");
$("#iTESTstatus").css("display","none");
$("#ABACUSstatus").attr("src","");
$("#ABACUSstatus").css("display","none");
$("#STCstatus").attr("src","");
$("#STCstatus").css("display","none");
}
}
for(var row=1;row<6;row++){
if(result.cmtsModels != null && result.cmtsModels != ""){
for(var i=0;i<result.cmtsModels.length;i++){
row_num = result.cmtsModels[i].rowNo;
column_num = result.cmtsModels[i].columnNo;
var cmtsStatus = result.cmtsModels[i].cmtsStatus;
var imgCmtsStatus="";
if(cmtsStatus=='pass')
imgCmtsStatus="images/green.png"
else if(cmtsStatus=='fail')
imgCmtsStatus="images/red.png"
else if(cmtsStatus=='test' || cmtsStatus=='inprogress')
{
test="true";
}
else
$( "#cmtsStatus"+row_num+column_num ).css("display", "none");
if(row == row_num){
if(imgCmtsStatus=="")
$( "#cmtsStatus"+row_num+column_num ).css("display", "none");
else{
$( "#cmtsStatus"+row_num+column_num ).css("display", "block");
$( "#cmtsStatus"+row_num+column_num ).attr("src",imgCmtsStatus);
}
break;
}
}
}
}
for(var col=4;col<16;col++){
for(var row=1;row<6;row++){
if(result.cpeModels != null && result.cpeModels != ""){
for(var i=0;i<result.cpeModels.length;i++){
//var cpeImgData = result.cpeModels[i].cpeModel;
row_num = result.cpeModels[i].rowNo;
column_num = result.cpeModels[i].columnNo;
var cpeStatus = result.cpeModels[i].cpeStatus;
//var imgData = "<img src=\"images/"+cpeImgData+".jpg\">"
//alert(cpeStatus);
var cpeOutput="";
var outArr = result.cpeModels[i].cpeOutput.split("$");
for(var k=0;k<outArr.length;k++)
{
cpeOutput=cpeOutput+outArr[k]+"<br>";
}
var imgStatus="";
if(cpeStatus=='pass')
imgStatus="images/green.png"
else if(cpeStatus=='fail')
imgStatus="images/red.png"
else if(cpeStatus=='test' || cpeStatus=='inprogress')
{
//alert("here");
test="true";
}
if(col == column_num && row == row_num){
//alert("#status"+row_num+column_num);
if(cpeOutput!="<br>")
{
$( "#"+row_num+column_num ).data('bs.tooltip',false) // Delete the tooltip
.tooltip({ title: cpeOutput});
}
//$( "#"+row_num+column_num ).tooltip('destroy');
//$( "#"+row_num+column_num ).attr("data-title",cpeOutput);
//$( "#"+row_num+column_num ).tooltip();
if(imgStatus=="")
$( "#status"+row_num+column_num ).css("display", "none");
else
{
$( "#status"+row_num+column_num ).css("display", "block");
$( "#status"+row_num+column_num ).attr("src",imgStatus);
}
//$( "#"+row_num+column_num ).append(imgStatus);
break;
}
}
}
}
}
//alert(test);
if(test!="true")
{
$("#VerifyEnv").removeAttr("disabled");
$("#SaveEnv").removeAttr("disabled");
$("#DeleteEnv").removeAttr("disabled");
clearInterval(loop);
$(".verifyLoader").hide();
}
else
{
//alert("here<--");
$(".verifyLoader").show();
loop = setTimeout(verifyStatus, 10000);
}
},
});
}
function resetEditEnv(){
var frm = document.getElementsByName('edit-form')[0];
frm.reset();
return true;
}
function rollbackEnv(){
//alert("Rollback the changes");
$.ajax({url: "user/rollbackEnv/"+environmentNameValue+"/"+userNetworkId,
success: function(response){
if(response=="success")
location.reload();
else
{
displayHideBox('1');
$("#editEnvErrorMsg").html(response).css('color','red');
}
}
});
return true;
}
function saveAddCpe(){
$( "#editEnvErrorMsg" ).html("");
if (typeof environmentNameValue == "undefined" || environmentNameValue == null || environmentNameValue==""){
$( "#addCpeErrorMsg" ).html("Please configure TestBed before CPE!").css('color','red');
return true;
}
var cpeVendor = $('#cpeVendor').val();
var cpeModel = $('#cpeModel').val();
var cmMac = $('#cmMac').val().trim();
var mtaMac = $('#mtaMac').val().trim();
var telephoneOne = $('#telephoneOne').val().trim();
var telephoneTwo = $('#telephoneTwo').val().trim();
var cpeVersion = $('#cpeVersion').val();
var json = {"cpeVendor" : cpeVendor,"cpeModel" : cpeModel,"cmMac" : cmMac,"mtaMac" : mtaMac,"telephoneOne" : telephoneOne,"telephoneTwo" : telephoneTwo,"columnNo" : column_num,"rowNo" : row_num,"environmentName" : environmentNameValue,"ownerNtId":userNetworkId,"cpeVersion":cpeVersion};
//alert(json);
if ((typeof cpeVendor == "undefined" || cpeVendor == null || cpeVendor=="") || (typeof cpeModel == "undefined" || cpeModel == null || cpeModel=="")
|| (typeof cmMac == "undefined" || cmMac == null || cmMac=="") || (typeof mtaMac == "undefined" || mtaMac == null || mtaMac=="") ||
(typeof telephoneOne == "undefined" || telephoneOne == null || telephoneOne=="")||
(typeof telephoneTwo == "undefined" || telephoneTwo == null || telephoneTwo=="")) {
$( "#addCpeErrorMsg" ).html("All the fields are mandatory").css('color','red');
}
else if((typeof cpeVersion == "undefined" || cpeVersion == null || cpeVersion==""))
{
$( "#addCpeErrorMsg" ).html("Please configure a firmware version for a vendor first").css('color','red');
// $("#cmMac").focus();
}
else if(!validatemac("cmMac"))
{
$( "#addCpeErrorMsg" ).html("CM Mac Should Be in proper format").css('color','red');
// $("#cmMac").focus();
}
else if(!validatemac("mtaMac"))
{
$( "#addCpeErrorMsg" ).html("MTA Mac Should Be in proper format").css('color','red');
// $("#mtaMac").focus();
}
else if(validatetn("telephoneOne") == "1")
{
$( "#addCpeErrorMsg" ).html("TN Line 1 Should Be of lenght 10").css('color','red');
// $("#telephoneOne").focus();
}
else if(validatetn("telephoneOne") == "2" )
{
$( "#addCpeErrorMsg" ).html("TN Line 1 Should Be Number only").css('color','red');
// $("#telephoneOne").focus();
}
else if(validatetn("telephoneTwo")=="1")
{
$( "#addCpeErrorMsg" ).html("TN Line 2 Should Be of lenght 10").css('color','red');
$("#telephoneTwo").val("");
// $("#telephoneTwo").focus();
}
else if(validatetn("telephoneTwo")=="2")
{
$( "#addCpeErrorMsg" ).html("TN Line 2 Should Be Number only").css('color','red');
$("#telephoneTwo").val("");
// $("#telephoneTwo").focus();
}
else{
//alert(validatetn("telephoneOne"));
$.ajax({
url: "user/addCpe",
type: 'POST',
data: JSON.stringify(json),
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "text/plain");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
if(response=="success"){
$( "#addCpeErrorMsg" ).html("Successfully saved CPE!").css('color','blue');
var imgData = "<img src=\"images/CPE_"+cpeModel+".jpg\"><img src=\"\" id=\"status"+row_num+column_num+"\" style=\"display:none;width:30px;height:30px;position: relative;top:-21px;left:21px;\">"
$( "#"+row_num+column_num ).html(imgData);
}
else if(response=="Updated successfully!")
{
$( "#addCpeErrorMsg" ).html("Successfully updated CPE!").css('color','blue');
var imgData = "<img src=\"images/CPE_"+cpeModel+".jpg\">"
$( "#"+row_num+column_num ).html(imgData);
}
else{
$( "#addCpeErrorMsg" ).html(response).css('color','red');
}
}
});
}
return true;
}
function resetAddCpe(){
var frm = document.getElementsByName('addCpe-form')[0];
frm.reset();
return true;
}
function validateIPaddress(inputText)
{
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if(ipformat.test(inputText))
{
return true;
}
else
{
return false;
}
}
function saveAddCmts(){
$( "#editEnvErrorMsg" ).html("");
var userName = $('#userName').val().trim();
var password = $('#password').val().trim();
var ipAddress = $('#ipAddress').val().trim();
var json = {"userName" : userName,"password" : password,"ipAddress" : ipAddress,"columnNo" : column_num,"rowNo" : row_num,"environmentName" : environmentNameValue,"ownerNtId":userNetworkId};
if ((typeof userName == "undefined" || userName == null || userName=="") || (typeof password == "undefined" || password == null || password=="")
|| (typeof ipAddress == "undefined" || ipAddress == null || ipAddress=="")) {
$( "#addCmtsErrorMsg" ).html("All the fields are mandatory").css('color','red');
}else if(!validateIPaddress(ipAddress)){
$( "#addCmtsErrorMsg" ).html("Please enter valid IP Address.").css('color','red');
return true;
}else{
$.ajax({
url: "user/addCmts",
type: 'POST',
data: JSON.stringify(json),
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "text/plain");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
if(response=="success"){
$( "#addCmtsErrorMsg" ).html("Successfully saved CMTS!").css('color','blue');
var imgData = "<img src=\"images/cmts.jpg\"><img src=\"\" id=\"cmtsStatus"+row_num+column_num+"\" style=\"display:none;width:30px;height:30px;position: relative;top:-21px;left:21px;\">"
$( "#"+row_num+column_num ).html(imgData);
$( "#cmtsStatus"+row_num+column_num ).css("display", "none");
}
else if(response=="Updated successfully!")
{
$( "#addCmtsErrorMsg" ).html("Successfully updated CMTS!").css('color','blue');
var imgData = "<img src=\"images/cmts.jpg\"><img src=\"\" id=\"cmtsStatus"+row_num+column_num+"\" style=\"display:none;width:30px;height:30px;position: relative;top:-21px;left:21px;\">"
$( "#"+row_num+column_num ).html(imgData);
$( "#cmtsStatus"+row_num+column_num ).css("display", "none");
}
else{
$( "#addCmtsErrorMsg" ).html(response).css('color','red');
}
}
});
}
return true;
}
function resetAddCmts(){
var frm = document.getElementsByName('addCmts-form')[0];
frm.reset();
return true;
}
function saveTestEnv(test)
{
var userName;
var password;
var ipAddress;
var testServer;
if(test == "iTest")
{
testServer = $('#testServer').val().trim();
userName = $('#EnvuserName').val().trim();
password = $('#Envpassword').val().trim();
ipAddress = $('#EnvipAddress').val().trim();
}
else
{
testServer = $('#testServerSTCAbabcus').val().trim();
userName = 'null';
password = 'null';
ipAddress = $('#EnvSTCAbabcusipAddress').val().trim();
}
var json = {"userName" : userName,"password" : password,"ipAddress" : ipAddress,"testServer" : testServer,"ownerNtId":userNetworkId,"environmentName" : environmentNameValue};
if ((typeof userName == "undefined" || userName == null || userName=="") || (typeof password == "undefined" || password == null || password=="")
|| (typeof ipAddress == "undefined" || ipAddress == null || ipAddress=="")) {
if(test == "iTest")
$( "#TestEnvErrorMsg" ).html("All the fields are mandatory").css('color','red');
else
$( "#TestSTCAbabcusEnvErrorMsg" ).html("All the fields are mandatory").css('color','red');
}else if(!validateIPaddress(ipAddress)){
if(test == "iTest")
$( "#TestEnvErrorMsg" ).html("Please enter valid IP Address.").css('color','red');
else
$( "#TestSTCAbabcusEnvErrorMsg" ).html("Please enter valid IP Address.").css('color','red');
return true;
}else{
//alert("okay");
$.ajax({
url: "user/addTestServer",
type: 'POST',
data: JSON.stringify(json),
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "text/plain");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
if(response=="success"){
$( "#editEnvErrorMsg" ).html("");
if(testServer=="iTEST")
{
iTEST="1";
$("#iTESTstatus").css("display","none");
$( "#TestEnvErrorMsg" ).html("Successfull!").css('color','blue');
}
else if(testServer=="ABACUS")
{
abacus="1";
$("#ABACUSstatus").css("display","none");
$( "#TestSTCAbabcusEnvErrorMsg" ).html("Successfull!").css('color','blue');
}
else if(testServer=="STC")
{
$("#AbacusStcIP").val(ipAddress);
stc="1";
$("#STCstatus").css("display","none");
$( "#TestSTCAbabcusEnvErrorMsg" ).html("Successfull!").css('color','blue');
}
}else{
if(testServer == "iTEST")
$( "#TestEnvErrorMsg" ).html(response).css('color','red');
else
$( "#TestSTCAbabcusEnvErrorMsg" ).html(response).css('color','red');
}
}
});
}
return true;
}
function DeleteTestEnv(test)
{
displayHideBox('1');
var ipAddress;
var testServer;
if(test == "iTest")
{
ipAddress = $('#EnvipAddress').val().trim();
testServer = $('#testServer').val().trim();
}
else
{
ipAddress = $('#EnvSTCAbabcusipAddress').val().trim();
testServer = $('#testServerSTCAbabcus').val().trim();
}
$.ajax({url: "user/deleteTestServer/"+environmentNameValue+"/"+testServer+"/"+userNetworkId,
success: function(response){
if(response=="success")
{
if(testServer == "iTEST")
{
$("#testEnvModal").modal('toggle');
$("#editEnvErrorMsg").html("Successfully deleted Test Controller").css('color','blue');
iTEST = "";
$("#iTESTstatus").css("display","none");
}
else if(testServer == "ABACUS")
{
$("#testEnvModalSTCAbacus").modal('toggle');
$("#editEnvErrorMsg").html("Successfully deleted Test Controller").css('color','blue');
abacus = "";
$("#ABACUSstatus").css("display","none");
}
else if(testServer == "STC")
{
$("#testEnvModalSTCAbacus").modal('toggle');
$("#editEnvErrorMsg").html("Successfully deleted Test Controller").css('color','blue');
stc = "";
$("#STCstatus").css("display","none");
}
}
else
{
if(testServer == "iTEST")
$("#testEnvModal").modal('toggle');
else
$("#testEnvModalSTCAbacus").modal('toggle');
$("#editEnvErrorMsg").html(response).css('color','red');
}
}
});
return true;
}
function generatorDetails(){
if(!validateIPaddress($("#EnvSTCAbabcusipAddress").val()))
{
$( "#TestSTCAbabcusEnvErrorMsg" ).html("Enter IP in valid format(Ex : 10.20.10.20)").css({color:'red'});
}
else if($("#AbacusStcIP").val()=="" || $("#AbacusStcIP").val()==null)
{
$( "#TestSTCAbabcusEnvErrorMsg" ).html("Save STC Information First").css({color:'red'});
}
else
{
$("#testControlletrSTCEditEnvErrorMsg").html("");
/*$(".modal-dialog").css({width:'1000px'});*/
fetchgenerator();
$('#testEnvModalSTCModal').modal('show');
}
}
function addgenerator()
{
$( "#testControlletrSTCEditEnvErrorMsg" ).html("");
if($("#clientPort").val().trim()=="" || $("#serverPort").val().trim()=="")
{
$( "#testControlletrSTCEditEnvErrorMsg" ).html("All fields are mandatory").css('color','red');
}
else if(!validateIPaddress($("#cpeIpVal").val()))
{
$( "#testControlletrSTCEditEnvErrorMsg" ).html("Please Enter valid Cpe Ip Address").css('color','red');
}
// else if(!validatemac("cpeMacVal"))
// {
//var patt = new RegExp("^([0-9a-fA-F]{2}[:-]){5}([0-9a-fA-F]{2})$");
//
//
// if(!patt.test($("#cpeMacVal").val()))
// {
//
// $( "#testControlletrSTCEditEnvErrorMsg" ).html("Please Enter valid Cpe Mac Address").css('color','red');
// }
//
//}
else if(!validateIPaddress($("#cpeGateway").val()))
{
$( "#testControlletrSTCEditEnvErrorMsg" ).html("Please Enter valid Cpe Gatway Ip Address").css('color','red');
}
else if(existingGenerator("undefined"))
{
$( "#testControlletrSTCEditEnvErrorMsg" ).html("Generator already exists").css('color','red');
}
else
{
$("#firsttr").append('<tr name="dynamictr'+cnt+'"><td name="clientPorttd">'+$("#clientPort").val()+'</td>'+
'<td name="serverPorttd">'+$("#serverPort").val()+'</td>'+
'<td name="cpeGatewaytd">'+$("#cpeGateway").val()+'</td>'+
//'<td name="cpeMacValtd">'+$("#cpeMacVal").val()+'</td>'+
'<td name="cpeIpValtd">'+$("#cpeIpVal").val()+'</td>'+
'<td name="operationstd"><input name="Edit'+cnt+'" class="form-control input-sm" type="button" onclick=editstcgenerator("Edit'+cnt+'") value="Edit"/>'+
'<input name="Delete'+cnt+'" class="form-control input-sm" onclick=deletestcgenerator("Delete'+cnt+'") type="button" value="Delete"/></td></tr>');
$("#clientPort").val("");
$("#serverPort").val("");
$("#cpeGateway").val("");
//$("#cpeMacVal").val("");
$("#cpeIpVal").val("");
cnt=cnt+1;
generatoRowCount=generatoRowCount+1;
}
}
function fetchgenerator()
{
//$('tr[name=dynamictr'*']').removeA();
$("tr[name^=dynamictr]").each(function (i, el) {
$(this).remove();
//It'll be an array of elements
});
var json = {"environmentNameValue" : environmentNameValue , "userNetworkId" : userNetworkId ,"stcIp" : $("#AbacusStcIP").val()};
$.ajax({
url: "user/environment/getGenerators",
type: 'POST',
data: JSON.stringify(json),
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(response){
cnt=1;
if(response!=""){
$(response).each(function (i, row) {
$("#firsttr").append('<tr name="dynamictr'+cnt+'"><td name="clientPorttd">'+row.clientPort+'</td>'+
'<td name="serverPorttd">'+row.serverPort+'</td>'+
'<td name="cpeGatewaytd">'+row.cpeGateway+'</td>'+
//'<td name="cpeMacValtd">'+row.cpeMacVal+'</td>'+
'<td name="cpeIpValtd">'+row.cpeIpVal+'</td>'+
'<td name="operationstd"><input name="Edit'+cnt+'" class="form-control input-sm" type="button" onclick=editstcgenerator("Edit'+cnt+'") value="Edit"/>'+
'<input name="Delete'+cnt+'" class="form-control input-sm" onclick=deletestcgenerator("Delete'+cnt+'") type="button" value="Delete"/></td></tr>');
cnt=cnt+1;
generatoRowCount=generatoRowCount+1;
});
}
else
{
generatoRowCount=0;
}
}
});
}
function deletestcgenerator(id1)
{
$("[name="+id1+"]").parent().parent().remove();
}
function editstcgenerator(id1)
{
var idnum=id1.replace("Edit", "");
var rep='<tr name="dynamictr'+idnum+'">';
$("[name="+id1+"]").parent().parent().children('td').each(function(i) {
if($(this).attr('name')!="operationstd")
rep=rep+'<td name="'+$(this).attr('name')+'"><input id="'+$(this).attr('name').substring(0,$(this).attr('name').length - 2)+'" name="'+$(this).attr('name').substring(0,$(this).attr('name').length - 2)+'" type="text" value="'+$(this).text()+'"></td>';
});
rep=rep+'<td name="operationstd"><input name="Edit'+idnum+'" class="form-control input-sm" type="button" onclick=editstcgenerator("Edit'+idnum+'") value="Edit"/>'+
'<input name="Delete'+idnum+'" class="form-control input-sm" onclick=deletestcgenerator("Delete'+idnum+'") type="button" value="Delete"/></td></tr>';
$("[name="+id1+"]").parent().parent().replaceWith( function() {
return rep;
});
/*$('tr[name=dynamictr]').remove();*/
/*$.ajax({url: "deleteStcGenerator/"+environmentNameValue+"/"+userNetworkId+"/"+generatorid,
success: function(response){
}
});*/
}
function popUp(recipient)
{
var select = document.getElementById('sel');
if(select.selectedIndex == -1){
$("#save").html("Please configure TestBed first in add TestBed page.")
displayHideBox('2');
return true;
}
else
{
var uname="";
var pass="";
var ip="";
$("#AbacusStcIP").val("");
if(recipient=="iTEST")
{
$('#title').text("");
$('#EnvuserName').val("");
$('#Envpassword').val("");
$('#EnvipAddress').val("");
$('#TestEnvErrorMsg').html("");
$('#testServer').val("");
}
else
{
$('#titleSTCAbacus').text("");
$('#EnvSTCAbabcusipAddress').val("");
$('#TestSTCAbabcusEnvErrorMsg').html("");
$('#testServerSTCAbabcus').val("");
}
$.ajax({url: "getTestSeverDetails/"+environmentNameValue+"/"+recipient+"/"+userNetworkId,
success: function(response){
//alert(response.userName+"--"+response.password+"--"+response.ipAddress);
uname=(response.userName==undefined)?"":response.userName;
pass=(response.password==undefined)?"":response.password;
ip=(response.ipAddress==undefined)?"":response.ipAddress;
//alert(uname+":"+pass+":"+ip);
//alert(recipient);
if(recipient=="iTEST")
{
if(uname == "")
$("#testCtrlDelete").attr('disabled',true);
else
$("#testCtrlDelete").removeAttr("disabled");
$('#title').text(recipient);
$('#EnvuserName').val(uname);
$('#Envpassword').val(pass);
$('#EnvipAddress').val(ip);
$('#TestEnvErrorMsg').html("")
$('#testServer').val(recipient);
$('#testEnvModal').modal('show');
}
else
{
if(ip == "")
$("#testCtrlSTCAbabcusDelete").attr('disabled',true);
else
$("#AbacusStcIP").val(ip);
$("#testCtrlSTCAbabcusDelete").removeAttr("disabled");
$('#titleSTCAbacus').text(recipient);
$('#EnvSTCAbabcusipAddress').val(ip);
$('#testServerSTCAbabcus').val(recipient);
$('#testEnvModalSTCAbacus').modal('show');
}
}
});
if(recipient=="STC"){
$(".GeneratorDiv").show();
}else{
$(".GeneratorDiv").hide();
}
}
}
function isEnvSet(task)
{
var select = document.getElementById('sel');
if(select.selectedIndex == -1){
$("#save").html("Please configure TestBed first in add TestBed page.")
displayHideBox('2');
return true;
}
else
{
if(task=="save")
{
$("#save").html("TestBed details saved successfully")
displayHideBox('2');
return false;
}
else
{
$("#error").html("Confirm TestBed deletion?")
$("#confirmButton").attr("onClick","rollbackEnv();return false;");
displayHideBox('1');
return false;
}
}
}
function getCpeMOdels(vendor,selectedCpe){
$("#cpeModel").html("");
$.ajax({
url: "addCpeModelList/"+vendor,
type: 'GET',
cache:false,
success:function(response){
for(var i=0;i<response.length;i++){
//alert(response[i]);
$("#cpeModel").append("<option value="+response[i]+">"+response[i]+"</option>");
}
if(selectedCpe!="null")
{
$('#cpeModel').val(selectedCpe);
}
return true;
}
});
}
function getFirmwareVersions(vendor,selectedVersion){
$("#cpeVersion").html("");
$.ajax({
url: "getFirmwareList/"+vendor,
type: 'GET',
cache:false,
success:function(response){
for(var i=0;i<response.length;i++){
//alert(response[i]);
$("#cpeVersion").append("<option value="+response[i]+">"+response[i]+"</option>");
}
if(selectedVersion!="null")
{
$('#cpeVersion').val(selectedVersion);
}
return true;
}
});
}
function deleteDevice(device)
{
if(device=='CPE')
{
//alert(cmMac);
$("#error").html("Confirm CPE deletion?");
$("#confirmButton").attr("onClick","deleteCpe();return false;");
}
else if(device=='CMTS')
{
$("#error").html("All CPE related to CMTS will also be deleted. Confirm CMTS deletion?");
$("#confirmButton").attr("onClick","deleteCMTS();return false;");
}
else
{
$("#error").html("Confirm test controller deletion?");
$("#confirmButton").attr("onClick","DeleteTestEnv('"+device+"');return false;");
}
displayHideBox('1');
return false;
}
function deleteCMTS()
{
var cmtsId = $('#cmtsId').val();
var json = {"cmtsId" : cmtsId};
$.ajax({
url: "deleteCmts",
type: 'POST',
data: JSON.stringify(json),
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "text/plain");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
if(response == "success")
{
displayHideBox('1');
$( "#addCmtsErrorMsg" ).html("Successfully deleted CMTS!").css('color','blue');
$("#cmtsDeleteButton").attr('disabled',true);
$('#userName').val("");
$('#password').val("");
$('#ipAddress').val("");
$( "#"+row_num+column_num ).html("");
for(var col=4;col<16;col++){
$( "#"+row_num+col).html("");
}
return false;
}
else
{
displayHideBox('1');
$( "#addCmtsErrorMsg" ).html(response).css('color','red');
return false;
}
},
});
}
function deleteCpe()
{
var cpeId = $('#cpeId').val();
var json = {"cpeId" : cpeId};
$.ajax({
url: "deleteCpe",
type: 'POST',
data: JSON.stringify(json),
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "text/plain");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
if(response == "success")
{
displayHideBox('1');
$( "#addCpeErrorMsg" ).html("Successfully deleted CPE!").css('color','blue');
$("#cpeDeleteButton").attr('disabled',true);
$('#cpeVendor').val("");
$('#cpeModel').val("");
$('#cmMac').val("");
$('#mtaMac').val("");
$('#telephoneOne').val("");
$('#telephoneTwo').val("");
$( "#"+row_num+column_num ).html("");
return false;
}
else
{
displayHideBox('1');
$( "#addCpeErrorMsg" ).html(response).css('color','red');
return false;
}
},
});
}
function displayHideBox(boxNumber)
{
if(document.getElementById("LightBox"+boxNumber).style.display=="none") {
document.getElementById("LightBox"+boxNumber).style.display="block";
document.getElementById("grayBG").style.display="block";
} else {
document.getElementById("LightBox"+boxNumber).style.display="none";
document.getElementById("grayBG").style.display="none";
}
}
function saveTestSTCGenerator(){
var bool=true;
var boolGen=true;
var allelements = [];
var finalobj = new Object();
$('#firsttr tr').each(function (i, row) {
// reference all the stuff you need first
if(i>=2)
{
var $row = $(row);
var TrName = $row.closest('tr').attr('name');
if($row.find('td[name="clientPorttd"]').find('input[name="clientPort"]').val()==null || $row.find('td[name="clientPorttd"]').find('input[name="clientPort"]').val()==undefined )
{
$clientPort=$row.find('td[name="clientPorttd"]').text();
}
else
{
if($row.find('td[name="clientPorttd"]').find('input[name="clientPort"]').val().trim()!="")
{
$clientPort=$row.find('td[name="clientPorttd"]').find('input[name="clientPort"]').val();
}
else
{
$( "#testControlletrSTCEditEnvErrorMsg" ).html("Please Enter Client Port").css('color','red');
bool=false;
}
}
if($row.find('td[name="serverPorttd"]').find('input[name="serverPort"]').val()==null || $row.find('td[name="serverPorttd"]').find('input[name="serverPort"]').val()==undefined )
{
$serverPort=$row.find('td[name="serverPorttd"]').text();
}
else
{
if($row.find('td[name="serverPorttd"]').find('input[name="serverPort"]').val().trim())
$serverPort=$row.find('td[name="serverPorttd"]').find('input[name="serverPort"]').val();
else
{
$( "#testControlletrSTCEditEnvErrorMsg" ).html("Please Enter Server Port").css('color','red');
bool=false;
}
}
if($row.find('td[name="cpeGatewaytd"]').find('input[name="cpeGateway"]').val()==null || $row.find('td[name="cpeGatewaytd"]').find('input[name="cpeGateway"]').val()==undefined )
{
$cpeGateway=$row.find('td[name="cpeGatewaytd"]').text();
}
else
{
$cpeGateway=$row.find('td[name="cpeGatewaytd"]').find('input[name="cpeGateway"]').val();
$row.find('td[name="cpeGatewaytd"]').find('input[name="cpeGateway"]').css({"box-shadow":"none"});
if(!validateIPaddress($cpeGateway))
{
$row.find('td[name="cpeGatewaytd"]').find('input[name="cpeGateway"]').css({"box-shadow":"0px 0px 5px red"})
bool=false;
}
}
// if($row.find('td[name="cpeMacValtd"]').find('input[name="cpeMacVal"]').val()==undefined || $row.find('td[name="cpeMacValtd"]').find('input[name="cpeMacVal"]').val()==null )
// {
//
// $cpeMacVal=$row.find('td[name="cpeMacValtd"]').text();
//
// }
// else
// {
// $cpeMacVal=$row.find('td[name="cpeMacValtd"]').find('input[name="cpeMacVal"]').val();
//
// $row.find('td[name="cpeMacValtd"]').find('input[name="cpeMacVal"]').css({"box-shadow":"none"});
//
// var patt = new RegExp("^([0-9a-fA-F]{2}[:-]){5}([0-9a-fA-F]{2})$");
//
//
// if(!patt.test($cpeMacVal))
// {
// $row.find('td[name="cpeMacValtd"]').find('input[name="cpeMacVal"]').css({"box-shadow":"0px 0px 5px red"});
// bool=false;
// }
//
// }
if($row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').val()==null || $row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').val()==undefined )
{
$cpeIpVal=$row.find('td[name="cpeIpValtd"]').text();
}
else
{
$cpeIpVal=$row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').val();
$row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').css({"box-shadow":"none"});
if(!validateIPaddress($cpeIpVal))
{
$row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').css({"box-shadow":"0px 0px 5px red"});
bool=false;
}
}
if(existingGenerator(TrName))
{
//alert("here");
boolGen=false;
}
$EditidCheck=$row.find('td[name="Edit"]').find( "input[name=Edit"+(i-1)+"]" ).val();
var myObject = new Object();
myObject.clientPort = $clientPort;
myObject.serverPort = $serverPort;
myObject.cpeGateway = $cpeGateway;
//myObject.cpeMacVal = $cpeMacVal;
myObject.cpeIpVal = $cpeIpVal;
myObject.EditId = $EditidCheck;
allelements.push(myObject);
}
});
finalobj.stcData=allelements;
finalobj.userNetworkId=userNetworkId;
finalobj.environmentNameValue=environmentNameValue;
finalobj.stcIp=$("#AbacusStcIP").val();
console.log(JSON.stringify(finalobj));
if(!bool)
{
$( "#testControlletrSTCEditEnvErrorMsg" ).html("Please provide all field in proper format").css('color','red');
}
else if(!boolGen)
{
$( "#testControlletrSTCEditEnvErrorMsg" ).html("Generator already configured").css('color','red');
}
else if(generatoRowCount==0)
{
$( "#testControlletrSTCEditEnvErrorMsg" ).html("Please add generator details first").css('color','red');
}
else
{
$.ajax({
url: "user/environment/addGenerator",
type: 'POST',
data: JSON.stringify(finalobj),
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
if(response){
$( "#testControlletrSTCEditEnvErrorMsg" ).html("Generator details saved Successfully").css('color','blue');
}else{
$( "#testControlletrSTCEditEnvErrorMsg" ).html("Generator details not saved, please try after sometime!").css('color','red');
}
}
});
}
}
function existingGenerator(TrName)
{
//alert("hi");
//alert(TrName);
if(TrName=="undefined")
{
//alert("undefined");
var clientPort = $("#clientPort").val();
var serverPort = $("#serverPort").val();
var cpeGateway = $("#cpeGateway").val();
var cpeIpVal = $("#cpeIpVal").val();
var flag=0;
$('#firsttr tr').each(function (i, row)
{
var $row = $(row);
var ExistClientPort = ($row.find('td[name="clientPorttd"]').find('input[name="clientPort"]').val()==null || $row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').val()==undefined )?$row.find('td[name="clientPorttd"]').text():$row.find('td[name="clientPorttd"]').find('input[name="clientPort"]').val();
var ExistServerPort = ($row.find('td[name="serverPorttd"]').find('input[name="serverPort"]').val()==null || $row.find('td[name="serverPorttd"]').find('input[name="serverPort"]').val()==undefined?$row.find('td[name="serverPorttd"]').text():$row.find('td[name="serverPorttd"]').find('input[name="serverPort"]').val());
var ExistCpeGateway = ($row.find('td[name="cpeGatewaytd"]').find('input[name="cpeGateway"]').val()==null || $row.find('td[name="cpeGatewaytd"]').find('input[name="cpeGateway"]').val()==undefined?$row.find('td[name="cpeGatewaytd"]').text():$row.find('td[name="cpeGatewaytd"]').find('input[name="cpeGateway"]').val());
var ExistCpeIpVal = ($row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').val()==null || $row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').val()==undefined?$row.find('td[name="cpeIpValtd"]').text():$row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').val());
//alert("ExistClientPort:"+ExistClientPort+"ExistServerPort:"+ExistServerPort+"ExistCpeGateway:"+ExistCpeGateway+"ExistCpeIpVal:"+ExistCpeIpVal);
if(ExistClientPort==clientPort && ExistServerPort==serverPort && cpeGateway==ExistCpeGateway && cpeIpVal==ExistCpeIpVal)
{
flag=1;
}
});
}
else
{
var clientPort = $('tr[name="'+TrName+'"]').find('td[name="clientPorttd"]').find('input[name="clientPort"]').val();
var serverPort = $('tr[name="'+TrName+'"]').find('td[name="serverPorttd"]').find('input[name="serverPort"]').val();
var cpeGateway = $('tr[name="'+TrName+'"]').find('td[name="cpeGatewaytd"]').find('input[name="cpeGateway"]').val();
var cpeIpVal = $('tr[name="'+TrName+'"]').find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').val();
//alert("clientPort"+clientPort+"serverPort"+serverPort+"cpeGateway"+cpeGateway+"cpeIpVal"+cpeIpVal);
$('#firsttr tr').each(function (i, row) {
var $row = $(row);
if($row.closest('tr').attr('name')!=TrName)
{
var ExistClientPort = ($row.find('td[name="clientPorttd"]').find('input[name="clientPort"]').val()==null || $row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').val()==undefined )?$row.find('td[name="clientPorttd"]').text():$row.find('td[name="clientPorttd"]').find('input[name="clientPort"]').val();
var ExistServerPort = ($row.find('td[name="serverPorttd"]').find('input[name="serverPort"]').val()==null || $row.find('td[name="serverPorttd"]').find('input[name="serverPort"]').val()==undefined?$row.find('td[name="serverPorttd"]').text():$row.find('td[name="serverPorttd"]').find('input[name="serverPort"]').val());
var ExistCpeGateway = ($row.find('td[name="cpeGatewaytd"]').find('input[name="cpeGateway"]').val()==null || $row.find('td[name="cpeGatewaytd"]').find('input[name="cpeGateway"]').val()==undefined?$row.find('td[name="cpeGatewaytd"]').text():$row.find('td[name="cpeGatewaytd"]').find('input[name="cpeGateway"]').val());
var ExistCpeIpVal = ($row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').val()==null || $row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').val()==undefined?$row.find('td[name="cpeIpValtd"]').text():$row.find('td[name="cpeIpValtd"]').find('input[name="cpeIpVal"]').val());
if(ExistClientPort==clientPort && ExistServerPort==serverPort && cpeGateway==ExistCpeGateway && cpeIpVal==ExistCpeIpVal)
{
flag=1;
}
}
});
}
if(flag==1)
return true;
else
return false;
}
|
import React from 'react'
import Link from 'gatsby-link'
import NavComponent from './NavComponent'
import '../assets/App.css'
const Nav = () => (
<div className="nav-bar">
<Link to="/intro" style={{textDecoration: 'none'}}>
<NavComponent title={"Intro"} />
</Link>
<Link to="/work" style={{ textDecoration: 'none' }}>
<NavComponent title={"Work"} />
</Link>
<Link to="/projects" style={{ textDecoration: 'none' }}>
<NavComponent title={"Projects"} />
</Link>
<Link to="/contact" style={{ textDecoration: 'none' }}>
<NavComponent title={"Contact"} />
</Link>
</div>
)
export default Nav
|
import Ember from 'ember';
export default Ember.TextField.extend({
}); |
var Event = require("../models/event")
const Events = module.exports
Events.list = () => {
return Event
.find()
.sort({name: -1})
.exec()
}
Events.getEvent = id => {
return Event
.findOne({_id: id})
.exec()
}
Events.createEvent = event => {
return Event.create(event)
}
Events.insertMany = events => {
return Event.insertMany(events)
}
Events.updateEvent = (id, event) => {
return Event
.findOneAndUpdate({_id: id}, event, {useFindAndModify: false})
.exec()
}
Events.deleteEvent = id => {
return Event
.findOneAndDelete({_id: id})
.exec()
}
Events.getEventsByDate = date => {
return Event
.find({ $and: [{ startDate: {$lte: date} }, { endDate: {$gte: date} }] })
.sort({startDate: 1, startHour: 1})
.exec()
}
Events.getEventsByHour = hour => {
return Event
.find({ $and: [{ startHour: {$lte: hour} }, { endHour: {$gte: hour} }] })
.sort({startDate: 1, startHour: 1})
.exec()
}
Events.getEventsByDateHour = (date, hour) => {
return Event
.find({ $and: [{ startDate: {$lte: date} }, { endDate: {$gte: date} }, { startHour: {$lte: hour} }, { endHour: {$gte: hour} }] })
.sort({startDate: 1, startHour: 1})
.exec()
}
Events.getEventsByLocal = localI => {
return Event
.find({local: localI})
.exec()
} |
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import LinearProgress from 'material-ui/LinearProgress';
import { crudGetManyReference as crudGetManyReferenceAction } from '../../actions/dataActions';
import { getReferences, nameRelatedTo } from '../../reducer/references/oneToMany';
/**
* Render related records to the current one.
*
* You must define the fields to be passed to the iterator component as children.
*
* @example Display all the comments of the current post as a datagrid
* <ReferenceManyField reference="comments" target="post_id">
* <Datagrid>
* <TextField source="id" />
* <TextField source="body" />
* <DateField source="created_at" />
* <EditButton />
* </Datagrid>
* </ReferenceManyField>
*
* @example Display all the books by the current author, only the title
* <ReferenceManyField reference="books" target="author_id">
* <SingleFieldList>
* <ChipField source="title" />
* </SingleFieldList>
* </ReferenceManyField>
*/
export class ReferenceManyField extends Component {
componentDidMount() {
const relatedTo = nameRelatedTo(this.props.reference, this.props.record.id, this.props.resource, this.props.target);
this.props.crudGetManyReference(this.props.reference, this.props.target, this.props.record.id, relatedTo);
}
componentWillReceiveProps(nextProps) {
if (this.props.record.id !== nextProps.record.id) {
const relatedTo = nameRelatedTo(nextProps.reference, nextProps.record.id, nextProps.resource, nextProps.target);
this.props.crudGetManyReference(nextProps.reference, nextProps.target, nextProps.record.id, relatedTo);
}
}
render() {
const { resource, reference, referenceRecords, children, basePath } = this.props;
if (React.Children.count(children) !== 1) {
throw new Error('<ReferenceManyField> only accepts a single child (like <Datagrid>)');
}
if (typeof referenceRecords === 'undefined') {
return <LinearProgress style={{ marginTop: '1em' }} />;
}
const referenceBasePath = basePath.replace(resource, reference); // FIXME obviously very weak
return React.cloneElement(children, {
resource: reference,
ids: Object.keys(referenceRecords),
data: referenceRecords,
basePath: referenceBasePath,
currentSort: {},
});
}
}
ReferenceManyField.propTypes = {
basePath: PropTypes.string.isRequired,
children: PropTypes.element.isRequired,
crudGetManyReference: PropTypes.func.isRequired,
includesLabel: PropTypes.bool,
label: PropTypes.string,
record: PropTypes.object,
reference: PropTypes.string.isRequired,
referenceRecords: PropTypes.object,
resource: PropTypes.string.isRequired,
source: PropTypes.string.isRequired,
target: PropTypes.string.isRequired,
};
function mapStateToProps(state, props) {
const relatedTo = nameRelatedTo(props.reference, props.record.id, props.resource, props.target);
return {
referenceRecords: getReferences(state, props.reference, relatedTo),
};
}
const ConnectedReferenceManyField = connect(mapStateToProps, {
crudGetManyReference: crudGetManyReferenceAction,
})(ReferenceManyField);
ConnectedReferenceManyField.defaultProps = {
includesLabel: false,
source: '',
};
export default ConnectedReferenceManyField;
|
function borrowMe() {
arguments.join = [].join;
var arg = arguments.join(":");
console.log(arg);
}
borrowMe(1,2,3,4,5);
|
class Validator {
constructor(name) {
this.name = name;
}
validateUsername() {
return /^[^_\W\d-][\w-]*[^_\W\d-]+$/.test(this.name) && !/\d{4}/.test(this.name);
}
}
export default Validator;
const valid = new Validator('h');
console.log(valid.validateUsername());
|
// 本期参与者
var DM_Commodity_PartInRecord = function(){
MessageMachine.call(this);
// url
this.url = url_host+"/trade/records/";
// template
this._template=
' <div class="ub ub-fh umar-ts bd-b-dashed" ontouchstart="dfh_touch()" onclick="openUserspace({{user.id}})"> '+
' <div class="ub-img1 img-head" style="background-image:url({{user.headImg}})"></div> '+
' <div class="umar-l ub-f1"> '+
' <div><em onclick="openUserspace({{user.id}})">{{user.nickName}}</em></div> '+
' <div class="ub ub-fh c-gray umar-ts f-small">IP:{{ip}}(城市:{{city}})</div> '+
' <div class="ub ub-fh c-gray f-small"> '+
' <div class="ub-f1">{{createTime}}</div> '+
' <div class="umar-l"><span class="c-important">{{count}}</span>人次</div> '+
' </div> '+
' </div> '+
' </div>';
// set Render
this.setRender(this._template);
// 数据格式转换
this.transfer = function(data){
if (data) {
// 日期格式
data.createTime = getFormatDateByLong(data.createTime, "yyyy-MM-dd hh:mm:ss.S");
}
return data;
}
// 测试数据
this.getTestData = function(){
var response = '{}';
return JSON.parse(response);
}
}
|
define([],function(){
app_cached_providers.$compileProvider.directive('psDatetimePicker',['$compile','$rootScope',
function($compile,$rootScope){
return {
restrict: 'A',
require: 'ngModel',
scope:{
format:'@',
mindate :'@',
maxdate :'@',
setDefault:'@',
oldDate:'@'
},
link: function (scope, element, attributes, ctrl) {
//console.log("Max date time value=====",scope.mindate);
//console.log("Min date time value=====",scope.mindate);
var currYear=new Date().getFullYear();
element.datetimepicker({
format: scope.format,
minDate:scope.mindate,
maxDate:scope.maxdate,
widgetPositioning:
{
horizontal: 'left',
vertical: 'bottom'
}
});
var picker = element.data("DateTimePicker");
element.focus(function(){
if(element.val()==="" && scope.oldDate){
element.val(scope.oldDate);
}
});
element.on("dp.change", function (e) {
});
if(scope.setDefault){
ctrl.$formatters.push(function (value) {
//console.log("date time value=====",value);
var date = moment(value);
if (date.isValid()) {
return '';//date.format(scope.format);
}
return '';
});
}
// scope.updateModel = function(item)
// {
// ctrl.$setViewValue(item);
// }
element.on('blur', function (event) {
console.log(element.val());
ctrl.$setViewValue(element.val());
});
}
};
}]);
});
|
angular.module('it').filter('serialization', function() {
return function(serialType) {
var serialOut = '';
switch(serialType) {
case 2:
serialOut = 'Advanced';
break;
case 1:
serialOut = 'Simple';
break;
case 0:
default:
serialOut = 'None';
break;
}
return serialOut;
}
}); |
/* eslint-disable jsx-a11y/anchor-is-valid */
import React from 'react';
const Contact = () => {
return (
// <!-- ##### Contact Area Start ##### -->
<section className="about-area section-padding-100-0">
<div className="container">
<div className="row">
{/* <!-- Section Heading --> */}
<div className="col-12">
<div className="section-heading">
<h2>Contact Us</h2>
<p>A church isn't a building—it's the people. We meet in locations around the United States and globally at Life.Church Online. No matter where you join us.</p>
</div>
</div>
</div>
<div className="row about-content justify-content-center">
{/* <!-- Single About Us Content --> */}
<div className="col-12 col-md-6 col-lg-4">
<div className="about-us-content mb-100">
<img src="img/bg-img/3.jpg" alt=""/>
<div className="about-text">
<h4>Contact</h4>
<p>Giáo Xứ Các Thánh Tử Đạo Việ Nam thuộc Tổng Giáo Phận Atlanta là cộng đoàn người Việt cùng sống, cử hành, loan truyền đức tin Công Giáo, đồng thời duy trì và pháttriển truyền thống văn hóa Việt Nam.</p>
<a href="#">Read More <i className="fa fa-angle-double-right"></i></a>
</div>
</div>
</div>
{/* <!-- Single About Us Content --> */}
<div className="col-12 col-md-6 col-lg-4">
<div className="about-us-content mb-100">
<img src="img/bg-img/4.jpg" alt=""/>
<div className="about-text">
<h4>Contact</h4>
<p>1992: Thánh Lễ Tiếng VIệt đầu tiên tại giáo xứ Holy Cross. Lm.Tuyên úy Toma Nguyễn Thái Thành. Sơ Christine Trương Mỹ Hạnh.</p>
<a href="#">Read More <i className="fa fa-angle-double-right"></i></a>
</div>
</div>
</div>
{/* <!-- Single About Us Content --> */}
<div className="col-12 col-md-6 col-lg-4">
<div className="about-us-content mb-100">
<img src="img/bg-img/5.jpg" alt=""/>
<div className="about-text">
<h4>Xây Dựng Thánh Đường</h4>
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form.</p>
<a href="#">Read More <i className="fa fa-angle-double-right"></i></a>
</div>
</div>
</div>
</div>
</div>
</section>
//<!-- ##### About Area End ##### -->
);
};
export default Contact |
define(['app', 'easyCodeConfiguration', 'easyCodeParser', 'controllers/popUp'], function(app, easyCodeConfiguration, Parser){
var formValidator = {
isEmpty : function(value) {
return value == undefined || value.trim().length == 0;
},
'define' : function(values) {
return !this.isEmpty(values.varname) && !this.isEmpty(values.type);
},
'read' : function(values) {
return !this.isEmpty(values.varname);
},
'afectation' : function(values) {
if (values.varType == 'array') {
if (!values.arrayType) {
return false;
}
if (values.arrayType == 3 && !values.expression) {
return false;
}
}
return values.varname != undefined ;
},
'if' : function(values) {
return !this.isEmpty(values.test);
},
'while' : function(values) {
return !this.isEmpty(values.test);
},
'foreach' : function(values) {
return !this.isEmpty(values.varname) && !this.isEmpty(values.array);
},
'for' : function(values) {
return !this.isEmpty(values.varname) && !this.isEmpty(values.start) && !this.isEmpty(values.end);
}
};
var codeConstructor = {
tabulate : function(lines){
return lines.replace(/\n/g, '\n\t');
},
escapeString : function(string) {
return string.replace(/"/g, '\\"');
},
/**
* if expression have error expression is a string
*/
refactorExpression : function(context, expression) {
var parser = new Parser(undefined, context);
parser.initParser(expression);
// try to parse expression
try {
parser.parseExpression();
} catch (exception) {
return '"'+ this.escapeString(expression) + '"';
}
return expression;
},
// définir varname vartype
'define' : function(context, values) {
return {code : 'DEFINIR ' + values.varname + ' ' + values.type};
},
'read' : function(context, values ) {
return {code : 'LIRE ' + values.varname};
},
'afectation' : function(context, values) {
var vartype = values.varType;
var expression = undefined;
console.log(vartype);
// it's a string
if (vartype == 'string' && values.message) {
expression = '"' + this.escapeString(values.message) + '"';
} else if (vartype == 'number' && values.number) {
expression = values.number;
} else if (vartype == 'boolean' && values.boolean) {
expression = values.boolean;
} else if (vartype == 'array') {
if (values.arrayType == 1) {
expression = '[';
if (values.arrayValues) {
for (var i in values.arrayValues) {
expression += this.refactorExpression(context, values.arrayValues[i]) + '; ';
}
expression = expression.substring(0, expression.length - 2);
}
expression += ']';
} else if (values.arrayType == 2) {
expression = '[';
if (values.arrayValues) {
for (var i in values.arrayValues) {
var value = values.arrayValues[i];
expression += this.refactorExpression(context, value.key) + ' : ' + this.refactorExpression(context, value.value) + '; ';
}
expression = expression.substring(0, expression.length - 2);
}
expression += ']';
} else if (values.arrayType == 3) {
values.varname += '[' + (values.index || '') + ']';
}
}
if (!expression) {
expression = this.refactorExpression(context, values.expression);
}
return {code : values.varname + ' = ' + expression}
},
'write' : function(context, values) {
var expression = undefined;
if (values.message) {
expression = '"' + this.escapeString(values.message) + '"';
}
if (!expression) {
expression = this.refactorExpression(context, values.expression);
}
return {code : 'ECRIRE ' + expression + (values.output ? ' \''+values.output+'\'' : '')}
},
'if' : function(context, values, selectedCode) {
var code = 'SI ' + values.test + '\n';
if (selectedCode) {
code += '\t' + this.tabulate(selectedCode.trim());
} else {
code += '\t' + '// code si le test est vrai';
}
if (values.elseBlock) {
code += '\nSI_NON\n\t//code si le test est faux';
}
code += '\nFIN_SI';
return {overrideSelection : true, code : code};
},
'while' : function(context, values, selectedCode) {
var code = 'TANT_QUE ' + values.test + '\n';
if (selectedCode) {
code += '\t' + this.tabulate(selectedCode.trim());
} else {
code += '\t' + '// code executé dans la boucle';
}
code += '\nFIN_TANT_QUE';
return {overrideSelection : true, code : code};
},
'foreach' : function(context, values, selectedCode) {
var code = '';
if (!context.isset(values.varname, false)) {
code = 'DEFINIR ' + values.varname + ' CHAINE // attention vérifier le type de la variable \n';
}
code += 'POUR ' + values.varname + ' DANS ' + values.array + '\n';
if (selectedCode) {
code += '\t' + this.tabulate(selectedCode.trim());
} else {
code += '\t' + '// code executé pour chaques element du tableau';
}
code += '\nFIN_POUR';
return {overrideSelection : true, code : code};
},
'for' : function(context, values, selectedCode) {
var code = '';
if (!context.isset(values.varname, false)) {
code = 'DEFINIR ' + values.varname + ' NOMBRE\n';
}
code += 'POUR ' + values.varname + ' DE ' + values.start + ' A ' + values.end;
if (values.step) {
code += ' PAR ' + values.step;
}
code += '\n';
if (selectedCode) {
code += '\t' + this.tabulate(selectedCode.trim());
} else {
code += '\t' + '// code executé pour chaques element du tableau';
}
code += '\nFIN_POUR';
return {overrideSelection : true, code : code};
}
};
app.controller('editorInstructionPopUp', function($scope, $modalInstance, $controller,$timeout, codeMirror){
// extends PopUpController
angular.extend(this, $controller('popUpController', {$scope: $scope, $modalInstance : $modalInstance, title : '', message : '', buttons : {}}));
$scope.sections = {
'Instruction' : {
'Définir une variable' : {id : 'define', title : 'Définir une variable'},
'Lire une variable' : {id : 'read', title : 'Lire une variable'},
'Ecrire un message' : {id : 'write', title : 'Ecrire un message'},
'Afecter une variable' : {id : 'afectation', title : 'Afectation d\'une variable'},
'position' : 1
},
'Structure conditionelle' : {
'Si' : {id : 'if', title : 'Condition'},
'position' : 2
},
'Structure itérative' : {
'Execution tant que vrai' : {id:'while', 'title' : 'Boucle tant que'},
'Parcour entre deux nombres' : {id:'for', 'title' : 'Boucle pour'},
'Parcour d\'un tableau' : {id:'foreach', 'title' : 'Boucle pour chaque'},
'position' : 3
},
'Aide' : {
'Liste de fonctions' : {type : 'help', id : 'functions', title : 'Fonctions'},
'Liste des variables' : {type : 'help', id : 'variables', title : 'Variables'},
'position' : 4
}
};
$scope.configuration = easyCodeConfiguration;
$scope.selected = undefined;
$scope.setSelected = function(menu) {
if (menu.type == 'help') {
$scope.help = menu;
} else {
if ($scope.selected) {
$scope.selected.selected = false;
}
$scope.selected = menu;
menu.selected = true;
$scope.isValidated = false;
}
};
$scope.closeHelp = function(){
$scope.help = undefined;
};
// init vars selectionnales
var parser = new Parser();
var parsed = parser.parse(codeMirror.getValue());
// get var by context
var pos = codeMirror.indexFromPos(codeMirror.getCursor());
var context = parsed.context.getContextFor(pos);
$scope.vars = context.getAccessibleVars();
$scope.functions = easyCodeConfiguration.getFunctions();
$scope.functionsDescription = easyCodeConfiguration.getFunctionsDescription();
$scope.removeArray = function(index) {
$scope.selected.arrayValues.splice(index, 1);
};
$scope.addArrayValue = function(value) {
if (!$scope.selected.arrayCurrentValue) {
return;
}
if ($scope.selected.arrayValues == undefined) {
$scope.selected.arrayValues = [];
}
$scope.selected.arrayValues.push($scope.selected.arrayCurrentValue);
$scope.selected.arrayCurrentValue = undefined;
};
$scope.validateForm = function(){
$scope.isValidated = true;
var selected = $scope.selected || {};
if (selected.id in formValidator) {
var valide = formValidator[selected.id](selected);
return valide;
}
return true;
};
// when the popup is closed
$modalInstance.result.then(function () {
// no selection just close the popup
if (!$scope.selected || !($scope.selected.id in codeConstructor)) {
return ;
}
function tabulate(indentNumber) {
var tab = '';
for (var i = 0; i < indentNumber; ++i) {
tab += ' ';
}
return tab;
}
var easyCodeMod = codeMirror.getMode({},"easyCode");
// timeout is used because replaceRange do digest error
$timeout(function(){
var selection = codeMirror.listSelections()[0];
var selected = $scope.selected || {};
// new line of code
var newLine = undefined;
// must remove the selected code
var overrideSelection = false;
// check if start == end
var selectedCode = undefined;
if(!(selection.head.line == selection.anchor.line && selection.head.ch == selection.anchor.ch)) {
var startSelected = CodeMirror.Pos(selection.head.line, 0);
var endLineSelected = codeMirror.getLine(selection.anchor.line);
var endSelected = CodeMirror.Pos(selection.anchor.line, endLineSelected.length);
selectedCode = codeMirror.getRange(startSelected, endSelected);
}
var value = codeConstructor[selected.id](context, selected, selectedCode);
newLine = value.code;
overrideSelection = value.overrideSelection || false;
var start = overrideSelection && selectedCode ? startSelected : selection.head;
var end = overrideSelection && selectedCode ? endSelected : selection.head;
// indent correctly the current line
var token = codeMirror.getTokenAt(start);
var indentNumber = easyCodeMod.indent(token.state, newLine);
// tabulate
var stringTabulate = tabulate(indentNumber);
console.log(newLine);
newLine = stringTabulate + newLine;
newLine = newLine.replace(/\n/g, '\n' + stringTabulate);
console.log(newLine);
// already add a new line end add the code at the end of line
var beforeCursor = codeMirror.getRange(CodeMirror.Pos(start.line, 0), start);
var line = codeMirror.getLine(start.line);
if (beforeCursor.trim().length > 0) {
// if we are not at start of line add the line after the current
start.ch = line.length;
newLine = '\n' + newLine;
} else if (line.trim().length > 0){
// if we are at start on an existing line add the line before this line
start.ch = 0;
newLine = newLine + (overrideSelection ? '' : '\n' );
} else {
// empty line add the line on this line
start.ch = 0;
}
// add code on code mirror
codeMirror.replaceRange (
newLine,
start,
end
);
codeMirror.setSelection(start, start);
})
});
});
}); |
(function () {
'use strict';
angular
.module('app')
.controller('ImagesController', ImagesController);
ImagesController.$inject = ['$scope','$http','ImagesService','uiGridConstants'];
function ImagesController($scope, $http, ImagesService, uiGridConstants) {
$scope.error = null;
var paginationOptions = {
pageNumber: 1,
pageSize: 10,
sort: null
};
ImagesService.getImages(
paginationOptions.pageNumber,
paginationOptions.pageSize).then(function(data){
$scope.gridOptions.data = data.content;
$scope.gridOptions.totalItems = data.totalElements;
},
function(error){
$scope.error = error
});
$scope.gridOptions = {
paginationPageSizes: [10, 20, 30],
paginationPageSize: paginationOptions.pageSize,
enableRowSelection: true,
enableColumnMenus:false,
useExternalPagination: true,
enableFiltering: true,
columnDefs: [
{ name: 'id', enableFiltering: false },
{ name: 'name'},
{ name: 'dateUpload', type: 'date', cellFilter: 'date:\'yyyy-MM-dd HH:mm\'', enableFiltering: false }
],
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
gridApi.pagination.on.paginationChanged(
$scope,
function (newPage, pageSize) {
paginationOptions.pageNumber = newPage;
paginationOptions.pageSize = pageSize;
ImagesService.getImages(newPage,pageSize)
.then(function(data){
$scope.gridOptions.data = data.content;
$scope.gridOptions.totalItems = data.totalElements;
});
});
}
};
}
})(); |
import { Typography } from "@material-ui/core";
import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import SearchIcon from "@material-ui/icons/Search";
import moment from "moment";
import React, { useState } from "react";
import demoServiceApi from "../../../api/demoServiceApi";
import DatePicker from "../../../components/controls/DatePicker";
import IntroVIPSearch from "../../../components/introVIPSearch/IntroVIPSearch";
import BackgroundImage from "../../../images/bg2.jpg";
import "./DemoService.scss";
import { Container } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
root: {
"& .MuiTextField-root": {
margin: "8px 0",
},
},
mtBtn: {
margin: "0 auto",
marginTop: "8px",
color: "white",
opacity: 0.8,
"&:hover": {
opacity: 1,
},
},
heading: {
textAlign: "center",
color: "#fff",
marginBottom: "1.5rem",
},
gridItem: {
padding: "12px 8px !important",
},
container: {
backgroundImage: `url(${BackgroundImage})`,
backgroundRepeat: " no-repeat",
backgroundSize: "cover",
position: "relative",
"&:after": {
content: "''",
position: "absolute",
top: 0,
left: 0,
bottom: 0,
right: 0,
background: "rgba(0,0,0,0.4)",
zIndex: 0,
},
},
}));
const DemoService = ({ data }) => {
const classes = useStyles();
// const formatYmd = (date) => date.toISOString().slice(0, 10);
const date = new Date();
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [birthDay, setBirthDay] = useState(date);
const [phoneNumber, setPhoneNumber] = useState("");
const [address, setAddress] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
const dataFormCheck = {
name: name,
email: email,
birthDay: moment(birthDay).format("YYYY-MM-DD"),
phoneNumber: phoneNumber,
address: address,
};
const fetchDemoService = () => {
try {
demoServiceApi
.postDemoService(dataFormCheck)
.then(function (response) {
console.log(response.data._id);
const idFreeSearch = response.data._id;
localStorage.setItem("idFreeSearch", idFreeSearch);
//history.push("/tra-cuu");
})
.catch(function (error) {
// setName("");
// setEmail("");
// setBirthDay("");
// setPhoneNumber("");
// setAddress("");
});
} catch (error) {
console.log("failed to fetch product list: ", error);
}
};
fetchDemoService();
};
return (
<Container className={classes.container}>
<div id="demoServiceBlock" className="block demoServiceBlock">
<Typography variant="h1" className={classes.heading}>
Dịch vụ của chúng tôi
</Typography>
<div className="demoServiceContent">
<Grid container spacing={8}>
<Grid item container md={6} xs={12} sm={6}>
<Typography variant="h3" component="h3" className="titleVIP">
Tra cứu miễn phí
</Typography>
<Grid item md={12} style={{ height: "80%" }}>
<form className={classes.root} onSubmit={handleSubmit}>
<Grid container item spacing={2}>
<Grid item xs={12} className={classes.gridItem}>
<TextField
label="Họ tên"
variant="outlined"
name="fullName"
type="text"
required={true}
value={name}
onChange={(e) => setName(e.target.value)}
fullWidth
autoComplete="off"
/>
</Grid>
<Grid item xs={12} className={classes.gridItem}>
<TextField
label="Email"
variant="outlined"
name="email"
type="email"
required={true}
value={email}
onChange={(e) => setEmail(e.target.value)}
fullWidth
autoComplete="off"
/>
</Grid>
<Grid item xs={12} sm={6} className={classes.gridItem}>
<DatePicker
label="Ngày sinh"
variant="outlined"
name="birthDay"
value={birthDay}
onChange={(e) => setBirthDay(e.target.value)}
fullWidth
/>
</Grid>
<Grid item xs={12} sm={6} className={classes.gridItem}>
<TextField
label="Số điện thoại"
variant="outlined"
name="phoneNumber"
type="number"
required={true}
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
fullWidth
autoComplete="off"
/>
</Grid>
<Grid item xs={12} className={classes.gridItem}>
<TextField
label="Địa chỉ"
variant="outlined"
name="address"
type="text"
required={true}
value={address}
onChange={(e) => setAddress(e.target.value)}
fullWidth
autoComplete="off"
/>
</Grid>
</Grid>
<div style={{ textAlign: "center", marginTop: "2rem" }}>
<Button
variant="contained"
color="primary"
type="submit"
endIcon={<SearchIcon />}
className={classes.mtBtn}
>
Tra Cứu Miễn Phí
</Button>
</div>
</form>
</Grid>
</Grid>
<Grid
container
item
md={6}
xs={12}
sm={6}
style={{ width: "100%" }}
justifyContent="center"
>
<IntroVIPSearch data={data} />
</Grid>
</Grid>
</div>
</div>
</Container>
);
};
export default DemoService;
|
function congratulations(config) {
const project = require('./project')(config);
console.info('\n - Congrats! Your react module is ready to be built.');
console.info('\n Get started by:');
console.info(' 1. "cd ' + project.name.kebabCase + '" into your new project\'s directory');
console.info(' 2. Start writing your devilish code:');
console.info(' * "npm run build" - will use babel to transpile jsx and es6 code to plain es5 javascript to the "dist" folder');
console.info(' * "npm start" - starts a web server at "http://localhost:9000" with a single page app that will require your already transpiled react module.');
console.info(' * "npm test" - will use mocha to run all "' + project.name.kebabCase + '/test" files');
console.info('');
}
module.exports = congratulations;
|
import React from 'react';
import i18n from 'i18n/en';
const { HEADER } = i18n.EMPLOYEE.LIST.TABLE;
const EmployeeTableHeader = () => (
<div className="employee-table--header">
<div className="employee-table--thead flex-1">{HEADER.EMPLOYEE}</div>
<div className="employee-table--thead flex-1">{HEADER.JOB_TITLE}</div>
<div className="employee-table--thead flex-1">{HEADER.COUNTRY}</div>
<div className="employee-table--thead flex-1">{HEADER.SALARY}</div>
<div className="flex-1" />
</div>
);
export default EmployeeTableHeader;
|
$(document).ready(function () {
$(function() {
$('.demoslide img:gt(0)').hide();
setInterval(function(){
$('.demoslide :first-child').fadeOut() //FadeOut là ảnh đang hiện
.next('img').fadeIn() //fadeIn ảnh tiếp theo
.end().appendTo('.demoslide'); // chuyển vị trí ảnh xuống cuối
}, 5000);
})
// $('.txt-number-giohang').click(function (e) {
// e.preventDefault();
// $('.list-child-giohang').toggleClass('active-giohang');
// });
}); |
(function(){
var injectParams = ['$scope', '$q', '$interval', '$translate', '$stateParams', 'ChannelsService'];
var LivePlotterController = function($scope, $q, $interval, $translate, $stateParams, ChannelsService) {
$scope.data = [];
$scope.channels = [];
$scope.selectedChannels = [];
if ($stateParams.name) {
$scope.livePlotter = $scope.getPlotter($stateParams.name);
}
if ($scope.livePlotter && $scope.livePlotter.refresh) {
$scope.refresh = $scope.livePlotter.refresh;
} else {
$scope.refresh = 500;
}
if ($scope.livePlotter && $scope.livePlotter.timePeriod) {
$scope.timePeriod = $scope.livePlotter.timePeriod;
} else {
$scope.timePeriod = 7;
}
if ($scope.livePlotter && $scope.livePlotter.timePeriodUnit) {
$scope.timePeriodUnit = $scope.livePlotter.timePeriodUnit;
} else {
$scope.timePeriodUnit = "seconds";
}
if ($scope.livePlotter && $scope.livePlotter.yAxisLabel) {
$scope.yLabel = $scope.livePlotter.yAxisLabel;
} else {
$translate('VALUES').then(function(text) {
$scope.yLabel = text;
});
}
if ($scope.livePlotter && $scope.livePlotter.xAxisLabel) {
$scope.xLabel = $scope.livePlotter.xAxisLabel;
} else {
$translate('TIME').then(function(text) {
$scope.xLabel = text;
});
}
$translate('NOW').then(function(text) {
$scope.nowText = text;
});
$translate('SECONDS').then(function(text) {
$scope.secondsText = text;
});
$translate('MINUTES').then(function(text) {
$scope.minutesText = text;
});
$translate('HOURS').then(function(text) {
$scope.hoursText = text;
});
ChannelsService.getAllChannelsIds().then(function(channels){
var allConfigChannelsDefined = false;
if($scope.livePlotter && $scope.livePlotter.channels){
allConfigChannelsDefined = true;
$.each($scope.livePlotter.channels, function(index, channel){
if($.inArray(channel.id, channels) === -1){
console.log("ERROR : No channel with id '" + channel.id + "'");
allConfigChannelsDefined = false;
}
//console.log(channel.id + ", " + channel.label + ", " + allConfigChannelsDefined);
});
}
if(allConfigChannelsDefined){
//console.log("All Channels defined")
$scope.channels = $scope.livePlotter.channels;
}else{
var dummyChannels = [];
$.each(channels, function(index, channel){
dummyChannels.push({id : channel, label : channel, preselect : false});
});
$scope.channels = dummyChannels;
}
//console.log($scope.channels);
$.each($scope.channels, function(index, channel){
//console.log(channel.preselect);
if(channel.preselect === "true"){
$scope.selectedChannels.push(channel);
}
});
});
$scope.xFunction = function(){
return function(d){
return d.x;
};
};
$scope.yFunction = function(){
return function(d){
return d.y;
}
};
$scope.xAxisLabel = function(){
return $scope.xLabel;
};
$scope.yAxisLabel = function(){
return $scope.yLabel;
};
$scope.xAxisTickFormat = function () {
return function (d) {
if (d == 0) {
return $scope.nowText;
} else {
if ($scope.timePeriodUnit == "seconds") {
if (d % 1 === 0) {
var seconds = d;
} else {
var seconds = d.toFixed(2);
}
return seconds + " " + $scope.secondsText;
} else if ($scope.timePeriodUnit == "minutes") {
var minutes = parseInt(Math.abs(d)/60);
var seconds = Math.abs(d) % 60;
if (d % 1 !== 0) {
seconds = seconds.toFixed(2);
}
if (seconds.toString().length == 1) {
seconds = "0" + seconds;
}
if (minutes.toString().length == 1) {
minutes = "0" + minutes;
}
return "-" + minutes + ":" + seconds + " " + $scope.minutesText;
} else {
var minutes = parseInt(Math.abs(d)/60);
var seconds = Math.abs(d) % 60;
var hours = parseInt(minutes/60);
minutes = minutes % 60;
if (seconds.toString().length == 1) {
seconds = "0" + seconds;
}
if (minutes.toString().length == 1) {
minutes = "0" + minutes;
}
if (hours.toString().length == 1) {
hours = "0" + hours;
}
if (d % 1 !== 0) {
seconds = seconds.toFixed(2);
}
return "-" + hours + ":" + minutes + ":" + seconds + " " + $scope.hoursText;
}
}
}
};
$scope.yAxisTickFormat = function () {
return function (d) {
return d;
};
};
$scope.plotRange = function() {
if($scope.livePlotter && $scope.livePlotter.plotRange){
return $scope.livePlotter.plotRange;
}else{
return 0;
}
};
$scope.interval = "";
$scope.disabledPlot = function () {
return $scope.selectedChannels.length == 0; // || $scope.selectedChannels.length > 3;
};
$scope.plotData = function () {
// get max values to display in seconds
if ($scope.timePeriodUnit == "seconds") {
$scope.maxValuesToDisplay = 1000/$scope.refresh * $scope.timePeriod;
} else if ($scope.timePeriodUnit == "minutes") {
$scope.maxValuesToDisplay = 1000/$scope.refresh * $scope.timePeriod * 60;
} else {
$scope.maxValuesToDisplay = 1000/$scope.refresh * $scope.timePeriod * 60 * 60;
}
$scope.data = [];
$.each($scope.selectedChannels, function(i, channel) {
$scope.data.push({key: channel.label,
values : [],
color : channel.color,
type : channel.type});
});
$interval.cancel($scope.interval);
$scope.interval = $interval(function(){
var requests = [];
$.each($scope.selectedChannels, function(i, channel) {
requests.push(ChannelsService.getChannelCurrentValue(channel.id).then(function(response){
return {
key: channel.label,
value: response.value,
color : channel.color,
type : channel.type
};
}));
});
$q.all(requests).then(function(data){
$.each(data, function(i, channelData) {
$scope.data[i].key = channelData.key;
if (typeof(channelData.value) == "number") {
var y = ChannelsService.valuesDisplayPrecision(channelData.value, 0.001);
// rotate x values to the left
$.each($scope.data[i].values, function(j, newData) {
$scope.data[i].values[j].x = $scope.data[i].values[j].x - ($scope.refresh/1000);
});
// complete the values with null values
for (j = ($scope.maxValuesToDisplay-$scope.data[i].values.length); j > 0; j--) {
$scope.data[i].values.push({x: -(j * ($scope.refresh/1000)), y: ""});
}
// remove last value
if ($scope.data[i].values.length > $scope.maxValuesToDisplay) {
$scope.data[i].values.shift();
}
// push new value
$scope.data[i].values.push({x: 0, y: y});
}
});
});
}, $scope.refresh);
};
$scope.$on('$destroy', function () {
$interval.cancel($scope.interval);
});
};
LivePlotterController.$inject = injectParams;
angular.module('openmuc.dataplotter').controller('LivePlotterController', LivePlotterController);
})(); |
$(function() {
var controller = new ScrollMagic.Controller();
var aboutTween = TweenMax.staggerFromTo('#aboutme', 0.5,
{
y: 50,
x: -50,
opacity: 0
},
{
y: 0,
x: 0,
opacity: 1
},
0.2
);
var containerScene = new ScrollMagic.Scene({
triggerElement: '#part2',
offset: 100
})
.setTween(aboutTween)
.addIndicators()
.addTo(controller);
});
|
const mongoose = require('mongoose')
var elementSchema = new mongoose.Schema({
element: Array
})
var pubSchema = new mongoose.Schema({
id: String,
type: String,
authors: elementSchema,
title: String,
booktitle: String,
address: String,
year: String,
month: String,
doi: String
})
module.exports = mongoose.model('pub',pubSchema) |
$(document).ready(function()
{
if($(".formValidation").length>0)$(".formValidation").validate();
$('#username').keypress(function( e ) {if(e.which === 32)return false;});
$('#tick').hide();
$('#cross').hide();
$('.regno').hide();
$('#new').click(function() {
$('.regno').hide();
});
$('#renew').click(function() {
$('.regno').show();
});
$('.submit').click(function() {
$('#action').val('userRegistration');
$('#actionrenew').val('userRegistration');
});
$('.print').click(function() {
$('#action').val('preview');
$('#actionrenew').val('preview');
});
$("#designation").change(function(){
if($("#designation option:selected").val()=='1')
{
$('#other').append('<input type="text" name="designationother" id="designationother" class="textsmall"/>');
}
else
{
$('#other').remove();
}
});
if($("#membercategory option:selected").val()=='1')
{
$('#amount').val('5,61,800');
}
else if($("#membercategory option:selected").val()=='2')
{
$('#amount').val('14,045');
}
else if($("#membercategory option:selected").val()=='3')
{
$('#amount').val('39,326');
}
$("#membercategory").click(function(){
if($("#membercategory option:selected").val()=='1')
{
$('#amount').val('5,61,800');
}
else if($("#membercategory option:selected").val()=='2')
{
$('#amount').val('14,045');
}
else if($("#membercategory option:selected").val()=='3')
{
$('#amount').val('39,326');
}
});
//User login Jquery
if($(".loginValidation").length>0)$(".loginValidation").validate();
$('#logintype').click(function(){
$("#username").attr("disabled",false);
$("#password").attr("disabled",false);
});
$('#state').change(function(){
var state = $('#state').val();
jQuery.ajax({
type: "POST",
url: site_root_dir+"ajax"+file_extn,
data: 'action=fetchcity&state='+ state,
datatype:'json',
cache: false,
success: function(data)
{
$("#citybox").html(data);
}
});
//}
});
//
});
//add more text box
$(function() {
var scntDiv = $('#p_scents');
var i = $('#businessmainline span').size() + 1;
$('#add_more').live('click', function()
{
$('<span><p><label>Main Line of Business :<span>*</span></label><input type="text" class="required" id="businessmainline' + i +'" size="20" name="businessmainline[]" value="" placeholder="" /> <a href="#re" class="remScnt">Remove</a><p></span>').appendTo(scntDiv);
i++;
return false;
});
$('.remScnt').live('click', function()
{
$(this).parent().remove();
//return false;
});
});
//--------------------------
$(function() {
var scntDiv = $('#f_services');
var i = $('#feeserviceMore p').size() + 1;
var j=5;
$('#add_moreservice1').live('click', function() {
$('<p><label>'+j+'</label><input type="text" name="feeserviceMore' + i +'[]" id="feeservice' + i +'" class="textsmall required" value="" /><input type="text" name="feeserviceMore' + i +'[]" id="feeservice' + i +'" class="textsmall required" value="" /><input type="text" name="feeserviceMore' + i +'[]" id="feeservice' + i +'" class="textsmall required" value="" /><input type="text" name="feeserviceMore' + i +'[]" id="feeservice' + i +'" class="textsmall required" value="" /><a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
j++;
return false;
});
$('#remScnt').live('click', function() {
//alert($('#feeservice1 p').size());
if( i > 0 ) {
//alert( $(this).parents('p'));
$(this).parents('p').remove();
i--;
}
return false;
});
});
//---------------------------------------------------------
$(function() {
var scntDiv = $('#c_services');
var i = $('#countryservice p').size() + 1;
var j=5;
$('#add_moreservice2').live('click', function() {
$('<p><label>'+j+'</label><input type="text" name="countryserviceMore' + i +'[]" id="countryservice' + i +'" class="textsmall required" value="" /><input type="text" name="countryserviceMore' + i +'[]" id="countryservice' + i +'" class="textsmall required" value="" /><input type="text" name="countryserviceMore' + i +'[]" id="countryservice' + i +'" class="textsmall required" value="" /><input type="text" name="countryserviceMore' + i +'[]" id="countryservice' + i +'" class="textsmall required" value="" /><a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
j++;
return false;
});
$('#remScnt').live('click', function() {
//alert($('#feeservice1 p').size());
if( i > 0 ) {
//alert( $(this).parents('p'));
$(this).parents('p').remove();
i--;
}
return false;
});
});
//------------------------------------
//---------------------------------
$(document).ready(function(){
$('#username').keyup(username_check);
$('#username').change(username_check);
$("#attach1").change(function() {
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
case 'doc': case 'xls': case 'pdf': case 'docx' :
$("#error").hide();
break;
default:
$(this).val('');
// error message here
$("#error").hide();
$('#attach1').after('<div id="error" style="color:red; ">Accept formate only - doc/xls/pdf/docx</div>');
break;
}
});
$("#attach2").change(function() {
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
case 'doc': case 'xls': case 'pdf': case 'docx' :
$("#error").hide();
break;
default:
$(this).val('');
// error message here
$("#error").hide();
$('#attach1').after('<div id="error" style="color:red; ">Accept formate only - doc/xls/pdf/docx</div>');
break;
}
});
$("#attach3").change(function() {
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
case 'doc': case 'xls': case 'pdf':
$("#error").hide();
break;
default:
$(this).val('');
// error message here
$("#error").hide();
$('#attach1').after('<div id="error" style="color:red; ">Accept formate only - doc/xls/pdf/docx</div>');
break;
}
});
$('#registrationno').change(function()
{
var regno = $('#registrationno').val();
jQuery.ajax({
type: "POST",
url: site_root_dir+"ajax"+file_extn,
data: 'action=fetchReg®no='+ regno,
datatype:'json',
cache: false,
success: function(data){
//alert(data);
var jsonp = '['+data+']';
var obj = $.parseJSON(jsonp);
$.each(obj, function() {
if ((this['applicantID']==null))
{
$('#registrationno').focus();
$("#error").hide();
$('#registrationno').after('<div id="error" style="color:red; ">Please Enter valid RCMC No</div>');
$("#companyname").attr("disabled", true);
$("#companytype").attr("disabled", true);
$("#membercategory").attr("disabled", true);
$("#registrationyear").attr("disabled", true);
}
else if(this['membercategory']==1 && (this['applicantID']!=null))
{
alert("You have LifeTime Membership , No need to Renew");
location.href=admin_url;
}
else
{
$("#renewfinancialyear").attr("disabled",false);
$("#error").hide("fast");
$("#registrationno").attr("readonly",'readonly');
$("#username").attr("readonly",'readonly');
$("#financialyear").attr("readonly",'readonly');
$("#establismentdate").val(this['establismentdate']);
$("#companyname").val(this['companyname']);
$("[name=companytype]").filter("[value='"+this['companytype']+"']").attr("checked",true);
$("#membercategory").val(this['membercategory']);
$("#financialyear").val(this['financialyear']);
$("#officername").val(this['officername']);
$("#designation").val(this['designationID']);
$("#mobileno").val(this['mobileno']);
$("#email").val(this['email']);
$("#offtelephone").val(this['offtelephone']);
$("#username").val(this['username']);
$("#password").val(this['password']);
$("#confirmpassword").val(this['confirmpassword']);
$("#email2").val(this['email2']);
$("#companytype").val(this['companytype']);
$("#companyadress").val(this['companyadress']);
$("#country").val(this['country']);
$("#city").val(this['city']);
$("#state").val(this['state']);
$("#pincode").val(this['pincode']);
$("#website").val(this['website']);
$("#headofficeaddress").val(this['headofficeaddress']);
$("#contactno").val(this['contactno']);
$("#pin2").val(this['pin2']);
$("#state").val(this['state']);
$("#city").val(this['city']);
$("#branchname").val(this['branchname']);
$("#branchaddress").val(this['branchaddress']);
$("#branchcontact").val(this['branchcontact']);
$("#branchpin").val(this['branchpin']);
$("#attach1").val(this['attach1']);
$("#unitofficename").val(this['unitofficename']);
$("#unitofficeaddress").val(this['unitofficeaddress']);
$("#attach2").val(this['attach2']);
$("#iecode").val(this['iecode']);
$("#iecissuedate").val(this['iecissuedate']);
$("#iecestablishment").val(this['iecestablishment']);
$("#ieauthority").val(this['ieauthority']);
$("#iepanno").val(this['iepanno']);
$("#serviceexportercategory").val(this['serviceexportercategory']);
$("#othercategory").val(this['othercategory']);
$("#membercategory").val(this['membercategory']);
$("#exporthousetype").val(this['exporthousetype']);
$("#exporthousecertificate").val(this['exporthousecertificate']);
$("#certificatevalid").val(this['certificatevalid']);
$("#detailtype").val(this['detailtype']);
$("#detailname").val(this['detailname']);
$("#detailfather").val(this['detailfather']);
$("#detailaddress").val(this['detailaddress']);
$("#detailnumber").val(this['detailnumber']);
$("#detailattachment").val(this['detailattachment']);
$("#businessmainline").val(this['businessmainline']);
$("#registrationyear").val(this['registrationyear']);
$("[name=payment]").filter("[value='"+this['payment']+"']").attr("checked",true);
jQuery.ajax({
type: "POST",
url: site_root_dir+"ajax"+file_extn,
data: 'action=fetchexpyear®no='+ regno,
datatype:'json',
cache: false,
success: function(data){
//alert(data);
$("#renewyear").html(data) ;
$('#renewfinancialyear').change(function()
{
var renewyr = $('#renewfinancialyear').val();
var regno = $('#registrationno').val();
jQuery.ajax({
type: "POST",
url: site_root_dir+"ajax"+file_extn,
data: 'action=fetchRenew&val='+ renewyr+'®no='+ regno,
datatype:'json',
cache: false,
success: function(data){
$("#amount").val(data);}
//}
});
});
}
});
// $('#renewfinancialyear').find('option:eq(2)').attr('disabled', true);
}
});
}
});
});
});
function username_check(){
var username = $('#username').val();
if(username !=""&& username.length >=5)
{
jQuery.ajax({
type: "POST",
url: site_root_dir+"ajax"+file_extn,
data: 'action=checkAvail&username='+ username,
cache: false,
success: function(response){
if(response >= 1){
$('#username').css('border', '1px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
}else{
$('#username').css('border', '1px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}}
});
}}
|
var utils = require('utils')
var PublicKey = require(__dirname+'/public_key')
var Message = require(__dirname+'/message')
var Signature = require(__dirname+'/signature')
class Verifier {
constructor(publicKey) {
utils.assert(publicKey instanceof PublicKey)
this.publicKey = publicKey
}
verify(message, signature) {
utils.assert(message instanceof Message)
utils.assert(signature instanceof Signature)
}
}
module.exports = Verifier
|
// The menu isn't perfect, but I spent way too long on it, and it works good enough
"strict mode";
const openMenuContainer = document.getElementById("open-menu-container");
var menu = {
async open() {
if (await this._transition(true)) this.pushDepth();
},
async close() {
if (Modal.openModal) return;
this.forceClosed = true;
if (await this._transition(false)) {
try {
const depth = history.state && history.state.menuDepth || 0;
if (depth) history.go(-depth);
history.replaceState(this.clearedState, "");
if (currentPage !== location.href) throw new Error("Menu cannot be closed if it was never opened"); // This will probably never run, as it only runs after use is redirected
menu._depth = -1;
menu.depth = 1;
}
catch (err) {
handle(err);
}
}
await setImmediateAsync(() => {
this.forceClosed = false;
});
},
_transition (forwards) {
if (this.isOpen === forwards) return Promise.resolve(false);
else return new Promise(resolve => {
menu.element.addEventListener("transitionend", () => resolve());
if (!this.isOpen && this.depth !== 1) handle(new Error("The error should never be thrown: The menu is closed but not at the top level"));
document[(forwards ? "add" : "remove") + "EventListener"]("click", menu._closeOnClickOut);
this.element.classList[forwards ? "add" : "remove"]("open");
})
.then(() => true);
},
toggle () {
if (this.isOpen) this.close();
else this.open();
},
initSubMenus (subMenu = this.listElement) {
for (let li of subMenu.children) {
const liSubMenu = li.getElementsByTagName("ul")[0];
if (li.getElementsByTagName("ul").length) {
li.classList.add("menu");
li.addEventListener("click", event => {
event.stopPropagation();
menu.depth++;
this._invisablify();
liSubMenu.classList.add("sub-open");
menu.pushDepth();
});
if (liSubMenu) this.initSubMenus(liSubMenu);
}
else {
li.addEventListener("click", event => {
event.stopPropagation();
});
}
}
},
pushDepth () {
const state = this.clearedState;
if (menu.open) state.menuDepth = menu.depth;
history.pushState(state, "");
},
async updateMenuState () {
if (this.forceClosed && history.state && history.state.menuDepth) history.replaceState(this.clearedState, "");
if (history.state && history.state.menuDepth) {
if (menu.depth !== (history.state && history.state.menuDepth)) menu.depth = history.state.menuDepth;
await menu.open();
}
else await menu.close();
},
get clearedState () {
const state = Object.apply({}, history.state);
delete state.menuDepth;
return state;
},
_closeOnClickOut (event) {
if (!Array.from(document.getElementsByClassName("modal")).concat(menu.element, Modal.overlay).some(e => e.contains(event.target))) menu.close();
},
element: document.getElementsByTagName("nav")[0],
get listElement () {
return this.element.getElementsByTagName("ul")[0];
},
listContainer: document.getElementById("lists"),
_depth: 1,
get depth () {
return this._depth;
},
set depth (value) {
const prev = this.depth;
if (value === this.depth) return;
if (value < 1) handle(new RangeError(`Menu depth cannot be set to ${value}, must be 1 or greater`));
this._depth = value;
menu.listContainer.style.right = (menu.depth - 1) * menu.listContainer.clientWidth + "px";
},
_invisablify () {
const uls = Array.from(document.querySelectorAll("#lists > ul" + " > li > ul".repeat(this.depth - 1) + ".sub-open"));
if (this.depth === 2 && settings.classList.contains("sub-open")) uls.push(settings);
for (let ul of uls) ul.classList.remove("sub-open");
},
get isOpen () {
return this.element.classList.contains("open");
},
forceClosed: false
};
for (let e in menu) {
if (typeof menu[e] === "function") menu[e] = menu[e].bind(menu);
}
menu.initSubMenus();
openMenuContainer.addEventListener("click", event => {
event.stopPropagation();
menu.open();
});
document.getElementById("close-menu").parentNode.addEventListener("click", history.back.bind(history)); |
import Example from './example'
export {Example}
|
let Direction = {
right:"right",
left:"left",
up:"up",
down:"down"
};
let Color = {
White: "White",
Black: "Black"
}
class Game{
constructor(){
this.board = new Board();
this.players = [];
this.players[0] = new Player(Color.White);
this.players[1] = new Player(Color.Black);
this.instance = null;
}
getInstance(){
if(this.instance === null){
this.instance = new Game();
}
return this.instance;
}
getBoard(){
return this.board;
}
}
class Board{
constructor(){
this.board = [];
}
//Initialize center black and white pieces.
initialize(){}
//Attempts to place a piece of color color at (row,column) Return true if we ere succesfull.
placeColor(){}
//Flips pieces starting at (row column) and proceeding in direction d
flipSection(){}
getScoreForColor(){}
//Updates the board with additional newPieces pieces of color newColor. Decrease score of opposite color
updateScore(){}
}
class Piece{
constructor(color){
this.color = color;
}
flip(){
this.color = this.color===Color.White ? Color.Black : Color.White;
}
getColor(){
return this.color;
}
}
class Player{
constructor(color){
this.color = color;
}
getScore(){}
playPiece(row,column){
return Game.getInstance().getBoard().placeColor(row,column);
}
getColor(){
return this.color;
}
}
|
import React, { Component } from 'react';
function Header() {
return (
<div>
<div id="middle" className="header">
<h2 className="title">SHOP SMARTER</h2>
</div>
<div className="header">
<h3 className="sub">Select Your Favorite Stores To Get Started</h3>
</div>
</div>
);
}
export default Header;
|
function upper(strings,...values) {
return strings.map((el, i)=>{
return el + values[i] ? values[i].toUpperCase() : ''
}).join('');
}
var name = "kyle",
twitter = "getify",
classname = "es6 workshop";
console.log(
upper`Hello ${name} (@${twitter}), welcome to the ${classname}!` ===
"Hello KYLE (@GETIFY), welcome to the ES6 WORKSHOP!"
);
function getPromise(){
return new Promise(( res, rej )=>{
setTimeout(()=>{
// res({ name : 'Seba' });
rej({ name : 'Seba' });
},
2000
)
});
}
const obj = {
[a]:'jjj'
}
getPromise()
.then( data => data );
.then( data => console.log('fsdfsdfsd',data) )
.catch( err => console.log('error', err) );
function* createId(){
yield* ['Seba','Kamil'];
}
const moja = createId();
console.log(moja.next());
console.log(moja.next());
console.log(moja.next());
//https://app.pluralsight.com/library/courses/rapid-es6-training/table-of-contents
//https://app.pluralsight.com/library/courses/nodejs-advanced/table-of-contents
//https://app.pluralsight.com/library/courses/javascript-development-environment/table-of-contents
|
angular.module('expensesController',[])
.controller('expensesController',['expensesService','$stateParams','$state',function(expensesService,$stateParams,$state){
var expensesScope = this;
expensesScope.saveExpenses = function(){
var formdata = new FormData();
formdata.append('expenseName', expensesScope.expenseName);
formdata.append('expenseAmount', expensesScope.expenseAmount);
formdata.append('file', expensesScope.expenseFile);
var success = function(response){
console.log(response)
expensesScope.successmsg = true
expensesScope.errormsg = false
}
var failure = function(response){
console.log(response)
expensesScope.successmsg = false
expensesScope.errormsg = true
}
expensesService.addexpenses(formdata,success,failure)
}
expensesScope.getDetails = function(){
var success = function(response){
console.log(response.data.data)
expensesScope.details = response.data.data
}
var failure = function(response){
console.log(response)
}
expensesService.listExpenses(success,failure)
}
// Delete user
expensesScope.deleteExpense = function(id, $index){
if (confirm('Are you sure?')){
var success = function(response){
expensesScope.users.splice($index,1)
}
var failure = function(response){
console.log(response)
console.log('fail')
}
expensesService.deleteExpenses(id,success,failure)
}
}
//
//
// Change State with id
expensesScope.changeState = function(expenseId){
$state.go('editexpenses',{
'obj': expenseId
})
}
// get user values to update
expensesScope.getDatatoUpdate= function(){
id = $stateParams.obj
var success = function(response){
console.log('success')
expensesScope.data = response.data.data[0]
console.log(expensesScope.data)
expensesScope.data.upload = '/static/dist/expensedoc/'+ expensesScope.data.uploadImage
}
var failure = function(response){
console.log(response)
console.log('failure')
}
expensesService.geteditdata(id, success, failure)
}
// Update User
expensesScope.saveUpdatedUser = function(){
dataobj = {
"id" : expensesScope.data.expenseId,
"expenseName" : expensesScope.data.expenseName,
"uploadImage" : expensesScope.data.uploadImage,
"empensePrice" : expensesScope.data.empensePrice,
}
var success = function(response){
console.log(expensesScope.data)
expensesScope.successmsg = true
expensesScope.errormsg = false
}
var failure = function(response){
console.log(response)
console.log('failure')
expensesScope.successmsg = false
expensesScope.errormsg = true
}
expensesService.updatedExpense(dataobj, success, failure)
}
return expensesScope;
}])
.directive('fileModel',['$parse', function($parse){
return{
restrict: 'A',
link: function(scope,element,attrs){
var model=$parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]); |
let data={
"status": "ok",
"totalResults": 13304,
"articles": [
{
"source": {
"id": null,
"name": "Raw Story"
},
"author": "Agence France-Presse",
"title": "US regulators probe 'spontaneous' fire of top-end Tesla",
"description": "US transportation safety regulators said Friday they are probing an incident in which a brand-new Tesla apparently burst into flames, temporarily trapping the driver, with firefighters needing more than two hours to extinguish the blaze.The cause of the fire …",
"url": "https://www.rawstory.com/us-regulators-probe-spontaneous-fire-of-top-end-tesla-2653646542/",
"urlToImage": "https://www.rawstory.com/media-library/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpbWFnZSI6Imh0dHBzOi8vYXNzZXRzLnJibC5tcy8yNjg5MDkyOS9vcmlnaW4ucG5nIiwiZXhwaXJlc19hdCI6MTYyOTc4Njc1M30.amHAgsWTITfJwWtO895GZa-dlIMLEL82o5bHYatYUYA/image.png?width=1200&coordinates=0%2C62%2C0%2C62&height=600",
"publishedAt": "2021-07-03T11:32:10Z",
"content": "\"There was no state cover-up,\" Genevieve Darrieusseq, junior defense minister, told AFP in a brief comment on the sidelines of the event, where she has ruled out any official apology from France.\r\nIn… [+3507 chars]"
},
{
"source": {
"id": null,
"name": "Golem.de"
},
"author": null,
"title": "Elon Musk: Tesla Cybertruck bekommt Krabbengang",
"description": "Der Tesla Cybertruck wird eine Vierrad-Lenkung erhalten, die es dem Fahrzeug erlauben soll, seitwärts zu fahren. Der Krabbengang wurde von General Motors abgeguckt. (Tesla, Elektroauto)",
"url": "https://www.golem.de/sonstiges/zustimmung/auswahl.html?from=https%3A%2F%2Fwww.golem.de%2Fnews%2Felon-musk-tesla-cybertruck-bekommt-krabbengang-2107-157853.html&referer=https%3A%2F%2Ft.co%2Fd047cc6c48",
"urlToImage": null,
"publishedAt": "2021-07-03T11:15:00Z",
"content": "Besuchen Sie Golem.de wie gewohnt mit Werbung und Tracking, indem Sie der Nutzung aller Cookies zustimmen.\r\n Details zum Tracking finden Sie im Privacy Center.\r\nSkript wurde nicht geladen. Informatio… [+575 chars]"
},
{
"source": {
"id": null,
"name": "Fox46.com"
},
"author": "iSeeCars, via Nexstar Media Wire",
"title": "16 cars that actually cost more used than new",
"description": "The price gap between new and slightly used cars has drastically narrowed, and some used cars have even become more expensive than their new versions.",
"url": "https://www.fox46.com/news/16-cars-that-actually-cost-more-used-than-new/",
"urlToImage": "https://www.fox46.com/wp-content/uploads/sites/109/2021/07/Kia-Telluride.jpg?w=1280",
"publishedAt": "2021-07-03T11:03:36Z",
"content": "(iSeeCars) – The global microchip shortage has restricted new car supply, which has led to a record surge in used car prices. According to iSeeCars.coms latest analysis of over 470,000 new and lightl… [+8020 chars]"
},
{
"source": {
"id": null,
"name": "Motley Fool"
},
"author": "newsfeedback@fool.com (Lou Whiteman)",
"title": "Why NIO Stock Accelerated in June",
"description": "Momentum is building for the Chinese electric vehicle maker.",
"url": "https://www.fool.com/investing/2021/07/03/why-nio-stock-accelerated-in-june/",
"urlToImage": "https://g.foolcdn.com/editorial/images/632622/nio-fleet-source-nio.jpg",
"publishedAt": "2021-07-03T11:00:00Z",
"content": "What happened\r\nChinese electric vehicle manufacturer NIO(NYSE:NIO) was in the fast lane in June, climbing 37.8% for the month, according to data provided by S&P Global Market Intelligence. The co… [+1885 chars]"
},
{
"source": {
"id": "business-insider",
"name": "Business Insider"
},
"author": "Shalini Nagarajan",
"title": "Elon Musk is losing his power over the crypto community after his latest tweets failed to boost dogecoin or bitcoin",
"description": "Summary List PlacementThe \"Elon Musk Effect,\" a phenomenon that roiled the crypto ecosystem this year, when every little tweet from the Tesla boss could send token prices skyrocketing or plunging, seems to be losing its luster.\nThe billionaire has been a key …",
"url": "https://markets.businessinsider.com/news/stocks/elon-musk-tweets-dogecoin-bitcoin-influence-over-crypto-community-cryptocurrencies-2021-7",
"urlToImage": "https://images2.markets.businessinsider.com/60df0cad4a93e200191299c4?format=jpeg",
"publishedAt": "2021-07-03T11:00:00Z",
"content": "Win McNamee/Getty Images/Pavlo Gonchar/SOPA Images/LightRocket via Getty Images\r\nThe \"Elon Musk Effect,\" a phenomenon that roiled the crypto ecosystem this year, when every little tweet from the Tesl… [+3107 chars]"
},
{
"source": {
"id": null,
"name": "Abertoatedemadrugada.com"
},
"author": "Carlos Martins",
"title": "Antena Starlink em automóvel dá multa",
"description": "Um norte-americano apanhou uma\nmulta ao ser apanhado a circular com uma antena Starlink no capot.",
"url": "https://abertoatedemadrugada.com/2021/07/antena-starlink-em-automovel-da-multa.html",
"urlToImage": "https://1.bp.blogspot.com/-OMJsnZ6U-3c/YN_3cP01tbI/AAAAAAAGPKE/9TJJMC914ogpxTXdr3YSApQbbBwns0tIgCLcBGAsYHQ/w1200-h630-p-k-no-nu/priusstarlink.jpg",
"publishedAt": "2021-07-03T11:00:00Z",
"content": "Apesar de Elon Musk ter dito que o serviço Starlink não era adequado para automóveis devido às dimensões da antena, isso não impediu um norte-americano de a colocar no seu automóvel, valendo-lhe uma … [+1470 chars]"
},
{
"source": {
"id": null,
"name": "Motley Fool"
},
"author": "newsfeedback@fool.com (Lou Whiteman, John Rosevear, and Rich Duprey)",
"title": "Tesla's Under Pressure in China. Here Are 3 EV Companies That Can Capitalize on This",
"description": "Competition is heating up. Here's who stands to benefit.",
"url": "https://www.fool.com/investing/2021/07/03/teslas-under-pressure-in-china-here-are-three-ev-c/",
"urlToImage": "https://g.foolcdn.com/editorial/images/632367/electric-vehicle-parking-spot-source-getty.jpg",
"publishedAt": "2021-07-03T11:00:00Z",
"content": "It's been a rough couple of months for Tesla(NASDAQ:TSLA) as the electric-vehicle (EV) company tries to make inroads in the all-important Chinese auto market.\r\nA Chinese regulator announced last week… [+6390 chars]"
},
{
"source": {
"id": null,
"name": "Businessinsider.com.pl"
},
"author": "Avery Hartmans",
"title": "Elon Musk skończył 50 lat. Oto jak budował swoje firmy i stał się jednym z najbogatszych ludzi świata",
"description": "Elon Musk w poniedziałek obchodził 50. urodziny. Oto życie prezesa Tesli i SpaceX, od szykanowanego ucznia po jednego z najbardziej utalentowanych i zarazem najbardziej kontrowersyjnych osób w świecie technologii.",
"url": "https://businessinsider.com.pl/technologie/nowe-technologie/elon-musk-skonczyl-50-lat-oto-jak-budowal-swoje-firmy-i-stal-sie-jednym-z/zr340w3",
"urlToImage": "https://ocdn.eu/pulscms-transforms/1/q94k9kpTURBXy8xNDc2ZGJiMTQwN2NlNzc0Y2Y4NDYzY2YxNmNiMGE5Mi5wbmeSlQMAAM0EsM0CdJMFzQNXzQHCgaExAQ",
"publishedAt": "2021-07-03T10:50:52Z",
"content": "Elon Musk w poniedziaek obchodzi 50. urodziny. Oto ycie prezesa Tesli i SpaceX, od szykanowanego ucznia po jednego z najbardziej utalentowanych i zarazem najbardziej kontrowersyjnych osób w wiecie te… [+17572 chars]"
},
{
"source": {
"id": null,
"name": "Clubic"
},
"author": "Nerces",
"title": "Un exemplaire de la Tesla Model S Plaid prend feu dans d'étranges circonstances",
"description": "Un accident survenu dans la nuit du 29 juin non loin de Philadelphie et impliquant le tout récent modèle Plaid signé Tesla.",
"url": "https://www.clubic.com/pro/entreprises/tesla/actualite-376820-un-exemplaire-de-la-tesla-model-s-plaid-prend-feu-dans-d-etranges-circonstances.html",
"urlToImage": "https://pic.clubic.com/v1/images/1898268/raw?width=900&height=600&fit=max&hash=28838704f141eb47498d5c3142306326e099e01d",
"publishedAt": "2021-07-03T10:43:00Z",
"content": "Un accident survenu dans la nuit du 29 juin non loin de Philadelphie et impliquant le tout récent modèle Plaid signé Tesla.\r\nÀ Haverford, dans la banlieue de Philadlephie, Pennslyvanie, une toute réc… [+1763 chars]"
},
{
"source": {
"id": null,
"name": "Freerepublic.com"
},
"author": "Townhall.com",
"title": "Real Threats to Planet and People",
"description": "Environmental activism was already nasty and lethal when I wrote Eco-Imperialism: Green Power – Black Death18 years ago. It’s gotten steadily worse since then, especially with hysteria about the “looming manmade climate apocalypse” driving ever more extreme d…",
"url": "https://freerepublic.com/focus/f-news/3973038/posts",
"urlToImage": null,
"publishedAt": "2021-07-03T10:36:56Z",
"content": "Skip to comments.\r\nReal Threats to Planet and PeopleTownhall.com ^\r\n | July 3, 2021\r\n | Paul Driessen\r\nPosted on 07/03/2021 3:36:56 AM PDT by Kaslin\r\nEnvironmental activism was already nasty and leth… [+9152 chars]"
},
{
"source": {
"id": null,
"name": "Forbes"
},
"author": "Sergei Klebnikov, Forbes Staff, \n Sergei Klebnikov, Forbes Staff\n https://www.forbes.com/sites/sergeiklebnikov/",
"title": "Where Elon Musk Lives Since He Pledged To Ditch ‘Almost All Physical Possessions’",
"description": "After promising to sell nearly everything he owned last year including six mansions in California, Tesla’s billionaire CEO has taken up residence in a studio-apartment sized rental – here’s what it looks like inside and out.",
"url": "https://www.forbes.com/sites/sergeiklebnikov/2021/07/03/where-elon-musk-lives-since-he-pledged-to-ditch-almost-all-physical-possessions/",
"urlToImage": "https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F60df2aafbd04bc615f446fdb%2F0x0.jpg",
"publishedAt": "2021-07-03T10:30:00Z",
"content": "GETTY IMAGES, ILLUSTRATION BY FORBES\r\nAfter promising to sell nearly everything he owned last year including six mansions in California, Teslas billionaire CEO has taken up residence in a studio-apar… [+4580 chars]"
},
{
"source": {
"id": null,
"name": "Forbes"
},
"author": "Alistair Charlton, Senior Contributor, \n Alistair Charlton, Senior Contributor\n https://www.forbes.com/sites/alistaircharlton/",
"title": "Everrati Signature Review: This 964-Generation Porsche 911 is Electric",
"description": "Everrati is a British firm that takes iconic sports cars and swaps out their engine for an electric motor.",
"url": "https://www.forbes.com/sites/alistaircharlton/2021/07/03/everrati-signature-review-this-964-generation-porsche-911-is-electric/",
"urlToImage": "https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F60df17779daf200892aa4e5b%2F0x0.jpg",
"publishedAt": "2021-07-03T10:28:33Z",
"content": "The car is powered by a Tesla motor and brand new battery, with an output of 500 horsepower\r\nEverrati\r\nYes, this is an electric 964-generation Porsche 911. And the fact of the matter is, that sentenc… [+6840 chars]"
},
{
"source": {
"id": null,
"name": "Slashdot.org"
},
"author": "feedfeeder",
"title": "Tech Titans Fueling Market Rally; These Three Are In Buy Range - Investor's Business Daily",
"description": "Tech Titans Fueling Market Rally; These Three Are In Buy RangeInvestor's Business Daily The S&P 500 just hit its seventh straight record highCNN 7 Strong Stocks to Buy for July 2021InvestorPlace Dow Jones Rallies As Apple, Microsoft Lead; AMC Stock Dives; Tes…",
"url": "https://slashdot.org/firehose.pl?op=view&id=148662458",
"urlToImage": null,
"publishedAt": "2021-07-03T10:13:11Z",
"content": "The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way."
},
{
"source": {
"id": null,
"name": "Naked-science.ru"
},
"author": "Илья Ведмеденко",
"title": "Tesla Model S Plaid «самовоспламенилась», когда внутри был водитель",
"description": "Новая версия Model S внезапно загорелась, когда внутри находился человек. Он не пострадал.",
"url": "https://naked-science.ru/article/hi-tech/tesla-model-s-plaid-samovosplamenilas-kogda-vnutri-byl-voditel",
"urlToImage": "https://naked-science.ru/wp-content/uploads/2021/07/image3.jpg",
"publishedAt": "2021-07-03T10:11:53Z",
"content": "Model S , . . ( ). Tesla Model S Plaid : - .\r\n , «». « , Tesla Model S Plaid, 250. . . Tesla, », . , .\r\n Tesla Model S Plaid / ©meiselasb\r\n, Tesla , , - . « ( !) , , Tesla . ? », Twitter 2019-.\r\n Tes… [+191 chars]"
},
{
"source": {
"id": null,
"name": "Caradisiac.com"
},
"author": "Caradisiac.com",
"title": "Le Top 100 des ventes de voitures au premier semestre 2021",
"description": "Les surprises sont nombreuses dans le classement des voitures les plus vendues en 2021.",
"url": "https://www.caradisiac.com/le-top-100-des-ventes-au-premier-semestre-2021-190855.htm",
"urlToImage": "https://images.caradisiac.com/images/0/8/5/5/190855/S1-le-top-100-des-ventes-au-premier-semestre-2021-682717.jpg",
"publishedAt": "2021-07-03T10:11:01Z",
"content": "La 208 championne\r\nDéjà reine des ventes en 2020, la Peugeot 208 avait pris le large en début d'année face à sa meilleure ennemie, la Clio. Cette dernière a été ralentie par l'absence momentanée de m… [+2521 chars]"
},
{
"source": {
"id": "lenta",
"name": "Lenta"
},
"author": "Владимир Седов",
"title": "Бывший американский военный сравнил армию России с «Запорожцем»",
"description": "Бывший американский военный — капитан первого ранга ВМС США в отставке Гарри Табах сравнил армию России с «Запорожцем», а силы НАТО с Tesla, мотивируя тем, что у России нет высоких технологий и профессионализма. Такое мнение он высказал в прямом эфире украинс…",
"url": "https://lenta.ru/news/2021/07/03/zporojec/",
"urlToImage": "https://icdn.lenta.ru/images/2021/07/03/12/20210703124434843/share_1bf4b1436c2053a622209160554e34e1.jpg",
"publishedAt": "2021-07-03T10:05:47Z",
"content": "«», Tesla. , 3 , «».\r\n , « », , . , , , . , .\r\n Defender, , , , « », - . , - , , .\r\n , , 2014 . , «», ."
},
{
"source": {
"id": null,
"name": "Komputerswiat.pl"
},
"author": "Dawid Długosz",
"title": "Tesla pobiła rekord. W jeden kwartał dostarczyła ponad 200 tys. aut",
"description": "Tesla poprzedni kwartał z pewnością może zaliczyć do bardzo udanych. Firma pobiła ustanowiony wcześniej rekord. W okresie od początku kwietnia do końca czerwca dostarczyła na rynek ponad 200 tys. samochodów. Pomimo wielu wyzwań, z którymi Tesla spotkała się n…",
"url": "https://www.komputerswiat.pl/moto/tesla-pobila-rekord-w-jeden-kwartal-dostarczyla-ponad-200-tys-aut/d2nq3mn",
"urlToImage": "https://ocdn.eu/pulscms-transforms/1/QwDktkpTURBXy82ZGEyOWVkMTU0NzIyOGM5Mjg4ZTgzNjVmODNjZmJhNC5qcGeSlQMAAM0FAM0C0JMFzQSwzQJ2",
"publishedAt": "2021-07-03T10:01:00Z",
"content": "Tesla sprzedaje coraz wicej samochodów, co byo doskonale wida po zeszym roku. Teraz firma ustanowia nowy rekord. W drugim kwartale producent dostarczy na rynek ponad 200 tys. samochodów. W ten sposób… [+590 chars]"
},
{
"source": {
"id": null,
"name": "Forbes"
},
"author": "James Morris, Contributor, \n James Morris, Contributor\n https://www.forbes.com/sites/jamesmorris/",
"title": "Can Tesla Really Do Without Radar For Full Self-Driving?",
"description": "Tesla has removed the radar from its Model 3 and Y. Can it really deliver on the promise of self-driving cars with just cameras?",
"url": "https://www.forbes.com/sites/jamesmorris/2021/07/03/can-tesla-really-do-without-radar-for-full-self-driving/",
"urlToImage": "https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F60df74701b3d17f18787c1b5%2F0x0.jpg%3FcropX1%3D0%26cropX2%3D3450%26cropY1%3D173%26cropY2%3D2114",
"publishedAt": "2021-07-03T10:00:00Z",
"content": "Just over a month ago, Tesla caused a stir by announcing that it was dropping the use of radar for its Autopilot and Full Self-Driving features in the Model 3 and Y. This came on top of the companys … [+5055 chars]"
},
{
"source": {
"id": null,
"name": "BFMTV"
},
"author": null,
"title": "Avec sa voiture volante, cette startup slovaque fait de la science fiction une réalité",
"description": "Une startup slovaque vient de réussir les tests de l'AirCar. Cette voiture volante a décollé pour atteindre une altitude de 2500 mètres pendant 35 minutes avant d'atterrir et prendre la route.",
"url": "https://www.bfmtv.com/economie/entreprises/avec-sa-voiture-volante-cette-startup-slovaque-fait-de-la-science-fiction-une-realite_AV-202107030095.html",
"urlToImage": "https://images.bfmtv.com/rzjFrZuSWX78Xm_qzpmI03ClDec=/0x106:2048x1258/2048x0/images/L-AirCar-de-Klein-Vision-est-un-avion-deux-places-qui-se-transforme-en-voiture-en-quelques-secondes-1060074.jpg",
"publishedAt": "2021-07-03T09:43:46Z",
"content": "Une startup slovaque vient de réussir les tests de l'AirCar. Cette voiture volante a décollé pour atteindre une altitude de 2500 mètres pendant 35 minutes avant d'atterrir et prendre la route.\r\nLa vo… [+2313 chars]"
},
{
"source": {
"id": null,
"name": "HYPEBEAST"
},
"author": "info@hypebeast.com (HYPEBEAST), HYPEBEAST",
"title": "Tesla Delivered Record 201,250 Electric Vehicles in One Quarter",
"description": "Tesla has done it again, topping its own delivery record and reaching a significant record-breaking milestone for the company. The electric vehicles carmaker has delivered an all-time high of 201,250 cars in Q2 of 2021, the most it has ever done in just one q…",
"url": "https://hypebeast.com/2021/7/tesla-breaks-own-record-delivered-200k-cars-in-one-quarter",
"urlToImage": "https://image-cdn.hypb.st/https%3A%2F%2Fhypebeast.com%2Fimage%2F2021%2F07%2Ftesla-breaks-own-record-delivered-200k-cars-in-one-quarter-tw.jpg?w=960&cbr=1&q=90&fit=max",
"publishedAt": "2021-07-03T09:38:23Z",
"content": "Tesla\r\n has done it again, topping its own delivery record and reaching a significant record-breaking milestone for the company. \r\nThe electric vehicles carmaker has delivered an all-time high of 201… [+1230 chars]"
}
]
} |
import React from 'react'
import { Button, Input, Select, Card } from 'antd'
import { connect } from 'react-redux'
import { Container, CenteredRow } from './GeneralComponents'
import styled from 'styled-components'
import { handleEditPost, fetchPost } from '../actions/posts'
import { defer } from 'lodash'
const Option = Select.Option
const FormCard = styled(Card)`
background-color: #FEFEFE;
margin: 24px;
width: 50%;
box-shadow: 0 0 10px 2px rgba(0,0,0,0.18) !important;
`
const ErrorMessage = styled.h3`
color: red;
font-weight: bold;
`
class EditPostForm extends React.Component {
state = {
title: '',
body: '',
error: ''
}
componentDidMount() {
const { fetchPostContent, match } = this.props
fetchPostContent(match.params.id)
}
componentWillReceiveProps() {
defer(() => {
if (this.props.post) {
const { title, body } = this.props.post
this.setState({
title,
body
}, () => {
this.forceUpdate()
})
}
})
}
handleBodyChange = (e) => {
this.setState({
body: e.target.value
})
}
handleTitleChange = (e) => {
this.setState({
title: e.target.value
})
}
handlePostEditSubmit = () => {
const { post, editPostContent } = this.props
const { title, body } = this.state
if (!body || !title) {
this.setState({
error: 'Please, fill all fields.'
})
} else {
const postContent = {
body,
title
}
editPostContent(post, postContent)
this.props.history.push(`/${post.category}/${post.id}`)
}
}
render() {
const { post, categories } = this.props
const { error } = this.state
return (
'title' in post && (
<Container>
<FormCard>
<h2>Edit Post</h2>
<ErrorMessage>{error && `* ${error}`}</ErrorMessage>
<h4>Title</h4>
<CenteredRow>
<Input defaultValue={post.title} placeholder="Type post's title..." onChange={this.handleTitleChange} />
</CenteredRow>
<h4>Category</h4>
<CenteredRow>
<Select
style={{ width: '100%' }}
disabled={true}
defaultValue={post.category}
>
{categories.map((c) => (
<Option key={c.name} value={c.name}>{c.name}</Option>
))}
</Select>
</CenteredRow>
<h4>Author</h4>
<CenteredRow>
<Input disabled={true} placeholder="Type author's username..." defaultValue={post.author} />
</CenteredRow>
<h4>Content</h4>
<CenteredRow>
<Input.TextArea defaultValue={post.body} placeholder="Type post content..." onChange={this.handleBodyChange} />
</CenteredRow>
<CenteredRow>
<Button type="primary" icon="edit" onClick={this.handlePostEditSubmit}>Save</Button>
</CenteredRow>
</FormCard>
</Container>
)
)
}
}
const mapStateToProps = ({ post, categories }) => {
return {
post,
categories
}
}
const mapDispatchToProps = (dispatch) => ({
fetchPostContent: (id) => {
dispatch(fetchPost(id))
},
editPostContent: (post, postContent) => {
const { id, title, body} = post
dispatch(handleEditPost(id, postContent, {title, body}))
}
});
export default connect(mapStateToProps, mapDispatchToProps)(EditPostForm) |
const initSetupCurrent = [
{
id: "empty-deck",
type: "decks",
slug: "none",
view: "empty",
title: "Pick a deck",
},
{
id: "empty-trucks",
type: "trucks",
slug: "none",
view: "empty",
title: "Pick a truck",
},
{
id: "empty-wheels",
type: "wheels",
slug: "none",
view: "empty",
title: "Pick your wheels",
},
];
const initItem = {
view: "simple",
type: "",
id: "",
custom: "",
title: "",
slug: "",
location: "",
};
export const state = () => ({
title: "Longboard Setup",
setupCurrent: [...initSetupCurrent],
itemCurrent: { ...initItem },
setupNotEdited: true,
showShareModel: false,
});
export const mutations = {
//------------------------------------------------------//
// Add a item 🔨 to the setup 🧰 or change one
//------------------------------------------------------//
setupAdd(state, payload) {
const changeItemCheck = state.setupCurrent.findIndex(
item => item.type == payload.type
);
if (changeItemCheck >= 0) {
state.setupCurrent.splice(changeItemCheck, 1, payload);
} else {
state.setupCurrent.push(payload);
}
state.setupNotEdited = false;
},
// END Add a item 🔨 to the setup 🧰 or change one
// END Add a item 🔨 to the setup 🧰 or change one
//------------------------------------------------------//
// Remove an item 🔨 from the setup 🧰
//------------------------------------------------------//
setupRemove(state, payload) {
const changeItemCheck = state.setupCurrent.findIndex(
item => item.id == payload.id
);
state.setupCurrent.splice(changeItemCheck, 1);
},
// END Remove an item 🔨 from the setup 🧰
//------------------------------------------------------//
// ❌ Clear the whole setup 🧰 and restore it
//------------------------------------------------------//
setupClear(state) {
state.setupCurrent = [...initSetupCurrent];
},
// END ❌ Clear the whole setup 🧰 and restore it
//------------------------------------------------------//
// ❌ Clear the whole item 🔨 and restore it
//------------------------------------------------------//
itemCurrentClear(state) {
state.itemCurrent = { ...initItem };
},
// END ❌ Clear the whole setup 🔨 and restore it
itemCurrentAdd(state, payload) {
state.itemCurrent = { ...payload };
},
setSetupNotEdited(state, payload) {
state.setupNotEdited = payload;
},
setShowShareModel(state, payload) {
state.showShareModel = payload;
},
};
//------------------------------------------------------//
// Getters
//------------------------------------------------------//
export const getters = {
//------------------------------------------------------//
// Get current setup 🧰
//------------------------------------------------------//
getSetupCurrent: state => {
return state.setupCurrent;
},
// END Get current setup 🧰
//------------------------------------------------------//
// Get current item 🔨
//------------------------------------------------------//
getCurrentItem: state => {
return state.itemCurrent;
},
// END Get current setup 🔨
//------------------------------------------------------//
// 🐦 Create share URL
//------------------------------------------------------//
getShareURL: (state, getters, rootState, rootGetters) => {
const queries = state.setupCurrent.reduce((obj, item) => {
obj[item.type] = item.slug;
return obj;
}, {});
queries.name = rootGetters["name/getName"];
return queries;
},
getSetupNotEdited: state => {
return state.setupNotEdited;
},
// END 🐦 Create share URL
getShowShareModel: state => {
return state.showShareModel;
},
getRealSetupLength: state => {
const filteredState = state.setupCurrent.filter(
item => item.view != "empty"
);
const realLength = filteredState.length;
return realLength;
},
getIfCustomItem: state => {
const checkUsername = item => item.type.includes("custom");
return state.setupCurrent.some(checkUsername);
},
// //------------------------------------------------------//
// // 🔔 Genarate notification based on number of items in 🧰 setup
// //------------------------------------------------------//
// getNumberOfSetupAndName: state => {
// if (state.) {
// }
// return true;
// return false;
// },
// // END 🔔 Genarate notification based on number of items in 🧰 setup
};
//------------------------------------------------------//
// END Getters
//------------------------------------------------------//
|
import { useReducer, useContext, createContext } from 'react';
import * as actionTypes from './actionTypes';
const AuthStateContext = createContext();
const AuthDispatchContext = createContext();
const initialState = {
token: null,
authRedirectPath: '/shop'
}
const reducer = (state, action) => {
switch (action.type) {
case actionTypes.SET_TOKEN:
localStorage.setItem('auth-token', action.payload);
return { ...state, token: action.payload }
case actionTypes.LOGOUT:
localStorage.removeItem('auth-token');
return initialState
case actionTypes.SET_AUTH_REDIRECT_PATH:
return { ...state, authRedirectPath: action.path }
default:
throw new Error(`Unknown action: ${action.type}`)
}
}
export const AuthProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<AuthDispatchContext.Provider value={dispatch}>
<AuthStateContext.Provider value={state}>
{children}
</AuthStateContext.Provider>
</AuthDispatchContext.Provider>
)
}
export const useAuth = () => useContext(AuthStateContext)
export const useDispatchAuth = () => useContext(AuthDispatchContext)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.