text
stringlengths 7
3.69M
|
|---|
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// test API Gateway endpoint
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function testAPI() {
console.log('testAPI: starting');
fetch('https://uh3xocp8qa.execute-api.ap-southeast-2.amazonaws.com/dev/mpgputitem', { method: 'post',
mode: 'no-cors',
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: '{"text": "A text from the client"}' })
.then(res => console.log('Success: res:', res))
.catch(err => console.log('Error: error:', err));
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// call testAPI
//////////////////////////////////////////////////////////////////////////////////////////////////////////
testAPI();
|
import { Switch, Route } from 'react-router-dom';
import Downloads from './Downloads';
import Upload from './Upload';
import Logs from './accessLogs'
const Routes = (user) => {
return (
<main>
<Switch>
<Route exact path="/upload" component={() => <Upload user={user} />}></Route>
<Route exact path="/download" component={() => <Downloads user={user} />}></Route>
<Route path="/logs" component={Logs}></Route>
<Route path="/*" component={Logs}></Route>
</Switch>
</main>
)
}
export default Routes;
|
const path = require('path');
const stream = require('stream');
const express = require('express')
const multer = require('multer')
const parse = require("csv-parse/lib/sync");
const stringify = require('csv-stringify/lib/sync');
const iconv = require('iconv-lite');
const app = express();
const port = process.env.PORT || 3000
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));
const storage = multer.memoryStorage();
const upload = multer({ storage: storage })
app.use(express.static(path.join(__dirname, 'public')))
app.get('/', (request, response) => response.redirect('/upload'));
app.get('/upload', (req, res) => res.sendFile(path.join(__dirname, 'public/upload.html')))
app.post('/upload', upload.fields([{ name: 'csvfile1', maxCount: 1 }, { name: 'csvfile2', maxCount: 1 }]), function (req, res) {
// 文字コード変換する。
const csv1 = iconv.decode(req.files['csvfile1'][0].buffer, req.body.encoding1);
const csv2 = iconv.decode(req.files['csvfile2'][0].buffer, req.body.encoding1);
const records1 = parse(csv1, {
columns: true,
skip_empty_lines: true
});
let records_worktime = [];
for (const record of records1) {
let record_worktime = { name: '', worktime: 0.0 };
console.log(record);
for (const key in record) {
if (/^\s*利用者名\s*$/.test(key)) {
record_worktime.name = record[key];
}
else if (/^\s*\d+月時間\s*$/.test(key) && /^\d+(\.\d+)?$/.test(record[key])) {
record_worktime.worktime = parseFloat(record[key]);
}
}
if (record_worktime.name != '' && record_worktime.worktime > 0.0) {
records_worktime.push(record_worktime);
}
}
/*
const records_worktime = records1.map((record) => {
const name_tmp = record[Object.keys(record).find(key => /^\s*利用者名\s*$/.test(key))];
const worktime_tmp = record[Object.keys(record).find(key => /^\s*\d+月時間\s*$/.test(key))];
if (name_tmp && worktime_tmp && name_tmp != '' && worktime_tmp != '' && /^\d+(\.\d+)?$/.test(worktime_tmp)) {
return { name: name_tmp, worktime: parseFloat(worktime_tmp) };
}
});
*/
if (records_worktime === undefined || records_worktime.length < 1) {
res.send('<html><head></head><body><h1>エラー</h1><p>稼働時間が不正です。</p><hr/><p></p></body></html>');
return;
}
else
console.log(records_worktime);
const records2 = parse(csv2, {
columns: true,
skip_empty_lines: true
});
let records_usage = [];
for (const record in records2) {
let record_usage = { name: '', usage: '', quantity: 0.0 };
for (const key in record) {
if (/^\s*利用者名\s*$/.test(key)) {
record_usage.name = record[key];
}
else if (/^\s*利用料項目\s*$/.test(key)) {
record_usage.usage = record[key];
}
else if (/^\s*数量\s*$/.test(key) && /^\d+(\.\d+)?$/.test(record[key])) {
record_usage.quantity = parseFloat(record[key]);
}
}
if (record_usage.name != '' && record_usage.usage != '' && record_usage.quantiry > 0.0) {
records_usage.push(record_usage);
}
}
/*
const records_usage = records2.map((record) => {
const name_tmp = record[Object.keys(record).find(key => /^\s*利用者名\s*$/.test(key))];
const usage_tmp = record[Object.keys(record).find(key => /^\s*利用料項目\s*$/.test(key))];
const quantity_tmp = record[Object.keys(record).find(key => /^\s*数量\s*$/.test(key))];
if (
name_tmp && usage_tmp && quantity_tmp &&
name_tmp != '' &&
usage_tmp != '' &&
(/^\s*昼食代(\-保険適用)?\s*$/.test(usage_tmp) || /^\s*施設外時間数\s*$/.test(usage_tmp)) &&
/^\d+(\.\d+)?$/.test(quantity_tmp)
) {
return { name: name_tmp, usage: usage_tmp, quantity: parseFloat(quantity_tmp) };
}
});
*/
if (!records_usage) {
res.send('<html><head></head><body><h1>エラー</h1><p>利用項目が不正です。</p><hr/><p></p></body></html>');
return;
}
const data = stringify(records_worktime, {
bom: true,
header: true,
columns: [
{ key: 'name', header: '利用者名' },
{ key: 'worktime', header: '時間' }
]
}); // CSVファイルデータにUTF-8のBOMを付与してExcelでの文字化けを防ぐ
const resultcsv = new stream.PassThrough();
resultcsv.end(data); // streamにCSVデータを渡す
res.set('Content-disposition', 'attachment; filename=result.csv');
res.set('Content-Type', 'text/csv');
resultcsv.pipe(res); // streamを出力する
})
app.listen(port, function () {
console.log(`Example app listening on port ${port}!`)
})
|
var day0 = [], day1 = [], day2 = [], day3 = [], day4 = [], day5 = [], day6 = [];
var emp0 = [], emp1 = [], emp2 = [], emp3 = [], emp4 = [], emp5 = [], emp6 = [];
var month_ar = [];
var colors = ['#79c7fa', '#F6DE3D' ,'#A6F7B8', '#e3b8ff'],
red = '#ff315c',
green = '#00CC99';
function randomColor(){
return colors[Math.floor(Math.random() * colors.length)];
}
var defaultSettings = {
headers: [],
day0: [], day1: [], day2: [], day3: [], day4: [], day5: [], day6: [],
emp0: [], emp1: [], emp2: [], emp3: [], emp4: [], emp5: [], emp6: [],
month_ar: [],
cardTemplate: '<div>${id}</div>',
onClick: function (e, task) {openModal(task);},
containerCssClass: 'skeduler-container',
headerContainerCssClass: 'skeduler-headers',
schedulerContainerCssClass: 'skeduler-main',
taskPlaceholderCssClass: 'skeduler-task-placeholder',
cellCssClass: 'skeduler-cell',
lineHeight: 40,
borderWidth: 1,
debug: false
};
var settings = {};
var root = this;
var this_tab=0;
function toTimeString(value) {
return (value < 10 ? '0' : '') + Math.ceil(value) + (Math.ceil(value) > Math.floor(value) ? ':30' : ':00');
}
function getCardHeight(duration) {
var dur = (settings.lineHeight + settings.borderWidth) * (duration / 60) - 1;
return dur;
}
function renderInnerCardContent(task) {
var result = settings.cardTemplate;
for (var key in task) {
if (task.hasOwnProperty(key)) {
// TODO: replace all
result = result.replace('${' + key + '}', task[key]);
}
}
return $(result);
}
function renderEmptyCardContent(task) {
var result = settings.emptyCardTemplate;
return $(result);
}
function getCardTopPosition(startTime) {
return (settings.lineHeight + settings.borderWidth) * (startTime);
}
function appendTasks(placeholder, tasks) {
tasks.forEach(function(task) {
appendTask(task, placeholder);
}, this);
}
function appendTask(task, placeholder) {
if (task.column>6){
placeholder = (typeof placeholder !== 'undefined') ? placeholder : $("#monthly_day_"+task.column);
var card = $('<div style="background-color: '+randomColor()+'" class="month-event" id="event_month_'+task.id+'">'+task.title+'<span>'+task.startTimeString+'</span>'+'</div>');
card.appendTo("#monthly_day_"+task.column);
}
if(task.column<7) {
placeholder = $("#colum_place_holder"+task.column);
var innerContent = renderInnerCardContent(task);
var top = getCardTopPosition(task.startTime);
var height = getCardHeight(task.duration);
var card = $('<div id="event_'+task.id+'"></div>')
.attr({
style: 'top: ' + top + 'px; height: ' + height + 'px',
title: task.title,
//title: toTimeString(task.startTime) + ' - ' + toTimeString(task.startTime + task.duration)
});
card.on('click', function (e) { settings.onClick && settings.onClick(e, task) });
card.append(innerContent)
.appendTo(placeholder);
if (task.overlap) document.getElementById("event_" + task.id).style.backgroundColor=red;
}
}
function appendEmptyTask(task, placeholder) {
placeholder = (typeof placeholder !== 'undefined') ? placeholder : $("#colum_place_holder"+task.column);
var innerContent = renderEmptyCardContent(task);
var top = getCardTopPosition(task.startTime);
var dur = (settings.lineHeight + settings.borderWidth) * (task.duration) - 1;
var height = dur;
var duration = makeDurationInStringFromExact(task.duration);
var card = $('<span class="skeduler-task-placeholder-empty empty_event_column_'+task.column+'" id="empty_event_'+task.column+'">'+duration+'</span>')
.attr({
style: 'top: ' + top + 'px; line-height: ' + height + 'px',
title: 'ss',
});
//card.on('click', function (e) { settings.onClick && settings.onClick(e, task) });
card.append(innerContent)
.appendTo(placeholder);
}
function fillCalendarWithTasks(){
for(var i=0; i < day0.length; i++) appendTask(day0[i]);
for(var i=0; i < day1.length; i++) appendTask(day1[i]);
for(var i=0; i < day2.length; i++) appendTask(day2[i]);
for(var i=0; i < day3.length; i++) appendTask(day3[i]);
for(var i=0; i < day4.length; i++) appendTask(day4[i]);
for(var i=0; i < day5.length; i++) appendTask(day5[i]);
for(var i=0; i < day6.length; i++) appendTask(day6[i]);
for(var i=0; i < month_ar.length; i++) appendTask(month_ar[i]);
draw_empty_areas_full();
}
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
function makeDurationInString(duration){
var durationInString = "00:";
var hour = Math.floor(duration/60);
var hourNew = hour>9?hour:"0"+hour;
if (hour>0) durationInString = hourNew + ":";
var minute = duration%60;
if (minute<10) minute = "0" + minute;
durationInString += minute;
return durationInString;
}
function makeDurationInStringFromExact(duration){
var newduration = Math.round(duration * 60);
return makeDurationInString(newduration);
}
function makeEndTimeInString(endTime){
var exactHour = Math.floor(endTime) + calendar_startHour;
exactHour = exactHour % 24;
var exactMinute = endTime - Math.floor(endTime);
exactMinute = Math.round(exactMinute * 60);
var hourString = exactHour < 10 ? "0"+exactHour:exactHour;
var minuteString = exactMinute < 10 ? "0"+exactMinute:exactMinute;
return hourString + ":" + minuteString;
}
function addTask(task){
var newHour = task.startTimeHour < calendar_startHour ? Number(task.startTimeHour) + 24 : task.startTimeHour;
newHour = newHour - calendar_startHour;
var newMinute = round((task.startTimeMinute / 60), 5);
task.startTime = newHour + newMinute;
var hourString = task.startTimeHour < 10 ? "0"+task.startTimeHour:task.startTimeHour;
var minuteString = task.startTimeMinute < 10 ? "0"+task.startTimeMinute:task.startTimeMinute;
task.startTimeString = hourString + ":" + minuteString;
task.durationString = makeDurationInString(task.duration);
task.endTime = round(task.startTime, 5) + round((task.duration / 60), 5);
task.endTimeString = makeEndTimeInString(task.endTime);
if (task.startTime<0) { currentError = errorText_calendar_earlierTime; return false;}
if (task.endTime>24) { currentError = errorText_calendar_overlap; return false;}
if (isNaN(task.startTime) || isNaN(task.duration) || isNaN(task.column)) { currentError = errorText_calendar_InvalidValue; return false;}
task.overlap = false;
task.id = taskCounter++;
task.column = (typeof task.column !== 'undefined') ? task.column : 0;
if (task.column < 0) task.column = 0;
//if (task.type!='month') if (task.column > 6) task.column = 6;
if (task.upl==1){} else {
$.ajax({
url: 'calendar_catalog_jquery_save.php',
type: 'post',
data: { data:JSON.stringify(task) },
success: function(response) {
task.realid = response;
}
});
}
//return;
if (task.column>6){
month_ar.push(task);
}
if(task.column<7){
var targetArray = "day" + task.column;
for(var i=0; i< this[targetArray].length; i++){
if (this[targetArray][i].id == task.id) continue;
var top1 = this[targetArray][i].startTime;
var bottom1 = this[targetArray][i].endTime;
var top2 = task.startTime;
var bottom2 = task.endTime;
if ((top1 >= top2 && top1 < bottom2) || (top2 >= top1 && top2 < bottom1) || (bottom1 > top2 && bottom1 <= bottom2) || (bottom2 > top1 && bottom2 <= bottom1)){
task.overlap = true;
break;
}
}
for(var placeInArray=0; placeInArray< this[targetArray].length; placeInArray++){
if (this[targetArray][placeInArray].id == task.id) continue;
if (this[targetArray][placeInArray].startTime > task.startTime) break;
}
if (placeInArray==0) this[targetArray].unshift(task);
else if (placeInArray < this[targetArray].length) this[targetArray].splice( placeInArray, 0, task);
else this[targetArray].push(task);
/////////
// CREATING EMPTY SPACES
/////////
var targetEmptyArray = "emp" + task.column;
if (task.batch){} else {
task.batch = false;
draw_empty_areas(this[targetArray], this[targetEmptyArray], task.column);
}
}
return true;
}
////*****
/// WRITE EMPTY SPACES
///******
function draw_empty_areas_full(){
for(i=0; i<7; i++){
var targetArray = "day"+i;
var targetEmptyArray = "emp"+i;
if (this[targetArray].length > 0) draw_empty_areas(this[targetArray], this[targetEmptyArray], i);
}
}
function draw_empty_areas(tasks, empties, column){
empties = [];
if (tasks.length == 0) {
var empty_task = { startTime: 0, duration: 24, column: column};
appendEmptyTask(empty_task);
return;
}
$( ".empty_event_column_0" +column ).remove();
if (tasks.length == 0) return;
if (tasks[0].startTime > 0){
var empty_task = { startTime: 0, duration: tasks[0].startTime, column: column};
empties.push(empty_task);
}
for(var placeInArray=0; placeInArray< tasks.length-1; placeInArray++){
var this_duration = tasks[placeInArray+1].startTime - tasks[placeInArray].endTime;
if (this_duration>0){
var empty_task = { startTime: tasks[placeInArray].endTime, duration: this_duration, column: column};
empties.push(empty_task);
}
}
var placeInArray = tasks.length-1;
var endTime = tasks[placeInArray].endTime;
var last_duration = 24 - endTime;
if (last_duration>0){
var empty_task = { startTime: tasks[placeInArray].endTime, duration: last_duration, column: column};
empties.push(empty_task);
}
for(var j=0; j < empties.length; j++) appendEmptyTask(empties[j]);
}
function divcollision($div1, $div2) {
var y1 = $div1.offset().top;
var h1 = $div1.outerHeight(true);
var b1 = y1 + h1;
var y2 = $div2.offset().top;
var h2 = $div2.outerHeight(true);
var b2 = y2 + h2;
if (b1 < y2 || y1 > b2) return false;
return true;
}
function openModalwithID(id, day){
var targetArray = "day" + day;
for(var i=0; i<this[targetArray].length; i++){
if (this[targetArray][i].id == id){
openModal(this[targetArray][i]);
return;
}
}
}
function openModal(task) {
if (task.e) {
$("#myModal").modal();
$("#calendar-modal-header").text(task.title);
$("#calendar-modal-starthour").val(task.startTimeHour);
$("#calendar-modal-startminute").val(task.startTimeMinute);
if (!task.durationHour) task.durationHour = Math.floor(task.duration/60);
if (!task.durationMinute) task.durationMinute = task.duration - (task.durationHour*60);
$("#calendar-modal-durationMinute").val(task.durationMinute);
$("#calendar-modal-durationHour").val(task.durationHour);
$("#calendar-modal-id").val(task.id);
$("#calendar-modal-day-id").val(task.column);
}
}
function modal_save_task(){
var hour = Number($("#calendar-modal-starthour").val());
var minute = Number($("#calendar-modal-startminute").val());
var durHour = Number($("#calendar-modal-durationHour").val());
var durMinute = Number($("#calendar-modal-durationMinute").val());
var duration = durHour * 60 + durMinute;
var durationString = makeDurationInString(duration);
var id = Number($("#calendar-modal-id").val());
var day = Number($("#calendar-modal-day-id").val());
var targetArray = "day" + day;
var targetEmptyArray = "emp" + day;
for(var i=0; i<this[targetArray].length; i++){
if (this[targetArray][i].id == id){
var arr = this[targetArray][i];
arr.startTimeHour = hour;
arr.startTimeMinute = minute;
arr.duration = duration;
arr.durationHour = durHour;
arr.durationMinute = durMinute;
arr.durationString = durationString;
$.ajax({
url: 'calendar_catalog_jquery_update.php',
type: 'post',
data: { data:JSON.stringify(arr) },
success: function(response) {
console.log(response);
}
});
document.getElementById("event_"+id).remove();
this[targetArray].splice(i,1);
if (addTask(arr)) {
appendTask(arr);
}
else alert(currentError);
break;
}
}
update_tab(this_tab);
$('#myModal').modal('toggle');
}
function update_db(task){
$.ajax({
url: 'calendar_catalog_jquery_update.php',
type: 'post',
data: { data:JSON.stringify(task) },
success: function(response) {
console.log(response);
}
});
}
function modal_delete_task(){
var id = $("#calendar-modal-id").val();
var day = $("#calendar-modal-day-id").val();
delete_task(id, day);
$('#myModal').modal('toggle');
}
function delete_task_from_page(id, day, tabID){
delete_task(id, day);
update_tab(tabID);
}
function delete_month_task_from_page(id, day){
var targetArray = "day" + day;
for(var i=0; i<month_ar.length; i++){
if (month_ar[i].id == id){
document.getElementById("event_month_"+id).remove();
month_ar.splice(i,1);
break;
}
}
}
function delete_task(id, day){
var targetArray = "day" + day;
var targetEmptyArray = "emp" + day;
for(var i=0; i<this[targetArray].length; i++){
if (this["day"+day][i].id == id){
$.ajax({
url: 'calendar_catalog_jquery_delete.php',
type: 'post',
data: { data:JSON.stringify(this["day"+day][i]) },
success: function(response) {
console.log(response);
}
});
if (this["day"+day][i].type == "month") delete_month_task_from_page(id, day);
document.getElementById("event_"+id).remove();
this[targetArray].splice(i,1);
break;
}
}
draw_empty_areas(this[targetArray], this[targetEmptyArray], day);
}
function update_tab(tabID){
for(var j=0; j<4; j++)
for(var i=0; i<7; i++) {
$('#catalog_chk_'+j+"_"+i).attr('checked', false);
$('#catalog_chk_'+j+"_"+i).attr('disabled', true);
}
if (tabID==0){
for(var i=0; i<7; i++) {
$('#catalog_chk_0_'+i).attr('disabled', false);
}
}
if (tabID==8){
for(var j=0; j<4; j++)
for(var i=0; i<7; i++) {
$('#catalog_chk_'+j+"_"+i).attr('checked', false);
$('#catalog_chk_'+j+"_"+i).attr('disabled', false);
}
}
if (tabID > 0 && tabID < 8) {
day = tabID-1;
//$('#catalog_chk_0_'+day).attr('checked', true);
//$('#catalog_chk_0_'+day).attr('disabled', true);
var targetArray = 'day' + day;
var fulltext = '';
for(var i=0; i<root[targetArray].length; i++){
var task = root[targetArray][i];
var timeline = '';
timeline += '<div class="entry">';
timeline += '<div class="title">';
timeline += '<h3>'+root[targetArray][i].startTimeString+' - '+root[targetArray][i].endTimeString+'</h3>';
timeline += '<p></p>';
timeline += '</div>';
timeline += '<div class="body">';
timeline += '<p>'+root[targetArray][i].title+'</p>';
timeline += '<ul><li>'+makeDurationInString(root[targetArray][i].duration)+'</li></ul>';
timeline += '</div>';
timeline += '<div class="actions"><a class="btn btn-default" href="#" onclick="openModalwithID('+task.id+','+task.column+');return false;">Редактировать</a><a class="btn btn-danger" href="#" onclick="delete_task_from_page('+task.id+','+task.column+', '+tabID+');return false;">Удалить</a> </div>';
timeline += '</div>';
//test
// timeline += '<div class="entry">';
// timeline += '<div class="title">';
// timeline += '<h3>'+root[targetArray][i].startTimeString+' - '+root[targetArray][i].endTimeString+'</h3>';
// timeline += '<p></p>';
// timeline += '</div>';
// timeline += '<div class="body">';
// timeline += '<p>'+root[targetArray][i].title+'</p>';
// timeline += '<ul><li>'+makeDurationInString(root[targetArray][i].duration)+'</li></ul>';
// timeline += '</div>';
// timeline += '<div class="actions"><a class="btn btn-default" href="#" onclick="openModalwithID('+task.id+','+task.column+');return false;">Редактировать</a><a class="btn btn-danger" href="#" onclick="delete_task_from_page('+task.id+','+task.column+', '+tabID+');return false;">Удалить</a> </div>';
// timeline += '</div>';
fulltext += timeline +' ';
if (i < (root[targetArray].length-1)){
var this_duration = root[targetArray][i+1].startTime - root[targetArray][i].endTime;
if (this_duration>0){
timeline = '';
timeline += '<div class="entry">';
timeline += '<div class="title">';
timeline += '<h3>'+root[targetArray][i].endTimeString+' - '+root[targetArray][i+1].startTimeString+'</h3>';
timeline += '<p></p>';
timeline += '</div>';
timeline += '<div class="body">';
timeline += '<p style="color:'+green+'">Доступное время</p>';
timeline += '<ul><li style="color:'+green+'">'+makeDurationInStringFromExact(this_duration)+'</li></ul>';
timeline += '</div>';
timeline += '</div>';
fulltext += timeline +' ';
}
if (this_duration < 0){
timeline = '';
timeline += '<div class="entry">';
timeline += '<div class="title">';
timeline += '<h3>'+root[targetArray][i+1].startTimeString+' - '+root[targetArray][i].endTimeString+'</h3>';
timeline += '<p></p>';
timeline += '</div>';
timeline += '<div class="body">';
timeline += '<p style="color:'+red+'">Превышение хронометража</p>';
timeline += '<ul><li style="color:'+red+'">'+makeDurationInStringFromExact(-1*this_duration)+'</li></ul>';
timeline += '</div>';
timeline += '</div>';
fulltext += timeline +' ';
}
}
}
$('#timeline'+day).html(fulltext);
}
}
|
var searchData=
[
['fromcstring_18',['fromCString',['../poem__sorter_8h.html#ac975ff6420860ee734d7c16349fba1b7',1,'poem_sorter.cpp']]]
];
|
//CRUD functionality for users account information
const router = require("express").Router();
const user = require("../models/user-models");
const userInstance = new user();
// router.get("/", userInstance.getUser);
router.put("/:id", userInstance.updateUser);
router.delete("/:id", userInstance.deleteUser);
module.exports = router;
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
}
function btnCallFun(){
window.plugins.CallNumber.callNumber(function(){ alert("calling");},function(e){},"8655877317");
}
|
import React from 'react'
class Page1 extends React.Component {
constructor(props) {
super(props)
this.state = { foo: '' }
}
render() {
return (
<h1>Page 1</h1>
)
}
}
export default Page1
|
require('./app/main')
require('./app/today')
function init() {
}
addEventListener('DOMContentLoaded', () => {
init()
})
|
const products = [
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
{
id: Math.random(),
name: "Electic Bulb",
image: "img1.jpg",
},
];
export default products;
|
import angular from 'angular'
import uirouter from 'angular-ui-router'
import routing from './appConfig'
import home from './features/home'
angular.module('app', [uirouter, home])
.config(routing)
|
"use strict";
var React = require('react');
var container_1 = require('../components/container');
;
function AboutPage(props) {
return (<container_1["default"] size={4} center>
<h2 className="caps">About Us</h2>
<p>
Rangle.io is a next-generation HTML5 design and development firm
dedicated to modern, responsive web and mobile applications.
</p>
</container_1["default"]>);
}
exports.__esModule = true;
exports["default"] = AboutPage;
|
var classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1activity_1_1_p_d_e_account_authenticator_activity =
[
[ "onCreate", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1activity_1_1_p_d_e_account_authenticator_activity.html#a7138d6d815e3ed6165f4010f61b699d5", null ]
];
|
/**
* Created by Pradip on 5/11/2016.
* Modified by Jake on 8/26/18
*/
var BUILD = false;
var DEV = false;
var PROD = true;
// Ends configuration setting
if (BUILD && DEV) {
throw "Cannot have different environment true at same time";
}
var gulp = require('gulp'),
sass = require('gulp-sass'),
sassGlob = require('gulp-sass-glob'),
sourcemaps = require('gulp-sourcemaps'),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
minify = require('gulp-minify'),
browserSync = require('browser-sync').create(),
exec = require('child_process').exec;
var config = {
sassPath: './source/css',
bootstrapPath: './source/node_modules/bootstrap/scss',
nodeModules: './source/node_modules',
sassWebFontPath: './node_modules/sass-web-fonts',
prodFolder: './pl/public'
};
var buildPaths = {
target: './public_html',
styleGuide: './pl/public/index.html',
home: './pl/public/patterns/05-prod-index-index/05-prod-index-index.html',
portfolio: './pl/public/patterns/05-prod-portfolio-portfolio/05-prod-portfolio-portfolio.html',
feed: './pl/public/patterns/05-prod-feed-feed/05-prod-feed-feed.html',
skills: './pl/public/patterns/05-prod-skills-skills/05-prod-skills-skills.html',
education: './pl/public/patterns/05-prod-education-education/05-prod-education-education.html',
experience: './pl/public/patterns/05-prod-experience-experience/05-prod-experience-experience.html',
marvel: './pl/public/patterns/05-prod-marvel-marvel/05-prod-marvel-marvel.html',
ncp: './pl/public/patterns/05-prod-ncp-ncp/05-prod-ncp-ncp.html',
vgs: './pl/public/patterns/05-prod-video-game-series-video-game-series/05-prod-video-game-series-video-game-series.html',
}
var sassOption = {
errLogToConsole: true,
// Default environment is dev
outputStyle: BUILD ? 'compressed' : 'expanded',
includePaths: [
config.sassWebFontPath + '/_web-fonts.scss',
config.sassPath,
config.nodeModules
]
};
gulp.task('sass', function() {
return gulp.src(config.sassPath + '/**/style.scss')
.pipe(sassGlob())
.pipe(concat('style.css'))
.pipe(rename({
basename: 'style',
extname: '.css'
}))
.pipe(sourcemaps.init())
.pipe(sass({ outputStyle: 'compressed' }).on('error', sass.logError))
.pipe(sourcemaps.write('./source/maps'))
.pipe(gulp.dest('./source/css'))
.pipe(browserSync.stream());
});
gulp.task('pl', ['sass'], function(cb) {
exec('php ./pl/core/console --generate', function(err, stdout, stderr) {
browserSync.reload();
cb(err);
});
});
gulp.task('js', ['pl'], function(cb) {
gulp.src('./node_modules/bootstrap/dist/js/bootstrap.min.js')
.pipe(gulp.dest('./source/js'));
gulp.src('./node_modules/particlesjs/dist/particles.min.js')
.pipe(gulp.dest('./source/js'));
gulp.src('./node_modules/materialize-css/dist/js/materialize.min.js')
.pipe(gulp.dest('./source/js'));
gulp.src('./node_modules/progressbar.js/dist/progressbar.min.js')
.pipe(gulp.dest('./source/js'));
return gulp.src('./source/_patterns/**/*.js')
.pipe(concat('script.js'))
.pipe(minify())
.pipe(sourcemaps.write('./source/js'))
.pipe(gulp.dest('./source/js'))
.pipe(browserSync.stream());
});
gulp.task('build_prod', ['sass', 'js', 'pl'], function(cb) {
//Pattern Lab and Sass Will be Generated First Based on Dependencies
// Home Page
console.log("Starting Home Build...");
gulp.src(buildPaths.home)
.pipe(rename({
basename: 'index',
extname: '.html'
}))
.pipe(gulp.dest(buildPaths.target));
console.log("Home Build Finished");
// Portfolio
console.log("Starting Portfolio Build...");
gulp.src(buildPaths.portfolio)
.pipe(rename({
basename: 'index',
extname: '.html'
}))
.pipe(gulp.dest('./public_html/portfolio'));
console.log("Portfolio Build Finished");
// Feed
console.log("Starting Feed Build...");
gulp.src(buildPaths.feed)
.pipe(rename({
basename: 'index',
extname: '.html'
}))
.pipe(gulp.dest('./public_html/feed'));
console.log("Feed Build Finished");
// Skills
console.log("Starting Skills Build...");
gulp.src(buildPaths.skills)
.pipe(rename({
basename: 'index',
extname: '.html'
}))
.pipe(gulp.dest('./public_html/skills'));
console.log("Skills Build Finished");
// Education
console.log("Starting Education Build...");
gulp.src(buildPaths.education)
.pipe(rename({
basename: 'index',
extname: '.html'
}))
.pipe(gulp.dest('./public_html/education'));
console.log("Education Build Finished");
// Experience
console.log("Starting Experience Build...");
gulp.src(buildPaths.experience)
.pipe(rename({
basename: 'index',
extname: '.html'
}))
.pipe(gulp.dest('./public_html/experience'));
console.log("Experience Build Finished");
// Marvel
console.log("Starting Marvel Build...");
gulp.src(buildPaths.marvel)
.pipe(rename({
basename: 'index',
extname: '.html'
}))
.pipe(gulp.dest('./public_html/marvel'));
console.log("Marvel Build Finished");
// VGS
console.log("Starting VGS Build...");
gulp.src(buildPaths.vgs)
.pipe(rename({
basename: 'index',
extname: '.html'
}))
.pipe(gulp.dest('./public_html/video-game-series'));
console.log("VGS Build Finished");
// NCP
console.log("Starting NCP Build...");
gulp.src(buildPaths.ncp)
.pipe(rename({
basename: 'index',
extname: '.html'
}))
.pipe(gulp.dest('./public_html/ncp'));
console.log("NCP Build Finished");
// Copy CSS
console.log("Starting Copy of CSS");
gulp.src('./source/css/style.css')
.pipe(gulp.dest('./public_html/css'));
console.log("Finished Copying CSS");
// Copy JS
console.log("Starting Copy of JS");
gulp.src('./source/js/*.js')
.pipe(gulp.dest('./public_html/js'));
console.log("Finished Copying JS");
// Copy Images
console.log("Starting Copy of Images");
gulp.src('./source/assets/**/*')
.pipe(gulp.dest('./public_html/assets'));
console.log("Finished Copying Images");
// Copy Fonts
console.log("Starting Copy of Fonts");
gulp.src('./source/fonts/**/*')
.pipe(gulp.dest('./public_html/fonts'));
console.log("Finished Copying Fonts");
});
// Start Static Server
gulp.task('serve', ['sass', 'pl'], function() {
browserSync.init({
server: {
baseDir: './',
},
startPath: 'pl/public/',
open: true
});
});
// Watching Source Files
gulp.task('source:watch', ['sass', 'pl', 'js'], function() {
gulp.watch('./source/_patterns/**/*.twig', ['pl']);
gulp.watch('./source/_patterns/**/*.scss', ['sass', 'pl']);
gulp.watch('./source/css/scss/**/*.scss', ['sass', 'pl']);
gulp.watch('./source/_patterns/**/*.js', ['pl', 'js']);
});
gulp.task('default', ['source:watch', 'serve']);
|
import React from "react";
import { storiesOf } from "@storybook/react";
import { withKnobs } from "@storybook/addon-knobs";
import { getStoryName } from "storybook/storyTree";
import L10n from "@paprika/l10n";
import ShowcaseStory from "./examples/Showcase";
import { OverflowMenuStory } from "./OverflowMenu.stories.styles";
import OverflowMenuExample from "./examples/OverflowMenuExample";
import OverflowMenuMultiConfirmationExample from "./examples/OverflowMenuMultiConfirmationExample";
import OverflowMenuDividersExample from "./examples/OverflowMenuDividersExample";
import OverflowMenuLongestExample from "./examples/OverflowMenuLongestExample";
import OverflowMenuTriggerExample from "./examples/OverflowMenuTriggerExample";
import OverflowMenuOnCloseExample from "./examples/OverflowMenuOnCloseExample";
import OverflowMenuWithCustomClassExample from "./examples/OverflowMenuWithCustomClassExample";
import ZIndexExample from "./examples/ZIndex";
import AutoFocusExample from "./examples/AutoFocusExample";
const storyName = getStoryName("OverflowMenu");
storiesOf(storyName, module)
.addDecorator(withKnobs)
.add("Showcase", ShowcaseStory);
storiesOf(`${storyName}/Examples`, module)
.add("Basic", () => (
<OverflowMenuStory>
<OverflowMenuExample />
</OverflowMenuStory>
))
.add("with locale", () => (
<OverflowMenuStory>
<L10n locale="zh">
<OverflowMenuExample />
</L10n>
</OverflowMenuStory>
))
.add("with multiple confirmation modals", () => (
<OverflowMenuStory>
<OverflowMenuMultiConfirmationExample />
</OverflowMenuStory>
))
.add("with dividers", () => (
<OverflowMenuStory>
<OverflowMenuDividersExample />
</OverflowMenuStory>
))
.add("with longest story", () => (
<OverflowMenuStory>
<OverflowMenuLongestExample />
</OverflowMenuStory>
))
.add("with trigger examples", () => (
<OverflowMenuStory>
<OverflowMenuTriggerExample />
</OverflowMenuStory>
))
.add("with onClose", () => (
<OverflowMenuStory>
<OverflowMenuOnCloseExample />
</OverflowMenuStory>
))
.add("with custom class on Popover content", () => (
<OverflowMenuStory>
<OverflowMenuWithCustomClassExample />
</OverflowMenuStory>
));
storiesOf(`${storyName}/Backyard/Sandbox`, module)
.add("Z Index", () => (
<OverflowMenuStory>
<ZIndexExample />
</OverflowMenuStory>
))
.add("Auto-focus", () => (
<OverflowMenuStory>
<AutoFocusExample />
</OverflowMenuStory>
));
storiesOf(`${storyName}/Backyard/Tests`, module).add("Cypress", () => <OverflowMenuExample />);
|
import React, { Component } from "react";
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import axios from 'axios';
import { Platform, Image, View, StatusBar, Linking, TouchableHighlight, Text, ImageBackground, ScrollView, Switch, FlatList, TouchableOpacity } from "react-native";
import { Container, Content } from "native-base";
import Icon from 'react-native-vector-icons/dist/FontAwesome';
import FeatherIcon from 'react-native-vector-icons/dist/Feather';
//import MaterialIcon from 'react-native-vector-icons/dist/MaterialIcon';
// Components
import Header from '../components/Header/Header';
import Footer from '../components/Footer/Footer';
import VODCategory from '../components/VODCategory/VODCategory';
import Slider from '../components/Slider/Slider';
// Styles
import { styles } from "../style/appStyles";
import VODStyle from "../style/vodStyle";
import liveChannelStyle from "../style/liveChannelStyle";
// Other data/helper functions
import data from '../data/moviesData.json';
import { movie_1, movie_2, tv_1, tv_2, thumbnail } from "../assets/Images";
import { getVideoOrChannelRelatedData } from '../actions/PlayActions';
import { showMessage } from '../actions/FlashMessageActions';
import { show, hide } from '../actions/ActivityIndicatorActions';
import { getDetails, getInterests } from '../actions/AccountActions';
import { getVideosPackages, getVideos, getTVCategories, getChannels } from '../actions/CategoryActions';
import { addFavoriteChannel, addFavoriteVideo, addLikesChannels, addLikesVideos } from '../actions/FavoriteActions';
import { addVideoHistory, addChannelHistory, addShowHistory } from '../actions/HistoryActions';
import * as vars from '../constants/api';
import { messages } from '../constants/messages';
import { console_log } from '../utils/helper';
import NavigationService from "../utils/NavigationService";
import { movies } from '../constants/movies';
import { bidiotvMoviesData } from '../constants/bidiotvmovies';
import { esmobiotv } from '../constants/esmobiotv';
import Loader from '../components/Loader/Loader';
import Search from '../components/Search/Search';
let movies1 = movies;
import SplashScreen from 'react-native-splash-screen'
import MessageBar from '../components/Message/Message';
import Globals from '../constants/Globals';
import DeviceType from '../../App';
let bidiotvMovies = Globals.type === 'es' ? esmobiotv : bidiotvMoviesData;
class VOD extends Component {
constructor(props) {
super(props);
this.state = {
data: data.moviesData,
favoriteSwitch: false,
dataLoad: false,
color: '',
message:'',
showMessage:false,
};
//console.log('bidiotvmovies1:', bidiotvmovies1)
//this.videoFavorite = this.videoFavorite.bind(this);
//this.isVideoFavorite = this.isVideoFavorite.bind(this);
this.switchFavorite = this.switchFavorite.bind(this);
axios.defaults.headers.common['authorization'] = this.props.accessToken;
}
clickedButton() {
}
componentWillMount(){
//console.log('%%%%%')
axios.defaults.headers.common['authorization'] = this.props.accessToken;
if(Globals.url === 'http://uk.mobiotv.com' && this.props.category.categories.length === 0) {
this.props.show();
axios.all([axios.get(vars.BASE_API_URL + '/getUserProfile'), axios.get(vars.BASE_API_URL + '/interests'), axios.get(vars.BASE_API_URL + '/categories'), axios.get(vars.BASE_API_URL + '/packages'), axios.get(vars.BASE_API_URL + '/favorites'), axios.get(vars.BASE_API_URL + '/history'), axios.get(vars.BASE_API_URL + '/likes')])
//axios.all([axios.get(vars.BASE_API_URL + '/getUserProfile'), axios.get(vars.BASE_API_URL + '/interests'), axios.get(vars.BASE_API_URL + '/categories'), axios.get(vars.BASE_API_URL + '/packages'), axios.get(vars.BASE_API_URL + '/favorites'), axios.get(vars.BASE_API_URL + '/likes')])
.then(axios.spread((userProfile, interests, categories, packages, favorites, history, likes) => {
//.then(axios.spread((userProfile, interests, categories, packages, favorites, likes) => {
// console.log('history.data.data:',history.data.data)
// for user details
if (userProfile.data.data) {
this.props.getDetails(userProfile.data.data);
}
// for interests
if (interests.data.data) {
this.props.getInterests(interests.data.data);
}
// for channel categories
if (categories.data.data) {
this.props.getTVCategories(categories.data.data);
}
// for packages of Video On Demand
if (packages.data.data.packages) {
this.props.getVideosPackages(packages.data.data.packages);
// for Videos On Demand
axios.all(packages.data.data.packages.map(l => axios.get(vars.BASE_API_URL + '/packages/' + l.id)))
.then(axios.spread((...res) => {
// all requests are now complete
res.map((packageDetails) => {
if (packageDetails) {
this.props.getVideos(packageDetails.data.data.package);
}
});
}));
}
// for favorites
if (favorites.data.data) {
this.props.addFavoriteChannel(favorites.data.data.channels);
this.props.addFavoriteVideo(favorites.data.data.videos);
}
//for history
if (history.data.data) {
this.props.addChannelHistory(history.data.data.channels);
this.props.addVideoHistory(history.data.data.videos);
this.props.addShowHistory(history.data.data.shows);
}
// for likes
if (likes.data.data) {
this.props.addLikesChannels(likes.data.data.channels);
this.props.addLikesVideos(likes.data.data.videos);
}
//this.props.hide();
this.setState({dataLoad: true})
}));
}
}
componentDidMount(){
this.setState({dataLoad: true})
this.props.show();
setTimeout(() => {
this.props.hide();
Platform.OS !== 'ios' ? SplashScreen.hide() : null;
}, 1500);
}
componentWillReceiveProps(newProps){
if(newProps.category.categories.length !== 0){
// this.setState({dataLoad: true})
} }
_onViewAllButtonPress(categoryId, from) {
if(from === 'channel'){
NavigationService.navigate('Channels',{from: 'VOD',categoryId: categoryId});
}
else{
NavigationService.navigate('VideoList',{from: 'VOD',categoryId: categoryId});
}
}
_handleFavoriteClicked(data) {
//console.log(JSON.stringify(data));
this.videoFavorite(data.video);
}
_onPressButton(data) {
//console_log('****', data)
NavigationService.navigate('PlayVOD');
this.props.getVideoOrChannelRelatedData(data);
}
_onPressButtonVODChannel(data) {
NavigationService.navigate('PlayOthers');
this.props.getVideoOrChannelRelatedData(data);
}
videoFavorite(data) {
let favoriteVideos = this.props.favorite.videos;
let indexOf = favoriteVideos.findIndex((f) => {
return f.videoId == data.id;
});
let videoToBeUpdated = {
videoId: data.id,
duration: data.duration,
name: data.name,
preview: data.preview
};
if (indexOf == -1) {
favoriteVideos.push(videoToBeUpdated);
axios.post(vars.BASE_API_URL+"/favorites/videos", videoToBeUpdated)
.then((response) => {
this.props.showMessage({
message: messages.addToFavorites,
type: true
});
//console_log('addVide' + response);
})
.catch((error) => {
console_log(error);
});
this.setState({color:'green', message: messages.addToFavorites, showMessage: !this.state.showMessage})
} else {
favoriteVideos.splice(indexOf, 1);
axios.delete(vars.BASE_API_URL+"/favorites/videos/"+videoToBeUpdated.videoId)
.then((response) => {
this.props.showMessage({
message: messages.removeFromFavorites,
type: false
});
//console_log(response);
})
.catch((error) => {
console_log(error);
});
this.setState({color:'red', message: messages.removeFromFavorites, showMessage: !this.state.showMessage})
}
this.props.addFavoriteVideo(favoriteVideos);
}
isVideoFavorite(videoId) {
let indexOf = this.props.favorite.videos.findIndex((f) => {
return f.videoId == videoId;
});
if (indexOf != -1) {
return true;
}
return false;
}
switchFavorite() {
this.setState({ favoriteSwitch: !this.state.favoriteSwitch });
}
LoadVOD = () =>{
//console_log('***', this.props.category.videos.length)
let favoriteVideosIds = this.props.favorite.videos.map((v) => v.videoId);
return(
<View>
{!this.state.favoriteSwitch && movies1 ?
movies1.map((category, i) => {
return (
<View key={i}>
<View style={{ height: 35, flexDirection: 'row', paddingTop: 5, paddingBottom: 5, paddingLeft: 10, paddingRight: 10, justifyContent: 'space-between', backgroundColor: 'black', alignItems: 'center' }}>
<View>
<Text numberOfLines={1} style={[styles.avRegular, liveChannelStyle.categoryName]}>
{category.name}
</Text>
</View>
<TouchableOpacity onPress={this._onViewAllButtonPress.bind(this, category.id, 'video')}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Icon name='th' size={15} style={{ backgroundColor: 'transparent', paddingRight: 5 }} color='#d51a92' />
<Text style={[styles.avRegular, liveChannelStyle.browseAll]}>
Ver todos
</Text>
</View>
</TouchableOpacity>
</View>
{category.videos.length > 0 ?
<ScrollView horizontal={true} >
<View style={{ flexDirection: 'row' }}>
{
category.videos.map((m, index) => {
return (
<View style={liveChannelStyle.imageThmbnail} key={index}>
<TouchableOpacity onPress={this._onPressButton.bind(this, {video: m})}>
<ImageBackground style={liveChannelStyle.imageBackground} source={m.preview}>
<TouchableOpacity style={liveChannelStyle.tvFavoriteBg} onPress={this._handleFavoriteClicked.bind(this, {video: m})}>
<View style={liveChannelStyle.tvFavoriteView}>
<Icon name='star' size={15} style={{ backgroundColor: 'transparent' }} color={this.isVideoFavorite(m.id) ? "#FFC107" : "#fff"} />
</View>
</TouchableOpacity>
</ImageBackground>
</TouchableOpacity>
</View>
)
})
}
</View>
</ScrollView>
: null}
</View>
)
})
: movies1.map((category, i) => {
let newVideos = category.videos.filter((video) => {
if (~favoriteVideosIds.indexOf(video.id)) {
return video;
}
});
//console_log('newVideos://',newVideos)
if (newVideos.length > 0) {
return (
<View key={i}>
<View style={{
height: 35,
flexDirection: 'row',
paddingTop: 5,
paddingBottom: 5,
paddingLeft: 10,
paddingRight: 10,
justifyContent: 'space-between',
backgroundColor: 'black',
alignItems: 'center'
}}>
<View>
<Text numberOfLines={1}
style={[styles.avRegular, liveChannelStyle.categoryName]}>
{category.name}
</Text>
</View>
<TouchableOpacity onPress={this._onViewAllButtonPress.bind(this, category.id, 'video')}>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<Icon name='th' size={15}
style={{backgroundColor: 'transparent', paddingRight: 5}}
color='#d51a92'/>
<Text style={[styles.avRegular, liveChannelStyle.browseAll]}>
Ver todos
</Text>
</View>
</TouchableOpacity>
</View>
{newVideos.length > 0 ?
<ScrollView horizontal={true}>
<View style={{flexDirection: 'row'}}>
{
newVideos.reverse().map((m, index) => {
return (
<View style={liveChannelStyle.imageThmbnail}
key={index}>
<TouchableOpacity onPress={this._onPressButton.bind(this, {video: m})}>
<ImageBackground style={liveChannelStyle.imageBackground} source={m.preview}>
<TouchableOpacity style={liveChannelStyle.tvFavoriteBg} onPress={this._handleFavoriteClicked.bind(this, {video: m})}>
<View style={liveChannelStyle.tvFavoriteView}>
<Icon name='star' size={15} style={{backgroundColor: 'transparent'}} color={this.isVideoFavorite(m.id) ? "#FFC107" : "#fff"}/>
</View>
</TouchableOpacity>
</ImageBackground>
</TouchableOpacity>
</View>
)
})
}
</View>
</ScrollView>
: null}
</View>
)
}
})
}
{!this.state.favoriteSwitch && this.props.category.videos ?
this.props.category.videos.sort((a, b) => a.id > b.id).map((videos, key) => {
return (<View key = {key}>
<View style={{ height: 35, flexDirection: 'row', paddingTop: 5, paddingBottom: 5, paddingLeft: 10, paddingRight: 10, justifyContent: 'space-between', backgroundColor: 'black', alignItems: 'center' }}>
<View>
<Text numberOfLines={1} style={[styles.avRegular, liveChannelStyle.categoryName]}>
{videos.name}
</Text>
</View>
<TouchableOpacity onPress={this._onViewAllButtonPress.bind(this, videos.id, 'channel')}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Icon name='th' size={15} style={{ backgroundColor: 'transparent', paddingRight: 5 }} color='#d51a92' />
<Text style={[styles.avRegular, liveChannelStyle.browseAll]}>
Ver todos
</Text>
</View>
</TouchableOpacity>
</View>
{videos.videos?
<ScrollView horizontal={true} >
<View style={{ flexDirection: 'row' }}>
{videos.videos.map((v, k) => {
return (
<View style={liveChannelStyle.tvThmbnail} key={k}>
<TouchableOpacity onPress={this._onPressButtonVODChannel.bind(this, {video: v})}>
<ImageBackground style={liveChannelStyle.tvImageBackground} source={{uri: v.preview}}>
<View style={{flex: 1, backgroundColor: "rgba(0,0,0,.5)"}}>
<TouchableOpacity style={liveChannelStyle.tvFavoriteBg} onPress={this._handleFavoriteClicked.bind(this, {video: v})}>
<View style={liveChannelStyle.tvFavoriteView}>
<Icon name='star' size={15} style={{ backgroundColor: 'transparent' }} color={this.isVideoFavorite(v.id)? "#FFC107" : "#fff"} />
</View>
</TouchableOpacity>
<View style={liveChannelStyle.videoTitleView}>
<Text numberOfLines={1} style={[styles.avRegular, liveChannelStyle.videoTitle]}>{v.name}</Text>
<View style={[liveChannelStyle.videoDurationView]}>
<Text style={[styles.avRegular, liveChannelStyle.videoDuration,{paddingBottom: 1}]}>1h 40m</Text>
</View>
</View>
</View>
</ImageBackground>
</TouchableOpacity>
</View>
)
},this)
}
</View>
</ScrollView>
: ''
}
</View>
)
})
:
this.props.category.videos.sort((a, b) => a.id > b.id).map((videos, key) => {
let packageVideos = videos.videos.filter((video) => {
if (~favoriteVideosIds.indexOf(video.id)) {
return video;
}
});
if (packageVideos.length > 0) {
return (
<View key = {key}>
<View style={{ height: 35, flexDirection: 'row', paddingTop: 5, paddingBottom: 5, paddingLeft: 10, paddingRight: 10, justifyContent: 'space-between', backgroundColor: 'black', alignItems: 'center' }}>
<View>
<Text numberOfLines={1} style={[styles.avRegular, liveChannelStyle.categoryName]}>
{videos.name}
</Text>
</View>
<TouchableOpacity onPress={this._onViewAllButtonPress.bind(this, videos.id, 'channel')}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Icon name='th' size={15} style={{ backgroundColor: 'transparent', paddingRight: 5 }} color='#d51a92' />
<Text style={[styles.avRegular, liveChannelStyle.browseAll]}>
Ver todos
</Text>
</View>
</TouchableOpacity>
</View>
{packageVideos?
<ScrollView horizontal={true} >
<View style={{ flexDirection: 'row' }}>
{packageVideos.map((v, k) => {
//console_log(v.preview)
return (
<View style={liveChannelStyle.tvThmbnail} key={k}>
<TouchableOpacity onPress={this._onPressButtonVODChannel.bind(this, {video: v})}>
<ImageBackground style={liveChannelStyle.tvImageBackground} source={{uri: v.preview}}>
<View style={{flex: 1, backgroundColor: "rgba(0,0,0,.5)"}}>
<TouchableOpacity style={liveChannelStyle.tvFavoriteBg} onPress={this._handleFavoriteClicked.bind(this, {video: v})}>
<View style={liveChannelStyle.tvFavoriteView}>
<Icon name='star' size={15} style={{ backgroundColor: 'transparent' }} color={this.isVideoFavorite(v.id) ? "#FFC107" : "#fff"} />
</View>
</TouchableOpacity>
<View style={liveChannelStyle.videoTitleView}>
<Text numberOfLines={1} style={[styles.avRegular, liveChannelStyle.videoTitle]}>{v.name}</Text>
<View style={liveChannelStyle.videoDurationView}>
<Text style={[styles.avRegular, liveChannelStyle.videoDuration]}>1h 40m</Text>
</View>
</View>
</View>
</ImageBackground>
</TouchableOpacity>
</View>
)
},this)
}
</View>
</ScrollView>
: ''
}
</View>
)
}
})
}
</View>
)
}
LoadBiodtv = () =>{
let favoriteVideosIds = this.props.favorite.videos.map((v) => v.videoId);
let bidiotvfavourite = [].concat.apply([], bidiotvMovies.map((c) => c.videos)).filter((v) => {
if (~favoriteVideosIds.indexOf(v.id)) {
return v;
}
});
//console.log('bidiotvfavourite:', bidiotvfavourite.length)
return(
<View >
{!this.state.favoriteSwitch ?
bidiotvMovies.sort((a, b) => a.id > b.id).map((videos, key) => {
return (<View key = {key}>
<View style={{ height: 35, flexDirection: 'row', paddingTop: 5, paddingBottom: 5, paddingLeft: 10, paddingRight: 10, justifyContent: 'space-between', backgroundColor: 'black', alignItems: 'center' }}>
<View>
<Text numberOfLines={1} style={[styles.avRegular, liveChannelStyle.categoryName]}>
{videos.name}
</Text>
</View>
<TouchableOpacity onPress={this._onViewAllButtonPress.bind(this, videos.id, Globals.type === 'es' ? 'video' : 'channel')}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={[styles.avRegular, liveChannelStyle.browseAll]}>
{Globals.type === 'es' ? "Más" : 'More'}
</Text>
<FeatherIcon name='chevron-right' size={17} style={{ backgroundColor: 'transparent', paddingRight: 5, marginTop: 2 }} color='#d51a92' />
</View>
</TouchableOpacity>
</View>
{videos.videos?
<ScrollView showsHorizontalScrollIndicator={false} horizontal={true} >
<View style={{ flexDirection: 'row' }}>
{videos.videos.map((v, k) => {
return (
Globals.type === 'es' ?
<View style={liveChannelStyle.imageThmbnail}
key={k}>
<TouchableOpacity onPress={this._onPressButton.bind(this, {video: v})}>
<ImageBackground style={liveChannelStyle.imageBackground} resizeMode= 'stretch' source={v.preview}>
<TouchableOpacity style={liveChannelStyle.tvFavoriteBg} onPress={this._handleFavoriteClicked.bind(this, {video: v})}>
<View style={liveChannelStyle.tvFavoriteView}>
<Icon name='star' size={Globals.DeviceType === 'Phone' ? 15 : 20} style={{backgroundColor: 'transparent'}} color={this.isVideoFavorite(v.id) ? "#FFC107" : "#fff"}/>
</View>
</TouchableOpacity>
</ImageBackground>
</TouchableOpacity>
</View>
:
<View style={liveChannelStyle.tvThmbnail} key={k}>
<TouchableOpacity onPress={this._onPressButtonVODChannel.bind(this, {video: v})}>
<ImageBackground style={liveChannelStyle.tvImageBackground} resizeMode="stretch" source={v.preview}>
<View style={{flex: 1, backgroundColor: "rgba(0,0,0,.5)"}}>
<TouchableOpacity style={liveChannelStyle.tvFavoriteBg} onPress={this._handleFavoriteClicked.bind(this, {video: v})}>
<View style={liveChannelStyle.tvFavoriteView}>
<Icon name='star' size={Globals.DeviceType === 'Phone' ? 15 : 20} style={{ backgroundColor: 'transparent' }} color={this.isVideoFavorite(v.id)? "#FFC107" : "#fff"} />
</View>
</TouchableOpacity>
<View style={liveChannelStyle.videoTitleView}>
<Text numberOfLines={1} style={[styles.avRegular, liveChannelStyle.videoTitle]}>{v.name}</Text>
<View style={[liveChannelStyle.videoDurationView]}>
<Text style={[styles.avRegular, liveChannelStyle.videoDuration,{paddingBottom: 1}]}>1h 40m</Text>
</View>
</View>
</View>
</ImageBackground>
</TouchableOpacity>
</View>
)
},this)
}
</View>
</ScrollView>
: ''
}
</View>
)
})
:
bidiotvfavourite.length !==0 ?
bidiotvMovies.sort((a, b) => a.id > b.id).map((videos, key) => {
let packageVideos = videos.videos.filter((video) => {
if (~favoriteVideosIds.indexOf(video.id)) {
return video;
}
});
if (packageVideos.length > 0) {
return (
<View key = {key}>
<View style={{ height: 35, flexDirection: 'row', paddingTop: 5, paddingBottom: 5, paddingLeft: 10, paddingRight: 10, justifyContent: 'space-between', backgroundColor: 'black', alignItems: 'center' }}>
<View>
<Text numberOfLines={1} style={[styles.avRegular, liveChannelStyle.categoryName]}>
{videos.name}
</Text>
</View>
<TouchableOpacity onPress={this._onViewAllButtonPress.bind(this, videos.id, Globals.type === 'es' ? 'video' : 'channel')}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={[styles.avRegular, liveChannelStyle.browseAll]}>
{Globals.type === 'es' ? "Más" : 'More'}
</Text>
<FeatherIcon name='chevron-right' size={17} style={{ backgroundColor: 'transparent', paddingRight: 5, marginTop: 2 }} color='#d51a92' />
</View>
</TouchableOpacity>
</View>
{packageVideos?
<ScrollView showsHorizontalScrollIndicator={false} horizontal={true} >
<View style={{ flexDirection: 'row' }}>
{packageVideos.map((v, k) => {
//console_log(v.preview)
return (
Globals.type === 'es' ?
<View style={liveChannelStyle.imageThmbnail}
key={k}>
<TouchableOpacity onPress={this._onPressButton.bind(this, {video: v})}>
<ImageBackground style={liveChannelStyle.imageBackground} resizeMode= 'stretch' source={v.preview}>
<TouchableOpacity style={liveChannelStyle.tvFavoriteBg} onPress={this._handleFavoriteClicked.bind(this, {video: v})}>
<View style={liveChannelStyle.tvFavoriteView}>
<Icon name='star' size={Globals.DeviceType === 'Phone' ? 15 : 20} style={{backgroundColor: 'transparent'}} color={this.isVideoFavorite(v.id) ? "#FFC107" : "#fff"}/>
</View>
</TouchableOpacity>
</ImageBackground>
</TouchableOpacity>
</View>
:
<View style={liveChannelStyle.tvThmbnail} key={k}>
<TouchableOpacity onPress={this._onPressButtonVODChannel.bind(this, {video: v})}>
<ImageBackground style={liveChannelStyle.tvImageBackground} resizeMode="stretch" source={v.preview}>
<View style={{flex: 1, backgroundColor: "rgba(0,0,0,.5)"}}>
<TouchableOpacity style={liveChannelStyle.tvFavoriteBg} onPress={this._handleFavoriteClicked.bind(this, {video: v})}>
<View style={liveChannelStyle.tvFavoriteView}>
<Icon name='star' size={Globals.DeviceType === 'Phone' ? 15 : 20} style={{ backgroundColor: 'transparent' }} color={this.isVideoFavorite(v.id) ? "#FFC107" : "#fff"} />
</View>
</TouchableOpacity>
<View style={liveChannelStyle.videoTitleView}>
<Text numberOfLines={1} style={[styles.avRegular, liveChannelStyle.videoTitle]}>{v.name}</Text>
<View style={liveChannelStyle.videoDurationView}>
<Text style={[styles.avRegular, liveChannelStyle.videoDuration]}>1h 40m</Text>
</View>
</View>
</View>
</ImageBackground>
</TouchableOpacity>
</View>
)
},this)
}
</View>
</ScrollView>
: ''
}
</View>
)
}
}) : <View>
<View style={favoriteStyles.noChannelsViewTitle}>
<Text style={[styles.avRegular, favoriteStyles.noData]}>{Globals.type=== 'es' ? "Ningún video añadido para ver más tarde" : "No Videos Added To Favorites Yet"}</Text>
</View>
<View style={favoriteStyles.noChannelsViewDesc}>
<Text style={[styles.avRegular, favoriteStyles.noDataSubHeader]}>{Globals.type=== 'es' ? "Agrega tus videos favoritos para poder verlos fácilmente y sin problemas." : "Add your favorite videos to access and watch easily without any hassles."}</Text>
</View>
<TouchableHighlight onPress={()=> this.setState({ favoriteSwitch: false })} style={[favoriteStyles.exploreButtonView]}>
<View style={[favoriteStyles.exploreButton, {backgroundColor: "#e83e8c"}]}>
<Text style={[favoriteStyles.buttonText, styles.avRegular]}>
{Globals.type=== 'es' ? "Explora más videos" : "Explore Videos"}
</Text>
</View>
</TouchableHighlight>
</View>
}
</View>
)
}
render() {
let favoriteVideosIds = this.props.favorite.videos.map((v) => v.videoId);
return (
<Container >
<ImageBackground style={{ zIndex: 999 }}>
<Header
isDrawer={true}
isTitle= {Globals.url !== 'http://uk.mobiotv.com' ? true : false}
title='VOD'
isSearch={true}
showSearch={true}
rightLabel=''
/>
</ImageBackground>
<Loader visible={this.props.loader.isLoading}/>
{/*<Search from={"videos"}/>*/}
<View style={[VODStyle.contentView]}>
<MessageBar showMessage={this.state.showMessage} color={this.state.color} message={this.state.message}/>
<ScrollView bounces={false} keyboardShouldPersistTaps={'always'} keyboardDismissMode='on-drag'>
<View style={{flex: 1}}>
<View style={VODStyle.sliderView}>
<Slider text="Select your favorite show today!" isTvVideo={false}/>
</View>
<View>
<View style={{ height: 40, flexDirection: 'row', paddingTop: 10, paddingBottom: 5, paddingLeft: 10, paddingRight: 10, justifyContent: 'space-between', backgroundColor: 'black', alignItems: 'center' }}>
<View>
<Text style={[styles.avRegular, VODStyle.allCategory]}>
{Globals.type === 'es' ? "Todas las categorías" : 'All Categories'}
</Text>
</View>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={[styles.avRegular, VODStyle.favoriteSwitchText]}>
{Globals.type === 'es' ? "Favoritos" : 'Favorites'}
</Text>
<Switch style={{ transform: [{ scaleX: .85 }, { scaleY: .75 }] }} value={this.state.favoriteSwitch} onValueChange={this.switchFavorite} />
</View>
</View>
</View>
{ this.state.dataLoad ? this.LoadBiodtv() : null}
</View>
{/*<Footer />*/}
</ScrollView>
</View>
</Container>
);
}
}
const mapStateToProps = (state) => {
return {
accessToken: state.WelcomeReducer.token,
account: state.AccountReducer,
category: state.CategoryReducer,
country: state.CountryReducer,
domain: state.DomainReducer,
favorite: state.FavoriteReducer,
flashmessage: state.FlashMessageReducer,
historyVideos: state.HistoryReducer,
loader: state.ActivityIndicatorReducer,
play: state.PlayReducer,
smartTV: state.SmartTVReducer,
user: state.AuthenticationReducer
};
};
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({
show,
hide,
getVideoOrChannelRelatedData,
addFavoriteChannel,
addFavoriteVideo,
showMessage,
getDetails,
getInterests,
getVideosPackages,
getVideos,
getTVCategories,
getChannels,
addChannelHistory,
addVideoHistory,
addShowHistory,
addLikesChannels,
addLikesVideos
}, dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(VOD);
|
/**
* Created by Simon on 11-11-2014.
*/
$(function() {
var jsonData = [];
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "js/groups.json",
dataType: "json",
success: function( data ) {
jsonData = data;
for(i in jsonData) {
$('#researchGroup').append($("<option></option>")
.attr("value",i)
.text(jsonData[i].name));
}
},
error: function() {alert('it doesnt work')}
});
$('#researchGroup').change(function() {
$('p').text(jsonData[this.value].admin);
var selected = jsonData[this.value].members;
for(i in selected){
$('#members').append($("<option></option>")
.attr("value",i)
.text(selected[i]));
}
})
});
|
function html_encode(str) {
var s = "";
if (str.length == 0)
return "";
s = str.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/\'/g, "'");
s = s.replace(/\"/g, """);
return s;
}
KE.lang['code'] = "插入程序代码或脚本";
KE.plugin['code'] = {
click : function (id) {
KE.util.selection(id);
var dialog = new KE.dialog({
id : id,
cmd : 'code',
file : '../../../content/plugins/syntaxHighlighter/code.html',
width : 530,
height : 300,
title : KE.lang['code'],
yesButton : KE.lang['yes'],
noButton : KE.lang['no']
});
dialog.show();
},
check : function (id) {
var dialogDoc = KE.util.getIframeDoc(KE.g[id].dialog);
var lang = KE.$('ic_lang', dialogDoc).value;
var source = KE.$('ic_source', dialogDoc).value;
if (lang == '') {
alert('编程语言必须选择');
return false;
}
if (source == '') {
alert('请输入程序代码或者脚本');
return false;
}
return true;
},
exec : function (id) {
KE.util.select(id);
var iframeDoc = KE.g[id].iframeDoc;
var dialogDoc = KE.util.getIframeDoc(KE.g[id].dialog);
if (!this.check(id))
return false;
var lang = KE.$('ic_lang', dialogDoc).value;
var source = KE.$('ic_source', dialogDoc).value;
this.insert(id, lang, source);
},
insert : function (id, lang, source) {
var html = '<pre class="brush:' + lang + '; toolbar: true; auto-links: true;">';
html += html_encode(source);
html += '</pre>';
KE.util.insertHtml(id, html);
KE.layout.hide(id);
KE.util.focus(id);
document.getElementById("codeype").value = lang;
}
};
function loadEditor(id) {
KE.show({
id : id,
resizeMode : 1,
allowUpload : false,
urlType : 'absolute',
items : ['code', 'bold', 'italic', 'underline', 'strikethrough', 'textcolor', 'bgcolor', 'fontname', 'fontsize', 'removeformat', 'wordpaste', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'justifyleft', 'justifycenter', 'justifyright', 'link', 'unlink', 'image', 'flash', 'advtable', 'emoticons', 'source', '|', 'about']
});
}
|
/*global ODSA */
// Explain why sets top at position n-1.
$(document).ready(function() {
"use strict";
var av_name = "astackTopCON";
// Load the config object with interpreter and code created by odsaUtils.js
var config = ODSA.UTILS.loadConfig({av_name: av_name}),
interpret = config.interpreter; // get the interpreter
var av = new JSAV(av_name);
// Relative offsets
var leftMargin = 300;
var topMargin = 25;
var arr = av.ds.array([12, 45, 5, 81, "", "", "", ""],
{indexed: true, left: leftMargin, top: topMargin});
// Vertical arrows
var arrow1_x = leftMargin + 17;
var arrow1 = av.g.line(arrow1_x, topMargin - 5, arrow1_x, topMargin + 15,
{"arrow-end": "classic-wide-long",
opacity: 100, "stroke-width": 2});
var arrow2_x = leftMargin + 107;
var arrow2 = av.g.line(arrow2_x, topMargin - 5, arrow2_x, topMargin + 15,
{"arrow-end": "classic-wide-long",
opacity: 100, "stroke-width": 2});
arrow2.hide();
var arrow3_x = leftMargin + 77;
var arrow3 = av.g.line(arrow3_x, topMargin - 5, arrow3_x, topMargin + 15,
{"arrow-end": "classic-wide-long",
opacity: 100, "stroke-width": 2});
arrow3.hide();
// Array and label for "top" variable
var topArr = av.ds.array([0], {left: leftMargin - 100, top: topMargin});
av.label("top", {left: leftMargin - 130, top: topMargin + 5});
// Slide 1
av.umsg(interpret("sc1"));
arr.highlight(0);
arr.addClass([4, 5, 6, 7], "unused");
av.displayInit();
// Slide 2
av.umsg(interpret("sc2"));
arr.highlight([1, 2, 3]);
av.step();
// Slide 3
av.umsg(interpret("sc3"));
arr.unhighlight([0, 1, 2]);
arrow1.hide();
arrow2.show();
topArr.value(0, 3);
av.step();
// Slide 4
av.umsg(interpret("sc4"));
arr.value(3, "");
arr.addClass(3, "unused");
arr.unhighlight(3);
arrow2.hide();
arrow3.show();
topArr.value(0, 2);
av.step();
// Slide 5
av.umsg(interpret("sc5"));
arr.value(0, "");
arr.value(1, "");
arr.value(2, "");
arr.addClass([0, 1, 2], "unused");
arrow3.hide();
arrow1.show();
topArr.value(0, 0);
arr.highlight(0);
av.step();
// Slide 6
av.umsg(interpret("sc6"));
arr.unhighlight(0);
topArr.value(0, -1);
arr.unhighlight(0);
av.recorded();
});
|
const reverseString = require("./reverse");
test("is the functions working", () => {
expect(reverseString().toBeDefined());
});
|
/**
* Created by yonixee on 15/11/2.
*/
$(function() {
var formTmpl =
'<div><div class="wonuo-panel line">' +
'<h2>设置抢单时间</h2>' +
'<em>(选定时间后, 等待时间到达会自动完成下单)</em><br /><br />' +
'<input name="hour" type="number" class="input" min="0" max="23" value="22" />时' +
'<input name="minute" type="number" class="input" min="0" max="59" value="0" />分' +
'<input name="second" type="number" class="input" min="0" max="59" value="0" />秒' +
'</div><div class="display">双十一快到了, 插件君表示压力好大... ( >﹏< )</div>' +
'</div>';
var storage = window.sessionStorage;
var shopIdRegx = /view_shop\.htm\?.*user_number_id=(\d+)/;
function _getId(container, regx) {
var as = container.find('a.J_MakePoint');
for (var i = as.length; i--;) {
var m = regx.exec(as[i].href);
if (m) {
return m[1];
}
}
return null;
}
// 获取店铺id
function getShopId(shopContainer) {
return _getId(shopContainer, shopIdRegx);
}
var itemIdRegx = /item\.htm\?.*id=(\d+)/;
// 获取商品ID
function getItemId(container) {
return _getId(container, itemIdRegx);
}
var settingWindow = {
/**
* 初始化购物车
*/
initSelection: function() {
var self = this;
$('#content').css('position', 'relative');
var lop = lazyOperate(1500);
var _handle = function() {
var tag = this;
if (tag.tagName.toLowerCase() == 'input' ||
tag.className == 'J_CheckBoxItem') {
// 判断是否是勾选
if (this.checked) {
var result = self.selectItem(this.value);
}
else {
var result = self.unselectItem(this.value);
}
// 查看处理结果
if (result) {
lop.run(function() {
self.resetTimer();
});
}
}
};
this._refresh_checkbox_handle = setInterval(function() {
$('input.J_CheckBoxItem').each(function(i, e) {
if (e._change_handle) {
return;
}
e._change_handle = _handle;
$(e).change(_handle).change();
})
}, 500);
},
/**
* 清除各种选择事件
*/
destroySelection: function() {
// 剔除事件循环
clearInterval(this._refresh_checkbox_handle);
// 剔除所有安插的侦听器
$('input.J_CheckBoxItem').each(function(i, e) {
if (e._change_handle) {
$(e).unbind('change', e._change_handle);
delete e._change_handle;
}
});
// 移除接头暗号输入框
for (var k in this._shops) {
if (this._shops.hasOwnProperty(k)) {
this._shops[k].frame.remove();
}
}
},
/**
* 选择一件商品
* @param id
*/
selectItem: function(id) {
if (this._selectItems[id]) {
return false;
}
var el = $('#J_Item_' + id);
var shopContainer = el.parents('.order-content').parent();
var shopId = getShopId(shopContainer);
// 如果不存在指定商铺信息, 新建商铺信息
var shop = this._shops[shopId];
if (!shop) {
shop = this._shops[shopId] = {
id: shopId,
remark: null,
selItemsCount: 0,
frame: this.createRemarkFrame(shopContainer, function(remark) {
shop.remark = remark;
})
};
}
this._selectItems[id] = {
id: id,
itemId: getItemId(el),
shop: shop
};
shop.selItemsCount++;
this._selectCount++;
console.log(id, this._selectItems[id]);
return true;
},
/**
* 取消选择
* @param id
*/
unselectItem: function(id) {
if (!this._selectItems[id]) {
return false;
}
var item = this._selectItems[id];
// 检查店铺信息是否已经没有商品了, 如果是, 移除这个商铺信息
if (--item.shop.selItemsCount < 1) {
var shop = this._shops[item.shop.id];
shop.frame.remove();
delete this._shops[shop.id];
}
delete this._selectItems[id];
this._selectCount--;
return true;
},
/**
* 创建暗号输入框
* @param bundle
*/
createRemarkFrame: function(shopContainer, callback) {
var b = shopContainer[0];
var parent = b.offsetParent;
var frame = $('<div class="wonuo-remark"><label>接头暗号:</label><input class="input" type="text"></div>').appendTo(parent);
var input = frame.find('input');
var f = frame[0];
frame.css({
right: '5px',
top: (b.offsetTop + b.offsetHeight - f.offsetHeight - 5) + 'px'
});
input.change(function() {
callback && callback(this.value);
});
return frame;
},
/**
* 初始化时间控件
*/
initTimeInput: function() {
var self = this;
var lop = lazyOperate(1500);
this._window.find('input[type=number]').each(function(i, input) {
input.value = self._time[input.name];
}).blur(function() {
console.log('blur', this, this._beforeValue, this.value);
var input = this;
if (input._beforeValue != input.value) {
// 保证填写的值合法
var v = parseInt(input.value) || 0,
min = parseInt(input.min), max = parseInt(input.max);
input.value = self._time[input.name] = Math.min(Math.max(min, v), max);
}
// 设置完成后1.5秒后自动重新设置计时器
lop.run(function() {
self.resetTimer();
});
}).focus(function() {
console.log('focus', this);
lop.clear();
var input = this;
input._beforeValue = input.value;
// 当用户输入时间时, 停止计时器, 等待用户输入
self.stopTimer();
self.displayStatus('不急不急, 慢慢设置... <(▰˘◡˘▰)>');
});
},
/**
* 重置计时器
*/
resetTimer: function() {
this.stopTimer();
// 如果发现没有选择任何东西
if (this._selectCount < 1) {
this.displayStatus('你至少得勾选一件东西吧... (>_<)');
return;
}
var time = new Date(), now = new Date();
var t = this._time;
var self = this;
time.setHours(t.hour, t.minute, t.second, 0);
var d = time.getTime() - now.getTime();
// 如果选择时间小于当前时间, 就认为这是第二天的时间
if (d <= 0) {
d += 24 * 3600 * 1000;
}
// console.log('time:', time);
this.displayStatus('插件君已经打起了十二分精神! (^0_0^)');
//
this._timer_handle = setTimeout(function() {
self.submit();
}, d);
},
/**
* 停止计时器
*/
stopTimer: function() {
if (this._timer_handle) {
clearTimeout(this._timer_handle);
this._timer_handle = null;
}
},
/**
* 显示状态
*/
displayStatus: function(text) {
this._display.html(text);
},
/**
* 提交订单
*/
submit: function() {
console.log('start submit .......', new Date());
/* var arr = [];
for (var k in this._shops) {
if (this._shops.hasOwnProperty(k)) {
var s = this._shops[k];
arr.push({
id: s.id,
remark: s.remark
});
}
} */
chrome.storage.local.set({ shops: this._selectItems });
doClick('J_Go');
},
/**
* 进入启用状态
*/
enable: function() {
var content = $(formTmpl);
var self = this;
var disableBtn = $('<button class="close">X</button>').click(function() {
self.disable();
});
this._window.html(content);
this._window.append(disableBtn);
this._display = this._window.find('.display');
this._time = {
hour: 22,
minute: 10,
second: 10
};
// 已选中的商品
this._selectItems = {};
// 已选择的商品数量
this._selectCount = 0;
// 与已选中的商品相关的店铺信息
this._shops = {};
this.initSelection();
this.initTimeInput();
},
/**
* 进入禁用状态
*/
disable: function() {
var self = this;
this.destroySelection();
var enbaleBtn = $('<a href="javascript:;">抢</a>').click(function() {
self.enable();
});
this._window.html(enbaleBtn);
},
/**
* 初始化
*/
init: function() {
this._window = $('<div class="wonuo-swindow" />').appendTo(document.body);
this.disable();
}
};
settingWindow.init();
$(window).bind('unload', function() {
console.log('unload');
});
});
|
// Returns a function that calls the given method on the given instance.
function callback(instance, method) {
return function() {
method.apply(instance, arguments);
};
}
// Adds the given CSS class name to the given element.
function cssAddClass(element, className) {
cssClassManipulate(element, className, true);
}
// Removes the given CSS class name to the given element.
function cssRemoveClass(element, className) {
cssClassManipulate(element, className, false);
}
// Adds or removes the given CSS class name to the given element.
function cssClassManipulate(element, className, add) {
var classes = element.className.split(" ");
var newClasses = [];
for (var i = 0; i < classes.length; i++) {
if (classes[i] != className) {
newClasses.push(classes[i]);
}
}
if (add) {
newClasses.push(className);
}
element.className = newClasses.join(" ");
}
//Cancels the default action of the given event.
function cancelEvent(e) {
if (!e) e = window.event;
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );};
obj.attachEvent( 'on'+type, obj[type+fn] );
} else
obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
if ( obj.detachEvent ) {
obj.detachEvent( 'on'+type, obj[type+fn] );
obj[type+fn] = null;
} else
obj.removeEventListener( type, fn, false );
}
var Event = function(sender) {
this.sender = sender;
this.listeners = [];
};
Event.prototype = {
attach : function(listener) {
this.listeners.push(listener);
},
notify : function(args) {
for (var i = 0; i < this.listeners.length; i++) {
this.listeners[i](this.sender, args);
}
}
};
function swapProperties(o1, o2, prop) {
var temp;
temp = o1[prop];
o1[prop] = o2[prop];
o2[prop] = temp;
}
Array.prototype.contains = function(value) {
for(i=0, max=this.length; i<max; i++) {
if (this[i] == value) return true;
}
return false;
};
function extractNumber(value)
{
var n = parseInt(value);
return n == null || isNaN(n) ? 0 : n;
}
|
'use strict';
const imdb = require('../src/imdb');
const actor = 'nm0000243';
//DENZEL_IMDB_ID
require('../src/model');
var mongoose = require('mongoose'),
Movie = mongoose.model('Movie');
//GET movies/populate
exports.populate_the_db = async function(req, res){
const movies = await imdb(actor);
console.log(movies);
//Movie.save(movies);
Movie.insertMany(movies, function(err){
// Movie.save(movies, function(err){
if(err)
res.send(err);
res.json(movies);
});
//src/imdb.js
};
//movies .get
exports.must_watch_movies = function(req, res){
//const awesome = movies.filter(movie => movie.metascore >= 70);
Movie.find({}, function(err){
if(err)
res.send(err);
res.json(movies);
});
};
exports.list_all_movies = function(req, res) {
Movie.find({}, function(err, movie) {
if (err)
res.send(err);
res.json(movie);
});
};
// movies .post
exports.create_a_movie = function(req, res) {
var new_movie = new Movie(req.body);
new_movie.save(function(err, movie) {
if (err)
res.send(err);
res.json(movie);
});
};
// movies/:id .get
exports.read_a_movie = function(req, res) {
Movie.findById(req.params.id, function(err, movie) {
if (err)
res.send(err);
res.json(movie);
});
};
// movies/:id .put
exports.update_a_movie = function(req, res) {
Movie.findOneAndUpdate({_id: req.params.id}, req.body, {new: true}, function(err, movie) {
if (err)
res.send(err);
res.json(movie);
});
};
// movies/ : id .delete
exports.delete_a_movie = function(req, res) {
Movie.remove({
_id: req.params.id
}, function(err, movie) {
if (err)
res.send(err);
res.json({ message: 'Movie successfully deleted' });
});
};
//POST /movies/:id
//save a watched date and a review
//date - the watched date
//review - the personal review
exports.review_a_movie = function(req, res){
//Movie.
};
|
/*获取服务器时间*/
function getServerTime(){
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
xmlHttp.open("GET", window.location.href.toString(), false);
xmlHttp.setRequestHeader("Range", "bytes=-1");
xmlHttp.send(null);
var severtime=new Date(xmlHttp.getResponseHeader("Date"));
return severtime
}
|
let fields = {
FirstName: 'Cris',
LastName: 'Test',
Email: 'cris@spiralyze.com',
Phone: '1234567890',
Title: 'Tester',
Job_Role__c: 'Other',
Company: 'Spiralyze',
Country: 'Philippines',
Main_Product_Interest__c: 'Digital, Social'
};
let dropdowns = [
'Job_Role__c',
'Country',
'Main_Product_Interest__c'
];
function prefill() {
for (let property in fields) {
let element = document.getElementById(property);
console.log(property, element);
if (element) {
element.value = fields[property];
if (dropdowns.indexOf(property) >= 0) {
setTimeout(function () {
element.dispatchEvent(new Event('change'));
}, 500);
}
}
}
}
function waitForElement() {
let element = document.getElementById('FirstName');
console.log('Element', element);
if (element) {
prefill();
} else {
setTimeout(waitForElement, 100);
}
}
setTimeout(waitForElement, 100);
|
'use strict'
const path = require('path')
const config = {}
module.exports = function() {
// Already initialized, don't change
if ('rootdir' in config) return config
// Store app root directory
config.rootdir = __dirname
// Load custom config.json
try {
const cfgJson = require('fs').readFileSync('./data/config.json').toString()
const cfg = JSON.parse(cfgJson)
Object.assign(config, cfg)
}
catch(e) {
return config
}
// Additional global constants
config.QUEUE_LENGTH_HEADER = 'x-queue-length'
config.DIR_JOBS_PENDING = path.join(config.rootdir, '/data/jobs/pending')
config.DIR_JOBS_READY = path.join(config.rootdir, '/data/jobs/ready')
config.HOST_URL_READY = config.host_url+config.host_path_ready
config.CDB_COMPILER_DIR = path.join(config.rootdir, '../clouduboy-compiler')
config.CDB_PLATFORMS_DIR = path.join(config.rootdir, '../clouduboy-platforms')
return config
}
|
// Given 2 array, find if each element of first array has squared value in other array.
function isArraySame(arr1, arr2){ //[1,2,3] , [9,4,1]
if(arr1.length > arr2.length)
return false;
let result = true;
let frequencyCounter1 ={} ; frequencyCounter2 ={};
for(let val of arr1){
frequencyCounter1[val] = (frequencyCounter1[val] || 0) + 1; //{1:1,2:1,3:1}
}
for(let i=0; i< arr2.length; i++){
frequencyCounter2[arr2[i]] = (frequencyCounter2[arr2[i]] || 0) + 1; //{9:1,4:1,1:1}
}
console.log(frequencyCounter1, frequencyCounter2);
for(let key in frequencyCounter1){
if(!(key * key in frequencyCounter2))
return false
if(frequencyCounter1[key] !== frequencyCounter2[key* key])
return false;
}
return result;
}
//console.log(isArraySame([1,2,4],[9,4]))
//ANAGRAMS
function validAnagram(str1, str2){ //"iceman","cinema"
if(str1.length !== str2. length)
return false;
let frequencyCounter1 ={};
let frequencyCounter2={};
for(let i =0; i< str1.length; i++){
frequencyCounter1[str1[i]] = ++frequencyCounter1[str1[i]] || 0 ; // {i : 1, c :1, e:1, m:1, a:1, n:1}
frequencyCounter2[str2[i]] = ++frequencyCounter2[str2[i]] || 0; // {c:1, i:1, n:1, e:1, m:1, a:1}
}
for(let key in frequencyCounter1){
if(!frequencyCounter2.hasOwnProperty(key))
return false;
if(frequencyCounter1[key] !== frequencyCounter2[key])
return false;
}
return true;
}
// console.log(["iceman","cinema"],validAnagram("iceman","cinema"));
// console.log(['',''],validAnagram("",""));
// console.log(['aaz','zza'],validAnagram("aaz","zza"));
// console.log(["anagram","nagaram"],validAnagram("anagram","nagaram"));
// console.log(['rat','car'],validAnagram("rat","car"));
// console.log(['awesome','awesom'],validAnagram('awesome','awesom'));
// console.log(['querty','qeywrt'],validAnagram('querty','qeywrt'));
// console.log(['quertys','qeywrtm'],validAnagram('querty','qeywrt'));
//Hacker rank question //https://www.hackerrank.com/challenges/anagram/problem
function anagram1(s){ // bbxx xaxb
if(s.length % 2 !== 0)
return -1;
let result = 0;
let fc1 = {};
let lengthOfStr = s.length;;
for(let i=0; i< lengthOfStr/2;i++){
fc1[s[i]] = ++fc1[s[i]] || 1;
}
console.log(fc1);
for(let i=lengthOfStr/2; i< lengthOfStr ;i++){
if(fc1[s[i]])
--fc1[s[i]];
else
result++;
}
return result;
}
// for(let item of ["aaabbb","ab","abc","mnop","xyyx","xaxbbbxx"]){
// console.log(item, anagram(item));
// }
//https://www.hackerrank.com/challenges/making-anagrams/problem?h_r=next-challenge&h_v=zen
function anagram2(s1, s2){ // bbxx xaxb
let result = 0;
let fc1 = {};let fc2={};
for(let i=0; i< s1.length;i++){
fc1[s1[i]] = ++fc1[s1[i]] || 1; //{a:1,b:1,c:1}
}
for(let i=0; i< s2.length;i++){
fc2[s2[i]] = ++fc2[s2[i]] || 1; //{a:1,m:1,n:1,o:1, p:1}
}
console.log(fc1);
for(let key in fc1){
if(fc2[key]){
let diff = fc1[key] - fc2[key];
result += diff > 0 ? diff : diff*-1;
fc1[key] =0;
fc2[key] =0;
}
else
result += fc1[key];
}
for(let key in fc2){
if(fc2[key])
result += fc2[key];
}
return result;
}
//console.log(anagram2('cde','abc'));
function countPairs(arr) {
// Write your code here
// Write your code here
let result=0;
let arrPair =[];
let j =arr.length -1;
let obj = {};
for(let i=0; i < arr.length; i++){
while(j >i){
let item = arr[i] > arr[j] ? arr[i].toString() +"-"+ arr[j].toString() : arr[j].toString() +"-"+ arr[i].toString()
obj[item] = ++obj[item] || 1;
--j;
}
j = arr.length -1;
}
console.log(obj);
for(var key in obj){
let item = key.split('-');
let bitAnd = item[0] & item[1];
console.log(item, bitAnd)
while(bitAnd > 10){
bitAnd = bitAnd / 2;
}
if(bitAnd % 2 == 0 && bitAnd != 0){
let x = (bitAnd /2) % 2;
if(x == 0 || bitAnd == 2)
result += obj[key];
}
else if(bitAnd == 1)
result += obj[key];
}
// }
console.log(arrPair);
return result;
}
console.log(countPairs([1, 2, 1, 3]));
var arr = [1,2,3,4,5]
|
Tennisify.Views.NewUser = Backbone.ErrorView.extend({
template: JST['users/form'],
events: {
"click .create-user": "createUser"
},
className: "user-form .col-md-6 .col-md-offset-3",
tagName: "form",
createUser: function (event) {
event.preventDefault();
var attrs = $(event.delegateTarget).serializeJSON()["user"];
var user = new Tennisify.Models.User(attrs);
user.save({}, {
success: function (user) {
currentUser = user.id;
$('#modal').modal('toggle')
$(".create-meeting").removeClass("disabled");
$(".show-profile").removeClass("disabled");
Backbone.history.navigate("users/" + currentUser, {trigger: true});
},
error: function (user, errors) {
this.renderErrors(errors);
}.bind(this)
})
},
render: function () {
var content = this.template({
user: this.model,
title: "Sign Up",
submit: "Create Account"
});
this.$el.html(content);
return this;
},
});
|
import React from 'react';
import FancyBorder from "./FancyBorder";
import ErrorBoundary from "./ErrorBoundary";
import Dialog from "./Dialog";
function WelcomeDialog() {
throw "Error";
return (
<Dialog title="Welcome" description="Thank you for visiting our spacecraft!"/>
);
}
export default WelcomeDialog;
|
import React, { Component } from 'react';
import { Card, Button } from 'reactstrap';
import { faThumbsDown, faThumbsUp, faTrashAlt } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { isEmpty } from "../../tools";
import 'react-quill/dist/quill.snow.css';
class Comment extends Component {
constructor(props) {
if (props.comment !== null && typeof props.comment !== "undefined") {
let comment = props.comment;
super();
this.delete = props.delete;
this.state = {
id: isEmpty(comment.id, null),
likes: isEmpty(comment.likes, 0),
dislikes: isEmpty(comment.dislikes, 0),
content: isEmpty(comment.content, ""),
user: isEmpty(comment.user, ""),
}
}
}
render() {
return (
<Card className="m-2 p-3 border bg-light">
<div className="text-right">
<Button color="danger" size="sm"
onClick={() => this.delete(this.state.id)}>
<FontAwesomeIcon
values="test"
icon={faTrashAlt}
/> </Button>
</div>
<h4>{this.state.user}</h4>
<p dangerouslySetInnerHTML={{__html: this.state.content}} ></p>
<span className="m-2">
<span class="counters">
<i className="app-i mr-1 ml-1">{this.state.likes}</i>
<span >
<FontAwesomeIcon
onClick={() => { this.setState({ ...this.state, likes: isEmpty(this.state.likes, 0) + 1 }) }}
className="clickable"
values="test"
icon={faThumbsUp}
color="blue" />
</span>
</span>
<span class="counters">
<i className="app-i mr-1 ml-1">{this.state.dislikes}</i>
<FontAwesomeIcon
onClick={() => { this.setState({ ...this.state, dislikes: isEmpty(this.state.dislikes, 0) + 1 }) }}
className="clickable"
values="test"
icon={faThumbsDown}
color="red" />
</span>
</span>
</Card>
);
}
}
export default Comment;
|
function date_time(id) {
date = new Date;
year = date.getFullYear();
month = date.getMonth();
months = new Array('Jan', 'Febr', 'Mar', 'Apr', 'May', 'June', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
d = date.getDate();
day = date.getDay();
days = new Array('Sun', 'Mon', 'Tues', 'Wedn', 'Thur', 'Fri', 'Sat');
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}
result = ''+days[day]+' '+months[month]+' '+d+' '+year+' '+h+':'+m+':'+s;
jQuery(id).html(result);
setTimeout(function(){date_time(id)},'1000');
return true;
}
jQuery(document).ready(function(){
jQuery("#category img, #dashboard img").each(function(){
var showtext = jQuery(this).attr("alt");
jQuery(this).parent().hover(function(){
jQuery("div."+showtext.toLowerCase()).show();
},function(){
jQuery("div."+showtext.toLowerCase()).hide();
});
});
jQuery(".fancybox_dash").fancybox({
padding: [10,0,5,0],
openEffect: "elastic",
openSpeed: 250,
closeEffect: "elastic",
closeSpeed: 250,
closeClick: true,
helpers:{
title:{
type: 'float',// 'float', 'inside', 'outside' or 'over'
},
overlay : {
closeClick : true, // if true, fancyBox will be closed when user clicks on the overlay
speedOut : 200, // duration of fadeOut animation
showEarly : true, // indicates if should be opened immediately or wait until the content is ready
css : {
'background':'rgba(200,200,200,0.5)',
}, // custom CSS properties
locked : true // if true, the content will be locked into overlay
},
},
});
jQuery(".fancybox_new").fancybox({
openEffect: 'elastic',
openSpeed: 300,
closeEffect:'elastic',
closeSpeed:300,
closeClick:false,
helpers:{
overlay:{
closeClick:true,
speedOut:200,
showEarly: true,
css: {
'background':'rgba(200,200,200,0.5)',
},
locked: true
},
},
autoSize: false,
width: 600,
maxHeight:500,
beforeShow: function(){
initTinyMCE();
}
});
jQuery( '.navigation ul' ).lavaLamp({ startItem: 0 });
});
function initTinyMCE(){
tinymce.init({
selector:"#ar_text",
theme:"modern",
height:220,
plugins: [
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking save table contextmenu directionality",
"emoticons template paste textcolor openmanager"
],
toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media | forecolor backcolor emoticons | ibrowser",
theme_advanced_buttons3_add: "ibrowser",
image_advtab: true,
file_browser_callback: "openmanager",
open_manager_upload_path: '../../../../media/',
templates: [
{title: 'Test template 1', content: 'Test 1'},
{title: 'Test template 2', content: 'Test 2'}
],
theme_advanced_toolbar_location : "top"
});
}
|
import React, { useState, useEffect } from "react";
import { Route, Switch } from "react-router-dom";
import { CurrentUserContext } from "../../contexts/CurrentUserContext";
import { NewsContext } from "../../contexts/NewsContext";
import Header from "../Header/Header";
import Main from "../Main/Main";
import Footer from "../Footer/Footer";
import SavedNews from "../SavedNews/SavedNews";
import Login from "../Login";
import Register from "../Register";
import InfoTooltip from "../InfoTooltip";
import api from "../../utils/NewsApi";
import * as auth from "../../utils/MainApi";
import "./App.css";
import ProtectedRoute from "../ProtectedRoute";
import PreloaderXXL from "../PreloaderXXL/PreloaderXXL";
function App() {
// Хуки состояния at the top
// Авторизация:
const [currentUser, setCurrentUser] = useState({});
const [name, setName] = useState(null);
const [loggedIn, setLoggedIn] = useState(false);
// Поиск
const [isSearchStarted, setSearchStarted] = useState(false); // NewsList
const [isSubmitted, setIsSubmitted] = useState(false); // Preloader
const [cards, setCards] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
// Модальные окна:
const [isOpenLogin, setIsOpenLogin] = useState(false);
const [isOpenRegister, setIsOpenRegister] = useState(false);
const [isOpenPopupInfo, setIsOpenPopupInfo] = useState(false); // InfoTooltip
// Ошибки с сервера (валидация)
const [errorServerMessage, setErrorServerMessage] = useState("");
// Карточки //сохранение статеек в лк
const [savedNews, setSavedNews] = React.useState([]);
//Auth
async function getCurrentUser() {
try {
const userInfo = await auth.api.getUserData();
setCurrentUser(userInfo);
setName(userInfo.name);
} catch (err) {
console.log(`getCurrentUser ${err}`);
}
}
function handleLogin(email, password) {
setIsLoading(true);
auth
.authorize(email, password)
.then((res) => {
if (res.token) {
localStorage.setItem("jwt", res.token);
// console.log("Установил токен " + res.token);
auth.getUserInfo(res.token);
setLoggedIn(true);
closeAllPopups();
getSavedNews();
}
})
.catch((err) => {
if (err === 400) {
setErrorServerMessage("Не передано одно из полей");
} else if (err === 401) {
setErrorServerMessage("Неправильные почта или пароль");
}
setErrorServerMessage("Не удалось осуществить вход O_o");
setLoggedIn(false);
})
.finally(() => {
setIsLoading(false);
});
}
function handleRegister(email, password, name) {
setIsLoading(true);
auth
.register(email, password, name)
.then((res) => {
console.log(res); // при 400 приходит андеф, иначе мыло с _id
if (res.status !== 400) {
setIsOpenRegister(false);
setIsOpenPopupInfo(true);
}
})
.catch((err) => {
if (err.code === 400) {
setErrorServerMessage("Попробуйте ещё раз, " + err.message);
}
else if (err.code === 409) {
setErrorServerMessage("Такой user уже есть, " + err.message);
}
setErrorServerMessage("Регистрация не выполнена. Измените введенные данные"); // при регистрации не может быть 401
console.log(err)
})
.finally(() => {
setIsLoading(false);
});
}
function handleLogOut() {
setLoggedIn(false);
setName(null);
localStorage.clear();
setSearchStarted(false);
}
function tokenCheck() {
// для того чтобы не регаться каждый раз
const token = localStorage.getItem("jwt");
if (token) {
setIsLoading(true)
auth
.getUserInfo(token)
.then((res) => {
//res.json()
if (res) {
setLoggedIn(true);
setName(res.name);
setIsOpenLogin(false);
}
})
.catch((err) => {
console.log("Сервер не узнал токен при tokenCheck: " + err);
setLoggedIn(false);
setName("");
})
.finally(()=>(
setIsLoading(false)
));
} else {
setIsLoading(false)
console.log("Нет токена при tokenCheck: " + token);
}
}
useEffect(() => {
if (!loggedIn) {
tokenCheck();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (!loggedIn) return;
getCurrentUser();
getSavedNews(); // загрузка сохраненок
}, [loggedIn]);
useEffect(() => {
const localStorageNews = JSON.parse(localStorage.getItem("news"));
if (localStorageNews && localStorageNews.length) {
setCards(localStorageNews);
setSearchStarted(true);
}
}, []);
// Поиск
useEffect(() => {
if (isSubmitted) {
api
.search(searchQuery)
.then((data) => {
const news = data.articles.map((item) => ({
source: item.source.name,
title: item.title,
description: item.description,
url: item.url,
urlToImage: item.urlToImage,
publishedAt: item.publishedAt,
// author: item.author,
// content: item.content,
keyword: searchQuery,
}));
setCards(news);
localStorage.setItem("news", JSON.stringify(news));
setIsSubmitted(false);
setSearchQuery("");
setSearchStarted(true);
})
.catch((err) => alert("Ошибка поискового запроса"));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isSubmitted, searchQuery]);
const handleSubmit = () => {
setCards([]);
setIsSubmitted(true);
setSearchStarted(true);
};
// Модальные окна:
function closeAllPopups() {
setIsOpenLogin(false);
setIsOpenRegister(false);
setIsOpenPopupInfo(false);
}
// при нажатии на Авторизоваться
function handleOpenLogin() {
setIsOpenLogin(true);
setErrorServerMessage("");
}
function handleRedirect(evt) {
evt.preventDefault();
if (isOpenPopupInfo) {
setIsOpenPopupInfo(false);
handleOpenLogin();
} else {
if (isOpenLogin) {
setIsOpenLogin(false);
setIsOpenRegister(true);
setErrorServerMessage("");
} else {
setIsOpenRegister(false);
handleOpenLogin();
}
}
}
// Карточки //сохранение статеек в лк, вначале - новые.
function getSavedNews() {
auth.api
.getSavedNews()
.then(
(news) =>
setSavedNews(news.reverse())
)
.catch((err) => setErrorServerMessage(`Ошибка getSavedNews: ${err.message}`));
}
function handleBtnClick(article) {
if (!loggedIn) return handleOpenLogin();
const saved = savedNews.find(
(i) => i.publishedAt === article.publishedAt && i.title === article.title
);
if (!saved) {
auth.api
.saveArticle(article)
.then((newArticle) => setSavedNews([newArticle, ...savedNews]))
.catch((err) => setErrorServerMessage(`Ошибка handleBtnClick: ${err.message}`));
return;
}
handleDeleteArticle(saved);
}
function handleDeleteArticle(article) {
auth.api
.deleteArticle(article._id)
.then(() =>
setSavedNews(savedNews.filter((item) => item._id !== article._id))
)
.catch((err) => setErrorServerMessage(`Ошибка handleDeleteArticle: ${err}`));
}
if (isLoading) {
return <PreloaderXXL/>
}
return (
<CurrentUserContext.Provider value={currentUser}>
<NewsContext.Provider value={{ cards, savedNews }}>
<div className="app">
<Switch>
<Route exact path="/">
<Header
name={name}
loggedIn={loggedIn}
onLogIn={handleOpenLogin}
onSignOut={handleLogOut}
handleSubmit={handleSubmit}
searchQuery={searchQuery}
setSearchQuery={setSearchQuery}
isSubmitted={isSubmitted}
/>
<Main
isSearchStarted={isSearchStarted}
loggedIn={loggedIn}
isSubmitted={isSubmitted}
keyWord={searchQuery}
onBtnClick={handleBtnClick}
/>
</Route>
<ProtectedRoute
path="/saved-news"
loggedIn={loggedIn}
handleOpenLogin={handleOpenLogin}
isLoading = {isLoading}
>
<Header
name={name}
loggedIn={loggedIn}
onLogIn={handleOpenLogin}
onSignOut={handleLogOut}
handleSubmit={handleSubmit}
searchQuery={searchQuery}
setSearchQuery={setSearchQuery}
isSubmitted={isSubmitted}
/>
<SavedNews
loggedIn={loggedIn}
onBtnClick={handleBtnClick}
/>
</ProtectedRoute>
</Switch>
<Footer />
<Login
isOpen={isOpenLogin}
onClose={closeAllPopups}
onLogin={handleLogin}
loading={isLoading}
redirect={handleRedirect}
// setErrorServerMessage={setErrorServerMessage}
errorServerMessage={errorServerMessage}
/>
<Register
isOpen={isOpenRegister}
onClose={closeAllPopups}
redirect={handleRedirect}
onRegister={handleRegister}
loading={isLoading}
// setErrorServerMessage={setErrorServerMessage}
errorServerMessage={errorServerMessage}
/>
<InfoTooltip
isOpen={isOpenPopupInfo}
onClose={closeAllPopups}
redirect={handleRedirect}
/>
</div>
</NewsContext.Provider>
</CurrentUserContext.Provider>
);
}
export default App;
|
/*
* @lc app=leetcode.cn id=685 lang=javascript
*
* [685] 冗余连接 II
*/
// @lc code=start
/**
* @param {number[][]} edges
* @return {number[]}
*/
var findRedundantDirectedConnection = function (edges) {
const n = edges.length;
// 并查集
let vector = [];
// 初始化
const init = () => {
vector = new Array(n + 1).fill(0).map((item, index) => index)
}
// 并查集中寻找该节点的父节点
const find = (node) => {
if (vector[node] === node) {
return node;
} else {
return find(vector[node])
}
}
// 判断两个节点是否是同一个父节点
const same = (node1, node2) => {
const val1 = find(node1), val2 = find(node2);
return val1 === val2;
}
// 将node1 -> node2 将边加入并查集
const add = (parent, child) => {
const val1 = find(parent), val2 = find(child);
if (val1 === val2) return;
vector[child] = parent;
}
// 在第三种情况,有向图中寻找到闭环的边
const getRemoveEdge = () => {
init();
for (let i = 0; i < n; i++) {
if (same(edges[i][0], edges[i][1])) {
return edges[i];
}
add(edges[i][0], edges[i][1])
}
return [];
}
// 1. 遍历所有的节点,并记录节点的入度
const inDegree = new Array(n + 1).fill(0);
for (let i = 0; i < n; i++) {
inDegree[edges[i][1]]++;
}
// 2. 倒序遍历,记录所有入度为2的节点
const canDeleteNode = [];
for (let i = n - 1; i >= 0; i--) {
if (inDegree[edges[i][1]] === 2) {
canDeleteNode.push(i);
}
}
// 3. 删除边,看还是否能构成树,如果可以就直接返回
let ifDeleteNodeCanTree = (edges, node) => {
init();// 初始化并查集
for (let i = 0; i < n; i++) {
if (i == node) continue;
if (same(edges[i][0], edges[i][1])) {
return false;
}
add(edges[i][0], edges[i][1])
}
return true;
}
if (canDeleteNode.length > 0) {
if (ifDeleteNodeCanTree(edges, canDeleteNode[0])) {
return edges[canDeleteNode[0]]
} else {
return edges[canDeleteNode[1]]
}
}
return getRemoveEdge();
};
// @lc code=end
|
import React from 'react'
import { Spinner, Button, Container } from 'reactstrap'
import { useCreatedPhrases, useCreatedSentiments } from 'hooks/useEvents'
import { Phrase } from 'components/Phrase'
import { Sentiment } from 'components/Sentiment'
export default function Landing () {
const createdPhrases = useCreatedPhrases()
const createdSentiments = useCreatedSentiments()
if (createdPhrases == null || createdSentiments == null) { return <Spinner type="grow" color="secondary" /> }
return (
<Container className="bg-light border" style={{ padding: '30px' }}>
<h3 className="text-dark">Introduction</h3>
<div className="text-secondary" style={{ fontSize: '18px' }}>
<p>
Phrase is a content publishing platform that builds a meaningful
experience around direct funding. It does this by using a novel
feature called <i>value-backed sentiment.</i>
</p>
<p>
In the context of Phrase, the term <i>phrase</i> is used as an
umbrella descriptor for digital content. This includes:
</p>
<ul>
<li>Albums</li>
<li>Videos</li>
<li>Podcasts</li>
</ul>
<p>
And may also be extended to things like:
</p>
<ul>
<li>Political campaigns</li>
<li>Open-source projects</li>
</ul>
</div>
{ createdPhrases.length !== 0 &&
<>
<p>
<i>Here's an example of a phrase:</i>
</p>
<Phrase _key={ createdPhrases[0].phrase } />
</>
}
<br />
<div className="text-secondary" style={{ fontSize: '18px' }}>
<p>
Viewing phrases is free and you won't be pestered by ads here, but, if you
would like, you can send cryptocurrency directly to the creator by
purchasing a sentiment. If you do this, the sentiment will be dispayed
on your profile in association with the phrase and your profile will be
displayed on the phrase in association with the sentiment.
</p>
</div>
{ createdSentiments.length !== 0 &&
<>
<p>
<i>Here's an example of a sentiment:</i>
</p>
<Sentiment _key={ createdSentiments[0].sentiment } />
</>
}
<br />
<div className="text-secondary" style={{ fontSize: '18px' }}>
<p>
The phrases you create and sentiments you express coalesce on your
profile into something that demonstrates to people what it is you
find meaningful, and, of course, as a biproduct of this, you are
funding the work required to create meaningful things.
</p>
</div>
<br />
<Button color="primary" className="btn-lg">Get Started</Button>
</Container>
)
}
/*
export default function Landing () {
const createdPhrases = useCreatedPhrases()
if (createdPhrases == null) return <Spinner type="grow" color="secondary" />
const feed = creatorToPhrasesList(createdPhrases).map(creatorAndPhrases => {
return (
<div key={ `profileActivity-${creatorAndPhrases.creator}` } style={{ marginBottom: '5px' }}>
<ProfileActivity
profile={ creatorAndPhrases.creator }
createdPhrases={ creatorAndPhrases.phrases }
/>
</div>
)
})
return (
<>
<Subtle>----- New Phrases -----</Subtle>
{ feed }
</>
)
}
*/
|
app.factory('roomCrudAdminServ',function(restServ){return restServ.getCrud('/room/:id','ru');});
app.factory('roomTypeCrudAdminServ',function(restServ){return restServ.getCrud(
'/room/room_type',
{
getAll: {method: 'GET', isArray: true},
updateAll: {method: 'PUT', isArray: true}
}
);});
app.factory('roomAdminServ',function(roomCrudAdminServ,roomTypeCrudAdminServ,structureGetAdminServ,uiServ){
var structure = [];
var roomType = [];
return {
set: function(){structure = structureGetAdminServ.getAll(function(){
window.dirtyRoom = true;
uiServ.loader0hide();
});},
setType: function(){roomType = roomTypeCrudAdminServ.getAll();},
getOne: function(fixId){return roomCrudAdminServ.get({id: fixId}); },
get: function(){return structure;},
getType: function(){return roomType;},
update: function(room,fixId){
var self = this;
roomCrudAdminServ.update({id: fixId},room,function(){
$('#bems-admin-room-type-modal-success').modal('show');
self.set();
});
},
updateType: function(type){roomTypeCrudAdminServ.updateAll(type,function(){$('#bems-admin-room-modal-success').modal('show');});}
};
});
app.controller('roomAdminCtrl',function($scope,$interval,$timeout,roomAdminServ,Upload,constServ){
roomAdminServ.set();
$scope.data = roomAdminServ.get();
roomAdminServ.setType();
$scope.roomType = roomAdminServ.getType();
$scope.tOps = {nodeChildren: 'nodes'};
$scope.roomTab = true;
$scope.hideRoom = true;
window.dirtyRoom = false;
var intervalAdminRoom = $interval(function(){ if(window.dirtyRoom){
$scope.data = roomAdminServ.get();
window.dirtyRoom = false;
}},500);
$scope.$on('$destroy',function(){if(intervalAdminRoom) $interval.cancel(intervalAdminRoom);});
$scope.nocacheImg = function(src){return src+'?decache='+(new Date()).getTime();};
$scope.tabbing = function(bool){$scope.roomTab = bool;};
$scope.removeFile = function(){
$scope.roomFile = null;
$scope.roomText = "";
};
$scope.editRoom = function(id){
$scope.hideRoom = false;
$scope.idRoom = id;
$scope.detailRoom = roomAdminServ.getOne(id);
$scope.removeFile();
$('html,body').scrollTop(0);
};
$scope.update = function(room){
if(room.name.length !== 0) roomAdminServ.update(room,$scope.idRoom);
else $('#bems-admin-room-modal-alert').modal('show');
};
$scope.uploadFile = function(file,fixId){
file.upload = Upload.upload({
url: constServ.getUrl()+'/setting/image/room/'+fixId,
data: {image: file},
headers: {'token': sessionStorage.getItem('ustk')}
});
file.upload.then(function(response){ $timeout(function(){
$('#bems-admin-room-img-modal-success').modal('show');
});});
};
function checkRoomType(type){
for(var run in type) if(typeof type[run].name !== 'undefined') if(type[run].name.length === 0) return false;
return true;
}
$scope.updateType = function(type){
if(checkRoomType(type)) roomAdminServ.updateType(type);
else $('#bems-admin-room-type-modal-alert').modal('show');
};
});
|
import React from 'react';
import './Popup.css';
export const Popup = ({ children, handleShowPopup }) => {
return (
<div className="popup-wrapper">
<div className="popup-container">
<span className="close-icon" onClick={() => handleShowPopup(false)}>
X
</span>
<div className="content-container">{children}</div>
</div>
</div>
);
};
|
var largestRectangleArea = function(heights) {
if (heights == null || heights.length == 0) {
return 0;
}
let stack = [];
let max = 0;
let arrayCounter = 0;
while (arrayCounter < heights.length) {
// push index to stack when the current height is larger than the previous one
if (
stack.length == 0 ||
heights[arrayCounter] >= heights[stack[stack.length - 1]]
) {
stack.push(arrayCounter);
arrayCounter++;
} else {
// calculate max value when the current height is less than the previous one
let topStackElement = stack.pop();
let itemHeight = heights[topStackElement];
let wide =
stack.length == 0
? arrayCounter
: arrayCounter - stack[stack.length - 1] - 1;
let area = itemHeight * wide;
max = Math.max(area, max);
}
}
// for only ladder type (increasing-only) histograms.
while (stack.length > 0) {
let topStackElement = stack.pop();
let itemHeight = heights[topStackElement];
let wide =
stack.length == 0
? arrayCounter
: arrayCounter - stack[stack.length - 1] - 1;
let area = itemHeight * wide;
max = Math.max(area, max);
}
return max;
};
// 3
console.log(largestRectangleArea([2, 1, 2]));
// 4
console.log(largestRectangleArea([4, 2]));
// 1
console.log(largestRectangleArea([1]));
// 2
console.log(largestRectangleArea([1, 1]));
// 10
console.log(largestRectangleArea([2, 1, 5, 6, 2, 3]));
|
Ext.ux.customRecord = Ext.extend(Ext.data.Record,{
getRecord: function(type){
if (type == 'BRF' || type == 'BRFP')
{
return [
{ name: "id" },
{ name: "kode_brg" },
{ name: "nama_brg" },
{ name: "prj_kode" },
{ name: "sit_kode" },
{ name: "workid" },
{ name: "sequence" },
{ name: "requester" },
{ name: "trano" },
{ name: "trano_ref" },
{ name: "qty", type: 'float' },
{ name: "harga", type: 'float' },
{ name: "total", type: 'float' },
{ name: "val_kode" },
{ name: "original_qty", type: 'float' },
{ name: "original_harga", type: 'float' },
{ name: "original_total", type: 'float' },
{ name: "tgl" },
{ name: 'persen' }
];
}
},
initComponent: function() {
Ext.ux.customRecord.superclass.initComponent.call(this);
}
});
Ext.ux.customGrid = Ext.extend(Ext.grid.GridPanel,{
initColumns: function(type) {
if (type == 'BRF' || type == 'BRFP')
{
return [
new Ext.grid.RowNumberer({
width: 30
}),
this.rowactions,
{header: "Sequence",width: 80, dataIndex: 'sequence'},
{header: "Name",width: 150, dataIndex: 'nama_brg'},
{header: "Valuta",width: 40, dataIndex: 'val_kode'},
{header: "Ori. Total",width: 150, dataIndex: 'original_total',
renderer: function(v){
return v ? Ext.util.Format.number(v, '0,0.00') : '';
},
align:'right'
},
{header: "Percentage",width: 80, dataIndex: 'persen',
renderer: function(v, p, r){
// var p = (parseFloat(r.get("total")) / parseFloat(r.get("original_total"))) * 100;
// return p ? Ext.util.Format.number(p, '0,0.00') + "%" : '0 %';
var p = v;
return p ? Ext.util.Format.number(p, '0,0.00') + "%" : '0 %';
},
align:'right',
editor: {
xtype: 'numberfield',
allowBlank: false,
allowNegative: false,
enableKeyEvents: true,
listeners: {
'disable': function(txttext)
{
txttext.getEl().addClass('text-tebal');
}
}
}
},
{
header: "New Total",width: 150, dataIndex: 'harga',
editor: {
xtype: 'numberfield',
allowBlank: false,
allowNegative: false,
enableKeyEvents: true,
listeners: {
'disable': function(txttext)
{
txttext.getEl().addClass('text-tebal');
}
}
},renderer: function(v){
return v ? Ext.util.Format.number(v, '0,0.00') : '';
},
align:'right'
}
];
}
},
initAction: function(type){
var rowactions = null;
if (type == 'BRF' || type == 'BRFP')
{
rowactions = new Ext.ux.grid.RowActions({
actions:[
{
iconCls:'icon-edit',
qtip:'Edit',
id: 'edit'
}
]
,index: 'actions'
,header: ''
});
rowactions.on('action',function(grid,record,action,row,col){
if(action == 'icon-edit')
{
this.editor.startEditing(row,false);
}
},this);
}
return rowactions;
},
initEditor: function(type){
var editor = null;
if (type == 'BRF' || type == 'BRFP')
{
editor = new Ext.ux.grid.RowEditor({
saveText: 'Update',
clicksToEdit: ''
});
//Triggered after Update button is clicked, record not committed YET...
editor.on('stopedit', function(ed,fields,rec) {
if ((rec.data['qty'] > 0 && rec.data['harga'] > 0) && rec.data['original_qty'] > 0)
{
var totalEdited = parseFloat(rec.get("qty")) * parseFloat(rec.get("harga")),
totalOriginal = parseFloat(rec.get("original_total"));
if (moneycomp(totalEdited,'>',totalOriginal,2))
{
// Ext.each(fields, function (t, index){
// if (t.id == 'credit' || t.id == 'debit')
// {
// t.markInvalid('Debit or Credit field must be greater than 0!');
// }
// });
Ext.Msg.alert('Error','Total Edited is greater than Total Original<br>If You want to change this value greater than it\'s original, please Reject this BT to the Submitter for Editing.');
return false;
}
}
},this);
editor.on('afteredit', function(ed,obj,rec,index,fields){
var recs = this.store.getAt(index);
// var newTotal = parseFloat(recs.get("qty")) * parseFloat(recs.get("harga")),
// persen = (newTotal / parseFloat(recs.get("original_total"))) * 100;
var newTotal = recs.get("original_total");
ed.record.beginEdit();
if (obj.persen != undefined && obj.harga == undefined)
newTotal = (parseFloat(recs.get("persen")) / 100) * parseFloat(recs.get("original_total"));
else
{
newTotal = parseFloat(recs.get("qty")) * parseFloat(recs.get("harga"));
recs.data['persen'] = (newTotal / parseFloat(recs.get("original_total"))) * 100;
}
recs.data["total"] = parseFloat(recs.get("qty")) * newTotal;
recs.data["harga"] = newTotal;
ed.record.endEdit();
ed.record.commit();
},this);
editor.on('canceledit', function(roweditor, forced){
roweditor.record.cancelEdit();
},this);
}
return editor;
},
getStore: function()
{
return this.store;
},
loadData: function(json)
{
if (!json)
return false;
this.store.removeAll();
this.store.loadData(json);
this.getView().refresh();
},
initLoadData: function(type) {
if (type == 'BRF' || type == 'BRFP')
{
Ext.Ajax.request({
url: this.urlLoadData,
params: this.paramsLoadData,
method:'POST',
scope: this,
success: function(resp){
var returnData = Ext.util.JSON.decode(resp.responseText);
if (returnData.success)
{
var data = returnData.payment,i=0;
Ext.each(data,function(d){
data[i].original_qty = d.qty;
data[i].original_harga = d.harga;
data[i].original_total = d.total;
data[i].persen = (parseFloat(d.total) / parseFloat(data[i].original_total)) * 100;
i++;
});
this.loadData(data);
}
else
{
Ext.Msg.alert('Error', returnData.msg);
}
},
failure:function( action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Error!', obj.errors.reason);
}else{
Ext.Msg.alert('Warning!', 'Server is unreachable : ' + action.response.responseText);
}
}
});
}
},
getJSONFromStore: function()
{
var json = '';
if (this.store.getCount() > 0)
{
this.store.each(function(store){
var encode = Ext.util.JSON.encode(store.data);
if (encode != undefined)
json += encode + ',';
});
json = '[' + json.substring(0, json.length - 1) + ']';
}
return json;
},
initComponent : function() {
var cr = new Ext.ux.customRecord();
this.records = cr.getRecord(this.type);
this.store = new Ext.data.Store ({
reader:new Ext.data.JsonReader({
root: this.rootLoadData,
fields: this.records
})
});
var plugins = [];
this.editor = this.initEditor(this.type);
if (this.editor != null)
plugins.push(this.editor);
this.rowactions = this.initAction(this.type);
if (this.rowactions != null)
plugins.push(this.rowactions);
if (plugins.length > 0)
this.plugins = plugins;
this.columns = this.initColumns(this.type);
if (this.urlLoadData != undefined)
{
if (this.paramsLoadData == undefined)
this.paramsLoadData = {};
this.initLoadData(this.type);
}
Ext.ux.grid.gridJurnal.superclass.initComponent.call(this);
}
});
|
function unk(){
console.log('unk')
}
unk();
|
import products from './products.json';
/** True = 65%, False = 35% */
const rejectByChance = () => {
return Math.random() <= 0.35;
};
/** Emulate get request */
export const getProducts = ({ commit }) => new Promise((resolve, reject) => {
if (rejectByChance()) {
return reject({ error : 'something went wrong'});
}
const delay = parseInt(Math.random() * 1000);
setTimeout(() => {
resolve(products)
commit('GET_PRODUCTS', products)
}, delay);
});
/** Emulate delete request */
export const deleteProducts = ({ commit }, idArray) => new Promise((resolve, reject) => {
if (rejectByChance()) {
alert('Возникла ошибка, повторите действие еще раз')
return reject({
});
}
const delay = parseInt(Math.random() * 1000);
setTimeout(() => {
commit('DELETE_PRODUCTS', idArray);
resolve({ message: 'deleted' });
}, delay);
});
|
/*TMODJS:{"version":48,"md5":"78c4d2fef9a07acde72fc2265d97d414"}*/
define(function(require) {
return require("../template")("rec/list", function($data, $id) {
var $helpers = this, $each = $helpers.$each, data = $data.data, $value = $data.$value, $index = $data.$index, $escape = $helpers.$escape, $out = "";
$out += ' <section class="focus"> <div widget-role="focus-wrap" widget-width="540" widget-height="300" widget-scale="0.9" style="margin:0 auto"> <ul class="focus_wrap" widget-role="focus-data-wrap"> ';
$each(data.slide, function($value, $index) {
$out += ' <li><img src="';
$out += $escape($value.slide_pic);
$out += '" link="';
$out += $escape($value.slide_url);
$out += '"/></li> ';
});
$out += ' </ul> <div class="dot_wrap" widget-role="focus-dot-wrap"> </div> </div> </section> <div class="case main-list" sc="slide-wrap"> <div class="inner"> <div class="title-area clearfix"> <span class="fl">热门排行</span> <span class="fr" sc="slide" islide="yes">收起>></span> </div> <div class="content-area" sc="slide-content"> <ul class="clearfix"> ';
$each(data.goods_rank, function($value, $index) {
$out += ' <li class="clearfix"> <p class="fl"> <a href="';
$out += $escape($value.goods_url);
$out += '"><span class="mr_10">Top';
$out += $escape($index + 1);
$out += "</span>";
$out += $escape($value.goods_title);
$out += '</a> </p> <div class="fr"> <span class="small-fav-logo vt_m"></span> <span class="fav-num-text">';
$out += $escape($value.goods_likes);
$out += "</span> </div> </li> ";
});
$out += ' </ul> </div> </div> </div> <div class="match main-list" sc="slide-wrap"> <div class="inner"> <div class="title-area clearfix"> <span class="fl">优惠套餐</span> <span class="fr" sc="slide" islide="yes">收起>></span> </div> <div class="content-area" id="iscroll-wrap" sc="slide-content"> <ul class="clearfix" sc="roll-area"> ';
$each(data.packs, function($value, $index) {
$out += ' <li sc="roll-list" class="clearfix"> <img src="';
$out += $escape($value.pack_pic);
$out += '" width="60" height="40" class="fl mr_10"> <span class="fl mt_10"> <a href="';
$out += $escape($value.pack_url);
$out += '">';
$out += $escape($value.pack_title);
$out += '</a> </span> <span class="fr pink mt_10"> ¥';
$out += $escape($value.pack_price);
$out += ' <span class="gray2 thr ml_5">';
$out += $escape($value.all_price);
$out += "</span> </span> </li> ";
});
$out += ' </ul> </div> </div> </div> <div class="net main-list" sc="slide-wrap"> <div class="inner"> <div class="title-area clearfix"> <span class="fl">促销活动</span> <span class="fr" sc="slide" islide="yes">收起>></span> </div> <div class="content-area" sc="slide-content"> <ul class="clearfix"> ';
$each(data.acts, function($value, $index) {
$out += ' <li class="clearfix"> <span class="fl">';
$out += $escape($value.act_title);
$out += '</span> <a href="';
$out += $escape($value.act_url);
$out += '" class="fr">进入店铺</a> </li> ';
});
$out += " </ul> </div> </div> </div>";
return new String($out);
});
});
|
var app3 = new Vue({
delimiters: ['[[', ']]'],
el: '#app-3',
data: {
message: jsonObject[0],
beg: 0,
end: 23,
range: [0,1,2,3,4,5,6,7,8,9,10,11,12,13
,14,15,16,17,18,19,20,21,22,23]
},
methods: {
getData: function (i) {
this.message = jsonObject[i]
},
addRange: function() {
// jsonObject.length
if( this.end <= 8725-24){
this.beg += 24
this.end += 24
var list = [];
for (var i = this.beg; i <= this.end; i++) {
list.push(i);
}
this.range = list
}
},
removeRange: function() {
if(this.beg != 0){
this.beg -= 24
this.end -= 24
var list = [];
for (var i = this.beg; i <= this.end; i++) {
list.push(i);
}
this.range = list
}
}
}
})
|
function sortArray(array, order) {
return order == 'asc'
? array.sort((a, b) => a - b)
: array.sort((a, b) => b - a);
}
console.log(sortArray([14, 7, 17, 6, 8], 'asc'));
console.log(sortArray([14, 7, 17, 6, 8], 'desc'));
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "2c4526ed69bedd4b07581ba33a5ffb1b",
"url": "/goit-react-hw-02-phonebook/index.html"
},
{
"revision": "38b4ee5f8fe2f881f155",
"url": "/goit-react-hw-02-phonebook/static/css/2.764ccc25.chunk.css"
},
{
"revision": "c684afdfbb65d6b0ac41",
"url": "/goit-react-hw-02-phonebook/static/css/main.dfcaf89c.chunk.css"
},
{
"revision": "38b4ee5f8fe2f881f155",
"url": "/goit-react-hw-02-phonebook/static/js/2.d4ba3a1e.chunk.js"
},
{
"revision": "d705cb622423d72c5defbf368ca70dcc",
"url": "/goit-react-hw-02-phonebook/static/js/2.d4ba3a1e.chunk.js.LICENSE"
},
{
"revision": "c684afdfbb65d6b0ac41",
"url": "/goit-react-hw-02-phonebook/static/js/main.d101fa28.chunk.js"
},
{
"revision": "86e8f61da2e8edff8d43",
"url": "/goit-react-hw-02-phonebook/static/js/runtime-main.5b470970.js"
}
]);
|
var navs = [{
"title": "业务管理",
"icon": "fa-paper-plane-o",
"spread": true,
"children": [{
"title": "服务项目",
"icon": "fa-navicon",
"href": "yewumanage/serviceitems/index.html"
}, {
"title": "商家管理",
"icon": "fa-plane",
"href": "yewumanage/businessmanage/index.html"
}, {
"title": "工单管理",
"icon": "",
"href": "yewumanage/ordersmanage/index.html"
}]
}, {
"title": "订单管理",
"icon": "fa-folder-open-o",
"spread": false,
"children": [{
"title": "订单处理",
"icon": "",
"href": "ordersmanage/ordersHandle/index.html"
}, {
"title": "订单查询",
"icon": "",
"href": "ordersmanage/ordersQuery/index.html"
}]
}, {
"title": "运营管理",
"icon": "fa-shopping-bag",
"spread": false,
"children": [{
"title": "新闻管理",
"icon": "fa-newspaper-o",
"href": "operationmanage/newsManage/index.html"
}, {
"title": "互动管理",
"icon": "fa-group",
"href": "operationmanage/interactionManage/index.html"
}, {
"title": "banner管理",
"icon": "",
"href": "operationmanage/bannerManage/index.html"
}, {
"title": "二维码管理",
"icon": "fa-qrcode",
"href": "operationmanage/qrCodeManage/index.html"
}]
}, {
"title": "资源管理",
"icon": "",
"spread": false,
"children": [{
"title": "用户管理",
"icon": "",
"href": "resourcemanage/usermanage/index.html"
}, {
"title": "预约管理",
"icon": "",
"href": "resourcemanage/appointmentmanage/index.html"
}, {
"title": "通知管理",
"icon": "fa-volume-up",
"href": "resourcemanage/noticemanage/index.html"
}]
}, {
"title": "财务管理",
"icon": "fa-calculator",
"spread": false,
"children": [{
"title": "财务管理",
"icon": "",
"href": "financeManage/financeManage/index.html"
}, {
"title": "优惠券管理",
"icon": "fa-credit-card",
"href": "financeManage/couponManage/index.html"
}, {
"title": "积分管理",
"icon": "fa-star",
"href": "financeManage/pointsManage/index.html"
}]
}, {
"title": "系统管理",
"icon": "fa-dashboard",
"spread": false,
"children": [{
"title": "角色管理",
"icon": "fa-user-plus",
"href": "systemmanage/roleManage/index.html"
}, {
"title": "属性管理",
"icon": "fa-cube",
"href": "systemmanage/attrManage/index.html"
}, {
"title": "日志管理",
"icon": "fa-file-code-o",
"href": "systemmanage/logManage/index.html"
}, {
"title": "自定义步骤",
"icon": "fa-plus",
"href": "systemmanage/customStep/index.html"
}]
}];
|
import React, { Component } from 'react'
import './App.css'
import Title from './components/Title'
import Form from './components/Form'
export class App extends Component {
constructor(props) {
super(props)
this.state = {
items: [
{name: "Acheter le pain"},
{name: "Appeler Gilles"}
]
}
}
addItem = (todo) => {
this.setState(prevState => ({
items : [...prevState.items, todo]
}))
}
renderItems = () => {
return (
<ul style={{textAlign:'center', listStyle: 'none'}}>
{this.state.items.map(item =>
<li key={item.name}>{item.name}</li>
)}
</ul>
)
}
render() {
return (
<div>
<Title />
<Form addItem={this.addItem}/>
{this.renderItems()}
</div>
)
}
}
export default App
|
describe('common.js', function(){
var onSuccess = function(res){ console.log('onSucess', res) }
var onError = function(res){ console.log('onError', res) }
it('$NC 객체 초기화', function(){
//console.log($NC)
expect( typeof $NC ).toBe('object');
expect( $NC.G_USERINFO ).toBeNull();
//localStorage.setItem('_MOCK', true);
})
describe('가상 Ajax 설정', function(){
beforeEach(function(){
spyOn($, 'ajax').and.callFake(function (req) {
//console.info('서비스 호출')
req.success({}, '', {status:''});
req.complete();
return true
});
})
xit('비동기 통신: mockId가 있으면 가상데이터를 반환한다.', function(){
$NC.serviceCall("/WC/getSessionUserInfo.do", null, onSuccess, onError, {}, '7090E_RS_T1_MASTER');
expect().toBe();
})
xit('비동기 통신: mockId가 있으면 가상데이터를 반환한다.', function(){
$NC.serviceCall("/WC/getSessionUserInfo.do", null, onSuccess, onError, {}, 'commonGetSessionUserInfo');
var data = {P_QUERY_ID:'WC.GET_CSMSG'}
$NC.serviceCall('/WC/getDataSet.do', data, onSuccess, onError, {}, 'wcGetCsMsg');
var data = {P_QUERY_ID:'WC.POP_CSNOTICE'}
$NC.serviceCall('/WC/getDataSet.do', data, onSuccess, onError, {}, 'wcPopCsNotice');
expect().toBe();
})
xit('동기 통신: mockId가 있으면 가상데이터를 반환한다.', function(){
$NC.serviceCallAndWait("/WC/getSessionUserInfo.do", null, onSuccess, onError, {}, 'commonGetSessionUserInfo');
var data = {P_QUERY_ID:'WC.GET_CSMSG'}
$NC.serviceCallAndWait('/WC/getDataSet.do', data, onSuccess, onError, {}, 'wcGetCsMsg');
var data = {P_QUERY_ID:'WC.POP_CSNOTICE'}
$NC.serviceCallAndWait('/WC/getDataSet.do', data, onSuccess, onError, {}, 'wcPopCsNotice');
expect().toBe();
})
xit('비동기 통신: mockId가 없으면 실데이터를 반환한다.', function(){
$NC.serviceCall("/WC/getSessionUserInfo.do", null, onSuccess, onError, {});
expect().toBe();
})
xit('동기 통신: mockId가 없으면 실데이터를 반환한다.', function(){
$NC.serviceCallAndWait("/WC/getSessionUserInfo.do", null, onSuccess, onError, {});
expect().toBe();
})
})
describe('비밀번호 정책: $NC.varidationPw()', function(){
var userInfo
beforeEach(function(){
userInfo = {
USER_ID: 'WMS7',
USER_NM: 'WMS7'
}
window.alert = function(){}
})
it('비밀번호에 ID를 포함할수 없음', function(){
var pwObj = $NC.varidationPw('awms7', userInfo)
expect( pwObj ).toBeFalsy();
})
it('비밀번호는 8글자 이상이어야 함', function(){
var pwObj = $NC.varidationPw('qwer123', userInfo)
expect( pwObj ).toBeFalsy();
})
it('대문자, 소문자, 숫자, 특수문자조합이 2이면 10자리보다 많아야 한다.', function(){
var pwObj = $NC.varidationPw('qwer12efs', userInfo)
expect( pwObj ).toBeFalsy();
})
it('대문자, 소문자, 숫자, 특수문자조합이 3이면 8자리보다 많아야 한다.', function(){
var pwObj = $NC.varidationPw('qwer#13', userInfo)
expect( pwObj ).toBeFalsy();
})
it('동일숫자/문자 4개이상 사용불가', function(){
var pwObj = $NC.varidationPw('qwerasdf1234', userInfo)
expect( pwObj ).toBeFalsy();
var pwObj = $NC.varidationPw('qwerasdf4321', userInfo)
expect( pwObj ).toBeFalsy();
var pwObj = $NC.varidationPw('qwerasdfabcd', userInfo)
expect( pwObj ).toBeFalsy();
var pwObj = $NC.varidationPw('qwerasdfdcba', userInfo)
expect( pwObj ).toBeFalsy();
})
it('비밀번호 통과함', function(){
var pwObj = $NC.varidationPw('q1w2e3r4t5y6', userInfo)
expect( pwObj ).toBeTruthy();
})
})
describe('날짜 비교값 리턴: $NC.getDiffDate', function(){
beforeEach(function(){
})
it('현재시간과 초를 비교한다.', function(){
var addTime = moment().add(50, 's').format('YYYY-MM-DD HH:mm:ss')
var subTime = moment().subtract(50, 's').format('YYYY-MM-DD HH:mm:ss')
expect( $NC.getDiffDate(addTime, 'sec') ).toBe(49)
expect( $NC.getDiffDate(subTime, 'sec') ).toBe(-51)
})
it('현재시간과 분를 비교한다.', function(){
var addTime = moment().add(50, 'm').format('YYYY-MM-DD HH:mm:ss')
var subTime = moment().subtract(50, 'm').format('YYYY-MM-DD HH:mm:ss')
expect( $NC.getDiffDate(addTime, 'min') ).toBe(49)
expect( $NC.getDiffDate(subTime, 'min') ).toBe(-51)
})
it('현재시간과 시를 비교한다.', function(){
var addTime = moment().add(50, 'h').format('YYYY-MM-DD HH:mm:ss')
var subTime = moment().subtract(50, 'h').format('YYYY-MM-DD HH:mm:ss')
expect( $NC.getDiffDate(addTime, 'hour') ).toBe(49)
expect( $NC.getDiffDate(subTime, 'hour') ).toBe(-51)
})
it('현재시간과 날짜를 비교한다.', function(){
var addTime = moment().add(50, 'd').format('YYYY-MM-DD HH:mm:ss')
var subTime = moment().subtract(50, 'd').format('YYYY-MM-DD HH:mm:ss')
expect( $NC.getDiffDate(addTime, 'day') ).toBe(49)
expect( $NC.getDiffDate(subTime, 'day') ).toBe(-51)
})
it('현재시간과 월을 비교한다.', function(){
var addTime = moment().add(50, 'M').format('YYYY-MM-DD HH:mm:ss')
var subTime = moment().subtract(50, 'M').format('YYYY-MM-DD HH:mm:ss')
expect( $NC.getDiffDate(addTime, 'month') ).toBe(50)
expect( $NC.getDiffDate(subTime, 'month') ).toBe(-51)
})
it('현재시간과 년을 비교한다.', function(){
var addTime = moment().add(50, 'y').format('YYYY-MM-DD HH:mm:ss')
var subTime = moment().subtract(50, 'y').format('YYYY-MM-DD HH:mm:ss')
expect( $NC.getDiffDate(addTime, 'year') ).toBe(50)
expect( $NC.getDiffDate(subTime, 'year') ).toBe(-50)
})
})
describe('Ajax', function(){
onGetMaster = jasmine.createSpy();
onError = jasmine.createSpy();
beforeEach(function(){
spyOn($, 'ajax').and.callFake(function (req) {
//console.info('서비스 호출')
req.success({}, '', {status:''});
req.complete();
return true
});
})
xit('2중 호출 방지', function(){
var param = {
'queryId': ' LOM7010E.RS_MASTER',
'queryParams': {
'P_BU_CD': '5000',
'P_CENTER_CD': 'G1'
}
}
var param1 = {
'queryId': 'AAAAAAAAAAAAAAAAAAAAAAA'
}
$NC.serviceCall("/LOM7010E/getDataSet.do", param, onGetMaster, onError);
$NC.serviceCall("/LOM7010E/getDataSet.do", param, onGetMaster, onError);
$NC.serviceCall("/LOM7010E/getDataSet.do", param1, onGetMaster, onError);
expect(onGetMaster).toHaveBeenCalled()
})
})
})
|
var flickrApp = angular.module('flickrApp', []);
flickrApp.controller('flickrCtrl', function ($scope, $http) {
$scope.tag = "dogs";
$scope.newest = true;
$scope.quantity = 10;
$scope.page = 1;
$scope.search = function () {
$http.get('/Umbraco/Api/Images/GetJson?tag=' + $scope.tag).success(function (response) {
$scope.page = 1;
// cleanup Flickr Json response
response = response.replace('jsonFlickrFeed(', '');
response = response.replace('})', '}');
response = response.replace(/\\'/g, "'");
response = JSON.parse(response);
$scope.images = response.items;
});
};
$scope.search();
$scope.nextPage = function () {
$scope.page++;
var from = $scope.quantity * ($scope.page - 1);
var to = $scope.quantity * $scope.page;
$scope.images = $scope.images.splice(from, to);
}
$scope.toggle = function (property) {
$scope.newest = (property === 'date') ? !$scope.newest : $scope.newest;
}
});
|
import React, { PureComponent } from 'react';
import utils from '../../utils/utils';
/*
|--------------------------------------------------------------------------
| Header - PlayingBar
|--------------------------------------------------------------------------
*/
export default class TrackCover extends PureComponent {
static propTypes = {
path: React.PropTypes.string,
}
constructor(props) {
super(props);
this.state = {
coverPath: null,
};
this.fetchInitialCover = this.fetchInitialCover.bind(this);
}
render() {
if(this.state.coverPath) {
const coverPath = encodeURI(this.state.coverPath)
.replace(/'/g, '\\\'')
.replace(/"/g, '\\"');
const styles = { backgroundImage: `url('${coverPath}')` };
return <div className='cover' style={ styles } />;
}
return(
<div className='cover empty'>
<div className='note'>♪</div>
</div>
);
}
componentDidMount() {
this.fetchInitialCover();
}
async componentWillUpdate(nextProps) {
if(nextProps.path !== this.props.path) {
const coverPath = await utils.fetchCover(nextProps.path);
this.setState({ coverPath });
}
}
async fetchInitialCover() {
const coverPath = await utils.fetchCover(this.props.path);
this.setState({ coverPath });
}
}
|
var searchData=
[
['media_5froot',['MEDIA_ROOT',['../namespaceblogproj_1_1settings.html#a614b4b3b7f6280602a354734a9574444',1,'blogproj::settings']]],
['media_5furl',['MEDIA_URL',['../namespaceblogproj_1_1settings.html#abd9b885dfabb4265579418f19ccd4706',1,'blogproj::settings']]],
['middleware',['MIDDLEWARE',['../namespaceblogproj_1_1settings.html#afcde31515902a4a6de202e1343a9bcf5',1,'blogproj::settings']]]
];
|
(function() {
return function(req) {
return {
"links": [
{source:0,target:1},
{source:1,target:2},
{source:2,target:3},
{source:3,target:4},
{source:4,target:5},
{source:5,target:6}
],
"axisData": ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
"data": [872, 1190, 2192, 1513, 662, 4344, 6429]
}
}
})();
|
/*
Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
*/
let countBits = function(n) {
let ones = 0;
while (n !== 0) {
let remainder = n % 2;
if (remainder === 1) {
ones += 1;
}
n = Math.floor(n/2);
}
return ones;
};
|
import React from 'react';
import './SearchBar.css';
class SearchBar extends React.Component{
constructor(props){
super(props)
this.search=this.search.bind(this);
this.handleTermChange=this.handleTermChange.bind(this);
}
handleTermChange(e){
this.setState({searchTerm: e.target.value})
console.log(e.target.value)
}
search(){
//const search = e.target.value;
this.props.onSearch(this.state.searchTerm);
console.log(`searched: ${this.state.searchTerm}`)
}
render(){
return(
<div className="SearchBar">
<input onChange={this.handleTermChange} placeholder="Enter A Song, Album, or Artist"/>
<a onClick={this.search} >SEARCH</a>
</div>
)
}
}
export default SearchBar;
|
import React from 'react';
import unsplash from '../api/unsplash';
import SearchBar from './SearchBar';
import ImageList from './ImageList';
class App extends React.Component {
state = { images: [] };
onSearchSubmit = async (term) => {
const response = await unsplash.get('/search/photos', {
params: { query: term },
});
this.setState({ images: response.data.results });
};
render() {
return (
<div className="ui container" style={{ margin: '1rem' }}>
<SearchBar submit={this.onSearchSubmit} />
<ImageList images={this.state.images} />
</div>
);
}
}
export default App;
// **********************************************************************
// On jsx elements like form, input, button, etc, we need to use specific prop names like onSubmit, onClick, etc
// HOWEVER, on our own components like SearchBar, we name them whatever we want
// Passing a prop to a child component CLASS ----------------------
// Remember, we need to use that prop name on the child element
// props.onSubmit
// However, we need to use 'this' to access the props
// this.props.onSubmit
// Axios Vs Fetch ------------------------------------------------------
// axios: 3rd party package
// fetch: function built into modern browsers
// Fetch is a lower level function, may need to write more code
// Downloading axios:
// 1. end the session ^c
// 2. npm install --save axios
// 3. import axios from 'axios';
// Viewing Request Results --------------------------------------------
// 1. Look at api documentation
// - single page of photo requests: Get /search/photos
// 2. In axios, we do axios.get()
// - takes two arguements ('address', {object w/ customizations})
// - first: find location and add /search/photos
// - second: we need to identify ourselves to access it
// - find authorization and look how to identify
// 3. Inside the object, we need properties 'params' and 'headers'
// - Inside headers, we need an object with 'Authorization:' and our private key given from the api
// Handling Requests with Async Await -----------------------------------
// Method 1: Oromise-based syntax(harder)
// - When we make an axios request, it returns an obj called a promise
// - A prmise is an object that gives a us a notification when some amount of work is completed
// - in order to get a promise, we chain on a .then() function at the end of the axios call
// 1. attach a .then() function to the end of the axios.get function
// 2. place a callback function inside .then()
// - this will be called when the "job" is done
// 3. the callback will automatically be passed the information
// 4. Find the results you're looking for (response.data.results)
// .then((response) => {
// console.log(response.data.results);
// });
// Method 2: Async Await Syntax
// 1. place 'async' before our method (onSearchSubmit)
// - This allows us to use the async await syntax inside
// 2. In front of axios, place 'await' and assign it to a variable
// const response = await axios
// 2a. "Find whatever is returning/taking some time"
// - in this case its the network request
// Binding Callbacks ----------------------------------------------------
// - we had three options: binding, onSearchSubmit, making it an arrow function, or wrapping the callback 'submit={this.onSearchSubmit}' in an arrow function
// Refactoring async methods to an arrow function
// async methodName (arg) {}
// methodName = async (arg) => {}
|
P.common.traits.Mixin = function(Trait) {
var original_init = this.prototype.initialize,
events = this.prototype.events || {};
events = _.extend(events, Trait.events || {});
_.extend(this.prototype, Trait);
this.prototype.events = events;
if (_.isFunction(original_init) && _.isFunction(Trait.initialize)) {
this.prototype.initialize = function() {
var args = Array.prototype.slice.call(arguments);
original_init.apply(this, args);
Trait.initialize.apply(this, args);
};
}
return this;
};
|
var content = {
talkelgo: function () {
if (this.newcutscene("mission1")) {
state.done.knowwari = true
} else {
this.cutscene("healinfo")
}
},
talkwari: function () {
if (this.newcutscene("mission2")) {
state.jhang = 1
state.done.knowsemt = true
state.you.maxhp += 1
} else {
this.cutscene("wingusage")
}
},
talksemt: function () {
if (this.newcutscene("mission3")) {
state.canbuild = true
state.done.knowpald = true
state.you.maxhp += 1
} else {
this.cutscene("buildusage")
}
},
talkpald: function () {
if (this.newcutscene("mission4")) {
state.canwarp = true
state.done.knowlume = true
state.you.maxhp += 1
} else {
this.cutscene("warpusage")
}
},
talklume: function () {
if (this.newcutscene("mission5")) {
state.done.knowmian = true
state.done.knowlige = true
state.done.knowsank = true
state.you.maxhp += 1
state.njump += 1
} else if (!state.done.rescuelige) {
this.cutscene("tosavelige")
} else if (!state.done.rescuesank) {
this.cutscene("tosavesank")
} else if (!state.done.rescuemian) {
this.cutscene("tosavemian")
} else if (this.newcutscene("restoresun")) {
state.njump += 1
state.you.maxhp += 1
state.sun = true
state.gp += 999999999
} else {
this.cutscene("seeksart")
}
},
talklige: function () {
if (this.newcutscene("getinfolige")) {
state.you.maxhp += 1
state.jhang += 1
} else {
this.cutscene("complete")
}
},
talksank: function () {
if (this.newcutscene("getinfosank")) {
state.you.maxhp += 1
state.jhang += 1
} else {
this.cutscene("complete")
}
},
talkmian: function () {
if (this.newcutscene("getinfomian")) {
state.you.maxhp += 1
state.jhang += 1
} else {
this.cutscene("complete")
}
},
talksarf: function () {
UFX.scene.push("endscene")
},
cutscene: function (cname) {
UFX.scene.push("cutscene", cutscenes[cname])
},
newcutscene: function (cname) {
if (state.done[cname]) return false
state.done[cname] = true
UFX.scene.push("cutscene", cutscenes[cname])
return true
},
}
var HouseNames = {
elgo: "Eldar",
wari: "Avex",
semt: "Kraftin",
pald: "Zume",
lume: "Brite",
lige: "Mentix",
sank: "Querda",
mian: "Cogno",
sarf: "Nirva",
}
var cutscenes = {
mission1: [
"Apprentice, my time is short. My thoughts of late have turned to Heaven.",
"You've heard the story of Heaven, yes? But do you know what that word means?",
"What we know as Heaven is in fact the surface of this world, which our ancestors abandoned 100 generations ago.",
"There is a place beyond the darkness, a place that might still be there, but this fact seems to have been forgotten by our people.",
"Promise me that you will keep this knowledge alive.",
"Go to the House of Avex. There you will find a powerful tool.",
],
healinfo: [
"Remember, return to any House if you need to heal.",
],
mission2: [
"There was once a lamp brighter than anything you can imagine, called the Artifical Sun.",
"But sadly it broke many years ago, before you were born.",
"How I wish you could have seen the daylight....",
"Since the Sun disappeared, the creatures of the darkness have grown bolder.",
"Will you sojourn at the House of Kraftin? I have not heard from them in ages and I fear the worst.",
"Received Wings! You now slash when you jump. Hold Up while jumping to hover.",
],
wingusage: [
"Have you learned to use your wings?",
"Press Up near an enemy to slash it. Hold Up and you will hang in the air briefly.",
],
mission3: [
"Thank you! Never have these creatures attacked Houses before. This is cause for alarm!",
"Our shelters have served us well for many centuries, but they are finally decaying.",
"Our ancestors were builders, you know. Very little existed here before they came.",
"Although most of their technologies have been lost, I can teach you one.",
"Press and hold Space to create a platform. Use Arrow keys to place it.",
"Platforms cost " + settings.pcost + "GP each. If you run low, slay some monsters or visit any House.",
"Please visit the House of Zume. I believe your path lies there.",
],
buildusage: [
"Have you learned to build pathways?",
"Press and hold Space while standing on a platform.",
"Choose the placement with the arrow keys, then release Space to build.",
"What? You want to build a path to Heaven? No, it would never work.",
"These pathways cannot be built above 60 fathoms. Such technology is long lost, I'm afraid.",
],
mission4: [
"Wow, close one. I don't know how much longer we can last.",
"Look, I know that mentor of yours likes old stories of Heaven and salvation, but we have real problems to deal with.",
"Right now we need to turn the Sun back on, before these attacks destroy us.",
"Find the House of Brite and see what can be done, if it's not too late.",
"Got warp! Press Tab to warp between Houses you've visited.",
],
warpusage: [
"Press Tab at any time to warp to a random House that you've already visited.",
"Houses will refill your health and money (up to 20GP) and save your progress.",
],
mission5: [
"This is where we once controlled the Artificial Sun, but we have not seen daylight in many years.",
"I could repair it, I know, if only I had replacement parts....",
"The technology of our ancestors is thought to be lost, but it is simply scattered.",
"Perhaps if you visit the Houses of Mentix, Querda, and Cogno, you may find what I need.",
"Learned Double Jump! Tap Up twice.",
],
tosavelige: [
"Visit the Houses of Mentix, Querda, and Cogno to restore the Sun.",
"You still have not come back from Mentix.",
],
tosavesank: [
"Visit the Houses of Mentix, Querda, and Cogno to restore the Sun.",
"You still have not come back from Querda.",
],
tosavemian: [
"Visit the Houses of Mentix, Querda, and Cogno to restore the Sun.",
"You still have not come back from Cogno.",
],
getinfolige: [
"The House of Brite seeks to restore the Sun?",
"Their retroencabulator must be broken, please take this replacement!",
"Wings upgraded!",
],
getinfosank: [
"The House of Brite seeks to restore the Sun?",
"Their improbability drive must be broken, please take this replacement!",
"Wings upgraded!",
"Er.... I don't really know how to get out of here. Better press Tab.",
],
getinfomian: [
"The House of Brite seeks to restore the Sun?",
"Their flux capacitor must be broken, please take this replacement!",
"Wings upgraded!",
],
restoresun: [
"Amazing! With the parts you've collected, I think we may be able to restore the Sun....",
"....",
"Let there be light!",
"Got triple jump!",
"Got unlimited GP!",
],
seeksart: [
"Thanks to you, the light is restored.... for now.",
"You want to know if there is a path to Heaven? As in the actual Heaven?",
"Legend tells of one to the east, of course, but I'm sure it's long gone, if it ever existed.",
"Still....",
],
complete: [
"Good luck, young one.",
],
}
UFX.scenes.cutscene = {
start: function (texts) {
this.texts = texts.slice(0)
},
thinkargs: function (dt) {
return [dt, UFX.key.state()]
},
think: function (dt, kstate) {
if (kstate.down.space) {
this.texts.shift()
if (!this.texts.length) {
UFX.scene.pop()
playsound("powerup")
playmusic("song" + state.njump)
}
}
},
draw: function () {
UFX.scenes.play.draw()
UFX.draw("fs rgba(0,0,0,0.9) f0")
if (!this.texts[0]) return
UFX.draw("[ fs white sh #00A 1 1 0 font 40px~'Pirata~One' textalign center")
wordwrap(this.texts[0], 500, context).forEach(function (t, j, ts) {
context.fillText(t, canvas.width / 2, canvas.height / 2 + 50 * (j - ts.length / 2))
})
UFX.draw("]")
},
}
UFX.scenes.endscene = {
start: function (texts) {
this.texts = [
"Whoa, you okay? Did you just come out of that hole in the ground?",
"You having trouble seeing? It's just sunlight. Let's get you inside.",
"Now, how long have you been down there? Your whole life?!",
"What? Is this 'Heaven'? Yeah sure, whatever you want. Just sit tight for a minute.",
"How many of you people are underground? A whole race?! Holy smokes, what a find!",
"Hey, do you have an agent? Of course not, I'll be your agent. I'm your best friend, after all!",
"A race of subterranian people... hey, are you a cannibal? No? Okay, well, maybe we can say you are anyway.",
"I can see it now... front pages... talk shows... here we come!",
"Welcome to Heaven, kid, you're gonna love it!",
]
},
thinkargs: function (dt) {
return [dt, UFX.key.state()]
},
think: function (dt, kstate) {
if (kstate.down.space) {
this.texts.shift()
if (!this.texts.length) { UFX.scene.pop() ; UFX.scene.swap("reset") }
}
},
draw: function () {
UFX.scenes.play.draw()
UFX.draw("fs rgba(0,0,0,0.9) f0")
if (!this.texts[0]) return
UFX.draw("[ fs white sh #00A 1 1 0 font 40px~'Pirata~One' textalign center")
wordwrap(this.texts[0], 500, context).forEach(function (t, j, ts) {
context.fillText(t, canvas.width / 2, canvas.height / 2 + 50 * (j - ts.length / 2))
})
UFX.draw("]")
},
}
function wordwrap(text, twidth, con) {
con = con || context
twidth = twidth || con.canvas.width
var texts = [text], n = 0, s
while (con.measureText(texts[n]).width > twidth && (s = texts[n].indexOf(" ")) > -1) {
var t = texts[n], a = t.lastIndexOf(" ")
while (con.measureText(t.substr(0, a)).width > twidth && a > s) a = t.lastIndexOf(" ", a-1)
texts[n++] = t.substr(0, a)
texts.push(t.substr(a+1))
}
return texts
}
|
// - Создать произвольный елемент с id = text. Используя JavaScript, сделайте так, чтобы при клике на кнопку исчезал элемент с id="text".
let textID=document.getElementById('text');
textID.onclick=()=>{
textID.style.display='none';
}
// - Создайте кнопку, при клике на которую, она будет скрывать сама себя.
let btn=document.querySelector('#btn');
btn.onclick=()=>{
btn.style.display='none';
}
// - створити інпут який приймає вік людини та кнопку яка підтверджує дію.При натисканні на кнопку зчитати інформацію з інпуту та перевірити вік чи меньше він ніж 18, та повідомити про це користувача
let age = document.forms.formAge;
age.ageBtn.onclick=(ev)=>{
ev.preventDefault();
const input=age.ageUser.value;
age.ageUser.value='';
if (input<18) {
alert('Ви не можете знаходитися на цьому сайті!!!');
}
//console.log(input);
}
// - Создайте меню, которое раскрывается/сворачивается при клике
let menu=document.querySelector('#menu');
let title=menu.querySelector('#title');
menu.classList.add('inTitle');
title.onclick=()=>{
menu.classList.toggle('inTitle');
};
// - Создать список комментариев , пример объекта коментария - {title : 'lorem', body:'lorem ipsum dolo sit ameti'}.
let comments=[
{title : 'lorem', body:'lorem ipsum dolo sit ameti'},
{title : 'Создать', body:'Создать список комментариев , пример объекта коментария'},
{title : 'Вывести', body:'Вывести список комментариев в документ, каждый в своем блоке.'},
{title : 'Добавьте', body:'Добавьте каждому комментарию по кнопке для сворачивания его body.'}
]
// Вывести список комментариев в документ, каждый в своем блоке.
// Добавьте каждому комментарию по кнопке для сворачивания его body.
let listUl=document.createElement('ul');
for (const com of comments) {
let listLi=document.createElement('li');
let listH1=document.createElement('h1');
let listP=document.createElement('p');
listH1.innerHTML=com.title +'<button type="button">Згорнути</button>';
listP.innerHTML=com.body;
listP.classList.add('content');
listLi.appendChild(listH1);
listLi.appendChild(listP);
listUl.appendChild(listLi);
}
document.body.appendChild(listUl);
let contentP=document.querySelectorAll('ul p');
let btnList=document.querySelectorAll('ul button');
for (let i = 0; i < btnList.length; i++) {
btnList[i].onclick=()=>{
contentP[i].classList.toggle('content');
}
}
// - створити 2 форми по 2 інпути в кожній. ствоирити кнопку при кліку на яку считується та виводиться на консоль інформація з цих 2х форм.
// Кнопка повинна лежати за межами форм (Щоб ьуникнути перезавантаження сторінки)
// Доступ до інпутів через Forms API. Отже дайте формі та інпутам всі необхідні атрибути.
let forma1=document.createElement('form');
let forma2=document.createElement('form');
let input11=document.createElement('input');
let input12=document.createElement('input');
let input21=document.createElement('input');
let input22=document.createElement('input');
forma1.appendChild(input11);
forma1.appendChild(input12);
forma2.appendChild(input21);
forma2.appendChild(input22);
document.body.appendChild(forma1);
document.body.appendChild(forma2);
forma1.name="forma1";
forma2.name="forma2";
input11.type="text";
input11.name='someText11';
input12.type="text";
input12.name="someText12";
input21.type="text";
input21.name='someText21';
input22.type="text";
input22.name="someText22";
let btnInfo=document.createElement('button');
btnInfo.type="button";
btnInfo.id="btnInfo";
btnInfo.innerHTML='Зібрати всю інформацію';
document.body.appendChild(btnInfo);
let infoWithForm1= document.forms.forma1;
let infoWithForm2= document.forms.forma2;
let infoBtn=document.getElementById('btnInfo');
infoBtn.onclick=()=>{
let allInfo=[];
allInfo.push(infoWithForm1.someText11.value,infoWithForm1.someText12.value,infoWithForm2.someText21.value,infoWithForm2.someText22.value);
console.log(allInfo);
infoWithForm1.someText11.value='';
infoWithForm2.someText21.value='';
infoWithForm1.someText12.value='';
infoWithForm2.someText22.value='';
}
// - Створити функцію, яка генерує таблицю.
// Перший аргумент визначає кількість строк.
// Другий параметр визначає кліькіть ячеєк в кожній строці.
// Третій параметр визначає елемент в який потрібно таблицю додати.
function createTable(row,cell,tableElem,textInTable) {
for (let i = 0; i < row; i++) {
let rowTable=document.createElement('tr');
for (let j = 0; j < cell; j++) {
let cellTable=document.createElement('td');
cellTable.innerHTML=textInTable;
rowTable.appendChild(cellTable);
}
tableElem.appendChild(rowTable);
}
document.body.appendChild(tableElem);
}
let tableElem=document.createElement('table');
// - Створити 3 инпута та кнопку. Один визначає кількість рядків, другий - кількість ячеєк, третій вмиіст ячеєк.
// При натисканні кнопки, вся ця інформація зчитується і формується табличка, з відповідним вмістом.
// (Додатковачастина для завдання)
let myForm=document.createElement('form');
let numberRow=document.createElement('input');
let numberCol=document.createElement('input');
let textInTable=document.createElement('input');
let btnMyForm=document.createElement('input');
myForm.name="myForm";
numberRow.type="text";
numberRow.name='numberRow';
numberCol.type="text";
numberCol.name="numberCol";
textInTable.type="text";
textInTable.name='textInTable';
btnMyForm.type="submit";
btnMyForm.name="btnMyForm";
btnMyForm.value="OK";
myForm.appendChild(numberRow);
myForm.appendChild(numberCol);
myForm.appendChild(textInTable);
myForm.appendChild(btnMyForm);
document.body.appendChild(myForm);
btnMyForm.onclick=(ev)=>{
ev.preventDefault();
createTable(numberRow.value,numberCol.value,tableElem,textInTable.value);
numberRow.value='';
numberCol.value='';
textInTable.value='';
}
// - Напишите «Карусель» – ленту изображений, которую можно листать влево-вправо нажатием на стрелочки.
let divImg=document.createElement('div');
let image=document.createElement('img');
let btnImg1=document.createElement('button');
let btnImg2=document.createElement('button');
btnImg1.innerHTML='<-';
btnImg2.innerHTML='->';
divImg.appendChild(image);
divImg.appendChild(btnImg1);
divImg.appendChild(btnImg2);
document.body.appendChild(divImg);
let imgSrc=['homer.png','Marge.png','liza.png','bart.png','Maggie.png'];
let indexImg=0;
image.src=imgSrc[indexImg];
btnImg2.onclick=()=>{
if (indexImg+1>imgSrc.length-1) {
indexImg=0;
}else{
indexImg+=1;
}
image.src=imgSrc[indexImg];
}
btnImg1.onclick=()=>{
if (indexImg-1<0) {
indexImg=imgSrc.length-1;
}else{
indexImg-=1;
}
image.src=imgSrc[indexImg];
}
// - Сворити масив не цензцрних слів.
let wordNan=['Сворити', 'масив','не', 'цензурних','слів'];
// Сворити інпут текстового типу.
let formWord=document.createElement('form');
let textInput=document.createElement('input');
let submitInput=document.createElement('input');
formWord.name='formWord';
textInput.type="text";
textInput.name="textInput";
submitInput.type="submit";
submitInput.name="submitInput";
submitInput.value="Перевірити";
formWord.appendChild(textInput);
formWord.appendChild(submitInput);
document.body.appendChild(formWord);
// submitInput.onclick=(ev)=>{
// ev.preventDefault();
// if (wordNan.includes(textInput.value)) {
// alert('Так не можна!!!');
// }
// textInput.value='';
// }
// Якщо людина вводить слово і воно міститься в масиві не цензурних слів
// кинути алерт з попередженням.
// Перевірку робити при натисканні на кнопку
// - Сворити масив не цензцрних слів.
// Сворити інпут текстового типу.
// Потрібно перевіряти чи не містить ціле речення в собі погані слова.
// Кинути алерт з попередженням у випадку якщо містить.
// Перевірку робити при натисканні на кнопку
submitInput.onclick=(ev)=>{
ev.preventDefault();
for (const word of wordNan) {
if (textInput.value.includes(word)) {
alert('Так не можна!!!');
}
}
textInput.value='';
}
|
import { UPDATE_INIT_STATE } from "./actionTypes";
export const updateState = (state) => dispatch => {
alert();
dispatch({
type: UPDATE_INIT_STATE,
payload: state
});
}
|
import React from 'react';
import './style.css';
import Logo from './logozaltron.svg';
import { Link } from 'react-router-dom';
import GmailLogo from './gmailLogo.png';
function Header(props){
return(
<>
<div className="navContainer">
<Link to="/"><img src={Logo} alt="Zaltrons logo" className="logo"/></Link>
<div className="aboutMe headerElement">
<span role="img" aria-label="Black heart emoji. Click on it for a surprise." ><a target="_blank" rel="noopener noreferrer" href="https://www.youtube.com/watch?v=dQw4w9WgXcQ">🖤</a></span>
</div>
<a class="headerElement" target="_blank" rel="noopener noreferrer" href="mailto:zaltron.julian@gmail.com"><img src={GmailLogo} alt="Gmail logo" className="gmail"/></a>
</div>
</>
);
}
export default Header;
|
import React from "react";
function LogoMain() {
return <img className="logo-main" src="./image/prato.png" />;
}
export default LogoMain;
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjetSchema = new Schema(
{
typeObjetCd: {
type: String,
required: true,
max: 100,
},
libelle: {
type: String,
required: [true,'Le libelle est requis.'],
max:[15,'La longeur maximum du libellé ne doit pas dépasser 15 caractères.']
},
mqttId: {
type: String,
max: 7,
validate: {
validator: function(v) {
return /^[A-Z]{3}-[A-Z]{3}$/.test(v);
},
message: props => `${props.value} n'est pas un identifiant de connexion valide !`
},
required: [true, 'L\'identifiant de connexion est requis.']
},
code :{
type : String,
required: true,
max :100,
}
}
);
// // Virtual for author's full name
// AuthorSchema
// .virtual('name')
// .get(function () {
// return this.family_name + ', ' + this.first_name;
// });
// // Virtual for author's lifespan
// AuthorSchema
// .virtual('lifespan')
// .get(function () {
// return (this.date_of_death.getYear() - this.date_of_birth.getYear()).toString();
// });
// // Virtual for author's URL
// AuthorSchema
// .virtual('url')
// .get(function () {
// return '/catalog/author/' + this._id;
// });
//Export model
module.exports = mongoose.model('Objet', ObjetSchema);
|
// String, objetos, funções, números
// const names = new Array('Eduardo', 'João', 'Maria');
/* const names = ['Eduardo', 'João', 'Maria'];
const newName = [...names];
newName.pop();
console.log(names);
console.log(newName); */
/* names.unshift('Carlos')
names.unshift('Wallace')
names.shift
names.pop()
names.push() */
// const names = ['Eduardo', 'João', 'Maria', 'Wallace', 'Joana'];
// const newArray = names.slice(1, -2);
// console.log(newArray);
const nomes = [ 'Luiz', 'Otávio', 'Miranda' ];
const nome = nomes.join(' ');
console.log(nome);
|
const db = require('./db');
class Message {
async setup() {
try {
await db.query(
'CREATE TABLE message (id SERIAL PRIMARY KEY, text VARCHAR(1023) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);',
[],
);
return null;
} catch (err) {
return err;
}
}
async get({ id }) {
try {
const { rows } = await db.query('SELECT * FROM message WHERE id=$1;', [
id,
]);
return [rows[0], null];
} catch (err) {
return [null, err];
}
}
async getAll({ offset = 0, limit = 5000 }) {
try {
const { rows } = await db.query(
'SELECT * FROM message LIMIT $1 OFFSET $2',
[limit, offset],
);
return [rows, null];
} catch (err) {
return [null, err];
}
}
async create({ text }) {
try {
const { rows } = await db.query(
'INSERT INTO message (text) VALUES ($1) RETURNING id;',
[text],
);
return {
id: rows[0].id,
err: '',
};
} catch (err) {
return {
err,
};
}
}
}
module.exports = Message;
|
// Challenge 1 solution
export default function tobiesFriends(n, scores) {
//it doesnt say that i can't sort the array of scores so...
const scoresInOrder = [...scores].sort((a, b) => b - a);
let numberOfCalls = 0;
for(let i=0; i<= n ; i++) {
console.log(`Called ${scoresInOrder[i]}`)
scoresInOrder[i] = Math.min(...scoresInOrder)
for(let j=i+1; j <= n; j++) {
scoresInOrder[j]++;
}
numberOfCalls++;
}
return numberOfCalls; //this is the same as n as you only have to iterate over the sorted array to call of his friends, you could just return "n" if you only need this and don't actually need to modify the scores
}
|
let twelve = "12.956px";
console.log(parseInt(twelve)); //получаем целое число, остальное откидываем
console.log(parseFloat(twelve)); //получаем десятичное число, остальное откидываем
|
let api = {};
let contador = 2;
let clientes = [{ "_id": 1, "nome": "Raul", "sobrenome": "De melo", "apelido": "Heuhe", "telefone": "", "celular": "16 9999-9999", "email": "hue@hotmail.com" }];
api.lista = function (req, res) {
res.json(clientes);
console.log("lista");
};
api.buscaPorId = function (req, res) {
let id = req.params.id;
let cliente = clientes.find(function (cliente) {
return cliente._id == id;
});
if (!cliente) {
res.end("Cliente nao encontrado");
}
res.json(cliente);
};
api.removePorId = function (req, res) {
clientes = clientes.filter(function (cliente) {
return cliente._id != req.params.id;
});
res.sendStatus(204);
};
api.adiciona = function (req, res) {
console.log(req);
let cliente = req.body;
//cliente._id = ++contador;
clientes.push(cliente);
res.sendStatus(204);
console.log("Adiciona");
};
api.atualiza = function (req, res) {
var cliente = req.body;
var clienteId = req.params.id;
var indice = clientes.findIndex(function (cliente) {
return cliente._id == clienteId;
});
clientes[indice] = cliente;
res.sendStatus(200);
};
module.exports = api;
|
import React, { Component } from 'react';
import logo from './wolf.jpg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={wolf} className="App-wolf" alt="wolf" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
<p className="red">
loremgduuzedgzygchvevcuyfgouzvctvcuy
</p>
<br><br/>
<hr><hr/>
<p className="blue">
hfcbujhvcuqybscjyvshgvvloremgduuzedgzygchvevcuyfgouzvctvcuy
</p>
</div>
);
}
}
export default App;
|
import React from 'react';
import carouselImg1 from '../../../images/ship1.png';
import carouselImg2 from '../../../images/ship2.jpg';
import carouselImg3 from '../../../images/ship3.jpg';
import CarouselItem from '../CarouselItem/CarouselItem';
const carouselData = [
{
id: 1,
img: carouselImg1,
title: 'WELCOME',
desc: 'A B S M can guarantee exceptional ship support and superior ship owner\'s satisfaction.'
},
{
id: 2,
img: carouselImg2,
title: 'EXCEPTIONAL SERVICES',
desc: 'We offer second to none, very efficient, cost effective & round the clock quality services.'
},
{
id: 3,
img: carouselImg3,
title: 'ABOUT US',
desc: 'A B SHIP MANAGEMENT is one of the premier general ship supplying companies located in Bangladesh. The company was established in 2006 at the port of Chittagong & Mongla with Chittagong OPL in Bangladesh.'
}
]
const HeaderMain = () => {
return (
<div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-indicators">
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button>
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button>
</div>
<div class="carousel-inner">
{
carouselData.map(data => <CarouselItem key={data.id} data={data} />)
}
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
);
};
export default HeaderMain;
|
import React, { useEffect, useState } from 'react';
import Book from '../Book/Book';
import Header from '../Header/Header';
import './Home.css'
const Home = () => {
const [books, setBooks] = useState([]);
const [loading, setLoading] = useState(true);
useEffect((loading) => {
fetch('https://banana-tart-33572.herokuapp.com/books')
.then(res => res.json())
.then(data => {
setLoading(false);
setBooks(data)
})
}, [])
return (
<>
<Header></Header>
{
loading ? (
<div class="d-flex justify-content-center text-muted mt-5">
<div class="spinner-border" role="status">
<span class="sr-only ">Loading...</span>
</div>
</div>
) : (
<div className="home">
{
books.map(book => <Book book={book}></Book>)
}
</div>
)
}
</>
);
};
export default Home;
|
/**
* Created by Matas on 2017.08.08.
*/
// result button click event
// marks the selected result with a className 'y'
$('ol').click(function (e) {
if (e.target.tagName === 'BUTTON') {
var resultString;
const button = e.target;
const li = button.parentNode.parentNode;
const action = button.textContent;
const points = getDifficulty(button) * 10;
const selected = button.classList.contains('y');
const nameActions = {
Flash: function () {
if (!selected) {
if (button.nextElementSibling.classList.contains('y')) {
button.nextElementSibling.classList.remove('y');
score -= points;
}
button.classList.add('y');
score += points * 1.2;
resultString = resultReplace('F', getRouteNumber(li.id), result.value);
} else {
button.classList.remove('y');
score -= points * 1.2;
resultString = resultReplace('0', getRouteNumber(li.id), result.value);
}
},
Top: function () {
if (!selected) {
if (button.previousElementSibling.classList.contains('y')) {
button.previousElementSibling.classList.remove('y');
score -= points * 1.2;
}
button.classList.add('y');
score += points;
resultString = resultReplace('T', getRouteNumber(li.id), result.value);
} else {
button.classList.remove('y');
score -= points;
resultString = resultReplace('0', getRouteNumber(li.id), result.value);
}
},
"Special Challenge": function () {
if (!selected) {
button.classList.add('y');
score += points;
} else {
button.classList.remove('y');
score -= points;
}
}
}
nameActions[action]();
$('.score').html(scoreDisplay(score));
result.value = resultString;
total.value = score;
}
}); //end button click
// clear button click event
// clears everything
$('.clear').click(function() {
for (var i = 1; i <= numberOfRoutes; i++) {
var idName = (i < 10) ? 'no0' + i : 'no' + i;
var listButtons = document.getElementById(idName).firstElementChild.children;
if (listButtons[0].classList.contains('y')) {
listButtons[0].classList.remove('y');
} else if (listButtons[1].classList.contains('y')) {
listButtons[1].classList.remove('y');
}
}
result.value = standartResultString;
total.value = 0;
$('.score').html(scoreDisplay(score = 0));
}); //end clear click
// Hide button click event
// Hides column-route culumns
$('.hideBtn').click(function (e) {
var button = e.target;
if (!button.classList.contains('hidden')) {
for (var i = 0; i < $('.column-route').length; i++) {
$('.column-route')[i].classList.add('hide');
}
for (var i = 0; i < $('.column-chal').length; i++) {
$('.column-chal')[i].classList.add('hide');
}
button.classList.add('hidden')
} else {
for (var i = 0; i < $('.column-route').length; i++) {
$('.column-route')[i].classList.remove('hide');
}
for (var i = 0; i < $('.column-chal').length; i++) {
$('.column-chal')[i].classList.remove('hide');
}
button.classList.remove('hidden')
}
}); //End hide click
// Export button click event
// Download results file in .xls
$("#btnExport").click(function(e) {
e.preventDefault();
//getting data from our table
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('table_wrapper');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
var a = document.createElement('a');
a.href = data_type + ', ' + table_html;
a.download = json.name + '_' + json.date + '.xls';
a.click();
}); //end Export click
|
import React from 'react';
import {Link,Route} from 'react-router-dom'
import Axios from 'axios';
let style = {
linkStyle:{
textDecoration:"none",
display: "inline-block",
marginRight: "10px",
height: "50px",
lineHeight: "50px",
}
}
export default class Header extends React.Component{
constructor(props){
super(props);
this.state = {
user:null,
isLogined:false
}
}
componentWillMount(){
var userJson = sessionStorage.getItem("user");
if(userJson){
this.setState({user:JSON.parse(userJson)});
}
else {
this.setState({user:null});
}
}
goLogin(){
this.props.history.push("/login");
}
logOut(){
Axios.get("/api/user/logout",{
withCredentials: true
}).then((result)=>{
}).catch((err)=>{
console.log(err);
})
}
render(){
return(
<div className="blog_header">
<div className="blog_logo">LOGO</div>
<div className="blog_nav">
{
this.state.user == null ?
(
<ul>
<li onClick={this.goLogin.bind(this)}>登陆/注册</li>
</ul>
):
(
<div>
<div>
<Link to="home/newArticle">写文章</Link>
</div>
<div className="blog_user_label">
{"欢迎您!"+this.state.user.userName}
<span><a href="javascript:void(0)" onClick={this.logOut.bind(this)}>退出</a></span>
</div>
</div>
)
}
</div>
</div>
)
}
}
class DynamicUserState extends React.Component{
constructor(){
super();
}
render(){
return(
<div>
</div>
);
}
}
|
import React from 'react'
class User extends React.Component {
render() {
console.log(this.props.match)
return <h1>Users Users Users Users Users Users Users Users Users Users Users Users</h1>
}
}
export default User
|
import React, {Component, Fragment} from 'react';
import {Layout, Row, Col, Carousel, List, Breadcrumb, BackTop, } from 'antd';
import {Link} from "react-router-dom";
import {Style} from './style';
const {
Footer, Content
} = Layout;
const data1 = [
'列表法',
'作图法',
'逐差法',
'回归法',
'最小二乘法',
// '误差分析法'
'XXXXXX'
];
const data2 = [
'方差工具',
// '标准差工具',
// '方差工具',
// '进制转换工具',
// '光学相关查询工具',
// '误差分析'
'XXXXXX',
'XXXXXX',
'XXXXXX',
'XXXXXX',
'XXXXXX'
];
const data3 = [
'牛顿环法测透镜曲率半径',
'迈克尔逊干涉仪',
'杨氏静态模量实验',
'分光计的调整和使用',
'衍射光栅实验',
'热导率的测量'
];
const data4 = [
// '塞曼效应',
// '光电效应法测定普朗克常量',
// '光强分布的测量',
// '电位差计的使用',
// '液体黏性系数的测量',
// '铁磁材料磁滞回线的测绘',
'XXXXXX',
'XXXXXX',
'XXXXXX',
'XXXXXX',
'XXXXXX',
'XXXXXX'
];
class Home extends Component {
render() {
return (
<Fragment>
<Style>
<Row>
<Col span={24}>
<Layout className="layout">
<Content style={{padding: '0 50px'}}>
<Breadcrumb style={{margin: '16px 0'}}>
<Breadcrumb.Item>
<span className="iconfont"
style={{fontSize: '18px'}}> 欢迎来到物理实验数据处理平台</span>
</Breadcrumb.Item>
</Breadcrumb>
<div style={{background: '#fff', paddingTop: 15,paddingLeft:10,paddingRight:10,paddingBottom:50, minHeight: 550}}>
<Carousel autoplay>
<div><h1>物理实验就是人类追寻科学的印迹</h1></div>
<div><h1>人们在不断的科学试验中不断总结</h1></div>
<div><h1>在大学物理实验中学习前人智慧</h1></div>
<div><h1>从纷繁的实验现象中发现简单规律</h1></div>
</Carousel>
<hr/>
<Row>
<Col xs={24} sm={12} xl={6}>
<List
className='list'
header={<h2>数据处理方法</h2>}
bordered
dataSource={data1}
renderItem={(item,index) => (<List.Item className='list'><Link id='link' to={'/dataHandle/'+index}><span>{item}</span></Link></List.Item>)}
/>
</Col>
<Col xs={24} sm={12} xl={6}>
<List
className='list'
header={<h2>通用工具</h2>}
bordered
dataSource={data2}
renderItem={(item,index)=> (<List.Item className='list'><Link id='link' to={'/generalTools/'+index}><span>{item}</span></Link></List.Item>)}
/>
</Col>
<Col xs={24} sm={12} xl={6}>
<List
className='list'
header={<h2>实验项目A</h2>}
bordered
dataSource={data3}
renderItem={(item,index) => (<List.Item className='list'>
<Link id='link' to={'/physicalExperiment/'+index}><span>{item}</span></Link>
</List.Item>)}
/>
</Col>
<Col xs={24} sm={12} xl={6}>
<List
className='list'
header={<h2>实验项目B</h2>}
bordered
dataSource={data4}
renderItem={item => (<List.Item className='list'><Link id='link' to={'/detail/1'}><span>{item}</span></Link></List.Item>)}
/>
</Col>
</Row>
</div>
</Content>
<Footer style={{textAlign: 'center'}}>
Ant Design ©2019 Created by Junking
</Footer>
</Layout>
</Col>
</Row>
<BackTop visibilityHeight={50}/>
</Style>
</Fragment>
)
}
}
export default Home;
|
var DeleteFolderView = Backbone.View.extend({
initialize: function (options) {
_.bindAll(this, "render");
this.applicationState = options.applicationState;
},
className: "delete-folder-modal",
template: Handlebars.compile($("#delete-folder-template").html()),
events: {
"click .delete-button": "delete",
"click .cancel-button": "cancel"
},
delete: function () {
// Destroy the folder and remove from collection.
this.model.destroy();
this.model.collection.remove(this.model);
// If the folder or a child list is the current view, then return to inbox.
var applicationState = this.applicationState;
var returnToInbox = false;
var folderID = this.model.get("id");
if (applicationState.folderSelected(folderID))
returnToInbox = true;
this.model.get("taskLists").each (function (taskList) {
if (applicationState.listSelected(taskList.get("id")))
returnToInbox = true;
});
if (returnToInbox)
window.router.navigate("inbox", true);
// Close the modal.
$.modal.close();
},
cancel: function () {
$.modal.close();
},
render: function () {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
|
import React from "react";
import styled from "styled-components";
import Grid from "../components/Grid";
import Headline from "../components/Headline";
import MenuCard from "../components/MenuCard";
import HeaderData from "../components/ShowDataHeader";
const Main = styled.div`
display: flex;
flex-direction: row;
justify-content: space-evenly;
align-items: center;
flex-wrap: wrap;
max-width: 500px;
`;
const StyledBody = styled.div`
display: flex;
flex-direction: column;
align-items: center;
`;
function Menu({ history }) {
return (
<Grid type="main">
<HeaderData
title="Menu"
button="button"
direction="/"
history={history}
/>
<Headline size="L">Information</Headline>
<StyledBody>
<Main>
<MenuCard
icon="fa-home"
title="Family"
direction="familyData"
history={history}
/>
<MenuCard
icon="fa-child"
title="Children"
direction="childrenDataInput"
history={history}
/>
<MenuCard
icon="fa-first-aid"
title="Medical"
direction="medicalDataInput"
history={history}
/>
<MenuCard
icon="fa-utensils"
title="Food"
direction="foodDataInput"
history={history}
/>
<MenuCard
icon="fa-tshirt"
title="Clothing"
direction="clothingDataInput"
history={history}
/>
<MenuCard
icon="fa-address-book"
title="Contacts"
direction="contactsDataInput"
history={history}
/>
</Main>
</StyledBody>
</Grid>
);
}
export default Menu;
/*
<Headline size="L">Other functions</Headline>
<Main>
<MenuCard
icon="fa-baby-carriage"
title="Babysitter"
direction="generalData"
history={history}
/>
</Main>
*/
|
var HOME = BASE_URL + 'user_pwd/';
var pwd_error = 1;
var cpwd_error = 1;
function changePassword() {
var uid = $('#uid').val();
var user_id = $('#user_id').val();
var cpwd = $('#cpwd').val(); //--- current pwd
var pwd = $('#pwd').val(); //--- new pwd
var cfpwd = $('#cfpwd').val();
if(cpwd.length === 0) {
set_error($('#cpwd'), $('#cpwd-error'), "Required");
return false;
}
else {
clear_error($('#cpwd'), $('#cpwd-error'));
}
if(pwd.length === 0) {
set_error($('#pwd'), $('#pwd-error'), "Required");
return false;
}
else {
clear_error($('#pwd'), $('#pwd-error'));
}
if(cfpwd !== pwd) {
set_error($('#cfpwd'), $('#cfpwd-error'), "Password Mismatch");
return false;
}
else {
clear_error($('#cfpwd'), $('#cfpwd-error'));
}
$.ajax({
url:HOME + 'verify_password',
type:'POST',
cache:false,
data:{
'uid' : uid,
'pwd' : cpwd
},
success:function(rs) {
var rs = $.trim(rs);
if(rs === 'success') {
var user_id = $('#user_id').val();
$.ajax({
url:HOME + 'change_password',
type:'POST',
cache:false,
data:{
'user_id' : user_id,
'pwd' : pwd
},
success:function(rs) {
var rs = $.trim(rs);
if(rs === 'success') {
swal({
title:'Success',
text:'Password changed',
type:'success',
timer:1000
});
setTimeout(function(){
window.location.reload();
},1200);
}
else {
swal({
title:'Error!',
text:rs,
type:'error'
});
}
}
})
}
else {
set_error($('#cpwd'), $('#cpwd-error'), rs);
return false;
}
}
})
}
function check_pwd() {
var cpwd = $('#cpwd').val();
var pwd = $('#pwd').val();
var cfpwd = $('#cfpwd').val();
var el = $('#cfpwd');
var label = $('#cfpwd-error');
if(pwd !== cfpwd) {
set_error(el, label, "รหัสผ่านไม่ตรงกัน");
pwd_error = 1;
}
else {
clear_error(el, label);
pwd_error = 0;
}
}
$('#pwd').focusout(function(){
var pwd = $(this).val();
if(pwd.length > 0) {
check_pwd();
}
})
$('#cfpwd').focusout(function(){
check_pwd();
})
function validData(el, label, error) {
if(el.val() == '') {
set_error(el, label, "Required");
window[error] = 1;
}
else {
clear_error(el, label);
window[error] = 0;
}
console.log(error + " = " + window[error]);
}
|
import React from 'react';
import "./Hitachivantara.css";
import NavigationBar from './NavigationBar';
class IBMS extends React.Component {
render() {
return (
<div class="myclasssearch">
<NavigationBar/>
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingOne">
<h1 class="mb-0">
<button type="button" style={{fontSize:"large"}} class="btn btn-link" data-toggle="collapse" data-target="#collapseOne"><i class="fa fa-plus"></i> IBM Blade firmware upgrade procedure
</button>
</h1>
</div>
<div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="card-body">
<p style={{fontSize:"large"}}>very interesting subject please click. <a href="/SLV1" target="_blank">Learn more.</a></p>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingTwo">
<h2 class="mb-0">
<button type="button" style={{fontSize:"large"}} class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo"><i class="fa fa-plus"></i> second problem on this</button>
</h2>
</div>
<div id="collapseTwo" class="collapse show" aria-labelledby="headingTwo" data-parent="#accordionExample">
<div class="card-body">
<p style={{fontSize:"large"}}>Add conventions . <a href=" " target="_blank">Learn more.</a></p>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingTwo">
<h2 class="mb-0">
<button type="button" style={{fontSize:"large"}} class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo"><i class="fa fa-plus"></i> second problem on this</button>
</h2>
</div>
<div id="collapseTwo" class="collapse show" aria-labelledby="headingTwo" data-parent="#accordionExample">
<div class="card-body">
<p style={{fontSize:"large"}}>Add conventions . <a href=" " target="_blank">Learn more.</a></p>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingTwo">
<h2 class="mb-0">
<button type="button" style={{fontSize:"large"}} class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo"><i class="fa fa-plus"></i> second problem on this</button>
</h2>
</div>
<div id="collapseTwo" class="collapse show" aria-labelledby="headingTwo" data-parent="#accordionExample">
<div class="card-body">
<p style={{fontSize:"large"}}>Add conventions . <a href=" " target="_blank">Learn more.</a></p>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingThree">
<h2 class="mb-0">
<button type="button" style={{fontSize:"large"}} class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree"><i class="fa fa-plus"></i> 3rd problem and solution </button>
</h2>
</div>
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">
<div class="card-body">
<p style={{fontSize:"large"}}>Work In Progress <a href=" " target="_blank">Learn more.</a></p>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default IBMS;
|
/**
* Created by conroyp on 4/5/14.
*/
/** basic barchart module utilizes d3.js to dynamically create a svg barchart from object data.
* target element is specified in options, and chart is created there. data array can use whatever
* field names you choose but they must be specifed in options.
* requires you supply options object as below. currently implemented as a function rather than class.
* will change this later in order to make chart updatable.
* your html page should load d3.js before loading this code.
* also see barchart.css for styling
* example options object below
options=
{
margin: {top: 20, right: 20, bottom: 30,left: 60},
target: "#CoreDocsChart",
totalWidth: 500,
totalHeight: 400,
data: [{name:"sent", numDocs:30}, {name:"inbox", numDocs:20},{name:"deleted", numDocs:100}],
yLabel: "Documents",
yField: "numDocs",
xField: "name",
Yticks: 10
}
*/
function BarChart(options )
{
var _options=options;
var margin= _options.margin,
width=_options.totalWidth - margin.left - margin.right,
height=_options.totalHeight - margin.top -margin.bottom;
_options.data=_options.data.map(function(d) {
d.xField=d[_options.xField];
d.yField=d[_options.yField];
return d;
})
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear().range([height,0]);
x.domain(_options.data.map(function(d) {
return d.xField;}));
y.domain([0,d3.max(_options.data,function(d){
return d.yField;
})]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);
var svg= d3.select(_options.target).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height +margin.top + margin.bottom )
.append("g")
.attr("transform","translate(" + margin.left +"," + margin.top+")");
svg.append("g")
.attr("class", "x axis")
.attr("transform","translate(0,"+height+")")
.call(xAxis);
svg.append("g")
.attr("class","y axis")
.call(yAxis)
.append("text")
.attr("transform","rotate(-90)")
.attr("y",6)
.attr("dy",".71em")
.style("text-anchor","end")
.text(_options.yLabel);
/* svg.data(function(data){
x.domain(data.map(function(d) { return d.name; }));
y.domain([0,d3.max(data,function(d){return d.numDocs;})]);
*/
svg.selectAll(".bar")
.data(_options.data)
.enter()
.append("rect")
.attr("class","bar")
.attr("x", function(d){ return x(d.xField); })
.attr("y", function(d){ return y(d.yField); })
.attr("height", function(d) { return height - y(d.yField); })
.attr("width", x.rangeBand());
/*
var type =function(d)
{
d.name= d.letter;
d.value = +d.frequency; //coerce to number
return d;
}
*/
}
|
import "../styles.css";
import React from "react";
import { PlayerList } from "../components/PlayerList";
import { Layout } from "antd";
const { Content, Sider } = Layout;
const GamePage = ({ players }) => {
const playersSortedByScore = players.sort((first, second) =>
first.score <= second.score ? 1 : -1
);
return (
<Layout>
<Layout>
<Content>
<canvas id="stage"></canvas>
</Content>
<Sider className="transparent">
<PlayerList players={playersSortedByScore} />
</Sider>
</Layout>
</Layout>
);
};
export default GamePage;
|
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
class App extends Component {
state = {
response: "",
username: "",
password: ""
};
login = async () => {
const { username, password } = this.state;
const response = await fetch("/login", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
username,
password
})
});
const body = await response.json();
this.setState({ response: body.express });
};
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<div className="Field">
Username:
<input
className="Input"
onChange={i => this.setState({ username: i.target.value })}
/>
</div>
<div className="Field">
Password:
<input
className="Input"
type="password"
onChange={i => this.setState({ password: i.target.value })}
/>
</div>
<button className="Field" onClick={this.login}>
Log In
</button>
<h2 className="App-intro">{this.state.response}</h2>
</div>
);
}
}
export default App;
|
const postcss = require('postcss');
module.exports = postcss.plugin('postcss-interim', (opts) => {
return (root, result) => {
if (!process.argv[2] || process.argv[2].trim() != "--production") {
return;
}
root.walkRules( (rule) => {
if (rule.selector.trim() === ".interim &") {
const clonedDecls = [];
const clonedPropertyNames = [];
rule.walkDecls((decl) => {
clonedDecls.push(decl.clone());
clonedPropertyNames.push(decl.prop);
decl.remove();
})
rule.parent.walkDecls((potentialDuplicate) => {
if(clonedPropertyNames.includes(potentialDuplicate.prop) ) {
potentialDuplicate.remove();
}
});
clonedDecls.forEach(clonedDecl => {
rule.parent.append(clonedDecl);
});
rule.remove();
}
});
}
});
|
import React from "react";
const Trend = ({ trend }) => {
return (
<div className="text-blue-500 text-sm w-full md:w-1/3 lg:w-full">
<a href={`${trend.url}`} rel="noopener noreferrer" target="_blank">
{" "}
{`${trend.name}`}
<span className="text-gray-600"> {trend.tweet_volume} Tweets</span>
</a>
</div>
);
};
export default Trend;
|
'use strict'
import React from 'react'
import ReactDOM from 'react-dom'
import MainWindow from './'
import {ipcRenderer} from 'electron'
import store from 'Redux/store'
import * as actions from 'Redux/actions'
require('../../styles/global.scss')
ipcRenderer.on('action', (evt, action) => {
if ($('.Modal').length && action.indexOf('Instance') !== -1) {
return
}
store.skipPersist = true
store.dispatch(actions[action]())
store.skipPersist = false
})
ReactDOM.render(MainWindow, document.getElementById('content'))
|
import { renderString } from '../../src/index';
describe(`Returns topic cluster associated with a piece of content.`, () => {
it(`unnamed case 0`, () => {
const html = renderString(`{{ topic_cluster_by_content_id(123) }}`);
});
});
|
import Header from "../components/Header./Header"
function Home() {
return (
<div className="App">
<Header />
</div>
)
}
export default Home;
|
import {emit} from "../../../utilities/tools";
import {template, createElement} from "../../../utilities/travrs";
// ------------------------------------------------
// ---- CONTENT CORE ----------------
// ------------------------
export default (function Content () {
// Create UI element.
const element = createElement('div');
const updateElement = (event) => {
const root = event.target.closest('div[data-type=content] > div[data-type]');
root && element.dispatchEvent(emit('update.element', { ref: root }));
}
element.addEventListener('blur', updateElement, true);
// Replace old content with new one.
const set = (content) => {
content.classList.add('content');
if (!element.firstElementChild) element.appendChild(content);
else element.replaceChild(content, element.firstElementChild);
// Dispatch update event.
element.dispatchEvent(emit('changed'));
};
// Get Content pure content
const pull = () => element.firstElementChild;
// Public API.
return { element, set, pull };
}());
|
const path = require('path')
module.exports = {
LOG_LEVEL: process.env.LOG_LEVEL || 'debug', // Winston log level
LOG_FILE: path.join(__dirname, '../app.log'), // File to write logs to
INFORMIX: { // Informix connection options
host: process.env.INFORMIX_HOST || 'localhost',
port: parseInt(process.env.INFORMIX_PORT, 10) || 2021,
user: process.env.INFORMIX_USER || 'informix',
password: process.env.INFORMIX_PASSWORD || 'password',
database: process.env.INFORMIX_DATABASE || 'db',
server: process.env.INFORMIX_SERVER || 'informixserver',
minpool: parseInt(process.env.MINPOOL, 10) || 1,
maxpool: parseInt(process.env.MAXPOOL, 10) || 60,
maxsize: parseInt(process.env.MAXSIZE, 10) || 0,
idleTimeout: parseInt(process.env.IDLETIMEOUT, 10) || 3600,
timeout: parseInt(process.env.TIMEOUT, 10) || 30000
},
POSTGRES: { // Postgres connection options
user: process.env.PG_USER || 'pg_user',
host: process.env.PG_HOST || 'localhost',
database: process.env.PG_DATABASE || 'postgres', // database must exist before running the tool
password: process.env.PG_PASSWORD || 'password',
port: parseInt(process.env.PG_PORT, 10) || 5432,
triggerFunctions: process.env.TRIGGER_FUNCTIONS || 'prod_db_notifications', // List of trigger functions to listen to
triggerTopics: process.env.TRIGGER_TOPICS || ['prod.db.postgres.sync'], // Names of the topic in the trigger payload
triggerOriginators: process.env.TRIGGER_ORIGINATORS || ['tc-postgres-delta-processor'] // Names of the originator in the trigger payload
},
KAFKA: { // Kafka connection options
brokers_url: process.env.KAFKA_URL || 'localhost:9092', // comma delimited list of initial brokers list
SSL: {
cert: process.env.KAFKA_CLIENT_CERT || null, // SSL client certificate file path
key: process.env.KAFKA_CLIENT_CERT_KEY || null // SSL client key file path
},
topic: process.env.KAFKA_TOPIC || 'db.topic.sync', // Kafka topic to push and receive messages
partition: process.env.partition || [0], // Kafka partitions to use
maxRetry: process.env.MAX_RETRY || 10,
errorTopic: process.env.ERROR_TOPIC || 'db.scorecardtable.error',
recipients: ['admin@abc.com'], // Kafka partitions to use,
KAFKA_URL: process.env.KAFKA_URL,
KAFKA_GROUP_ID: process.env.KAFKA_GROUP_ID || 'prod-postgres-ifx-consumer',
KAFKA_CLIENT_CERT: process.env.KAFKA_CLIENT_CERT ? process.env.KAFKA_CLIENT_CERT.replace('\\n', '\n') : null,
KAFKA_CLIENT_CERT_KEY: process.env.KAFKA_CLIENT_CERT_KEY ? process.env.KAFKA_CLIENT_CERT_KEY.replace('\\n', '\n') : null,
},
SLACK: {
URL: process.env.SLACKURL || 'us-east-1',
SLACKCHANNEL: process.env.SLACKCHANNEL || 'ifxpg-migrator',
SLACKNOTIFY: process.env.SLACKNOTIFY || 'false'
},
RECONSILER: {
RECONSILER_START: process.env.RECONSILER_START || 30,
RECONSILER_END: process.env.RECONSILER_END || 1,
RECONSILER_DURATION_TYPE: process.env.RECONSILER_DURATION_TYPE || 'm'
},
DYNAMODB:
{
DYNAMODB_TABLE: process.env.DYNAMODB_TABLE || 'prod_pg_ifx_payload_sync',
DD_ElapsedTime: process.env.DD_ElapsedTime || 600000
},
AUTH0_URL: process.env.AUTH0_URL,
AUTH0_AUDIENCE: process.env.AUTH0_AUDIENCE,
TOKEN_CACHE_TIME: process.env.TOKEN_CACHE_TIME,
AUTH0_CLIENT_ID: process.env.AUTH0_CLIENT_ID,
AUTH0_CLIENT_SECRET: process.env.AUTH0_CLIENT_SECRET,
BUSAPI_URL: process.env.BUSAPI_URL,
KAFKA_ERROR_TOPIC: process.env.KAFKA_ERROR_TOPIC,
AUTH0_PROXY_SERVER_URL: process.env.AUTH0_PROXY_SERVER_URL
}
|
/// <reference path="site.js" />
/// <reference path="clean-blog.js" />
/// <reference path="clean-blog.js" />
/// <reference path="https://code.jquery.com/jquery-3.2.1.min.js" />
/// <reference path="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"/>
|
import { Box, Grid, makeStyles } from "@material-ui/core";
import React from "react";
import { Cards } from "../cards";
const usestyles = makeStyles({
bgClr: {
backgroundColor: "#FFF9F4",
padding: 40,
},
heading: {
fontWeight: 700,
fontSize: 45,
lineHeight: "1.2em",
color: "#000000",
fontFamily: "Circular-Loom",
display: "flex",
justifyContent: "center",
},
headingDetail: {
color: "#000000",
fontSize: 15,
fontWeight: 400,
fontFamily: "Circular-Loom",
marginTop: 25,
width: "85%",
lineHeight: "25px",
},
dFlex: {
display: "flex",
justifyContent: "center",
textAlign: "center",
},
});
export const OurServices = ({ image, name, description }) => {
const classes = usestyles();
return (
<Box className={classes.bgClr}>
<Box className={classes.heading}>Our Services</Box>
<Box className={classes.dFlex}>
<Box className={classes.headingDetail}>
Tech Tiz specializes in all coding languages and app development
software, ensuring our clients are always a step ahead of the
competition. We deliver custom mobile application services for mobile
devices, IoT, augmented reality devices, and mobile devices, helping
you set a digital presence across all platforms.
</Box>
</Box>
<Grid spacing={8} container>
<Cards
image="https://techtiz.com/wp-content/uploads/2021/05/Android-2.png"
name="Android"
description="TechTiz custom mobile developers have hands-on command in android mobile app development, which streamlines your business goals"
/>
<Cards
image="https://techtiz.com/wp-content/uploads/2021/05/Ios-1.png"
name="iOS"
description="TechTiz builds secure and practical iOS applications that don’t leave a user wanting more."
/>
<Cards
image="https://techtiz.com/wp-content/uploads/2021/05/responsive_screen-512-copy-1.png"
name="Cross-Platform "
description="Our experts design cross-platform apps to facilitate the users and help you grow across different devices."
/>
<Cards
image="https://techtiz.com/wp-content/uploads/2021/05/Web-Development-1.png"
name="Back-end "
description="Our experts design cross-platform apps to facilitate the users and help you grow across different devices."
/>
<Cards
image="https://techtiz.com/wp-content/uploads/2021/05/117-1174725_cloud-computing-cloud-computing-icon-transparent-1.png"
name="Cloud-based apps "
description="Our experts design cross-platform apps to facilitate the users and help you grow across different devices."
/>
<Cards
image="https://techtiz.com/wp-content/uploads/2021/05/Game-Development-1.png"
name="Game development "
description="Our experts design cross-platform apps to facilitate the users and help you grow across different devices."
/>
</Grid>
</Box>
);
};
|
import React from 'react'
import {Parallax} from 'react-parallax';
import Img from 'gatsby-image';
import {graphql} from 'gatsby';
class Header extends React.Component {
render() {
const imgUrl = this.props.src;
const children = this.props.children;
const image = this.props.data.img.childImageSharp.fluid;
return (
<div
className="parallax"
>
<Img
title="Header image"
alt="Greek food laid out on table"
fluid={image}
>
</Img>
{children}
</div>
)
}
}
export default Header
export const pageQuery = graphql`query {
img: file(relativePath: { eq: "eiffel.jpg" }) {
childImageSharp {
fluid(maxWidth: 1000) {
...GatsbyImageSharpFluid
}
}
}
}
`
|
import Vue from 'vue'
import vuex from 'vuex'
import Supplier from '../../models/BusinessAssociate'
import axios from 'axios'
import Constants from '../../Utility/constants'
const BASE_URL=Constants.BASE_URL
const MODEL_URL='suppliers/'
const URL=BASE_URL+MODEL_URL
Vue.use(vuex)
export default{
state:{
suppliers:[]
},
getters:{
getSuppliers:state=>state.suppliers
},
mutations:{
addNewSupplier:(state,payload)=>{
state.suppliers.push(payload)
},
getSuppliers:(state,payload)=>{
state.suppliers=payload
},
updateSupplier:(state,payload)=>{
var supplier=state.suppliers.find(supplier=>{
return supplier.ba_id===payload.ba_id
})
const index=state.suppliers.indexOf(supplier)
state.suppliers.splice(index,1,payload)
},
deleteSupplier:(state,payload)=>{
const index=state.suppliers.indexOf(payload)
state.suppliers.splice(index,1)
}
},
actions:{
addNewSupplier({commit,getters},payload){
axios.post(URL,payload)
.then(res=>{
console.log(res)
if(res.status==200)
commit('addNewSupplier',payload)
})
.catch(err=>{
console.log(err)
})
},
getSuppliers({commit,getters}){
axios.get(URL)
.then(res=>{
console.log(res.data)
commit('getSuppliers',res.data)
})
.catch(err=>{
console.log(err)
})
},
updateSupplier({commit,getters},payload){
axios.put(URL+payload.ba_id,payload)
.then(res=>{
if(res.status==200)
commit('updateSupplier',payload)
})
.catch(err=>{
console.log(err)
})
},
deleteSupplier({commit,getters},payload){
axios.delete(URL+payload.ba_id)
.then(res=>{
if(res.status==200)
commit('deleteSupplier',payload)
})
.catch(err=>{
console.log(err)
})
}
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import Svg, { Rect, Path } from 'react-native-svg';
type InputType = {
size: number,
color: string,
};
const CreditCardIcon = ({ size, color }: InputType) => (
<Svg
version="1.1"
xmlnsXlink="http://www.w3.org/1999/xlink"
x="0px"
y="0px"
width={size}
height={size}
viewBox="0 0 512 512"
enableBackground="new 0 0 512 512"
xmlSpace="preserve"
>
<Path
fill={color}
d="M480 96H32c-17.688 0-32 14.313-32 32v256c0 17.688 14.313 32 32 32h448c17.688 0 32-14.313 32-32V128c0-17.687-14.312-32-32-32zm0 288H32V224h448v160zm0-224H32v-32h448v32z"
/>
<Rect fill={color} x={64} y={320} width={64} height={32} />
<Rect fill={color} x={160} y={320} width={64} height={32} />
<Path
fill={color}
d="M336 352c12.344 0 23.5-4.813 32-12.469 8.5 7.656 19.656 12.469 32 12.469 26.5 0 48-21.5 48-48s-21.5-48-48-48c-12.344 0-23.5 4.813-32 12.469-8.5-7.656-19.656-12.469-32-12.469-26.5 0-48 21.5-48 48s21.5 48 48 48z"
/>
</Svg>
);
CreditCardIcon.propTypes = {
size: PropTypes.number,
color: PropTypes.string,
};
export default CreditCardIcon;
|
import React from 'react';
import { ActivityIndicator } from 'react-native';
import { Container } from 'native-base';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import SplashScreen from 'react-native-splash-screen';
class StageScreen extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
(this.props.token) ? this.props.navigation.navigate(this.getScreen()) : this.props.navigation.navigate('authorization');
// this.props.navigation.navigate('authorization');
SplashScreen.hide();
}
getScreen = () =>{
const { role } = this.props;
switch (role) {
case 'RecipientUser' :
return 'userHome';
case 'sender' :
return 'senderHome';
case 'executor' :
return 'executorHome';
}
}
render() {
return (
<Container style={{
flexGrow: 1, width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center',
}}>
<ActivityIndicator size="large" color='#ef7f1a' />
</Container>
);
}
}
StageScreen.propTypes = {
navigation: PropTypes.object,
token: PropTypes.string,
};
const mapStateToProps = ({ authReducer }) => ({
role: authReducer.role,
token: authReducer.token,
});
export default connect(mapStateToProps, null)(StageScreen);
|
/**
* Created by Wwei on 2016/9/1.
*/
Ext.define('Admin.view.users.UserController', {
extend: 'Admin.view.BaseViewController',
alias: 'controller.user',
requires: [
'Admin.view.users.UserForm'
],
search: function () {
var me = this,
grid = me.lookupReference('grid'),
form = me.lookupReference('form');
if (!form.isValid()) {
return false;
}
grid.getStore().loadPage(1);
},
createUser: function () {
Ext.create('Admin.view.users.UserForm', {
action: 'create',
store: this.lookupReference('grid').getStore()
}).show();
},
activeUser: function (grid, rowIndex, colIndex) {
Ext.Msg.confirm(
"请确认"
, "确定激活该用户吗?"
, function (button, text) {
if (button == 'yes') {
var rec = grid.getStore().getAt(rowIndex),
userId = rec.get('userId');
this.confirmDoUser('active', {userId: userId});
}
}, this);// 指定作用域,否则无法调用confirmDelUser方法
},
disableUser: function (grid, rowIndex, colIndex) {
Ext.Msg.confirm(
"请确认"
, "确定禁用该用户吗?"
, function (button, text) {
if (button == 'yes') {
var rec = grid.getStore().getAt(rowIndex),
userId = rec.get('userId');
this.confirmDoUser('disable', {userIds: userId});
}
}, this);// 指定作用域,否则无法调用confirmDelUser方法
},
disableUsers: function (btn, event) {
var me = this,
grid = me.lookupReference('grid'),
selMod = grid.getSelectionModel(),
records = selMod.getSelection(),
userIds = [];
if (records == undefined || records.length <= 0) {
Ext.Msg.alert('提醒', '请勾选相关记录!');
return;
}
Ext.Msg.confirm(
'请确认'
, '确定禁用吗?'
, function (button, text) {
if (button == 'yes') {
for (var i = 0; i < records.length; i++) {
userIds.push(records[i].get('userId'));
}
this.confirmDoUser('disable', {userIds: userIds});
}
}, this);// 指定作用域,否则无法调用confirmDelUser方法
},
confirmDoUser: function (action, params) {
var me = this,
searchBtn = me.lookupReference('btn_search');
Common.util.Util.doAjax({
url: Common.Config.requestPath('System', 'Users', action),
method: 'post',
params: params
}, function (data) {
if (data.code === '0') {
searchBtn.fireEvent('click');
}
});
},
/** grid 渲染之前 初始化操作
* add beforeload listener to grid store
* @param {Ext.Component} component
*/
gridBeforeRender: function () {
var me = this,
form = me.lookupReference('form'),
grid = me.lookupReference('grid');
grid.getStore().addListener({
'beforeload': function (store) {
grid.getScrollTarget().scrollTo(0, 0); //每次加载之前 scrolly to 0
Ext.apply(store.getProxy().extraParams, form.getValues(false, true));
return true;
},
'load': function (store) {
store.getProxy().extraParams = {};
},
'beginupdate': function () {
grid.setHeight(grid.getHeight()); //设置grid height,如果不这样则一页显示数据多了则不显示scrolly 估计是extjs6的bug
return true;
}
});
},
/** 重置密码
* @param {Ext.button.Button} component
* @param {Event} e
*/
resetpassword: function (btn, event) {
var me = this,
grid = me.lookupReference('grid'),
selMod = grid.getSelectionModel(),
records = selMod.getSelection(),
userIds = [];
if (records == undefined || records.length <= 0) {
Ext.Msg.alert('提醒', '请勾选相关记录!');
return;
}
Ext.Msg.confirm(
'请确认'
, '确定重置密码吗?'
, function (button, text) {
if (button == 'yes') {
for (var i = 0; i < records.length; i++) {
userIds.push(records[i].get('userId'));
}
Common.util.Util.doAjax({
url: Common.Config.requestPath('System', 'Users', 'resetpassword'),
method: 'post',
params: {userIds: userIds}
}, function (data) {
if (data.code == '0') {
Common.util.Util.toast("密码修改成功");
}
});
}
}, this);// 指定作用域,否则无法调用confirmDelUser方法
},
/**
* 修改用户
*/
updateUser: function (grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
Ext.create('Admin.view.users.UserForm', {
action: 'update',
title: '用户修改',
store: this.lookupReference('grid').getStore(),
viewModel: {
links: {
theUser: {
type: 'users.User',
create: rec.data
}
},
data: {
usernameDis:true,
showIdCardButton:rec.data.idPath.length>0?false:true,
showEntryformButton:rec.data.entryformPath.length>0?false:true
}
}
}).show();
},
/**
* 用户角色分配
*/
changeUserRole: function (grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
Common.util.Util.doAjax({
url: Common.Config.requestPath('System', 'Users', 'getUserRole'),
method: 'get',
params: {userId: rec.get('userId')}
}, function (data) {
var UserRoleWindow = Ext.create('Ext.window.Window', {
title: '角色分配',
layout: 'fit',
modal: true,
height: 250,
width: 300,
items: {
xtype: 'form',
items: [{xtype: 'hidden', name: 'userId', value: rec.get('userId')}, {
xtype: 'tagfield',
fieldLabel: '角色列表',
store: 'users.RoleType',
valueField: "id",
displayField: "name",
name: 'roleId',
filterPickList: true,
allowBlank : false,
value: data.data,
listeners:{
beforerender:function(){
this.getStore().load();
}
}
}],
buttons: [{
text: '确定',
handler: function () {
var me = this,
form = me.up('form');
if (!form.isValid()) {
return false;
}
var formValues = form.getValues();
Common.util.Util.doAjax({
url: Common.Config.requestPath('System', 'Users', 'updateUserRole'),
method: 'post',
params: formValues
}, function (data) {
UserRoleWindow.close();
Common.util.Util.toast("角色更改成功");
});
}
}]
}
});
UserRoleWindow.show();
});
},
distributeBrand: function (grid, rowIndex) {
var rec = grid.getStore().getAt(rowIndex);
Common.util.Util.doAjax({
url: Common.Config.requestPath('Brand', 'getUserBrand'),
method: 'get',
params: {userId: rec.get('userId')}
}, function (data) {
var UserRoleWindow = Ext.create('Ext.window.Window', {
title: '品牌的分配',
layout: 'fit',
modal: true,
height: 250,
width: 300,
items: {
xtype: 'form',
items: [{xtype: 'hidden', name: 'userId', value: rec.get('userId')}, {
xtype: 'tagfield',
fieldLabel: '品牌列表',
store: 'brand.Brand',
valueField: "id",
displayField: "name",
name: 'brandId',
filterPickList: true,
allowBlank : false,
value: data.data,
listeners:{
beforerender:function(){
this.getStore().load();
}
}
}],
buttons: [{
text: '确定',
handler: function () {
var me = this,
form = me.up('form');
if (!form.isValid()) {
return false;
}
var formValues = form.getValues();
Common.util.Util.doAjax({
url: Common.Config.requestPath('Brand', 'updateUserBrand'),
method: 'post',
params: formValues
}, function (data) {
UserRoleWindow.close();
Common.util.Util.toast("品牌分配成功");
});
}
}]
}
});
UserRoleWindow.show();
});
},
/** 清除 查询 条件
* @param {Ext.button.Button} component
* @param {Event} e
*/
reset: function () {
this.lookupReference('form').reset();
}
});
|
jQuery(function($) {'use strict',
//copyrights year
today=new Date();
year=today.getFullYear();
var start=2019;
if(year>start){
$('#c_year').text(start+' - '+year);
}else{
$('#c_year').text(start);
}
if(year<start){
$('#c_year').text(start);
}
});
//#main-slider
$('#submit').on('click', function() {
console.log('called');
var fname = $('#p_name').val();
var subject = $('#p_subject').val();
var email = $('#p_email').val();
var tele = $('#p_phone').val();
var message = $('#p_message').val();
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!regex.test(email)) {
alert('Please enter valid email');
return false;
}
fname = $.trim(fname);
subject = $.trim(subject);
email = $.trim(email);
tele = $.trim(tele);
message = $.trim(message);
if (fname != '' && email != '' && tele != '') {
var values = "fname=" + fname + "&subject=" + subject + "&email=" + email + " &tele=" + tele+ " &message=" + message;
$.ajax({
type: "POST",
url: "mail.php",
data: values,
success: function() {
$('#p_name').val('');
$('#p_subject').val('');
$('#p_email').val('');
$('#p_phone').val('');
$('#p_message').val('');
$('.cf-msg').fadeIn().html('<div class="alert alert-success"><strong>Success!</strong> Email has been sent successfully.</div>');
setTimeout(function() {
$('.cf-msg').fadeOut('slow');
}, 4000);
}
});
} else {
$('.cf-msg').fadeIn().html('<div class="alert alert-danger"><strong>Warning!</strong> Please fillup the informations correctly.</div>')
}
return false;
});
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const tribeSchema = new Schema({
name: String,
members: [ { type: Schema.Types.ObjectId, ref: 'User' } ]
});
const Tribe = mongoose.model('Tribe', tribeSchema);
module.exports = Tribe;
|
import { intervalToDuration, parseISO } from 'date-fns';
function register(env) {
env.addFilter("between_times", handler);
}
// TODO: implement unit
function handler(input, end, unit) {
const res = intervalToDuration({ start: input, end: end}, unit);
if (!res[unit]) {
throw Error("Unit not implemented yet.")
}
return res[unit];
}
export {
handler,
register as default
};
|
/**
* Copyright 2014 Pacific Controls Software Services LLC (PCSS). All Rights Reserved.
*
* This software is the property of Pacific Controls Software Services LLC and its
* suppliers. The intellectual and technical concepts contained herein are proprietary
* to PCSS. Dissemination of this information or reproduction of this material is
* strictly forbidden unless prior written permission is obtained from Pacific
* Controls Software Services.
*
* PCSS MAKES NO REPRESENTATION OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTANILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGMENT. PCSS SHALL
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*/
/**
* Version : 1.0
* User : pcscs204
* Function : This file
*/
gxMainApp.controller('adminNotificationController', function($scope, $filter, $rootScope,$modal, ngDialog, ngTableParams,adminFunctionsService) {
//Function to open Main Menu
$scope.showPopupStatus = function (p,size) {
$scope.selectedRow = p;
if($scope.selectedRow.status == 'Plan Features')
{
var modalInstance = $modal.open({
templateUrl: 'views/adminNotification/gxPlannedFeatures.html',
controller: ModalInstanceCtrl,
size: size,
resolve: {
selectedRowData: function () {
return $scope.selectedRow;
}
}
});
modalInstance.result.then(function (selectedItem) {
console.log('clicked OK');
}, function () {
console.log('clicked Cancel');
});
}
else
{
var modalInstance = $modal.open({
templateUrl: 'views/adminNotification/gxStatusDetails.html',
controller: ModalInstanceCtrl,
size: size,
resolve: {
selectedRowData: function () {
return $scope.selectedRow;
}
}
});
modalInstance.result.then(function (selectedItem) {
console.log('clicked OK');
}, function () {
console.log('clicked Cancel');
});
}
};
$scope.showPopupAction = function (p,size) {
$scope.selectedRow = p;
console.log($scope);
alert($scope.selectedRow.status);
if($scope.selectedRow.status == 'Plan Features')
{
var modalInstance = $modal.open({
templateUrl: 'views/adminNotification/gxPlannedFeatures.html',
controller: ModalInstanceCtrl,
size: size,
resolve: {
selectedRowData: function () {
return $scope.selectedRow;
}
}
});
modalInstance.result.then(function (selectedItem) {
console.log('clicked OK');
}, function () {
console.log('clicked Cancel');
});
}
else
{
var modalInstance = $modal.open({
templateUrl: 'views/adminNotification/gxActionDetails.html',
controller: ModalInstanceCtrl,
size: size,
resolve: {
selectedRowData: function () {
return $scope.selectedRow;
}
}
});
modalInstance.result.then(function (selectedItem) {
console.log('clicked OK');
}, function () {
console.log('clicked Cancel');
});
}
};
$scope.showCompanyDetails = function (p,size) {
$scope.selectedRow = p;
var modalInstance = $modal.open({
templateUrl: 'views/adminNotification/gxCompanyDetails.html',
controller: ModalInstanceCtrl,
size: size,
resolve: {
selectedRowData: function () {
return $scope.selectedRow;
}
}
});
modalInstance.result.then(function (selectedItem) {
console.log('clicked OK');
}, function () {
console.log('clicked Cancel');
});
};
/** Code for integrating with service side**/
$scope.notificationArray = adminFunctionsService.notificationArray;
//// $scope.rows=[];
//// $scope.rows=
//
// $scope.rows = [
// {
// "id":1,
// "date":"17-July-2014 10:25:00AM",
// "userid":"Smith",
// "status":"Approved",
// "companyname":"ZZ Company",
// "email":"j.smith@company.com",
// "phone":"617-321-4567",
// "actions":"Create App",
// "ac":true,
// "dl":false
// }
// ,
// {
// "id":2,
// "date":"15-July-2014 10:25:00AM",
// "userid":"Mae",
// "status":"Approved",
// "companyname":"M Company",
// "email":"mae@company.com",
// "phone":"617-321-4567",
// "actions":"Create App",
// "ac":true,
// "dl":false
// },
// {
// "id":3,
// "date":"15-July-2014 10:25:00AM",
// "userid":"Anju",
// "status":"Pending Verification",
// "companyname":"A Company",
// "email":"ajnu@company.com",
// "phone":"617-321-4567",
// "actions":"Verify",
// "ac":true,
// "dl":false
// },
// {
// "id":4,
// "date":"17-July-2014 10:25:00AM",
// "userid":"Smith",
// "status":"Verified",
// "companyname":"CEO",
// "email":"j.smith@company.com",
// "phone":"617-321-4567",
// "actions":"Plan Features",
// "ac":true,
// "dl":false
// },
// {
// "id":5,
// "date":"17-July-2014 10:25:00AM",
// "userid":"Smith",
// "status":"Verified",
// "companyname":"CEO",
// "email":"j.smith@company.com",
// "phone":"617-321-4567",
// "actions":"Plan Features",
// "ac":true,
// "dl":false
// },
// {
// "id":6,
// "date":"17-July-2014 10:25:00AM",
// "userid":"Smith",
// "status":"Verified",
// "companyname":"S Company",
// "email":"j.smith@company.com",
// "phone":"617-321-4567",
// "actions":"Plan Features",
// "ac":true,
// "dl":false
// },
// {
// "id":7,
// "date":"17-July-2014 10:25:00AM",
// "userid":"Smith",
// "status":"Pending Confirmation",
// "companyname":"XX Company",
// "email":"j.smith@company.com",
// "phone":"617-321-4567",
// "actions":"Features Selected",
// "ac":true,
// "dl":false
// },
// {
// "id":8,
// "date":"17-July-2014 10:25:00AM",
// "userid":"Smith",
// "status":"Pending Confirmation",
// "companyname":"Smith Company",
// "email":"smith@company.com",
// "phone":"617-321-4567",
// "actions":"Features Selected",
// "ac":true,
// "dl":false
// },
//
// {"id":9,
// "date":"17-July-2014 10:25:00AM",
// "userid":"Smith",
// "status":"Pending Confirmation",
// "companyname":"FF Company",
// "email":"j.smith@company.com",
// "phone":"617-321-4567",
// "actions":"Features Selected",
// "ac":true,
// "dl":false
// },
// {
// "id":10,
// "date":"17-July-2014 10:25:00AM",
// "userid":"Smith",
// "status":"Feature list Rejected",
// "companyname":"LL Company",
// "email":"j.smith@company.com",
// "phone":"617-321-4567",
// "actions":"Plan Features",
// "ac":true,
// "dl":false
// },
// {
// "id":11,
// "date":"17-July-2014 10:25:00AM",
// "userid":"Smith",
// "status":"Feature list Rejected",
// "companyname":"SD Company",
// "email":"j.smith@company.com",
// "phone":"617-321-4567",
// "actions":"Plan Features",
// "ac":true,
// "dl":false
// },
//
// {
// "id":12,
// "date":"17-July-2014 10:25:00AM",
// "userid":"Smith",
// "status":"Feature list Rejected",
// "companyname":"SQ Company",
// "email":"j.smith@company.com",
// "phone":"617-321-4567",
// "actions":"Plan Features",
// "ac":true,
// "dl":false
// },
// {
// "id":13,
// "date":"17-July-2014 10:25:00AM",
// "userid":"Smith",
// "status":"Feature list Accepted",
// "companyname":"SH Company",
// "email":"j.smith@company.com",
// "phone":"617-321-4567",
// "actions":"Approved",
// "ac":true,
// "dl":false
// },
//
// {
// "id":14,
// "date":"17-July-2014 10:25:00AM",
// "userid":"Smith",
// "status":"Feature list Accepted",
// "companyname":"YY Company",
// "email":"j.smith@company.com",
// "phone":"617-321-4567",
// "actions":"Approved",
// "ac":true,
// "dl":false
// }
//
// ];
//
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
companyname: 'asc' // initial sorting
}
},
{
total: $scope.notificationArray.length, // length of data
getData: function($defer, params) {
var resultPromise = adminFunctionsService.resultPromise;
var resultPromise = adminFunctionsService.getNotificationArray();
console.log(resultPromise);
resultPromise.then(function(data){
var orderedData = params.sorting() ?
$filter('orderBy')(data, params.orderBy()) :
data;
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
angular.copy(data,$scope.notificationArray);
})
// use build-in angular filter
}
});
console.log($scope.notificationArray);
$scope.editId = -1;
$scope.setEditId = function(pid) {
$scope.rejectId = -1;
$scope.editId = pid;
};
$scope.rejectId = -1;
$scope.setRejectId = function(pid) {
$scope.editId = -1;
$scope.rejectId = pid;
};
// $scope.rows= data;
$scope.temp = false;
$scope.deleteRow = function(p){
$scope.notificationArray.splice($scope.notificationArray.indexOf(p),1);
};
$scope.isTemp = function(i){
return i===$scope.notificationArray.length-1 && $scope.temp;
};
var ModalInstanceCtrl = function ($scope, $modalInstance,selectedRowData) {
$scope.selectedRowData = selectedRowData;
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
});
|
import React from "react";
import PropTypes from "prop-types";
import styles from "./input.css";
const Input = ({ label, id, type, value, ...attr }) => (
<input
aria-label={label}
type={type}
className={styles.inputField}
id={id}
value={value}
required
{...attr}
/>
);
Input.propTypes = {
label: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
value: PropTypes.string.isRequired
};
export default Input;
|
import React from 'react'
const Calculator = React.createClass({
getInitialState(){
return {numberOne: 0, numberTwo: 0}
},
sum(){
var numberOne = this.refs.numberOne;
var numberTwo = this.refs.numberTwo;
if(numberOne.value && numberTwo.value){
alert('Somaaaaaaaaaaaa de ' + numberOne.value
+ ' + '
+ numberTwo.value
+ ' = ' + (Number(numberOne.value)+Number(numberTwo.value)));
return;
}
},
render(){
return <div>
<input ref="numberOne" type="number" placeholder="Primeiro numero"/>
<input ref="numberTwo" type="number" placeholder="Segundo numero"/>
<button onClick={this.sum}>SOMAR</button>
</div>;
}
})
export default Calculator
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.