text
stringlengths
7
3.69M
var i1 = 4; var i2 = 11; var i3 = "cAda"; // var i4 = "AbrAcadAbRa"; var i4 = "AbrAcadAbRaTaacAAderTdAca"; var mWords = 0; var cWord = ""; for(var i = 0; i < i4.length - i1; i++){ cWord = i4.substr(i, i1); //console.log(cWord); //console.log(cWord.replace(/a/g,'')); for(var j=0; j < cWord.length; j++){ //console.log(i3.indexOf(cWord.substr(j, 1))); if(i3.indexOf(cWord.substr(j, 1)) == -1){ break; } else if ( cWord.replace(cWord.substr(j,1),'').indexOf(cWord.substr(j, 1)) != -1) { //console.log(cWord.replace(cWord.substr(j,1),'')); break; } if(j == i1-1){ //console.log(cWord); mWords= mWords + 1; } } } console.log(mWords);
'use strict'; var fs = require('fs'); var geojsonVt = require('geojson-vt'); var vtpbf = require('vt-pbf'); var zlib = require('zlib'); var mbtilesPromises = require('../mbtiles-promises'); var queue = require('queue-async'); var turf = require('turf'); var lineclip = require('lineclip'); var sphericalmercator = new (require('sphericalmercator'))({size: 512}); var rbush = require('rbush'); var lodash = require('lodash'); var stats = require('simple-statistics'); var applyFilter = require('../applyFilter.js'); var outputDir = global.mapOptions.outputDir + '/'; var binningFactor = global.mapOptions.binningFactor; // number of slices in each direction var analytics = JSON.parse(fs.readFileSync(global.mapOptions.analyticsPath)); analytics.layers.forEach(function(layer) { layer.filterKey = layer.filter.tagKey; layer.filter = applyFilter(layer.filter); }); var geomTiles = []; var aggrTiles = []; var initialized = false; var users = {}; if (global.mapOptions.experiencesPath) users = JSON.parse(fs.readFileSync(global.mapOptions.experiencesPath)); // Filter features touched by list of users defined by users.json module.exports = function _(tileLayers, tile, writeData, done) { if (!initialized) { var handles = []; analytics.layers.forEach(function(layer) { handles.push(mbtilesPromises.openWrite(outputDir + layer.name + '/geom.' + process.pid + '.z13.mbtiles')); handles.push(mbtilesPromises.openWrite(outputDir + layer.name + '/aggr.' + process.pid + '.z12.mbtiles')); }) Promise.all(handles).then(function(dbHandles) { analytics.layers.forEach(function(layer, index) { geomTiles[index] = dbHandles[index * 2]; aggrTiles[index] = dbHandles[index * 2 + 1]; }); initialized = true; _(tileLayers, tile, writeData, done); // restart process after initialization }).catch(function(err) { console.error("error while opening mbtiles db", err); }); return; } var filteredData = analytics.layers.map(function() { return []; }); tileLayers.osmqatiles.osm.features.forEach(function(feature) { analytics.layers.forEach(function(layer, layerIndex) { if (layer.filter(feature)) { filteredData[layerIndex].push(feature); } }); }); if (filteredData.map(function(features) { return features.length; }).reduce(function(a,b) { return a+b; }) === 0) return done(); // enhance with user experience data filteredData = filteredData.map(function(features, layerIndex) { return features.map(function(feature) { var output = Object.assign({}, feature); var user = feature.properties['_uid']; output.properties = { _uid: user, _timestamp: feature.properties['_timestamp'], _tagValue: feature.properties[analytics.layers[layerIndex].filterKey] } output.properties._userExperience = users[user][analytics.layers[layerIndex].experienceField]; if (analytics.layers[layerIndex].processing && analytics.layers[layerIndex].processing.indexOf("geometry:calculate_centroid") !== -1) { output.geometry = turf.centroid(feature).geometry; } return output; }); }); var resultQueue = queue(); filteredData.forEach(function(features, layerIndex) { var tilesIndex = geojsonVt(turf.featurecollection(features), { maxZoom: 13, buffer: 0, tolerance: 1, // todo: faster if >0? (default is 3) indexMaxZoom: 13 }); function putTile(z,x,y, done) { var tileData = tilesIndex.getTile(z, x, y); if (tileData === null || tileData.features.length === 0) { done(); } else { var pbfout = zlib.gzipSync(vtpbf.fromGeojsonVt({ 'osm': tileData })); geomTiles[layerIndex].putTile(z, x, y, pbfout, done); } } var putTileQueue = queue(1); putTileQueue.defer(putTile, tile[2]+1, tile[0]*2, tile[1]*2); putTileQueue.defer(putTile, tile[2]+1, tile[0]*2, tile[1]*2+1); putTileQueue.defer(putTile, tile[2]+1, tile[0]*2+1, tile[1]*2+1); putTileQueue.defer(putTile, tile[2]+1, tile[0]*2+1, tile[1]*2); resultQueue.defer(putTileQueue.awaitAll); var tileBbox = sphericalmercator.bbox(tile[0],tile[1],tile[2]); var bins = [], bboxMinXY = sphericalmercator.px([tileBbox[0], tileBbox[1]], tile[2]), bboxMaxXY = sphericalmercator.px([tileBbox[2], tileBbox[3]], tile[2]), bboxWidth = bboxMaxXY[0]-bboxMinXY[0], bboxHeight = bboxMaxXY[1]-bboxMinXY[1]; for (var i=0; i<binningFactor; i++) { for (var j=0; j<binningFactor; j++) { var binMinXY = [ bboxMinXY[0] + bboxWidth /binningFactor*j, bboxMinXY[1] + bboxHeight/binningFactor*i ], binMaxXY = [ bboxMinXY[0] + bboxWidth /binningFactor*(j+1), bboxMinXY[1] + bboxHeight/binningFactor*(i+1) ]; var binMinLL = sphericalmercator.ll(binMinXY, tile[2]), binMaxLL = sphericalmercator.ll(binMaxXY, tile[2]); bins.push([ binMinLL[0], binMinLL[1], binMaxLL[0], binMaxLL[1], i*binningFactor + j ]); } } var binCounts = Array(bins.length+1).join(0).split('').map(Number); // initialize with zeros var binDistances = Array(bins.length+1).join(0).split('').map(Number); // initialize with zeros var binObjects = Array(bins.length); var binTree = rbush(); binTree.load(bins); features.forEach(function(feature) { var clipper, geometry = feature.geometry.coordinates; if (feature.geometry.type === 'Point') { clipper = (coords, bbox) => coords[0] > bbox[0] && coords[0] < bbox[2] && coords[1] > bbox[1] && coords[1] < bbox[3]; } else if (feature.geometry.type === 'LineString') { clipper = lineclip.polyline; } else if (feature.geometry.type === 'Polygon' && geometry.length === 1) { clipper = lineclip.polygon; geometry = geometry[0]; } else return; // todo: handle polygons with holes (aka multipolygons) // todo: support more geometry types var featureBbox = turf.extent(feature); var featureBins = binTree.search(featureBbox).filter(function(bin) { var clipped = clipper(geometry, bin); return clipped === true || clipped.length > 0; }); featureBins.forEach(function(bin) { var index = bin[4]; binCounts[index] += 1/featureBins.length; if (feature.geometry.type === 'LineString') { clipper(geometry, bin).forEach(function(coords) { binDistances[index] += turf.lineDistance(turf.linestring(coords), 'kilometers'); }); } if (!binObjects[index]) binObjects[index] = []; binObjects[index].push({ //id: feature.properties._osm_way_id, // todo: rels?? _timestamp: feature.properties._timestamp, _userExperience: feature.properties._userExperience, _uid: feature.properties._uid, _tagValue: feature.properties._tagValue }); }); }); var output = turf.featurecollection(bins.map(turf.bboxPolygon)); output.features.forEach(function(feature, index) { feature.properties.binX = index % binningFactor; feature.properties.binY = Math.floor(index / binningFactor); feature.properties._count = binCounts[index]; feature.properties._lineDistance = binDistances[index]; if (!(binCounts[index] > 0)) return; feature.properties._timestamp = lodash.meanBy(binObjects[index], '_timestamp'); // todo: don't hardcode properties to average? feature.properties._userExperience = lodash.meanBy(binObjects[index], '_userExperience'); //feature.properties.osm_way_ids = binObjects[index].map(function(o) { return o.id; }).join(';'); // ^ todo: do only partial counts for objects spanning between multiple bins? var timestamps = lodash.map(binObjects[index], '_timestamp'); var sampleIndices = lodash.sampleSize(Array.apply(null, {length: timestamps.length}).map(Number.call, Number), 16); feature.properties._timestampMin = stats.quantile(timestamps, 0.25); feature.properties._timestampMax = stats.quantile(timestamps, 0.75); feature.properties._timestamps = sampleIndices.map(function(idx) { return timestamps[idx]; }).join(';'); var experiences = lodash.map(binObjects[index], '_userExperience'); feature.properties._userExperienceMin = stats.quantile(experiences, 0.25); feature.properties._userExperienceMax = stats.quantile(experiences, 0.75); feature.properties._userExperiences = sampleIndices.map(function(idx) { return experiences[idx]; }).join(';'); var uids = lodash.map(binObjects[index], '_uid'); feature.properties._uids = sampleIndices.map(function(idx) { return uids[idx]; }).join(';'); var tagValues = lodash.map(binObjects[index], '_tagValue'); feature.properties._tagValues = sampleIndices.map(function(idx) { return tagValues[idx]; }).join(';'); }); output.features = output.features.filter(function(feature) { return feature.properties._count > 0; }); //output.properties = { tileX: tile[0], tileY: tile[1], tileZ: tile[2] }; var tileData = geojsonVt(output, { maxZoom: 12, buffer: 0, tolerance: 1, // todo: faster if >0? (default is 3) indexMaxZoom: 12 }).getTile(tile[2], tile[0], tile[1]); if (tileData !== null && tileData.features.length > 0) { var pbfout = zlib.gzipSync(vtpbf.fromGeojsonVt({ 'osm': tileData })); resultQueue.defer(function(done) { aggrTiles[layerIndex].putTile(tile[2], tile[0], tile[1], pbfout, done); }); } }); resultQueue.await(function(err) { if (err) console.error(err); done(); }); }; process.on('SIGHUP', function() { Promise.all([] .concat( geomTiles.map(function(geomTiles) { return mbtilesPromises.closeWrite(geomTiles); }) ).concat( aggrTiles.map(function(aggrTiles) { return mbtilesPromises.closeWrite(aggrTiles); }) ) ).then(function() { process.exit(0); }).catch(function(err) { console.error("error while closing db", err); process.exit(13); }); });
import React, { Component } from 'react' import UploadWrap from './Upload.styled' import Text from '../ui/Text' import { createForm } from 'rc-form'; const TextWrapper = createForm()(Text); class Upload extends Component { state = { } // onLeftClick = () => { // let { history } = this.props // history.goBack() // } // detailClick = () =>{ // let { history } = this.props // history.push('/article') // } render() { return ( <UploadWrap> <TextWrapper ></TextWrapper> </UploadWrap> ) } } export default Upload
var struct________________________________classes________________8js________8js____8js__8js_8js = [ [ "struct________________classes________8js____8js__8js_8js", "struct________________________________classes________________8js________8js____8js__8js_8js.html#a48d793dc82b6dc7f5b3fa99636d4e87a", null ] ];
import React, { PureComponent } from 'react'; import ListItemLink from '../component/ListItemLink'; import Collapse from '@material-ui/core/Collapse'; import List from '@material-ui/core/List'; import { useStyles } from '../static/MiniDrawerStyles'; const classes = useStyles; class ListItemLinkContainer extends PureComponent { constructor(props) { super(props); this.state = { isOpen: false } } handleClick = (e) => { this.setState({ isOpen: !this.state.isOpen }) } render() { const { menuObj } = this.props; return ( <React.Fragment> {menuObj.submenu.length > 0 ? ( <ListItemLink key={menuObj.id} to={menuObj.path} menuText={menuObj.menuName} icon={menuObj.icon} open={this.state.isOpen} onClick={this.handleClick} /> ) : ( <ListItemLink key={menuObj.id} to={menuObj.path} menuText={menuObj.menuName} icon={menuObj.icon} /> ) } <Collapse component="li" in={this.state.isOpen} timeout="auto" unmountOnExit> <List disablePadding> {menuObj.submenu.map((sub, index) => ( <ListItemLink key={sub.id} to={sub.path} menuText={sub.menuName} icon={sub.icon} className={classes.nested} /> ))} </List> </Collapse> </React.Fragment> ) } } export default ListItemLinkContainer;
import React from 'react'; import Imported from './imported'; export default () => { return <Container> <Imported/> </Container>; }; const Container = ({children}) => { return <div>{children}</div> }
var ui = { modal: { setTitle: function(text) { $('#modal .content .title').html(text); }, setMessage: function(text) { $('#modal .content .message').html(text); }, show: function() { $('#modal').removeClass('fadeOut'); $('#modal').addClass('fadeIn'); $('#modal').removeClass('hidden'); }, hide: function() { $('#modal').removeClass('fadeIn'); $('#modal').addClass('fadeOut'); $('#modal').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() { $('#modal').addClass('hidden'); }); } }, formValidation: { valid: function(fieldID) { var errorMessage = $(fieldID + ' .error-message'); var field = $(fieldID + ' .field'); field.removeClass('invalid'); errorMessage.addClass('hidden'); }, invalid: function(fieldID, message) { var errorMessage = $(fieldID + ' .error-message'); var field = $(fieldID + ' .field'); field.addClass('invalid'); errorMessage.removeClass('hidden'); errorMessage.html(message); } } }
import React, { PropTypes } from 'react'; import _ from 'lodash'; import { Table } from 'react-bootstrap'; import { isBusy } from '@shoutem/redux-io'; import { LoaderContainer } from '@shoutem/react-web-ui'; import { getCategoriesDisplayLabel } from '../../services'; import './style.scss'; function getCategoryName(resource) { const categories = _.filter(resource.categories, { autoCreated: false }); const categoryNames = _.map(categories, 'name'); return getCategoriesDisplayLabel(categoryNames); } export default function ContentPreview({ resources, titleProp, hasContent }) { return ( <div className="content-preview"> {hasContent && <span className="content-preview__overlay" />} <LoaderContainer isLoading={isBusy(resources)} isOverlay > <Table className="content-preview__table"> <thead> <tr> <th>Title</th> <th>Category</th> </tr> </thead> <tbody> {!hasContent && <tr> <td colSpan="2">No content yet.</td> </tr> } {hasContent && resources.map(resource => <tr key={resource.id}> <td>{resource[titleProp] || ''}</td> <td>{getCategoryName(resource)}</td> </tr> )} </tbody> </Table> </LoaderContainer> </div> ); } ContentPreview.propTypes = { categories: PropTypes.array, resources: PropTypes.object.isRequired, titleProp: PropTypes.string.isRequired, hasContent: PropTypes.bool, inProgress: PropTypes.bool, };
/** *Authentication */ (function () { 'use strict', angular .module('app.authentication.services') .factory('Authentication',Authentication); Authentication.$inject=['$cookies','$http']; function Authentication($cookies, $http){ var Authentication={ getAuthenticatedAccount:getAuthenticatedAccount, isAuthenticated:isAuthenticated, setAuthenticatedAccount:setAuthenticatedAccount, unauthenticate:unauthenticate, login:login, register:register, logout:logout, }; return Authentication; function getAuthenticatedAccount(){ if(!$cookies.get('account')){ return; } return JSON.parse($cookies.get('account')); } function isAuthenticated(){ return !!$cookies.get('account'); } function register(email, password, username) { return $http.post('/api/v1/accounts/',{ username:username, password:password, email:email }).then(registerSuccessFn, registerErrorFn); function registerSuccessFn(data, status, headers, config){ Authentication.login(email, password); } function registerErrorFn(data, status, headers, config){ console.error(data); } } function login( email, password){ return $http.post('/api/v1/auth/login/',{ email:email, password:password }).then(loginSuccessFn, loginErrorFn); function loginSuccessFn(data, status, header, config){ Authentication.setAuthenticatedAccount(data.data); window.location='/'; } function loginErrorFn(data, status, header, config){ console.error('Epic failure!'); } } function logout(){ return $http.post('/api/v1/auth/logout/') .then(logoutSuccessFn, logoutErrorFn); function logoutErrorFn(data, status, headers,config){ console.error('Epic failure!'); } function logoutSuccessFn(data, status, headers, config){ Authentication.unauthenticate(); window.location ='/'; } } function setAuthenticatedAccount(account){ $cookies.put('account',JSON.stringify(account)); } function unauthenticate(){ delete $cookies.remove('account'); } } })();
// @flow const defaultTo: <D, V>(D) => V => D | V = defaultValue => value => value == null ? defaultValue : value; export default defaultTo;
import { baseComponent } from '@xmini/wxapp-component-base/index'; let tempIndex = -1; baseComponent({ props: { msgData: { type: Object, value: [] } }, data:{ activeIndex: -1, duration: 6000, animationInfo: {}, }, watch: { msgData(newVal, oldVal) { // console.log('来新数据了', newVal); this.startCarousel(); }, }, // 计算属性 computed: { }, created() { this.animation = wx.createAnimation({ duration: 1000, timeFunction: 'ease-in-out', }); this.startCarousel(); }, // 事件 methods: { onDetailPage(e) { let item = e.currentTarget.dataset.item; this.$page.forward('detail',{ id: item.pin_activities_id }) }, testFn(data){ console.log(data) }, startCarousel() { if (this.data.msgData.length) { this.start(); } else { this.stop(); } }, start() { this.stop(); tempIndex = -1; this.change(); this.interTime = setInterval(() => { this.change(); }, this.data.duration + 1000); }, stop() { clearInterval(this.interTime); }, change() { if (tempIndex == this.data.msgData.length - 1) { tempIndex = -1; this.stop(); return; } else { tempIndex++; } this.animation.opacity(1).translateY(0).step(); this.setData({ activeIndex: tempIndex, animationInfo: this.animation.export() }); setTimeout(() => { this.animation.opacity(0).translateY(20).step(); this.setData({ animationInfo: this.animation.export() }); }, this.data.duration) }, }, })
import { Button, Card, CardActions, CardContent, CardHeader, CardMedia, Grid, Typography } from '@mui/material'; import React from 'react'; import { Link } from 'react-router-dom'; const SingleProduct = ({ product }) => { const { title, img, price, detail, _id } = product; const url = `/explore/${_id}`; return ( <Grid item xs={4} sm={4} md={4}> <Card sx={{ maxWidth: 345 }}> <CardHeader title={title} /> <CardMedia component="img" height="140" image={img} alt="" /> <CardContent> <Typography variant="body1" color="text.secondary"> {detail} </Typography> <Typography variant="h6" color="#d84315"> $ {price} </Typography> </CardContent> <CardActions> <Link to={url} style={{ textDecoration: 'none' }}> <Button size="small" variant="contained" color="warning">Buy Now!</Button> </Link> </CardActions> </Card> </Grid> ); }; export default SingleProduct;
import React from "react"; import { StyleSheet, View, Image, ImageBackground, TouchableOpacity, Alert, SafeAreaView, ScrollView, FlatList } from "react-native"; import { Container, Header, StyleProvider, Thumbnail, Card, Form, Item, Left, Title, Right, Input, Label, Content, List, CheckBox, Body, ListItem, Text, Button } from "native-base"; import AsyncStorage from "@react-native-community/async-storage"; import * as COLOR_CONSTS from "../constants/color-consts"; import * as ROUTE_CONSTS from "../constants/route-consts"; import * as APP_CONSTS from "../constants/app-consts"; import * as API_CONSTS from "../constants/api-constants"; import getTheme from "../../native-base-theme/components"; import material from "../../native-base-theme/variables/platform"; import { SearchBar } from "react-native-elements"; import Loader from "../components/loader"; import SubmitButton from "../components/submitButtonSqr"; import { AppEventEmitter, AppEvent } from "../components/appEventEmitter"; export default class SelectCourseScreen extends React.Component { constructor(props) { super(props); this.state = { search: "", searchArr: [], usersArr: [], userArrNew: [], loading: false, currentPage: 0, totalPage: 0, pageLoading: true }; this.getStarted = this.getStarted.bind(this); this.closeButtonTapped = this.closeButtonTapped.bind(this); this.handleLoadMore = this.handleLoadMore.bind(this); } componentDidMount() { this.getAllUsers(1); } getAllUsers(pageNo) { if (pageNo == 1) { this.setState({ loading: true }); } this.setState({ pageLoading: false }); var self = this; const keyword = this.state.search || ""; var url = API_CONSTS.API_BASE_URL + API_CONSTS.API_COURSES_LIST + `?page=${pageNo}&limit=10&keyword=${keyword}`; console.log(url); fetch(url, { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: global.token } }) .then(response => { if (response.status === 200) { return response.json(); } else if (response.status === 401) { this.props.navigation.navigate("Home"); return { code: response.status, message: "Plese login again" }; } else { return { code: response.status, message: "Something went wrong " + response.status }; } }) .then(responseJson => { this.setState({ loading: false, pageLoading: true }); console.log("userData", responseJson.body); if (responseJson.code == 200) { responseJson.body.forEach(user => { user.checked = false; }); if (pageNo != 1) { this.setState({ usersArr: this.state.usersArr.concat(responseJson.body), searchArr: this.state.searchArr.concat(responseJson.body), totalPage: responseJson.totalPages, currentPage: responseJson.currentPage }); } else { this.setState({ usersArr: responseJson.body, searchArr: responseJson.body, totalPage: responseJson.totalPages, currentPage: responseJson.currentPage }); } } }) .catch(error => { console.error(error); }); } handleLoadMore() { console.log("handleLoadMore"); if ( this.state.currentPage < this.state.totalPage && this.state.pageLoading ) { //call api this.setState( { currentPage: this.state.currentPage + 1 }, function() { console.log("CURRENT PAGE", this.state.currentPage); this.getAllUsers(this.state.currentPage); } ); } } getStarted = async () => { // this.props.navigation.navigate(ROUTE_CONSTS.LOGIN_SCREEN) let userArr = []; const data = await this.state.usersArr.forEach(user => { if (user.checked == true) { userArr.push({ courseId: user.id }); } this.setState({ userArrNew: userArr }); }); if (this.state.userArrNew.length > 0) { this.updateStudentCourses(); } else { alert("Please select courses"); } }; updateStudentCourses() { this.setState({ loading: true }); var self = this; let url = API_CONSTS.API_BASE_URL + API_CONSTS.API_STUDENT_COURSES; // alert(url) fetch(url, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: global.token }, body: JSON.stringify({ courses: this.state.userArrNew }) }) .then(response => response.json()) .then(responseJson => { this.setState({ loading: false }); console.log(JSON.stringify(responseJson)); if (responseJson.code == 200) { // this.forceUpdate() // this.props.navigation.navigate('Home') AsyncStorage.setItem(APP_CONSTS.COURSEADDED, "true"); AppEventEmitter.emit(AppEvent.RefreshDashBoardScreenCourses); this.props.navigation.navigate(ROUTE_CONSTS.DASHBOARD_PAGE, { user: "", isNew: false }); } else { Alert.alert("Message", responseJson.message, [ { text: "OK", onPress: () => this.setState({ loading: false }, function() { // this.forceUpdate() // this.props.navigation.navigate('Home') this.props.navigation.navigate("Home"); }) } ]); } }) .catch(error => { console.error(error); }); } closeButtonTapped() { let { params = {} } = this.props.navigation.state; console.log("params", params); if (params.backScreen) { if (params.backScreen == "dashboard") { this.props.navigation.navigate(ROUTE_CONSTS.DASHBOARD_PAGE, { user: "", isNew: false }); } else if (params.backScreen == "login") { this.props.navigation.navigate(ROUTE_CONSTS.LOGIN_SCREEN, { data: params.institute }); } } else { this.props.navigation.goBack(); } } updateSearch = search => { if (search != "") { this.setState({ search }, () => this.getAllUsers(2)); console.log(search); var items = []; this.state.usersArr.filter(item => { let val = item.title.toLowerCase(); let val2 = search.toLowerCase(); if (val.indexOf(val2) !== -1) { items.push(item); this.setState({ usersArr: items }); console.log(item); } else { this.setState({ usersArr: items }); } }); } else { this.setState({ search }, () => this.getAllUsers(2)); this.setState({ usersArr: this.state.searchArr }); } }; checkedItem(item) { if (item.checked == true) { item.checked = false; this.setState({ usersArr: this.state.usersArr, checked: false }); } else { item.checked = true; this.setState({ usersArr: this.state.usersArr, checked: true }); } console.log(this.state.usersArr); } loadOrganizationsCell = ({ item, index }) => { return ( <View> <List> {/* <ListItem avatar noBorder style={{marginTop:10}}> <Left> <Thumbnail source={require('../../assets/o1.png')} /> </Left> <Body style={{justifyContent:'center',marginTop:10}}> <Text style={{fontWeight:'500'}}>Silicon Valley Bank</Text> </Body> <Right style={{justifyContent:'center',marginRight:10,marginTop:12}}> <CheckBox checked={false} /> </Right> </ListItem> */} <ListItem avatar noBorder style={{ marginTop: 10 }}> {/* <Left> <Thumbnail source={{uri: data.image}} /> </Left> */} <Body style={{ justifyContent: "center", marginTop: 10 }}> <Text style={{ fontWeight: "500" }}>{item.title}</Text> </Body> <Right style={{ justifyContent: "center", marginRight: 10, marginTop: 12 }} > <CheckBox checked={item.checked} onPress={() => this.checkedItem(item)} /> </Right> </ListItem> {/* <ListItem avatar noBorder style={{marginTop:10}}> <Left> <Thumbnail source={require('../../assets/o5.jpg')} /> </Left> <Body style={{justifyContent:'center',marginTop:10}}> <Text style={{fontWeight:'500'}}>The City University of New York</Text> </Body> <Right style={{justifyContent:'center',marginRight:10,marginTop:12}}> <CheckBox checked={false} /> </Right> </ListItem> */} {/* <ListItem avatar noBorder style={{marginTop:10}}> <Left> <Thumbnail source={require('../../assets/o4.png')} /> </Left> <Body style={{justifyContent:'center',marginTop:10}}> <Text style={{fontWeight:'500'}}>The city College of New York</Text> </Body> <Right style={{justifyContent:'center',marginRight:10,marginTop:12}}> <CheckBox checked={false} /> </Right> </ListItem> */} </List> </View> ); }; loadOrganizations() { // let organisationComponent = [] // this.state.usersArr.forEach(data => { // organisationComponent.push( // <View> // <List> // <ListItem avatar noBorder style={{marginTop:10}}> // <Body style={{justifyContent:'center',marginTop:10}}> // <Text style={{fontWeight:'500'}}>{data.title}</Text> // </Body> // <Right style={{justifyContent:'center',marginRight:10,marginTop:12}}> // <CheckBox checked={data.checked} onPress={()=>this.checkedItem(data)}/> // </Right> // </ListItem> // </List> // </View> // ) // }); // return <View > // <ScrollView // vertical // showsHorizontalScrollIndicator={false} // style={styles.cardContainer} // > // {organisationComponent} // </ScrollView> // </View> return ( <FlatList data={this.state.usersArr} ListEmptyComponent={this._listEmptyComponent} extraData={this.state} initialNumToRender={5} maxToRenderPerBatch={5} windowSize={5} renderItem={this.loadOrganizationsCell} keyExtractor={(item, index) => index.toString()} onEndReached={this.handleLoadMore} onEndReachedThreshold={0.01} /> ); } _listEmptyComponent = () => { return ( <View style={{ height: "100%", justifyContent: "center", alignSelf: "center", paddingTop: 30 }} > <Text style={{ textAlign: "center", color: "grey" }} /> </View> ); }; render() { const { search } = this.state; return ( <StyleProvider style={getTheme(material)}> <Container style={styles.container}> <Loader loading={this.state.loading} /> <Header style={styles.headerStyle}> <Left style={{ flex: 3 }}> <View style={{ padding: 10, marginTop: 1, alignItems: "flex-start" }} > <TouchableOpacity onPress={this.closeButtonTapped}> <Image source={require("../../assets/bck.png")} style={{ width: 20, height: 20, resizeMode: "contain" }} /> </TouchableOpacity> </View> </Left> <Body style={{ flex: 3 }}> <Title style={styles.title}>Select Courses</Title> </Body> <Right style={{ flex: 3 }}> {/* <View style={{ padding: 10, marginTop: 1, alignItems: "flex-start" }}> <TouchableOpacity onPress={this.closeButtonTapped}> <Image source={require('../../assets/cart.png')} style={{ width: 20, height: 20, resizeMode: 'contain' }} /> </TouchableOpacity> </View> */} </Right> </Header> <View style={{ flex: 1 }}> <View style={{ marginTop: 20, margin: 10, borderWidth: 1, borderRadius: 5, borderColor: COLOR_CONSTS.APP_GREY_COLOR }} > <SearchBar lightTheme={true} placeholder="Search Courses" onChangeText={this.updateSearch} value={search} containerStyle={{ backgroundColor: COLOR_CONSTS.APP_WHITE_COLOR, borderRadius: 10 }} inputContainerStyle={{ backgroundColor: COLOR_CONSTS.APP_WHITE_COLOR }} searchIcon={ <Image source={require("../../assets/search.png")} style={{ width: 20, height: 20 }} /> } cancelIcon={null} clearIcon={null} /> </View> {this.loadOrganizations()} </View> <SafeAreaView> <SubmitButton title="Continue" buttonTapAction={this.getStarted} /> {/* <View style={{height:50,width:'100%',justifyContent:'space-around',alignItems:'center',flexDirection:'row'}}> <Button style={{height:35,width:160,marginTop:10,backgroundColor:COLOR_CONSTS.APP_GREEN_COLOR,justifyContent:'center'}}> <Text style={{color:'black',fontWeight:'500',fontSize:15,textAlign:'center'}}>Share to Selected</Text> </Button> <Button style={{height:35,width:160,marginTop:10,backgroundColor:COLOR_CONSTS.APP_GREEN_COLOR,justifyContent:'center'}}> <Text style={{color:'black',fontWeight:'500',fontSize:15}}>Share to All</Text> </Button> </View> */} </SafeAreaView> </Container> </StyleProvider> ); } } const styles = StyleSheet.create({ container: { backgroundColor: COLOR_CONSTS.APP_OFF_WHITE_COLOR }, headerStyle: { backgroundColor: COLOR_CONSTS.APP_BLACK_COLOR }, title: { color: COLOR_CONSTS.APP_WHITE_COLOR, fontSize: 16, fontWeight: "bold" }, marketList: { backgroundColor: COLOR_CONSTS.APP_WHITE_COLOR, marginTop: 15 }, marketName: { color: COLOR_CONSTS.APP_BLACK_COLOR, fontSize: 20 }, eventsCardContainer: { height: 140, width: "100%", resizeMode: "cover", borderRadius: 5, backgroundColor: "transparent" } });
import { getTodo } from '@/services/todoList'; console.log(getTodo); export default { namespace: 'todoList', // reducer 's state -> props obj state: { data: [ { id: 12, title: 'todo 0', checked: false, }, { id: 121, title: 'todo 1', checked: false, }, { id: 1212, title: 'todo 2', checked: false, }, ], }, effects: { *fetchTodo({ payload, callback }, { call, put }) { const { data } = yield call(getTodo, payload); yield put({ type: 'addTodo', payload: data, }); }, *deleteAll({ payload, callback }, { call, put }) { yield call(getTodo, payload); yield put({ type: 'deleteTodo', }); }, }, reducers: { addTodo(state, { payload: item }) { const { data } = state; state.data = [...data, item]; return { ...state }; }, updateTodoChecked(state, { payload: item }) { const arr = state.data.map(obj => { if (obj.id == item.id) { return { id: obj.id, title: obj.title, checked: !obj.checked, }; } return obj; }); return { ...state, data: arr }; }, deleteTodo(state) { const arr = state.data.filter(obj => { return !obj.checked; }); return { ...state, data: arr, }; }, }, };
window.addEvent('domready', function() { var comform = document.id('comment-form'); new Form.Validator.Inline(comform); new Form.Request(comform, 'comment-form-section', { extraData: { 'partial': 'true' } }); });
var tokki = angular.module('directives').directive('intercambioReader', ["Notification", function(Notification) { 'use strict'; return { restrict: "A", link: function (scope, ele, attrs) { ele.bind('change', function(eve){ var f = eve.target.files[0]; var r = new FileReader(); if (!f.type.match('xml')) { Notification.error('El archivo no es un xml.'); ele[0].value = ""; scope.dtes = {}; scope.$apply(); } else{ r.onload = (function (f) { return function (e) { var contents = e.target.result; scope.output = contents; scope.dtes = []; var x2js = new X2JS(); var doc = x2js.xml_str2json(scope.output); var caratula = doc.EnvioDTE.SetDTE.Caratula; var dte = doc.EnvioDTE.SetDTE.DTE; var envioId = doc.EnvioDTE.SetDTE._ID; scope.respuesta.rutReceptor = caratula.RutReceptor; scope.respuesta.rutEmisor = caratula.RutEmisor; $scope.respuesta.envioid = envioId; if(scope.respuesta.rutReceptor != scope.info.rut) Notification.warning('el archivo XML parece estar dirijido a un <strong>rut diferente</strong> a la suya, verifique que el rut antes de responder'); else Notification.success('Esta viendo los contenidos del xml: ' + f.name); if(dte.constructor !== Array) dte = [dte]; scope.respuesta.nroDetalles = dte.length; for(var x=0; x<dte.length; x++){ var detalles = []; if(dte[x].Documento.Detalle.constructor !== Array){ dte[x].Documento.Detalle = [dte[x].Documento.Detalle]; } for(var y=0; y<dte[x].Documento.Detalle.length;y++){ var UnmdItem = ''; var exe = ''; if(dte[x].Documento.Detalle[y].UnmdItem) UnmdItem = dte[x].Documento.Detalle[y].UnmdItem; if(dte[x].Documento.Detalle[y].IndExe) UnmdItem = dte[x].Documento.Detalle[y].IndExe; detalles.push({ 'dte': dte[x].Documento.Encabezado.IdDoc.TipoDTE, 'id': dte[x].Documento.Encabezado.IdDoc.Folio, 'producto': dte[x].Documento.Detalle[y].NmbItem, 'unidad': UnmdItem, 'exe': exe, 'cantidad': dte[x].Documento.Detalle[y].QtyItem, 'precio': dte[x].Documento.Detalle[y].PrcItem }) } if(dte[x].Documento.Encabezado.Receptor.RUTRecep != scope.info.rut) Notification.warning('hay un <strong>rut diferente</strong> a la suya en el detalle, verifique que el rut antes de responder'); scope.dtes.push({ 'dte': dte[x].Documento.Encabezado.IdDoc.TipoDTE, 'id': dte[x].Documento.Encabezado.IdDoc.Folio, 'fecha': dte[x].Documento.Encabezado.IdDoc.FchEmis, 'rutEmisor': dte[x].Documento.Encabezado.Emisor.RUTEmisor, 'rutReceptor': dte[x].Documento.Encabezado.Receptor.RUTRecep, 'razon': dte[x].Documento.Encabezado.Emisor.RznSoc, 'giro': dte[x].Documento.Encabezado.Emisor.GiroEmis, 'direccion': dte[x].Documento.Encabezado.Emisor.DirOrigen, 'comuna': dte[x].Documento.Encabezado.Emisor.CiudadOrigen, 'ciudad': dte[x].Documento.Encabezado.Emisor.RznSoc, 'exento': dte[x].Documento.Encabezado.Totales.MntExe, 'neto': dte[x].Documento.Encabezado.Totales.MntNeto, 'iva': dte[x].Documento.Encabezado.Totales.IVA, 'total': dte[x].Documento.Encabezado.Totales.MntTotal, 'rechazado': false, 'rechazo': '', 'recepcion': 0, 'detalles': detalles, 'dtexml': x2js.json2xml_str(dte[x]) }); } scope.$apply(); }; })(f); r.readAsText(f, 'ISO-8859-1'); } }); } }; } ]);
/** * Created by rs on 22/01/17. */ import {getMembersAPI, addMemberAPI, updateMemberAPI} from '../api/members' export const getMembers = () => { return { types: ["REQ_GET_MEMBERS", "REQ_GET_MEMBERS_SUCCESS", "REQ_GET_MEMBERS_FAILURE"], promise: () => { return getMembersAPI(); } }; }; export const addMember = (member) => { return { types: ["ADD_MEMBER", "ADD_MEMBER_S", "ADD_MEMBER_F"], promise: () => { return addMemberAPI(member); } } } export const updateMember = (id, member) => { return { types: ["UPDATE_MEMBER", "UPDATE_MEMBER_S", "UPDATE_MEMBER_F"], promise: () => { return updateMemberAPI(id, member); } } }
import styled, { css } from "styled-components"; import tokens from "@paprika/tokens"; import { fontSize } from "@paprika/stylers/lib/helpers"; import * as types from "./types"; export const Table = styled.table` border: 1px solid ${tokens.border.color}; border-collapse: collapse; &:focus { outline: 0; } & .is-highlighted-focus { outline: 2px solid blue; } & .is-highlighted-idle { outline: 2px solid transparent; } `; export const TBody = styled.tbody(({ hasZebraStripes }) => { let zebras = ""; if (hasZebraStripes) { zebras = css` & tr { background: ${tokens.table.row.backgroundColor}; } & tr:nth-child(even) { background-color: ${tokens.table.rowEven.backgroundColor}; } `; } return css` ${zebras}; `; }); export const Thead = styled.thead` background: ${tokens.table.header.backgroundColor}; text-align: left; `; const borderTypesStyles = { [types.NONE]: "", [types.VERTICAL]: css` border-color: ${tokens.border.color}; border-style: solid; border-width: 0px 1px 0px 1px; `, [types.HORIZONTAL]: css` border-color: ${tokens.border.color}; border-style: solid; border-width: 1px 0px 1px 0px; `, [types.GRID]: css` border: 1px solid ${tokens.border.color}; `, }; export const TD = styled.td(({ borderType }) => { return css` ${borderType in borderTypesStyles ? borderTypesStyles[borderType] : ""} padding: ${tokens.space}; text-align: left; `; }); export const TH = styled.th(({ borderType }) => { return css` ${fontSize()} ${borderType in borderTypesStyles ? borderTypesStyles[borderType] : ""} font-weight: bold; padding: ${tokens.space}; text-align: left; `; });
import { hasDot, inlineCalculation } from './reducer-utils.js' import { defaultState } from '../Calculator.js' export const calculatorReducer = (state, action) => { if (action.type === 'FIRST_DIGIT') { let newValue = [...state.currentValue] if (action.payload === '.') { newValue = [...newValue, action.payload] } else { newValue[0] = action.payload.toString() } return {...state, currentValue: newValue, valueIsAdded: false} } if (action.type === 'ANOTHER_DIGIT') { let newValue = [...state.currentValue] if (newValue[0]==="-" && newValue[1]==="0" && newValue[2]!=="." && newValue[2]!==undefined) { newValue[1] = action.payload } else { if (action.payload === '.' && !hasDot(state)) { newValue = [...newValue, action.payload] } if (action.payload !== '.') { newValue = [...newValue, action.payload.toString()] } } return {...state, currentValue: newValue, valueIsAdded: false} } if (action.type === 'MATH_OPERATION') { const newValue = Number(state.currentValue.join('')) let valueIsAdded = state.valueIsAdded let newExpression = [...state.currentExpression] if (!valueIsAdded) { newExpression = [...newExpression, { type: "VALUE", value: newValue }, { type: "OPERATION", value: action.payload }] valueIsAdded = true } else { if (state.currentExpression.length >= 2) { newExpression[newExpression.length-1] = { type: "OPERATION", value: action.payload } } } return {...state, currentExpression: newExpression, valueIsAdded: valueIsAdded, currentValue: ["0"]} } if (action.type === "CALCULATE") { const result = inlineCalculation(state) let currentValue = [] let currentExpression = [] if (result.status === "SUCCESS") { currentExpression = [...result.updatedExpression] currentExpression.push({ type: "OPERATION", value: "=" }) currentValue = [...result.result] return { currentValue, currentExpression, valueIsAdded: false, isCalculated: true, isError: false, } } if (result.status === "FAILURE") { return {currentValue: result.result, currentExpression: [], valueIsAdded: false, isCalculated: true, isError: true, } } return {...state} } if (action.type === "CLEAR_EXPRESSION") { return defaultState } if (action.type === "CLEAR_VALUE") { return {...state, currentValue: ["0"], valueIsAdded: false} } if (action.type === "DELETE_SYMBOL") { let newValue = [...state.currentValue] if (newValue.length>1 && newValue[0] !== "-") { newValue.pop() } else { newValue = ["0"] } return {...state, currentValue: newValue} } if (action.type === "MULTIPLY_MINUS_ONE") { let newValue = [...state.currentValue] if (newValue[0]==='-') { newValue.shift() } else { newValue.unshift('-') } return {...state, currentValue: newValue} } if (action.type === "COPY_EXPRESSION") { let copiedExpression = [...action.payload.expression] let expression = [...copiedExpression] expression.pop() let value = expression[expression.length -1].value expression.pop() //console.log(expression, value); const valueStr = value.toString() const valueArr = valueStr.split('') return {currentValue: [...valueArr], currentExpression: [...expression], valueIsAdded: false, isCalculated: false, isError: false, } } throw new Error('no matching action type') }
import { combineReducers } from "redux"; import users from './users'; export const reducers = combineReducers({ users: users }); export default function reducerCall(state, action, reducerClass) { } https://youtu.be/l9QC2ajMelg?list=PLJBrYU54JD2pTblB20OmV7GL6H5J-p2g8
/** * Created by cl-macmini-63 on 2/6/17. */ 'use strict'; const responseFormatter = require('Utils/responseformatter.js'); const SPProfileSchema = require('schema/mongo/SPprofile'); var SPGigLocationMappingSchema = require('schema/mongo/SPgiglocationmapper'); const messenger = require('Utils/messenger.js'); var bookingSchema = require('schema/mongo/bookingschema'); const gigServiceSchema = require('schema/mongo/gigsschema'); const SPGigLocationMapperSchema = require('schema/mongo/SPgiglocationmapper'); const SPpushcount = require('schema/mongo/SPpushcount'); const stateCodesSchema = require('schema/mongo/stateCodes'); const userSchema = require('schema/mongo/userschema') const spTimeSchema = require('schema/mongo/SPtimeslots'); const gigsSchema = require('schema/mongo/gigsschema'); const SPLocationMapping = require('schema/mongo/serviceLocationMapper') const constantsSchema = require('schema/mongo/constantsschema'); const log = require('Utils/logger.js'); const logger = log.getLogger(); const async = require('async'); const commonFunction = require('Utils/commonfunction.js'); const distance = require('google-distance-matrix'); const bookingModel = require('model/bookingmodel') const sendPush = require('Utils/push.js'); const Mongoose = require('mongoose') var config = require('config'); let AWS = config.amazon.s3; let geocoder = require('geocoder'); var paginator = require('Utils/paginate.js'); var SPGigProductInfoSchema = require('schema/mongo/SPgigproductinfo'); let _ = require('lodash'); const adminGlobalDataSchema = require('schema/mongo/adminglobaldata'); bookingSchema.Booking.paginate = paginator.paginate; var mongoose = require('mongoose'); var sendPushToUnavailableProviders = function (unavailableProviders , callback) { console.log("********** In sendPushToUnavailableProviders *************"); const parallelF = [] unavailableProviders.forEach(function (result) { console.log("result+++++++++++", result) parallelF.push(function (cbb) { userSchema.User.findOne({user_id: result.provider_id}, { device_token: 1, device_type: 1, role_token:1, first_name:1, last_name:1, profilePhoto:1, provider_notification_flag:1 }, {lean: true}, function (err, userData) { console.log('response :: err :: ', err, " userData", userData); if (err) { cbb(err) } else { const n = new Date(); const deviceDetails = []; let deviceToken = null; let deviceType = userData.device_type; let deviceTokenFound = false; if(userData.role_token && userData.role_token.length){ for(var i = 0; i < userData.role_token.length; i++){ if(userData.role_token[i].role == 'PROVIDER'){ deviceToken = userData.role_token[i].token; deviceTokenFound = true; break; } } } if(!deviceTokenFound || userData.provider_notification_flag == false){ console.log('in sendPushToUnavailableProviders Failed to Send Push......Device Token not found for ',result.provider_id," Either this provider is logged out or his notification_flag is false"); cbb(null, true); }else{ let provider_name = userData.first_name+" "+userData.last_name; deviceDetails.push({ device_type: deviceType , //userData.device_type, device_token: deviceToken // userData.device_token }); const pushDetailsSP = { deviceDetails: deviceDetails, text: "You Have a New Booking Available but your availability is off", payload: { "push_type" : 'notify-UnavailableProvider', "message" : "You Have a New Booking Available but your availability is off"}, "provider_name" : provider_name, "provider_image" : userData.profilePhoto, "booking_type" : 'ODS' } sendPush.sendPush(pushDetailsSP, "PROVIDER"); cbb(null, true) } } }); }); }) console.log("paralleF", parallelF); async.parallel(parallelF, function (error, data) { if (error) { return callback(error); } else { console.log("in sendPushToUnavailableProviders parallelF final data", data) callback(null, data) } }); } var createBookingForSystemSelect = function (user, callback) { console.log("********** In createBookingForSystemSelect *************"); let seekerData = null let bookingData = null let gigData = null async.series([ function (cb) { // console.log("user data in seeker select", user) // console.log("seeker_id++++++++", user.seeker_id) userSchema.User.findOne({user_id: user.seeker_id}, {}, {lean: true}, function (err, data) { if (err) { return cb(err) } else { seekerData = data return cb(null) } }) }, function (cb) { gigsSchema.Gigs.findOne({gig_id: user.gig_id}, { gig_id: 1, service_id: 1, gig_name: 1, service_name: 1 }, {lean: true}, function (err, data) { if (err) { return cb(err) } else { gigData = data return cb(null) } }) }, function (cb) { let newBooking = new bookingSchema.Booking() newBooking.seeker_id = user.seeker_id newBooking.seeker_name = user.seeker_name, newBooking.seeker_device_token = user.seeker_device_token, newBooking.seeker_device_type = user.seeker_device_type, newBooking.ODS_type = user.ODS_type newBooking.booking_item_info.gig_name = gigData.gig_name newBooking.booking_item_info.service_name = gigData.service_name newBooking.booking_item_info.service_id = user.service_id newBooking.booking_item_info.gig_id = user.gig_id newBooking.tools = user.tools newBooking.supplies = user.supplies newBooking.description = user.description //newBooking.is_product_based=user.is_product_based newBooking.unit = user.unit newBooking.quantity = user.quantity newBooking.status = 'Unconfirmed' newBooking.seeker_image = { original: seekerData.profilePhoto.original, thumbnail: seekerData.profilePhoto.thumbnail } newBooking.booking_datetime = new Date().toISOString() if (user.is_seeker_location == true) { if (user.virtual_address) { newBooking.is_seeker_location = user.is_seeker_location, newBooking.virtual_address = user.virtual_address } else { newBooking.is_seeker_location = user.is_seeker_location; newBooking.booking_address = user.booking_address; newBooking.booking_latitude = user.booking_latitude; newBooking.booking_longitude = user.booking_longitude; newBooking.booking_address1 = user.booking_address1; newBooking.booking_latitude1 = user.booking_latitude1; newBooking.booking_longitude1 = user.booking_longitude1; } } else { newBooking.is_seeker_location = user.is_seeker_location } newBooking.save(function (err, data) { if (err) { cb(err) } else { bookingData = data; // console.log("saved data for booking", bookingData) cb(null) } }) } ], function (err, data) { //console.log("series end final", err, data); if (err) { callback(err); } else { console.log("new System select booking created successfully ==================================") callback(null, bookingData); } }) } var notifySPForSystemSelect = function (provider,user, bookingData, callback) { console.log("********** In Push *************"); let seekerData = null let gigData = null async.series([ function (cb) { userSchema.User.findOne({user_id: user.seeker_id}, {}, {lean: true}, function (err, data) { if (err) { return cb(err) } else { seekerData = data return cb(null) } }) }, function (cb) { userSchema.User.findOne( {user_id: provider.provider_id}, { device_token: 1, device_type: 1, role_token:1, provider_notification_flag:1 }, {lean: true}, function (err, userData) { console.log('response :: err :: ', err, " userData", userData); if (err) { cb(err) } else { if(userData == null){ console.log('Unable to find User Data corresponding to provider_id :',provider.provider_id," So failed to send push"); cb(err); }else{ const pushCount = new SPpushcount.SPPush({ booking_id: bookingData._id, provider_id: provider.provider_id, }) pushCount.save(function (err) { if (err) { cb(err) } else { const n = new Date(); const deviceDetails = []; let deviceToken = null; let deviceType = userData.device_type; let deviceTokenFound = false; if(userData.role_token && userData.role_token.length){ for(var i = 0; i < userData.role_token.length; i++){ if(userData.role_token[i].role == 'PROVIDER'){ deviceToken = userData.role_token[i].token; deviceTokenFound = true; break; } } } console.log('deviceTokenFound --->',deviceTokenFound); if(!deviceTokenFound || userData.provider_notification_flag == false){ console.log('in notifySPForSystemSelect Failed to Send Push......Device Token not found for ',provider.provider_id," Either this provider is logged out or role_token object is not present in user collection."); cb(null, true); }else{ console.log('in notifySPForSystemSelect sending push to ......',provider.provider_id," deviceType : ",deviceType," DeviceToken :",deviceToken); const bookPayload = {}; if (user.booking_address1) { bookPayload.booking_address1 = user.booking_address1 } else { bookPayload.booking_address1 = '' } if (user.virtual_address) { bookPayload.virtual_address = user.virtual_address } else { bookPayload.virtual_address = '' } if (user.booking_address) { bookPayload.booking_address = user.booking_address // console.log(" bookPayload.booking_address ", bookPayload.booking_address) } else { bookPayload.booking_address = {} } bookPayload.profile_photo = seekerData.profilePhoto, bookPayload.first_name = seekerData.first_name, bookPayload.last_name = seekerData.last_name, bookPayload.booking_type = bookingData.booking_type, bookPayload.booking_id = bookingData._id, bookPayload.booking_data = n.toISOString(), bookPayload.push_type = 'new booking' , bookPayload.ODS_type = user.ODS_type, bookPayload.is_seeker_location = user.is_seeker_location, //bookPayload.is_product_based=user.is_product_based bookPayload.push_date = n.toISOString(), bookPayload.bid_amount = "", //bookPayload.pricing=location.pricing deviceDetails.push({ device_type: deviceType, device_token: deviceToken }); // console.log("bookPayload data System Select", bookPayload) const pushDetailsSP = { deviceDetails: deviceDetails, text: "You Have a New Booking Available Please Confirm", payload: bookPayload } sendPush.sendPush(pushDetailsSP, "PROVIDER"); cb(null, true) } } }); } } }); } ], function (err, data) { console.log("series end final", err, data); if (err) { callback(err); } else { console.log("=========================== new System select push SENT==================================") callback(null, bookingData); } }) } var reverseBid = function (providers, user, bidAmount, callback) { let seekerData = null let bookingData = null let gigData = null async.series([ function (cb) { console.log("seeker_id++++++++", user.seeker_id) userSchema.User.findOne({user_id: user.seeker_id}, {}, {options: true}, function (err, data) { if (err) { cb(err) } else { seekerData = data cb(null) } }) }, function (cb) { gigsSchema.Gigs.findOne({gig_id: user.gig_id}, { gig_id: 1, service_id: 1, gig_name: 1, service_name: 1 }, {lean: true}, function (err, data) { if (err) { cb(err) } else { gigData = data cb(null) } }) }, function (cb) { let newBooking = new bookingSchema.Booking() newBooking.seeker_id = user.seeker_id newBooking.seeker_name = seekerData.first_name+" "+seekerData.last_name, newBooking.seeker_device_token = user.seeker_device_token, newBooking.seeker_device_type = user.seeker_device_type, newBooking.ODS_type = user.ODS_type newBooking.booking_item_info.gig_name = gigData.gig_name newBooking.booking_item_info.service_name = gigData.service_name newBooking.booking_item_info.service_id = user.service_id newBooking.booking_item_info.gig_id = user.gig_id newBooking.booked_price_value=bidAmount newBooking.tools = user.tools newBooking.supplies = user.supplies newBooking.description = user.description // newBooking.booking_address = user.booking_address; newBooking.unit = user.unit newBooking.quantity = user.quantity newBooking.status = 'Unconfirmed' newBooking.seeker_image.original = seekerData.profilePhoto.original newBooking.seeker_image.thumbnail = seekerData.profilePhoto.thumbnail newBooking.booking_datetime = new Date().toISOString() if (user.is_seeker_location == true) { if (user.virtual_address) { newBooking.is_seeker_location = user.is_seeker_location, newBooking.virtual_address = user.virtual_address } else { newBooking.is_seeker_location = user.is_seeker_location; newBooking.booking_address = user.booking_address; newBooking.booking_latitude = user.booking_latitude; newBooking.booking_longitude = user.booking_longitude; newBooking.booking_address1 = user.booking_address1; newBooking.booking_latitude1 = user.booking_latitude1; newBooking.booking_longitude1 = user.booking_longitude1; } } else { newBooking.is_seeker_location = user.is_seeker_location } newBooking.save(function (err, data) { if (err) { cb(err) } else { bookingData = data cb(null) } }) /*if(payload.is_product_based==false){ } /*else{ cb(null) }*/ }, function (cb) { const parallelF = [] providers.forEach(function (result) { console.log("result+++++++++++", result) parallelF.push(function (cbb) { userSchema.User.findOne({user_id: result.provider_id}, { device_token: 1, device_type: 1, role_token:1, provider_notification_flag:1 }, {lean: true}, function (err, userData) { console.log('response :: err :: ', err, " userData", userData); if (err) { cbb(err) } else { const pushCount = new SPpushcount.SPPush({ booking_id: bookingData._id, provider_id: result.provider_id, }) pushCount.save(function (err) { if (err) { cb(err) } else { const n = new Date(); const deviceDetails = []; let deviceToken = null; let deviceType = userData.device_type; let deviceTokenFound = false; if(userData.role_token && userData.role_token.length){ for(var i = 0; i < userData.role_token.length; i++){ if(userData.role_token[i].role == 'PROVIDER'){ deviceToken = userData.role_token[i].token; deviceTokenFound = true; break; } } } if(!deviceTokenFound || userData.provider_notification_flag == false){ console.log('in reverseBid Failed to Send Push......Device Token not found for ',result.provider_id," Either this provider is logged out or role_token object is not present in user collection."); cbb(null, true); }else{ const bookPayload = {}; if (user.booking_address1) { bookPayload.booking_address1 = user.booking_address1 } else { bookPayload.booking_address1 = '' } if (user.virtual_address) { bookPayload.virtual_address = user.virtual_address } else { bookPayload.virtual_address = '' } if (user.booking_address) { bookPayload.booking_address = user.booking_address } else { bookPayload.booking_address = {} } bookPayload.profile_photo = seekerData.profilePhoto, bookPayload.first_name = seekerData.first_name, bookPayload.last_name = seekerData.last_name, bookPayload.booking_type = bookingData.booking_type, bookPayload.booking_id = bookingData._id, bookPayload.booking_data = n.toISOString(), bookPayload.push_type = 'new booking' , bookPayload.ODS_type = user.ODS_type, bookPayload.is_seeker_location = user.is_seeker_location, bookPayload.is_product_based = user.is_product_based bookPayload.push_date = n.toISOString(), bookPayload.bid_amount = bidAmount /*if(user.is_product_based==false){ }*/ /* else{ bookPayload.profile_photo = seekerData.profilePhoto, bookPayload.first_name = seekerData.first_name, bookPayload.last_name = seekerData.last_name, bookPayload.booking_type = user.booking_type, bookPayload.booking_id = '', bookPayload.booking_data = n.toISOString(), bookPayload.booking_address = bookingData.booking_address, bookPayload.push_type = 'new booking' , bookPayload.ODS_type=user.ODS_type, bookPayload.is_seeker_location = user.is_seeker_location, bookPayload.is_product_based=user.is_product_based bookPayload.push_date = n.toISOString(), bookPayload.bid_amount = "" }*/ deviceDetails.push({ device_type: deviceType, device_token: deviceToken }); console.log("bookPayload data System Select", bookPayload) const pushDetailsSP = { deviceDetails: deviceDetails, text: "You Have a New Booking Available Please Confirm", payload: bookPayload } sendPush.sendPush(pushDetailsSP, "PROVIDER"); cbb(null, true) } } }); } }); }); }) console.log("paralleF", parallelF); async.parallel(parallelF, function (error, data) { if (error) { return cb(error); } else { console.log("__________", data) cb(null, data) } }); } ], function (err, data) { console.log("sbse final", err, data); if (err) { callback(err) } else { console.log("bookingData+++++++", bookingData) callback(null, bookingData) } }) } var seekerSelect = function (providers, quantity, locationId, callback) { const parallelF = []; console.log("locationId---->", locationId); console.log("providersData---->", providers); //var providerinfo = {}; providers.forEach(function (result) { console.log('result.provider_id :: ', result.provider_id); parallelF.push(function (cbb) { async.waterfall([ function (cb) { userSchema.User.findOne({user_id: result.provider_id}, { email: 1, first_name: 1, last_name: 1, mobile: 1, countryCode: 1, profilePhoto: 1, address: 1, dob:1 }, {lean: true}, function (err, data) { console.log('err~~~~~', err, ' data ~~~~~~~ ', data); if (err) { cb(err) } else { //providerinfo=data cb(null, data); } }) }, function (providerinfo, cb) { SPGigLocationMapperSchema.SPGigLocationMapper.findOne({ provider_id: result.provider_id, 'location.locationID': locationId }, {revenue: 1, pricing: 1, min_hourly_amount: 1, _id: 0}, {lean: true}, function (err, data) { console.log('err-----', err, 'pricing data initial------- ', data); if (err) { cbb(err, null) } else { if (data && data.pricing) { for (var i = 0; i < data.pricing.length; i++) { if (data.pricing[i].type == 'fixed') { console.log('seekerSelect inital price fixed : ', data.pricing[i].value); data.pricing[i].value = data.pricing[i].value * quantity; console.log('seekerSelect final price fixed : ', data.pricing[i].value); } if (data.pricing[i].type == 'hourly') { console.log('seekerSelect inital price hourly : ', data.pricing[i].value); data.pricing[i].value = data.pricing[i].value * data.min_hourly_amount; console.log('seekerSelect final price hourly : ', data.pricing[i].value); } } console.log('pricing data final :: ', data); var age = (new Date().getFullYear() - new Date(providerinfo.dob).getFullYear()); providerinfo.age = age; result.pricingDetails = data; result.providerInfo = providerinfo; cbb(null, result); } else { cbb(null ,null); /*var age = (new Date().getFullYear() - new Date(providerinfo.dob).getFullYear()); providerinfo.age = age; result.providerInfo = providerinfo; cbb(null, result);*/ } } }).sort({_id: -1}).limit(1) } ], function (err, data) { console.log("sbse final", err, data); if (err) { console.log("err+++++++", err) } else { console.log("data+++++++", data) } }) }) }); console.log("paralleF", parallelF); async.parallel(parallelF, function (error, data) { console.log('error data : ------', error, data); if (error) { console.log('error : ', error); return callback(); } else { console.log("in seekerSelect final", data); data.filter(function(val) { if(val)return val }).join(", "); console.log("in seekerSelect final ***** ", data); callback(data); } }); } var lowestDeal = function (providers, quantity, locationId, callback) { const parallelF = [] console.log("in lowestDeal -----> locationID", locationId, " quantity :",quantity," providers :: ",providers); providers.forEach(function (result) { parallelF.push(function (cbb) { async.waterfall([ function (cb) { userSchema.User.findOne({user_id: result.provider_id}, { email: 1, first_name: 1, last_name: 1, mobile: 1, countryCode: 1, profilePhoto: 1, address: 1, dob:1 }, {lean: true} , function (err, data) { console.log('err~~~~~', err, ' data ~~~~~~~ ', data); if (err) { cb(err) } else { //providerinfo=data cb(null, data); } }) }, function (providerinfo, cb) { console.log("locationID, provider_id ", locationId); SPGigLocationMapperSchema.SPGigLocationMapper.findOne({ provider_id: result.provider_id, 'location.locationID': locationId }, { revenue: 1, pricing: 1, min_hourly_amount: 1, discount: 1, _id: 0 }, {lean: true}, function (err, data) { console.log('err-----', err, 'pricing data initial------- ', data); if (err) { cbb(err, null) } else { let discount = null; if(data.discount){ discount = data.discount; } else{ discount = 0; } if (data && data.pricing && discount !=0) { for (var i = 0; i < data.pricing.length; i++) { if (data.pricing[i].type == 'fixed') { console.log('lowestDeal inital price fixed : ', data.pricing[i].value); //data.pricing[i].value = data.pricing[i].value * quantity; data.pricing[i].value = data.pricing[i].value - (discount / 100 * data.pricing[i].value); data.pricing[i].value = data.pricing[i].value * quantity; data.pricing[i].value = data.pricing[i].value.toFixed(2); console.log('lowestDeal final price fixed : ', data.pricing[i].value); } if (data.pricing[i].type == 'hourly') { console.log('lowestDeal inital price hourly : ', data.pricing[i].value); //data.pricing[i].value = data.pricing[i].value * quantity; data.pricing[i].value = data.pricing[i].value - (discount / 100 * data.pricing[i].value); data.pricing[i].value = data.pricing[i].value * data.min_hourly_amount; data.pricing[i].value = data.pricing[i].value.toFixed(2) console.log('lowestDeal final price hourly : ', data.pricing[i].value); } } console.log('pricing data final :: ', data); var age = (new Date().getFullYear() - new Date(providerinfo.dob).getFullYear()); providerinfo.age = age; result.pricingDetails = data; result.providerInfo = providerinfo; console.log("providerinfo result in gig location mapper", result); cbb(null, result); } else { // Do nothing console.log('in lowest deal , else No pricing details or discount is 0'); cbb(null , null); /*var age = (new Date().getFullYear() - new Date(providerinfo.dob).getFullYear()); providerinfo.age = age; result.providerInfo = providerinfo; cbb(null, result);*/ } } }).sort({_id: -1}).limit(1) } ], function (err, data) { console.log("sbse final", err, data); if (err) { console.log("err+++++++", err) } else { console.log("data+++++++", data) } }) }) }); console.log("paralleF", parallelF); async.parallel(parallelF, function (error, data) { if (error) { console.log('error : ', error); return callback(error); } else { console.log("in lowestDeal final", data) console.log("providers lowest deal data", providers) //callback(providers); data.filter(function(val) { if(val)return val }).join(", "); callback(data); } }); } module.exports = {}; module.exports.createSPProfile = function (payload, callback) { console.log("in model createSPProfile : payload ", payload); let dataToSave = payload let SPProfileRecord = new SPProfileSchema.SPProfile(dataToSave); SPProfileRecord.profile_id = SPProfileRecord._id; console.log(' SPProfileRecord :: ', SPProfileRecord); let savedData = null async.series([ function (cb) { if (payload.hasOwnProperty("certificate") && payload.certificate) { let fileName = payload.certificate.filename; let tempPath = payload.certificate.path; if (typeof payload.certificate !== 'undefined' && payload.certificate.length) { fileName = payload.certificate[1].filename; tempPath = payload.certificate[1].path; } console.log("tempPath", fileName) commonFunction.uploadFile(tempPath, fileName, "aLarge", function (err) { if (err) { cb(err); } else { let x = fileName; let fileNameFirst = x.substr(0, x.lastIndexOf('.')); let extension = x.split('.').pop(); SPProfileRecord.certificate = { original: AWS.s3URL + AWS.folder.aLarge + "/" + fileName, thumbnail: AWS.s3URL + AWS.folder.aLarge + "/" + fileNameFirst + "_thumb." + extension }; console.log("file upload success"); console.log("teamPhoto", SPProfileRecord.certificate); cb(null) } }); } else { cb(null); } }, function (cb) { if (payload.hasOwnProperty("licence") && payload.licence) { let fileName = payload.licence.filename; let tempPath = payload.licence.path; if (typeof payload.licence !== 'undefined' && payload.licence.length) { fileName = payload.licence[1].filename; tempPath = payload.licence[1].path; } console.log("tempPath", fileName) commonFunction.uploadFile(tempPath, fileName, "aLarge", function (err) { if (err) { cb(err); } else { let x = fileName; let fileNameFirst = x.substr(0, x.lastIndexOf('.')); let extension = x.split('.').pop(); SPProfileRecord.licence = { original: AWS.s3URL + AWS.folder.aLarge + "/" + fileName, thumbnail: AWS.s3URL + AWS.folder.aLarge + "/" + fileNameFirst + "_thumb." + extension }; console.log("file upload success"); console.log("teamPhoto", SPProfileRecord.licence); cb(null) } }); } else { cb(null); } }, function (cb) { SPProfileRecord.save(function (err, savedProfileRecord) { if (err) { responseFormatter.formatServiceResponse(err, cb); } else { savedData = savedProfileRecord console.log("in success : SPProfileRecord created successfully"); responseFormatter.formatServiceResponse(savedProfileRecord, cb, 'SP Profile created successfully', 'success', 200); } }); } ], function (err, data) { if (err) { callback(err) } else { data = savedData callback(null, data) } }) }; module.exports.AddServicesAndGigs = function (payload, callback) { console.log("payload.service_and_gigs_info.level", payload.service_and_gigs_info.gigs.level) payload.service_and_gigs_info.gigs.level = (payload.service_and_gigs_info.gigs.level).split(',') console.log("payload.service_and_gigs_info.level", payload.service_and_gigs_info.gigs.level) console.log('in SPProfile model : Payload == ', payload); // If service already exists with some gigs then push gigs info in service_and_gigs_info.gigs[] : SPProfileSchema.SPProfile.update({ provider_id: payload.provider_id, "service_and_gigs_info.service_id": payload.service_and_gigs_info.service_id, "service_and_gigs_info.gigs": payload.service_and_gigs_info.gigs.gig_id }, {$addToSet: {"service_and_gigs_info.$.gigs": payload.service_and_gigs_info.gigs}}, function (err, result) { console.log('AddServicesAndGigs result :: ', result); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { if (result.n != 0) { responseFormatter.formatServiceResponse({}, callback, 'Service and Gig added successfully to Provider profile', 'success', 200); } else { // else create a new embedded service_and_gigs_info doc with service and first gig data. SPProfileSchema.SPProfile.update({provider_id: payload.provider_id}, {$addToSet: {"service_and_gigs_info": payload.service_and_gigs_info}}, function (err, result) { console.log('$addToSet AddServicesAndGigs result :: ', result); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { if (result.n != 0) { responseFormatter.formatServiceResponse({}, callback, 'Service and Gig added successfully to Provider profile', 'success', 200); } else { responseFormatter.formatServiceResponse({}, callback, 'Provider not found', 'error', 404); } } }); } } }); }; module.exports.AddServicesAndGigs1 = function (payload, callback) { payload.service_and_gigs_info.gigs.level = (payload.service_and_gigs_info.gigs.level).split(',') console.log('in SPProfile model : Payload == ', payload); var gigFound = false; // Note - > Finding info from gig table whether this gig is product based or not. gigsSchema.Gigs.findOne({gig_id: payload.service_and_gigs_info.gigs.gig_id}, { gig_id: 1, is_product_based: 1 }, {lean: true}, function (err, gig) { console.log('in AddServicesAndGigs1 gig info returned -- gig : ', gig); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { payload.service_and_gigs_info.gigs.is_product_based = gig.is_product_based; console.log('in SPProfile model : Payload changed == ', payload); SPProfileSchema.SPProfile.findOne({ provider_id: payload.provider_id, "service_and_gigs_info.service_id": payload.service_and_gigs_info.service_id }, {service_and_gigs_info: 1}, function (err, result) { console.log('AddServicesAndGigs result :: ', result); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { if (!result) { SPProfileSchema.SPProfile.update({provider_id: payload.provider_id}, {$addToSet: {"service_and_gigs_info": payload.service_and_gigs_info}}, function (err, result) { console.log('$addToSet AddServicesAndGigs result :: ', result); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { if (result.n != 0) { responseFormatter.formatServiceResponse({}, callback, 'Service and Gig added successfully to Provider profile', 'success', 200); } else { responseFormatter.formatServiceResponse({}, callback, 'Provider not found', 'error', 404); } } }); } else { for (var i = 0; i < result.service_and_gigs_info.length; i++) { if (result.service_and_gigs_info[i].service_id == payload.service_and_gigs_info.service_id) { console.log('service found : at : ', i); for (var j = 0; j < result.service_and_gigs_info[i].gigs.length; j++) { if (result.service_and_gigs_info[i].gigs[j].gig_id == payload.service_and_gigs_info.gigs.gig_id) { gigFound = true; console.log('gigFound :: ', gigFound, "at : ", j); var crt = 'service_and_gigs_info.' + i + ".gigs." + j; var obj = {}; obj[crt] = payload.service_and_gigs_info.gigs SPProfileSchema.SPProfile.update({ provider_id: payload.provider_id, "service_and_gigs_info.service_id": payload.service_and_gigs_info.service_id, "service_and_gigs_info.gigs.gig_id": payload.service_and_gigs_info.gigs.gig_id }, {$set: obj}, function (err, result) { console.log('gig already present inside service element so update same gig : result : ', result); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { responseFormatter.formatServiceResponse(result, callback, 'Service and Gig updated successfully in Provider profile', 'success', 200); } }) break; } } break; } // need not to handle this if coz result will always be having service. } if (!gigFound) { SPProfileSchema.SPProfile.update({ provider_id: payload.provider_id, "service_and_gigs_info.service_id": payload.service_and_gigs_info.service_id }, {$push: {"service_and_gigs_info.$.gigs": payload.service_and_gigs_info.gigs}}, function (err, result) { console.log('gig not found in service element so push gig inside service element : ', result); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { if (result.n != 0) { responseFormatter.formatServiceResponse({}, callback, 'Service and Gig added successfully to Provider profile', 'success', 200); } else { responseFormatter.formatServiceResponse({}, callback, 'Service or gig not found in provider profile', 'error', 404); } } }); } } } }); } }) }; module.exports.addLocationsAndPricingToGig = function (payload, callback) { SPGigLocationMappingSchema.SPGigLocationMapper.insertMany(payload.docs, function (err, SPGigLocationMappings) { console.log('SPGigLocationMappings :: ', SPGigLocationMappings); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { callback(null, SPGigLocationMappings) } }); }; module.exports.updateLocationsAndPricingToGig = function (payload, callback) { console.log('payload in updateLocationsAndPricingToGig :: ',payload); if(payload.docs && payload.docs.length != 0 && payload.docs[0].provider_id){ var provider_id = payload.docs[0].provider_id; SPGigLocationMappingSchema.SPGigLocationMapper.remove({provider_id : provider_id},function(err,numberRemoved){ if(err){ callback(err); }else{ console.log("in updateLocationsAndPricingToGig inside remove call back" + numberRemoved); SPGigLocationMappingSchema.SPGigLocationMapper.insertMany(payload.docs, function (err, SPGigLocationMappings) { console.log('SPGigLocationMappings :: ', SPGigLocationMappings); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { callback(null, SPGigLocationMappings) } }); } }); } /*var count = 0; for(var i = 0 ; i< payload.docs.length; i++){ if(payload.docs[i].doc_id){ const id = mongoose.Types.ObjectId(payload.docs[i].doc_id); delete payload.docs[i]["doc_id"]; SPGigLocationMappingSchema.SPGigLocationMapper.findOneAndUpdate({_id:id},payload.docs[i],{new:true},function(err,data){ if(err){ console.log('Error Occurred findOneAndUpdate in updateLocationsAndPricingToGig : ',err); count++; console.log('in err : count :: ',count); } else{ console.log(" in updateLocationsAndPricingToGig Pricing and Revenue of location for gig updated successfully ------------",data); count++; console.log('in update success : count :: ',count); } }) }else{ SPGigLocationMappingSchema.SPGigLocationMapper.insertOne(payload.docs[i]).then(function(result) { console.log('in updateLocationsAndPricingToGig ---result of insert new location delivery price and revenue for gig :: ',result); count++; console.log('in insert success : count :: ',count); }) } console.log('count after iteration ',i," is :: ",count); } if(count == payload.docs.length){ callback(null , {"msg" : "All location docs updated succesfully"}); }else{ callback(null , {"msg" : "Something went wrong."}); }*/ }; module.exports.getAllProvidersByGigId = function (service_id, gig_id, latitude, longitude, callback) { var nearByProviderByGigId = [{ $geoNear: { near: {type: "Point", coordinates: [longitude, latitude]}, distanceField: 'dist.calculated', maxDistance: 50000, query: { service_and_gigs_info: { "$elemMatch": { service_id: service_id, "gigs": { "$elemMatch": {gig_id: gig_id} } } } }, spherical: true } }, { $sort: { dist: 1 } }, { $limit: 50 }, { $project: { 'provider_id': 1, 'provider_email': 1, 'first_name': 1, 'last_name': 1, 'geometry': 1, 'ratings': 1, 'description': 1, mode_of_transport:1 } }]; SPProfileSchema.SPProfile.aggregate(nearByProviderByGigId, function (err, providers) { console.log("providers", providers) if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { var parallel = []; var eta = []; var minDistance = []; let mode_of_transport=[] if (providers && providers.length > 0) { for (var i = 0; i < providers.length; i++) { let count = 0 count += 1 console.log("count", count) console.log("providers[i].geometry", providers[i].geometry) const dataToPush = providers[i].geometry.coordinates[1] + "," + providers[i].geometry.coordinates[0]; parallel.push(dataToPush) if(providers[i].mode_of_transport){ mode_of_transport.push(providers[i].mode_of_transport) } console.log("dataToPush", dataToPush) } console.log("parallel", parallel) const latlong = latitude + ',' + longitude console.log("latlong", latlong) var origins = [latlong]; console.log("origins array", origins) var destinations = parallel; console.log("destinations>>>>>>", destinations) console.log("providers[i].mode_of_transport",mode_of_transport) //var ETA = {}; distance.key('AIzaSyDBPGL4OzGCJ7De1wCRPqsO9cD8w6eOEIA'); /*if(mode_of_transport.length == 0){ mode_of_transport = 'driving'; }else { distance.mode(mode_of_transport[0]); }*/ //distance.key('AIzaSyBTV_8yxiceJSOdyoFggFzhfzxEexgEtPo'); distance.mode('driving'); distance.matrix(origins, destinations, function (err, distances) { if (err) { console.log('error in distance matrix api : ', err); callback(err); } else { if (distances.error_message) { console.log('Google api failed to find distances : Response is not eta filtered :::::'); responseFormatter.formatServiceResponse({providers: providers}, callback, "Providers Fetched Successfully", "success", 200); //ETA = providers; } else { console.log("distances", distances); var elements = distances.rows[0].elements; console.log('elements :::: ',elements); //var eta=distances.rows[0].elements; for (var j = 0; j < elements.length; j++) { console.log("elements[j].duration", elements[j].duration.value) eta.push(elements[j].duration.value); minDistance.push(elements[j].distance.value); } console.log("eta:", eta); var min = eta[0]; var minIndex = 0; for (var i = 1; i < eta.length; i++) { if (eta[i] < min) { minIndex = i - 1; min = eta[i]; } } var minDis = minDistance[0]; var minDistanceIndex = 0; for (var i = 1; i < minDistance.length; i++) { if (minDistance[i] < minDis) { minDistanceIndex = i - 1; minDis = minDistance[i]; } } console.log("min & index:", minIndex, min) //providers.splice=(index,0,parallel); //console.log("providers[index]",providers[index]) //providers[minIndex].eta=min; var ETA = {"eta": (min / 60), "minDistance": (minDis / 1000), providers} responseFormatter.formatServiceResponse(ETA, callback, "min eta added.", "success", 200); } } }) } else { responseFormatter.formatServiceResponse({providers: []}, callback, "No providers Found.", "error", 404); } } }); }; var isBookingAcceptedBySP = function (bookingID, callback) { const id = mongoose.Types.ObjectId(bookingID); bookingSchema.Booking.findOne({_id: id, is_accepted: true}, function (err, booking) { console.log('Booking details returned----------------', booking); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback, 'Error Occurred Please Try After Some Time', 'error', 500); } else { console.log("is bookingAccepted>>> booking", booking) if (!booking) { callback(null, false); //responseFormatter.formatServiceResponse({}, callback ,'service provider is busy at this moment please try again later','success',200); } else { callback(null, booking); } //if(booking){ // responseFormatter.formatServiceResponse(booking, callback ,'booking already accepted by one of the SP','success',200); // // callback(null,booking) //} // else{ // responseFormatter.formatServiceResponse({}, callback ,'No Providers Found Nearby Please Try After Some Time','error',404); // // callback(null,{}) //} } }); } var findEtaWieghtage = function(etaFilter,etaSlabs){ for(var i =0; i< etaSlabs.eta_priority_ranges.length; i++){ for(var j = 0 ; j< etaFilter.length; j++){ if ((i == 0) && (etaFilter[j].eta) / 60 >= etaSlabs.eta_priority_ranges[i].min && (etaFilter[j].eta) / 60 < etaSlabs.eta_priority_ranges[i].max) { console.log('etaSlabs.eta_priority_ranges[i].min : ',etaSlabs.eta_priority_ranges[i].min,' etaSlabs.eta_priority_ranges[i].max : ',etaSlabs.eta_priority_ranges[i].max,' etaFilter[j].eta : ',(etaFilter[j].eta)/60); console.log('in 1st Slab'); etaFilter[j].weight = etaSlabs.eta_priority_ranges[i].weight; }else if((i == 1) && (etaFilter[j].eta) / 60 >= etaSlabs.eta_priority_ranges[i].min && (etaFilter[j].eta) / 60 < etaSlabs.eta_priority_ranges[i].max){ console.log('etaSlabs.eta_priority_ranges[i].min : ',etaSlabs.eta_priority_ranges[i].min,' etaSlabs.eta_priority_ranges[i].max : ',etaSlabs.eta_priority_ranges[i].max,' etaFilter[j].eta : ',(etaFilter[j].eta)/60); console.log('in 2nd Slab'); etaFilter[j].weight = etaSlabs.eta_priority_ranges[i].weight; }else if((i == 2) && (etaFilter[j].eta) / 60 >= etaSlabs.eta_priority_ranges[i].min && (etaFilter[j].eta) / 60 < etaSlabs.eta_priority_ranges[i].max){ console.log('etaSlabs.eta_priority_ranges[i].min : ',etaSlabs.eta_priority_ranges[i].min,' etaSlabs.eta_priority_ranges[i].max : ',etaSlabs.eta_priority_ranges[i].max,' etaFilter[j].eta : ',(etaFilter[j].eta)/60); console.log('in 3th Slab'); etaFilter[j].weight = etaSlabs.eta_priority_ranges[i].weight; }else if((i == 3) && (etaFilter[j].eta) / 60 >= etaSlabs.eta_priority_ranges[i].min && (etaFilter[j].eta) / 60 < etaSlabs.eta_priority_ranges[i].max){ console.log('etaSlabs.eta_priority_ranges[i].min : ',etaSlabs.eta_priority_ranges[i].min,' etaSlabs.eta_priority_ranges[i].max : ',etaSlabs.eta_priority_ranges[i].max,' etaFilter[j].eta : ',(etaFilter[j].eta)/60); console.log('in 4th Slab'); etaFilter[j].weight = etaSlabs.eta_priority_ranges[i].weight; }else if((i == 4) && (etaFilter[j].eta) / 60 >= etaSlabs.eta_priority_ranges[i].min && (etaFilter[j].eta) / 60 < etaSlabs.eta_priority_ranges[i].max){ console.log('etaSlabs.eta_priority_ranges[i].min : ',etaSlabs.eta_priority_ranges[i].min,' etaSlabs.eta_priority_ranges[i].max : ',etaSlabs.eta_priority_ranges[i].max,' etaFilter[j].eta : ',(etaFilter[j].eta)/60); console.log('in 5th Slab'); etaFilter[j].weight = etaSlabs.eta_priority_ranges[i].weight; }else if((i == 5) && (etaFilter[j].eta) / 60 >= etaSlabs.eta_priority_ranges[i].min && (etaFilter[j].eta) / 60 < etaSlabs.eta_priority_ranges[i].max){ console.log('etaSlabs.eta_priority_ranges[i].min : ',etaSlabs.eta_priority_ranges[i].min,' etaSlabs.eta_priority_ranges[i].max : ',etaSlabs.eta_priority_ranges[i].max,' etaFilter[j].eta : ',(etaFilter[j].eta)/60); console.log('in 6th Slab'); etaFilter[j].weight = etaSlabs.eta_priority_ranges[i].weight; } } } return etaFilter; } var findRatingWieghtage = function(etaFilter , ratingSlabs){ var avgRating = 0; var maxRating = 5; for(var i = 0 ; i< etaFilter.length; i++){ var sumOfRatings = 0; if (etaFilter[i].ratings && etaFilter[i].ratings.length != 0) { console.log('ratings available'); for(var j = 0 ; j < etaFilter[i].ratings.length ; j++ ){ console.log("etaFilter[i].ratings[j] :: ",etaFilter[i].ratings[j]); sumOfRatings += Number(etaFilter[i].ratings[j]); } console.log('sumOfRatings : ',sumOfRatings) avgRating = sumOfRatings / etaFilter[i].ratings.length; console.log('avgRating for :: ',etaFilter[i].first_name," is :: ", avgRating); if(etaFilter[i].weight){ etaFilter[i].weight += (Number(avgRating)/Number(maxRating))* Number(ratingSlabs.total_weight); console.log('Totaal Weight ' ,Number(ratingSlabs.total_weight)); } else { etaFilter[i].weight = (Number(avgRating)/Number(maxRating))*Number(ratingSlabs.total_weight); } }else { console.log("rating not available for etaFilter[i].ratings[j] :: 5 is picked deafut case"); if(etaFilter[i].weight){ etaFilter[i].weight+=5; } else { etaFilter[i].weight = 5; } } } return etaFilter; } var findSkillWieghtage = function(etaFilter , gig_id, service_id , skillSlabs){ for(var i = 0 ; i< etaFilter.length; i++) { for (var j = 0; j < etaFilter[i].service_and_gigs_info.length; j++) { for (var k = 0; k < etaFilter[i].service_and_gigs_info[j].gigs.length; k++) { console.log('etaFilter[i].service_and_gigs_info.gigs', etaFilter[i].service_and_gigs_info[j].gigs[k]); if(etaFilter[i].service_and_gigs_info[j].gigs[k].gig_id == gig_id){ console.log('etaFilter[i].service_and_gigs_info[j].gigs[k].level',etaFilter[i].service_and_gigs_info[j].gigs[k].level[0]); for(var z = 0; z < skillSlabs.skill_priority_ranges.length; z++){ if(etaFilter[i].service_and_gigs_info[j].gigs[k].level[0] == skillSlabs.skill_priority_ranges[z].name){ console.log('skill name matched :: '); if(etaFilter[i].weight){ etaFilter[i].weight += skillSlabs.skill_priority_ranges[z].weight; } else { etaFilter[i].weight = skillSlabs.skill_priority_ranges[z].weight; } } } } } }console.log("************************ Chak De***************************",etaFilter[i].weight); } return etaFilter; } var findJobAcceptanceWieghtage = function(etaFilter , jobAcceptanceSlabs){ for(var i = 0 ; i< etaFilter.length; i++){ var acceptancePercentage = 0; if(etaFilter[i].acceptance_count && etaFilter[i].rejectance_count && (etaFilter[i].acceptance_count + etaFilter[i].rejectance_count)!=0) { acceptancePercentage = Number(etaFilter[i].acceptance_count)*100/(Number(etaFilter[i].acceptance_count) + Number(etaFilter[i].rejectance_count)); console.log('acceptancePercentage for :: ',etaFilter[i].first_name," is :: ", acceptancePercentage); if(etaFilter[i].weight){ etaFilter[i].weight += (acceptancePercentage/100)*Number(jobAcceptanceSlabs.total_weight); } else { etaFilter[i].weight = (acceptancePercentage/100)*Number(jobAcceptanceSlabs.total_weight); } } else { console.log("Not accepted and Rejected any requests :: 5 is picked deafut case"); if(etaFilter[i].weight){ etaFilter[i].weight+=5; } else { etaFilter[i].weight = 5; } } } return etaFilter; } var findPriceWeightage = function (etaFilter, gig_id, locationId , totalWeight, callback) { console.log('in findPriceWeightage :: etaFilter :, gig_id :, locationId :, totalWeight :',etaFilter, gig_id, locationId , totalWeight); const parallelF = []; etaFilter.forEach(function (result) { console.log('result.provider_id :: ', result.provider_id); parallelF.push(function (cbb) { async.waterfall([ function (cb) { gigsSchema.Gigs.findOne({gig_id: gig_id}, { gig_id: 1, pricing:1, number_of_hours:1 }, {lean: true}, function (err, data) { if (err) { cb(err) } else { console.log("gigData =", data); cb(null , data); } }) }, function (gigPriceInfo, cb) { console.log('in waterfall gigPriceInfo :: ',gigPriceInfo); SPGigLocationMapperSchema.SPGigLocationMapper.findOne({ provider_id: result.provider_id, 'location.locationID': locationId }, { pricing: 1, min_hourly_amount: 1, _id: 0}, {lean: true}, function (err, data) { console.log('in findPriceWeightage err-----', err, 'pricing data initial------- ', data); if (err) { cbb(err, null) } else { if (data && data.pricing) { var priceArray = []; var fixedPrice = 0; var hourlyPrice = 0; var fixedMedianPrice = 0; var hourlyMedianPrice = 0; var fixedWt = 0; var hourlyWt = 0; for (var i = 0; i < data.pricing.length; i++) { if (data.pricing[i].type == 'fixed') { fixedPrice = data.pricing[i].value ; console.log('in findPriceWeightage priceArray fixed : ', fixedPrice); } if (data.pricing[i].type == 'hourly') { hourlyPrice = data.pricing[i].value * 1; console.log('in findPriceWeightage priceArray hourly : ', hourlyPrice); } } for(var i = 0; i< gigPriceInfo.pricing.length; i++){ if (gigPriceInfo.pricing[i].type == 'fixed') { fixedMedianPrice = gigPriceInfo.pricing[i].median ? Number(gigPriceInfo.pricing[i].median) : 0; console.log('in findPriceWeightage priceArray fixed : ', fixedMedianPrice); } if (gigPriceInfo.pricing[i].type == 'hourly') { hourlyMedianPrice = gigPriceInfo.pricing[i].median ? Number(gigPriceInfo.pricing[i].median) * 1 : 0; console.log('in findPriceWeightage priceArray hourly : ', hourlyMedianPrice); } } var priceVariance = [1-((Number(fixedPrice) - Number(fixedMedianPrice))/Number(fixedMedianPrice))]; if(priceVariance < 0) { priceVariance = 0; } fixedWt = Number(priceVariance) * Number(totalWeight); var hourlyVariance = [1-((Number(hourlyPrice) - Number(hourlyMedianPrice))/Number(hourlyMedianPrice))]; if(hourlyVariance < 0) { hourlyVariance = 0; } hourlyWt = hourlyVariance * Number(totalWeight); var avgWt=(Number(fixedWt) + Number(hourlyWt))/2; if(result.weight){ result.weight += avgWt ; } else { result.weight = avgWt; } cbb(null, result); } else { if(result.weight){ result.weight += 0; } else { result.weight = 0; } cbb(null, result); } } }).sort({_id: -1}).limit(1) } ], function (err, data) { console.log("sbse final", err, data); if (err) { console.log("err+++++++", err) } else { console.log("data+++++++", data) } }) }) }); console.log("paralleF", parallelF); async.parallel(parallelF, function (err, data) { console.log('error data : ------', err, data); if (err) { console.log('error : ', err); return callback(err); } else { console.log("in findPriceWeightage final", data) callback(err , data); } }); } function addZero(i) { if (i < 10) { i = "0" + i; } return i; } module.exports.filterProviders = function (payload, callback) { let filters = { latitude: payload.location.latitude, longitude: payload.location.longitude, service_id: payload.service_id, gig_id: payload.gig_id, eta_min_val: payload.eta.min_val, eta_max_val: payload.eta.max_val, tool_flag: [payload.tools], SP_level_array: payload.SP_level, supplies: [payload.supplies] }; if (!payload.tools || payload.tools == false) { filters.tool_flag = [true, false] } if (!payload.supplies || payload.supplies == false) { filters.supplies = [true, false] } let gigs = { "$elemMatch": { gig_id: filters.gig_id, tools: {$in: filters.tool_flag}, supplies: {$in: filters.supplies}, level: {$in: filters.SP_level_array} } }; // let gig_specific_param_element_query = {}; if (payload.attributes && payload.attributes.length > 0) { console.log("condition only when gsp screen has params") for (var i = 0; i < payload.attributes.length; i++) { var jsonObjectKey = "gig_specific_param." + payload.attributes[i].key; console.log('jsonObjectKey ::: ', jsonObjectKey); gigs["$elemMatch"][jsonObjectKey] = {$in: payload.attributes[i].value}; if (payload.attributes[i].type == 'slider') { console.log('payload.attributes[i].value[1] ::: ', payload.attributes[i].value[1]); gigs["$elemMatch"][jsonObjectKey] = { $elemMatch: { $gte: parseInt(payload.attributes[i].value[0]), $lte: parseInt(payload.attributes[i].value[1]) } }; } } } console.log('filters : ', filters); console.log("gigs filter", gigs) //console.log('gig_specific_param_element_query : ', gig_specific_param_element_query); adminGlobalDataSchema.AdminGlobalData.findOne({}, {}, {lean: true}, function (err, adminGolbalData) { if (err) { console.log('error in addGlobalData :: ', err); responseFormatter.formatServiceResponse(err, callback); } else { console.log('result from AdminGlobalData before filtering SP : result : ', adminGolbalData); var SPProviderByFilters = [{ $geoNear: { near: {type: "Point", coordinates: [filters.longitude, filters.latitude]}, distanceField: 'dist.calculated', maxDistance: adminGolbalData.filter_radius ? Number(adminGolbalData.filter_radius)*1000 : 50000, query: { service_and_gigs_info: { "$elemMatch": { service_id: filters.service_id, gigs: gigs, //'gigs.booking_type': {$elemMatch: {$eq: payload.booking_type}} } } }, spherical: true } }, { $sort: { dist: 1 } }, { $limit: 50 }, { $project: { 'provider_id': 1, 'provider_email': 1, 'first_name': 1, 'last_name': 1, 'geometry': 1, 'ratings': 1, 'acceptance_count': 1, 'rejectance_count': 1, 'description': 1, 'service_and_gigs_info.gigs': 1, 'average_rating': 1, 'is_available':1, 'insurance':1, 'gender' :1, 'i_can_travel':1, 'discount':1, 'reviews':1 } }, { $lookup: { from: "SPtimeslots", localField: "provider_id", foreignField: "provider_id", as: "slotData" } }, { $project: { 'provider_id': 1, 'provider_email': 1, 'first_name': 1, 'last_name': 1, 'geometry': 1, 'ratings': 1, 'acceptance_count': 1, 'rejectance_count': 1, 'description': 1, 'mode_of_transport': 1, 'service_and_gigs_info.gigs': 1, 'slotData': {'$filter': { input: '$slotData', as: 'slotsArray', cond: { "$eq": ["$$slotsArray.gig_id", filters.gig_id] } }}, 'average_rating': 1, 'is_available':1, 'insurance':1, 'gender' :1, 'i_can_travel':1, 'discount':1, 'reviews':1 } } ]; console.log('*******', JSON.stringify(SPProviderByFilters[0]['$geoNear'])); let user = { seeker_id: payload.seeker_id, seeker_name: payload.seeker_name, seeker_device_token: payload.seeker_device_token, seeker_device_type: payload.seeker_device_type, is_seeker_location: payload.is_seeker_location, booking_address: payload.booking_address, booking_latitude: payload.booking_latitude, booking_longitude: payload.booking_longitude, booking_address1: payload.booking_address1, booking_latitude1: payload.booking_latitude1, booking_longitude1: payload.booking_longitude1, ODS_type: payload.ODS_type, gig_id: payload.gig_id, service_id: payload.service_id, tools: payload.tools, supplies: payload.supplies, description: payload.description, unit: payload.unit, quantity: payload.quantity, virtual_address: payload.virtual_address, is_product_based: payload.is_product_based, level: payload.SP_level } SPProfileSchema.SPProfile.aggregate(SPProviderByFilters, function (err, providers) { console.log("providers are:", providers); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { if (providers && providers.length == 0) { console.log("no providers found", providers.length) responseFormatter.formatServiceResponse(providers, callback, "No providers Found.", "error", 404); } else { //responseFormatter.formatServiceResponse(providers, callback, "Temperory providers Found.", "success", 200); // Now filter those providers whose availabilty is on var unavailableProviders = []; for (var i = 0; i < providers.length; i++) { if (providers[i].is_available) { console.log('provider is available :: name :', providers[i].first_name, " is_available : ", providers[i].is_available); } else { unavailableProviders.push(providers[i]); providers.splice(i, 1); } } // This block will be executing in async manner to send push in parallel process. sendPushToUnavailableProviders(unavailableProviders, function (err, pushResult) { if (err) { console.log('sending notification to unavailable providers failed'); } else { console.log('sending notification to unavailable providers successfull -- result ', pushResult); } }); if(providers.length == 0){ console.log('No Providers are available now. Please try sone other time.We will notify all unavailable providers about this booking request.'); return responseFormatter.formatServiceResponse(providers, callback, "No Providers are available now. Please try sone other time.", "error", 404); } var etaFilter = []; var i_can_travel_filter = []; var parallel = []; var eta = []; var distancesArray = []; var providerTemp = []; var providerTempIndex = 0; if (providers && providers.length > 0) { if(payload.booking_type == 'SCH'){ var dayList = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"]; console.log('In SCH payload.sch_booking_date : ',payload.sch_booking_date); var booking_date = new Date(payload.sch_booking_date); var booking_day = booking_date.getDay(); var current_day = dayList[booking_day]; var booking_slot = payload.sch_booking_slot; console.log('In SCH payload.sch_booking_slot : ',payload.sch_booking_slot); var current_slot = Number(booking_slot); console.log('In SCH current_slot : ',current_slot); // For now , current time slot used , Ask Nandan for time slot in SCH booking type /*if (payload.time_offset) { current_slot = Number((new Date().getHours().toString()) + ((new Date().getMinutes()) >= 10 ? new Date().getMinutes().toString() : '0' + new Date().getMinutes().toString())); current_slot = current_slot + Number(payload.time_offset); console.log("current slot", Number(new Date().getHours().toString() + ((new Date().getMinutes()) > 10 ? new Date().getMinutes().toString() : '0' + new Date().getMinutes().toString())), Number(payload.time_offset)) } else { current_slot = Number(new Date().getHours().toString() + new Date().getMinutes().toString()) + Number(530); } */ }else{ var today = new Date(); var day = today.getDay(); var dayList = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"]; var current_day = dayList[day]; var current_slot; console.log(new Date().getHours().toString()); console.log(new Date().getMinutes().toString()); console.log('0+new Date().getMinutes().toString() :: ', '0' + new Date().getMinutes().toString()); console.log("payload time offset", payload.time_offset); if (payload.time_offset) { current_slot = Number((new Date().getHours().toString()) + ((new Date().getMinutes()) >= 10 ? new Date().getMinutes().toString() : '0' + new Date().getMinutes().toString())); current_slot = current_slot + Number(payload.time_offset); console.log("current slot", Number(new Date().getHours().toString() + ((new Date().getMinutes()) > 10 ? new Date().getMinutes().toString() : '0' + new Date().getMinutes().toString())), Number(payload.time_offset)) } else { current_slot = Number(new Date().getHours().toString() + new Date().getMinutes().toString()) + Number(530); } } //Number(today.getHours().toString()+today.getMinutes().toString()); //1500;//Number(addZero(today.getHours())+addZero(today.getMinutes())); console.log("Current Day :: ", current_day, " Current slot :: ", current_slot); for (var i = 0; i < providers.length; i++) { // Now filter the already filtered providers on current day and time slots. console.log('providers.name :: index i ',i," ---> ",providers[i].first_name); if (providers[i].slotData && providers[i].slotData.length != 0 && providers[i].slotData[0].slots && providers[i].slotData[0].slots.length != 0) { console.log('provider[i].timeSlots :::: ', providers[i].slotData[0].slots); for (var j = 0; j < providers[i].slotData[0].slots.length; j++) { console.log("Time Slot log :::",providers[i].slotData[0].slots[j].day ," ",current_day ); console.log("Time Slot log 2 :::",Number(providers[i].slotData[0].slots[j].start_time) ," ",current_slot," ",Number(providers[i].slotData[0].slots[j].end_time)); if (providers[i].slotData[0].slots[j].day == current_day && Number(providers[i].slotData[0].slots[j].start_time) <= Number(current_slot) && Number(providers[i].slotData[0].slots[j].end_time) >= Number(current_slot)) { console.log('provider slot matched.'); providerTemp[providerTempIndex] = providers[i]; const dataToPush = providerTemp[providerTempIndex].geometry.coordinates[1] + "," + providerTemp[providerTempIndex].geometry.coordinates[0]; parallel.push(dataToPush); providerTempIndex++; console.log('providerTemp :: ', providerTemp); console.log('parallel :: ', parallel); break; } } } } if (providerTemp.length == 0) { console.log('No providers found after filtering with current slot and current day : '); //providerTemp = providers; return responseFormatter.formatServiceResponse(providerTemp, callback, "No providers found after filtering with current slot and current day", "error", 404); } const latlong = user.booking_latitude + ',' + user.booking_longitude var origins = [latlong]; console.log("latlong:", latlong); var destinations = parallel; distance.key('AIzaSyDBPGL4OzGCJ7De1wCRPqsO9cD8w6eOEIA'); if (providerTemp.mode_of_transport) { distance.mode(providerTemp.mode_of_transport); } //distance.key('AIzaSyBTV_8yxiceJSOdyoFggFzhfzxEexgEtPo'); distance.matrix(origins, destinations, function (err, distances) { console.log('distances:', distances); if (err) { callback(err); } else { if (distances.error_message) { console.log('Google api failed to find distances : Response is not eta filtered :::::'); etaFilter = providerTemp; } else { var elements = distances.rows[0].elements; console.log("elements:", elements); for (var j = 0; j < elements.length; j++) { console.log("elements[j].duration", elements[j].duration) eta.push(elements[j].duration.value); distancesArray.push(elements[j].distance.value); } console.log('eta ::::: ', eta, " distances :::: ",distancesArray); for (var k = 0; k < providerTemp.length; k++) { providerTemp[k].eta = eta[k]; providerTemp[k].distance_from_current_booking = distancesArray[k]; } console.log('eta and distances punched to providers :: ', providerTemp); // Now filter with eta min and max value for (var z = 0; z < providerTemp.length; z++) { if (providerTemp[z].eta >= filters.eta_min_val && providerTemp[z].eta <= filters.eta_max_val) { etaFilter.push(providerTemp[z]); } } console.log('without i_can_travel filtered providers :', etaFilter); //Now filter with i_can_travel param for (var z = 0; z < etaFilter.length; z++) { if ( Number(etaFilter[z].i_can_travel) >= Number(etaFilter[z].eta) ) { i_can_travel_filter.push(etaFilter[z]); } } // now make etafiltered data equals to i_can_travel filtered data etaFilter = i_can_travel_filter; etaFilter.sort(function (a, b) { return parseFloat(a.eta) - parseFloat(b.eta); }); console.log('sorted etaFilter : ', etaFilter); if (etaFilter.length == 0) { console.log("No Provider present in min and max range of ETA.............."); return responseFormatter.formatServiceResponse(providerTemp, callback, "No Provider present in min and max range of ETA", "error", 404); } } if (payload.ODS_type == "System Select") { var self = this; //console.log("inside System Select filtered providers:", etaFilter); adminGlobalDataSchema.AdminGlobalData.findOne({}, {}, {lean: true}, function (err, adminGolbalData) { if (err) { console.log('error in addGlobalData :: ', err); responseFormatter.formatServiceResponse(err, callback); } else { console.log("in filter api AdminGlobalData for finding wieghtage data :: ", adminGolbalData); if (adminGolbalData.eta && adminGolbalData.eta.is_active) { etaFilter = findEtaWieghtage(etaFilter, adminGolbalData.eta); console.log('without sorted weightage ETA filtered Provider ::::::', etaFilter); } if (adminGolbalData.skill_level && adminGolbalData.skill_level.is_active) { etaFilter = findSkillWieghtage(etaFilter, user.gig_id, user.service_id, adminGolbalData.skill_level); console.log('without sorted weightage skill filtered Provider ::::::', etaFilter); } if (adminGolbalData.rating && adminGolbalData.rating.is_active) { etaFilter = findRatingWieghtage(etaFilter, adminGolbalData.rating); console.log('without sorted weightage Rating filtered Provider ::::::', etaFilter); } if (adminGolbalData.job_acceptance && adminGolbalData.job_acceptance.is_active) { etaFilter = findJobAcceptanceWieghtage(etaFilter, adminGolbalData.job_acceptance); console.log('without sorted weightage Job Acceptance filtered Provider ::::::', etaFilter); } //if(adminGolbalData.price && adminGolbalData.price.is_active) var locationData = {}; async.waterfall([ function (cb) { geocoder.reverseGeocode(payload.location.latitude, payload.location.longitude, function (err, data) { if (err) { cb(err); } else { console.log("location Data", data.results[0].address_components); var addressData = data.results[0].address_components; addressData.forEach(function (val, index) { if (val.types[0] == "administrative_area_level_1") { locationData.locationShort = val.short_name; } if (val.types[0] == "country") { locationData.countryName = val.short_name; } }); console.log('===>', locationData); cb(null, locationData); } }); }, function (locationData, cb) { stateCodesSchema.CodeSchema.findOne({ code: locationData.locationShort, country: locationData.countryName }, {}, {lean: true}, function (err, location) { console.log('Location Found in our Database-----------', location); if (err) { cb(err) } else { cb(null, location); } }) } ], function (err, locationData) { console.log('data in final async waterfall getting location Id : ', locationData); if (err) { callback(err) } else { findPriceWeightage(etaFilter, user.gig_id, locationData._id, adminGolbalData.price.total_weight, function (err, etaFilter) { if (err) { console.log('error in findPriceWeightage :: ', err); responseFormatter.formatServiceResponse(err, callback); } else { console.log('without sorted weightage price filtered Provider ::::::', etaFilter); etaFilter.sort(function (a, b) { return parseFloat(b.weight) - parseFloat(a.weight); }); console.log('sorted on weightage Provider :::::::', etaFilter); var waitingTImeInMinutes = 2; var etaBasedSortedArray = []; var sortedByPrice, sortedBySkill, sortedByRating, sortedByJobAcceptance; var sortByPrice, sortBySkill, sortByRating, sortByJobAcceptance; var waitUpto = Number(new Date().getTime()) + Number(2 * 60 * 60 * 10); var now = 0; var timeToWaitInMinutes = 1; var c = []; async.waterfall([ function (cb) { createBookingForSystemSelect(user, function (err, bookingData) { if (err) { cb(err); } else { console.log('in System select waterfall booking created....'); c.push(bookingData); cb(null, bookingData); } }) }, function (bookingData, cb) { console.log('bookingData got in waterfall 2nd stage:: ', bookingData); //console.log('data.eta.eta_priority_ranges :: ', data.eta.eta_priority_ranges[i]); for (var j = 0; j < etaFilter.length; j++) { (function (b) { var execAt = timeToWaitInMinutes * b * 60 * 1e3; setTimeout(function () { console.log('etaFilter[j]', etaFilter[b].first_name, "------", etaFilter[b].eta / 60); console.log('--- In Wait Time -------'); console.log("-------------------", b); now = new Date().getTime(); if (now > waitUpto) { console.log('current time ',now," and waitUpto Time : ",waitUpto); console.log('Booking Failed. Time Over......') //mark booking as failed } else { isBookingAcceptedBySP(bookingData._id, function (err, bookingFound) { if (err) { console.log('Error occurred :::: inSPprofileModel systemselect : '); // cb(err); } else { if (!bookingFound) { //sendpush to next SP notifySPForSystemSelect(etaFilter[b], user, bookingData, function (err, result) { // cb(null, result); }); } else { console.log('Booking accepted by SP. So stop sending push and send response'); // cb(null, bookingFound); } } }); } // End Else //}// End IF console.log("************************************************* After Time out**********************************"); }, execAt) // setTimeOut end })(j); }//End For Loop return cb(null); } // waterfall 2nd function ends ], function (err, systemSelectResult) { console.log('data in final async series getting location Id : ', systemSelectResult, " err :: ", err); if (err) { callback(err) } else { callback(null, c); //responseFormatter.formatServiceResponse(systemSelectResult, callback, '', 'success', 200); } }) } }) } }); }// admin global data else completed }); // admin global data callback result } // SYSTEM SELECT END else if (payload.ODS_type == 'Seeker Select') { // check is_available flag and filter provider array into two parts var locationData = {}; async.waterfall([ function (cb) { geocoder.reverseGeocode(payload.location.latitude, payload.location.longitude, function (err, data) { if (err) { cb(err); } else { // By Chandan Sharma console.log("location Data", data.results[0].address_components); var addressData = data.results[0].address_components; addressData.forEach(function (val, index) { if (val.types[0] == "administrative_area_level_1") { locationData.locationShort = val.short_name; } if (val.types[0] == "country") { locationData.countryName = val.short_name; } }); console.log('===>', locationData); cb(null, locationData); } }); }, function (locationData, cb) { stateCodesSchema.CodeSchema.findOne({ code: locationData.locationShort, country: locationData.countryName }, {}, {lean: true}, function (err, location) { console.log('-----------', location); if (err) { cb(err) } else { cb(null, location); } }) } ], function (err, data) { console.log('data in final async series getting location Id : ', data); if (err) { callback(err) } else { if (!data) { seekerSelect(etaFilter, payload.quantity, null, function (result) { //if (result) { //responseFormatter.formatServiceResponse(result, callback ,'SP list fetched successfully','success',200); callback(null, result); //} }) } else { seekerSelect(etaFilter, payload.quantity, data._id, function (result) { //if (result) { // responseFormatter.formatServiceResponse(result, callback ,'SP list fetched successfully','success',200); callback(null, result); //} }) } } }) } else if (payload.ODS_type == 'Reverse Bid') { reverseBid(etaFilter, user, payload.bid_amount, function (err, result) { console.log("result Reverse Bid", result) if (result) { console.log("data._id++++++++++++Reverse Bid", result._id) //Set timeout timer to be controlled by admin constantsSchema.constantSchema.find({}, {booking_timer: 1}, {lean: true}, function (err, constants) { const timer = Number(constants[0].booking_timer + 15000) console.log("timer", timer) setTimeout(function () { bookingModel.isBookingAcceptedBySP(result._id, callback) }, timer); }) } }); } else { var locationData = {}; async.waterfall([ function (cb) { geocoder.reverseGeocode(payload.location.latitude, payload.location.longitude, function (err, data) { if (err) { cb(err) } else { // By Chandan Sharma console.log("location Data", data.results[0].address_components); var addressData = data.results[0].address_components; addressData.forEach(function (val, index) { if (val.types[0] == "administrative_area_level_1") { locationData.locationShort = val.short_name; } if (val.types[0] == "country") { locationData.countryName = val.short_name; } }); console.log('===>', locationData); cb(null, locationData); } }); }, function (locationData, cb) { stateCodesSchema.CodeSchema.findOne({ code: locationData.locationShort, country: locationData.countryName }, {}, {lean: true}, function (err, location) { console.log('-----------', location); if (err) { cb(err) } else { cb(null, location); } }) } ], function (err, data) { console.log('data in final async series getting location Id : ', data); if (err) { callback(err) } else { // In lowest deal only those SP are visible who has made discount active. etaFilter.filter(function(el){ return el.discount === true }); if (!data) { lowestDeal(etaFilter, payload.quantity, null, function (result) { //if (result) { //responseFormatter.formatServiceResponse(result, callback ,'SP list fetched successfully','success',200); callback(null, result) //} }) } else { lowestDeal(etaFilter, payload.quantity, data._id, function (result) { //if (result) { //responseFormatter.formatServiceResponse(result, callback ,'SP list fetched successfully','success',200); callback(null, result) //} }) } } }) } } }) } } } }); } // else completed for admin global data filter radius value }); //callback result for admin global data filter radius value }; module.exports.CategoriesByGigId = function (gig_id, callback) { console.log('gig_id : ', gig_id); const id = Mongoose.Types.ObjectId(gig_id); gigServiceSchema.Gigs.find({_id: id}, {gig_categories: 1}, function (err, result) { console.log('lCategoriesByGigId result :: ', result); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { if (result && result.length == 0) { responseFormatter.formatServiceResponse([], callback, 'No categories found', 'error', 400); } else { responseFormatter.formatServiceResponse(result, callback, 'Get All Categories By GigId Success', 'success', 200); } } }); }; module.exports.addSPTimeSlots = function (payload, callback) { let timeData = null let spTimeSlots = new spTimeSchema.spTimeSlots(payload) async.series([ function (cb) { SPProfileSchema.SPProfile.findOne({profile_id: payload.profile_id}, {}, {lean: true}, function (err, data) { if (err) { cb(err) } else { console.log("provider data", data) if (!data) { responseFormatter.formatServiceResponse({}, cb, 'Sp profile not Created', 'error', 400); } else { cb(null) } } }) }, function (cb) { gigsSchema.Gigs.findOne({gigs_id: payload.gigs_id}, {}, {lean: true}, function (err, data) { if (err) { cb(err) } else { if (data) { cb() } else { responseFormatter.formatServiceResponse({}, cb, 'Gig not found', 'error', 400); } } }) }, function (cb) { spTimeSlots.save(function (err, data) { if (err) { cb(err) } else { timeData = data cb(null) } }) } ], function (err, data) { if (err) { callback(err) } else { data = timeData callback(null, data) } }) } module.exports.updateSPTimeSlots = function(payload,callback){ spTimeSchema.spTimeSlots.findOneAndUpdate({provider_id : payload.provider_id}, payload ,{new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback ,'Error Occurred','error',500); } else{ console.log("update SPTimeSlots data------------",data); responseFormatter.formatServiceResponse(data, callback, 'Slot data changed', 'success', 200); } }) } module.exports.searchGigs = function (payload, callback) { var search = payload.search //gigsSchema.gigSchema.find({$text:{$search:"payload.search"}},{},function(err,data) gigsSchema.Gigs.find({gig_name: new RegExp('^' + search, 'i')}, { service_name: 1, service_id: 1 }, function (err, data) { if (err) { callback(err) } else { if (data && data.length == 0) { responseFormatter.formatServiceResponse({}, callback, 'no such service exist', 'error', 400); } else { callback(null, data) } } }) } module.exports.getProviderModelTemp = function (payload, callback) { SPProfileSchema.SPProfile.findOne({provider_id: payload.provider_id}, {}, {lean: true}, function (err, profileData) { console.log('profileData :: ', profileData); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { if (profileData) { const parallelF = []; profileData.service_and_gigs_info.forEach(function (service) { console.log('service ::: ', service); var service_id = service.service_id; var service_name = service.service_name; service.gigs.forEach(function (result) { console.log('result.gig_id :: ', result.gig_id); parallelF.push(function (cbb) { SPGigLocationMapperSchema.SPGigLocationMapper.find({ provider_id: payload.provider_id, gig_id: result.gig_id }, {revenue: 1, pricing: 1, _id: 0,location:1}, {lean: true}, function (err, data) { console.log('err-----', err, ' data ------- ', data); if (err) { cbb(err, null) } else { if (data && data.length != 0) { gigsSchema.Gigs.findOne({gig_id:result.gig_id},{number_of_hours:1},{lean:true},function(err,gigData){ if(err){ cbb(err,null) } else{ if(gigData){ spTimeSchema.spTimeSlots.findOne({provider_id:result.provider_id,gig_id:result.gig_id},{slots:1},{lean:true},function(err,timeSlots){ if(err){ cbb(err,null) } else{ if(timeSlots){ result.number_of_hours=gigData.number_of_hours; result.slots=timeSlots.slots, result.pricingDetails = data; result.service_id = service_id; result.service_name = service_name; console.log('~~~~~~~ result :: ', result); cbb(null, result); } else{ result.number_of_hours=gigData.number_of_hours; result.pricingDetails = data; result.service_id = service_id; result.service_name = service_name; console.log('~~~~~~~ result :: ', result); cbb(null, result); } } }) } else{ result.pricingDetails = data; result.service_id = service_id; result.service_name = service_name; console.log('~~~~~~~ result :: ', result); cbb(null, result); } } }) } else { console.log('##### result :: ', result); result.service_id = service_id; result.service_name = service_name; cbb(null, result); } } }) }) }) }) console.log("paralleF", parallelF); async.parallel(parallelF, function (error, data) { console.log('error data : ------', error, data); if (error) { console.log('error : ', error); responseFormatter.formatServiceResponse(err, callback); } else { console.log("in getProviderModelTemp final", data); profileData.service_and_gigs_info = data; responseFormatter.formatServiceResponse(profileData, callback, '', 'success', 200); } }); /*}else{ responseFormatter.formatServiceResponse(profileData , callback ,'','success',200); }*/ } else { responseFormatter.formatServiceResponse({}, callback, "No profileData Found.", "error", 404); } } }); }; module.exports.getProviderModel = function (payload, callback) { let userData = {} let profileData = {} let locationData = {} let timeData = {} //userSchema.User.aggregate([ // { // $match: { // _id: require('mongoose').Schema.Types.ObjectId(payload.provider_id) // } // }, // { // $lookup:{ // from:"SPgiglocationmappings", // localField:"_id", // foreignField:"provider_id", // as:"gigData" // } // // }, // { // "$group": { // "_id": "$_id", // "subjects": {"$push": "$subjects"} // } // } // } //]) let aggregation = [ { $match: { provider_id: payload.provider_id } }, { $lookup: { from: "SPgiglocationmappings", localField: "provider_id", foreignField: "provider_id", as: "gigData" } }, { "$group": { "_id": "$provider_id", "subjects": {"$push": "$subjects"} } } ] SPProfileSchema.SPProfile.aggregate(aggregation, function (err, data) { if (err) { callback(err) } else { console.log("aggregation data", data) callback(null, data) } }) //async.series([ // //function(cb){ // // userSchema.User.find({user_id:payload.provider_id},{first_name:1,last_name:1,mobile:1,email:1},{lean:true},function(err,data){ // // if(err){ // // cb(err) // // } // // else{ // // if(data && data.length==0){ // // responseFormatter.formatServiceResponse({}, cb, 'Provider not found', 'error', 400); // // } // // else{ // // userData=data // // cb(null) // // } // // } // // }) // //}, // function (cb) { // SPProfileSchema.SPProfile.find({provider_id: payload.provider_id}, {}, {lean: true}, function (err, data) { // if (err) { // cb(err) // } // else { // if (data && data.length ==0) { // responseFormatter.formatServiceResponse({}, cb, 'Provider not found', 'error', 400); // } // else { // console.log("data",data) // profileData = data // userData=profileData[0].service_and_gigs_info[0].gigs // console.log("data at 0 position") // cb(null) // } // // } // }) // }, // function (cb) { // SPGigLocationMappingSchema.SPGigLocationMapper.find({provider_id: payload.provider_id}, {}, {lean: true}, function (err, data) { // if (err) { // cb(err) // } // else { // if (data && data.length==0) { // responseFormatter.formatServiceResponse({}, cb, 'Location Pricing not set for SP', 'error', 400); // } // else { // console.log("data+++++++++++++",data) // locationData = data // // //userData=locationData[0].service_and_gigs_info[0].gigs // cb(null) // } // // } // }) // }, // //function(cb){ // // spTimeSchema.spTimeSlots.findOne({provider_id: payload.provider_id}, {}, {lean: true}, function (err, data) { // // if (err) { // // cb(err) // // } // // else { // // //if (!data) { // // // responseFormatter.formatServiceResponse({}, cb, 'Time Slots Not defined for SP', 'error', 400); // // //} // // //else { // // // locationData = data // // //} // // timeData=data // // cb(null) // // } // // }) // //} //],function(err,data){ // if(err){ // callback(err) // } // else{ // data=commonFunction.MergeDataWithKey(userData,locationData,"gig_id") // callback(null,data) // } //}) } module.exports.pushTestModel = function (payload, callback) { let bookingData = null let providerData = null let pushDetailsSP = null async.series([ function (cb) { let newBooking = new bookingSchema.Booking() newBooking.seeker_id = payload.seeker_id, newBooking.save(function (err, data) { if (err) { cb(err) } else { bookingData = data, cb(null) } }) }, function (cb) { userSchema.User.findOne({user_id: payload.provider_id}, {}, {lean: true}, function (err, data) { if (err) { cb(err) } else { providerData = data cb(null) } }) }, function (cb) { const n = new Date(); const deviceDetails = [] const bookPayload = { profile_photo: providerData.profilePhoto, first_name: providerData.first_name, last_name: providerData.last_name, booking_type: bookingData.booking_type, booking_id: bookingData._id, booking_data: n.toISOString(), push_type: "new booking" } deviceDetails.push({ device_type: payload.device_type, device_token: payload.device_token }); pushDetailsSP = { deviceDetails: deviceDetails, text: "SP Push", payload: bookPayload } sendPush.sendPush(pushDetailsSP, "PROVIDER"); cb(null) } ], function (err, data) { if (err) { callback(err) } else { data = pushDetailsSP callback(null, data) } }) } module.exports.getProviderBookings = function (payload, callback) { bookingSchema.Booking.find({provider_id: payload.provider_id}, function (err, booking) { console.log('Booking details returned----------------', booking); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback, 'Error Occurred Please Try After Some Time', 'error', 500); } else { if (booking.length != 0) { responseFormatter.formatServiceResponse(booking, callback, 'Provider bookings fetched successfully', 'success', 200); // callback(null,booking) } else { responseFormatter.formatServiceResponse({}, callback, 'No booking found', 'error', 404); // callback(null,{}) } } }); } module.exports.getGigInfoForProvider = function (provider_id, gig_id, service_id, callback) { console.log('provider_id , gig_id , service_id', provider_id, gig_id, service_id); // /*async.waterfall([ // function (cb) { // SPProfileSchema.SPProfile.findOne({ // provider_id: provider_id, /*"service_and_gigs_info.service_id " : service_id,*/ // "service_and_gigs_info.gigs.gig_id": gig_id // }, {}, {lean: true}, function (err, data) { // // console.log('data gig info for provider : ', data); // if (err) { // cb(err) // } // else { // console.log("provider data", data) // if (!data) { // cb(null, {}); // } // else { // console.log('===>', data); // // for (var i = 0; i < data.service_and_gigs_info.length; i++) { // console.log('data.service_and_gigs_info[i].service_id : ', data.service_and_gigs_info[i].service_id); // if (data.service_and_gigs_info[i].service_id != service_id) { // data.service_and_gigs_info.splice(i, 1) // } // } // cb(null, data); // } // } // }) // // }, // function (providerInfo, cb) { // SPGigLocationMapperSchema.SPGigLocationMapper.find({provider_id: provider_id, gig_id: gig_id}, { // revenue: 1, // pricing: 1, // location: 1, // _id: 0 // }, {lean: true}, function (err, data) { // console.log('err-----', err, ' data ------- ', data); // if (err) { // cb(err, null) // } // else { // providerInfo.pricingDetails = data; // cb(null, providerInfo); // // } // }) // // }, // function (providerInfoWithPricing, cb) { // spTimeSchema.spTimeSlots.findOne({provider_id: provider_id, gig_id: gig_id}, { // slots: 1, // _id: 0 // }, {lean: true}, function (err, data) { // console.log('err-----', err, ' data ------- ', data); // if (err) { // cb(err, null) // } // else { // providerInfoWithPricing.timeSlots = data; // cb(null, providerInfoWithPricing); // // } // }) // // } // ], function (err, data) { // console.log('data in final async series getting location Id : ', data); // if (err) { // callback(err) // } // else { // if (!data) { // // } else { // responseFormatter.formatServiceResponse(data, callback, '', 'success', 200); // } // } // })*/ let gigData=null let providerData=null async.series([ function (cb) { gigServiceSchema.Gigs.findOne({gig_id: gig_id}, {}, {lean: true}, function (err, gig) { if(err){ cb(err) } else{ const id=mongoose.Types.ObjectId(gig_id) SPLocationMapping.Mapper.find({gig: id}, { location: 1, location_name: 1, pricing:1, revenue_model:1 },{lean:true}, function (err, location) { if(err){ cb(err) } else{ console.log("location in mapper function",location) gig.location=location gigData=gig cb(null) } }) } }) }, function(cb){ SPProfileSchema.SPProfile.aggregate( // Pipeline [ // Stage 1 { $match: { provider_id: provider_id } }, // Stage 2 { $unwind: { path: "$service_and_gigs_info", preserveNullAndEmptyArrays: true } }, // Stage 3 { $match: { 'service_and_gigs_info.gigs.gig_id': gig_id } }, // Stage 4 { $project: { 'first_name': 1, 'profile_id': 1, 'service_and_gigs_info.service_id': 1, 'service_and_gigs_info.service_name': 1, 'service_and_gigs_info.gigs': { '$filter': { input: '$service_and_gigs_info.gigs', as: 'chandan', cond: { "$eq": ["$$chandan.gig_id", gig_id] } } } } } // Stage 5 /* { $unwind: {path: "$service_and_gigs_info.gigs"} }, // Stage 6 { $lookup: { "from": "gigs", "localField": "service_and_gigs_info.gigs.gig_id", "foreignField": "gig_id", "as": "gig" } }, // Stage 7 { $project: { 'first_name': 1, 'profile_id': 1, 'service_and_gigs_info.service_id': 1, 'service_and_gigs_info.service_name': 1, 'service_and_gigs_info.gigs': 1, 'gig.revenue_model': 1, 'gig.pricing': 1 } }*/ ] ).exec(function(err,SPdata){ console.log("SPdata",SPdata) if(err){ cb(err) } else{ if(SPdata && SPdata.length==0){ providerData={} cb(null) } else{ SPGigLocationMapperSchema.SPGigLocationMapper.find({provider_id:provider_id,gig_id:gig_id},{location:1,revenue:1,pricing:1,min_hourly_amount:1,is_revenue_paid:1,discount:1},{lean:true},function(err,SPlocation){ console.log("SPlocation",SPlocation) if(err){ cb(err) } else{ spTimeSchema.spTimeSlots.findOne({provider_id:provider_id,gig_id:gig_id},{slots:1,_id:0},{lean:true},function (err,slots) { if(err){ cb(err) } else{ console.log("time slots",slots) if(slots){ providerData={ first_name:SPdata[0].first_name, service_and_gigs_info:SPdata[0].service_and_gigs_info, SPlocation:SPlocation, slots:slots } cb(null) } else{ providerData={ first_name:SPdata[0].first_name, service_and_gigs_info:SPdata[0].service_and_gigs_info, SPlocation:SPlocation, } cb(null) } } }) } }) } } }) } ],function(err,data){ if(err){ callback(err) } else{ data={ gig:gigData, provider:providerData } callback(null,data) } }) } module.exports.getProviderBookingsByPagination = function (query, path, callback) { let sort=null if (query.filter.status == 'Confirmed') { sort = {updatedAt: -1}; } else { sort = {booking_datetime: -1}; } //sort[query.sort_param] = -1; var filter = query.filter ? query.filter : {}; var fields = query.fields ? query.fields : ''; console.log("filter - : ", filter, " fields - : ", fields); var url = path; console.log('query ::: ', query); var first = true; for (var key in query) { if (key != 'pageno' && key != 'fields' && key != 'filter') { if (first) { url += '?' + key + '=' + query[key]; first = false; } else { url += '&' + key + '=' + query[key]; } } } console.log('filter, query.pageno, query.resultsperpage, query.pagelist, url, fields, - - - - ', filter, query.pageno, query.resultsperpage, query.pagelist, url, fields, sort); bookingSchema.Booking.paginate(filter, query.pageno, parseInt(query.resultsperpage), query.pagelist, url, fields, callback, sort); }; /* * Service_id is not being used here * for provider we are getting gigs where product based is true*/ module.exports.getProductBasedGigsForProvider = function (provider_id, callback) { // console.log('provider_id , service_id',provider_id , service_id); /* SPProfileSchema.SPProfile.findOne({provider_id:provider_id},{},{lean:true},function(err,data){ if(err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback ,'Error Occurred Please Try After Some Time','error',500); } else{ console.log("provider data",data) if(!data){ responseFormatter.formatServiceResponse({}, callback ,'No Provider Profile found ','error',400); } else{ console.log("data.service_and_gigs_info",data.service_and_gigs_info) for(var i = 0 ; i< data.service_and_gigs_info.length ;i++){ console.log('data.service_and_gigs_info[i].service_id : ',data.service_and_gigs_info[i].service_id); if(data.service_and_gigs_info[i].service_id != service_id){ data.service_and_gigs_info.splice(i,1); i--; } //console.log('`````````data.service_and_gigs_info :: ',data.service_and_gigs_info); //console.log('data.service_and_gigs_info[i] :: ',data.service_and_gigs_info[i]); for(var j = 0; j< data.service_and_gigs_info[i].gigs.length ; j++){ //console.log('data.service_and_gigs_info[i].gigs[j].gig_id : ',data.service_and_gigs_info[i].gigs[j].gig_id); if(data.service_and_gigs_info[i].gigs[j].is_product_based == false){ data.service_and_gigs_info[i].gigs.splice(j,1); j--; } } } responseFormatter.formatServiceResponse(data, callback ,'Product based gigs found successfully','success',200); } } }) */ /* SPProfileSchema.SPProfile.findOne({ provider_id:provider_id, },{ service_and_gigs_info:1 },{lean:true},function(err,data){ if(err){ callback(err) } else{ // console.log("getProductBasedGigsForProvider end",data) const pullData= _.filter(data.service_and_gigs_info.gigs, { gigs: [{is_product_based: true}] } ) console.log("lodash data",pullData) callback(null,pullData) } })*/ /*SPProfileSchema.SPProfile.aggregate( // AggregationPipeline [ // Stage 1 match provider id { $match: { provider_id: provider_id } }, // Stage 2 open array services_and_gigs_info { $unwind: {path: "$service_and_gigs_info", preserveNullAndEmptyArrays: true} }, // Stage 3 matching that only those are shown where services and gigs info true { $match: { 'service_and_gigs_info.gigs.is_product_based':true } }, // Stage 4 { $project: { first_name:1, 'service_and_gigs_info.service_id':1, 'service_and_gigs_info.service_name':1, //'service_and_gigs_info':1, 'service_and_gigs_info.gigs':{ '$filter':{ input:'$service_and_gigs_info.gigs', as:'chandan', cond:{ "$eq":[ "$$chandan.is_product_based",true] } } } } } ] ).exec(function (err, data) { console.log("getProductBasedGigsForProvider",JSON.stringify(err),JSON.stringify(data)) if (err) { callback(err) } else { callback(null, data) } })*/ console.log("provider_id ++++", provider_id) SPProfileSchema.SPProfile.aggregate( // Pipeline [ // Stage 1 { $match: { provider_id: provider_id } }, // Stage 2 { $unwind: { path: "$service_and_gigs_info", preserveNullAndEmptyArrays: true } }, // Stage 3 { $match: { 'service_and_gigs_info.gigs.is_product_based': true } }, // Stage 4 { $project: { 'first_name': 1, 'profile_id': 1, 'service_and_gigs_info.service_id': 1, 'service_and_gigs_info.service_name': 1, 'service_and_gigs_info.gigs': { '$filter': { input: '$service_and_gigs_info.gigs', as: 'chandan', cond: { "$eq": ["$$chandan.is_product_based", true] } } } } }, // Stage 5 { $unwind: {path: "$service_and_gigs_info.gigs"} }, // Stage 6 { $lookup: { "from": "gigs", "localField": "service_and_gigs_info.gigs.gig_id", "foreignField": "gig_id", "as": "gig" } }, // Stage 7 { $project: { 'first_name': 1, 'profile_id': 1, 'service_and_gigs_info.service_id': 1, 'service_and_gigs_info.service_name': 1, 'service_and_gigs_info.gigs': 1, 'gig.revenue_model': 1, 'gig.pricing': 1 } } ] // Created with 3T MongoChef, the GUI for MongoDB - http://3t.io/mongochef ).exec(function (err, data) { console.log("getProductBasedGigsForProvider", JSON.stringify(err), JSON.stringify(data)) if (err) { callback(err) } else { if (data && data.length == 0) { responseFormatter.formatServiceResponse([], callback, 'No product based gigs for provider', 'error', 400); } else { callback(null, data) } } }) } module.exports.addProductInfoForGig = function (payload, callback) { let productInfo = payload.product_info let finalData = null async.series([ function (cb) { if (payload.hasOwnProperty("product_image") && payload.product_image) { let fileName = payload.product_image.filename; let tempPath = payload.product_image.path; if (typeof payload.product_image !== 'undefined' && payload.product_image.length) { fileName = payload.product_image[1].filename; tempPath = payload.product_image[1].path; } console.log("tempPath", fileName) commonFunction.uploadFile(tempPath, fileName, "aLarge", function (err) { if (err) { cb(err); } else { let x = fileName; let fileNameFirst = x.substr(0, x.lastIndexOf('.')); let extension = x.split('.').pop(); productInfo.product_image = { original: AWS.s3URL + AWS.folder.aLarge + "/" + fileName, thumbnail: AWS.s3URL + AWS.folder.aLarge + "/" + fileNameFirst + "_thumb." + extension }; console.log("file upload success", productInfo.product_image); console.log("teamPhoto"); cb(null) } }); } else { cb(null); } }, function (cb) { console.log("async waterfall productinfo", productInfo) let dataToUpdate = { "profile_id": payload.profile_id, "provider_id": payload.provider_id, "gig_id": payload.gig_id, "category_id": payload.category_id } SPGigProductInfoSchema.SPGigProductsInfo.findOneAndUpdate({ provider_id: payload.provider_id, category_id: payload.category_id }, { $push: {product_info: productInfo}, $set: dataToUpdate }, {new: true, upsert: true}, function (err, product) { if (err) { responseFormatter.formatServiceResponse(err, cb, 'Error Occurred', 'error', 500); } else { finalData = product cb(null) } }) } ], function (err, data) { if (err) { callback(err) } else { data = finalData console.log("final data after series", data) callback(null, data) } }) } module.exports.getProductInfoForGig = function (payload, callback) { /*SPGigProductInfoSchema.SPGigProductsInfo.aggregate([ { "$match": { gig_id: payload.gig_id } }, { "$lookup": { from: "gigs", localField: "gig_id", foreignField: "_id", as: "productData" }, }, { "$project": { provider_id: 1, gig_id: 1, 'productData.gig_name': 1, category_id: 1, product_info: 1 } } ]).exec(function (err, data) { if (err) { callback(err) } else { console.log("getProductInfoForGig stop", data) callback(null, data) } }) SPGigProductInfoSchema.SPGigProductsInfo.find({},{},function(err,data) { if(err) { callback(err) } else { console.log('full data',data); callback(data) } }) */ /* SPGigProductInfoSchema.SPGigProductsInfo.aggregate( [ { $group : { _id : {category_id:"$category_id" }} }, { $lookup: { from: "gigcategories", localField: "category_name", foreignField: "category_id", as: "category_name" } } ] ).exec(function (err, data) { if (err) { callback(err) } else { if(data &&data.length==0){ responseFormatter.formatServiceResponse({}, callback, 'No product in Gig for provider', 'error', 400); } else{ callback(null, data) } } }) */ SPGigProductInfoSchema.SPGigProductsInfo.find({ gig_id: payload.gig_id, provider_id: payload.provider_id }, {category_id: 1, product_info: 1}, {lean: true}, function (err, product) { if (err) { callback(err) } else { if (product && product.length == 0) { responseFormatter.formatServiceResponse([], callback, 'No products register for gig', 'error', 400); } else { let parallelF = [] product.forEach(function (result) { console.log('result.provider_id :: ', result); parallelF.push(function (cbb) { gigsSchema.Gigs.findOne({gig_id: payload.gig_id}, {gig_categories: 1}, {lean: true}, function (err, category) { for (var i = 0; i < category.gig_categories.length; i++) { if (category.gig_categories[i]._id == result.category_id) { result.category_name = category.gig_categories[i].category_name console.log("in for loop", result.category_name) } } cbb(null, result) }) }) }) //console.log("paralleF", parallelF); async.parallel(parallelF, function (error, data) { console.log('error data : ------', error, data); if (error) { console.log('error : ', error); return callback(err); } else { console.log("final data in format", data) callback(null, data); } }) } } }) } module.exports.getAllUnregisteredGigsByServiceId = function (providerId, serviceId, callback) { let aggregation = [ // Stage 1 { $match: { provider_id: providerId } }, // Stage 2 { $project: { 'service_and_gigs_info': { '$filter': { input: '$service_and_gigs_info', as: 'gigsArray', cond: { "$eq": ["$$gigsArray.service_id", serviceId] } } } } }, { $project: { 'service_and_gigs_info.gigs.gig_id': 1 } } ] SPProfileSchema.SPProfile.aggregate(aggregation, function (err, data) { if (err) { callback(err) } else { console.log("aggregation data", data); var gigIds = []; if(data.length !=0 && data[0].service_and_gigs_info.length !=0 && data[0].service_and_gigs_info[0].gigs.length!=0){ for(var i = 0; i < data[0].service_and_gigs_info[0].gigs.length; i++ ){ gigIds.push(data[0].service_and_gigs_info[0].gigs[i].gig_id); } }else{ gigIds = []; } console.log("gigIds ----> ",gigIds); gigsSchema.Gigs.aggregate([ {"$match":{ "service_id" : serviceId, "gig_id" : { $nin: gigIds } }}, { "$project": { service_id:1, service_name:1, alternate_gig_name:1, gig_id:1, gig_name:1, gig_image:1, pricing:1, revenue_model:1, skill_level:1, is_product_based:1, gig_categories:1, flow:1, min_age:1, max_fixed_price:1, max_hourly_price:1, number_of_hours:1, gig_booking_options:1, tool_required:1, additional_comments:1, set_unit:1, is_active:1, addSupplies:1, gig_specific_param:1, booking_location:1, "insensitive": { "$toLower": "$gig_name" } }}, { "$sort": { "insensitive": 1 } } ]).exec(function(err,gigData){ console.log('response from gigModel :: err : ',err," gigData :: ",gigData); if(err){ callback(err) } else{ console.log("in getAllGigsModel aggregation>>>>>",gigData) callback(null,gigData) } }); } }) } module.exports.updateSPAvailability = function(payload,callback){ SPProfileSchema.SPProfile.findOneAndUpdate({provider_id : payload.provider_id}, payload ,{new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback ,'Error Occurred','error',500); } else{ console.log("in updateSPAvailability data------------",data); if(data){ responseFormatter.formatServiceResponse(data, callback, 'SP availability changed successfully', 'success', 200); }else{ responseFormatter.formatServiceResponse({}, callback, 'SP Profile not found. Please update your profile first.', 'error', 404); } } }) } module.exports.toggleDiscountFlagForSP = function(payload,callback){ SPProfileSchema.SPProfile.findOneAndUpdate({provider_id : payload.provider_id}, payload ,{new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback ,'Error Occurred','error',500); } else{ console.log("in toggleDiscountFlagForSP data------------",data); if(data){ responseFormatter.formatServiceResponse(data, callback, 'SP discount status changed successfully', 'success', 200); }else{ responseFormatter.formatServiceResponse({}, callback, 'SP Profile not found. Please create your profile first.', 'error', 404); } } }) } module.exports.updateSPRevenuePaymentStatusDummy = function(payload,callback){ SPGigLocationMappingSchema.SPGigLocationMapper.findOneAndUpdate({provider_id : payload.provider_id}, payload ,{new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback ,'Error Occurred','error',500); } else{ console.log("in updateSPRevenuePaymentStatusDummy data------------",data); if(data){ responseFormatter.formatServiceResponse(data, callback, 'SP revenue payment status changed successfully', 'success', 200); }else{ responseFormatter.formatServiceResponse({}, callback, 'SP Profile not found. Please update your profile first.', 'error', 404); } } }) }; module.exports.addOrganizationData = function (payload,provider_id, callback) { let orgDetails = payload.org_details; let finalData = null async.series([ function (cb) { if (payload.hasOwnProperty("certificate") && payload.certificate) { let fileName = payload.certificate.filename; let tempPath = payload.certificate.path; if (typeof payload.certificate !== 'undefined' && payload.certificate.length) { fileName = payload.certificate[1].filename; tempPath = payload.certificate[1].path; } console.log("tempPath", fileName) commonFunction.uploadFile(tempPath, fileName, "aLarge", function (err) { if (err) { cb(err); } else { let x = fileName; let fileNameFirst = x.substr(0, x.lastIndexOf('.')); let extension = x.split('.').pop(); orgDetails.certificate = { original: AWS.s3URL + AWS.folder.aLarge + "/" + fileName, thumbnail: AWS.s3URL + AWS.folder.aLarge + "/" + fileNameFirst + "_thumb." + extension }; console.log("file upload success", orgDetails.certificate); console.log("cerificateimage"); cb(null) } }); } else { cb(null); } }, function (cb) { if (payload.hasOwnProperty("licence") && payload.licence) { let fileName = payload.licence.filename; let tempPath = payload.licence.path; if (typeof payload.licence !== 'undefined' && payload.licence.length) { fileName = payload.licence[1].filename; tempPath = payload.licence[1].path; } console.log("tempPath", fileName) commonFunction.uploadFile(tempPath, fileName, "aLarge", function (err) { if (err) { cb(err); } else { let x = fileName; let fileNameFirst = x.substr(0, x.lastIndexOf('.')); let extension = x.split('.').pop(); orgDetails.licence = { original: AWS.s3URL + AWS.folder.aLarge + "/" + fileName, thumbnail: AWS.s3URL + AWS.folder.aLarge + "/" + fileNameFirst + "_thumb." + extension }; console.log("file upload success", orgDetails.licence); console.log("licenceimage"); cb(null) } }); } else { cb(null); } }, function (cb) { console.log("async series orgDetails", orgDetails); let SPorganization = new SPProfileSchema.SPProfile(orgDetails); SPorganization.profile_id = SPorganization._id; SPorganization.provider_id = provider_id; SPorganization.org_tab_flag = true; SPorganization.save(function(err,SPorganization) { if (err) { responseFormatter.formatServiceResponse(err, callback); } else { console.log("SPorganization savedData______", SPorganization); finalData = SPorganization; cb(null); } }) } ], function (err, data) { if (err) { callback(err) } else { data = finalData; console.log("final data after series", data) callback(null, data); } }) } module.exports.addInsuranceDetails = function (payload, callback) { let insuranceDetails = payload.insurance_details; let finalData = null async.series([ function (cb) { if (payload.hasOwnProperty("insurance_doc") && payload.insurance_doc) { let fileName = payload.insurance_doc.filename; let tempPath = payload.insurance_doc.path; if (typeof payload.insurance_doc !== 'undefined' && payload.insurance_doc.length) { fileName = payload.insurance_doc[1].filename; tempPath = payload.insurance_doc[1].path; } console.log("tempPath", fileName) commonFunction.uploadFile(tempPath, fileName, "aLarge", function (err) { if (err) { cb(err); } else { let x = fileName; let fileNameFirst = x.substr(0, x.lastIndexOf('.')); let extension = x.split('.').pop(); insuranceDetails.insurance_doc = { original: AWS.s3URL + AWS.folder.aLarge + "/" + fileName, thumbnail: AWS.s3URL + AWS.folder.aLarge + "/" + fileNameFirst + "_thumb." + extension }; console.log("file upload success", insuranceDetails.insurance_doc); console.log("insurance_doc"); cb(null) } }); } else { cb(null); } }, function (cb) { SPProfileSchema.SPProfile.findOneAndUpdate({"profile_id":payload.organization_profile_id}, {'insurance_details' : insuranceDetails, $set:{insurance_tab_flag : true}}, {lean:true,new:true},function(err,organizationDetails){ console.log("async series updated orgDetails with insurance details :", organizationDetails); if (err){ console.log('error in addInsuranceDetails : ',err); responseFormatter.formatServiceResponse(err, callback); } else { finalData = organizationDetails cb(null); } }) } ], function (err, data) { if (err) { callback(err) } else { data = finalData; console.log("final data after series", data) callback(null, data); } }) } module.exports.addBankDetails = function(payload,callback){ let bank_details = payload.bank_details; SPProfileSchema.SPProfile.findOneAndUpdate({"profile_id":payload.organization_profile_id}, {'bank_details' : bank_details, $set:{bank_tab_flag : true}}, {lean:true,new:true},function(err,organizationDetails){ console.log("async series updated orgDetails with bank details :", organizationDetails); if (err){ console.log('error in addBankDetails : ',err); responseFormatter.formatServiceResponse(err, callback); } else { if(organizationDetails){ responseFormatter.formatServiceResponse(organizationDetails , callback,'Bank Details Added successfully','success',200); }else{ responseFormatter.formatServiceResponse(organizationDetails , callback,'SP Organization profile not found','error',404); } } }) }; module.exports.getAllApprovedReviews = function (provider_id , callback) { SPProfileSchema.SPProfile.aggregate( // Pipeline [ // Stage 1 { $unwind : "$reviews" }, // Stage 2 { $match : { "reviews.is_approved_by_admin" : true } }, // Stage 3 { $group : { _id : "$_id", reviews : {$push : "$reviews"} } } ] // Created with 3T MongoChef, the GUI for MongoDB - http://3t.io/mongochef ).exec(function (err, data) { console.log("getAllApprovedReviews", JSON.stringify(err), JSON.stringify(data)) if (err) { logger.error("in getAllApprovedReviews Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { if (data && data.length == 0) { responseFormatter.formatServiceResponse([], callback, 'No Reviews found for provider', 'error', 400); } else { responseFormatter.formatServiceResponse(result, callback, 'Get All Reviews By provider id Success', 'success', 200); //callback(null, data) } } }); /*SPProfileSchema.SPProfile.findOne({provider_id : provider_id, reviews: { $elemMatch: { is_approved_by_admin : true }}}, {reviews : 1}, function (err, result) { console.log('getAllApprovedReviews result :: ', result); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { if (result && result.length == 0) { responseFormatter.formatServiceResponse([], callback, 'No Reviews found', 'error', 400); } else { responseFormatter.formatServiceResponse(result, callback, 'Get All Reviews By provider id Success', 'success', 200); } } }); */ };
const jwt = require("jsonwebtoken"); const SECRET_KEY = process.env.SECRET_KEY; function createToken(payload) { return jwt.sign(payload, SECRET_KEY); } function checkToken(token) { return jwt.verify(token, SECRET_KEY); } module.exports = { createToken, checkToken };
export default { lang: 'ja', mediaPlayer: { oldBrowserVideo: '動画を再生するため、JavaScriptを有効にする必要があります。また、ブラウザーはHTML5をサポートする必要があります。', // 'To view this video please enable JavaScript and/or consider upgrading to a browser that supports HTML5 video.', oldBrowserAudio: 'オーディオを再生するため、JavaScriptを有効にする必要があります。また、ブラウザーはHTML5をサポートする必要があります。', // 'To listen to this audio please enable JavaScript and/or consider upgrading to a browser that supports HTML5 audio.', pause: '保留', // 'Pause' play: 'プレイ', // 'Play' settings: '設定', // 'Settings' toggleFullscreen: 'フルスクリーン', // 'Toggle Fullscreen' mute: '消音', // 'Mute' unmute: '消音を解除', // 'Unmute' speed: 'スピード', // 'Playback rate' language: '言語', // 'Language' playbackRate: '再生スピード', // 'Playback Rate', waitingVideo: '動画読み込み中', // 'Waiting for video' waitingAudio: 'オーディオ読み込み中', // 'Waiting for audio' ratePoint5: '.5x', rateNormal: '普通', // 'Normal' rate1Point5: '1.5x', rate2: '2x', trackLanguageOff: 'オフ', noLoadVideo: '動画の読み込みエラー', // 'Unable to load video', noLoadAudio: 'オーディオの読み込みエラー', // 'Unable to load audio', cannotPlayVideo: '動画を再生できません', // 'Cannot play video', cannotPlayAudio: 'オーディオを再生できません' // 'Cannot play audio' } }
export function convertMonthToWord(month) { if (month >= 1 && month <= 12) { let words = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; return words[month - 1]; } return ''; }; export function convertFinancial(month, year) { // let dateNow = new Date(); // let monthNow = dateNow.getMonth(); // let list = []; let words = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // if (monthNow < 6) { // for (let i = monthNow; i >= 0; i--) { // list.push({month: i + 1, word: words[i] + ' - ' + (+year + 1)}); // } // for (let i = 11; i >= 6; i--) { // list.push({month: i + 1, word: words[i] + ' - ' + year}); // } // } // else { // for (let i = monthNow; i < 12; i++) { // list.push({month: i + 1, word: words[i] + ' - ' + year}); // } // for (let i = 0; i < 6; i++) { // list.push({month: i + 1, word: words[i] + ' - ' + (+year + 1)}); // } // } // console.log('list month', list); if (month >= 1 && month <= 12) { let yearx = month < 7 ? +year + 1 : year; return words[month - 1] + ' - ' + yearx; } return 'None'; }; export function convertToString(date, option) { if (date) { option = checkDateOptions(option); return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], option); } return ''; }; export function convertToDateString(date, option) { if (date) { return new Date(date).toLocaleDateString([], option); } return ''; }; export function convertToTimeString(date, option) { if (date) { option = checkDateOptions(option); return date.toLocaleTimeString([], option); } return ''; }; export function getListMonthName(begin, end, month) { let date = new Date(); let monthCurrent = date.getMonth() + 1; let yearCurrent = date.getFullYear(); let position; let list = [{month: 1, name: 'January', year: null, allow: true}, {month: 2, name: 'February', year: null, allow: true}, {month: 3, name: 'March', year: null, allow: true}, {month: 4, name: 'April', year: null, allow: true}, {month: 5, name: 'May', year: null, allow: true}, {month: 6, name: 'June', year: null, allow: true}, {month: 7, name: 'July', year: null, allow: true}, {month: 8, name: 'August', year: null, allow: true}, {month: 9, name: 'September', year: null, allow: true}, {month: 10, name: 'October', year: null, allow: true}, {month: 11, name: 'November', year: null, allow: true}, {month: 12, name: 'December', year: null, allow: true}]; for (let i = 0; i < list.length; i++) { if (list[i].month === month) { position = i; break; } } let listPart1 = list.slice(0, position); let listPart2 = list.slice(position, list.length); if (yearCurrent > begin) { listPart2.forEach(item => { item.allow = true; }); listPart1.forEach(item => { if (item.month < monthCurrent) item.allow = true; else item.allow = false; }); } else { listPart1.forEach(item => { item.allow = false; }); listPart2.forEach(item => { if (item.month < monthCurrent) item.allow = true; else item.allow = false; }); } let result = listPart2.concat(listPart1); for (let item of result) { if (item.month < month) item.year = end; else item.year = begin; } return result; }; export function timeFromNow(date) { let seconds = Math.floor((new Date() - new Date(date)) / 1000); let time = new Date(date); let result = Math.floor(seconds / 86400); if (result >= 2) return formatSingleDigitNumber(time.getDate()) + '/' + formatSingleDigitNumber(Number(time.getMonth() + 1)) + '/' + time.getFullYear(); if (result >= 1 && result < 2) return 'Yesterday'; result = Math.floor(seconds / 3600); if (result >= 1) return result + ' hours'; result = Math.floor(seconds / 60); if (result > 1) return result + ' minutes'; if (seconds > 60) return 1 + ' minutes'; return Math.floor(seconds) + ' seconds'; }; export function formatDate(date) { if (!date) return undefined; let result = new Date(date); return formatSingleDigitNumber(result.getDate()) + '/' + formatSingleDigitNumber(result.getMonth() + 1) + '/' + result.getFullYear(); } export function formatTime(time) { if (!time) return undefined; let result = new Date(time); return ('0' + result.getHours()).slice(-2) + ':' + ('0' + result.getMinutes()).slice(-2) + ':' + ('0' + result.getSeconds()).slice(-2); } function formatSingleDigitNumber(number) { if (isNaN(number)) return undefined; return ('0' + number).slice(-2); } export function listYears(endYear) { let startYear = 2017; let list = []; if (!endYear || endYear <= startYear) endYear = (new Date()).getFullYear(); for (let i = startYear; i <= endYear; i++) { list.push({name: '', financial: i + ' - ' + (i + 1), year: i}); } return list; } export function listYear(endYear) { let startYear = 2017; let list = []; if (!endYear || endYear <= startYear) endYear = (new Date()).getFullYear() + 10; for (let i = startYear; i <= endYear; i++) { list.push(i); } return list; } function checkDateOptions(option) { if (!option) option = {}; if (!option.hour12) option.hour12 = false; return option; };
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext, MyRetirement, MyRetirementRemote*/ Ext.define('MyRetirement.model.Enumeration', { extend: 'Ext.data.Model' ,idProperty: 'value' ,fields: [ { name: 'label', type: 'string' } ,{ name: 'sortOrder', type: 'integer' } ,{ name: 'value', type: 'integer' } ] });
const Send = require("../send.js") const Log = require("../logging.js") function pin(msg, args){ return new Promise( (done, error) => { var _reason = "MentalBot was told to" if(args.length > 2){ _reason = args[2] for (var i = 3; i < args.length; i++) _reason += ' ' + args[i] } var cnl = msg.channel; if (msg.reference){ var refID = msg.reference.messageID; cnl.messages.fetch(refID).then(found => { found.pin({ reason: _reason }).then(result => { Log.success(`Pin success for message "${found.content}", with reason "${_reason}"`) done(result) }).catch(error) }).catch(error) } else { error(`No referenced message`) } }) } module.exports = { desc: 'Pin a message', func: pin }
import { connect } from 'react-redux'; import OrderPage from './components/OrderPage'; import helper from '../../../common/common'; import {Action} from '../../../action-reducer/action'; import {getPathValue} from '../../../action-reducer/helper'; import EditContainer from './EditContainer' import showPopup from '../../../standard-business/showPopup'; import {buildEditState} from './EditContainer' const STATE_PATH = ['platform', 'messageTheme']; const URL_LIST = '/api/platform/messageTheme/list'; const URL_DEL = '/api/platform/messageTheme/del'; //刷新表格 const updateTable = async (dispatch, getState) => { const {tabKey} = getSelfState(getState()); const list = helper.getJsonResult(await helper.fetchJson(URL_LIST,'post')); dispatch(action.assign({tableItems:list}, tabKey)); }; const action = new Action(STATE_PATH); const getSelfState = (rootState) => { const parent = getPathValue(rootState, STATE_PATH); return parent[parent.activeKey]; }; const addActionCreator = (dispatch, getState) => { const {editConfig} = getPathValue(getState(), STATE_PATH); if(buildEditState(editConfig, {},false,dispatch)){ showPopup(EditContainer, {refreshTable:updateTable}); } }; const editActionCreator = (dispatch, getState) => { const {editConfig} = getPathValue(getState(), STATE_PATH); const {tableItems} = getSelfState(getState()); const index = helper.findOnlyCheckedIndex(tableItems); if (index === -1) { helper.showError('请勾选一条记录进行编辑'); return; } if(buildEditState(editConfig, tableItems[index],true,dispatch)){ showPopup(EditContainer, {refreshTable:updateTable}); } }; const delActionCreator = async(dispatch,getState) => { const {tableItems} = getSelfState(getState()); const index = helper.findOnlyCheckedIndex(tableItems); if (index === -1) { helper.showError('请勾选一条记录进行删除'); return; } const {returnCode,returnMsg} = await helper.fetchJson(`${URL_DEL}/${tableItems[index].id}`,'delete') if(returnCode != 0){ helper.showError(returnMsg) return } helper.showSuccessMsg('删除成功') return updateTable(dispatch,getState) } const toolbarActions = { add:addActionCreator, edit:editActionCreator, del:delActionCreator }; const clickActionCreator = (key) => { if (toolbarActions.hasOwnProperty(key)) { return toolbarActions[key]; } else { console.log('unknown key:', key); return {type: 'unknown'}; } }; const doubleClickActionCreator = (rowIndex) => (dispatch, getState) => { const {editConfig} = getPathValue(getState(), STATE_PATH); const {tableItems} = getSelfState(getState()); if(buildEditState(editConfig, tableItems[rowIndex],true,dispatch)){ showPopup(EditContainer, {refreshTable:updateTable}); } }; const changeActionCreator = (key, value) => (dispatch,getState) =>{ const {tabKey} = getSelfState(getState()); dispatch(action.assign({[key]: value}, [tabKey, 'searchData'])); }; const checkActionCreator = (isAll, checked, rowIndex) => (dispatch, getState) =>{ const {tabKey} = getSelfState(getState()); isAll && (rowIndex = -1); dispatch(action.update({checked}, [tabKey, 'tableItems'], rowIndex)); }; const mapStateToProps = (state) => { return getSelfState(state); }; const actionCreators = { onClick: clickActionCreator, onChange: changeActionCreator, onCheck: checkActionCreator, onDoubleClick: doubleClickActionCreator, }; const MessageThemeContainer = connect(mapStateToProps, actionCreators)(OrderPage); export default MessageThemeContainer;
var aKey = 97; var lKey = 108; var divs = 12; $(document).ready(function(){ //Player constructor. function Player(player, color, key) { this.player = player; this.color = color; this.key = key; this.position = 0; this.name = getName(); this.road = makeRoad(this.player); this.move = move(); }; Player.prototype.getName = function(){ return prompt('What is your name?').toUpperCase(); //$('#name1').text(this.name); }; Player.prototype.makeRoad = function(playerNum){ //create playerIdDiv var playerIdDiv = $('div').addClass(playerNum); for (var i = 0; i < divs; i++){ if (i === 0){ $('div').addClass('active1'); $(playerIdDiv).append('<div class="road"></div>'); } else { $(playerIdDiv).append('<div class="road"></div>'); } } //append playerIdDiv to body $('body').append(playerIdDiv); } // Remember: prototypes are shared functions between all game instances //update player's position Player.prototype.move = function() { $(document).on('keypress', function(event){ //if the key pressed is the player's key if(event.which === this.key){ //remove the class active1 from the div, then add it to the next div with class of road in the player's div $('div').removeClass('active1'); $(playerIdDiv + '.road').eq(this.position + 1).addClass('active1'); player1++; } }); }; function Game() { //Create a new instance of player 1 var player1 = new Player("Player 1", "red"); //Do the same for a player 2 var player2 = new Player("Player 2", "blue"); } // `Game.prototype.init` kicks off a new game with a board and two players Game.prototype.init = function() { // }; // Start the game! var game = new Game(); game.init(); })
const supertest = require('supertest'); const tap = require('tap'); const app = require('../lib/app'); const facts = require('../lib/facts.json'); let server; let request; tap.beforeEach((done) => { server = app.listen(); request = supertest(server); done(); }); tap.afterEach((done) => { server.close(); done(); }); tap.test('Getting a fact', (t) => { request .post('/') .expect(200) .end((err, res) => { if (err) throw err; t.equal(res.body.response_type, 'in_channel'); t.ok(facts.includes(res.body.text)); t.end(); }); });
/** * ProjectController * * @description :: Server-side actions for handling incoming requests. * @help :: See https://sailsjs.com/docs/concepts/actions */ const _ = require('lodash'); module.exports = { getProjects: (req, res, next) => { Project.find() .populate('votings') .then(found => { found.forEach(project => { let userVotings = []; project.votings.forEach(vote => { if (vote.user === req.userId) {userVotings.push(vote);} }); project.votings = userVotings; }); return res.json(found); }) .catch(err => { return res.serverError(err); }); }, };
const fourthLittlePig = { name: 'Pork Chop' } fourthLittlePig.house = 'steel' fourthLittlePig.favoriteHobby = 'dancing' console.log(fourthLittlePig) fourthLittlePig['favoriteHobby'] = 'Running from the Big Bad Wolf' console.log(fourthLittlePig) delete fourthLittlePig['favoriteHobby'] console.log(fourthLittlePig) const favoriteFood = [ 'pork', 'bacon', 'ham' ] console.log(favoriteFood) favoriteFood.unshift('tendorloin') console.log(favoriteFood) favoriteFood.push('greens') console.log(favoriteFood) favoriteFood[2] = 'Pizza' console.log(favoriteFood) const threeLittlePigs = { number: 5, adjective: 'cute', noun: 'dog', verbs: ['run', 'dance', 'jump', 'eat', 'drink', 'lie'], pluralNouns: ['students', 'geese', 'boys'] } console.log(`Once upon a time a time, there were ${threeLittlePigs.number} ${threeLittlePigs['adjective']} pigs. One day, their ${threeLittlePigs.noun} said, "You are all grown up and must ${threeLittlePigs.verbs[0]} on your own." So they left to ${threeLittlePigs.verbs[1]} their houses.The first little pig wanted only to ${threeLittlePigs.verbs[2]} all day and quickly built his house out of ${threeLittlePigs.pluralNouns[0]}.The second little pig wanted to ${threeLittlePigs.verbs[3]} and ${threeLittlePigs.verbs[4]} all day so he built his house with ${threeLittlePigs.pluralNouns[1]}.The third little pig knew the wolf lived nearby and worked hard to ${threeLittlePigs.verbs[5]} his house out of ${threeLittlePigs.pluralNouns[2]}.`)
/** * 创建时间:2018-08-30 10:32:46 * 作者:sufei Xerath * 邮箱:fei.su@gemii.cc * 版本号:1.0 * @版权所有 **/ import React, { Component } from 'react' import './index.css' import IptLimit from "../../../shareComponent/IptLimit"; import IptNum from "../../../shareComponent/IptNum"; import ColorPicker from "../../../shareComponent/RcolorPicker"; export default class PageButton extends Component { constructor() { super(); this.state = { colorState: false, block: false } this.selectColor = this.selectColor.bind(this); } selectColor() { const {disabled}= this.props if(disabled) return this.setState({ colorState: true }) } hideColor=() =>{ if(this.state.block) return this.setState({ colorState: false }) } mouseEnter = () => { this.setState({ block: true }) } mouseLeave = () =>{ this.setState({ block: false }) } setparamsHandle=(k,v)=>{ let data = this.props.data let css = eval('('+data.css+')') if(k=='pageButtonTxt'){ // 设置按钮文字 data.label = v }else if(k=='pageButtonSize'){ // 设置按钮文字大小 css.fontSize = v+'px' data.css = JSON.stringify(css) }else{ // 设置按钮文字颜色 css.backgroundColor = v.hex data.css = JSON.stringify(css) } this.props.updateItem(data) } render() { let { colorState } = this.state; let { data,disabled } = this.props let css = eval('('+data.css+')') return ( <div className='PageButton'> <div className="Pagetitle">提交按钮:</div> <div className="PageContent"> <div className='row'> <IptLimit widths={{ width: '316px' }} paramName={'pageButtonTxt'} placeholder={'请输入文字'} label={'显示文字:'} maxLength={10} value={data.label} limitState={false} widthsLa={{ width: '70px', textAlign: "right" }} setparamsHandle={this.setparamsHandle} disabled={disabled} /> </div> <div className="row"> <IptNum widths={{ width: '316px' }} paramName={'pageButtonSize'} label={'字体大小:'} limitState={false} minNum={12} value={isNaN(parseInt(css.fontSize))?'':parseInt(css.fontSize)} widthsLa={{ width: '70px', textAlign: "right" }} setparamsHandle={this.setparamsHandle} disabled={disabled} /> </div> <div className="row" tabIndex='1' onFocus={this.selectColor} onBlur={this.hideColor} onMouseEnter={this.mouseEnter} onMouseLeave={this.mouseLeave}> <div className="color-title"></div> <div className='color-content'> <span className='color-icon'></span> 按钮颜色 </div> { colorState ? <ColorPicker widths={{ top: '-300px', left: "160px" }} handleColor={this.setparamsHandle} paramName={'pageButttonColor'} pageTitleColor={css.backgroundColor} /> : '' } </div> </div> </div> ) } }
import dbFactory from '../../dbFactory'; import { exists } from 'fs'; const getDbRef = collectionName => { const db = dbFactory.create('firebase'); const ref = db.firestore().collection(collectionName); return ref; }; export const getAllCategory = () => { return getDbRef('subject') .doc('B95MoOWUo1V7rCNbN7hn') .get(); }; export const createSubjects = subjects => { return getDbRef('subject') .doc('B95MoOWUo1V7rCNbN7hn') .set(subjects); }; // For checking banner existance. export const getBannerFromDB = () => { return getDbRef('banner').get(); }; // create banner document if not exists. export const createBanner = bannerData => { return getDbRef('banner') .doc() .set(bannerData); };
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { withInfo } from '@storybook/addon-info'; import { checkA11y } from '@storybook/addon-a11y'; import Icon from './Icon'; const props = { style: { margin: '50px', }, description: 'This is a description of the icon and what it does in context', className: 'fa', }; storiesOf('Icon', module) .add('Icon', withInfo( ` Icons are used in the product to present common actions and commands. Modify the fill property to change the color of the icon. The name property defines which icon to display. For accessibility, provide a context-rich description with the description prop. `, ) (() => ( <div> <Icon name="fa-plus" {...props} /> <Icon name="fa-facebook" {...props} /> <Icon name="fa-user-circle" {...props} /> </div> )) );
import { useState } from "react" import { search } from "../api" import NewsCard from "./NewsCard" const Search = () => { const [searchResult, setSearchResult] = useState([]) const [searchQuery, setSearchQuery] = useState(''); const searchNews = async (query) => { const { data } = await search(query) setSearchResult(data.articles) } return ( <div className="min-h-screen w-[90vw]"> <div className="mt-64 w-[90vw]"> <h1 className="text-center font-black text-6xl text-dark">Cari berita di Newsthetic</h1> <div className="flex xl:w-1/2 m-auto border border-gray-400 mt-8"> <div className="flex items-center w-full"> <span className="material-symbols-outlined font-bold text-2xl ml-2 text-gray-500"> search </span> <input className="p-2 bg-white/20 placeholder:italic w-full" value={searchQuery} onChange={e => setSearchQuery(e.target.value)} onKeyPress={(e) => { if (e.key === 'Enter') { searchNews(searchQuery) } }} type="text" placeholder="Cari berita" /> </div> <button className="bg-dark text-white px-6" onClick={() => searchNews(searchQuery)}>Search</button> </div> <div className="flex flex-col md:grid gap-4 md:grid-cols-3 xl:grid-cols-4 mt-8"> {searchResult.sort((a, b) => { return new Date(b.publishedAt) - new Date(a.publishedAt) }).map((news, i) => ( <NewsCard key={i} news={news} /> ))} </div> </div> </div> ) } export default Search
import React, { PureComponent } from 'react'; import { Col } from 'reactstrap'; import { Card, CardBody, CardFooter } from 'reactstrap'; import { Field, reduxForm } from 'redux-form'; import DefaultPanelWithSubheader from './DefaultPanelWithSubhead'; import { PieChart, Pie, Tooltip, Legend, ResponsiveContainer } from 'recharts'; import { translate } from 'react-i18next'; class WizardFormOne extends PureComponent { constructor(props) { super(props); this.state = { isLoading: true, accounts: [], }; } async componentDidMount() { const response = await fetch('/api/getMyAccounts'); const body = await response.json(); this.setState({ accounts: body, isLoading: false }); } render() { const { accounts, isLoading } = this.state; const { t } = this.props; return ( <Col md={12} lg={12}> <form className='form'> <Card> <CardBody> <div className='card__title'> <h5 className='bold-text'>{t('forms.wizard_from.wizard_from_step1.title')}</h5> <h5 className='subhead'>{t('forms.wizard_from.wizard_from_step1.subtitle')}</h5> </div> <DefaultPanelWithSubheader data={accounts} /> </CardBody> </Card> </form> </Col> ) } } export default reduxForm({ form: 'wizard', destroyOnUnmount: false, forceUnregisterOnUnmount: true, })(translate('common')(WizardFormOne));
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export const store = new Vuex.Store({ strict: true, state:{ videoUrl: 'https://www.youtube.com/embed/DtKCNJmARF0' }, getters: { asteriskUrl: function(state){ var newUrl = '*' + state.videoUrl + '*'; return newUrl; } }, mutations: { changeUrl: (state, newUrl) => { var temp = newUrl.split('?'); temp = temp[temp.length-1].split('='); if(temp[0]=='v') state.videoUrl = 'https://www.youtube.com/embed/' + temp[temp.length-1]; else if (temp[0]=='list') { state.videoUrl = 'https://www.youtube.com/embed/videoseries?list=' + temp[temp.length-1] } } }, actions: { changeUrl: (context, payload) => { context.commit('changeUrl', payload); } } })
import { Model, DataTypes } from "sequelize"; class Office extends Model { static init(sequelize) { super.init( { id_office: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, id_office_niv_1: { type: DataTypes.INTEGER, }, id_office_niv_2: { type: DataTypes.INTEGER, }, id_office_niv_3: { type: DataTypes.INTEGER, }, id_office_niv_4: { type: DataTypes.INTEGER, }, }, { sequelize, schema: "public", freezeTableName: true, // mantém o nome da tabela singular tableName: "office", // nome da tabela timestamps: true, } ); return this; } static associate(models) { this.belongsTo(models.OfficeNiv01, { foreignKey: "id_office_niv_1", as: "office_niv_1", }); this.belongsTo(models.OfficeNiv02, { foreignKey: "id_office_niv_2", as: "office_niv_2", }); this.belongsTo(models.OfficeNiv03, { foreignKey: "id_office_niv_3", as: "office_niv_3", }); this.belongsTo(models.OfficeNiv04, { foreignKey: "id_office_niv_4", as: "office_niv_4", }); } } export default Office;
// Logger const logger = require('../logger'); // Business Errors const errorNames = require('../errors'); const BusinessError = require('../BusinessError'); // Entities const { Statistics } = require('../entities'); /** * Method to read the statistics * @param {Object} query - Filter query * @param {Object} select - Fields of document to return * @returns {Object} - The method returns an object with the element found by * the query criteria */ const readOne = async (query, select = { _id: 1 }) => (await Statistics.find(query, select) .limit(1) .lean({ virtuals: true }))[0]; /** * Method to create a new user statistic. * @param {Object} userId - Id of the User * @returns {Object} - The method returns an object with the * new user created. */ const create = async (userId) => { // Will create a new user; let userCreated; try { userCreated = await Statistics.create({ user: userId, gamesWins: 0, gamesDefeats: 0, gamesTie: 0, }); } catch (err) { logger.error(`(rps-user-module): Error creating user statistic: ${err.message}`); throw new BusinessError(errorNames.DATABASE_ERROR, 'rps-user-module'); } return userCreated; }; /** * Method to report statistics * @param {String} userId - Id of user * @param {String} kind - Type of statistic */ const reportStatistic = async (userId, kind) => { let paramsToUpdate = {}; switch (kind) { case 'WIN': paramsToUpdate = { $inc: { gamesWins: 1 } }; break; case 'DEFEAT': paramsToUpdate = { $inc: { gamesDefeats: 1 } }; break; case 'TIE': paramsToUpdate = { $inc: { gamesTie: 1 } }; break; default: paramsToUpdate = {}; } // Update statistics const updateStatus = await Statistics.update({ user: userId, }, paramsToUpdate); if ((updateStatus.ok === 0) || (updateStatus.nModified === 0)) { throw new BusinessError(errorNames.USER_DOES_NOT_EXISTS, 'rps-user-module'); } }; module.exports = { readOne, create, reportStatistic, };
angular.module('myApp.controllers', []) .controller('MainController', [ '$scope', 'RedditService', function($scope, RedditService) { var fetchSuccess = function(data, status) { $scope.articles = data.data.children; }; $scope.voteUp = function(article) { if (article.votes === undefined) { article.votes = 0; } article.votes++; }; $scope.voteDown = function(article) { if (article.votes === undefined) { article.votes = 0; } article.votes--; }; RedditService.fetchArticles(fetchSuccess); }]) .controller('SettingsController', ['$scope', function($scope) { $scope.setting = "initiated!"; }]);
var LinkedList = require('../linkedlist').SinglyLinkedList; var deleteDups = require('../01_remove_dup').deleteDups; var expect = require('chai').expect; describe("LinkedList", function() { describe("#deleteDups", function() { var ll; beforeEach(function() { ll = new LinkedList(); }); describe("empty LinkedList", function() { it("next should be null", function() { deleteDups(ll.head); expect(ll.head.next).to.be.null; }); }); describe("LinkedList with no duplicates", function() { it("should return the original LinkedList", function() { ll.insert("one"); ll.insert("two"); ll.insert("three"); deleteDups(ll.head); expect(ll.toArray()).to.deep.equal([ "one", "two", "three" ]); }); }); describe("LinkedList with duplicates", function() { it("should return a unique LinkedList", function() { ll.insert("one"); ll.insert("two"); ll.insert("three", "one"); ll.insert("three", "two"); ll.insert("two", "one"); deleteDups(ll.head); expect(ll.toArray()).to.deep.equal([ "one", "two", "three" ]); }); }); }); });
import React from 'react'; export default class Form extends React.Component { render() { return ( <div>Form <input></input> <input onChange={this.handleChange}>Add to Inventory</input> <input onClick={this.handleChange}>Cancel</input> </div> ) } }
import Menu from '../../Menu/Menu.page' import React from 'react'; import FooterComponent from '../../Footer/FooterComponent.page'; import BannerComponent from '../../BannerComponent/BannerComponent.page.jsx' import './Madrid.page.css' import reactDom from 'react-dom'; import VideoComponent from '../../VideoComponent/VideoComponent.page' import Gallary from '../../Gallary/Gallary.page'; export default function Madrid({sendRoute}){ const styleObject={ fontSize: 22, lineHight: 1.15, fontWeight: 400, letterSpace: 1.15 } const sendHome = (status) => { // the callback. Use a better name console.log("home",status); sendRoute(status); }; return( <div> <Menu sendHome={sendHome} /> <BannerComponent title={'Madrid'} imageLink={`/Assets/Spain/Madrid/9.jpg`}/> <div className="container visitingPlace"> <div className="row row-no-gutters"> <div className="col-xs-12 col-md-8"> <br /> <p style={styleObject}><b>Madrid, cheerful and vibrant at all hours, is famous for being an open city with all kinds of people from anywhere in the world.</b></p> <p style={styleObject}>In addition to its famous museums, busy streets dotted with all kinds of shops, restaurants with world cuisine or unbeatable nightlife, Madrid will surprise you with its charming, tranquil historic spots, with traditional and family-run century-old bars where friends meet up for a drink, all kinds of neighbourhoods, and cultural centres that offer an alternative type of tourism. Madrid has an authenticity that is hard to match. It is welcoming and diverse. Madrid is, without a doubt, one of Europe’s most interesting cities.</p> </div> <div className="col-xs-6 col-md-4"> <img src="/Assets/Spain/Madrid/7.jpg" alt="bilbao-pic" /> </div> </div> <hr className="lineOnPlace"/> <div className="row row-no-gutters"> <div className="col"> <h2>Culture and leisure at any time</h2> <p>Anyone in search of culture will find some of the most important museums in the world, such as the Prado, Reina Sofía or Thyssen. But we must not forget smaller options, full of charm, such as the Sorolla Museum or cultural centres like the Matadero or Conde Duque, which are continuously offering innovative exhibitions, concerts, guided tours, etc.</p> <p>Walking around Madrid means coming across iconic spots such as the stunning Royal Palace, the Plaza Mayor with 400 years of history, the buzzing Puerta del Sol, the famous Gran Vía full of shops, or the four tallest towers in Spain. Each neighbourhood offers a different experience: La Latina is ideal for tapas, Las Letras has the perfect combination of literature and fine dining… But Madrid also means relaxing in enormous parks such as the Parque del Retiro, and other lesser-known but equally charming parks like El Capricho.</p> <h2>Capital of food, fashion and nightlife</h2> <p>When it comes time to eat Madrid has two facets, both equally delicious. On the one hand, traditional bars where you can discover the old-fashioned, unpretentious atmosphere known as ‘castizo’, and why tapas are so much fun. On the other hand, avant-garde restaurants such as DiverXO and traditional markets converted into new gourmet spaces like San Miguel, which have become true temples of gastronomy. In Madrid, any time is a good time to enjoy a lively, urban atmosphere. For example, the increasingly famous weekend brunches in enclosed glass terraces, courtyards, rooftops, etc.</p> <p>Fashionistas will find all options: luxury shops on the Golden Mile, vintage establishments in areas such as Fuencarral, new designer markets like the Mercado de Motores, and craft workshops and bookshops over 100 years old. At dusk, some of the city’s viewpoints will surprise you with unique sunsets, at the Temple of Debod or the rooftop bar of the Círculo de Bellas Artes, for example. And at the end of the day... nightlife in Madrid is legendary with live music, all kinds of ambiences, music until the sun comes up...</p> <p>Madrid has its own beauty. Madrid stimulates and inspires. Madrid is an experience.</p> </div> </div> <hr className="lineOnPlace"/> <div className="row row-no-gutters"> <div className="col"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d194348.13981401525!2d-3.8196216908107608!3d40.437869758269194!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0xd422997800a3c81%3A0xc436dec1618c2269!2sMadrid%2C%20Spain!5e0!3m2!1sen!2sca!4v1625161332717!5m2!1sen!2sca" width="100%" height="400" allowfullscreen="" loading="lazy"></iframe> </div> </div> <div> <VideoComponent imageUrl={'/Assets/Spain/Madrid/5.jpg'} videoUrl={'https://www.youtube.com/watch?v=O1HTAwL9_bY&ab_channel=WonderlivTravel'}/> </div> <hr className="lineOnPlace"/> <div className="row row-no-gutters"> <div className="col gallary"> <h2 className="mb-4">Gallary</h2> <Gallary destination="Madrid" /> </div> </div> </div> <FooterComponent /> </div> ) }
import * as React from 'react'; import {useEffect, useState} from 'react'; import Card from '@material-ui/core/Card'; import CardHeader from '@material-ui/core/CardHeader'; import CardContent from '@material-ui/core/CardContent'; import Avatar from '@material-ui/core/Avatar'; import {makeStyles} from "@material-ui/core/styles"; import SubsDAL from "../../adapters/SubsDAL"; import AddSub from './Member/AddSub' import MovieList from './Member/MovieList' import {CardActions} from "@material-ui/core"; import MemberDelete from "./Member/MemberDelete"; import MemberEdit from "./Member/MemberEdit"; const useStyles = makeStyles((theme) => ({ root: { maxWidth: 300, }, button: { margin: theme.spacing(1), }, })); const getInitials = (nameString) => { const fullName = nameString.split(' '); const initials = fullName.shift().charAt(0) + fullName.pop().charAt(0); return initials.toUpperCase(); } export default function MemberComp(props) { const classes = useStyles(); const [subs, setSubs] = useState([]) const [toggleRerender, setToggleRerender] = useState(false) useEffect(async () => { const respSubs = await SubsDAL.getSubs(props.member._id) setSubs(respSubs.data) }, [toggleRerender]) const handleAddMovie = (obj) => { props.callBackAddMovie(obj) setToggleRerender(!toggleRerender) } return ( <Card className={classes.root} style={{backgroundColor: "#f3f3f3"}}> <CardHeader avatar={ <Avatar aria-label="member" style={{ backgroundColor: props.member.color }}> {getInitials(props.member.name)} </Avatar> } title={props.member.name} subheader={props.member.email} /> <CardContent> <AddSub id={props.member._id} rerenderParentCallback={() => setToggleRerender(!toggleRerender)} callBackAddMovie={handleAddMovie} /> <br/> { subs.movies && subs.movies.map((movie, i) => { return <MovieList key={i} movie={movie} rerenderParentCallback={() => setToggleRerender(!toggleRerender)} callBackDeleteMovie={(id) => props.callBackDeleteMovie({movieId: id, subsId: subs._id})} /> }) } </CardContent> <CardActions> <MemberEdit member={props.member} callBack={(obj) => props.callBackEdit(obj)} /> <MemberDelete member={props.member} callBack={(id) => props.callBackDelete(id)} /> </CardActions> </Card> ); }
var searchData= [ ['secondsuntil',['secondsUntil',['../classlsd__slam_1_1_timestamp.html#a4caed49b69cb2a1a6f0634dc5a76c7e8',1,'lsd_slam::Timestamp']]], ['setdepth',['setDepth',['../classlsd__slam_1_1_frame.html#aa869fc645781090678dc61399ef26f73',1,'lsd_slam::Frame']]], ['setdepthfromgroundtruth',['setDepthFromGroundTruth',['../classlsd__slam_1_1_frame.html#a7e563deb5eadcaddc85d7618bb021b1b',1,'lsd_slam::Frame']]], ['setreceiver',['setReceiver',['../classlsd__slam_1_1_notify_buffer.html#abff5c7a6af7790acfc5cc2f83ae541c0',1,'lsd_slam::NotifyBuffer']]], ['setvisualization',['setVisualization',['../classlsd__slam_1_1_slam_system.html#a3e42198c83b0bc44bef086dd77647535',1,'lsd_slam::SlamSystem']]], ['size',['size',['../classlsd__slam_1_1_notify_buffer.html#ac077a4a4bb56f5dd9acd551c7c56a3a3',1,'lsd_slam::NotifyBuffer']]] ];
/* * Copyright (C) 2009-2013 SAP AG or an SAP affiliate company. All rights reserved */ jQuery.sap.declare("sap.ca.ui.charts.BarListItemRenderer"); jQuery.sap.require("sap.ui.core.Renderer"); jQuery.sap.require("sap.m.ListItemBaseRenderer"); /** * @class DisplayListItem renderer. * @static */ sap.ca.ui.charts.BarListItemRenderer = sap.ui.core.Renderer.extend(sap.m.ListItemBaseRenderer); /** * Renders the HTML for the given control, using the provided * {@link sap.ui.core.RenderManager}. * * @param {sap.ui.core.RenderManager} * oRenderManager the RenderManager that can be used for writing to the * Render-Output-Buffer * @param {sap.ui.core.Control} * oControl an object representation of the control that should be * rendered */ sap.ca.ui.charts.BarListItemRenderer.renderLIAttributes = function(rm, oLI) { rm.addClass("sapMBLI"); }; sap.ca.ui.charts.BarListItemRenderer.renderLIContent = function(rm, oLI) { var isAxis = oLI.getAxis(); // List item axis if (isAxis) { rm.write("<p for='" + oLI.getId() + "-axis' class='sapMBLIAxis'>"); rm.writeEscaped(oLI.getAxis()); rm.write("</p>"); } var isGroup = oLI.getGroup(); // List item group if (isGroup) { rm.write("<label for='" + oLI.getId() + "-value' class='sapMBLIGroup'>"); rm.writeEscaped(oLI.getGroup()); rm.write("</label>"); } var isValue = oLI.getValue(); // List item value if (isValue) { rm.write("<div id='" + oLI.getId() + "-value' class='sapMBLIValue'>"); rm.writeEscaped(oLI.getValue()); rm.write("</div>"); } };
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const { translatedSchema } = require('../../shared/schemas'); const { CONTENT_TYPES } = require('../../shared/constants'); const { deserialize } = require('./lib/serialization'); const ContentSchema = new Schema( { type: { type: String, enum: Object.values(CONTENT_TYPES), }, title: translatedSchema, urlSlugs: { type: [String], validate: arr => !!arr.length, }, pageSlug: String, images: [{ type: String, ref: 'Image' }], }, { timestamps: true, strict: false, } ); ContentSchema.index({ createdAt: -1 }); ContentSchema.index({ urlSlugs: 1 }); ContentSchema.virtual('urlSlug').get(function() { return this.urlSlugs[0]; }); ContentSchema.method('deserialize', function() { return deserialize(this); }); module.exports = mongoose.model('Content', ContentSchema, 'content');
import Link from "next/link"; import LinkCard from "../../../components/LinkCard"; const presentations = [ { _id: "ddb9da7e-5031-11eb-ae93-0242ac130002", title: "360° of Separation", description: "Association of Talent Development International Conference - A presenation on how to use 360° video and web technolgies (including authoring tools) to produce proof-of-concept interactive video.", bgImage: "/images/pages/presentations/360.jpg", image: "/images/pages/presentations/360_logo.png", color: "#542f9e", href: "/portfolio/presentations/360-degrees-of-separation", }, { _id: "ddb9da7e-5031-11eb-ae93-asf23423434", title: "Promise vs Hype", description: "Association of Talent Development International Conference - A presenation and rubric for evaluating technology prior to large-scale organizational adoption.", bgImage: "/images/pages/presentations/hype.jpg", image: "/images/pages/presentations/tech_logo.png", color: "#836409", href: "/portfolio/presentations/promise-vs-hype", tech: ["react", "sass", "xd", "ps", "ga", "sheets"], roles: ["tech", "software", "ux/ui", "graphics"], tags: ["home"], }, { _id: "ddb9da7e-5031-11eb-ae93-2342397asdf", title: "Interactive Video in Articulate Storyline", description: "Association of Talent Development Central Indiana Chapter Tech Summit Presenation on more effective ways to put together interactive video.", bgImage: "/images/pages/presentations/storyline.jpg", image: "/images/pages/presentations/storyline_logo.png", color: "#45179f", href: "/portfolio/presentations/high-fidelity-low-cost-interactive-video-in-storyline", tech: ["react", "sass", "xd", "ps", "ga", "sheets"], roles: ["tech", "software", "ux/ui", "graphics"], tags: ["home"], }, ]; const HomePageConferencePresentations = () => { return ( <section> <article className="container-fluid bg-info text-center text-white pt-5 pb-3"> <div className="container py-3"> <h3>Conference Presentations</h3> <div className="col-12 offset-0 col-md-8 offset-md-2 mt-3 px-4"> <p> I'm a bit of a nerd. I enjoy sharing cool new ideas, techniques, and technologies just as much as I love to learn. The best thing is seeing someone get excited by a new idea. My wife tells me I should be a teacher. </p> </div> </div> </article> <article id="HomePage-presentations" className="container-fluid bg-info pb-2 mb-5" > <div className="container"> <div className="row mb-5"> {/* map over hope page portfolioItems */} {presentations.map((item) => ( <LinkCard key={item._id} card={item} /> ))} </div> </div> </article> </section> ); }; export default HomePageConferencePresentations;
//页面加载 (function(){ var $nav = $('.container .nav'); var $panels = $('.container .panels'); $nav.append('<li class="all">全部</li>'); $panels.append('<li>\ <div class="box c-tabs" data-p="-1">\ <div class="hd">\ <div class="loader">\ <input data-p="-1" type="button" value="重新获取"/>\ <img src="../image/loader.gif"/>\ </div>\ <h2>全部</h2>\ <ul class="c-nav"><li>最新</li></ul>\ </div>\ <div class="bd">\ <ul class="c-panels"><li></li></ul>\ </div>\ </div>\ </li>'); for(var i=0;i<_data.length;i++){ $nav.append('<li>'+_data[i]['name']+'</li>'); var names = ''; var lists = ''; for(var j=0;j<_data[i]['items'].length;j++){ names += '<li>'+_data[i]['items'][j]['name']+'</li>'; lists += '<li></li>'; } $panels.append('<li>\ <div class="box c-tabs" data-p="'+i+'">\ <div class="hd">\ <div class="loader">\ <input data-p="'+i+'" type="button" value="重新获取"/>\ <img src="../image/loader.gif"/>\ </div>\ <h2>'+_data[i]['name']+'</h2>\ <ul class="c-nav">'+names+'</ul>\ </div>\ <div class="bd">\ <ul class="c-panels">'+lists+'</ul>\ </div>\ </div>\ </li>'); } $nav.append('<li class="setting">设置</li>'); $panels.append('<li>\ <div class="box c-tabs">\ <div class="hd">\ <h2>设置</h2>\ </div>\ <div class="bd">\ <p></p>\ <p><label>黑名单:</label><textarea id="blacklist" placeholder="关键词之间使用英文\',\'分割"></textarea></p>\ <p><label>白名单:</label><textarea id="whitelist" placeholder="关键词之间使用英文\',\'分割"></textarea></p>\ </div>\ </div>\ </li>'); })(); //页面tabs效果 var $tabs = $(".tabs"); var $panels = $tabs.find(".panels>li"); var $c_tabs = $(".c-tabs"); var $c_panels = $c_tabs.find(".c-panels>li"); $tabs.tabs({ contentCls:"panels", triggerType:"click" }); $c_tabs.tabs({ navCls:"c-nav", contentCls:"c-panels", triggerType:"click" }); //设置 (function(){ var $blacklist = $("#blacklist"); var $whitelist = $("#whitelist"); if(localStorage['blacklist']){ $blacklist.val(localStorage['blacklist']); } if(localStorage['whitelist']){ $whitelist.val(localStorage['whitelist']); } $blacklist.change(function(){ localStorage['blacklist']=$blacklist.val(); }); $whitelist.change(function(){ localStorage['whitelist']=$whitelist.val(); }); })(); //默认数据加载 (function(){ var data = {}; var num = 0; if(localStorage['updateTime']&&+new Date()-localStorage['updateTime']<3.6e6*_global['expires']){ //如果再有效期内则不更新(cookie的方式失效了) for(var i=0;i<_data.length;i++){ for(var j=0;j<_data[i]['items'].length;j++){ (function(p,c){ var item = _data[p]['items'][c]; var id = p+','+c; if(localStorage[id]){ //缓存存在 data = JSON.parse(localStorage[id]); //获取缓存中的数据 data.length = _global['page_count']; //截取缓存中第一页的数据 _global['page'][id] = Math.ceil(_global['page_count']/item['count']); load_list(p+1,c,data); num++; if(num==_global['port_count']){ load_list(0,0,getNewsSort()); } }else{ //缓存不存在 getNews(id,function(data){ //请求数据借口,获取数据 load_list(p+1,c,data); num++; if(num==_global['port_count']){ load_list(0,0,getNewsSort()); } }); } })(i,j); } } }else{ //如果缓存过期,获取全部新数据 getAllNews(); } })(); //手动数据加载 $(".loader input").click(function(){ var $this = $(this); var p = +$this.data('p'); var $img = $this.next().show(); console.log('p#',p); if(p<0){ //如果加载的数据源是全部,则更新所有数据 getAllNews(function(){ $img.hide(); }); }else{ var items = _data[p]['items']; var num = 0; var $cpanel = $panels.eq(p).find(".c-panels>li").html("<span class='loading'>数据加载中...</span>"); for(var i = 0;i <items.length;i++){ (function(c){ var id = p+','+c; _global['page'][id]=0; //只加载第一页 getNews(id,function(data){ $cpanel.eq(c).empty(); load_list(p+1,c,data); //改变当前页数据 num++ if(num==items.length){ _global['page']['all'] = 0; load_list(0,0,getNewsSort()); //改变汇总页数据 $img.hide(); } }); })(i); } } }); //加载更多 $(".box").on("click",".more a",function(){ var $this = $(this); var $cpanel = $this.parents('.c-panels li'); var c = $cpanel.index(); var p = +$cpanel.parents('.box').data('p'); $this.replaceWith("<span>加载中...</span>"); if(p<0){ //如果加载的数据源是全部,则更新所有数据 load_list(0,0,getNewsSort()); }else{ var items = _data[p]['items']; item = items[c]; var id = p+','+c; getNews(id,function(data){ load_list(p+1,c,data); //改变当前页数据 _global['page']['all'] = 0; load_list(0,0,getNewsSort()); //改变汇总页数据 }); } return false; }); //加载节点 function load_list(p,c,data){ var len = data.length; var sum = Math.floor(len/_global['page_count'])*_global['page_count']; //只输入page_count的倍数 var $panel = $panels.eq(p); var $c_panel = $panel.find(".c-panels li:eq("+c+")"); if(len==_global['page_count']){ //数据只有page_count说明为非追加数据 $c_panel.empty(); }else{ $c_panel.find('.more').remove(); } for(var i=sum-_global['page_count']; i<sum; i++){ var item = data[i]; $c_panel.append("<p><span class='time'>"+showTime(item['time'])+"</span><a href='"+item['url']+"' target='_blank'>"+item['title']+"</a></p>"); } $c_panel.append("<div class='more'><a href='#'>加载更多</a></div>"); } //获取所有游戏 function getAllNews(callback){ callback = callback || function(){}; var data = []; var num = 0; localStorage['updateTime'] = +new Date(); //最后更新时间 for(var i=0;i<_data.length;i++){ for(var j=0;j<_data[i]['items'].length;j++){ (function(p,c){ var id = p+','+c; _global['page'][id]=0; //只加载第一页 getNews(id,function(data){ load_list(p+1,c,data); num++; if(num==_global['port_count']){ _global['page']['all']=0; load_list(0,0,getNewsSort()); callback(); } }); })(i,j); } } return data; }
/** * @param {string} s * @param {number} rows * @return {string} */ const zigzag = (s, rows) => { // // Y(1)E(2)L(3)L(4)O(3)W(2)P(1)I(2)N(3)K(4) if (rows === 1) { return s; } let results = []; for (let i = 0; i < rows; i++) { results[i] = ''; } let chars = s.split(''); let down = true; let row = 0; for (let i = 0; i < chars.length; i++) { results[row] += chars[i]; if (down) { row++; if (row === rows - 1) { down = false; } } else { row--; if (row === 0) { down = true; } } } let result = ''; for (let i = 0; i < results.length; i++) { result += results[i]; } return result; }; console.log(zigzag('YELLOWPINK', 4));
import React from 'react'; import {BrowserRouter, Link, Route} from 'react-router-dom'; import {SeverityLevel} from '@microsoft/applicationinsights-web'; import './App.css'; import { getAppInsights } from './TelemetryService'; import TelemetryProvider from './telemetry-provider'; const Home = () => ( <div> <h2>Home Page</h2> </div> ); const About = () => ( <div> <h2>About Page</h2> </div> ); const Header = () => ( <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> ); const App = () => { let appInsights = null; function trackException() { appInsights.trackException({ error: new Error('some error'), severityLevel: SeverityLevel.Error }); } function trackTrace() { appInsights.trackTrace({ message: 'some trace', severityLevel: SeverityLevel.Information }); } function trackEvent() { appInsights.trackEvent({ name: 'some event' }); } function throwError() { let foo = { field: { bar: 'value' } }; // This will crash the app; the error will show up in the Azure Portal return foo.fielld.bar; } function ajaxRequest() { let xhr = new XMLHttpRequest(); xhr.open('POST', 'https://httpbin.org/status/200'); xhr.setRequestHeader('Authorization', 'Bearer blablabla'); xhr.setRequestHeader('Something', 'SomethingElse'); xhr.setRequestHeader('SomeOtherThing', 'SomeOtherElse'); xhr.send(); } function fetchRequest() { fetch('https://httpbin.org/status/200', { method: 'POST', headers: { 'Authorization': 'Bearer blablabla', 'someHeader': 'someValue' }}); } return ( <BrowserRouter> <TelemetryProvider instrumentationKey="YOURINSTRUMENTATIONKEY" after={() => { appInsights = getAppInsights() }}> <div > <Header /> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </div> <div className="App"> <button onClick={trackException}>Track Exception</button> <button onClick={trackEvent}>Track Event</button> <button onClick={trackTrace}>Track Trace</button> <button onClick={throwError}>Autocollect an Error</button> <button onClick={ajaxRequest}>Autocollect a Dependency (XMLHttpRequest)</button> <button onClick={fetchRequest}>Autocollect a dependency (Fetch)</button> </div> </TelemetryProvider> </BrowserRouter> ); }; export default App;
import React, {Fragment} from 'react'; import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, TouchableOpacity, Image, } from 'react-native'; import HomeSearchTop from '../navigations/HomeSearchTopNavigation'; const HomeSearch = ({navigation}) => { return ( <HomeSearchTop /> // <Fragment> // <StatusBar barStyle="dark-content" /> // <SafeAreaView /> // <ScrollView style={{backgroundColor: 'lightgray'}}> // <View> // <Text>홈 검색</Text> // </View> // </ScrollView> // </Fragment> ); }; const styles = StyleSheet.create({}); export default HomeSearch;
const expect = require('chai').expect; const FlashCache = require('../index'); const INTREVAL = 1000; var cache = new FlashCache({interval:INTREVAL}); const TEST_LEN = 100 * 1000;//100K const data = new Array(TEST_LEN); for (let i=0;i<TEST_LEN;i++) { data[i] = i+1; } const KEY = 'key'; const VALUE = 'something'; describe('clear test',function() { it('should set cache success',function() { cache.save(KEY,VALUE); expect(cache.get(KEY)).to.equal(VALUE); }); it('should remove a value success',function() { cache.remove(KEY); expect(cache.getElement(KEY)).to.be.equal(null); }); it('should insert ' + TEST_LEN + ' elements success',function(done) { for (let i=0;i<TEST_LEN;i++) { cache.save(i,data[i]); } expect(cache.young.size).to.be.equal(TEST_LEN); setTimeout(function() { expect(cache.young.size).to.be.equal(0); expect(cache.old.size).to.be.equal(TEST_LEN); done(); },INTREVAL) }); it('should clear all success', function() { cache.clearAll(); expect(cache.young.size).to.be.equal(0); expect(cache.old.size).to.be.equal(0); }); });
$(function () { /* style scroll end*/ })
import "./App.css"; import Header from "./Componets/Header"; import HomeScreen from "./Screens/HomeScreen"; import { BrowserRouter as Router, Route } from "react-router-dom"; import { Container } from "react-bootstrap"; function App() { return ( <Router> <Header /> <main className="py-5"> <Container> <Route path="/" exact component={HomeScreen} /> </Container> </main> </Router> ); } export default App;
//ajax request to logout, sends to functions.php, buttontype tells functions what our request wants to be done. function logout() { var postreq = new XMLHttpRequest(); postreq.onreadystatechange = function () { if (postreq.readyState == 4) { if (postreq.status == 200 || window.location.href.indexOf("http") == -1) { location.reload(); } else { alert("An error has occured making the request"); } } } var buttontypeval = encodeURIComponent("logout"); var parameters = "buttontype=" + buttontypeval; postreq.open("POST", "http://www.alanguagebank.com/employeecenter/functions.php", true); postreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); postreq.send(parameters); }
import Observable from "./observable.js"; import TaskArr from "../task/taskArr.js"; import Task from "../task/task.js"; import { createId, isArray, isFunction } from "../utils/utils.js"; import get from '../utils/get.js'; const interceptorNames = [ 'onError', 'onStart', 'onEnd', 'onTaskStart', 'onTaskError', 'onTaskEnd', ]; const pipelineRunId = createId('$pipeline_run_id'); /** * base queue */ class BasePipeline { constructor(config) { const ctx = config.context; this.config = config; this.config.context = (ctx !== undefined) && (ctx !== false); this._tasks = new TaskArr(); // 每次执行共享,后续考虑是否分隔每次执行context this.context = this.config.context ? ctx : null; this._initObservables(); this._runIds = {}; } _initObservables() { this.observables = {}; interceptorNames.forEach((name) => { this.observables[ name ] = new Observable(); }); } addTask(task) { if (isArray(task)) { const tasks = task.filter(Task.isValid); this._tasks.push(tasks); task.forEach(this._setup.bind(this)); } else { if (Task.isValid(task)) { this._tasks.push(task); this._setup(task); } } return this; } intercept(config = {}) { const ids = {}; interceptorNames.forEach((name) => { const fn = config[ name ]; if (isFunction(fn)) { ids[ name ] = this.observables[ name ].subscribe(fn); } }); return this; } unintercept(ids = {}) { interceptorNames.forEach((name) => { const id = ids[ name ]; this.observables[ name ].unsubscribe(id); }); } _trigger(eventName, ...args) { const observable = this.observables[ eventName ]; if (observable) { observable.trigger(...args); } } _setup(task) { task.setup({ onError: this._onTaskError.bind(this), onExecute: this._onTaskStart.bind(this), onDone: this._onTaskEnd.bind(this), config: this.config, }); } _cleanRunStatus(runId) { if (this._runIds[ runId ]) { delete this._runIds[ runId ]; } } _onPipelineStart() { this._trigger('onStart'); } // 当bail 或者所有的task都执行完毕 _onPipelineEnd(runId, result) { const config = this._runIds[ runId ]; if (config) { this._trigger('onEnd', result); config.status = 'done'; config.resolve(result); this._cleanRunStatus(runId); } } // 并行不会block,所以永远不会走到这里 // 只有串行,且continueIfError设置为false _onPipelineError(runId, e) { const config = this._runIds[ runId ]; if (config) { this._trigger('onError', e); config.status = 'error'; config.reject(e); this._cleanRunStatus(runId); } } _onTaskStart(runId, task) { this._trigger('onTaskStart', task.name); this._updateTaskStatus(runId, task, 'start', null, false); } _onTaskEnd(runId, task, result) { this._trigger('onTaskEnd', task.name, result); this._updateTaskStatus(runId, task, 'end', result); } _onTaskError(runId, task, e, checkStatus) { this._trigger('onTaskError', task.name, e); this._updateTaskStatus(runId, task, 'error', null, checkStatus); } _updateTaskStatus(runId, task, status, result, checkStatus = true) { const tasks = get(this._runIds, `${runId}.tasks`); if (tasks) { tasks[ task.id ] = status; } checkStatus && this._checkRunnableTask(runId, result); } _checkRunnableTask(runId, result) { const runConfig = this._runIds[ runId ]; if (!runConfig || (runConfig !== 'start')) { return; } const tasks = runConfig.tasks; if (!tasks) { return; } const stillRunTask = Object.keys(tasks) .find((taskId) => { return tasks[ taskId ] === 'start'; }); if (!stillRunTask) { this._onPipelineEnd(result); } } _getTaskArgs(runId, isFirstTask = false) { const { context, waterfall } = this.config; let newArgs; const config = this._runIds[ runId ]; if (config) { if (waterfall && !isFirstTask) { newArgs = [ config.waterfall ]; } else { newArgs = config.runArgs; } } if (context) { newArgs.unshift(this.context); } return newArgs; } run() { this._onPipelineStart(); return pipelineRunId(); } } export default BasePipeline;
var mainModule = angular.module("mainApp"); mainModule.controller("sliderController",function($scope){ });
import React from "react"; import { Marker } from "react-simple-maps"; class Circle extends React.Component { static defaultProps = { zoom: 1, }; render() { const {zoom} = this.props; return ( <circle r={3 / zoom} fill="#F00" stroke="#fff" strokeWidth={0.5 / zoom} /> ); } } class Markers extends React.Component { static defaultProps = { zoom: 1, } render() { const {markers, zoom, onMouse} = this.props; return ( markers.map( ({name, latitude, longitude}, index) => ( <Marker key={index} coordinates={[longitude, latitude]} onMouseEnter={() => {onMouse(name);}} onMouseLeave={() => {onMouse("");}} > <Circle zoom={zoom}/> /> </Marker> ) ) ); } } export default Markers;
importScripts('https://pxl.daria-markina.dev.altkraft.com/service-worker.js?id=MXwzMw..');
(function() { 'use strict'; angular.module('app').controller('UserProfileController', UserProfileController); UserProfileController.$inject = [ '$location', '$rootScope', 'UserService' ]; function UserProfileController($location, $rootScope, UserService) { var vm = this; vm.userEmail = $rootScope.globals.currentUser.username; UserService.get(vm.userEmail).then(function(response) { vm.userName = response.name; vm.userPassword = response.password; }, function(error) { vm.error = error; }); vm.edit = edit; vm.error = null; function edit() { UserService.update(vm.userEmail, vm.userName, vm.userPassword) .then(function(response) { if (response.message) { vm.error = response.message; } else { $rootScope.logout(); } }); } } })();
'use strict'; var classNames = require('classnames'); var React = require('react'); module.exports = React.createClass({ displayName: 'MenuItem', propTypes: { disabled: React.PropTypes.bool, selected: React.PropTypes.bool, }, getDefaultProps() { return { disabled: false, selected: false, }; }, render: function() { var {className, disabled, selected, ...props} = this.props; var disabledClass = disabled && 'pure-menu-disabled'; var selectedClass = selected && 'pure-menu-selected'; return ( <li className={ classNames('pure-menu-item', className, disabledClass, selectedClass) } {...props}>{props.children}</li> ); }, });
const express = require('express') const app = express.Router() const Users = require('./users') const AuthenMiddleware = require('./../../middleware/authen') const multer = require('multer') var upload = multer({ fileFilter: (req, file, cb) => { var filetypes = /jpg|peg|png|gif/.test(file.mimetype) if (filetypes) { return cb(null, true) } } }) app.get('', (req, res)=>{ res.send('API users running.') }) app.post('/search', new Users().search) app.get('/profile',[ new AuthenMiddleware().verifyJWT ], new Users().getByID) app.post('/create', [ new AuthenMiddleware().accessAll ],new Users().createUser) app.put('/update/:user_id', [ new AuthenMiddleware().verifyJWT ], new Users().updateUser) app.delete('/delete/:user_id',[ new AuthenMiddleware().accessAll ], new Users().deleteUser) app.post('/upload',[ upload.single('file') ], new Users().UploadImage) module.exports = app
export const state = () => ({ paymentList: [] }) export const actions = { getPaymentList ({ commit }, data) { commit('SET_PAYMENT_LIST', [ { id: '1', name: 'QR code' }, { id: '2', name: 'Billing' }, { id: '3', name: 'House use' } ]) } } export const mutations = { SET_PAYMENT_LIST (state, data) { state.paymentList = data } }
export const filters = { _: 'filters', get: () => [filters._], year: { get: () => [filters._, 'year'], }, genre: { get: () => [filters._, 'genre'], }, rating: { get: () => [filters._, 'rating'], }, playId: { get: () => [filters._, 'play_id'], }, }
const Paragraph = require("../src/Paragraph.js") const argv = require("minimist")(process.argv.slice(2)) var para = new Paragraph(argv._[0] || "Hello, I'm Joel") para.fetchInfo().then(() => { for(var i in para.bits) { if(!para.bits[i].isWord) console.log(para.bits[i]) else { console.log(para.bits[i].w, para.bits[i]._pos) } } })
var communityId=3; var this_week_an=0; var this_week_zu=0; var last_week_an=0; var last_week_zu=0; var to_day_an=0; var to_day_zu=0; var this_data_an=0; var this_data_zu=0; var map={}; function getCommunityId(communit) { var top_name= document.getElementsByName("top_name"); for ( var i = 0; i < top_name.length; i++) { top_name[i].className=""; } document.getElementById("top_"+communit).className="select"; communityId=communit; thisClickNum2(); } function thisClickNum2() { // var path = "/api/v1/communities/1/users/1/orderHistories/getClickAmount?url=http://120.24.232.121:8080/statUsers/stat/getStat.do"; var path="/stat/getStat.do?communityId="+communityId; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { var week=data.Week; map["this_week_an"]=week[1]; map["this_week_zu"]=week[3]; var this_date=data.today; map["this_data_an"]=this_date[1]; map["this_data_zu"]=this_date[3]; var to_day=data.yesterday; map["to_day_an"]=to_day[1]; map["to_day_zu"]=to_day[3]; var last_week=data.lastWeek; map["last_week_an"]=last_week[1]; map["last_week_zu"]=last_week[3]; getUserTop(); getTop(); }, error : function(er) { } }); } thisClickNum2(); setInterval("thisClickNum2()",1000*60*2); function getUserTop() { var path = "/api/v1/communities/"+communityId+"/userStatistics/getUserRegister"; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; zong=data.installsNum; document.getElementById("zong_num").innerHTML = data.registerNum; document.getElementById("zong_num_an").innerHTML = data.installsNum-data.testNum; }, error : function(er) { } }); } function getUserRegisterTime(biao,startTime,endTime) { var path = "/api/v1/communities/"+communityId+"/userStatistics/getUserRegisterEndTime?endTime="+endTime; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; var total=0; var testTotal=0; var registerList=0; var listUn=0; var listUn2=0; var registerUser=data.installsNum-data.testNum; var registerNum=data.registerNum; var an=map[biao+"_an"]; var zu=map[biao+"_zu"]; document.getElementById(biao).innerHTML = an; var top_user = 0; var registerUser_user = 0; if(registerNum>0){ top_user = (((zu /registerNum)) * 100).toFixed(2); } if(registerUser>0){ registerUser_user = (((an /registerUser)) * 100).toFixed(2); } document.getElementById(biao+"_xiao").innerHTML = registerUser_user+"%"; document.getElementById(biao+"_register_huo").innerHTML = zu; document.getElementById(biao+"_register_xiao").innerHTML = top_user+"%"; }, error : function(er) { } }); } function active(biao,startTime,endTime,registerNum,registerUser,installsUser) { var myDate = new Date(stringToTime(startTime)); var myDate2 = new Date(stringToTime(endTime)); var dates = Math.abs((myDate2 - myDate)) / (1000 * 60 * 60 * 24); var path = "/api/v1/communities/"+communityId+"/userStatistics/getLaunchesStatistics?startTime="+startTime+"&endTime="+endTime; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; var total=0; var testTotal=0; var registerList=0; var listUn=0; var listUn2=0; var listU1=new Array(); var listU= mapActive[biao]; for ( var i = 0; i < data.length; i++) { if(mapUser[data[i].userClick.emobId]=="1"){ if(data[i].userClick.emobId!="null"&&data[i].userClick.emobId!=-1){ if(mapTryOut[data[i].userClick.emobId]!="1"){ listU1[listUn++]=data[i].userClick.emobId; total++; }else{ testTotal++; } } } } listU1= listU1.concat(listU); listU1=listU1.unique2(); total=listU1.length; for ( var i = 0; i < listU1.length; i++) { if(mapRegisterList[listU1[i]]=="1"){ registerList++; } } document.getElementById(biao).innerHTML = total; var top_user = 0; var registerUser_user = 0; if(registerNum>0){ top_user = (((total /registerNum)) * 100).toFixed(2); } if(registerUser>0){ registerUser_user = (((registerList /registerUser)) * 100).toFixed(2); } document.getElementById(biao+"_xiao").innerHTML = top_user+"%"; document.getElementById(biao+"_register_huo").innerHTML = registerList; document.getElementById(biao+"_register_xiao").innerHTML = registerUser_user+"%"; }, error : function(er) { } }); } function quickUserData(){ var myDate = new Date(); var month = myDate.getMonth() + 1; var da = myDate.getDate() + 1; var startTime = myDate.getFullYear() + "-" + month + "-" + myDate.getDate() + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00"; getUserRegisterTime('this_data',startTime,endTime); } function thisUserData(){ var myDate = new Date(); var month = myDate.getMonth() + 1; var da = myDate.getDate()-1; var startTime = myDate.getFullYear() + "-" + month + "-" +da + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" + myDate.getDate() + " 00:00:00"; getUserRegisterTime('to_day',startTime,endTime); } function weekUser() { var d = getPreviousWeekStartEnd(); var startTime = d.start; var endTime = d.end; getUserRegisterTime('last_week',startTime,endTime); } function benWeekUser() { var d = getWeekBenUp(); var startTime = d.start; var endTime = d.end; getUserRegisterTime('this_week',startTime,endTime); } function getTop() { thisUserData(); quickUserData(); weekUser() ; benWeekUser(); }
const em = EventEmitter(); let referenceId = 0; let isCollecting = false; let isUpdating = false; function defineProps(store, key, target, globalKey) { Object.defineProperty(store, key, { get: function () { em.emit('get', { value: target[key], globalKey }); return target[key]; }, set: function (newValue) { const diffs = target[key] !== newValue; target[key] = newValue; (diffs || isCollecting && !isUpdating) && em.emit(globalKey.toString(), target[key]); }, enumerable: true }); } function getter(fn) { let ret = ''; const rem = em.on('get', function (p) { ret = p; isCollecting = false; }); fn(); rem(); return ret; } (function () { function Reactive() {} window.rx = { create: function (target) { const store = new Reactive(); Object.keys(target).forEach(function (key) { let globalKey = referenceId.toString(); const isFunction = target[key] instanceof Function; if (isFunction) { let get = getter(target[key]); globalKey = get.globalKey; target[key] = get.value; em.on(globalKey, value => target[key] = value); } else { referenceId++; } defineProps(store, key, target, globalKey); if (!isFunction && store[key] instanceof Array) { const oldPush = store[key].push; const oldSplice = store[key].splice; store[key].push = function () { oldPush.apply(store[key], arguments); em.emit(globalKey.toString(), store[key]); }; store[key].splice = function () { oldSplice.apply(store[key], arguments); em.emit(globalKey.toString(), store[key]); }; } }); return store; }, connect: function (store, callback) { const reactive = (store instanceof Reactive) ? store : window.rx.create(store); const remove = Object.keys(reactive) .map(key => { isCollecting = true; const { globalKey } = getter(() => { reactive[key] = reactive[key]; }); return em.on(globalKey, function (v) { reactive[key] = v; callback(reactive, key); }); }); callback(reactive, ''); return () => remove.forEach(r => r()); }, update: function (store, props) { isUpdating = true; Object.keys(store).forEach(function (key) { if (props[key] && props[key] instanceof Array) { store[key].splice(0, store[key].length); store[key].push(...props[key]); } else if (props[key] !== undefined) { store[key] = props[key]; } }); isUpdating = false; } }; })();
var Mongo = require('../../config/mongo'); describe('mongo configuration test', function() { var mongo, appSettings, mongoSettings; describe('when successfully configured', function() { beforeEach(function(done) { // Since it takes a second or two to connect, emulate some time passing. setTimeout(function() { mongo = new Mongo(app); mongo.should.be.an.Object; done(); }, 100); }); it('should make a connection to the mongo database', function(done) { app.should.be.a.Function; appSettings = app.settings.publish; mongoSettings = appSettings['mongo']; mongoSettings.should.be.an.Object; mongoSettings.should.have.property('databaseName'); mongoSettings.should.have.property('serverConfig'); done(); }); }); describe('when unsuccessfully configured', function() { beforeEach(function(done) { mongoSettings = null; done(); }); it('should fail connecting with invalid parameters', function(done) { appSettings['MONGO CONNECTION STRING'] = 'blah'; // To test for thrown errors, we must wrap the methods in anonymous // functions. (function() { mongo = new Mongo(app); }).should.throw( 'URL must be in the format mongodb://user:pass@host:port/dbname'); done(); }); it('should fail connecting with a missing connection string', function(done) { appSettings['MONGO CONNECTION STRING'] = null; // To test for thrown errors, we must wrap the methods in anonymous // functions. (function() { mongo = new Mongo(app); }).should.throw( 'Could not connect to Mongo DB using connection string "undefined"'); done(); }); }); });
import config from 'config' import logger from './../lib/utils/logger' import { apiService } from '../lib/apiService' const getWeatherByCityName = async cityName => { const options = { params: { q: cityName, APPID: config.get('openWeather.apiKey') } } try { const { data } = await apiService.get('/weather', options) return data } catch (error) { logger.error(error, `Failed to fetch weather for ${cityName}`) error.logged = true throw error } } export { getWeatherByCityName }
(function () { angular .module('myApp') .controller('responseOfContingentAnswerController', responseOfContingentAnswerController) responseOfContingentAnswerController.$inject = ['$state', '$scope', '$rootScope']; function responseOfContingentAnswerController($state, $scope, $rootScope) { // ************** router: responseOfContingentAnswer ***************** $rootScope.setData('showMenubar', true); $rootScope.setData('backUrl', "groupRoot"); $scope.question = $rootScope.settings.question; $scope.groupChoice = $scope.groupChoice ? $scope.groupChoice : 'main'; $scope.options = []; $scope.length = $scope.question.subQuestions.length; for (i = 0; i < Math.pow(2, $scope.length); i++) { $scope.options[i] = String("00000000000000" + i.toString(2)).slice(-1 * $scope.length); $scope.options[i] = $scope.options[i].replace(/0/g, "A"); $scope.options[i] = $scope.options[i].replace(/1/g, "B"); } $rootScope.safeApply(); $scope.$on("$destroy", function () { if ($rootScope.instFeedRef) $rootScope.instFeedRef.off('value'); if ($rootScope.publicNoteRef) $rootScope.publicNoteRef.off('value') if ($rootScope.teacherNoteRef) $rootScope.teacherNoteRef.off('value') if ($rootScope.privateNoteRef) $rootScope.privateNoteRef.off('value') if ($scope.userGroupRef) $scope.userGroupRef.off('value') if ($scope.answerRef) $scope.answerRef.off('value') }); $scope.init = function () { $rootScope.setData('loadingfinished', false); $scope.getUsersInGroup(); $scope.getAnswer(); } $scope.getUsersInGroup = function () { $scope.userGroupRef = firebase.database().ref('StudentGroups/'); $scope.userGroupRef.on('value', function (snapshot) { $scope.usersInGroup = []; for (var userKey in snapshot.val()) { var userGroups = snapshot.val()[userKey]; for (var key in userGroups) { if (userGroups[key] == $rootScope.settings.groupKey) { $scope.usersInGroup.push(userKey); } } }; $scope.ref_1 = true; $scope.finalCalc(); }); } $scope.getAnswer = function () { $scope.answerRef = firebase.database().ref('NewAnswers/' + $scope.question.code + '/answer'); $scope.answerRef.on('value', function (snapshot) { $scope.allAnswers = snapshot.val() || {} $scope.ref_2 = true; $scope.finalCalc(); }); } $scope.finalCalc = function () { if (!$scope.ref_1 || !$scope.ref_2) return; $scope.mainvalues = []; $scope.mainlabels = []; $scope.othervalues = []; $scope.otherlabels = []; $scope.totalvalues = []; $scope.totallabels = []; $scope.maincount = 0; $scope.othercount = 0; $scope.totalcount = 0; for (var i = 0; i < $scope.options.length; i++) { $scope.mainvalues.push(0); $scope.othervalues.push(0); $scope.totalvalues.push(0); $scope.mainlabels.push($scope.options[i]); $scope.otherlabels.push($scope.options[i]); $scope.totallabels.push($scope.options[i]); } for (userKey in $scope.allAnswers) { var answerArr = $scope.allAnswers[userKey].answer; var ansIndex = $scope.getIndex(answerArr); if ($scope.usersInGroup.indexOf(userKey) > -1) { $scope.mainvalues[ansIndex]++; $scope.maincount++; } else { $scope.othervalues[ansIndex]++; $scope.othercount++; } $scope.totalvalues[ansIndex]++; $scope.totalcount++; } var tempValue = 0; for (var i = 0; i < $scope.options.length - 1; i++) { for (var j = i + 1; j < $scope.options.length; j++) { if ($scope.mainvalues[j] > $scope.mainvalues[i]) { tempValue = $scope.mainvalues[i]; $scope.mainvalues[i] = $scope.mainvalues[j]; $scope.mainvalues[j] = tempValue; tempValue = $scope.mainlabels[i]; $scope.mainlabels[i] = $scope.mainlabels[j]; $scope.mainlabels[j] = tempValue; } if ($scope.othervalues[j] > $scope.othervalues[i]) { tempValue = $scope.othervalues[i]; $scope.othervalues[i] = $scope.othervalues[j]; $scope.othervalues[j] = tempValue; tempValue = $scope.otherlabels[i]; $scope.otherlabels[i] = $scope.otherlabels[j]; $scope.otherlabels[j] = tempValue; } if ($scope.totalvalues[j] > $scope.totalvalues[i]) { tempValue = $scope.totalvalues[i]; $scope.totalvalues[i] = $scope.totalvalues[j]; $scope.totalvalues[j] = tempValue; tempValue = $scope.totallabels[i]; $scope.totallabels[i] = $scope.totallabels[j]; $scope.totallabels[j] = tempValue; } } } $scope.changeGroupChoice(); $rootScope.setData('loadingfinished', true); $rootScope.safeApply(); } $scope.getIndex = function (arr) { var ansIndex = 0; for (var i = 0; i < arr.length; i++) { ansIndex += arr[i] * Math.pow(2, arr.length - i - 1); } return ansIndex; } $scope.changeGroupChoice = function () { switch ($scope.groupChoice) { case 'main': $scope.chartDescription = "Compared only in your group!"; $scope.numberOfAnswers = $scope.maincount; $scope.paintgraph($scope.mainlabels, $scope.mainvalues, "barChart"); break; case 'other': $scope.chartDescription = "Compared to all groups except your group!"; $scope.numberOfAnswers = $scope.othercount; $scope.paintgraph($scope.otherlabels, $scope.othervalues, "barChart"); break; case 'all': $scope.chartDescription = "Compared to all groups include your group!"; $scope.numberOfAnswers = $scope.totalcount; $scope.paintgraph($scope.totallabels, $scope.totalvalues, "barChart"); break; } $rootScope.safeApply(); } $scope.paintgraph = function (title, value, Dom) { var canvas = document.getElementById(Dom); var ctx = canvas.getContext("2d"); // ==========update chart================ if ($scope.myChart) { $scope.myChart.data.labels = title; $scope.myChart.data.datasets[0].data = value; $scope.myChart.update(); return; } //=========== create chart================= $scope.myChart = new Chart(ctx, { type: 'horizontalBar', data: { labels: title, datasets: [{ label: '# of Votes', data: value, backgroundColor: [ 'rgba(230, 25, 75, 0.3)', 'rgba(47, 71, 255, 0.2)', 'rgba(255, 225, 25, 0.4)', 'rgba(129, 72, 68, 0.2)', 'rgba(60, 180, 75, 0.6)', 'rgba(245, 130, 48, 0.5)', 'rgba(145, 30, 180, 0.4)', 'rgba(70, 240, 240, 0.3)', 'rgba(0, 128, 128, 0.5)', 'rgba(230, 190, 255, 0.3)', 'rgba(170, 110, 40, 0.4)', 'rgba(170, 255, 195, 0.2)', 'rgba(255, 215, 180, 0.6)', 'rgba(240, 50, 230, 0.7)', 'rgba(210, 245, 60, 0.2)', 'rgba(255, 206, 86, 0.7)', 'rgba(75, 192, 192, 0.5)', 'rgba(153, 102, 255, 0.3)', 'rgba(255, 159, 64, 0.4)', 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.6)' ], borderColor: [ 'rgba(230, 25, 75, 1)', 'rgba(47, 71, 255, 1)', 'rgba(255, 225, 25, 1)', 'rgba(129, 72, 68, 1)', 'rgba(60, 180, 75, 1)', 'rgba(245, 130, 48, 1)', 'rgba(145, 30, 180, 1)', 'rgba(70, 240, 240,1)', 'rgba(0, 128, 128, 1)', 'rgba(230, 190, 255, 1)', 'rgba(170, 110, 40, 1)', 'rgba(170, 255, 195, 1)', 'rgba(255, 215, 180, 1)', 'rgba(240, 50, 230,1)', 'rgba(210, 245, 60, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)' ], borderWidth: 1 }] }, options: { legend: { display: false }, scales: { yAxes: [{ ticks: { beginAtZero: true, }, barPercentage: 0.5 }], xAxes: [{ // Change here gridLines: { display: false, }, ticks: { beginAtZero: true, stepSize: 1 } }] }, elements: { rectangle: { borderSkipped: 'left' } } } }); } } })();
require.config({ paths: { domReady: './libs/requirejs-domready/domReady', angular: './libs/angular/angular', ngRoute: './libs/angular/angular-route.min', ngAnimate: './libs/angular/angular-animate.min', resource: './libs/angular/angular-resource.min', /*Underscore: './libs/underscore-min',*/ 'ui.bootstrap': './libs/ui-bootstrap-tpls-0.11.0.min' }, shim: { 'angular': { exports: 'angular' }, 'ngRoute': ['angular'], 'ngAnimate': ['angular'], 'ui.bootstrap': ['angular'], 'resource': ['angular'], 'app': { deps:['angular'] } }, deps: ['./bootstrap'] });
'use strict'; const scriptInfo = { name: 'Money', desc: 'Conversions and such', createdBy: 'IronY' }; const _ = require('lodash'); require('lodash-addons'); const request = require('request-promise-native'); const logger = require('../../lib/logger'); const scheduler = require('../../lib/scheduler'); // Get a monatary symbol const getSymbol = require('currency-symbol-map'); // Money and Accounting const fx = require('money'); const accounting = require('accounting-js'); // API Information const fixerApi = 'http://api.fixer.io/latest'; // API For Country exchange rates const btcApi = 'https://bitpay.com/api/rates'; // API For BTC exchange rates module.exports = app => { // Base currency const baseCur = _.getString(_.get(app.Config, 'features.exchangeRate.base'), 'USD').toUpperCase(); const updateScheduleTime = _.get(app.Config, 'features.exchangeRate.updateScheduleTime', { hour: [...Array(24).keys()], // Every hour minute: 0 // On the hour }); // Set base currency in money.js fx.base = baseCur; scheduler.schedule('updateCurRates', updateScheduleTime, () => // Get the initial conversion rates request(fixerApi, { json: true, method: 'get', qs: { base: baseCur } }) // Set the rate sin money.js .then(data => { // No rates available if (!_.isObject(data.rates) || _.isEmpty(data.rates)) { logger.error(`Something went wrong fetching exchange rates`, { data }); return; } // Received Rates logger.info('Updating exchange rates'); // Adjust rates in money fx.rates = data.rates }) .then(() => // Get the BTC Rate request(btcApi, { json: true, method: 'get' }) // Set the BTC Rate .then(data => { // No Data available if (!_.isArray(data) || _.isEmpty(data)) { logger.error('Error fetching BitCoin data for exchange seeding', { data }); return; } // Find the base currency in the btc info let btc = _.find(data, o => o.code === baseCur); if (!btc || !btc.code || isNaN(btc.rate) || btc.rate === 0) { logger.error('Error fetching BitCoin data, data returned is not formated correctly', { data }); return; } // Set the BTC rate based on inverse exchange fx.rates.BTC = 1 / btc.rate; })) // Problem with request chains .catch(err => logger.error('Something went wrong getting currency rates', { err })) ); // initial run if (_.isFunction(scheduler.jobs.updateCurRates.job)) scheduler.jobs.updateCurRates.job(); // The function does not exist, log error else logger.error(`Something went wrong with the currency exchange rate job, no function exists`); // Provide exchange const exchange = (to, from, text, message) => { // No exchange rates available if (!_.isObject(fx.rates) || _.isEmpty(fx.rates)) { app.say(to, `It seems I am without the current exchange rates, sorry ${from}`); return; } // No text available if (_.isEmpty(text)) { app.say(to, `I need some more information ${from}`); return; } // Extract variables let [amount, cFrom, cTo] = text.split(' '); // Normalize amount through accounting amount = accounting.unformat(amount); // Verify amount is numeric if (!amount) { app.say(to, `Invalid amount or 0 amount given ${from}, I cannot do anything with that`); return; } // Verify we have a target currency if (!cFrom) { app.say(to, `I need a currency to convert from`); return; } // Normalize cFrom = cFrom.toUpperCase(); cTo = (cTo || baseCur).toUpperCase(); // Attempt conversion try { // If no cTo is provided, assume default base let result = fx.convert(amount, { from: cFrom, to: cTo }); // Format result and amount throught accounting.js result = accounting.formatMoney(result, { symbol: getSymbol(cTo) || '' }); amount = accounting.formatMoney(amount, { symbol: getSymbol(cFrom) || '' }) // Report back to IRC app.say(to, `At the current exchange rate ${amount} ${cFrom} is ${result} ${cTo}, ${from}`); } // Problem with money.js conversion catch (err) { app.say(to, `I am unable to convert ${cFrom} to ${cTo} ${from}`); } }; // Evaluate app.Commands.set('exchange', { desc: '[amount from to?] - Convert currency based on current exchange rates', access: app.Config.accessLevels.identified, call: exchange }); return scriptInfo; };
//首先抓取每个元素 function Tab() { this.GetElement(); } Tab.prototype.GetElement = function () { this.btn = document.getElementsByTagName("input"); this.box = document.getElementsByClassName("box"); for(var i = 0; i < btn.length; i++){ this.btn[i].onclick = function () { this.btn[i].clc(); } } } Tab.prototype.clc = function () { for(var i = 0; i < this.btn.length; i++){ this.btn[i].index = i; this.btn[i].className = ""; this.box[i].style.display = "none"; } this.btn[this.index].className = "active"; this.box[this.index].style.display = "block"; }
module.exports = { name: 'Admin System', prefix: 'system', footerText: 'TROY ADMIN SYSTEM © 2017 ', logo: '/logo.png', iconFontCSS: '/iconfont.css', iconFontJS: '/iconfont.js', // activeUrl: 'http://10.0.40.90:8081', activeUrl: 'http://10.0.40.47:8081', baseURL: '/system', YQL: ['http://www.zuimeitianqi.com'], CORS: ['http://localhost:7000'], openPages: ['/login'], apiPrefix: '/system', api: { userLogin: '/user/login', userLogout: '/user/logout', userInfo: '/userInfo', users: '/users', user: '/user/:id', dashboard: '/dashboard', mycity: 'http://www.zuimeitianqi.com/zuimei/myCity', myWeather: 'http://www.zuimeitianqi.com/zuimei/queryWeather', }, }
describe('pascalprecht.iterator', function () { beforeEach(module('pascalprecht.iterator')); it('should have a $iterator factory', function () { inject(function ($iterator) { expect($iterator).toBeDefined(); }); }); describe('$iterator', function () { it('should be function', function () { inject(function ($iterator) { expect(typeof $iterator).toBe('function'); }); }); it('should throw error if given aggregate is not an array', function () { inject(function ($iterator) { expect(function () { $iterator(5); }).toThrow('Couldn\'t create Iterator, aggregate is not an array!'); }); }); it('should return instances with iterator interface', function () { inject(function ($iterator) { var it = $iterator([3,4,5]); expect(it.next).toBeDefined(); expect(it.hasNext).toBeDefined(); expect(it.rewind).toBeDefined(); expect(it.current).toBeDefined(); }); }); describe('#next()', function () { var iterator; beforeEach(inject(function ($iterator) { iterator = $iterator([2,3,4]); })); afterEach(function () { iterator.rewind(); }); it('should be function', function () { expect(typeof iterator.next).toBe('function'); }); it('should return next element', function () { expect(iterator.current()).toBe(2); expect(iterator.next()).toBe(3); expect(iterator.next()).toBe(4); }); it('should return null hasn\'t next', function () { expect(iterator.next()).toBe(3); expect(iterator.next()).toBe(4); expect(iterator.next()).toBe(null); }); }); describe('#hasNext()', function () { var iterator; beforeEach(inject(function ($iterator) { iterator = $iterator([2,3,4]); })); afterEach(function () { iterator.rewind(); }); it('should be function', function () { expect(typeof iterator.hasNext).toBe('function'); }); it('should return true as long as has next', function () { expect(iterator.hasNext()).toBe(true); iterator.next(); expect(iterator.hasNext()).toBe(true); }); it('should return false if hasn\'t next', function () { expect(iterator.hasNext()).toBe(true); iterator.next(); expect(iterator.hasNext()).toBe(true); iterator.next(); expect(iterator.hasNext()).toBe(false); }); }); describe('#rewind()', function () { var iterator; beforeEach(inject(function ($iterator) { iterator = $iterator([2,3,4]); })); afterEach(function () { iterator.rewind(); }); it('should be function', function () { expect(typeof iterator.rewind).toBe('function'); }); it('should reset iterator index', function () { iterator.next(); iterator.next(); expect(iterator.current()).toBe(4); iterator.rewind(); expect(iterator.current()).toBe(2); }); }); describe('#current()', function () { var iterator; beforeEach(inject(function ($iterator) { iterator = $iterator([2,3,4]); })); afterEach(function () { iterator.rewind(); }); it('should be function', function () { expect(typeof iterator.current).toBe('function'); }); it('should return current element', function () { expect(iterator.current()).toBe(2); iterator.next(); expect(iterator.current()).toBe(3); iterator.next(); expect(iterator.current()).toBe(4); }); }); }); });
 define(function (require, exports, module) { require("jquery"); require("pager"); var Global = require("global"), doT = require("dot"); var FeedBack = {}; FeedBack.Params = { pageIndex: 1, type: -1, status: -1, beginDate: '', endDate:'', keyWords: '', id:'' }; //列表初始化 FeedBack.init = function () { FeedBack.bindEvent(); FeedBack.bindData(); }; //绑定事件 FeedBack.bindEvent = function () { //关键字查询 require.async("search", function () { $(".searth-module").searchKeys(function (keyWords) { if (FeedBack.Params.keyWords != keyWords) { FeedBack.Params.pageIndex = 1; FeedBack.Params.keyWords = keyWords; FeedBack.bindData(); } }); }); //下拉状态、类型查询 require.async("dropdown", function () { var Types = [ { ID: "1", Name: "问题" }, { ID: "2", Name: "建议" }, { ID: "3", Name: "需求" } ]; $("#FeedTypes").dropdown({ prevText: "意见类型-", defaultText: "所有", defaultValue: "-1", data: Types, dataValue: "ID", dataText: "Name", width: "120", onChange: function (data) { FeedBack.Params.pageIndex = 1; FeedBack.Params.type = parseInt(data.value); FeedBack.Params.beginDate = $("#BeginTime").val(); FeedBack.Params.endDate = $("#EndTime").val(); FeedBack.bindData(); } }); $(".search-tab li").click(function () { $(this).addClass("hover").siblings().removeClass("hover"); var index = $(this).data("index"); $(".content-body div[name='navContent']").hide().eq(parseInt(index)).show(); FeedBack.Params.pageIndex = 1; FeedBack.Params.status = index == 0 ? -1 : index; FeedBack.Params.beginDate = $("#BeginTime").val(); FeedBack.Params.endDate = $("#EndTime").val(); FeedBack.bindData(); }); }); //时间段查询 $("#SearchFeedBacks").click(function () { if ($("#BeginTime").val() != '' || $("#EndTime").val() != '') { FeedBack.Params.pageIndex = 1; FeedBack.Params.beginDate = $("#BeginTime").val(); FeedBack.Params.endDate = $("#EndTime").val(); FeedBack.bindData(); } }); }; //绑定数据列表 FeedBack.bindData = function () { $(".tr-header").nextAll().remove(); Global.post("/FeedBack/GetFeedBacks", FeedBack.Params, function (data) { doT.exec("template/FeedBack-list.html?3", function (templateFun) { var innerText = templateFun(data.Items); innerText = $(innerText); $(".tr-header").after(innerText); }); $("#pager").paginate({ total_count: data.TotalCount, count: data.PageCount, start: FeedBack.Params.pageIndex, display: 5, border: true, rotate: true, images: false, mouse: 'slide', onChange: function (page) { FeedBack.Params.pageIndex = page; FeedBack.bindData(); } }); }); } FeedBack.detailInit = function (id) { FeedBack.Params.id = id; FeedBack.detailBindEvent(); FeedBack.getFeedBackDetail(); } FeedBack.detailBindEvent = function () { $("#btn-finish").click(function () { FeedBack.updateFeedBackStatus(2); }); $("#btn-cancel").click(function () { FeedBack.updateFeedBackStatus(3); }); $("#btn-delete").click(function () { FeedBack.updateFeedBackStatus(9); }); } //详情 FeedBack.getFeedBackDetail = function () { Global.post("/FeedBack/GetFeedBackDetail", { id: FeedBack.Params.id }, function (data) { if (data.Item) { var item = data.Item; $("#Title").html(item.Title); var typeName = "问题"; if (item.Type == 2) typeName = "建议"; else if (item.Type == 3) typeName = "需求"; $("#Type").html(typeName); var statusName = "待解决"; if (item.Status == 2) { statusName = "已解决"; $('#btn-finish').hide(); $('#btn-cancel').hide(); $('#btn-delete').hide(); } else if (item.Status == 3) { statusName = "驳回"; $('#btn-finish').hide(); $('#btn-cancel').hide(); $('#btn-delete').hide(); } else if (item.Status == 9) { statusName = "删除"; } $("#Status").html(statusName); $("#ContactName").html(item.ContactName); $("#MobilePhone").html(item.MobilePhone); $("#Remark").html(item.Remark); $("#Content").html(item.Content); $("#CreateTime").html(item.CreateTime.toDate("yyyy-MM-dd hh:mm:ss")); } }); }; //更改状态 FeedBack.updateFeedBackStatus = function (status) { Global.post("/FeedBack/UpdateFeedBackStatus", { id: FeedBack.Params.id, status: status, content: $('#Content').val() }, function (data) { if (data.Result == 1) { alert("保存成功"); FeedBack.getFeedBackDetail(); } else { alert("保存失败"); } }); }; module.exports = FeedBack; });
// import {bindActionCreators} from 'redux'; // import {connect} from 'react-redux'; // import {load as loadSounds } from 'redux/modules/content/sounds'; import React, { Component, PropTypes } from 'react'; import Helmet from 'react-helmet'; import { Well, Row, Col } from 'react-bootstrap'; import { SoundPlayerContainer } from 'react-soundplayer/addons'; import Player from './Player/Player'; import { Icons } from 'react-soundplayer/components'; const clientId = '0d35c7e491d8eff85a353a22baa5b15e'; const playListUrl = 'https://soundcloud.com/rob-halff/sets/robberthalff'; export default class Sounds extends Component { static propTypes = { sounds: PropTypes.array.isRequired } static defaultProps = { } render() { const styles = require('./Sounds.scss'); return ( <div className={styles.sounds}> <Helmet title="SoundLog" /> <div className="container"> <div className="window soundWindow center-block"> <div className="panel"> <div className="panel-body"> <Well> <Icons.SoundCloudLogoSVG /> <hr /> <div className="well"> <Row> <Col xs={12} md={12}> <div className="blog"> <SoundPlayerContainer resolveUrl={playListUrl} clientId={clientId}> <Player /> </SoundPlayerContainer> </div> </Col> </Row> </div> </Well> </div> </div> </div> </div> </div> ); } }
// https://github.com/balloob/pynetgear/ const http = require('http'); const config = require('config'); class NetgearRouter { constructor() { this.sessionId = 'A7D88AE69687E58D9A00'; this.action = { login: 'urn:NETGEAR-ROUTER:service:ParentalControl:1#Authenticate', getAttachedDevices: 'urn:NETGEAR-ROUTER:service:DeviceInfo:1#GetAttachDevice', }; this.envelope = { login: ` <?xml version="1.0" encoding="utf-8" ?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header> <SessionID xsi:type="xsd:string" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance">{sessionId}</SessionID> </SOAP-ENV:Header> <SOAP-ENV:Body> <Authenticate> <NewUsername>{username}</NewUsername> <NewPassword>{password}</NewPassword> </Authenticate> </SOAP-ENV:Body> </SOAP-ENV:Envelope> `, getAttachedDevices: ` <?xml version="1.0" encoding="utf-8" standalone="no"?> <SOAP-ENV:Envelope xmlns:SOAPSDK1="http://www.w3.org/2001/XMLSchema" xmlns:SOAPSDK2="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAPSDK3="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header> <SessionID>{sessionId}</SessionID> </SOAP-ENV:Header> <SOAP-ENV:Body> <M1:GetAttachDevice xmlns:M1="urn:NETGEAR-ROUTER:service:DeviceInfo:1"></M1:GetAttachDevice> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ` }; } request(action, params, callback) { params = params || {}; let postData = this.formatEnvelope(this.envelope[action], params); let httpOpts = { host: 'routerlogin.net', port: 5000, path: '/soap/server_sa/', method: 'POST', headers: { 'Content-Type': 'text/xml;charset=UTF-8', 'SOAPAction': this.action[action], 'Content-Length': Buffer.byteLength(postData) } }; let request = http.request(httpOpts, (response) => { response.setEncoding('utf8'); if(typeof callback === 'function') { callback(response); } }); request.write(postData); request.end(); return request; } requestPromise(action, params) { return new Promise((resolve, reject) => { let data = ''; let request = this.request(action, params, (response) => { if (response.statusCode === 200) { response.on('data', function (chunk) { data += chunk; }); response.on('end', () => { resolve(data); }); } }); request.on('error', (err) => { reject(err); }); }); } formatEnvelope(envelope, params) { let formattedEnvelope = envelope; for(let param in params) { let value = params[param]; formattedEnvelope = formattedEnvelope.replace('{' + param +'}', value); } return formattedEnvelope; } isValidResponse(data) { return data.indexOf('<ResponseCode>000</ResponseCode>') > -1; } async login(sessionId, username, password) { sessionId = sessionId || this.sessionId; let data = await this.requestPromise('login', { sessionId: sessionId, username: username, password: password }); return this.isValidResponse(data); } async getAttachedDevices(sessionId) { sessionId = sessionId || this.sessionId; let data = await this.requestPromise('getAttachedDevices', { sessionId: sessionId }) let dataString = data.substring( data.indexOf('<NewAttachDevice>') + '<NewAttachDevice>'.length, data.indexOf('</NewAttachDevice>') ); let dataSplit = dataString.split('@'); let numberOfDevices = dataSplit[0]; let attachedDevices = []; for(let deviceString of dataSplit) { let deviceSplit = deviceString.split(';'); if (deviceSplit.length === 8) { let device = { ip_addr: deviceSplit[1] ? deviceSplit[1] : null, name: deviceSplit[2] ? deviceSplit[2] : null, mac_addr: deviceSplit[3] ? deviceSplit[3] : null, connection_type: deviceSplit[4] ? deviceSplit[4] : null, bandwidth: deviceSplit[5] ? deviceSplit[5] : null, signal_strength: deviceSplit[6] ? deviceSplit[6] : null, access_control: deviceSplit[7] ? deviceSplit[7] : null, reference: null }; if (device.mac_addr) { let reference = config.netgear.references.find(function(reference) { return reference.mac.toLowerCase() === device.mac_addr.toLowerCase(); }); if (reference) { device.reference = reference; } } attachedDevices.push(device); } } return { devices: attachedDevices }; } } module.exports = NetgearRouter;
const axios = require('axios') const { Router } = require('express'); const router = Router(); const { Videogame, Genero } = require('../../db') const { API_KEY } = process.env; router.get('/', async (req, res) => { let generos = [] const api = await axios.get(`https://api.rawg.io/api/genres?key=${API_KEY}`) generos = await api.data.results.map(el => el.name) generos.forEach(el => { Genero.findOrCreate({ where: { name: el } }); }); const allgeneros = await Genero.findAll() res.send(allgeneros) }) module.exports = router;
const mongoose = require("mongoose"); const Schema = mongoose.Schema; // require("mongoose-currency").loadType(mongoose); // var Currency = mongoose.Types.Currency; var medicationsSchema = new Schema( { nama_obat: { type: String, }, dosis: { type: Number, }, satuan: { type: String, }, tujuan: { type: String, default: "" } } ); var logSchema = new Schema( { idLog:{ type:mongoose.Schema.ObjectId, default:mongoose.Schema.ObjectId }, idPasien: { type: String, required: true, }, idDoctor: { type: String, required: true, }, tanggal_pengisian: { type: Date, default: Date.now() }, keterangan: { type: String, required: true, default: "" }, medikasi: [medicationsSchema], }, { timestamps: true, createdAt: 'created_at', updatedAt: 'updated_at' } ); var log = mongoose.model("Log", logSchema); var medications = mongoose.model("Medication", medicationsSchema); module.exports = { log, medications };
// build Google API map with epicenter of earthquake as center function initMap(lat, long, msg) { if ((lat == null) || (long == null)) { lat = parseFloat(-34.397) long = parseFloat(150.644) } bounds = new google.maps.LatLngBounds(); map = new google.maps.Map(document.getElementById('map'), { center: {lat: lat, lng: long}, zoom: 11 }); marker = new google.maps.Marker({ position: map.center, map: map, title: 'Epicenter of earthquake', label: "Epicenter" }); bounds.extend(marker.position) } // creates custom timestamp function timeStamp() { // Create a date object with the current time var now = new Date(); // Create an array with the current month, day and time var date = [ now.getMonth() + 1, now.getDate(), now.getFullYear() ]; // Create an array with the current hour, minute and second var time = [ now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds()]; // Determine AM or PM suffix based on the hour var suffix = ( time[0] < 12 ) ? "AM" : "PM"; // Convert hour from military time time[0] = ( time[0] < 12 ) ? time[0] : time[0] - 12; // If hour is 0, set it to 12 time[0] = time[0] || 12; // If seconds and minutes are less than 10, add a zero for ( var i = 1; i < 3; i++ ) { if ( time[i] < 10 ) { time[i] = "0" + time[i]; } } // Return the formatted string return date.join("/") + " " + time.join(":") + " " + suffix; } // check if a passed string contains JSON function IsJsonString(str) { try { JSON.parse(str); } catch (e) { return false; } return true; } // gets distance between two points in KM function distance(lat1, lng1, lat2, lng2, miles) { // miles optional if (typeof miles === "undefined"){miles=false;} function deg2rad(deg){return deg * (Math.PI/180);} function square(x){return Math.pow(x, 2);} var r=6371; // radius of the earth in km lat1=deg2rad(lat1); lat2=deg2rad(lat2); var lat_dif=lat2-lat1; var lng_dif=deg2rad(lng2-lng1); var a=square(Math.sin(lat_dif/2))+Math.cos(lat1)*Math.cos(lat2)*square(Math.sin(lng_dif/2)); var d=2*r*Math.asin(Math.sqrt(a)); if (miles){ return d * 0.621371; } //return miles else{ return d; } //return km } function getTime(lat, long, m, res) { let dist; if (lat !== null && long !== null) { dist = distance(parseFloat(res[0]), parseFloat(res[1]), lat, long) } // number of seconds using speed of 3km/s let tmp = dist / 3 date = new Date(m.orig_time) date.setSeconds(date.getSeconds() + tmp) return date; } function addCircle(m, circleData, map) { var circle = new google.maps.Circle({ map: map, radius: m.radius, fillColor: circleData[m.intensity].color, center: map.center }) return circle; }
import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import {SuperForm, ModalWithDrag} from '../../../components'; import s from './EditDialog.less'; class EditDialog extends React.Component { toForm = () => { const {controls, value, valid, readonly, onChange, onSearch, onExitValid, onAdd} = this.props; const props = { controls, value, valid, readonly, colNum: 2, container: true, onChange, onSearch, onExitValid, onAdd }; return <SuperForm {...props} /> ; }; toBody = () => { return ( <div className={s.root}> {this.toForm()} </div> ); }; getProps = () => { const {title, ok, cancel, visible, confirmLoading, res, onCancel, onOk, afterClose} = this.props; return { title, visible, onCancel, onOk, afterClose: () => afterClose(res), okText: ok, cancelText: cancel, width: 520, maskClosable: false, confirmLoading }; }; render() { return ( <ModalWithDrag {...this.getProps()}> {this.toBody()} </ModalWithDrag> ); } } export default withStyles(s)(EditDialog);
const permutations = list => { let output = [] if(list.length === 2){return [list,[list[1], list[0]]]} else{ list.forEach(digit => { let results = permutations(list.filter(e => e != digit)) results.forEach(result => output.push([digit, ...result])) }) return output } } const pandigitalProducts = list => { let perms = permutations(list) let products = [] perms.forEach(perm => { let add = false let product = Number(perm.slice(5).join("")) for(let i = 1; i < 5; i++){ let mult1 = Number(perm.slice(0,i).join("")) let mult2 = Number(perm.slice(i,5).join("")) if(mult1 * mult2 === product){ add = true } } if(add && !products.includes(product)){ products.push(product) } }) return products.reduce((a,b)=>a+b) } console.log(pandigitalProducts([1,2,3,4,5,6,7,8,9])) //45228
/*global ODSA */ $(document).ready(function() { "use strict"; var av_name = "TernaryRelationshipStoreYSol3"; var interpret = ODSA.UTILS.loadConfig({av_name: av_name}).interpreter; var av = new JSAV(av_name); //some attributes controlling entities matrices var arrayWidth=120; var arrayLeft=60; var arrayGap=250; var arrayTop=50; //lines connecting matrices in slide 35 so Mtrx referes to matrix not rectangles like above Lines //each line here has its two cardinality labels below itself //original country matrix line down connecting it to distributor/country bridge var DMtrxDwnLine = av.g.line(480, 135, 480, 280,{opacity: 100, "stroke-width": 2}); DMtrxDwnLine.hide(); var DMtrxDwnCardLab=av.label("<span style='color:blue;'>M</span>", {left: 483, top:120 }); DMtrxDwnCardLab.css({"font-weight": "bold", "font-size": 15}); DMtrxDwnCardLab.hide(); //var DistConBdgMtrxUpCardLab=av.label("<span style='color:blue;'>M</span>", {left: 483, top:165 }); //DistConBdgMtrxUpCardLab.css({"font-weight": "bold", "font-size": 15}); //DistConBdgMtrxUpCardLab.hide(); //original product matrix line down connecting it to distributor/country bridge //&&&&&&&&&&&& var ProdMtrxDwnLine = av.g.line(980, 135, 980, 195,{opacity: 100, "stroke-width": 2}); ProdMtrxDwnLine.hide(); var prodMtrxDwnCardLab=av.label("<span style='color:blue;'>1</span>", {left: 980, top:120 }); prodMtrxDwnCardLab.css({"font-weight": "bold", "font-size": 15}); prodMtrxDwnCardLab.hide(); var DistProdBdgMtrxUpCardLab=av.label("<span style='color:blue;'>M</span>", {left: 980, top:165 }); DistProdBdgMtrxUpCardLab.css({"font-weight": "bold", "font-size": 15}); DistProdBdgMtrxUpCardLab.hide(); //line connecting distributor to original distributor/country bridge var DistConBdgMtrxRgtLine = av.g.line(480, 280, 690, 280,{opacity: 100, "stroke-width": 2}); DistConBdgMtrxRgtLine.hide(); var ConMtrxLeftCardLab=av.label("<span style='color:blue;'>1</span>", {left: 680, top:245 }); ConMtrxLeftCardLab.css({"font-weight": "bold", "font-size": 15}); ConMtrxLeftCardLab.hide(); //var DistConBdgMtrxRgtCardLab=av.label("<span style='color:blue;'>M</span>", {left: 595, top:245 }); //DistConBdgMtrxRgtCardLab.css({"font-weight": "bold", "font-size": 15}); //DistConBdgMtrxRgtCardLab.hide(); //line connecting distributor to original distributor/product bridge//*************** */ var DistProdBdgMtrxLeftLine = av.g.line(830, 280, 910, 280,{opacity: 100, "stroke-width": 2}); DistProdBdgMtrxLeftLine.hide(); var DistMtrxRgtCardLab2=av.label("<span style='color:blue;'>1</span>", {left: 835, top:245 }); DistMtrxRgtCardLab2.css({"font-weight": "bold", "font-size": 15}); DistMtrxRgtCardLab2.hide(); var DistProdBdgMtrxLeftCardLab=av.label("<span style='color:blue;'>M</span>", {left: 897, top:245 }); DistProdBdgMtrxLeftCardLab.css({"font-weight": "bold", "font-size": 15}); DistProdBdgMtrxLeftCardLab.hide(); //line connecting country to original bridge 1 (product/country bridge with price) var Bdg1DistMtrxHorLine = av.g.line(620, 90, 560, 90,{opacity: 100, "stroke-width": 2}); Bdg1DistMtrxHorLine.hide(); var DistMtrxRgtCardLab=av.label("<span style='color:blue;'>M</span>", {left: 605, top:55 }); DistMtrxRgtCardLab.css({"font-weight": "bold", "font-size": 15}); DistMtrxRgtCardLab.hide(); var Bdg1MtrxLeftCardLab=av.label("<span style='color:blue;'>1</span>", {left: 563, top:55 }); Bdg1MtrxLeftCardLab.css({"font-weight": "bold", "font-size": 15}); Bdg1MtrxLeftCardLab.hide(); //line connecting product to original bridge 1 (product/country bridge with price) var Bdg1ProdMtrxHorLine = av.g.line(835, 90, 910, 90,{opacity: 100, "stroke-width": 2}); Bdg1ProdMtrxHorLine.hide(); var ProdMtrxLeftCardLab=av.label("<span style='color:blue;'>1</span>", {left: 900, top:55 }); ProdMtrxLeftCardLab.css({"font-weight": "bold", "font-size": 15}); ProdMtrxLeftCardLab.hide(); var Bdg1MtrxRgtCardLab=av.label("<span style='color:blue;'>M</span>", {left: 835, top:55 }); Bdg1MtrxRgtCardLab.css({"font-weight": "bold", "font-size": 15}); Bdg1MtrxRgtCardLab.hide(); // to lines forming X sign to get rid of redundant relation distributor/product bridge var WronSignRedundantRelation1 = av.g.line(910, 190, 1050, 350,{opacity: 100, "stroke-width": 4, "stroke":"red"}); WronSignRedundantRelation1.hide(); var WronSignRedundantRelation2 = av.g.line(1050, 190, 910, 350,{opacity: 100, "stroke-width": 4, "stroke":"red"}); WronSignRedundantRelation2.hide(); var StoreXsol3Analysis=av.label("<span style='color:blue;'>Store Y Third & Forth Solutions Analysis</span>", {left: 350, top: arrayTop-60 }); StoreXsol3Analysis.css({"font-weight": "bold", "font-size": 28}); var SolutionType=av.label("<span style='color:blue;'>- Three Binary relationships, 1:M (distributor/country) , N:M (distributor/product) & N:M (country/product) including price relationships</span>", {left: 70, top: arrayTop+60 }); SolutionType.css({"font-weight": "bold", "font-size": 22}); var SolutionType1=av.label("<span style='color:blue;'>- Two Binary relationships, 1:M (distributor/country) & N:M (country/product) including price relationships</span>", {left: 70, top: arrayTop+145 }); SolutionType1.css({"font-weight": "bold", "font-size": 22}); var Note=av.label("<span style='color:red;'>NOTE:</span> only Store Y dataset records that reveal solution bugs will be examined for time saving", {left: 70, top: arrayTop+280 }); Note.css({"font-weight": "bold", "font-size": 18}); // Slide 1 av.umsg(interpret("Here are the problems' statments").bold().big()); av.displayInit(1); av.step(); //slide 2 StoreXsol3Analysis.hide(); SolutionType.hide(); SolutionType1.hide(); Note.hide(); var theDataSetY = [["Country","Product","Distributer","Price"],["Egypt","TV","ali","3000"],["Egypt","watch","ali","5000"],["UK","blender","ali","2500"],["UK","watch","ali","2300"],["USA","TV","adam","4500"],["USA","watch","adam","4700"],["USA","blender","adam","2000"],["lebanon","TV","morad","4000"],["lebanon","blender","morad","3000"]]; av.umsg(interpret("4- Discuss pros and cons of all possible <span style='color:blue;'>Store Y solutions</span> to determine the correct one. <br> <br><span style='color:blue;'> <u>Store Y third sol. analysis:</u></span> ").bold().big()); var RealDataSetY= av.ds.matrix(theDataSetY, {style: "table", top: 0, left: 20 }); var sate1X1st=av.label("These are tables representing third solution relations, try to fill tables with records in <br> dataset to see weather these relations are correct or not.", {left: 20, top:325 }); sate1X1st.css({"font-weight": "bold", "font-size": 16}); for (var i=0; i < theDataSetY.length; i++) { RealDataSetY._arrays[i].css([0,1,2,3], {"font-size": 12}); RealDataSetY._arrays[i].show(); } var DistributorMatrixLab=av.label("<span style='color:blue;'>Distributor</span>", {left: 690, top:215 }); DistributorMatrixLab.css({"font-weight": "bold", "font-size": 14}); var theDistributorArrays = [["D-no","D-name"],["d1","ali"],["d2","adam"],["d3","tarek"]]; var theDistributorMatrix= av.ds.matrix(theDistributorArrays, {style: "table", top: 230, left: 690 }); theDistributorMatrix._arrays[0].css([0,1], {"font-weight": "bold", "color": "black"}); theDistributorMatrix._arrays[0].css([0], {"text-decoration": "underline"}); //var DistConBrdgMatrixLab=av.label("<span style='color:blue;'></span>", {left: 390, top:-15 }); //DistConBrdgMatrixLab.css({"font-weight": "bold", "font-size": 14}); //var theDistConBrdgArrays = [["D-no","c-no"],["",""],["",""],["",""],["",""]]; //var theDistConBrdgMatrix= av.ds.matrix(theDistConBrdgArrays, {style: "table", top: 180, left: 450 }); //theDistConBrdgMatrix._arrays[0].css([0,1], {"font-weight": "bold", "color": "black"}); //theDistConBrdgMatrix._arrays[0].css([0,1], {"text-decoration": "underline"}); var theBridge1Arrays = [["d-no","p-no"],["",""],["",""],["",""],["",""]]; var theBridge1Matrix= av.ds.matrix(theBridge1Arrays, {style: "table", top: 180, left: 910 }); theBridge1Matrix._arrays[0].css([0,1,2], {"font-weight": "bold", "color": "black"}); theBridge1Matrix._arrays[0].css([0,1], {"text-decoration": "underline"}); var Bridge2MatrixLab=av.label("<span style='color:blue;'>Bridge</span>", {left: 620, top:-15 }); Bridge2MatrixLab.css({"font-weight": "bold", "font-size": 14}); var theBridge2Arrays = [["c-no","p-no","price"],["","",""],["","",""],["","",""],["","",""],["","",""]]; var theBridge2Matrix= av.ds.matrix(theBridge2Arrays, {style: "table", top: 0, left: 620 }); theBridge2Matrix._arrays[0].css([0,1,2], {"font-weight": "bold", "color": "black"}); theBridge2Matrix._arrays[0].css([0,1], {"text-decoration": "underline"}); var CountryMatrixLab=av.label("<span style='color:blue;'>Country</span>", {left: 350, top:-15 }); CountryMatrixLab.css({"font-weight": "bold", "font-size": 14}); var theCountryArrays = [["C-no","c-name", "d-no"],["c1","Egypt", ""],["c2","USA", ""],["c3","UK", ""]]; var theCountryMatrix= av.ds.matrix(theCountryArrays, {style: "table", top: 0, left: 350 }); theCountryMatrix._arrays[0].css([0,1,2], {"font-weight": "bold", "color": "black"}); theCountryMatrix._arrays[0].css([0], {"text-decoration": "underline"}); var ProductMatrixLab=av.label("<span style='color:blue;'>Product</span>", {left: 910, top:-15 }); ProductMatrixLab.css({"font-weight": "bold", "font-size": 14}); var theProductArrays = [["p-no","p-name"],["p1","TV"],["p2","Watch"],["p3","blender"]]; var theProductMatrix= av.ds.matrix(theProductArrays, {style: "table", top: 0, left: 910 }); theProductMatrix._arrays[0].css([0,1], {"font-weight": "bold", "color": "black"}); theProductMatrix._arrays[0].css([0], {"text-decoration": "underline"}); DMtrxDwnLine.show(); DMtrxDwnCardLab.show(); // DistConBdgMtrxUpCardLab.show(); DistConBdgMtrxRgtLine.show(); ConMtrxLeftCardLab.show(); // DistConBdgMtrxRgtCardLab.show(); Bdg1DistMtrxHorLine.show(); DistMtrxRgtCardLab.show(); Bdg1MtrxLeftCardLab.show(); ProdMtrxLeftCardLab.show(); Bdg1MtrxRgtCardLab.show(); Bdg1ProdMtrxHorLine.show(); DistProdBdgMtrxLeftLine.show(); DistMtrxRgtCardLab2.show(); DistProdBdgMtrxLeftCardLab.show(); prodMtrxDwnCardLab.show(); ProdMtrxDwnLine.show(); DistProdBdgMtrxUpCardLab.show(); av.step(); //slide 3 sate1X1st.hide(); var sate2X1st=av.label("In this solution inserting for example first dataset record requires inserting </br>in three different tables.", {left: 20, top:325 }); sate2X1st.css({"font-weight": "bold", "font-size": 16}); RealDataSetY._arrays[1].highlight(); av.step(); //slide 4 sate2X1st.hide(); var sate3X1st=av.label("As <span style='color:green;'>(ali)</span> is the distributor of <span style='color:blue;'>(egypt)</span> </br>So ali's id <span style='color:green;'>(d1)</span> should be inserted in country table as a <span style='color:green;'>foreign key</span>, to represent </br> distributor/country <span style='color:green;'>(1:M)</span> relation.", {left: 20, top:315 }); sate3X1st.css({"font-weight": "bold", "font-size": 16}); theCountryMatrix._arrays[1].value(2,"<span style='color:red;'>d1</span>"); theDistributorMatrix._arrays[1].highlight(); theCountryMatrix._arrays[1].highlight(); var FKPOinter = av.pointer("<span style='color:red;'><b>FK of distributor</b></span>",theCountryMatrix._arrays[2].index(2), {right: 150, top: 270}); av.step(); //slide 5 sate3X1st.hide(); FKPOinter.hide(); var sate4X1st=av.label("To specify that <span style='color:green;'>TV</span> is the product that ali sells in <span style='color:green;'>Egypt</span> with <span style='color:green;'>price=3000</span> </br> Fill in <span style='color:blue;'>(country/product)</span> bridge as shown.", {left: 20, top:315 }); sate4X1st.css({"font-weight": "bold", "font-size": 16}); theProductMatrix._arrays[1].highlight(); theBridge2Matrix._arrays[1].value(0,"<span style='color:red;'>c1</span>"); theBridge2Matrix._arrays[1].value(1,"<span style='color:red;'>p1</span>"); theBridge2Matrix._arrays[1].value(2,"<span style='color:red;'>3000</span>"); av.step(); //slide 6 sate4X1st.hide(); var sate5X1st=av.label("<span style='color:green;'>who sells TV in Egypt?</span> <span style='color:blue;'>(ali)</span> </br>So last step is to fill in <span style='color:green;'>(distributor/product)</span> bridge.", {left: 20, top:315 }); sate5X1st.css({"font-weight": "bold", "font-size": 16}); theBridge1Matrix._arrays[1].value(0,"<span style='color:red;'>d1</span>"); theBridge1Matrix._arrays[1].value(1,"<span style='color:red;'>p1</span>"); av.step(); //slide 7 theBridge1Matrix._arrays[1].unhighlight(); sate5X1st.hide(); var sate6X1st=av.label("All other dataset records should be inserted in the same way as done with first record. </br> <span style='color:red;'>But the problem here</span> is that <span style='color:green;'>no constraints exist</span> to ensure <span style='color:green;'>data integrity</span></br> Assume that user entered a wrong data while filling in (distributor/product) bridge", {left: 20, top:315 }); sate6X1st.css({"font-weight": "bold", "font-size": 16}); var redundantRelationConflict =av.g.ellipse(980,240,65,15, {"stroke-width": 3,"stroke":"red" }); theBridge1Matrix._arrays[1].value(0,""); theBridge1Matrix._arrays[1].value(1,""); av.step(); //slide 8 sate6X1st.hide(); var sate7X1st=av.label("Assume for any reason that <span style='color:green;'>(id=d2)</span> is inserted for ali instead of <span style='color:green;'>(d1)</span> in the </br> (distributor/product) for last step of representing first dataset recod.", {left: 20, top:325 }); sate7X1st.css({"font-weight": "bold", "font-size": 16}); theBridge1Matrix._arrays[1].value(0,"<span style='color:red;'>d2</span>"); theBridge1Matrix._arrays[1].value(1,"<span style='color:red;'>p1</span>"); av.step(); //slide 9 redundantRelationConflict.hide(); sate7X1st.hide(); var sate8X1st=av.label("<span style='color:green;'>Unfortunately,</span> the design will not recognize this data conflict. </br> <span style='color:green;'>d-no</span> in <span style='color:blue;'>(distributor/product)</span> bridge should be equal to <span style='color:green;'>d-no (FK)</span> in <span style='color:blue;'>country table</span></br> This design allows <span style='color:red;'>data corruption</span>.", {left: 20, top:315 }); sate8X1st.css({"font-weight": "bold", "font-size": 16}); var DnoCountry =av.g.ellipse(530,60,15,15, {"stroke-width": 3,"stroke":"red"}); var DnoBridge =av.g.ellipse(945,240,15,15, {"stroke-width": 3,"stroke":"red"}); var DnoCountryPOinter = av.pointer("<span style='color:red;'><b>value conflict</b></span>",theCountryMatrix._arrays[2].index(2), {left: 100, top: 270}); var DnoBridgePOinter = av.pointer("<span style='color:red;'><b>value conflict</b></span>",theBridge1Matrix._arrays[2].index(0), {right: 150, top: 100}); av.step(); //slide 10 DnoCountryPOinter.hide(); DnoBridgePOinter.hide(); DnoCountry.hide(); DnoBridge.hide(); sate8X1st.hide(); var sate9X1st=av.label("<span style='color:green;'>Redundant relationships</span> is the drawback of this design </br>The redundancy is in distributor/product direct relation, this relation is indirectly exists </br>in the design through the country entity </br> To illustrate this concept dataset was hidened.", {left: 20, top:290 }); sate9X1st.css({"font-weight": "bold", "font-size": 16}); theCountryMatrix._arrays[1].unhighlight(); theDistributorMatrix._arrays[1].unhighlight(); theProductMatrix._arrays[1].unhighlight(); theBridge1Matrix._arrays[1].value(0,""); theBridge1Matrix._arrays[1].value(1,""); for (var i=0; i < theDataSetY.length; i++) { RealDataSetY._arrays[i].hide(); } theBridge2Matrix._arrays[2].value(0,"<span style='color:red;'>c1</span>"); theBridge2Matrix._arrays[2].value(1,"<span style='color:red;'>p2</span>"); theBridge2Matrix._arrays[2].value(2,"<span style='color:red;'>5000</span>"); av.step(); //slide 11 theDistributorMatrix._arrays[1].unhighlight(); theBridge1Matrix._arrays[2].unhighlight(); sate9X1st.hide(); var sate10X1st=av.label("The selected part in the design <span style='color:green;'>(1:M) relation</span> between <span style='color:green;'>(country & distributor)</span> means , </br> <b>Each country is associated with only one distributor</b>.", {left: 20, top:325 }); sate10X1st.css({"font-weight": "bold", "font-size": 16}); var OneMRelationCDPart =av.g.ellipse(450,170,100,170, {"stroke-width": 3,"stroke":"red"}); av.step(); //slide 12 OneMRelationCDPart.hide(); sate10X1st.hide(); var sate11X1st=av.label("While this part of the design relates each <span style='color:green;'>country</span> to all <span style='color:green;'>its products</span>.", {left: 20, top:325 }); sate11X1st.css({"font-weight": "bold", "font-size": 16}); var MMRelationCPPart =av.g.ellipse(700,75,400,70, {"stroke-width": 3,"stroke":"red"}); av.step(); //slide 13 MMRelationCPPart.hide(); sate11X1st.hide(); var sate12X1st=av.label("<span style='color:green;'>For Exapmle:</span> By looking at first record in country table we know </br> that Ali is the sole distributor in Egypt (c1) through <span style='color:green;'>FK (d-no=d1)</span>.", {left: 20, top:325 }); sate12X1st.css({"font-weight": "bold", "font-size": 16}); theCountryMatrix._arrays[1].highlight(); theDistributorMatrix._arrays[1].highlight(); DnoCountry.show(); av.step(); //slide 14 theDistributorMatrix._arrays[1].unhighlight(); DnoCountry.hide(); sate12X1st.hide(); var sate13X1st=av.label("And from <span style='color:green;'>first & second record in (country/product)</span> bridge, we know that </br><span style='color:blue;'>TVs (p1) & watches (p2) are sold in Egypt (c1)</span>.", {left: 20, top:325 }); sate13X1st.css({"font-weight": "bold", "font-size": 16}); theCountryMatrix._arrays[1].unhighlight(); theBridge2Matrix._arrays[1].highlight(); theBridge2Matrix._arrays[2].highlight(); av.step(); //slide 15 sate13X1st.hide(); var sate14X1st=av.label("Then logically we can conclude that ali is the only distributor of tvs and watches</br> without need to use the direct distributor/product relation.", {left: 20, top:325 }); sate14X1st.css({"font-weight": "bold", "font-size": 16}); theBridge2Matrix._arrays[1].unhighlight(); theBridge2Matrix._arrays[2].unhighlight(); theCountryMatrix._arrays[1].highlight(); theProductMatrix._arrays[1].highlight(); theDistributorMatrix._arrays[1].highlight(); av.step(); //slide 16 sate14X1st.hide(); var sate15X1st=av.label("So we should git rid of the useless redundant distributor/product relation.", {left: 20, top:325 }); sate15X1st.css({"font-weight": "bold", "font-size": 16}); theCountryMatrix._arrays[1].unhighlight(); theProductMatrix._arrays[1].unhighlight(); theDistributorMatrix._arrays[1].unhighlight(); RealDataSetY._arrays[1].unhighlight(); for (var i=0; i < theDataSetY.length; i++) { RealDataSetY._arrays[i].show(); } WronSignRedundantRelation1.show(); WronSignRedundantRelation2.show(); av.step(); //slide 17 WronSignRedundantRelation1.hide(); WronSignRedundantRelation2.hide(); av.umsg(interpret("4- Discuss pros and cons of all possible <span style='color:blue;'>Store Y solutions</span> to determine the correct one. <br> <span style='color:orange;'>Pay attention as the forth design is the correct solution </span> <br><span style='color:blue;'> <u>Store Y forth sol. analysis:</u></span> ").bold().big()); sate15X1st.hide(); var sate16X1st=av.label("<span style='color:green;'>The new effecient solution after removing the redundant relation is here</span>.", {left: 20, top:325 }); sate16X1st.css({"font-weight": "bold", "font-size": 16}); for (var i=0; i < theBridge1Arrays.length; i++) { theBridge1Matrix._arrays[i].hide(); } ProdMtrxDwnLine.hide(); prodMtrxDwnCardLab.hide(); DistProdBdgMtrxUpCardLab.hide(); DistProdBdgMtrxLeftLine.hide(); DistMtrxRgtCardLab2.hide(); DistProdBdgMtrxLeftCardLab.hide(); // StoreXsol3Analysis.hide(); // var notification=av.label("<span style='color:orange;'>Pay attention as the forth design is the correct solution </span>", {left: 350, top: arrayTop-30 }); // notification.css({"font-weight": "bold", "font-size": 28}); // var StoreXsol4Analysis=av.label("<span style='color:blue;'>Store Y forth Solution Analysis</span>", {left: 350, top: arrayTop-60 }); // StoreXsol4Analysis.css({"font-weight": "bold", "font-size": 28}); av.step(); //slide 18 //notification.hide(); sate16X1st.hide(); var sate17X1st=av.label("Continue inserting dataset records here to ensure <span style='color:green;'>solution correctness</span> </br> In dataset third record as distributor ali also sells in uk</br> ali's id inserted in FK feild at UK record in country table.", {left: 20, top:315 }); sate17X1st.css({"font-weight": "bold", "font-size": 16}); RealDataSetY._arrays[3].highlight(); theCountryMatrix._arrays[3].value(2,"<span style='color:red;'>d1</span>"); theCountryMatrix._arrays[3].highlight(); theDistributorMatrix._arrays[1].highlight(); av.step(); //slide 19 sate17X1st.hide(); var sate18X1st=av.label("As ali sells <span style='color:green;'>blenders with price=2500 </span> in <span style='color:blue;'>UK</span> </br> Then insert <span style='color:red;'>UK-id (c3) & blender-id (p3)</span> in <span style='color:red;'>(product/country)</span> bridge.", {left: 20, top:325 }); sate18X1st.css({"font-weight": "bold", "font-size": 16}); theBridge2Matrix._arrays[3].value(0,"<span style='color:red;'>c3</span>"); theBridge2Matrix._arrays[3].value(1,"<span style='color:red;'>p3</span>"); theBridge2Matrix._arrays[3].value(2,"<span style='color:red;'>2500</span>"); //theBridge2Matrix._arrays[4].highlight(); //theDistributorMatrix._arrays[3].unhighlight(); theProductMatrix._arrays[3].highlight(); av.step(); //slide 20 sate18X1st.hide(); var sate19X1st=av.label("While inserting dataset forth record skip <span style='color:red;'>first step (adding distributor id as</br> a FK in country table)</span> because UK has only one exclusive distributor ali whose</br> id <span style='color:blue;'>is already added</span> at previous record insertion process </i>(record 3 in dataset)</i>.", {left: 20, top:305 }); sate19X1st.css({"font-weight": "bold", "font-size": 16}); RealDataSetY._arrays[4].highlight(); RealDataSetY._arrays[3].unhighlight(); theProductMatrix._arrays[3].unhighlight(); //var aliEgyptPricepointer = av.pointer("<span style='color:blue;'>adam's blender price for Egypt</span>",theBridge2Matrix._arrays[3].index(2), {left: 140, top: 150}); // var aliUSAtPricepointer = av.pointer("<span style='color:green;'>tarek's blender price for Egypt</span>",theBridge2Matrix._arrays[4].index(2), {left: 55, top: 120}); av.step(); //slide 21 sate19X1st.hide(); var sate20X1st=av.label("<span style='color:red;'>But</span> the relation between <span style='color:blue;'>UK & watches</span> sold there with price <span style='color:blue;'>2300</span> </br> should be expressed by inserting (c3, p2) Keys in (country/product) bridge.", {left: 20, top:325 }); sate20X1st.css({"font-weight": "bold", "font-size": 16}); theProductMatrix._arrays[2].highlight(); theBridge2Matrix._arrays[4].value(0,"<span style='color:red;'>c3</span>"); theBridge2Matrix._arrays[4].value(1,"<span style='color:red;'>p2</span>"); theBridge2Matrix._arrays[4].value(2,"<span style='color:red;'>2300</span>"); av.step(); //slide 22 sate20X1st.hide(); var sate21X1st=av.label("<span style='color:red;'>Record 5 insertion</span> results shown at diagram where <span style='color:blue;'>USA country</span> linked with distributor </br>adam through adding <span style='color:blue;'>d2 as a FK</span> in the country table. </br> Then add record details of <span style='color:blue;'>USA product & its price</span> in (product/country) bridge.", {left: 20, top:310 }); sate21X1st.css({"font-weight": "bold", "font-size": 16}); RealDataSetY._arrays[5].highlight(); RealDataSetY._arrays[4].unhighlight(); theProductMatrix._arrays[2].unhighlight(); theProductMatrix._arrays[1].highlight(); theCountryMatrix._arrays[3].unhighlight(); theCountryMatrix._arrays[2].highlight(); theDistributorMatrix._arrays[1].unhighlight(); theDistributorMatrix._arrays[2].highlight(); theBridge2Matrix._arrays[5].value(0,"<span style='color:red;'>c2</span>"); theBridge2Matrix._arrays[5].value(1,"<span style='color:red;'>p1</span>"); theBridge2Matrix._arrays[5].value(2,"<span style='color:red;'>4500</span>"); theCountryMatrix._arrays[2].value(2,"<span style='color:red;'>d2</span>"); av.step(); //slide 23 sate21X1st.hide(); var sate22X1st=av.label("<span style='color:red;'>The remaining dataset records</span> shoulld be added in the same way</br> IF new country or distributor founded (e.g. lebanon country, distributor morad) </br> in record 8 & 9 in dataset, their data should be added as new records in main tables (country & distributor).", {left: 20, top:300 }); sate22X1st.css({"font-weight": "bold", "font-size": 16}); theCountryMatrix._arrays[2].unhighlight(); theDistributorMatrix._arrays[2].unhighlight(); theProductMatrix._arrays[1].unhighlight(); RealDataSetY._arrays[5].unhighlight(); RealDataSetY._arrays[6].highlight(); RealDataSetY._arrays[7].highlight(); RealDataSetY._arrays[8].highlight(); RealDataSetY._arrays[9].highlight(); av.step(); //slide 24 sate22X1st.hide(); var sate23X1st=av.label("As proved <span style='color:red;'>forth solution</span> is the correct design for store Y</br> - Effeciently fulfill all store Y requirments </br> - No redundant relations, no data conflict </br> - No violation for primary key constraint or data integrity.", {left: 20, top:295 }); sate23X1st.css({"font-weight": "bold", "font-size": 16}); RealDataSetY._arrays[6].unhighlight(); RealDataSetY._arrays[7].unhighlight(); RealDataSetY._arrays[8].unhighlight(); RealDataSetY._arrays[9].unhighlight(); av.step(); av.recorded(); });
/* See license.txt for terms of usage */ define([ "firebug/firebug", "firebug/lib/trace", "firebug/lib/object", "firebug/lib/array", "firebug/chrome/module" ], function(Firebug, FBTrace, Obj, Arr, Module) { "use strict"; // ********************************************************************************************* // // Constants // ********************************************************************************************* // // Implementation /** * @module Should be used by modules (Firebug specific task controllers) that supports * activation. An example of such 'activable' module can be the debugger module * {@link Firebug.Debugger}, which can be disabled in order to avoid performance * penalties (in cases where the user doesn't need a debugger for the moment). */ var ActivableModule = Obj.extend(Module, /** @lends ActivableModule */ { /** * Every activable module is disabled by default waiting for on a panel * that wants to have it enabled (and display provided data). The rule is * if there is no panel (view) the module is disabled. */ enabled: false, /** * List of observers (typically panels). If there is at least one observer registered * The module becomes active. */ observers: null, /** * List of dependent modules. */ dependents: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Initialization initialize: function() { Module.initialize.apply(this, arguments); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Observers (dependencies) hasObservers: function() { return this.observers ? this.observers.length > 0 : false; }, addObserver: function(observer) { if (!this.observers) this.observers = []; if (this.observers.indexOf(observer) === -1) { this.observers.push(observer); this.onObserverChange(observer); // targeted, not dispatched. } // else no-op }, removeObserver: function(observer) { if (!this.observers) return; if (this.observers.indexOf(observer) !== -1) { Arr.remove(this.observers, observer); this.onObserverChange(observer); // targeted, not dispatched } // else no-op }, /** * This method is called if an observer (e.g. {@link Panel}) is added or removed. * The module should decide about activation/deactivation upon existence of at least one * observer. */ onObserverChange: function(observer) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Firebug Activation onSuspendingFirebug: function() { // Called before any suspend actions. First caller to return true aborts suspend. }, onSuspendFirebug: function() { // When the number of activeContexts decreases to zero. Modules should remove // listeners, disable function that takes resources }, onResumeFirebug: function() { // When the number of activeContexts increases from zero. Modules should undo the // work done in onSuspendFirebug }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Module enable/disable APIs. isEnabled: function() { return this.hasObservers(); }, isAlwaysEnabled: function() { return this.hasObservers(); } }); // ********************************************************************************************* // // Registration // xxxHonza: backward compatibility Firebug.ActivableModule = ActivableModule; return ActivableModule; // ********************************************************************************************* // });
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Created with IntelliJ IDEA. * User: Natalia.Ukhorskaya * Date: 3/30/12 * Time: 3:37 PM */ var ConverterView = (function () { function ConverterView(element, converterModel) { var my_editor; var model = converterModel; $("body div:first").after("<div class=\"myPopupForConverterFromJavaToKotlin\" title=\"Enter Java code\"><textarea class=\"CodeMirror\" name=\"myTextareaForConverterFromJavaToKotlin\"></textarea></div>"); var popup = $(".myPopupForConverterFromJavaToKotlin"); var instance = { closeDialog:function () { popup.dialog("close"); } }; my_editor = CodeMirror.fromTextArea(document.getElementsByName("myTextareaForConverterFromJavaToKotlin")[0], { lineNumbers:true, matchBrackets:true, mode:"text/x-java", minHeight:"430px" }); element.click(function () { var height = popup.dialog("option", "height") - 120; $("div #scroll", popup).css("height", height + "px"); popup.dialog("open"); my_editor.refresh(); }); popup.dialog({ modal:"true", width:640, height:480, autoOpen:false, resizeStop:function (event, ui) { var height = popup.dialog("option", "height") - 120; $("div #scroll", popup).css("height", height + "px"); my_editor.refresh(); }, buttons:[ { text:"Convert to Kotlin", click:function () { model.convert(my_editor.getValue()); } }, { text:"Cancel", click:function () { popup.dialog("close"); } } ] }); return instance; } return ConverterView; })();
// Fastest const array = [1, 2, 3]; array.constructor === Array; // Returns true // Other forms of typechecking typeof 'abc' // Returns string [1, 2, 3] instanceof Array // Returns true Array.isArray([1, 2, 3]) // Returns true
let a = new Map( [ [ 'a', '123' ], [ 'b', '123213' ] ] ); // 遍历所有[ key, value ] for( let i of a.entries() ) { console.log( i ); console.log( i[ 1 ] ); }
let wordBrokenArray; const alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); let game = { wins: 0, losses: 0, guessesLeft: 9, lettersGuessed: [], wordBank: [ "bluth", "gob", "michael", "george michael", "hot cops", "hermano", "lucille", "buster", "tobias", "anne", "cousins", "lindsey", "brother", "bannana", "judge", "mrf", "seal", "steve holt", "oscar", "uncle father", "lucille ii", "teamocil", "carl weathers", "tbd" ] }; // Turn word into array // Create a loop for array and add true false tags function breakWord(str) { wordBrokenArray = str .split("") .map(char => char === " " ? { char, isShow: true } : { char, isShow: false } ); return wordBrokenArray; } function renderGuessArray(arr) { renderScoreBoard(); const mainBody = document.getElementById("main-container"); console.log(mainBody); mainBody.innerHTML = ""; let container = document.createElement("div"); container.classList.add("container"); arr.forEach(char => { let charDivs = document.createElement("div"); charDivs.classList.add("char-divs"); if (char.isShow) { charDivs.innerHTML = char.char.toUpperCase(); console.log("Div is set with char!"); } else { charDivs.innerHTML = "*"; console.log("Div is set with -"); } container.append(charDivs); }); mainBody.append(container); } function renderScoreBoard() { const scoreBoardContainer = document.getElementById("score-board"); scoreBoardContainer.innerHTML = ""; console.log(scoreBoardContainer); const grouping = document.createElement("ul"); let wins = document.createElement("li"); wins.innerHTML = `Wins: ${game.wins}`; let losses = document.createElement("li"); losses.innerHTML = `Losses: ${game.losses}`; let guessesLeft = document.createElement("li"); guessesLeft.innerHTML = `Guesses Left: ${game.guessesLeft}`; grouping.append(wins, losses, guessesLeft); scoreBoardContainer.append(grouping); } function render() { renderScoreBoard(); renderGuessArray(wordBrokenArray); renderAlphabet(); } function checkGuess(guess) { if (game.lettersGuessed.includes(guess)) { const gameMessage = document; } else { let correctArr = wordBrokenArray.map(char => char.char); if (correctArr.indexOf(guess) !== -1) { for (let i = 0; i < wordBrokenArray.length; i++) { if (wordBrokenArray[i].char === guess) { console.log(correctArr); wordBrokenArray[i].isShow = true; checkWin(wordBrokenArray); console.log(wordBrokenArray); } } game.lettersGuessed.push(guess.toUpperCase()); } else { console.log(correctArr); console.log("wrong"); game.guessesLeft--; checkLoss(); console.log(game.guessesLeft); game.lettersGuessed.push(guess.toUpperCase()); } } render(); } function renderAlphabet() { document.getElementById("alphabet-container").innerHTML = ""; alphabet.forEach(letter => { let ltrBoxElem = document.createElement("div"); ltrBoxElem.classList.add("letter-box"); if (game.lettersGuessed.includes(letter.toUpperCase())) { ltrBoxElem.classList.add("letter-used"); } ltrBoxElem.innerHTML = `<p>${letter}</p>`; document.getElementById("alphabet-container").appendChild(ltrBoxElem); }); } function checkLoss() { game.guessesLeft === 0 ? giveLoss() : collectGuessedChar(); } function giveWin() { game.wins++; resetGame(); } function giveLoss() { game.losses++; resetGame(); } function checkWin(arr) { let len = arr.length; let checkIsShow = arr.filter(char => char.isShow === true).length; len === checkIsShow ? giveWin() : collectGuessedChar(); } function resetGame() { console.log("Resetting game"); getRandomWord(game.wordBank); game.guessesLeft = 9; game.lettersGuessed = []; } function getRandomWord(arr) { let randomIndex = Math.floor(Math.random() * arr.length); breakWord(arr[randomIndex]); renderGuessArray(wordBrokenArray); renderAlphabet(); collectGuessedChar(); } getRandomWord(game.wordBank); function collectGuessedChar() { document.onkeyup = e => { e.preventDefault(); let guess = e.key; checkGuess(guess); }; }
import lazy from '@kuba/lazy' export default lazy(() => import('@kuba/navigation' /* webpackChunkName: "navigation" */))
// var first = prompt("Input first number: ", ' ');] // var second = prompt("Input second number: ",' '); var suma; do{ var first = prompt("Input first number: ", ' '); } while(first != 1); suma = first + second;
module.exports = function(ImageService, ImageApiService, $state) { this.getImageList = function(scope) { console.log('ImageRouteService: getImageList') console.log('foo: ', scope.foo) /* scope.title = ImageService.title() scope.imageArray = ImageService.ImageList() scope.ImageCount = ImageService.ImageCount() */ } this.getImage = function(scope, id) { console.log('ImageRouteService: getImage ' + id) ImageApiService.getImage(id) .then( function (response) { ImageService.updateScope(scope) $state.go('images', {}, {reload: true}) }, function (error) { // handle errors here // console.log(error.statusText); console.log('ERROR!'); } ); } }
import React from "react"; import Button from "../atoms/button"; function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); console.log(e); } function JsxVsJs() { return ( <React.Fragment> {/* jsx */} <div> jsx: <Button className="red" ariaLabel="click me button" tooltip="tooltip" onClick={handleClick}> Click me! </Button> </div> {/* javascript syntax */} {React.createElement( "div", null, "javascript: ", React.createElement( Button, { className: "blue", ariaLabel: "click me button", tooltip: "tooltip", onClick:handleClick }, "trykk på meg!" ) )} </React.Fragment> ); } export default JsxVsJs;
/* * @lc app=leetcode.cn id=316 lang=javascript * * [316] 去除重复字母 */ // @lc code=start /** * @param {string} s * @return {string} */ var removeDuplicateLetters = function(s) { let newSet = new Set(); let stack = []; let newMap = new Map(); for (let i = 0; i < s.length; i++) { newMap.set(s[i], newMap.get(s[i]) + 1 || 1); } for (let i = 0; i < s.length; i++) { if (!newSet.has(s[i])) { while(stack.length && stack[stack.length - 1] > s[i] && newMap.get(stack[stack.length - 1] ) > 0) { newSet.delete(stack.pop()); } newSet.add(s[i]); stack.push(s[i]) } newMap.set(s[i], newMap.get(s[i]) -1 || -1); } return stack.join(''); }; // @lc code=end
import * as THREE from "three"; import {OrbitControls} from "three/examples/jsm/controls/OrbitControls"; /** * Initializes all the necessary THREE.js objects * @param canvas reference to the canvas dom element * @param width canvas width * @param height canvas height * @param numV number of vertices of the network to add to the scene * @param numE number of edges of the network to add to the scene */ export function createNetworkSystem(canvas, width, height, numV, numE){ const renderer = new THREE.WebGLRenderer({canvas: canvas, alpha:true}); renderer.setSize(width, height); const camera = new THREE.PerspectiveCamera(75, 1, 0.1); camera.aspect = width/height; const pointLight = new THREE.PointLight(0xffffff, 1); pointLight.position.set(1,1,2); camera.add(pointLight); const controls = new OrbitControls(camera, canvas); controls.target.set(width/2, height/2, Math.max(height/2, width/2)); camera.position.set(width/2, height/2, 1.7 * Math.max(height, width)); controls.update(); const nodeScene = createNodesInScene(camera, numV, numE, width, height); const rayCaster = new THREE.Raycaster(); const pointer = new THREE.Vector2(); //creating a highlight cursor const cursorGeometry = new THREE.SphereGeometry(5, 4,4); const cursorMaterial = new THREE.MeshBasicMaterial( {color: 0xffff00} ); const cursor = new THREE.Mesh(cursorGeometry, cursorMaterial); cursor.visible = false; nodeScene.scene.add(cursor); return { renderer: renderer, camera: camera, pointLight: pointLight, controls: controls, scene: nodeScene.scene, nodes: nodeScene.nodes, connections: nodeScene.connections, raycaster: rayCaster, pointer: pointer, cursor: cursor, }; } /** * * @param camera THREE.js camera for our scene * @param numV number of vertices to create in the network * @param numE number of edges to create in the network * @param width width of the canvas * @param height height of the canvas * @returns {{nodes: THREE.Points, connections: THREE.Line, scene: THREE.Scene}} */ export function createNodesInScene(camera, numV, numE, width, height){ const scene = new THREE.Scene(); scene.add(camera); const systemGeometry = new THREE.BufferGeometry(); const vertices = []; const color = new THREE.Color(); let colors = []; console.time("vertices js"); for(let i = 0; i < numV; i++){ const x = Math.random() * width; const y = Math.random() * height; const z = Math.random() * Math.max(height,width); vertices.push(x); vertices.push(y); vertices.push(z); const vx = (x / width); const vy = (y / height); const vz = (z / Math.max(height, width)); color.setRGB(vx, vy, vz); colors.push(color.r, color.g, color.b); } console.timeEnd("vertices js"); const elements = new Float32Array(vertices); systemGeometry.setAttribute("position", new THREE.Float32BufferAttribute(elements, 3)); systemGeometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3)); const material = new THREE.PointsMaterial({vertexColors: true, size: 5}); const nodes = new THREE.Points(systemGeometry, material); nodes.geometry.computeBoundingSphere(); nodes.geometry.computeBoundingBox(); scene.add(nodes); console.time("edges js"); const connectionGeometry = new THREE.BufferGeometry(); const edges = []; colors = [] for(let i = 0; i < numE; i++){ const vStart = Math.floor(Math.random()*numV); const vEnd = Math.floor(Math.random()*numV); edges.push(nodes.geometry.attributes.position.array[3 * vStart]); edges.push(nodes.geometry.attributes.position.array[3 * vStart + 1]); edges.push(nodes.geometry.attributes.position.array[3 * vStart + 2]); edges.push(nodes.geometry.attributes.position.array[3 * vEnd]); edges.push(nodes.geometry.attributes.position.array[3 * vEnd + 1]); edges.push(nodes.geometry.attributes.position.array[3 * vEnd + 2]); color.setRGB( nodes.geometry.attributes.color.array[3 * vStart], nodes.geometry.attributes.color.array[3 * vStart + 1], nodes.geometry.attributes.color.array[3 * vStart + 2] ); colors.push(color.r, color.g, color.b); color.setRGB( nodes.geometry.attributes.color.array[3 * vStart], nodes.geometry.attributes.color.array[3 * vStart + 1], nodes.geometry.attributes.color.array[3 * vStart + 2] ); colors.push( nodes.geometry.attributes.color.array[3 * vEnd], nodes.geometry.attributes.color.array[3 * vEnd + 1], nodes.geometry.attributes.color.array[3 * vEnd + 2] ) } console.timeEnd("edges js"); const elements2 = new Float32Array(edges); connectionGeometry.setAttribute("position", new THREE.Float32BufferAttribute(elements2, 3)); connectionGeometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3)); const material2 = new THREE.MeshBasicMaterial({vertexColors: true, transparent: true, opacity: 0.3}); const connections = new THREE.Line(connectionGeometry, material2); connections.geometry.computeBoundingSphere(); connections.geometry.computeBoundingBox(); scene.add(connections); return {scene: scene, nodes: nodes, connections: connections}; }
chrome.extension.onRequest.addListener(function(request, sender) {localStorage.setItem("dom",request.message);});
import React from "react"; import {Accordion} from "react-bootstrap"; const Connections = (props) => { return ( <> <Accordion className='fonts'> <Accordion.Item eventKey="0"> <Accordion.Header>Connections</Accordion.Header> <Accordion.Body className='backgroundInfo'> Group affiliation: {props.connections?.["group-affiliation"]}<br/> Relatives: {props.connections?.relatives} </Accordion.Body> </Accordion.Item> </Accordion> </> ) } export default Connections;
import { getToken } from '@/lib/auth' import jwtDecode from "jwt-decode"; export default { userInfo: getToken() && jwtDecode(getToken()), }
"use strict" const { isSkipToken } = require("./token-utils") /** * Extract prop name tokens * @param {*} sourceCode * @param {*} start */ function extractTokens(sourceCode, start) { const cursor = sourceCode.createScopeTokenCursor(start) let token = cursor.next() const tokens = [] let endIndex = start while (token) { if (cursor.scopeLevel === 0) { if (isSkipToken(token)) { // end endIndex = token.range[0] - 1 break } if (token.type === "string" && tokens.length > 0) { // end endIndex = token.range[0] - 1 break } if (token.value === ".") { if ( tokens.length > 0 && tokens[tokens.length - 1].range[1] === token.range[0] ) { // maybe member expression } else { // end endIndex = token.range[0] - 1 break } } if ( token.value === ":" || token.value === "=" || token.value === "," || token.value === "!" || token.value === "}" ) { // end endIndex = token.range[0] - 1 break } } tokens.push(token) endIndex = token.range[1] - 1 token = cursor.next() } return { tokens, endIndex, } } module.exports = (sourceCode, start) => { const { tokens, endIndex } = extractTokens(sourceCode, start) return { prop: tokens.map((t) => t.value).join(""), raw: {}, endIndex, } }