text
stringlengths
7
3.69M
import React, { useState, useEffect } from 'react'; import { StyleSheet, Text, View, Button, ActivityIndicator, Alert, } from 'react-native'; import Colors from '../constants/Colors'; import MapPreview from './MapPreview'; import * as Location from 'expo-location'; const LocationPicker = (props) => { const [location, setLocation] = useState(null); const [isFetching, setIsFetching] = useState(false); const mapPickedLocation = props.navigation.getParam('pickedLocation'); useEffect(() => { setLocation(mapPickedLocation); props.onLocationPicked(mapPickedLocation); }, [mapPickedLocation?.lat, mapPickedLocation?.lng, props.onLocationPicked]); const verifyPermissions = async () => { if (Platform.OS !== 'web') { const { status } = await Location.requestForegroundPermissionsAsync(); if (status !== 'granted') { Alert.alert( 'Insufficient permissions', 'Permission to access location was denied', [{ text: 'Okay' }] ); return false; } return true; } }; let text = 'Waiting..'; if (location) { text = JSON.stringify(location); } const getLocationHandler = async () => { const hasPermission = await verifyPermissions(); if (!hasPermission) { return; } try { setIsFetching(true); const loc = await Location.getCurrentPositionAsync(); setLocation({ lat: loc.coords.latitude, lng: loc.coords.longitude }); props.onLocationPicked({ lat: loc.coords.latitude, lng: loc.coords.longitude, }); } catch (err) { Alert.alert( 'Could not get location', 'Try again later or pick a location on the map', [{ text: 'Okay' }] ); } finally { setIsFetching(false); } }; const pickOnMapHandler = () => { props.navigation.navigate('Map'); }; return ( <View style={styles.locationPicker}> <MapPreview onPress={pickOnMapHandler} location={location} style={styles.mapPreview} > {isFetching ? ( <ActivityIndicator size="large" color={Colors.primary} /> ) : ( <Text>{text}</Text> )} </MapPreview> <View style={styles.actions}> <Button title="Get User Location" color={Colors.primary} onPress={getLocationHandler} /> <Button title="Pick on Map" color={Colors.primary} onPress={pickOnMapHandler} /> </View> </View> ); }; export default LocationPicker; const styles = StyleSheet.create({ locationPicker: { marginBottom: 15, }, mapPreview: { marginBottom: 10, width: '100%', height: 150, borderColor: '#ccc', borderWidth: 1, }, actions: { flexDirection: 'row', justifyContent: 'space-around', width: '100%', }, });
import React from 'react'; import classes from './FilterItem.module.css'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faTimes } from '@fortawesome/free-solid-svg-icons' const FilterItem = (props) => { return ( <div className={classes.item}> <p className={classes.p}>{props.tag}</p> <div className={classes.iconContainer} onClick={() => props.removeTag(props.tag)}> <FontAwesomeIcon icon={faTimes} size="lg" className={classes.icon} /> </div> </div> ); } export default FilterItem;
import categoryRoute from './category.routes' export default angular.module('category.index',[]) .config(categoryRoute) .name
import React, {Component} from 'react'; import './stylesheets/styleSheet.css'; import './stylesheets/EventPopup.css' // Component to act as container for login system export class EventPopup extends Component { constructor(props) { super(props); this.state = { title: '', startTime: '', endTime: '', organizer: '', description: '' }; this.handleTitleChange = this.handleTitleChange.bind(this); this.handleOrganizerChange = this.handleOrganizerChange.bind(this); this.handleDescriptionChange = this.handleDescriptionChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleTitleChange(e) { this.setState({title: e.target.value}); } handleStartTimeChange(e) { this.setState({startTime: e.target.value}); } handleEndTimeChange(e) { this.setState({endTime: e.target.value}); } handleOrganizerChange(e) { this.setState({organizer: e.target.value}); } handleDescriptionChange(e) { this.setState({description: e.target.value}); } handleSubmit(event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); } render() { const style = { position: "absolute", top: this.props.position.top, left: this.props.position.left, right: this.props.position.right, bottom: this.props.position.bottom, width: this.props.position.width.toString() + "px", height: this.props.position.height.toString() + "px", }; console.log(style); return ( <div className="body"> <form onSubmit={this.handleSubmit} className="popup" style={style}> <input type="text" value={this.state.title} onChange={this.handleTitleChange} style={{gridArea: "1 / 2 / 2 / 3"}} placeholder="Title" /> <img src="timeIcon.png" alt="Time Icon" className="icon" style={{gridArea: "2 / 1 / 3 / 2"}} /> <div style={{gridArea: "2 / 2 / 3 / 22"}}> <input type="text" value={this.state.startTime} onChange={this.handleStartTimeChange} placeholder="Start Time" /> <span> - </span> <input type="text" value={this.state.endTime} onChange={this.handleEndTimeChange} placeholder="End Time" /> </div> <img src="organizerIcon.jpg" alt="Organizer Icon" className="icon" style={{gridArea: "3 / 1 / 4 / 2"}} /> <input type="text" value={this.state.organizer} onChange={this.handleOrganizerChange} style={{gridArea: "3 / 2 / 4 / 3"}} placeholder="Organizer Name" /> <img src="descriptionIcon.jpg" alt="Description Icon" className="icon" style={{gridArea: "4 / 1 / 5 / 2", alignSelf: "flex-start"}} /> <textarea type="text" value={this.state.description} onChange={this.handleDescriptionChange} style={{gridArea: "4 / 2 / 5 / 3"}} placeholder="Description" /> <div className="submitPanel" style={{gridArea: "5 / 2 / 6 / 3"}}> <input type="submit" value="Save" /> <input type="submit" value="Cancel" onClick={this.props.closePopup} /> </div> </form> </div> ); } }
import React from 'react'; import {View, Text, Image} from 'react-native'; import { ButtonRoundet } from '../common'; import {RATIO, WIDTH_RATIO} from '../../styles/constants' let labelFontSize = WIDTH_RATIO <= 1 ? 11 : 13; const CardComponent = ({onPress, children, imageSrc, style, imageParentStyle, imageContainerStyles, isDisabled}) => { const {container, imageContainer, imageStyle, textStyle, buttonStyle} = styles; return ( <View style={[ container, style ]}> <View style={[imageContainer, imageContainerStyles]}> <Image // resizeMode={'contain'} style={[imageStyle, imageParentStyle]} source={imageSrc} /> </View> <View style={{ // backgroundColor: '#61c9eb', marginBottom: 18, height: 35, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'flex-start', paddingLeft: 9*WIDTH_RATIO, paddingRight: 6*WIDTH_RATIO }}> <ButtonRoundet isDisabled={isDisabled} style={[buttonStyle, {backgroundColor: isDisabled ? '#e1a700' : '#FFC200'}]} textStyle={[textStyle, {color: isDisabled ? '#e0e0e0' : '#1d1d1d'}]} onPress={onPress} > {children} </ButtonRoundet> </View> </View> ) } const styles = { container: { // width: 160, height: 180 * WIDTH_RATIO, flex:1, flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'center', borderWidth:1, borderRadius:4, borderColor: '#bcbcb3', marginHorizontal: 10, }, imageContainer: { flex:1, // backgroundColor: '#286', justifyContent: 'center', alignItems: 'center', // marginBottom: 34 * WIDTH_RATIO, // marginTop: 26 * WIDTH_RATIO, }, imageStyle: { width: 45, height: 64 }, textStyle: { color:'#1d1d1d', fontSize: labelFontSize, fontWeight: '400' }, buttonStyle: { justifyContent: 'center', alignItems: 'center', // alignSelf: 'stretch', // paddingRight: 10*WIDTH_RATIO, // paddingLeft: 10*WIDTH_RATIO, backgroundColor: '#FFC200', borderColor:'#FFC200', marginRight: 1, marginLeft: 1, } } export default CardComponent;
$('#submitFormBtn').on('click',function (e){ // Show search section $('#feature-area').fadeIn(); $('#reviewDiv').empty(); // Show content when search var x = document.getElementById("reviewDiv"); x.style.display = "block"; e.preventDefault(); /* Add something like this after we catagorize data if (e.options[e.selectedIndex].value == "All") { } */ var dataSize = 0; $(searchResultTitle).text("Search Result"); var searchValue = document.getElementById("productNameTB").value; var searchDropDown = document.getElementById("searchDropDown"); var searchCategory = searchDropDown.options[searchDropDown.selectedIndex].text; if (searchCategory == "All") { searchCategory = '*'; } else { searchCategory = "'" + searchCategory + "'"; } var startCount = document.getElementById("searchStartCount").value; var count = document.getElementById("searchEndCount").value; if (startCount == "" || isNaN(startCount)) { startCount = 1; count = 10; document.getElementById("searchStartCount").innerHTML = startCount; document.getElementById("searchEndCount").innerHTML = count; //document.getElementById("nextBtn").style.display = "block"; } else { // Increment count startCount = startCount + 1; document.getElementById("searchStartCount").innerHTML = startCount; count = count + 10; document.getElementById("searchEndCount").innerHTML = count; //document.getElementById("nextBtn").style.display = "block"; } $.ajax({ 'url': 'http://localhost:8983/solr/4034_IR/select', 'data': {'wt':'json', 'q': "'" + searchValue + "'", 'fq':"category:" + searchCategory, //searchCategory + "'"}, 'start': parseInt(startCount) - 1, 'sort': "" //'rows': count }, 'success': function(data) { var dataSize = data.response.numFound; if (dataSize > 0) { $(resultsMsg1).text("Displaying"); $(resultsMsg2).text("-"); $(searchString).text(" results for '" + searchValue + "' | Total: " + dataSize + " results (" + data.responseHeader.QTime + "ms)" ); document.getElementById("sortBy").style.display = "block"; //document.getElementById("searchString").value = dataSize + " search results on " + searchValue + " found"; } else { document.getElementById("searchStartCount").style.display = "none"; document.getElementById("searchEndCount").style.display = "none"; document.getElementById("resultsMsg1").style.display = "none"; document.getElementById("resultsMsg2").style.display = "none"; $(searchString).text("No results found"); //document.getElementById("searchString").value = } if (document.getElementById("searchString").innerHTML == "No results found") { document.getElementById("prevBtn").style.display = "none"; document.getElementById("nextBtn").style.display = "none"; } else { document.getElementById("nextBtn").style.display = "block"; } if (count == dataSize || dataSize == 10) { document.getElementById("nextBtn").style.display = "none"; } if (count > dataSize) { document.getElementById("searchEndCount").innerHTML = dataSize; document.getElementById("nextBtn").style.display = "none"; } var i; for (i = 0; i < dataSize; i++) { //alert(data.response.docs[i]); //var $innerFormDiv = document.createElement("FORM"); //$innerFormDiv.setAttribute("name", "showAllReviewForm"); //$innerFormDiv.className = "feature-item"; var $innerReviewDiv = document.createElement("div"); $innerReviewDiv.className = "feature-item"; //$("innerReviewDiv").css({"float": "right", "clear": "left"}); // Product Image var $innerReviewDivProdImg = document.createElement("img"); $innerReviewDivProdImg.setAttribute("src", data.response.docs[i]["image"]); $innerReviewDivProdImg.setAttribute("width", "150"); $innerReviewDivProdImg.setAttribute("height", "200"); $innerReviewDivProdImg.setAttribute("class", "prodImg"); // Product Name var $innerReviewDivProdName = document.createElement("h4"); $innerReviewDivProdName.setAttribute("name", "pdtName"); $innerReviewDivProdName.innerHTML = data.response.docs[i]["name"]; // Product URL var $innerReviewDivProdUrl = document.createElement("a"); $innerReviewDivProdUrl.setAttribute("href", data.response.docs[i]["url"]); $innerReviewDivProdUrl.innerHTML = data.response.docs[i]["url"]; // Product Price var $innerReviewDivProdPrice = document.createElement("p"); $innerReviewDivProdPrice.innerHTML = "Price: $" + data.response.docs[i]["price"]; // Product 5 stars ratings var $innerReviewDivProdRating5 = document.createElement("p"); $innerReviewDivProdRating5.innerHTML = "5 Stars Rating: " + data.response.docs[i]["ratings.5_star"] + "%"; // Product Summary var $innerReviewDivProdSummary = document.createElement("p"); $innerReviewDivProdSummary.innerHTML = "Review Summary: " + data.response.docs[i]["summary"]; $innerReviewDiv.appendChild($innerReviewDivProdImg); $innerReviewDiv.appendChild($innerReviewDivProdName); $innerReviewDiv.appendChild($innerReviewDivProdUrl); $innerReviewDiv.appendChild($innerReviewDivProdPrice); $innerReviewDiv.appendChild($innerReviewDivProdRating5); $innerReviewDiv.appendChild($innerReviewDivProdSummary); document.getElementById("reviewDiv").appendChild($innerReviewDiv); } }, 'dataType': 'jsonp', 'jsonp': 'json.wrf' }); $([document.documentElement, document.body]).animate({ scrollTop: $(".feature-area").offset().top }, 400); }); $('#nextBtn').on('click',function (e){ var sortByCondition = document.getElementById("sortBy").value; // Show content when search var x = document.getElementById("reviewDiv"); x.style.display = "block"; e.preventDefault(); var dataSize = 0; $(searchResultTitle).text("Search Result"); var searchValue = document.getElementById("productNameTB").value; var searchDropDown = document.getElementById("searchDropDown"); var searchCategory = searchDropDown.options[searchDropDown.selectedIndex].text; if (searchCategory == "All") { searchCategory = '*'; } else { searchCategory = "'" + searchCategory + "'"; } var startCount = document.getElementById("searchStartCount").innerHTML; var count = document.getElementById("searchEndCount").innerHTML; // Check if this is first page of results if (parseInt(startCount) == false) { startCount = 1; count = 10; document.getElementById("searchStartCount").innerHTML = startCount; document.getElementById("searchEndCount").innerHTML = count; document.getElementById("nextBtn").style.display = "block"; } // Check if this is not first page of results else { $("#reviewDiv").empty(); // Increment count startCount = parseInt(count) + 1; document.getElementById("searchStartCount").innerHTML = startCount; count = parseInt(count) + 10; document.getElementById("searchEndCount").innerHTML = count; document.getElementById("prevBtn").style.display = "block"; document.getElementById("nextBtn").style.display = "block"; } $.ajax({ 'url': 'http://localhost:8983/solr/4034_IR/select', 'data': {'wt':'json', 'q': "'" + searchValue + "'", 'fq':"category:" + searchCategory, //searchCategory + "'"}, 'start': parseInt(startCount) - 1, 'sort': sortByCondition //'rows': parseInt(count) }, 'success': function(data) { var dataSize = data.response.numFound; if (dataSize > 0) { $(resultsMsg1).text("Displaying"); $(resultsMsg2).text("-"); $(searchString).text(" results for '" + searchValue + "' | Total: " + dataSize + " results (" + data.responseHeader.QTime + "ms)" ); //document.getElementById("searchString").value = dataSize + " search results on " + searchValue + " found"; } else { document.getElementById("searchStartCount").style.display = "none"; document.getElementById("searchEndCount").style.display = "none"; document.getElementById("resultsMsg1").style.display = "none"; document.getElementById("resultsMsg2").style.display = "none"; startCount = 0; document.getElementById("prevBtn").style.display = "none"; $(searchString).text("No results found"); //document.getElementById("searchString").value = } if (count > dataSize) { count = dataSize; document.getElementById("searchEndCount").innerHTML = count; document.getElementById("prevBtn").style.display = "block"; document.getElementById("nextBtn").style.display = "none"; } if (dataSize == 10) { document.getElementById("nextBtn").style.display = "none"; } if (document.getElementById("searchString").innerHTML == "No results found") { document.getElementById("prevBtn").style.display = "none"; } var i; for (i = 0; i < dataSize; i++) { //alert(data.response.docs[i]); //var $innerFormDiv = document.createElement("FORM"); //$innerFormDiv.setAttribute("name", "showAllReviewForm"); //$innerFormDiv.className = "feature-item"; var $innerReviewDiv = document.createElement("div"); $innerReviewDiv.className = "feature-item"; //$("innerReviewDiv").css({"float": "right", "clear": "left"}); // Product Image var $innerReviewDivProdImg = document.createElement("img"); $innerReviewDivProdImg.setAttribute("src", data.response.docs[i]["image"]); $innerReviewDivProdImg.setAttribute("width", "150"); $innerReviewDivProdImg.setAttribute("height", "200"); $innerReviewDivProdImg.setAttribute("class", "prodImg"); // Product Name var $innerReviewDivProdName = document.createElement("h4"); $innerReviewDivProdName.setAttribute("name", "pdtName"); $innerReviewDivProdName.innerHTML = data.response.docs[i]["name"]; // Product URL var $innerReviewDivProdUrl = document.createElement("a"); $innerReviewDivProdUrl.setAttribute("href", data.response.docs[i]["url"]); $innerReviewDivProdUrl.innerHTML = data.response.docs[i]["url"]; // Product Price var $innerReviewDivProdPrice = document.createElement("p"); $innerReviewDivProdPrice.innerHTML = "Price: $" + data.response.docs[i]["price"]; // Product 5 stars ratings var $innerReviewDivProdRating5 = document.createElement("p"); $innerReviewDivProdRating5.innerHTML = "5 Stars Rating: " + data.response.docs[i]["ratings.5_star"] + "%"; // Product Summary var $innerReviewDivProdSummary = document.createElement("p"); $innerReviewDivProdSummary.innerHTML = "Review Summary: " + data.response.docs[i]["summary"]; $innerReviewDiv.appendChild($innerReviewDivProdImg); $innerReviewDiv.appendChild($innerReviewDivProdName); $innerReviewDiv.appendChild($innerReviewDivProdUrl); $innerReviewDiv.appendChild($innerReviewDivProdPrice); $innerReviewDiv.appendChild($innerReviewDivProdRating5); $innerReviewDiv.appendChild($innerReviewDivProdSummary); document.getElementById("reviewDiv").appendChild($innerReviewDiv); } }, 'dataType': 'jsonp', 'jsonp': 'json.wrf' }); $([document.documentElement, document.body]).animate({ scrollTop: $(".feature-area").offset().top }, 400); }); $('#prevBtn').on('click',function (e){ var sortByCondition = document.getElementById("sortBy").value; // Show content when search var x = document.getElementById("reviewDiv"); x.style.display = "block"; e.preventDefault(); var dataSize = 0; $(searchResultTitle).text("Search Result"); var searchValue = document.getElementById("productNameTB").value; var searchDropDown = document.getElementById("searchDropDown"); var searchCategory = searchDropDown.options[searchDropDown.selectedIndex].text; if (searchCategory == "All") { searchCategory = '*'; } else { searchCategory = "'" + searchCategory + "'"; } var startCount = document.getElementById("searchStartCount").innerHTML; var count = document.getElementById("searchEndCount").innerHTML; $("#reviewDiv").empty(); // Decrement count count = parseInt(startCount) - 1; document.getElementById("searchEndCount").innerHTML = count; startCount = parseInt(startCount) - 10; document.getElementById("searchStartCount").innerHTML = startCount; document.getElementById("prevBtn").style.display = "block"; document.getElementById("nextBtn").style.display = "block"; // Check if this is first page of results if ((parseInt(startCount) - 10) <= 1) { document.getElementById("prevBtn").style.display = "none"; document.getElementById("prevBtn").style.float = "left"; } $.ajax({ 'url': 'http://localhost:8983/solr/4034_IR/select', 'data': {'wt':'json', 'q': "'" + searchValue + "'", 'fq':"category:" + searchCategory, //searchCategory + "'"}, 'start': parseInt(startCount) - 1, 'sort': sortByCondition //'rows': parseInt(count) }, 'success': function(data) { var dataSize = data.response.numFound; if (dataSize > 0) { $(resultsMsg1).text("Displaying"); $(resultsMsg2).text("-"); $(searchString).text(" results for '" + searchValue + "' | Total: " + dataSize + " results (" + data.responseHeader.QTime + "ms)" ); //document.getElementById("searchString").value = dataSize + " search results on " + searchValue + " found"; } else { document.getElementById("searchStartCount").style.display = "none"; document.getElementById("searchEndCount").style.display = "none"; document.getElementById("resultsMsg1").style.display = "none"; document.getElementById("resultsMsg2").style.display = "none"; startCount = 0; document.getElementById("prevBtn").style.display = "none"; $(searchString).text("No results found"); //document.getElementById("searchString").value = } if (document.getElementById("searchString").innerHTML == "No results found") { document.getElementById("prevBtn").style.display = "none"; } if (dataSize == 10) { document.getElementById("nextBtn").style.display = "none"; } var i; for (i = 0; i < dataSize; i++) { //alert(data.response.docs[i]); //var $innerFormDiv = document.createElement("FORM"); //$innerFormDiv.setAttribute("name", "showAllReviewForm"); //$innerFormDiv.className = "feature-item"; var $innerReviewDiv = document.createElement("div"); $innerReviewDiv.className = "feature-item"; //$("innerReviewDiv").css({"float": "right", "clear": "left"}); // Product Image var $innerReviewDivProdImg = document.createElement("img"); $innerReviewDivProdImg.setAttribute("src", data.response.docs[i]["image"]); $innerReviewDivProdImg.setAttribute("width", "150"); $innerReviewDivProdImg.setAttribute("height", "200"); $innerReviewDivProdImg.setAttribute("class", "prodImg"); // Product Name var $innerReviewDivProdName = document.createElement("h4"); $innerReviewDivProdName.setAttribute("name", "pdtName"); $innerReviewDivProdName.innerHTML = data.response.docs[i]["name"]; // Product URL var $innerReviewDivProdUrl = document.createElement("a"); $innerReviewDivProdUrl.setAttribute("href", data.response.docs[i]["url"]); $innerReviewDivProdUrl.innerHTML = data.response.docs[i]["url"]; // Product Price var $innerReviewDivProdPrice = document.createElement("p"); $innerReviewDivProdPrice.innerHTML = "Price: $" + data.response.docs[i]["price"]; // Product 5 stars ratings var $innerReviewDivProdRating5 = document.createElement("p"); $innerReviewDivProdRating5.innerHTML = "5 Stars Rating: " + data.response.docs[i]["ratings.5_star"] + "%"; // Product Summary var $innerReviewDivProdSummary = document.createElement("p"); $innerReviewDivProdSummary.innerHTML = "Review Summary: " + data.response.docs[i]["summary"]; $innerReviewDiv.appendChild($innerReviewDivProdImg); $innerReviewDiv.appendChild($innerReviewDivProdName); $innerReviewDiv.appendChild($innerReviewDivProdUrl); $innerReviewDiv.appendChild($innerReviewDivProdPrice); $innerReviewDiv.appendChild($innerReviewDivProdRating5); $innerReviewDiv.appendChild($innerReviewDivProdSummary); document.getElementById("reviewDiv").appendChild($innerReviewDiv); } }, 'dataType': 'jsonp', 'jsonp': 'json.wrf' }); $([document.documentElement, document.body]).animate({ scrollTop: $(".feature-area").offset().top }, 400); }); $("#sortBy").change(function (e) { $('#reviewDiv').empty(); // Get sort by value var sortByCondition = $(this).val(); // Show content when search var x = document.getElementById("reviewDiv"); x.style.display = "block"; e.preventDefault(); var dataSize = 0; $(searchResultTitle).text("Search Result"); var searchValue = document.getElementById("productNameTB").value; var searchDropDown = document.getElementById("searchDropDown"); var searchCategory = searchDropDown.options[searchDropDown.selectedIndex].text; if (searchCategory == "All") { searchCategory = '*'; } else { searchCategory = "'" + searchCategory + "'"; } var startCount = document.getElementById("searchStartCount").value; var count = document.getElementById("searchEndCount").value; if (startCount == "" || isNaN(startCount)) { startCount = 1; count = 10; document.getElementById("searchStartCount").innerHTML = startCount; document.getElementById("searchEndCount").innerHTML = count; //document.getElementById("nextBtn").style.display = "block"; } else { // Increment count startCount = startCount + 1; document.getElementById("searchStartCount").innerHTML = startCount; count = count + 10; document.getElementById("searchEndCount").innerHTML = count; document.getElementById("prevBtn").style.display = "block"; //document.getElementById("nextBtn").style.display = "block"; } $.ajax({ 'url': 'http://localhost:8983/solr/4034_IR/select', 'data': {'wt':'json', 'q': "'" + searchValue + "'", 'fq':"category:" + searchCategory, //searchCategory + "'"}, 'start': startCount - 1, 'sort': sortByCondition //'rows': count }, 'success': function(data) { var dataSize = data.response.numFound; if (dataSize > 0) { $(resultsMsg1).text("Displaying"); $(resultsMsg2).text("-"); $(searchString).text(" results for '" + searchValue + "' | Total: " + dataSize + " results (" + data.responseHeader.QTime + "ms)" ); document.getElementById("sortBy").style.display = "block"; //document.getElementById("searchString").value = dataSize + " search results on " + searchValue + " found"; } else { document.getElementById("searchStartCount").style.display = "none"; document.getElementById("searchEndCount").style.display = "none"; document.getElementById("resultsMsg1").style.display = "none"; document.getElementById("resultsMsg2").style.display = "none"; $(searchString).text("No results found"); //document.getElementById("searchString").value = } if (count > dataSize) { count = dataSize; document.getElementById("searchEndCount").innerHTML = count; document.getElementById("prevBtn").style.display = "none"; //document.getElementById("nextBtn").style.display = "none"; } else { document.getElementById("nextBtn").style.display = "block"; } if (document.getElementById("searchString").innerHTML == "No results found") { document.getElementById("prevBtn").style.display = "none"; } if (dataSize == 10) { document.getElementById("nextBtn").style.display = "none"; } if (startCount == 1) { document.getElementById("prevBtn").style.display = "none"; } var i; for (i = 0; i < dataSize; i++) { //alert(data.response.docs[i]); //var $innerFormDiv = document.createElement("FORM"); //$innerFormDiv.setAttribute("name", "showAllReviewForm"); //$innerFormDiv.className = "feature-item"; var $innerReviewDiv = document.createElement("div"); $innerReviewDiv.className = "feature-item"; //$("innerReviewDiv").css({"float": "right", "clear": "left"}); // Product Image var $innerReviewDivProdImg = document.createElement("img"); $innerReviewDivProdImg.setAttribute("src", data.response.docs[i]["image"]); $innerReviewDivProdImg.setAttribute("width", "150"); $innerReviewDivProdImg.setAttribute("height", "200"); $innerReviewDivProdImg.setAttribute("class", "prodImg"); // Product Name var $innerReviewDivProdName = document.createElement("h4"); $innerReviewDivProdName.setAttribute("name", "pdtName"); $innerReviewDivProdName.innerHTML = data.response.docs[i]["name"]; // Product URL var $innerReviewDivProdUrl = document.createElement("a"); $innerReviewDivProdUrl.setAttribute("href", data.response.docs[i]["url"]); $innerReviewDivProdUrl.innerHTML = data.response.docs[i]["url"]; // Product Price var $innerReviewDivProdPrice = document.createElement("p"); $innerReviewDivProdPrice.innerHTML = "Price: $" + data.response.docs[i]["price"]; // Product 5 stars ratings var $innerReviewDivProdRating5 = document.createElement("p"); $innerReviewDivProdRating5.innerHTML = "5 Stars Rating: " + data.response.docs[i]["ratings.5_star"] + "%"; // Product Summary var $innerReviewDivProdSummary = document.createElement("p"); $innerReviewDivProdSummary.innerHTML = "Review Summary: " + data.response.docs[i]["summary"]; $innerReviewDiv.appendChild($innerReviewDivProdImg); $innerReviewDiv.appendChild($innerReviewDivProdName); $innerReviewDiv.appendChild($innerReviewDivProdUrl); $innerReviewDiv.appendChild($innerReviewDivProdPrice); $innerReviewDiv.appendChild($innerReviewDivProdRating5); $innerReviewDiv.appendChild($innerReviewDivProdSummary); document.getElementById("reviewDiv").appendChild($innerReviewDiv); } }, 'dataType': 'jsonp', 'jsonp': 'json.wrf' }); $([document.documentElement, document.body]).animate({ scrollTop: $(".feature-area").offset().top }, 400); });
'use strict'; var app = angular.module('myApp.orders.services', ['ngResource',]); app.factory('Order', ['$resource', '$localStorage', 'API_END_POINT', function($resource, $localStorage, API_END_POINT){ return $resource(API_END_POINT + '/store_orders/:id/:action', { q: '@q', id: '@id' }, { get: { method: 'GET', isArray: false, dataType: 'json', params: { q: '@q', page: '@page', client_mac: '@client_mac' } }, query: { method: 'GET', isArray: false, dataType: 'json', params: { id: '@id' } }, update: { method: 'PATCH', isArray: false, dataType: 'json', params: { id: '@id', store_order: '@store_order' } } }); }]);
// Our collection of restaurants Restaurants = new Meteor.Collection("restaurants"); // Publish complete set of restaurants to all clients Meteor.publish("restaurants", function () { return Restaurants.find({}); });
Router.configure({ loadingTemplate: 'loading', notFoundTemplate: 'notFound', layoutTemplate: 'layout' }); Router.map(function() { this.route('index', { path: '/', template: 'index', waitOn:function(){ Session.set("ClassifierResult",undefined); return Meteor.subscribe("AllVideos"); }, action: function() { if(this.ready()) { this.render(); //render your templates as normal when data in onWait is ready } else { console.log("loading!"); this.render('loading'); } } }), this.route('classifier', { path: '/demos/classifier', template: 'classifier', waitOn:function(){ Session.set("ClassifierResult",undefined); }, action: function() { if(this.ready()) { this.render(); //render your templates as normal when data in onWait is ready } else { console.log("loading!"); this.render('loading'); } } }), this.route('videos', { path: '/video/analytics/:id', template: 'video', waitOn:function(){ return Meteor.subscribe('SingleVideo',this.params.id); }, data:function(){ if(this.ready()){ return Videos.findOne({'videoID':this.params.id});} }, action: function() { if(this.ready()) { this.render(); //render your templates as normal when data in onWait is ready } else { console.log("loading!"); this.render('loading'); } } }) }); Router.route('/word2vec', function () { this.render('word2vec'); });
//<![CDATA[ // Public constants var monthlist = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; window.onload = function() { var greeting = getTodaysDate() + ' - ' + getGreeting() + "!"; $('#dateHeading').text(greeting); setCurrentQuarter(); } function getTodaysDate() { var today = new Date(); var day = today.getDay(); var daylist = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]; var minutes = today.getMinutes(); minutes = (minutes < 10) ? '0' + minutes : minutes; return daylist[day] + ' ' + today.getDate() + ' ' + monthlist[today.getMonth()] + ' ' + today.getFullYear() + ' - ' + today.getHours() + ':' + minutes; } function getGreeting(){ var data = [ [0, 4, "Good Night"], [5, 11, "Good Morning"], [12, 16, "Good Afternoon"], [17, 20, "Good Evening"], [21, 23, "Good Night"] ], hr = new Date().getHours(); for(var i = 0; i < data.length; i++){ if(hr >= data[i][0] && hr <= data[i][1]){ return (data[i][2]); } } } function setCurrentQuarter() { var currentQuarter = $("#currentQuarterId").val(); var today = new Date(); var year = today.getFullYear(); var startMonth = 0; var endMonth = 2; if (currentQuarter == 2) { startMonth = 3; endMonth = 5; } else if (currentQuarter == 3) { startMonth = 6; endMonth = 8; } else if (currentQuarter == 4) { startMonth = 9; endMonth = 11; } var month = new Array(3); var pos = 0; for (i = startMonth; i <= endMonth; i++) { month[pos] = monthlist[i] + ' ' + year; pos++; } for (i = 0; i < 3; i++) { $("#month" + i).val(month[i]); } } //]]>
export const dateFormat = (date_str)=>{ const t = new Date(date_str) if(isNaN(t.getFullYear())){ return "timeErr" } return t.getFullYear() + "-" + (parseInt(t.getMonth().toString())+1) + "-" + t.getDate() + " " + t.getHours() + ":" + t.getMinutes() + ":" + t.getSeconds() }
export { default as OrderBookScreen } from './OrderBookScreen';
import React, { useContext, useEffect, useState } from "react" import { LotContext } from "../lot/LotProvider" import "./Lot.css" import { useHistory, useParams } from 'react-router-dom'; import { Button } from 'reactstrap'; export const LotForm = () => { const { addLot, getLotById, updateLot } = useContext(LotContext) //for edit, hold on to state of Vehicle in this view const [lot, setLot] = useState({}) //wait for data before button is active /* const [isLoading, setIsLoading] = useState(true); */ const {lotId} = useParams(); const history = useHistory(); //when field changes, update state. This causes a re-render and updates the view. //Controlled component const handleControlledInputChange = (event) => { //When changing a state object or array, //always create a copy make changes, and then set state. const newLot = { ...lot } //Lot is an object with properties. //set the property to the new value newLot[event.target.name] = event.target.value //update state setLot(newLot) } const handleSaveLot = () => { const user = localStorage.getItem("PF_token") //disable the button - no extra clicks if (lotId){ //PUT - update updateLot({ id: lot.id, super: parseInt(user), lotSize: lot.lotSize, lotNumber: lot.lotNumber, }) .then(() => history.push(`/lots/${lot.id}`)) }else { //POST - add addLot({ super: parseInt(user), lotSize: lot.lotSize, lotNumber: lot.lotNumber, }) .then(() => history.push("/lots")) } } // Get customers and locations. If lotId is in the URL, getLotById useEffect(() => { if (lotId) { getLotById(lotId) .then(lot => { setLot(lot) }) } }, [])// this array is empty is because the lot doesnt exist yet // the empty array on the useEffect runs on page load. If there is nothing to watch, then it just runs the function inside it. //since state controlls this component, we no longer need //useRef(null) or ref return ( <form className="lotForm"> <h2 className="lotForm__title">{lotId ? <>Edit Lot</> : <>New Lot</>}</h2> <fieldset> <div className="form-group"> <label htmlFor="lotNumber">lot Number:</label> <input type="text" id="lotNumber" name="lotNumber" required autoFocus className="form-control" placeholder="lot Number" value={lot.lotNumber} onChange={handleControlledInputChange} value={lot.lotNumber} /> </div> </fieldset> <fieldset> <div className="form-group"> <label htmlFor="lotSize">lot Size:</label> <input type="text" id="lotSize" name="lotSize" required autoFocus className="form-control" placeholder="lot Size" value={lot.lotSize} onChange={handleControlledInputChange} value={lot.lotSize} /> </div> </fieldset> <div className="lotSaveButton"> <Button className="lotSaveButton" onClick={event => { event.preventDefault() // Prevent browser from submitting the form and refreshing the page handleSaveLot() }}> {lotId ? <>Save lot</> : <>Add lot</>}</Button> </div> </form> ) }
import React,{Component} from 'react' import $ from 'jquery' import QAcard from './QAcard' import OldQAcard from './OldQAcard' import ImgModal from './ImgModal' import {sendEvent} from '.././../funStore/CommonFun' // import KWcard from './KWcard' // const msg = { // title:'ๅฎๅฎๅ‘็ƒงๆ€ŽไนˆๅŠž๏ผŸๅฎๅฎๅ‘็ƒงๆ€ŽไนˆๅŠž๏ผŸๅฎๅฎๅ‘็ƒงๆ€ŽไนˆๅŠž๏ผŸๅฎๅฎๅ‘็ƒงๆ€ŽไนˆๅŠž๏ผŸๅฎๅฎๅ‘็ƒงๆ€ŽไนˆๅŠž๏ผŸๅฎๅฎๅ‘็ƒงๆ€ŽไนˆๅŠž๏ผŸ', // text:'ๅฎๅฆˆ่ฏทๅˆซ็€ๆ€ฅ๏ผŒๅฎๅฎ็Žฐๅœจๅ‡ ๅฒไบ†๏ผŸๅฎๅฆˆ่ฏทๅˆซ็€ๆ€ฅ๏ผŒๅฎๅฎ็Žฐๅœจๅ‡ ๅฒไบ†๏ผŸๅฎๅฆˆ่ฏทๅˆซ็€ๆ€ฅ๏ผŒๅฎๅฎ็Žฐๅœจๅ‡ ๅฒไบ†๏ผŸๅฎๅฆˆ่ฏทๅˆซ็€ๆ€ฅ๏ผŒๅฎๅฎ็Žฐๅœจๅ‡ ๅฒไบ†๏ผŸ' // } const LoadingAnimation = () => { return( <div className="loadingBox"> <div className="loadingGif"> <img src={`${process.env.PUBLIC_URL}/images/icon/loading.svg`} alt=""/> </div> <div className="loadingText">ๅŠ ่ฝฝไธญ...</div> </div> ) } class KnowledgeBase extends Component { constructor(props){ super(props) this.state={ loading: false, imgModalFlag: false } this.msgFreshCallBack = this.msgFreshCallBack.bind(this) } componentDidMount(){ this.props.hotTipIcon&&this.props.cwList.itemList.length==0&&this.props.initKW() } msgFreshCallBack () { this.setState({ loading: false }) // this.refs.fresh.style.display = 'none'; $('.fresh').css('display','none') this.refs.rightBox&&(this.refs.rightBox.scrollTop = this.refs.rightBox.scrollTop-50) } setStateAsync(state) { return new Promise((resolve) => { this.setState(state, resolve) }); } // scrollHandle () { // let {rightBox,fresh} = this.refs; // let scrollTop = rightBox.scrollTop; // let scrollHeight = rightBox.scrollHeight; // let clientHeight = rightBox.offsetHeight; // if(!this.state.loading){ // if(scrollTop==scrollHeight-clientHeight){ // // ไธŠๆ‹‰ๅˆทๆ–ฐ... // // console.log('่ฏทๆฑ‚ๆ•ฐๆฎๅ•ฆ') // this.setStateAsync({ // loading: true // }) // .then((resolve)=>{ // // console.log(this.state.loading) // fresh.style.display = 'block' // // $('.fresh').css('display','block') // this.props.scrollEvent(this.msgFreshCallBack) // }) // } // } // } showImgModal = (url) =>{ this.setState({ imgUrl: url, imgModalFlag: true }) } hideImgModal = () =>{ this.setState({ imgModalFlag: false }) } sendBefore(){ const immemId = this.props.userInfo.info.immemId const groupList = this.props.groupList const chatGroupId = this.props.groupList.chatGroupId const groupCode = this.props.groupList.targetGroup.code const memberList = this.props.memberList const chatMemberId = this.props.memberList.chatMemberId const selectRoomType = this.props.selectRoomType const atAll = memberList.altAll let groups = '' if(chatGroupId==''){ // ็พคๅ‘็š„ๆถˆๆฏ groups = groupList.listData.map(item => item.altSelected === true ? {groupCode:item.code,atAll:atAll,users:[],sendId:item.robotGroupMemList[0]?item.robotGroupMemList[0].robotCode:''}:'' ) groups = groups.filter(item => item!= '') }else { let users = memberList.listData.map(item => item.altSelected === true ? item.memCode:'') users = users.filter(item => item!= '') if(selectRoomType=='MEMBER'&&chatMemberId!=''){ // @ๆŸไธชไบบ็š„ groups = [{groupCode:groupCode,atAll:false,users:[chatMemberId],sendId:groupList.targetGroup.robotGroupMemList[0]?groupList.targetGroup.robotGroupMemList[0].robotCode:''}] }else { // @ๅคšไบบ ๆญฃๅธธ็พค่Š groups = [{groupCode:groupCode,atAll:atAll,users:users,sendId:groupList.targetGroup.robotGroupMemList[0]?groupList.targetGroup.robotGroupMemList[0].robotCode:''}] } } return groups!= '' ? {imMemId:immemId,groups:groups} : '' } sendHandle = () => { const {imgUrl} = this.state const socket = this.props.socket.state.socket const beforeData = this.sendBefore() if(beforeData!=''){ sendEvent('message', {txt: 'ๅ›พ็‰‡ๆญฃๅœจๅ‘้€ไธญ๏ผŒ่ฏท็จๅ€™~', code: 1000}) const result = Object.assign({},beforeData,{msgType:'photo',content:imgUrl}) socket.send(JSON.stringify({command:252,frame:1,data:result})) } } render () { const {imgModalFlag,imgUrl} = this.state let {loadingText,cwList,hotTip,hotTipIcon,groupList,userInfo,memberList,selectRoomType,socket}=this.props; // console.log(cwList) return ( <div ref='rightBox' className='gm-kmBaseWrapper'> <div className='kwBaseBox'> {cwList.itemList&&cwList.itemList.map((item)=> { return ( item.origin_type ?<OldQAcard question={item.problem} answers={item.answer} groupList={groupList} questionTxt={cwList.searchKey}/> :<QAcard key={item.id} item={item} questionTxt={cwList.searchKey} showImgModal={this.showImgModal}/> ) })} { hotTipIcon ?cwList.itemList.length==0? <div className="emptyBase"> <div className="sit"></div> <p>ๆœ็ดข้—ฎ้ข˜๏ผŒ่Žทๅพ—ๆƒๅจ็ญ”ๆกˆๅง~</p> </div>:null : cwList.itemList.length!=0? <div className='fresh' ref='fresh' style={{display:'none',padding:'10px 0',textAlign:'center',fontSize:'26px'}}> <LoadingAnimation loadingText={loadingText}/> </div> : <div className="emptyBase"> <div className="none"></div> <p>ๆฒกๆœ‰ๆ‰พๅˆฐ็ญ”ๆกˆๅ“ฆ~</p> </div> } </div> {imgModalFlag?<ImgModal src={imgUrl} closeClickHandle={this.hideImgModal} canSend={true} sendHandle={this.sendHandle} />:''} </div> ) } } export default KnowledgeBase
import { combineReducers } from 'redux'; import { routerReducer as routing } from 'react-router-redux'; import tasks from './tasks'; import user from './user'; // import flashMessage from './flashMessage'; export default combineReducers({ user, tasks // flashMessage, // routing });
// setup server // YOUR CODE var express = require('express') var app = express() var low = require('lowdb'); var fs = require('lowdb/adapters/FileSync'); var adapter = new fs('db.json'); var db = low(adapter); var cors = require('cors'); app.use(cors()); app.use(express.static('public')) app.get('/', function(req, res){ res.send('Hello World!') }) app.listen(3000, function(){ console.log("Running on port 3000") }) app.use(express.static('public')) db.defaults({ accounts: []}).write(); // setup directory used to serve static files // YOUR CODE // setup data store // YOUR CODE // required data store structure // YOUR CODE /* { accounts:[ {name : '', email : '', balance : 0, password : '', transactions: []} ] } */ app.get('/account/create/:name/:email/:password', function (req, res) { // YOUR CODE // Create account route // return success or failure string var account = { "name": req.params.name, "email": req.params.email, "balance" : 0, "password" : req.params.password, "transactions": [] } db.get('accounts').push(account).write(); console.log("Account created for the account ", account) res.send(account) }); app.get('/account/login/:email/:password', function (req, res) { // YOUR CODE // Login user - confirm credentials // If success, return account object // If fail, return null var email = req.params.email var password = req.params.password var account = db.get('accounts').find({email: email}).value() if(account.password==password){ console.log("User logged in ", account) res.send(account) }else{ console.log("Incorrect password ", password); res.status(404).send({"message": "Invalid credentials"}) } }); app.get('/account/get/:email', function (req, res) { // YOUR CODE // Return account based on email var email = req.params.email console.log("Get account for ", email) var account = db.get('accounts').find({email: email}).value() if(!account){ res.status(404).send({"message": "No account found under this email"}) } res.send(account) }); app.get('/account/deposit/:email/:amount', function (req, res) { // YOUR CODE // Deposit amount for email // return success or failure string var email = req.params.email var amount = Number(req.params.amount) console.log("Deposit on account ", email, "for ", amount) var account = db.get('accounts').find({email: email}).value() if(!account){ console.log("No account found for ", email) res.status(404).send({"message": "No account found under this email"}) } account.balance += amount var audit = { 'type': 'deposit', 'amount': amount, 'balance': account.balance } account.transactions.push(audit) console.log("Updating the balance to ", account.balance) account = db.get('accounts').find({email: email}).assign(account).write() res.send(account) }); app.get('/account/withdraw/:email/:amount', function (req, res) { // YOUR CODE // Withdraw amount for email // return success or failure string var email = req.params.email var amount = Number(req.params.amount) console.log("Withdraw on account ", email, "for ", amount) var account = db.get('accounts').find({email: email}).value() if(!account){ res.status(404).send({"message": "No account found under this email"}) } if(amount>account.balance){ console.log("Not enough balance", account.balance) res.status(405).send({"message": "Not enough money in the account. Please try lower amounts"}) }else{ account.balance -= amount console.log("Updating the balance to ", account.balance) var audit = { 'type': 'withdraw', 'amount': amount, 'balance': account.balance } account.transactions.push(audit) account = db.get('accounts').find({email: email}).assign(account).write() res.send(account) } }); app.get('/account/transactions/:email', function (req, res) { // YOUR CODE // Return all transactions for account var email = req.params.email var account = db.get('accounts').find({email: email}).value() if(!account){ console.log("No account found for ", email) res.status(404).send({"message": "No account found under this email"}) }else{ console.log("Sending all transactions for ", email) res.send(account.transactions) } }); app.get('/account/balance/:email', function (req, res) { // YOUR CODE // Return account based on email var email = req.params.email console.log("Get account for ", email) var account = db.get('accounts').find({email: email}).value() if(!account){ console.log("No account found for ", email) res.status(404).send({"message": "No account found under this email"}) } console.log("Sending balance ", JSON.stringify(account.balance)) res.send({'balance': Number(account.balance)}) }); app.get('/account/all', function (req, res) { // YOUR CODE // Return data for all accounts var accounts = db.get('accounts').value() console.log("Sending all accounts information", accounts) res.send(accounts) });
$('document').ready(function(){ var klowdEPG = { // Active station will be pulled from URL possibly activeStation: "23321", // Stations the user is subscribed to userStations: [89093,78763,62628,33691,90880], apikey: "umstwy76p8shpfkxhugr6a2v", baseUrl: "http://data.tmsapi.com/v1/lineups/USA-VA70448-DEFAULT/grid", zipcode: "20002", // Use klowdjs to determine how many hours to show findEPGSize: function() { breakpoint = klowdjs.breakpoints.getBreakpoint(); if (breakpoint > 768) { epgHours = 2; epgMinutes = 30; } else if (breakpoint > 560) { epgHours = 1; epgMinutes = 30; } else { epgHours = 1; epgMinutes = 0; } return { hours: epgHours, minutes: epgMinutes }; }, // Convert the js Date object to a format acceptable by gracenote findCorrectISOTime: function(date){ date = date.toISOString().substr(0,16); if (parseInt(date.substr(14,2)) >= 30 ){ return date.substring(0, 14) + "30Z" } else { return date.substring(0, 14) + "00Z" } }, // Determine if an item is in an array (used to determine whether channels are available to usrs or not, returning true or false) inArray: function(value, array){ contains = false; for(var i = 0; i < array.length; i++){ if(array[i] == value){ contains = true; } } return contains; }, // Determine difference in minutes between two times (used to determine how many minutes is left in a show) findTimeDifference: function(startHour, startMin, currentHour, currentMin){ if(startHour > currentHour){ diff = (24 - startHour + currentHour) diff = diff * 60 + currentMin - startMin; } else { diff = (currentHour - startHour); diff = diff * 60 + currentMin - startMin; } return diff; }, // If gracenote does not have a field such as short description for a particular show, replace it with an empty string isUndefined: function(string){ if(string){ return string; } else{ return ''; } }, // Actually create the elements that are added to the EPG fillEPG: function(data, today, hours, minutes){ console.log(data); // Parse through the data provided by gracenote for(var j = 0; j < data.length; j++){ // Check to see if we are in mobile view or not if (klowdjs.breakpoints.getBreakpoint() < 768){ var row = "<div class='grid grid-pad'><div class='col-2-12'><div class='content station'><div class='width-25-percent inline-block'><img src='https://www.klowdtv.com/klowd/images/channels/" + data[j]["callSign"].toLowerCase() + "/logo_small.png' class=' inline-block' /></div><div class='stationInfo inline-block text-align-center'></div></div></div><div class='col-10-12'><div class='content'><ul class='programs inactive' channel-id='" + data[j]["stationId"] + "'></ul></div></div></div>" } else { var row = "<div class='grid grid-pad'><div class='col-2-12'><div class='content'><div class='inline-block image-container width-100-percent'><img src='https://www.klowdtv.com/klowd/images/channels/" + data[j]["callSign"].toLowerCase() + "/logo_small.png' /></div></div></div><div class='col-10-12'><div class='content'><ul class='programs inactive' channel-id='" + data[j]["stationId"] + "'></ul></div></div></div>" } // Add the row to the table $('#programGuide').append(row); // Highlight the channel if it's what we're currently watching if (this.activeStation === data[j]["stationId"]){ $('.programs').eq(j).addClass('active'); } // Remove the inactive coloring for stations if (this.inArray(data[j]["stationId"].toString(), this.userStations)){ $('.programs').eq(j).removeClass('inactive'); } var airings = data[j]["airings"]; // Find the amount of minutes being displayed var durationLeft = (hours * 60) + minutes; for(var i = 0; i < airings.length; i++){ // Find how much time is left of current program by subtracting the difference between start time and current time if(i === 0){ airings[i]["duration"] -= this.findTimeDifference(parseInt(airings[i]["startTime"].substr(11,2)), parseInt(airings[i]["startTime"].substr(14,2)), parseInt(today.substr(11,2)), parseInt(today.substr(14,2))); } // Make sure that there's time left in the epg row if(durationLeft > 0){ var program = airings[i]; if (durationLeft - program["duration"] < 0) { program["duration"] = durationLeft; } // Handle universal attributes here, and desktop specific in if statement // Replace all double quotes so that we don't break out of the title attribute var episodeTitle = this.isUndefined(program["program"]["episodeTitle"]).replace(/"/g,"'"); if(klowdjs.breakpoints.getBreakpoint() < 768){ if(data[j]["stationId"].toString() === this.activeStation){ var button = ""; } else if(this.inArray(data[j]["stationId"].toString(), this.userStations)){ button = "<a href='https://klowdtv.com/myKlowd/watchMyKlowd.ktv?watch=" + data[j]["callSign"].toLowerCase() + "'><button class='change-channel inline-block vertical-align-top' channel-id='" + data[j]["stationId"] + "'>Switch to Channel</button></a>"; } else { button = "<a href='https://klowdtv.com/myKlowd/editSubscription.ktv'><button class='inline-block vertical-align-top' channel-id='" + data[j]["stationId"] + "'>Purchase Channel</button></a>"; } } else{ // Link to channel if you have the channel if(data[j]["stationId"].toString() === this.activeStation){ var button = ""; } else if(this.inArray(data[j]["stationId"].toString(), this.userStations)){ button = "&lt;a href=&quot;https://klowdtv.com/myKlowd/watchMyKlowd.ktv?watch=" + data[j]["callSign"].toLowerCase() + "&quot;&gt;&lt;button class=&quot;change-channel&quot; channel-id=&quot;" + data[j]["stationId"] + "&quot; &gt; Switch to Channel &lt;/button&gt;&lt;/a&gt;"; } // Link to purchase the channel if you do not else { button = "&lt;a href=&quot;https://klowdtv.com/myKlowd/editSubscription.ktv&quot;&gt;&lt;button class=&quot;purchase&quot; channel-id=&quot;" + data[j]["stationId"] + "&quot; &gt; Purchase Channel &lt;/button&gt;&lt;/a&gt;"; } } // Need to figure out how to avoid blank spaces where an element that isn't large enough to be displayed if (program["duration"] < 2) { program["duration"] = 0; } if(program["duration"] > 0){ // Skip steps if mobile view if (klowdjs.breakpoints.getBreakpoint() < 768){ if(i === 0){ if(episodeTitle != ''){ episodeTitle = ": " + episodeTitle; } $('.stationInfo').eq(j).html("<h3>" + program["program"]["title"] + episodeTitle + "</h3>"); $('.station').eq(j).append(button); } $('.programs').eq(j).append("<li class='centered-text-li'>"+ program["program"]["title"] +"</li>"); } else { var shortDescription = this.isUndefined(program["program"]["shortDescription"]).replace(/"/g,"'"); // If top cast is provided by gracenote, created a ul with each actor as an li var cast = ""; if (program["program"]["topCast"]){ cast += "&lt;ul&gt;" for (var actor = 0; actor < program["program"]["topCast"].length; actor++){ cast += "&lt;li&gt;" + program["program"]["topCast"][actor] + "&lt;/li&gt;" } cast += "&lt;/ul&gt;" } console.log('In media query'); // Append a li for the program, combining all of the information we have into the tooltip $('.programs').eq(j).append("<li class='tooltip centered-text-li' title=\"&lt;h2&gt;" + (program["program"]["title"]) + "&lt;/h2&gt; &lt;h3&gt;" + episodeTitle + "&lt;/h3&gt; &lt;p&gt;" + shortDescription + " &lt;/p&gt; &lt;/br&gt; " + cast + button + "\" class='tooltip'>" + program["program"]["title"] + "</li>"); } currentProgram = $('.programs li').last(); // Determine how large li will be based on how wide the timeline is are if (hours === 2) { minuteDiff = (((program["duration"]) / 30 ) * 20 - 1); } else if (minutes === 30){ minuteDiff = (((program["duration"]) / 30 ) * 33.33 - 1)} else { minuteDiff = (((program["duration"]) / 30 ) * 50 - 1); } if(minuteDiff > 100){ minuteDiff = "99%"; } else{ minuteDiff = minuteDiff + "%"; } currentProgram.width(minuteDiff); durationLeft -= program["duration"]; } } // If we're out of time in the display, break out of the for loop else { break; } } } }, // Move forward in time by making api call and resetting the EPG addTimeBlock: function(time, hours, minutes){ time = new Date(time); time = new Date(time.setHours(time.getHours() + hours)); time = new Date(time.setMinutes(time.getMinutes() + minutes)); $('.date').text(time.toString().substr(0,15)); return this.findCorrectISOTime(time); }, // Move backward in time by making api call and resetting the EPG removeTimeBlock: function(time, hours, minutes){ time = new Date(time); time = new Date(time.setHours(time.getHours() - hours)); time = new Date(time.setMinutes(time.getMinutes() - minutes)); $('.date').text(time.toString().substr(0,15)); return this.findCorrectISOTime(time); }, // Stylize times getHoursMinutes: function(hours, minutes){ var meridiem = "AM"; if (hours > 12){ hours -= 12; meridiem = "PM"; } else if(hours == 00){ hours = 12; } if (minutes >= 30){ minutes = ":30"; } else { minutes = ":00"; } return hours + minutes + meridiem; }, // Place time blocks into the timebar setTimeBar: function(today, hours, minutes){ // Determine how many 30 minute blocks to create var length = (hours * 2); if (minutes > 0){ length += 1; } for (var i = 0; i < length; i++){ var date = new Date(new Date(today).getTime() + ((i) * 30)*60000); var hours = date.getHours(); var minutes = date.getMinutes(); $('#time').append('<li class="half-hour"><p class="pushed-to-bottom">' + this.getHoursMinutes(hours, minutes) + '</p></li>'); } // Determine size based on thirty min blocks if (length === 5){ $('.half-hour').width('20%'); } else if (length === 3){ $('.half-hour').width('33.33%'); } else { $('.half-hour').width('50%'); } }, // On initialization init: function(){ epg = this; // Change the text of the date object to todays date $('.date').text(new Date().toString().substr(0,15)); // Figure out the time right now time = this.findCorrectISOTime(new Date()); // Find EPG size in terms of hours and minutes displayed hoursMins = this.findEPGSize(); // Set the EPG using the current time and the hours and minutes being displayed as arguments this.setEPG(time, hoursMins["hours"], hoursMins["minutes"]); // Use Fetching data to prevent users from spamming the button while it's running // Any function that talks with the API requires fetchingData to be false, and sets it true when it starts // At the end of the function, after a certain amount of time, it sets fetchingData to false var fetchingData = false; // Add the functionality to the next and previous button $('#next').on('click', function(){ if(fetchingData != true){ fetchingData = true; // Empty the EPG of its current contents $('#programGuide').empty(); // Remove the half hours from the timebar $('.half-hour').remove(); // Figure out how large the epg's scope is based off of screen size hoursMins = epg.findEPGSize(); // Find new time by adding time to current time time = epg.addTimeBlock(time, hoursMins["hours"], hoursMins["minutes"]); // Run the setEPG method again with the new time, and total hours and minutes being displayed as arguments epg.setEPG(time, hoursMins["hours"], hoursMins["minutes"]); setTimeout(function(){ fetchingData = false; }, 1000); } }); $('#previous').on('click', function(){ if(fetchingData != true){ fetchingData = true; // Empty the EPG of its current contents $('#programGuide').empty(); // Remove the half hours from the timebar $('.half-hour').remove(); // Figure out how large the epg's scope is based off of the screen size hoursMins = epg.findEPGSize(); // Find new time by removing time to current time time = epg.removeTimeBlock(time, hoursMins["hours"], hoursMins["minutes"]); // Run the setEPG method again with the new time, and total hours and minutes being displayed as arguments epg.setEPG(time, hoursMins["hours"], hoursMins["minutes"]); setTimeout(function(){ fetchingData = false; }, 1000); } }); // If window resizes, make sure to refresh the EPG to the new size $(window).resize(function(){ if(fetchingData != true){ fetchingData = true; setTimeout(function(){ // Empty the EPG of its current contents $('#programGuide').empty(); // Remove the half hours from the timebar $('.half-hour').remove(); console.log('resize'); hoursMins = epg.findEPGSize(); epg.setEPG(time, hoursMins["hours"], hoursMins["minutes"]); fetchingData = false; }, 1000); } }) }, setEPG: function(time, hours, minutes){ // Set 'this' as a variable so I can access it in the ajax var epg = this; // Determine ISO 8601 in Zulu time (What Gracenote Uses) epg.setTimeBar(time, hours, minutes); // If you're looking at the current time, you can't go back, so remove the previous button if (time === epg.findCorrectISOTime(new Date())){ $('#previous').hide(); } else { $('#previous').show(); } // Send request to gracenote $.ajax({ url: epg.baseUrl, data: { startDateTime: time, api_key: epg.apikey, }, }) .done(function(data){ // Fill the EPG with the data we just pulled epg.fillEPG(data, time, hours, minutes); // Initialize tooltipster for the clickable information if screen is mobile // Documentation for tooltipster: http://iamceege.github.io/tooltipster/ if(klowdjs.breakpoints.getBreakpoint() > 768){ $('.tooltip').tooltipster({ trigger: 'click', contentAsHTML: true, interactive: true, }); } }); }, } klowdEPG.init(); });
import React from 'react'; import classes from './MyPosts.module.css'; import Post from './Post/Post'; const MyPosts = () => { const postData = [ {id: '1', post: 'Hi, how are you?', likes: 20}, {id: '2', post: "It's my first post", likes: 30} ]; return( <div className={classes.content}> <div> <h3>my posts</h3> <div> <textarea name="" id="" cols="30" rows="10"></textarea> <div> <button>Add post</button> </div> </div> <div className={classes.posts}> <Post message={postData[0].post} likes={postData[0].likes} /> <Post message={postData[1].post} likes={postData[1].likes} /> </div> </div> </div> ) } export default MyPosts;
import { Router } from "express"; import multer from "multer"; import multerConfig from "../../../config/multer"; import authenticateMiddleware from "../../../shared/middlewares/authenticateMiddleware"; class AvatarRouter { static configure(avatarController) { const route = Router(); route.post( "/files", multer(multerConfig).single("file"), authenticateMiddleware, avatarController.uploadAvatar ); return route; } } export default AvatarRouter;
import styled from 'styled-components'; export const Container = styled.div` width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; ` export const InputLine = styled.div` width: 60%; height: 5%; margin-top: 1%; ` export const InfoDiv = styled.div` width: 25%; height: 100%; float: left; ` export const Info = styled.p` text-align: right; font-size: 2vw; ` export const InputBox = styled.input` width: 70%; height: 100%; padding-top: 2%; padding-bottom: 2%; margin-top: 3.4%; margin-left: 1%; border: 1px solid; ` export const InputEmail = styled.input.attrs({ type: "email", checked: true })` width: 53%; height: 100%; padding-top: 2%; padding-bottom: 2%; margin-top: 3.4%; margin-left: 1%; border: 1px solid; ` export const InputError = styled.p` font-size: 1vw; color: red; margin: 0 27% 0 0; ` export const InputEmailInfo = styled.p` font-size: 1vw; color: greenyellow; margin: 0 27% 0 0; ` export const InputPassword = styled.input.attrs({ type: 'password', checked: true })` width: 70%; height: 100%; padding-top: 2%; padding-bottom: 2%; margin-top: 3.4%; margin-left: 1%; border: 1px solid; ` export const CheckButton = styled.button` width: 15%; height: 100%; border: none; border-radius: 50px; padding: 2%; margin: 2%; color: rgba(0, 0, 200); background-color: rgba(187, 215, 240); ` export const SubmitButton = styled.button.attrs({ type: 'submit' })` width: 30%; padding: 1%; font-size: 1.3vw; color: white; background-color: rgba(0, 0, 200); border: none; border-radius: 50px; margin: 1%; left: 31%; `
import React, { Component } from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' const Container = styled.div` display: flex; flex-direction: column; box-sizing: border-box; width: 310px; height: 180px; border-radius: 10px; background-image: url(${props => props.bg}); background-size: cover; position: relative; padding: 23px 30px; ` const Title = styled.div` font-family: 'ThaiSans Neue'; font-style: normal; font-weight: bold; font-size: 22px; line-height: 18px; color: #fff; ` const Value = styled.div` font-family: 'ThaiSans Neue'; font-style: normal; font-weight: 800; font-size: 55px; line-height: 70px; color: #fff; ` const Icon = styled.div` width: 82px; height: 82px; background-image: url(${props => props.icon}); background-size: cover; position: absolute; top: 49px; right: 23px; ` class Card extends Component { render() { return ( <Container bg={this.props.bg}> <Title>{this.props.title}</Title> <Value>{this.props.value}</Value> <Icon icon={this.props.icon} /> </Container> ) } } Card.propTypes = { bg: PropTypes.any, icon: PropTypes.any, title: PropTypes.string, value: PropTypes.number, } export default Card
module.exports = { DONE : 'DONE', UNDONE : 'UNDONE' };
import { renderComponent, expect } from '../../test_helper'; import Sidebar from '../../../public/components/navigation/sidebar'; describe('#dashboard-nav: NavigationBar (Component, sidebar.js)', () => { let component; beforeEach(() => { const props = { items: [ { text: "Drag & Drop", icon: "fa fa-th", path: "/design-board" }]}; component = renderComponent(Sidebar, props); }); it('has the correct class .side-bar', () => { expect(component).to.have.class('side-bar'); }); it('contains navigation elements', () => { expect(component.find('li').length).to.equal(1); }); });
let date = new Date(2015, 0, 2) console.log(date) function getWeekDay(date) { let weekDay = [ 'ะ’ะก', 'ะŸะ', 'ะ’ะข', 'ะกะ ', 'ะงะข', 'ะŸะข', 'ะกะ‘' ] return weekDay[date.getDay()] } function getLocalyDay(date) { let localyDay = date.getDay() if (localyDay == 0) { localyDay = 7 } return localyDay; } function getDayAgo(date, days) { let dateAgo = new Date(date) dateAgo.setDate(date.getDate() - days) return dateAgo.getDate() } function getLastDayOfMonth(year, month) { let date = new Date(year, month, 0) return date.getDate() } function getSecondsToday() { const today = new Date() return today.getHours() * 3600 + today.getMinutes() * 60 + today.getSeconds() } function getSecondsToTomorrow() { const now = new Date() const totalSeondsInADay = 86400 return totalSeondsInADay - (now.getHours() * 60 + now.getMinutes()) * 60 + now.getSeconds() } function formatDate(date) { const diff = new Date() - date if (diff < 1000) { return 'ะŸั€ัะผะพ ัะตะนั‡ะฐั' } let sec = Math.floor(diff / 1000) if (sec < 60) { return sec + ' ัะตะบ ะฝะฐะทะฐะด' } let min = Math.floor(diff / 60000) if (min < 60) { return min + ' ะผะธะฝ ะฝะฐะทะฐะด' } let d = date d = [ '0' + d.getDate(), '0' + (d.getMonth() + 1), '' + d.getFullYear(), '0' + d.getHours(), '0' + d.getMinutes() ].map(component => component.slice(-2)) return d.slice(0, 3).join('.') + ' ' + d.slice(3).join(':') } console.log(getLocalyDay(date)) console.log(getWeekDay(date)) console.log(getDayAgo(date, 3)) console.log(getLastDayOfMonth(2013, 2)) console.log(getSecondsToday()) console.log(getSecondsToTomorrow()) console.log(formatDate(new Date(new Date - 1))) console.log(formatDate(new Date(new Date - 2 * 1000))) console.log(formatDate(new Date(new Date - 5 * 60 * 1000))) console.log(formatDate(new Date(new Date - 86400 * 1000)))
var mongodb = require('./MongodDbUtil'); var ObjectID = mongodb.ObjectID; module.exports.create = function(data, collectionName, callback){ var db = mongodb.getDb(); var collection = db.collection(collectionName); collection.insert(data, function(err, res){ if(err){ callback(err, null); } else{ callback(null, res); } }); } module.exports.getById = function(id, collectionName, callback){ var db = mongodb.getDb(); var collection = db.collection(collectionName); var query = {_id: ObjectID(id)}; collection.find(query).limit(1).toArray(function(err, res){ if(err){ callback(err, null); } else{ callback(null, res); } }); } module.exports.getByQuery = function(query, collectionName, callback){ var db = mongodb.getDb(); var collection = db.collection(collectionName); collection.find(query).toArray(function(err, res){ if(err){ callback(err, null); } else{ callback(null, res); } }); } module.exports.find = function(collectionName, callback){ var db = mongodb.getDb(); var collection = db.collection(collectionName); collection.find().toArray(function(err, res){ if(err){ callback(err, null); } else{ callback(null, res); } }); } module.exports.updateById = function(id, record, collectionName, callback){ var db = mongodb.getDb(); var collection = db.collection(collectionName); collection.updateOne({_id: ObjectID(id)}, { $set: record }, function(err, res){ if(err){ callback(err, null); } else{ callback(null, res); } }); } module.exports.removeProductById = function(id, collectionName, callback){ var db = mongodb.getDb(); var collection = db.collection(collectionName); var query = {_id: ObjectID(id)}; collection.remove(query, function(err, res){ if(err){ callback(err, null); } else{ callback(null, res); } }); }
const fs = require("fs") const userinfo = require("./json/userinfo.json") module.exports.getArgs = (args) => { delete args[0] args = args.join(" ") args = args.split("") delete args[0] return args = args.join("") } module.exports.countLines = (filePath) => { // function copied from https://stackoverflow.com/questions/12453057/node-js-count-the-number-of-lines-in-a-file var contents = fs.readFileSync(filePath) return contents.toString().split('\n').length - 1 }; module.exports.countFileSize = (filePath) => { // returns in KB return fs.statSync(filePath).size/1000 } module.exports.messageGreg = (client, content) => { client.users.cache.get("257482333278437377").send(content) } module.exports.registerUser = (id) => { if(userinfo[id].balances) return userinfo[id] = {} userinfo[id].balances = {} }
//Use this script to generate your character function Person(race, item) { this.race = race; this.item = item; this.currenthealth = 100; this.maxHealth = 100; this.min = 3; this.maxDamage = 20; this.maxHealing = 30; this.heal = function () {}; this.damage = function () {}; this.totalDamage = this.damage(); this.displayChar = function () { return console.log(`I am a ${this.race}, I wield a ${this.item}, my total health point are ${this.maxHealth}`); }; }
/** * ============= * Panas Jakarta * ============= * * [Instruction] * Buatlah pseudocode untuk kasus bedikut: * Jakarta sedang panas, seorang student phase 0 ingin menurunkan suhu badannya * tergantung dari tingginya suhu (dalam celcius) di luar ruangan. * 1. Jika suhu <= 26, maka tidak menggunakan kipas atau AC * 2. Jika suhu <= 28, maka menggunakan kipas tangan * 3. Jika suhu <= 30, maka menggunakan kipas angin * 4. Jika suhu > 30, maka menggunakan AC * * Tampilkan apa yang akan student tersebut lakukan jika suhu udara adalah x? */ // Write pseudocode here SET x TO ANY VALUE IF x LOWER THAN EQUALS 26 THEN PRINT 'tidak menggunakan kipas atau AC' ELSE IF x LOWER THAN EQUALS 28 THEN PRINT 'menggunakan kipas tangan' ELSE IF x LOWER THEN EQUALS 30 THEN PRINT 'menggunakan kipas angin' ELSE PRINT 'menggunakan AC' END IF
// create object and adding properties to that object const team = { _players: [ { firstName: "Steve", lastName: "Smith", age: 32, }, { firstName: "Pat", lastName: "Cummins", age: 30, }, { firstName: "Kishen", lastName: "Muhunthan", age: 25, }, ], _games: [ { opponent: "India", teamPoints: 42, opponentPoints: 27, }, { opponent: "Srilanka", teamPoints: 35, opponentPoints: 25, }, { opponent: "England", teamPoints: 55, opponentPoints: 45, }, ], // get the information using getter method get players() { return this._players; }, get games() { return this._games; }, // add or appending values to and array // this add new values to an array addPlayer(firstName, lastName, age) { let player = { firstName: firstName, lastName: lastName, age: age, }; this.players.push(player); }, addGame(opponentName, teamPoints, opponentPoints) { let game = { opponent: opponentName, teamPoints: teamPoints, opponentPoints: opponentPoints, }; this.games.push(game); }, }; // add dummy data to append and print using console log team.addPlayer("Steph", "Curry", 28); team.addPlayer("Lisa", "Leslie", 40); team.addPlayer("Bugs", "Bunny", 76); console.log(team.players); team.addGame("Singapore", 14, 28); team.addGame("South Africa", 33, 32); team.addGame("New Zealand", 78, 23); console.log(team.games);
import React from 'react'; import {ModalWithDrag, SuperToolbar, SuperTable, SuperForm, Card} from '../../../../components'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './SendInfoDialog.less'; class SendInfoDialog extends React.Component { constructor (props) { super(props); this.state = { remainingWords: 0 }; } getProps = () => { const {title, onCancel, onOk} = this.props; return { onCancel, onOk, title, width: 1000, visible: true, maskClosable: false, okText: 'ๅ‘้€' }; }; onChangeOperate = (key,value) => { value && this.setState({remainingWords: value.length}); }; toContent = () => { const {messageContent,onChange,onCheck} = this.props; const {remainingWords} = this.state; const tableProps = {callback: {onCheck},...this.props,maxHeight:'400px'}; messageContent.onChange = onChange; messageContent.onChangeOperate = this.onChangeOperate; let isSystemMessage = this.props.CURRENT_KEY == 0; return ( <div className={s.root}> {!isSystemMessage && <Card className={s.pldCard}><SuperToolbar {...this.props} /></Card>} {!isSystemMessage && <Card className={s.pldCard}><SuperTable {...tableProps}/></Card>} <Card className={s.textArea}> <span className={s.wordsTip}>{remainingWords}/1000</span> <SuperForm {...this.props.messageContent}/> </Card> </div> ); }; render() { return ( <ModalWithDrag {...this.getProps()}> {this.toContent()} </ModalWithDrag> ); } } export default withStyles(s)(SendInfoDialog);
const fs = require('fs'); const path = require('path'); const process = require('process'); const readline = require('readline'); class FileWriter { stdout = process.stdout; stdin = process.stdin; readLines = readline.createInterface({ input: this.stdin, output: this.stdout, }); constructor(fileName) { process.on('exit', () => this.sayGoodBye()); this.stream = fs.createWriteStream(path.join(__dirname, fileName), 'utf-8'); this.readLines.on('line', (answer) => this.writeToFile(answer)); } sayGoodBye() { this.stdout.write('Good luck!\n'); this.readLines.close(); process.exit(0); } sayHello() { this.stdout.write('Please enter any text\n'); } writeToFile(answer) { if (answer === 'exit') { this.readLines.close(); process.exit(0); } this.stream.write(`${answer}\n`); } } const fileWriter = new FileWriter('text.txt'); fileWriter.writeToFile(''); fileWriter.sayHello();
// dao.js const fs = require("fs"); const sqlite3 = require('sqlite3') const Promise = require('bluebird') class AppDAO { constructor(dbFile) { this.dbFile = dbFile; this.db_exists = fs.existsSync(dbFile); this.db = new sqlite3.Database(dbFile, (err) => { if (err) { console.log(`Could not connect to database at ${dbFile}`, err) } else { console.log(`Connected to database at ${dbFile}`) } }); this.init(); } } AppDAO.prototype.init = function init(name = "List") { const db = this.db; db.serialize(() => { if (!this.db_exists) { console.log(`Creating new table '${name}' at ${this.dbFile}`); db.run( `CREATE TABLE ${name} (id INTEGER PRIMARY KEY AUTOINCREMENT, item TEXT)` ); // insert default items db.serialize(() => { db.run( `INSERT INTO ${name} (item) VALUES ("first item"), ("milk"), ("third item")` ); }); } else { console.log(`DB already exists at ${this.dbFile}`); db.each(`SELECT * from ${name}`, (err, row) => { if (row) { console.log(`record: ${row.item}`); } }); } }); } // https://stackabuse.com/a-sqlite-tutorial-with-node-js/ AppDAO.prototype.run = function(sql, params=[]) { return new Promise((resolve, reject) => { this.db.run(sql, params, function (err) { if (err) { console.log(`Error running sql ${sql}`); console.log(err); reject(err); } else { resolve({ id: this.lastID }); } }); }); } AppDAO.prototype.all = function(sql, params=[]) { return new Promise((resolve, reject) => { this.db.all(sql, params, (err, rows) => { if (err) { console.log(`Error running sql ${sql}`); console.log(err); reject(err); } else { resolve(rows); } }); }); } AppDAO.prototype.clear = function() { return new Promise((resolve, reject) => { this.db.each("SELECT * from List", (err, row) => { this.db.run(`DELETE FROM List WHERE ID=?`, row.id, error => { if (row) { console.log(`deleted row ${row.id}`); } }); }, err => { if (err) { console.log(`Error running sql ${sql}`); console.log(err); reject(err); } else { resolve("success"); } }); }); } module.exports = AppDAO
// a very basic HTTP request handler example const {createServer} = require('http'); const process = require('process'); const server = createServer((req, resp)=>{ console.log('Some client called from address : '+req.url); resp.end('Hello, from pavan! My server time is : '+new Date().toString()); }); const port = process.env.PORT || 4000; server.listen(port, ()=> { console.log(`Server started at http://10.150.220.40:${port}`); });
//Sucessor e Antecessor var num = 20; var sucessor = num + 1; var antecessor = num - 1; console.log("Antecessor -> "+antecessor+"\nSucessor -> "+sucessor);
import React from "react" import styled from "styled-components" import Img from "gatsby-image" const Container = styled.div` display: grid; grid-template-columns: repeat(2, 1fr); position: relative; @media only screen and (max-width: 30em) { grid-template-columns: 1fr; grid-template-rows: repeat(2, 25rem); } ` const Overlay = styled.div` position: absolute; top: 0; left: 0; height: 100%; width: 100vw; background: #000; opacity: 0.65; z-index: 2; ` const Image = styled(Img)` width: 100%; object-fit: contain; ` const Details = styled.div` position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100%; z-index: 3; ` const Gallery = ({ images, children }) => ( <Container> <Overlay /> {images.slice(0, 2).map(({ node }, count) => ( <Image key={count} fluid={node.childImageSharp.fluid} objectFit="contain" objectPosition="0 50%" /> ))} <Details>{children}</Details> </Container> ) export default Gallery
var template= _.template(require('./product-list.html')); require('./product-list.css'); module.exports=Backbone.View.extend({ initialize:function (options) { this.cache=options.cache||''; this.getDate(); }, getDate:function(){ if(this.cache){ this.render(); }else{ $.sync({ }) } }, render:function(){ this.$el.html(template(this.cache)); return this; }, events:{ 'tap .product-box li':'changePage', 'tap .add-cart-btn':'addCart' }, addCart:function(e){ var obj=$(e.currentTarget); if(obj.text()!='ๅŠ ๅ…ฅ่ดญ็‰ฉ่ฝฆ'){ return; } obj.addCart(); return false; }, changePage:function(e){ var link=$(e.currentTarget).attr('data-link'); $.changePage(link); } });
import Colors from './colors'; import Spacing from './spacing'; import Typography from './typography'; import ViewPropTypes from './ViewPropTypes'; export { Colors, Spacing, Typography, ViewPropTypes };
const { puppeteer, DEFAULT_ARGS } = require('./puppeteer') class Browser { constructor({ executablePath, args } = {}) { this.executablePath = executablePath this.args = args // Load puppeteer this._puppeteer = puppeteer() this._browser = null } defaultArgs() { const args = [...DEFAULT_ARGS] if (this.args) { args.push(...this.args) } return args } async get() { if (!this._browser) { this._browser = await this._puppeteer.launch({ args: this.defaultArgs(), defaultViewport: { deviceScaleFactor: 1, hasTouch: false, height: 1080, isLandscape: true, isMobile: false, width: 1920 }, executablePath: this.executablePath || this._puppeteer.executablePath(), headless: true }) } return this._browser } async close() { if (this._browser) { await this._browser.close() } } } module.exports = Browser
const Stack = require('./stackLinkedList'); const Queue = require('./queueLinkedList'); class BinarySearchTreeNode { constructor(value = null) { this.value = value; this.left = this.right = null; } }; class BinarySearchTree { constructor() { this.root = null; } insert(value, node = this.root) { if (this.isEmpty()) return this.root = new BinarySearchTreeNode(value); if (value === node.value) return; /* Implementations vary, this one does not allow duplicates */ if (value < node.value) { if (!node.left) node.left = new BinarySearchTreeNode(value); else this.insert(value, node.left); } else { if (!node.right) node.right = new BinarySearchTreeNode(value); else this.insert(value, node.right); } } contains(value, node = this.root) { if (value === node.value) return true; else if (value < node.value && node.left) return this.contains(value, node.left); else if (value > node.value && node.right) return this.contains(value, node.right); else return false; } preOrder(node = this.root, result = []) { result.push(node.value); if (node.left) this.preOrder(node.left, result); if (node.right) this.preOrder(node.right, result); return result; } inOrder(node = this.root, result = []) { if (node.left) this.inOrder(node.left, result); result.push(node.value); if (node.right) this.inOrder(node.right, result); return result; } postOrder(node = this.root, result = []) { if (node.left) this.postOrder(node.left, result); if (node.right) this.postOrder(node.right, result); result.push(node.value); return result; } dfs() { const result = []; const stack = new Stack(); stack.push(this.root); while (!stack.isEmpty()) { const node = stack.pop(); result.push(node.value); if (node.right) stack.push(node.right); if (node.left) stack.push(node.left); } return result; } bfs() { const result = []; const queue = new Queue(); queue.enqueue(this.root); while (!queue.isEmpty()) { const node = queue.dequeue(); result.push(node.value); if (node.left) queue.enqueue(node.left); if (node.right) queue.enqueue(node.right); } return result; } isEmpty() { return !this.root; } }; const binarySearchTree = new BinarySearchTree(); binarySearchTree.insert(10); binarySearchTree.insert(4); binarySearchTree.insert(30); binarySearchTree.insert(3); binarySearchTree.insert(15); binarySearchTree.insert(5); binarySearchTree.insert(40); console.log(binarySearchTree); /* 10 4 30 3 5 15 40 */ console.log('*** preOrder ***') // [ 10, 4, 3, 5, 30, 15, 40 ] console.log(binarySearchTree.preOrder()); console.log('*** inOrder ***') // [ 3, 4, 5, 10, 15, 30, 40 ] console.log(binarySearchTree.inOrder()); console.log('*** postOrder ***') // [ 3, 5, 4, 15, 40, 30, 10 ] console.log(binarySearchTree.postOrder()); console.log('*** dfs ***') // [ 10, 4, 3, 5, 30, 15, 40 ] console.log(binarySearchTree.dfs()); console.log('*** bfs ***') // [ 10, 4, 30, 3, 5, 15, 40 ] console.log(binarySearchTree.bfs()); const sumOfLevels = tree => { const levels = []; const queue = new Queue(); queue.enqueue([tree.root, 0]); while (!queue.isEmpty()) { const [node, level] = queue.dequeue(); levels[level] = (levels[level] || 0) + node.value; if (node.left) queue.enqueue([node.left, level + 1]); if (node.right) queue.enqueue([node.right, level + 1]); } return levels; }; console.log('*** sumOfLevels ***') console.log(sumOfLevels(binarySearchTree))
import axios from 'util/axios' const methods = {}; /** * ่Žทๅ–ๅŸŽๅธ‚ๅˆ—่กจ */ methods.queryCity = () => axios.post('web/city/findByCondition', { status: 1 }); /** * ่Žทๅ–ๆ‰‹ๆœบ้ชŒ่ฏ็  */ methods.getPhoneCode = phone => axios.get(`web/manager/generalCode/${phone}`); /** * ๆไบคไผไธš่ฎค่ฏ */ methods.updateApprove = params => axios.post('web/manager/adddeveloperinfo', params); /** * ๆŸฅ่ฏขไผไธš่ฎค่ฏ */ methods.queryApprove = mId => axios.post(`web/manager/developerinfo/${mId}`); /** * ๆŸฅ่ฏขๆˆฟๆบ็”ต่ฏๅ’Œ400็”ต่ฏ */ methods.queryHousePhone = show_managerId => axios.get(`web/manager/find/${show_managerId}`); /** * ไฟฎๆ”นๆˆฟๆบ็”ต่ฏ */ methods.updateHousePhone = params => axios.get(`web/manager/updatemanager/`, params); /** * ๆŸฅๆ‰พ่ฑก็›’่ฟ›ๅฎขๅˆ—่กจๆ•ฐๆฎ */ methods.queryEntryList = params => axios.post(`web/manager/record/pageforTuangou`, params); export default methods
import { createStore, combineReducers, applyMiddleware } from 'redux'; import { Blogs } from './Reducers/blogs'; import { Login } from './Reducers/login'; import { Signup } from './Reducers/signUp'; import { Users } from './Reducers/users'; import { AuthUser } from './Reducers/authUser'; import { Comments } from './Reducers/comments'; import { SingleBlog } from './Reducers/singleBlog'; import thunk from 'redux-thunk'; import logger from 'redux-logger'; export const ConfigureStore = () => { const store = createStore( combineReducers({ blogs: Blogs, login: Login, signup: Signup, users: Users, authUser: AuthUser, singleBlog: SingleBlog, comments: Comments }), applyMiddleware(thunk, logger) ); return store; }
import { createSlice } from '@reduxjs/toolkit' export const initialState = { loading: false, success: { add: false, get: false }, error: { add: false, get: false }, message: '', listPostFB: [] } export const FavoriteSlice = createSlice({ name: 'favorite', initialState, reducers: { addFavorite: ( state ) => ({ ...state, loading: true, message: 'Agregando a favorito' }), addFavoriteSuccess: ( state, { payload } ) => ({ ...state, loading: false, success: { ...state.success, add: true }, message: payload.message, listPostFB: [...state.listPostFB, { id: payload.id, title: payload.title, body: payload.body, user: payload.user, link: payload.link, idFirebase: payload.idFirebase }] }), addFavoriteFailed: ( state, { payload } ) => ({ ...state, loading: false, error: { ...state.error, add: true }, message: payload.message, success: { ...state.success, add: false } }), getFavorite: ( state ) => ({ ...state, loading: true, message: 'obteniendo sus posts favoritos' }), getFavoriteSuccess: ( state, { payload } ) => ({ ...state, loading: false, success: { ...state.success, get: true }, message: payload.message, listPostFB: payload.favorites }), getFavoriteFailed: ( state, { payload } ) => ({ ...state, loading: false, error: { ...state.success, get: true }, message: payload.message }) } })
var db = require('./Storage.js') var debug = true function dc(title,variable){ if(!debug) return console.log('\n#DEBUG:'+title) if(variable) console.log(variable) } function lookup(word){ db.Word.find( { w : word.toLowerCase() }, function(err,res){ if(err) return dc('Lookup error') if(!res) return dc('Word not in index') displayAllResults(word,res) }) } function displayResult(res){ db.Book.findOne( { '_id' : res.b } ,function(err,book){ if(err) return dc('Lookup error') if(!book) return dc('Book not in index',r.b) console.log('\n\t * Page '+res.p+' of Book: '+book.t+' ('+book.l+')') db.iLft-- } ) } function displayAllResults(word,data){ // dc('Results for '+word,data) dcount = data.length db.iLft = dcount db.processAndExit() for(i=0;i<dcount;i++){ r = data.pop() displayResult(r) } } db.link.on('open',function(){ lookup('vehicle') })
const capitalizeFirstLetter = string => string.charAt(0).toUpperCase() + string.slice(1); export const formatConfidenceScore = score => { try { return Number(score).toFixed(0); } catch (err) { console.error(err); return score; } }; export const drawRect = (detections, ctx) => { let text = ''; let value = 0; const padding = 10; // Loop through each prediction detections.forEach(prediction => { // Extract boxes and classes const [x, y, width, height] = prediction.bbox; text = capitalizeFirstLetter(prediction.class); value = prediction.score * 100; // Set styling const color = '12b84f'; ctx.strokeStyle = `#${color}`; ctx.font = '24px Arial'; // Draw rectangles and text ctx.beginPath(); ctx.fillStyle = `#${color}`; ctx.fillText( text, x + width / 2 - ctx.measureText(text).width, y - padding, ); ctx.rect(x, y, width, height); ctx.stroke(); }); return { text, score: value }; };
import styled from 'styled-components/macro'; import wave from '../../Images/wave.png'; import { WaveAnim, WaveAnimRev } from '../../Styling'; import { QUERIES } from '../../Styling'; export const RecipeListCont = styled.div` justify-content: center; text-align: center; user-select: none; margin-top: 100px; @media (${QUERIES.medium}) { margin: unset; } a { display: flex; text-align: center; text-decoration: none; align-items: center; text-transform: uppercase; margin: 30px 0; -webkit-text-fill-color: black; -webkit-text-stroke-color: black; -webkit-text-stroke-width: 1px; position: relative; ::after { display: block; position: absolute; top: 0; left: 0; width: 100%; height: auto; content: 'Chemex'; font-size: 25px; letter-spacing: 0.1em; line-height: 149%; -webkit-text-fill-color: transparent; -webkit-text-stroke-color: black; -webkit-text-stroke-width: 1px; background-image: url(${wave}); background-repeat: repeat-x; background-size: cover; background-position-y: 85px; animation: ${WaveAnimRev} 2s forwards; @media (${QUERIES.medium}) { font-size: 70px; letter-spacing: 0.1em; line-height: 149%; } } :hover { ::after { animation: ${WaveAnim} 2s forwards; } } } & .frenchpress { :hover::after, ::after { content: 'french press'; } } & .aeropress { :hover::after, ::after { content: 'aeropress'; } } & .espresso { :hover::after, ::after { content: 'espresso'; } } & .pourover { :hover::after, ::after { content: 'pourover'; } } `; export const Option = styled.div` font-size: 25px; width: 100%; line-height: 149%; align-items: center; text-align: center; position: relative; letter-spacing: 0.1em; @media (${QUERIES.medium}) { font-size: 70px; } `;
import React from "react"; const Headliner = ({ headline, quote }) => { return ( <section className="global-page-header"> <div className="container"> <div className="row"> <div className="col-md-12"> <div className="block"> <h2>{headline}</h2> <p>{quote}</p> </div> </div> </div> </div> </section> ); }; export default Headliner;
//codewars by my partner Big Al // a pack yak can hold 28 items given the number of items the pack yak is currently holding display the number of available item slots. class MakeFamiliar { constructor(carryLimit, occupiedSpace, color, age, catchPhrase, species) { this.carryLimit = carryLimit; this.occupiedSpace = occupiedSpace; this.color = color; this.age = age; this.catchPhrase = catchPhrase; this.species = species; } freeSlots() { return this.carryLimit - this.occupiedSpace; } announceFamiliar() { return `"${this.catchPhrase}", said the ${this.age} year old ${this.color} ${this.species}.`; } } let pakYak = new MakeFamiliar(28, 7, "purple", 100000, "Wowie", "Yak"); console.log(pakYak.carryLimit); console.log(pakYak.occupiedSpace); console.log(pakYak.freeSlots()); console.log(pakYak.announceFamiliar());
import React, { useContext } from 'react' import { View, Text, ScrollView, ImageBackground, RefreshControl } from 'react-native' import { connect } from 'react-redux'; import { HeaderCustom } from '../Constants/Header'; import { styles } from './scheduleStyling'; import LinearGradient from 'react-native-linear-gradient'; import { Accordion } from 'native-base'; import { getSchedule, getScheduleDetail } from '../../../../Redux/Actions/userAction'; import { TouchableOpacity } from 'react-native-gesture-handler'; import { LocalizationContext } from '../../../../Localization/LocalizationContext'; const ScheduleBooking = (props) => { const contextType = useContext(LocalizationContext) const { translations, appLanguage } = contextType const { schedule, fetching, getSchedule, userDetails, getScheduleDetail } = props const scheduleBookings = [ { from: 'Karachi', destination: 'Lahore', timing: '03:00 AM', date: '27-Nov-2020', availableSeats : 3, price: '1450' }, { from: 'Karachi', destination: 'Lahore', timing: '03:00 AM', date: '27-Nov-2020', availableSeats : 3, price: '1450' }, { from: 'Karachi', destination: 'Lahore', timing: '03:00 AM', date: '27-Nov-2020', availableSeats : 3, price: '1450' }, { from: 'Karachi', destination: 'Lahore', timing: '03:00 AM', date: '27-Nov-2020', availableSeats : 3, price: '1450' }, ] const onRefresh = () => { getSchedule(userDetails.data.id, translations, appLanguage) } let arrow = "<----->" return( <View> <ImageBackground style={styles.backroundImage} source={require('../../../../../assets/Splash.png')}> <View style={styles.container}> <View style={{...styles.itemContainer, marginVertical: 10}}> <HeaderCustom add logo navigation={props.navigation}/> </View> <ScrollView showsVerticalScrollIndicator={false} refreshControl={<RefreshControl colors={["#3A91FA"]} refreshing={fetching} onRefresh={onRefresh} />}> {schedule ? <View> {schedule.map((val, ind) => ( <View key={ind} style={[styles.scheduleCard]}> <LinearGradient style={[styles.round, { width: '100%' }]} colors={['#3895FC', '#16C7FE', "#01E5FE"]} start={{ x: 0, y: 0 }} end={{ x: 0, y: 1 }}> <View style={[styles.itemContainer, styles.round]}> <Accordion expandedIcon style={{ borderWidth: 0 }} headerStyle={{ backgroundColor: 'transparent' }} renderHeader={(e) => { return ( <Text numberOfLines={1} style={{ ...styles.whiteBoldTxt, width: '70%' }}> {val.pickup_name} {val.destination_name} </Text> ); } } dataArray={[val]} renderContent={(e) => { return ( <Text style={[styles.whiteNormalTxt, {borderTopWidth: 2, borderTopColor: '#fff', paddingVertical: 5}]}> <Text style={styles.whiteBoldTxt}>{translations.FROM}</Text> : {val.pickup_name} {'\n'} <Text style={styles.whiteBoldTxt}>{translations.TO}</Text> : {val.destination_name} </Text> ); } } expanded={ind} /> </View> </LinearGradient> <TouchableOpacity onPress={() => { getScheduleDetail(userDetails.data.id, val.schedule_id, translations,appLanguage); // props.navigation.navigate("ViewScheduleDetails") } }> <View style={[styles.row, styles.spaceBtw, styles.itemContainer]}> <Text style={styles.whiteNormalTxt}> {translations.TIMING} </Text> <Text style={styles.whiteNormalTxt}> {val.timing} </Text> </View> <View style={[styles.row, styles.spaceBtw, styles.itemContainer]}> <Text style={styles.whiteNormalTxt}> {translations.DATE} </Text> <Text style={styles.whiteNormalTxt}> {val.date} </Text> </View> <View style={[styles.row, styles.spaceBtw, styles.itemContainer]}> <Text style={styles.whiteNormalTxt}> {translations.AVAILABLE_SEATS} </Text> <Text style={styles.whiteNormalTxt}> {val.seat_available} </Text> </View> <View style={[styles.row, styles.spaceBtw, styles.itemContainer]}> <Text style={styles.whiteNormalTxt}> {translations.TOTAL_SEATS} </Text> <Text style={styles.whiteNormalTxt}> {val.seat} </Text> </View> <View style={[styles.row, styles.spaceBtw, styles.itemContainer]}> <Text style={styles.whiteNormalTxt}> {translations.PRICE} </Text> <Text style={styles.whiteNormalTxt}> ${val.price} </Text> </View> </TouchableOpacity> </View> ))} </View> : <View style={{justifyContent: 'center', alignContent:'center', marginTop: '60%'}}> <Text style={{color:"#fff", alignSelf:'center', fontSize: 20}}> {translations.YOU_HAVE_NOT_CREATED_ANY_SCHEDULE} </Text> </View> } </ScrollView> </View> </ImageBackground> </View> ) } const mapStateToProps = state => { return { userDetails: state.user.userDetails, fetching: state.user.fetching, schedule: state.user.schedule, }; }; const mapDispatchToProps = { getSchedule, getScheduleDetail }; export default connect(mapStateToProps, mapDispatchToProps)(ScheduleBooking);
import React from 'react'; import {View, Text, TouchableOpacity} from 'react-native'; import MapView from 'react-native-maps'; import {useNavigation} from '@react-navigation/native'; import normalize from 'react-native-normalize'; import MapViewDirections from 'react-native-maps-directions'; const SingleRegionView = ({api, initialRegion, stages, name}) => { const navigation = useNavigation(); return ( <View> <MapView initialRegion={initialRegion} zoomEnabled={true} style={{height: '100%'}}> <View> <TouchableOpacity activeOpacity={0.5} style={{ fontSize: normalize(15, 'width'), paddingLeft: normalize(15, 'width'), paddingTop: normalize(15, 'width'), }} onPress={() => navigation && navigation.navigate('RegionDetails', {regionName: name}) } loading> <Text style={{ color: '#ffffff', backgroundColor: '#EF7D21', width: normalize(70, 'width'), textAlign: 'center', padding: normalize(5, 'width'), borderRadius: 20, }}> Details </Text> </TouchableOpacity> </View> {stages && stages.map(stage => { if (stage.index % 2 === 0) { return ( <MapViewDirections key={stage.index} origin={stage.origin} destination={stage.destination} apikey={api} strokeWidth={5} strokeColor="#EF7D21" /> ); } else { return ( <MapViewDirections key={stage.index} origin={stage.origin} destination={stage.destination} apikey={api} strokeWidth={5} strokeColor="#000000" /> ); } })} </MapView> </View> ); }; export default SingleRegionView;
$(document).ready(function() { // variables var topics = ["aardvark","albatross","alligator","alpaca","antelope", // Collection of words used in the game "arctic fox","armadillo","axolotl","baboon","badger", "bandicoot","barnacle","barracuda","basilisk","beaver", "beetle","bobcat","bonobo","buffalo","bumble bee", "butterfly","camel","canary","capybara","caterpillar", "centipede","chameleon","cheetah","chicken","chimpanzee", "chinchilla","chipmunk","cougar","coyote","crane", "crocodile","cuttlefish","dingo","dolphin","dolphin", "donkey","dragonfly","dugong","eagle","earthworm", "elephant","falcon","falcon","ferret","flamingo","gazelle", "gecko","gecko","gibbon","gila monster","giraffe","goose", "gopher","gorilla","guinea pig","hamster","hedgehog", "hippopotamus","horse","hyena","iguana","impala","jackal", "jaguar","jellyfish","kangaroo","koala","komodo dragon", "krill","lemming","lemur","leopard","llama","lobster", "manatee","mandrill","manta ray","marmoset", "meerkat","millipede","mongoose","monkey","moray eel", "mouse","nightingale","ocelot","octopus","opossum", "orangutan","ostrich","otter","oyster","panda","panther", "panther","peacock","penguin","pirahna","platypus", "polar bear","porcupine","puffer fish","rabbit", "raccoon","reindeer","rhinoceros","rooster","salamander", "scorpion","sea cucumber","sea lion","sea sponge", "seahorse","shark","sheep","sloth","snail","snake", "sparrow","squid","squirrel","starfish","stingray", "sturgeon","tamarin","tapir","tiger","tortoise","toucan", "turtle","vampire bat","walrus","warthog","weasel","whale", "wildebeast","wolverine","wombat","woodchuck","zebra"]; // function var addButton = function(topic) { var button = $("<button>").addClass("topic btn btn-primary").attr("data-topic",topic).text(topic); button.on("click", function() { var term = $(this).attr("data-topic"); var apiKey = "dc6zaTOxFJmzC"; var queryUrl = "http://api.giphy.com/v1/gifs/search?q=" + term +"&limit=10&api_key=" + apiKey; $.ajax({ url: queryUrl, method: "GET" }).done(function(response){ console.log(response); $("#gifs").empty(); var data = response.data; for( var i = 0; i < data.length; i++) { var gifDiv = $("<div>"); gifDiv.addClass("gif-wrapper"); var rating = $("<p>"); rating.text("Rating: " + data[i].rating); var gif = $("<img>").addClass("gif"); gif.attr("src",data[i].images.fixed_height_still.url); gif.attr("data-state","still") gif.attr("data-still",data[i].images.fixed_height_still.url); gif.attr("data-animate",data[i].images.fixed_height.url); gif.on("click", function() { var state = $(this).attr("data-state"); if(state === "still") { // change to animated gif $(this).attr("data-state","animate"); $(this).attr("src",$(this).attr("data-animate")); } else if(state === "animate") { // change to still gif $(this).attr("data-state","still"); $(this).attr("src",$(this).attr("data-still")); } }); rating.appendTo(gifDiv); gif.appendTo(gifDiv); $("#gifs").append(gifDiv); } }); }); $("#topics").append(button); } var addAllTopics = function() { for(var i = 0; i < topics.length; i++) { addButton(topics[i]); } } // event listeners $("#add").on("click", function(event) { // prevent page from refreshing event.preventDefault(); var topic = $("#topic-input").val().trim() if(topic.length > 0) { topics.push(topic); addButton(topic); } }); // add all topic buttons when page loads addAllTopics(); });
module.exports = { formats: { '.esl': require('glagol-eslisp')({ extraTransformMacros: [ require('eslisp-dotify') , require('eslisp-camelify') , require('eslisp-propertify') ] }) } }
self.onSongleAPIReady = function(Songle) { var player = new Songle.SyncPlayer({ accessToken: "0000009a-Wh9Gam9", // Please edit your access token mediaElement: "#songle" }); var player2 = new Songle.SyncPlayer({ accessToken: "0000009a-tctdSbR", // Please edit your access token mediaElement: "#songle2" }); player.addPlugin(new Songle.Plugin.Beat()); player.addPlugin(new Songle.Plugin.Chord()); player.addPlugin(new Songle.Plugin.Chorus()); // IFrame API Playerใ‚’่ชญใฟ่พผใ‚€ /*Sconst tag = document.createElement('script'); tag.src = "https://www.youtube.com/player_api"; const firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); let ytplayer; function onYouTubePlayerAPIReady() { ytplayer = new YT.Player('#songle', { height: '360', width: '640', }); } ytplayer.cueVideoById({videoId: "zweVJrnE1uY"}); const media = new Songle.Media.YtVideo("https://www.youtube.com/watch?v=zweVJrnE1uY"); player.useMedia(media);*/ player.useMedia("https://www.youtube.com/watch?v=hxSg2Ioz3LM"); player2.useMedia("https://www.youtube.com/watch?v=dUnma5RLuYk"); player.on("beatPlay", function(ev) { var beatElement = document.querySelector(".beat"); var beatInfo1Element = document.querySelector(".beat .info1"); var beatInfo2Element = document.querySelector(".beat .info2"); beatElement.className = "beat beat-" + ev.data.beat.position; beatInfo1Element.textContent = ev.data.beat.position; beatInfo2Element.textContent = ev.data.beat.count; }); player.on("chordEnter", function(ev) { var chordNameElement = document.querySelector(".chord .name"); chordNameElement.textContent = ev.data.chord.name; }); player.on("chorusSectionEnter", function(ev) { document.body.style.backgroundColor = "#000000"; document.body.style.color = "#f3f5f6"; }); player.on("chorusSectionLeave", function(ev) { document.body.style.backgroundColor = "#f3f5f6"; document.body.style.color = "#000000"; }); var playButton = document.querySelector("button.play"); var stopButton = document.querySelector("button.stop"); playButton.addEventListener("click", function() { player.play(); player2.play(); player2.volume = 0; }); stopButton.addEventListener("click", function() { player.stop(); player2.stop(); }); setInterval( function() { if(player.isPlaying) { var timeElement = document.querySelector(".time"); var second = parseInt(player.position / 1000 % 60); var minute = parseInt(player.position / 1000 / 60); timeElement.textContent = minute + ":" + (second < 10 ? ("0" + second) : second); } }, 1000); }
(function() { var TableOfContents, TableOfContentsNode, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __slice = [].slice; TableOfContentsNode = (function() { TableOfContentsNode.handelize = function(text) { return text.toLowerCase().split('(')[0].split(':')[0].replace(/[\'\"\(\)\[\]]/g, '').replace(/\W/g, ' ').replace(/\ +/g, '-').replace(/(-+)$/g, '').replace(/^(-+)/g, ''); }; TableOfContentsNode._functionSignature = /\w+\(.*\)/i; TableOfContentsNode._classfunctionSignature = /@\w+\(.*\)/i; TableOfContentsNode._typeInformation = /\s*:\s*(?:\[\s*(?:\w|\|)+\s*\]|\w+)/ig; TableOfContentsNode._defaultArgumentValues = /(\w+)\s*\=\s*\w+/ig; TableOfContentsNode.extractSignature = function(text) { var result; result = text.replace(this._typeInformation, ''); if (this._functionSignature.test(text)) { return result.replace(this._defaultArgumentValues, '$1'); } else { return result; } }; TableOfContentsNode.prototype.parent = null; TableOfContentsNode.prototype["class"] = ""; function TableOfContentsNode(depth, text, searchable) { this.depth = depth; this.text = text; this.searchable = searchable; this.children = []; this._extractSignature(); } TableOfContentsNode.prototype.hasChildren = function() { return this.children.length > 0; }; TableOfContentsNode.prototype.addChild = function(child) { var grandChild, grandChildren, _i, _len; this._clearMemos(); this.children.push(child); child.parent = this; if (this.id.length > 0) { child.id = this.id + "-" + child.baseID; } grandChildren = child.children.splice(0, child.children.length); for (_i = 0, _len = grandChildren.length; _i < _len; _i++) { grandChild = grandChildren[_i]; child.addChild(grandChild); } return child; }; TableOfContentsNode.prototype.index = function() { var child, item, q, _i, _len, _ref; if (!this._index) { this._index = {}; q = [this]; while (q.length > 0) { item = q.shift(); _ref = item.children; for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; q.push(child); } if (item.handle) { this._index[item.handle] = item.id; } } } return this._index; }; TableOfContentsNode.prototype.root = function() { var current; if (!this._root) { current = this; while (current.parent) { current = current.parent; } this._root = current; } return this._root; }; TableOfContentsNode.prototype.autolink = function(linkContents) { var handle, id, index, rootIndex, signature; signature = this.constructor.extractSignature(linkContents); handle = this.constructor.handelize(signature); index = this.index(); rootIndex = this.root().index(); id = index[signature] || index[handle] || rootIndex[signature] || rootIndex[handle]; if (id != null) { return "<a href=\"" + id + "\">" + linkContents + "</a>"; } else { return linkContents; } }; TableOfContentsNode.prototype._extractSignature = function() { var handle, old; old = this.text; this.text = this.constructor.extractSignature(this.text); handle = this.constructor.handelize(this.text); this["class"] = (function() { if (this.searchable) { switch (this.depth) { case 1: return ""; case 2: return "class"; case 3: if (this.text.match(this.constructor._classFunctionSignature)) { return "class-function"; } else if (this.text.match(this.constructor._functionSignature)) { return "function"; } else { return "property"; } break; default: return ""; } } else { return ""; } }).call(this); return this.baseID = this.id = handle; }; TableOfContentsNode.prototype._clearMemos = function() { delete this._index; return delete this._root; }; return TableOfContentsNode; })(); TableOfContents = (function(_super) { __extends(TableOfContents, _super); TableOfContents.prototype.parent = false; function TableOfContents() { TableOfContents.__super__.constructor.call(this, 0, ""); this.id = ""; this._root = this; } TableOfContents.prototype.merge = function() { var child, subject, subjects, _i, _j, _len, _len1, _ref; subjects = 1 <= arguments.length ? __slice.call(arguments, 0) : []; this._clearMemos(); for (_i = 0, _len = subjects.length; _i < _len; _i++) { subject = subjects[_i]; _ref = subject.children; for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { child = _ref[_j]; this.addChild(child); } } return this; }; TableOfContents.prototype._extractSignature = function() {}; return TableOfContents; })(TableOfContentsNode); module.exports = { TableOfContents: TableOfContents, TableOfContentsNode: TableOfContentsNode }; }).call(this);
/** * Created by debal on 03.03.2016. */ var React = require('react'); var ReactRedux = require('react-redux'); var RouteList = require('./route-list'); var Properties = require('../../const/properties'); const mapStateToProps = (state) => { return { items: state.Routes.items, isAuthorized: state.User.isAuthorized, context: state.Routes.context, error: state.Routes.error, message: state.Routes.message, userLocation: state.User.location }; }; const RouteContainer = ReactRedux.connect(mapStateToProps)(RouteList); module.exports = RouteContainer;
const Dateify = require("./Dateify"); const TournamentMembers = require("./TournamentMembers"); class Tournament { constructor(tournamentData) { this.tag = tournamentData.tag; this.type = tournamentData.type; this.status = tournamentData.status; this.creatorTag = tournamentData.creatorTag; this.tournamentName = tournamentData.name; this.levelCap = tournamentData.levelCap; this.firstPlaceCardPrize = tournamentData.firstPlaceCardPrize; this.capacity = tournamentData.capacity; this.maxCapacity = tournamentData.maxCapacity; this.preparationDuration = tournamentData.preparationDuration; this.duration = tournamentData.duration; this.createdDate = new Dateify(tournamentData.createdTime); this.startedDate = new Dateify(tournamentData.startedTime); this.endedDate = new Dateify(tournamentData.endedTime); this.members = new TournamentMembers(tournamentData.membersList); } } module.exports = Tournament;
const maxFlags = array => { // find peaks const peaks = array.slice().map(e => 0); for(let i=1; i < array.length - 1; i++) { if(array[i] > array[i-1] && array[i] > array[i+1]) peaks[i] = array[i]; } // console.log(peaks); // find location of next peak const next = peaks.slice().map(e => 0); next[peaks.length - 1] = -1; for(let i=peaks.length - 2; i >= 0; i--) { if(peaks[i] != 0) next[i] = i; else next[i] = next[i + 1]; } // console.log(`${peaks}\n${next}`); let max = 0; for(let i=1; i < Math.sqrt(array.length) + 1; i++) { let pos = 0; let count = 0; while(pos < array.length && count < i) { pos = next[pos]; if(pos == -1) break; count += 1; pos += i; } max = Math.max(max, count); } console.log(`${peaks}\n${next}`); // return max flags return max; } module.exports = maxFlags;
import * as React from 'react' const useAutocompleteSingle = (props) => { const [value, setValue] = React.useState(props.defaultValue) const handleChange = React.useCallback(name => { setValue(name) }, []); return { ...props, value, onChange: handleChange, setValue, } } export default useAutocompleteSingle;
$(document).ready(function() { $("#formOne").submit(function(event) { const nameInput = $("input#name").val(); const foodInput = $("input#food").val(); const musicInput = $("input:radio[name=music]:checked").val(); const dobInput = $("#dob").val(); const colorInput = $("#color").val(); $(".name").text(nameInput); $(".food").text(foodInput); $(".music").text(musicInput); $(".dob").text(dobInput); $(".color").text(colorInput); $("#output").show(); event.preventDefault(); }); });
/* See license.txt for terms of usage */ define([ "firebug/lib/trace", "firebug/firebug", "firebug/lib/object", "firebug/lib/promise", "firebug/debugger/clients/objectClient", "firebug/debugger/clients/clientFactory", ], function (FBTrace, Firebug, Obj, Promise, ObjectClient, ClientFactory) { // ********************************************************************************************* // // Constants var gripNull = new ObjectClient({type: "null"}); var gripUndefined = new ObjectClient({type: "undefined"}); var gripNaN = new ObjectClient({type: "NaN"}); // ********************************************************************************************* // // ClientCache function ClientCache(debuggerClient, context) { this.debuggerClient = debuggerClient; this.context = context; // Initialization this.clear(); } ClientCache.prototype = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Objects clear: function() { for each (var grip in this.clients) grip.valid = false; this.clients = {}; this.signatures = {}; }, /** * Return a client object (i.e. instance of {@link ObjectClient}) according to the * grip (handle) passed into the function. * * The grip can be: * 1) Real grip that has its own actor (ID). * 2) Wrapped primitive value for undefined, null, +/-Infinity, NaN and -0. * 3) Unwrapped for any other primitive value e.g. a number, an empty string, boolean. */ getObject: function(grip) { // Return if grip is null or undefined. Note that if grip represents null or undefined, // it has to be wrapped in JSON in order to be a valid grip. if (grip == null) return grip; // Null and undefined values has it's own type, so return predefined grip. // Or again, directly the passed value. if (typeof grip === "object" && !grip.actor) { if (grip.type == "null") return gripNull; else if (grip.type == "undefined") return gripUndefined; else if (grip.type == "NaN") return gripNaN; // Can be a primitive value evaluated to 'true' (e.g. a string, boolean true, etc.). return grip; } var object; if (typeof grip === "object") { object = this.clients[grip.actor]; if (object) return object; } object = ClientFactory.createClientObject(grip, this); // We don't cache primitive grips. if (typeof grip === "object") this.clients[grip.actor] = object; return object; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Packets request: function(packet) { // xxxHonza: packets should be also cached. // xxxHonza: we need to check if the same request is in progress and // return the existing promise. // There should be a map requestID -> promise; where requestID = {actorID + packetType} // The same map could be also used to cache the packets. var deferred = Promise.defer(); this.debuggerClient.request(packet, function(response) { deferred.resolve(response); }); return deferred.promise; }, }; // ********************************************************************************************* // // Registration return ClientCache; // ********************************************************************************************* // });
import React, { Component } from 'react'; import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router' class App extends Component { render() { return ( <div> <h1>Employee</h1> <nav className="navbar navbar-default"> <div className="container-fluid"> <div className="navbar-header"> <a className="navbar-brand" href="/">Home</a> </div> <ul className="nav navbar-nav"> <li><Link to="addEmployee">ADD</Link> </li> <li><Link to="Update">EDIT</Link> </li> <li><Link to="Delete">DELETE</Link></li> </ul> </div> </nav> {this.props.children} </div> )} } export default App;
({ readCSV : function(component, event, helper) { } })
import Layout from "../../components/Layout"; import axios from "axios"; import {useEffect, useState} from "react"; import {env} from "../../next.config"; import Link from "next/link"; import reactHtml from "react-render-html"; import moment from "moment"; import InfiniteScroll from 'react-infinite-scroller'; const Links = ({query, category, links, totalLinks, linksLimit, linkSkip}) => { const [setLinks, setLinksState] = useState(links); const [setTrending, setTrendingState] = useState([]); // to determine load more or not const [setLimit, setLimitState] = useState(linksLimit); const [setSkip, setSkipState] = useState(0); const [setSize, setSizeState] = useState(totalLinks); // load trending useEffect(() => { loadTrending() }, []); const loadTrending = async () => { const response = await axios.get(`${env.API}/link/popular/${category.slug}`) setTrendingState(response.data); } const handleClick = async (link_Id) => { const response = await axios.put(`${env.API}/view-count`, {link_Id}); updateLinks(); loadTrending(); }; const updateLinks = async () => { // set skip and limit to default; const response = await axios.post(`${env.API}/category/${query.slug}`); setLinksState(response.data.links) } const allLinks = () => { return ( setLinks.map((link, index) => { return ( <div className="row" style={{"marginLeft": "20px"}}> <div className="col-md-8 filter-drop-shadow box"> <a className="custom text-secondary" href={link.url} target="_blank"> <h3 onClick={() => handleClick(link._id)} className="title-width">{link.title}</h3> </a> <div className="col-md-4"> <span className="badge text-dark">{moment(link.createdAt).fromNow()} added by {link.postedBy.name}</span> {/* <span className="badge text-dark">{moment(link.createdAt).fromNow()} added by </span> */} </div> <div className="col-md-12"> <span className="badge text-dark"> {link.type} </span> <span className="badge text-dark"> {link.medium} </span> {link.categories.map((link, index) => { return <span className="badge text-dark">{link.name}</span> })} </div> <span className="badge text-dark">{link.views} views</span> </div> </div> ) }) ) } const handleLoad = async () => { let Skips = setSkip + setLimit; const response = await axios.post(`${env.API}/category/${query.slug}`, {skip: Skips, limit: setLimit}); setLinksState([...setLinks, ...response.data.links]) setSizeState(response.data.links.length); setSkipState(Skips); } // const loadButton = () => { // return ( // setSize > 0 && setSize >= setLimit && ( // <div className="text-center"> // <button onClick={handleLoad} className="btn btn-lg btn-secondary">Load more links</button> // </div> // ) // ) // } const displayLinks = () => { return ( setTrending.map((link, index) => { return ( <div className="row alert alert-secondary"> <div className="col-md-6" onClick={() => handleClick(link._id)}> <a href={link.url} target="_blank" className="custom text-secondary">{link.title}</a> </div> <div className="col-md-6"> <span className="badge text-dark">{moment(link.createdAt).fromNow()} added by {link.postedBy.name} </span> {/* <span className="badge text-dark">{moment(link.createdAt).fromNow()} added by </span> */} </div> <div className="colmd-12"> <span className="badge text-dark">{link.type} {link.medium}</span> <span className="badge text-dark">{link.views} views</span> {link.categories.map((category, index) => { return ( <span className="badge text-dark">{category.name}</span> ) })} </div> </div> ) }) ) } return ( <Layout> <div className="row"> <div className="col-md-4"> <img src={category.image.url} alt={category.name} style={{"width": "auto", "maxHeight": "150px"}}></img> </div> <div className="col-md-8"> <h1>{category.name}</h1> <div>{reactHtml(category.content) || ""}</div> </div> </div> <br/> <div className="row" style={{"paddingTop": "150px"}}> <div className="col-md-5"> <h2>top trending</h2> {displayLinks()} </div> <div className="col-md-7"> {allLinks()} {/* {loadButton()} */} </div> <div className="row"> <div className="col-md-4"></div> <div className="col-md-8 text-center"> <InfiniteScroll pageStart={0} loadMore={handleLoad} hasMore={setSize > 0 && setSize >= setLimit } // loader={<div className="loader" key={0}>Loading ...</div>} loader={<img key={0} className="custom-image" src="/static/images/loading.gif" alt="loading" />} > </InfiniteScroll> </div> </div> </div> </Layout> ) }; Links.getInitialProps = async ({query, req}) => { // for infinite scrolling let skip = 0; let limit = 2; // get slug from query const response = await axios.post(`${env.API}/category/${query.slug}`, {skip, limit}) return { query, category: response.data.category, links: response.data.links, totalLinks: response.data.links.length, linksLimit: limit, linkSkip: skip } } export default Links;
define("/WEB-UED/fancy/dist/p/myOrder/list-debug.handlebars", ["alinw/handlebars/1.3.0/runtime-debug"], function(require, exports, module) { var Handlebars = require("alinw/handlebars/1.3.0/runtime-debug"); var template = Handlebars.template; module.exports = template(function(Handlebars, depth0, helpers, partials, data) { this.compilerInfo = [4, ">= 1.0.0"]; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var stack1, functionType = "function", escapeExpression = this.escapeExpression, self = this, helperMissing = helpers.helperMissing, blockHelperMissing = helpers.blockHelperMissing; function program1(depth0, data) { var buffer = "", stack1; buffer += "\r\n "; stack1 = (stack1 = typeof depth0 === functionType ? depth0.apply(depth0) : depth0, blockHelperMissing.call(depth0, stack1, { hash: {}, inverse: self.noop, fn: self.program(2, program2, data), data: data })); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n"; return buffer } function program2(depth0, data) { var buffer = "", stack1, helper, options; buffer += '\r\n <div class="bg-white mb10">\r\n '; stack1 = helpers.each.call(depth0, depth0 && depth0.detailMap, { hash: {}, inverse: self.noop, fn: self.program(3, program3, data), data: data }); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += '\r\n <ul class="goods-list mb10">\r\n '; stack1 = helpers.each.call(depth0, depth0 && depth0.detailMap, { hash: {}, inverse: self.noop, fn: self.program(7, program7, data), data: data }); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += '\r\n </ul>\r\n <div class="color-gray ar pd10 borderB">\r\n ๅ…ฑ่ฎก'; if (helper = helpers.goodsCount) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.goodsCount; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + 'ไปถ ๅˆ่ฎก๏ผš<span class="color-orange">๏ฟฅ'; if (helper = helpers.totalPrice) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.totalPrice; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + "</span>\r\n (ๅซ่ฟ่ดน๏ฟฅ"; if (helper = helpers.expressCost) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.expressCost; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + ')\r\n </div>\r\n <div class="pd10 ar">\r\n '; stack1 = (helper = helpers.ifCond || depth0 && depth0.ifCond, options = { hash: {}, inverse: self.noop, fn: self.program(11, program11, data), data: data }, helper ? helper.call(depth0, depth0 && depth0.state, "==", -1, options) : helperMissing.call(depth0, "ifCond", depth0 && depth0.state, "==", -1, options)); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n "; stack1 = (helper = helpers.ifCond || depth0 && depth0.ifCond, options = { hash: {}, inverse: self.noop, fn: self.program(13, program13, data), data: data }, helper ? helper.call(depth0, depth0 && depth0.state, "==", 0, options) : helperMissing.call(depth0, "ifCond", depth0 && depth0.state, "==", 0, options)); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n "; stack1 = (helper = helpers.ifCond || depth0 && depth0.ifCond, options = { hash: {}, inverse: self.noop, fn: self.program(15, program15, data), data: data }, helper ? helper.call(depth0, depth0 && depth0.state, "==", 1, options) : helperMissing.call(depth0, "ifCond", depth0 && depth0.state, "==", 1, options)); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n "; stack1 = (helper = helpers.ifCond || depth0 && depth0.ifCond, options = { hash: {}, inverse: self.noop, fn: self.program(17, program17, data), data: data }, helper ? helper.call(depth0, depth0 && depth0.state, "==", 2, options) : helperMissing.call(depth0, "ifCond", depth0 && depth0.state, "==", 2, options)); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n "; stack1 = (helper = helpers.ifCond || depth0 && depth0.ifCond, options = { hash: {}, inverse: self.noop, fn: self.program(19, program19, data), data: data }, helper ? helper.call(depth0, depth0 && depth0.state, "==", 3, options) : helperMissing.call(depth0, "ifCond", depth0 && depth0.state, "==", 3, options)); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n "; stack1 = (helper = helpers.ifCond || depth0 && depth0.ifCond, options = { hash: {}, inverse: self.noop, fn: self.program(21, program21, data), data: data }, helper ? helper.call(depth0, depth0 && depth0.state, "==", 5, options) : helperMissing.call(depth0, "ifCond", depth0 && depth0.state, "==", 5, options)); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n "; stack1 = (helper = helpers.ifCond || depth0 && depth0.ifCond, options = { hash: {}, inverse: self.noop, fn: self.program(23, program23, data), data: data }, helper ? helper.call(depth0, depth0 && depth0.state, "==", 5, options) : helperMissing.call(depth0, "ifCond", depth0 && depth0.state, "==", 5, options)); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n "; stack1 = (helper = helpers.ifCond || depth0 && depth0.ifCond, options = { hash: {}, inverse: self.noop, fn: self.program(25, program25, data), data: data }, helper ? helper.call(depth0, depth0 && depth0.state, "==", 7, options) : helperMissing.call(depth0, "ifCond", depth0 && depth0.state, "==", 7, options)); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n </div>\r\n </div>\r\n "; return buffer } function program3(depth0, data) { var buffer = "", stack1; buffer += '\r\n <ul class="goods-list borderB has-express">\r\n '; stack1 = helpers.each.call(depth0, depth0, { hash: {}, inverse: self.noop, fn: self.program(4, program4, data), data: data }); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n </ul>\r\n "; return buffer } function program4(depth0, data) { var buffer = "", stack1, helper, options; buffer += "\r\n "; stack1 = (helper = helpers.ifCond || depth0 && depth0.ifCond, options = { hash: {}, inverse: self.noop, fn: self.program(5, program5, data), data: data }, helper ? helper.call(depth0, data == null || data === false ? data : data.key, "!=", "N", options) : helperMissing.call(depth0, "ifCond", data == null || data === false ? data : data.key, "!=", "N", options)); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n "; return buffer } function program5(depth0, data) { var buffer = "", stack1, helper; buffer += '\r\n <li class="goods-list-item bg-white" data-id="'; if (helper = helpers.id) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.id; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '">\r\n <a external _href="/order/orderDetail.html?orderNo='; if (helper = helpers.orderNo) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.orderNo; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '">\r\n <div class="goods-list-img">\r\n <img src="'; if (helper = helpers.goodsImgUrl) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.goodsImgUrl; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '">\r\n </div>\r\n <div class="goods-list-description">\r\n <div class="goods-list-title color-gray">\r\n <i class="iconfont fz18 color-orange mr5">&#xe646;</i>'; if (helper = helpers.goodsName) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.goodsName; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '\r\n </div>\r\n <div class="fz12 color-gray">'; if (helper = helpers.specify) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.specify; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '</div>\r\n <div class="color-gray">\r\n <span class="price mr5">๏ฟฅ'; if (helper = helpers.salePrice) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.salePrice; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '</span>\r\n <span class="color-gray fz10 line-throuth">๏ฟฅ'; if (helper = helpers.originalPrice) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.originalPrice; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '</span>\r\n </div>\r\n </div>\r\n </a>\r\n </li>\r\n <li class="goods-list-item bg-white hide ar J-view-li">\r\n <a class="f-btn f-btn-orange J-view" data-expressNo="'; if (helper = helpers.expressNo) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.expressNo; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '" data-expressCode="'; if (helper = helpers.expressCompanyName) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.expressCompanyName; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '">ๆŸฅ็œ‹็‰ฉๆต</a>\r\n </li>\r\n '; return buffer } function program7(depth0, data) { var buffer = "", stack1; buffer += "\r\n "; stack1 = helpers.each.call(depth0, depth0, { hash: {}, inverse: self.noop, fn: self.program(8, program8, data), data: data }); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n "; return buffer } function program8(depth0, data) { var buffer = "", stack1, helper, options; buffer += "\r\n "; stack1 = (helper = helpers.ifCond || depth0 && depth0.ifCond, options = { hash: {}, inverse: self.noop, fn: self.program(9, program9, data), data: data }, helper ? helper.call(depth0, data == null || data === false ? data : data.key, "==", "N", options) : helperMissing.call(depth0, "ifCond", data == null || data === false ? data : data.key, "==", "N", options)); if (stack1 || stack1 === 0) { buffer += stack1 } buffer += "\r\n "; return buffer } function program9(depth0, data) { var buffer = "", stack1, helper; buffer += '\r\n <li class="goods-list-item bg-white" data-id="'; if (helper = helpers.id) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.id; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '">\r\n <a external _href="/order/orderDetail.html?orderNo='; if (helper = helpers.orderNo) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.orderNo; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '">\r\n <div class="goods-list-img">\r\n <img src="'; if (helper = helpers.goodsImgUrl) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.goodsImgUrl; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '">\r\n </div>\r\n <div class="goods-list-description">\r\n <div class="goods-list-title color-gray">\r\n <i class="iconfont fz18 color-orange mr5">&#xe646;</i>'; if (helper = helpers.goodsName) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.goodsName; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '\r\n </div>\r\n <div class="fz12 color-gray">'; if (helper = helpers.specify) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.specify; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '</div>\r\n <div class="color-gray">\r\n <span class="price mr5">๏ฟฅ'; if (helper = helpers.salePrice) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.salePrice; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '</span>\r\n <span class="color-gray fz10 line-throuth">๏ฟฅ'; if (helper = helpers.originalPrice) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.originalPrice; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + "</span>\r\n </div>\r\n </div>\r\n </a>\r\n </li>\r\n "; return buffer } function program11(depth0, data) { var buffer = "", stack1, helper; buffer += '\r\n ๅทฒๅ–ๆถˆใ€€\r\n <a class="f-btn f-btn-gray J-delete" data-orderNo="'; if (helper = helpers.orderNo) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.orderNo; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '">ๅˆ ้™ค่ฎขๅ•</a>\r\n '; return buffer } function program13(depth0, data) { var buffer = "", stack1, helper; buffer += '\r\n <a class="f-btn f-btn-gray mr5 J-cancle" data-orderNo="'; if (helper = helpers.orderNo) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.orderNo; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '">ๅ–ๆถˆ่ฎขๅ•</a>\r\n <a class="f-btn f-btn-orange J-pay" data-orderNo="'; if (helper = helpers.orderNo) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.orderNo; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '" paymentType="'; if (helper = helpers.paymentType) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.paymentType; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '">็ซ‹ๅณไป˜ๆฌพ</a>\r\n '; return buffer } function program15(depth0, data) { return "\r\n ๅทฒไป˜ๆฌพ๏ผŒ็ญ‰ๅพ…ๅ–ๅฎถๅ‘่ดง\r\n " } function program17(depth0, data) { var buffer = "", stack1, helper; buffer += '\r\n ๅ–ๅฎถๅทฒๅ‘่ดง,็ญ‰ๅพ…ๆ”ถ่ดง\r\n <a class="f-btn f-btn-orange ml5 J-confirm" data-orderNo="'; if (helper = helpers.orderNo) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.orderNo; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '"> ็กฎ่ฎคๆ”ถ่ดง</a>\r\n '; return buffer } function program19(depth0, data) { var buffer = "", stack1, helper; buffer += '\r\n ไบคๆ˜“ๆˆๅŠŸ\r\n <a class="f-btn f-btn-gray mr5 J-delete" data-orderNo="'; if (helper = helpers.orderNo) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.orderNo; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '">ๅˆ ้™ค่ฎขๅ•</a>\r\n <!-- a class="f-btn f-btn-orange J-comments">่ฏ„ไปท</a -->\r\n '; return buffer } function program21(depth0, data) { return "\r\n ้€€ๆฌพ็”ณ่ฏทไธญ\r\n " } function program23(depth0, data) { return "\r\n ้€€ๆฌพๅค„็†ไธญ\r\n " } function program25(depth0, data) { var buffer = "", stack1, helper; buffer += '\r\n ้€€ๆฌพๅฎŒๆˆ\r\n <a class="f-btn f-btn-gray mr5 J-delete" data-orderNo="'; if (helper = helpers.orderNo) { stack1 = helper.call(depth0, { hash: {}, data: data }) } else { helper = depth0 && depth0.orderNo; stack1 = typeof helper === functionType ? helper.call(depth0, { hash: {}, data: data }) : helper } buffer += escapeExpression(stack1) + '">ๅˆ ้™ค่ฎขๅ•</a>\r\n '; return buffer } function program27(depth0, data) { return '\r\n <div class="no-data">\r\n <p>ๆš‚ๆ— ๆ•ฐๆฎ</p>\r\n <i class="iconfont">&#xe688;</i>\r\n </div>\r\n' } stack1 = helpers["if"].call(depth0, depth0, { hash: {}, inverse: self.program(27, program27, data), fn: self.program(1, program1, data), data: data }); if (stack1 || stack1 === 0) { return stack1 } else { return "" } }) });
import Vue from 'vue' import Vuex from 'vuex' import lazy from './mod/lazy' import storePath from './mod/store_path' Vue.use(Vuex); // ๆ•ดๅˆๅˆๅง‹็Šถๆ€ๅ’Œๅ˜ๆ›ดๅ‡ฝๆ•ฐ๏ผŒๆˆ‘ไปฌๅฐฑๅพ—ๅˆฐไบ†ๆˆ‘ไปฌๆ‰€้œ€็š„ store // ่‡ณๆญค๏ผŒ่ฟ™ไธช store ๅฐฑๅฏไปฅ่ฟžๆŽฅๅˆฐๆˆ‘ไปฌ็š„ๅบ”็”จไธญ export default new Vuex.Store({ modules: { lazy, storePath }, strict: true })
import React, { Component } from 'react'; class AccountDetails extends Component { constructor(props) { super(props); this.state = { NanoAddress: null, Amount: null }; this.onNanoAddressChanged = this.onNanoAddressChanged.bind(this); this.onAmountChanged = this.onAmountChanged.bind(this); } render() { return ( <> Current Balance: 0<br /> Pending Balance: 0.01 Details of block to receive that pending block... </> ); } } export default AccountDetails;
import { CheckIcon, CurrencyRupeeIcon } from '@heroicons/react/outline' import React from 'react' function SpecificCategory(props) { return ( <div> <div className="flex flex-col mx-4 my-4 rounded-lg shadow-lg overflow-hidden"> <div className="flex-1 flex flex-col justify-between px-6 pt-2 pb-4 bg-gray-50 space-y-6 sm:p-8 sm:pt-2"> <div className="flex justify-center"> <img className="h-24 w-24 shadow-full mt-2" src={props.product ? props.product.image : ""} /> </div> <div> <h2 className="text-gray-800 text-sm font-bold overflow-none md:truncate sm:truncate lg:truncate">{props.product ? props.product.title : ""}</h2> </div> <div className={"flex justify-center md:justify-end"}> <CurrencyRupeeIcon className="h-4 w-4 mt-1 text-gray-500" /> <p className="text-gray-600 justify-center"> {props.product ? props.product.price : ""}</p> </div> <div className="rounded-md shadow"> <a href={"#"} className="flex items-center justify-center px-5 py-3 border border-transparent text-base font-medium rounded-md text-white bg-orange-500 hover:bg-orange-600" aria-describedby="tier-standard" > <CurrencyRupeeIcon className="h-4 w-4 mt-1 text-white" />Buy Now </a> </div> </div> </div> </div> ) } export default SpecificCategory
/** * @param {number[]} A * @param {number[][]} queries * @return {number[]} */ var sumEvenAfterQueries = function(A, queries) { var sum = 0; for(let i=0;i<A.length;i++) { if(A[i]%2==0) sum += A[i]; } const arr = []; for(let i=0;i<queries.length;i++) { let index = queries[i][1]; const oldVal = A[index]; const newVal = A[index] + queries[i][0]; if(oldVal % 2 !== 0 && newVal % 2 === 0) { sum = sum + newVal; } else if(oldVal % 2 === 0 && newVal % 2 !== 0) { sum = sum - oldVal; } else if(oldVal % 2 === 0 && newVal % 2 === 0){ sum = sum - oldVal + newVal; } A[index] = newVal; arr.push(sum); } return arr; };
// ็›ดๆŽฅๅฏผๅ‡บ export const button = 'button'
var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); var bluebird = require('bluebird'); var Request = require('./request'); // var mongoose = require('mongoose'); /* * Connection stuff to help test the database connection */ // var url = "mongodb://banal:banal@ds031203.mongolab.com:31203/banal"; // mongoURI = url; // mongoose.connect("mongodb://banal:banal@ds031203.mongolab.com:31203/heroku_b2mnmqj4/"); // // Run in seperate terminal window using 'mongod' // var db = mongoose.connection; // db.on('error', console.error.bind(console, 'connection error:')); // db.once('open', function () { // console.log('Mongodb connection open'); // }); // module.exports = db; var userSchema = mongoose.Schema({ name: { type: String, required: true}, username: { type: String, required: true, index: { unique: true } }, uid: { type: String }, password: { type: String }, location: { type: String }, email: {type: String, index: { unique: true }}, talents: { type: Object} }); userSchema.statics.findAllTalents = function(name, cb){ return this.find({'name': name}, cb) } var User = mongoose.model('User', userSchema); User.comparePassword = function(candidatePassword, savedPassword, cb) { bcrypt.compare(candidatePassword, savedPassword, function(err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); }; userSchema.pre('save', function(next){ var cipher = bluebird.promisify(bcrypt.hash); return cipher(this.password, null, null).bind(this) .then(function(hash) { this.password = hash; next(); }); }); User.getAllTalents = function(talent, callback){ } User.getTalents = function(talent, callback){ } module.exports = User; // var patrick = new User({ // username: "Patrick2", // password: "Test", // location: "Hawaii", // email: "Pavtran2@gmail.com", // talent: {'Piano': 2} // }) // console.log(patrick); // patrick.save(function(err){ // if(err) console.log(err); // console.log('successful!'); // }) // (User.find(function(err, results){ // console.log(results); // }));
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Modal } from 'reactstrap'; import Carousel from '@brainhubeu/react-carousel'; import ChevronLeftIcon from 'mdi-react/ChevronLeftIcon'; import ChevronRightIcon from 'mdi-react/ChevronRightIcon'; import '@brainhubeu/react-carousel/lib/style.css'; export default class Gallery extends Component { static propTypes = { images: PropTypes.arrayOf(PropTypes.shape({ src: PropTypes.string, type: PropTypes.string, alt: PropTypes.string, })).isRequired, tags: PropTypes.arrayOf(PropTypes.shape({ tag: PropTypes.string, title: PropTypes.string, })).isRequired, }; constructor(props) { super(props); this.state = { images: props.images, currentTag: 'all', tags: props.tags, lightboxIsOpen: false, currentImage: 0, carouselImages: [], }; } onFilter = (tag) => { const { images } = this.props; const image = images; if (tag === 'all') { this.setState({ images: image, currentTag: 'all', }); } else { this.setState({ images: image.filter(t => t.type === tag), currentTag: tag, }); } }; openLightbox = (index, event) => { event.preventDefault(); this.carouselImages(); this.setState({ currentImage: index, lightboxIsOpen: true, }); }; closeLightbox = () => { this.setState({ currentImage: 0, lightboxIsOpen: false, }); }; onChange = (value) => { this.setState({ currentImage: value }); }; carouselImages = () => { const { images } = this.state; this.setState({ carouselImages: images.map(item => item.src), }); }; render() { const { currentImage, lightboxIsOpen, tags, images, currentTag, carouselImages, } = this.state; return ( <div className="gallery"> <div className="gallery__btns"> <button type="button" className={`gallery__btn${currentTag === 'all' ? ' gallery__btn--active' : ''}`} onClick={e => this.onFilter('all', e)} > all </button> {tags.map(btn => ( <button type="button" className={`gallery__btn${btn.tag === currentTag ? ' gallery__btn--active' : ''}`} key={btn} onClick={e => this.onFilter(btn.tag, e)} > {btn.title} </button> ))} </div> {images.map((img, index) => ( <button className="gallery__img-wrap" key={img} onClick={event => this.openLightbox(index, event)} > <img src={img.src} alt={img.alt} /> </button> ))} <Modal isOpen={lightboxIsOpen} toggle={this.closeLightbox} className="modal-dialog--primary modal-dialog--carousel" > <div className="modal__body"> <div className="modal__header"> <button className="lnr lnr-cross modal__close-btn" type="button" onClick={this.closeLightbox} /> </div> <Carousel value={currentImage} onChange={this.onChange} slides={ carouselImages.map(item => ( <img src={item} alt="" /> ))} addArrowClickHandler arrowLeft={ <div className="modal__btn"> <ChevronLeftIcon className="modal__btn_left" /> </div>} arrowRight={ <div className="modal__btn"> <ChevronRightIcon className="modal__btn_right" /> </div>} /> <div className="modal__footer"> <p>{currentImage + 1} of {carouselImages.length}</p> </div> </div> </Modal> </div> ); } }
const Checkout = require('../../src/core/checkout'); describe('checkout', () => { it('calculates total as 0 when no products added', async () => { const checkout = new Checkout({}); const total = await checkout.total(); expect(total).to.equal(0); }); it('calculates total when no price rules given', async () => { const productsStore = { fetchById: sinon.stub() }; productsStore.fetchById.withArgs('A').returns(Promise.resolve({id: 'A', price: 100})); productsStore.fetchById.withArgs('B').returns(Promise.resolve({id: 'B', price: 200})); productsStore.fetchById.withArgs('C').returns(Promise.resolve({id: 'C', price: 300})); const checkout = new Checkout({productsStore}); await checkout.add('A'); await checkout.add('C'); await checkout.add('A'); const total = await checkout.total(); expect(total).to.equal(500); }); it('calculates total by applying price rules', async () => { const productsStore = { fetchById: sinon.stub() }; productsStore.fetchById.withArgs('A').returns(Promise.resolve({id: 'A', price: 100})); productsStore.fetchById.withArgs('B').returns(Promise.resolve({id: 'B', price: 200})); productsStore.fetchById.withArgs('C').returns(Promise.resolve({id: 'C', price: 300})); const priceRules = [ createFixedPriceRule('A', 50), createFixedPriceRule('C', 100) ] const checkout = new Checkout({productsStore, priceRules}); await checkout.add('A'); await checkout.add('C'); await checkout.add('A'); const total = await checkout.total(); expect(total).to.equal(200); }); function createFixedPriceRule(productId, price) { return { apply: async (pricingContext) => { const item = pricingContext.checkoutItems[productId]; if (!item) return; const adjustAmount = (item.qty * price) - item.total(); pricingContext.addProductAdjustment(productId, adjustAmount) } } } });
let products = [ { id: 'tt0107048', name: 'Groundhog Day', runtime: 101, description: 'A weatherman finds himself inexplicably living the same day over and over again.', rating: 8, price: 2, image: 'https://m.media-amazon.com/images/M/MV5BZWIxNzM5YzQtY2FmMS00Yjc3LWI1ZjUtNGVjMjMzZTIxZTIxXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_UX182_CR0,0,182,268_AL_.jpg', year: 1993, }, { id: 'tt0088763', name: 'Back to the Future', runtime: 116, description: 'Marty McFly, a 17-year-old high school student, is accidentally sent thirty years into the past in a time-traveling DeLorean invented by his close friend, the maverick scientist Doc Brown.', rating: 8.5, price: 1.5, image: 'https://m.media-amazon.com/images/M/MV5BZmU0M2Y1OGUtZjIxNi00ZjBkLTg1MjgtOWIyNThiZWIwYjRiXkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_UX182_CR0,0,182,268_AL_.jpg', year: 1985, }, { id: 'tt0286112', name: 'Shaolin Soccer', runtime: 113, description: 'A young Shaolin follower reunites with his discouraged brothers to form a soccer team using their martial art skills to their advantage.', rating: 7.3, price: 1, image: 'https://m.media-amazon.com/images/M/MV5BZjdiYTBiMDUtNTg0Yy00N2NhLWIxZmEtMTEwNDNlYzRkMGY3L2ltYWdlXkEyXkFqcGdeQXVyNTAyODkwOQ@@._V1_UY268_CR15,0,182,268_AL_.jpg', year: 2001, }, { id: 'tt0093779', name: 'The Princess Bride', runtime: 98, description: 'While home sick in bed, a young boy\'s grandfather reads him a story called The Princess Bride.', rating: 8.1, price: 1, image: 'https://m.media-amazon.com/images/M/MV5BMGM4M2Q5N2MtNThkZS00NTc1LTk1NTItNWEyZjJjNDRmNDk5XkEyXkFqcGdeQXVyMjA0MDQ0Mjc@._V1_UX182_CR0,0,182,268_AL_.jpg', year: 1987, }, ]; export default products;
const { resolve } = require('path') module.exports = { rootDir: resolve(__dirname, '..'), buildDir: resolve(__dirname, '.nuxt'), head: { title: 'nuxt-gtm-module' }, srcDir: __dirname, render: { resourceHints: false }, modules: [ { handler: require('../') } ], plugins: [ '~/plugins/gtm' ], gtm: { id: process.env.GTM_ID || 'GTM-KLQB72K', scriptDefer: true, pageTracking: true, // layer: 'test', variables: { test: '1' } }, publicRuntimeConfig: { gtm: { id: 'GTM-KLQB72K&runtime' } } }
import React, { Component } from 'react'; import { graphql } from 'react-apollo'; import { Container, Grid, Image, Button, Icon, Tab } from 'semantic-ui-react'; import { Link } from 'react-router-dom'; import moment from 'moment'; import { QueryGetLoggedUserInfo } from '../GraphQL'; import UserPosts from '../Components/UserPosts'; import Following from '../Components/Following'; import Followers from '../Components/Followers'; const panes = [ { menuItem: 'My Posts', render: () => <UserPosts /> }, { menuItem: 'Followers', render: () => <Followers /> }, { menuItem: 'Following', render: () => <Following /> }, ] class ProfilePage extends Component { constructor(props) { super(props) this.state = { username: '', name: '', bio: '', email: '', phoneNumber: '', gender: '', country: '', profilePic: null, followingCount: 0, followersCount: 0, postsCount: 0 } } componentWillReceiveProps(newProps){ this.setState({ ...newProps }) } getUrl = (file) => { try { if (file) { const { bucket, region, key } = file; const url = `https://s3-${region}.amazonaws.com/${bucket}/${key}`; return url; } return null; } catch (err) { console.error(err); } } render() { const { username, bio, profilePic, createdAt, followingCount, followersCount, postsCount } = this.state const imageUrl = profilePic ? this.getUrl(profilePic) : null const joinedTime = createdAt ? moment(parseInt(createdAt, 10)).format("DD MMMM YYYY") : null return ( <Container text> <Grid columns={2}> <Grid.Column width={4}> <Image circular src={imageUrl} /> </Grid.Column> <Grid.Column width={12}> <div style={{ padding:'10px' }}> <div style={{ fontSize:'1.5em', marginBottom:'8px' }}> {username} &nbsp; <Button icon labelPosition='left' as={ Link } to='/account/edit' ><Icon name='settings' />Account Settings</Button> </div> <div style={{ color: 'rgba(0,0,0,.4)', marginBottom:'5px', fontSize: '1em' }}>Joined since {joinedTime}</div> <div style={{ marginBottom:'15px' }}> <div style={{ display:'inline', marginRight: '1em' }}><b>{postsCount}</b> posts</div> <div style={{ display:'inline', marginRight: '1em' }}><b>{followersCount}</b> followers</div> <div style={{ display:'inline' }}><b>{followingCount}</b> following</div> </div> <div> {bio} </div> </div> </Grid.Column> </Grid> <br /> <Tab menu={{ secondary: true, pointing: true }} panes={panes} /> </Container> ) } } export default graphql( QueryGetLoggedUserInfo, { options: { fetchPolicy: 'cache-and-network', }, props: (props) => { return { ...props.data.getLoggedUserInfo } } } )(ProfilePage);
/** * @author Piyush Shrivastava */ var appModule = angular.module("appModule", ['ngRoute', 'ui.bootstrap', 'ngSanitize']); appModule.config(function ($routeProvider, $locationProvider) { $locationProvider.hashPrefix(''); $routeProvider. when('/', { templateUrl: 'view/home.html', controller: 'HomeController' }). when('/skills', { templateUrl: 'view/skills.html', controller: 'SkillsController' }). when('/experience', { templateUrl: 'view/experience.html', controller: 'ExperienceController' }). when('/projects', { templateUrl: 'view/projects.html', controller: 'ProjectsController' }). when('/education', { templateUrl: 'view/education.html', controller: 'EducationController' }). when('/achievements', { templateUrl: 'view/achievements.html', controller: 'AchievementsController' }). when('/personal-info', { templateUrl: 'view/personal-info.html', controller: 'PersonalInfoController' }). when('/resume', { templateUrl: 'view/resume.html', controller: 'ResumeController' }). otherwise({ redirectTo: '/' }); });
/** * Created by intralizee on 2016-06-07. */ var bcrypt = require('bcryptjs'); var User = require('../utils/db').User; //-| create user 'added to [users] collection' |---| module.exports.create = function create(user, cb) { let dbUser = new User({ username : user.username, password : hash(user.password), contact : { email : user.email } }); dbUser.save(function (err) { if (err) cb(err); else cb(null, dbUser); }); }; //-| remove |------------------------------------| module.exports.remove = function remove(id, cb) { User.remove({_id: id}, function(err) { cb(err); }); }; //-| register |----------------------------------------| module.exports.register = function register(user, cb) { if (user.username == null || user.email == null || user.password == null || user.username == '' || user.email == '' || user.password == '') cb('error'); else { User.findOne({'contact.email': user.email}, function (err, dbUser) { if (err) return cb(err); if (dbUser) cb(null, 'email already exists error'); else { User.findOne({username: user.username}, function (err, dbUser) { if (err) return cb(err); if (dbUser) cb(null, 'user already exists error'); else cb(); }); } }); } }; //-| authenticate |--------------------------------------------| module.exports.authenticate = function authenticate(user, cb) { User.findOne({username: user.username}, '-location -contact -__v', function (err, dbUser) { if (err) cb(err); else if (dbUser && bcrypt.compareSync(user.password, dbUser.password)) { storeLoginInformation(dbUser, user.ip); cb(null, dbUser); } else cb(null); } ); }; //-| get user by id |----------------------| module.exports.get = function get(id, cb) { User.findOne({_id: id}, function (err, user) { if (err) cb(err); else cb(user); }); }; //-| get all users |-------------------| module.exports.all = function all(cb) { User.find({}, function(err, users) { if (err) cb(err); else cb(users); }); }; //-| hash data 'a string' |--------| function hash(data) { return bcrypt.hashSync(data, 8); } //-| store user IP Address and time of login. |-----------------| function storeLoginInformation(user, ip) { if (user.info.ip.login.now != null) user.info.ip.previous = user.info.ip.now; if (user.info.date.login.now != null) user.info.date.login.previous = user.info.date.login.now; user.info.date.login.now = Date.now(); user.info.date.login.history.push( { date: Date.now() }); user.info.ip.login.now = ip; user.info.ip.login.history.push({ ip: ip }); user.save(); }
function cron() { this.panel = { macros: function() { var content = { title : 'Liste des macros enregistrรฉes', store: Ext.data.StoreManager.lookup('DataMacros'), disableSelection: false, loadMask: true, width: '100%', icon: 'imgs/list_32x28.png', autoScroll: true, closable: false, features: [{ ftype: 'filters', encode: true, local: false, phpMode: true },{ ftype: 'groupingsummary', groupHeaderTpl: [ '{columnName}: {name} ({rows.length} commande{[values.rows.length > 1 ? "s" : ""]})'+ '<span> - <a href="#" class="buttonTpl" onclick="{rows:this.formatClick}"><span class="accept">Sรฉlectionner</span></a></span>', { formatClick: function (rows) { var id_macro = rows[0].data.id_macro; var nom = rows[0].data.nom; return "\ var form=Ext.getCmp('formAddCron').getForm();\ var values=form.getValues();\ var apply=true;\ if (values.favoris != ''){\ Ext.MessageBox.confirm('Confirmation','Vous avez dรฉjร  inscrit un Favoris, voulez-vous le remplacer par cette Macro ?', function(res) {\ if (res == 'yes') {\ form.setValues({macros:"+id_macro+",favoris:'',trame:''});\ Ext.getCmp('formCronFavorisNom').update('&nbsp;');\ Ext.getCmp('formCronMacrosNom').update('<span><i>"+nom+"</i></span>');\ }\ });\ } else if (values.trame != ''){\ Ext.MessageBox.confirm('Confirmation','Vous avez dรฉjร  inscrit une Trame, voulez-vous la remplacer par cette Macro ?', function(res) {\ if (res == 'yes') {\ form.setValues({macros:"+id_macro+",favoris:'',trame:''});\ Ext.getCmp('formCronFavorisNom').update('&nbsp;');\ Ext.getCmp('formCronMacrosNom').update('<span><i>"+nom+"</i></span>');\ }\ });\ } else {\ form.setValues({macros:"+id_macro+",favoris:'',trame:''});\ Ext.getCmp('formCronFavorisNom').update('&nbsp;');\ Ext.getCmp('formCronMacrosNom').update('<span><i>"+nom+"</i></span>');\ }\ "; } } ], hideGroupedHeader: false, startCollapsed: true, enableGroupingMenu: true }], columns: [ {text: 'Id de la Commande', dataIndex: 'id_command', width: 131, hidden: true, filter: {type: 'string'}}, {text: 'Id de la Macro', dataIndex: 'id_macro', width: 131, hidden: true, filter: {type: 'string'}}, {text: 'Nom de la Macro', dataIndex: 'nom', width: 350, hidden: true, filter: {type: 'string'}}, {text: 'Id du Favoris', dataIndex: 'id_favoris', hidden: true, width: 131, filter: {type: 'string'}}, {text: 'Nom de la Commande', dataIndex: 'nom_command', width: 200, filter: {type: 'string'}}, {text: 'Trame executรฉe', dataIndex: 'trame', width: 131, hidden: true, filter: {type: 'string'}}, {text: 'Temporisation', dataIndex: 'timing', width: 200, filter: {type: 'numeric'}, renderer: function(val) { if (val == 0) { return '<span style="font-style:italic;">Immรฉdiat</span>'; } else if (val == 1) { return '<span style="font-style:italic;">'+val+'<sup>รจre</sup> seconde</span>'; } else { return '<span style="font-style:italic;">'+val+'<sup>รจme</sup> secondes</span>'; } }} ], bbar: Ext.create('Ext.PagingToolbar', { store: Ext.data.StoreManager.lookup('DataMacros'), displayInfo: true, displayMsg: 'Liste des macros {0} - {1} de {2}', emptyMsg: "Aucune macros" }) }; return new Ext.grid.Panel(content); }, favoris: function() { var content = { id: 'winCronPanelFavoris', title : 'Liste des favoris enregistrรฉs', store: Ext.data.StoreManager.lookup('DataFavoris'), disableSelection: false, loadMask: true, width: '100%', icon: 'imgs/heart_stroke_32x28.png', autoScroll: true, closable: false, features: [{ ftype: 'filters', encode: true, local: false, phpMode: true, filters: [{ type: 'boolean', dataIndex: 'visible' }] }], columns: [ { text: 'Nom', dataIndex: 'nom', width: 390, filter: { type: 'string' } },{ text: 'Rรฉfรฉrence', dataIndex: 'id', width: 75, hidden: true, filter: { type: 'string' } },{ xtype:'actioncolumn', text: 'Sรฉlรฉction', align: 'right', width: 80, items: [{ icon: 'imgs/accept.png', tooltip: 'Sรฉlรฉctionner', handler: function(grid, rowIndex, colIndex) { var rec = grid.getStore().getAt(rowIndex); var form = Ext.getCmp('formAddCron').getForm(); var values = form.getValues(); if (values.macros != '') { Ext.MessageBox.confirm('Confirmation', 'Vous avez dรฉjร  inscrit une Macro, voulez-vous la remplacer par ce Favoris ?', function(res) { if (res == 'yes') { form.setValues({favoris:rec.get('id'),macros:'',trame:''}); Ext.getCmp('formCronFavorisNom').update('<span style="font-style:italic;">'+rec.get('nom')+'</span>'); Ext.getCmp('formCronMacrosNom').update('&nbsp;'); } }); } else if (values.trame != '') { Ext.MessageBox.confirm('Confirmation', 'Vous avez dรฉjร  inscrit une Trame, voulez-vous la remplacer par ce Favoris ?', function(res) { if (res == 'yes') { form.setValues({favoris:rec.get('id'),macros:'',trame:''}); Ext.getCmp('formCronFavorisNom').update('<span style="font-style:italic;">'+rec.get('nom')+'</span>'); Ext.getCmp('formCronMacrosNom').update('&nbsp;'); } }); } else { form.setValues({favoris:rec.get('id'),macros:'',trame:''}); Ext.getCmp('formCronFavorisNom').update('<span style="font-style:italic;">'+rec.get('nom')+'</span>'); Ext.getCmp('formCronMacrosNom').update('&nbsp;'); } } }] },{ text: 'trame', dataIndex: 'trame', width: 200, hidden: true } ], bbar: Ext.create('Ext.PagingToolbar', { store: Ext.data.StoreManager.lookup('DataFavoris'), displayInfo: true, displayMsg: 'Liste des favoris {0} - {1} de {2}', emptyMsg: "Aucun favoris" }) }; return new Ext.grid.Panel(content); }, cron: function() { var content = { id: 'panelCron', title : 'Liste des jalons enregistrรฉs', icon: 'imgs/clock_32x32.png', emptyText: 'Aucun jalon trouvรฉ', store: Ext.data.StoreManager.lookup('DataCron'), disableSelection: false, loadMask: true, width: '100%', height: 500, autoScroll: true, closable: true, selModel: { listeners: { selectionchange: function(sm, selections) { if (selections.length) { Ext.getCmp('cronsToolbarBtnDel').enable(); Ext.getCmp('cronsToolbarBtnMod').enable(); } else { Ext.getCmp('cronsToolbarBtnDel').disable(); Ext.getCmp('cronsToolbarBtnMod').disable(); } } } }, features: [{ ftype: 'filters', encode: true, local: false, phpMode: true },{ ftype: 'groupingsummary', groupHeaderTpl: '{columnName}: {name} ({rows.length} jalon{[values.rows.length > 1 ? "s" : ""]})', hideGroupedHeader: false, enableGroupingMenu: true }], columns: [ {text: 'Id Cron', dataIndex: 'id_cron', width: 131, hidden: true, filter: {type: 'string'}, tooltip:'Identifiant du Jalon'}, {text: 'Nom', dataIndex: 'nom', width: 131, filter: {type: 'string'}, tooltip:'Nom du Jalon'}, {text: 'Horodatage', dataIndex: 'readCron', width: 500, tooltip:'Horodatage complet des executions'}, {text: 'Minutes', dataIndex: 'minutes', width: 131, hidden: true, filter: {type: 'string'}, tooltip:'Selection des minutes'}, {text: 'Heures', dataIndex: 'heures', width: 131, hidden: true, filter: {type: 'string'}, tooltip:'Selection des heures'}, {text: 'Jours du mois', dataIndex: 'jour', width: 131, hidden: true, filter: {type: 'string'}, tooltip:'Selection des jours du mois'}, {text: 'Jours de la Semaine', dataIndex: 'jourSemaine', width: 131, hidden: true, filter: {type: 'string'}, tooltip:'Selection des jours de la semaine'}, {text: 'Mois', dataIndex: 'mois', width: 131, hidden: true, filter: {type: 'string'}, tooltip:'Selection des mois'}, {text: 'Id du favoris', dataIndex: 'id_favoris', width: 131, hidden: true, filter: {type: 'string'}, renderer: function(val) { if (val == 0) { return 'Aucun'; } return val; }, tooltip:'Identifiant du Favoris'}, {text: 'Nom du favoris', dataIndex: 'nom_favoris', width: 131, hidden: false, filter: {type: 'string'}, renderer: function(val) { if (val == 0) { return 'Aucun'; } return val; }, tooltip:'Nom du Favoris'}, {text: 'Id de la Macro', dataIndex: 'id_macro', width: 131, hidden: true, filter: {type: 'string'}, renderer: function(val) { if (val == 0) { return 'Aucun'; } return val; }, tooltip:'Identifiant de la Macro'}, {text: 'Nom de la Macro', dataIndex: 'nom_macro', width: 131, hidden: false, filter: {type: 'string'}, renderer: function(val) { if (val == 0) { return 'Aucun'; } return val; }, tooltip:'Nom de la Macro'}, {text: 'Trame', dataIndex: 'trame', width: 131, hidden: false, filter: {type: 'string'}, tooltip:'Trame ร  รฉxecuter'}, {text: 'Actif', dataIndex: 'active', width: 65, filter: {type: 'boolean'}, renderer: function(val) { if (val == 1) { return '<span style="color:green;"><b>OUI</b></span>'; } else { return '<span style="color:red;"><b>NON</b></span>'; } }, tooltip:'Si le Jalon est actif ou non'}, { xtype:'actioncolumn', tooltip:'Opรฉration sur le jalon', text: 'Action', width: 70, items: [{ icon: 'imgs/edit.png', tooltip: 'Editer', handler: function(grid, rowIndex, colIndex) { var rec = grid.getStore().getAt(rowIndex); cron.win.upd(rec); } },{ icon: 'imgs/delete.png', tooltip: 'Effacer', handler: function(grid, rowIndex, colIndex) { var rec = grid.getStore().getAt(rowIndex); cron.func.del(rec); } }] } ], dockedItems: [{ xtype: 'toolbar', items: [{ id:'cronsToolbarBtnAdd', icon: 'imgs/add.png', text: 'Ajouter', tooltip:'Ajouter un jalon', disabled: false, handler: function(widget, event) { cron.win.add(); } },{ id:'cronsToolbarBtnMod', icon: 'imgs/edit.png', text: 'Editer', tooltip:'Editer le jalon', disabled: true, handler: function(widget, event) { var rec = Ext.getCmp('panelCron').getSelectionModel().getSelection()[0]; cron.win.upd(rec); } },{ id:'cronsToolbarBtnDel', icon: 'imgs/delete.png', text: 'Effacer', tooltip:'Effacer le jalon', disabled: true, handler: function(widget, event) { var rec = Ext.getCmp('panelCron').getSelectionModel().getSelection()[0]; cron.func.del(rec); } }] }], bbar: Ext.create('Ext.PagingToolbar', { store: Ext.data.StoreManager.lookup('DataCron'), displayInfo: true, displayMsg: 'Liste des jalons {0} - {1} de {2}', emptyMsg: "Aucun jalon" }) }; return new Ext.grid.Panel(content); } }, this.win = { add: function() { var winCron = Ext.getCmp('winCron'); if (!winCron) { winCron = Ext.create('Ext.window.Window', { xtype: 'form', id: 'winCron', icon: 'imgs/clock_alt_fill_32x32.png', items: [{ xtype: 'form', id: 'formAddCron', items: [cron.form.ref, cron.form.date, cron.form.action()] }], buttons: [{ text: 'Effacer', id: 'winCronBtnClear', handler: function() { Ext.getCmp('formCronFavorisNom').update('&nbsp;'); Ext.getCmp('formCronMacrosNom').update('&nbsp;'); Ext.getCmp('formAddCron').getForm().reset(); } },{ text: 'Annuler', handler: function() { Ext.getCmp('winCron').close(); } },{ text: 'Enregistrer', id: 'winCronBtnSave', handler: function() { cron.func.validateAdd(); } }] }); } winCron.show(); Ext.data.StoreManager.lookup('DataFavoris').reload(); Ext.data.StoreManager.lookup('DataMacros').reload(); Ext.getCmp('formAddCron').getForm().reset(); winCron.setTitle('Ajout d\'un jalon'); Ext.getCmp('winCronBtnClear').show(); Ext.getCmp('formRefNomaddCron').enable(true); Ext.getCmp('formCronFavorisNom').update('&nbsp;'); Ext.getCmp('formCronMacrosNom').update('&nbsp;'); Ext.getCmp('winCronBtnSave').setHandler(function() { cron.func.validateAdd(); }); }, upd: function(rec) { cron.win.add(); var winCron = Ext.getCmp('winCron'); winCron.setTitle('Modification d\'un jalon'); var form = Ext.getCmp('formAddCron').getForm(); Ext.getCmp('formCronFavorisNom').update('&nbsp;'); Ext.getCmp('formCronMacrosNom').update('&nbsp;'); if (rec.get('id_favoris')!='0') { Ext.getCmp('formCronFavorisNom').update('<span><i>'+rec.get('nom_favoris')+'</i></span>'); } if (rec.get('id_macro')!='0') { Ext.getCmp('formCronMacrosNom').update('<span><i>'+rec.get('nom_macro')+'</i></span>'); } Ext.getCmp('formRefNomaddCron').disable(true); Ext.getCmp('winCronBtnClear').hide(); Ext.getCmp('winCronBtnSave').setHandler(function() { cron.func.validateUpd(); }); var active = rec.get('active')=='0'?'non':'oui'; var favoris = rec.get('id_favoris')=='0'?'':rec.get('id_favoris'); var macro = rec.get('id_macro')=='0'?'':rec.get('id_macro'); form.setValues({ nom:rec.get('nom'), minutes:rec.get('minutes'), heures:rec.get('heures'), jour:rec.get('jour'), jourSemaine:rec.get('jourSemaine'), mois:rec.get('mois'), favoris:favoris, macros:macro, trame:rec.get('trame'), active:active }); }, dayOfMonth: function() { var selectDayOfMonth = Ext.getCmp('selectDayOfMonth'); if (!selectDayOfMonth) { selectDayOfMonth = Ext.create('Ext.window.Window', { id: 'selectDayOfMonth', title: 'Selection des jours du mois', closeAction: 'destroy', listeners: { afterrender: { fn: function() { Ext.get(Ext.query('.select_day_of_month td')).on('mousedown', function(e, t, o) { Ext.get(t).toggleCls('selected_day_of_month'); }); } }, afterlayout: { fn: function() { Ext.get(Ext.query('.select_day_of_month td')).removeCls('selected_day_of_month'); } } }, items: [{ html : "<table class='select_day_of_month'><thead><tr><th colspan='7'>Cliquer pour choisir un jour</th></tr></thead><tbody>" + "<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td></tr>" + "<tr><td>8</td><td>9</td><td>10</td><td>11</td><td>12</td><td>13</td><td>14</td></tr>" + "<tr><td>15</td><td>16</td><td>17</td><td>18</td><td>19</td><td>20</td><td>21</td></tr>" + "<tr><td>22</td><td>23</td><td>24</td><td>25</td><td>26</td><td>27</td><td>28</td></tr>" + "<tr><td>29</td><td>30</td><td>31</td></tr>" + "</tbody></table>" }], buttons: [{ text: 'Tous les jours', handler: function() { Ext.get(Ext.query('.select_day_of_month td')).addCls('selected_day_of_month'); } },{ text: 'Effacer la selection', handler: function() { Ext.get(Ext.query('.select_day_of_month td')).removeCls('selected_day_of_month'); } },{ text: 'Valider', handler: function() { var elems = Ext.select('.selected_day_of_month'); var res = []; for (var elem in elems.elements) { res.push(elems.elements[elem].firstChild.data); } var ret = ''; if (res.length == 0) { Ext.Msg.show({ icon: Ext.Msg.ERROR, title: 'Erreur', buttons: Ext.Msg.OK, msg: 'Sรฉlรฉctionner au moins un jour !' }); return; } if (res.length == 31) { ret = '*'; } else { for (var i=0; res[i]; i++) { if (ret != '') { ret += ','; } if (res[i+1] == parseInt(res[i])+1 && res[i+2] == parseInt(res[i])+2) { ret += res[i]+'-'; while (res[i+1] == parseInt(res[i])+1) { i++; } } ret += res[i]; } } var form = Ext.getCmp('formAddCron').getForm(); form.setValues({jour:ret}); Ext.getCmp('selectDayOfMonth').close(); } }] }); } selectDayOfMonth.show(); }, minutes: function() { var selectMinutes = Ext.getCmp('selectMinutes'); if (!selectMinutes) { selectMinutes = Ext.create('Ext.window.Window', { id: 'selectMinutes', title: 'Selection des minutes', closeAction: 'destroy', listeners: { afterrender: { fn: function() { Ext.get(Ext.query('.select_minutes td')).on('mousedown', function(e, t, o) { Ext.get(t).toggleCls('selected_minutes'); }); } }, afterlayout: { fn: function() { Ext.get(Ext.query('.select_minutes td')).removeCls('selected_minutes'); } } }, items: [{ html : "<table class='select_minutes'><thead><tr><th colspan='10'>Cliquer pour choisir une minute</th></tr></thead><tbody>" + "<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td></tr>" + "<tr><td>11</td><td>12</td><td>13</td><td>14</td><td>15</td><td>16</td><td>17</td><td>18</td><td>19</td><td>20</td></tr>" + "<tr><td>21</td><td>22</td><td>23</td><td>24</td><td>25</td><td>26</td><td>27</td><td>28</td><td>29</td><td>30</td></tr>" + "<tr><td>31</td><td>32</td><td>33</td><td>34</td><td>35</td><td>36</td><td>37</td><td>38</td><td>39</td><td>40</td></tr>" + "<tr><td>41</td><td>42</td><td>43</td><td>44</td><td>45</td><td>46</td><td>47</td><td>48</td><td>49</td><td>50</td></tr>" + "<tr><td>51</td><td>52</td><td>53</td><td>54</td><td>55</td><td>56</td><td>57</td><td>58</td><td>59</td><td>0</td></tr>" + "</tbody></table>" }], buttons: [{ text: 'Toutes les minutes', handler: function() { Ext.get(Ext.query('.select_minutes td')).addCls('selected_minutes'); } },{ text: 'Effacer la selection', handler: function() { Ext.get(Ext.query('.select_minutes td')).removeCls('selected_minutes'); } },{ text: 'Valider', handler: function() { var elems = Ext.select('.selected_minutes'); var res = []; for (var elem in elems.elements) { res.push(elems.elements[elem].firstChild.data); } var ret = ''; if (res.length == 0) { Ext.Msg.show({ icon: Ext.Msg.ERROR, title: 'Erreur', buttons: Ext.Msg.OK, msg: 'Sรฉlรฉctionner au moins une minute !' }); return; } if (res.length == 60) { ret = '*'; } else { for (var i=0; res[i]; i++) { if (ret != '') { ret += ','; } if (res[i+1] == parseInt(res[i])+1 && res[i+2] == parseInt(res[i])+2) { ret += res[i]+'-'; while (res[i+1] == parseInt(res[i])+1) { i++; } } ret += res[i]; } } var form = Ext.getCmp('formAddCron').getForm(); form.setValues({minutes:ret}); Ext.getCmp('selectMinutes').close(); } }] }); } selectMinutes.show(); }, hours: function() { var selectHours = Ext.getCmp('selectHours'); if (!selectHours) { selectHours = Ext.create('Ext.window.Window', { id: 'selectHours', title: 'Selection des heures', closeAction: 'destroy', listeners: { afterrender: { fn: function() { Ext.get(Ext.query('.select_hours td')).on('mousedown', function(e, t, o) { Ext.get(t).toggleCls('selected_hours'); }); } }, afterlayout: { fn: function() { Ext.get(Ext.query('.select_hours td')).removeCls('selected_hours'); } } }, items: [{ html : "<table class='select_hours'><thead><tr><th colspan='12'>Cliquer pour choisir une heure</th></tr></thead><tbody>" + "<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td><td>11</td><td>12</td></tr>" + "<tr><td>13</td><td>14</td><td>15</td><td>16</td><td>17</td><td>18</td><td>19</td><td>20</td><td>21</td><td>22</td><td>23</td><td>0</td></tr>" + "</tbody></table>" }], buttons: [{ text: 'Toutes les heures', handler: function() { Ext.get(Ext.query('.select_hours td')).addCls('selected_hours'); } },{ text: 'Effacer la selection', handler: function() { Ext.get(Ext.query('.select_hours td')).removeCls('selected_hours'); } },{ text: 'Valider', handler: function() { var elems = Ext.select('.selected_hours'); var res = []; for (var elem in elems.elements) { res.push(elems.elements[elem].firstChild.data); } var ret = ''; if (res.length == 0) { Ext.Msg.show({ icon: Ext.Msg.ERROR, title: 'Erreur', buttons: Ext.Msg.OK, msg: 'Sรฉlรฉctionner au moins une heure !' }); return; } if (res.length == 24) { ret = '*'; } else { for (var i=0; res[i]; i++) { if (ret != '') { ret += ','; } if (res[i+1] == parseInt(res[i])+1 && res[i+2] == parseInt(res[i])+2) { ret += res[i]+'-'; while (res[i+1] == parseInt(res[i])+1) { i++; } } ret += res[i]; } } var form = Ext.getCmp('formAddCron').getForm(); form.setValues({heures:ret}); Ext.getCmp('selectHours').close(); } }] }); } selectHours.show(); }, dayOfWeek: function() { var dayToNumber = { 'Lundi':1, 'Mardi':2, 'Mercredi':3, 'Jeudi':4, 'Vendredi':5, 'Samedi':6, 'Dimanche':7 }; var selectDayOfWeek = Ext.getCmp('selectDayOfWeek'); if (!selectDayOfWeek) { selectDayOfWeek = Ext.create('Ext.window.Window', { id: 'selectDayOfWeek', title: 'Selection des jours de la semaine', closeAction: 'destroy', listeners: { afterrender: { fn: function() { Ext.get(Ext.query('.select_day_of_week td')).on('mousedown', function(e, t, o) { Ext.get(t).toggleCls('selected_day_of_week'); }); } }, afterlayout: { fn: function() { Ext.get(Ext.query('.select_day_of_week td')).removeCls('selected_day_of_week'); } } }, items: [{ html : "<table class='select_day_of_week'><thead><tr><th colspan='5'>Cliquer pour choisir le jour</th></tr></thead><tbody>" + "<tr><td>Lundi</td><td>Mardi</td><td>Mercredi</td><td>Jeudi</td><td>Vendredi</td></tr>" + "<tr><td>Samedi</td><td>Dimanche</td></tr>" + "</tbody></table>" }], buttons: [{ text: 'Toutes les jours', handler: function() { Ext.get(Ext.query('.select_day_of_week td')).addCls('selected_day_of_week'); } },{ text: 'Effacer la selection', handler: function() { Ext.get(Ext.query('.select_day_of_week td')).removeCls('selected_day_of_week'); } },{ text: 'Valider', handler: function() { var elems = Ext.select('.selected_day_of_week'); var res = []; for (var elem in elems.elements) { var dayNum = dayToNumber[elems.elements[elem].firstChild.data]; res.push(dayNum); } var ret = ''; if (res.length == 0) { Ext.Msg.show({ icon: Ext.Msg.ERROR, title: 'Erreur', buttons: Ext.Msg.OK, msg: 'Sรฉlรฉctionner au moins un jour !' }); return; } if (res.length == 7) { ret = '*'; } else { for (var i=0; res[i]; i++) { if (ret != '') { ret += ','; } if (res[i+1] == parseInt(res[i])+1 && res[i+2] == parseInt(res[i])+2) { ret += res[i]+'-'; while (res[i+1] == parseInt(res[i])+1) { i++; } } ret += res[i]; } } var form = Ext.getCmp('formAddCron').getForm(); form.setValues({jourSemaine:ret}); Ext.getCmp('selectDayOfWeek').close(); } }] }); } selectDayOfWeek.show(); }, month: function() { var monthToNumber = { 'Janvier':1, 'Fรฉvrier':2, 'Mars':3, 'Avril':4, 'Mai':5, 'Juin':6, 'Juillet':7, 'Aoรปt':8, 'Septembre':9, 'Octobre':10, 'Novembre':11, 'Dรฉcembre':12 }; var selectMonth = Ext.getCmp('selectMonth'); if (!selectMonth) { selectMonth = Ext.create('Ext.window.Window', { id: 'selectMonth', title: 'Selection des mois', closeAction: 'destroy', listeners: { afterrender: { fn: function() { Ext.get(Ext.query('.select_month td')).on('mousedown', function(e, t, o) { Ext.get(t).toggleCls('selected_month'); }); } }, afterlayout: { fn: function() { Ext.get(Ext.query('.select_month td')).removeCls('selected_month'); } } }, items: [{ html : "<table class='select_month'><thead><tr><th colspan='6'>Cliquer pour choisir un mois</th></tr></thead><tbody>" + "<tr><td>Janvier</td><td>Fรฉvrier</td><td>Mars</td><td>Avril</td><td>Mai</td><td>Juin</td></tr>" + "<tr><td>Juillet</td><td>Aoรปt</td><td>Septembre</td><td>Octobre</td><td>Novembre</td><td>Dรฉcembre</td></tr>" + "</tbody></table>" }], buttons: [{ text: 'Tous les mois', handler: function() { Ext.get(Ext.query('.select_month td')).addCls('selected_month'); } },{ text: 'Effacer la selection', handler: function() { Ext.get(Ext.query('.select_month td')).removeCls('selected_month'); } },{ text: 'Valider', handler: function() { var elems = Ext.select('.selected_month'); var res = []; for (var elem in elems.elements) { var monthNum = monthToNumber[elems.elements[elem].firstChild.data]; res.push(monthNum); } var ret = ''; if (res.length == 0) { Ext.Msg.show({ icon: Ext.Msg.ERROR, title: 'Erreur', buttons: Ext.Msg.OK, msg: 'Sรฉlรฉctionner au moins un mois !' }); return; } if (res.length == 12) { ret = '*'; } else { for (var i=0; res[i]; i++) { if (ret != '') { ret += ','; } if (res[i+1] == parseInt(res[i])+1 && res[i+2] == parseInt(res[i])+2) { ret += res[i]+'-'; while (res[i+1] == parseInt(res[i])+1) { i++; } } ret += res[i]; } } var form = Ext.getCmp('formAddCron').getForm(); form.setValues({mois:ret}); Ext.getCmp('selectMonth').close(); } }] }); } selectMonth.show(); } }; this.form = { ref: { xtype: 'fieldset', title: 'Rรฉfรฉrence du Jalon', collapsible: true, defaults: { width: 500, columns: 4 }, items: [{ xtype: 'textfield', id: 'formRefNomaddCron', name: 'nom', fieldLabel: 'Nom', msgTarget: 'side', allowBlank: false },{ xtype: 'radiogroup', fieldLabel: 'Activation', items: [{ xtype: 'radiofield', name: 'active', inputValue: 'oui', checked: true, boxLabel: 'oui' },{ xtype: 'radiofield', name: 'active', inputValue: 'non', boxLabel: 'non' }] }] }, date: { xtype: 'fieldset', title: 'Horodatage du Jalon', collapsible: true, defaults: { width: 500, layout: { type: 'hbox', defaultMargins: {top: 0, right: 5, bottom: 0, left: 0} } }, items: [{ xtype: 'fieldcontainer', items: [{ xtype: 'textfield', flex: 4, name: 'minutes', id: 'minutes', fieldLabel: 'Minutes', msgTarget: 'side', labelWidth: 120, allowBlank: false },{ xtype: 'button', flex: 1, text: 'Sรฉlรฉction', icon: 'imgs/accept.png', iconAlign: 'left', tooltip: 'Selection des minutes', handler: function() { cron.win.minutes(); } }] },{ xtype: 'fieldcontainer', items: [{ xtype: 'textfield', flex: 4, name: 'heures', id: 'heures', fieldLabel: 'Heures', msgTarget: 'side', labelWidth: 120, allowBlank: false },{ xtype: 'button', flex: 1, text: 'Sรฉlรฉction', icon: 'imgs/accept.png', iconAlign: 'left', tooltip: 'Selection des heures', handler: function() { cron.win.hours(); } }] },{ xtype: 'fieldcontainer', items: [{ xtype: 'textfield', flex: 4, name: 'jour', id: 'jour', fieldLabel: 'Jours du mois', msgTarget: 'side', labelWidth: 120, allowBlank: false },{ xtype: 'button', flex: 1, text: 'Sรฉlรฉction', icon: 'imgs/accept.png', iconAlign: 'left', tooltip: 'Selection des jours du mois', handler: function() { cron.win.dayOfMonth(); } }] },{ xtype: 'fieldcontainer', items: [{ xtype: 'textfield', flex: 4, name: 'jourSemaine', id: 'jourSemaine', fieldLabel: 'Jours de la semaine', labelWidth: 120, msgTarget: 'side', allowBlank: false },{ xtype: 'button', flex: 1, text: 'Sรฉlรฉction', icon: 'imgs/accept.png', iconAlign: 'left', tooltip: 'Selection des jours de la semaine', handler: function() { cron.win.dayOfWeek(); } }] },{ xtype: 'fieldcontainer', items: [{ xtype: 'textfield', flex: 4, name: 'mois', id: 'mois', fieldLabel: 'Mois', msgTarget: 'side', labelWidth: 120, allowBlank: false },{ xtype: 'button', flex: 1, text: 'Sรฉlรฉction', icon: 'imgs/accept.png', iconAlign: 'left', tooltip: 'Selection des mois', handler: function() { cron.win.month(); } }] },{ xtype: 'radiogroup', fieldLabel: 'Soleil', items: [{ xtype: 'radiofield', name: 'sun', inputValue: 'none', checked: true, boxLabel: 'Non', listeners: { change: function (cb, nv, ov) { if (nv) { Ext.getCmp('minutes').enable(); Ext.getCmp('heures').enable(); Ext.getCmp('jour').enable(); Ext.getCmp('jourSemaine').enable(); Ext.getCmp('mois').enable(); var form = Ext.getCmp('formAddCron').getForm(); form.setValues({ minutes:'', heures:'', jour:'', jourSemaine:'', mois:'', }); } } } },{ xtype: 'radiofield', name: 'sun', inputValue: 'sunset', boxLabel: 'Coucher', listeners: { change: function (cb, nv, ov) { if (nv) { Ext.getCmp('minutes').disable(); Ext.getCmp('heures').disable(); Ext.getCmp('jour').disable(); Ext.getCmp('jourSemaine').disable(); Ext.getCmp('mois').disable(); var form = Ext.getCmp('formAddCron').getForm(); form.setValues({ minutes:'0', heures:'*', jour:'*', jourSemaine:'*', mois:'*', }); } } } },{ xtype: 'radiofield', name: 'sun', inputValue: 'sunrise', boxLabel: 'Lever', listeners: { change: function (cb, nv, ov) { if (nv) { Ext.getCmp('minutes').disable(); Ext.getCmp('heures').disable(); Ext.getCmp('jour').disable(); Ext.getCmp('jourSemaine').disable(); Ext.getCmp('mois').disable(); var form = Ext.getCmp('formAddCron').getForm(); form.setValues({ minutes:'0', heures:'*', jour:'*', jourSemaine:'*', mois:'*', }); } } } }] }] }, action: function() { var content = { title: 'Action du Jalon', collapsible: true, items: [{ xtype: 'tabpanel', plain:true, width:500, items: [{ title: 'Favoris', id: 'formAddCronTabFavoris', items: [{ xtype: 'fieldset', padding: 0, margin: 0, border: 0, defaults: { layout: 'hbox', padding: 0, margin: 0 }, items: [ { xtype: 'fieldcontainer', margin: 5, items: [{ xtype: 'textfield', flex: 2, fieldLabel: 'Rรฉfรฉrence du Favoris', msgTarget: 'side', labelWidth : 120, name: 'favoris', allowBlank: true },{ xtype: 'box', id: 'formCronFavorisNom', flex: 2, border: 0, margin: 2, html: '' },{ xtype: 'button', margin: '0 0 0 5', flex: 1, icon: 'imgs/delete.png', iconAlign: 'left', text: 'Effacer', tooltip: 'Efface la selection du favoris en cours', handler: function() { Ext.getCmp('formAddCron').getForm().setValues({favoris:null}); Ext.getCmp('formCronFavorisNom').update('&nbsp;'); } }] },{ xtype: 'fieldcontainer', items: [ cron.panel.favoris() ] } ] } ] },{ title: 'Macros', id: 'formAddCronTabMacros', items: [{ xtype: 'fieldset', padding: 0, margin: 0, border: 0, defaults: { layout: 'hbox', padding: 0, margin: 0 }, items: [ { xtype: 'fieldcontainer', margin: 5, items: [{ xtype: 'textfield', flex: 2, fieldLabel: 'Rรฉfรฉrence de la Macros', msgTarget: 'side', labelWidth : 140, name: 'macros', allowBlank: true },{ xtype: 'box', id: 'formCronMacrosNom', flex: 2, border: 0, margin: 2, html: '' },{ xtype: 'button', margin: '0 0 0 5', flex: 1, icon: 'imgs/delete.png', iconAlign: 'left', text: 'Effacer', tooltip: 'Efface la selection de la Macro en cours', handler: function() { Ext.getCmp('formAddCron').getForm().setValues({macros:null}); Ext.getCmp('formCronMacrosNom').update('&nbsp;'); } }] },{ xtype: 'fieldcontainer', items: [ cron.panel.macros() ] } ] } ] },{ title: 'Trame', id: 'formAddCronTabTrame', items: [{ xtype: 'textfield', width: 450, labelWidth: 50, padding: 10, name: 'trame', fieldLabel: 'Trame', msgTarget: 'side', allowBlank: true, listeners: { change: { fn: function(elem, new_value, old_vlaue, opts) { var form = Ext.getCmp('formAddCron').getForm(); var values = form.getValues(); if (new_value == '') { return; } if (values.macros != '') { Ext.MessageBox.confirm('Confirmation', 'Vous avez dรฉjร  inscrit une Macro, voulez-vous la remplacer par une Trame ?', function(res) { if (res == 'yes') { form.setValues({macros:'',favoris:''}); Ext.getCmp('formCronFavorisNom').update('&nbsp;'); Ext.getCmp('formCronMacrosNom').update('&nbsp;'); } else { form.setValues({trame:''}); } }); } else if (values.favoris != '') { Ext.MessageBox.confirm('Confirmation', 'Vous avez dรฉjร  inscrit un Favoris, voulez-vous le remplacer par une Trame ?', function(res) { if (res == 'yes') { form.setValues({macros:'',favoris:''}); Ext.getCmp('formCronFavorisNom').update('&nbsp;'); Ext.getCmp('formCronMacrosNom').update('&nbsp;'); } else { form.setValues({trame:''}); } }); } } } } }] }] }] }; return new Ext.form.FieldSet(content); } }; this.func = { validateAdd: function() { var form = Ext.getCmp('formAddCron').getForm(), encode = Ext.String.htmlEncode; var error = false; if (form.isValid()) { Ext.getCmp('minutes').enable(); Ext.getCmp('heures').enable(); Ext.getCmp('jour').enable(); Ext.getCmp('jourSemaine').enable(); Ext.getCmp('mois').enable(); var formValues = form.getValues(); var nom = encode(formValues.nom); var minutes = encode(formValues.minutes); var heures = encode(formValues.heures); var jour = encode(formValues.jour); var jourSemaine = encode(formValues.jourSemaine); var mois = encode(formValues.mois); var favoris = formValues.favoris||'null'; var macros = formValues.macros||'null'; var trame = formValues.trame!=''?"'"+encode(formValues.trame)+"'":'null'; var active = formValues.active=='oui'?'true':'false'; var sunset = formValues.sun=='sunset'?'true':'false'; var sunrise = formValues.sun=='sunrise'?'true':'false'; var commentaires = ''; if (favoris == 'null' && macros == 'null' && trame == 'null') { error = true; } else { var params = "'"+nom+"','"+minutes+"','"+heures+"','"+jour+"','"+jourSemaine+"','"+mois+"',"+favoris+","+macros+","+trame+","+active+","+sunset+","+sunrise+",'"+commentaires+"'"; requestCall('add_cron', params, {ok:'jalon ajoutรฉ !', error:'impossible d\'ajouter le jalon !'}, { onsuccess:function(response){ Ext.getCmp('formAddCron').getForm().reset(); Ext.getCmp('winCron').close(); Ext.data.StoreManager.lookup('DataCron').reload(); }, onfailure:function(response){ Ext.MessageBox.show({ title: 'Erreur', msg: 'Le jalon "'+formValues.nom+'" na pas pu รชtre ajoutรฉ ! Erreur de communication, rรฉessayez plus tard.', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR }); } }); } } else { error = true; } if (error) { Ext.MessageBox.show({ title: 'Erreur', msg: 'Les champs ne sont pas valides ou vous n\'avez pas choisi d\'action !', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR }); } }, validateUpd: function() { var form = Ext.getCmp('formAddCron').getForm(), encode = Ext.String.htmlEncode; var error = false; if (form.isValid()) { Ext.getCmp('minutes').enable(); Ext.getCmp('heures').enable(); Ext.getCmp('jour').enable(); Ext.getCmp('jourSemaine').enable(); Ext.getCmp('mois').enable(); Ext.getCmp('formRefNomaddCron').enable(true); var formValues = form.getValues(); var nom = encode(formValues.nom); var minutes = encode(formValues.minutes); var heures = encode(formValues.heures); var jour = encode(formValues.jour); var jourSemaine = encode(formValues.jourSemaine); var mois = encode(formValues.mois); var favoris = formValues.favoris||'null'; var macros = formValues.macros||'null'; var trame = formValues.trame!=''?"'"+encode(formValues.trame)+"'":'null'; var sunset = formValues.sun=='sunset'?'true':'false'; var sunrise = formValues.sun=='sunrise'?'true':'false'; var active = formValues.active=='oui'?'true':'false'; var commentaires = ''; if (favoris == 'null' && macros == 'null' && trame == 'null') { error = true; } else { var params = "'"+nom+"','"+minutes+"','"+heures+"','"+jour+"','"+jourSemaine+"','"+mois+"',"+favoris+","+macros+","+trame+","+active+","+sunset+","+sunrise+",'"+commentaires+"'"; requestCall('add_cron', params, {ok:'jalon modifiรฉ !', error:'impossible de modifier le jalon !'}, { onsuccess:function(response){ Ext.getCmp('formAddCron').getForm().reset(); Ext.getCmp('winCron').close(); Ext.data.StoreManager.lookup('DataCron').reload(); }, onfailure:function(response){ Ext.MessageBox.show({ title: 'Erreur', msg: 'Le jalon "'+formValues.nom+'" na pas pu รชtre modifiรฉ ! Erreur de communication, rรฉessayez plus tard.', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR }); } }); } } else { error = true; } if (error) { Ext.MessageBox.show({ title: 'Erreur', msg: 'Les champs ne sont pas valides ou vous n\'avez pas choisi d\'action !', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR }); } }, del: function(rec) { if (rec) { var id = rec.get('id_cron'); Ext.MessageBox.confirm('Confirm', 'Voulez vous vraiment supprimer le jalon <b>"'+rec.get('nom')+'"</b> ?', function(btn) { if (btn == 'yes') { requestCall('del_cron', id, {ok:'jalon รฉffacรฉ !', error:'impossible d\'รฉffacer le jalon !'}, { onsuccess:function(response){ Ext.data.StoreManager.lookup('DataCron').reload(); }, onfailure:function(response){ Ext.MessageBox.show({ title: 'Erreur', msg: 'Le jalon "'+formValues.nom+'" na pas pu รชtre effacรฉ ! Erreur de communication, rรฉessayez plus tard.', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR }); } }); } }); } }, panelList: function() { if (Ext.getCmp('panelCron')) { Ext.data.StoreManager.lookup('DataCron').reload(); } else { layout.func.clear(); layout.func.add(cron.panel.cron()); Ext.data.StoreManager.lookup('DataCron').reload(); }; } }; }; var cron = new cron();
var board = new Array(8); var remaining = []; var turn = "white"; var tried = false; for (var i = 0; i < 8; i++) { board[i] = new Array(8); } createBoard(); function createBoard() { document.writeln("<table id='board'>"); for (var i = 0; i < 8; i++) { document.writeln("<tr>"); for (var j = 0; j < 8; j++) { document.writeln("<td>"); document.writeln("<div class='cells' id='c" + i + "" + j + "' onClick='putTile(this)' onmouseover='hov(this)' onmouseout='white(this)'></div>"); document.writeln("</td>"); board[i][j] = document.getElementById("c" + i + "" + j); remaining.push(board[i][j]); } document.writeln("</tr>"); } document.writeln("</table>"); board[3][3].style.backgroundColor = "black"; board[4][4].style.backgroundColor = "black"; board[3][4].style.backgroundColor = "white"; board[4][3].style.backgroundColor = "white"; remaining.splice(remaining.indexOf(board[3][3]), 2); remaining.splice(remaining.indexOf(board[4][3]), 2); document.writeln("<div id='box'><div id='status'><h3>Turn:</h3>White<br/></div>"); document.writeln("<form><input type='button' value='No Moves??' onClick='autoMove()'/></form></div>"); } function putTile(cell) { if (!checkAdjacent(cell)) { return; } var rows = validPlacement(cell); if (rows.length == 0) { return; } cell.style.backgroundColor = turn; flipTiles(rows); changeTurn(); tried = false; remaining.splice(remaining.indexOf(cell), 1); if (remaining.length == 0) { checkWinner(); return; } } function autoMove() { var len = remaining.length; for (var i = 0; i < len; i++) { var temp = remaining[i]; putTile(temp); if (remaining.length != len) { return; } } if (tried) { checkWinner(); return; } changeTurn(); tried = true; } function flipTiles(rows) { for (var i = 0; i < rows.length; i++) { for (var j = 0; j < rows[i].length; j++) { rows[i][j].style.backgroundColor = turn; } } } function checkWinner() { var b = 0, w = 0; for (var i = 0; i < 8; i++) { for (var j = 0; j < 8; j++) { if (board[i][j].style.backgroundColor[0] == 'w') { w++; } else { b++; } } } if (b > w) { window.alert("Black win."); } else if (w > b) { window.alert("White win."); } else { window.alert("Draw."); } } function validPlacement(cell) { var r = x(cell); var c = y(cell); var rows = []; // r positive var pieces = []; for (var i = 1; i < 8; i++) { if (r + i > 7) { break; } var temp = board[r + i][c]; if (temp.style.backgroundColor[0] == opp()) { pieces.push(temp); continue; } if (temp.style.backgroundColor[0] == turn[0]) { if (pieces.length > 0) { rows.push(pieces); } } break; } // r negative pieces = []; for (var i = 1; i < 8; i++) { if (r - i < 0) { break; } var temp = board[r - i][c]; if (temp.style.backgroundColor[0] == opp()) { pieces.push(temp); continue; } if (temp.style.backgroundColor[0] == turn[0]) { if (pieces.length > 0) { rows.push(pieces); } } break; } // c positive pieces = []; for (var i = 1; i < 8; i++) { if (c + i > 7) { break; } var temp = board[r][c + i]; if (temp.style.backgroundColor[0] == opp()) { pieces.push(temp); continue; } if (temp.style.backgroundColor[0] == turn[0]) { if (pieces.length > 0) { rows.push(pieces); } } break; } // c negative pieces = []; for (var i = 1; i < 8; i++) { if (c - i < 0) { break; } var temp = board[r][c - i]; if (temp.style.backgroundColor[0] == opp()) { pieces.push(temp); continue; } if (temp.style.backgroundColor[0] == turn[0]) { if (pieces.length > 0) { rows.push(pieces); } } break; } // r pos c pos pieces = []; for (var i = 1; i < 8; i++) { if (r + i > 7 || c + i > 7) { break; } var temp = board[r + i][c + i]; if (temp.style.backgroundColor[0] == opp()) { pieces.push(temp); continue; } if (temp.style.backgroundColor[0] == turn[0]) { if (pieces.length > 0) { rows.push(pieces); } } break; } // r pos c neg pieces = []; for (var i = 1; i < 8; i++) { if (r + i > 7 || c - i < 0) { break; } var temp = board[r + i][c - i]; if (temp.style.backgroundColor[0] == opp()) { pieces.push(temp); continue; } if (temp.style.backgroundColor[0] == turn[0]) { if (pieces.length > 0) { rows.push(pieces); } } break; } // r neg c pos pieces = []; for (var i = 1; i < 8; i++) { if (r - i < 0 || c + i > 7) { break; } var temp = board[r - i][c + i]; if (temp.style.backgroundColor[0] == opp()) { pieces.push(temp); continue; } if (temp.style.backgroundColor[0] == turn[0]) { if (pieces.length > 0) { rows.push(pieces); } } break; } // r neg c neg pieces = []; for (var i = 1; i < 8; i++) { if (r - i < 0 || c - i < 0) { break; } var temp = board[r - i][c - i]; if (temp.style.backgroundColor[0] == opp()) { pieces.push(temp); continue; } if (temp.style.backgroundColor[0] == turn[0]) { if (pieces.length > 0) { rows.push(pieces); } } break; } return rows; } function changeTurn() { if (turn[0] == 'w') { turn = "black"; document.getElementById("status").innerHTML = "<h3>Turn:</h3>Black<br/>"; return; } if (turn[0] == 'b') { turn = "white"; document.getElementById("status").innerHTML = "<h3>Turn:</h3>White<br/>"; return; } } function opp() { if (turn[0] == 'w') { return 'b'; } return 'w'; } function hov(cell) { if (cell.style.backgroundColor[0] == 'b') { return; } if (cell.style.backgroundColor[0] == 'w') { return; } if (!checkAdjacent(cell)) { return; } if (turn[0] == 'w') { cell.style.backgroundColor = "rgb(147, 205, 152)"; return; } if (turn[0] == 'b') { cell.style.backgroundColor = "rgb(19, 78, 25)"; return; } } function white(cell) { if (cell.style.backgroundColor[0] == 'b') { return; } if (cell.style.backgroundColor[0] == 'w') { return; } cell.style.backgroundColor = "#389B49"; } function checkAdjacent(cell) { var r = x(cell); var c = y(cell); for (var i = -1; i <= 1; i++) { for (var j = -1; j <= 1; j++) { if (i == 0 && j == 0) { continue; } if (r + i > 7 || r + i < 0) { continue; } if (c + j > 7 || c + j < 0) { continue; } if (board[r + i][c + j].style.backgroundColor[0] == 'w') { return true; } if (board[r + i][c + j].style.backgroundColor[0] == 'b') { return true; } } } return false; } function x(cell) { return parseInt(cell.id[1]); } function y(cell) { return parseInt(cell.id[2]); }
import path from 'path'; import EventIn from '../src/common/source/EventIn'; import Logger from '../src/common/sink/Logger'; import DataToFile from '../src/node/sink/DataToFile'; ['txt', 'csv', 'json'].forEach((format) => { const eventIn = new EventIn({ frameSize: 2, frameRate: 1, frameType: 'vector', }); const dataToFile = new DataToFile({ filename: path.join(__dirname, './node_sink.DataToFile.test.' + format), format: format, }); const logger = new Logger({ data: true, }); eventIn.connect(logger); eventIn.connect(dataToFile); eventIn.start(); let time = 0; const period = 1; (function loop(){ const data = [Math.random(), Math.random()]; eventIn.process(time, data); time += period; if (time < 20) setTimeout(loop, 300); else eventIn.stop(); }()); });
const express = require('express'); const router = express.Router(); const User = require('../models/User'); const Tribe = require('../models/Tribe'); const Task = require('../models/Task'); // router.get('/task', (req, res, next) => { // Task.find() // .then(task => { // res.render("task/index", { task }); // }) // .catch(error => { // res.render("index"); // }) // }) router.get('/task/new', (req, res, next) => { res.render("task/new", { members: [ {name: 'Georges', id: '1234'}, {name: 'Janine', id: '12345'} ] }) }) router.post('/task/new', (req, res, next) => { const { task, description } = req.body; const newTask = new Task({task, description}) newTask.save() .then(task => { res.redirect('/task') }) .catch((error) => { console.log(error) }) }); // router.get('/task/:id', (req, res, next) => { // let taskId = req.params.id; // Task.findOne({'_id': taskId}) // .then(task => { // res.render("task/id", { task }) // }) // .catch(error => { // console.log(error) // }) // }); router.post('/task/:id/delete', (req, res, next) => { let taskId = req.params.id; Task.findByIdAndRemove({'_id': taskId}) .then(task => { res.redirect('/task') }) .catch((error) => { console.log(error) }) }); router.get('/task/:id/edit', (req, res, next) => { let taskId = req.params.id; task.findOne({'_id': taskId}) .then(task => { res.render("task/edit", { task }) }) .catch(error => { console.log(error) }) }); router.post('/task/:id/edit', (req, res, next) => { let taskId = req.params.id; const { name, occupation, catchPhrase } = req.body; task.update({'_id': taskId},{ $set: { name, occupation, catchPhrase } }) .then(task => { res.redirect('/task') }) .catch(error => { console.log(error) }) }); router.get('/task', (req, res, next) => { //pour afficher le detail par celebrity dans show.hbs let userId = req.params.id; User.findOne({_id: userId}) //attention syntaxe .populate ('task') .then(user => { res.render("/task/index", { user }) //attention syntaxe , ici jaune = url et celeb = info bdd }) .catch(error => { console.log(error) }) }); // User. // findOne(). // populate({ name: 'Val' } // path: 'task', // }); module.exports = router;
const greetings = ['Hi', 'Hello', "What's up"]; const people = ['Jim', 'George', 'Kelvin']; const predicates = ["how's the wife?", "how's the kids?", "please give me back the sugar you keep taking from my house this is the tenth time I've had to ask you this has got to stop."] const message = { greetings: greetings, people: people, predicates: predicates }; const getRandString = (arr) => arr[arr.length * Math.random() << 0]; const mixedMessage = () => { const greeting = getRandString(greetings); const person = getRandString(people); const predicate = getRandString(predicates); console.log(`${greeting} ${person}, ${predicate}`); }; mixedMessage();
global.moment = require('moment'); "use strict"; global.config; var setConfig = require('./config').read(configLoaded); function configLoaded(cfg) { global.config = cfg; try { var charge = require('./chargeRates'); charge.test(); } catch(e) { console.log(e.stack); } }
const express = require('express') const { getAllUsers } = require('../controllers/userController') const router = express.Router() router.get('/', async(req, res) => { try { let request = await getAllUsers(req._username) if (request) { res.status(200).json({ message: request.message }) } else { res.status(400).json({ message: request.message }) } } catch (error) { res.status(400).json({ message: "An Error occured : " + error.message }) } }) module.exports = router
const uuid = require('uuid') const { Configurator } = require('./config') describe('Configurator', () => { test('constructor with given parameters', () => { const options = { baseUrl: `http://${uuid.v4()}.localhost`, accessToken: uuid.v4() } const tested = new Configurator(options) expect(tested.baseUrl).toEqual(options.baseUrl) expect(tested.accessToken).toEqual(options.accessToken) }) describe('without environment variables', () => { let prevGrUrl = null let prevGrToken = null beforeEach(() => { prevGrUrl = process.env.GLOBAL_REGISTRY_URL prevGrToken = process.env.GLOBAL_REGISTRY_TOKEN delete process.env.GLOBAL_REGISTRY_URL delete process.env.GLOBAL_REGISTRY_TOKEN }) afterEach(() => { process.env.GLOBAL_REGISTRY_URL = prevGrUrl process.env.GLOBAL_REGISTRY_TOKEN = prevGrToken }) test('constructor with default value', () => { const options = { accessToken: uuid.v4() } const tested = new Configurator(options) expect(tested.baseUrl).toEqual('https://backend.global-registry.org') expect(tested.accessToken).toEqual(options.accessToken) }) }) describe('with environment variables', () => { beforeEach(() => { process.env.GLOBAL_REGISTRY_URL = `http://${uuid.v4()}.localhost` process.env.GLOBAL_REGISTRY_TOKEN = uuid.v4() }) afterEach(() => { delete process.env.GLOBAL_REGISTRY_URL delete process.env.GLOBAL_REGISTRY_TOKEN }) test('constructor with default value', () => { const tested = new Configurator() expect(tested.baseUrl).toEqual(process.env.GLOBAL_REGISTRY_URL) expect(tested.accessToken).toEqual(process.env.GLOBAL_REGISTRY_TOKEN) }) }) })
import React, { Component } from 'react' import Link from 'gatsby-link' import { Menu } from 'antd' import Logo from '../images/logo/rising-logo.svg'; import './navbar.scss' class Navbar extends Component { constructor(props) { super(props); this.state = { isMobileMenuOpen: false, hasHash: false }; this.handleScroll = this.handleScroll.bind(this); this.stateMenuClick = this.stateMenuClick.bind(this); } componentDidMount() { // add listener for scroll event const hashParts = window.location.hash.split("#"); if (hashParts.length > 1) { this.state.hasHash = true; const hash = hashParts[1]; let el = document .querySelector(`#${hash}`) .scrollIntoView({ behavior: "instant" }); } document.addEventListener("scroll", this.handleScroll, false); // document.addEventListener('scroll', this.addMenuActiveState, false) } stateMenuClick() { this.state.hasHash = true; } handleScroll() { const navHeight = document.querySelector(".navbar"); const headerHeight = document.querySelector(".main-header"); if (window.scrollY > 200) { navHeight.classList.add("scrolled"); navHeight.classList.remove("unscrolled"); headerHeight.classList.add("scrolled"); headerHeight.classList.remove("unscrolled"); } else { navHeight.classList.add("unscrolled"); navHeight.classList.remove("scrolled"); headerHeight.classList.add("unscrolled"); headerHeight.classList.remove("scrolled"); } } componentWillUnmount() { document.removeEventListener("scroll", this.handleScroll, false); } render() { return ( <div className="navbar container unscrolled"> <div className="logo"> <img src={Logo} className="logo-white" /> <img src={Logo} className="logo-plain" /> </div> <Menu mode="horizontal" defaultSelectedKeys={['2']} className="nav" > <Menu.Item key="1"> <Link to="/">Menu 1</Link></Menu.Item> <Menu.Item key="2"><Link to="/corporate">Menu 2</Link></Menu.Item> <Menu.Item key="3"><Link to="/projects">Menu 3</Link></Menu.Item> </Menu> </div> ) } } export default Navbar
import autobahn from "autobahn-browser"; import React from "react"; const url = "ws://my.wamp.dnp.dappnode.eth:8080/ws"; const realm = "dappnode_admin"; const Home = () => { React.useEffect(() => { const connection = new autobahn.Connection({ url, realm }); connection.onopen = session => { console.log("CONNECTED to \nurl: " + url + " \nrealm: " + realm); session .call("listPackages.dappmanager.dnp.dappnode.eth") .then(res => { res = JSON.parse(res).result.reduce((accum, curr) => { accum[curr.packageName] = curr; return accum; }, {}); console.log(res); // debugger; // this.setState({ packagesList: res || [] }); }); }; // connection closed, lost or unable to connect connection.onclose = (reason, details) => { console.error("CONNECTION_CLOSE", { reason, details }); }; connection.open(); }, []); return null; }; export default Home;
//Clase Movies, para obtener las Peliculas de Star Wars API class Movies{ constructor(){ this.path = "https://swapi.co/api/films/"; } async getMovies(){ const response = await fetch (this.path); return await ( await response.json()); } async getMoviesByID(id){ const response = await fetch(this.path+`${id}`); return await (await response.json()); } } module.exports = Movies;
var tabuleiro = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ]; function jogar(id, p1, p2){ let opcao = document.getElementById(id); let jogardor = document.getElementById("jogador1"); if (jogardor.checked){ let x = document.getElementById(id+'X'); x.style.zIndex = "4"; jogardor.checked = false; document.getElementById("jogador2").checked = true; opcao.style.pointerEvents = 'none'; tabuleiro[p1][p2] = 1; checarVencedor(); let label1 = document.getElementById("jogador1Label") label1.style.visibility = 'hidden'; let label2 = document.getElementById("jogador2Label") label2.style.visibility = 'visible'; } else { let o = document.getElementById(id+'O'); o.style.zIndex = "4"; document.getElementById("jogador1").checked = true; opcao.style.pointerEvents = 'none'; tabuleiro[p1][p2] = 2; checarVencedor(); let label1 = document.getElementById("jogador1Label") label1.style.visibility = 'visible'; let label2 = document.getElementById("jogador2Label") label2.style.visibility = 'hidden'; } } function checarVencedor(){ if((tabuleiro[0][0] == 1 && tabuleiro[0][1] == 1 && tabuleiro[0][2] == 1) || (tabuleiro[1][0] == 1 && tabuleiro[1][1] == 1 && tabuleiro[1][2] == 1) || (tabuleiro[2][0] == 1 && tabuleiro[2][1] == 1 && tabuleiro[2][2] == 1) || (tabuleiro[0][0] == 1 && tabuleiro[1][0] == 1 && tabuleiro[2][0] == 1) ||(tabuleiro[0][1] == 1 && tabuleiro[1][1] == 1 && tabuleiro[2][1] == 1) || (tabuleiro[0][2] == 1 && tabuleiro[1][2] == 1 && tabuleiro[2][2] == 1) || (tabuleiro[0][0] == 1 && tabuleiro[1][1] == 1 && tabuleiro[2][2] == 1) || (tabuleiro[0][2] == 1 && tabuleiro[1][1] == 1 && tabuleiro[2][0] == 1) ){ console.log("Jogador 1 Venceu"); document.getElementById("resultado").innerHTML = "Jogador 1 Venceu"; let pointers = document.getElementById("grid-template") pointers.style.pointerEvents = 'none'; let label2 = document.getElementById("quemJoga") label2.style.display = 'none'; } else if((tabuleiro[0][0] == 2 && tabuleiro[0][1] == 2 && tabuleiro[0][2] == 2) || (tabuleiro[1][0] == 2 && tabuleiro[1][1] == 2 && tabuleiro[1][2] == 2) || (tabuleiro[2][0] == 2 && tabuleiro[2][1] == 2 && tabuleiro[2][2] == 2) || (tabuleiro[0][0] == 2 && tabuleiro[1][0] == 2 && tabuleiro[2][0] == 2) ||(tabuleiro[0][1] == 2 && tabuleiro[1][1] == 2 && tabuleiro[2][1] == 2) || (tabuleiro[0][2] == 2 && tabuleiro[1][2] == 2 && tabuleiro[2][2] == 2) || (tabuleiro[0][0] == 2 && tabuleiro[1][1] == 2 && tabuleiro[2][2] == 2) || (tabuleiro[0][2] == 2 && tabuleiro[1][1] == 2 && tabuleiro[2][0] == 2) ){ console.log("Jogador 2 Venceu"); document.getElementById("resultado").innerHTML = "Jogador 2 Venceu"; let pointers = document.getElementById("grid-template") pointers.style.pointerEvents = 'none'; let label1 = document.getElementById("quemJoga"); label1.style.display = 'none'; } }
//import logo from './logo.svg'; import Stories, { WithSeeMore } from 'react-insta-stories' import Gallery, {Photo} from "react-photo-gallery"; import SelectedImage from "./SelectedImage"; import PhotoTile from './tile' import HorizontalScroll from 'react-scroll-horizontal' import { Alignment, Button, H5, Navbar, } from "@blueprintjs/core"; import { GoogleLogin } from 'react-google-login'; import { Card, Elevation, Spinner } from "@blueprintjs/core"; import DialogExample from './Dialog' import firebase from 'firebase'; import { render } from '@testing-library/react'; import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth'; import { photos } from "./photos"; import { ShoppingCart, Search, ExternalLink, XCircle } from 'react-feather'; import { BrowserRouter as Router, Switch, Route, useHistory, Link } from "react-router-dom"; import FeatherIcon from 'feather-icons-react'; import Carousel, { Modal, ModalGateway } from "react-images"; import React, { useState, useCallback } from "react"; import Masonry from 'react-masonry-css' import reactImageSize from 'react-image-size'; import "@blueprintjs/core/lib/css/blueprint.css"; //import "@blueprintjs/icons/lib/css/blueprint-icons.css"; import './App.css'; var firebaseConfig = { apiKey: "AIzaSyB7SnAHuew4550eCG0rAMvS3637HcYDREg", authDomain: "dryp-e44a9.firebaseapp.com", databaseURL: "https://dryp-e44a9.firebaseio.com", projectId: "dryp-e44a9", storageBucket: "dryp-e44a9.appspot.com", messagingSenderId: "SENDER_ID", appId: "1:979226334513:web:aca5a43ef25fbcdee48c10", measurementId: "G-MEASUREMENT_ID", } // Initialize Firebase firebase.initializeApp(firebaseConfig); const uiConfig = { // Popup signin flow rather than redirect flow. signInFlow: 'popup', // Redirect to /signedIn after sign in is successful. Alternatively you can provide a callbacks.signInSuccess function. signInSuccessUrl: '/', // We will display Google and Facebook as auth providers. signInOptions: [ firebase.auth.GoogleAuthProvider.PROVIDER_ID, //firebase.auth.FacebookAuthProvider.PROVIDER_ID, ], callbacks: { signInSuccessWithAuthResult: (authResult, redirectUrl) => { console.log("yo") console.log(this) console.log('signInSuccessWithAuthResult', authResult, redirectUrl); //this.props.history.push('/'); console.log("yo") return false } }, }; console.log(window.location.origin) let API_URL = (window.location.origin.includes("localhost")) ? 'http://localhost:5000' : 'https://dripp-py.herokuapp.com' API_URL = (window.location.origin.includes("gitpod")) ? 'https://5000-peach-cat-avh4l9cg.ws-us08.gitpod.io' : API_URL //API_URL = 'https://5000-peach-cat-avh4l9cg.ws-us11.gitpod.io' API_URL = 'https://dripp-py-flask-infer-ohzllhpmcq-ue.a.run.app' //API_URL = 'https://dripp-py.herokuapp.com' /* function api_url() { console.log("api_url") if(window.location.origin.includes("localhost")){ const API_URL = 'http://localhost:5000' } else { const API_URL = 'https://dripp-py.herokuapp.com' } console.log(API_URL) return API_URL } */ //function App() { class App extends React.Component { /* * Need to adjust as this only works with functional components const [currentImage, setCurrentImage] = useState(0); const [viewerIsOpen, setViewerIsOpen] = useState(false); const openLightbox = useCallback((event, { photo, index }) => { console.log("yo") setCurrentImage(index); setViewerIsOpen(true); }, []); const closeLightbox = () => { setCurrentImage(0); setViewerIsOpen(false); }; */ /* const imageRenderer = useCallback( ({ index, left, top, key, photo }) => ( <div className="yoyo"> <div>"bruh"</div> <img alt={photo.title} {...photo} /> </div> ), ); */ render() { //console.log("user",this.state.user) return ( <Router> <div style={{display:"none",position:"fixed",top:0,zIndex:100,paddingRight:10,backgroundColor:"white",width:"100%",height:60,fontWeight:"bold"}}> <a href="/" style={{textDecoration:"None"}}> <img src={"/logo2.png"} alt="Logo" style={{height:30,marginTop:10}}/> </a> <div style={{display:"inline-block",marginLeft:15,marginTop:-40}}> <Link to="/" style={{marginRight:5,textDecoration:"none",color:"black"}} >Inspiration</Link> <Link to="/" style={{marginRight:5,textDecoration:"none",color:"black"}}>Retailers</Link> <Link to="/" style={{marginRight:5,textDecoration:"none",color:"black"}}>Brands</Link> </div> <input text="text" type="text" style={{display:"block",marginLeft:"auto",marginRight:"auto",marginTop:-35,fontSize:16,padding:10,borderRadius:30,textHighlight:"none",outline:"none", width:300,backgroundColor:"#eee"}}/> <div style={{float:"right",marginTop:-30, marginRight:30}}> <ShoppingCart /> </div> </div> <MainNav /> <Switch> <Route exact path="/" component={HomeFeed}> </Route> <Route path="/@:name" component={InfluencerProfile}> </Route> <Route path="/post/:id" component={InfluencerPostDetails} > </Route> <Route path="/influencer/post"> <InfluencerPost /> </Route> <Route path="/retailer"> <About /> </Route> <Route path="/search/:query" component={SearchPage}> </Route> <Route path="/boards" component={Boards}> </Route> <Route path="/brand" > </Route> <Route path="/home"> <Home /> </Route> <Route path="/about"> <About /> </Route> <Route path="/dashboard"> <Dashboard /> </Route> </Switch> </Router> ); } } export class MainNav extends React.Component { constructor(props) { super(props) this.state = { user: null, width: 0, height: 0 } } componentDidMount() { this.updateWindowDimensions(); window.addEventListener('resize', this.updateWindowDimensions); } componentWillUnmount() { window.removeEventListener('resize', this.updateWindowDimensions); } updateWindowDimensions = () => { let width = document.querySelector("#my-extension-root").offsetWidth let height = document.querySelector("#my-extension-root").offsetHeight this.setState({ width: width, height: height }); } render() { console.log(this.state) let logoGroupStyle = (this.state.width > 500) ? {marginLeft:90} : {marginLeft:10} let rightGroupStyle = (this.state.width > 500) ? {marginRight:90} : {marginRight:10,display:"none"} let searchStyle = (this.state.width > 500) ? {marginLeft:50} : {marginLeft:50,display:"none"} return ( <Navbar style={{position:"fixed",top:0,zIndex:11}}> <Navbar.Group align={Alignment.LEFT} style={logoGroupStyle}> <Navbar.Heading> <a href="/"><img src={"https://storage.googleapis.com/dripp-public/webassets/Group%2033.png"} style={{marginTop:5, height:50}}/></a> </Navbar.Heading> </Navbar.Group> <Navbar.Group> <div className="bp3-input-group" style={searchStyle}> <form onSubmit={(e) => { e.preventDefault() console.log("submit") window.location.href = "/search/"+document.getElementById("search-input").value.replace(" ","+") }}> <input type="text" className="bp3-input bp3-large" id="search-input" placeholder="Search" large /> </form> <button className="bp3-button bp3-minimal bp3-intent-primary bp3-icon-arrow-right bp3-large"></button> </div> </Navbar.Group> <Navbar.Group align={Alignment.RIGHT} style={{margnRight:10}}> <div style={{display:"none"}}> <ShoppingCart height={20}/> <Search height={20}/> <ExternalLink height={20}/> </div> <div style={{cursor:"pointer"}} onClick={()=>{ console.log("hide") console.log(document.querySelector("#my-extension-root")) document.querySelector("#my-extension-root").style.display = "none" //$('#my-extension-root').hide() }}> <XCircle height={20}/> </div> </Navbar.Group> <Navbar.Group align={Alignment.RIGHT} style={rightGroupStyle}> <Button className="bp3-minimal bp3-large" icon="shopping-cart" text="$0.00" style={{display:"none"}}/> <Button className="bp3-minimal bp3-large" icon="bookmark" text="" onClick={() => window.location.href = "/boards"}/> <Button className="bp3-minimal bp3-large" icon="user" text="" /> {(!this.props.user) ? <StyledFirebaseAuth uiConfig={uiConfig} firebaseAuth={firebase.auth()} /> : <a onClick={() => firebase.auth().signOut() }>Sign-out</a> } {/* <GoogleLogin clientId="467393818187-jo9eqf5fu4apptd5h5gk0gp01chd0lb4.apps.googleusercontent.com" render={renderProps => ( <button onClick={renderProps.onClick} disabled={renderProps.disabled}>This is my custom Google button</button> )} buttonText="Login" onSuccess={responseGoogle} onFailure={responseGoogle} cookiePolicy={'single_host_origin'} /> */} </Navbar.Group> </Navbar> ) } } export class HomeFeed extends React.Component{ constructor(props) { super(props) this.state = { feed: [], currentImage:0, user:null, setCurrentImage:0, viewerIsOpen: false, setViewerIsOpen: false } } componentWillMount(){ window.addEventListener('scroll', (e) => { this.loadMore() }); this.authFirebaseListener = firebase.auth().onAuthStateChanged((user) => { console.log(user) this.setState({user}) this.setState({ loading: false, // For the loader maybe user, // User Details isAuth: true }); let db = firebase.firestore(); let _this = this; db.collection("Board").where("userId", "==", user.uid).get() .then(function(boards){ console.log("boards",boards) let data = [] boards.forEach((doc) => { // doc.data() is never undefined for query doc snapshots //console.log(doc.id, " => ", doc.data()); //return doc.data() let d = doc.data() d["id"] = doc.id data.push(d) }) console.log(data) _this.setState({"boards":data}) }) }); } componentWillUnmount(){ window.removeEventListener('scroll', this.loadMore); this.authFirebaseListener && this.authFirebaseListener() // Unlisten it by calling it as a function } loadMore() { if (window.innerHeight + document.documentElement.scrollTop === document.scrollingElement.scrollHeight) { this.loadData() } } async getSize(img) { let src = img.url let { width, height } = await reactImageSize(src); //console.log(width, height) return {width: width, height: height, src: src, ...img} } async loadData() { console.log(API_URL) let _this = this; let res = await fetch(`${API_URL}/rbgfeed`) let result = await res.json() //console.log(result) let feed = result.map(function(img) { //let imgSrc = img.replace("gs://","https://storage.googleapis.com/") return _this.getSize(img) }) //console.log(feed) feed = await Promise.all(feed) //console.log("feed",feed) let _feed = this.state.feed this.setState({ feed: _feed.concat(feed) }); } componentDidMount() { console.log("yo") this.loadData() } imageRenderer(index, left, top, key, photo ) { return <div>yoyo</div> } imageRenderer ({ index, left, top, key, photo }) { <SelectedImage key={key} margin={"2px"} index={index} photo={photo} left={left} top={top} /> } render(){ let { viewerIsOpen, closeLightbox, currentImage } = this.state return( <div> <div style={{paddingLeft:100,paddingRight:100,backgroundColor:"#eee",paddingTop:60}}> { (this.state.feed.length) ? <Gallery photos={this.state.feed} columns={5} margin={7} renderImage={props => { return <SelectedImage {...props} boards={this.state.boards} user={this.state.user}/> }} direction={"column"} onClick={(e, i, a) => { let inf = i.photo.src.split("/")[5] window.location.href=`/influencer/${inf}` } } /> : <div></div> } </div> <div style={{display:"none"}}> <Masonry breakpointCols={3} className="my-masonry-grid" columnClassName="my-masonry-grid_column"> {this.state.feed.map(function(img){ //console.log(img) return ( <div><img src={img.src} /> </div>) })} </Masonry> </div> <ModalGateway> {viewerIsOpen ? ( <Modal onClose={closeLightbox}> <Carousel currentIndex={currentImage} views={photos.map(x => ({ ...x, srcset: x.srcSet, caption: x.title }))} /> </Modal> ) : null} </ModalGateway> </div> ) } } const Photo1 = ({ index, onClick, photo, margin, direction, top, left, key }) => { const imgStyle = { margin: margin, display: 'block' }; if (direction === 'column') { imgStyle.position = 'absolute'; imgStyle.left = left; imgStyle.top = top; } const handleClick = event => { onClick(event, { photo, index }); }; return ( <img key={key} style={onClick ? { ...imgStyle } : imgStyle} {...photo} onClick={onClick ? handleClick : null} /> ); }; const responseGoogle = (response) => { console.log(response); } export class InfluencerProfile extends React.Component{ constructor(props) { super(props) this.state = { feed: [], currentImage:0, setCurrentImage:0, viewerIsOpen: false, setViewerIsOpen: false, currentPost: "", igPosts: [] } } async getSize(img) { let src = img.url let { width, height } = await reactImageSize(src); //console.log(width, height) return {width: width, height: height, src: src, ...img} } async loadData() { console.log(API_URL) let _this = this; let res = await fetch(`${API_URL}/inf/rbg/${this.props.match.params.name}`) let result = await res.json() let feed = result.map(function(img) { //let imgSrc = img.replace("gs://","https://storage.googleapis.com/") return _this.getSize(img) }) feed = await Promise.all(feed) let _feed = this.state.feed this.setState({ feed: _feed.concat(feed) }); } componentDidMount() { console.log("yo") this.loadData() this.loadIGPosts() } loadIGPosts(){ console.log("this props") console.log(this.props) fetch(`${API_URL}/inf/${this.props.match.params.name}`) .then(res => res.json()) .then( (result) => { console.log(result) let feed= result.map(function(img) { return { src: img, width:2, height:2, } }) console.log(feed) this.setState({ igPosts:feed }); }, // Note: it's important to handle errors here // instead of a catch() block so that we don't swallow // exceptions from actual bugs in components. (error) => { this.setState({ isLoaded: true, error }); } ) } render() { return ( <div> <br/> <br/> <br/> <div style={{paddingTop:50,paddingLeft:50}}> <div style={{height:100,width:100,borderRadius:200,display:"block"}}> <img src="https://storage.googleapis.com/dripp-pub/184601555_1414186115596009_4741948367379115170_n.jpeg" style={{height:200,borderRadius:200}}/> </div> <div style={{paddingLeft:250,marginTop:-50,marginBottom:75}}> <h2>{"@"+this.props.match.params.name}</h2> <button>Follow</button> </div> </div> <br/> <br/> {(this.state.feed.length) ? <Gallery photos={this.state.feed} columns={5} margin={7} renderImage={props => { console.log("props",props) console.log(this.state.feed) return <SelectedImage {...props} /> }} direction={"column"} onClick={(e, i, a) => { let inf = i.photo.src.split("/")[5] window.location.href=`/influencer/${inf}` } } /> : <div/> } {(this.state.igPosts.length) ? <Gallery photos={this.state.igPosts} direction={"column"} /> : <div></div>} </div> ); } } export function InfluencerPost() { return ( <div> <br/> <br/> <br/> <div style={{paddingTop:50,paddingLeft:50}}> <div style={{height:100,width:100,borderRadius:200,display:"block"}}> <img src="https://storage.googleapis.com/dripp-pub/184601555_1414186115596009_4741948367379115170_n.jpeg" style={{height:200,borderRadius:200}}/> </div> <div style={{paddingLeft:250,marginTop:-50,marginBottom:75}}> <h2>First Name, Last Name</h2> <button>Follow</button> </div> </div> <br/> <br/> <Gallery photos={photos} direction={"column"} /> </div> ); } export class InfluencerPostDetails extends React.Component { constructor(props) { super(props) this.state = { feed: [], currentImage:0, setCurrentImage:0, viewerIsOpen: false, setViewerIsOpen: false, currentPost: "", recs: [], ecom: [] } } async getSize(img) { let src = img.url let { width, height } = await reactImageSize(src); //console.log(width, height) return {width: width, height: height, src: src, ...img} } async loadData() { console.log(API_URL) let _this = this; if(this.props){ console.log("params", this.props) console.log("params", this.props.match.params.id) } let recs_req = await fetch(`${API_URL}/recs/${this.props.match.params.id}`) let result = await recs_req.json() let ecom_req = await fetch(`${API_URL}/ecom/${this.props.match.params.id}`) let ecom = await ecom_req.json() this.setState({recs: result, ecom: ecom}) let post = await fetch(`${API_URL}${window.location.pathname}`) post = await post.json() console.log("current post",post) console.log("current post",post[0]) //post = post[0] post.src = post.url post.width = "auto" post.height = "auto" this.setState({currentPost: post}) let feed = result.map(function(img) { //let imgSrc = img.replace("gs://","https://storage.googleapis.com/") return _this.getSize(img) }) feed = await Promise.all(feed) let _feed = this.state.feed this.setState({ feed: _feed.concat(feed) }); } componentDidMount() { console.log("yo") this.loadData() } render() { console.log(this.state.feed) console.log("yo",this.state.feed) let p = {} if(this.state.feed.length) { p = this.state.feed[0] p.width = 600*(p.height/p.width) p.height = 600 } else { } const child = { width: `30px`, height: `100px`,backgroundColor:"blue",margin:15} const parent = { width: `300px`, height: `100px`,backgroundColor:"blue",margin:15} return ( <div> <br/> <br/> <br/> <div style={{paddingTop:50,paddingLeft:50}}> <div style={{width:"50%",position:"relative",height:p.height,display:"block"}}> {(this.state.currentPost) ? <PhotoTile {...{photo: this.state.currentPost}} /> : <div /> } </div> <div style={{paddingLeft:0,marginTop:-550,marginBottom:75,marginLeft:350,float:"right",width:"50%"}}> <h2>Shop This Look</h2> <a href={(this.state.currentPost) ? `/@${this.state.currentPost.src.split("/")[5]}` : ""} > {(this.state.currentPost) ? `@${this.state.currentPost.src.split("/")[5]}` : ""} </a> <button>Follow</button> <br/> <br/> Tops <div style={{height:250,width:"100%",overflowX:"scroll" , display: "flex", flexWrap: "wrap", flexDirection: "column", overflowY:"hidden", overflowX: "scroll"}}> {//[...Array(15).keys()].map(function(){ this.state.ecom.slice(0, 4).map(function(item){ console.log("ecom",item) return ( <div style={{margin:5,borderRadius:5,height:250}}> <a href={item["og:url"]}> <img src={item.img_url} style={{height:200,width:"auto",borderRadius:5}}/> <h5 style={{margin:0}}>{item["og:title"]}: ${item["og:price:amount"]}</h5> <h5 style={{margin:0}}>Aritzia</h5> <div style={{display:"inline-block",margin:5, height:150,width:150,backgroundColor:"blue",visibility:"hidden"}}></div> </a> </div> ) })} </div> Bottoms <div style={{height:250,width:"100%",overflowX:"scroll" ,overflowY: "hidden", display: "flex", flexWrap: "wrap", flexDirection: "column", overflowX: "scroll"}}> {//[...Array(15).keys()].map(function(){ this.state.ecom.slice(4, 8).map(function(item){ console.log("ecom",item) return ( <div style={{margin:5,borderRadius:5,height:250}}> <a href={item["og:url"]}> <img src={item.img_url} style={{height:200,width:"auto",borderRadius:5}}/> <h5 style={{margin:0}}>{item["og:title"]}: ${item["og:price:amount"]}</h5> <h5 style={{margin:0}}>Aritzia</h5> <div style={{display:"inline-block",margin:5, height:150,width:150,backgroundColor:"blue",visibility:"hidden"}}></div> </a> </div> ) })} </div> <div> </div> </div> </div> <br/> <br/> <br/> <br/> <div style={{marginLeft:90,marginRight:90}}> {(this.state.feed.length) ? <Gallery photos={this.state.feed} columns={5} margin={7} renderImage={props => { console.log("props",props) console.log(this.state.feed) return <SelectedImage {...props} /> }} direction={"column"} onClick={(e, i, a) => { let inf = i.photo.src.split("/")[5] window.location.href=`/influencer/${inf}` } } /> : <div/> } </div> </div> ); } } export class LoginScreen extends React.Component { constructor(props) { super(props) this.state = { } } render() { return ( <div style={{overflow:"hidden"}}> <div style={{position:"absolute",zIndex:2,width:"100%"}}> <div style={{fontWeight:"black",fontFamily:"Poppins",width:"45%",float:"left", paddingLeft:100,marginTop:100}}> <img src="./Group 76.png" style={{height:50}}/> <h1 style={{fontSize:40}}>Get started with your personal shopping assistant.</h1> <h4 style={{fontFamily:"Open Sans",fontSize:24,fontWeight:100}}>Shop your favorite influencers styles</h4> <h4 style={{fontFamily:"Open Sans",fontSize:24,fontWeight:100}}>Price match similar outfits in retailer</h4> <h4 style={{fontFamily:"Open Sans",fontSize:24,fontWeight:100}}>Join the largest fashion community</h4> </div> <div style={{width:"20%",marginLeft:200,float:"left",height:300,width:400}}> <div style={{fontWeight:"800",fontStyle:"poppins",padding:50,paddingBottom:50, marginTop:130,backgroundColor:"white",boxShadow: "0px 10px 30px rgba(0, 0, 0, 0.25)", borderRadius:50}}> <AuthScreen /> </div> </div> </div> <div style={{background: "linear-gradient(89.53deg, rgba(255, 255, 255, 0.95) 45.81%, rgba(255, 255, 255, 0.1) 103.91%)", height:100,width:100,position:"absolute",top:0,left:0,zIndex:1,height:"100%",width:"100%"}}></div> <img src="./fash_pint.png" style={{filter: "blur(3px)",position:"absolute",top:0,right:0,zIndex:0,height:"100%"}}/> </div> ) } } export class PrivacyPolicy extends React.Component { constructor(props) { super(props) this.state = { } } render() { return ( <div style={{overflow:"hidden"}}> <div style={{position:"absolute",zIndex:2,width:"100%"}}> <div style={{fontWeight:"black",fontFamily:"Poppins",width:"45%",float:"left", paddingLeft:100,marginTop:100}}> <img src="./Group 76.png" style={{height:50}}/> <h1 style={{fontSize:40}}>Privacy Policy</h1> <h4 style={{fontFamily:"Open Sans",fontSize:24,fontWeight:100}}> For your consideration </h4> </div> <div style={{float:"left",width:"50%",height:"90%"}}> <div style={{fontWeight:"800",fontFamily:"Open Sans",fontWeight:100,padding:50,paddingBottom:50, marginTop:30,backgroundColor:"white",boxShadow: "0px 10px 30px rgba(0, 0, 0, 0.25)", borderRadius:50,height:700,overflow:"auto"}}> Join Dryp Privacy Policy <br/><br/> This Privacy Policy describes how your personal information is collected, used, and shared when you visit or make a purchase from joindryp.com (the โ€œSiteโ€). <br/><br/> PERSONAL INFORMATION WE COLLECT <br/><br/> When you visit the Site, we automatically collect certain information about your device, including information about your web browser, IP address, time zone, and some of the cookies that are installed on your device. Additionally, as you browse the Site, we collect information about the individual web pages or products that you view, what websites or search terms referred you to the Site, and information about how you interact with the Site. We refer to this automatically-collected information as โ€œDevice Information.โ€ <br/><br/> We collect Device Information using the following technologies: <br/><br/> - โ€œCookiesโ€ are data files that are placed on your device or computer and often include an anonymous unique identifier. For more information about cookies, and how to disable cookies, visit http://www.allaboutcookies.org. - โ€œLog filesโ€ track actions occurring on the Site, and collect data including your IP address, browser type, Internet service provider, referring/exit pages, and date/time stamps. - โ€œWeb beacons,โ€ โ€œtags,โ€ and โ€œpixelsโ€ are electronic files used to record information about how you browse the Site. <br/><br/> Additionally when you make a purchase or attempt to make a purchase through the Site, we collect certain information from you, including your name, billing address, shipping address, payment information (including credit card numbers), email address, and phone number. We refer to this information as โ€œOrder Information.โ€ <br/><br/> When we talk about โ€œPersonal Informationโ€ in this Privacy Policy, we are talking both about Device Information and Order Information. <br/><br/> HOW DO WE USE YOUR PERSONAL INFORMATION? <br/><br/> We use the Order Information that we collect generally to fulfill any orders placed through the Site (including processing your payment information, arranging for shipping, and providing you with invoices and/or order confirmations). Additionally, we use this Order Information to: Communicate with you;Screen our orders for potential risk or fraud; and When in line with the preferences you have shared with us, provide you with information or advertising relating to our products or services. <br/><br/> We use the Device Information that we collect to help us screen for potential risk and fraud (in particular, your IP address), and more generally to improve and optimize our Site (for example, by generating analytics about how our customers browse and interact with the Site, and to assess the success of our marketing and advertising campaigns). <br/><br/> We share your Personal Information with third parties to help us use your Personal Information, as described above. For example, we use Shopify to power our online store--you can read more about how Shopify uses your Personal Information here: https://www.shopify.com/legal/privacy. We also use Google Analytics to help us understand how our customers use the Site--you can read more about how Google uses your Personal Information here: https://www.google.com/intl/en/policies/privacy/. You can also opt-out of Google Analytics here: https://tools.google.com/dlpage/gaoptout. <br/><br/> Finally, we may also share your Personal Information to comply with applicable laws and regulations, to respond to a subpoena, search warrant or other lawful request for information we receive, or to otherwise protect our rights. <br/><br/> BEHAVIOURAL ADVERTISING As described above, we use your Personal Information to provide you with targeted advertisements or marketing communications we believe may be of interest to you. For more information about how targeted advertising works, you can visit the Network Advertising Initiativeโ€™s (โ€œNAIโ€) educational page at http://www.networkadvertising.org/understanding-online-advertising/how-does-it-work. <br/><br/> DO NOT TRACK Please note that we do not alter our Siteโ€™s data collection and use practices when we see a Do Not Track signal from your browser. <br/><br/> YOUR RIGHTS If you are a European resident, you have the right to access personal information we hold about you and to ask that your personal information be corrected, updated, or deleted. If you would like to exercise this right, please contact us through the contact information below.Additionally, if you are a European resident we note that we are processing your information in order to fulfill contracts we might have with you (for example if you make an order through the Site), or otherwise to pursue our legitimate business interests listed above. Additionally, please note that your information will be transferred outside of Europe, including to Canada and the United States. <br/><br/> DATA RETENTION When you place an order through the Site, we will maintain your Order Information for our records unless and until you ask us to delete this information. <br/><br/> CHANGES We may update this privacy policy from time to time in order to reflect, for example, changes to our practices or for other operational, legal or regulatory reasons.CONTACT US For more information about our privacy practices, if you have questions, or if you would like to make a complaint, please contact us by e-mail at mross@joindryp.com. <br/><br/> </div> </div> </div> <div style={{background: "linear-gradient(89.53deg, rgba(255, 255, 255, 0.95) 45.81%, rgba(255, 255, 255, 0.1) 103.91%)", height:100,width:100,position:"absolute",top:0,left:0,zIndex:1,height:"100%",width:"100%"}}></div> <img src="./fash_pint.png" style={{filter: "blur(3px)",position:"absolute",top:0,right:0,zIndex:0,height:"100%"}}/> </div> ) } } export class Template extends React.Component { constructor(props) { super(props) this.state = { } } render() { return ( <div>Test</div> ) } } export class ChromePostDetails extends React.Component { constructor(props) { super(props) this.state = { feed: [], currentImage: props.currentImage, setCurrentImage:0, viewerIsOpen: false, setViewerIsOpen: false, currentPost: "", //currentImage:"https://idsb.tmgrup.com.tr/ly/uploads/images/2020/07/08/45343.jpg", recs: [], recsPage:1, loading:true, ecom: [] } } async getSize(img) { let src = img.url let reactImageSize = (await import('react-image-size')).default let { width, height } = await reactImageSize(src); //console.log(width, height) return {width: width, height: height, src: src, ...img} } async loadEcomData() { let id = null; if(this.props.currentImage) { let params = {user: 1, url: this.props.currentImage} params = new URLSearchParams(params).toString() id = 1 this.setState({loading:true}) let ecom_req = await fetch(`${API_URL}/chrome_ecom/${id}?${params}`,) let ecom = await ecom_req.json() console.log("ecom",ecom) this.setState({ecom: ecom, loading:false}) } } async loadData() { console.log(API_URL) let _this = this; if(this.props){ console.log("params", this.props) if(this.props.match) { let id = this.props.match.params.id console.log("params1", this.props.match.params.id) } else { console.log("else") let id = this.props.query.id console.log("id",id) } } let id = null; if(this.props.match) { id = this.props.match.params.id console.log("params1", this.props.match.params.id) } else { console.log("else") id = this.props.query.id console.log("id",id) } console.log("id",id) let recs_req = await fetch(`${API_URL}/recs/${id}/${this.state.recsPage}`) let result = await recs_req.json() this.setState({recs: result}) let post = await fetch(`${API_URL}/post/${id}`) post = await post.json() //console.log("current post",post) //console.log("current post",post[0]) //post = post[0] post.src = post.url post.width = "auto" post.height = "auto" this.setState({currentPost: post}) //console.log("result",result) let feed = result.map(function(img) { //let imgSrc = img.replace("gs://","https://storage.googleapis.com/") return _this.getSize(img) }) feed = await Promise.all(feed) let _feed = this.state.feed let recsPage = this.state.recsPage recsPage = recsPage+1 console.log("Recs page",recsPage, _feed.length, feed.length) this.setState({ feed: _feed.concat(feed), loading:false, recsPage: recsPage }); } componentDidUpdate(prevProps) { // Typical usage (don't forget to compare props): console.log("did update",prevProps) //this.setState({loading:true}) if (this.props.currentImage !== prevProps.currentImage) { this.loadEcomData(); } } componentDidMount(){ //this.loadData() this.loadEcomData() console.log("yo did mount") /* window.addEventListener('scroll', (e) => { this.loadMore() }); */ document.querySelectorAll("*").forEach(element => element.addEventListener("scroll", ({target}) => console.log(target, target.id, target.parent, target.parent.id))); this.authFirebaseListener = firebase.auth().onAuthStateChanged((user) => { console.log("user",user) this.setState({user}) this.setState({ loading: false, // For the loader maybe user, // User Details isAuth: true }); let db = firebase.firestore(); let _this = this; let uid = (user) ? user.uid : null if(uid) { db.collection("Board").where("userId", "==", uid).get() .then(function(boards){ console.log("boards",boards) let data = [] boards.forEach((doc) => { // doc.data() is never undefined for query doc snapshots //console.log(doc.id, " => ", doc.data()); //return doc.data() let d = doc.data() d["id"] = doc.id data.push(d) }) console.log(data) _this.setState({"boards":data}) }) } }); } componentWillUnmount(){ console.log("unmount") window.removeEventListener('scroll', this.loadMore); this.authFirebaseListener && this.authFirebaseListener() // Unlisten it by calling it as a function } debounce(method, delay) { clearTimeout(method._tId); method._tId= setTimeout(function(){ method(); }, delay); } loadMore() { //console.log('scroll') if (window.innerHeight + document.documentElement.scrollTop === document.scrollingElement.scrollHeight) { if(!this.state.loading) { console.log("LOAD") this.setState({loading:true}) this.loadData() } } } render() { return ( <div> <br/> <br/> <div style={{fontWeight:800,fontSize:20,margin:20}}>Shop this look</div> <div style={{marginLeft:10,marginRight:20,paddingTop:0,paddingLeft:0, borderRadius: 20}} className="post-details-area"> <div style={{width:"90%",position:"relative",height:200,display:"block",backgroundColor:"#fff", borderTopLeftRadius:20,borderBottomLeftRadius:20}}> <img id="main" //alt={this.state.currentPost.title} src={this.props.currentImage} style={{boxShadow: '0px 10px 30px rgb(0 0 0 / 25%)', borderTopLeftRadius:20,borderBottomLeftRadius:20,borderRadius:20,opacity:1,top:0,left:0,zIndex:3,height:630,maxWidth:"80%",maxHeight:"100%",marginRight:"auto",marginLeft:"auto"}} /> </div> <div style={{paddingLeft:20,marginTop:-600,marginBottom:75,marginLeft:350,float:"right",width:"40%",display:"none"}}> <h2 style={{fontWeight:800,fontSize:25,paddingTop:10,paddingBottom:10}}>Chrome This Look <a style={{marginLeft:50,fontSize:20}} href={(this.state.currentPost) ? `/@${this.state.currentPost.src.split("/")[5]}` : ""} > {(this.state.currentPost) ? `@${this.state.currentPost.src.split("/")[5]}` : ""} </a> </h2> <hr style={{marginBottom:10,width:"70%"}} /> <div style={{height:250,width:"100%",overflowX:"scroll" , display: "flex", //flexWrap: "wrap", //flexDirection: "column", overflowY:"hidden", overflowX: "scroll"}}> {//[...Array(15).keys()].map(function(){ this.state.ecom.slice(0, 4).map(function(item){ console.log("ecom",item) return ( <div style={{margin:5,borderRadius:5,height:250,width:170}}> yo <a href={item["og:url"]}> <img src={item.img_url} style={{height:200,width:"auto",borderRadius:5}}/> <h5 style={{margin:0}}>{item["og:title"]}: ${item["og:price:amount"]}</h5> <h5 style={{margin:0}}>Aritzia</h5> <div style={{display:"inline-block",margin:5, height:150,width:150,backgroundColor:"blue",visibility:"hidden"}}></div> </a> </div> ) })} </div> <div style={{height:250,width:"100%",overflowX:"scroll" ,overflowY: "hidden", display: "flex", //flexWrap: "wrap", //flexDirection: "column", overflowX: "scroll"}}> {//[...Array(15).keys()].map(function(){ this.state.ecom.slice(4, 8).map(function(item){ //console.log("ecom",item) return ( <div style={{margin:5,borderRadius:5,height:250,width:170}}> <a href={item["og:url"]}> <img src={item.img_url} style={{height:200,width:"auto",borderRadius:5}}/> <div style={{height:30}}> <h5 style={{margin:0}}>{item["og:title"]}: ${item["og:price:amount"]}</h5> <h5 style={{margin:0}}>Aritzia</h5> </div> <div style={{display:"inline-block",margin:5, height:150,width:150,backgroundColor:"blue",visibility:"hidden"}}></div> </a> </div> ) })} </div> <div> </div> </div> </div> <br/> <br/> <br/> <br/> <div style={{marginLeft:0,marginRight:0,marginTop:-50}}> <div style={{fontWeight:800,fontSize:20,margin:10}}> Retailers </div> {(this.state.loading) ? <Spinner size={20} /> : <div> {this.state.ecom.slice(0, 24).map(function(item){ return ( <div style={{margin:5,borderRadius:5,height:200,width:150,display:"inline-block"}}> <a href={`${item["og:url"]}`}> <img src={item.img_url} style={{height:200,width:"auto",borderRadius:5}}/> <div style={{height:30,overflow:"hidden"}}> <h5 style={{margin:0}}>{item["og:title"]}: ${item["og:price:amount"]}</h5> <h5 style={{margin:0}}>Aritzia</h5> </div> </a> </div> ) })} </div>} {(this.state.feed.length) ? <div> <Gallery photos={this.state.feed} columns={5} margin={7} renderImage={props => { console.log("post detail", props) return <SelectedImage {...props} boards={this.state.boards} user={this.state.user}/> }} direction={"column"} onClick={(e, i, a) => { let inf = i.photo.src.split("/")[5] window.location.href=`/influencer/${inf}` } } /> <div style={{marginBottom:20,marginTop:10,visibility:(this.state.loading) ? "visible": "hidden"}}> <Spinner size={20} /> <br/><br/> </div> </div> : <div/> } </div> </div> ); } } export class SearchPage extends React.Component { constructor(props) { super(props) this.state = { feed: [], currentImage:0, setCurrentImage:0, viewerIsOpen: false, setViewerIsOpen: false, currentPost: "" } } async getSize(img) { let src = img.url let { width, height } = await reactImageSize(src); //console.log(width, height) return {width: width, height: height, src: src, ...img} } async loadData() { console.log(API_URL) let _this = this; let res = await fetch(`${API_URL}/search/${this.props.match.params.query}`) let result = await res.json() //console.log(result) let feed = result.map(function(img) { //let imgSrc = img.replace("gs://","https://storage.googleapis.com/") return _this.getSize(img) }) //console.log(feed) feed = await Promise.all(feed) //console.log("feed",feed) let _feed = this.state.feed this.setState({ feed: _feed.concat(feed) }); } componentDidMount() { this.loadData() } render() { console.log(this.props) let qry = this.props.match.params.query.replace("+"," ") return ( <div style={{marginLeft:100,marginTop:100}}> <h2>Search : {qry}</h2> {(this.state.feed.length) ? <Gallery photos={this.state.feed} columns={5} margin={7} renderImage={props => { console.log("props",props) console.log(this.state.feed) return <SelectedImage {...props} /> }} direction={"column"} onClick={(e, i, a) => { let inf = i.photo.src.split("/")[5] window.location.href=`/influencer/${inf}` } } /> : <div/> } </div> ) } } export function EcommPost() { return ( <div> <h2>EcommPost</h2> </div> ); } export function Home() { return ( <div> <h2>Home</h2> </div> ); } export class Boards extends React.Component { constructor(props) { super(props) this.state = { boards: [], userId: null } } componentWillMount() { let db = firebase.firestore(); let _this = this; firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. console.log(user) _this.setState({userId: user.uid}) db.collection("Board").where("userId", "==", user.uid).get() .then(function(boards){ console.log("boards",boards) let data = [] boards.forEach((doc) => { // doc.data() is never undefined for query doc snapshots console.log(doc.id, " => ", doc.data()); //return doc.data() data.push(doc.data()) }) console.log(data) _this.setState({"boards":data}) }) } else { // No user is signed in. } }); } addBoard(boards) { //let boards = this.state.boards //boards.push(boards) this.setState({boards}) } render() { return ( <div style={{marginTop:70,paddingLeft:110,paddingRight:100}}> <h2>Boards</h2> <DialogExample addBoard={(board) => { this.addBoard(board) }} boards={this.state.boards}/> <br/> <br/> <br/> {this.state.boards.map(function(board) { return ( <Card interactive={true} elevation={Elevation.TWO} style={{width:"25%",margin:10,display:"inline-block"}}> <h3><a href="#">{board.name}</a></h3> </Card> ) })} </div> ); } } export function About() { return ( <div> <h2>About</h2> </div> ); } export function Dashboard() { return ( <div> <h2>Dashboard</h2> </div> ); } export class AuthScreen extends React.Component { constructor(props) { super(props) this.state = { authScreen:true, login:true, signup: false } this.loginEmailInput = React.createRef(); this.loginPasswordInput = React.createRef(); this.signupEmailInput = React.createRef(); this.signupPasswordInput = React.createRef(); this.authScreen = React.createRef(); this.appScreen = React.createRef(); } render() { return ( <div ref={this.authScreen} style={{width:"100%",textAlign:"center",display:(this.state.authScreen) ? "block": "none"}}> <br/> <br/> <img src="https://storage.googleapis.com/dripp-public/webassets/Group%2033.png" style={{height:100,width:100}}/> <br/> <br/> <br/> <div style={{marginBottom:20}}> <a onClick={() => { console.log("signup") this.setState({signup:true,login:false}) }} style={{marginRight:10}}>Sign Up</a> | <a style={{marginLeft:10}} onClick={() => { console.log("login") this.setState({signup:false,login:true}) }}>Login</a> </div> <form id="login-form" style={{display:(this.state.login) ? "block" : "none"}} onSubmit={(e) => { e.preventDefault() console.log("login form submit") }}> <input ref={this.loginEmailInput} type="text" className="bp3-input bp3-large" id="search-input" placeholder="email" large /> <br/> <br/> <input ref={this.loginPasswordInput} type="password" className="bp3-input bp3-large" id="search-input" placeholder="password" large /> <br/> <br/> <br/> <button role="button" className="bp3-button bp3-primary bp3-large bp3-minimal" style={{width:100,height:30,borderRadius:5,color:"white",backgroundColor:"blue",fontWeight:"bold"}} onClick={() => { console.log(this.loginEmailInput.value) console.log(this.loginPasswordInput.value) var email = this.loginEmailInput.current.value var password = this.loginPasswordInput.current.value console.log("login",email, password) let _this = this; firebase.auth().signInWithEmailAndPassword(email, password) .then((userCredential) => { // Signed in console.log("login user", userCredential) var user = userCredential.user; localStorage.setItem('dryp-auth',JSON.stringify(userCredential)) // ... console.log("auth", _this.ref.authScreen) console.log("app",_this.ref.appScreen) _this.setState({appScreen: true, authScreen: false, user: userCredential}) }) .catch((error) => { console.log("error",error) var errorCode = error.code; var errorMessage = error.message; }); }}>LOGIN</button> </form> <form id="signup-form" style={{display:(this.state.signup) ? "block" : "none"}} onSubmit={(e) => { e.preventDefault() console.log("login") }}> <input ref={this.signupEmailInput} type="text" className="bp3-input bp3-large" id="search-input" placeholder="email" large /> <br/> <br/> <input ref={this.signupPasswordInput} type="password" className="bp3-input bp3-large" id="search-input" placeholder="password" large /> <br/> <br/> <input type="password" className="bp3-input bp3-large" id="search-input" placeholder="password" large /> <br/> <br/> <br/> <a role="button" className="bp3-button bp3-primary bp3-large bp3-minimal" style={{width:100,height:30,borderRadius:5,color:"white",backgroundColor:"blue"}} onClick={() => { console.log(this.signupEmailInput) console.log(this.signupPasswordInput) var email = this.signupEmailInput.current.value var password = this.signupPasswordInput.current.value console.log(email, password) firebase.auth().createUserWithEmailAndPassword(email, password) .then((userCredential) => { // Signed in console.log(userCredential) var user = userCredential.user; localStorage.setItem('dryp-auth',JSON.stringify(userCredential)) // ... this.setState({appScreen: true, authScreen: false, user: userCredential}) }) .catch((error) => { var errorCode = error.code; var errorMessage = error.message; // .. }); }}>SIGN UP</a> </form> </div> ) } } /* <Stories stories={stories2} defaultInterval={1500} width={432} height={768} /> */ const Story2 = ({ action, isPaused }) => { return <div style={{ ...contentStyle, background: 'Aquamarine', color: '#16161d' }}> <h1>You get the control of the story.</h1> <p>Render your custom JSX by passing just a <code style={{ fontStyle: 'italic' }}>content</code> property inside your story object.</p> <p>You get a <code style={{ fontStyle: 'italic' }}>action</code> prop as an input to your content function, that can be used to play or pause the story.</p> <h1>{isPaused ? 'Paused' : 'Playing'}</h1> <h4>v2 is out ๐ŸŽ‰</h4> <p>React Native version coming soon.</p> </div> } const stories2 = [ { content: ({ action, isPaused }) => { return <div style={contentStyle}> <h1>The new version is here.</h1> <p>This is the new story.</p> <p>Now render React components right into your stories.</p> <p>Possibilities are endless, like here - here's a code block!</p> <pre> <code style={code}> console.log('Hello, world!') </code> </pre> <p>Or here, an image!</p> <br /> <img style={image} src="https://images.unsplash.com/photo-1565506737357-af89222625ad?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1650&q=80"></img> <h3>Perfect. But there's more! โ†’</h3> </div> } }, { content: ({ action, story }) => { return <WithSeeMore story={story} action={action}><div style={{ background: 'pink', padding: 20 }}> <h1 style={{ marginTop: '100%', marginBottom: 0 }}>๐ŸŒ</h1> <h1 style={{ marginTop: 5 }}>We have our good old image and video stories, just the same.</h1> </div></WithSeeMore> }, seeMoreCollapsed: ({ toggleMore, action }) => <p style={customSeeMore} onClick={() => toggleMore(true)}>A custom See More message โ†’</p>, seeMore: ({ close }) => <div style={{ maxWidth: '100%', height: '100%', padding: 40, background: 'white' }}><h2>Just checking the see more feature.</h2><p style={{ textDecoration: 'underline' }} onClick={close}>Go on, close this popup.</p></div>, duration: 5000 }, { url: 'https://picsum.photos/1080/1920', seeMore: ({ close }) => <div style={{ maxWidth: '100%', height: '100%', padding: 40, background: 'white' }}><h2>Just checking the see more feature.</h2><p style={{ textDecoration: 'underline' }} onClick={close}>Go on, close this popup.</p></div> }, { url: 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4', type: 'video' }, { content: Story2 } ] const image = { display: 'block', maxWidth: '100%', borderRadius: 4, } const code = { background: '#eee', padding: '5px 10px', borderRadius: '4px', color: '#333' } const contentStyle = { background: 'salmon', width: '100%', padding: 20, color: 'white' } const customSeeMore = { textAlign: 'center', fontSize: 14, bottom: 20, position: 'relative' } export default App;
function onProcessPreE() { var rowCount = G_GRDMASTERE.data.getLength(); if (rowCount === 0) { alert("์กฐํšŒ ํ›„ ์ฒ˜๋ฆฌํ•˜์‹ญ์‹œ์˜ค."); return; } var result = confirm("๋ฐฐ์†ก์™„๋ฃŒ ์ทจ์†Œ ์ฒ˜๋ฆฌํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?"); if (!result) { return; } if (G_GRDMASTERE.view.getEditorLock().isActive()) { G_GRDMASTERE.view.getEditorLock().commitCurrentEdit(); } var processDS = [ ]; var chkCnt = 0; var chkProcessState = $NC.G_VAR.stateFWBW[$NC.G_VAR.activeView.PROCESS_CD].CANCEL; for ( var row = 0; row < rowCount; row++) { var rowData = G_GRDMASTERE.data.getItem(row); if (rowData.CHECK_YN == "Y") { chkCnt++; // ์ ์น˜ํ™•์ • ์ƒํƒœ์ธ ์ „ํ‘œ๋งŒ ๋Œ€์ƒ if (rowData.OUTBOUND_STATE === chkProcessState) { var processData = { P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_OUTBOUND_DATE: rowData.OUTBOUND_DATE, P_OUTBOUND_NO: rowData.OUTBOUND_NO }; processDS.push(processData); } } } if (chkCnt == 0) { alert("๋ฐฐ์†ก์™„๋ฃŒ ์ฒ˜๋ฆฌํ•  ๋ฐ์ดํ„ฐ๋ฅผ ์„ ํƒํ•˜์‹ญ์‹œ์˜ค."); return; } if (processDS.length == 0) { alert("์„ ํƒํ•œ ๋ฐ์ดํ„ฐ ์ค‘ ๋ฐฐ์†ก์™„๋ฃŒ ์ฒ˜๋ฆฌ ๊ฐ€๋Šฅํ•œ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."); return; } $NC.serviceCall("/LOM2010E/callLOProcessing.do", { P_DS_MASTER: $NC.getParams(processDS), P_PROCESS_CD: "E", P_DIRECTION: "BW", P_OUTBOUND_BATCH: "", P_OUTBOUND_BATCH_NM: "", P_DELIVERY_BATCH_CD: "", P_DELIVERY_BATCH_NM: "", P_PROCESS_STATE_BW: $NC.G_VAR.stateFWBW[$NC.G_VAR.activeView.PROCESS_CD].CANCEL, P_PROCESS_STATE_FW: $NC.G_VAR.stateFWBW[$NC.G_VAR.activeView.PROCESS_CD].CONFIRM, P_USER_ID: $NC.G_USERINFO.USER_ID }, onSaveE, onSaveErrorE, 2); } function onProcessNxtE() { var rowCount = G_GRDMASTERE.data.getLength(); if (rowCount === 0) { alert("์กฐํšŒ ํ›„ ์ฒ˜๋ฆฌํ•˜์‹ญ์‹œ์˜ค."); return; } var result = confirm("๋ฐฐ์†ก์™„๋ฃŒ ์ฒ˜๋ฆฌํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?"); if (!result) { return; } var processDS = [ ]; var chkCnt = 0; var chkProcessState = $NC.G_VAR.stateFWBW[$NC.G_VAR.activeView.PROCESS_CD].CONFIRM; for ( var row = 0; row < rowCount; row++) { var rowData = G_GRDMASTERE.data.getItem(row); if (rowData.CHECK_YN == "Y") { chkCnt++; // ์ž…๊ณ ํ™•์ • ์ƒํƒœ์ธ ์ „ํ‘œ๋งŒ ๋Œ€์ƒ if (rowData.OUTBOUND_STATE === chkProcessState) { var processData = { P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_OUTBOUND_DATE: rowData.OUTBOUND_DATE, P_OUTBOUND_NO: rowData.OUTBOUND_NO }; processDS.push(processData); } } } if (chkCnt == 0) { alert("๋ฐฐ์†ก์™„๋ฃŒ ์ฒ˜๋ฆฌํ•  ๋ฐ์ดํ„ฐ๋ฅผ ์„ ํƒํ•˜์‹ญ์‹œ์˜ค."); return; } if (processDS.length == 0) { alert("์„ ํƒํ•œ ๋ฐ์ดํ„ฐ ์ค‘ ๋ฐฐ์†ก์™„๋ฃŒ์ฒ˜๋ฆฌ ๊ฐ€๋Šฅํ•œ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."); return; } $NC.serviceCall("/LOM2010E/callLOProcessing.do", { P_DS_MASTER: $NC.getParams(processDS), P_PROCESS_CD: "E", P_DIRECTION: "FW", P_OUTBOUND_BATCH: "", P_OUTBOUND_BATCH_NM: "", P_DELIVERY_BATCH_CD: "", P_DELIVERY_BATCH_NM: "", P_PROCESS_STATE_BW: $NC.G_VAR.stateFWBW[$NC.G_VAR.activeView.PROCESS_CD].CANCEL, P_PROCESS_STATE_FW: $NC.G_VAR.stateFWBW[$NC.G_VAR.activeView.PROCESS_CD].CONFIRM, P_USER_ID: $NC.G_USERINFO.USER_ID }, onSaveE, onSaveErrorE, 2); } function grdMasterEOnGetColumns() { var processFormatter = function(row, cell, value, columnDef, dataContext) { if (dataContext.OUTBOUND_STATE === $NC.G_VAR.stateFWBW[$NC.G_VAR.activeView.PROCESS_CD].CANCEL) { return "<span class='ui-icon-prior'>&nbsp;</span>"; } return "<span class='ui-icon-next'>&nbsp;</span>"; }; var columns = [ ]; $NC.setGridColumn(columns, { id: "OUTBOUND_STATE_P", field: "OUTBOUND_STATE", name: "P", minWidth: 30, maxWidth: 30, sortable: false, formatter: processFormatter }, false); $NC.setGridColumn(columns, { id: "OUTBOUND_STATE_S", field: "OUTBOUND_STATE", name: "S", minWidth: 30, maxWidth: 30, formatter: grdStateFormatter }, false); $NC.setGridColumn(columns, { id: "CHECK_YN", field: "CHECK_YN", minWidth: 30, maxWidth: 30, sortable: false, cssClass: "align-center", formatter: Slick.Formatters.CheckBox, editor: Slick.Editors.CheckBox, editorOptions: { valueChecked: "Y", valueUnChecked: "N" } }, false); $NC.setGridColumn(columns, { id: "OUTBOUND_NO", field: "OUTBOUND_NO", name: "์ถœ๊ณ ๋ฒˆํ˜ธ", minWidth: 70, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "INOUT_NM", field: "INOUT_NM", name: "์ถœ๊ณ ๊ตฌ๋ถ„", minWidth: 80 }); $NC.setGridColumn(columns, { id: "OUTBOUND_STATE_D", field: "OUTBOUND_STATE_D", name: "์ง„ํ–‰์ƒํƒœ", minWidth: 80 }); $NC.setGridColumn(columns, { id: "ORDERER_NM", field: "ORDERER_NM", name: "์ฃผ๋ฌธ์ž๋ช…", minWidth: 90 }); $NC.setGridColumn(columns, { id: "SHIPPER_NM", field: "SHIPPER_NM", name: "์ˆ˜๋ น์ž๋ช…", minWidth: 90 }); $NC.setGridColumn(columns, { id: "ORDER_DIV_D", field: "ORDER_DIV_D", name: "์ฃผ๋ฌธ๊ตฌ๋ถ„", minWidth: 100 }); $NC.setGridColumn(columns, { id: "TOT_CONFIRM_QTY", field: "TOT_CONFIRM_QTY", name: "์ด์ˆ˜๋Ÿ‰", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "TOTAL_AMT", field: "TOTAL_AMT", name: "์ด๊ธˆ์•ก", minWidth: 100, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "OUTBOUND_BATCH", field: "OUTBOUND_BATCH", name: "์ถœ๊ณ ์ฐจ์ˆ˜", minWidth: 70, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "BRAND_CD_D", field: "BRAND_CD_D", name: "ํŒ๋งค์‚ฌ์ฝ”๋“œ", minWidth: 80, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "BRAND_NM_D", field: "BRAND_NM_D", name: "ํŒ๋งค์‚ฌ๋ช…", minWidth: 120 }); $NC.setGridColumn(columns, { id: "MALL_CD_D", field: "MALL_CD_D", name: "MALL๋ช…", minWidth: 80 }); $NC.setGridColumn(columns, { id: "INORDER_TYPE_D", field: "INORDER_TYPE_D", name: "๋งค์ž…ํ˜•ํƒœ", minWidth: 80 }); $NC.setGridColumn(columns, { id: "DELIVERY_TYPE2_D", field: "DELIVERY_TYPE2_D", name: "๋ฐฐ์†ก์ง€์—ญ๊ตฌ๋ถ„", minWidth: 80 }); $NC.setGridColumn(columns, { id: "SHIP_TYPE_D", field: "SHIP_TYPE_D", name: "์šด์†ก๊ตฌ๋ถ„", minWidth: 80 }); $NC.setGridColumn(columns, { id: "SHIP_PRICE_TYPE_D", field: "SHIP_PRICE_TYPE_D", name: "์šด์†ก๋น„๊ตฌ๋ถ„", minWidth: 80 }); $NC.setGridColumn(columns, { id: "SHIP_PRICE", field: "SHIP_PRICE", name: "์šด์†ก๋น„", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "DELIVERY_TYPE_D", field: "DELIVERY_TYPE_D", name: "๋ฐฐ์†ก์œ ํ˜•", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "MALL_MSG", field: "MALL_MSG", name: "์˜จ๋ผ์ธ๋ชฐ๋ฉ”์‹œ์ง€", minWidth: 200 }); $NC.setGridColumn(columns, { id: "SHIPPER_TEL", field: "SHIPPER_TEL", name: "์ „ํ™”๋ฒˆํ˜ธ", minWidth: 120 }); $NC.setGridColumn(columns, { id: "SHIPPER_HP", field: "SHIPPER_HP", name: "ํœด๋Œ€ํฐ๋ฒˆํ˜ธ", minWidth: 120 }); $NC.setGridColumn(columns, { id: "SHIPPER_ZIP_CD", field: "SHIPPER_ZIP_CD", name: "์šฐํŽธ๋ฒˆํ˜ธ", minWidth: 60, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "SHIPPER_ADDR", field: "SHIPPER_ADDR", name: "์ฃผ์†Œ", minWidth: 200 }); $NC.setGridColumn(columns, { id: "PLANED_DATETIME", field: "PLANED_DATETIME", name: "๋‚ฉํ’ˆ์˜ˆ์ •์ผ์‹œ", minWidth: 130, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "REMARK1", field: "REMARK1", name: "๋น„๊ณ ", minWidth: 100 }); $NC.setGridColumn(columns, { id: "CONFIRM_USER_ID", field: "CONFIRM_USER_ID", name: "ํ™•์ •์‚ฌ์šฉ์ž", minWidth: 90 }); $NC.setGridColumn(columns, { id: "CONFIRM_DATETIME", field: "CONFIRM_DATETIME", name: "ํ™•์ •์ผ์‹œ", minWidth: 130, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "DELIVERY_USER_ID", field: "DELIVERY_USER_ID", name: "๋ฐฐ์†ก์™„๋ฃŒ์ž", minWidth: 90 }); $NC.setGridColumn(columns, { id: "DELIVERY_DATETIME", field: "DELIVERY_DATETIME", name: "๋ฐฐ์†ก์™„๋ฃŒ์ผ์‹œ", minWidth: 120, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "MISSED_YN", field: "MISSED_YN", name: "๋ฏธ๋ฐฐ์†ก์ฒ˜๋ฆฌ์—ฌ๋ถ€", minWidth: 120, formatter: Slick.Formatters.CheckBox, cssClass: "align-center" }); return $NC.setGridColumnDefaultFormatter(columns); } function grdMasterEInitialize() { var options = { frozenColumn: 5, specialRow: { compareKey: "OUTBOUND_STATE", compareVal: "50", compareOperator: ">=", cssClass: "specialrow1" } }; // Grid Object, DataView ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™” $NC.setInitGridObject("#grdMasterE", { columns: grdMasterEOnGetColumns(), queryId: "LOM2010E.RS_T4_MASTER", sortCol: "OUTBOUND_NO", gridOptions: options }); G_GRDMASTERE.view.onHeaderClick.subscribe(grdMasterEOnHeaderClick); G_GRDMASTERE.view.onClick.subscribe(grdMasterEOnClick); G_GRDMASTERE.view.onSelectedRowsChanged.subscribe(grdMasterEOnAfterScroll); $NC.setGridColumnHeaderCheckBox(G_GRDMASTERE, "CHECK_YN"); } /** * ๋ฐฐ์†ก์™„๋ฃŒ์ฒ˜๋ฆฌํƒญ ์ƒ๋‹จ๊ทธ๋ฆฌ๋“œ ํ–‰ ํด๋ฆญ์‹œ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ๊ฐ’ ์ทจ๋“ํ•ด์„œ ํ‘œ์‹œ ์ฒ˜๋ฆฌ * * @param e * @param args */ function grdMasterEOnAfterScroll(e, args) { var row = args.rows[0]; if (G_GRDMASTERE.lastRow != null) { if (row == G_GRDMASTERE.lastRow) { e.stopImmediatePropagation(); return; } } var rowData = G_GRDMASTERE.data.getItem(row); // ์กฐํšŒ์‹œ ์ „์—ญ ๋ณ€์ˆ˜ ๊ฐ’ ์ดˆ๊ธฐํ™” $NC.setInitGridVar(G_GRDDETAILE); onGetDetailE({ data: null }); // ํŒŒ๋ผ๋ฉ”ํ„ฐ ์„ธํŒ… G_GRDDETAILE.queryParams = $NC.getParams({ P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_OUTBOUND_DATE: rowData.OUTBOUND_DATE, P_OUTBOUND_NO: rowData.OUTBOUND_NO }); // ๋ฐ์ดํ„ฐ ์กฐํšŒ $NC.serviceCall("/LOM2010E/getDataSet.do", $NC.getGridParams(G_GRDDETAILE), onGetDetailE); // ์ƒ๋‹จ ํ˜„์žฌ๋กœ์šฐ/์ด๊ฑด์ˆ˜ ์—…๋ฐ์ดํŠธ $NC.setGridDisplayRows("#grdMasterE", row + 1); } function grdMasterEOnHeaderClick(e, args) { if (args.column.id == "CHECK_YN") { if ($(e.target).is(":checkbox")) { if (G_GRDMASTERE.data.getLength() == 0) { e.preventDefault(); e.stopImmediatePropagation(); return; } if (G_GRDMASTERE.view.getEditorLock().isActive() && !G_GRDMASTERE.view.getEditorLock().commitCurrentEdit()) { e.preventDefault(); e.stopImmediatePropagation(); return; } var checkVal = $(e.target).is(":checked") ? "Y" : "N"; var rowCount = G_GRDMASTERE.data.getLength(); var rowData; G_GRDMASTERE.data.beginUpdate(); for ( var row = 0; row < rowCount; row++) { rowData = G_GRDMASTERE.data.getItem(row); if (rowData.CHECK_YN !== checkVal) { rowData.CHECK_YN = checkVal; if (rowData.CRUD === "R") { rowData.CRUD = "U"; } G_GRDMASTERE.data.updateItem(rowData.id, rowData); } } G_GRDMASTERE.data.endUpdate(); e.stopPropagation(); e.stopImmediatePropagation(); } return; } } function grdMasterEOnClick(e, args) { if (args.cell === G_GRDMASTERE.view.getColumnIndex("CHECK_YN")) { if ($(e.target).is(":checkbox")) { if (G_GRDMASTERE.view.getEditorLock().isActive() && !G_GRDMASTERE.view.getEditorLock().commitCurrentEdit()) { e.preventDefault(); e.stopImmediatePropagation(); return; } var checkVal = $(e.target).is(":checked") ? "Y" : "N"; var rowData = G_GRDMASTERE.data.getItem(args.row); if (rowData.CHECK_YN !== checkVal) { if (rowData.CRUD === "R") { rowData.CRUD = "U"; } G_GRDMASTERE.data.updateItem(rowData.id, rowData); } // e.stopPropagation(); // e.stopImmediatePropagation(); } return; } } function grdDetailEOnGetColumns() { var columns = [ ]; $NC.setGridColumn(columns, { id: "LINE_NO", field: "LINE_NO", name: "์ˆœ๋ฒˆ", minWidth: 40, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "BRAND_CD", field: "BRAND_CD", name: "์œ„ํƒ์‚ฌ", minWidth: 80 }); $NC.setGridColumn(columns, { id: "BRAND_NM", field: "BRAND_NM", name: "์œ„ํƒ์‚ฌ๋ช…", minWidth: 100 }); $NC.setGridColumn(columns, { id: "DEAL_ID", field: "DEAL_ID", name: "๋”œID", minWidth: 80 }); $NC.setGridColumn(columns, { id: "DEAL_NM", field: "DEAL_NM", name: "๋”œ๋ช…", minWidth: 150 }); $NC.setGridColumn(columns, { id: "OPTION_ID", field: "OPTION_ID", name: "์˜ต์…˜ID", minWidth: 100 }); $NC.setGridColumn(columns, { id: "OPTION_VALUE", field: "OPTION_VALUE", name: "์˜ต์…˜๋ช…", minWidth: 150 }); $NC.setGridColumn(columns, { id: "ITEM_CD", field: "ITEM_CD", name: "์ƒํ’ˆ์ฝ”๋“œ", minWidth: 90 }); $NC.setGridColumn(columns, { id: "ITEM_NM", field: "ITEM_NM", name: "์ƒํ’ˆ๋ช…", minWidth: 150 }); $NC.setGridColumn(columns, { id: "ITEM_SPEC", field: "ITEM_SPEC", name: "๊ทœ๊ฒฉ", minWidth: 80 }); $NC.setGridColumn(columns, { id: "LOCATION_CD", field: "LOCATION_CD", name: "๋กœ์ผ€์ด์…˜", minWidth: 120 }); $NC.setGridColumn(columns, { id: "ITEM_STATE_F", field: "ITEM_STATE_F", name: "์ƒํƒœ", minWidth: 80, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "OPTION_QTY", field: "OPTION_QTY", name: "์˜ต์…˜์ˆ˜๋Ÿ‰", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ORDER_QTY", field: "ORDER_QTY", name: "์˜ˆ์ •์ˆ˜๋Ÿ‰", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ENTRY_QTY", field: "ENTRY_QTY", name: "๋“ฑ๋ก์ˆ˜๋Ÿ‰", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "CONFIRM_QTY", field: "CONFIRM_QTY", name: "ํ™•์ •์ˆ˜๋Ÿ‰", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "DELIVERY_QTY", field: "DELIVERY_QTY", name: "๋ฐฐ์†ก์ˆ˜๋Ÿ‰", minWidth: 70, cssClass: "align-right", editor: Slick.Editors.Number, editorOptions: { isKeyField: true } }); $NC.setGridColumn(columns, { id: "MISSED_QTY", field: "MISSED_QTY", name: "๋ฏธ๋ฐฐ์†ก์ˆ˜๋Ÿ‰", minWidth: 90, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "MISSED_DIV_F", field: "MISSED_DIV_F", name: "๋ฏธ๋ฐฐ์†ก์‚ฌ์œ ", minWidth: 150, editor: Slick.Editors.ComboBox, editorOptions: $NC.getGridComboEditorOptions("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CMCODE", P_QUERY_PARAMS: $NC.getParams({ P_CODE_GRP: "MISSED_DIV", P_CODE_CD: "%", P_SUB_CD1: "", P_SUB_CD2: "" }) }, { codeField: "MISSED_DIV", dataCodeField: "CODE_CD", dataFullNameField: "CODE_CD_F", isKeyField: true }) }); $NC.setGridColumn(columns, { id: "MISSED_COMMENT", field: "MISSED_COMMENT", name: "๋ฏธ๋ฐฐ์†ก์‚ฌ์œ ๋‚ด์—ญ", minWidth: 200, editor: Slick.Editors.Text }); $NC.setGridColumn(columns, { id: "SUPPLY_PRICE", field: "SUPPLY_PRICE", name: "๊ณต๊ธ‰๋‹จ๊ฐ€", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "DC_PRICE", field: "DC_PRICE", name: "ํ• ์ธ๋‹จ๊ฐ€", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "APPLY_PRICE", field: "APPLY_PRICE", name: "์ ์šฉ๋‹จ๊ฐ€", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "SUPPLY_AMT", field: "SUPPLY_AMT", name: "๊ณต๊ธ‰๊ธˆ์•ก", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "VAT_AMT", field: "VAT_AMT", name: "๋ถ€๊ฐ€์„ธ์•ก", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "DC_AMT", field: "DC_AMT", name: "ํ• ์ธ๊ธˆ์•ก", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "TOTAL_AMT", field: "TOTAL_AMT", name: "ํ•ฉ๊ณ„๊ธˆ์•ก", minWidth: 80, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ITEM_ORDER_DIV_F", field: "ITEM_ORDER_DIV_F", name: "์ƒํ’ˆ์ฃผ๋ฌธ์œ ํ˜•", minWidth: 100 }); $NC.setGridColumn(columns, { id: "ORDER_DATE", field: "ORDER_DATE", name: "์˜ˆ์ •์ผ์ž", minWidth: 100, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "ORDER_NO", field: "ORDER_NO", name: "์˜ˆ์ •๋ฒˆํ˜ธ", minWidth: 70, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "ORDER_LINE_NO", field: "ORDER_LINE_NO", name: "์˜ˆ์ •์ˆœ๋ฒˆ", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "REMARK1", field: "REMARK1", name: "๋น„๊ณ ", minWidth: 200 }); $NC.setGridColumn(columns, { id: "BU_DATE", field: "BU_DATE", name: "์ „ํ‘œ์ผ์ž", minWidth: 100, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "BU_NO", field: "BU_NO", name: "์ „ํ‘œ๋ฒˆํ˜ธ", minWidth: 120 }); $NC.setGridColumn(columns, { id: "BU_LINE_NO", field: "BU_LINE_NO", name: "์ „ํ‘œ์ˆœ๋ฒˆ", minWidth: 100 }); $NC.setGridColumn(columns, { id: "BU_KEY", field: "BU_KEY", name: "์ „ํ‘œID", minWidth: 90 }); $NC.setGridColumn(columns, { id: "OPTION_MSG", field: "OPTION_MSG", name: "์˜ต์…˜๋ฉ”์‹œ์ง€", minWidth: 150 }); return $NC.setGridColumnDefaultFormatter(columns); } function grdDetailEInitialize() { var options = { editable: true, autoEdit: true, frozenColumn: 5 }; // Grid Object, DataView ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™” $NC.setInitGridObject("#grdDetailE", { columns: grdDetailEOnGetColumns(), queryId: "LOM2010E.RS_T4_DETAIL", sortCol: "LINE_NO", gridOptions: options }); G_GRDDETAILE.view.onSelectedRowsChanged.subscribe(grdDetailEOnAfterScroll); G_GRDDETAILE.view.onBeforeEditCell.subscribe(grdDetailEOnBeforeEditCell); G_GRDDETAILE.view.onCellChange.subscribe(grdDetailEOnCellChange); } function grdDetailEOnAfterScroll(e, args) { var row = args.rows[0]; if (G_GRDDETAILE.lastRow != null) { if (row == G_GRDDETAILE.lastRow) { e.stopImmediatePropagation(); return; } if (!grdDetailEOnBeforePost(G_GRDDETAILE.lastRow)) { e.stopImmediatePropagation(); return; } } // ์ƒ๋‹จ ํ˜„์žฌ๋กœ์šฐ/์ด๊ฑด์ˆ˜ ์—…๋ฐ์ดํŠธ $NC.setGridDisplayRows("#grdDetailE", row + 1); } /** * ๋ฐฐ์†ก์™„๋ฃŒ์ฒ˜๋ฆฌ ํƒญ : ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ํŽธ์ง‘๋ถˆ๊ฐ€๋Šฅ * * @param e * @param args * @returns {Boolean} */ function grdDetailEOnBeforeEditCell(e, args) { var rowData = G_GRDDETAILE.data.getItem(args.row); var canEdit = rowData.OUTBOUND_STATE === $NC.G_VAR.stateFWBW[$NC.G_VAR.activeView.PROCESS_CD].CONFIRM && $NC.G_VAR.policyVal.LO510 === "1"; if (rowData) { if (rowData.OUTBOUND_STATE == $NC.G_VAR.stateFWBW[$NC.G_VAR.activeView.PROCESS_CD].CANCEL) { return false; } else if (args.column.field === "DELIVERY_QTY") { return canEdit; } else if (args.column.field === "MISSED_DIV_F" || args.column.field === "MISSED_COMMENT") { return Number(rowData.MISSED_QTY) > 0; } else { return true; } } return true; } /** * ๋ฐฐ์†ก์™„๋ฃŒ์ฒ˜๋ฆฌ ํƒญ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ์˜ ์…€ ๊ฐ’ ๋ณ€๊ฒฝ์‹œ ์ฒ˜๋ฆฌ * * @param e * @param args */ function grdDetailEOnCellChange(e, args) { var rowData = args.item; if (args.cell == G_GRDDETAILE.view.getColumnIndex("DELIVERY_QTY")) { var isError = false; if ($NC.isNull(rowData.DELIVERY_QTY)) { rowData.DELIVERY_QTY = 0; } if (Number(rowData.DELIVERY_QTY) < 0) { alert("๋ฐฐ์†ก์ˆ˜๋Ÿ‰์— 0๋ณด๋‹ค ์ž‘์€๊ฐ’์„ ์ž…๋ ฅํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); rowData.DELIVERY_QTY = 0; rowData.MISSED_QTY = rowData.CONFIRM_QTY; isError = true; } else if (Number(rowData.CONFIRM_QTY) < Number(rowData.DELIVERY_QTY)) { alert("๋ฐฐ์†ก์ˆ˜๋Ÿ‰์ด ํ™•์ •์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); rowData.DELIVERY_QTY = rowData.CONFIRM_QTY; rowData.MISSED_QTY = 0; isError = true; } else { rowData.MISSED_QTY = Number(rowData.CONFIRM_QTY) - Number(rowData.DELIVERY_QTY); } if (rowData.MISSED_QTY == 0) { rowData.MISSED_DIV = ""; rowData.MISSED_DIV_F = ""; rowData.MISSED_COMMENT = ""; } if (isError) { setTimeout(function() { $NC.setGridSelectRow(G_GRDDETAILE, { selectRow: args.row, activeCell: G_GRDDETAILE.view.getColumnIndex("DELIVERY_QTY"), editMode: true }); }, 300); } else if (Number(rowData.MISSED_QTY) > 0) { setTimeout(function() { $NC.setGridSelectRow(G_GRDDETAILE, { selectRow: args.row, activeCell: G_GRDDETAILE.view.getColumnIndex("MISSED_DIV_F"), editMode: true }); }, 300); } } if (rowData.CRUD == "R") { rowData.CRUD = "U"; } G_GRDDETAILE.data.updateItem(rowData.id, rowData); // ๋งˆ์ง€๋ง‰ ์„ ํƒ Row ์ˆ˜์ • ์ƒํƒœ๋กœ ๋ณ€๊ฒฝ G_GRDDETAILE.lastRowModified = true; } /** * ๋ฐฐ์†ก์™„๋ฃŒ์ฒ˜๋ฆฌ ํƒญ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ์˜ ์ž…๋ ฅ์ฒดํฌ ์ฒ˜๋ฆฌ */ function grdDetailEOnBeforePost(row) { // ๋งˆ์ง€๋ง‰ ๋ ˆ์ฝ”๋“œ๊ฐ€ ์ˆ˜์ •๋˜์—ˆ์„ ๊ฒฝ์šฐ๋งŒ ์ฒ˜๋ฆฌ if (!G_GRDDETAILE.lastRowModified) { return true; } var rowData = G_GRDDETAILE.data.getItem(row); if ($NC.isNull(rowData)) { return true; } /* // ์‚ญ์ œ ๋ฐ์ดํ„ฐ๋ฉด Return if (rowData.CRUD == "D") { return true; } // ์‹ ๊ทœ์ผ ๋•Œ ํ‚ค ๊ฐ’์ด ์—†์œผ๋ฉด ์‹ ๊ทœ ์ทจ์†Œ if (rowData.CRUD == "N") { } */ if (rowData.CRUD != "R") { if ($NC.isNull(rowData.DELIVERY_QTY)) { alert("๋ฐฐ์†ก์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•˜์‹ญ์‹œ์˜ค."); $NC.setGridSelectRow(G_GRDDETAILE, { selectRow: row, activeCell: G_GRDDETAILE.view.getColumnIndex("DELIVERY_QTY"), editMode: true }); return false; } if (Number(rowData.DELIVERY_QTY) > Number(rowData.CONFIRM_QTY)) { alert("๋ฐฐ์†ก์ˆ˜๋Ÿ‰์ด ํ™•์ •์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); $NC.setGridSelectRow(G_GRDDETAILE, { selectRow: row, activeCell: G_GRDDETAILE.view.getColumnIndex("DELIVERY_QTY"), editMode: true }); return false; } if (Number(rowData.MISSED_QTY) != 0 && $NC.isNull(rowData.MISSED_DIV)) { alert("๋ฏธ๋ฐฐ์†ก์‚ฌ์œ ๋ฅผ ์„ ํƒํ•˜์‹ญ์‹œ์˜ค."); $NC.setGridSelectRow(G_GRDDETAILE, { selectRow: row, activeCell: G_GRDDETAILE.view.getColumnIndex("MISSED_DIV_F"), editMode: true }); return false; } } return true; } function onGetMasterE(ajaxData) { $NC.setInitGridData(G_GRDMASTERE, ajaxData); // ์ฒดํฌ ์ปฌ๋Ÿผ ํ—คํ„ฐ ์ดˆ๊ธฐํ™” $NC.setGridColumnHeaderCheckBox(G_GRDMASTERE, "CHECK_YN"); if (G_GRDMASTERE.data.getLength() > 0) { if ($NC.isNull(G_GRDMASTERE.lastKeyVal)) { $NC.setGridSelectRow(G_GRDMASTERE, 0); } else { $NC.setGridSelectRow(G_GRDMASTERE, { selectKey: "INBOUND_NO", selectVal: G_GRDMASTERE.lastKeyVal }); } } else { $NC.setGridDisplayRows("#grdMasterE", 0, 0); // ๋””ํ…Œ์ผ ์ดˆ๊ธฐํ™” $NC.setInitGridVar(G_GRDDETAILE); onGetDetailE({ data: null }); // ์ž…๊ณ ์ง€์‹œ ์ดˆ๊ธฐํ™” } // ์ „ํ‘œ ๊ฑด์ˆ˜ ์ •๋ณด ์—…๋ฐ์ดํŠธ setMasterSummaryInfo(); // ๊ณตํ†ต ๋ฒ„ํŠผ ํ™œ์„ฑํ™” setTopButtons(); } function onGetDetailE(ajaxData) { $NC.setInitGridData(G_GRDDETAILE, ajaxData); if (G_GRDDETAILE.data.getLength() > 0) { if ($NC.isNull(G_GRDDETAILE.lastKeyVal)) { $NC.setGridSelectRow(G_GRDDETAILE, 0); } else { $NC.setGridSelectRow(G_GRDDETAILE, { selectKey: "LINE_NO", selectVal: G_GRDDETAILE.lastKeyVal }); } } else { $NC.setGridDisplayRows("#grdDetailE", 0, 0); } } function onSaveE(ajaxData) { var resultData = $NC.toArray(ajaxData); if (!$NC.isNull(resultData)) { if (resultData.RESULT_DATA !== "OK") { alert(resultData.RESULT_DATA); } } var lastKeyVal = $NC.getGridLastKeyVal(G_GRDMASTERE, { selectKey: "INBOUND_NO" }); _Inquiry(); G_GRDMASTERE.lastKeyVal = lastKeyVal; } function onSaveErrorE(ajaxData) { $NC.onError(ajaxData); setMasterSummaryInfo(); }
import React from "react"; import PropTypes from "prop-types"; import GridGallery from "react-grid-gallery"; import Loading from "../Loading/ScaleLoader"; import "./Gallery.css"; const Gallery = props => { return ( <div> {props.photos.length === 0 && props.errors === "" ? ( <Loading /> ) : ( <div> {props.errors === "" ? ( <div className="Gallery__container"> <GridGallery images={props.photos} margin={10} showLightboxThumbnails={true} enableImageSelection={false} backdropClosesModal={true} /> </div> ) : ( <div className="Gallery__container"> <h2>{props.errors}</h2> </div> )} </div> )} </div> ); }; Gallery.propTypes = { photos: PropTypes.array.isRequired, errors: PropTypes.string.isRequired }; export default Gallery;
import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import Label from '../Label/Label'; import Input from '../Input/Input'; const Form = ({ inputFields, inputValues, onInputChange, onSubmit }) => { const [isFormSubmitted, setIsFormSubmitted] = useState(false); const isSubmitButtonDisabled = Object.keys(inputValues).some( (inputValue) => !inputValues[inputValue].trim() ); const handleSubmitButtonClick = (ev) => { setIsFormSubmitted(true); setTimeout(() => setIsFormSubmitted(false), 2000); onSubmit(); ev.preventDefault(); }; return ( <form className="form"> <div className="form__decoration"></div> <h2 className="form__claim"> <span>Hey!</span> Could you fill this form for us? </h2> <Link to="/submissions"> <p className="form__link">Show all submissions</p> </Link> {inputFields.map( ({ label, id, placeholder, type, maxLength, options }) => ( <div className="form__group" key={id}> <Label id={id} title={label} isRequired></Label> <Input id={id} placeholder={placeholder} type={type} maxLength={maxLength} options={options} value={inputValues[id]} onChange={(ev) => onInputChange(ev, id)} /> </div> ) )} <input type="submit" value="Submit" onClick={handleSubmitButtonClick} className="form__submitBtn" disabled={isSubmitButtonDisabled} /> <div className="form__submittedMessageContainer"> {isFormSubmitted && ( <p className="form__submittedMessage"> Your form has been submitted successfully!{' '} <span role="img" aria-label="icon"> ๐Ÿ’ƒ๐Ÿป </span> </p> )} </div> </form> ); }; Form.propTypes = { inputFields: PropTypes.array.isRequired, inputValues: PropTypes.object.isRequired, onInputChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, }; export default Form;
module.exports = function (grunt) { 'use strict'; grunt.util.linefeed = '\n'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { style: { files: [ { 'styles/style.css': 'styles/style.scss' } ] } }, postcss: { prefix: { options: { processors: [ require('autoprefixer')({ browsers: ['last 5 version', 'ie 9', 'ie 8'] }) ] }, files: [ { src: 'styles/style.css' } ] }, min: { options: { processors: [ require('cssnano') ] }, files: [ { src: 'dist/css/style.css', dest: 'dist/css/style.min.css' } ] } }, cmq: { options: { log: false }, your_target: { files: [ { 'dist/css/style.css': ['styles/style.css'] } ] } }, concat: { options: { separator: '\n' }, basic_and_extras: { files: { 'dist/js/built.js': ['js/script.js'] } } }, uglify: { build: { src: 'dist/js/built.js', dest: 'dist/js/built.min.js' } }, imagemin: { dynamic: { files: [{ expand: true, cwd: 'dist/images', src: ['**/*.{png,jpg,gif}'], dest: 'dist/images/build' }] } }, watch: { html: { files: ['dist/*.html'], options: { livereload: true, spawn: false } }, css: { files: ['styles/*.scss'], tasks: ['style'], options: { livereload: true, spawn: false } }, scripts: { files: ['js/*.js'], tasks: ['concat', 'uglify'], options: { livereload: true, spawn: false } } }, connect: { server: { options: { port: 8080, base: 'dist', keepalive: true, livereload: false, open: true, hostname: 'localhost' } } } }); require('load-grunt-tasks')(grunt, {scope: 'devDependencies'}); grunt.registerTask('default', [ 'style', 'scripts' ]); grunt.registerTask('style', [ 'sass:style', 'postcss:prefix', 'cmq', 'postcss:min' ]); grunt.registerTask('scripts', ['concat', 'uglify']); grunt.registerTask('server', function () { return grunt.task.run(['connect:server']) }); };
jQuery(document).ready(function(){ jQuery('.fa-reply').click(function(){ var view = '<li class="has">' + '<div class="comment-avatar col-xs-1 ">' + '<img src="http://i9.photobucket.com/albums/a88/creaticode/avatar_1_zps8e1c80cd.jpg" alt=""> ' + '</div>' + '<div class="comment-box col-xs-11">' + '<textarea name="" class="comment__here"></textarea>' + '</div>' + '</li>'; var id = jQuery(this).closest('.area__comment').data('comment-id'); var this_ = jQuery(this).closest('.area__comment').find('.reply-list'); if (this_.find('li').hasClass('has')) {} else { this_.append(view); } this_.find('li .comment__here').focus(); }); });
define(['knockout', 'jquery', 'ojL10n!pcs/resources/nls/pcsSnippetsResource', 'pcs/tasksearch/filter/filterOperator', 'pcs/tasksearch/filter/filterType', 'pcs/tasksearch/filter/filterValue', 'pcs/tasksearch/filter/filterValueType'], function(ko, $, bundle, filterOperator, filterType, filterValue, filterValueType) { 'use strict'; function Filter(options) { var self = this; self.name = options.name || ''; self.displayName = options.displayName || ''; self.type = ko.observable(options.type || ''); self.filterOperator = ko.observableArray(options.filterOperator || []); var filterOperatorLOV = options.filterOperators ? options.filterOperators : filterOperator.getFilterOperatorsByType(options.type); self.filterOperators = ko.observableArray(filterOperatorLOV || []); self.values = ko.observableArray([]); self.canDelete = options.canDelete || false; self.isMust = ko.observableArray([]); if (options.values) { self.values(options.values); } else { if (self.type() === filterType.filterTypes.DATE) { self.filterOperator([filterOperator.operators.operator.OPERATOR_ON]); self.values([new filterValue({ type: filterValueType.valueTypes.DATE })]); } if (self.type() === filterType.filterTypes.STRING) { self.filterOperator([filterOperator.operators.operator.OPERATOR_IS]); self.values([new filterValue({ type: filterValueType.valueTypes.STRING })]); } if (self.type() === filterType.filterTypes.DOUBLE) { self.filterOperator([filterOperator.operators.operator.OPERATOR_IS]); self.values([new filterValue({ type: filterValueType.valueTypes.DOUBLE })]); } if (self.type() === filterType.filterTypes.INTEGER) { self.filterOperator([filterOperator.operators.operator.OPERATOR_IS]); self.values([new filterValue({ type: filterValueType.valueTypes.INTEGER })]); } } function handleDateFilterOperatorChange(event, data) { var filterElementId = '#' + event.currentTarget.id; var filterValues = $(filterElementId).siblings('.pcs-ts-filter-values'); var newValue = data.value[0]; if (filterOperator.operators.operator.OPERATOR_IN_LAST === newValue || filterOperator.operators.operator.OPERATOR_WITH_IN === newValue) { $(filterValues).empty(); self.values.removeAll(); var availableListofValues = [{ value: 'Days', label: bundle.pcs.tasksearch.days }, { value: 'Months', label: bundle.pcs.tasksearch.months }, { value: 'years', label: bundle.pcs.tasksearch.years }]; self.values([new filterValue({ type: filterValueType.valueTypes.DATE }), new filterValue({ type: filterValueType.valueTypes.LIST, listOfValues: availableListofValues }) ]); } if (filterOperator.operators.operator.OPERATOR_BEFORE === newValue || filterOperator.operators.operator.OPERATOR_AFTER === newValue || filterOperator.operators.operator.OPERATOR_ON === newValue) { $(filterValues).empty(); self.values.removeAll(); self.values([new filterValue({ type: filterValueType.valueTypes.DATE })]); } if (filterOperator.operators.operator.OPERATOR_BETWEEN === newValue) { $(filterValues).empty(); self.values.removeAll(); self.values([new filterValue({ type: filterValueType.valueTypes.DATE }), new filterValue({ type: filterValueType.valueTypes.DATE }) ]); } } function handleNumberFilterOperatorChange(event, data, valueType) { var filterElementId = '#' + event.currentTarget.id; var filterValues = $(filterElementId).siblings('.pcs-ts-filter-values'); var newValue = data.value[0]; if (filterOperator.operators.operator.OPERATOR_IS === newValue || filterOperator.operators.operator.OPERATOR_GREATER_THAN === newValue || filterOperator.operators.operator.OPERATOR_LESSER_THAN === newValue || filterOperator.operators.operator.OPERATOR_CONTAINS === newValue) { $(filterValues).empty(); self.values.removeAll(); self.values([new filterValue({ type: valueType })]); } if (filterOperator.operators.operator.OPERATOR_BETWEEN === newValue) { $(filterValues).empty(); self.values.removeAll(); self.values([new filterValue({ type: valueType }), new filterValue({ type: valueType }) ]); } } self.handleFilterOperatorChange = function handleFilterOperatorChange(event, data) { if (self.type() === filterType.filterTypes.DATE) { handleDateFilterOperatorChange(event, data); } if (self.type() === filterType.filterTypes.INTEGER || self.type() === filterType.filterTypes.DOUBLE) { handleNumberFilterOperatorChange(event, data, self.type()); } }; } return Filter; } );
// !Gender Combobox StudentCentre.combo.Gender = function(config) { config = config || {}; Ext.applyIf(config, { store: new Ext.data.ArrayStore({ fields: ['value','display'] ,data: [ [0,''] ,[1,_('studentcentre.male')] ,[2,_('studentcentre.female')] ] }) ,mode: 'local' ,displayField: 'display' ,valueField: 'value' }); StudentCentre.combo.Gender.superclass.constructor.call(this, config); }; Ext.extend(StudentCentre.combo.Gender, MODx.combo.ComboBox); Ext.reg('combo-gender-status', StudentCentre.combo.Gender); // !Student Update StudentCentre.panel.StudentsUpdate = function(config) { config = config || {}; //console.log(config); Ext.apply(config,{ border: false ,url: StudentCentre.config.connectorUrl ,baseCls: 'modx-formpanel' ,cls: 'container' ,items: [{ html: '<h2>New Student</h2>' ,id: 'sc-student-header' ,border: false ,cls: 'modx-page-header' },{ xtype: 'modx-tabs' ,defaults: { border: false ,autoHeight: true, bodyStyle: 'padding:10px' } ,border: true ,items: [{ layout: 'form' ,title: _('studentcentre.profile') ,labelWidth: 150 ,defaults: { autoHeight: true } ,items: [{ xtype: 'hidden' ,name: 'class_key' ,value: 'scModUser' },{ xtype: 'hidden' ,name: 'passwordnotifymethod' ,value: 's' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.username') ,name: 'username' ,allowBlank: false ,anchor: '100%' },{ name: 'active' ,fieldLabel: _('studentcentre.active') ,xtype: 'xcheckbox' ,inputValue: 1 },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.first_name') ,name: 'firstname' ,allowBlank: false ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.middle_name') ,name: 'middlename' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.last_name') ,name: 'lastname' ,allowBlank: false ,anchor: '100%' },{ xtype: 'datefield' ,name: 'start_date' ,fieldLabel: _('studentcentre.start_date') ,format: 'Y-m-d' },{ xtype: 'combo-gender-status' ,fieldLabel: _('studentcentre.gender') ,name: 'gender' ,hiddenName: 'gender' },{ xtype: 'datefield' ,name: 'dob' ,fieldLabel: _('studentcentre.birth_date') ,format: 'Y-m-d' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.email') ,name: 'email' ,allowBlank: false ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.email') ,name: 'email2' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.email') ,name: 'email3' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.email') ,name: 'email4' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.address') ,name: 'address' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.city') ,name: 'city' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.province') ,name: 'province' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.postal_code') ,name: 'postalcode' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.phone') ,name: 'phone' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.contact_name1') ,name: 'contactname1' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.contact_phone1') ,name: 'contactphone1' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.contact_name2') ,name: 'contactname2' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.contact_phone2') ,name: 'contactphone2' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.contact_name3') ,name: 'contactname3' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.contact_phone3') ,name: 'contactphone3' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.contact_name4') ,name: 'contactname4' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.contact_phone4') ,name: 'contactphone4' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_contact_name1') ,name: 'emergname1' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_phone1a') ,name: 'emergphone1a' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_phone1b') ,name: 'emergphone1b' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_phone1c') ,name: 'emergphone1c' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_rel1') ,name: 'emergrel1' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_contact_name2') ,name: 'emergname2' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_phone2a') ,name: 'emergphone2a' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_phone2b') ,name: 'emergphone2b' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_phone2c') ,name: 'emergphone2c' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_rel2') ,name: 'emergrel2' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_contact_name3') ,name: 'emergname3' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_phone3a') ,name: 'emergphone3a' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_phone3b') ,name: 'emergphone3b' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_phone3c') ,name: 'emergphone3c' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_rel3') ,name: 'emergrel3' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_contact_name4') ,name: 'emergname4' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_phone4a') ,name: 'emergphone4a' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_phone4b') ,name: 'emergphone4b' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_phone4c') ,name: 'emergphone4c' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.emerg_rel4') ,name: 'emergrel4' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.referral') ,name: 'referral' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.notes') ,name: 'notes' ,anchor: '100%' }] }] // only to redo the grid layout after the content is rendered // to fix overflow components' panels, especially when scroll bar is shown up ,listeners: { 'afterrender': function(tabPanel) { tabPanel.doLayout(); } } }] ,buttons: [{ text: _('studentcentre.save') ,id: 'btn_save' ,listeners: { click: { fn: this.submitForm, scope: this } } }] ,listeners: { 'setup': {fn:this.setup,scope:this} } }); StudentCentre.panel.StudentsUpdate.superclass.constructor.call(this,config); }; Ext.extend(StudentCentre.panel.StudentsUpdate,MODx.FormPanel,{ setup: function() { if (this.config.studentId === '' || this.config.studentId === 0) { this.fireEvent('ready'); return false; } //console.log(this.config.studentId); MODx.Ajax.request({ url: StudentCentre.config.connectorUrl ,params: { action: 'mgr/students/scModUserGet' ,id: this.config.studentId } ,listeners: { 'success': {fn:function(r) { this.getForm().setValues(r.object); //console.log(this.getForm()); console.log(r.object); Ext.get('sc-student-header').update('<h2>'+_('studentcentre.student')+': '+r.object.username+'</h2>'); this.fireEvent('ready',r.object); MODx.fireEvent('ready'); },scope:this} } }); } ,submitForm: function(button, e) { var form = this.getForm(); if (form) { if(form.isValid()) { form.submit({ waitMsg: _('studentcentre.processing') ,url: StudentCentre.config.connectorUrl ,params: { action: 'mgr/students/scModUserUpdate' ,id: this.config.studentId } ,success: function(form, action) { Ext.MessageBox.alert(_('studentcentre.success'), _('studentcentre.stu_student_update_success'), function() { location.href = '?a='+StudentCentre.action+'&action=studentshome'; }); } ,failure: function(form, action){ //console.log(action); var responseObj = Ext.decode(action.response.responseText); Ext.MessageBox.alert(_('studentcentre.error'), responseObj.message); } }); } } } }); Ext.reg('sc-students-panel-update',StudentCentre.panel.StudentsUpdate);
import React from 'react' import { View, Image, TouchableOpacity } from 'react-native' import { bindActionCreators } from 'redux' import DefaultText from '../DefaultText' import Price from '../Price' import { connect } from 'react-redux' import Colors from '@Colors/colors' import { openLoginForm } from '../../store/reducer/login' import { showModal, modalState } from '../../store/reducer/navigation' import { LOGIN_STATUSES } from '../../store/reducer/login' import style from './TabBarStyle' import Config from '@Config/config' import Images from '@Assets/images' // NOTE - The image URLs must be known statically // see: https://facebook.github.io/react-native/docs/images.html const TabItem = (active, inactive, label) => ({ active, inactive, label }) const TABS = [ TabItem( Images.searchActive, Images.searchInactive, 'Search Tab' ), TabItem( Images.spendingActive, Images.spendingInactive, 'Spending Tab' ), TabItem( Images.meActive, Images.meInactive, 'My Details Tab' ) ] const isDevMode = Config.FLAVOUR === 'dev' const TabBar = (props) => <View style={style.tabBar}> {TABS.map((tab, index) => <View style={style.centerChildren} key={index}> <TouchableOpacity style={style.iconContainer} onPress={() => props.goToPage(index)} onLongPress={() => {isDevMode && props.showModal(modalState.developerOptions)}} accessibilityLabel={tab.label}> <Image source={props.tabIndex === index ? tab.active : tab.inactive}/> </TouchableOpacity> {index !== TABS.length - 1 ? <View style={style.separator}/> : undefined} </View> )} <View style={style.amountContainer}> { props.loggedIn ? <View style={style.amountInnerContainer}> <Image source={Images.balanceSymbol} style={style.balanceSymbol}/> <Price style={style.amount} price={props.balance} prefix='' size={30} color={Colors.primaryBlue}/> </View> : <TouchableOpacity style={style.centerChildren} onPress={props.connection ? () => props.openLoginForm(true) : undefined} accessibilityLabel='Log in Tab'> <View> <DefaultText style={{ color: props.connection ? Colors.primaryBlue : Colors.offWhite }}>Log in</DefaultText> </View> </TouchableOpacity> } </View> </View> const mapStateToProps = (state) => ({ loggedIn: state.login.loginStatus === LOGIN_STATUSES.LOGGED_IN, balance: state.account.balance, connection: state.networkConnection.status, tabIndex: state.navigation.tabIndex }) const mapDispatchToProps = (dispatch) => bindActionCreators({ openLoginForm, showModal }, dispatch) export default connect(mapStateToProps, mapDispatchToProps)(TabBar)
import React from 'react' import { connect } from 'react-redux' import * as modalActions from '../store/actions/modal.actions' import { bindActionCreators } from 'redux' function Modal({ showState, show, hide, show_async }) { const styles = { width: 400, height: 400, position: 'absolute', top: '50%', left: '50%', backgroundColor: 'blue', display: showState ? 'block' : 'none' } return <div> <button onClick={show_async}>show</button> <button onClick={hide}>hide</button> <div style={styles}></div> </div> } const mapStateToProps = state => { return { showState: state.modal.showState } } const mapActionsToProps = dispatch => bindActionCreators(modalActions, dispatch) export default connect(mapStateToProps, mapActionsToProps)(Modal)
/** * Created by T4rk on 7/29/2017. */ /** * global object filler, either global, window or self. */ export const globalScope = (() => { // eslint-disable-next-line no-undef const glob = typeof module !== 'undefined' && module.exports ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {} /* istanbul ignore next */ const acb = { asyncCallback: (func) => setTimeout(func, 0), clearCallback: (callId) => clearTimeout(callId), scope: glob } const setACB = (cb, clear) => { acb.asyncCallback = (func) => cb(func) acb.clearCallback = (callId) => clear(callId) } /* istanbul ignore else */ if (glob.requestIdleCallback) setACB(glob.requestIdleCallback, glob.cancelIdleCallback) else if (glob.setImmediate) setACB(glob.setImmediate, glob.clearImmediate) return Object.freeze ? Object.freeze(acb) : acb })()
let speechOutput; let welcomeOutput = 'Hi, I am Food Nutrition Guru. You can ask me about calorie, protein and fat content information of food items.'; let welcomeReprompt = 'For example, you can say how many calories are in butter salted or you can say how many proteins are in 1 grams of butter salted'; "use strict"; const Alexa = require('alexa-sdk'); const appName = 'Nutrition Guru'; const APP_ID = 'amzn1.ask.skill.0f17036c-4530-4118-963f-e2218535ad23'; const STOP_MESSAGE = 'Thanks for using '+appName+'. Have a great day!'; const CANCEL_MESSAGE = 'Thanks for using '+appName+'. Have a nice day!'; const LAUNCH_SPEAK = 'I can help you to get your nutrtion.'; const UNHANDLED_MESSAGE = 'I am Sorry, Can you please repeat that'; speechOutput = ''; const handlers = { 'LaunchRequest': function () { const speechOutput = "<say-as interpret-as=\"interjection\">"+getPartOfDay()+"</say-as><break time=\"300ms\"/>"+ "<say-as interpret-as=\"interjection\">"+welcomeOutput+"</say-as><break time=\"300ms\"/>"+welcomeReprompt; this.response.speak(speechOutput).listen(welcomeReprompt); this.emit(':responseReady'); }, 'AMAZON.HelpIntent': function () { const speechOutput = welcomeOutput; const reprompt = welcomeReprompt; this.response.speak(speechOutput).listen(reprompt); this.emit(':responseReady'); }, 'AMAZON.CancelIntent': function () { this.response.speak(CANCEL_MESSAGE); // this.emit(':tell', CANCEL_MESSAGE); this.emit(':responseReady'); }, 'AMAZON.StopIntent': function () { this.response.speak(STOP_MESSAGE); // this.emit(':tell', STOP_MESSAGE); this.emit(':responseReady'); }, 'SessionEndedRequest': function () { speechOutput = ''; //this.emit(':saveState',true);//uncomment to save attributes to db on session end this.emit(':tell', speechOutput); }, 'AMAZON.FallbackIntent': function () { this.emit(":ask", UNHANDLED_MESSAGE); }, 'AMAZON.NavigateHomeIntent': function () { speechOutput = ''; //any intent slot variables are listed here for convenience //Your custom intent handling goes here speechOutput = "This is a place holder response for the intent named AMAZON.NavigateHomeIntent. This intent has no slots. Anything else?"; this.emit(":ask", speechOutput, speechOutput); }, 'GetNutritionCaloriesInfo': function () { let FoodItemSlotRaw = this.event.request.intent.slots.FoodItem.value; console.log(FoodItemSlotRaw); let FoodItemSlot = resolveCanonical(this.event.request.intent.slots.FoodItem); console.log(FoodItemSlot); let WeightSlotRaw = this.event.request.intent.slots.Weight.value; console.log(WeightSlotRaw); let WeightSlot = resolveCanonical(this.event.request.intent.slots.Weight); console.log(WeightSlot); let TeaSpoonSlotRaw = this.event.request.intent.slots.TeaSpoon.value; console.log(TeaSpoonSlotRaw); let TeaSpoonSlot = resolveCanonical(this.event.request.intent.slots.TeaSpoon); console.log(TeaSpoonSlot); var MAX_RESPONSES = 3; var MAX_FOOD_ITEMS = 10; speechOutput = ''; var foodDb = require('./food_db.json'); var results = searchFood(foodDb,FoodItemSlot); if (results.length == 0) { speechOutput = "Could not find any food item for" +FoodItemSlot+ "Please try different food item."; } else { results.slice(0, MAX_RESPONSES).forEach(function (item) { let weightpermygm = (item[1]/100)*WeightSlot; let weightpermytsp = (item[1]/400)*TeaSpoonSlot; if(WeightSlot) { speechOutput = WeightSlot+" grams of "+ item[0] +" contains " +weightpermygm+ " calories"; } else if(TeaSpoonSlot) { speechOutput = TeaSpoonSlot+" tea spoon "+ item[0] +" contains " +weightpermytsp+ " calories"; } else{ speechOutput = "100 grams of "+ item[0] +" contains " +(item[1])+ " calories"; } }); } this.emit(":ask", speechOutput, speechOutput); }, 'GetNutritionProteinInfo': function () { let FoodItemSlotRaw = this.event.request.intent.slots.FoodItem.value; console.log(FoodItemSlotRaw); let FoodItemSlot = resolveCanonical(this.event.request.intent.slots.FoodItem); console.log(FoodItemSlot); let WeightSlotRaw = this.event.request.intent.slots.Weight.value; console.log(WeightSlotRaw); let WeightSlot = resolveCanonical(this.event.request.intent.slots.Weight); console.log(WeightSlot); let TeaSpoonSlotRaw = this.event.request.intent.slots.TeaSpoon.value; console.log(TeaSpoonSlotRaw); let TeaSpoonSlot = resolveCanonical(this.event.request.intent.slots.TeaSpoon); console.log(TeaSpoonSlot); var MAX_RESPONSES = 3; var MAX_FOOD_ITEMS = 10; speechOutput = ''; var foodDb = require('./food_db.json'); var results = searchFood(foodDb,FoodItemSlot); if (results.length == 0) { speechOutput = "Could not find any food item for" +FoodItemSlot+ "Please try different food item."; } else { results.slice(0, MAX_RESPONSES).forEach(function (item) { let weightpermygm = (item[2]/100)*WeightSlot; let weightpermytsp = (item[2]/400)*TeaSpoonSlot; if(WeightSlot) { speechOutput = WeightSlot+" grams of "+ item[0] +" contains " +weightpermygm+ " proteins"; } else if(TeaSpoonSlot) { speechOutput = TeaSpoonSlot+" tea spoon "+ item[0] +" contains " +weightpermytsp+ " proteins"; } else{ speechOutput = "100 grams of "+ item[0] +" contains " +(item[2])+ " proteins"; } }); } this.emit(":ask", speechOutput, speechOutput); }, 'GetNutritionFatInfo': function () { let FoodItemSlotRaw = this.event.request.intent.slots.FoodItem.value; console.log(FoodItemSlotRaw); let FoodItemSlot = resolveCanonical(this.event.request.intent.slots.FoodItem); console.log(FoodItemSlot); let WeightSlotRaw = this.event.request.intent.slots.Weight.value; console.log(WeightSlotRaw); let WeightSlot = resolveCanonical(this.event.request.intent.slots.Weight); console.log(WeightSlot); let TeaSpoonSlotRaw = this.event.request.intent.slots.TeaSpoon.value; console.log(TeaSpoonSlotRaw); let TeaSpoonSlot = resolveCanonical(this.event.request.intent.slots.TeaSpoon); console.log(TeaSpoonSlot); var MAX_RESPONSES = 3; var MAX_FOOD_ITEMS = 10; speechOutput = ''; var foodDb = require('./food_db.json'); var results = searchFood(foodDb,FoodItemSlot); if (results.length == 0) { speechOutput = "Could not find any food item for" +FoodItemSlot+ "Please try different food item."; } else { results.slice(0, MAX_RESPONSES).forEach(function (item) { let weightpermygm = (item[3]/100)*WeightSlot; let weightpermytsp = (item[3]/400)*TeaSpoonSlot; if(WeightSlot) { speechOutput = WeightSlot+" grams of "+ item[0] +" contains " +weightpermygm+ " fats"; } else if(TeaSpoonSlot) { speechOutput = TeaSpoonSlot+" tea spoon "+ item[0] +" contains " +weightpermytsp+ " fats"; } else{ speechOutput = "100 grams of "+ item[0] +" contains " +(item[3])+ " fats"; } }); } this.emit(":ask", speechOutput, speechOutput); }, 'GetNutritionInfo': function () { speechOutput = ''; let FoodItemSlotRaw = this.event.request.intent.slots.FoodItem.value; console.log(FoodItemSlotRaw); let FoodItemSlot = resolveCanonical(this.event.request.intent.slots.FoodItem); console.log(FoodItemSlot); let TeaSpoonSlotRaw = this.event.request.intent.slots.TeaSpoon.value; console.log(TeaSpoonSlotRaw); let TeaSpoonSlot = resolveCanonical(this.event.request.intent.slots.TeaSpoon); console.log(TeaSpoonSlot); let WeightSlotRaw = this.event.request.intent.slots.Weight.value; console.log(WeightSlotRaw); let WeightSlot = resolveCanonical(this.event.request.intent.slots.Weight); console.log(WeightSlot); var MAX_RESPONSES = 3; var MAX_FOOD_ITEMS = 10; speechOutput = ''; var foodDb = require('./food_db.json'); var results = searchFood(foodDb,FoodItemSlot); if (results.length == 0) { speechOutput = "Could not find any food item for" +FoodItemSlot+ "Please try different food item."; } else { results.slice(0, MAX_RESPONSES).forEach(function (item) { // let weightpermygm = (item[1]/100)*WeightSlot; let weightpermytsp = (item[1]/400)*TeaSpoonSlot; if(WeightSlot) { speechOutput = WeightSlot+" grams of "+ item[0] +" contains " +(item[1]/100)*WeightSlot+ " calories"+(item[2]/100)*WeightSlot+" proteins"+(item[3]/100)*WeightSlot+"fats"; } else if(TeaSpoonSlot) { speechOutput = TeaSpoonSlot+" tea spoon "+ item[0] +" contains " +weightpermytsp+ " calories"; } else{ speechOutput = "100 grams of "+ item[0] +" contains " +(item[1])+ " calories"; } }); } this.emit(":ask", speechOutput, speechOutput); }, 'GetNextEventIntent': function () { speechOutput = ''; //any intent slot variables are listed here for convenience //Your custom intent handling goes here speechOutput = "This is a place holder response for the intent named GetNextEventIntent. This intent has no slots. Anything else?"; this.emit(":ask", speechOutput, speechOutput); }, 'DontKnowIntent': function () { speechOutput = ''; //any intent slot variables are listed here for convenience //Your custom intent handling goes here speechOutput = "This is a place holder response for the intent named DontKnowIntent. This intent has no slots. Anything else?"; this.emit(":ask", speechOutput, speechOutput); }, 'Unhandled': function () { speechOutput = "The skill didn't quite understand what you wanted. Do you want to try something else?"; this.emit(':ask', speechOutput, speechOutput); } }; // END of Intent Handlers {} ======================================================================================== // 3. Helper Function ================================================================================================= function resolveCanonical(slot){ //this function looks at the entity resolution part of request and returns the slot value if a synonyms is provided let canonical; try{ canonical = slot.resolutions.resolutionsPerAuthority[0].values[0].value.name; }catch(err){ console.log(err.message); canonical = slot.value; } return canonical; } function searchFood(fDb, foodName) { foodName = foodName.toLowerCase(); foodName = foodName.replace(/,/g, ''); var foodWords = foodName.split(/\s+/); var regExps = []; var searchResult = []; foodWords.forEach(function (sWord) { regExps.push(new RegExp(`^${sWord}(es|s)?\\b`)); regExps.push(new RegExp(`^${sWord}`)); }); fDb.forEach(function (item) { var match = 1; var fullName = item[0]; var cmpWeight = 0; foodWords.forEach(function (sWord) { if (!fullName.match(sWord)) { match = 0; } }); if (match == 0) { return; } regExps.forEach(function (rExp) { if (fullName.match(rExp)) { cmpWeight += 10; } }); if (fullName.split(/\s+/).length == foodWords.length) { cmpWeight += 10; } searchResult.push([item, cmpWeight]); }); var finalResult = searchResult.filter(function (x) { return x[1] >= 10; }); if (finalResult.length == 0) { finalResult = searchResult; } else { finalResult.sort(function (a, b) { return b[1] - a[1]; }); } finalResult = finalResult.map(function (x) { return x[0]; }); return finalResult; } function getPartOfDay() { let partOfDay; let IST = new Date(); IST.setHours(IST.getHours() + 5); IST.setMinutes(IST.getMinutes() + 30); if(IST.getHours() > 9 && IST.getHours() <12) { partOfDay = "Good Morning"; }else if(IST.getHours() >= 12 && IST.getHours() < 16){ partOfDay = "Good Afternoon"; }else { partOfDay = "Good Evening"; } return partOfDay; } exports.handler = function (event, context, callback) { const alexa = Alexa.handler(event, context, callback); alexa.APP_ID = APP_ID; alexa.registerHandlers(handlers); alexa.execute(); };