text stringlengths 7 3.69M |
|---|
let Post = require("../models/post");
let Profile = require("../models/profile");
let PostState = require("../models/postState")
//let CommentState = require("../models/commentState")
exports.check = function (req, res) {
PostState.find({
username: req.session.user
}, function (err, doc) {
if (err) throw err
if (doc.length) {
res.send(doc)
}
})
}
exports.vote = function (req, res) {
console.log(req.params.id)
if (req.body.action == "increment") {
console.log("increment")
Profile.update({
username: req.body.user
}, {
$inc: {
karma_post: 1
}
}, function (err, result) {
if (err) throw err;
if (result) {
console.log(`votes increased!`)
//console.log(`post number: []`)
}
});
} else if (req.body.action == "decrement") {
console.log("decrement")
Profile.update({
username: req.body.user
}, {
$inc: {
karma_post: -1
}
}, function (err, result) {
if (err) throw err;
if (result) {
console.log(`votes decreased!`)
//console.log(`post number: []`)
}
});
}
let query = {
username: req.session.user,
ref: req.params.id
};
let update = {
vote: req.body.state
};
let options = {
upsert: true,
setDefaultsOnInsert: true
};
Post.update({
_id: req.params.id
}, {
votes: req.body.vote
}, function (err, result) {
if (err) throw err;
if (result) {
console.log(`vote count changed!`)
}
})
PostState.findOneAndUpdate(query, update, options, function (err, result) {
if (err) throw err;
if (result) {
console.log(`vote count changed!`)
res.send("OK")
}
})
} |
import React from 'react';
import { Link } from 'react-router-dom';
import Styles from './TopBarContent.module.scss'
class TopBarContent extends React.Component {
constructor(props) {
super(props);
this.TopBarContentRef = React.createRef();
}
render() {
return(
<div className={Styles.WholeTopBarContent} ref={this.TopBarContentRef} onClick={this.props.hideMenus}>
<Link to = '/' onClick = {this.props.hideTopBar} className={Styles.SingleContent}><i className="fas fa-home fa-2x"></i><span>Strona Główna</span></Link>
<Link to='/coin' onClick = {this.props.hideTopBar} className={Styles.SingleContent}><i className="fas fa-coins fa-2x"></i><span>Monety</span></Link>
<Link to='/user' onClick = {this.props.hideTopBar} className={Styles.SingleContent}><i className="fas fa-user fa-2x"></i><span>Profil</span></Link>
</div>
)
}
}
export default TopBarContent; |
require("./sequelize");
const {user} = require("./models/user");
const {registration} = require("./models/registration");
const {configuration} = require("./models/configuration");
const {url} = require("./models/url");
const {device} = require("./models/device");
configuration.hasMany(device, {foreignKey: 'configurationId'});
device.belongsTo(configuration, {foreignKey: 'configurationId'});
url.belongsToMany(configuration, {through: 'urlcfgjunction', foreignKey: 'urlId', otherKey: 'configurationId'});
configuration.belongsToMany(url, {through: 'urlcfgjunction', foreignKey: 'configurationId', otherKey: 'urlId'});
registration.findOne().then(r => {
console.log("fetched PSK: "+r.registerkey);
require('./../tools/global').REGISTERKEY = r.registerkey;
console.log("set PSK: "+require('./../tools/global').REGISTERKEY);
}).catch(error => console.error(error));
|
// start up the program.
// loads configuration, users and tasks. schedules task executions. watches
// task directory & task files for changes
var path = require('path');
var async = require('async');
var tasks = require(path.join(__dirname, 'tasks'));
var users = require(path.join(__dirname, 'users'));
var data = require(path.join(__dirname, 'data'));
// load lasks, store valid enabled & valid disabled in memory
// schedule enabled tasks
var main = function main(app) {
// load configuration
data.setSync('mail:sender', app.get('mailSender'));
// load user & task definitions
async.series([
users.load,
tasks.load,
tasks.schedule,
//users.watch,
tasks.watch
],
function(err, results) {
if (err) throw new Error('could not initialize. ' + err);
console.log('initalized. results:', results);
});
};
// function loadScripts(cb){
// cb(null, 'one');
// },
// function(callback){
// // do some more stuff ...
// callback(null, 'two');
// }
// ],
// // optional callback
// function(err, results){
// // results is now equal to ['one', 'two']
// });
// function loadTasks() {
// async.each(, iterator, callback)
// }
// function scheduleTasks() {
// }
// module.exports = {
// loadTasks: loadTasks,
// scheduleTasks: scheduleTasks
// }
module.exports = main; |
(function ()
{
'use strict';
angular
.module('employee.create')
.controller('createController', createController);
function createController($scope,empApi,empService){
$scope.submit = function(){
empApi.employees().save({
'id': $scope.id,
'name': $scope.name,
'designation': $scope.designation
},
function(response) {
alert("Data added successfully : "+ JSON.stringify(response));
empService.setData (response);
// alert(empService.getData());
},
function(error) {
console.log(error)
alert("err:"+error.data);
});
}
}
})();
|
export const Error = ({ message }) => {
return <div className="alert alert-danger my-3">{message}</div>;
};
|
import Navbar from "./components/Navbar"
import Card from "./components/Card"
import CardDesc from "./components/CardDesc"
import Cart from "./components/Cart"
import Login from "./components/Login"
import Register from "./components/Register"
import ProductInfo from "./components/ProductInfo"
import Products from "./components/Products"
import ItemState from "./context/item/ItemState"
import AuthState from "./context/auth/AuthState"
import {
BrowserRouter as Router,
Switch,
Route,
} from "react-router-dom";
function App() {
return (
<AuthState>
<ItemState>
<Router>
<div className="App">
<Navbar/>
<Switch>
<Route exact path="/">
<Card/>
</Route>
{/* <Route exact path="/products">
<Products/>
<ProductInfo/>
</Route> */}
<Route exact path="/cart">
<Cart/>
</Route>
<Route exact path="/login">
<Login/>
</Route>
<Route exact path="/register">
<Register/>
</Route>
<Route exact path="/detail/:id">
<CardDesc/>
</Route>
</Switch>
</div>
</Router>
</ItemState>
</AuthState>
);
}
export default App;
|
import React, {Fragment} from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
TouchableOpacity,
Image,
Dimensions,
} from 'react-native';
import {SvgXml} from 'react-native-svg';
import SVG from '../components/SvgComponent';
const TESTDATAS = [
{
exist: true,
product: {image: '', heart: 'HEART_RED', brand: '뽀득', name: '뽀득 세제'},
point: '',
info: {safety: '', caution: ''},
},
{
exist: true,
product: {image: '', heart: 'HEART_RED', brand: '뽀득', name: '뽀득 세제'},
point: '',
info: {safety: '', caution: ''},
},
{exist: false},
];
const DATAS = [1, 2, 3];
const TEST = (datas) => {
return datas.map((data, index) => {
return (
<View key={index}>
{/* product */}
<View
style={{
marginTop: 24,
borderBottomColor: 'lightgray',
borderBottomWidth: 1,
alignItems: 'center',
width: (Dimensions.get('screen').width - 32) / 3,
paddingBottom: 15,
}}>
{TESTDATAS[index].exist ? (
<>
<TouchableOpacity
style={{
position: 'absolute',
top: 0,
left: (Dimensions.get('screen').width - 32) / 3 - 16 - 16,
top: 0,
bottom: 0,
zIndex: 10,
}}
onPress={() => {
alert('비교함에서 제거하시겠습니까?');
}}>
<SvgXml xml={SVG('CANCEL')} />
</TouchableOpacity>
<View>
<Image
source={require('../images/4.jpeg')}
resizeMode="contain"
style={{
width: (Dimensions.get('screen').width - 32) / 3 - 10,
backgroundColor: 'white',
height: (Dimensions.get('screen').width - 32) / 3,
}}
/>
</View>
<SvgXml xml={SVG(TESTDATAS[index].product.heart)} />
<Text style={{color: 'gray', fontSize: 10, marginTop: 10}}>
{TESTDATAS[index].product.brand}
</Text>
<Text style={{marginTop: 5, fontSize: 16}}>
{TESTDATAS[index].product.name}
</Text>
</>
) : (
<View style={{backgroundColor: 'white'}}>
<View
style={{
width: (Dimensions.get('screen').width - 32) / 3 - 10,
backgroundColor: 'white',
height: (Dimensions.get('screen').width - 32) / 3,
justifyContent: 'center',
alignItems: 'center',
}}>
<SvgXml xml={SVG('PLUS_GRAY')} />
</View>
<SvgXml xml={SVG('ALARM')} />
<Text style={{color: 'gray', fontSize: 10, marginTop: 8.5}}>
{' '}
</Text>
<Text style={{marginTop: 5, fontSize: 16}}> </Text>
</View>
)}
{/* */}
</View>
{/* info */}
{TESTDATAS[index].exist ? (
index == 0 ? (
<>
<View
style={[
{alignItems: 'center', paddingTop: 15, flex: 1},
index == 1 ? {backgroundColor: '#f3f3f3'} : null,
]}>
{/* point */}
<View
style={{
flexDirection: 'row',
paddingTop: 15,
paddingBottom: 15,
}}>
<SvgXml xml={SVG('STAR_CHECKED')} />
<Text style={{color: '#32cc73'}}>4.7</Text>
<Text>(2,121)</Text>
</View>
{/* info */}
<View style={{paddingTop: 5}}>
{/* */}
<View
style={{
alignItems: 'center',
paddingTop: 16,
paddingBottom: 16,
}}>
<SvgXml xml={SVG('SAFETY')} width="32" height="32" />
<View style={{flexDirection: 'row', marginTop: 5}}>
<Text>EWG</Text>
<Text style={{color: '#33bc2a', marginLeft: 3}}>
nn개
</Text>
</View>
</View>
{/* */}
{/* */}
<View
style={{
alignItems: 'center',
paddingTop: 16,
paddingBottom: 16,
}}>
<SvgXml xml={SVG('CAUTION')} width="32" height="32" />
<View style={{flexDirection: 'row', marginTop: 5}}>
<Text>EWG</Text>
<Text style={{color: '#fe8522', marginLeft: 3}}>
nn개
</Text>
</View>
</View>
{/* */}
{/* */}
<View
style={{
alignItems: 'center',
paddingTop: 16,
paddingBottom: 16,
}}>
<SvgXml xml={SVG('DANGER')} width="32" height="32" />
<View style={{flexDirection: 'row', marginTop: 5}}>
<Text>EWG</Text>
<Text style={{color: '#f1322d', marginLeft: 3}}>
nn개
</Text>
</View>
</View>
{/* */}
{/* */}
<View
style={{
alignItems: 'center',
paddingTop: 16,
paddingBottom: 16,
}}>
<SvgXml xml={SVG('KCII_DANGER')} width="32" height="32" />
<View style={{flexDirection: 'row', marginTop: 5}}>
<Text>EWG</Text>
<Text style={{color: '#ee433c', marginLeft: 3}}>
nn개
</Text>
</View>
</View>
{/* */}
</View>
</View>
</>
) : (
<>
<View
style={[
{alignItems: 'center', paddingTop: 15, flex: 1},
index == 1 ? {backgroundColor: '#f3f3f3'} : null,
]}>
{/* point */}
<View
style={{
flexDirection: 'row',
paddingTop: 15,
paddingBottom: 15,
}}>
<SvgXml xml={SVG('STAR_CHECKED')} />
<Text style={{color: '#32cc73'}}>4.7</Text>
<Text>(2,121)</Text>
</View>
{/* info */}
<View style={{paddingTop: 5}}>
{/* */}
<View
style={{
alignItems: 'center',
paddingTop: 16,
paddingBottom: 16,
}}>
<Text>nn Kal</Text>
</View>
{/* */}
{/* */}
<View
style={{
alignItems: 'center',
paddingTop: 16,
paddingBottom: 16,
}}>
<View
style={{
flexDirection: 'row',
marginTop: 5,
alignItems: 'center',
}}>
<Text>알레르기</Text>
<Text style={{color: '#f00045', marginLeft: 3}}>
nn개
</Text>
<SvgXml xml={SVG('DOWNMORE')} />
</View>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
width: (Dimensions.get('screen').width - 32) / 3 - 32,
}}>
<SvgXml xml={SVG('EGG')} />
<SvgXml xml={SVG('MILK')} />
<SvgXml xml={SVG('HEART_GRAY')} />
</View>
</View>
{/* */}
{/* */}
<View
style={{
alignItems: 'center',
paddingTop: 16,
paddingBottom: 16,
}}>
<SvgXml
xml={SVG('FOOD_ADDITIVES')}
width="32"
height="32"
/>
<View style={{flexDirection: 'row', marginTop: 5}}>
<Text>식품첨가물</Text>
<Text style={{color: '#fea728', marginLeft: 3}}>
nn개
</Text>
</View>
</View>
{/* */}
</View>
</View>
</>
)
) : null}
</View>
);
});
};
const Compare = ({navigation}) => {
return (
<Fragment>
<StatusBar barStyle="dark-content" />
<SafeAreaView />
<ScrollView style={{flex: 1}}>
<View
style={{
backgroundColor: 'white',
flex: 1,
padding: 16,
paddingBottom: 0,
flexDirection: 'row',
}}>
{TEST(DATAS)}
</View>
<View
style={{
borderTopColor: 'lightgray',
borderTopWidth: 1,
alignItems: 'center',
}}>
<View>
<Text>탄.단.지 그래프</Text>
</View>
</View>
</ScrollView>
</Fragment>
);
};
const styles = StyleSheet.create({});
export default Compare;
|
let app;
let fs = require("fs");
function init(express){
app = express;
console.log("Launching REST API...");
/*============================================================================
Main Endpoints
============================================================================*/
let rest_users = require("./req_users.js");
let rest_trips = require("./req_trips.js");
let rest_communities = require("./req_communities.js");
let rest_coops = require("./req_coops");
let pdf_report_generator = require("./req_pdf_report.js");
let registrations = require("./req_registrations");
let sms = require("./req_sms");
let rest_v_register_app = require("./req_app_versions/req_version_registerapp.js");
rest_users.init(app);
rest_trips.init(app);
rest_communities.init(app);
rest_coops.init(app);
pdf_report_generator.init(app);
registrations.init(app);
sms.init(app);
rest_v_register_app.init(app);
// These have been removed because they are initialized elsewhere
// let rest_tags = require("./req_tag_id");
// rest_tags.init(app);
/*============================================================================
Done!
============================================================================*/
console.log("REST API Initialized.\n");
}
module.exports = {
init: init
};
|
function convert() {
var lines = document.getElementById("input").value.split('\n');
console.log(lines);
var output = "String page=\"\";\n";
for (var i = 0; i < lines.length; i++) {
output += "page+=\"";
output += lines[i].replace(/\"/g, '\\\"');
output += "\";\n";
}
document.getElementById("output").value = output;
} |
// function sumArg() {
// return [].reduce.call(arguments, function(a, b) {
// return a + b;
// });
// }
function sumArg() {
arguments.reduce = [].reduce;
return arguments.reduce(function(a, b) {
return a + b;
})
}
console.log(sumArg(1,2,3,4,5,6)); |
// Code in ~2 hours by Bemmu, idea and sound code snippet from Viznut.
// 2011-09-30 - Modifications by raer.
// 2011-10-07 - Modifications by raer.
// 2019-04 - modernisation by edave64 and opensofias
const $form = document.forms[0];
// ui object contains input elements
const ui =
't0, tmod, seconds, separation, oneliner, oneliner2'
.split(', ').reduce ((acc, cur) => (
acc [cur] = document.getElementById(cur), acc
), {}
)
function makeSampleFunction(oneLiner) {
const {sin, cos, tan, floor, ceil} = Math;
eval("var f = function (t) { return " + oneLiner + "}");
return f;
}
const getCheckedOption = (optionGroup) => {
for (option of $form[optionGroup])
if (option.checked) return option.value | 0
}
const getUiNumbers = (settingsList) =>
settingsList.reduce ((acc, setting) => (
acc[setting] = ui[setting].value < 0 ?
0 :
ui[setting].value,
acc)
,{})
const mixAB = (a, b, t) =>
(a + b * t) / (1 + t)
const clamp = (val, min, max) =>
Math.max(min, Math.min(max,
Number(val) || min)
)
function getSoundSettings () {
return {
sampleRate: getCheckedOption ('sampleRate'),
sampleResolution: getCheckedOption ('sampleResolution'),
...getUiNumbers('t0, tmod, seconds'.split(', ')),
separation: 1 - clamp(ui.separation.value, 0, 100) / 100, // wtf
f: makeSampleFunction(ui.oneliner.value),
f2: ui.oneliner2.value ? makeSampleFunction(ui.oneliner2.value) : null,
}
}
function applySoundSettings ({sampleRate, t0, tmod, seconds, separation, f, f2}) {
ui.t0.value = t0;
ui.tmod.value = tmod;
ui.seconds.value = seconds;
ui.separation.value = separation;
}
function generateSound({sampleRate, t0, tmod, seconds, separation, f, f2, sampleResolution}) {
var sampleArray = [];
var channels = f2 ? 2 : 1;
var sampleMask = sampleResolution == 8 ? 0xff : 0xffff;
for (var t = t0; t < sampleRate * seconds; t++) {
//mod t with user-set value if any
var cT;
if (tmod > 0) {
cT = t % tmod;
}
else {
cT = t;
}
//left channel
var sample = f(cT);
// TODO: pretty reduced resolution. sample seems to go from 0 to 65280, but the function value only from 0 to 255
var sample2;
if (channels > 1) {
//right channel
sample2 = f2(cT);
//calculate value with stereo separation and normalize
var newSample = mixAB(sample, sample2, separation);
var newSample2 = mixAB(sample2, sample, separation);
sample = newSample;
sample2 = newSample2;
sample2 = sample2;
}
//store left sample
sampleArray.push(sample & sampleMask);
//store right sample if any
if (channels > 1) sampleArray.push(sample2 & sampleMask);
}
return {sampleRate, sampleArray, channels, sampleResolution};
}
var canvas = null;
var ctx = null;
var imgd = null;
function generatePreview({sampleRate, sampleArray, channels, sampleResolution}) {
//get canvas element
canvas = document.getElementById('canvas');
//get drawing context from canvas element
ctx = canvas.getContext("2d");
if (!canvas.getContext) {
canvas.innerHTML += "No canvas support. Your browser sucks!";
return;
}
imgd = false;
var width = canvas.width;
var height = canvas.height;
imgd = ctx.createImageData(width, height);
//clear image
ctx.fillStyle = "#FF0000FF";
ctx.fillRect(0, 0, width, height);
//get actual pixel data
var pix = imgd.data;
const sampleResolutionToColorDepth = 2 ** (sampleResolution - 8);
var iSample = 0;
for (var pxIdx = 0; pxIdx < (width * height); pxIdx++) {
//accumulate sample data for pixel
var sampleValue = 0;
var sampleValue2 = 0;
var sampleIdx = Math.floor(iSample) * channels;
sampleValue = sampleArray[sampleIdx];
sampleValue = sampleValue / sampleResolutionToColorDepth;
if (channels > 1) {
sampleValue2 = sampleArray[sampleIdx + 1];
sampleValue2 = sampleValue2 / sampleResolutionToColorDepth;
}
// Byte position of out current pixel, going from top to bottom, left to right. (With 4 bytes per pixel)
var index = (width * Math.floor(pxIdx % height) + Math.floor(pxIdx / height)) * 4;
pix[index] = sampleValue; // R
pix[index + 1] = sampleValue2; // G
pix[index + 2] = 00; // B
pix[index + 3] = 0xFF; // A
//increase sample index
iSample += 2 ** 8 / height;
}
//write image data to canvas
ctx.putImageData(imgd, 0, 0);
}
/**
* [255, 0] -> "%FF%00"
* @param {number[]} values
*/
function toHexString(values) {
return values.reduce((acc, x) => {
let hex = x.toString(16);
if (hex.length == 1) hex = "0" + hex;
return acc + "%" + hex;
}, "").toUpperCase();
}
// Character to ASCII value, or string to array of ASCII values.
const toCharCodes = (str) => [...str].map((c) => c.charCodeAt(0));
function split32bitValueToBytes(l) {
return [l & 0xff, (l & 0xff00) >> 8, (l & 0xff0000) >> 16, (l & 0xff000000) >> 24];
}
function FMTSubChunk({channels, sampleResolution, sampleRate}) {
var byteRate = sampleRate * channels * sampleResolution / 8;
var blockAlign = channels * sampleResolution / 8;
return [].concat(
toCharCodes("fmt "),
split32bitValueToBytes(16), // Subchunk1Size for PCM
[1, 0], // PCM is 1, split to 16 bit
[channels, 0],
split32bitValueToBytes(sampleRate),
split32bitValueToBytes(byteRate),
[blockAlign, 0],
[sampleResolution, 0]
);
}
/**
*
* @param {number[]} sampleArray
* @param {number} sampleResolution
* @returns {number[]}
*/
function sampleArrayToData(sampleArray, sampleResolution) {
if (![8, 16].includes(sampleResolution)) {
alert("Only 8 or 16 bit supported.");
return;
} else if (sampleResolution === 8) return sampleArray;
else {
var data = [];
for (var i = 0; i < sampleArray.length; i++) {
data.push( 0x00ff & sampleArray[i] );
data.push((0xff00 & sampleArray[i]) >> 8);
}
return data;
}
}
function dataSubChunk({channels, sampleResolution, sampleArray}) {
return [].concat(
toCharCodes("data"),
split32bitValueToBytes(sampleArray.length * sampleResolution / 8),
sampleArrayToData(sampleArray, sampleResolution)
);
}
function chunkSize(fmt, data) {
return split32bitValueToBytes(4 + (8 + fmt.length) + (8 + data.length));
}
function RIFFChunk(soundData) {
var fmt = FMTSubChunk(soundData);
var data = dataSubChunk(soundData);
var header = [].concat(toCharCodes("RIFF"), chunkSize(fmt, data), toCharCodes("WAVE"));
return [].concat(header, fmt, data);
}
function makeDataURL() {
var settings = getSoundSettings();
applySoundSettings(settings);
var generated = generateSound(settings);
generatePreview(generated);
return "data:audio/x-wav," + toHexString(RIFFChunk({...generated}));
}
var el;
var lastPosition;
function onTimeUpdate() {
if (el && canvas && ctx && imgd) {
var pix = imgd.data;
//alpha values from last position to FF again
var index = lastPosition * 4;
for (var p = 0; p < canvas.height; p++) {
pix[index] = pix[index] ^ 0xFF;
pix[index + 1] = pix[index + 1] ^ 0xFF;
pix[index + 2] = pix[index + 2] ^ 0xFF;
index += canvas.width * 4;
}
var time = el.currentTime;
var seconds = el.seconds;
var pos = Math.floor(canvas.width * time / seconds);
index = pos * 4;
for (var p = 0; p < canvas.height; p++) {
pix[index] = pix[index] ^ 0xFF;
pix[index + 1] = pix[index + 1] ^ 0xFF;
pix[index + 2] = pix[index + 2] ^ 0xFF;
index += canvas.width * 4;
}
lastPosition = pos;
//write image data to canvas
ctx.putImageData(imgd, 0, 0);
}
}
function stop() {
if (el) {
//stop audio and reset src before removing element, otherwise audio keeps playing
el.pause();
el.src = "";
document.getElementById('player').removeChild(el);
lastPosition = 0;
}
el = null;
}
function playDataURI(uri) {
stop();
el = document.createElement("audio");
el.setAttribute("autoplay", true);
el.setAttribute("src", uri);
el.setAttribute("controls", "controls");
el.ontimeupdate = onTimeUpdate;
document.getElementById('player').appendChild(el);
}
|
// pages/info/child-components/info-item/info-item.js
Component({
/**
* 组件的属性列表
*/
properties: {
iconPath: String,
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
itemClick() {
this.triggerEvent('itemClick', {}, {})
}
}
})
|
import React, { Component } from "react";
import {
FormLabel,
FormInput,
FormValidationMessage
} from "react-native-elements";
import styled from "styled-components/native";
import Axios from "axios";
const Title = styled.Text`
color: palevioletred;
font-weight: bold;
font-size: 20px;
`;
const Container = styled.View`
display: flex;
justify-content: center;
align-items: center;
background-color: white;
`;
const StyledView = styled.View`
padding: 5%;
`;
export default class Login extends Component {
render() {
return (
<Container>
<Title>LOGIN</Title>
<Image
style={{
width: 300,
height: 400
}}
source={require("../assets/images/icon.png")}
/>
<FormLabel>Name</FormLabel>
<FormInput onChangeText={someFunction} />
<FormValidationMessage>Error message</FormValidationMessage>
</Container>
);
}
}
|
import React from 'react'
import { RegisterForm } from '../components/RegisterForm';
export const Register = () => {
return (
<RegisterForm />
)
}
|
// const MongoClient = require('mongodb').MongoClient;
// module.exports = function(agenda) {
// agenda.define('archive ride', function(job, done) {
// // Connect to the db
// MongoClient.connect('mongodb://localhost:27017/data', function(err, db) {
// if (!err) {
// // If no error then I query and update my database
// db.collection('rides').findOneAndUpdate(
// { _id: job.attrs.data.rideId },
// { $set: { status: 'expired' } },
// function(err) {
// if (!err) {
// done();
// }
// }
// );
// }
// if (err) {
// console.log(err);
// done();
// }
// });
// });
// };
|
function validateform(){
var fname = document.getElementById("FName").value;
var lname = document.getElementById("LName").value;
var uname = document.getElementById("UName").value;
var add1 = document.getElementById("address").value;
var zip = document.getElementById("zip").value;
var rbtn1 = document.getElementById("radiobtn1").value;
var rbtn2 = document.getElementById("radiobtn2").value;
var rbtn3 = document.getElementById("radiobtn3").value;
var noc = document.getElementById("cardholder").value;
var ccn = document.getElementById("cardnumber").value;
var expiry = document.getElementById("expirydate").value;
var cvv = document.getElementById("cvvnumber").value;
if(fname.length == 0 ){
document.getElementById("msgF").innerHTML = "Valid first name required";
}else if(lname.length == 0){
document.getElementById("msgL").innerHTML = "Valid last name required"
}else if(uname.length == 0){
document.getElementById("msgU").innerHTML = "Valid username required"
}else if(add1.length == 0){
document.getElementById("msgA1").innerHTML = "Valid address required"
}
else if(isNaN(zip)|| zip.length == 0|| zip.length !=5){
document.getElementById("msgZ").innerHTML = "Valid zip code required"
}
else if((rbtn1 == false)&&(rbtn2 == false)&&(rbtn3 == false)){
document.getElementById("msgR").innerHTML = "Please select one option"
}else if(noc.length == 0){
document.getElementById("msgNC").innerHTML = "Valid name required"
}
else if(isNAN(ccn)|| ccn.length == 0 || ccn.length<0 || ccn.length>19){
document.getElementById("msgCCN").innerHTML = "Valid credit card number required"
}
else if(expiry.length == 0){
document.getElementById("msgEx").innerHTML = "Valid expiry date required"
}
else if(isNaN(cvv)|| cvv.length == 0 || cvv.length >4){
document.getElementById("msgCVV").innerHTML = "Valid cvv number required"
}
} |
export function fetchMovies() {;};
|
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./App'],
extensions: [
'.ios.ts',
'.android.ts',
'.ts',
'.ios.tsx',
'.android.tsx',
'.tsx',
'.jsx',
'.js',
'.json',
],
alias: {
'@assets': './App/assets',
'@components': './App/components',
'@containers': './App/containers',
'@config': './App/config',
'@database': './App/database',
'@redux': './App/redux',
'@styles': './App/styles',
'@utils': './App/utils',
},
},
],
]
};
/*
‘root’ specifies your project main directory. Usually, it is called ‘src’.
‘extensions’ allow you to limit the plugin to specific file types.
‘alias’ lets you specify all the folders you need shortcuts for your module imports.
NOTE: You should use full paths for your alias folders otherwise the plugin won’t be able to locate the folders you specified.
*/ |
var gulp = require('gulp');
var watch = require('gulp-watch');
var url = require('url');
var proxy = require('proxy-middleware');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var browserSync = require('browser-sync').create();
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var babel = require('babelify');
function compile(watch) {
var bundler = watchify(browserify('./src/js-cbts.js', {debug: true}).transform(babel));
return bundler.bundle()
.on('error', function(err) {
console.error(err);
this.emit('end');
})
.pipe(source('js-cbts.js'))
// .pipe(buffer()).pipe(sourcemaps.init({loadMaps: true}))
// .pipe(sourcemaps.write('./')).on('error', console.log)
.pipe(gulp.dest('./dist')).on('error', console.log);
}
function taskWatch(which) {
switch(which) {
case "js":
compile(true).pipe(browserSync.stream());
break;
default:
compile(true).pipe(browserSync.stream());
}
};
gulp.task('build', function() {
compile();
});
gulp.task('watch', function() {
// example
var proxyOptions = url.parse('http://localhost:4200/bugreport');
proxyOptions.route = '/bugreport';
browserSync.init({
server: {
baseDir: ['./'],
middleware: [proxy(proxyOptions)]
}
});
watch('./src/*.js', function() {
taskWatch('js');
});
taskWatch();
});
gulp.task('default', ['watch']);
|
var nameLocalStoregeIdentificadores = 'identificadores';
var idEdicao = "";
function adicionarIdentificador() {
const tipoIdentificador = document.getElementById('tipoIdentificadorSl').value;
const areaGeografica = document.getElementById('areaGeograficaSl').value;
const data = document.getElementById('dateInput').value;
const designacao = document.getElementById('designacaoInput').value;
const emissor = document.getElementById('emissorInput').value;
const tipoCertidao = document.getElementById('tipoCertidaoSl').value;
const nomeCartorio = document.getElementById('nomeCartorioInput').value;
const livro = document.getElementById('livroInput').value;
const folha = document.getElementById('folhaInput').value;
const termo = document.getElementById('termoInput').value;
const carteiraSerie = document.getElementById('serieCarteiraInput').value;
const carteiraEstado = document.getElementById('estadoCarteiraInput').value;
const tituloSecao = document.getElementById('secaoTituloInput').value;
const tituloZona = document.getElementById('zonaTituloInput').value;
var id = "id" + Math.random().toString(16).slice(2);
document.getElementById('tabelaVaziaIdentificador').style.display = 'none';
var identificadorObj = new identificadorC(id, tipoIdentificador, areaGeografica, data, designacao, emissor,
tipoCertidao, nomeCartorio, livro, folha, termo, carteiraSerie, carteiraEstado,
tituloSecao, tituloZona);
adicionarItemTableIdentificador(identificadorObj);
saveLocalStorage(identificadorObj,nameLocalStoregeIdentificadores);
clearAllModalIdentificador();
}
function adicionarItemTableIdentificador(identificadorC){
const tableRefIdent = document.getElementById('tableIdentificador').getElementsByTagName('tbody')[0];
const newRowIdent = tableRefIdent.insertRow(tableRefIdent.rows.length);
// Insert a cell in the row at index 0
let cell0 = newRowIdent.insertCell(0);//Tipo identificador
let cell1 = newRowIdent.insertCell(1);//Área geográfica
let cell2 = newRowIdent.insertCell(2);//Data
let cell3 = newRowIdent.insertCell(3);//Designação
let cell4 = newRowIdent.insertCell(4);//Emissor
let cell5 = newRowIdent.insertCell(5);//Tipo de certidão
let cell6 = newRowIdent.insertCell(6);//Nome do cartório
let cell7 = newRowIdent.insertCell(7);//Opçoes
let inputHidden = document.createElement("input");
inputHidden.setAttribute("type", "hidden");
inputHidden.setAttribute("value", identificadorC.id);
cell0.appendChild(inputHidden);
cell0.appendChild(document.createTextNode(identificadorC.tipoIdentificador));
cell1.appendChild(document.createTextNode(identificadorC.areaGeografica));
cell2.appendChild(document.createTextNode(identificadorC.data));
cell3.appendChild(document.createTextNode(identificadorC.designacao));
cell4.appendChild(document.createTextNode(identificadorC.emissor));
cell5.appendChild(document.createTextNode(identificadorC.tipoCertidao));
cell6.appendChild(document.createTextNode(identificadorC.nomeCartorio));
let btnEdit = document.createElement('button');
btnEdit.innerHTML = 'Editar';
btnEdit.className = 'btn btn-sm btn-primary';
btnEdit.setAttribute('type', 'button');
btnEdit.setAttribute('data-target', '#cadastroIdentificadorModal');
btnEdit.setAttribute('data-toggle', 'modal');
btnEdit.addEventListener("click", () => {
editarIdentificador(newRowIdent);
});
let btnDel = document.createElement('button');
btnDel.innerHTML = 'Apagar';
btnDel.className = 'btn btn-sm btn-danger ';
btnDel.addEventListener("click", () => {
tableRefIdent.removeChild(newRowIdent);
if(tableRefIdent.rows.length == 0){
document.getElementById('tabelaVaziaIdentificador').style.display = '';
}
});
cell7.appendChild(btnEdit);
cell7.appendChild(btnDel);
}
function findIdentificadorByid(idVal){
const item = localStorage.getItem(nameLocalStoregeIdentificadores);
const jsonList = JSON.parse(item);
for (var i = 0; i < jsonList.length; i++){
if (jsonList[i].id == idVal){
var objFound = jsonList[i];
}
}
return objFound;
}
function editarIdentificador(node){
let idVal = node.childNodes[0].childNodes[0].value;
const objFound = findIdentificadorByid(idVal);
idEdicao = idVal;
document.getElementById('tipoIdentificadorSl').value = objFound.tipoIdentificador;
document.getElementById('areaGeograficaSl').value = objFound.areaGeografica;
document.getElementById('dateInput').value = objFound.data;
document.getElementById('designacaoInput').value = objFound.designacao;
document.getElementById('emissorInput').value = objFound.emissor;
document.getElementById('tipoCertidaoSl').value = objFound.tipoCertidao;
document.getElementById('nomeCartorioInput').value = objFound.nomeCartorio;
document.getElementById('livroInput').value = objFound.livro;
document.getElementById('termoInput').value = objFound.termo;
document.getElementById('serieCarteiraInput').value = objFound.carteiraSerie;
document.getElementById('estadoCarteiraInput').value = objFound.carteiraEstado;
document.getElementById('secaoTituloInput').value = objFound.tituloSecao;
document.getElementById('zonaTituloInput').value = objFound.tituloZona;
}
function clearAllModalIdentificador() {
idEdicao = "";
document.getElementById('tipoIdentificadorSl').value = '';
document.getElementById('areaGeograficaSl').value = '';
document.getElementById('dateInput').value = '';
document.getElementById('designacaoInput').value = '';
document.getElementById('emissorInput').value = '';
document.getElementById('tipoCertidaoSl').value = '';
document.getElementById('nomeCartorioInput').value = '';
document.getElementById('livroInput').value = '';
document.getElementById('termoInput').value = '';
document.getElementById('serieCarteiraInput').value = '';
document.getElementById('estadoCarteiraInput').value = '';
document.getElementById('secaoTituloInput').value = '';
document.getElementById('zonaTituloInput').value = '';
}
|
/*
Escribe las funciones para llevar a cabo las siguientes
operaciones para un array de una dimensión:
a) Establecer los 10 elementos del array a cero.
b) Añadir 1 a cada uno de los elementos del array.
c) Muestra los valores del array separados por espacios.toString()
*/
function init(){
var list= new Array();
document.write("<h2>Lista de 10 números</h2>");
for (i=1;i<=10;i++){
list.push(i);
}
document.write(list);
toO(list);
to1(list);
splitSpace(list);
}
function toO(x){
document.write("<h2>Lista de 0's números</h2>");
for (i=0;i<10;i++){
x[i]=0;
}
document.write(x);
}
function to1(x){
document.write("<h2>Lista de 1's números</h2>");
for (i=0;i<10;i++){
x[i]=1;
}
document.write(x);
}
function splitSpace(x){
document.write("<h2>números separados por espacios</h2>");
var string = x.toString();
var newString="";
for (i=0;i<string.length;i++){
if (string[i]==","){
newString+= " ";
}else{
newString+=string[i];
}
}
document.write(newString);
}
window.onload = function(){
init();
} |
function puntoMedio() {
var x1 = Number(prompt("En la cordenada 1 escribe tu x1"));
var x2 = Number(prompt("En la cordenada 1 escribe tu x2"));
var y1 = Number(prompt("En la coedenada 2 escribe tu y1"));
var y2 = Number(prompt("En la coedenada 2 escribe tu y2"));
productoUno = (x1+x2)/2;
productoDos = (y1+y2)/2;
alert("El punto medio del segmento de extremos , los puntos:" + "( "+x1+ " ; "+ x2+" )"+" y "+ "( "+y1+"; "+ y2+" )"+ " es: "+ "( "+productoUno+ " ; "+ productoDos+" )" );
} |
var stat = require('node-static');
var bodyParser = require('body-parser');
var express = require('express');
var d = require('../libjs/durable');
var app = express();
var host = d.getHost();
var fileServer = new stat.Server(__dirname);
app.use(bodyParser.json());
function printAction(actionName) {
return function(c) {
c.s.label = actionName;
console.log('Running ' + actionName);
}
}
host.getAction = function(actionName) {
return printAction(actionName);
};
app.get('/:rulesetName/state/:sid', function (request, response) {
response.contentType = 'application/json; charset=utf-8';
try {
response.status(200).send(host.getState(request.params.rulesetName, request.params.sid));
} catch (reason) {
response.status(500).send({ error: reason });
}
});
app.post('/:rulesetName/events/:sid', function (request, response) {
response.contentType = "application/json; charset=utf-8";
var message = request.body;
message.sid = request.params.sid;
host.post(request.params.rulesetName, message, function(e) {
if (e) {
response.status(500).send({ error: e });
} else {
response.status(200).send({});
}
});
});
app.get('/:rulesetName/definition', function (request, response) {
response.contentType = 'application/json; charset=utf-8';
try {
response.status(200).send(host.getRuleset(request.params.rulesetName).getDefinition());
} catch (reason) {
response.status(500).send({ error: reason });
}
});
app.post('/:rulesetName/definition', function (request, response) {
response.contentType = "application/json; charset=utf-8";
host.setRulesets(request.body , function (e, result) {
if (e) {
response.status(500).send({ error: e });
}
else {
response.status(200).send();
}
});
});
app.get('/durableVisual.js', function (request, response) {
request.addListener('end',function () {
fileServer.serveFile('/durableVisual.js', 200, {}, request, response);
}).resume();
});
app.get('/testdynamic.html', function (request, response) {
request.addListener('end', function () {
fileServer.serveFile('/testdynamic.html', 200, {}, request, response);
}).resume();
});
app.get('/:rulesetName/:sid/admin.html', function (request, response) {
request.addListener('end',function () {
fileServer.serveFile('/admin.html', 200, {}, request, response);
}).resume();
});
app.listen(5000, function () {
console.log('Listening on 5000');
});
|
"use strict";
exports.__esModule = true;
var mobile_1 = require("./mobile");
var MobileLibrary_1 = require("./MobileLibrary");
var nokia3210 = new mobile_1.mobile("Nokia3210", "3210", "Nokia", 4, "black", false, 0, 50);
var iPhone3G = new mobile_1.mobile("iPhone3G", "3G", "iPhone", 12, "white", false, 1, 150);
var samsungGalaxy10 = new mobile_1.mobile("Samsung Galaxy 10", "Galaxy 10", "Samsung", 256, "blue", true, 4, 500);
var arrayMobil = [nokia3210, iPhone3G, samsungGalaxy10];
var mobil1 = new mobile_1.mobile("nombre", "modelo", "marca", 256, "color", true, 4, 500);
var mobil2 = new mobile_1.mobile("nombre", "modelo", "marca", 256, "color", true, 4, 500);
var mobil3 = new mobile_1.mobile("nombre", "modelo", "marca", 256, "color", true, 4, 500);
var arraymobil2 = [mobil1, mobil2, mobil3];
var librerianueva = new MobileLibrary_1.mobileLibrary("La Librería", "Calle nueva", arrayMobil);
var libreria2 = new MobileLibrary_1.mobileLibrary("Otra librería", "otra calle", arraymobil2);
function totalPriceCalculation(libreria) {
var totalPrice = 0;
libreria.getMobiles().forEach(function (movil) { return totalPrice = totalPrice + movil.getPrice(); });
return totalPrice;
}
libreria2.printLIbrary();
console.log("-----------------------------------------------------------------");
librerianueva.printLIbrary();
console.log("-----------------------------------------------------------------");
librerianueva.setLocation(libreria2.getLocation());
librerianueva.setMobiles(libreria2.getMobiles());
librerianueva.setName(libreria2.getName());
librerianueva.setTotalPrice(librerianueva.getTotalPrice());
librerianueva.printLIbrary();
|
var indexSectionsWithContent =
{
0: "_acdimnpqrstu",
1: "acdimnpqrstu",
2: "i",
3: "_"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "namespaces",
3: "functions"
};
var indexSectionLabels =
{
0: "All",
1: "Classes",
2: "Namespaces",
3: "Functions"
};
|
const crypto = require('crypto')
const digest = (string) => {
return crypto.createHash('md5').update(string).digest('hex')
}
const addSalt = ({ password, salt }) => {
let ticket = digest(digest(digest(password) + salt) + 'charlene')
return ticket
}
const randstr = (len = 16) => {
let s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
let re = ''
for (let i = 0; i < len; i ++) {
let idx = ~~(Math.random() * s.length)
re = `${re}${s[idx]}`
}
return re
}
module.exports = {
digest,
addSalt,
randstr
} |
function clickpic(e) {
var x = e.offsetX;
var y = e.offsetY;
console.log(x,y);
if (e.target.getAttribute("id")=="confess1"){
e.target.setAttribute("class", "confess2");
e.target.setAttribute("id", "confess2");
}
else if (e.target.getAttribute("id")=="confess2"){
e.target.setAttribute("class", "confess3");
e.target.setAttribute("id", "confess3");
}
else if (e.target.getAttribute("id")=="confess3"){
e.target.setAttribute("class", "confess4");
e.target.setAttribute("id", "confess4");
}
else if (e.target.getAttribute("id")=="confess4"){
e.target.setAttribute("class", "confess5");
e.target.setAttribute("id", "confess5");
}
else if (e.target.getAttribute("id")=="confess5"){
e.target.setAttribute("class", "confess6");
e.target.setAttribute("id", "confess6");
}
else if (e.target.getAttribute("id")=="confess6"){
e.target.setAttribute("class", "confess7");
e.target.setAttribute("id", "confess7");
}
else if (e.target.getAttribute("id")=="confess7"){
e.target.setAttribute("class", "confess8");
e.target.setAttribute("id", "confess8");
}
else if (e.target.getAttribute("id")=="confess8"){
e.target.setAttribute("class", "confess9");
e.target.setAttribute("id", "confess9");
}
else if (e.target.getAttribute("id")=="confess9"){
e.target.setAttribute("class", "confess10");
e.target.setAttribute("id", "confess10");
}
else if (e.target.getAttribute("id")=="confess10"){
e.target.setAttribute("class", "confess11");
e.target.setAttribute("id", "confess11");
}
else if (e.target.getAttribute("id")=="confess11"){
e.target.setAttribute("class", "confess12");
e.target.setAttribute("id", "confess12");
}
else if (e.target.getAttribute("id")=="confess12"){
e.target.setAttribute("class", "confess13");
e.target.setAttribute("id", "confess13");
}
else if (e.target.getAttribute("id")=="confess13"){
e.target.setAttribute("class", "confess14");
e.target.setAttribute("id", "confess14");
}
else if (e.target.getAttribute("id")=="confess14"){
e.target.setAttribute("class", "confess15");
e.target.setAttribute("id", "confess15");
}
else if (e.target.getAttribute("id")=="confess15"){
e.target.setAttribute("class", "confess16");
e.target.setAttribute("id", "confess16");
}
else if (e.target.getAttribute("id")=="confess16"){
e.target.setAttribute("class", "confess17");
e.target.setAttribute("id", "confess17");
}
else if(e.target.getAttribute("id")=="confess17"){
localStorage.setItem("#li6",1);
$("#li6").css("color", "black");
$("#li6").mouseenter(function () {
$("#li6").css("cursor", "pointer");
});
}
} |
import { Injectable } from '@angular/core';
var LeaveComponentGuard = (function () {
function LeaveComponentGuard() {
}
LeaveComponentGuard.prototype.canDeactivate = function (component, route, state) {
return component.canDeactivate();
};
return LeaveComponentGuard;
}());
export { LeaveComponentGuard };
LeaveComponentGuard.decorators = [
{ type: Injectable },
];
/** @nocollapse */
LeaveComponentGuard.ctorParameters = function () { return []; };
|
// Members handler
const _data = require("./data");
const helpers = require("./helpers");
const config = require("./config");
const { _tokens } = require("./tokensHandler");
const members = (data, callback) => {
const acceptableMethods = ["post", "get", "put", "delete"];
if (acceptableMethods.indexOf(data.method) > -1) {
_members[data.method](data, callback);
} else {
callback(405);
}
};
const _members = {};
// Members: post
// Required data: firstName, email
// Optional data: lastName
_members.post = (data, callback) => {
const { payload, headers } = data;
// validate inputs
const firstName =
typeof payload.firstName == "string" && payload.firstName.trim().length > 0
? payload.firstName.trim()
: false;
const lastName =
typeof payload.lastName == "string" && payload.lastName.trim().length > 0
? payload.lastName.trim()
: false;
// TODO: Add email validation
const email =
typeof payload.email == "string" && payload.email.trim().length > 0
? payload.email.trim()
: false;
if (firstName && email) {
// get the token from headers
const token = typeof headers.token == "string" ? headers.token : false;
// Lookup the team by reading the token
_data.read("tokens", token, (err, tokenData) => {
if (!err && tokenData) {
const teamName = tokenData.name;
// Lookup team data
_data.read("teams", teamName, (err, teamData) => {
if (!err && teamData) {
const teamMembers =
typeof teamData.members == "object" &&
teamData.members instanceof Array
? teamData.members
: [];
// verify that the team has less than the number of max-members-per-team
if (teamMembers.length < config.maxMembers) {
// create a random id for the member
const memberId = helpers.createRandomString(20);
// create the member object, and include the team's name
const memberObject = {
id: memberId,
teamName,
firstName,
lastName,
email
};
// save the object
_data.create("members", memberId, memberObject, err => {
if (!err) {
// Add the member id to the team's object
teamData.members = teamMembers;
teamData.members.push(memberId);
// save the new team data
_data.update("teams", teamName, teamData, err => {
if (!err) {
// Return the data about the new member
callback(200, memberObject);
} else {
callback(500, {
Error: "Could not update the team with new member."
});
}
});
} else {
callback(500, { Error: "Could not create the new member" });
}
});
} else {
callback(400, {
Error: `The team already has the maximum number of members ${config.maxMembers}`
});
}
} else {
callback(403);
}
});
} else {
callback(403);
}
});
} else {
callback(400, { Error: "Missing required inputs, or inputs are invalid" });
}
};
// Members - get
// Required data: id
// Optional: none
_members.get = (data, callback) => {
// Check that the id is valid.
const { queryStringObject: qs } = data;
const id =
typeof qs.id == "string" && qs.id.trim().length == 20
? qs.id.trim()
: false;
if (id) {
// Lookup the check
_data.read("members", id, (err, memberData) => {
if (!err && memberData) {
// Get the token from the headers
const token =
typeof data.headers.token == "string" ? data.headers.token : false;
// verify that the given token is valid for the and belongs to the team who created the member
_tokens.verifyToken(token, memberData.teamName, tokenIsValid => {
if (tokenIsValid) {
// Return the member data
callback(200, memberData);
} else {
callback(403);
}
});
} else {
callback(404);
}
});
} else {
callback(400, { Error: "Missing required field" });
}
};
// Members: put
// Required data: id
// Optional data: firstName, lastName, email (one must be sent)
_members.put = (data, callback) => {
// Check for the required field
const { payload } = data;
const id =
typeof payload.id == "string" && payload.id.trim().length == 20
? payload.id.trim()
: false;
// Check for the optional fields
// validate inputs
const firstName =
typeof payload.firstName == "string" && payload.firstName.trim().length > 0
? payload.firstName.trim()
: false;
const lastName =
typeof payload.lastName == "string" && payload.lastName.trim().length > 0
? payload.lastName.trim()
: false;
// TODO: Add email validation
const email =
typeof payload.email == "string" && payload.email.trim().length > 0
? payload.email.trim()
: false;
// Check to make sure id is valid
if (id) {
// Check to make sure one or more optiona fields has been sent
if (firstName || lastName || email) {
// Lookup the members
_data.read("members", id, (err, memberData) => {
if (!err && memberData) {
// Get the token from the headers
const token =
typeof data.headers.token == "string" ? data.headers.token : false;
// verify that the given token is valid and belongs to the team who created the member
_tokens.verifyToken(token, memberData.teamName, tokenIsValid => {
if (tokenIsValid) {
// Update the member where necessary
if (firstName) {
memberData.firstName = firstName;
}
if (lastName) {
memberData.lastName = lastName;
}
if (email) {
memberData.email = email;
}
// Store the new updates
_data.update("members", id, memberData, err => {
if (!err) {
callback(200);
} else {
callback(500, { Error: "Could not update the member" });
}
});
} else {
callback(403);
}
});
} else {
callback(400, { Error: "Member ID did not exist" });
}
});
} else {
callback(400, { error: "Missing fields to update" });
}
} else {
callback(400, { Error: "Missing required field" });
}
};
// Members - delete
// Required data: id
// Optional data: none
_members.delete = (data, callback) => {
// Check that the id is valid.
const { queryStringObject: qs } = data;
const id =
typeof qs.id == "string" && qs.id.trim().length == 20
? qs.id.trim()
: false;
// Lookup the team
if (id) {
// Lookup the member
_data.read("members", id, (err, memberData) => {
if (!err && memberData) {
// Get the token from the headers
const token =
typeof data.headers.token == "string" ? data.headers.token : false;
// verify that the given token is valid for the team
_tokens.verifyToken(token, memberData.teamName, tokenIsValid => {
if (tokenIsValid) {
// Delete the member data
_data.delete("members", id, err => {
if (!err) {
// Lookup the team
_data.read("teams", memberData.teamName, (err, teamData) => {
if (!err && teamData) {
const teamMembers =
typeof teamData.members == "object" &&
teamData.members instanceof Array
? teamData.members
: [];
// Remove the deleted member from their list of members
const memberPosition = teamMembers.indexOf(id);
if (memberPosition > -1) {
teamMembers.splice(memberPosition, 1);
// re-save the team's data
_data.update(
"teams",
memberData.teamName,
teamData,
err => {
if (!err) {
callback(200);
} else {
callback(500, {
Error: "Could not update the team"
});
}
}
);
} else {
callback(500, {
Error:
"Could not find the member on the teams's object, so could not remove it."
});
}
} else {
callback(500, {
Error:
"Could not find the team who created the member, so could not remove the member from the list of members on the team object"
});
}
});
} else {
callback(500, { Error: "Could not delete the member data" });
}
});
} else {
callback(403);
}
});
} else {
callback(400, { Error: "The specified member ID does not exist" });
}
});
} else {
callback(400, { Error: "Missing required field" });
}
};
module.exports = members;
|
const nodeFetch = require('node-fetch')
const { createApi } = require('unsplash-js')
const dotenv = require('dotenv').config()
const unsplash = createApi({
accessKey: process.env.UNSPLASH_ACCESS_KEY,
fetch: nodeFetch
})
const getRandomLandlordImage = async () => {
const { response } = await unsplash.photos.getRandom({ query: "person", orientation: "squarish" })
return response.urls.regular
}
module.exports = {
unsplash,
getRandomLandlordImage
} |
function myselfPlugin() {}
myselfPlugin.prototype.apply = function(compiler) {
compiler.plugin('run', function(compiler, callback) {
console.log('webpack 开始构建');
callback();
})
}
module.exports = myselfPlugin; |
const mongoose = require('mongoose');
const secrets = require('../config/secrets');
const autores = require('../models/autores.model');
const recetas = require('../models/recetas.model')
//Conectarse a mongo!
mongoose.connect(secrets.mongo_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
//Crear las funciones que irán asociadas a los endpoints
//CRRUD
//1.- CREATE
exports.registrarAutor = async (req, res) => {
//Checkear el body
const nuevoAutor = new autores({
"_id": mongoose.Types.ObjectId(),
"firstName": req.body.firstName,
"secondName": req.body.secondName,
"age": req.body.age
});
try {
const result = await nuevoAutor.save();
res.send(result)
} catch (error) {
console.log(error);
res.send({"error": "No se ha podido registrar el usuario"})
}
}
//2.- UPDATE
exports.actualizarAutor = async (req, res) => {
//Checkear el body
const id = req.body._id;
try {
const result = await autores.findByIdAndUpdate(id, {
$set: {
"firstName": req.body.firstName,
"secondName": req.body.secondName,
"age": req.body.age,
"__v": req.body.__v
}
})
res.send({"ok": "usuario modificado"})
} catch (error) {
console.log(error);
res.send({"error": "el usuario no se ha podido modificar"})
}
}
// 3.- Read (single)
exports.leerAutorPorId = async (req, res) => {
const _id = req.params._id;
try {
const usuario = await autores.find({
"_id": _id
})
res.send(usuario)
} catch (error) {
console.log(error);
res.send({"error": "usuario no encontrado!"})
}
}
// 4.- Read (all)
exports.leerTodosLosAutores = async (req, res) => {
try {
const usuario = await autores.find()
res.send(usuario)
} catch (error) {
console.log(error);
res.send({"error": "usuario no encontrado!"})
}
}
// 5.- Delete
exports.eliminarAutorPorId = async (req, res) => {
const _id = req.params._id;
try {
const result = await autores.findByIdAndDelete(_id);
res.send(result)
} catch (error) {
console.log(error);
res.send({"error": "el usuario no se ha podido eliminar"})
}
}
// 6.- Create RECETA
exports.registrarReceta = async (req, res) => {
//Checkear el body
const nuevoReceta = new recetas({
"_id": mongoose.Types.ObjectId(),
"name": req.body.name,
"ingredientes": req.body.ingredientes,
"author_id": req.body.author_id
});
try {
const result = await nuevoReceta.save();
res.send(result)
} catch (error) {
console.log(error);
res.send({"error": "No se ha podido registrar la receta"})
}
}
//7.- GET (single receta)
exports.leerRecetaPorId = async (req, res) => {
const _id = req.params._id;
try {
const receta = await recetas.find({
"_id": _id
})
const author = await autores.find({
"_id": receta[0].author_id
})
res.send({"receta": receta, "author": author})
} catch (error) {
console.log(error);
res.send({"error": "receta no encontrada!"})
}
}
|
(function (angular) {
"use strict";
function constructor($location, usersService) {
var vm = this;
function addUser(user) {
var index=usersService.addUser(user);
$location.path("/list");
}
vm.addUser = addUser;
}
constructor.$inject = ['$location','usersService'];
angular.module("mainApp").controller("createNewController", constructor);
})(window.angular);
|
var mongoose = require('mongoose');
var keyRecord = require('../models/keyRecord');
var Keyword = require('../models/keyword');
var async = require("async");
var constant = require('../constants.js');
exports.addRecord = function(req,res){
console.log(req.body);
var type = req.body.type;
var key = req.body.key;
if( typeof type === 'undefined' || typeof key === 'undefined' || key == '' || type =='' ){
res.json({
status: 'error',
messages: 'invaild message format'
});
}else{
keyRecord.findOne({'key':key, 'type': type}, function(err, record){
if(record == null){
// create new record is not exist
var newRecord = new keyRecord({
'key': key,
'type': type,
'exist': false
});
async.series([
function(callback){
Keyword.find({'value': key, 'type': type}, function(err, result){
if(result.length > 0)
newRecord.exist = true;
callback();
});
},
function(callback){
newRecord.save(function(err, result){
if(err){
res.json({
status: 'error',
data: err
});
}else{
res.json({
status: 'ok',
data: result
});
}
});
}
]);
}else{
record.count++;
record.save(function(err, result){
res.json({
status: 'ok',
data: result
});
});
}
});
}
}
exports.getRecords = function(req,res){
keyRecord.find({exist:true}).sort('-count').exec(function(err, docs) {
console.log(docs);
res.json({
status: 'ok',
data: docs
});
});
} |
/**
*
* @authors zx.wang (zx.wang1991@gmail.com)
* @date 2016-08-22 18:08:16
* @version $Id$
*/
/**
* Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?
* Find all unique quadruplets in the array which gives the sum of target.
* Note: The solution set must not contain duplicate quadruplets.
*
* For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
*
* A solution set is:
* [
* [-1, 0, 0, 1],
* [-2, -1, 1, 2],
* [-2, 0, 0, 2]
* ]
*
* 题意:
* 给定一个含有n个整数的数组S,是否存在元素a, b, c, 和 d 在数组S中可以满足 a + b + c + d = target ?
* 在给定目标值的和以后找到在数组S中所有不重复的元素组合。
*/
/**
* 方法一:4 to 3 to 2
*/
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
let result = [];
const len = nums.length;
if (nums === null || len < 4) return result;
nums.sort(function(a, b) {
return a - b;
});
let max = nums[len - 1];
if (4 * nums[0] > target || 4 * max < target) return result;
let i, z;
for (i = 0; i < len; i++) {
z = nums[i];
if (i > 0 && z == nums[i - 1]) // avoid duplicate
continue;
if (z + 3 * max < target) // z is too small
continue;
if (4 * z > target) // z is too large
break;
if (4 * z == target) { // z is the boundary
if (i + 3 < len && nums[i + 3] == z) {
let inres = [];
inres.push(z);
inres.push(z);
inres.push(z);
inres.push(z);
result.push(inres);
break;
}
}
threeSumForFourSum(nums, target - z, i + 1, len - 1, result, z);
}
return result;
};
function threeSumForFourSum(nums, target, low, high, fourSumList, z1) {
if (low + 1 >= high)
return;
let max = nums[high];
if (3 * nums[low] > target || 3 * max < target)
return;
let i, z;
for (i = low; i < high - 1; i++) {
z = nums[i];
if (i > low && z == nums[i - 1]) // avoid duplicate
continue;
if (z + 2 * max < target) // z is too small
continue;
if (3 * z > target) // z is too large
break;
if (3 * z == target) { // z is the boundary
if (i + 1 < high && nums[i + 2] == z) {
let infourSumList = [];
infourSumList.push(z1);
infourSumList.push(z);
infourSumList.push(z);
infourSumList.push(z);
fourSumList.push(infourSumList);
break;
}
}
twoSumForFourSum(nums, target - z, i + 1, high, fourSumList, z1, z);
}
}
function twoSumForFourSum(nums, target, low, high, fourSumList, z1, z2) {
if (low >= high)
return;
if (2 * nums[low] > target || 2 * nums[high] < target)
return;
let i = low,
j = high,
sum, x;
while (i < j) {
sum = nums[i] + nums[j];
if (sum == target) {
let infourSumList = [];
infourSumList.push(z1);
infourSumList.push(z2);
infourSumList.push(nums[i]);
infourSumList.push(nums[j]);
fourSumList.push(infourSumList);
x = nums[i];
while (++i < j && x == nums[i]) // avoid duplicate
;
x = nums[j];
while (i < --j && x == nums[j]) // avoid duplicate
;
}
if (sum < target)
i++;
if (sum > target)
j--;
}
return;
}
/**
* 方法二
*/
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
let res = [];
nums.sort(function(a, b) {
return a - b;
});
if (nums === null || nums.length < 4) return res;
for (let i = 0; i < nums.length - 3; i++) {
if (i !== 0 && nums[i] === nums[i - 1]) {
continue;
}
for (let j = i + 1; j < nums.length - 2; j++) {
if (j !== i + 1 && nums[j] === nums[j - 1]) {
continue;
}
let left = j + 1;
let right = nums.length - 1;
while (left < right) {
let sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
let tmp = [];
tmp.push(nums[i]);
tmp.push(nums[j]);
tmp.push(nums[left]);
tmp.push(nums[right]);
res.push(tmp);
left++;
right--;
while (left < right && nums[left] === nums[left - 1]) {
left++;
}
while (left < right && nums[right] === nums[right + 1]) {
right--;
}
}
}
}
}
return res;
};
|
/*
My friend wants a new band name for her band.
She like bands that use the formula: 'The' + a noun with first letter capitalized.
dolphin -> The Dolphin
However, when a noun STARTS and ENDS with the same letter, she likes to repeat the noun twice and connect them together with the first and last letter, combined into one word like so (WITHOUT a 'The' in front):
alaska -> Alaskalaska
europe -> Europeurope
Can you write a function that takes in a noun as a string, and returns her preferred band name written as a string?
*/
function bandNameGenerator(str) {
let firstLetter = str[0];
let lastLetter = str[str.length-1];
let resultStr = "";
if (firstLetter === lastLetter) {
let firstPart = str[0].toUpperCase() + str.slice(1);
let secondPart = str.slice(1);
resultStr = resultStr + firstPart + secondPart;
} else {
resultStr = 'The' + ' ' + str[0].toUpperCase() + str.slice(1);
}
return resultStr;
}
|
import React, { useContext } from 'react';
import cn from 'classnames';
import style from './style.module.css';
import { StateContext } from '../../app/App';
export const Preloader = () => {
const {state: {
preloaderText,
isAppReady,
}} = useContext(StateContext);
return (
<div className={cn(style.preloader, isAppReady && style.preloader_hidden )}>
<div className={style['lds-dual-ring']}></div>
<div className={style.preloader__text}>
{preloaderText}
</div>
</div>
)
};
|
window.onload = function (){
var btn = document.getElementById("tAdd");
var body = document.getElementById("block");
loadFeed();
btn.addEventListener("click",(event)=>{
let user = "Utkarsh";
event.preventDefault();
text = document.getElementById("tweetCnt").value;
if(text == ""){
}
else{
tweet = createTweet(user,text);
body.appendChild(tweet);
storeTweet(user,text);
}
document.getElementById("tweetCnt").value = "";
})
};
function createTweet(username,content)
{
tweet = document.createElement('div');
tweet.setAttribute("class","tweet");
head = document.createElement("h1");
head.innerHTML = username;
hr = document.createElement("hr");
hr.style.size ="1";
hr.style.width= "90%";
hr.style.color = "lightskyblue"
br = document.createElement("br");
p = document.createElement("p");
p.innerHTML = content;
tweet.appendChild(head);
tweet.appendChild(hr);
tweet.appendChild(br);
tweet.appendChild(p);
return tweet;
}
async function storeTweet(username,content)
{
await axios.post('http://localhost:5000/addPost',
JSON.stringify({
"username" : username,
"content" : content
}))
.then(function (response) {
console.log(response);
})
.catch(err => {
console.error(err);
});
}
async function loadFeed()
{
var body = document.getElementById("block");
await axios.get('http://localhost:5000/getPosts')
.then(function (response) {
var data = response.data;
for(let i=data.length-1;i>=0;i--)
{
tweet = createTweet(data[i].username,data[i].content);
body.appendChild(tweet);
}
})
.catch(err => {
console.error(err);
});
} |
var expect = require('chai').expect;
var getBossMW = require('../../middleware/boss/getBossMW');
describe('getBoss middleware ', function () {
it('should return boss with id 1 from db and put it to res.locals.boss', function (done) {
const mw =getBossMW({
BossModel: {
findOne: (p1,cb) => {
expect(p1).to.be.eql({_id:'1'});
cb(null,{
name:'name1',
dateOfBirth:new Date("1990-12-10"),
nickName:'nick1',
wealth:12,
picture:'pic1'
});
}
}
});
const resMock = {
locals: {}
}
mw({
params: {
bossid:'1'
}
},
resMock,
(err) => {
expect(err).to.be.eql(undefined);
expect(resMock.locals).to.be.eql({boss: {
name:'name1',
dateOfBirth:new Date("1990-12-10"),
nickName:'nick1',
wealth:12,
picture:'pic1'
}, formattedDate: '1990-12-10'});
done();
})
});
it('should return with db error', function (done) {
const mw =getBossMW({
BossModel: {
findOne: (p1,cb) => {
expect(p1).to.be.eql({_id:'1'});
cb('dbError',null);
}
}
});
const resMock = {
locals: {}
}
mw({
params: {
bossid:'1'
}
},
resMock,
(err) => {
expect(err).to.be.eql('dbError');
done();
})
});
it('should return boss not found err', function (done) {
const mw =getBossMW({
BossModel: {
findOne: (p1,cb) => {
expect(p1).to.be.eql({_id:'1'});
cb(undefined,null);
}
}
});
const resMock = {
locals: {}
}
mw({
params: {
bossid:'1'
}
},
resMock,
(err) => {
expect(err).to.be.eql(undefined);
expect(resMock.locals).to.be.eql({})
done();
})
});
});
|
// Generated by CoffeeScript 1.4.0
(function() {
var Cc, Ci, Cm, Cr, Cu, ObserverHandler, WebTxt, data, file, sendSMS, tabs, widget, widgets, _ref,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
data = require('sdk/self').data;
WebTxt = (function() {
function WebTxt() {
this.run = __bind(this.run, this);
this.sendMessage = __bind(this.sendMessage, this);
var _this = this;
this.chatBox = require('sdk/panel').Panel({
contentScriptWhen: 'ready',
contentScriptFile: [data.url('jquery-2.1.0.min.js'), data.url('webtxt.js')],
contentURL: data.url('textpanel.html'),
onMessage: function(msg) {
return _this.sendMessage(msg);
},
position: {
right: 0,
bottom: 0
},
width: 250,
height: 300
});
console.log('ran constructor', this.chatBox);
}
WebTxt.prototype.sendMessage = function(msg) {
this.chatBox.postMessage(msg);
return sendSMS(msg);
};
WebTxt.prototype.run = function() {
console.log('showing panel');
return this.chatBox.show();
};
return WebTxt;
})();
this.webTxt = new WebTxt;
widgets = require('sdk/widget');
tabs = require('sdk/tabs');
widget = widgets.Widget({
id: 'launch-webtxt',
label: 'WebTxt',
contentURL: require('sdk/self').data.url('media/toolbar-large.png'),
onClick: this.webTxt.run
});
_ref = require('chrome'), Cc = _ref.Cc, Ci = _ref.Ci, Cm = _ref.Cm, Cr = _ref.Cr, Cu = _ref.Cu;
Cu["import"]("resource://gre/modules/Services.jsm");
console.log('Initializing node server');
file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsILocalFile);
file.initWithPath('/home/shadowhawke/bin/node-v0.10.26/node');
if (!file.exists()) {
console.log('Server failed to Initialize');
return;
}
this.process = Cc['@mozilla.org/process/util;1'].createInstance(Ci.nsIProcess);
this.process.init(file);
ObserverHandler = {
observe: function(subject, topic, data) {
switch (topic) {
case "process-finished":
return console.log("Process finished");
case "process-failed":
return console.log("Process failed");
case "quit-application-granted":
return this.process.kill();
}
}
};
sendSMS = function(msg) {
var args;
args = ["/home/shadowhawke/Documents/CS-Homework/Dc2/webtxt/lib/sms.js", msg];
return this.process.runAsync(args, args.length, ObserverHandler);
};
Services.obs.addObserver(ObserverHandler, "quit-application-granted", false);
}).call(this);
|
/*
后台登录 内在灵魂,沉稳坚毅
生成时间:Sat Oct 08 2016 破门狂人R2-D2为您服务!
*/
define('adminLogin', [
'avalon',
'text!../../package/adminLogin/adminLogin.html',
'css!../../package/adminLogin/adminLogin.css',
'../../obj/bridge/User',
'../../plugins/isIt/isIt.js',
'../../plugins/Gate/Gate.js'
], function (avalon, html, css, obj) {
var vm = avalon.define({
$id: "adminLogin",
ready: function (i) {
var obj = ''
if (obj != "") {
require(['../../obj/Management/' + obj + '.js'], function () {
start()
})
} else {
start()
}
function start() {
vm.reset()
index.html = html
//以及其他方法
//自动登陆
Gate.comeIn({
haveLogin: function (res) {
if (res.d.Company.CompanyID !== '1') {
tip.on('请使用管理员账户登录')
require(['../../obj/bridge/User'],function (User) {
User.logout(function () {
goto('#!/adminLogin/0');
})
})
Gate.reset()
return
}
// var G=res.G
index.uid = res.UID
goto('#!/OrderListAdmin/0');
},
})
}
},
reset: function () {
avalon.mix(vm, {
info: {
Account: '',
PWD: ''
},
flag: 0,
count: 60,
accountPhone: "",
Code:"",
})
},
info: {
Account: '',
PWD: ''
},
flag: 0,
waitingCode: false,
count: 60,
accountPhone: "",
Code:"",
waitCode: function () {
vm.waitingCode = true;
clearInterval(vm.interval);
vm.interval = setInterval(function () {
vm.count--;
if (vm.count <= 0) {
clearInterval(vm.interval);
vm.waitingCode = false;
vm.count=60;
}
}, 1000)
},
getInChange: function () {
if (vm.flag == 0) {
vm.flag = 1;
} else {
vm.flag = 0;
}
},
getCode: function () {
vm.waitCode();
var data = {
Account: '',
Type: "Alidayu",
UID: ""
};
var accountVal = document.getElementById('Phone').value;
data.Account = vm.accountPhone;
if (data.Account == '') {
if (accountVal == '') {
tip.on("账户名或手机号码不能为空");
return
} else {
data.Account = accountVal
}
}
// if (isIt.mobile(data.Account) === false) {
// tip.on("请正确填写手机号");
// return
// }
obj.sendVerify(data.UID, data.Account, data.Type, function (res) {
tip.on("短信验证码已发送,请注意接收", 1, 3000);
}, function (err) {
tip.on("发送失败", 0, 3000);
console.error("ERROR :" + err);
})
},
getInByMsg: function () {
var data = {
Account: '',
Code: ""
};
var accountVal = document.getElementById('Phone').value,
codeVal = document.getElementById('Code').value;
data.Account = vm.accountPhone;
data.Code = vm.Code;
if (data.Account == '') {
if (accountVal == '') {
tip.on("手机号码不能为空");
return
} else {
data.Account = accountVal
}
}
if (data.Code == '') {
if (codeVal == '') {
tip.on("请输入验证码");
return
} else {
data.Code = accountVal
}
}
obj.loginByCode(data.Account, data.Code, function (res) {
if (res.Company.CompanyID !== '1') {
tip.on('请使用管理员账户登录');
User.logout();
Gate.reset();
return
}
goto("#!/OrderListAdmin/0")
cache.go(res)
index.uid = cache.go('UID')
cache.go('UN')
index.un = res.Name
}, function (err) {
tip.on(err)
})
},
login: function () {
if (vm.flag == 0) {
vm.loginByPWD();
} else {
vm.getInByMsg();
}
},
loginByPWD: function () {
var data = {
Account: '',
PWD: ''
};
var accountVal = document.getElementById('Account').value,
PWDVal = document.getElementById('PWD').value
avalon.mix(data, vm.info)
if (data.Account == '') {
if (accountVal == '') {
tip.on("用户名不能为空")
return
} else {
data.Account = accountVal
}
}
if (data.PWD == "") {
if (PWDVal == '') {
tip.on("密码不能为空")
return
} else {
data.PWD = PWDVal
}
}
obj.login(data.Account, data.PWD, function (res) {
if (res.Company.CompanyID !== '1') {
tip.on('请使用管理员账户登录')
obj.logout(function () {
goto('#!/adminLogin/0');
})
Gate.reset()
return
}
goto("#!/OrderListAdmin/0")
cache.go(res)
index.uid = cache.go('UID')
cache.go('UN')
index.un = res.Name
}, function (err) {
tip.on(err)
})
}
})
return window[vm.$id] = vm
}) |
import invariant from 'invariant';
let __DefaultComponent;
export const setDefaultComponent = Component =>
(__DefaultComponent = Component);
export const getDefaultComponent = () => {
invariant(__DefaultComponent, '[Redux Intl] Default component is not set.');
return __DefaultComponent;
};
|
(function(){
"use strict";
angular
.module("Main.cart",[] )
.controller("cartController", cartController);
function cartController($http, $scope, $rootScope, cartService) {
/*$scope.removeItem = function(cartProduct){
cartService.removeItem(cartProduct);
}*/
$scope.removeItem = function(product){
cartService.removeItem(product);
}
$scope.increaseQuantity = function(product){
cartService.increaseQuantity(product);
}
$scope.decreaseQuantity = function(product){
cartService.decreaseQuantity(product);
}
$scope.invoice = function(cartProducts){
var userInfo = {};
var u = $scope.user;
var invoice = [userInfo, $rootScope.cartProducts];
userInfo["firstname"] = u.firstname;
userInfo["lastname"] = u.lastname;
userInfo["email"] = u.email;
userInfo["city"] = u.city;
userInfo["zip"] = u.zip;
console.log(invoice);
$http.post('/checkout', invoice).success(function() {
window.location= '#/';
});
}
}
}()); |
const gulp =require("gulp");
gulp.task("hello",function(){
console.log("hello");
})
//html
gulp.task("copy-html",function(){
return gulp.src("html/*.html")
.pipe(gulp.dest("dist/html"))
.pipe(connect.reload());
})
//images拷贝图片
gulp.task("images",function(){
return gulp.src("images/**/*")
.pipe(gulp.dest("dist/images"))
.pipe(connect.reload());
})
//拷贝js文件
gulp.task("scripts",function(){
return gulp.src("js/*.js")
.pipe(gulp.dest("dist/js"))
.pipe(connect.reload());
})
gulp.task("icon",function(){
return gulp.src("icon/*.css")
.pipe(gulp.dest("dist/icon"))
.pipe(connect.reload());
})
//将scss文件转化成css文件
//生成两部分 min.css .css
//gulp-scss giulp-minify-css gulp-rename
const scss =require("gulp-sass-china");
const minify = require("gulp-minify-css");
const rename =require("gulp-rename");
//css
gulp.task("scss-index",function(){
return gulp.src("scss/index.scss")
.pipe(scss())
.pipe(gulp.dest("dist/css"))
.pipe(minify())
.pipe(rename("index.min.css"))
.pipe(gulp.dest("dist/css"))
.pipe(connect.reload());
})
gulp.task("scss-enter",function(){
return gulp.src("scss/enter.scss")
.pipe(scss())
.pipe(gulp.dest("dist/css"))
.pipe(minify())
.pipe(rename("enter.min.css"))
.pipe(gulp.dest("dist/css"))
.pipe(connect.reload());
})
gulp.task("scss-register",function(){
return gulp.src("scss/register.scss")
.pipe(scss())
.pipe(gulp.dest("dist/css"))
.pipe(minify())
.pipe(rename("register.min.css"))
.pipe(gulp.dest("dist/css"))
.pipe(connect.reload());
})
gulp.task("scss-productlist",function(){
return gulp.src("scss/productlist.scss")
.pipe(scss())
.pipe(gulp.dest("dist/css"))
.pipe(minify())
.pipe(rename("productlist.min.css"))
.pipe(gulp.dest("dist/css"))
.pipe(connect.reload());
})
//拷贝data文件 整理数据源
gulp.task("data",function(){
return gulp.src("data/*.json")
.pipe(gulp.dest("dist/data"))
.pipe(connect.reload());
})
//上述操作都是整理文件的,作为整体,建立项目的整体,让他们一起来执行
gulp.task("build",["copy-html","images","scripts","data","scss-index","icon","scss-enter","scss-register","scss-productlist"],function(){
console.log("编译成功");
})
//gulp的监听
gulp.task("watch",function(){
/*
两个参数
第一个参数我们要监听文件路径
第二个参数我们监听到变化以后,要去执行的任务
*/
gulp.watch("html/*.html",["copy-html"]);
gulp.watch("images/**/*",["images"]);
gulp.watch("js/*.js",["scripts"]);
gulp.watch("data/*.json",["data"]);
gulp.watch("scss/*.scss",["scss-index"]);
gulp.watch("scss/*.scss",["scss-enter"]);
gulp.watch("scss/*.scss",["scss-register"]);
gulp.watch("scss/*.scss",["scss-productlist"]);
})
//启动服务器
// gulp-connect
var connect = require("gulp-connect");
gulp.task("server",function(){
connect.server({
root:"dist",
port:8888,
livereload:true //自动刷新
})
})
gulp.task("default",["watch","server"]); |
/**
* Change color of logotype, menu button,
* language links and top links when scroll
*/
import $ from 'jquery';
import ScrollMagic from 'scrollmagic';
import debounce from 'lodash/debounce';
// selectors for sections on page that may trigger changes of color
const sections = ['.hero-group', '.footer', '.toparea'];
const root = $('body');
const createController = () => new ScrollMagic.Controller({ container: 'body' });
export default function navColorChange(controller = createController()) {
sections.forEach(selector => {
const section = $(selector);
if (!section.length) return;
const duration = section.outerHeight();
// top line
const scene1 = new ScrollMagic.Scene({
triggerHook: 'onLeave',
triggerElement: section[0],
offset: -40,
duration: duration
}).on('enter leave', () => {
root.toggleClass('top-line-cc');
}).addTo(controller);
// middle line
const scene2 = new ScrollMagic.Scene({
triggerHook: 'onCenter',
triggerElement: section[0],
duration
}).on('enter leave', () => {
root.toggleClass('middle-line-cc');
}).addTo(controller);
$(window).on('resize', debounce(() => {
const duration = section.outerHeight();
scene1.duration(duration);
scene2.duration(duration);
}, 200));
});
}
|
/**
* File: user list item
* Author: Filip Jarno
* Date: 23.08.2014
*/
define([
'backbone',
'marionette',
'jquery',
'underscore',
'config'
], function (Backbone, Marionette, $, _, config) {
'use strict';
var CLASS = {
USER_LIST_ITEM: 'user-list-item',
LIST_GROUP_ITEM: 'list-group-item',
BADGE: 'badge',
TEXT: 'text',
PICTURE: 'picture',
IS_BUYING_PRESENT:'is-buying-present',
CHECKMARK: 'checkmark'
},
TEMPLATE =
'<div class="placeholder person-placeholder">\
<div class="picture"></div>\
</div>\
<span class="badge"></span>\
<span class="text"></span>\
<span class="checkmark"> ✓</span>';
app.views.UserListItem = Marionette.ItemView.extend({
template: _.template(TEMPLATE),
tagName: 'a',
className: CLASS.USER_LIST_ITEM + ' ' + CLASS.LIST_GROUP_ITEM,
ui: {
presentsCount: '.' + CLASS.BADGE,
text: '.' + CLASS.TEXT,
picture: '.' + CLASS.PICTURE,
checkmark: '.' + CLASS.CHECKMARK
},
triggers: {
'click': app.EVENTS.USER.SHOW
},
onRender: function () {
this.setText(this.model.get('username'));
this.setPresentsCount(this.model.get('presentsCount'));
this.setPicture(config.USER_PICTURES_PATH + this.model.id + '.jpg');
this.setNewActivityStatus();
this.setIsBuyingPresent(this.model.isBuyingPresent());
this.ui.checkmark.tooltip({title: app.language.BUYING_PRESENT_FOR + ' ' + this.model.get('username') + '!', placement: 'right', delay: {show: 500, hide: 0}});
},
setText: function (text) {
this.ui.text.text(text);
return this;
},
setPresentsCount: function (count) {
this.ui.presentsCount.text(count);
return this;
},
setPicture: function (url) {
this.ui.picture.css('background-image', 'url(' + url + ')');
return this;
},
setNewActivityStatus: function () {
var lastActivity = this.model.get('lastActivity'),
lastSeen = app.user.get('lastSeen') || {},
hasNewActivity = lastActivity && (!lastSeen[this.model.id] || lastSeen[this.model.id] < lastActivity.date);
this.$el.toggleClass('has-new-activity', !!hasNewActivity);
return this;
},
setIsBuyingPresent: function (value) {
this.$el.toggleClass(CLASS.IS_BUYING_PRESENT, value);
}
});
return app.views.UserListItem;
}); |
'use strict';
import JWT from 'passport-jwt';
import { UserAccount } from '../models/user';
import config from '../config/database';
const AUTH_HEADER = 'jwt';
exports.AUTH_HEADER = AUTH_HEADER;
exports.config = function(passport) {
const opts = {};
opts.secretOrKey = config.secret;
opts.jwtFromRequest = JWT.ExtractJwt.fromHeader(AUTH_HEADER);
passport.use(new JWT.Strategy(opts, function(jwt_payload, callback) {
UserAccount.findOne({id: jwt_payload.id}, function(err, user) {
if (err) return callback(err, false);
if (user) {
callback(null, user);
} else {
callback(null, false);
}
});
}));
};
|
const Intern = require('../lib/Intern');
test("creates a Intern object", () => {
const intern = new Intern("Tony", "1", "ironman@email.com", "UNISA");
expect(intern.name).toEqual("Tony");
expect(intern.id).toEqual("1");
expect(intern.email).toEqual("ironman@email.com");
expect(intern.school).toEqual("UNISA");
});
test("gets intern school", () => {
const intern = new Intern("Tony", "1", "ironman@email.com", "UNISA");
expect(intern.getSchool()).toEqual("UNISA");
});
test("gets intern role", () => {
const intern = new Intern("Tony", "1", "ironman@email.com", "UNISA");
expect(intern.getRole()).toEqual("Intern");
});
|
import React from "react";
import {Card, Select} from "antd";
const Option = Select.Option;
const WithValue = () => {
function handleChange(value) {
console.log(value); // { key: "lucy", label: "Lucy (101)" }
}
return (
<Card className="gx-card" title="With Value">
<Select labelInValue defaultValue={{key: 'lucy'}} style={{width: 120}} onChange={handleChange}>
<Option value="jack">Jack (100)</Option>
<Option value="lucy">Lucy (101)</Option>
</Select>
</Card>
);
};
export default WithValue;
|
/**
* FLOOR MANAGER
* populates the dance floor
*/
var floorMgr = {};
floorMgr.addPartyAnimal = function(){
// for testing
//$( ui.floor ).text( JSON.stringify(round.animalsCreated) );
//$( ui.floor ).append( JSON.stringify(ANIMIX.currParts) + "<br>" );
//console.log( ANIMIX.currParts );
var newAnimal = {};
newAnimal.head = "<div class='bobbing-head'><div class='partier-head animal-" + ANIMIX.currParts.a + "'></div></div>";
newAnimal.torso = "<div class='partier-torso animal-" + ANIMIX.currParts.b + "'></div>";
newAnimal.butt = "<div class='partier-butt animal-" + ANIMIX.currParts.c + "'></div>";
var wrapper = $( ui.panels.animal ).clone().removeClass( "hide" ).attr("id","");
// FIXME couldn't get this to work - maybe something to do with it not being a dom node yet? hardcoded for now
// function bobbing( elem ){
// return $( elem ).wrap( "<div class='bobbing-head'></div>" );
// }
// console.log(bobbing(newAnimal.head));
wrapper
.append( newAnimal.head )
.append( newAnimal.torso )
.append( newAnimal.butt );
$( ui.floor ).prepend( wrapper );
};
//console.log("pausing!"); |
var IsHelpedBys = require('../models/isHelpedBys')
, _ = require('lodash')
, writeResponse = require('../helpers/response').writeResponse
, dbUtils = require('../neo4j/dbUtils');
/**
* @swagger
* definition:
* IsHelpedBy:
* type: object
* properties:
* id:
* type: integer
* singleId:
* type: integer
* friendId:
* type: integer
*/
/**
* @swagger
* /api/v0/ishelpedby:
* post:
* tags:
* - ishelpedby
* description: Create a new relation of type IS_HELPED_BY
* produces:
* - application/json
* parameters:
* - name: body
* in: body
* type: object
* schema:
* properties:
* singleId:
* type: object
* friendId:
* type: object
* responses:
* 201:
* description: Your new relation
* schema:
* $ref: '#/definitions/IsHelpedBy'
* 400:
* description: Error message(s)
*/
exports.createRelation = function (req, res, next) {
const singleId = _.get(req.body, 'singleId');
const friendId = _.get(req.body, 'friendId');
IsHelpedBys.createRelation(dbUtils.getSession(req), singleId, friendId)
.then(response => writeResponse(res, response, 201))
.catch(next);
}; |
/**
* Created by root on 6/17/16.
*/
var db = require('../routes/helper/db');
var async = require('async');
var validator = require('../routes/helper/validator');
var pushController = require('../routes/helper/send_push');
//We'll store the socket ids
//to check if user is connected or not
var connected = {};
//User connecting to socket
exports.connect = function (data){
connected[data.tag] = data.socketId;
console.log('SOCKET >>', data.id + " " + connected[data.tag]);
};
//User disconnecting to socket
exports.logout = function (data){
var tag = data.tag;
console.log(tag);
console.log("WILL DELETE TAG >> ", connected[tag]);
delete connected[tag];
console.log("DELETED TAG >> ", connected[tag]);
};
//will find device token (tag) via user_id
//for push notification
function findDeviceTag(data, cb){
var query = "SELECT `tag`, `user_id` FROM `push_tag`";
query += " " + "WHERE `user_id`=" + db.escape(data.user_id);
if(data.tag){
query += " " + "AND `tag`=" + db.escape(data.tag);
}
db.query(query, function (err, tags){
if(err) return cb(err, null);
if(tags){
cb(null, tags);
}
});
}
//will delete tag if user emit in logout
//to disable push notification
exports.deleteTag = function(data, cb){
var query = "DELETE FROM `push_tag`";
query += " " + "WHERE `user_id`=" + db.escape(data.id);
query += " " + "AND `tag`=" + db.escape(data.tag);
db.query(query, function (err, result){
if(err)return cb({error: true});
if(result.affectedRows > 0){
cb({error: false});
}else{
cb({error: true});
}
});
};
//=================================================================================
//* GROUP CHAT *
//=================================================================================
//Register event to generate event chat id
exports.registerEventForChat = function (data, cb){
var eventId = data.event_id;
var user_id = data.user_id;
async.waterfall([
getEventChatIdByEventId,
function (doNext, done){
var query = "INSERT INTO `eventChat` SET ?";
db.query(query, {event_id: eventId}, function (err, result){
if(err){
//TODO: change message on production
return done({error: true, message: err});
}
if(result.insertId > 0){
exports.addUserToEvent({
eventChat_id: result.insertId,
user_id: user_id
}, function (err){
if(err.error === true)return done(err);
done({error: false, eventChat: result.insertId});
});
}else{
done({error: true, message: "failed"});
}
});
}
], function (resp){
cb(resp);
});
//search for existing record of event chat
//this will return the eventChat_id to the client
//to be use for getting messages
function getEventChatIdByEventId(cb){
var query = "SELECT `id` FROM `eventChat`";
query += " " + "WHERE `event_id`=" + db.escape(eventId);
db.query(query, function(err, result){
if(err)return cb({error: false, err: err});
if(result && result.length){
cb({error: false, eventChat: result[0].id});
}else{
cb(null, false);
}
});
}
};
//will be called if event owner/creator accepts a request
//from other user to join the event
exports.addUserToEvent = function (data, cb){
if(!data.user_id){
return;
}
var query = "INSERT INTO `chat_users` SET ?";
db.query(query, {
eventChat_id: data.eventChat_id,
user_id: data.user_id
}, function (err, result){
if(err){
if(err.code === "ER_DUP_ENTRY"){
return cb({error: false, message: "success"});
}else{
//TODO change message on production
return cb({error: true, message: err});
}
}
if(result.insertId > 0){
cb({error: false, message: "success"});
}else{
cb({error: true, message: "failed"});
}
});
};
//Send message to an event
//this will broadcast the message to a specific event chat
//except the sender
exports.sendMessageToEvent = function (socket, data, cb){
console.log(data);
if(validator.isMissing(data.eventChat_id)){
return cb({error: true, message: "Missing chatHead"});
}
var query = "INSERT INTO `eventMessages` SET ?";
db.query(query, data, function (err, result){
if(err) return cb({error: true, message: err});
if(result.insertId > 0){
//Send message to event chat
socket.broadcast.to(data.eventChat_id).emit('newMessage', data);
//will get the users in an event via eventChat_id
//then check if they have an active socket
//if not connected, we will send a push notification
getEventUsers({
eventChat_id: data.eventChat_id,
user_id: data.from
}, function (err, users){
console.log(users);
async.map(users, sendPush);
});
cb(data);
}else{
cb({error: true, message: "Sending failed."});
}
});
function sendPush(sndData){
var connectedSockets = connected[sndData.tag];
console.log("PUSH DATA", sndData);
console.log("CONNECTED SOCKETS", connected);
if(!connectedSockets){
pushController.sendPush(sndData.tag, data, function (resp){
console.log("PUSH SEND EVENT", resp);
})
}
}
};
function getEventUsers(data, cb){
var query = "SELECT * FROM `chat_users`";
query += " " + "LEFT JOIN `push_tag`";
query += " " + "ON `push_tag`.`user_id` = `chat_users`.`user_id`";
query += " " + "WHERE `chat_users`.`eventChat_id`=" + db.escape(data.eventChat_id);
query += " " + "AND `chat_users`.`user_id` !=" + db.escape(data.user_id);
db.query(query, cb);
console.log(query);
}
//If eventChat_id is unobtainable
//client side will use the event id
//to get the eventChat_id
exports.getEventChatIdByEventId = function (data, cb){
var query = "SELECT `id` FROM `eventChat`";
query += " " + "WHERE `event_id`=" + db.escape(data.eventId);
db.query(query, function(err, result){
if(err) return cb({error: true, message: err});
if(result && result.length){
cb({error: false, eventChat: result[0].id})
}else {
//in case event is not yet registered for chatting
exports.registerEventForChat({
event_id: data.eventId
}, function(resp){
cb(resp);
});
}
});
};
//will return 10 latest messages by eventChat_id
//providing last_message_id will return 10 messages
//prior to the last_message_id
exports.getEventMessages = function (data, cb){
var query = "SELECT * FROM `eventMessages`";
query += " " + "WHERE `eventChat_id`=" + db.escape(data.eventChat_id);
if(!validator.isMissing(data.last_message_id)){
query += " " + "AND `id` <" + db.escape(data.last_message_id);
}
query += " " + "ORDER BY `id` DESC";
query += " " + "LIMIT 10";
db.query(query, function (err, results){
if(err) return cb({error: true, message: err});
var data = {
messages: results,
hasNext : results.length == 10
};
cb(data);
})
};
//Ignore this section .. this will be use later if personal messaging is available
//=================================================================================
//* ONE ON ONE CHAT *
//=================================================================================
exports.startChat = function (data, cb){
var users = data.users;
if(!users.length){
return cb({error: true, message: "users must be an array e.g [ user_1, user_2 ]"});
}
var insrtData = {
user_1 : users[0],
user_2 : users[1]
};
var query = "SELECT `id` FROM `chatHead`";
query += " " + "WHERE (`user_1`=" + db.escape(users[0]);
query += " " + "AND `user_2`=" + db.escape(users[1]);
query += " " + ")";
query += " " + "OR (`user_2`=" + db.escape(users[0]);
query += " " + "AND `user_1`=" + db.escape(users[1]);
query += " " + ")";
db.query(query, function (err, result){
if(err) return cb({error: true, message: err});
if(result.length){
cb({error: false, chatHead: result[0].id});
}else{
db.query("INSERT INTO `chatHead` SET ?", insrtData, function (err, result){
if(err) return cb({error: true, message: err});
if (result.insertId > 0){
cb({error : false, chatHead: result.insertId});
}else{
cb({error: true, message: "Failed to start chat"});
}
});
}
});
};
exports.getUserInbox = function (data, cb){
if(validator.isMissing(data.id)){
return cb({error: true, message: "Missing id"});
}
var query = "SELECT * FROM `chatHead`";
query += " " + "WHERE user_1=" + db.escape(data.id);
query += " " + "OR user_2=" + db.escape(data.id);
db.query(query, function (err, result){
if(err) return cb({error: true, message: err});
async.map(result, getLastMessage, function (err, users){
cb(users);
});
});
};
function getLastMessage(data, cb){
var query = "SELECT * FROM `chatMessages`";
query += " " + "WHERE `chatHead`=" + db.escape(data.id);
query += " " + "ORDER BY `id` DESC";
query += " " + "LIMIT 1";
db.query(query, function (err, result){
if(err){
cb(null, data);
}else{
if(result.length){
data.last_message = result[0];
}
cb(null, data);
}
});
}
exports.saveMessage = function (socket, data, cb){
if(validator.isMissing(data.chatHead)){
return cb({error: true, message: "Missing chatHead"});
}
var query = "INSERT INTO `chatMessages` SET ?";
db.query(query, data, function (err, result){
if(err) return cb({error: true, message: err});
if(result.insertId > 0){
socket.broadcast.to(data.chatHead).emit('newMessage', data);
var connectedSockets = connected[data.to];
console.log("CONNECTED SOCKET", connectedSockets);
if(!connectedSockets || !connectedSockets.length){
findDeviceTag({user_id: data.to}, function (err, tags){
if(tags && tags.length){
tags.forEach(function (tag){
pushController.sendPush(tag, data, function (resp){
console.log("PUSH", resp);
})
});
}
})
}
exports.markAsRead({
id: result.insertId,
chatMateId: data.to
}, function(){
});
cb({error: false, data: data});
}else{
cb({error: true, message: "Sending failed."});
}
});
};
exports.markAsRead = function (data, cb){
var query = "UPDATE `chatMessages` SET `status`='read'";
query += " " + "WHERE `id` <= " + db.escape(data.id);
query += " " + "AND `from`=" + db.escape(data.chatMateId);
db.query(query, function (err, result){
if(err) return cb({error: true, message: err});
if(result.affectedRows > 0){
cb({error: false});
}else{
cb({error: true});
}
});
};
exports.getMessages = function (data, cb){
var query = "SELECT * FROM `chatMessages`";
query += " " + "WHERE `chatHead`=" + db.escape(data.chatHead);
if(!validator.isMissing(data.last_message_id)){
query += " " + "AND `id` <" + db.escape(data.last_message_id);
}
query += " " + "ORDER BY `id` DESC";
query += " " + "LIMIT 10";
db.query(query, function (err, results){
if(err) return cb({error: true, message: err});
var data = {
messages: results,
hasNext : results.length == 10
};
cb(data);
})
}; |
var class_object_pool_1_1_startup_pool =
[
[ "prefab", "class_object_pool_1_1_startup_pool.html#a2bda7f7361547d012d331f23f6594c56", null ],
[ "size", "class_object_pool_1_1_startup_pool.html#a5edd1a6e6eb9c58b75233b641bffb8ef", null ]
]; |
var BarGraph = React.createClass({
getDefaultProps: function() {
return {
width: '500px',
height: '100px'
};
},
componentDidMount: function() {
var el = this.getDOMNode();
ns.create(el, this.props);
if(this.props.chem){
ns.update(el, this.props.chem);
}
// dispatcher.on('point:mouseover', this.showTooltip);
// dispatcher.on('point:mouseout', this.hideTooltip);
},
componentDidUpdate: function() {
var el = React.findDOMNode(this);
ns.removeContent(el);
if(this.props.chem){
ns.update(el, this.props.chem);
}
},
// getChartState: function() {
// var appState = this.props.appState;
//
// var tooltips = [];
// if (appState.showingAllTooltips) {
// tooltips = appState.data;
// }
// else if (appState.tooltip) {
// tooltips = [appState.tooltip];
// }
//
// return _.assign({}, appState, {tooltips: tooltips});
// },
render: function() {
return (
<div className="Chart"></div>
);
},
// showTooltip: function(d) {
// if (this.props.appState.showingAllTooltips) {
// return;
// }
//
// this.props.setAppState({
// tooltip: d,
// // Disable animation
// prevDomain: null
// });
// },
//
// hideTooltip: function() {
// if (this.props.appState.showingAllTooltips) {
// return;
// }
//
// this.props.setAppState({
// tooltip: null,
// prevDomain: null
// });
// }
});
|
import React from 'react';
const Timer = ({timeLeft}) => {
const timeLeftLength = Object.keys(timeLeft).length;
return (
<div id="timer" className="timer">
<div className="timer__body">
{timeLeftLength !== 0 && (
<>
<div className="timer-cell timer-cell_type_day">
<span className="timer-cell__value">{timeLeft.days} </span><br />
<span>days</span>
</div>
<div className="timer-cell">
<span className="timer-cell__value">{timeLeft.hours} </span><br />
<span>hours</span>
</div>
<div className="timer-cell">
<span className="timer-cell__value">{timeLeft.minutes} </span><br />
<span>minutes</span>
</div>
<div className="timer-cell">
<span className="timer-cell__value">{timeLeft.seconds} </span><br />
<span>seconds</span>
</div>
</>
)}
{timeLeftLength === 0 && (<p>The countdown is finished!</p>)}
</div>
</div>
);
};
export default Timer; |
import db from '../models/index.js';
import fanPageQueries from '../DB/queries/fanPage-queries.js';
const { User, FanPage } = db;
//add fanPage queries
const { addUpvote, removeUpvote } = fanPageQueries;
// return all fan pages ordered by date created
const exploreData = async (req, res) => {
try {
// send all fan pages based on created date desc order
const allPages = await FanPage.find().sort('-createdAt').select('pageTitle artistData');
if (!allPages) throw 'noPages';
return res.status(200).json({
status: 200,
message: 'Success',
allPages,
requestAt: new Date().toLocaleString()
});
} catch (error) {
console.log(error)
// return error message if no fan pages created yet
if (error === "noPages") {
return res.status(204).json({
status: 204,
message: 'No Fan Pages',
requestAt: new Date().toLocaleString()
});
}
return res.status(500).json({
status: 500,
message: 'Server error',
requestAt: new Date().toLocaleString()
});
}
}
// return top five fan pages based on upvote
const topFivePages = async (req, res) => {
try {
// send top five fan pages with most upvotes in desc order
const topFivePages = await FanPage.aggregate([
{ $unwind: "$upvote" },
{
$group: {
//returns the fields we want returned
_id: { id: '$_id', pageTitle: '$pageTitle', artistData: '$artistData' },
//gives us the number of elements in upvote array (min is set to 1);
len: { $sum: 1 }
}
},
{ $sort: { len: -1 } },
{ $limit: 5 }
]);
return res.status(200).json({
status: 200,
message: 'Success',
topFivePages,
requestAt: new Date().toLocaleString()
});
} catch (error) {
console.log(error)
return res.status(500).json({
status: 500,
message: 'Server error',
requestAt: new Date().toLocaleString()
});
}
}
const getFanPage = async (req, res) => {
try {
//get user data minus the password
let foundFanPage = await FanPage.findById(req.params.fanPageID).lean(); // lean allows us to add extra key values
if (foundFanPage === null) throw "noFanPageContent";
const authorUsername = await User.findById(foundFanPage.author).select("username");
if (!authorUsername) throw "noAuthor";
foundFanPage.username = authorUsername.username;
return res.status(200).json({
status: 200,
message: 'Success',
foundFanPage,
requestAt: new Date().toLocaleString()
});
} catch (error) {
if (error === "noFanPageContent") {
return res.status(204).json({
status: 204,
message: 'No Content',
requestAt: new Date().toLocaleString()
});
}
if (error === "noAuthor") {
return res.status(204).json({
status: 204,
message: 'No Content Author',
requestAt: new Date().toLocaleString()
});
}
return res.status(500).json({
status: 500,
message: 'Server error',
requestAt: new Date().toLocaleString()
});
}
}
//create FanPage
const createFanPage = async (req, res) => {
try {
const { artistData, pageTitle, pageDetail, trackList, albumList, userShows } = req.body;
console.log(req.user);
// throw error if pageTitle exists
if (!pageTitle || !artistData) throw "missingRequiredFields";
// create the user in DB
const newFanPage = {
author: req.user._id,
artistData,
pageTitle,
pageDetail,
trackList,
albumList,
userShows,
};
// send FanPage to db for creation
const fanPage = await FanPage.create(newFanPage);
return res.status(201).json({
status: 201,
message: 'FanPage was created successfully',
fanPage,
requestedAt: new Date().toLocaleString(),
});
} catch (error) {
console.log(error); //keep just incase if db error
//fan page missing required fields to create the page (either page title/artist/author)
if (error === "missingRequiredFields") {
return res.status(409).json({
status: 409,
message: "Missing Required Fields",
received: req.body,
requestAt: new Date().toLocaleString()
});
}
// all other errors
return res.status(500).json({
status: 500,
message: "Server error",
requestAt: new Date().toLocaleString()
});
}
}
// FanPage Delete
const destroyFanPage = async (req, res) => {
try {
const deletedFanPage = await db.FanPage.findByIdAndDelete(req.params.fanPageID);
return res.status(200).json({
status: 200,
message: 'Fan Page Deleted Successfully!!!!',
deletedFanPage,
requestedAt: new Date().toLocaleString(),
});
} catch (error) {
res.status(500).json({
status: 500,
message: 'Sorry something went wrong. Internal server Error',
requestAt: new Date().toLocaleString()
});
}
};
const updateFanPage = async (req, res) => {
try {
// // Validation for TitlePage is not null
const { pageTitle } = req.body;
if (!pageTitle) throw "missingRequiredFields";
// Update the fanPage information
const updatedFanPage = await FanPage.findByIdAndUpdate(
req.params.fanPageID,
{
$set: {
...req.body
}
},
{
new: true
}
);
return res.status(200).json({
status: 200,
message: 'Success',
updatedFanPage,
requestAt: new Date().toLocaleString()
});
} catch (error) {
console.log(error); //keep just incase if db error
// all other errors
return res.status(500).json({
status: 500,
message: "Server Error",
requestAt: new Date().toLocaleString()
});
}
}
const updateUpvote = async (req, res) => {
try {
const userDBId = req.user._id;
const fanPageId = req.params.fanPageID;
//see if the current fanPage is already liked by the user
const check = await FanPage.find({
_id: fanPageId,
upvote: userDBId
});
if (!check.length) {
//call addUpvote to add the user to upvote for fan page
const updatedFanPage = await addUpvote(fanPageId, userDBId);
//throw error if addUpvote sends false
if (updatedFanPage === false) throw "addUpvoteFailed";
return res.status(200).json({
status: 200,
message: "Success, page upvoted by user",
updatedFanPage,
requestAt: new Date().toLocaleString()
});
}
const updatedFanPage = await removeUpvote(fanPageId, userDBId);
//throw error if DB failed to update
if (updatedFanPage === false) throw 'removeUpvoteFailed';
return res.status(200).json({
status: 200,
message: "Success, page un-upvoted by user ",
updatedFanPage,
requestAt: new Date().toLocaleString()
});
} catch (error) {
console.log(error);
// send error message if addUpvote fails
if (error === "addUpvoteFailed") {
return res.status(400).json({
status: 400,
message: 'addUpvote failed to update upvote',
requestAt: new Date().toLocaleString()
});
}
// send error message if addUpvote fails
if (error === "removeUpvoteFailed") {
return res.status(400).json({
status: 400,
message: 'removeUpvote failed to update upvote',
requestAt: new Date().toLocaleString()
});
}
// all other errors
return res.status(500).json({
status: 500,
message: "Server Error",
requestAt: new Date().toLocaleString()
});
}
}
const melophiedCtrls = {
exploreData,
createFanPage,
getFanPage,
topFivePages,
destroyFanPage,
updateFanPage,
updateUpvote,
}
export default melophiedCtrls; |
class Platform extends Entity {
constructor({ behaviour, ...options }) {
super(options);
this.gameObject = new GameObject({
startX: options.startX, startY: options.startY, width: options.width, height: options.height
});
this.behaviour = behaviour;
this.collider = new Collider({
isTrigger: true,
width: options.width,
height: options.height,
x: options.startX,
y: options.startY,
xOffset: 0,
yOffset: 0,
});
}
update() {
if (this.behaviour) {
this.behaviour.move(this.gameObject)
this.collider.setPosition({
x: this.gameObject.actualX,
y: this.gameObject.actualY
});
}
}
draw({renderContext}) {
this.sprite.draw({
renderContext,
x: this.gameObject.actualX,
y: this.gameObject.startY
});
// renderContext.beginPath();
// renderContext.rect(this.gameObject.actualX, this.gameObject.actualY, this.gameObject.width, this.gameObject.height);
// renderContext.stroke();
}
carry(gameObjectToCarry) {
if (this.behaviour) {
this.behaviour.move(gameObjectToCarry)
}
}
isInside(gameObject) {
const middleX = gameObject.actualX+(gameObject.width/2);
const middleY = gameObject.actualY+(gameObject.height/2);
return (middleX > this.gameObject.actualX &&
middleX < this.gameObject.actualX+this.gameObject.width &&
middleY > this.gameObject.actualY &&
middleY < this.gameObject.actualY+this.gameObject.height);
}
} |
var sectorData;
var tickerData;
var graphOptions;
var sectorChart;
var tickerChart;
var sectorctx = document.getElementById("sector-chart");
var tickerctx = document.getElementById("ticker-chart");
// Utility Functions
function getSectors(quotes){
var sectors = {}
for (var d in quotes){
if (quotes[d]['sector'] in sectors){
sectors[quotes[d]['sector']] += 1
}
else{
sectors[quotes[d]['sector']] = 1
}
}
return sectors
}
var Options = {
maintainAspectRatio: false,
legend: {
display: true,
position: 'right',
labels: {
fontColor: 'white'
}
}
}
function createGraph(data, ctx, options, type){
var bootstrapColors = [
'#17a2b8',
'#ffc107',
'#28a745',
'#dc3545',
'#007bff',
'#ffffff',
'#868e96',
]
var graphData = {
labels: Object.keys(data),
datasets: [{
data: Object.values(data),
backgroundColor: bootstrapColors
}],
};
var graph = new Chart(ctx, {
type: type,
data: graphData,
options: options
});
}
// Charts
$(document).ready(function(){
createGraph(stocks, tickerctx, Options, 'doughnut');
createGraph(getSectors(quotes), sectorctx, Options, 'doughnut');
})
|
const mongoose = require('mongoose');
const fileSchema = new mongoose.Schema({
length: Number,
chunkSize: Number,
uploadDate: Date,
filename: String,
md5: String,
contentType: String,
});
exports.File = mongoose.model('File', fileSchema);
const ObjectId = mongoose.Schema.ObjectId;
const chunkSchema = new mongoose.Schema({
files_id: ObjectId,
n: Number,
data: Buffer
});
exports.Chunk = mongoose.model('Chunk', chunkSchema); |
//引入express模块
const express = require("express");
//定义路由及中间件
const router = express.Router();
//引入数据模型模块
const Fri = require("../models/fri");
// 登陆接口
router.post('/login', function(req, res, next) {
var username = req.body.username;
var password = req.body.password;
if(username === 'murphyli' && password === 'admin'){
res.cookie('user',username);
return res.send({
status: "success",
info: '欢迎登陆'
});
}
return res.send({
status: "fail",
info: "登陆失败,账号或密码错误"
});
});
//查询所有朋友信息路由
router.post("/getFriList", (req,res) => {
var friName = req.body.friName,
age = req.body.age,
friSex = req.body.friSex,
friEmail = req.body.friEmail;
var sqlObj = {};
if(friName){
sqlObj.friName = friName;
}
if(age){
sqlObj.age = age;
}
if(friSex){
sqlObj.friSex = friSex;
}
if(friEmail){
sqlObj.friEmail = friEmail;
}
var friList = Fri.find(sqlObj);
});
//添加一个朋友信息路由
router.post('/addFri', (req,res) => {
//使用model上的方法
console.log(req)//方便调试用
Fri.create(req.body, (err, fri) => {
if (err) {
res.json({
status: "fail",
error: err
});
} else {
res.json({
status: "success",
message: "添加成功"
});
}
});
console.log(req.body)
});
module.exports = router;
|
import React, { useEffect, useState } from "react";
import HotelList from "./HotelList";
import Typography from "@material-ui/core/Typography";
import { fetchHotelData } from "./apiHelper/profileHelper";
import GoogleMap from "./GoogleMap";
import Grid from "@material-ui/core/Grid";
import { MDBContainer } from "mdbreact";
const CustomerDashboard = () => {
const [hoteluserdata, setHotelUserData] = useState([]);
useEffect(() => {
fetchHotelData().then(hoteldata => {
setHotelUserData(hoteldata);
});
}, []);
return (
<div>
<MDBContainer fluid>
<br />
<br />
<br />
<Typography variant="h4" gutterBottom>
Hotel List
</Typography>
<Grid container spacing={1} style={{ marginTop: "50px" }}>
<Grid item xs={4}>
{hoteluserdata.map(hotelUser => (
<HotelList
key={hotelUser._id}
_id={hotelUser._id}
hotelname={hotelUser.hotelname}
hotelcontact={hotelUser.hotelcontact}
hotelemail={hotelUser.hotelemail}
hotelcity={hotelUser.hoteladdress.hotelcity}
hotelimage={hotelUser.hotelimages}
lat={hotelUser.hoteladdress.geo.lat}
lng={hotelUser.hoteladdress.geo.lng}
/>
))}
</Grid>
<Grid item xs={8} style={{ position: "relative" }}>
<GoogleMap data={hoteluserdata} />
</Grid>
</Grid>
</MDBContainer>
</div>
);
};
export default CustomerDashboard;
|
function Controller() {
function changeSettings() {
var a = Titanium.UI.createAnimation({
left: APP.numberOperation(-$.mapView.size.width, "/", 2, false),
duration: 300
});
var a2 = Titanium.UI.createAnimation({
left: 20,
duration: 300
});
var b = Titanium.UI.createAnimation({
left: APP.numberOperation($.mapView.size.width, "/", 2, false),
duration: 300
});
var o = Titanium.UI.createAnimation({
opacity: .8,
duration: 300
});
var o2 = Titanium.UI.createAnimation({
opacity: 1,
duration: 300
});
if ($.typesView.isOpen) {
a.addEventListener("complete", function() {
$.typesView.zIndex = 98;
$.typesView.animate(a2);
});
$.typesView.animate(o);
$.typesView.animate(a);
b.addEventListener("complete", function() {
$.settingsView.zIndex = 99;
$.settingsView.animate(o2);
$.settingsView.animate(a2);
});
$.settingsView.animate(b);
} else {
a.addEventListener("complete", function() {
$.settingsView.zIndex = 98;
$.settingsView.animate(a2);
});
$.settingsView.animate(o);
$.settingsView.animate(a);
b.addEventListener("complete", function() {
$.typesView.zIndex = 99;
$.typesView.animate(o2);
$.typesView.animate(a2);
});
$.typesView.animate(b);
}
$.typesView.isOpen = !$.typesView.isOpen;
}
function changeSwitch(_event) {
if (true == _event.source.value) if (0 == _event.source.filterID) {
shouldLoadMap = true;
$.fsw2.value = true;
$.fsw3.value = true;
$.fsw4.value = true;
$.fsw5.value = true;
$.fsw6.value = true;
$.fsw7.value = true;
$.fsw8.value = true;
$.fsw9.value = true;
$.fsw10.value = true;
$.fsw11.value = true;
$.fsw12.value = true;
$.fsw13.value = true;
$.fsw14.value = true;
$.fsw15.value = true;
$.fsw17.value = true;
$.fsw16.value = true;
setTimeout(function() {
shouldLoadMap = false;
Ti.API.info("load map");
getCrimes({
lat: latitude,
lon: longitude
});
}, 1500);
} else {
var tempString = Ti.App.Properties.getString("MapFilter.Categories.EnabledCategories");
Ti.App.Properties.setString("MapFilter.Categories.EnabledCategories", tempString + "," + _event.source.filterID);
} else if (0 == _event.source.filterID) {
shouldLoadMap = true;
$.fsw2.value = false;
$.fsw3.value = false;
$.fsw4.value = false;
$.fsw5.value = false;
$.fsw6.value = false;
$.fsw7.value = false;
$.fsw8.value = false;
$.fsw9.value = false;
$.fsw10.value = false;
$.fsw11.value = false;
$.fsw12.value = false;
$.fsw13.value = false;
$.fsw14.value = false;
$.fsw15.value = false;
$.fsw17.value = false;
$.fsw16.value = false;
setTimeout(function() {
shouldLoadMap = false;
getCrimes({
lat: latitude,
lon: longitude
});
}, 1500);
} else {
var tempString = Ti.App.Properties.getString("MapFilter.Categories.EnabledCategories", "4,1,2,3,5,6,7,9,10,11,12,13,14,15,16,18,19");
var regString = new RegExp("," + _event.source.filterID + "\\b", "g");
Ti.App.Properties.setString("MapFilter.Categories.EnabledCategories", tempString.replace(regString, ""));
}
false == shouldLoadMap && getCrimes({
lat: latitude,
lon: longitude
});
}
function currentPosition() {
APP.getCurrentLocation(function(_event) {
if (_event.success) {
_event.faname = "Current Location";
getCrimes(_event);
} else APP.hideActivityindicator();
});
}
function getAlerts(event, callback) {
APP.getToken({
openLogin: true,
callback: function(token) {
var _ws_request = {
atoken: token,
flat: event.lat,
flon: event.lon,
usehome: 0
};
APP.http.request({
url: L("ws_getalerts"),
type: "GET",
format: "JSON",
data: _ws_request
}, function(response) {
if (0 == response._result) APP.closeWindow(); else if (0 != response._data.errorcode) {
Ti.API.warn(response._data.message);
callback && callback();
} else callback && callback(response._data.data);
return true;
});
return true;
}
});
return true;
}
function getCountCrimes(_event) {
var dataTemp = {
url: L("ws_getcrimelevel"),
type: "POST",
format: "JSON",
data: {
atoken: APP.getToken({
openLogin: false
}),
flat: _event.lat,
flon: _event.lon,
usehome: 0
}
};
APP.http.request(dataTemp, function(_result) {
if (1 == _result._result && 0 == _result._data.errorcode) {
$.crimeTitle.text = _result._data.data[0].crimecnt;
$.sexTitle.text = _result._data.data[0].oscount;
}
});
}
function getCrimes(_event) {
APP.showActivityindicator();
latitude = _event.lat;
longitude = _event.lon;
$.mapView.setRegion({
latitude: _event.lat,
longitude: _event.lon,
animate: true,
latitudeDelta: latitudeDelta,
longitudeDelta: longitudeDelta
});
$.alertsTitle.text = _event.faname;
getCountCrimes(_event);
var dataTemp = {
url: L("ws_getcrimes"),
type: "POST",
format: "JSON",
data: {
atoken: APP.getToken({
openLogin: false
}),
flat: _event.lat,
flon: _event.lon,
usehome: 0,
weathercheck: 1,
sodcheck: 1,
neighborcheck: 1,
location: "",
rdate: Ti.App.Properties.getString("MapFilter.Days.NumberOfDays", "ALL"),
ctype: Ti.App.Properties.getString("MapFilter.Categories.EnabledCategories", "4,1,2,3,5,6,7,9,10,11,12,13,14,15,16,18,19")
}
};
APP.http.request(dataTemp, function(_result) {
if (1 == _result._result) if (0 == _result._data.errorcode) {
var tempCrimeList = _result._data.data;
var tempCrimeAnno = [];
for (var i = 0; tempCrimeList.length > i; i++) {
var tempImage = tempCrimeList[i].ncticon.slice(19, -4) + ".png";
tempImage = tempImage.split("/");
var alertImage = "/images/Crimes/" + tempImage[tempImage.length - 1];
tempCrimeList[i].image = alertImage;
if ("Weather" == tempCrimeList[i].cdtype || "Sex Offender" === tempCrimeList[i].cdtype) var baseurl = tempCrimeList[i].url; else if ("Neighbor" == tempCrimeList[i].cdtype) {
var baseurl = "http://alertid.com/commmore.asp?athread=" + tempCrimeList[i].pkcrimedata;
baseurl = "Neighbor";
} else var baseurl = "http://alertid.com/commmore.asp?cdid=" + tempCrimeList[i].pkcrimedata;
tempCrimeAnno.push({
anno: map.createAnnotation({
latitude: _result._data.data[i].cdlat,
longitude: _result._data.data[i].cdlon,
title: _result._data.data[i].ncttype,
subtitle: _result._data.data[i].cddatetime + " - " + tempCrimeList[i].miles + " miles away " + tempCrimeList[i].cdagency,
pincolor: Titanium.Map.ANNOTATION_RED,
animate: true,
rightButton: alertImage,
image: alertImage,
crimeid: _result._data.data[i].pkcrimedata,
url: baseurl
})
});
$.mapView.addAnnotation(tempCrimeAnno[i].anno);
}
getAlerts(_event, function(alertsData) {
setListView(alertsData, tempCrimeList, tempCrimeAnno);
return true;
});
APP.hideActivityindicator();
} else APP.hideActivityindicator(); else APP.hideActivityindicator();
});
}
function openListView(_forceClose) {
true == _forceClose ? $.listView.isOpen = true : openSettings(true);
if ($.listView.isOpen) {
$.listView.animate({
right: APP.numberOperation(-$.mapView.size.width, "-", 0, false),
duration: 150
});
$.listView.animate({
top: APP.numberOperation($.mapView.size.height, "+", 20, false),
duration: 150
});
} else {
$.listView.animate({
right: 20,
duration: 150
});
$.listView.animate({
top: 64,
duration: 150
});
}
$.listView.isOpen = !$.listView.isOpen;
}
function openSettings(_forceClose) {
APP.popOut();
true == _forceClose ? $.settingsView.isOpen = true : openListView(true);
if ($.settingsView.isOpen) {
$.settingsView.animate({
left: APP.numberOperation(-$.mapView.size.width, "-", 0, false),
duration: 150
});
$.typesView.animate({
left: APP.numberOperation(-$.mapView.size.width, "-", 0, false),
duration: 150
});
$.settingsView.animate({
top: APP.numberOperation($.mapView.size.height, "+", 20, false),
duration: 150
});
$.typesView.animate({
top: APP.numberOperation($.mapView.size.height, "+", 20, false),
duration: 150
});
} else {
$.settingsView.animate({
left: 20,
duration: 150
});
$.typesView.animate({
left: 20,
duration: 150
});
$.settingsView.animate({
top: 64,
duration: 150
});
$.typesView.animate({
top: 64,
duration: 150
});
}
$.settingsView.isOpen = !$.settingsView.isOpen;
}
function searchAddress(_address) {
if (APP.getToken({
openLogin: false
})) {
APP.showActivityindicator();
var dataTemp = {
url: "http://maps.google.com/maps/api/geocode/json?address=" + _address + "&sensor=true",
type: "GET",
format: "JSON"
};
APP.http.request(dataTemp, function(_result) {
if (1 == _result._result) if (_result._data.results.length > 0) {
getCrimes({
lat: _result._data.results[0].geometry.location.lat,
lon: _result._data.results[0].geometry.location.lng,
faname: _address
});
APP.openCloseOptions();
} else APP.hideActivityindicator(); else APP.hideActivityindicator();
});
}
}
function selectDays() {
var daysSelectDialog = Titanium.UI.createOptionDialog({
title: "Select Days Filter",
options: [ "Last 24 hours", "Last 3 days", "Last 7 days", "Last 30 days", "Last 90 days", "All days" ],
cancel: -1
});
daysSelectDialog.addEventListener("click", function(e) {
if (e.index >= 0) {
$.daysLabel.text = "Show: " + days[e.index].title;
getCrimes({
lat: latitude,
lon: longitude
});
}
});
daysSelectDialog.show();
}
function selectRegion() {
var zoomSelectDialog = Titanium.UI.createOptionDialog({
title: "Select Region",
options: [ "Neighborhood", "Community", "City" ],
cancel: -1
});
zoomSelectDialog.addEventListener("click", function(e) {
if (e.index >= 0) {
if (0 === e.index) {
latitudeDelta = .02;
longitudeDelta = .02;
$.regionLabel.text = "Region: Neighborhood";
} else if (1 === e.index) {
latitudeDelta = .04;
longitudeDelta = .04;
$.regionLabel.text = "Region: Community";
} else if (2 === e.index) {
latitudeDelta = .17;
longitudeDelta = .18;
$.regionLabel.text = "Region: City";
}
$.mapView.setRegion({
latitude: latitude,
longitude: longitude,
animate: true,
latitudeDelta: latitudeDelta,
longitudeDelta: longitudeDelta
});
}
});
zoomSelectDialog.show();
}
function setHybView() {
$.mapView.setMapType(Titanium.Map.HYBRID_TYPE);
}
function setListView(alerts_data, advisors_data, advisors_annotations) {
$.listView.remove($.tableAlerts);
$.tableAlerts = Alloy.createController("MyAlerts/TableAlerts", {
map: $.mapView,
alerts_data: alerts_data,
advisors_data: advisors_data,
advisors_annotations: advisors_annotations,
openListView: function() {
openListView();
return true;
}
}).getView();
$.listView.add($.tableAlerts);
}
function setSatView() {
$.mapView.setMapType(Titanium.Map.SATELLITE_TYPE);
}
function setStandView() {
$.mapView.setMapType(Titanium.Map.STANDARD_TYPE);
}
function setTrafficView() {
APP.openWindow({
controller: "MyAlerts/TrafficView",
controllerParams: {
title: "Traffic View",
lat: latitude,
lon: longitude
}
});
}
function updateView() {
APP.headerbar.removeAllCustomViews();
APP.headerbar.setLeftButton(0, false);
APP.headerbar.setRightButton(0, false);
APP.headerbar.setLeftButton(APP.OPENMENU, true);
APP.headerbar.setRightButton(APP.OPENOPTIONS, true, {}, 1);
APP.headerbar.setTitle("My Alerts");
APP.optionbar.changeView(1, function() {
APP.openWindow({
controller: "Settings/EditAddress",
controllerParams: {
callback: function() {
APP.optionbar.updateMyAddresses();
}
}
});
});
if (APP.getToken({
openLogin: false
})) {
false == _isLogged && currentPosition();
_isLogged = true;
} else {
$.alertsTitle.text = "";
_isLogged = false;
}
return true;
}
function refreshMap() {
APP.getToken({
openLogin: true
}) && getCrimes({
lat: _updateLatitude,
lon: _updateLongitude
});
}
function initializeView() {
APP.optionbar.changeView(1, function() {
APP.openWindow({
controller: "Settings/EditAddress",
controllerParams: {
callback: function() {
APP.optionbar.updateMyAddresses();
}
}
});
});
currentPosition();
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "MyAlerts/MyAlerts";
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
arguments[0] ? arguments[0]["__itemTemplate"] : null;
var $ = this;
var exports = {};
var __defers = {};
$.__views.container = Ti.UI.createView({
backgroundColor: "#ecf1f4",
id: "container"
});
$.__views.container && $.addTopLevelView($.__views.container);
var __alloyId78 = [];
$.__views.mapView = Ti.Map.createView({
top: 0,
left: 0,
right: 0,
bottom: 0,
annotations: __alloyId78,
id: "mapView",
ns: Ti.Map,
animate: "true",
regionFit: "true",
userLocation: "true",
mapType: Ti.Map.STANDARD_TYPE,
enableZoomControls: "false"
});
$.__views.container.add($.__views.mapView);
$.__views.alertsTitleContainer = Ti.UI.createView({
top: 40,
backgroundImage: "/images/bg_whiteimage_flex.png",
left: 0,
right: 0,
height: 30,
id: "alertsTitleContainer"
});
$.__views.container.add($.__views.alertsTitleContainer);
$.__views.alertsTitle = Ti.UI.createLabel({
color: "#17B8E4",
font: {
fontSize: 14
},
left: 10,
right: 150,
text: "Current Location",
id: "alertsTitle"
});
$.__views.alertsTitleContainer.add($.__views.alertsTitle);
$.__views.__alloyId79 = Ti.UI.createButton({
backgroundSelectedImage: "/images/ic_crimes_pressed.png",
backgroundImage: "/images/ic_crimes.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 0,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
right: 125,
width: 18,
height: 17,
id: "__alloyId79"
});
$.__views.alertsTitleContainer.add($.__views.__alloyId79);
$.__views.crimeTitle = Ti.UI.createLabel({
color: "#17B8E4",
font: {
fontSize: 14
},
right: 80,
text: "0",
id: "crimeTitle"
});
$.__views.alertsTitleContainer.add($.__views.crimeTitle);
$.__views.__alloyId80 = Ti.UI.createButton({
backgroundSelectedImage: "/images/ic_sexoffender_pressed.png",
backgroundImage: "/images/ic_sexoffender.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 0,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
right: 55,
width: 18,
height: 17,
id: "__alloyId80"
});
$.__views.alertsTitleContainer.add($.__views.__alloyId80);
$.__views.sexTitle = Ti.UI.createLabel({
color: "#17B8E4",
font: {
fontSize: 14
},
right: 10,
text: "0",
id: "sexTitle"
});
$.__views.alertsTitleContainer.add($.__views.sexTitle);
$.__views.refreshMap = Ti.UI.createButton({
backgroundSelectedImage: "/images/ic_map_refresh_pressed.png",
backgroundImage: "/images/ic_map_refresh.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 0,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
backgroundColor: "transparent",
top: 78,
right: 10,
width: 38,
height: 38,
id: "refreshMap"
});
$.__views.container.add($.__views.refreshMap);
refreshMap ? $.__views.refreshMap.addEventListener("click", refreshMap) : __defers["$.__views.refreshMap!click!refreshMap"] = true;
$.__views.settingsView = Ti.UI.createView({
left: 0,
top: "100%",
height: "100%",
width: "100%",
id: "settingsView",
isOpen: "false"
});
$.__views.container.add($.__views.settingsView);
$.__views.__alloyId81 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bgBlackOpacity39.png",
backgroundImage: "/images/bg_popup_flex.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 0,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
left: 0,
top: 0,
right: 0,
bottom: 0,
touchEnabled: false,
backgroundLeftCap: 10,
backgroundTopCap: 10,
id: "__alloyId81"
});
$.__views.settingsView.add($.__views.__alloyId81);
$.__views.__alloyId82 = Ti.UI.createLabel({
color: "#17B8E4",
font: {
fontSize: 18
},
left: 10,
top: 10,
text: "Alerts",
id: "__alloyId82"
});
$.__views.settingsView.add($.__views.__alloyId82);
$.__views.__alloyId83 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bgBlackOpacity39.png",
backgroundImage: "/images/transparent.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 1,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
right: 49,
top: 10,
height: 25,
width: 80,
title: "Map Types",
id: "__alloyId83"
});
$.__views.settingsView.add($.__views.__alloyId83);
changeSettings ? $.__views.__alloyId83.addEventListener("click", changeSettings) : __defers["$.__views.__alloyId83!click!changeSettings"] = true;
$.__views.close = Ti.UI.createButton({
backgroundSelectedImage: "/images/ic_close_pressed.png",
backgroundImage: "/images/ic_close.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 0,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
width: 36,
height: 36,
top: 0,
right: 5,
id: "close"
});
$.__views.settingsView.add($.__views.close);
openSettings ? $.__views.close.addEventListener("click", openSettings) : __defers["$.__views.close!click!openSettings"] = true;
$.__views.__alloyId84 = Ti.UI.createScrollView({
top: 50,
left: 3,
right: 6,
bottom: 6,
contentHeight: Ti.UI.SIZE,
borderRadius: 5,
backgroundColor: "white",
layout: "vertical",
id: "__alloyId84"
});
$.__views.settingsView.add($.__views.__alloyId84);
$.__views.__alloyId85 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId85"
});
$.__views.__alloyId84.add($.__views.__alloyId85);
$.__views.regionLabel = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Region: Neighborhood",
id: "regionLabel"
});
$.__views.__alloyId85.add($.__views.regionLabel);
$.__views.__alloyId86 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bgBlackOpacity39.png",
backgroundImage: "/images/transparent.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 1,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 12
},
right: 10,
width: 56,
height: 23,
top: 8,
title: "Select",
id: "__alloyId86"
});
$.__views.__alloyId85.add($.__views.__alloyId86);
selectRegion ? $.__views.__alloyId86.addEventListener("click", selectRegion) : __defers["$.__views.__alloyId86!click!selectRegion"] = true;
$.__views.__alloyId87 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId87"
});
$.__views.__alloyId84.add($.__views.__alloyId87);
$.__views.__alloyId88 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId88"
});
$.__views.__alloyId84.add($.__views.__alloyId88);
$.__views.daysLabel = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Show: All days",
id: "daysLabel"
});
$.__views.__alloyId88.add($.__views.daysLabel);
$.__views.__alloyId89 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bgBlackOpacity39.png",
backgroundImage: "/images/transparent.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 1,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 12
},
right: 10,
width: 56,
height: 23,
top: 8,
title: "Select",
id: "__alloyId89"
});
$.__views.__alloyId88.add($.__views.__alloyId89);
selectDays ? $.__views.__alloyId89.addEventListener("click", selectDays) : __defers["$.__views.__alloyId89!click!selectDays"] = true;
$.__views.__alloyId90 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId90"
});
$.__views.__alloyId84.add($.__views.__alloyId90);
$.__views.__alloyId91 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId91"
});
$.__views.__alloyId84.add($.__views.__alloyId91);
$.__views.__alloyId92 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "All categories",
id: "__alloyId92"
});
$.__views.__alloyId91.add($.__views.__alloyId92);
$.__views.fsw0 = Ti.UI.createSwitch({
right: 6,
id: "fsw0",
value: "true",
filterID: "0"
});
$.__views.__alloyId91.add($.__views.fsw0);
changeSwitch ? $.__views.fsw0.addEventListener("change", changeSwitch) : __defers["$.__views.fsw0!change!changeSwitch"] = true;
$.__views.__alloyId93 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId93"
});
$.__views.__alloyId84.add($.__views.__alloyId93);
$.__views.__alloyId94 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId94"
});
$.__views.__alloyId84.add($.__views.__alloyId94);
$.__views.__alloyId95 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Sex Offenders (always on)",
id: "__alloyId95"
});
$.__views.__alloyId94.add($.__views.__alloyId95);
$.__views.__alloyId96 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId96"
});
$.__views.__alloyId84.add($.__views.__alloyId96);
$.__views.__alloyId97 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId97"
});
$.__views.__alloyId84.add($.__views.__alloyId97);
$.__views.__alloyId98 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Crimes against children",
id: "__alloyId98"
});
$.__views.__alloyId97.add($.__views.__alloyId98);
$.__views.fsw2 = Ti.UI.createSwitch({
right: 6,
id: "fsw2",
value: "true",
filterID: "1"
});
$.__views.__alloyId97.add($.__views.fsw2);
changeSwitch ? $.__views.fsw2.addEventListener("change", changeSwitch) : __defers["$.__views.fsw2!change!changeSwitch"] = true;
$.__views.__alloyId99 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId99"
});
$.__views.__alloyId84.add($.__views.__alloyId99);
$.__views.__alloyId100 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId100"
});
$.__views.__alloyId84.add($.__views.__alloyId100);
$.__views.__alloyId101 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Crimes against the elderly",
id: "__alloyId101"
});
$.__views.__alloyId100.add($.__views.__alloyId101);
$.__views.fsw3 = Ti.UI.createSwitch({
right: 6,
id: "fsw3",
value: "true",
filterID: "15"
});
$.__views.__alloyId100.add($.__views.fsw3);
changeSwitch ? $.__views.fsw3.addEventListener("change", changeSwitch) : __defers["$.__views.fsw3!change!changeSwitch"] = true;
$.__views.__alloyId102 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId102"
});
$.__views.__alloyId84.add($.__views.__alloyId102);
$.__views.__alloyId103 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId103"
});
$.__views.__alloyId84.add($.__views.__alloyId103);
$.__views.__alloyId104 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Homocide",
id: "__alloyId104"
});
$.__views.__alloyId103.add($.__views.__alloyId104);
$.__views.fsw4 = Ti.UI.createSwitch({
right: 6,
id: "fsw4",
value: "true",
filterID: "10"
});
$.__views.__alloyId103.add($.__views.fsw4);
changeSwitch ? $.__views.fsw4.addEventListener("change", changeSwitch) : __defers["$.__views.fsw4!change!changeSwitch"] = true;
$.__views.__alloyId105 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId105"
});
$.__views.__alloyId84.add($.__views.__alloyId105);
$.__views.__alloyId106 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId106"
});
$.__views.__alloyId84.add($.__views.__alloyId106);
$.__views.__alloyId107 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Kidnapping/Missing person",
id: "__alloyId107"
});
$.__views.__alloyId106.add($.__views.__alloyId107);
$.__views.fsw5 = Ti.UI.createSwitch({
right: 6,
id: "fsw5",
value: "true",
filterID: "3"
});
$.__views.__alloyId106.add($.__views.fsw5);
changeSwitch ? $.__views.fsw5.addEventListener("change", changeSwitch) : __defers["$.__views.fsw5!change!changeSwitch"] = true;
$.__views.__alloyId108 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId108"
});
$.__views.__alloyId84.add($.__views.__alloyId108);
$.__views.__alloyId109 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId109"
});
$.__views.__alloyId84.add($.__views.__alloyId109);
$.__views.__alloyId110 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Sex crimes",
id: "__alloyId110"
});
$.__views.__alloyId109.add($.__views.__alloyId110);
$.__views.fsw6 = Ti.UI.createSwitch({
right: 6,
id: "fsw6",
value: "true",
filterID: "2"
});
$.__views.__alloyId109.add($.__views.fsw6);
changeSwitch ? $.__views.fsw6.addEventListener("change", changeSwitch) : __defers["$.__views.fsw6!change!changeSwitch"] = true;
$.__views.__alloyId111 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId111"
});
$.__views.__alloyId84.add($.__views.__alloyId111);
$.__views.__alloyId112 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId112"
});
$.__views.__alloyId84.add($.__views.__alloyId112);
$.__views.__alloyId113 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Weapons offense",
id: "__alloyId113"
});
$.__views.__alloyId112.add($.__views.__alloyId113);
$.__views.fsw7 = Ti.UI.createSwitch({
right: 6,
id: "fsw7",
value: "true",
filterID: "14"
});
$.__views.__alloyId112.add($.__views.fsw7);
changeSwitch ? $.__views.fsw7.addEventListener("change", changeSwitch) : __defers["$.__views.fsw7!change!changeSwitch"] = true;
$.__views.__alloyId114 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId114"
});
$.__views.__alloyId84.add($.__views.__alloyId114);
$.__views.__alloyId115 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId115"
});
$.__views.__alloyId84.add($.__views.__alloyId115);
$.__views.__alloyId116 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Assault & Battery",
id: "__alloyId116"
});
$.__views.__alloyId115.add($.__views.__alloyId116);
$.__views.fsw17 = Ti.UI.createSwitch({
right: 6,
id: "fsw17",
value: "true",
filterID: "6"
});
$.__views.__alloyId115.add($.__views.fsw17);
changeSwitch ? $.__views.fsw17.addEventListener("change", changeSwitch) : __defers["$.__views.fsw17!change!changeSwitch"] = true;
$.__views.__alloyId117 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId117"
});
$.__views.__alloyId84.add($.__views.__alloyId117);
$.__views.__alloyId118 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId118"
});
$.__views.__alloyId84.add($.__views.__alloyId118);
$.__views.__alloyId119 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Burglary",
id: "__alloyId119"
});
$.__views.__alloyId118.add($.__views.__alloyId119);
$.__views.fsw8 = Ti.UI.createSwitch({
right: 6,
id: "fsw8",
value: "true",
filterID: "7"
});
$.__views.__alloyId118.add($.__views.fsw8);
changeSwitch ? $.__views.fsw8.addEventListener("change", changeSwitch) : __defers["$.__views.fsw8!change!changeSwitch"] = true;
$.__views.__alloyId120 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId120"
});
$.__views.__alloyId84.add($.__views.__alloyId120);
$.__views.__alloyId121 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId121"
});
$.__views.__alloyId84.add($.__views.__alloyId121);
$.__views.__alloyId122 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Drug/Alcohol violations",
id: "__alloyId122"
});
$.__views.__alloyId121.add($.__views.__alloyId122);
$.__views.fsw9 = Ti.UI.createSwitch({
right: 6,
id: "fsw9",
value: "true",
filterID: "9"
});
$.__views.__alloyId121.add($.__views.fsw9);
changeSwitch ? $.__views.fsw9.addEventListener("change", changeSwitch) : __defers["$.__views.fsw9!change!changeSwitch"] = true;
$.__views.__alloyId123 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId123"
});
$.__views.__alloyId84.add($.__views.__alloyId123);
$.__views.__alloyId124 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId124"
});
$.__views.__alloyId84.add($.__views.__alloyId124);
$.__views.__alloyId125 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Hazardous materials/Gass",
id: "__alloyId125"
});
$.__views.__alloyId124.add($.__views.__alloyId125);
$.__views.fsw10 = Ti.UI.createSwitch({
right: 6,
id: "fsw10",
value: "true",
filterID: "19"
});
$.__views.__alloyId124.add($.__views.fsw10);
changeSwitch ? $.__views.fsw10.addEventListener("change", changeSwitch) : __defers["$.__views.fsw10!change!changeSwitch"] = true;
$.__views.__alloyId126 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId126"
});
$.__views.__alloyId84.add($.__views.__alloyId126);
$.__views.__alloyId127 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId127"
});
$.__views.__alloyId84.add($.__views.__alloyId127);
$.__views.__alloyId128 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Fire/Arson",
id: "__alloyId128"
});
$.__views.__alloyId127.add($.__views.__alloyId128);
$.__views.fsw11 = Ti.UI.createSwitch({
right: 6,
id: "fsw11",
value: "true",
filterID: "16"
});
$.__views.__alloyId127.add($.__views.fsw11);
changeSwitch ? $.__views.fsw11.addEventListener("change", changeSwitch) : __defers["$.__views.fsw11!change!changeSwitch"] = true;
$.__views.__alloyId129 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId129"
});
$.__views.__alloyId84.add($.__views.__alloyId129);
$.__views.__alloyId130 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId130"
});
$.__views.__alloyId84.add($.__views.__alloyId130);
$.__views.__alloyId131 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Property crime",
id: "__alloyId131"
});
$.__views.__alloyId130.add($.__views.__alloyId131);
$.__views.fsw12 = Ti.UI.createSwitch({
right: 6,
id: "fsw12",
value: "true",
filterID: "12"
});
$.__views.__alloyId130.add($.__views.fsw12);
changeSwitch ? $.__views.fsw12.addEventListener("change", changeSwitch) : __defers["$.__views.fsw12!change!changeSwitch"] = true;
$.__views.__alloyId132 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId132"
});
$.__views.__alloyId84.add($.__views.__alloyId132);
$.__views.__alloyId133 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId133"
});
$.__views.__alloyId84.add($.__views.__alloyId133);
$.__views.__alloyId134 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Theft/Lacerny",
id: "__alloyId134"
});
$.__views.__alloyId133.add($.__views.__alloyId134);
$.__views.fsw13 = Ti.UI.createSwitch({
right: 6,
id: "fsw13",
value: "true",
filterID: "11"
});
$.__views.__alloyId133.add($.__views.fsw13);
changeSwitch ? $.__views.fsw13.addEventListener("change", changeSwitch) : __defers["$.__views.fsw13!change!changeSwitch"] = true;
$.__views.__alloyId135 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId135"
});
$.__views.__alloyId84.add($.__views.__alloyId135);
$.__views.__alloyId136 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId136"
});
$.__views.__alloyId84.add($.__views.__alloyId136);
$.__views.__alloyId137 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Suspicious person/Prowler",
id: "__alloyId137"
});
$.__views.__alloyId136.add($.__views.__alloyId137);
$.__views.fsw14 = Ti.UI.createSwitch({
right: 6,
id: "fsw14",
value: "true",
filterID: "5"
});
$.__views.__alloyId136.add($.__views.fsw14);
changeSwitch ? $.__views.fsw14.addEventListener("change", changeSwitch) : __defers["$.__views.fsw14!change!changeSwitch"] = true;
$.__views.__alloyId138 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId138"
});
$.__views.__alloyId84.add($.__views.__alloyId138);
$.__views.__alloyId139 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId139"
});
$.__views.__alloyId84.add($.__views.__alloyId139);
$.__views.__alloyId140 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Vehicle Break-in/Theft",
id: "__alloyId140"
});
$.__views.__alloyId139.add($.__views.__alloyId140);
$.__views.fsw15 = Ti.UI.createSwitch({
right: 6,
id: "fsw15",
value: "true",
filterID: "13"
});
$.__views.__alloyId139.add($.__views.fsw15);
changeSwitch ? $.__views.fsw15.addEventListener("change", changeSwitch) : __defers["$.__views.fsw15!change!changeSwitch"] = true;
$.__views.__alloyId141 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId141"
});
$.__views.__alloyId84.add($.__views.__alloyId141);
$.__views.__alloyId142 = Ti.UI.createView({
right: 0,
left: 0,
height: 40,
backgroundColor: "white",
id: "__alloyId142"
});
$.__views.__alloyId84.add($.__views.__alloyId142);
$.__views.__alloyId143 = Ti.UI.createLabel({
color: "#231f20",
font: {
fontSize: 14
},
left: 9,
right: 70,
text: "Natural Disasters/Rescue",
id: "__alloyId143"
});
$.__views.__alloyId142.add($.__views.__alloyId143);
$.__views.fsw16 = Ti.UI.createSwitch({
right: 6,
id: "fsw16",
value: "true",
filterID: "18"
});
$.__views.__alloyId142.add($.__views.fsw16);
changeSwitch ? $.__views.fsw16.addEventListener("change", changeSwitch) : __defers["$.__views.fsw16!change!changeSwitch"] = true;
$.__views.__alloyId144 = Ti.UI.createView({
backgroundColor: "#CCC",
width: Ti.UI.FILL,
height: 1,
top: 0,
id: "__alloyId144"
});
$.__views.__alloyId84.add($.__views.__alloyId144);
$.__views.typesView = Ti.UI.createView({
left: 0,
top: "100%",
height: "100%",
width: "100%",
id: "typesView",
isOpen: "false"
});
$.__views.container.add($.__views.typesView);
$.__views.__alloyId145 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bgBlackOpacity39.png",
backgroundImage: "/images/bg_popup_flex.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 0,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
left: 0,
top: 0,
right: 0,
bottom: 0,
touchEnabled: false,
backgroundLeftCap: 10,
backgroundTopCap: 10,
id: "__alloyId145"
});
$.__views.typesView.add($.__views.__alloyId145);
$.__views.__alloyId146 = Ti.UI.createLabel({
color: "#17B8E4",
font: {
fontSize: 18
},
left: 10,
top: 10,
text: "Types",
id: "__alloyId146"
});
$.__views.typesView.add($.__views.__alloyId146);
$.__views.__alloyId147 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bgBlackOpacity39.png",
backgroundImage: "/images/transparent.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 1,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
right: 49,
top: 10,
height: 25,
width: 80,
title: "Map Alerts",
id: "__alloyId147"
});
$.__views.typesView.add($.__views.__alloyId147);
changeSettings ? $.__views.__alloyId147.addEventListener("click", changeSettings) : __defers["$.__views.__alloyId147!click!changeSettings"] = true;
$.__views.close = Ti.UI.createButton({
backgroundSelectedImage: "/images/ic_close_pressed.png",
backgroundImage: "/images/ic_close.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 0,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
width: 36,
height: 36,
top: 0,
right: 5,
id: "close"
});
$.__views.typesView.add($.__views.close);
openSettings ? $.__views.close.addEventListener("click", openSettings) : __defers["$.__views.close!click!openSettings"] = true;
$.__views.__alloyId148 = Ti.UI.createScrollView({
top: 50,
left: 3,
right: 6,
bottom: 6,
contentHeight: Ti.UI.SIZE,
borderRadius: 5,
backgroundColor: "white",
layout: "vertical",
id: "__alloyId148"
});
$.__views.typesView.add($.__views.__alloyId148);
$.__views.__alloyId149 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bgBlackOpacity39.png",
backgroundImage: "/images/transparent.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 1,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 17
},
left: 15,
right: 15,
height: 30,
top: 10,
title: "Standard",
id: "__alloyId149"
});
$.__views.__alloyId148.add($.__views.__alloyId149);
setStandView ? $.__views.__alloyId149.addEventListener("click", setStandView) : __defers["$.__views.__alloyId149!click!setStandView"] = true;
$.__views.__alloyId150 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bgBlackOpacity39.png",
backgroundImage: "/images/transparent.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 1,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 17
},
left: 15,
right: 15,
height: 30,
top: 10,
title: "Satellite",
id: "__alloyId150"
});
$.__views.__alloyId148.add($.__views.__alloyId150);
setSatView ? $.__views.__alloyId150.addEventListener("click", setSatView) : __defers["$.__views.__alloyId150!click!setSatView"] = true;
$.__views.__alloyId151 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bgBlackOpacity39.png",
backgroundImage: "/images/transparent.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 1,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 17
},
left: 15,
right: 15,
height: 30,
top: 10,
title: "Hybrid",
id: "__alloyId151"
});
$.__views.__alloyId148.add($.__views.__alloyId151);
setHybView ? $.__views.__alloyId151.addEventListener("click", setHybView) : __defers["$.__views.__alloyId151!click!setHybView"] = true;
$.__views.__alloyId152 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bgBlackOpacity39.png",
backgroundImage: "/images/transparent.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 1,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 17
},
left: 15,
right: 15,
height: 30,
top: 10,
title: "Traffic",
id: "__alloyId152"
});
$.__views.__alloyId148.add($.__views.__alloyId152);
setTrafficView ? $.__views.__alloyId152.addEventListener("click", setTrafficView) : __defers["$.__views.__alloyId152!click!setTrafficView"] = true;
$.__views.listView = Ti.UI.createView({
right: 0,
top: "100%",
height: "100%",
width: "100%",
id: "listView",
isOpen: "false"
});
$.__views.container.add($.__views.listView);
$.__views.__alloyId153 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bgBlackOpacity39.png",
backgroundImage: "/images/bg_popup_flex.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 0,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
left: 0,
top: 0,
right: 0,
bottom: 0,
touchEnabled: false,
backgroundLeftCap: 10,
backgroundTopCap: 10,
id: "__alloyId153"
});
$.__views.listView.add($.__views.__alloyId153);
$.__views.close = Ti.UI.createButton({
backgroundSelectedImage: "/images/ic_close_pressed.png",
backgroundImage: "/images/ic_close.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 0,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
width: 36,
height: 36,
top: 0,
right: 5,
id: "close"
});
$.__views.listView.add($.__views.close);
openListView ? $.__views.close.addEventListener("click", openListView) : __defers["$.__views.close!click!openListView"] = true;
$.__views.__alloyId154 = Ti.UI.createLabel({
color: "#17B8E4",
font: {
fontSize: 18
},
left: 10,
top: 10,
text: "Alerts and Advisories",
id: "__alloyId154"
});
$.__views.listView.add($.__views.__alloyId154);
$.__views.tableAlerts = Ti.UI.createTableView({
top: 50,
left: 3,
right: 6,
bottom: 10,
borderRadius: 5,
backgroundColor: "white",
id: "tableAlerts"
});
$.__views.listView.add($.__views.tableAlerts);
$.__views.__alloyId155 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bt_setting_pressed.png",
backgroundImage: "/images/bt_setting.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 0,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
backgroundColor: "transparent",
left: 10,
bottom: Alloy.Globals.CONTENT_BOTTOM,
width: 38,
height: 38,
id: "__alloyId155"
});
$.__views.container.add($.__views.__alloyId155);
openSettings ? $.__views.__alloyId155.addEventListener("click", openSettings) : __defers["$.__views.__alloyId155!click!openSettings"] = true;
$.__views.__alloyId156 = Ti.UI.createButton({
backgroundSelectedImage: "/images/bt_menu_pressed.png",
backgroundImage: "/images/bt_menu.png",
color: "#17B8E4",
borderColor: "#18b2e0",
borderWidth: 0,
borderRadius: 1,
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
font: {
fontSize: 14
},
backgroundColor: "transparent",
right: 10,
bottom: Alloy.Globals.CONTENT_BOTTOM,
width: 38,
height: 38,
id: "__alloyId156"
});
$.__views.container.add($.__views.__alloyId156);
openListView ? $.__views.__alloyId156.addEventListener("click", openListView) : __defers["$.__views.__alloyId156!click!openListView"] = true;
exports.destroy = function() {};
_.extend($, $.__views);
var APP = require("/core");
arguments[0] || {};
var map = Ti.Map;
var _isLogged = false;
var latitude = 0;
var longitude = 0;
var _updateLatitude = 0;
var _updateLongitude = 0;
var shouldLoadMap = false;
var latitudeDelta;
var longitudeDelta;
var latitudeDelta = .02;
var longitudeDelta = .02;
var days = [ {
title: "Last 24 hours",
filterID: "last1"
}, {
title: "Last 3 days",
filterID: "last3"
}, {
title: "Last 7 days",
filterID: "last7"
}, {
title: "Last 30 days",
filterID: "last30"
}, {
title: "Last 90 days",
filterID: "last90"
}, {
title: "All Days",
filterID: "ALL"
} ];
currentPosition();
$.alertsTitleContainer.top = 43 + APP.fixSizeIos7();
$.refreshMap.top = 78 + APP.fixSizeIos7();
$.settingsView.isOpen = false;
$.typesView.isOpen = true;
$.listView.isOpen = false;
var tempFilters = Ti.App.Properties.getString("MapFilter.Categories.EnabledCategories", "4,1,2,3,5,6,7,9,10,11,12,13,14,15,16,18,19");
var regString = new RegExp("," + $.fsw2.filterID + "\\b", "g");
$.fsw2.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw3.filterID + "\\b", "g");
$.fsw3.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw4.filterID + "\\b", "g");
$.fsw4.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw5.filterID + "\\b", "g");
$.fsw5.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw6.filterID + "\\b", "g");
$.fsw6.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw7.filterID + "\\b", "g");
$.fsw7.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw8.filterID + "\\b", "g");
$.fsw8.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw9.filterID + "\\b", "g");
$.fsw9.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw10.filterID + "\\b", "g");
$.fsw10.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw11.filterID + "\\b", "g");
$.fsw11.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw12.filterID + "\\b", "g");
$.fsw12.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw13.filterID + "\\b", "g");
$.fsw13.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw14.filterID + "\\b", "g");
$.fsw14.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw15.filterID + "\\b", "g");
$.fsw15.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw16.filterID + "\\b", "g");
$.fsw16.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
var regString = new RegExp("," + $.fsw17.filterID + "\\b", "g");
$.fsw17.value = null != tempFilters.match(regString) && tempFilters.match(regString).length > 0 ? true : false;
$.fsw0.value = tempFilters.length >= 2 ? true : false;
$.mapView.addEventListener("postlayout", function() {
var tempWidth = $.mapView.size.width;
var tempHeight = $.mapView.size.height;
$.settingsView.opacity = .8;
$.settingsView.width = APP.numberOperation(tempWidth, "-", 36, false);
$.settingsView.height = APP.numberOperation(tempHeight, "-", 144, false);
$.settingsView.left = APP.numberOperation(-tempWidth, "-", 0, false);
$.settingsView.top = APP.numberOperation(tempHeight, "+", 20, false);
$.typesView.width = APP.numberOperation(tempWidth, "-", 36, false);
$.typesView.height = APP.numberOperation(tempHeight, "-", 144, false);
$.typesView.left = APP.numberOperation(-tempWidth, "-", 0, false);
$.typesView.top = APP.numberOperation(tempHeight, "+", 20, false);
$.listView.width = APP.numberOperation(tempWidth, "-", 40, false);
$.listView.height = APP.numberOperation(tempHeight, "-", 144, false);
$.listView.right = APP.numberOperation(-tempWidth, "-", 0, false);
$.listView.top = APP.numberOperation(tempHeight, "+", 20, false);
});
$.mapView.addEventListener("click", function(evt) {
var annotation = evt.annotation;
var url = evt.annotation ? evt.annotation.url : "http://alertid.com/our-story.asp";
("subtitle" === evt.clicksource || "leftButton" === evt.clicksource || "annotation" === evt.clicksource || "rightButton" === evt.clicksource || "title" === evt.clicksource) && ("Neighbor" == url ? APP.openWindow({
controller: "MyNeighborhoods/MyNeighborhoods",
controllerParams: {
pknmessage: annotation.crimeid
}
}) : APP.openWindow({
controller: "Widgets/Browser",
controllerParams: {
url: url,
title: evt.annotation.title
}
}));
});
$.mapView.addEventListener("regionChanged", function(e) {
_updateLatitude = e.latitude;
_updateLongitude = e.longitude;
});
exports.updateView = updateView;
exports.getCrimes = getCrimes;
exports.currentPosition = currentPosition;
exports.searchAddress = searchAddress;
exports.initializeView = initializeView;
__defers["$.__views.refreshMap!click!refreshMap"] && $.__views.refreshMap.addEventListener("click", refreshMap);
__defers["$.__views.__alloyId83!click!changeSettings"] && $.__views.__alloyId83.addEventListener("click", changeSettings);
__defers["$.__views.close!click!openSettings"] && $.__views.close.addEventListener("click", openSettings);
__defers["$.__views.__alloyId86!click!selectRegion"] && $.__views.__alloyId86.addEventListener("click", selectRegion);
__defers["$.__views.__alloyId89!click!selectDays"] && $.__views.__alloyId89.addEventListener("click", selectDays);
__defers["$.__views.fsw0!change!changeSwitch"] && $.__views.fsw0.addEventListener("change", changeSwitch);
__defers["$.__views.fsw2!change!changeSwitch"] && $.__views.fsw2.addEventListener("change", changeSwitch);
__defers["$.__views.fsw3!change!changeSwitch"] && $.__views.fsw3.addEventListener("change", changeSwitch);
__defers["$.__views.fsw4!change!changeSwitch"] && $.__views.fsw4.addEventListener("change", changeSwitch);
__defers["$.__views.fsw5!change!changeSwitch"] && $.__views.fsw5.addEventListener("change", changeSwitch);
__defers["$.__views.fsw6!change!changeSwitch"] && $.__views.fsw6.addEventListener("change", changeSwitch);
__defers["$.__views.fsw7!change!changeSwitch"] && $.__views.fsw7.addEventListener("change", changeSwitch);
__defers["$.__views.fsw17!change!changeSwitch"] && $.__views.fsw17.addEventListener("change", changeSwitch);
__defers["$.__views.fsw8!change!changeSwitch"] && $.__views.fsw8.addEventListener("change", changeSwitch);
__defers["$.__views.fsw9!change!changeSwitch"] && $.__views.fsw9.addEventListener("change", changeSwitch);
__defers["$.__views.fsw10!change!changeSwitch"] && $.__views.fsw10.addEventListener("change", changeSwitch);
__defers["$.__views.fsw11!change!changeSwitch"] && $.__views.fsw11.addEventListener("change", changeSwitch);
__defers["$.__views.fsw12!change!changeSwitch"] && $.__views.fsw12.addEventListener("change", changeSwitch);
__defers["$.__views.fsw13!change!changeSwitch"] && $.__views.fsw13.addEventListener("change", changeSwitch);
__defers["$.__views.fsw14!change!changeSwitch"] && $.__views.fsw14.addEventListener("change", changeSwitch);
__defers["$.__views.fsw15!change!changeSwitch"] && $.__views.fsw15.addEventListener("change", changeSwitch);
__defers["$.__views.fsw16!change!changeSwitch"] && $.__views.fsw16.addEventListener("change", changeSwitch);
__defers["$.__views.__alloyId147!click!changeSettings"] && $.__views.__alloyId147.addEventListener("click", changeSettings);
__defers["$.__views.close!click!openSettings"] && $.__views.close.addEventListener("click", openSettings);
__defers["$.__views.__alloyId149!click!setStandView"] && $.__views.__alloyId149.addEventListener("click", setStandView);
__defers["$.__views.__alloyId150!click!setSatView"] && $.__views.__alloyId150.addEventListener("click", setSatView);
__defers["$.__views.__alloyId151!click!setHybView"] && $.__views.__alloyId151.addEventListener("click", setHybView);
__defers["$.__views.__alloyId152!click!setTrafficView"] && $.__views.__alloyId152.addEventListener("click", setTrafficView);
__defers["$.__views.close!click!openListView"] && $.__views.close.addEventListener("click", openListView);
__defers["$.__views.__alloyId155!click!openSettings"] && $.__views.__alloyId155.addEventListener("click", openSettings);
__defers["$.__views.__alloyId156!click!openListView"] && $.__views.__alloyId156.addEventListener("click", openListView);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller; |
var socketIO = require('socket.io'),
http = require('http'),
port = process.env.PORT || 8080;
ip = process.env.IP || '127.0.0.1',
server = http.createServer().listen(port,ip,function(){
console.log('start socket');
}),
io = socketIO.listen(server);
io.set('origins','*:*');
var run = function(socket)
{
// user-ha nhan event tu admin roi gui toi client
socket.on('notice-inbox',function(data){
socket.broadcast.emit('user-' + data, data);
});
}
io.on('connection', run);
|
// author: catomatic
// website: https://github.com/catomatic
// source: personal projects library
var quickSort = function(someList) {
var listLen = someList.length;
if (listLen > 1) {
var pivot = someList[Math.floor(listLen / 2)];
var less = [];
var equal = [];
var greater = [];
for (i = 0; i < listLen; i++) {
if (someList[i] < pivot) {
less.push(someList[i]);
} else if (someList[i] == pivot) {
equal.push(someList[i]);
} else if (someList[i] > pivot) {
greater.push(someList[i]);
}
}
var less = quickSort(less);
var greater = quickSort(greater);
return less.concat(equal, greater);
} else {
return someList;
}
}
var numList = [2, 6, 1, 9, 7, 5, 8, 3, 4];
var wordList = ['orange', 'flying squirrel', 'banana', 'grapes', 'bob'];
console.log(quickSort(numList));
console.log(quickSort(wordList)); |
module.exports = {
"POST": {
"validate": 'body',
"schema": {
"type": "object",
"properties": {
"type": {
"type": 'string'
},
"public_key": {
"type": 'string'
},
"private_key": {
"type": 'string'
},
"activated": {
"type": "boolean"
}
},
"required": ['type', 'public_key', 'private_key', 'activated']
}
},
"PUT": {
"validate": 'params',
"schema": {
"type": "object",
"properties": {
"id": {
"type": 'string'
}
},
"required": ['id']
}
},
"DELETE": {
"validate": 'params',
"schema": {
"type": "object",
"properties": {
"id": {
"type": 'string'
}
},
"required": ['id']
}
}
} |
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { withFirebase } from '../Firebase';
import * as ROUTES from '../../constants/routes';
const PasswordForgetLink = () => (
<p>
<Link className="linkstyle" to={ROUTES.PASSWORD_FORGET}>Forgot Password?</Link>
</p>
);
export default PasswordForgetLink |
import { Random } from 'mockjs'
import createMock from 'util/create-mock'
// 示例查看地址:http://mockjs.com/examples.html#DPD
// 占位符 的格式为:
// @占位符
// @占位符(参数 [, 参数])
// 注意:
// 用 @ 来标识其后的字符串是 占位符
// 占位符 引用的是 Mock.Random 中的方法
// 通过 Mock.Random.extend() 来扩展自定义占位符
// 占位符 也可以引用 数据模板 中的属性
// 占位符 会优先引用 数据模板 中的属性
// 占位符 支持 相对路径 和 绝对路径
// 基本占位符
createMock('1、Basic占位符', {
// 布尔值
// Random.boolean( min, max, current )
boolean: {
ok: '@boolean',
no: '@boolean(1, 9, true)',
alter: Random.boolean(1, 9, true)
},
// 自然数
// Random.natural( min )
// Random.natural( min, max )
natural: {
a: '@natural',
b: '@natural(10000)',
c: Random.natural(60, 100)
},
// 整数
// Random.integer( min )
// Random.integer( min, max )
integer: {
a: '@integer',
b: '@integer(10000)',
c: Random.integer(60, 100)
},
// 浮点数
// Random.float( min )
// Random.float( min, max )
// Random.float( min, max, dmin )
// Random.float( min, max, dmin, dmax )
float: {
a: '@float',
b: '@float(1)',
c: Random.float(6, 100),
d: Random.float(5, 10, 2, 5)
},
// 字符
// Random.character( 'lower/upper/number/symbol' )
// Random.character( pool )
character: {
a: '@character',
b: '@character(number)',
// 指定类型的字符
c: Random.character('lower'),
d: Random.character('upper'),
e: Random.character('number'),
f: Random.character('symbol'),
// 随机字符池
g: Random.character('aeiou'),
h: '@character(hello)'
},
// 字符串
// Random.string( length )
// Random.string( pool, length )
// Random.string( min, max )
// Random.string( pool, min, max )
string: {
a: '@string',
b: '@string()',
c: '@string(6)',
d: Random.string('lower', 5),
e: Random.string('upper', 6),
f: Random.string('number', 7),
g: Random.string('symbol', 8),
h: Random.string('aeiou', 9),
i: '@string(1, 10)',
j: '@string("hello", 1, 5)'
},
// 数组
// Random.range( stop )
// Random.range( start, stop )
// Random.range( start, stop, step )
range: {
b: '@range(5)',
a: Random.range(2, 5),
c: '@range(1, 10, 2)'
}
})
// 日期和时间
createMock('2、Date', {
// 日期
// Random.date( format )
date: {
a: '@date',
b: '@date()',
c: '@date("yyyy-MM-dd")',
d: '@date("yy-MM-dd")',
e: '@date("yyyy yy y MM M dd d")'
},
// 时间
// Random.time( format )
time: {
a: Random.time('A HH:mm:ss'),
b: Random.time('a HH:mm:ss'),
c: Random.time('HH:mm:ss a'),
d: Random.time('H:m:s'),
e: '@datetime("HH H hh h mm m ss s SS S A a T")'
},
// 日期和时间
datetime: {
a: Random.datetime('yyyy-MM-dd A HH:mm:ss'),
b: Random.datetime('yy-MM-dd a HH:mm:ss'),
c: Random.datetime('y-MM-dd HH:mm:ss'),
d: Random.datetime('y-M-d H:m:s')
},
// 现在时间
now: {
a: '@now()',
b: '@now("year")',
c: Random.now('yyyy-MM-dd HH:mm:ss SS'),
d: Random.now('day', 'yyyy-MM-dd HH:mm:ss SS')
}
})
// 图片
createMock('3、图片', {
// 链接图片
image: {
// Random.image( size )
a: Random.image('100*200'),
// Random.image( size, background )
b: '@image("200x100", "#FF6600")',
// Random.image( size, background, text )
c: Random.image('200x100', '#4A7BF7', 'Hello'),
// Random.image( size, background, foreground, text )
d: Random.image('200x100', '#50B347', '#FFF', 'Mock.js'),
// Random.image( size, background, foreground, format, text )
e: Random.image('200x100', '#894FC4', '#FFF', 'png', '!')
},
// base64图片
dataImage: {
// Random.dataImage()
a: Random.dataImage(),
// Random.dataImage( size )
b: Random.dataImage('200x100'),
// Random.dataImage( size, text )
c: Random.dataImage('200x100', 'Hello Mock.js!')
}
}) |
///TODO: REVIEW
/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function(height) {
var l = 0, r = height.length -1;
var max = 0;
while ( l < r) {
max = Math.max(max, (r-l) * Math.min(height[l] , height[r]));
if (height[l] < height[r]) l++;
else r--;
}
return max;
};
console.log(maxArea([1, 3, 2, 4]));
console.log(maxArea([1,8,6,2,5,4,8,3,7])); |
import React from "react";
import ReactDOM from "react-dom";
import AppContainer from "./components/AppContainer";
import "./styles/styles.scss";
import { ThemeProvider } from "@material-ui/core/styles";
import theme from "./styles/theme";
import "fontsource-roboto";
require("dotenv").config();
ReactDOM.render(
<ThemeProvider theme={theme}>
<AppContainer />
</ThemeProvider>,
document.getElementById("root")
);
|
$(window).load(function() {
/* Mansonry */
// Animate loader off screen
$(".se-pre-con").fadeOut(500);
$('.picsBox').masonry({
itemSelector: '.picBox',
isFitWidth: true,
isAnimated: true
});
})
$(document).ready(function(){
/* Popup form */
// $('.switchTab ul li').click(function(){
// var curIndex = $(this).index();
// $('.userArea div').css({'display':'none'});
// $('.userArea div').eq(curIndex).css({'display':'block'});
// });
// $('.res_nav').click(function(){
// $('.userModal').addClass('isVisible');
// $('#userRegister').css({'display':'block'});
// $('#userLogin').css({'display':'none'});
// $('.btn_login').removeClass('tabActive')
// $('.btn_register').addClass('tabActive')
// });
// $('.log_nav').click(function(){
// $('.userModal').addClass('isVisible')
// $('#userLogin').css({'display':'block'});
// $('#userRegister').css({'display':'none'});
// $('.btn_register').removeClass('tabActive')
// $('.btn_login').addClass('tabActive')
// });
// $('.btn_login').click(function(){
// $('.btn_register').removeClass('tabActive')
// $('.btn_login').addClass('tabActive')
// });
// $('.btn_register').click(function(){
// $('.btn_login').removeClass('tabActive')
// $('.btn_register').addClass('tabActive')
// });
// $('.close_btn i').click(function() {
// $('.userModal').removeClass('isVisible');
// });
}) |
import Link from 'next/link';
import React from 'react';
import { ArrowRight, HighlightTwo } from '../../../svg';
const hero_contents = {
shapes: [
'hero-shape-5.1.png',
'hero-shape-4.png',
'hero-shape-4.png',
'hero-shape-5.2.png',
],
subtitle: <>Offer is going on till friday , <b>$84,99</b><span>/mo</span></>,
title: 'Business Planing',
highlight_text: 'Advisors',
short_text: <>At collax we specialize in designing, building, shipping and scaling <br /> beautiful, usable products with blazing.</>,
hero_img: '/assets/img/hero/hero-5.1.png',
social_links: [
{ num: 1, icon: 'fab fa-facebook-f social-icon-1', title: 'Facebook',link: 'http://facebook.com' },
{ num: 3, icon: 'fab fa-youtube social-icon-3', title: 'Youtube',link: 'https://www.youtube.com/' },
{ num: 2, icon: 'fab fa-twitter social-icon-2', title: 'Twitter',link: 'http://twitter.com' },
{ num: 2, icon: 'fab fa-behance social-icon-2', title: 'Behance',link: 'https://www.behance.net/' },
],
submit_text: 'Free Consultation'
}
const { hero_img, highlight_text, shapes, short_text, subtitle, title, social_links, submit_text } = hero_contents;
const HeroArea = () => {
return (
<div className="tp-hero-area tp-hero-border p-relative">
{shapes.map((s, i) => (
<div key={i} className={`bp-hero-shape-${i + 1} d-none d-xxl-block`}>
<img src={`/assets/img/hero/${s}`} alt="" />
</div>
))}
<div className="container">
<div className="row">
<div className="col-xl-7 col-lg-7">
<div className="tp-hero-section-box-five">
<div className="tp-hero-section-box-five__subtitle-wrapper d-flex justify-content-between align-items-center mb-40 wow tpfadeUp" data-wow-duration=".3s" data-wow-delay=".5s">
<div className="tp-hero-section-box-five__subtitle">
<h5>{subtitle}</h5>
</div>
<div className="tp-hero-section-box-five__subtitle-link">
<Link href="/price">
<a><ArrowRight /></a>
</Link>
</div>
</div>
<div className="tp-hero-section-box-five__title pb-45">
<h3 className="tp-hero-bs-title wow tpfadeUp" data-wow-duration=".5s" data-wow-delay=".7s">
{title}
<span className="tp-highlight">
<svg className="highlight-space" width="266" height="12" viewBox="0 0 266 12" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M0 0L266 12H0V0Z" fill="#FFDC60" /></svg>
<i>{highlight_text}</i>
</span>
</h3>
<p className="wow tpfadeUp" data-wow-duration=".7s" data-wow-delay=".9s">{short_text}</p>
</div>
<div className="tp-hero-section-box-five__input wow tpfadeUp" data-wow-duration=".9s" data-wow-delay="1s">
<form onSubmit={e => e.preventDefault()}>
<input type="text" placeholder="themepure@gmail.com" />
<button className="tp-btn-sky" type="submit">{submit_text}</button>
</form>
</div>
</div>
</div>
<div className="col-xl-5 col-lg-5 ">
<div className="tp-hero-right-side-five p-relative pt-100">
<div className="tp-yellow-circle-five"></div>
<div className="tp-hero-right-side-five__img wow tpfadeRight"
data-wow-duration=".9s" data-wow-delay="1.2s">
<img src={hero_img} alt="" />
</div>
</div>
</div>
</div>
<div className="tp-hero-icon-five">
<div className="tp-hero-social bp-hero-social tp-hero-social-bg-color">
{social_links.map((l, i) => (
<a key={i} className={`social-icon-${l.num} ${l.title === 'Behance' ? 'd-md-none' : ''}`}
href={l.link} target="_blank" rel="noreferrer">
<i className={l.icon}></i><span>{l.title}</span>
</a>
))}
</div>
</div>
</div>
</div>
);
};
export default HeroArea; |
angular.module('ngApp.express').controller("ExpressCreateShipmentController", function ($scope, $uibModal, UserService, SessionService, AppSpinner, Upload, config, $translate, PreAlertService, CustomerId, Hub, Bags, TradelaneBookingService, ExpressIntegrationShipmentService, toaster, TradelaneShipmentService, TopAirlineService, $uibModalInstance) {
//multilingual translation key
var setMultilingualOptions = function () {
$translate(['FrayteError', 'FrayteWarning', 'FrayteInformation', 'FrayteSuccess', 'CannotRemoveDetailAtleastTwoFlight', 'DeletingProblem', 'DeletedSuccessfully', 'ConfirmationDeleteFlight',
'SureDeleteGivenFlightDetail', 'MaxAddThreeFlight', 'FillMandataryFieldsStar', 'AgentSavedSuccessfully', 'Agent_Same', 'MAWBSavedSuccessfully',
'AgentSame', 'DocumentUploadedSuccessfully', 'ErrorUploadingDocument', 'Errorwhil_uploading_the_excel', 'DocumentAleadyUploadedFor', 'Successfully_Deleted_Document',
'Error_Deleting_Document', 'SuccessfullyUploadedForm', 'ErrorUploadingDocumentTryAgain', 'GettingDetails_Error', 'InitialDataValidation', 'PleaseSelectValidFile',
'Loading_Create_Manifest', 'Loading_Allocating_Agent_Shipment', 'UploadingDocument', 'Document_Already_Uploaded', 'Manifest_Created_Successfully']).then(function (translations) {
$scope.FrayteWarning = translations.FrayteWarning;
$scope.FrayteSuccess = translations.FrayteSuccess;
$scope.FrayteError = translations.FrayteError;
$scope.CannotRemoveDetailAtleastTwoFlight = translations.CannotRemoveDetailAtleastTwoFlight;
$scope.DeletingProblem = translations.DeletingProblem;
$scope.AgentSame = translations.Agent_Same;
$scope.DeletedSuccessfully = translations.DeletedSuccessfully;
$scope.ConfirmationDeleteFlight = translations.ConfirmationDeleteFlight;
$scope.SureDeleteGivenFlightDetail = translations.SureDeleteGivenFlightDetail;
$scope.MaxAddThreeFlight = translations.MaxAddThreeFlight;
$scope.FillMandataryFieldsStar = translations.FillMandataryFieldsStar;
$scope.MAWBSavedSuccessfully = translations.AgentSavedSuccessfully;
$scope.DocumentUploadedSuccessfully = translations.DocumentUploadedSuccessfully;
$scope.ErrorUploadingDocument = translations.ErrorUploadingDocument;
$scope.Errorwhil_uploading_the_excel = translations.Errorwhil_uploading_the_excel;
$scope.DocumentAleadyUploadedFor = translations.DocumentAleadyUploadedFor;
$scope.Successfully_Deleted_Document = translations.Successfully_Deleted_Document;
$scope.Error_Deleting_Document = translations.Error_Deleting_Document;
$scope.SuccessfullyUploadedForm = translations.SuccessfullyUploadedForm;
$scope.ErrorUploadingDocumentTryAgain = translations.ErrorUploadingDocumentTryAgain;
$scope.GettingDetails_Error = translations.GettingDetails_Error;
$scope.InitialDataValidation = translations.InitialDataValidation;
$scope.PleaseSelectValidFile = translations.PleaseSelectValidFile;
$scope.UploadingDocument = translations.UploadingDocument;
$scope.Loading_Create_Manifest = translations.Loading_Create_Manifest;
$scope.Loading_Allocating_Agent_Shipment = translations.Loading_Allocating_Agent_Shipment;
$scope.Document_Already_Uploaded = translations.Document_Already_Uploaded;
$scope.Manifest_Created_Successfully = translations.Manifest_Created_Successfully;
initials();
});
};
//add edit user
$scope.AddEditUser = function () {
modalInstance = $uibModal.open({
animation: true,
templateUrl: 'user/userDetail.tpl.html',
controller: 'UserDetailController',
windowClass: 'DirectBookingDetail',
size: 'lg',
backdrop: 'static',
resolve: {
RoleId: function () {
return $scope.UserRoleId;
},
UserId: function () {
return 0;
},
SystemRoles: function () {
return $scope.SystemRoles;
}
}
});
$scope.GetAgent();
};
//end
$scope.bagWeightTotal = function () {
if ($scope.tradelaneBookingIntegration && $scope.tradelaneBookingIntegration.Shipment && $scope.tradelaneBookingIntegration.Shipment.Packages.length) {
var total = 0;
for (var i = 0; i < $scope.tradelaneBookingIntegration.Shipment.Packages.length; i++) {
total += parseFloat($scope.tradelaneBookingIntegration.Shipment.Packages[i].Weight);
}
return total.toFixed(2);
}
return;
};
$scope.GetShipments = function (BagId) {
ModalInstance = $uibModal.open({
Animation: true,
controller: 'ExpressBagShipmentsController',
templateUrl: 'express/expressManifest/expressManifestShipment.tpl.html',
keyboard: true,
windowClass: 'directBookingDetail',
size: 'lg',
resolve: {
BagId: function () {
return BagId;
}
}
});
};
$scope.CheckSameAgent = function (WithLegJson, LegType) {
if (WithLegJson.FirstLeg.MawbMainObj.Agent !== null && WithLegJson.SecondLeg.MawbMainObj.Agent !== null && WithLegJson.FirstLeg.MawbMainObj.Agent.CustomerName == WithLegJson.SecondLeg.MawbMainObj.Agent.CustomerName && LegType === "Leg1") {
$scope.LegJsonValue1 = true;
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.AgentSame,
showCloseButton: true
});
}
else if (WithLegJson.FirstLeg.MawbMainObj.Agent !== null && WithLegJson.SecondLeg.MawbMainObj.Agent !== null && WithLegJson.FirstLeg.MawbMainObj.Agent.CustomerName == WithLegJson.SecondLeg.MawbMainObj.Agent.CustomerName && LegType === "Leg2") {
$scope.LegJsonValue2 = true;
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.AgentSame,
showCloseButton: true
});
}
else {
$scope.LegJsonValue1 = false;
$scope.LegJsonValue2 = false;
}
};
$scope.ChangeAirlineCode = function (Ary, index) {
if (index === 0) {
for (i = 0; i < $scope.AirlineList.length; i++) {
if (Ary.AirlineId === $scope.AirlineList[i].AirlineId) {
$scope.AirlineCode = $scope.AirlineList[i].AilineCode;
//$scope.AirlineCode2 = $scope.AirlineList[i].CarrierCode2;
Ary.AirlineCode2 = $scope.AirlineList[i].CarrierCode2;
break;
}
}
}
};
$scope.ChangeAirlineCodeLeg = function (Ary, index, Leg) {
if (index === 0 && Leg === 'Leg1') {
for (i = 0; i < $scope.AirlineList.length; i++) {
if (Ary.AirlineId === $scope.AirlineList[i].AirlineId) {
$scope.AirlineCodeLegOne = $scope.AirlineList[i].AilineCode;
//$scope.AirlineCode2LegOne = $scope.AirlineList[i].CarrierCode2;
Ary.AirlineCode2 = $scope.AirlineList[i].CarrierCode2;
break;
}
}
}
if (index === 0 && Leg === 'Leg2') {
for (i = 0; i < $scope.AirlineList.length; i++) {
if (Ary.AirlineId === $scope.AirlineList[i].AirlineId) {
$scope.AirlineCodeLegTwo = $scope.AirlineList[i].AilineCode;
//$scope.AirlineCode2LegTwo = $scope.AirlineList[i].CarrierCode2;
Ary.AirlineCode2 = $scope.AirlineList[i].CarrierCode2;
break;
}
}
}
if (index === 1 && Leg === 'Leg2') {
for (i = 0; i < $scope.AirlineList.length; i++) {
if (Ary.AirlineId === $scope.AirlineList[i].AirlineId) {
//$scope.AirlineCode2LegTwo = $scope.AirlineList[i].CarrierCode2;
Ary.AirlineCode2 = $scope.AirlineList[i].CarrierCode2;
break;
}
}
}
if (index === 2 && Leg === 'Leg2') {
for (i = 0; i < $scope.AirlineList.length; i++) {
if (Ary.AirlineId === $scope.AirlineList[i].AirlineId) {
//$scope.AirlineCode2LegTwo = $scope.AirlineList[i].CarrierCode2;
Ary.AirlineCode2 = $scope.AirlineList[i].CarrierCode2;
break;
}
}
}
};
$scope.save = function (isValid) {
if (isValid) {
$scope.SaveMawbfun();
$scope.FinalList = [];
if ($scope.ShipmentHandlerMethodId !== 5) {
for (i = 0; i < $scope.MawbMainObj.flightArray.length; i++) {
$scope.SaveMawbModel.TradelaneId = $scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId;
$scope.SaveMawbModel.MAWB = $scope.MawbMainObj.MAWB;
$scope.SaveMawbModel.MawbAllocationId = $scope.MawbMainObj.flightArray[i].MawbAllocationId;
$scope.SaveMawbModel.TimezoneId = $scope.MawbMainObj.flightArray[i].Timezone !== null ? $scope.MawbMainObj.flightArray[i].Timezone.TimezoneId : 0;
$scope.SaveMawbModel.AgentId = $scope.MawbMainObj.Agent.CustomerId;
$scope.SaveMawbModel.FlightNumber = $scope.MawbMainObj.flightArray[i].FlightNumber;
$scope.SaveMawbModel.AirlineId = $scope.MawbMainObj.flightArray[i].AirlineId;
$scope.SaveMawbModel.ETA = $scope.MawbMainObj.flightArray[i].ETA;
$scope.SaveMawbModel.ETD = $scope.MawbMainObj.flightArray[i].ETD;
$scope.SaveMawbModel.ETATime = $scope.MawbMainObj.flightArray[i].ETATime;
$scope.SaveMawbModel.ETDTime = $scope.MawbMainObj.flightArray[i].ETDTime;
$scope.SaveMawbModel.CreatedBy = $scope.CreatedBy;
$scope.FinalList.push($scope.SaveMawbModel);
$scope.SaveMawbfun();
}
}
else {
if ($scope.WithLegJson) {
if ($scope.WithLegJson.FirstLeg != null) {
for (i = 0; i < $scope.WithLegJson.FirstLeg.MawbMainObj.flightArray.length; i++) {
$scope.SaveMawbModel.TradelaneId = $scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId;
$scope.SaveMawbModel.MAWB = $scope.WithLegJson.FirstLeg.MawbMainObj.MAWB;
$scope.SaveMawbModel.LegNum = 'Leg1';
$scope.SaveMawbModel.MawbAllocationId = $scope.WithLegJson.FirstLeg.MawbMainObj.flightArray[i].MawbAllocationId;
$scope.SaveMawbModel.TimezoneId = $scope.WithLegJson.FirstLeg.MawbMainObj.flightArray[i].Timezone !== null ? $scope.WithLegJson.FirstLeg.MawbMainObj.flightArray[i].Timezone.TimezoneId : 0;
$scope.SaveMawbModel.AgentId = $scope.WithLegJson.FirstLeg.MawbMainObj.Agent.CustomerId;
$scope.SaveMawbModel.FlightNumber = $scope.WithLegJson.FirstLeg.MawbMainObj.flightArray[i].FlightNumber;
$scope.SaveMawbModel.AirlineId = $scope.WithLegJson.FirstLeg.MawbMainObj.flightArray[i].AirlineId;
$scope.SaveMawbModel.ETA = $scope.WithLegJson.FirstLeg.MawbMainObj.flightArray[i].ETA;
$scope.SaveMawbModel.ETD = $scope.WithLegJson.FirstLeg.MawbMainObj.flightArray[i].ETD;
$scope.SaveMawbModel.ETATime = $scope.WithLegJson.FirstLeg.MawbMainObj.flightArray[i].ETATime;
$scope.SaveMawbModel.ETDTime = $scope.WithLegJson.FirstLeg.MawbMainObj.flightArray[i].ETDTime;
$scope.SaveMawbModel.CreatedBy = $scope.CreatedBy;
$scope.FinalList.push($scope.SaveMawbModel);
$scope.SaveMawbfun();
}
}
if ($scope.WithLegJson.SecondLeg != null) {
for (j = 0; j < $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.length; j++) {
$scope.SaveMawbModel.TradelaneId = $scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId;
$scope.SaveMawbModel.MAWB = $scope.WithLegJson.SecondLeg.MawbMainObj.MAWB;
$scope.SaveMawbModel.LegNum = 'Leg2';
$scope.SaveMawbModel.MawbAllocationId = $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[j].MawbAllocationId;
$scope.SaveMawbModel.TimezoneId = $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[j].Timezone !== null ? $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[j].Timezone.TimezoneId : 0;
$scope.SaveMawbModel.AgentId = $scope.WithLegJson.SecondLeg.MawbMainObj.Agent.CustomerId;
$scope.SaveMawbModel.FlightNumber = $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[j].FlightNumber;
$scope.SaveMawbModel.AirlineId = $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[j].AirlineId;
$scope.SaveMawbModel.ETA = $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[j].ETA;
$scope.SaveMawbModel.ETD = $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[j].ETD;
$scope.SaveMawbModel.ETATime = $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[j].ETATime;
$scope.SaveMawbModel.ETDTime = $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[j].ETDTime;
$scope.SaveMawbModel.CreatedBy = $scope.CreatedBy;
$scope.FinalList.push($scope.SaveMawbModel);
$scope.SaveMawbfun();
}
}
}
}
if ($scope.FinalList.length > 0) {
AppSpinner.showSpinnerTemplate($scope.Loading_Allocating_Agent_Shipment, $scope.Template);
$scope.tradelaneBookingIntegration.MAWBList = $scope.FinalList;
$scope.tradelaneBookingIntegration.Shipment.CreatedBy = $scope.CreatedBy;
$scope.tradelaneBookingIntegration.Shipment.CustomerId = $scope.customerId;
$scope.tradelaneBookingIntegration.Shipment.Hub.HubId = $scope.hub.HubId;
$scope.tradelaneBookingIntegration.Shipment.Hub.Code = $scope.hub.Code;
$scope.tradelaneBookingIntegration.Shipment.Hub.Name = $scope.hub.Name;
$scope.tradelaneBookingIntegration.Shipment.MAWB = $scope.FinalList[0].MAWB;
ExpressIntegrationShipmentService.SaveTradelaneIntegrationShipment($scope.tradelaneBookingIntegration).then(function (response) {
if (response.data) {
toaster.pop({
type: 'success',
title: $scope.FrayteSuccess,
body: $scope.Manifest_Created_Successfully,
showCloseButton: true
});
AppSpinner.hideSpinnerTemplate();
$uibModalInstance.close({ reload: true });
}
}, function () {
AppSpinner.hideSpinnerTemplate();
});
}
}
else {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.FillMandataryFieldsStar,
showCloseButton: true
});
}
};
$scope.AdditemWithoutLeg = function (flightDetail) {
var flightObj = {
FlightNumber: "",
AirlineId: null,
Timezone: null,
ETA: null,
ETD: null,
ETAopened: false,
ETDopened: false,
IsRemove: false,
IsAdd: false,
dateOptions: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
},
dateOptions1: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
},
dateOptions2: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
}
};
if ($scope.MawbMainObj.flightArray.length > 0 && $scope.MawbMainObj.flightArray.length < 3) {
$scope.MawbMainObj.flightArray.push(flightObj);
$scope.MawbMainObj.flightArray[2].IsRemove = true;
$scope.MawbMainObj.flightArray[1].IsAdd = false;
}
else {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.MaxAddThreeFlight,
showCloseButton: true
});
}
};
$scope.RemoveitemWithoutLeg = function (flightDetail) {
if ($scope.MawbMainObj.flightArray.length > 2 && (flightDetail.MawbAllocationId === 0 || flightDetail.MawbAllocationId === undefined || flightDetail.MawbAllocationId === null || flightDetail.MawbAllocationId === "")) {
$scope.MawbMainObj.flightArray.splice($scope.MawbMainObj.flightArray.length - 1, 1);
$scope.MawbMainObj.flightArray[1].IsAdd = true;
}
else if ($scope.MawbMainObj.flightArray.length > 2 && flightDetail.MawbAllocationId > 0) {
var modalOptions = {
headerText: $scope.ConfirmationDeleteFlight,
bodyText: $scope.SureDeleteGivenFlightDetail
};
ModalService.Confirm({}, modalOptions).then(function (result) {
TradelaneShipmentService.DeleteMawbAllocation(flightDetail.MawbAllocationId).then(function (response) {
if (response.data.Status) {
toaster.pop({
type: 'success',
title: $scope.FrayteSuccess,
body: $scope.DeletedSuccessfully,
showCloseButton: true
});
for (i = 0; i < $scope.MawbMainObj.flightArray.length; i++) {
if ($scope.MawbMainObj.flightArray[i].MawbAllocationId === flightDetail.MawbAllocationId) {
$scope.MawbMainObj.flightArray.splice(i, 1);
//$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[1].IsAdd = true;
$scope.MawbMainObj.flightArray[1].IsAdd = true;
}
}
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.DeletingProblem,
showCloseButton: true
});
}
});
});
}
else {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.CannotRemoveDetailAtleastTwoFlight,
showCloseButton: true
});
}
};
$scope.Add = function (flightDetail) {
var flightObj = {
FlightNumber: "",
AirlineId: null,
Timezone: null,
ETA: null,
ETD: null,
ETAopened: false,
ETDopened: false,
IsRemove: false,
IsAdd: false,
dateOptions: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
},
dateOptions1: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
},
dateOptions2: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
}
};
if ($scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.length > 0 && $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.length < 3) {
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.push(flightObj);
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[2].IsRemove = true;
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[1].IsAdd = false;
}
else {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.MaxAddThreeFlight,
showCloseButton: true
});
}
};
$scope.Remove = function (flightDetail) {
if ($scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.length > 2 && (flightDetail.MawbAllocationId === 0 || flightDetail.MawbAllocationId === undefined || flightDetail.MawbAllocationId === null || flightDetail.MawbAllocationId === "")) {
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.splice($scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.length - 1, 1);
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[1].IsAdd = true;
}
else if ($scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.length > 2 && flightDetail.MawbAllocationId > 0) {
var modalOptions = {
headerText: $scope.ConfirmationDeleteFlight,
bodyText: $scope.SureDeleteGivenFlightDetail
};
ModalService.Confirm({}, modalOptions).then(function (result) {
TradelaneShipmentService.DeleteMawbAllocation(flightDetail.MawbAllocationId).then(function (response) {
if (response.data.Status) {
toaster.pop({
type: 'success',
title: $scope.FrayteSuccess,
body: $scope.DeletedSuccessfully,
showCloseButton: true
});
for (i = 0; i < $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.length; i++) {
if ($scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[i].MawbAllocationId === flightDetail.MawbAllocationId) {
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.splice(i, 1);
//$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[1].IsAdd = true;
}
}
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[1].IsAdd = true;
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.DeletingProblem,
showCloseButton: true
});
}
});
});
}
else {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.CannotRemoveDetailAtleastTwoFlight,
showCloseButton: true
});
}
};
$scope.GetFlightNo = function (index, AllocationArray) {
if (AllocationArray.length > 1) {
if (index === 0) {
return "First";
}
if (index === 1) {
return "Second";
}
if (index === 2) {
return "Third";
}
else if (AllocationArray.length === 1) {
return "";
}
}
};
$scope.SaveMawbfun = function () {
$scope.SaveMawbModel = {
MawbAllocationId: 0,
TradelaneId: 0,
MAWB: '',
AgentId: 0,
FlightNumber: '',
AirlineId: 0,
ETA: null,
ETD: null,
CreatedBy: 0
};
};
var setEditjsonWithoutLeg = function () {
var flightObj = {
FlightNumber: "",
AirlineId: null,
Timezone: null,
ETA: null,
ETD: null,
ETAopened: false,
ETDopened: false,
IsAdd: false,
dateOptions: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
},
dateOptions1: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
}
};
$scope.MawbMainObj = {
MAWB: "",
TradelaneShipmentId: $scope.TradelaneShipmentId,
Agent: null,
flightArray: []
};
$scope.MawbMainObj.MAWB = $scope.MawbAllocation[0].MAWB;
for (j = 0; j < $scope.Agents.length; j++) {
if ($scope.MawbAllocation[0].AgentId === $scope.Agents[j].CustomerId) {
$scope.MawbMainObj.Agent = $scope.Agents[j];
}
}
for (i = 0; i < $scope.MawbAllocation.length; i++) {
flightObj.FlightNumber = $scope.MawbAllocation[i].FlightNumber;
flightObj.MawbAllocationId = $scope.MawbAllocation[i].MawbAllocationId;
if ($scope.AirlineList != null && $scope.AirlineList.length > 0) {
for (j = 0; j < $scope.AirlineList.length; j++) {
if ($scope.MawbAllocation[i].AirlineId === $scope.AirlineList[j].AirlineId) {
flightObj.AirlineId = $scope.AirlineList[j].AirlineId;
flightObj.AirlineCode2 = $scope.AirlineList[j].CarrierCode2;
}
}
for (j = 0; j < $scope.AirlineList.length; j++) {
if ($scope.MawbAllocation[i].AirlineId === $scope.AirlineList[j].AirlineId && i === 0) {
$scope.AirlineCode = $scope.AirlineList[j].AilineCode;
flightObj.AirlineCode2 = $scope.AirlineList[j].CarrierCode2;
break;
}
}
}
if ($scope.timezones != null && $scope.timezones.length > 0) {
for (jj = 0; jj < $scope.timezones.length; jj++) {
if ($scope.MawbAllocation[i].TimezoneId === $scope.timezones[jj].TimezoneId) {
flightObj.Timezone = $scope.timezones[jj];
}
}
}
flightObj.ETA = $scope.MawbAllocation[i].ETA !== null ? new Date($scope.MawbAllocation[i].ETA) : null;
flightObj.ETD = $scope.MawbAllocation[i].ETD !== null ? new Date($scope.MawbAllocation[i].ETD) : null;
flightObj.ETATime = $scope.MawbAllocation[i].ETATime;
flightObj.TimezoneId = $scope.MawbAllocation[i].TimezoneId;
flightObj.ETDTime = $scope.MawbAllocation[i].ETDTime;
$scope.MawbMainObj.flightArray.push(flightObj);
flightObj = {
FlightNumber: "",
Timezone: null,
AirlineId: null,
ETA: null,
ETD: null,
ETAopened: false,
ETDopened: false,
IsAdd: false
};
}
if ($scope.MawbMainObj.flightArray != null && $scope.MawbMainObj.flightArray.length == 2) {
$scope.MawbMainObj.flightArray[1].IsAdd = true;
}
if ($scope.MawbMainObj.flightArray != null && $scope.MawbMainObj.flightArray.length == 3) {
$scope.MawbMainObj.flightArray[2].IsRemove = true;
}
};
var setjsonWithoutLeg = function () {
var flightObj = {
FlightNumber: "",
AirlineId: null,
Timezone: null,
TimezoneId: null,
ETA: null,
ETATime: null,
ETD: null,
ETDTime: null,
ETAopened: false,
ETDopened: false,
IsAdd: false,
dateOptions: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
},
dateOptions1: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
}
};
$scope.MawbMainObj = {
MAWB: "",
TradelaneShipmentId: $scope.TradelaneShipmentId,
Agent: null,
flightArray: []
};
if ($scope.tradelaneBookingIntegration.Shipment.ShipmentHandlerMethod.ShipmentHandlerMethodId === 1) {
$scope.MawbMainObj.flightArray.push(flightObj);
}
else if ($scope.tradelaneBookingIntegration.Shipment.ShipmentHandlerMethod.ShipmentHandlerMethodId === 2 || $scope.tradelaneBookingIntegration.Shipment.ShipmentHandlerMethod.ShipmentHandlerMethodId === 4) {
for (i = 0; i < 2; i++) {
$scope.MawbMainObj.flightArray.push(flightObj);
flightObj = {
FlightNumber: "",
AirlineId: null,
Timezone: null,
TimezoneId: null,
ETA: null,
ETATime: null,
ETD: null,
ETDTime: null,
IsAdd: false
};
}
$scope.MawbMainObj.flightArray[1].IsAdd = true;
}
};
var setEditjsonWithLeg = function () {
var flightObj = {
FlightNumber: "",
AirlineId: null,
Timezone: null,
ETA: null,
ETD: null,
ETAopened: false,
ETDopened: false,
IsRemove: false,
IsAdd: false,
dateOptions: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
},
dateOptions1: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
},
dateOptions2: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
}
};
$scope.MawbMainObj = {
MAWB: "",
TradelaneShipmentId: $scope.TradelaneShipmentId,
Agent: null,
flightArray: []
};
$scope.WithLegJson = {
FirstLeg: {
Leg1: "Leg 1",
MawbMainObj: {
MAWB: null,
TradelaneShipmentId: $scope.TradelaneShipmentId,
Agent: null,
flightArray: []
}
},
SecondLeg: {
Leg2: "Leg 2",
MawbMainObj: {
MAWB: null,
TradelaneShipmentId: $scope.TradelaneShipmentId,
Agent: null,
flightArray: []
}
}
};
$scope.WithLegJson.FirstLeg.MawbMainObj.MAWB = $scope.MawbAllocation[0].MAWB;
for (j = 0; j < $scope.Agents.length; j++) {
if ($scope.MawbAllocation[0].AgentId === $scope.Agents[j].CustomerId) {
$scope.WithLegJson.FirstLeg.MawbMainObj.Agent = $scope.Agents[j];
}
}
$scope.WithLegJson.SecondLeg.MawbMainObj.MAWB = $scope.MawbAllocation[1].MAWB;
for (j = 0; j < $scope.Agents.length; j++) {
if ($scope.MawbAllocation[1].AgentId === $scope.Agents[j].CustomerId) {
$scope.WithLegJson.SecondLeg.MawbMainObj.Agent = $scope.Agents[j];
}
}
for (i = 0; i < $scope.MawbAllocation.length; i++) {
if ($scope.MawbAllocation[i].LegNum === 'Leg1') {
flightObj.FlightNumber = $scope.MawbAllocation[i].FlightNumber;
flightObj.MawbAllocationId = $scope.MawbAllocation[i].MawbAllocationId;
//flightObj.TimezoneId = $scope.MawbAllocation[i].TimezoneId;
for (j = 0; j < $scope.AirlineList.length; j++) {
if ($scope.MawbAllocation[i].AirlineId === $scope.AirlineList[j].AirlineId) {
flightObj.AirlineId = $scope.AirlineList[j].AirlineId;
$scope.AirlineCodeLegOne = $scope.AirlineList[j].AilineCode;
// $scope.AirlineCode2LegOne = $scope.AirlineList[j].CarrierCode2;
flightObj.AirlineCode2 = $scope.AirlineList[j].CarrierCode2;
}
}
for (jj = 0; jj < $scope.timezones.length; jj++) {
if ($scope.MawbAllocation[i].TimezoneId === $scope.timezones[jj].TimezoneId) {
flightObj.Timezone = $scope.timezones[jj];
}
}
flightObj.ETA = $scope.MawbAllocation[i].ETA !== null ? new Date($scope.MawbAllocation[i].ETA) : null;
flightObj.ETD = $scope.MawbAllocation[i].ETD !== null ? new Date($scope.MawbAllocation[i].ETD) : null;
flightObj.ETATime = $scope.MawbAllocation[i].ETATime;
flightObj.ETDTime = $scope.MawbAllocation[i].ETDTime;
$scope.WithLegJson.FirstLeg.MawbMainObj.flightArray.push(flightObj);
flightObj = {
FlightNumber: "",
AirlineId: null,
Timezone: null,
ETA: null,
ETD: null,
ETAopened: false,
ETDopened: false,
IsRemove: false,
IsAdd: false
};
}
if ($scope.MawbAllocation[i].LegNum === 'Leg2') {
flightObj.FlightNumber = $scope.MawbAllocation[i].FlightNumber;
flightObj.MawbAllocationId = $scope.MawbAllocation[i].MawbAllocationId;
//flightObj.TimezoneId = $scope.MawbAllocation[i].TimezoneId;
for (j = 0; j < $scope.AirlineList.length; j++) {
if ($scope.MawbAllocation[i].AirlineId === $scope.AirlineList[j].AirlineId) {
flightObj.AirlineId = $scope.AirlineList[j].AirlineId;
//$scope.AirlineCode2LegTwo = $scope.AirlineList[j].CarrierCode2;
flightObj.AirlineCode2 = $scope.AirlineList[j].CarrierCode2;
}
}
for (j = 0; j < $scope.AirlineList.length; j++) {
if ($scope.MawbAllocation[i].AirlineId === $scope.AirlineList[j].AirlineId && i === 1) {
$scope.AirlineCodeLegTwo = $scope.AirlineList[j].AilineCode;
//$scope.AirlineCode2LegTwo = $scope.AirlineList[i].CarrierCode2;
$scope.AirlineCode2 = $scope.AirlineList[i].CarrierCode2;
break;
}
}
for (jj = 0; jj < $scope.timezones.length; jj++) {
if ($scope.MawbAllocation[i].TimezoneId === $scope.timezones[jj].TimezoneId) {
flightObj.Timezone = $scope.timezones[jj];
}
}
flightObj.ETA = $scope.MawbAllocation[i].ETA !== null ? new Date($scope.MawbAllocation[i].ETA) : null;
flightObj.ETD = $scope.MawbAllocation[i].ETD !== null ? new Date($scope.MawbAllocation[i].ETD) : null;
flightObj.ETATime = $scope.MawbAllocation[i].ETATime;
flightObj.ETDTime = $scope.MawbAllocation[i].ETDTime;
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.push(flightObj);
flightObj = {
FlightNumber: "",
AirlineId: null,
Timezone: null,
ETA: null,
ETD: null,
ETAopened: false,
ETDopened: false,
IsRemove: false,
IsAdd: false
};
}
}
if ($scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.length == 2) {
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[1].IsAdd = true;
}
if ($scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.length == 3) {
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[2].IsRemove = true;
}
};
var setjsonWithLeg = function () {
var flightObj = {
FlightNumber: "",
AirlineId: null,
Timezone: null,
TimezoneId: null,
ETA: null,
ETATime: null,
ETD: null,
ETDTime: null,
ETAopened: false,
ETDopened: false,
IsRemove: false,
IsAdd: false,
dateOptions: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
},
dateOptions1: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
},
dateOptions2: {
formatYear: 'yy',
startingDay: 1,
minDate: new Date()
}
};
$scope.MawbMainObj = {
MAWB: "",
TradelaneShipmentId: $scope.TradelaneShipmentId,
Agent: null,
flightArray: []
};
$scope.WithLegJson = {
FirstLeg: {
Leg1: "Leg 1",
MawbMainObj: {
MAWB: null,
TradelaneShipmentId: $scope.TradelaneShipmentId,
Agent: null,
flightArray: []
}
},
SecondLeg: {
Leg2: "Leg 2",
MawbMainObj: {
MAWB: null,
TradelaneShipmentId: $scope.TradelaneShipmentId,
Agent: null,
flightArray: []
}
}
};
for (i = 0; i < 1; i++) {
$scope.WithLegJson.FirstLeg.MawbMainObj.flightArray.push(flightObj);
flightObj = {
FlightNumber: null,
AirlineId: null,
Timezone: null,
TimezoneId: null,
ETA: null,
ETATime: null,
ETD: null,
ETDTime: null,
IsRemove: false,
IsAdd: false
};
}
for (i = 0; i < 2; i++) {
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.push(flightObj);
flightObj = {
FlightNumber: null,
AirlineId: null,
Timezone: null,
TimezoneId: null,
ETA: null,
ETATime: null,
ETD: null,
ETDTime: null,
IsRemove: false,
IsAdd: false
};
}
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[1].IsAdd = true;
};
var setMawbAddJson = function () {
if ($scope.tradelaneBookingIntegration.Shipment.ShipmentHandlerMethod != null && $scope.tradelaneBookingIntegration.Shipment.ShipmentHandlerMethod.ShipmentHandlerMethodId > 0) {
if ($scope.tradelaneBookingIntegration.Shipment.ShipmentHandlerMethod.ShipmentHandlerMethodId !== 5) {
setjsonWithoutLeg();
}
else {
setjsonWithLeg();
}
}
};
var setMawbEditJson = function () {
TradelaneShipmentService.GetShipmentHandlerId($scope.TradelaneShipmentId).then(function (response) {
$scope.ShipmentHandlerMethodId = response.data.ShipmentHandlerMethodId;
$scope.FromAirport = response.data.RouteFrom;
$scope.ToAirport = response.data.RouteTo;
$scope.ShipmentHandlerCode = response.data.ShipemntHandlerMethodCode;
if ($scope.ShipmentHandlerMethodId != null && $scope.ShipmentHandlerMethodId > 0) {
if ($scope.ShipmentHandlerMethodId !== 5) {
setEditjsonWithoutLeg();
}
else {
setEditjsonWithLeg();
}
}
});
};
$scope.ShipmentHandlerMethodChange = function () {
setMawbAddJson();
};
$scope.GetInitial = function () {
TradelaneShipmentService.GetAirlines().then(function (response) {
$scope.AirlineList = TopAirlineService.TopAirlineList(response.data);
});
TradelaneShipmentService.GetTimeZoneList().then(function (response) {
$scope.timezones = response.data;
});
$scope.GetAgent();
};
var getSystemRoles = function () {
UserService.GetSystemRoles($scope.userId).then(function (response) {
if (response.data) {
$scope.SystemRoles = response.data;
}
});
};
$scope.OpenCa = function ($event, index, arr) {
for (i = 0; i < $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.length; i++) {
if (index === i) {
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[i].ETAopened = true;
}
}
};
$scope.OpenCa1 = function ($event, index, arr) {
for (i = 0; i < $scope.WithLegJson.SecondLeg.MawbMainObj.flightArray.length; i++) {
if (index === i) {
$scope.WithLegJson.SecondLeg.MawbMainObj.flightArray[i].ETDopened = true;
}
}
};
$scope.OpenCal = function ($event, index, arr) {
for (i = 0; i < $scope.WithLegJson.FirstLeg.MawbMainObj.flightArray.length; i++) {
if (index === i) {
$scope.WithLegJson.FirstLeg.MawbMainObj.flightArray[i].ETAopened = true;
}
}
};
$scope.OpenCal1 = function ($event, index, arr) {
for (i = 0; i < $scope.WithLegJson.FirstLeg.MawbMainObj.flightArray.length; i++) {
if (index === i) {
$scope.WithLegJson.FirstLeg.MawbMainObj.flightArray[i].ETDopened = true;
}
}
};
$scope.OpenCalender = function ($event, index, arr) {
for (i = 0; i < $scope.MawbMainObj.flightArray.length; i++) {
if (index === i) {
$scope.MawbMainObj.flightArray[i].ETAopened = true;
}
}
};
$scope.OpenCalender1 = function ($event, index, arr) {
for (i = 0; i < $scope.MawbMainObj.flightArray.length; i++) {
if (index === i) {
$scope.MawbMainObj.flightArray[i].ETDopened = true;
}
}
};
var screenInitials = function () {
TradelaneShipmentService.GetAirlines().then(function (response) {
$scope.AirlineList = TopAirlineService.TopAirlineList(response.data);
TradelaneShipmentService.GetTimeZoneList().then(function (response) {
$scope.timezones = response.data;
$scope.GetAgent();
originCountryTimeZone($scope.bags[0].BagId);
}, function () {
AppSpinner.hideSpinnerTemplate();
});
}, function () {
AppSpinner.hideSpinnerTemplate();
});
};
$scope.GetAgent = function () {
TradelaneShipmentService.GetTradelaneAgents().then(function (response) {
$scope.Agents = response.data;
AppSpinner.hideSpinnerTemplate();
}, function () {
AppSpinner.hideSpinnerTemplate();
});
};
var newBooking = function () {
$scope.tradelaneBookingIntegration = {
TradelaneShipmentId: 0,
OpearionZoneId: 0,
CustomerId: $scope.customerId,
BatteryDeclarationType: 'None',
CustomerAccountNumber: null,
ShipmentStatusId: $scope.ShipmentStatus.Draft,
CreatedBy: $scope.CreatedBy,
CreatedOnUtc: new Date(),
ShipFrom: {
TradelaneShipmentAddressId: 0,
Country: null,
PostCode: "",
FirstName: "",
LastName: "",
CompanyName: "",
Address1: "",
Address2: "",
City: "",
State: "",
Area: "",
Phone: "",
Email: "",
IsDefault: false,
IsMailSend: false
},
ShipperAdditionalNote: '',
ShipTo: {
TradelaneShipmentAddressId: 0,
Country: null,
PostCode: "",
FirstName: "",
LastName: "",
CompanyName: "",
Address1: "",
Address2: "",
City: "",
State: "",
Area: "",
Phone: "",
Email: "",
IsDefault: false,
IsMailSend: false
},
ReceiverAdditionalNote: '',
NotifyParty: {
TradelaneShipmentAddressId: 0,
Country: null,
PostCode: "",
FirstName: "",
LastName: "",
CompanyName: "",
Address1: "",
Address2: "",
City: "",
State: "",
Area: "",
Phone: "",
Email: "",
IsMailSend: false
},
NotifyPartyAdditionalNote: '',
IsNotifyPartySameAsReceiver: true,
PayTaxAndDuties: "Shipper",
TaxAndDutyAccountNumber: '',
CustomsSigner: '',
TaxAndDutyAcceptedBy: '',
Currency: null,
Packages: [{
TradelaneShipmentDetailId: 0,
Length: null,
Width: null,
Height: null,
Weight: null,
Value: null,
HAWB: null
}],
ShipmentHandlerMethod: null,
UpdatedBy: 0,
UpdatedOnUtc: new Date(),
FrayteNumber: '',
DepartureAirportCode: '',
DestinationAirportCode: '',
ShipmentReference: '',
ShipmentDescription: '',
DeclaredValue: null,
DeclaredCurrency: null,
AirlinePreference: null,
TotalEstimatedWeight: null,
MAWB: '',
MAWBAgentId: '',
ManifestName: '',
FinalList: $scope.FinalList
};
};
var setPackageJSon = function () {
$scope.tradelaneBookingIntegration.Shipment.Packages = [];
if ($scope.bags && $scope.bags.length) {
for (var i = 0; i < $scope.bags.length; i++) {
var obj = {
TradelaneShipmentDetailId: 0,
TradelaneShipmentId: 0,
Length: 50,
Width: 50,
Height: 50,
Value: 50,
BagId: $scope.bags[i].BagId,
CartonNumber: $scope.bags[i].BagNumber,
NoOfPcs: $scope.bags[i].TotalShipments,
Carrier: $scope.bags[i].Carrier,
Weight: $scope.bags[i].TotalWeight
};
$scope.tradelaneBookingIntegration.Shipment.Packages.push(obj);
}
}
};
var initials = function () {
AppSpinner.showSpinnerTemplate($scope.Loading_Create_Manifest, $scope.Template);
TradelaneBookingService.BookingInitials($scope.userInfo.EmployeeId).then(function (response) {
AppSpinner.hideSpinnerTemplate();
$scope.ShipmentMethods = response.data.ShipmentMethods;
ExpressIntegrationShipmentService.TradelaneHubInitials($scope.customerId, $scope.hubId).then(function (response) {
$scope.tradelaneBookingIntegration = response.data;
$scope.tradelaneBookingIntegration.Shipment.ShipmentHandlerMethod = $scope.ShipmentMethods[0];
$scope.ShipmentHandlerMethodChange();
// MAWB initials
screenInitials();
setPackageJSon();
}, function () {
AppSpinner.hideSpinnerTemplate();
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.InitialDataValidation,
showCloseButton: true
});
});
},
function (response) {
AppSpinner.hideSpinnerTemplate();
if (response.status !== 401) {
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.InitialDataValidation,
showCloseButton: true
});
}
});
};
var ShipmentInitials = function () {
};
// MAWB Document
$scope.WhileAddingMAWB = function ($files, $file, $event) {
if (!$file) {
return;
}
if ($file.$error) {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.PleaseSelectValidFile,
showCloseButton: true
});
return;
}
AppSpinner.showSpinnerTemplate($scope.UploadingDocument, $scope.Template);
$scope.MawbDoc = $file.name;
// Upload the excel file here.
$scope.uploadMAWB = Upload.upload({
url: config.SERVICE_URL + '/ExpressManifest/UploadMAWBForms',
file: $file,
fields: {
ShipmentId: $scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId,
DocType: "MAWBDocument",
UserId: $scope.userId,
CustomerId: $scope.customerId,
HubId: $scope.hubId
}
});
$scope.uploadMAWB.progress($scope.progressMAWB);
$scope.uploadMAWB.success($scope.successMAWB);
$scope.uploadMAWB.error($scope.errorMAWB);
};
$scope.progressMAWB = function (evt) {
//To Do: show excel uploading progress message
};
$scope.successMAWB = function (data, status, headers, config) {
if (status = 200) {
AppSpinner.hideSpinnerTemplate();
if (data) {
if (!isNaN(data) && (parseInt(data, 10) > 0)) {
toaster.pop({
type: 'success',
title: $scope.FrayteSuccess,
body: $scope.DocumentUploadedSuccessfully,
showCloseButton: true
});
$scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId = data;
}
else if (data === "MAWB") {
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.ErrorUploadingDocument,
showCloseButton: true
});
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.ErrorUploadingDocument,
showCloseButton: true
});
}
}
else {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: data.Message,
showCloseButton: true
});
}
}
else {
AppSpinner.hideSpinnerTemplate();
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.ErrorUploadingDocument,
showCloseButton: true
});
}
};
$scope.errorMAWB = function (err) {
AppSpinner.hideSpinnerTemplate();
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.Errorwhil_uploading_the_excel,
showCloseButton: true
});
};
// end // MAWB Document
// Upload Other Document Section
$scope.WhileAddingOtherDoc = function ($files, $file, $event) {
if (!$file) {
return;
}
if ($file.$error) {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.PleaseSelectValidFile,
showCloseButton: true
});
return;
}
AppSpinner.showSpinnerTemplate($scope.UploadingDocument, $scope.Template);
// Upload the excel file here.
$scope.uploadExcel = Upload.upload({
url: config.SERVICE_URL + '/ExpressManifest/UploadOtherDocument',
file: $file,
fields: {
ShipmentId: $scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId,
DocType: "OtherDocument",
UserId: $scope.userId,
CustomerId: $scope.customerId,
HubId: $scope.hubId
}
});
$scope.uploadExcel.progress($scope.progressExcel);
$scope.uploadExcel.success($scope.successExcel);
$scope.uploadExcel.error($scope.errorExcel);
};
$scope.progressExcel = function (evt) {
//To Do: show excel uploading progress message
};
$scope.successExcel = function (data, status, headers, config) {
if (status = 200) {
AppSpinner.hideSpinnerTemplate();
if (data) {
if (!isNaN(data) && (parseInt(data, 10) > 0)) {
toaster.pop({
type: 'success',
title: $scope.FrayteSuccess,
body: $scope.DocumentUploadedSuccessfully,
showCloseButton: true
});
$scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId = data;
getshipmentOtherDocuments();
}
else if (data === "Failed") {
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.ErrorUploadingDocument,
showCloseButton: true
});
}
else {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.DocumentAleadyUploadedFor + data,
showCloseButton: true
});
}
}
else {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: data.Message,
showCloseButton: true
});
}
}
else {
AppSpinner.hideSpinnerTemplate();
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.ErrorUploadingDocument,
showCloseButton: true
});
}
};
$scope.errorExcel = function (err) {
AppSpinner.hideSpinnerTemplate();
if (err === 'OtherDocument') {
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.Document_Already_Uploaded, // document already uploaded
showCloseButton: true
});
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.ErrorUploadingDocument,
showCloseButton: true
});
}
};
var getshipmentOtherDocuments = function () {
PreAlertService.getTradelaneDocuments($scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId).then(function (response) {
if (response.data && response.data.length) {
$scope.otherDocuments = response.data[0];
otherDocumentJson();
}
AppSpinner.hideSpinnerTemplate();
}, function () {
AppSpinner.hideSpinnerTemplate();
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.GettingDetails_Error,
showCloseButton: true
});
});
};
var otherDocumentJson = function (type, UploadType) {
$scope.attachments = [];
if ($scope.otherDocuments.Documents.length) {
angular.forEach($scope.otherDocuments.Documents, function (obj) {
$scope.attachments.push(obj);
});
}
};
var removeDocument = function (doc, document) {
if ($scope.attachments && $scope.attachments.length) {
for (var j = 0; j < $scope.attachments.length ; j++) {
if ($scope.attachments[j].TradelaneShipmentDocumentId === doc.TradelaneShipmentDocumentId) {
$scope.attachments.splice(j, 1);
break;
}
}
}
if (!$scope.attachments.length) {
$scope.open = false;
}
};
$scope.removeDoc = function (doc, document) {
console.log(doc);
if (doc) {
AppSpinner.showSpinnerTemplate($scope.Loading_Create_Manifest, $scope.Template);
TradelaneBookingService.removeDocument(doc.TradelaneShipmentDocumentId).then(function (response) {
AppSpinner.hideSpinnerTemplate();
if (response.data.Status) {
toaster.pop({
type: 'success',
title: $scope.FrayteSuccess,
body: $scope.Successfully_Deleted_Document,
showCloseButton: true
});
removeDocument(doc, document);
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.Error_Deleting_Document,
showCloseButton: true
});
}
}, function () {
AppSpinner.hideSpinnerTemplate();
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.Error_Deleting_Document,
showCloseButton: true
});
});
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteError,
body: $scope.Error_Deleting_Document,
showCloseButton: true
});
}
};
//Upload BatteryFrom
$scope.WhileAddingMsBatteryForm = function ($files, $file, $event) {
if (!$file) {
return;
}
if ($file.$error) {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.PleaseSelectValidFile,
showCloseButton: true
});
return;
}
$scope.msdsBatteryFileName = $file.name;
// Upload the excel file here.
$scope.uploadMSDS = Upload.upload({
url: config.SERVICE_URL + '/ExpressManifest/UploadBatteryForms',
file: $file,
fields: {
ShipmentId: $scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId,
DocType: "BatteryDeclaration",
UserId: $scope.userId,
CustomerId: $scope.customerId,
HubId: $scope.hubId
}
});
$scope.uploadMSDS.progress($scope.progressuploadMSDS);
$scope.uploadMSDS.success($scope.successuploadMSDS);
$scope.uploadMSDS.error($scope.erroruploadMSDS);
};
$scope.progressuploadMSDS = function (evt) {
//To Do: show excel uploading progress message
};
$scope.successuploadMSDS = function (data, status, headers, config) {
if (status = 200) {
if (!isNaN(data) && (parseInt(data, 10) > 0)) {
$scope.MSDS = $scope.msdsBatteryFileName;
toaster.pop({
type: 'success',
title: $scope.FrayteSuccess,
body: $scope.SuccessfullyUploadedForm,
showCloseButton: true
});
$scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId = data;
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteWarning,
body: $scope.ErrorUploadingDocumentTryAgain,
showCloseButton: true
});
}
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteWarning,
body: $scope.ErrorUploadingDocumentTryAgain,
showCloseButton: true
});
}
};
$scope.erroruploadMSDS = function (err) {
if (err && err.Message === "BatteryForm") {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.DocumentAleadyUploadedFor + err.Message,
showCloseButton: true
});
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteWarning,
body: $scope.ErrorUploadingDocumentTryAgain,
showCloseButton: true
});
}
};
//Upload BatteryFrom UN38
$scope.WhileAddingUN38BatteryForm = function ($files, $file, $event) {
if ($file.$error) {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.PleaseSelectValidFile,
showCloseButton: true
});
return;
}
$scope.un38BatteryFileName = $file.name;
// Upload the excel file here.
$scope.uploadUN38 = Upload.upload({
url: config.SERVICE_URL + '/ExpressManifest/UploadBatteryForms',
file: $file,
fields: {
ShipmentId: $scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId,
DocType: "BatteryDeclaration",
UserId: $scope.userId,
CustomerId: $scope.customerId,
HubId: $scope.hubId
}
});
$scope.uploadUN38.progress($scope.progressuploadUN38);
$scope.uploadUN38.success($scope.successuploadUN38);
$scope.uploadUN38.error($scope.erroruploadUN38);
};
$scope.progressuploadUN38 = function (evt) {
//To Do: show excel uploading progress message
};
$scope.successuploadUN38 = function (data, status, headers, config) {
if (status = 200) {
if (!isNaN(data) && (parseInt(data, 10) > 0)) {
$scope.UN38 = $scope.un38BatteryFileName;
toaster.pop({
type: 'success',
title: $scope.FrayteSuccess,
body: $scope.SuccessfullyUploadedForm,
showCloseButton: true
});
$scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId = data;
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteWarning,
body: $scope.ErrorUploadingDocumentTryAgain,
showCloseButton: true
});
}
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteWarning,
body: $scope.ErrorUploadingDocumentTryAgain,
showCloseButton: true
});
}
};
$scope.erroruploadUN38 = function (err) {
if (err && err.Message === "BatteryForm") {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.DocumentAleadyUploadedFor + err.Message,
showCloseButton: true
});
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteWarning,
body: $scope.ErrorUploadingDocumentTryAgain,
showCloseButton: true
});
}
};
//Upload BatteryFrom UN38
$scope.WhileAddingBatteryDeclarationForm = function ($files, $file, $event) {
if ($file.$error) {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.PleaseSelectValidFile,
showCloseButton: true
});
return;
}
$scope.batteryDeclarationFormFileNBame = $file.name;
// Upload the excel file here.
$scope.uploadBatteryDeclarationForm = Upload.upload({
url: config.SERVICE_URL + '/ExpressManifest/UploadBatteryForms',
file: $file,
fields: {
ShipmentId: $scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId,
DocType: "BatteryDeclaration",
UserId: $scope.userId,
CustomerId: $scope.customerId,
HubId: $scope.hubId
}
});
$scope.uploadUN38.progress($scope.progressuploadBatteryDeclarationForm);
$scope.uploadUN38.success($scope.successuploadBatteryDeclarationForm);
$scope.uploadUN38.error($scope.erroruploadBatteryDeclarationForm);
};
$scope.progressuploadBatteryDeclarationForm = function (evt) {
//To Do: show excel uploading progress message
};
$scope.successuploadBatteryDeclarationForm = function (data, status, headers, config) {
if (status = 200) {
if (!isNaN(data) && (parseInt(data, 10) > 0)) {
$scope.BatteryDeclaration = $scope.batteryDeclarationFormFileNBame;
toaster.pop({
type: 'success',
title: $scope.FrayteSuccess,
body: $scope.SuccessfullyUploadedForm,
showCloseButton: true
});
$scope.tradelaneBookingIntegration.Shipment.TradelaneShipmentId = data;
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteWarning,
body: $scope.ErrorUploadingDocumentTryAgain,
showCloseButton: true
});
}
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteWarning,
body: $scope.ErrorUploadingDocumentTryAgain,
showCloseButton: true
});
}
};
$scope.erroruploadBatteryDeclarationForm = function (err) {
if (err && err.Message === "BatteryForm") {
toaster.pop({
type: 'warning',
title: $scope.FrayteWarning,
body: $scope.DocumentAleadyUploadedFor + err.Message,
showCloseButton: true
});
}
else {
toaster.pop({
type: 'error',
title: $scope.FrayteWarning,
body: $scope.ErrorUploadingDocumentTryAgain,
showCloseButton: true
});
}
};
//End Battery Form
function originCountryTimeZone(BagId) {
if (BagId !== undefined && BagId !== null && BagId !== '' && BagId > 0) {
ExpressIntegrationShipmentService.GetTimeZoneName(BagId).then(function (response) {
if (response.data !== undefined && response.data !== null && response.data !== '') {
angular.forEach($scope.timezones, function (item, key) {
if (response.data === item.Name) {
$scope.MawbMainObj.flightArray[0].Timezone = item;
}
});
}
});
}
}
function init() {
$scope.submitted = true;
$scope.Template = 'directBooking/ajaxLoader.tpl.html';
$scope.userInfo = SessionService.getUser();
$scope.UserRoleId = $scope.userInfo.RoleId;
$scope.userId = $scope.userInfo.EmployeeId;
$scope.ShipmentStatus = {
Draft: 27,
ShipmentBooked: 28,
Pending: 29,
Delivered: 35,
Rejeted: 34,
Departed: 30,
Intransit: 31,
Arrived: 32
};
$scope.CreatedBy = $scope.userInfo.EmployeeId;
$scope.hub = Hub;
$scope.hubId = $scope.hub.HubId;
$scope.customerId = CustomerId;
$scope.bags = Bags;
$scope.batteryDeclarations = [
{
key: 'None',
value: 'None'
},
{
key: 'PI966',
value: 'PI966'
},
{
key: 'PI967',
value: 'PI967'
}
];
setMultilingualOptions();
getSystemRoles();
}
init();
}); |
import React from "react"
import { Link } from "react-router-dom"
import { TwitterPicker } from "react-color"
export default function Settings(props) {
function handleNicknameChange(event) {
props.onChange({nickname: event.target.value})
}
function handleColorChange(color, event) {
props.onChange({color: color.hex})
}
const flexbox = {
display: "flex",
flexDirection: "column",
alignItems: "center",
margin: "20px",
}
const inputGroup = {
maxWidth: "400px",
marginBottom: "20px"
}
return (
<div style={flexbox}>
<div style={inputGroup}>
<label className="label">Nickname</label>
<input
type="text"
value={props.settings.nickname}
onChange={handleNicknameChange}
className="input mousetrap"
/>
</div>
<div style={{ marginBottom: "20px" }}>
<TwitterPicker
color={props.settings.color}
onChangeComplete={handleColorChange}
triangle="hide"
/>
</div>
<Link
to="/"
className="button is-primary"
>
Save
</Link>
</div>
)
}
|
import clearModal from './clearModal';
const togglePopup = () => {
const popupToggle = document.querySelectorAll('.open-popup, .callback-btn, .fixed-gift, .popup'),
giftPopup = document.getElementById('gift'),
forms = document.querySelectorAll('#form2, #form1'),
thanks = document.getElementById('thanks'),
checkbox = document.querySelectorAll('[for="check2"], [for="check"]');
popupToggle.forEach(item => {
item.addEventListener('click', (e) => {
const popup = document.querySelector(item.getAttribute('data-popup'));
if (item.hasAttribute('type')) {
popup.style.display = 'none';
} else if (e.target.closest('.free-visit > p') || e.target.closest('.callback-btn')) {
popup.style.display = 'block';
} else if (e.target.closest('.fixed-gift')) {
giftPopup.style.display = 'block';
e.target.style.display = 'none';
} else if (e.target.matches('.close_icon') || !e.target.closest('.form-content') || e.target.matches('.close-btn')) {
if (thanks.style.display !== 'block') {
forms.forEach(form => {
clearModal(form, checkbox);
});
item.style.display = 'none';
} else {
item.style.display = 'none';
}
}
});
});
};
export default togglePopup; |
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('private_block_log', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
blockNumber: {
allowNull: false,
comment: '区块高度',
type: Sequelize.INTEGER
},
blockHash: {
allowNull: false,
comment: '哈希',
type: Sequelize.STRING
},
txTrieRoot:{
allowNull: false,
comment: '根目录',
type: Sequelize.STRING
},
witnessAddress:{
allowNull: false,
comment: '挖矿地址',
type: Sequelize.STRING
},
parentHash:{
allowNull: false,
comment: '上个块的hash',
type: Sequelize.STRING
},
blockTimestamp:{
allowNull: false,
comment: '出块时间戳',
type: Sequelize.STRING
},
transactionsNum:{
allowNull: false,
comment: '交易数量',
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('private_block_log');
}
}; |
/*
* ヘッダ部のレイアウト編集
*
**/
var NEW_PARTS_BEG = 1;
var CURR_NEW_PARTS = NEW_PARTS_BEG;
var CURR_EDIT_TOP_PARTS_NO;
var CURR_EDIT_MAIN_PARTS_NO;
var CURR_EDIT_PARTS_CLASS;
var EXT_LIST;
var PAGEID;
var DLG_OBJ;
var DLG_OUTER_OBJ;
var DLG_STS;
var DLG_BTN_COLOR;
var NARROW_WIDTH = 320;
var MMAREA;
var PAGE_LIST_TOP = [
// 'HEADER' , /* ヘッダ */
'NEWS' , /* 新着ダイジェスト */
'ALBUM' , /* 女性リスト */
'SCHEDULE' , /* 出勤 */
// 'NOTICE' , /* 告知 */
'PRICEL' , /* 料金表 */
'RECRUIT' , /* 求人 */
'PD' , /* 写メ日記ダイジェスト */
'MASTERSBLOG' /* 店長ブログ */
];
var PAGE_LIST_NEWS = [
// 'HEADER' , /* ヘッダ */
'NEWSM' /* 本文 */
];
var PAGE_LIST = {
'TOP' : PAGE_LIST_TOP ,
'NEWS' : PAGE_LIST_NEWS
};
var OBJ_STR = {
// 'HEADER' : 'ヘッダ' ,
// 'NEWS' : '新着情報' ,
// 'ALBUM' : '女性リスト' ,
// 'SCHEDULE' : '出勤' ,
// 'NOTICE' : '告知' ,
// 'PRICEL' : '料金表' ,
// 'RECRUIT' : '求人' ,
// 'PD' : '写メ日記' ,
// 'MASTERSBLOG' : '店長ブログ' ,
'IMG' : '画像' ,
'STR' : '文字列'
};
/***** 更新対象ファイル *****/
var EDIT_FILE = {
'TOP' : true , /* top */
'NEWS' : true , /* 新着 */
'ALBUM' : true , /* 女性リスト */
'SCHEDULE' : true , /* 出勤 */
'NOTICE' : false , /* 告知 */
'PRICEL' : true , /* 料金表 */
'RECRUIT' : true , /* 求人 */
'PD' : false , /* 写メ日記 */
'MASTERSBLOG': false /* 店長ブログ */
};
$(window).load(function() {
initDialog();
/***** パセリ初期化 *****/
// $('form#seleNewImg').parsley({
// successClass : "has-success" ,
// errorClass : "has-error" ,
//
// errorsWrapper : '<div class="invalid-message"></div>' ,
// errorTemplate : '<span></span>'
// });
//
// $('form#formDlg').parsley({
// successClass : "has-success" ,
// errorClass : "has-error" ,
//
// errorsWrapper : '<div class="invalid-message"></div>' ,
// errorTemplate : '<span></span>'
// });
$(".dispImgSW").toggleSwitch();
});
$(document).ready(function() {
$('#uploadNewImg').click(function() {
//console.debug('click');
$('#seleNewImg').submit();
//console.debug('return from submit');
});
CKEDITOR.on('instanceReady', function(){
$.each( CKEDITOR.instances, function(instance) {
CKEDITOR.instances[instance].on("change", function(e) {
for(instance in CKEDITOR.instances)
CKEDITOR.instances[instance].updateElement();
});
CKEDITOR.instances[instance].on("blur", function(e) {
for(instance in CKEDITOR.instances)
CKEDITOR.instances[instance].updateElement();
});
});
});
// $('#formDlg').parsley();
//
// /***** 非表示項目のバリデーションを行わない *****/
// $.listen('parsley:field:validated', function(fieldInstance){
// if (fieldInstance.$element.is(":hidden")) {
// // hide the message wrapper
// fieldInstance._ui.$errorsWrapper.css('display', 'none'); // 要らない???
// // set validation result to true
// fieldInstance.validationResult = true;
// return true;
// }
// });
});
$(function() {
MMAREA = $('#mmArea')[0];
getLayoutScreen('INIT');
getImgList();
/********************
パセリ実行
********************/
/***** 入力域 *****/
$('#formDlg').submit(function(){
var noError = true;
// var validFormDlg = $("#formDlg").parsley().isValid();
// if(validFormDlg) {
// /***** no error *****/
// console.debug('no error');//alert('true');
// noError = true;
// } else {
// /***** any error *****/
// console.debug('any error');//alert('false');
// noError = false;
// }
if(noError) {
getEnterVals();
$("#editDlg").dialog("close");
} else {
//alert('any error');
// $("div.invalid-message").css("display" ,"inline");
// $("span.parsley-required").parent("div").css("display" ,"inline")
}
return false;
});
$('#formSTR').submit(function(){
var submitResult = submitForm('#formSTR');
if(submitResult) {
$("#editSTR").modal('hide');
}
return false;
});
$('#formIMG').submit(function(){
var submitResult = submitForm('#formIMG');
if(submitResult) {
$("#editIMG").modal('hide');
}
return false;
});
$('#seleNewImg').submit(function(){
var validTitleStr = $("#newTitle").parsley().isValid();
var validSeleFile = $("#newFile").parsley().isValid();
if(validTitleStr && validSeleFile) {
//console.debug('upload new file');
uploadNewImg();
}
return false;
});
setSortable();
CURR_NEW_PARTS = NEW_PARTS_BEG;
$("#newFile").change(function () {
fileSele(this);
});
PAGEID = $("#pageID").val();
/***** 編集領域を非表示 *****/
$("#layoutEditTitle").html(' ');
$(".editAreaO").hide();
$('div#mtnOut').exResize(function(){ /* div#editOutのどっちか */
adjustCurrentScreen();
});
setResize();
initShowPreview();
reshowCurrFile();
});
/* フォームサブミットの本体
*
@param formのID
@return -
*/
function submitForm(formID) {
var noError;
var validFormDlg = $(formID).parsley().isValid();
if(validFormDlg) {
/***** no error *****/
console.debug('no error');//alert('true');
noError = true;
} else {
/***** any error *****/
console.debug('any error');//alert('false');
noError = false;
}
if(noError) {
getEnterVals();
previewLayout();
} else {
// $("div.invalid-message").css("display" ,"inline");
// $("span.parsley-required").parent("div").css("display" ,"inline")
}
return noError;
}
/* プレビュー領域のリサイズ
*
@param -
@return -
*/
function setResize() {
$("#previewAreaR").resizable({ //mmArea
handles : 'e' ,
stop(event ,ui) {
var wArea = $("#previewAreaR").width();
var wAreaI = wArea - 2;
var wmmArea = wAreaI - 2;
// $("#previewArea").width(wArea + "px");
$("#previewAreaI").width(wAreaI + "px");
$("#mmArea").width(wmmArea + "px");
} ,
resize(event ,ui) {
var wArea = $("#previewAreaR").width();
var wAreaI = wArea - 2;
var wmmArea = wAreaI - 2;
// $("#previewArea").width(wArea + "px");
$("#previewAreaI").width(wAreaI + "px");
$("#mmArea").width(wmmArea + "px");
}
});
}
/* プレビュー領域の初期化
*
@param -
@return -
*/
function initShowPreview() {
/***** 高さの設定 *****/
var hEdOut = $("#editOut").outerHeight(true);
var hH1 = $("h1").outerHeight(true);
var hActBtn = $("#actBtn").outerHeight(true);
var hResize = $("#previewAreaR").outerHeight(true); //表示幅調整
var hIFramBtn = $("#iFrameBtn").outerHeight(true); //「戻る」ボタン
var mtEditMain = $("#editmain").css('margin-top');
var ptEditMain = $("#editmain").css('padding-top');
mtEditMain = parseInt(mtEditMain);
ptEditMain = parseInt(ptEditMain);
var h2 = hEdOut - (hH1 + mtEditMain + ptEditMain + hResize + hIFramBtn + hActBtn);
var hAreaI = h2 - 2;
var hmmArea = hAreaI - 2;
$("#previewAreaI").height(hAreaI + "px");
$("#mmArea").height(hmmArea + "px");
/***** 幅の設定 *****/
var wAreaR = $("#previewAreaI").width() - 20;
var wAreaI = wAreaR - 2;
var wmmArea = wAreaI - 2;
$("#previewAreaR").width(wAreaR + "px");
$("#previewAreaI").width(wAreaI + "px");
$("#mmArea").width(wmmArea + "px");
}
/* ファイル選択時の妥当性のチェック
*
@param ファイルオブジェクト
@return -
*/
function fileSele(obj) {
var fileAttr = obj.files[0];
var name = fileAttr.name;
//var size = fileAttr.size;
var type = fileAttr.type;
var str = '';
if(type == 'image/jpeg'
|| type == 'image/png'
|| type == 'image/gif') {
$("#strImgFile").html(''); //選択していないときのエラーメッセージを非表示
$('#newFile').parsley().reset();
$('.imgTypeCaution').html(str);
$("#newTitle").val(name);
} else {
/* ファイル形式が指定以外だったとき */
//選択したファイル名をリセット
$('#newFile').parsley().reset();
$('#newFile').after('<input type="file" name="newFile" id="newFileEnter" data-parsley-required="true" data-parsley-trigger="focusout submit change">');
$('#newFile').remove();
$('#newFileEnter').attr('id','newFile');
$('#newFile').on("change", function () {
fileSele(this);
});
$('#newFile').parsley({
successClass : "has-success",
errorClass : "has-error" ,
errorsWrapper : '<div class="invalid-message"></div>',
errorTemplate : '<span></span>'
});
$("#newFile").parsley().isValid();
/*
var c = $('#newFile').clone(true); //true ... イベントを継承
c.val('');
$('#newFile').replaceWith(c);
*/
str = 'jpg、png、gifのいずれかの形式のファイルを選択してください';
$('.imgTypeCaution').html(str);
}
//console.debug('str:' + str);
}
/********************************* 画面情報読み込み *********************************/
/* サーバからヘッダ編集画面の初期化に必要な情報の取得
*
@param 初期化モード
@return -
*/
function getLayoutScreen(mode) {
var result = ajaxGetLayout(mode);
var newsVals;
var valList;
result.done(function(response) {
console.debug(response);
if(response['ERROR'] == 'NO SESSION') {
forNoSession();
}
valList = response['VALLIST'];
/*
console.debug('pageID...' + PAGEID);
console.debug(valList);
*/
//$('#pageID').val(response['PAGEID']);
/* レイアウトリスト表示 */
$('div#posT').html(valList['tag']['TOP']);
$('div#posO').html(valList['tag']['OTHER']);
$('div#partsEditTab').html(valList['val']);
$('#partsNoList' ).val(valList['partsNo']);
$(".dispSW").toggleSwitch();
});
result.fail(function(result, textStatus, errorThrown) {
console.log("error for ajaxGetLayoutFromSess:" + result.status + ' ' + textStatus);
});
result.always(function() {
});
}
/* サーバからヘッダ編集画面の初期化に必要な情報の取得(ajax通信)
*
@param 初期化モード
@return -
*/
function ajaxGetLayout(mode) {
var jqXHR;
jqXHR = $.ajax({
type : "get" ,
url : "../cgi/ajax/mtn/getHeaderLayoutVal.php" ,
data : {
preview : mode ,
screen : PAGEID
} ,
cache : false ,
dataType : 'json'
});
return jqXHR;
}
/********************************* 画像選択 *********************************/
/* 画像リストの読み込み
*
@param -
@return -
*/
function getImgList() {
var result = ajaxGetImgList();
var imgList;
var viewWidth;
var imgNums;
result.done(function(response) {
//console.debug(response);
//console.debug(response['SEQ']);
imgList = response['SEQ']['data' ];
viewWidth = response['SEQ']['width'];
//console.debug(viewWidth);
imgNums = response['SEQ']['nums'];
showPhotoList(imgList ,viewWidth ,imgNums);
EXT_LIST = response['SEQ']['ext'];
//console.debug(EXT_LIST);
});
result.fail(function(result, textStatus, errorThrown) {
console.log("error for ajaxGetImgList:" + result.status + ' ' + textStatus);
});
result.always(function() {
//console.debug(ret['SEQ']);
});
}
/* 画像リストの読み込み(ajax通信)
*
@param -
@return -
*/
function ajaxGetImgList() {
var branchNo = $('#branchNo').val();
var jqXHR;
jqXHR = $.ajax({
type : "get" ,
url : "../cgi/ajax/mtn/getImgList.php" ,
data : {
branchNo : branchNo
} ,
cache : false ,
dataType : 'json'
});
return jqXHR;
}
/* 画像リスト表示
*
@param 画像リストのタグ文字列
@param 表示する領域の幅
@return -
*/
function showPhotoList(imgList ,viewWidth ,imgNums) {
var target = $('<div id="imgListI"></div>');
$('div#imgListI').width(viewWidth);
$('div#imgListI').html(imgList);
/***** 2017.10.30 左右の間隔が狭くなるため隙間を開ける *****/
if(imgNums >= 2) {
$('div.imgitem').css('margin-right' ,'10px');
$('div.imgitem').css('padding-right' ,'10px');
}
var allWidth;
target.ready(function() {
console.log(target.width()); // 表示後の実際の高さ
$("div.imgitem").each(function(i) {
console.log(i + ': ' + $(this).width());
console.log(i + ': ' + $(this).height());
});
});
}
/********************************* 編集ダイアログ *********************************/
/* パーツオブジェクトのD&D時の動作の定義
*
@param -
@return -
*/
function setSortable() {
$('.partslist').sortable({
connectWith: ['.partslist' ,'.trashcanm'] ,
/***** drop時の動作 *****/
receive : function(event, ui) {
var newParts = $(this).find('.newparts');
var newID;
var str;
/*** ID付与 ***/
newID = 'partsIdx-N' + CURR_NEW_PARTS;
$(newParts).attr('id' ,newID);
str = $(newParts).html();
/*** オブジェクト追加 ***/
newHTML = addNewDiv(CURR_NEW_PARTS ,str ,'SORTABLE' ,PAGEID);
$(newParts).html(newHTML);
$('#sw' + 'N' + CURR_NEW_PARTS).toggleSwitch();
/*** style削除 ***/
$(newParts).css('width' ,'');
$(newParts).css('height' ,'');
/*** class消去/追加 ***/
$(newParts).removeClass('ui-draggable');
$(newParts).removeClass('ui-draggable-handle');
$(newParts).addClass('ui-sortable-handle');
$(newParts).addClass('clearFix');
$(newParts).removeClass('newparts');
CURR_NEW_PARTS++;
}
});
$('.partsList').disableSelection();
/***** 新規追加 *****/
$('#newPartsList div').draggable({ //'#newPartsList div'
connectToSortable : '.partslist' ,
helper : 'clone' ,
revert : 'invalid'
});
$('#newPartsList div').disableSelection();
/***** ゴミ箱 *****/
$('.trashCan').sortable({
// connectWith: '.partsList' ,
/***** drop時の動作 *****/
receive : function(event, ui) {
var id = ui.item.attr("id");
//console.debug(id);
$("#" + id).css('display' ,'none');
}
});
$('.trashCan').disableSelection();
}
/* 新規オブジェクトのD&D時の動作
*
@param 新規パーツの識別の初期値
@param 表示文字
@param 新規パーツか否か
@param 配置場所
@return -
*/
function addNewDiv(newPartsNoSeed ,str ,mode ,place) {
/*
<div id="partsIdx-6" class="clearFix parts1"><input type="hidden" id="partsNo6" value="1"><div class="pageItem pageShow"><input type="checkbox" id="TOP" name="TOP" value="U" onchange="enableWriteNoticeDisp();" class="dispSW"></div><div class="pageItem pageName">上の絵A</div><div class="pageItem pageEdit"><input type="button" value=" " class="toEdit" onclick="editPageLayout('TOP')"></div></div>
*/
var newPartsNo = 'N' + newPartsNoSeed
var ret;
var cbID = 'sw' + newPartsNo;
var partsClass = '';
var editBtn = '';
var titleStr = '';
var checkboxTag = '';
var setMainParts = false;
var partsList = $('#partsNoList').val();
if(str == '文字列') {
partsClass = 'STR';
}
if(str == '画像') {
partsClass = 'IMG';
}
if(str == 'ヘッダ') {
partsClass = 'HEADER';
}
if(mode == 'SORTABLE') {
titleStr = '(新規' + str + ')';
} else {
titleStr = str;
}
if(setMainParts) {
partsList = partsList + ':' + newPartsNo;
$('#partsNoList').val(partsList);
}
//console.debug('new parts No:' + newPartsNo);
addHidden(PAGEID ,newPartsNo ,partsClass ,'#partsEditTab');
var onClickParam = '\'' + partsClass + '\'' + ',' + '\'' + newPartsNo + '\'';
editBtn = '<button class="btn btn-info" onclick="editParts(' + onClickParam + ')">編集</button>';
delBtn = '<button class="btn btn-danger" onclick="delParts(' + onClickParam + ')" >削除</button>';
if(mode == 'SORTABLE') {
checkboxTag = '<input type="checkbox" id="' + cbID + '" name="' + cbID + '" value="U" class="dispSW">';
} else {
checkboxTag = '<input type="checkbox" id="' + cbID + '" name="' + cbID + '" value="U" checked style="display:none">';
}
ret = '<div class="pageitem pageShow">' + checkboxTag + '</div>' +
'<div class="pageitem partsName" id="title' + newPartsNo + '">' + titleStr + '</div>' +
'<div class="btn-group-sm partsButton">' +
' <div class="partsdel">' + delBtn + '</div>' +
' <div class="partsedit">' + editBtn + '</div>' +
'</div>';
return ret;
}
/* 新規オブジェクトのパラメータの追加
*
@param ページ識別
@param 新規パーツNo
@param パーツクラス
@param 追加先のオブジェクトのID
@return -
*/
function addHidden(pageID ,newPartsNo ,partsClass ,appendID) {
var paramPrefix = 'param' + newPartsNo;
addHiddenMain(paramPrefix +'partsClass' ,partsClass ,appendID);
addHiddenMain(paramPrefix +'pageID' ,pageID ,appendID);
addHiddenMain(paramPrefix +'screenBkImgNo' ,'' ,appendID);
addHiddenMain(paramPrefix +'screenBkColor' ,'' ,appendID);
addHiddenMain(paramPrefix +'title' ,'' ,appendID);
addHiddenMain(paramPrefix +'titleBkImgNo' ,'' ,appendID);
addHiddenMain(paramPrefix +'titleBkColor' ,'' ,appendID);
addHiddenMain(paramPrefix +'titleForeColor' ,'' ,appendID);
addHiddenMain(paramPrefix +'titleUseBk' ,'' ,appendID);
addHiddenMain(paramPrefix +'width' ,'' ,appendID);
addHiddenMain(paramPrefix +'imgNo' ,'' ,appendID);
addHiddenMain(paramPrefix +'mainBkImgNo' ,'' ,appendID);
addHiddenMain(paramPrefix +'mainBkColor' ,'' ,appendID);
addHiddenMain(paramPrefix +'mainForeColor' ,'' ,appendID);
addHiddenMain(paramPrefix +'mainUseBk' ,'' ,appendID);
addHiddenMain(paramPrefix +'sData' ,'' ,appendID);
addHiddenMain(paramPrefix +'iData' ,'' ,appendID);
addHiddenMain(paramPrefix +'URL' ,'' ,appendID);
addHiddenMain(paramPrefix +'linkTarget' ,'' ,appendID);
addHiddenMain(paramPrefix +'imgClick' ,'' ,appendID);
addHiddenMain(paramPrefix +'imgClickAct' ,'' ,appendID);
}
/* 既存オブジェクトのパラメータの追加
*
@param ページ識別
@param 新規パーツNo
@param パーツクラス
@param 値リスト
@param 追加先のオブジェクトのID
@return -
*/
function addHiddenVal(pageID ,newPartsNo ,partsClass ,vals ,appendID) {
var paramPrefix = 'param' + newPartsNo;
addHiddenMain(paramPrefix + 'partsClass' ,partsClass ,appendID);
addHiddenMain(paramPrefix + 'pageID' ,pageID ,appendID);
addHiddenMain(paramPrefix + 'screenBkImgNo' ,vals['screenBkImgNo'] ,appendID);
addHiddenMain(paramPrefix + 'screenBkColor' ,vals['screenBkColor'] ,appendID);
addHiddenMain(paramPrefix + 'title' ,vals['title' ] ,appendID);
addHiddenMain(paramPrefix + 'titleBkImgNo' ,vals['titleBkImgNo' ] ,appendID);
addHiddenMain(paramPrefix + 'titleBkColor' ,vals['titleBkColor' ] ,appendID);
addHiddenMain(paramPrefix + 'titleForeColor' ,vals['titleForeColor'] ,appendID);
addHiddenMain(paramPrefix + 'titleUseBk' ,vals['titleUseBk' ] ,appendID);
addHiddenMain(paramPrefix + 'width' ,vals['width'] ,appendID);
addHiddenMain(paramPrefix + 'imgNo' ,vals['imgNo'] ,appendID);
addHiddenMain(paramPrefix + 'mainBkImgNo' ,vals['mainBkImgNo' ] ,appendID);
addHiddenMain(paramPrefix + 'mainBkColor' ,vals['mainBkColor' ] ,appendID);
addHiddenMain(paramPrefix + 'mainForeColor' ,vals['mainForeColor'] ,appendID);
addHiddenMain(paramPrefix + 'mainUseBk' ,vals['mainUseBk' ] ,appendID);
console.debug('sData:' + vals['sData']);
addHiddenMain(paramPrefix + 'sData' ,vals['sData'] ,appendID);
addHiddenMain(paramPrefix + 'iData' ,vals['iData'] ,appendID);
addHiddenMain(paramPrefix + 'URL' ,vals['URL' ] ,appendID);
addHiddenMain(paramPrefix + 'linkTarget' ,vals['linkTarget'] ,appendID);
addHiddenMain(paramPrefix + 'imgClick' ,vals['imgClick' ] ,appendID);
addHiddenMain(paramPrefix + 'imgClickAct' ,vals['imgClickAct'] ,appendID);
}
/* オブジェクトのパラメータの追加の本体
*
@param 新規パーツID
@param 値
@param 追加先のオブジェクトのID
@return -
*/
function addHiddenMain(id ,value ,addID) {
$('<input>').attr({
type : 'hidden' ,
id : id ,
value : value
}).appendTo(addID);
}
/********************************* パーツ削除 *********************************/
/* パーツ削除
*
@param パーツクラス
@param パーツNo
@return -
*/
function delParts(partsClass ,partsNo) {
jConfirm('削除しますか?' ,'パーツ削除' ,function(r){
if(r) {
$('div#trashcanm').append(partsNo + ',');
$('#partsIdx-' + partsNo).remove();
}
});
}
/********************************* 画像選択 *********************************/
/* 画像選択ダイアログの表示
*
* この形式のダイアログは使用しない
*
@param -
@return -
*/
function seleImg(partsSele ,partsPos ,dispImgNo) {
var imgValID = partsSele + dispImgNo;
var imgNo = $("#" + imgValID).val();
$('#seleImg').parsley().reset();
IMG_PARTS_SELE = partsSele;
IMG_PARTS_IMG_DISP = partsPos;
IMG_PARTS_IMG_NO = dispImgNo;
/* 画像ファイル名 */
$('#imgTypeCaution').removeClass('has-error'); //エラーメッセージ非表示
$("#strImgFile").html('');
/* 画像タイトル */
$('#newTitle').removeClass('has-error'); //エラーメッセージ非表示
$("#strTitle").html('');
$("#strSeleImg").html('');
/***** 現在選択されている画像 *****/
$("input[name='seleImg']").prop("checked", false);
$("#seleImg" + imgNo).prop("checked", true);
$("#seleNewImg").hide(); //selectNewImgArea
$('#imgSelectorDlg').modal('show');
}
/* 新画像追加領域の表示
*
@param -
@return -
*/
function showSelectNewImg() {
$('#seleNewImg').parsley().reset();
$("#seleNewImg").show(); //selectNewImgArea
}
/* 新画像アップロード
*
@param -
@return -
*/
function execUploadNewImg() {
//アップロード本体
console.debug('uploadNewImg');
//var anyErr = false;
//var imgFile = $("#newFile")[0].files[0];
//var strNewTitle = $('#newTitle').val();
// /* 画像ファイル名 */
// if(imgFile == null) {
// $('#imgTypeCaution').addClass('has-error'); //エラーメッセージ表示
// $("#strImgFile").html('ファイルを選択してください。');
// anyErr = true;
// }
// /* 画像タイトル */
// if(strNewTitle.length <= 0) {
// $('#newTitle').addClass('has-error'); //エラーメッセージ表示
// $("#strTitle").html('この項目は必須です。');
// anyErr = true;
// }
//
// if(!anyErr) {
uploadNewImgMain();
// }
}
/* 画像選択終了
*
@param -
@return -
*/
function setSelected() {
//選択された画像の取り出し
var seleImgNo = $("input[name='seleImg']:checked").val();
var branchNo = $('#branchNo').val();
//var titleStr = $('#newTitle').val();
if(seleImgNo != undefined) {
var partsNo = $("#editPartsNo").val();
var ext = EXT_LIST[seleImgNo];
var imgTag = '<img src="../img/' + branchNo + '/img/' + seleImgNo + '.' + ext + '" width="150">';
var imgDispID = "#" + IMG_PARTS_SELE + IMG_PARTS_IMG_DISP;
var imgParam = "#" + IMG_PARTS_SELE + IMG_PARTS_IMG_NO;
$("#param" + partsNo + imgParam).val(seleImgNo);
console.debug(imgDispID);
/*** 選択されている画像の表示と画像Noの保持 ***/
$(imgDispID).html(imgTag);
$(imgParam).val(seleImgNo);
$('#imgSelectorDlg').modal('hide');
}
}
/***********************************************************************************************************************************************************/
/***********************************************************************************************************************************************************/
/***********************************************************************************************************************************************************/
/***********************************************************************************************************************************************************/
/***********************************************************************************************************************************************************/
/***********************************************************************************************************************************************************/
/***********************************************************************************************************************************************************/
/***********************************************************************************************************************************************************/
/***********************************************************************************************************************************************************/
/***********************************************************************************************************************************************************/
/***********************************************************************************************************************************************************/
/* 新画像アップロード
*
@param -
@return -
*/
function uploadNewImgMain() {
var fd = new FormData();
var result
if($("#newFile").val() !== '') {
fd.append("newFile" ,$("#newFile").prop("files")[0]);
fd.append("branchNo" ,$('#branchNo').val());
fd.append("title" ,$('#newTitle').val());
console.debug('file upload beg');
result = ajaxUploadNewImg(fd);
console.debug('file upload end');
result.done(function(response) {
//console.debug(response);
getImgList(); //画像リスト再表示
});
result.fail(function(result, textStatus, errorThrown) {
console.log("error for ajaxUploadNewImg:" + result.status + ' ' + textStatus);
});
result.always(function() {
});
}
}
/* 新画像アップロードの本体(ajax通信)
*
@param データセット
@return -
*/
function ajaxUploadNewImg(fd) {
var jqXHR;
jqXHR = $.ajax({
type : "post" ,
url : "../cgi/ajax/mtn/uploadImgImg.php" ,
dataType : "text",
data : fd ,
processData : false ,
contentType : false ,
cache : false
});
return jqXHR;
}
/********************************* スケルトン→テンプレートファイル出力 *********************************/
/* テンプレートファイル出力
*
@param 対象デバイス
@param プレビューモード
@return -
*/
function bldTemplateFile(device ,previewMode) {
var result = ajaxBldTemplateFile(device ,previewMode);
result.done(function(response) {
console.debug(response);
//一時削除 bldHTMLMain(device ,'index' ,1 ,previewMode);
});
result.fail(function(result, textStatus, errorThrown) {
console.log("error for ajaxBldTemplate:" + result.status + ' ' + textStatus);
});
result.always(function() {
});
}
/* テンプレートファイル出力(ajax通信)
*
@param 対象デバイス
@param プレビューモード
@return -
*/
function ajaxBldTemplateFile(device ,previewMode) {
var jqXHR;
jqXHR = $.ajax({
type : "post" ,
url : "../cgi/ajax/mtn/bldTemplate.php" ,
data : {
mode : 'NOT_PROFILE' ,
devID : device ,
preview : previewMode
} ,
cache : false
});
return jqXHR;
}
/* 画像表示
*
* テスト用
*
@param -
@return -
*/
function enableWriteNoticeDisp() {
}
/********************
本ファイル出力
********************/
//function bldHTMLMain(device ,fileID ,readProf ,previewMode) {
//
//var result = ajaxBldHTML(device ,fileID ,readProf ,previewMode);
//
// result.done(function(response) {
// console.debug(response);
// });
//
// result.fail(function(result, textStatus, errorThrown) {
// console.log("error for ajaxBldHTML:" + result.status + ' ' + textStatus);
// });
//
// result.always(function() {
// });
//}
/********************
HTMLファイル出力(ajax)
********************/
//function ajaxBldHTML(device ,fileID ,readProf ,previewMode) {
//
//var jqXHR;
//
// jqXHR = $.ajax({
// type : "post" ,
// url : "../cgi/ajax/mtn/bldHTML.php" ,
// data : {
// mode : 'NOT_PROFILE' ,
// updID : fileID ,
// devID : device ,
// readProf : readProf ,
// preview : previewMode
// } ,
//
// cache : false
// });
//
// return jqXHR;
//}
/*********************************************************************************************************************/
/*********************************************************************************************************************/
/*********************************************************************************************************************/
/*********************************************************************************************************************/
/*********************************************************************************************************************/
/* プレビュー表示ダイアログ
*
* 現在非使用
*
@param -
@return -
*/
function setPreviewScreenDialog() {
$("div#previewDlg").dialog({
autoOpen : true , //true false
modal : false ,
width : NARROW_WIDTH ,
dialogClass : 'maxHeightDlg' ,
resizable : true ,
position : {
of : 'div#mtnOut' ,
at : 'right top' ,
my : 'right top'
} ,
buttons : [
{
text : "戻る" ,
class : 'previewBtn' ,
click : function() {
$('#previewMain')[0].contentWindow.history.back();
}
} ,
{
text : "最狭化" ,
class : 'toNarrow previewBtn' ,
click : function() {
$(this).dialog( {
width : NARROW_WIDTH ,
position : {
of : 'div#mtnOut' ,
at : 'right top' ,
my : 'right top'
}
} );
DLG_OUTER_OBJ.css('top' ,0);
dlgAdjustHeight(1);
}
} ,
{
text : "最小化" ,
class : 'toMinimum previewBtn' ,
click : function() {
$(this).dialog( {
width : NARROW_WIDTH ,
position : {
of : 'div#mtnOut' ,
at : 'right top' ,
my : 'right top'
}
} );
DLG_OBJ.css('min-height' ,'initial');
DLG_OUTER_OBJ.css('top' ,0);
var newHeight = dlgAdjustHeight(DLG_STS);
if(newHeight <= 0) {
/***** 最小化の時 *****/
DLG_STS = 1;
$(".toNarrow").prop('disabled' ,true); //最狭化無効
$(".toNarrow").css('color' ,"#aaa");
$(".toMinimum").html("伸長");
} else {
/***** 最小化以外のとき *****/
DLG_STS = 0;
$(".toNarrow").prop('disabled' ,false); //最狭化有効
$(".toNarrow").css('color' ,DLG_BTN_COLOR);
$(".toMinimum").html("最小化");
}
}
}
] ,
open : function(){
$('.ui-dialog-titlebar-close').hide();
adjustDlgInit();
setPreviewFile();
DLG_STS = 0;
dlgAdjustHeight(1);
}
});
}
/* プレビュー表示ダイアログの初期化
*
* 現在非使用
*
@param -
@return -
*/
function adjustDlgInit() {
DLG_OBJ = $("div#previewDlg");
DLG_OUTER_OBJ = $(".maxHeightDlg"); //DLG_OBJ.parent();
DLG_BTN_COLOR = $(".ui-button").css("color");
/***** 幅の調整 *****/
/* paddingをなくす */
DLG_OBJ.css('padding' ,'0px');
DLG_OBJ.css('margin' ,'0px');
DLG_OBJ.css('min-height' ,'initial');
DLG_OBJ.css('overflow' ,'hidden');
$(".previewBtn").css("font-size" ,"14px");
$(".ui-dialog-buttonpane").css("padding" ,"0px");
$(".ui-dialog-buttonpane").css("padding-bottom" ,"5px");
}
/* プレビュー表示ダイアログの高さの調整
*
* 現在非使用
*
@param -
@return -
*/
function dlgAdjustHeight(mode) {
var height; //表示する高さ
var titleBarH; //paddingとmarginを含んだタイトルバーの高さ
var footerH; //ボタン領域の高さ
$("div#previewDlg").css('top' ,0);
if(mode == 0) {
/***** 最小化の時 *****/
height = 0;
} else {
height = $("html").height(); /* windowの高さ */
titleBarH = 0; //$('div#previewDlg > .ui-dialog-titlebar' ).outerHeight(true);
footerH = 0; //$('div#previewDlg > .ui-dialog-buttonpane').outerHeight(true);
height = height - titleBarH - footerH - 115;
console.debug("titleBarH:" + titleBarH);
console.debug("footerH:" + footerH);
console.debug("height:" + height);
}
$("div#previewDlg").css('height' ,height);
$("iframe#previewMain").css('height' ,height);
return height;
}
/* プレビューファイルの表示
*
@param -
@return -
*/
function setPreviewFile() {
var date = new Date();
var time = date.getTime();
var yy = date.getYear();
var mm = date.getMonth();
var dd = date.getDate();
var hh = date.getHours();
var nn = date.getMinutes();
var ss = date.getSeconds();
var m = 'd' + yy + mm + dd + hh + nn + ss;
var outFile = previewFile + '?m=' + m;
MMAREA.contentDocument.location.replace(outFile);
}
/* プレビューファイルの再表示
*
@param -
@return -
*/
function reshowCurrFile() {
var date = new Date();
var time = date.getTime();
var yy = date.getYear();
var mm = date.getMonth();
var dd = date.getDate();
var hh = date.getHours();
var nn = date.getMinutes();
var ss = date.getSeconds();
var m = 'd' + yy + mm + dd + hh + nn + ss;
var outFile = outputFile + '?m=' + m;
MMAREA.contentDocument.location.replace(outFile);
}
/***** 2017.10.31 プレビュー領域のファイルの再表示 *****/
/* プレビューファイルの再表示
*
@param プレビューモード
@return -
*/
function reloadCurrFile(mode) {
var date = new Date();
var time = date.getTime();
var yy = date.getYear();
var mm = date.getMonth();
var dd = date.getDate();
var hh = date.getHours();
var nn = date.getMinutes();
var ss = date.getSeconds();
var m = 'd' + yy + mm + dd + hh + nn + ss;
var iframedoc = $('#mmArea')[0].contentWindow.document;
var hrefPrev = iframedoc.location.href;
var fileName = getFileName(hrefPrev ,mode);
var outFile = fileName + '?m=' + m;
console.debug(outFile);
MMAREA.contentDocument.location.replace(outFile);
}
/* プレビューされているファイル名の取得
*
@param 現在のファイル名
@param プレビューモード
@return -
*/
function getFileName(hrefOrg ,mode) {
var strA;
var strNoQuery;
var splitSlush;
var numSlush;
var branchName;
var fileName;
var fSplit;
var ret;
strA = hrefOrg.split('?');
//?で分離 なければ全体
if(strA.length >= 2) {
strNoQuery = strA[0];
} else {
strNoQuery = hrefOrg;
}
splitSlush = hrefOrg.split('/');
numSlush = splitSlush.length;
branchName = splitSlush[numSlush-2];
fileName = splitSlush[numSlush-1];
//プレビューモードで現行ファイルがプレビューでなければファイル名を変更
if(mode == 'PREVIEW') {
if(fileName.indexOf('PREVIEW') <= -1) {
fSplit = fileName.split('.');
fileName = fSplit[0] + mode + '.' + fSplit[1];
}
}
ret = '../' + branchName + '/' + fileName;
return ret;
}
|
//http://stackoverflow.com/questions/5643767/jquery-ui-autocomplete-width-not-set-correctly
jQuery.ui.autocomplete.prototype._resizeMenu = function () {
var ul = this.menu.element;
ul.outerWidth(this.element.outerWidth());
}
$(document).ready(function() {
var who = [
'Firefighter',
'Web Developer',
'Programmer',
'Astronaut'
],
country = [
'United States',
'UK',
'Poland',
'Germany',
'Australia'
],
hobby = [
'play football',
'read books',
'play video games'
];
function updateWidth($field) {
var val = $field.val();
$field.width((val.length * 20 + 10) + 'px');
}
function addInputEvents($field) {
$field.on('input',function() {
var $inpt = $(this);
updateWidth($inpt);
}).on('autocompletechange',function() {
var $inpt = $(this);
updateWidth($inpt);
}).on('autocompleteclose',function() {
var $inpt = $(this);
updateWidth($inpt);
});
}
var $who = $( "#who" ),
$country = $( "#country" ),
$hobby = $( "#hobby" );
$who.autocomplete({
source: who
});
addInputEvents($who);
$country.autocomplete({
source: country
});
addInputEvents($country);
$hobby.autocomplete({
source: hobby
});
addInputEvents($hobby);
}); |
const sveltePreprocess = require('svelte-preprocess');
const autoprefixer = require('autoprefixer');
const production = !process.env.ROLLUP_WATCH;
module.exports = {
preprocess: sveltePreprocess({
sourceMap: !production,
scss: {
prependData: `@import "src/assets/scss/variables.scss";`
},
postcss: {
plugins: [autoprefixer()]
}
}),
compilerOptions: {
// enable run-time checks when not in production
dev: !production
}
}; |
//"TaskId": "T_PRYCTSGSALFQY_996"
|
exports.validateBookingInfo = function(req, res, next) {
var body = req.body;
if(body.start_time > body.end_time){
return next(new Error("Start time should greater than end date."))
}
return next();
};
|
import React from 'react';
import ReactDOM from 'react-dom';
// redux
import {Provider} from 'react-redux';
import store from "./store"
// components
import App from './components/App/container';
// styles
import './style.css';
import 'bootstrap/dist/css/bootstrap.min.css';
// axios
import axios from 'axios';
axios.defaults.withCredentials = true;
axios.defaults.baseURL = 'http://rem-rest-api.herokuapp.com/api';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
|
const intersection = require('lodash/intersection')
const isNonEmptyString = require('predicates/isNonEmptyString')
const { classes } = require('typestyle')
const mergeClasses = (baseStyle = {}, ...args) => args.reduce((before, style = {}) => {
return {
...before,
...style,
...intersection(Object.keys(before), Object.keys(style))
.reduce((merged, key) => ({
...merged,
[key]: classes(before[key], style[key])
}), {})
}
}, baseStyle)
const bgMixin = background => ({ background })
const colorMixin = color => ({ color })
const Selector = input => isNonEmptyString(input)
? '.' + input.replace(' ', '.')
: void 0
module.exports = {
mergeClasses,
bgMixin,
colorMixin,
Selector
} |
import styled from "styled-components";
import { below } from "../utilities/mediaQueries";
export const StyledTrack = styled.div`
border: transparent;
background: #050607b7;
box-shadow: 1px 1px 20px #14181e;
min-width: 36vw;
max-width: 36vw;
height: 14vh;
border-radius: 5px;
margin: 3vh auto;
display: flex;
justify-content: space-between;
font-weight: bold;
padding: 10px;
& img {
width: 10vw;
width: 10vw;
height: 14vh;
border: transparent;
box-shadow: 1px 1px 20px #14181e;
border-radius: 3px;
}
& .fav-icon {
width: 5vw;
height: 5vh;
border: transparent;
}
${below.large`
min-width: 50vw;
max-width: 50vw;
`}
`;
export const StyledAlbum = styled(StyledTrack)`
border: transparent;
background: #050607b7;
box-shadow: 1px 1px 20px #14181e;
width: 36vw;
height: 14vh;
border-radius: 5px;
margin: 3vh auto;
display: flex;
justify-content: space-between;
font-weight: bold;
padding: 10px;
& img {
width: 10vw;
height: 14vh;
border: transparent;
box-shadow: 1px 1px 20px #14181e;
border-radius: 3px;
}
& .fav-icon {
width: 5vw;
height: 5vh;
border: transparent;
}
&span {
}
`;
|
angular.module('boosted')
.directive('footerView', function() {
return {
restrict: 'E',
templateUrl: 'public/app/directives/footer/footer.html',
controller: function($scope, service){
$scope.addEmail = function(email){
service.addemail(email);
}
},
link: function(scope, elem, attrs) {
}
}
});
|
/**
* Created by zhuo on 2017/9/17.
*/
class Enemy extends LiveObject {
constructor(name, mh, pp, mp, pd, md, speed, exp,desc) {
super(name, mh, pp, mp, pd, md, speed);
this.exp = exp || 1;
this.isLiving = true;
this.items = [];//携带道具
this.desc = desc || '管理员忘记描述了';
}
effectFromInFight(item, src) {
if (item.effective) {
item.effective(this, src);
}
this.checkDeath();
}
effectFromSkill(skill, src) {
if (skill.effective) {
skill.effective(this, src);
}
this.checkDeath();
}
checkDeath() {
if (this.health < 1) {
this.isLiving = false;
}
}
fuckPlayer() {//AI逻辑
var skill = Skills.normalPysicAttack;
player.effectFromSkill(skill);
fightState.addLog(this.name + '对' + player.name + '释放了:' + skill.name);
}
}
var Monsters = {
king: new Enemy('开挂哥布林', 20, 9, 3, 3, 3, 1, 10,"不是哥布林,是开挂的哥布林"),
king2: new Enemy('会念诗的史莱姆', 20, 3, 9, 3, 3, 14, 10,"不是史莱姆,是会念诗的史莱姆"),
poet: new Enemy('吟游诗人的灵魂', 50, 3, 12, 8, 5, 18, 10,'被诅咒囚禁的亡者灵魂'),
priest: new Enemy('圣堂牧师的灵魂', 50, 12, 3, 5, 8, 18, 10,'被诅咒囚禁的亡者灵魂'),
swimmer: new Enemy('穿泳衣的灵魂', 70, 9, 5, 0, 6, 18, 10,'被诅咒囚禁的亡者灵魂'),
peopleFishing: new Enemy('钓鱼的人', 70, 5, 9, 6, 10, 18, 10,'只是钓鱼的人而已'),
king2: new Enemy('会念诗的史莱姆', 20, 3, 9, 3, 3, 14, 10,"不是史莱姆,是会念诗的史莱姆"),
goblin: new Enemy('哥布林', 10, 3, 3, 3, 3, 2, 2,"普通的哥布林"),
slime: new Enemy('史莱姆', 10, 3, 3, 3, 3, 2, 2,"普通的史莱姆"),
bossOfOne: new Enemy('卡在墙里的死神', 99, 12, 12, 5, 5, 4, 100,"不是死神,是卡在墙里的死神"),
TheCain: new Enemy('该隐', 9999, 0, 0, 0, 0, 0, 100,'"永远与须臾的罪人"'),
}
//第一层
Monsters.king.fuckPlayer = function () {
var skill = Skills.normalPysicAttack;
// player.effectFromSkill(skill);
fightState.addLog(this.name + '对' + player.name + '释放了:' + skill.name);
skill.effective(player, this);
}
Monsters.king2.fuckPlayer = function () {
var skill = Skills.normalMagicAttack;
fightState.addLog(this.name + '对' + player.name + '释放了:' + skill.name);
skill.effective(player, this);
}
Monsters.goblin.fuckPlayer = function () {
var skill = Skills.normalPysicAttack;
fightState.addLog(this.name + '释放了:' + skill.name);
skill.effective(player, this);
}
Monsters.slime.fuckPlayer = function () {
var skill = Skills.normalMagicAttack;
fightState.addLog(this.name + '释放了:' + skill.name);
skill.effective(player, this);
}
Monsters.bossOfOne.fuckPlayer = function () {
var skill = Skills.frameDeathChop;
fightState.addLog(this.name + '释放了:' + skill.name);
skill.effective(player, this);
}
Monsters.bossOfOne.checkDeath = function () {
Enemy.prototype.checkDeath.call(this);
if (!this.isLiving) {
var theBossTile = Maps.plain1.obj_tile_map[20][21];
theBossTile.isStone = false;
theBossTile.beInterestedCallback = function () {
myAlertDialog.reOpen('现在你可以通过这里',function () {
myAlertDialog.bDown();
});
};
Maps.mapInfo.plain1.bossKilledFlag = true;
//改变地图显示
Maps.plain1.map.putTile(null,20,21,Maps.plain1.layer_objs);
Maps.plain1.map.putTile(null,20,20,Maps.plain1.layer_objs);
}
}
Monsters.TheCain.fuckPlayer = function () {
fightState.addLog('审判者对伤害来源施加了审判');
var damageSuffered = this.maxHealth - this.health;
console.log('收到伤害: '+damageSuffered* 7);
player.damageFrom(0,0,damageSuffered * 7);
}
Monsters.TheCain.checkDeath = function () {
Enemy.prototype.checkDeath.call(this);
if (!this.isLiving) {
var theBossTile = Maps.floor3.obj_tile_map[20][22];
theBossTile.isStone = false;
theBossTile.beInterestedCallback = function () {
myAlertDialog.reOpen('现在你可以通过这里',function () {
myAlertDialog.bDown();
});
};
Maps.mapInfo.plain1.bossKilledFlag = true;
//改变地图显示
Maps.floor3.map.putTile(null,20,20,Maps.floor3.objLayer);
Maps.floor3.map.putTile(null,20,21,Maps.floor3.objLayer);
Maps.floor3.map.putTile(null,20,22,Maps.floor3.objLayer);
//摘除玩家装备
player.discardEquipment(Items.curseOfAbe);
player.discardItem(Items.curseOfAbe);
}
}
Monsters.poet.fuckPlayer = function () {
var skill = Skills.normalMagicAttack;
fightState.addLog(this.name + '释放了:' + skill.name);
skill.effective(player, this);
}
Monsters.priest.fuckPlayer = function () {
var skill = Skills.normalPysicAttack;
fightState.addLog(this.name + '释放了:' + skill.name);
skill.effective(player, this);
}
Monsters.swimmer.fuckPlayer = function () {
var skill = Skills.normalPysicAttack;
fightState.addLog(this.name + '释放了:' + skill.name);
skill.effective(player, this);
}
Monsters.peopleFishing.fuckPlayer = function () {
var skill = Skills.normalMagicAttack;
fightState.addLog(this.name + '释放了:' + skill.name);
skill.effective(player, this);
} |
class People {
constructor(name, email, phone) {
this.name = name;
this.email = email;
this.phone = phone;
};
toString() {
return `Name: ${this.name} | e-Mail: ${this.email} | Phone: ${this.phone}`;
};
}
class Client extends People {
constructor(id, name, email, phone) {
super(name, email, phone);
this.id = id;
};
toString() {
return `id: ${this.id} | ${super.toString()}`;
};
}
let client = new Client(1, "João", "joaorca@gmail.com", "21999999999");
console.log(client.toString()); |
import React from 'react';
import { storiesOf } from '@storybook/react';
import { select } from '@storybook/addon-knobs';
import List from './List';
storiesOf('List', module).add('demo', () => (
<List
listType="liveOrder"
list={[
{
id: 1,
name: 'INVO/BTC',
lastPrice: 0.00022,
change24Perc: 2.56,
vol24: 2567.21,
logoUrl: 'https://via.placeholder.com/300.png',
},
{
id: 2,
name: 'ETH/BTC',
lastPrice: 0.00012,
change24Perc: -1.56,
vol24: 1567.21,
logoUrl: 'https://via.placeholder.com/300.png',
},
]}
actions={['remove']}
columns={['price', 'amount', 'filledAmount', 'type', 'side', 'favourites']}
columnNames={[
'price',
'amount',
'filledAmount',
'type',
'side',
'favourites',
]}
columnPostfixes={['', '', '', '%', '', '']}
colors={[
{},
{
attribute: 'change24Perc',
operator: '>',
value: '0',
True: '#47af00',
False: '#ff4e6d',
},
{},
{},
{},
{},
]}
theme={select('theme', ['light', 'dark', 'darkCmc'], 'dark')}
selectedItemId={1}
/>
));
|
/**
* http://www.geeksforgeeks.org/insertion-sort/
* Maintain a sorted portion of the array, and insert the remaining elements into the correct position
* in the sorted portion.
*/
const insertionSort = arr => {
for (let i = 1; i < arr.length; i++) {
let cur = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > cur) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = cur;
}
return arr;
};
module.exports = insertionSort;
|
//requires
var express = require('express');
var app = express();
var calc = require('./modules/calculate.js');
var path = require('path');
var bodyParser = require('body-parser');
//globals
var port = 5000;
//uses
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:true}));
//route for calculator
app.use('/calculator', calc);
//spin up server
app.listen(port, function(){
console.log('listening on port 5000');
});
//base url
app.get('/', function(req,res){
console.log('base url hit');
//send back index.html as a response
res.sendFile(path.resolve('public/views/index.html'));
});
// app.post( '/calculate', function( req, res ){
//
// res.send( 200 );
// });
|
var SearchSheetView = Backbone.View.extend({
initialize: function () {
_.bindAll(this, "render");
this.stack = [];
this.account = new AccountModel();
this.inbox = new TaskListModel();
this.areas = new AreaCollection();
this.tags = new TagCollection();
this.model = new TaskListModel();
this.searchText = "";
},
template: Handlebars.compile($("#search-sheet-template").html()),
render: function () {
// Render view.
$(this.el).html(this.template(this.model.toJSON()));
// Greate a task group view.
var tasks = new TaskGroupView({
el: $("#tasks"),
model: this.model.get("tasks"),
showNewTask: false,
displayTaskListTitle: true
}).render();
return this;
},
}); |
/* global module:true, test:true, expect:true */
/* global ok:true, equal:true */
"use strict";
module("group a");
test("a basic test example", function () {
ok(true, "this test is fine");
});
test("a basic test example 2", function () {
ok(true, "this test is fine");
});
module("group b");
test("a basic test example 3", function () {
ok(true, "this test is fine");
});
test("a basic test example 4", function () {
ok(true, "this test is fine");
});
test("a test", function () {
expect(2);
function calc(x, operation) {
return operation(x);
}
var result = calc(2, function (x) {
ok(true, "calc() calls operation function");
return x * x;
});
equal(result, 4, "2 square equals 4");
//notEquals
//deepEquals
//notDeepEquals
//strictEquals
//notStrictEquals
//raises
}); |
const config = require('dotenv').config();
const { Client } = require('pg')
console.log(process.env.PGDATABASE)
const client = new Client({
user: process.env.PGUSER,
host: process.env.PGHOST,//'boat.colorado.edu',
database: process.env.PGDATABASE,//'vbd23',
password: process.env.PGPASSWORD,//'viirs2018',
port: 5432,
}
)
const connect = async () => {
await client.connect()
}
module.exports = {connect, client} |
var app = new Vue({
el: '#app',
data: {
name: "",
link: "",
question: "",
location: "",
radius: "",
fields: []
},
methods: {
saveForm: function () {
if (this.validateForm()) {
this.fields.push({
question: this.question,
location: this.location,
radius: this.radius
})
this.clearForm()
} else {
alert("fill out all fields")
}
},
clearForm: function () {
this.question = "";
this.location = "";
this.radius = "";
},
validateForm: function () {
if (this.location == "" && this.radius == "" && this.question == ""){
return false
} else {
return true
}
},
editField: function (e) {
console.log(e.target)
}
}
})
|
import React from 'react';
import todoStore from '../../stores/TodoStore';
import * as TodoActions from '../../actions/TodoActions';
import Tasks from './Tasks';
class Todo extends React.Component {
constructor() {
super();
this.getTodos = this.getTodos.bind(this);
this.state = {
todos: todoStore.getAll(),
input: '',
};
}
componentDidMount() {
todoStore.on('change', this.getTodos );
console.log(todoStore.listenerCount('change'));
}
componentWillUnmount() {
todoStore.removeListener('change', this.getTodos );
}
getTodos() {
this.setState({
todos: todoStore.getAll(),
});
}
handleChange(e) {
this.setState({input: e.target.value});
}
handleSubmit(e) {
e.preventDefault();
this.createTodo();
}
createTodo() {
const inputValue = this.state.input;
if (inputValue) {
TodoActions.createTodo(inputValue);
}
}
deleteTodo(e) {
TodoActions.deleteTodo(e.target.id)
}
reloadTodos() {
TodoActions.reloadTodos();
}
render() {
return (
<div className="container">
<div className="wrapper">
<div className="todos">
<h1>ToDo List</h1>
<form action="" onSubmit={this.handleSubmit.bind(this)}>
<input
type="text"
onChange={this.handleChange.bind(this)}
/>
</form>
<button onClick={this.createTodo.bind(this)}>Add</button>
<br/>
<button onClick={this.reloadTodos.bind(this)}>REOLAD</button>
<Tasks onClick={this.deleteTodo} data={this.state.todos} />
</div>
</div>
</div>
);
}
};
export default Todo;
|
var render="datalist";
var win="addWindow";
var wform="saveForm";
var qform="queryForm";
var path = $('#path').val();
/**
* 数据列表
* @type
*/
var tcolumn=[[
{field:'name',title:'名称',width:120,sortable:true,align:'center'},
{field:'type',title:'类型',width:120,sortable:true,align:'center',
formatter:function(val,rec){
if(rec.type==0)
return '<font color="green">菜单</font>';
else if(rec.type==1)
return '<font color="red">按钮</font>';
else
return '';
}
},
{field:'pId',title:'关系',width:120,sortable:true,align:'center',
formatter:function(val,rec){
if(rec.type==0){
if(rec.pId == 0){
return '<font color="red">父菜单</font>';
}else {
return '<font color="green">子菜单</font>';
}
}
}},
/*{field:'url',title:'路径',width:120,sortable:true,align:'center'},*/
{field:'addTime',title:'创建时间',width:120,sortable:true,align:'center'}
]];
/**
* 菜单栏
*/
var tbar=[{
id:'btnadd',
text:'新增',
iconCls:'icon-add',
handler:function(){
$('#comtr').hide();
resetForm(wform);
openDiv(win);
}
},'-',{
id:'btnedit',
text:'修改',
iconCls:'icon-edit',
handler:edit
},'-',{
id:'btnremove',
text:'删除',
iconCls:'icon-remove',
handler:deleteobj
}];
/**
* 加载初始化
*/
$(function(){
init();
});
/**
* 刷新列表
*/
function init(){
queryInit(path+'/menu_query.do?timestamp=' + new Date().getTime(),tcolumn,tbar,render);
$.post(path+'/menu_getParentMenus.do?timestamp=' + new Date().getTime(),function(data){
var obj = eval('('+data+')');
if(obj !=null){
var html='';
$("#pId").html('<option value="0">请选择</option>');
for(var i=0;i<obj.length;i++){
html+='<option value="'+obj[i].id+'">'+obj[i].name+'</option>';
}
$("#pId").append(html);
}
});
}
/**
* 查询
*/
function query(){
var queryName=$('#queryName').val();
$('#'+render).datagrid('reload', {"queryName":queryName});
}
/**
* 增加和修改操作
*/
function submitForm(){
if($('#'+wform).form('validate')){
var url="";
var id=$('#id').val();
if(id==''){
url=path+"/menu_save.do";
}else{
url=path+"/menu_update.do";
}
$('#'+wform).form('submit', {
url:url,
onSubmit: function(){
},
success:function(data){
if("success"==data){
$.messager.alert('提示',"更新数据成功!");
resetForm(wform);
closeDiv(win);
init();
}else if('hased'==data){
$.messager.alert('提示',"该菜单已经存在!");
}else{
$.messager.alert('提示',"更新数据失败!");
}
}
});
}
}
/**
* 获取详细信息
* @param {} url
*/
function queryObjectbyID(url){
$.ajax({
type:'POST',
url:url,
success:function(msg){
if(msg !=''){
var arry = eval("("+msg+")");
$('input[name="menus.id"]').val(arry.id);
$('select[name="menus.type"]').val(arry.type);
$('input[name="menus.name"]').val(arry.name);
$('input[name="menus.url"]').val(arry.url);
$('select[name="menus.pId"]').val(arry.pId);
$('input[name="menus.sort"]').val(arry.sort);
$('input[name="menus.addTime"]').val(arry.addTime);
openDiv(win);
}else{
$.messager.alert('提示','信息不存在!');
}
}
});
}
/**
* 修改
*/
function edit(){
resetForm(wform);
var rows = $('#'+render).datagrid('getSelections');
if(rows.length==0){
alert("请选择一条记录!");
return;
}
var queryUrl=path+'/menu_getbyid.do?id='+rows[0].id;
$('#'+render).datagrid('clearSelections');
queryObjectbyID(queryUrl);
}
/**
* 删除
*/
function deleteobj(){
$.messager.confirm('系统提示', '您确定要删除吗?', function(r) {
if (r) {
var rows = $('#'+render).datagrid('getSelections');
var ids="";
if(rows.length>0){
for(var i=0;i<rows.length;i+=1){
if(i==0){
ids=rows[i].id;
}else{
ids+="_"+rows[i].id;
}
}
$.post(path+"/menu_deletebyids.do",{"ids":ids},function(data){
if("success"==data){
$('#'+render).datagrid('clearSelections');
$.messager.alert('提示',"更新数据成功!");
init();
}
});
}
}
});
}
|
define(function(require, exports, module){
var G=require('../../c/js/globale');
var encode64=require('../../c/js/base64').encode64;
var md5=require('../../c/js/md5').md5;
var main = {
init:function(){
var self=this;
self.loginToken=$('#J-loginToken').val();
G._getLoginUser(self._event);
/*替换url,后面带上target*/
self.target=G._getUrlParam('target')|| '';
$('a.add-target').each(function(){
var url=$(this).attr('href')+'?target='+self.target;
$(this).attr('href',url);
});
},
_event:function(userMess){
var self=main;
var timer;
var mobileInput=$('#J-phonenumber');
var codeInput=$('#J-register-code');
/*当有了手机号码才可以下一步*/
// $('#J-phonenumber').html(userMess.mobile || '<a class="external" href="/login/register.do?target=/customer/customerMsg.html">还没有手机信息,请填写></a>');
// if(!userMess.mobile){
// $('#J-register-code-box a').attr('href','/login/register.do');
// $('#J-next').attr('href','/login/register.do');
// return;
// };
/*验证输入的是否是手机号码*/
// $('#J-next').unbind('click').bind('click',function(){
// if(!codeInput.val().length){
// alert('请输入验证码');
// return;
// }else{
// $.router.loadPage('#next-page')
// clearInterval(timer);
// $('#J-register-code-box a').html('获取验证码');
// }
// });
/*获取验证码*/
// $('#J-register-code-box a').unbind('click').bind('click',function(){
// var $this=$(this);
// var time=60;
// $.ajax({
// type:'get',
// cach:false,
// url:'/login/jsonGetVerifyCode.do',
// data:{
// mobile:mobileInput.text()
// },
// success:function(res){
// if(res.info.ok==true){
// $this.text('剩余'+time+'秒');
// clearInterval(timer);
// timer=setInterval(function(){
// if(time<=0){
// $this.text('重新获取');
// clearInterval(timer);
// }else{
// time--;
// $this.text('剩余'+time+'秒');
// }
// },1000);
// }else{
// alert(res.info.message);
// }
// },
// beforeSend:function(){
// $.showIndicator();
// },
// complete:function(){
// $.hideIndicator();
// },
// error:function(){
// // alert('error');
// }
// });
// });
/*确定修改*/
$('#J-confirm').unbind('click').bind('click',function(){
var oldPas=$('#J-old-pas').val();
var newPas=$('#J-new-pas').val();
if(!oldPas.length){
alert('请输入旧密码');
return;
};
if(!newPas.length){
alert('请输入新密码');
return;
};
// oldPas=md5(self.loginToken+md5(oldPas));
oldPas=encode64(self.loginToken+oldPas);
newPas=encode64(self.loginToken+newPas);
self._confirm({
customerId:userMess.customerId,
password:oldPas,
newPassword:newPas
});
});
},
_confirm:function(data) {
var self=this;
$.ajax({
type:'get',
cach:false,
url:'/login/changePwd.json',
data:data,
success:function(res){
var url="/index.html";
if(window.fancyLoginUser){
url=G._getUrlParam('target') || "/index.html";
}else{
url="/login.do"
};
if(res.info.ok==true){
location.href=url;
}else{
alert(res.info.message);
}
},
beforeSend:function(){
$.showIndicator();
},
complete:function(){
$.hideIndicator();
},
error:function(){
// alert('error');
}
});
}
};
main.init();
}); |
const core = require("@actions/core");
(async () => {
try {
console.log(process.cwd());
let file = core.getInput("file", { required: true });
let githubUsername = core.getInput("github-username", { required: true });
let parsedMapping = JSON.parse(file);
const slackId = parsedMapping[0][githubUsername]
? parsedMapping[0][githubUsername]
: githubUsername;
core.setOutput("slack_id", slackId);
} catch (error) {
core.setFailed(error.message);
throw error;
}
})();
|
export default async function ({ system, wait }) {
try {
const req = RetryRequest('/api/login/register', {
headers: {
'Content-Type': 'application/json'
}
});
const res = await req.post(JSON.stringify(this));
if (res.responseText === 'exist') {
system.throw('exist');
}
} catch (e) {
system.throw(e.responseText)
}
} |
export function checkHttpStatus(response) {
if (response.code >= 200 && response.code < 300) {
return response
} else {
//console.log(response);
var error = new Error(response.statusText)
error.response = response
throw error
}
}
export function parseJSON(response) {
return response.json()
}
export function b64MaskToInt(b64Mask) {
return Buffer.from(b64Mask, 'base64').readUIntBE(12, 4);
}
export function b64MaskToPrefixSize(b64Mask) {
var maskInt = b64MaskToInt(b64Mask);
var maskBinStr = maskInt.toString(2);
return maskBinStr.indexOf('0');
}
export function ipportFormat(ipport) {
var ipportStr = ipport.IP;
if (ipport.Port != null) {
ipportStr += ":"+ipport.Port;
}
if (ipport.Protocol != null) {
ipportStr += "/"+ipport.Protocol;
}
return ipportStr;
}
export function ipportsFormat(ipports) {
if (ipports == null) {
return "";
}
var ipportsStr = [];
for (var i=0; i<ipports.length; i++) {
//console.log(this);
ipportsStr.push(ipportFormat(ipports[i]));
};
return ipportsStr.join(", ");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.