text
stringlengths
7
3.69M
import React from "react"; import { ActivityIndicator, Button, Platform, Clipboard, FlatList, Image, Share, StyleSheet, Text, ScrollView, View } from "react-native"; import * as ImagePicker from "expo-image-picker"; import * as Permissions from "expo-permissions"; import { MonoText } from "../components/StyledText"; import uuid from "uuid"; import Environment from "../config/environment"; import firebase from "../utils/firebase"; import lightning from "../assets/images/lightning-logo.png"; //Some functions are inspired by mlapeter at https://github.com/mlapeter/google-cloud-vision console.disableYellowBox = true; export default class StartScreen extends React.Component { state = { imageUrl: null, imagesCollection: [], uploading: false, googleResponse: null, step: 1 }; async componentDidMount() { await Permissions.askAsync(Permissions.CAMERA_ROLL); await Permissions.askAsync(Permissions.CAMERA); } render() { return ( <View style={styles.container}> <ScrollView style={styles.container} contentContainerStyle={styles.contentContainer} > <View style={styles.helpContainer}> {this.state.googleResponse && ( <View> {this.state.imageUrl !== null && ( <View style={{ alignItems: "center", marginBottom: 10 }}> <Image source={{ uri: this.state.imageUrl }} style={{ width: 300, height: 300 }} /> </View> )} <View style={{ height: 450 }}> <Text style={styles.h1}>Result</Text> <Text style={styles.paragraphText}>The image contains:</Text> <Text style={styles.paragraphText}> </Text> <FlatList data={ this.state.googleResponse.responses[0].labelAnnotations } extraData={this.state} keyExtractor={this._keyExtractor} renderItem={({ item }) => ( <View> <Text style={styles.paragraphText}> <Text style={{ fontWeight: "800" }}> {item.description} </Text>{" "} - {Math.round(item.score * 100)}% certainty. </Text> </View> )} /> </View> <Text style={styles.paragraphText}> </Text> <Text style={styles.paragraphText}> Full Response Data from Google: </Text> <Text style={styles.paragraphText}> </Text> <Text onPress={this._copyToClipboard} onLongPress={this._share} style={{ paddingVertical: 10, paddingHorizontal: 10 }} > {JSON.stringify(this.state.googleResponse.responses)} </Text> </View> )} {this._maybeRenderImage()} {this._maybeRenderUploadingOverlay()} </View> {!this.state.imageUrl && ( <View style={styles.welcomeContainer}> <Image source={lightning} style={{ width: 180, height: 220, resizeMode: "contain" }} /> <View style={styles.getStartedContainer}> <Text style={styles.h3}>Welcome to.</Text> <Text style={styles.h1}>C-Vision.</Text> <Text style={styles.paragraphText}>An image labeling app.</Text> <Text style={styles.paragraphText}> Upload an image to analyse. </Text> <Text style={styles.paragraphText}> </Text> </View> <Text style={styles.paragraphText}> Choose image from: </Text> <Button onPress={this._pickImage} title="Camera roll" /> <Button onPress={this._takePhoto} title="Take a photo" /> </View> )} </ScrollView> <View style={styles.tabBarInfoContainer}> <Text style={styles.tabBarInfoText}> <Text style={styles.tabBarInfoTextHighlighted}>Upload</Text> - Analyze - Compare </Text> </View> </View> ); } organize = array => { return array.map(function(item, i) { return ( <View key={i}> <Text>{item}</Text> </View> ); }); }; _maybeRenderUploadingOverlay = () => { if (this.state.uploading) { return ( <View style={[ StyleSheet.absoluteFill, { backgroundColor: "rgba(0,0,0,0.4)", alignItems: "center", justifyContent: "center" } ]} > <ActivityIndicator color="#fff" animating size="large" /> </View> ); } }; _maybeRenderImage = () => { let { imageUrl, googleResponse } = this.state; if (!imageUrl) { return; } return ( <View style={{ marginTop: 20, borderRadius: 3, elevation: 2 }} > <Image source={{ uri: imageUrl }} style={{ width: 300, height: 300 }} /> <Text /> <Button style={{ marginBottom: 10 }} onPress={() => this.submitToGoogle()} title="Analyze this image" /> <Text style={styles.paragraphText}> This will use Image Recogniztion to guess what this image contains </Text> <Text onPress={this._copyToClipboard} onLongPress={this._share} style={{ paddingVertical: 10, paddingHorizontal: 10 }} /> </View> ); }; _keyExtractor = (item, index) => item.id; _renderItem = item => { <Text>response: {JSON.stringify(item)}</Text>; }; _share = () => { Share.share({ message: JSON.stringify(this.state.googleResponse.responses), title: "Check it out", url: this.state.imageUrl }); }; _copyToClipboard = () => { Clipboard.setString(this.state.imageUrl); alert("Copied to clipboard"); }; _takePhoto = async () => { let pickerResult = await ImagePicker.launchCameraAsync({ allowsEditing: true, aspect: [4, 3] }); this._handleImagePicked(pickerResult); }; _pickImage = async () => { let pickerResult = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, aspect: [4, 3] }); this._handleImagePicked(pickerResult); }; _handleImagePicked = async pickerResult => { try { this.setState({ uploading: true }); if (!pickerResult.cancelled) { uploadUrl = await uploadImageAsync(pickerResult.uri); this.setState({ imageUrl: uploadUrl }); } } catch (e) { console.log(e); alert("Upload failed, sorry :("); } finally { this.setState({ uploading: false }); } }; submitToGoogle = async () => { try { this.setState({ uploading: true }); let { imageUrl } = this.state; let body = JSON.stringify({ requests: [ { features: [ { type: "LABEL_DETECTION", maxResults: 10 }, { type: "LANDMARK_DETECTION", maxResults: 5 }, { type: "FACE_DETECTION", maxResults: 5 }, { type: "LOGO_DETECTION", maxResults: 5 }, { type: "TEXT_DETECTION", maxResults: 5 }, { type: "DOCUMENT_TEXT_DETECTION", maxResults: 5 }, { type: "SAFE_SEARCH_DETECTION", maxResults: 5 }, { type: "IMAGE_PROPERTIES", maxResults: 5 }, { type: "CROP_HINTS", maxResults: 5 }, { type: "WEB_DETECTION", maxResults: 5 } ], image: { source: { imageUri: imageUrl } } } ] }); let response = await fetch( "https://vision.googleapis.com/v1/images:annotate?key=" + Environment["GOOGLE_CLOUD_VISION_API_KEY"], { headers: { Accept: "application/json", "Content-Type": "application/json" }, method: "POST", body: body } ); let responseJson = await response.json(); //console.log(responseJson); this.setState({ googleResponse: responseJson, uploading: false, step: 2 }); let topImageLabels = [ responseJson.responses[0].labelAnnotations[0].description, responseJson.responses[0].labelAnnotations[1].description, responseJson.responses[0].labelAnnotations[2].description, responseJson.responses[0].labelAnnotations[3].description ]; firebase .database() .ref( "images/" + topImageLabels[0] + " (" + topImageLabels[1] + ", " + topImageLabels[2] + ", " + topImageLabels[3] + ")" ) .set({ imageUrl: imageUrl, id: Math.round(Math.random() * 10000), confidence: responseJson.responses[0].labelAnnotations[0].score, fullResponseData: responseJson }); } catch (error) { console.log(error); } }; } readFromFirebase = () => { const database = firebase.database().ref("images"); database.on("value", snapshot => { let images = snapshot.val(); let newState = []; for (let image in images) { newState.push({ image: image, imageUrl: images[image].imageUrl, id: images[image].id, confidence: images[image].confidence, fullResponseData: images[image].fullResponseData }); } this.setState({ imagesReadFromFirebase: newState }); }); }; async function uploadImageAsync(uri) { // Why are we using XMLHttpRequest? See: // https://github.com/expo/expo/issues/2402#issuecomment-443726662 const blob = await new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.onload = function() { resolve(xhr.response); }; xhr.onerror = function(e) { console.log(e); reject(new TypeError("Network request failed")); }; xhr.responseType = "blob"; xhr.open("GET", uri, true); xhr.send(null); }); const ref = firebase .storage() .ref() .child(uuid.v4()); const snapshot = await ref.put(blob); // We're done with the blob, close and release it blob.close(); const imageUrl = await snapshot.ref.getDownloadURL(); return imageUrl; } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", paddingBottom: 10 }, contentContainer: { paddingTop: 30 }, welcomeContainer: { alignItems: "center", marginTop: 10, marginBottom: 10 }, getStartedContainer: { alignItems: "center", marginHorizontal: 50 }, h1: { fontSize: 42, fontWeight: "700", color: "rgba(96,100,109, 1)", lineHeight: 46, textAlign: "center" }, h3: { fontSize: 21, color: "rgba(96,100,109, 1)", lineHeight: 34, textAlign: "center" }, paragraphText: { fontSize: 17, color: "rgba(96,100,109, 1)", lineHeight: 24, textAlign: "center" }, helpContainer: { marginTop: 15, alignItems: "center" }, tabBarInfoContainer: { position: "absolute", bottom: 0, left: 0, right: 0, ...Platform.select({ ios: { shadowColor: "black", shadowOffset: { width: 0, height: -3 }, shadowOpacity: 0.1, shadowRadius: 3 }, android: { elevation: 20 } }), alignItems: "center", backgroundColor: "#fbfbfb", paddingVertical: 20 }, tabBarInfoText: { fontSize: 17, color: "rgba(96,100,109, 0.2)", textAlign: "center" }, tabBarInfoTextHighlighted: { color: "rgba(51,153,255, 0.8)" }, codeHighlightContainer: { backgroundColor: "rgba(0,0,0,0.05)", borderRadius: 3, paddingHorizontal: 4 }, navigationFilename: { marginTop: 5 }, codeHighlightText: { color: "rgba(96,100,109, 0.8)" } }); StartScreen.navigationOptions = { title: "Start" };
d3.csv("data/buildings/buildings.csv", function(data) { console.log(data); //Checking all data types for(var i=0; i < data.length; i++){ console.log(data[i].building); console.log(data[i].country); console.log(data[i].city); console.log(data[i].height_m); console.log(data[i].height_ft); console.log(data[i].height_px); console.log(data[i].floors); console.log(data[i].completed); console.log(data[i].image); } //Default values var building = data[0].building; document.getElementById("building").innerHTML="<b>" + building + "</b>"; var country = data[0].country; document.getElementById("country").innerHTML="<b>" + country + "</b>"; var city = data[0].city; document.getElementById("city").innerHTML="<b>" + city + "</b>"; var height = data[0].height_m; document.getElementById("height").innerHTML="<b>" + height + "</b>"; var floors = data[0].floors; document.getElementById("floors").innerHTML="<b>" + floors + "</b>"; var completed = data[0].completed; document.getElementById("completed").innerHTML="<b>" + completed + "</b>"; var the_image = data[0].image; document.getElementById("the-img").innerHTML='<img src="data/buildings/img/' + the_image + '" class="the-img"/>'; var theCount = 0; for (var i=0; i < data.length; i++) { theCount = theCount + 1; //get count document.getElementById("building-count").innerHTML="<p>Total Number of buildings:<b> &nbsp;" + theCount + "</b></p>"; } //Set size variables var width = 500; var height = 500; var barHeight = 30; var tip = d3.tip() .attr('class', 'd3-tip') .offset([-10,40]) .html(function(d) { var theBuilding = d.building; return "<strong>Click for more info on</strong> <span style='color:pink'>" + theBuilding + "</span>"; }); //Select the <body> and create a new SVG element //with the width and height values set above. var svg = d3.select("#svg-container").append("svg") .attr("width", width) .attr("height", height); svg.call(tip); //Create a series of 'rect' elements within the SVG, //with each 'rect' referencing a corresponding data values svg.selectAll("rect") .data(data) .enter() .append("rect") .sort(function(a,b){ return b.height_m - a.height_m; }) .attr("fill", "blue") .attr("x", 180) .attr("y", function(d, i) { return i * barHeight; }) .attr("width", function(d) { return parseInt(d.height_px) / 1.2; }) .attr("height", barHeight - 10) .on("mouseover", function(d) { d3.select(this).style("fill", "pink"); tip.show(d, document.getElementById("head")); }) .on("mouseout", function(d) { d3.select(this).style("fill", "blue"); tip.hide(d, document.getElementById("head")); }) .on("click", function(d) { document.getElementById("building").innerHTML="<b>" + d.building + "</b>"; document.getElementById("country").innerHTML="<b>" + d.country + "</b>"; document.getElementById("city").innerHTML="<b>" + d.city + "</b>"; document.getElementById("height").innerHTML="<b>" + d.height_m + "</b>"; document.getElementById("floors").innerHTML="<b>" + d.floors + "</b>"; document.getElementById("completed").innerHTML="<b>" + d.completed + "</b>"; document.getElementById("the-img").innerHTML='<img src="data/buildings/img/' + d.image + '" class="the-img"/>'; }); /* Tried adding a class - bld.height - but for some unknown reason the text did not show up in the graph. I was able to see it in the console however. svg.selectAll("span.bld-height") .data(data) .enter() .append("span") .attr("class","bld-height") .sort(function(a,b){ return b.height_m - a.building_m; }) .append("text", function(d) { return d.height_m; }) .attr("y", function(d, i) { return i * barHeight + 14; }) .attr("x", function(d) { return d.height_px - 10; }) .attr("font-family", "sans-serif") .attr("font-size", "11px") .attr("fill","red") .attr("text-anchor","end"); */ svg.selectAll("text") .data(data) .enter() .append("text") .sort(function(a,b){ return b.height_m - a.height_m; }) .text(function(d) { return d.height_m; }) .attr("y", function(d, i) { return i * barHeight + 14; }) .attr("x", function(d) { var theFig = parseInt(d.height_px) / 1.2; return (theFig + 170) - 15; }) .attr("font-family", "sans-serif") .attr("font-size", "11px") .attr("fill","white"); // .attr("text-anchor","end"); /*svg.append("text") .attr("class", "y label") .attr("text-anchor", "end") .attr("y", function(d, i) { return i * barHeight + 14; }) .attr("dy", ".55em") .attr("transform", "translate(30,0)") .text("Go Go Go Go");*/ svg.selectAll("g") .data(data) .enter() .append("text") .sort(function(a,b){ return b.height_m - a.height_m; }) .text(function(d) { return d.building; }) .attr("y", function(d, i) { return i * barHeight + 14; }) .attr("x", function(d) { return 0; }) .attr("font-family", "sans-serif") .attr("font-size", "11px") .attr("fill","black"); //.attr("text-anchor","end"); });
module.exports = function (tree) { var filterES6Modules = require('broccoli-es6-module-filter'), pickFiles = require('broccoli-static-compiler'); var cjsTree = filterES6Modules(pickFiles(tree, { srcDir: '/', destDir: '/cjs' }), { moduleType: 'cjs' }); var amdTree = filterES6Modules(pickFiles(tree, { srcDir: '/', destDir: '/amd' }), { moduleType: 'amd' }); return [cjsTree, amdTree]; };
const { watch, src, dest, parallel } = require('gulp'); const sass = require('gulp-sass'); const sourcemaps = require('gulp-sourcemaps'); const webserver = require('gulp-webserver'); function css() { return src('../totoro.scss') .pipe(sass.sync({ includePaths: ['../node_modules'] }).on('error', sass.logError)) .pipe(sourcemaps.write()) .pipe(dest('build')); } function server() { return src('../tests') .pipe(webserver({ livereload: true })); } function watcher() { const stalker = watch(['../*.scss', '../scss/**/*.scss']); stalker.on('change', css); } exports.css = css; exports.server = server; exports.watcher = watcher; exports.default = parallel(css, watcher, server);
(function () { 'use strict'; angular.module('app').factory('ListService', Service); Service.$inject = ['$http', 'serviceBasePath', '$httpParamSerializerJQLike', '$localStorage', 'toastr']; function Service($http, base, serialize, $localStorage, toastr) { var config = { headers: { 'Content-Type': 'text/plain; charset=utf-8' } }; var config_post = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; $http.defaults.headers.common.Authorization = 'Bearer ' + $localStorage.token; var service = {}; service.get = get; service.users = users; service.statuses = statuses; service.add = add; service.remove = remove; service.update = update; service.addUser = addUser; service.removeUser = removeUser; service.addStatus = addStatus; service.updateStatus = updateStatus; service.removeStatus = removeStatus; return service; // get------------------------------------------------------------- function get(folderid, callback) { $http.get(base + 'api/lists/get?folderid=' + folderid, {}, config) .then(function (response) { callback({ success: true, data: response.data }); }, function (response) { toastr.error(response.data); callback({ success: false }); }) } function users(listid, callback) { $http.get(base + 'api/lists/users?listid=' + listid, {}, config) .then(function (response) { callback({ success: true, data: response.data }); }, function (response) { toastr.error(response.data); callback({ success: false }); }) } function statuses(listid, callback) { $http.get(base + 'api/lists/statuses?listid=' + listid, {}, config) .then(function (response) { callback({ success: true, data: response.data }); }, function (response) { toastr.error(response.data); callback({ success: false }); }) } //insert---------------------------------------------------------- function add(folderid, listname, type, callback) { $http.post(base + 'api/lists/add?' + serialize({folderid: folderid, listname: listname, type: type}), {}, config_post) .then(function (response) { callback({ success: true, id: response.data }); }, function (response) { toastr.error(response.data); callback({ success: false }); }) } function addUser(listid, userid, typ, callback) { $http.post(base + 'api/lists/users/add?' + serialize({listid: listid, userid: userid, typ: typ}), {}, config_post) .then(function (response) { callback({ success: true }); }, function (response) { toastr.error(response.data); callback({ success: false }); }) } function addStatus(listid, statname, typ, callback) { $http.post(base + 'api/lists/statuses/add?' + serialize({listid: listid, statname: statname, typ: typ}), {}, config_post) .then(function (response) { callback({ success: true }); }, function (response) { toastr.error(response.data); callback({ success: false }); }) } //delete------------------------------------------------- function remove(listid, callback) { $http.post(base + 'api/lists/remove?listid=' + listid, {}, config_post) .then(function (response) { callback({ success: true, id: response.data }); }, function (response) { toastr.error(response.data); callback({ success: false }); }) } function removeUser(listid, userid, typ, callback) { $http.post(base + 'api/lists/users/remove?' + serialize({listid: listid, userid: userid, typ: typ}), {}, config_post) .then(function (response) { callback({ success: true }); }, function (response) { toastr.error(response.data); callback({ success: false }); }) } function removeStatus(listid, statid, callback) { $http.post(base + 'api/lists/statuses/remove?' + serialize({listid: listid, statid: statid}), {}, config_post) .then(function (response) { callback({ success: true }); }, function (response) { toastr.error(response.data); callback({ success: false }); }) } //update----------------------------------------- function update(listid, listname, callback) { $http.post(base + 'api/lists/update?' + serialize({listid: listid, listname: listname}), {}, config_post) .then(function (response) { callback({ success: true, id: response.data }); }, function (response) { toastr.error(response.data); callback({ success: false }); }) } function updateStatus(listid, statid, statname, callback) { $http.post(base + 'api/lists/statuses/update?' + serialize({listid:listid, statid: statid, statname: statname}), {}, config_post) .then(function (response) { callback({ success: true }); }, function (response) { toastr.error(response.data); callback({ success: false }); }) } } })();
'use strict'; const glob = require('glob'); const path = require('path'); const _ = require('lodash'); // add ping route by default for health check const routes = [{ method: 'GET', path: '/ping', handler: () => 'Hello World!!', config: { tags: ['api'], }, }]; glob.sync('./server/**/*Routes.js').forEach((file) => { routes.push(require(path.resolve(file))); }); // export routes module.exports = _.flattenDeep(routes);
const TITLE = "Benjamin Hinchliff's Website"; module.exports = { chainWebpack: config => { config.plugin("html").tap(args => { args[0].title = TITLE; args[0].template = "./public/index.ejs"; return args; }); } };
import React, { useState } from 'react' import { Image, View, Text, StyleSheet, ImageBackground, TouchableOpacity } from 'react-native' import Icon from "react-native-vector-icons/FontAwesome" import { useHeaderHeight } from '@react-navigation/stack' import HeaderText from "../components/HeaderText" import Button from './../components/Button' import EmphasizedText from "../components/EmphasizedText" import AdjustableText from "../components/AdjustableText" import { Consumer as UserStatusConsumer } from './../global/userStatus' import * as centralAPI from './../global/centralAPI' import { getDeviceId } from './../global/deviceId' import SIZES from "./../constants/Sizes" import COLORS from "./../constants/Colors" import IMAGES from "./../constants/Images" import { DefaultMargin } from "./../constants/Layout" export default ({ navigation: { goBack } }) => { const headerHeight = useHeaderHeight() // Stores the button selected - 0 = negative, 1 = positive, -1 = no button selected var [buttonSelected, setButtonSelected] = useState(-1) return ( <ImageBackground source={IMAGES.Background} style={IMAGES.BackgroundStyle}> <View style={{marginTop: headerHeight}}> <View style={styles.container}> <View style={styles.logoContainer}> <Image source={IMAGES.LogoText} resizeMode={"cover"} resizeMethod={"resize"} style={styles.logoStyle} /> </View> <HeaderText style={styles.headerText}> Self-Reporting </HeaderText> <EmphasizedText style={styles.pinVerified}> Your PIN has been verified <Icon name="certificate" color={COLORS.verified} size={SIZES.verified} /> </EmphasizedText> <View style={styles.radioBoxContainer}> <View style={styles.radioContainer}> <TouchableOpacity onPress={() => setButtonSelected(0)} style={[styles.radio, buttonSelected === 0 ? styles.radioActive : undefined]}> <Text style={[styles.radioTextSmall, buttonSelected === 0 ? styles.radioTextActive : undefined]}>My result was</Text> <AdjustableText style={[styles.radioText, buttonSelected === 0 ? styles.radioTextActive : undefined]} fontSize={SIZES.selfReportButton} numberOfLines={1}>Negative</AdjustableText> </TouchableOpacity> </View> <View style={[styles.radioContainer]}> <TouchableOpacity onPress={() => setButtonSelected(1)} style={[styles.radio, buttonSelected === 1 ? styles.radioActive : undefined]}> <Text style={[styles.radioTextSmall, buttonSelected === 1 ? styles.radioTextActive : undefined]}>My result was</Text> <AdjustableText style={[styles.radioText, buttonSelected === 1 ? styles.radioTextActive : undefined]} fontSize={SIZES.selfReportButton} numberOfLines={1}>Positive</AdjustableText> </TouchableOpacity> </View> </View> <View style={styles.confirmContainer}> <Button disabled={buttonSelected === -1} title="Confirm" // TODO: hook up confirm function (code needs to be sent to the server) onPress={() => {console.warn("Hook me up!")}} /> </View> </View> </View> </ImageBackground> ) } const styles = StyleSheet.create({ container: { flexDirection: "column", marginHorizontal: DefaultMargin, marginTop: 20 }, logoContainer: { marginBottom: "5%" }, logoStyle: { height: IMAGES.LogoSmallHeight, width: IMAGES.LogoSmallHeight * IMAGES.LogoSmallRatio }, headerText: { fontSize: SIZES.selfReportHeader, color: COLORS.altTintColor, textAlign: "left" }, pinVerified: { color: COLORS.verified, fontSize: SIZES.verified, textAlign: "left", marginTop: "10%" }, radioBoxContainer: { marginTop: 50, flexDirection: "row", justifyContent: "space-between" }, radioContainer: { flex: 1, justifyContent: "center", alignItems: "center", height: 145 }, radio: { paddingVertical: 40, paddingLeft: 10, paddingRight: 10, backgroundColor: COLORS.radioInactive, width: "95%", height: "100%", borderRadius: 10 }, radioActive: { backgroundColor: COLORS.altTintColor }, radioTextSmall: { color: COLORS.radioInactiveText, textAlign: "center", fontSize: SIZES.selfReportButtonSmall }, radioText: { color: COLORS.radioInactiveText, textAlign: "center", fontWeight: "bold" }, radioTextActive: { color: COLORS.radioActiveText }, confirmContainer: { marginTop: 50 } })
import React, { Component } from 'react' import { connect } from 'react-redux'; import Group from '../components/form/Group'; import Label from '../components/form/Label'; import Hint from '../components/form/Hint'; import { Save } from '../actions/options'; import DirectorySelect from '../components/form/DirectorySelect'; import Checkbox from '../components/form/Checkbox'; class MusicSettings extends Component { update(e, field) { const o = Object.assign({}, this.props.obj); switch(field) { case "copy": o.import.copyToMusicFolder = e.target.checked; this.props.update(o); break; case "delete": o.import.deleteAfterMove = e.target.checked; this.props.update(o); break; default: } } selectFolder(folder) { const o = Object.assign({}, this.props.obj); o.import.musicFolder = folder; this.props.update(o); } render() { return ( <div> <Group> <Label>Music Folder</Label> <DirectorySelect value={this.props.folder} onChange={(p) => this.selectFolder(p)}>Select</DirectorySelect> <Hint>Select the folder where you would like to store your music files</Hint> </Group> <Group> <Label>Copy to music folder?</Label> <Checkbox label={'Copy'} value={this.props.copy} onChange={(e) => this.update(e, "copy")} /> <Hint>When checked, files will be copied to the music folder when imported</Hint> </Group> <Group> <Label>Delete after move?</Label> <Checkbox label={'Delete'} value={this.props.delete} onChange={(e) => this.update(e, "delete")} /> <Hint>When checked, files will be deleted after moving them the music folder</Hint> </Group> </div> ) } } const mapStateToProps = state => { if (!state.options || !state.options.opts || !state.options.opts.import) { return { obj: {}, copy: "", delete: "" } } return { obj: state.options.opts, folder: state.options.opts.import.musicFolder, copy: state.options.opts.import.copyToMusicFolder, delete: state.options.opts.import.deleteAfterMove } } const mapDispatchToProps = dispatch => { return { update: (obj) => dispatch(Save(obj)) } } export default connect(mapStateToProps, mapDispatchToProps)(MusicSettings)
import React from 'react' import ProjectCard from './ProjectCard' import { UlList } from '../styles/GlobalStyledComponents' import styled from 'styled-components' import { graphql, useStaticQuery } from 'gatsby' const Projects = () => { const repoData = useStaticQuery(graphql` query { github { user(login: "emilpee") { pinnedItems(first: 6, types: [REPOSITORY, GIST]) { totalCount edges { node { ... on GitHub_Repository { id name createdAt description url languages(last: 1, orderBy: { direction: ASC, field: SIZE }) { nodes { color name } } } } } } } } } `) const ProjectCardList = styled(UlList)` display: grid; grid-gap: 2rem 0.5rem; grid-template-columns: repeat(3, auto); grid-template-rows: repeat(2, 250px); @media screen and (max-width: 768px) { grid-template-columns: repeat(1, auto); grid-row-gap: 2rem; grid-template-rows: repeat(2, 250px); } ` return ( <> <h2>Projects</h2> <ProjectCardList> <ProjectCard cardInfo={repoData} /> </ProjectCardList> </> ) } export default Projects
import { PureComponent } from 'react'; import PropTypes from 'prop-types'; import ImageKit from 'imagekit-javascript'; import { ImageKitContextType } from '../IKContext/ImageKitContextType'; import pkg from '../../../package.json'; class ImageKitComponent extends PureComponent { constructor(props, context) { super(props, context); this.getContext = this.getContext.bind(this); } getVersion() { return pkg.version; } getContext() { return this.context || {}; } getIKClient() { const contextOptions = this.getContext(); if (contextOptions.ikClient) { return contextOptions.ikClient; } var { urlEndpoint } = this.props; urlEndpoint = urlEndpoint || contextOptions.urlEndpoint; if(!urlEndpoint || urlEndpoint.trim() === "") { throw new Error("Missing urlEndpoint during initialization"); } var ikClient = new ImageKit({ sdkVersion: `react-${this.getVersion()}`, urlEndpoint: urlEndpoint }); return ikClient; } render() { return null; } } ImageKitComponent.contextType = ImageKitContextType; export default ImageKitComponent;
// miniprogram/pages/comment-detail/comment-detail.js import { formatTime } from '../../utils/api.js'; Page({ /** * 页面的初始数据 */ data: { mainComment: {}, replyComment: [], commentText: '', discussShow: false, userInfo: [], replyNum: 0, replyNickname: '', haveName: false, lasttime: 0 }, // 格式化时间 newTime(comment) { let newComment = [] let length = comment.length for (let i = 0; i < length; i++) { comment[i].time = formatTime(comment[i].time) } return comment }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { let that = this console.log(options) wx.cloud.callFunction({ name: 'getComment', data: { commentId: options.commentId }, success: res => { // console.log(res.result.mainComment) // let mainComment = that.newTime(res.result.mainComment) res.result.mainComment.time = formatTime(res.result.mainComment.time) this.setData({ mainComment: res.result.mainComment }) console.log(this.data.mainComment); //加载当前评论的回复信息 wx.cloud.callFunction({ name: 'getReply', data: { mainCommentId: that.data.mainComment._id }, success(res) { console.log('返回') let newReply = that.newTime(res.result.newreply) that.setData({ replyComment: newReply, replyNum: newReply.length }) console.log(that.data.replyComment) }, fail(err) { console.log(err) } }) } }), // 获取当前用户信息 wx.getUserInfo({ success: function (res) { // var simpleUser = res.userInfo; // console.log(res.userInfo); that.setData({ userInfo: res.userInfo }) console.log(that.data.userInfo) } }) }, //输入框文字改变时同步至输入框 onCommentTextChange(e) { // console.log(e) this.setData({ commentText: e.detail.value }) }, // 往数据库里添加评论 addComment() { let that = this; //判断用户是否输入了内容 if (that.data.commentText == '') { wx.showToast({ title: '评论内容不能为空', icon: 'none', duration: 2000 }) } else { wx.cloud.callFunction({ name: 'addReply', data: { replyText: that.data.commentText, info: that.data.userInfo, mainCommentId: that.data.mainComment._id, mainCommentNickname: that.data.replyNickname, haveName: that.data.haveName }, success() { console.log('插入成功'); wx.cloud.callFunction({ name: 'getReply', data: { mainCommentId: that.data.mainComment._id }, success(res) { console.log('返回') console.log(res.result) let newReply = that.newTime(res.result.newreply) that.setData({ replyComment: newReply, replyNum: newReply.length }) console.log(that.data.replyComment) }, fail(err) { console.log(err) } }) // 评论成功后清空数据,关闭评论框 that.setData({ discussShow: false, commentText: '' }) } }) } }, // 判断是否显示评论框 discussAct() { this.setData({ discussShow: !this.data.discussShow, replyNickname: this.data.mainComment.nickName, haveName: false }) }, replydiscussAct(e) { console.log(e) this.setData({ discussShow: !this.data.discussShow, replyNickname: e.currentTarget.dataset.name, haveName: true }) }, //提前改变 _dianzan(e) { var that = this; let d = new Date(); let nowtime = d.getTime();//获取点击时间 if (nowtime - that.data.lasttime > 1000) { console.log(e.currentTarget.dataset) if (e.currentTarget.dataset.index > -1){ that._Replydianzan1(e); console.log('非主评论'); }else{ that._dianzan1(e); console.log('主评论'); } } else { wx.showToast({ title: '您点击的太快了', duration: 1000, icon: 'none' }) } that.setData({ lasttime: nowtime }) }, //主评论点赞 _dianzan1(e) { console.log(e) let that = this; //提前在页面做好改变 // var thisComment = that.data.comment[e.currentTarget.dataset.index]; if (that.data.mainComment.bool) { that.data.mainComment.bool = false; that.data.mainComment.DZ_num = that.data.mainComment.DZ_num - 1; } else { that.data.mainComment.bool = true; that.data.mainComment.DZ_num = that.data.mainComment.DZ_num + 1; } that.setData({ mainComment: that.data.mainComment }) wx.cloud.callFunction({ name: 'Dianzan', data: { // userId: commentId: e.currentTarget.dataset.id, }, success(res) { let mainComment = that.newTime(res.result.maincomment.data) console.log(mainComment) that.setData({ mainComment: mainComment[0] }) // console.log(mainComment) // console.log(res.result.maincomment.data[0]) }, fail(error) { console.log(error) } }) }, //回复点赞 _Replydianzan1(e) { let that = this; //提前在页面做好改变 // var thisComment = that.data.comment[e.currentTarget.dataset.index]; if (that.data.replyComment[e.currentTarget.dataset.index].bool) { that.data.replyComment[e.currentTarget.dataset.index].bool = false; that.data.replyComment[e.currentTarget.dataset.index].DZ_num = that.data.replyComment[e.currentTarget.dataset.index].DZ_num - 1; } else { that.data.replyComment[e.currentTarget.dataset.index].bool = true; that.data.replyComment[e.currentTarget.dataset.index].DZ_num = that.data.replyComment[e.currentTarget.dataset.index].DZ_num + 1; } that.setData({ replyComment: that.data.replyComment }) wx.cloud.callFunction({ name: 'replyDianzan', data: { replyId: e.currentTarget.dataset.id, mainCommentId: that.data.mainComment._id }, success(res) { console.log('好了') console.log(res.result) let newReply = that.newTime(res.result.newReply) that.setData({ replyComment: newReply }) // console.log(that.data.replyComment) }, fail(error) { console.log(error) } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
define([ 'Utilities', 'Shapes', 'Core', 'TinyPubSub' ], function(utilities, Shapes, Core, TinyPubSub) { 'use strict'; var size = 20; var npc; var npcs = []; var particles = []; var that; var baseName; var core = new Core(); var msize = 8.5; var particleBaseName = "myParticle"; var shapes = new Shapes(); var myGrid; var npcX; var npcZ; var particle; var npcValue; var shapeType; function Particles() { that = this; } function showParticles(x, z, particleName) { var geometry = new THREE.IcosahedronGeometry(10, 2); var material = new THREE.PointCloudMaterial({ color : 0x00AA00, size : 0.2 }); var particleSystem = new THREE.PointCloud(geometry, material); particleSystem.position.set(x, 10, z); npcX=Math.round(x/size); npcZ=Math.round(z/size); particleSystem.name = particleName; core.scene.add(particleSystem); particles.push(particleSystem); } Particles.prototype.getNpcX = function() { return npcX; } Particles.prototype.getNpcZ = function() { return npcZ; } function getName(baseName, x, z) { return baseName + x + z; } Particles.prototype.rotateParticlesAroundWorldAxis = function( npcIndex, axis, radians, npc) { if (npcs.length > 0) { for (var i = 0; i < npcs.length; i++) { var object; if (npc === true) { object = npcs[i]; } else { object = particles[i]; } that.rotWorldMatrix = new THREE.Matrix4(); that.rotWorldMatrix.makeRotationAxis(axis.normalize(),radians); that.rotWorldMatrix.multiply(object.matrix); // pre-multiply object.matrix = that.rotWorldMatrix; object.rotation.setFromRotationMatrix(object.matrix); } } }; Particles.prototype.initNpc = function(fileName, scene, camera) { $.ajax({ url : fileName, cache : false, type : "GET", dataType : "json", success : function(gridData) { utilities.showDebug('Opening file: ' + fileName); // var shapes= new Shapes(); // core= new Core(); // core.gridNPCs=gridData; var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); for (var i = 0; i < gridData.length; i++) { shapeType = 4; console.log(gridData[i]); for (var j = 0; j < gridData[0].length; j++) { npcValue = gridData[j][i]; if (npcValue !== 0) { console.log("npcValue: ", npcValue); shapes.addStarObject(npcs, scene, camera, true, j * size, i * size, getName(particleBaseName, j, i)); showParticles(j * size, i * size, getName(particleBaseName, j, i)); context.fillStyle = "#800080"; context.fillRect(i * msize, j * msize, msize, msize) } } } myGrid = gridData; //return gridData; $.publish('drawMap',gridData, {type:"particle"},'Please redraw mini map'); }, error : utilities.showError }); Particles.prototype.isNpc = function(x, z) { if (myGrid && x >= 0 && x < myGrid.length && z >= 0 && z < myGrid[0].length ) { return myGrid[x][z] !== 0; } return false; }; Particles.prototype.NPCs = function(x, z, value) { if (myGrid[x][z] !== 0 && value === 0) { var objectName = getName(particleBaseName, x, z); var selectedObject = core.scene.getObjectByName(objectName); core.scene.remove(selectedObject); } myGrid[x][z] = value; }; }; return Particles; });
var api = require('./api.js'); var utils = require('./utils.js'); var certPaser = require('./utils-x509cert.js'); var X509Certificate = api.X509Certificate.extend({ _cert: null, constructor: function(buffer) { debug('cert:', JSON.stringify(buffer)); // convert certBuffer to arraybuffer var certBuffer = utils.toArrayBuffer(buffer); // parse the DER-encoded buffer var asn1 = certPaser.org.pkijs.fromBER(certBuffer); this._cert = {}; try { this._cert = new certPaser.org.pkijs.simpl.CERT({schema: asn1.result}); debug('decoded certificate:\n', JSON.stringify(this._cert, null, 4)); } catch (ex) { debug('error parsing certificate bytes: ', ex) throw ex; } }, criticalExtension: function(oid) { var ext; debug('oid: ', oid); this._cert.extensions.some(function (extension) { debug('extnID: ', extension.extnID); if (extension.extnID === oid) { ext = extension; return true; } }); debug('found extension: ', ext); debug('extValue: ', _toBuffer(ext.extnValue.value_block.value_hex)); return _toBuffer(ext.extnValue.value_block.value_hex); } }); // utility function to convert Javascript arraybuffer to Node buffers function _toBuffer(ab) { var buffer = new Buffer(ab.byteLength); var view = new Uint8Array(ab); for (var i = 0; i < buffer.length; ++i) { buffer[i] = view[i]; } return buffer; } module.exports = X509Certificate;
import React from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import {Well, Col, Row, Button, Badge} from 'react-bootstrap'; import {setBV} from '../../actions/BVsActions'; class BvItem extends React.Component { constructor(props){ super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { //TOGGLE BV const data = { _id: this.props._id, title: this.props.title, value: !this.props.value }; this.props.setBV(data); } render() { return ( <Well> <Row> <Col xs={12}> <Badge className="badge">{this.props.title}</Badge> <p>{this.props.description} <b>{ (this.props.value) ? 'ON' : 'OFF' } </b></p> {(this.props.readOnly) || <Button onClick={this.handleClick} bsStyle={ (this.props.value) ? 'danger' : 'primary' } bsSize="small" > { (this.props.value) ? 'OFF' : 'ON' } </Button> } </Col> </Row> </Well> ) } } function mapDispatchToProps(dispatch) { return bindActionCreators({ setBV: setBV }, dispatch) } export default connect(null, mapDispatchToProps)(BvItem);
var Circles=[]; var canvas; var context; window.onload=function() { canvas=document.getElementById("canvas"); context=canvas.getContext("2d"); canvas.onmousedown=canvasClick; canvas.onmouseup=stopDragging; canvas.onmouseout=stopDragging; canvas.onmousemove=dragCircle; } function clearCanvas() { context.clearRect(0,0,canvas.width,canvas.height); } function addRandomCircle() { var radius=randomFromTo(10,60); var x=randomFromTo(0,canvas.width); var y=randomFromTo(0,canvas.height); var colors=["green","blue","red","yellow","magenta","orange","brown","purple","pink"]; var color=colors[randomFromTo(0,8)]; var circle=new Circle(x,y,radius,color); Circles.push(circle); drawCircles(); } function drawCircles() { context.clearRect(0,0,canvas.width,canvas.height); context.globalAlpha=0.85; context.strokeStyle="black"; for(var i=0;i<Circles.length;i++) { var circle=Circles[i]; context.beginPath(); context.arc(circle.x,circle.y,circle.radius,0,Math.PI*2); context.fillStyle=circle.color; context.fill(); context.stroke(); } } function canvasClick() { } function stopDragging() { } function dragCircle() { } function randomFromTo(from,to) { return Math.floor(Math.random()*(to-from+1)+from); }
import React, { useState, useEffect } from 'react'; import '../ListaEstilos/listEqUtencilios.css'; import { getEquiposApi } from "../../../Api/Sistema/equipos"; import ListaEquipos from "../../../Components/EquiposUtensilios/ListaEquipos"; import { Link } from 'react-router-dom'; export default function ListEqutencilios() { const [equipos, setEquipos] = useState([]); const [reloadEquipo, setReloadEquipo] = useState(false); useEffect(() => { getEquiposApi().then(response => { setEquipos(response.equipos); }); setReloadEquipo(false) }, [reloadEquipo]) return ( <> <div className="row"> <div className="col-2"> <div class="row"> <div class="col-1"></div> <div class="col-sm" id="bannerEquipo"> <br /> <br /> <h2 class="listLabel">Lista de Equipos y Utensilios</h2> <div class="row"> <div id="circle-background"> <img src="https://icons-for-free.com/iconfiles/png/512/linecolor+version+svg+cutlery-1319964497043734753.png" alt="" id="imgListEquipo" /> </div> </div> </div> </div> </div> <div className="col-sm"> <div className="row-row-cols-lg-6"> <ListaEquipos equipos={equipos} setReloadEquipo={setReloadEquipo} /> </div> <div className="row"> <div className="col-sm d-flex justify-content-center"> <Link to='/AdminSistema/FormEqutencilios'><button className="btn btn-secondary ">Agregar Equipos y Utencilios</button></Link> </div> </div> </div> </div> </> ); }
const mongoose= require('mongoose'); const bookresultSchema = mongoose.Schema({ _id:mongoose.Schema.Types.ObjectId, tname:{type:String,required:true}, nic:{type:String,required:true}, not:{type:Number, required:true}, empType:{type:String,required:true}, firstPrice:{type:Number, required:true}, disountedPrice:{type:Number, required:true} }); module.exports = mongoose.model('BookResult', bookresultSchema);
import * as React from 'react' import './footer.styles.css' export const Footer = ({ text }) => { return ( <footer className="footer"> <p>{text}</p> </footer> ) }
export {_rating_} from './RatingStore';
const botconfig = require("./botconfig.json") const Discord = require("discord.js"); const colours = require("./colours.json"); const functions = require("./functions") const bot = new Discord.Client({disableEveryone: true}); const invites = {}; const wait = require('util').promisify(setTimeout); bot.on('ready', () => { bot.user.setActivity(`${bot.users.size} users || +help for help`, {type: "WATCHING"}); console.log("Im online") wait(1000); bot.guilds.forEach(g => { g.fetchInvites().then(guildInvites => { invites[g.id] = guildInvites; }); }); }); bot.on('guildMemberAdd', member => { member.guild.fetchInvites().then(guildInvites => { const ei = invites[member.guild.id]; invites[member.guild.id] = guildInvites; const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses); const inviter = bot.users.get(invite.inviter.id); const logChannel = member.guild.channels.find(channel => channel.name === "【👋】welcome-bye"); logChannel.send(`**${member.user.tag}** joined, using the invite link **${invite.code}** from **${inviter.tag}**. The invite code has been used ${invite.uses} since created`); const role = member.guild.roles.find("name", "Community") member.addRole (role) if(!role) return }); }); bot.on("message", async message => { if (message.guild && message.content.startsWith('+imsgall')) {//this command starts if the person says "+dmall", ofc you can change this to whatever you'd like. let embed = new Discord.RichEmbed() .setColor("#ff0000") .setTitle(`❌${message.author.username}, error!❌`) .setDescription(`Invaild permissions.\n permissions needed: "MANAGE_ROLES", "ADMINISTRATOR"`) .setTimestamp() if (!message.member.hasPermission(["MANAGE_ROLES", "ADMINISTRATOR"])) return message.channel.send(embed)//this then says you don't have permissions to do this. if they do have these permissions it will work. let text = message.content.slice('$dmall'.length); // cuts off the +dmall part and create the text var. message.guild.members.forEach(member => { if (member.id != bot.user.id && !member.user.bot) member.send(text);//gets every member in the server. }); } }) bot.on("guildMemberRemove", member => { const channel = member.guild.channels.find(channel => channel.name === "【👋】welcome-bye"); if(!channel) return channel.send(`**${member.displayName}** left`) }) const fs =require("fs"); bot.commands = new Discord.Collection(); bot.aliases = new Discord.Collection(); fs.readdir("./commands/", (err, files) =>{ if(err) console.log(err) let jsfile = files.filter(f => f.split(".").pop() === "js") if(jsfile.lenght <= 0) { return console.log("[LOGS] Couldn't Find Commands!"); } jsfile.forEach((f, i) => { let pull = require(`./commands/${f}`); bot.commands.set(pull.config.name, pull); pull.config.aliases.forEach(alias => { bot.aliases.set(alias, pull.config.name) }); }) }); bot.on("message", async message =>{ if(message.author.bot || message.channel.type === "dm") return; if (!message.content.startsWith(botconfig.prefix)) return; let prefix = botconfig.prefix; let args = message.content.slice(prefix.length).split(/ +/g); let cmd = args.shift().toLowerCase(); let commandfile = bot.commands.get(cmd) || bot.commands.get(bot.aliases.get(cmd)); if(commandfile) commandfile.run(bot,message,args) if(cmd === `${prefix}hello`){ return message.channel.send("hello") } console.log(bot.commands); }) bot.login(botconfig.token);
'use strict' const Helpers = use('Helpers') const Env = use('Env') module.exports = { /* |-------------------------------------------------------------------------- | Driver |-------------------------------------------------------------------------- | | driver defines the default driver to be used for sending emails. Adonis | has support for 'mandrill', 'mailgun', 'smtp', 'ses' and 'log' driver. | */ driver: Env.get('MAIL_DRIVER', 'smtp'), /* |-------------------------------------------------------------------------- | SMTP |-------------------------------------------------------------------------- | | Here we define configuration for sending emails via SMTP. | */ smtp: { pool: true, port: 2525, host: '', secure: false, auth: { user: Env.get('MAIL_USERNAME'), pass: Env.get('MAIL_PASSWORD') }, maxConnections: 5, maxMessages: 100, rateLimit: 10 }, /* |-------------------------------------------------------------------------- | Mandrill |-------------------------------------------------------------------------- | | Here we define api options for mandrill. Mail provider makes use of | mandrill raw api, which means you cannot set email body specific | options like template, tracking_domain etc. | */ mandrill: { apiKey: Env.get('MANDRILL_APIKEY'), async: false, ip_pool: 'Main Pool' }, /* |-------------------------------------------------------------------------- | Amazon SES |-------------------------------------------------------------------------- | | Here we define api credentials for Amazon SES account. Make sure you have | verified your domain and email address, before you can send emails. | */ ses: { accessKeyId: Env.get('SES_KEY'), secretAccessKey: Env.get('SES_SECRET'), region: 'us-east-1', rateLimit: 10 }, /* |-------------------------------------------------------------------------- | MailGun |-------------------------------------------------------------------------- | | Here we define api credentials for Amazon SES account. Make sure you have | verified your domain and email address, before you can send emails. | */ mailgun: { domain: Env.get('MAILGUN_DOMAIN'), apiKey: Env.get('MAILGUN_APIKEY') }, /* |-------------------------------------------------------------------------- | Log |-------------------------------------------------------------------------- | | Log driver is mainly for testing your emails expectations. Emails are | written inside a log file, which can be used for inspection. | */ log: { toPath: "/storage" } }
import "../components/Cart.css"; import ProductInCart from "../components/ProductInCart"; import formatPrice from "../services/utils"; import { Link } from "react-router-dom"; function Cart({ products, totalPrice, setProductQuantity, removeFromCart }) { return ( <div className="cart"> <article className="cart__main"> {products.length > 0 ? products.map((product) => { return ( <ProductInCart key={product.id} product={product} setProductQuantity={setProductQuantity} removeFromCart={removeFromCart} /> ); }) : "The cart is empty"} </article> <footer className="cart__footer"> <div>Total: {formatPrice(totalPrice)}</div> </footer> {products.length > 0 && ( <Link to="/cart/checkout"> <button>Go to checkout</button> </Link> )} </div> ); } export default Cart;
import React from 'react' const Footer = () => { return ( <section className="footer"> <div className="container row outer"> <div className="col-3 social_media"> <a href="#" target="_blank" rel="nofollow"> <div className="social_icon google" /> </a> <a href="#" target="_blank" rel="nofollow"> <div className="social_icon facebook" /> </a> <a href="#" target="_blank" rel="nofollow"> <div className="social_icon twitter" /> </a> <a href="#" target="_blank" rel="nofollow"> <div className="social_icon pinterest" /> </a> </div> <div className="col-5 title">Kreator Zmyślonych Cytatów</div> <div className="col-4 author"> <p> <a href="https://github.com/HGZdev" target="_blank" rel="noopener noreferrer" > HGZ&nbsp;webdesign </a> &nbsp;&copy;&nbsp;{new Date().getFullYear()} </p> </div> </div> </section> ) } export default Footer
const path = require("path"); const webpack = require("webpack"); const tsLoader = 'awesome-typescript-loader'; const CopyWebpackPlugin = require('copy-webpack-plugin') module.exports = { mode: "none", entry: `${__dirname}/src/index.ts`, output: { path: path.resolve(__dirname, "bin/"), publicPath: "/", filename: `[name].js` }, devtool: 'source-map', resolve: { extensions: ['.js', '.ts'] }, plugins: [ new WebpackOnBuildFinishPlugin((stats) => { const { errors } = stats.compilation; console.log(errors); }), new CopyWebpackPlugin([ {from: `template/`} ]) ], module: { rules: [ { enforce: 'pre', test: /\.js$/, use: 'source-map-loader', exclude: /node_modules\/reflect-metadata/ }, { test: /\.ts$/, loader: tsLoader, exclude: /node_modules/ } ] } }; function WebpackOnBuildFinishPlugin(callback) { this.callback = callback; } WebpackOnBuildFinishPlugin.prototype.apply = function (compiler) { compiler.plugin('done', this.callback); };
/** * The Charts widget provides a Flash control for displaying data * graphically by series across A-grade browsers with Flash Player installed. * * @module charts * @requires yahoo, dom, event, datasource * @title Charts Widget * @experimental */ /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * Chart class for the YUI Charts widget. * * @namespace YAHOO.widget * @class Chart * @uses YAHOO.widget.FlashAdapter * @constructor * @param type {String} The char type. May be "line", "column", "bar", or "pie" * @param containerId {HTMLElement} Container element for the Flash Player instance. * @param dataSource {YAHOO.util.DataSource} DataSource instance. * @param attributes {object} (optional) Object literal of configuration values. */ YAHOO.widget.Chart = function(type, containerId, dataSource, attributes) { YAHOO.widget.Chart.superclass.constructor.call(this, YAHOO.widget.Chart.SWFURL, containerId, attributes); this._type = type; this._dataSource = dataSource; /** * Fires when the user moves the mouse over the bounds of an item renderer in the chart. * * @event itemMouseOverEvent * @param event.type {String} The event type * @param event.item {Object} The data displayed by the renderer * @param event.index {Number} The position within the series that the item appears. * @param event.seriesIndex {Number} The position within the series definition that the series appears. * @param event.x {Number} The horizontal position of the mouse, relative to the SWF. * @param event.y {Number} The vertical position of the mouse, relative to the SWF. */ this.createEvent("itemMouseOverEvent"); /** * Fires when the user moves the mouse out of the bounds of an item renderer in the chart. * * @event itemMouseOutEvent * @param event.type {String} The event type * @param event.item {Object} The data displayed by the renderer * @param event.index {Number} The position within the series that the item appears. * @param event.seriesIndex {Number} The position within the series definition that the series appears. * @param event.x {Number} The horizontal position of the mouse, relative to the SWF. * @param event.y {Number} The vertical position of the mouse, relative to the SWF. */ this.createEvent("itemMouseOutEvent"); /** * Fires when the user clicks an item renderer in the chart with the mouse. * * @event itemClickEvent * @param event.type {String} The event type * @param event.item {Object} The data displayed by the renderer * @param event.index {Number} The position within the series that the item appears. * @param event.seriesIndex {Number} The position within the series definition that the series appears. * @param event.x {Number} The horizontal position of the mouse, relative to the SWF. * @param event.y {Number} The vertical position of the mouse, relative to the SWF. */ this.createEvent("itemClickEvent"); /** * Fires when the user double-clicks an item renderer in the chart with the mouse. * * @event itemDoubleClickEvent * @param event.type {String} The event type * @param event.item {Object} The data displayed by the renderer * @param event.index {Number} The position within the series that the item appears. * @param event.seriesIndex {Number} The position within the series definition that the series appears. * @param event.x {Number} The horizontal position of the mouse, relative to the SWF. * @param event.y {Number} The vertical position of the mouse, relative to the SWF. */ this.createEvent("itemDoubleClickEvent"); /** * Fires when the user presses the mouse down on an item to initiate a drag action. * * @event itemDragStartEvent * @param event.type {String} The event type * @param event.item {Object} The data displayed by the renderer * @param event.index {Number} The position within the series that the item appears. * @param event.seriesIndex {Number} The position within the series definition that the series appears. * @param event.x {Number} The horizontal position of the mouse, relative to the SWF. * @param event.y {Number} The vertical position of the mouse, relative to the SWF. */ this.createEvent("itemDragStartEvent"); /** * Fires when the user moves the mouse during a drag action. * * @event itemDragEvent * @param event.type {String} The event type * @param event.item {Object} The data displayed by the renderer * @param event.index {Number} The position within the series that the item appears. * @param event.seriesIndex {Number} The position within the series definition that the series appears. * @param event.x {Number} The horizontal position of the mouse, relative to the SWF. * @param event.y {Number} The vertical position of the mouse, relative to the SWF. */ this.createEvent("itemDragEvent"); /** * Fires when the user releases the mouse during a drag action. * * @event itemDragEndEvent * @param event.type {String} The event type * @param event.item {Object} The data displayed by the renderer * @param event.index {Number} The position within the series that the item appears. * @param event.seriesIndex {Number} The position within the series definition that the series appears. * @param event.x {Number} The horizontal position of the mouse, relative to the SWF. * @param event.y {Number} The vertical position of the mouse, relative to the SWF. */ this.createEvent("itemDragEndEvent"); }; YAHOO.extend(YAHOO.widget.Chart, YAHOO.widget.FlashAdapter, { /** * The type of this chart instance. * @property _type * @type String * @private */ _type: null, /** * The id returned from the DataSource's setInterval function. * @property _pollingID * @type Number * @private */ _pollingID: null, /** * The time, in ms, between requests for data. * @property _pollingInterval * @type Number * @private */ _pollingInterval: null, /** * Stores a reference to the dataTipFunction created by * YAHOO.widget.FlashAdapter.createProxyFunction() * @property _dataTipFunction * @type String * @private */ _dataTipFunction: null, /** * Stores references to series labelFunction values created by * YAHOO.widget.FlashAdapter.createProxyFunction() * @property _seriesLabelFunctions * @type Array * @private */ _seriesLabelFunctions: null, /** * Public accessor to the unique name of the Chart instance. * * @method toString * @return {String} Unique name of the Chart instance. */ toString: function() { return "Chart " + this._id; }, /** * Sets a single style value on the Chart instance. * * @method setStyle * @param name {String} Name of the Chart style value to change. * @param value {Object} New value to pass to the Chart style. */ setStyle: function(name, value) { //we must jsonify this because Flash Player versions below 9.0.60 don't handle //complex ExternalInterface parsing correctly value = YAHOO.lang.JSON.stringify(value); this._swf.setStyle(name, value); }, /** * Resets all styles on the Chart instance. * * @method setStyles * @param styles {Object} Initializer for all Chart styles. */ setStyles: function(styles) { //we must jsonify this because Flash Player versions below 9.0.60 don't handle //complex ExternalInterface parsing correctly styles = YAHOO.lang.JSON.stringify(styles); this._swf.setStyles(styles); }, /** * Sets the styles on all series in the Chart. * * @method setSeriesStyles * @param styles {Array} Initializer for all Chart series styles. */ setSeriesStyles: function(styles) { //we must jsonify this because Flash Player versions below 9.0.60 don't handle //complex ExternalInterface parsing correctly for(var i = 0; i < styles.length; i++) { styles[i] = YAHOO.lang.JSON.stringify(styles[i]); } this._swf.setSeriesStyles(styles); }, destroy: function() { //stop polling if needed if(this._dataSource !== null) { if(this._pollingID !== null) { this._dataSource.clearInterval(this._pollingID); this._pollingID = null; } } //remove proxy functions if(this._dataTipFunction) { YAHOO.widget.FlashAdapter.removeProxyFunction(this._dataTipFunction); } //call last YAHOO.widget.Chart.superclass.destroy.call(this); }, /** * Initializes the attributes. * * @method _initAttributes * @private */ _initAttributes: function(attributes) { YAHOO.widget.Chart.superclass._initAttributes.call(this, attributes); /** * @attribute request * @description Request to be sent to the Chart's DataSource. * @type String */ this.getAttributeConfig("request", { method: this._getRequest }); this.setAttributeConfig("request", { method: this._setRequest }); /** * @attribute dataSource * @description The DataSource instance to display in the Chart. * @type DataSource */ this.getAttributeConfig("dataSource", { method: this._getDataSource }); this.setAttributeConfig("dataSource", { method: this._setDataSource }); /** * @attribute series * @description Defines the series to be displayed by the Chart. * @type Array */ this.getAttributeConfig("series", { method: this._getSeriesDefs }); this.setAttributeConfig("series", { method: this._setSeriesDefs }); /** * @attribute categoryNames * @description Defines the names of the categories to be displayed in the Chart.. * @type Array */ this.getAttributeConfig("categoryNames", { method: this._getCategoryNames }); this.setAttributeConfig("categoryNames", { validator: YAHOO.lang.isArray, method: this._setCategoryNames }); /** * @attribute dataTipFunction * @description The string representation of a globally-accessible function * that may be called by the SWF to generate the datatip text for a Chart's item. * @type String */ this.getAttributeConfig("dataTipFunction", { method: this._getDataTipFunction }); this.setAttributeConfig("dataTipFunction", { method: this._setDataTipFunction }); /** * @attribute polling * @description A numeric value indicating the number of milliseconds between * polling requests to the DataSource. * @type Number */ this.getAttributeConfig("polling", { method: this._getPolling }); this.setAttributeConfig("polling", { method: this._setPolling }); }, /** * Called when the SWF is ready for communication. Sets the type, initializes * the styles, and sets the DataSource. * * @method _loadHandler * @private */ _loadHandler: function() { //the type is set separately because it must be first! this._swf.setType(this._type); //set initial styles if(this._attributes.style) { var style = this._attributes.style; this.setStyles(style); } YAHOO.widget.Chart.superclass._loadHandler.call(this); if(this._dataSource) { this.set("dataSource", this._dataSource); } }, /** * Sends (or resends) the request to the DataSource. * * @method refreshData */ refreshData: function() { if(!this._initialized) { return; } if(this._dataSource !== null) { if(this._pollingID !== null) { this._dataSource.clearInterval(this._pollingID); this._pollingID = null; } if(this._pollingInterval > 0) { this._pollingID = this._dataSource.setInterval(this._pollingInterval, this._request, this._loadDataHandler, this); } this._dataSource.sendRequest(this._request, this._loadDataHandler, this); } }, /** * Called when the DataSource receives new data. The series definitions are used * to build a data provider for the SWF chart. * * @method _loadDataHandler * @private */ _loadDataHandler: function(request, response, error) { if(this._swf) { if(error) { YAHOO.log("Unable to load data.", "error"); } else { var i; if(this._seriesLabelFunctions) { var count = this._seriesLabelFunctions.length; for(i = 0; i < count; i++) { YAHOO.widget.FlashAdapter.removeProxyFunction(this._seriesLabelFunctions[i]); } this._seriesLabelFunction = null; } this._seriesLabelFunctions = []; //make a copy of the series definitions so that we aren't //editing them directly. var dataProvider = []; var seriesCount = 0; var currentSeries = null; if(this._seriesDefs !== null) { seriesCount = this._seriesDefs.length; for(i = 0; i < seriesCount; i++) { currentSeries = this._seriesDefs[i]; var clonedSeries = {}; for(var prop in currentSeries) { if(YAHOO.lang.hasOwnProperty(currentSeries, prop)) { if(prop == "style") { if(currentSeries.style !== null) { clonedSeries.style = YAHOO.lang.JSON.stringify(currentSeries.style); } } else if(prop == "labelFunction") { if(currentSeries.labelFunction !== null && typeof currentSeries.labelFunction == "function") { clonedSeries.labelFunction = YAHOO.widget.FlashAdapter.createProxyFunction(currentSeries.labelFunction); this._seriesLabelFunctions.push(clonedSeries.labelFunction); } } else { clonedSeries[prop] = currentSeries[prop]; } } } dataProvider.push(clonedSeries); } } if(seriesCount > 0) { for(i = 0; i < seriesCount; i++) { currentSeries = dataProvider[i]; if(!currentSeries.type) { currentSeries.type = this._type; } currentSeries.dataProvider = response.results; } } else { var series = {type: this._type, dataProvider: response.results}; dataProvider.push(series); } this._swf.setDataProvider(dataProvider); } } }, /** * Storage for the request attribute. * * @property _request * @private */ _request: "", /** * Getter for the request attribute. * * @method _getRequest * @private */ _getRequest: function() { return this._request; }, /** * Setter for the request attribute. * * @method _setRequest * @private */ _setRequest: function(value) { this._request = value; this.refreshData(); }, /** * Storage for the dataSource attribute. * * @property _dataSource * @private */ _dataSource: null, /** * Getter for the dataSource attribute. * * @method _getDataSource * @private */ _getDataSource: function() { return this._dataSource; }, /** * Setter for the dataSource attribute. * * @method _setDataSource * @private */ _setDataSource: function(value) { this._dataSource = value; this.refreshData(); }, /** * Storage for the series attribute. * * @property _seriesDefs * @private */ _seriesDefs: null, /** * Getter for the series attribute. * * @method _getSeriesDefs * @private */ _getSeriesDefs: function() { return this._seriesDefs; }, /** * Setter for the series attribute. * * @method _setSeriesDefs * @private */ _setSeriesDefs: function(value) { this._seriesDefs = value; this.refreshData(); }, /** * Getter for the categoryNames attribute. * * @method _getCategoryNames * @private */ _getCategoryNames: function() { this._swf.getCategoryNames(); }, /** * Setter for the categoryNames attribute. * * @method _setCategoryNames * @private */ _setCategoryNames: function(value) { this._swf.setCategoryNames(value); }, /** * Setter for the dataTipFunction attribute. * * @method _setDataTipFunction * @private */ _setDataTipFunction: function(value) { if(this._dataTipFunction) { YAHOO.widget.FlashAdapter.removeProxyFunction(this._dataTipFunction); } if(value && typeof value == "function") { value = YAHOO.widget.FlashAdapter.createProxyFunction(value); this._dataTipFunction = value; } this._swf.setDataTipFunction(value); }, /** * Getter for the polling attribute. * * @method _getPolling * @private */ _getPolling: function() { return this._pollingInterval; }, /** * Setter for the polling attribute. * * @method _setPolling * @private */ _setPolling: function(value) { this._pollingInterval = value; this.refreshData(); } }); /** * Storage for the dataTipFunction attribute. * * @property Chart.SWFURL * @private * @static * @final * @default "assets/charts.swf" */ YAHOO.widget.Chart.SWFURL = "assets/charts.swf";
var taskManager = require('task.manager'); roleHealer = { Tick: function(creep){ if (creep.spawning){return} creep.memory.waypoint = creep.memory.waypoint || (creep.memory.originroom + 'waypoint') creep.memory.reachedwaypoint = creep.memory.reachedwaypoint || false; waypoint = Game.flags[creep.memory.waypoint] if ((!creep.memory.reachedwaypoint) && (creep.pos.getRangeTo(waypoint) > 2)){ creep.moveTo(waypoint); return } else { creep.memory.reachedwaypoint = true; } flagname = (creep.memory.task) flag = Game.flags[flagname] if (creep.pos.getRangeTo(flag) <= 4){ injured = taskManager.getInjured(creep.room.name) closestinjured = creep.pos.findClosestByRange(injured); if (injured.length > 0){ if (closestinjured.pos.getRangeTo(flag) <= 4){ check = creep.heal(closestinjured); switch (check){ case OK: return; case ERR_NOT_IN_RANGE: if (flag.pos.getRangeTo(closestinjured) <= 4){ creep.moveTo(closestinjured, {reusePath:0}); if (creep.pos.getRangeTo(closestinjured) > 1){ creep.rangedHeal(closestinjured); } else{ creep.heal(closestinjured); } return } } } } else { if (creep.pos.getRangeTo(flag) > 3){ creep.moveTo(flag, {reusePath: 20}); } } } else { creep.moveTo(flag, {reusePath: 20}); } } } module.exports = roleHealer
$(function(){ $('.approve').bind('ajax:success', function (event, data, status, xhr){ event.preventDefault(); var approval = "You've approved " + data.name + "'s request! Be sure to coordinate a pick up time" var share_item = '#share' + data.id $(share_item).html(approval); }); $('.deny').bind('ajax:success', function (event, data, status, xhr){ var deny = "You've denied " + data.name + "'s request." var share_item = '#share' + data.id $(share_item).html(deny); }); $('.picked_up').bind('ajax:success', function (event, data, status, xhr){ var picked_up = "Pick up confirmed by: " + data.name + " at " var share_item = '#share' + data.id $(share_item).html(picked_up); }); });
$(document).ready(function () { $('.button-collapse').sideNav({menuWidth: 240, activationWidth: 100}); $('select').material_select(); $('.collapsible').collapsible({ accordion : false // A setting that changes the collapsible behavior to expandable instead of the default accordion style }); var swiper = new Swiper('#swiper-1', { pagination: '#swiper-pagination-1', paginationClickable: true, loop: true, slidesPerView: 1 }); var swiper = new Swiper('#swiper-2', { pagination: '#swiper-pagination-2', paginationClickable: true, loop: true, slidesPerView: 1 }); var swiper = new Swiper('#swiper-3', { pagination: '#swiper-pagination-3', paginationClickable: true, loop: true, slidesPerView: 1 }); $("#shopping-list-add-button").click(function () { var itemName = $("#shopping-list-add").val(); //var list = $("#shopping-list-form"); $("<p><input type=\"checkbox\" /><label>"+itemName+"</label></p>").insertBefore("#item-submit") //("<p><input type=\"checkbox\" /><label>"+itemName+"</label></p>"); }); $("#filter-by").on('change', function () { var filterValue = $("#filter-by").val(); if (filterValue == 3) { $("#filter-by-ingredient-list").css("visibility", "visible"); $("#filter-by-ingredient-list").css("display", "block"); } else { $("#filter-by-ingredient-list").css("visibility", "hidden"); $("#filter-by-ingredient-list").css("display", "none"); }; }); <<<<<<< HEAD }); ======= }); var imgdata; var cameraimg; var file; $(function() { var file; // Set an event listener on the Choose File field. $('#fileselect').bind("change", function(e) { var files = e.target.files || e.dataTransfer.files; // Our file var now holds the selected file file = files[0]; }); // This function is called when the user clicks on Upload to Parse. It will create the REST API request to upload this image to Parse. $('#addRecipe').click(function() { var serverUrl = 'https://api.parse.com/1/files/' + file.name; $.ajax({ type: "POST", beforeSend: function(request) { request.setRequestHeader("X-Parse-Application-Id", 'yKtcMnRhdHbiATzIbmdJX9fDHvCwP4mVKjHhzoup'); request.setRequestHeader("X-Parse-REST-API-Key", 'edbOSElqeLfVn9pacN9YscGOXGE2M7DHqV8iBXBD'); request.setRequestHeader("Content-Type", file.type); }, url: serverUrl, data: file, processData: false, contentType: false, success: function(data) { console.log("File available at: " + data.url); imgdata = data.url; imgdata = JSON.stringify(imgdata); console.log(imgdata + "Is the Link"); window.open(imgdata); return(imgdata); // sendProfilePicture(); }, error: function(data) { var obj = jQuery.parseJSON(data); alert(obj.error); } }); }); }); function sendProfilePicture() { var user = Parse.User.current(); var ProfilePic = Parse.Object.extend("ProfilePicture"); var profilepic = new ProfilePic(); profilepic.set("User", user); profilepic.save(null, { success: function(profilepic) { profilepic.set("Link", imgdata); profilepic.save(); displayProfilePicture(); }, error: function(error) { alert("Error: " + error.code + " " + error.message); } }); } function displayProfilePicture() { var user = Parse.User.current(); var profilepic = Parse.Object.extend("ProfilePicture"); var query = new Parse.Query(profilepic); query.equalTo("User", user); query.find({ success: querySuccess, error: error }); function querySuccess(profilepic) { for (var i = 0; i < profilepic.length; i++) { $('#profilePic').html("<img id='image' src=" + profilepic[i].get('Link') + ">"); } } function error(error) { alert("Error: " + error.code + " " + error.message); } } function imgToParse(file){ var serverUrl = 'https://api.parse.com/1/files/' + file.name; $.ajax({ type: "POST", beforeSend: function(request) { request.setRequestHeader("X-Parse-Application-Id", 'yKtcMnRhdHbiATzIbmdJX9fDHvCwP4mVKjHhzoup'); request.setRequestHeader("X-Parse-REST-API-Key", 'edbOSElqeLfVn9pacN9YscGOXGE2M7DHqV8iBXBD'); request.setRequestHeader("Content-Type", file.type); }, url: serverUrl, data: file, processData: false, contentType: false, success: function(data) { console.log("File available at: " + data.url); imgdata = data.url; imgdata = JSON.stringify(imgdata); console.log(imgdata + "Is the Link"); return(imgdata); // sendProfilePicture(); }, error: function(data) { var obj = jQuery.parseJSON(data); alert(obj.error); } }); } >>>>>>> origin/Tom
const _ = require('lodash') const REPEAT = 0 // 顺序播放 const REPEAT_ONE = 1 // 单曲循环 const SHUFFLE = 2 // 随机 export default { state: { playing: false, currentPlay: null, currentTime: 0, titleTime: 0, duration: 0, percent: 0, playQueue: [], // swiper初始列表 operedQueue: [], // 切歌时间timeGap不能上下曲操作 timeGap: false, // 点击上下曲,同步swiper clickNextPrev: false, loopMode: REPEAT, modeID: -1 }, getters: { currentInd(state) { return state.playQueue.findIndex(v => { return _.isEqual(v,state.currentPlay) }) }, operedInd(state) { return state.operedQueue.findIndex(v => { return _.isEqual(v,state.currentPlay) }) }, loopModeIndex(state) { } }, mutations: { // 专辑页插入列表 albumAdd(state,obj) { let arr = [] obj.list.forEach((val) => { let song = { name: val.songname, mid: val.songmid, singer: obj.singer, albummid: val.albummid } song.url = `https://dl.stream.qqmusic.qq.com/C100${song.mid}.m4a?fromtag=46` song.img = `https://y.gtimg.cn/music/photo_new/T002R300x300M000${song.albummid}.jpg?max_age=2592000` arr.push(song) }) // 数组合并去重 let opered = _.unionWith(arr, state.playQueue, _.isEqual) state.playQueue = opered state.currentPlay = state.playQueue[obj.ind] }, // 插入播放列表 songTo(state,obj) { let arr = [] obj.list.forEach((val) => { let song = { name: val.name, mid: val.mid, singer: val.singer, albummid: val.albummid } song.url = `https://dl.stream.qqmusic.qq.com/C100${song.mid}.m4a?fromtag=46` song.img = `https://y.gtimg.cn/music/photo_new/T002R300x300M000${song.albummid}.jpg?max_age=2592000` arr.push(song) }) // 数组合并去重 let opered = _.unionWith(arr, state.playQueue, _.isEqual) state.playQueue = opered state.currentPlay = state.playQueue[obj.ind] }, deleteSong(state,obj) { state.playQueue.splice(obj.ind,1) let Cmid = state.currentPlay.mid if(state.playQueue.length === 0) { state.currentPlay = null return } if(obj.mid === Cmid && state.playQueue.length > 0) { state.currentPlay = state.playQueue[obj.ind] || state.playQueue[0] } } }, actions: { // 歌曲面板操作上/下首歌,val: 1表下一首,0表上一首 toNextPrev(context,val) { context.dispatch('_getRandom') let modeID = context.state.modeID let curr = context.state let currInd = curr.playQueue.findIndex(v => { return _.isEqual(v,curr.currentPlay) }) let sign = val || -1 let tar = val? 0: curr.playQueue.length - 1 if(currInd >= 0) { curr.currentPlay = null curr.currentPlay = curr.playQueue[currInd + (sign * modeID)] || curr.playQueue[tar] } curr.clickNextPrev = !curr.clickNextPrev }, // 针对swiper的切歌事件 playAtIndex(context,ind) { let curr = context.state if(typeof ind !== 'number') { let i = ind.ind if(i >= curr.playQueue.length) return curr.currentPlay = curr.playQueue[i] curr.clickNextPrev = !curr.clickNextPrev return } if(ind >= curr.operedQueue.length) return curr.currentPlay = curr.operedQueue[ind] }, // 对于随机播放更新random值 _getRandom(context) { let ctt = context.state switch(ctt.loopMode) { case REPEAT: ctt.modeID = 1 break case REPEAT_ONE: ctt.modeID = 0 break case SHUFFLE: let ind = parseInt(Math.random() * (ctt.playQueue.length - 1)) + 1 ctt.modeID = ind break } }, addToList(context,song) { let queue = context.state.playQueue let currInd = queue.findIndex(v => { return _.isEqual(v,song) }) if(currInd >= 0) { context.state.playQueue.splice(currInd,1) context.state.playQueue.push(song) return } let arr = [] arr.push(song) context.state.playQueue = _.unionWith(queue,arr, _.isEqual) if(context.state.playQueue.length === 1) { context.state.currentPlay = context.state.playQueue[0] } }, addPlayNext(context,song) { let queue = context.state.playQueue let currInd = queue.findIndex(v => { return _.isEqual(v,song) }) if(currInd === 0) return if(currInd > 0) { context.state.playQueue.splice(currInd,1) } if(context.state.playQueue.length === 0) { context.state.playQueue.push(song) context.state.currentPlay = context.state.playQueue[0] return } context.state.playQueue.splice(1,0,song) } } }
console.log('Loading function'); var fs = require('fs'); exports.handler = function (event, context) { fs.readFile('/tmp/test.txt', 'utf-8', function (err, data) { if (err) { console.log('readFile err =>', err); fs.writeFile('/tmp/test.txt', 'Hello World', function (err) { if (err) { console.log('writeFile err =>', err); } else { console.log('File write completed'); } context.done(err, 'success!'); }); } else { console.log('readFile data =>', data); context.done(err, 'success!'); } }); };
import React from 'react' import {Link} from 'react-router-dom' import "./index.css" import Alink from "@/components/common/List" import Time from "@/components/common/Time" import Author from "@/components/common/User/author" export default ({title,listData,show}) => { return ( <div> <h2>{title}</h2> <ul> { listData&&listData.map((item,index)=> <li className="list" key={index}> {show?<span className="photo"> <Author to={`/user/${item.author.loginname}`} imgUrl={item.author.avatar_url} ></Author> </span>:null} <span className="title"> <Alink to={`/topic/${item.id}`} title={item.title} ></Alink> </span> {show? <span className="time"> <Time timeStr={item.last_reply_at}></Time> </span>:null} </li> ) } </ul> </div> ) }
var dhhSprite = document.getElementById('dhh-sprite'); var dhhClips = { whoops: { start: 10.45, length: 0.731 }, worked: { start: 8.62, length: 1.67 }, not_doing: { start: 2.8, length: 1.7 }, not_alot: { start: 4.78, length: 3.5 }, ruby_everywhere: { start: 0.5, length: 1.8 } }; var currentDHH = {}; var everPlayed = false; var updateTimeTracking = function() { if (this.currentTime >= currentDHH.start + currentDHH.length) { this.pause(); } }; dhhSprite.addEventListener('timeupdate', updateTimeTracking, false); var setup_audio = function(btn_id, audio_id) { $(btn_id).on("click", function(event) { event.preventDefault(); playAudio(audio_id); }); }; playAudio = function(track) { if (dhhClips[track] && dhhClips[track].length) { currentDHH = dhhClips[track]; if (!everPlayed) { // This is shady mobile safari business here. We can't set the current time until it's been played. Lé sigh. dhhSprite.addEventListener("playing", function(){ this.currentTime = currentDHH.start; everPlayed = true; }); dhhSprite.play(); } else { dhhSprite.currentTime = currentDHH.start; dhhSprite.play(); } } }; setup_audio("#whoops-btn", 'whoops'); setup_audio("#it-worked-btn", "worked"); setup_audio("#not-doing-btn", "not_doing"); setup_audio("#not-a-lot-of-work-btn", "not_alot"); setup_audio("#ruby-everywhere-btn", "ruby_everywhere");
import React from 'react' import './card.css' import vlad from './../../images/vladi-shrek.png' function Vlad(){ return( <> <div className="container"> <div className="card"> <div className="sneaker"> <div className="circle"><img src={vlad}/></div> </div> <div className="info"> <h1 className="title">VladiShrek PACK</h1> <h3>Un monstre de performance, un midlaner impitoyavble, ses cris de rage feront fuire tout vos ennemis potentiel.</h3> <div className="purchase"> <button>69 420 </button> </div> </div> </div> </div> </> ) } export default Vlad;
import React from 'react'; import UserCommentCard from './UserCommentCard'; import UserNewCommentForm from './UserNewCommentForm'; function UserCommentList({currentUser, userPostComments, setUserPostComments, postId}){ function addComment(commentObj){ const newArr = [...userPostComments, commentObj] setUserPostComments(newArr) } function updateComment(updatedCommentObj){ const newArr = userPostComments.map((comment) => { if (comment.id === updatedCommentObj.id){ return updatedCommentObj } else { return comment } }) setUserPostComments(newArr) } function deleteComment(id){ const newArr = userPostComments.filter((comment) => { return comment.id !== id }) setUserPostComments(newArr) } const commentCardArr = userPostComments.map((comment) => { return( <div> <UserCommentCard // key={`comment-${comment.id}`} key={`comment-${comment.id}`} comment={comment} currentUser={currentUser} updateComment={updateComment} deleteComment={deleteComment} /> </div> ) }) return( <div className="post-comment-list-div"> {commentCardArr} <UserNewCommentForm currentUser={currentUser} postId={postId} addComment={addComment} /> </div> ) } export default UserCommentList;
import React from 'react'; import GraphiQL from 'graphiql'; import { getOperationAST, parse } from 'graphql'; import GraphiQLExplorer from 'graphiql-explorer'; import StorageAPI from 'graphiql/dist/utility/StorageAPI'; import './postgraphiql.css'; import { buildClientSchema, getIntrospectionQuery, isType, GraphQLObjectType } from 'graphql'; import { SubscriptionClient } from 'subscriptions-transport-ws'; import { createClient } from 'graphql-ws'; import formatSQL from '../formatSQL'; const defaultQuery = `\ # Welcome to PostGraphile's built-in GraphiQL IDE # # GraphiQL is an in-browser tool for writing, validating, and # testing GraphQL queries. # # Type queries into this side of the screen, and you will see intelligent # typeaheads aware of the current GraphQL type schema and live syntax and # validation errors highlighted within the text. # # GraphQL queries typically start with a "{" character. Lines that starts # with a # are ignored. # # An example GraphQL query might look like: # # { # field(arg: "value") { # subField # } # } # # Keyboard shortcuts: # # Prettify Query: Shift-Ctrl-P (or press the prettify button above) # # Merge Query: Shift-Ctrl-M (or press the merge button above) # # Run Query: Ctrl-Enter (or press the play button above) # # Auto Complete: Ctrl-Space (or just start typing) # `; const isSubscription = ({ query, operationName }) => { const node = parse(query); const operation = getOperationAST(node, operationName); return operation && operation.operation === 'subscription'; }; const { POSTGRAPHILE_CONFIG = { graphqlUrl: 'http://localhost:5000/graphql', streamUrl: 'http://localhost:5000/graphql/stream', enhanceGraphiql: true, websockets: 'none', // 'none' | 'v0' | 'v1' allowExplain: true, credentials: 'same-origin', }, } = window; const isValidJSON = json => { try { JSON.parse(json); return true; } catch (e) { return false; } }; const l = window.location; const websocketUrl = POSTGRAPHILE_CONFIG.graphqlUrl.match(/^https?:/) ? POSTGRAPHILE_CONFIG.graphqlUrl.replace(/^http/, 'ws') : `ws${l.protocol === 'https:' ? 's' : ''}://${l.hostname}${ l.port !== 80 && l.port !== 443 ? ':' + l.port : '' }${POSTGRAPHILE_CONFIG.graphqlUrl}`; const STORAGE_KEYS = { SAVE_HEADERS_TEXT: 'PostGraphiQL:saveHeadersText', HEADERS_TEXT: 'PostGraphiQL:headersText', EXPLAIN: 'PostGraphiQL:explain', }; /** * The standard GraphiQL interface wrapped with some PostGraphile extensions. * Including a JWT setter and live schema udpate capabilities. */ class PostGraphiQL extends React.PureComponent { // Use same storage as GraphiQL to save explorer visibility state _storage = new StorageAPI(); state = { // Our GraphQL schema which GraphiQL will use to do its intelligence // stuffs. schema: null, query: '', showHeaderEditor: false, saveHeadersText: this._storage.get(STORAGE_KEYS.SAVE_HEADERS_TEXT) === 'true', headersText: this._storage.get(STORAGE_KEYS.HEADERS_TEXT) || '{\n"Authorization": null\n}\n', explain: this._storage.get(STORAGE_KEYS.EXPLAIN) === 'true', explainResult: null, headersTextValid: true, explorerIsOpen: this._storage.get('explorerIsOpen') === 'false' ? false : true, haveActiveSubscription: false, socketStatus: POSTGRAPHILE_CONFIG.websockets === 'none' ? null : 'pending', }; restartRequested = false; restartSubscriptionsClient = () => { // implementation will be replaced... this.restartRequested = true; }; maybeSubscriptionsClient = () => { switch (POSTGRAPHILE_CONFIG.websockets) { case 'none': return; case 'v0': const client = new SubscriptionClient(websocketUrl, { reconnect: true, connectionParams: () => this.getHeaders() || {}, }); const unlisten1 = client.on('connected', () => { this.setState({ socketStatus: 'connected', error: null }); }); const unlisten2 = client.on('disconnected', () => { this.setState({ socketStatus: 'closed', error: new Error('Socket disconnected') }); }); const unlisten3 = client.on('connecting', () => { this.setState({ socketStatus: 'connecting' }); }); const unlisten4 = client.on('reconnected', () => { this.setState({ socketStatus: 'connected', error: null }); }); const unlisten5 = client.on('reconnecting', () => { this.setState({ socketStatus: 'connecting' }); }); const unlisten6 = client.on('error', error => { // tslint:disable-next-line no-console console.error('Client connection error', error); this.setState({ error: new Error('Subscriptions client connection error') }); }); this.unlistenV0SubscriptionsClient = () => { unlisten1(); unlisten2(); unlisten3(); unlisten4(); unlisten5(); unlisten6(); }; // restart by closing the socket which should trigger a silent reconnect this.restartSubscriptionsClient = () => { this.subscriptionsClient.close(false, true); }; // if any restarts were missed during the connection // phase, restart and reset the request if (this.restartRequested) { this.restartRequested = false; this.restartSubscriptionsClient(); } return client; case 'v1': return createClient({ url: websocketUrl, lazy: false, retryAttempts: Infinity, // keep retrying while the browser is open connectionParams: () => this.getHeaders() || {}, on: { connecting: () => { this.setState({ socketStatus: 'connecting' }); }, connected: socket => { this.setState({ socketStatus: 'connected', error: null }); // restart by closing the socket which will trigger a silent reconnect this.restartSubscriptionsClient = () => { if (socket.readyState === WebSocket.OPEN) { socket.close(4205, 'Client Restart'); } }; // if any restarts were missed during the connection // phase, restart and reset the request if (this.restartRequested) { this.restartRequested = false; this.restartSubscriptionsClient(); } }, closed: closeEvent => { this.setState({ socketStatus: 'closed', error: new Error(`Socket closed with ${closeEvent.code} ${closeEvent.reason}`), }); }, }, }); default: throw new Error(`Invalid websockets argument ${POSTGRAPHILE_CONFIG.websockets}`); } }; activeSubscription = null; componentDidMount() { // Update the schema for the first time. Log an error if we fail. this.updateSchema(); // Connect socket if should connect this.subscriptionsClient = this.maybeSubscriptionsClient(); // If we were given a `streamUrl`, we want to construct an `EventSource` // and add listeners. if (POSTGRAPHILE_CONFIG.streamUrl) { // Starts listening to the event stream at the `sourceUrl`. const eventSource = new EventSource(POSTGRAPHILE_CONFIG.streamUrl); // When we get a change notification, we want to update our schema. eventSource.addEventListener( 'change', () => { this.updateSchema(); }, false, ); // Add event listeners that just log things in the console. eventSource.addEventListener( 'open', () => { // tslint:disable-next-line no-console console.log('PostGraphile: Listening for server sent events'); this.setState({ error: null }); this.updateSchema(); }, false, ); eventSource.addEventListener( 'error', error => { // tslint:disable-next-line no-console console.error('PostGraphile: Failed to connect to event stream', error); this.setState({ error: new Error('Failed to connect to event stream') }); }, false, ); // Store our event source so we can unsubscribe later. this._eventSource = eventSource; } const graphiql = this.graphiql; this.setState({ query: graphiql._storage.get('query') || defaultQuery }); const editor = graphiql.getQueryEditor(); editor.setOption('extraKeys', { ...(editor.options.extraKeys || {}), 'Shift-Alt-LeftClick': this._handleInspectOperation, }); } componentWillUnmount() { // Dispose of connection if available if (this.subscriptionsClient) { if (this.unlistenV0SubscriptionsClient) { // v0 this.unlistenV0SubscriptionsClient(); } else { // v1 this.subscriptionsClient.dispose(); } this.subscriptionsClient = null; } // Close out our event source so we get no more events. this._eventSource.close(); this._eventSource = null; } _handleInspectOperation = (cm, mousePos) => { const parsedQuery = parse(this.state.query || ''); if (!parsedQuery) { console.error("Couldn't parse query document"); return null; } var token = cm.getTokenAt(mousePos); var start = { line: mousePos.line, ch: token.start }; var end = { line: mousePos.line, ch: token.end }; var relevantMousePos = { start: cm.indexFromPos(start), end: cm.indexFromPos(end), }; var position = relevantMousePos; var def = parsedQuery.definitions.find(definition => { if (!definition.loc) { console.log('Missing location information for definition'); return false; } const { start, end } = definition.loc; return start <= position.start && end >= position.end; }); if (!def) { console.error('Unable to find definition corresponding to mouse position'); return null; } var operationKind = def.kind === 'OperationDefinition' ? def.operation : def.kind === 'FragmentDefinition' ? 'fragment' : 'unknown'; var operationName = def.kind === 'OperationDefinition' && !!def.name ? def.name.value : def.kind === 'FragmentDefinition' && !!def.name ? def.name.value : 'unknown'; var selector = `.graphiql-explorer-root #${operationKind}-${operationName}`; var el = document.querySelector(selector); el && el.scrollIntoView(); }; cancelSubscription = () => { if (this.activeSubscription !== null) { this.activeSubscription.unsubscribe(); this.setState({ haveActiveSubscription: false, }); } }; /** * Get the user editable headers as an object */ getHeaders = () => { const { headersText } = this.state; let extraHeaders; try { extraHeaders = JSON.parse(headersText); for (const k in extraHeaders) { if (extraHeaders[k] == null) { delete extraHeaders[k]; } } } catch (e) { // Do nothing } return extraHeaders; }; /** * Executes a GraphQL query with some extra information then the standard * parameters. Namely a JWT which may be added as an `Authorization` header. */ executeQuery = async graphQLParams => { const extraHeaders = this.getHeaders(); const response = await fetch(POSTGRAPHILE_CONFIG.graphqlUrl, { method: 'POST', headers: Object.assign( { Accept: 'application/json', 'Content-Type': 'application/json', ...(this.state.explain && POSTGRAPHILE_CONFIG.allowExplain ? { 'X-PostGraphile-Explain': 'on' } : null), }, extraHeaders, ), credentials: POSTGRAPHILE_CONFIG.credentials, body: JSON.stringify(graphQLParams), }); const result = await response.json(); this.setState({ explainResult: result && result.explain ? result.explain : null }); return result; }; /** * Routes the request either to the subscriptionClient or to executeQuery. */ fetcher = graphQLParams => { this.cancelSubscription(); if (isSubscription(graphQLParams) && this.subscriptionsClient) { const client = this.subscriptionsClient; return { subscribe: observer => { setTimeout(() => { // Without this timeout, this message doesn't display on the first // subscription after the first render of the page. observer.next('Waiting for subscription to yield data…'); }, 0); const subscription = POSTGRAPHILE_CONFIG.websockets === 'v0' ? client.request(graphQLParams).subscribe(observer) : // v1 { unsubscribe: client.subscribe(graphQLParams, { next: observer.next, complete: observer.complete, error: err => { if (err instanceof Error) { observer.error(err); } else if (err instanceof CloseEvent) { observer.error( new Error( `Socket closed with event ${err.code}` + err.reason ? `: ${err.reason}` // reason will be available on clean closes : '', ), ); } else { // GraphQLError[] observer.error(new Error(err.map(({ message }) => message).join(', '))); } }, }), }; this.setState({ haveActiveSubscription: true }); this.activeSubscription = subscription; return subscription; }, }; } else { return this.executeQuery(graphQLParams); } }; /** * When we recieve an event signaling a change for the schema, we must rerun * our introspection query and notify the user of the results. */ // TODO: Send the introspection query results in the server sent event? async updateSchema() { try { // Fetch the schema using our introspection query and report once that has // finished. const { data } = await this.executeQuery({ query: getIntrospectionQuery() }); // Use the data we got back from GraphQL to build a client schema (a // schema without resolvers). const schema = buildClientSchema(data); // Update our component with the new schema. this.setState({ schema }); // Do some hacky stuff to GraphiQL. this._updateGraphiQLDocExplorerNavStack(schema); // tslint:disable-next-line no-console console.log('PostGraphile: Schema updated'); this.setState({ error: null }); } catch (error) { // tslint:disable-next-line no-console console.error('Error occurred when updating the schema:'); // tslint:disable-next-line no-console console.error(error); this.setState({ error }); } } /** * Updates the GraphiQL documentation explorer’s navigation stack. This * depends on private API. By default the GraphiQL navigation stack uses * objects from a GraphQL schema. Therefore if the schema is updated, the * old objects will still be in the navigation stack. This is bad for us * because we want to reflect the new schema information! So, we manually * update the navigation stack with this function. * * I’m sorry Lee Byron. */ // TODO: Submit a PR which adds this as a non-hack. _updateGraphiQLDocExplorerNavStack(nextSchema) { // Get the documentation explorer component from GraphiQL. Unfortunately // for them this looks like public API. Muwahahahaha. const { docExplorerComponent } = this.graphiql; if (!docExplorerComponent) { console.log('No docExplorerComponent, could not update navStack'); return; } const { navStack } = docExplorerComponent.state; // If one type/field isn’t find this will be set to false and the // `navStack` will just reset itself. let allOk = true; let exitEarly = false; // Ok, so if you look at GraphiQL source code, the `navStack` is made up of // objects that are either types or fields. Let’s use that to search in // our new schema for matching (updated) types and fields. const nextNavStack = navStack .map((navStackItem, i) => { // If we are not ok, abort! if (exitEarly || !allOk) return null; // Get the definition from the nav stack item. const typeOrField = navStackItem.def; // If there is no type or field then this is likely the root schema view, // or a search. If this is the case then just return that nav stack item! if (!typeOrField) { return navStackItem; } else if (isType(typeOrField)) { // If this is a type, let’s do some shenanigans... // Let’s see if we can get a type with the same name. const nextType = nextSchema.getType(typeOrField.name); // If there is no type with this name (it was removed), we are not ok // so set `allOk` to false and return undefined. if (!nextType) { exitEarly = true; return null; } // If there is a type with the same name, let’s return it! This is the // new type with all our new information. return { ...navStackItem, def: nextType }; } else { // If you thought this function was already pretty bad, it’s about to get // worse. We want to update the information for an object field. // Ok, so since this is an object field, we will assume that the last // element in our stack was an object type. const nextLastType = nextSchema.getType(navStack[i - 1] ? navStack[i - 1].name : null); // If there is no type for the last type in the nav stack’s name. // Panic! if (!nextLastType) { allOk = false; return null; } // If the last type is not an object type. Panic! if (!(nextLastType instanceof GraphQLObjectType)) { allOk = false; return null; } // Next we will see if the new field exists in the last object type. const nextField = nextLastType.getFields()[typeOrField.name]; // If not, Panic! if (!nextField) { allOk = false; return null; } // Otherwise we hope very much that it is correct. return { ...navStackItem, def: nextField }; } }) .filter(_ => _); // This is very hacky but works. React is cool. if (allOk) { this.graphiql.docExplorerComponent.setState({ // If we are not ok, just reset the `navStack` with an empty array. // Otherwise use our new stack. navStack: nextNavStack, }); } } getQueryEditor = () => { return this.graphiql.getQueryEditor(); }; handleEditQuery = query => { this.setState({ query }); }; handleEditHeaders = headersText => { this.setState( { headersText, headersTextValid: isValidJSON(headersText), }, () => { if (this.state.headersTextValid && this.state.saveHeadersText) { this._storage.set(STORAGE_KEYS.HEADERS_TEXT, this.state.headersText); } if (this.state.headersTextValid && this.subscriptionsClient) { // Reconnect to websocket with new headers this.restartSubscriptionsClient(); } }, ); }; handlePrettifyQuery = () => { const editor = this.getQueryEditor(); if (typeof window.prettier !== 'undefined' && typeof window.prettierPlugins !== 'undefined') { // TODO: window.prettier.formatWithCursor editor.setValue( window.prettier.format(editor.getValue(), { parser: 'graphql', plugins: window.prettierPlugins, }), ); } else { return this.graphiql.handlePrettifyQuery(); } }; handleToggleHistory = e => { this.graphiql.handleToggleHistory(e); }; handleToggleHeaders = () => { this.setState({ showHeaderEditor: !this.state.showHeaderEditor }); }; handleToggleExplorer = () => { this.setState({ explorerIsOpen: !this.state.explorerIsOpen }, () => this._storage.set( 'explorerIsOpen', // stringify so that storage API will store the state (it deletes key if value is false) JSON.stringify(this.state.explorerIsOpen), ), ); }; handleToggleSaveHeaders = () => { this.setState( oldState => ({ saveHeadersText: !oldState.saveHeadersText }), () => { this._storage.set( STORAGE_KEYS.SAVE_HEADERS_TEXT, JSON.stringify(this.state.saveHeadersText), ); this._storage.set( STORAGE_KEYS.HEADERS_TEXT, this.state.saveHeadersText ? this.state.headersText : '', ); }, ); }; handleToggleExplain = () => { this.setState( oldState => ({ explain: !oldState.explain }), () => { this._storage.set(STORAGE_KEYS.EXPLAIN, JSON.stringify(this.state.explain)); try { this.graphiql.handleRunQuery(); } catch (e) { /* ignore */ } }, ); }; renderSocketStatus() { const { socketStatus, error } = this.state; if (socketStatus === null) { return null; } const icon = { connecting: '🤔', connected: '😀', closed: '☹️', }[socketStatus] || '😐'; const tick = ( <path fill="transparent" stroke="white" d="M30,50 L45,65 L70,30" strokeWidth="8" /> ); const cross = ( <path fill="transparent" stroke="white" d="M30,30 L70,70 M30,70 L70,30" strokeWidth="8" /> ); const decoration = { connecting: null, connected: tick, closed: cross, }[socketStatus] || null; const color = { connected: 'green', connecting: 'orange', closed: 'red', }[socketStatus] || 'gray'; const svg = ( <svg width="25" height="25" viewBox="0 0 100 100" style={{ marginTop: 4 }}> <circle fill={color} cx="50" cy="50" r="45" /> {decoration} </svg> ); return ( <> {error ? ( <div style={{ fontSize: '1.5em', marginRight: '0.25em' }} title={error.message || `Error occurred: ${error}`} onClick={() => this.setState({ error: null })} > <span aria-label="ERROR" role="img"> {'⚠️'} </span> </div> ) : null} <div style={{ fontSize: '1.5em', marginRight: '0.25em' }} title={'Websocket status: ' + socketStatus} onClick={this.cancelSubscription} > <span aria-label={socketStatus} role="img"> {svg || icon} </span> </div> </> ); } setGraphiqlRef = ref => { if (!ref) { return; } this.graphiql = ref; this.setState({ mounted: true }); }; render() { const { schema } = this.state; const sharedProps = { ref: this.setGraphiqlRef, schema: schema, fetcher: this.fetcher, }; if (!POSTGRAPHILE_CONFIG.enhanceGraphiql) { return <GraphiQL {...sharedProps} />; } else { return ( <div className={`postgraphiql-container graphiql-container ${ this.state.explain && this.state.explainResult && this.state.explainResult.length ? 'explain-mode' : '' }`} > <GraphiQLExplorer schema={schema} query={this.state.query} onEdit={this.handleEditQuery} onRunOperation={operationName => this.graphiql.handleRunQuery(operationName)} explorerIsOpen={this.state.explorerIsOpen} onToggleExplorer={this.handleToggleExplorer} //getDefaultScalarArgValue={getDefaultScalarArgValue} //makeDefaultArg={makeDefaultArg} /> <GraphiQL onEditQuery={this.handleEditQuery} query={this.state.query} headerEditorEnabled headers={this.state.headersText} onEditHeaders={this.handleEditHeaders} {...sharedProps} > <GraphiQL.Logo> <div style={{ display: 'flex', alignItems: 'center' }}> <div> <img alt="PostGraphile logo" src="https://www.graphile.org/images/postgraphile-tiny.optimized.svg" width="32" height="32" style={{ marginTop: '4px', marginRight: '0.5rem' }} /> </div> <div> PostGraph <em>i</em> QL </div> </div> </GraphiQL.Logo> <GraphiQL.Toolbar> {this.renderSocketStatus()} <GraphiQL.Button onClick={this.handlePrettifyQuery} title="Prettify Query (Shift-Ctrl-P)" label="Prettify" /> <GraphiQL.Button onClick={this.handleToggleHistory} title="Show History" label="History" /> <GraphiQL.Button label="Explorer" title="Construct a query with the GraphiQL explorer" onClick={this.handleToggleExplorer} /> <GraphiQL.Button onClick={this.graphiql && this.graphiql.handleMergeQuery} title="Merge Query (Shift-Ctrl-M)" label="Merge" /> <GraphiQL.Button onClick={this.graphiql && this.graphiql.handleCopyQuery} title="Copy Query (Shift-Ctrl-C)" label="Copy" /> {POSTGRAPHILE_CONFIG.allowExplain ? ( <GraphiQL.Button label={this.state.explain ? 'Explain ON' : 'Explain disabled'} title="View the SQL statements that this query invokes" onClick={this.handleToggleExplain} /> ) : null} <GraphiQL.Button label={'Headers ' + (this.state.saveHeadersText ? 'SAVED' : 'unsaved')} title="Should we persist the headers to localStorage? Header editor is next to variable editor at the bottom." onClick={this.handleToggleSaveHeaders} /> </GraphiQL.Toolbar> <GraphiQL.Footer> <div className="postgraphile-footer"> {this.state.explainResult && this.state.explainResult.length ? ( <div className="postgraphile-plan-footer"> {this.state.explainResult.map(res => ( <div> <h4> Result from SQL{' '} <a href="https://www.postgresql.org/docs/current/sql-explain.html"> EXPLAIN </a>{' '} on executed query: </h4> <pre className="explain-plan"> <code>{res.plan}</code> </pre> <h4>Executed SQL query:</h4> <pre className="explain-sql"> <code>{formatSQL(res.query)}</code> </pre> </div> ))} <p> Having performance issues?{' '} <a href="https://www.graphile.org/support/">We can help with that!</a> </p> <hr /> </div> ) : null} <div className="postgraphile-regular-footer"> PostGraphile:{' '} <a title="Open PostGraphile documentation" href="https://graphile.org/postgraphile/introduction/" target="new" > Documentation </a>{' '} |{' '} <a title="Open PostGraphile documentation" href="https://graphile.org/postgraphile/examples/" target="new" > Examples </a>{' '} |{' '} <a title="PostGraphile is supported by the community, please sponsor ongoing development" href="https://graphile.org/sponsor/" target="new" > Sponsor </a>{' '} |{' '} <a title="Get support from the team behind PostGraphile" href="https://graphile.org/support/" target="new" > Support </a> </div> </div> </GraphiQL.Footer> </GraphiQL> </div> ); } } } export default PostGraphiQL;
SB.Examples.Monsters = function() { SB.Game.call(this); this.helpScreen = null; } goog.inherits(SB.Examples.Monsters, SB.Game); SB.Examples.Monsters.prototype.initialize = function(param) { if (!param) param = {}; if (!param.backgroundColor) param.backgroundColor = SB.Examples.Monsters.default_bgcolor; if (!param.displayStats) param.displayStats = SB.Examples.Monsters.default_display_stats; param.tabstop = true; SB.Game.prototype.initialize.call(this, param); this.initEntities(); } SB.Examples.Monsters.prototype.initEntities = function() { this.root = new SB.Entity; var ambientLight = new SB.Entity; var light = new SB.AmbientLight({color:0xFFFFFF}); ambientLight.addComponent(light); this.root.addChild(ambientLight); var grid = new SB.Grid({size: 14}); this.root.addComponent(grid); var m1 = new SB.Examples.Monster(); m1.transform.position.x = 5; var m2 = new SB.Examples.Monster(); m2.transform.position.x = -5; var m3 = new SB.Examples.Monster(); m3.transform.position.z = -5; this.monsters = [m1, m2, m3]; this.activeMonster = null; var viewer = SB.Prefabs.WalkthroughController({ active : true, headlight : false }); viewer.transform.position.set(0, 2.5, 3.67); this.root.addChild(m1); this.root.addChild(m2); this.root.addChild(m3); this.root.addChild(viewer); this.addEntity(this.root); this.root.realize(); } SB.Examples.Monsters.prototype.onKeyDown = function(keyCode, charCode) { if (this.activeMonster) this.activeMonster.onKeyDown(keyCode, charCode); else SB.Game.prototype.onKeyDown.call(this, keyCode, charCode) } SB.Examples.Monsters.prototype.onKeyUp = function(keyCode, charCode) { var mi; var handled = false; switch (String.fromCharCode(keyCode)) { case 'H' : this.help(); handled = true; break; case '1' : mi = 1; break; case '2' : mi = 2; break; case '3' : mi = 3; break; default : break; } if (!handled && this.activeMonster) { this.activeMonster.onKeyUp(keyCode, charCode); } if (mi) { var monster = this.monsters[mi-1]; this.setActiveMonster(monster); } if (!handled) SB.Game.prototype.onKeyUp.call(this, keyCode, charCode) } SB.Examples.Monsters.prototype.onKeyPress = function(keyCode, charCode) { SB.Game.prototype.onKeyPress.call(this, keyCode, charCode) } SB.Examples.Monsters.prototype.setActiveMonster = function(monster) { if (this.activeMonster) { this.activeMonster.setActive(false); } monster.setActive(true); this.activeMonster = monster; } SB.Examples.Monsters.prototype.help = function() { if (!this.helpScreen) { this.helpScreen = new SB.Examples.MonstersHelp(); } this.helpScreen.show(); } SB.Examples.Monsters.default_bgcolor = '#000000'; SB.Examples.Monsters.default_display_stats = true;
import db from '../_database.js'; export async function get(req, res) { console.log('Getting popular tabs...') const popularTabs = await db.getPopular().catch((e) => { console.log('ERROR getting popular tabs: ') console.log(e) }) // const recentTabs = await db.checkHealth().catch((e) => {console.log("ERROR: "); console.log(e)}) // // console.log(recentTabs) res.writeHead(200, { 'Content-Type': 'application/json' }); res.on('error', (err) => { console.error(err) }) res.end(JSON.stringify(popularTabs)); }
module('formalia.js tests'); test('Test a simple form', function() { var form = '<form>' + '<input type="text" name="test1">' + '<input type="text" name="test2">' + '<input type="text" name="test3">' + '<input type="text" name="test4">' + '</form>'; var $form1 = $(form); $form1.formalia(); $form1.find('[name=test1]').prop('value', 'Test 1').trigger('change');; var $form2 = $(form); $form2.formalia(); ok($form1.find('[name=test1]').prop('value') == $form2.find('[name=test1]').prop('value'), 'Content is cached and loaded into form again'); }); test('Submitting a form removes cache content', function() { var form = '<form>' + '<input type="text" name="test1">' + '<input type="text" name="test2">' + '<input type="text" name="test3">' + '<input type="text" name="test4">' + '</form>'; var $form1 = $(form); $form1.formalia(); $form1.find('[name=test1]').prop('value', 'Test 1').trigger('change').trigger('submit'); var $form2 = $(form); $form2.formalia(); ok($form2.find('[name=test1]').prop('value') === '', 'Cached content is cleared on submit.'); }); test('Test actions performed on form', function() { var form = '<form>' + '<input type="text" name="test1">' + '<input type="text" name="test2">' + '<input type="text" name="test3">' + '<input type="text" name="test4">' + '</form>'; var $form1 = $(form); $form1.formalia(); $form1.find('[name=test1]').prop('value', 'Test 1').trigger('change'); $form1.formalia('reset'); ok($form1.find('[name=test1]').prop('value') === '', 'Form is reset to default values'); });
import styled from "styled-components"; import fenli from "../../assets/img/icon_cla@2x.png"; import kefu from "../../assets/img/icon_service@2x.png"; import sear from "../../assets/img/nav_search@2x.png"; export const WraperHeader = styled.div` padding: 10px 0; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; display: flex; margin: 0; background:green; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; -webkit-text-size-adjust: none; -webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); box-sizing: border-box; ` export const HeaderFenli = styled.div` width: 10%; text-align: center; display: block; ` export const Fenli = styled.a` color: #333; font-size: 10px; display: block; width: 100%; height: 100%; text-decoration: none; cursor: pointer; color: #888888; -webkit-tap-highlight-color: rgba(255, 255, 255, 0); ` export const IconTag = styled.i` display: block; width: 37.5px; height: 18px; margin: 0 auto; font-style: normal; margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; -webkit-text-size-adjust: none; -webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); &.head_icon{ background-image: url(${fenli}); background-size: 18px auto; background-repeat: no-repeat; background-position:9px 0; }; ` export const SearchBar = styled.div` position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; -webkit-flex-shrink: 1; -ms-flex-negative: 1; flex-shrink: 1; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; ` export const KeFu = styled.div` width: 10%; text-align: center; ` export const IconTags = styled.i` display: block; width: 37.5px; height: 18px; margin: 0 auto; font-style: normal; margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; -webkit-text-size-adjust: none; -webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); &.kefu_icon{ background-image: url(${kefu}); background-size: 18px auto; background-repeat: no-repeat; background-position:9px 0; }; ` export const Inpu = styled.input.attrs({ placeholder:"请输入搜索内容" })` width: 100%; padding-left: 42px; height: 30px; line-height: 30px; border-radius: 25px; border: none; background: #f6f6f6; box-sizing: border-box; font-size: 13px; outline:none; ` export const Searc = styled.i` display: block; width: 18.48px; height: 19.98px; position: absolute; top: 50%; left: 14px; -webkit-transform: translate3d(0, -50%, 0); -ms-transform: translate3d(0, -50%, 0); transform: translate3d(0, -50%, 0); &.search{ background: url(${sear}) no-repeat; background-size: cover; } `
/** * Created by candellc on 2016-02-29. */ function whenClicked(brick) { $(brick).addClass("animateBrickPulse"); $(".CRABrickWideSpecial").addClass("animateSeparateCrack"); $(".CRBrickWideSpecial").addClass("animateSeparateCrumble"); $(".CRABrickWideSpecial").one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() { // code to execute after animation ends $(".CRABrickWideSpecial").css("background-image", "url('Img/scratchBrickSeperatedComplete.png')"); $(".CRABrickWideSpecial").removeClass("animateSeparateCrack"); $(".CRABrickWideSpecial").css("background-image", "url('Img/transparentPNG.png')"); $(".crackedBrickWideSpecialLeft").css("z-index", "10"); $(".crackedBrickWideSpecialRight").css("z-index", "10"); $(".crackedBrickWideSpecialLeft").css("display", "inline-block"); $(".crackedBrickWideSpecialRight").css("display", "inline-block"); //myBox.removeClass('change-size'); }); $(".CRBrickWideSpecial").one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() { // code to execute after animation ends $(".CRBrickWideSpecial").css("background-image", "url('Img/CrumbleBrickSeparatedComplete.png')"); $(".CRBrickWideSpecial").removeClass("animateSeparateCrumble"); $(".CRBrickWideSpecial").css("background-image", "url('Img/transparentPNG.png')"); $(".CrumbleBrickWideSpecialLeft").css("z-index", "10"); $(".CrumbleBrickWideSpecialRight").css("z-index", "10"); $(".CrumbleBrickWideSpecialLeft").css("display", "inline-block"); $(".CrumbleBrickWideSpecialRight").css("display", "inline-block"); /* $(".CrumbleBrickWideSpecialRight").css("background-image", "url('Img/transparentPNG.png')"); $(".CrumbleBrickWideSpecialLeft").css("background-image", "url('Img/transparentPNG.png')"); $(".crackedBrickWideSpecialLeft").css("background-image", "url('Img/transparentPNG.png')"); $(".crackedBrickWideSpecialRight").css("background-image", "url('Img/transparentPNG.png')"); $(".runeBrickNorm1Special").css("background-image", "url('Img/transparentPNG.png')"); $(".runeBrickNorm2Special").css("background-image", "url('Img/transparentPNG.png')"); */ $(".runeBrickNorm1Special").addClass("item1animate"); $(".crackedBrickWideSpecialLeft").addClass("item2animate"); $(".crackedBrickWideSpecialRight").addClass("item3animate"); $(".runeBrickNorm2Special").addClass("item4animate"); $(".CrumbleBrickWideSpecialLeft").addClass("item5animate"); $(".CrumbleBrickWideSpecialRight").addClass("item6animate"); /* $(".CrumbleBrickWideSpecialRight").css("display", "none"); $(".CrumbleBrickWideSpecialLeft").css("display", "none"); $(".runeBrickNorm1Special").css("display", "none"); $(".runeBrickNorm2Special").css("display", "none"); $(".CRBrickWideSpecial").css("display", "none"); $(".crackedBrickWideSpecialLeft").css("display", "none"); $(".crackedBrickWideSpecialRight").css("display", "none"); $(".CRABrickWideSpecial").css("display", "none"); $("#item1").css("display", "inline-block"); $("#item2").css("display", "inline-block"); $("#item3").css("display", "inline-block"); $("#item4").css("display", "inline-block"); $("#item5").css("display", "inline-block"); $("#item6").css("display", "inline-block"); */ /* $("#item1").addClass("item1animate"); $("#item2").addClass("item2animate"); $("#item3").addClass("item3animate"); $("#item4").addClass("item4animate"); $("#item5").addClass("item5animate"); $("#item6").addClass("item6animate"); //myBox.removeClass('change-size'); */ }); $(".runeBrickNorm1Special").one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() { $(".runeBrickNorm1Special").css("background-image", "url('Img/item1animate/item1animate4.png')"); $(".runeBrickNorm1Special").removeClass("item1animate"); }); $(".crackedBrickWideSpecialLeft").one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() { $(".crackedBrickWideSpecialLeft").css("background-image", "url('Img/item2animate/item2animate4.png')"); $(".crackedBrickWideSpecialLeft").removeClass("item2animate"); }); $(".crackedBrickWideSpecialRight").one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() { $(".crackedBrickWideSpecialRight").css("background-image", "url('Img/item3animate/item3animate4.png')"); $(".crackedBrickWideSpecialRight").removeClass("item3animate"); }); $(".runeBrickNorm2Special").one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() { $(".runeBrickNorm2Special").css("background-image", "url('Img/item4animate/item4animate4.png')"); $(".runeBrickNorm2Special").removeClass("item4animate"); }); $(".CrumbleBrickWideSpecialLeft").one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() { $(".CrumbleBrickWideSpecialLeft").css("background-image", "url('Img/item5animate/item5animate4.png')"); $(".CrumbleBrickWideSpecialLeft").removeClass("item5animate"); }); $(".CrumbleBrickWideSpecialRight").one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() { $(".CrumbleBrickWideSpecialRight").css("background-image", "url('Img/item6animate/item6animate4.png')"); $(".CrumbleBrickWideSpecialRight").removeClass("item6animate"); $(".CrumbleBrickWideSpecialRight").css("display", "none"); $(".CrumbleBrickWideSpecialLeft").css("display", "none"); $(".runeBrickNorm1Special").css("display", "none"); $(".runeBrickNorm2Special").css("display", "none"); $(".CRBrickWideSpecial").css("display", "none"); $(".crackedBrickWideSpecialLeft").css("display", "none"); $(".crackedBrickWideSpecialRight").css("display", "none"); $(".CRABrickWideSpecial").css("display", "none"); $("#item1").css("display", "inline-block"); $("#item2").css("display", "inline-block"); $("#item3").css("display", "inline-block"); $("#item4").css("display", "inline-block"); $("#item5").css("display", "inline-block"); $("#item6").css("display", "inline-block"); }); //$('#animateFirst').addClass("animateBrickStart"); //brick.setTimeout('$(brick).addClass("animateBrickStart")', 2000); //$(brick).addClass("animateBrickPulse"); //$(brick).removeClass("active"); /* $('active').css('-webkit-animation','basicBrickPulse 2s linear infinite alternate'); $('active').css('-moz-animation','basicBrickPulse 2s linear infinite alternate'); $('active').css('-ms-animation','basicBrickPulse 2s linear infinite alternate'); $('active').css('-o-animation','basicBrickPulse 2s linear infinite alternate'); $('active').css('animation','basicBrickPulse 2s linear infinite alternate'); $(brick).addClass("active"); */ } function puzzle() { var Array1 = $('.sortable').dragswap('toArray'); console.log(Array1[0]); console.log(Array1[1]); console.log(Array1[2]); console.log(Array1[3]); console.log(Array1[4]); console.log(Array1[5]); console.log("--------"); var flag = true; for(var i = 0; i < 6; i++) { if(i === 0) { if(Array1[0] !== "item1") { flag = false; } } if(i === 1) { if(Array1[1] !== "item4") { flag = false; } } if(i === 2) { if(Array1[2] !== "item5") { flag = false; } } if(i === 3) { if(Array1[3] !== "item3") { flag = false; } } if(i === 4) { if(Array1[4] !== "item6") { flag = false; } } if(i === 5) { if(Array1[5] !== "item2") { flag = false; } } } if (flag !== false) { //alert("Puzzle Complete"); $("#item1").css("display", "none"); $("#item2").css("display", "none"); $("#item3").css("display", "none"); $("#item4").css("display", "none"); $("#item5").css("display", "none"); $("#item6").css("display", "none"); $(".brickWideSuper").addClass("brickWideAnimation"); $(".brickWideSuper").css("background-image", "url('Img/brickWideAnimation/brickWideAnimation15.png')"); } }
QUnit.test("accMul test", function( assert ){ x = accMul(2, 4); assert.equal(x, 8, "yay"); }); QUnit.test("accAdd test", function( assert ){ x = accAdd(2, 4); assert.equal(x, 6); }); QUnit.test("accDiv test", function( assert ){ x = accDiv(8, 2); assert.equal(x, 4); }); QUnit.test("QRisk test", function (assert){ p = { 'givenName': "Francesco", 'familyName': "Fiacco", 'gender': {'value': "male"}, 'age': {'value': 65}, 'hsCRP': 0, 'cholesterol': 5.2, 'HDL': 1.4, 'smoker_p': 0, 'b_AF': 1, 'b_atypicalantipsy': 1, 'b_migraine': 1, 'b_ra' : 0, 'b_renal': 1, 'b_semi' : 0, 'b_sle': 0, 'b_treatedhyp': 0, 'b_type1': 1, 'b_type2': 0, 'bmi': 20.83, 'ethrisk': 1, 'fh_cvd': 0, 'rati': 3.71, 'sbp': 120, 'sbps5': 10, 'smoke_cat': 2, 'b_impotence': 0, 'postCode': "EH8 8EQ", 'cigsperDay': 10, 'chdFamilyHistory': 0, 'arthritis': 0, 'b_corticosteroids': 0 }; x = qrisk_score(p); assert.equal(Math.round(x * 10) / 10, 77.5); p.smoke_cat = 0; x = qrisk_score(p); assert.equal(Math.round(x * 10) / 10, 65.6); p.fh_cvd = 1; x = qrisk_score(p); assert.equal(Math.round(x * 10) / 10, 75.2); }); QUnit.test("Assign test", function (assert){ p = { 'givenName': "Francesco", 'familyName': "Fiacco", 'gender': {'value': "male"}, 'age': {'value': 65}, 'hsCRP': 0, 'cholesterol': {'value': 5.2}, 'HDL': {'value': 1.4}, 'smoker_p': 0, 'b_AF': 1, 'b_atypicalantipsy': 1, 'b_migraine': 1, 'b_ra' : 0, 'b_renal': 1, 'b_semi' : 0, 'b_sle': 0, 'b_treatedhyp': 0, 'b_type1': 1, 'b_type2': 0, 'bmi': 20.83, 'ethrisk': 1, 'fh_cvd': 0, 'rati': 3.71, 'sbp': 120, 'sbps5': 10, 'smoke_cat': 2, 'b_impotence': 0, 'postCode': null, 'cigsperDay': 10, 'chdFamilyHistory': 0, 'arthritis': 0, 'b_corticosteroids': 0 }; x = assign_score(p); assert.equal(Math.round(x), 34); p.cigsperDay = 0; x = assign_score(p); assert.equal(Math.round(x), 29); });
import React from 'react' import { List } from 'immutable' import Reviews from './Reviews' import AutoSizer from 'react-virtualized-auto-sizer' import { createShallow } from '@material-ui/core/test-utils' import { withStyles } from '@material-ui/core/styles' import PropTypes from 'prop-types' import { mount } from 'enzyme' const styles = { fill: {} } const Composer = props => { return ( <Reviews {...props} /> ) } Composer.propTypes = { classes: PropTypes.object.isRequired, reviews: PropTypes.instanceOf(List), } const Wrapper = withStyles(styles)(Composer) describe('Reviews Component', () => { describe('<Reviews />', () => { const shallow = createShallow() it('should render Reviews', () => { const wrapper = shallow(<Wrapper classes={{}} reviews={List([{ id: '1' }])} />) expect(wrapper.dive().find(Reviews)).toHaveLength(1) }) }) describe('<Reviews /> uses Autosizer', () => { it('should render Reviews with react window Autosizer', () => { const wrapper = mount(<Wrapper classes={{}} reviews={List([{ id: '1' }])} />) expect(wrapper.find(AutoSizer)).toHaveLength(1) }) }) })
const puppeteer = require('puppeteer'); const URL = 'https://hiwijaya.com'; (async () => { const browser = await puppeteer.launch({headless: true}); const page = await browser.newPage(); await page.setViewport({width: 1680, height: 1050}); await page.goto(URL, {waitUntil: 'load', timeout: 0}); // await page.screenshot({path: 'screenshot.png'}); console.log('crawling...'); const posts = await page.evaluate(() => { try { let data = []; const allSelector = document.querySelectorAll('div.blog-item'); for (let element of allSelector) { const post = { title: element.querySelector('div.blog-title h3').innerHTML, date: element.querySelector('div.blog-date h5').textContent.trim(), desc: element.querySelector('div.blog-desc').innerHTML.trim() } data.push(post); } return data; } catch(error) { console.log(error.toString()); } }); await browser.close(); for (var i = 0; i < posts.length; i++) { console.log(posts[i]); } })();
const MOCK_CARD_CREATE = { name: 'Obelisk The Tormentor', types: 'MONSTER', attribute: 'DIVINE', level: 10, atk: '4000', def: '4000' } const MOCK_CARD_UPDATE = { name: 'Bakura', types: 'DIVINE-BEAST/EFFECT', attribute: 'DIVINE', level: 10, atk: '?', def: '?' } let MOCK_CARD_ID = null module.exports = { MOCK_CARD_CREATE, MOCK_CARD_UPDATE, MOCK_CARD_ID }
'use strict'; const routes = require('../main/constants/routes.json'); module.exports = (onLogout) => { return { login: { label: 'Login', route: routes.login }, register: { label: 'Register', route: routes.register }, tasks: { label: 'Tasks', route: routes.tasks }, logout: { label: 'Logout', action: onLogout } }; };
function figure3(p5) { let circ = make_ngon(200), p_on=true, state = {w:540, h:350}, cv, w, h, ratio, cvparent, cam, button, c1, orientation, distance, orbitOn=true, olabel, dlabel function size(cv) { // size scales the canvas according to the width of the containing div let domwidth = parseInt(window.getComputedStyle(cvparent).width); ratio = domwidth / state.w w = ratio * state.w h = ratio * state.h } p5.preload = function() { roboto = p5.loadFont('scripts/Roboto/Roboto-Bold.ttf'); } p5.setup = function() { cv = p5.createCanvas(state.w, state.h, p5.WEBGL); cvparent = cv.parent() size(cv) p5.resizeCanvas(w, h) p5.setAttributes('antialias', true); cam = p5.createCamera() p5.ortho(-w/2, w/2, -h/2, h/2, -4*w, 4*w) // controls button = p5.createButton('Reset'); button.position(10, p5.height-50); button.mousePressed(()=>{cam.camera();orientation.value(0)}); c1 = p5.createCheckbox('Show planes', p_on) c1.position(110, p5.height-50) c1.style('color', 'white') c1.changed(()=>p_on=c1.checked()) orientation = p5.createSlider(0,90,0,1) orientation.position(110, p5.height-25) orientation.style('width','70px') orientation.mouseMoved(()=>false) distance = p5.createSlider(100,300,250,1) distance.position(300, p5.height-25) distance.style('width','100px') for (elem of [orientation, distance]) { //elem.mousePressed(()=>{orbitOn=false}) //elem.mouseReleased(()=>{orbitOn=true}) } olabel = p5.createDiv('Rotate lens:') olabel.position(10, p5.height-25) olabel.style('color', 'white') dlabel = p5.createDiv('Move screen:') dlabel.position(200, p5.height-25) dlabel.style('color', 'white') p5.textFont(roboto) p5.textSize(20) } p5.windowResized = function () { size(cv) p5.resizeCanvas(w, h) button.position(10, h-50); c1.position(110, p5.height-50) orientation.position(110, p5.height-25) distance.position(300, p5.height-25) olabel.position(10, p5.height-25) dlabel.position(200, p5.height-25) p5.ortho(-w/2, w/2, -h/2, h/2, -4*w, 4*w) } p5.draw = function() { p5.mouseY<(p5.height-50) && p5.orbitControl() p5.background(0, 61, 93) p5.translate(-20*ratio,-30*ratio,0) // shifts the drawing up a bit // lens p5.fill(200, 200, 255) p5.strokeWeight(4) p5.stroke(200, 200, 255) showobj(0, 0, 0, 150*ratio, circ) // rays p5.stroke(255, 255, 255, 100) p5.strokeWeight(1) p5.noFill() p5.blendMode(p5.ADD) let r = orientation.value() let d = distance.value() let params = {n:7, pos:[0,0,0], Fy:1/250, Fz:1/150, d:d, aperture:150, rotation:r} let limits = rays(params) // screen p5.fill(180) p5.stroke(180) p5.strokeWeight(3); showobj(d*ratio,0,0, 250*ratio, make_ngon(4)) // images p5.noFill() p5.stroke(255,0,0) if (Math.abs(d-1/params.Fy)<5 || Math.abs(d-1/params.Fz)<5) { limits = limits.sort((a,b)=>-(a[3]-b[3])) let xcoord = limits[0][0]-1*ratio p5.line(xcoord, limits[0][1], limits[0][2], xcoord, -limits[0][1], -limits[0][2]) } if (Math.abs(d-2/(params.Fy+params.Fz))<5) { limits = limits.sort((a,b)=>-(a[3]-b[3])) let xcoord = limits[0][0]-1*ratio, r = limits[0][3]**0.5 showobj(xcoord, 0, 0, 2*r, circ) } // planes let lim = 150*0.5*ratio p5.noStroke() if (p_on) { p5.fill(0,200,0, 100) p5.beginShape() p5.vertex(-200*ratio,...rot(r,0,lim)) p5.vertex(-200*ratio,...rot(r,0,-lim)) p5.vertex(d*ratio,...rot(r,0,-lim)) p5.vertex(d*ratio,...rot(r,0,lim)) p5.vertex(-200*ratio,...rot(r,0,lim)) p5.endShape() } if (p_on) { p5.fill(100,100,190, 100) p5.beginShape() p5.vertex(-200*ratio,...rot(r,lim,0)) p5.vertex(-200*ratio,...rot(r,-lim,0)) p5.vertex(d*ratio,...rot(r,-lim,0)) p5.vertex(d*ratio,...rot(r,lim,0)) p5.vertex(-200*ratio,...rot(r,lim,0)) p5.endShape() } } // for speed, generate the ngon sin/cos coords function make_ngon(n) { var rim = {x:[], y:[], z:[]} for (let i=0; i<n+1; i++) { rim.x.push(0) rim.y.push(p5.sin(p5.TWO_PI/n*i+p5.PI/4)) rim.z.push(p5.cos(p5.TWO_PI/n*i+p5.PI/4)) } return rim } function showobj(x, y, z, d, perimeter) { p5.beginShape(); for (let i = 0; i < perimeter.x.length; i++) { p5.vertex(x+perimeter.x[i], y+perimeter.y[i]*d/2, z+perimeter.z[i]*d/2) } p5.endShape(); } function linspace(start, finish, n) { let s = [] for (let i=0; i<n; i++) { s.push(start+i*(finish-start)/(n-1)) } return s } function rot(angle, x, y) { // rotates x & y by a specific angle let c = Math.cos(angle*Math.PI/180), s = Math.sin(angle*Math.PI/180) return [c*x-s*y, s*x+c*y] } function sumv(a,b) { return [a[0]+b[0], a[1]+b[1]]} function rays(params) { // generates 3d lines going through a thin lens centred at (x,y,z) // with diameter d in y & z directions. // params: {n:5, pos:[0,0,0], Fy:1/200, Fz:1/200, d:250, aperture:150} let n = params.n, a = linspace(-params.aperture*0.45, params.aperture*0.45, n), [x0,y0,z0] = params.pos || [0,0,0], d = params.d, r = -(params.rotation || 0) let limits = [] for (yi=0; yi<n; yi++) { for (zi=0; zi<n; zi++) { let y = a[yi], z = a[zi] // get the yz coordinates in the rotated principal meridians. let [yr, zr] = rot(r,y,z) // work out the point where they hit the screen yr *= (1-d*params.Fy) zr *= (1-d*params.Fz) // work out the point in unrotated coordinates ;[yr,zr] = sumv(rot(-r,yr,0), rot(-r,0,zr)) if ((y**2+z**2)<=(params.aperture/2)**2) { p5.beginShape() p5.vertex((x0-200)*ratio, y*ratio, z*ratio) p5.vertex(x0*ratio, y*ratio, z*ratio) p5.vertex((x0+d)*ratio, yr*ratio, zr*ratio) p5.endShape() limits.push([(x0+d)*ratio, yr*ratio, zr*ratio, yr**2+zr**2]) } } } return limits } p5.mouseDragged = function() { if (p5.mouseY>=0 && p5.mouseY<(h-25)) { return false } // eliminate page scrolling } } new p5(figure3,'figure3img') popout.openButton('Figure3') popout.addhelp('Figure3', ()=>false)
import styled from 'styled-components'; export const Container = styled.div` font-size: 17px; padding: 20px 20px; -webkit-align-items: flex-start; -webkit-box-align: flex-start; -ms-flex-align: flex-start; align-items: flex-start; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; text-align: center; `; export const Table = styled.table` width: 100%; color: black; text-align: center; border-spacing: 0px; background-color: rgba(255, 141, 107, 0.2); border-collapse: collapse; border-radius: 0.5em; overflow: hidden; th, td { padding: 8px; } th { background-color: #fe7600; color: white; } td { border-bottom: 1px solid #ff8d6b; } tr:hover { background-color: rgba(255, 141, 107, 0.3); } `; export const Negative = styled.div` display: flex; justify-content: center; span { color: red; } `; export const Positive = styled.div` display: flex; justify-content: center; span { color: green; } `; export const Select = styled.select` font-size: 16px; flex: 1; padding: 0.2em; color: #000; cursor: pointer; position: relative; display: flex; width: 20em; height: 3em; line-height: 3; background: #fff; overflow: hidden; border-radius: 0.25em; option { background: #fff; height: 30px; border: 1px solid #cbcbcb; padding-left: 17px; padding-top: 12px; } `;
const login = (name, pwd) => { utils.ajax.get() }
import React from 'react'; function Card (props) { return ( <li className={`${props.status ? 'completed' : ''}`}> <div>First Name: {props.firstName}</div> <div>Last Name: {props.lastName}</div> <div>Age: {props.age}</div> <div>Born: {props.born}</div> <div>Profession: {props.profession}</div> <button onClick={props.onDelete}>Delete</button> <button onClick={props.onChangeStatus}>Change Status</button> </li> ); } export default Card;
function timing() { }
/** * Created by shiwuhao on 2017/4/10. */ console.log('two');
import React, { useRef } from 'react'; import useHover from '../hooks/useHover'; const Hover = ({ firstColor, secondColor }) => { const ref = useRef(); const isHovering = useHover(ref); return ( <div ref={ref} style={{ width: 300, height: 300, background: isHovering ? secondColor : firstColor, }} ></div> ); }; export default Hover;
(function(angular, app) { "use strict"; app.service("factService",["$window", "$http", function($window, $http) { var _url = { allFactsUrl : '/facts.json', factCreateUrl : '/facts.json', deleteFactUrl : function(fact_id){ return '/facts/'+fact_id+'.json'; }, updateFactUrl: function(fact_id){ return '/facts/'+fact_id+'.json'; } }; var getAllFacts = function(sortBy){ return $http.get(_url.allFactsUrl,{params:{sort:sortBy}}); }; var createFact = function(title,content){ return $http.post(_url.factCreateUrl, {title:title, content:content}); }; var deleteFact = function(fact_id){ return $http['delete'](_url.deleteFactUrl(fact_id)); }; var updateFact = function(fact_id, title, content){ return $http.put(_url.updateFactUrl(fact_id), {title:title, content:content}); }; return { getAllFacts: getAllFacts, createFact:createFact, deleteFact:deleteFact, updateFact:updateFact }; }]); })(angular, app);
DrunkCupid.Models.Message = Backbone.Model.extend({ urlRoot: "api/messages", toJSON: function () { return {msg: _.clone(this.attributes)} } })
self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "7c551a56069ba6b99f2aea25f4ce08c7", "url": "/index.html" }, { "revision": "28d5f14664b829b9d76e", "url": "/static/css/main.6a864d12.chunk.css" }, { "revision": "8ae1c9cf72b980d8ebb8", "url": "/static/js/2.8be04a46.chunk.js" }, { "revision": "28d5f14664b829b9d76e", "url": "/static/js/main.3cede45f.chunk.js" }, { "revision": "42ac5946195a7306e2a5", "url": "/static/js/runtime~main.a8a9905a.js" } ]);
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); /* GET home page. */ router.get('/', function(req, res) { res.sendFile('./public/index.html'); }); // API calls // Get list of games router.get('/api/getlist', function(req, res) { mongoose.model('games').find(function(err, games){ if(err){ res.send(err); } res.send(games); }); }); // Save a game to the db router.post('/api/savegame/:name', function(req, res){ console.log(req.params.name); var game = mongoose.model('games'); var item = new game({ name: req.params.name }); item.save(function(err, item, na){ if(err){ res.send('err'); } res.send('Saved'); }); }); // Update Game router.put('/api/updategame', function(req, res) { var item = req.query.name; var replace = req.query.newname; mongoose.model('games').findOne({name: item}, function(err, doc){ if(err){ res.send(err); } doc.name = replace; doc.save(); res.send('Updated'); }); }); // Delete a game router.delete('/api/delete/:id', function(req, res){ mongoose.model('games').remove({_id: req.params.id}, function(err){ if(err) { res.send(err); } res.send('Deleted'); }); }); module.exports = router;
var taskManager = require('task.manager'); var spawnManager = { emergencyHarvester: [WORK,WORK,CARRY,MOVE], emergencyDistributor: [CARRY,CARRY,MOVE,MOVE], queueSpawn: function(creepOrder){ let roomName = creepOrder.roomName let room = Game.rooms[roomName] let spawnName = room.memory.spawn.primaryspawn let spawn = Game.spawns[spawnName] let orderMemory = spawn.memory.queue var duplicate = false for (let i=0; i<spawn.memory.queue.length; i++){ if (_.isMatch(creepOrder, orderMemory[i])){ duplicate = true } } if (!duplicate){ orderMemory.push(creepOrder); } }, creepOrder: function(roomName, type, priority, task = null, body = null) { this.roomName = roomName this.type = type this.priority = priority this.task = task this.body = body }, spawnCreep: function(creepOrder, test){ let roomName = creepOrder.roomName; let role = creepOrder.type; let priority = creepOrder.priority; let task = creepOrder.task; let body = creepOrder.body; let room = Game.rooms[roomName]; let spawnName = room.memory.spawn.primaryspawn; let spawn = Game.spawns[spawnName]; let config = room.memory.config; switch (creepOrder.type){ case 'claimer': body = [CLAIM,MOVE]; break; case 'harvester': body = config.harvesterbody; break; case 'smallharvester': body = this.emergencyHarvester; break; case 'towerdistributor': case 'distributor': body = config.distributorbody; break; case 'smalldistributor': body = this.emergencyDistributor; break; case 'builder': body = config.builderbody; break; case 'repairer': body = config.repairerbody; break; case 'upgrader': body = config.upgraderbody; break; case 'carrier': body = config.carrierbody; break; case 'explorer': body = [MOVE]; break; case 'reserver': body = config.reserverbody; break; default: body = creepOrder.body; break; } if (test == 'test') { check = spawn.canCreateCreep(body, undefined) return check; } if (test == 'make') { newName = spawn.createCreep(body, undefined, {role: role, task: task, originroom: room.name}) return newName; } }, replaceDeadCreeps: function(room){ if (room.memory.new){ var builders = _.filter(room.memory.creeps, (creep) => (creep.role == 'builder')); if(builders.length < room.memory.config.builders) { constructions = taskManager.getConstructions(room.name); if (builders.length < constructions.length){ order = new this.creepOrder(room.name, 'builder', 1) this.queueSpawn(order) } } } else{ var harvestersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'harvester')); var distributorsearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'distributor')); if ((harvestersearch.length == 0) && (distributorsearch.length == 0)){ let harvesterorder = new this.creepOrder(room.name, 'harvester', 1) let distributororder = new this.creepOrder(room.name, 'distributor', 2) this.queueSpawn(harvesterorder); this.queueSpawn(distributororder); } else { var carriersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'carrier')); var repairersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'repairer')); var upgradersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'upgrader')); var buildersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'builder')); var towersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'towerdistributor')); if (distributorsearch.length < room.memory.config.distributors){ let order = new this.creepOrder(room.name, 'distributor', 4); this.queueSpawn(order); } if (harvestersearch.length < (room.memory.config.harvesterpersource * room.memory.sources.length)){ let order = new this.creepOrder(room.name, 'harvester', 5); this.queueSpawn(order); } if (towersearch.length < room.memory.config.towerdistributors){ let order = new this.creepOrder(room.name, 'towerdistributor', 6) this.queueSpawn(order); } if (repairersearch.length < room.memory.config.repairers){ let order = new this.creepOrder(room.name, 'repairer', 6); this.queueSpawn(order); } if (upgradersearch.length < room.memory.config.upgraders){ let order = new this.creepOrder(room.name, 'upgrader', 7); this.queueSpawn(order); } if (carriersearch.length < room.memory.config.carriers){ let order = new this.creepOrder(room.name, 'carrier', 8) this.queueSpawn(order); } if (buildersearch.length < room.memory.config.builders){ constructions = taskManager.getConstructions(room.name); if (buildersearch.length < constructions.length){ let order = new this.creepOrder(room.name, 'builder', 9); this.queueSpawn(order) } } } } }, Tick: function(room) { this.replaceDeadCreeps(room); let spawnName = room.memory.spawn.primaryspawn let spawn = Game.spawns[spawnName] let memory = spawn.memory.queue if (memory.length > 0){ let sortMemory = _.sortBy(memory, function(creep) {return (creep.priority)}); spawn.memory.queue = sortMemory; } if (spawn) { spawning: { while(memory.length > 0){ creep = memory[0] let order = new this.creepOrder(creep.roomName, creep.type, creep.priority, creep.task, creep.body) let creepTest = this.spawnCreep(order, 'test'); switch(creepTest){ case OK: let newName = this.spawnCreep(order, 'make') newArray = memory.slice(0) newArray.splice(0, 1) spawn.memory.queue = newArray console.log(room.name + ' is spawning a creep of type ' + creep.type + ': ' + newName) if (order.role == 'harvester' || order.role == 'distributor'){ for (let creepname in room.memory.creeps){ creep = Game.creeps[creepname] if (creep.memory.role = ('small' + order.role)){ creep.suicide(); } } } break spawning; case ERR_BUSY: break spawning; case ERR_INVALID_ARGS: newArray = memory.slice(0) newArray.splice(0, 1) spawn.memory.queue = newArray console.log(room.name + 'failed to create a creep of type ' + creep.type + ' because the body is defined badly.'); break; case ERR_RCL_NOT_ENOUGH: newArray = memory.slice(0) newArray.splice(0) spawn.memory.queue = newArray console.log(room.name + 'failed to create a creep of type ' + creep.type + ' because the room RCL is not high enough.'); break; case ERR_NOT_ENOUGH_ENERGY: if (order.role == 'distributor'){ var distributorsearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'smalldistributor')); if (distributorsearch.length == 0){ let order = new this.creepOrder(room.name, 'smalldistributor', 2) this.queueSpawn(order) } } if (order.role == 'harvester'){ var harvestersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'smallharvester')); if (harvestersearch.length == 0){ let order = new this.creepOrder(room.name, 'smallharvester', 1) } } break spawning; default: newArray = memory.slice(0) newArray.splice(0) spawn.memory.queue = newArray console.log(room.name + 'failed to create a creep of type ' + creep.role + ' because of an unaccounted for error. Error code: '+ creepTest) break; } } } } }, run: function(room) { roomspawn = room.memory.spawn.primaryspawn spawn = Game.spawns[roomspawn] if (spawn){ if (room.memory.new){ var builders = _.filter(room.memory.creeps, (creep) => (creep.role == 'builder')); if(builders.length < 1) { if (spawn.canCreateCreep(room.memory.config.harvesterbody, undefined) == OK) { var newName = spawn.createCreep(room.memory.config.harvesterbody, undefined, {role: 'builder', originroom: room.name, task: null}); console.log('Spawning new container builder: ' + newName); } } } else { var harvestersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'harvester')); var distributorsearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'distributor')); if(harvestersearch.length < (room.memory.sources.length * room.memory.config.harvesterpersource)) { if (spawn.canCreateCreep(room.memory.config.harvesterbody, undefined) == OK) { var newName = spawn.createCreep(room.memory.config.harvesterbody, undefined, {role: 'harvester', originroom: room.name, task: null}); console.log('Spawning new harvester: ' + newName); } else { if ((distributorsearch.length == 0) && (harvestersearch.length > 0) && (spawn.canCreateCreep([CARRY,CARRY,CARRY,MOVE,MOVE,MOVE], undefined) == OK)) { var smalldistributor = _.filter(room.memory.creeps, (creep) => (creep.role == 'smalldistributor')); if (smalldistributor.length == 0){ var newName = spawn.createCreep([CARRY,CARRY,CARRY,MOVE,MOVE,MOVE], undefined, {role: 'smalldistributor', originroom: room.name, task: null}); console.log('Emergency: Spawning new small distributor: ' + newName); } } if ((harvestersearch.length == 0) && (distributorsearch.length == 0) && (spawn.canCreateCreep([WORK,CARRY,MOVE,MOVE], undefined) == OK)) { var newName = spawn.createCreep([WORK,CARRY,MOVE,MOVE], undefined, {role: 'harvester', originroom: room.name, task: null}); console.log('Spawning new harvester: ' + newName); } } } else { if(distributorsearch.length < room.memory.config.distributors) { if (spawn.canCreateCreep(room.memory.config.distributorbody, undefined) == OK) { var newName = spawn.createCreep(room.memory.config.distributorbody, undefined, {role: 'distributor', originroom: room.name, task: null}); console.log('Spawning new distributor: ' + newName); } else { if (spawn.canCreateCreep([CARRY,CARRY,CARRY,MOVE,MOVE,MOVE], undefined) == OK) { var newName = spawn.createCreep([CARRY,CARRY,CARRY,MOVE,MOVE,MOVE], undefined, {role: 'distributor', originroom: room.name, task: null}); console.log('Spawning new small distributor: ' + newName); } } } else { var carriersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'carrier')); if(carriersearch.length < room.memory.config.carriers) { if(spawn.canCreateCreep(room.memory.config.carrierbody, undefined) == OK) { var newName = spawn.createCreep(room.memory.config.carrierbody, undefined, {role: 'carrier', originroom: room.name, task: null}); console.log('Spawning new carrier: ' + newName); } } var repairersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'repairer')); if(repairersearch.length < room.memory.config.repairers) { if (spawn.canCreateCreep(room.memory.config.repairerbody, undefined) == OK){ var newName = spawn.createCreep(room.memory.config.repairerbody, undefined, {role: 'repairer', originroom: room.name, task: null}); console.log('Spawning new repairer: ' + newName); } } var upgradersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'upgrader')); if(upgradersearch.length < room.memory.config.upgraders) { if (spawn.canCreateCreep(room.memory.config.upgraderbody, undefined) == OK) { var newName = spawn.createCreep(room.memory.config.upgraderbody, undefined, {role: 'upgrader', originroom: room.name, task: null}); console.log('Spawning new upgrader: ' + newName); } } var buildersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'builder')); if(buildersearch.length < room.memory.config.builders) { if (spawn.canCreateCreep(room.memory.config.builderbody, undefined) == OK) { var newName = spawn.createCreep(room.memory.config.builderbody, undefined, {role: 'builder', originroom: room.name, task: null}); console.log('Spawning new builder: ' + newName); } } var towersearch = _.filter(room.memory.creeps, (creep) => (creep.role == 'towerdistributor')); if(towersearch.length < room.memory.config.towerdistributors) { if (spawn.canCreateCreep(room.memory.config.distributorbody, undefined) == OK) { var newName = spawn.createCreep(room.memory.config.distributorbody, undefined, {role: 'towerdistributor', originroom: room.name, task: null}); console.log('Spawning new tower distributor: ' + newName); } } } } } } }, } module.exports = spawnManager;
const Sequelize = require('sequelize'); module.exports = function(sequelize, DataTypes) { return sequelize.define('NewsletterQueue', { queue_id: { autoIncrement: true, type: DataTypes.INTEGER.UNSIGNED, allowNull: false, primaryKey: true, comment: "Queue ID" }, template_id: { type: DataTypes.INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: "Template ID", references: { model: 'newsletter_template', key: 'template_id' } }, newsletter_type: { type: DataTypes.INTEGER, allowNull: true, comment: "Newsletter Type" }, newsletter_text: { type: DataTypes.TEXT, allowNull: true, comment: "Newsletter Text" }, newsletter_styles: { type: DataTypes.TEXT, allowNull: true, comment: "Newsletter Styles" }, newsletter_subject: { type: DataTypes.STRING(200), allowNull: true, comment: "Newsletter Subject" }, newsletter_sender_name: { type: DataTypes.STRING(200), allowNull: true, comment: "Newsletter Sender Name" }, newsletter_sender_email: { type: DataTypes.STRING(200), allowNull: true, comment: "Newsletter Sender Email" }, queue_status: { type: DataTypes.INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: "Queue Status" }, queue_start_at: { type: DataTypes.DATE, allowNull: true, comment: "Queue Start At" }, queue_finish_at: { type: DataTypes.DATE, allowNull: true, comment: "Queue Finish At" } }, { sequelize, tableName: 'newsletter_queue', timestamps: false, indexes: [ { name: "PRIMARY", unique: true, using: "BTREE", fields: [ { name: "queue_id" }, ] }, { name: "NEWSLETTER_QUEUE_TEMPLATE_ID", using: "BTREE", fields: [ { name: "template_id" }, ] }, ] }); };
var placeCannon = false var speed = 3 var gravity = 0.9 var tile = 50 var player1 var player2 var jumpSpeed = 6 var ammocount = 0 var ammos = [] var bricks = [] var bullets = [] var bulletImages = [] var playerIdleImages = [] var playerJumpingImages = [] var playerFallingImages = [] var turretBase var turretGun var grass var selectedCannonSize function setup() { noSmooth() var width = int(1050 / tile) * tile var height = int(600 / tile) * tile createCanvas(width, height) player1 = new Player(200, 200, 1) player2 = new Player(width - 200, 200, 2) grid = twoDArray(int(width / tile), int(height / tile) - 1) } function draw() { background(244, 255, 196) fill(0, 100, 0) text(player1.ammo, 20, 20) text(player2.ammo, width - 20, 20) text(player1.life, 20, 40) text(player2.life, width - 20, 40) drawMap() controlls() player1.update() player2.update() if (frameCount % 500 == 0) { ammos.push(new Ammo(int(random(20, width - 20)))) } for (var i = ammos.length - 1; i >= 0; i--) { ammos[i].update() } for (var i = 0; i < bullets.length; i++) { bullets[i].update() if(bullets[i].isDead){ bullets.splice(i,1) i = i-1 } } for (var x = 0; x < grid.length; x++) { image(grass, x * tile, (grid[0].length - 1) * tile, tile, tile) } fill(0) rect(0, (grid[0].length) * tile, width, tile) } function preload() { playerIdleImages[1] = new AnimImage( [ "players/player1/idle1.png", "players/player1/idle2.png", "players/player1/idle3.png", "players/player1/idle4.png", "players/player1/idle5.png" ], 5) playerIdleImages[2] = new AnimImage( [ "players/player2/idle1.png", "players/player2/idle2.png", "players/player2/idle3.png", "players/player2/idle4.png", "players/player2/idle5.png" ], 5) turretBase = loadImage("pixel-art/turrets/base.png") turretGun = loadImage("pixel-art/turrets/gun.png") playerJumpingImages[1] = loadImage("players/player1/jumping.png") playerJumpingImages[2] = loadImage("players/player2/jumping.png") playerFallingImages[1] = loadImage("players/player1/falling.png") playerFallingImages[2] = loadImage("players/player2/falling.png") ammoImage = loadImage("pixel-art/ammo.png") bulletImages[1] = loadImage("pixel-art/bullets/bullet1.png") bulletImages[2] = loadImage("pixel-art/bullets/bullet2.png") bulletImages[3] = loadImage("pixel-art/bullets/bullet3.png") bricks[4] = loadImage("pixel-art/blocks/block1.png") bricks[3] = loadImage("pixel-art/blocks/block2.png") bricks[2] = loadImage("pixel-art/blocks/block3.png") bricks[1] = loadImage("pixel-art/blocks/block4.png") grass = loadImage("pixel-art/grass.png") } function whatDidYouHit(x, y) { x = pixelToIndex(x) y = pixelToIndex(y) if (x >= 0 && x < grid.length && y >= 0 && y < grid[1].length) { if (grid[x][y] == null) { return (true) } else { return grid[x][y] } } else { return (false) } } function validiatePosition(x, y) { x = pixelToIndex(x) y = pixelToIndex(y) if (x >= 0 && x < grid.length && y >= 0 && y < grid[1].length) { if (grid[x][y] == null) { return (true) } else { return (false) } } else { return (false) } } function drawMap() { for (w = 0; w < grid.length; w++) { for (l = 0; l < grid[0].length; l++) { if (grid[w][l] != null) { grid[w][l].display() } } } } function mouseClicked() { if (placeCannon) { //fill(138,43,226) //rect(int(mouseX/tile)*tile,int(mouseY/tile)*tile,tile*2,tile) //fill(255) grid[pixelToIndex(mouseX)][pixelToIndex(mouseY)] = new Turret(roundToTile(mouseX), roundToTile(mouseY), selectedCannonSize) placeCannon = false } else { //rect(int(mouseX/tile)*tile,int(mouseY/tile)*tile,tile,tile) grid[pixelToIndex(mouseX)][pixelToIndex(mouseY)] = new Brick(roundToTile(mouseX), roundToTile(mouseY)) } } function twoDArray(lenght, depth) { var temp = new Array(lenght); for (var i = 0; i < temp.length; i++) { temp[i] = new Array(depth); } return temp } function collison(xcord, ycord, xspeed, yspeed, wd, ht, applyX, applyY) { movementsPossible = { x: false, y: false, up:false, down:false, right:false, left:false } if (xspeed < 0) { if (validiatePosition(xcord + xspeed, ycord) && validiatePosition(xcord + xspeed, ycord + ht)) { movementsPossible.x = true movementsPossible.left = true } } else if (xspeed > 0) { if (validiatePosition(xcord + xspeed + wd, ycord) && validiatePosition(xcord + xspeed + wd, ycord + ht)) { movementsPossible.x = true movementsPossible.right = true } } if (yspeed < 0) { if (validiatePosition(xcord, ycord + yspeed) && validiatePosition(xcord + wd, ycord + yspeed)) { movementsPossible.y = true movementsPossible.up = true } } if (yspeed > 0) { if (validiatePosition(xcord, ycord + yspeed + ht) && validiatePosition(xcord + ht, ycord + yspeed + ht)) { movementsPossible.y = true movementsPossible.down = true } } return (movementsPossible) } function pixelToIndex(pixel) { return (int(pixel / tile)) } function indexToPixel(index) { return (index * tile) } function roundToTile(pixel) { return indexToPixel(pixelToIndex(pixel)) } function angleToVector(angle, length) { length = typeof length !== 'undefined' ? length : 10; angle = angle * Math.PI / 180; // if you're using degrees instead of radians return [length * Math.cos(angle), length * Math.sin(angle)] }
import mock from './mock' export default { mock }
import React,{Component} from "react"; import ReactDOM from "react-dom"; import Counter from "./counter"; class Counters extends Component{ state={ counters:[ {id:1,value:7}, {id:2,value:0}, {id:3,value:0}, {id:4,value:2}, ] } handleDelete=(id)=>{ console.log(id) const counters=this.state.counters.filter(c=>c.id != id) this.setState({counters:counters}) //since } handleReset=()=>{ const counters=this.state.counters.map(c=>{ c.value=0; return c; }) this.setState({counters}) ; //counters:counters }; handleIncrement=counter=>{ // this.setState({counters:counter.value+1}) const counters= this.state.counters.map(each=>{ if (counter.id===each.id) each.value=each.value+1 return each }) this.setState({counters}) ; } render(){ const b=2; const arr =[2,4,6,8,10] const a=<counter/> const disp=this.state.counters.map(cont=> <Counter key={cont.id} cont={cont} selected={true} delete={this.handleDelete} onIncrement={this.handleIncrement}/>) return( <div> <button className="btn btn-primary btn-sm m-2" onClick={this.handleReset}> Reset</button> <br/> <br/> {disp} </div> ); } } export default Counters
/** * Created by dianwoba on 2015/7/31. */ 'use strict'; var Reflux = require('reflux'); var resultAction = Reflux.createActions([ 'getResults' ]); module.exports = resultAction;
// Sample code from the source. This isn't referenced anywhere so don't implement your logic here. var AjaxTransport = (Target => class AjaxTransport extends (Target || Base) { static get $name() { return 'AjaxTransport'; } /** * Configuration of the AJAX requests used by __Crud Manager__ to communicate with a server-side. * * ```javascript * transport : { * load : { * url : 'http://mycool-server.com/load.php', * // HTTP request parameter used to pass serialized "load"-requests * paramName : 'data', * // pass extra HTTP request parameter * params : { * foo : 'bar' * } * }, * sync : { * url : 'http://mycool-server.com/sync.php', * // specify Content-Type for requests * headers : { * 'Content-Type' : 'application/json' * } * } * } *``` * Since the class uses Fetch API you can use * any its [Request interface](https://developer.mozilla.org/en-US/docs/Web/API/Request) options: * * ```javascript * transport : { * load : { * url : 'http://mycool-server.com/load.php', * // HTTP request parameter used to pass serialized "load"-requests * paramName : 'data', * // pass few Fetch API options * method : 'GET', * credentials : 'include', * cache : 'no-cache' * }, * sync : { * url : 'http://mycool-server.com/sync.php', * // specify Content-Type for requests * headers : { * 'Content-Type' : 'application/json' * }, * credentials : 'include' * } * } *``` * * An object where you can set the following possible properties: * @config {Object} transport * @property {Object} transport.load Load requests configuration: * @property {String} transport.load.url URL to request for data loading. * @property {String} [transport.load.method='GET'] HTTP method to be used for load requests. * @property {String} [transport.load.paramName='data'] Name of the parameter that will contain a serialized `load` request. * The value is mandatory for requests using `GET` method (default for `load`) so if the value is not provided `data` string is used as default. * This value is optional for HTTP methods like `POST` and `PUT`, the request body will be used for data transferring in these cases. * @property {Object} [transport.load.params] An object containing extra HTTP parameters to pass to the server when sending a `load` request. * * ```javascript * transport : { * load : { * url : 'http://mycool-server.com/load.php', * // HTTP request parameter used to pass serialized "load"-requests * paramName : 'data', * // pass extra HTTP request parameter * // so resulting URL will look like: http://mycool-server.com/load.php?userId=123456&data=... * params : { * userId : '123456' * } * }, * ... * } * ``` * @property {Object} [transport.load.headers] An object containing headers to pass to each server request. * * ```javascript * transport : { * load : { * url : 'http://mycool-server.com/load.php', * // HTTP request parameter used to pass serialized "load"-requests * paramName : 'data', * // specify Content-Type for "load" requests * headers : { * 'Content-Type' : 'application/json' * } * }, * ... * } * ``` * @property {Object} [transport.load.fetchOptions] **DEPRECATED:** Any Fetch API options can be simply defined on the upper configuration level: * ```javascript * transport : { * load : { * url : 'http://mycool-server.com/load.php', * // HTTP request parameter used to pass serialized "load"-requests * paramName : 'data', * // Fetch API options * method : 'GET', * credentials : 'include' * }, * ... * } * ``` * @property {Object} [transport.load.requestConfig] **DEPRECATED:** The config options can be defined on the upper configuration level. * @property {Object} transport.sync Sync requests (`sync` in further text) configuration: * @property {String} transport.sync.url URL to request for `sync`. * @property {String} [transport.sync.method='POST'] HTTP request method to be used for `sync`. * @property {String} [transport.sync.paramName=undefined] Name of the parameter in which `sync` data will be transferred. * This value is optional for requests using methods like `POST` and `PUT`, the request body will be used for data transferring in this case (default for `sync`). * And the value is mandatory for requests using `GET` method (if the value is not provided `data` string will be used as fallback). * @property {Object} [transport.sync.params] HTTP headers to pass with an HTTP request handling `sync`. * * ```javascript * transport : { * sync : { * url : 'http://mycool-server.com/sync.php', * // extra HTTP request parameter * params : { * userId : '123456' * } * }, * ... * } * ``` * @property {Object} [transport.sync.headers] HTTP headers to pass with an HTTP request handling `sync`. * * ```javascript * transport : { * sync : { * url : 'http://mycool-server.com/sync.php', * // specify Content-Type for "sync" requests * headers : { * 'Content-Type' : 'application/json' * } * }, * ... * } * ``` * @property {Object} [transport.sync.fetchOptions] **DEPRECATED:** Any Fetch API options can be simply defined on the upper configuration level: * ```javascript * transport : { * sync : { * url : 'http://mycool-server.com/sync.php', * credentials : 'include' * }, * ... * } * ``` * @property {Object} [transport.sync.requestConfig] **DEPRECATED:** The config options can be defined on the upper configuration level. */ static get defaultMethod() { return { load: 'GET', sync: 'POST' }; } /** * Cancels a sent request. * @param {Promise} requestPromise The Promise object wrapping the Request to be cancelled. * The _requestPromise_ is the value returned from the corresponding {@link #function-sendRequest} call. * @param {Function} reject The reject handle of the requestPromise */ cancelRequest(requestPromise, reject) { reject(); } shouldUseBodyForRequestData(packCfg, method, paramName) { return !(method === 'HEAD' || method === 'GET') && !paramName; } /** * Sends a __Crud Manager__ request to the server. * @param {Object} request The request configuration object having following properties: * @param {String} request.type The request type. Either `load` or `sync`. * @param {String} request.data The encoded __Crud Manager__ request data. * @param {Object} request.params An object specifying extra HTTP params to send with the request. * @param {Function} request.success A function to be started on successful request transferring. * @param {String} request.success.rawResponse `Response` object returned by the [fetch api](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). * @param {Function} request.failure A function to be started on request transfer failure. * @param {String} request.failure.rawResponse `Response` object returned by the [fetch api](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). * @param {Object} request.thisObj `this` reference for the above `success` and `failure` functions. * @return {Promise} The fetch Promise object. * @fires beforesend */ sendRequest(request) { const me = this, { data } = request, transportConfig = me.transport[request.type] || {}, // clone parameters defined for this type of request requestConfig = Objects.assign({}, transportConfig, transportConfig.requestConfig); requestConfig.method = requestConfig.method || AjaxTransport.defaultMethod[request.type]; requestConfig.params = Objects.assign(requestConfig.params || {}, request.params); let { paramName } = requestConfig; // transfer package in the request body for some types of HTTP requests if (me.shouldUseBodyForRequestData(transportConfig, requestConfig.method, paramName)) { requestConfig.body = data; // for requests having body we set Content-Type to 'application/json' by default requestConfig.headers = requestConfig.headers || {}; requestConfig.headers['Content-Type'] = requestConfig.headers['Content-Type'] || 'application/json'; } else { // when we don't use body paramName is mandatory so fallback to 'data' as name paramName = paramName || 'data'; requestConfig.params[paramName] = data; } if (!requestConfig.url) { throw new Error('Trying to request without URL specified'); } // sanitize request config delete requestConfig.requestConfig; delete requestConfig.paramName; /** * Fires before a request is sent to the server. * * ```javascript * crudManager.on('beforeSend', function ({ params, type }) { * // let's set "sync" request parameters * if (type == 'sync') { * // dynamically depending on "flag" value * if (flag) { * params.foo = 'bar'; * } * else { * params.foo = 'smth'; * } * } * }); * ``` * @event beforeSend * @param {Scheduler.crud.AbstractCrudManager} crudManager The CRUD manager. * @param {Object} params HTTP request params to be passed in the request URL. * @param {String} type CrudManager request type (`load`/`sync`) * @param {Object} requestConfig Configuration object for Ajax request call */ me.trigger('beforeSend', { params: requestConfig.params, type: request.type, requestConfig, config: request }); // AjaxHelper.fetch call it "queryParams" requestConfig.queryParams = requestConfig.params; delete requestConfig.params; let responsePromise; const fetchOptions = Objects.assign({}, requestConfig, requestConfig.fetchOptions), ajaxPromise = AjaxHelper.fetch(requestConfig.url, `fetchOptions`); ajaxPromise.catch(error => { const signal = fetchOptions.abortController && fetchOptions.abortController.signal; if (signal && !signal.aborted) { console.warn(error); } }).then(response => { if (response && response.ok) { var _request$success; responsePromise = (_request$success = request.success) === null || _request$success === void 0 ? void 0 : _request$success.call(request.thisObj || me, response, fetchOptions); } else { var _request$failure; responsePromise = (_request$failure = request.failure) === null || _request$failure === void 0 ? void 0 : _request$failure.call(request.thisObj || me, response, fetchOptions); } }); return Promise.all([ajaxPromise, responsePromise]); } });
import React, { useEffect, useState } from 'react'; const AuthorsList = (props) => { const { items, onSelect } = props; const [authors, setAuthors] = useState([]); useEffect(() => { if (items.length > 0) { const unique = [...new Set(items.map((i) => i.author?.name))]; setAuthors(unique); } }, [items]); return ( <> <div>Authors</div> <select onChange={(evt) => onSelect(evt.target.value)}> <option value={''} /> {authors?.map((item, idx) => { return ( <option key={idx} value={item}> {item} </option> ); })} </select> </> ); }; export default AuthorsList;
const express = require('express'); const mongoose = require('mongoose'), ObjectId = mongoose.Types.ObjectId; const emailRouter = express.Router(); const nodemailer = require('nodemailer'); const Email = require('../../../models/emailModel'); emailRouter.post('/', (req,res)=>{ const output = ` <h2>Confirmation Mail for Reservation at ${req.body.groundname}</h2> <p>You have a booking at ${req.body.groundname} today from ${req.body.slots} be sure to come and play </p> <p>Please confirm your booking by clicking the confirm button below if you dont confirm it your booking will automatically be canceled 2 hr before your reserved time</p> <button>Confirm Booking</button> <button>Cancel Booking</button>`; var transporter = nodemailer.createTransport({ service: 'gmail', port: 587, // secure: false, // true for 465, false for other ports auth: { user: 'futplay.project@gmail.com', // generated ethereal user pass: 'projectfutplay9' // generated ethereal password }, tls: { rejectUnauthorized : false } }); // setup email data with unicode symbols var mailOptions = { from: '"Futplay" <futplay.project@gmail.com>', // sender address to: `${req.body.Email}`, // list of receivers subject: 'Booking Confirmation ✔', // Subject line text: '', // plain text body html: output// html body }; // send mail with defined transport object transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log('Message sent: %s', info.response); console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info)); // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com> // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou... }); }) // const newEmail = new emailRouter({ // groundName : req.body.groundName, // userId: req.body.userId, // userName : req.body.userName, // date: req.body.date, // slots: req.body.slots // }) // newEmail.save() // .then(Email=>res.json(Email)); // }) module.exports = emailRouter;
import React from 'react'; import {View, StyleSheet} from 'react-native'; import Colors from '../variables/Colors'; import ChatDialog from '../components/ChatDialog'; const Chatbot = ({route, profile, navigation}) => { const {API, avatar, title} = route.params; return ( <View style={styles.screen}> <ChatDialog avatar={avatar} API={API} title={title} profile={profile} navigation={navigation} /> </View> ); }; const styles = StyleSheet.create({ screen: { width: '100%', height: '100%', backgroundColor: Colors.ghostWhite, }, }); export default Chatbot;
/* Global Object 전역 객체는 개발자가 생성할 수 없다. 전역 객체는 전역 스코프를 갖게된다. ' encodeURI()/ decodeURI() */
"use strict"; const Joi = require("@hapi/joi"); const mysqlPool = require("../../../database/mysql-pool"); async function validate(payload) { const schema = Joi.object({ regionId: Joi.number().required(), provinceId: Joi.number().required(), }); Joi.assert(payload, schema); } async function getCitiesProvinceRegion(req, res) { const regionId = req.params.regionId; const provinceId = req.params.provinceId; try { await validate({ regionId, provinceId }); } catch (e) { console.error(e); return res.status(400).send("Data are not valid"); } let connection; try { connection = await mysqlPool.getConnection(); const sqlQuery = `SELECT c.id, c.name FROM cities AS c WHERE c.region_id =? AND c.province_id =? ORDER BY c.name;`; const [rows] = await connection.execute(sqlQuery, [regionId, provinceId]); connection.release(); if (rows.length === 0) { return res.status(404).send("Cities not founded"); } return res.send(rows); } catch (e) { if (connection) { connection.release(); } console.error(e); return res.status(500).send(); } } module.exports = getCitiesProvinceRegion;
import { render, screen } from '@testing-library/react'; import App from '../../App'; // const header = require('../Header/.jsx'); import Header from "../Header/Header"; test('renders Header', () => { render(<App />); const myHeader = screen.getByText(/HANG-GIT/i); expect(myHeader).toBeInTheDocument(); });
$("#paisesSelect2").load("tabs/paisesSelect.html"); var nameLocalStorageDadoDemografico = 'dadoDemografico'; new dgCidadesEstados({ cidade: document.getElementById('cidade2'), estado: document.getElementById('estado2') }) function changePais2(radioInput) { if (radioInput.value == 'BRASIL') { document.getElementById('cardBrasil2').style.display = ''; document.getElementById('cardOutro2').style.display = 'none'; } else { document.getElementById('cardBrasil2').style.display = 'none'; document.getElementById('cardOutro2').style.display = ''; } } function adicionarDadoDemografico() { const nomeMae = document.getElementById('nomeMae').value; const nomePai = document.getElementById('nomePai').value; const situacaoFamiliar = $("input[name='situacaoFamiliar']:checked").val(); const dataNascimento = document.getElementById('dataNascimento').value; const indicadorDiaNascimento = $("input[name='indicador_acuracia_dia_nascimento']:checked").val(); const indicadorMesNascimento = $("input[name='indicador_acuracia_mes_nascimento']:checked").val(); const indicadorAnoNascimento = $("input[name='indicador_acuracia_ano_nascimento']:checked").val(); const seguimento = document.getElementById('seguimento').checked; const dataObito = document.getElementById('dataObito').value; const indicadorDiaObito = $("input[name='indicador_acuracia_dia_obito']:checked").val(); const indicadorMesObito = $("input[name='indicador_acuracia_mes_obito']:checked").val(); const indicadorAnoObito = $("input[name='indicador_acuracia_ano_obito']:checked").val(); const fonteNotificacao = $("input[name='fonteNotificacao']:checked").val(); const etnia = $("input[name='etnia']:checked").val(); const genero = $("input[name='genero']:checked").val(); const nacionalidade = $("input[name='nacionalidade']:checked").val(); var varPais = ''; var varDataEntradaNoBrasil = null; var varEstadoNascimento = ''; var varCidadeNascimento = ''; if ($("input[name='nacionalidade']:checked").val() == 'BRASIL') { varPais = 'Brasil'; varEstadoNascimento = document.getElementById('estado2').value; varCidadeNascimento = document.getElementById('cidade2').value; } else { varPais = document.getElementById('paisesSelect2').value; varDataEntradaNoBrasil = $("input[name='dataEntradaNoBrasil']:checked").val(); } const estadoNascimento = varEstadoNascimento; const cidadeNascimento = varCidadeNascimento; const pais = varPais; const dataEntradaNoBrasil = varDataEntradaNoBrasil; const pluralidadeNascimento = document.getElementById('pluralidadeNascimento').value; const ordemNascimento = document.getElementById('ordemNascimento').value; const comentarioIdentificacao = document.getElementById('comentarioIdentificacao').value; var id = "id" + Math.random().toString(16).slice(2); document.getElementById('tabelaVaziaDadoDemografico').style.display = 'none'; var dadoDemograficoObj = new dadoDemograficoC(id, nomeMae, nomePai, situacaoFamiliar, dataNascimento, indicadorDiaNascimento, indicadorMesNascimento, indicadorAnoNascimento, seguimento, dataObito, indicadorDiaObito, indicadorMesObito, indicadorAnoObito, fonteNotificacao, etnia, genero, nacionalidade, pais, estadoNascimento, cidadeNascimento, dataEntradaNoBrasil, pluralidadeNascimento, ordemNascimento, comentarioIdentificacao ); saveDadoDemograficoLocalStorage(dadoDemograficoObj, nameLocalStorageDadoDemografico); clearAllModalDadoDemografico(); adicionarItemTableDadoDemografico(dadoDemograficoObj); } function adicionarItemTableDadoDemografico(dadoDemograficoC) { var tableRef = document.getElementById('tableDadoDemografico').getElementsByTagName('tbody')[0]; var newRow = tableRef.insertRow(tableRef.rows.length); // Insert a cell in the row at index 0 var cell0 = newRow.insertCell(0);//Nome da Mãe var cell1 = newRow.insertCell(1);//Nome do Pai var cell2 = newRow.insertCell(2);//Data de Nascimento var cell3 = newRow.insertCell(3);//Etnia var cell4 = newRow.insertCell(4);//Gênero var cell5 = newRow.insertCell(5);//País var cell6 = newRow.insertCell(6);//Opções var inputHidden = document.createElement("input"); inputHidden.setAttribute("type", "hidden"); inputHidden.setAttribute("value", dadoDemograficoC.id); cell0.appendChild(inputHidden); cell0.appendChild(document.createTextNode(dadoDemograficoC.nomeMae)); cell1.appendChild(document.createTextNode(dadoDemograficoC.nomePai)); cell2.appendChild(document.createTextNode(dadoDemograficoC.dataNascimento)); cell3.appendChild(document.createTextNode(dadoDemograficoC.etnia)); cell4.appendChild(document.createTextNode(dadoDemograficoC.genero)); cell5.appendChild(document.createTextNode(dadoDemograficoC.pais)); const btnEdit = document.createElement('button'); btnEdit.setAttribute('type', 'button'); btnEdit.innerHTML = 'Editar'; btnEdit.className = 'btn btn-sm btn-primary float-right mr-1'; btnEdit.setAttribute('data-target', '#cadastroDadoDemograficoModal'); btnEdit.setAttribute('data-toggle', 'modal'); btnEdit.addEventListener("click", () => { editarDadoDemografico(newRow); }); const btnDel = document.createElement('button'); btnDel.innerHTML = 'Apagar'; btnDel.className = 'btn btn-sm btn-danger float-right mr-1'; btnDel.addEventListener("click", () => { tableRef.removeChild(newRow); if (tableRef.rows.length == 0) { document.getElementById('tabelaVaziaDadoDemografico').style.display = ''; } }); cell6.appendChild(btnEdit); cell6.appendChild(btnDel); } function findDadoDemograficoByid(idVal) { currentList = JSON.parse(localStorage .getItem(nameLocalStorageDadoDemografico) || []); const objFound = currentList.find(item => item.id === idVal); return objFound; } function editarDadoDemografico(node) { var idVal = node.childNodes[0].childNodes[0].value; const objFound = findDadoDemograficoByid(idVal); removeDadoDemograficoLocalStorage(idVal); document.getElementById('dataNascimento').value = objFound.dataNascimento; $('input:radio[name="indicador_acuracia_dia_nascimento"][value="' + objFound.indicadorDiaNascimento + '"]').prop('checked', true); $('input:radio[name="indicador_acuracia_mes_nascimento"][value="' + objFound.indicadorMesNascimento + '"]').prop('checked', true); $('input:radio[name="indicador_acuracia_ano_nascimento"][value="' + objFound.indicadorAnoNascimento + '"]').prop('checked', true); document.getElementById('seguimento').checked = objFound.seguimento.checked; document.getElementById('dataObito').value = objFound.dataObito; $('input:radio[name="indicador_acuracia_dia_obito"][value="' + objFound.indicadorDiaObito + '"]').prop('checked', true); $('input:radio[name="indicador_acuracia_mes_obito"][value="' + objFound.indicadorMesObito + '"]').prop('checked', true); $('input:radio[name="indicador_acuracia_ano_obito"][value="' + objFound.indicadorAnoObito + '"]').prop('checked', true); $('input:radio[name="fonteNotificacao"][value="' + objFound.fonteNotificacao + '"]').prop('checked', true); $('input:radio[name="etnia"][value="' + objFound.etnia + '"]').prop('checked', true); $('input:radio[name="genero"][value="' + objFound.genero + '"]').prop('checked', true); $('input:radio[name="nacionalidade"][value="' + objFound.nacionalidade + '"]').prop('checked', true); if ($("input[name='nacionalidade']:checked").val() == 'BRASIL') { pais = "Brasil" } else { document.getElementById('paisesSelect2').value = objFound.pais; dataEntradaNoBrasil = objFound.dataEntradaNoBrasil; } document.getElementById('estado2').value = objFound.estado; document.getElementById('cidade2').value = objFound.cidade; document.getElementById('pluralidadeNascimento').value = objFound.pluralidadeNascimento; document.getElementById('ordemNascimento').value = objFound.ordemNascimento; document.getElementById('comentarioIdentificacao').value = objFound.comentarioIdentificacao; } function clearAllModalDadoDemografico() { document.getElementById('dataNascimento').value = ''; $("input:radio[name='indicador_acuracia_dia_nascimento']:checked").val(['']); $("input:radio[name='indicador_acuracia_mes_nascimento']:checked").val(['']); $("input:radio[name='indicador_acuracia_ano_nascimento']:checked").val(['']); document.getElementById('seguimento').checked = ''; document.getElementById('dataObito').value = ''; $("input:radio[name='indicador_acuracia_dia_obito']:checked").val(['']); $("input:radio[name='indicador_acuracia_mes_obito']:checked").val(['']); $("input:radio[name='indicador_acuracia_ano_obito']:checked").val(['']); $("input:radio[name='fonteNotificacao']:checked").val(['']); $("input:radio[name='etnia']:checked").val(['']); $("input:radio[name='genero']:checked").val(['']); $("input:radio[name='nacionalidade']:checked").val(['']); pais = ''; document.getElementById('estado2').value = ''; document.getElementById('cidade2').value = ''; document.getElementById('paisesEndereco').value = ''; dataEntradaNoBrasil = null; document.getElementById('pluralidadeNascimento').value = ''; document.getElementById('ordemNascimento').value = ''; document.getElementById('comentarioIdentificacao').value = ''; } function saveDadoDemograficoLocalStorage(dadoDemografico, tag) { currentList = JSON.parse(localStorage.getItem(tag)) || []; const index = currentList.findIndex(item => item.id === dadoDemografico.id); if (index > -1) { currentList.splice(index, 1, bond); } else { currentList.push(dadoDemografico); } localStorage.setItem(tag, JSON.stringify(currentList)); } function removeDadoDemograficoLocalStorage(id) { currentList = JSON.parse(localStorage .getItem(nameLocalStorageDadoDemografico)) || []; currentList.forEach(storageItem => { const index = currentList.findIndex(item => item.id === id); if (index > -1) { currentList.splice(index, 1); } }); localStorage.setItem(nameLocalStorageDadoDemografico, JSON.stringify(currentList)); }
///TODO REVIEW /** * @param {number[]} nums * @return {number[][]} */ var threeSum = function(nums) { if (nums.length === 0) return []; nums.sort(function(a, b){ return a-b; }); if (nums[nums.length-1] < 0) return []; var result = []; for (var i = 0; i < nums.length; i++) { if (nums[i] > 0) break; if (i > 0 && nums[i-1] === nums[i]) continue; var target = 0 - nums[i]; var start = i+1, end = nums.length -1; while (start < end) { if (nums[start] + nums[end] === target) { result.push([nums[i], nums[start], nums[end]]); while(start < end && nums[start] === nums[start+1]) start++; while(start < end && nums[end] === nums[end-1]) end--; start++; end--; } else if (nums[start] + nums[end] < target) { start++; } else { end--; } } } return result; }; console.log(threeSum([-1, 0, 1, 2, -1, -4]));
const request = require('supertest'); const app = require('../app').app; it('should return nums array', done => { const nums = [ { id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'e' } ]; request(app) .get('/api/users') .expect(200) .expect(nums) .end(done); });
// there's probably a better way to do the license badge section function renderLicenseBadge(license) { if (license[0] === `APACHE 2.0`) { return `[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)` } else if (license[0] === `MIT`) { return `[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)` } else if (license[0] === `GPL 3.0`) { return `[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)` } else if (license[0] === `BSD 3`) { return `[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)` } else if (license[0] === `None` || !license[0]) { return ``; } } // creates license section if there is a license selected function renderLicenseSection(license) { if (license[0] === `None` || !license[0]) { return ``; } else { return ` and License`; } } // generates optional sections based on whether or not there's input const generateSection = (propertyContent, headerText) => { if (!propertyContent) { return ``; } return `## ${headerText} ${propertyContent} ` } // creates tabel of contents links for optional sections const generateOptionalLink = (property, linkText) => { if (!property) { return ``; } return `- [${linkText}](#${linkText.toLowerCase()})` } function generateMarkdown(data) { return `# ${data.title} ## Description${renderLicenseSection(data.license)} ${data.description} ${renderLicenseBadge(data.license)} ## Table of Contents ${generateOptionalLink(data.installInstructions, `Installation`)} ${generateOptionalLink(data.usageInfo, `Usage`)} ${generateOptionalLink(data.contribution, `Contribution`)} ${generateOptionalLink(data.testInstructions, `Testing`)} - [Questions](#questions) ${generateSection(data.installInstructions, `Installation`)} ${generateSection(data.usageInfo, `Usage`)} ${generateSection(data.contribution, `Contribution`)} ${generateSection(data.testInstructions, `Testing`)} ## Questions If you have any questions: Find me on <a href = "http://www.github.com/${data.github}" target = "_blank">GitHub</a> or Contact me at ${data.email}. `; } module.exports = generateMarkdown;
// import { message } from 'antd' // import { ERROR } from '../config/error.config'; // import createHistory from 'history/createHashHistory'; // import axios from "axios"; // let cancelFlag:boolean = false; // // // 响应拦截 // axios.interceptors.response.use((response) => { // return response // }, (err) => { // if(err.response.status === '401'){ // if(cancelFlag) return Promise.reject(err); // cancelFlag = true; // message.error(ERROR.LOGIN_EXPIRESSED); // localStorage.removeItem('__config_center_token'); // localStorage.removeItem('__config_center_niceName'); // localStorage.removeItem('__config_center_imageUrl'); // const history = createHistory(); // setTimeout(() => { // history.push('/login') // setTimeout(() => { // cancelFlag = false; // },1000) // },1500) // } // return Promise.reject(err) // })
//index sayfası için angularjs kodlarını içerir. 'use strict'; angular.module('NetolcerApp', []) .controller('anasayfaController', ['$scope', function($scope) { //login - register için sayfa düzenlemesi ve request gönderme $scope.kayit = { kurum:"", sehir:"", telno:"", mail:"", sifre:"", adres:"" }; $scope.giris = { alan:"", sifre:"" }; $scope.girisyap = function(){ alert($scope.giris); if($scope.girisform.$valid) { // use $.param jQuery function to serialize data from JSON var data = $.param($scope.giris); var config = { headers : { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' } }; $http.post("/Musteriler",data,config).success(function(data,status,headers,config){ //sisteme giriş yapılır. var ResponseDetails = "Data: " + data + "<hr />status: " + status + "<hr />headers: " + header + "<hr />config: " + config; alert(ResponseDetails); }).error(function (data, status, header, config) { var ResponseDetails = "Data: " + data + "<hr />status: " + status + "<hr />headers: " + header + "<hr />config: " + config; alert(ResponseDetails); }); } }; $scope.kayitol=function(){ alert($scope.kayit.kurum); } //yan sayılar -> yöneticinin belirlediği sayılar //sunum için sunucudan video veya bağlanti çekme //ücretler //mail gönderme }]);
/** * 分值计算 */ class Data{ constructor(){ this.fruitNum = 0;//果实数量 this.double = 1;//是否吃到蓝色果实 this.score = 0;//分值 this.gameOver = false;//游戏结束 this.alpha = 0; } reset(){ this.fruitNum = 0;//果实数量 this.double = 1;//是否吃到蓝色果实 } draw(){ var w = can1.width; var h = can1.height; ctx1.save(); ctx1.shadowBlur = 10; ctx1.shadowColor = "white"; ctx1.fillStyle = 'white'; ctx1.fillText('score: ' + this.score, w * 0.5, 50); if(this.gameOver){ this.alpha += deltaTime * 0.0005; if(this.alpha > 1){ this.alpha = 1; } ctx1.fillStyle = "rgba(255, 255, 255, "+ this.alpha +")" ctx1.fillText('game over', w * 0.5 , h * 0.5); } ctx1.restore(); } addScore(){ this.score += this.fruitNum * 100 * this.double; this.reset(); } }
const fs = require('fs') const Discord = require('discord.js') const config = require('./config.json') const storage = require('./util/storage.js') const currentGuilds = storage.currentGuilds if (config.logging.logDates === true) require('./util/logDates.js')() const Manager = new Discord.ShardingManager('./server.js', {respawn: false}) const missingGuilds = {} if (!config.advanced || typeof config.advanced.shards !== 'number' || config.advanced.shards < 1) { if (!config.advanced) config.advanced = {} config.advanced.shards = 1 console.log('SH MANAGER: No valid shard count found in config, setting default of 1') } Manager.spawn(config.advanced.shards, 0) const activeShardIds = [] const refreshTimes = [config.feedSettings.refreshTimeMinutes ? config.feedSettings.refreshTimeMinutes : 15] // Store the refresh times for the setIntervals of the cycles for each shard const scheduleIntervals = [] // Array of intervals for each different refresh time const scheduleTracker = {} // Key is refresh time, value is index for activeShardIds Manager.shards.forEach(function (val, key) { activeShardIds.push(key) }) let initShardIndex = 0 Manager.broadcast({type: 'startInit', shardId: activeShardIds[0]}) // Send the signal for first shard to initialize fs.readdir('./settings/schedules', function (err, files) { if (err) return console.log(err) for (var i in files) { fs.readFile('./settings/schedules/' + files[i], function (err, data) { if (err) return console.log(err) const refreshTime = JSON.parse(data).refreshTimeMinutes if (!refreshTimes.includes(refreshTime)) refreshTimes.push(refreshTime) }) } }) Manager.on('message', function (shard, message) { if (message === 'kill') process.exit() if (message.type === 'missingGuild') { if (!missingGuilds[message.content]) missingGuilds[message.content] = 1 else missingGuilds[message.content]++ } else if (message.type === 'initComplete') { initShardIndex++ if (initShardIndex === Manager.totalShards) { console.log(`SH MANAGER: All shards initialized.`) for (var gId in message.guilds) { // All guild profiles, with guild id as keys and guildRss as value currentGuilds.set(gId, message.guilds[gId]) } for (var guildId in missingGuilds) { if (missingGuilds[guildId] === Manager.totalShards) console.log('SH MANAGER: WARNING - Missing Guild from bot lists: ' + guildId) } for (var i in refreshTimes) { const refreshTime = refreshTimes[i] scheduleIntervals.push(setInterval(function () { scheduleTracker[refreshTime] = 0 // Key is the refresh time, value is the activeShardIds index let p = scheduleTracker[refreshTime] Manager.broadcast({type: 'runSchedule', shardId: activeShardIds[p], refreshTime: refreshTime}) }, refreshTime * 60000)) } try { require('./web/app.js')(null, Manager) } catch (e) {} } else if (initShardIndex < Manager.totalShards) Manager.broadcast({type: 'startInit', shardId: activeShardIds[initShardIndex]}) // Send signal for next shard to init } else if (message.type === 'scheduleComplete') { scheduleTracker[message.refreshTime]++ // Index for activeShardIds if (scheduleTracker[message.refreshTime] !== Manager.totalShards) Manager.broadcast({shardId: activeShardIds[scheduleTracker[message.refreshTime]], type: 'runSchedule', refreshTime: message.refreshTime}) // Send signal for next shard to start cycle // else console.log(`SH MANAGER: Cycles for all shards complete. for interval ${message.refreshTime} minutes`) } else if (message.type === 'updateGuild') { currentGuilds.set(message.guildRss.id, message.guildRss) } else if (message.type === 'deleteGuild') { currentGuilds.delete(message.guildId) } })
module.exports = (sequelize, DataTypes) => { const UsersRoles = sequelize.define( 'UsersRoles', { userId: { type: DataTypes.BIGINT, allowNull: false, primaryKey: true, references: { model: sequelize.User, key: 'id' } }, roleId: { type: DataTypes.BIGINT, allowNull: false, primaryKey: true, references: { model: sequelize.Role, key: 'id' } }, active: { type: DataTypes.BOOLEAN, allowNull: false }, created: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW } }, { sequelize, underscored: true, tableName: 'users_roles', createdAt: 'created', updatedAt: false } ); UsersRoles.associate = function (models) { this.belongsTo(models.User, { foreignKey: 'UserId' }); this.belongsTo(models.Role, { foreignKey: 'RoleId' }); }; return UsersRoles; };
const express = require('express'); const DroneModel = require('../models/drone-model.js'); const router = express.Router(); router.get('/', (req, res, next) => { res.render('index'); }); router.get('/drones', (req, res, next) => { DroneModel.find((err, dronesArray)=>{ if (err) { next(err); return; } res.render('../views/drones/all-drones-view.ejs', { dronesList : dronesArray }); }); }); // Adding a new drone --------------------------- router.get('/drones/new', (req, res, next) => { res.render('../views/drones/new.ejs'); }); router.post('/drones', (req, res, next) => { const newDrone = new DroneModel ({ droneName: req.body.droneName, propellers: req.body.dronePropellers, maxSpeed: req.body.droneMaxSpeed }); newDrone.save((err)=>{ if (err) { // use next() to skip to the ERROR PAGE next(err); return; } res.redirect('/drones'); }); }); // Editing existing drone -------------------- //Step 1 of form submission for updating a product router.get('/drones/:myID/edit', (req, res, next) => { DroneModel.findById( req.params.myID, (err, droneFromDb) => { if(err) { next(err); return; } res.render('drones/edit',{ theDrone : droneFromDb }); } ); }); //STEP #2 of form submission for an edit product router.post('/drones/:myID/update',(req, res, next)=>{ // The parameters that findByIdandUpdate needs: DroneModel.findByIdAndUpdate( req.params.myID, // 1: the ID { //2: object fields to update droneName: req.body.droneName, propellers: req.body.dronePropellers, maxSpeed: req.body.droneMaxSpeed }, (err, productFromDb) => { //3: callback if(err) { next(err); return; } res.redirect('/drones'); } ); }); // REMOVING ITEM --------------------------------- router.post('/drones/:myID/remove',(req, res, next)=>{ // The parameters that findByIdandRemoveneeds: DroneModel.findByIdAndRemove( req.params.myID, // 1: the ID (err, droneFromDb) => { //2: callback if(err) { next(err); return; } res.redirect('/drones'); } ); }); module.exports = router;
"use strict"; angular.module('deposito'). controller('registroSalidaController',function($scope,$http,$modal){ $scope.insumoSelect = {}; $scope.terceroSelect = {}; $scope.documentoSelect = {}; $scope.terceros = []; $scope.documentos = []; $scope.listInsumos = []; $scope.insumos = []; $scope.alert = {}; $scope.refreshInsumos = function(insumo) { var params = {insumo: insumo}; return $http.get( 'inventario/getInsumosInventario', {params: params} ).then(function(response){ $scope.listInsumos = response.data }); }; $http.get('/documentos/all/salidas') .success( function(response){ $scope.documentos = response;}); $scope.agregarInsumos = function(){ if(!$scope.insumoSelect.selected){ $scope.alert = {type:"danger" , msg:"Por favor especifique un insumo"}; return; } if( insumoExist($scope.insumoSelect.selected.codigo) ){ $scope.alert = {type:"danger" , msg:"Este insumo ya se ha agregado en esta entrada"}; return; } $scope.insumos.unshift( { 'id':$scope.insumoSelect.selected.id, 'codigo':$scope.insumoSelect.selected.codigo, 'descripcion':$scope.insumoSelect.selected.descripcion } ); $scope.insumoSelect = {}; } $scope.registrar = function(){ if( !validaCantidad() ){ $scope.alert = {type:"danger" , msg:"Especifique valores validos para cada insumo"}; return; } $scope.modalInstance = $modal.open({ animation: true, templateUrl: 'confirmeRegister.html', 'scope':$scope }); $scope.cancel = function () { $scope.modalInstance.dismiss('cancel'); }; $scope.cofirme = function(){ save(); $scope.modalInstance.dismiss('cancel'); $scope.loader = true; } } var save = function($data){ var $data = { 'documento': parseDocumento(), 'tercero' : parseTercero(), 'insumos' : empaquetaData() }; $http.post('/registrarSalida', $data) .success( function(response){ $scope.loader = false; if(response.status == 'unexist'){ marcaInsumos(response.data); $scope.alert = {type:'danger', msg:'La cantidad de los insumos marcados son insuficientes'}; return; } if( response.status == 'success'){ $modal.open({ animation: true, templateUrl: 'successRegister.html', controller: 'successRegisterCtrl', resolve: { response: function () { return response; } } }); restablecer(); return; } $scope.alert = {type:response.status , msg: response.menssage}; } ); } $scope.eliminarInsumo = function(index){ $scope.insumos.splice(index, 1); }; $scope.closeAlert = function(){ $scope.alert = {}; }; $scope.thereInsumos = function(){ return $scope.insumos.length > 0 ? true:false; }; $scope.searchTerceros = function(){ if($scope.documentoSelect.hasOwnProperty('selected')){ $scope.terceros = []; $scope.terceroSelect = {}; if($scope.documentoSelect.selected.tipo != "interno"){ $http.get('/depositos/terceros/'+ $scope.documentoSelect.selected.tipo) .success(function(response){ $scope.terceros = response; $scope.panelTerceros = true; }); } else{ $scope.panelTerceros = false; } } } function insumoExist(codigo){ var index; for(index in $scope.insumos){ if($scope.insumos[index].codigo == codigo) return true; } return false; }; function validaCantidad(){ var index; for( index in $scope.insumos){ if( !$scope.insumos[index].despachado || $scope.insumos[index].despachado < 0 || $scope.insumos[index].solicitado < $scope.insumos[index].despachado) return false; } return true; } function empaquetaData(){ var index; var insumos = []; for( index in $scope.insumos){ insumos.push({'id': $scope.insumos[index].id, 'solicitado':$scope.insumos[index].solicitado, 'despachado':$scope.insumos[index].despachado}); } return insumos; } function marcaInsumos(ids){ var index; var id; for(index in $scope.insumos){ $scope.insumos[index].style = ''; } for( id in ids){ for(index = 0; index < $scope.insumos.length; index++) if($scope.insumos[index].id == ids[id] ){ $scope.insumos[index].style = 'danger'; break; } } } function restablecer(){ $scope.insumos = []; $scope.terceros = []; $scope.alert = {}; $scope.documentoSelect = {}; $scope.terceroSelect = {}; $scope.panelTerceros = false; $scope.insumoSelect = {}; } var parseDocumento = function(){ if($scope.documentoSelect.hasOwnProperty('selected')) return $scope.documentoSelect.selected.id; return ''; } var parseTercero = function(){ if($scope.terceroSelect.hasOwnProperty('selected')) return $scope.terceroSelect.selected.id; return ''; } }); angular.module('deposito').controller('successRegisterCtrl', function ($scope, $modalInstance, response) { $scope.response = response; $scope.ok = function () { $modalInstance.dismiss('cancel'); }; });
const _ = require('lodash'); const fileUtils = require('./fileUtils'); function cloneBoilerplate(config, sourceDir, options) { const project = require('./project')(config); if (!options.force && fileUtils.exists(project.destinationDir)) { fail('\n - Error: "' + project.destinationDir + '" already exists!\n'); } fileUtils.copy(sourceDir, project.destinationDir, processFile.bind(null, project.name)); _.each(['gitignore', 'eslintrc', 'npmignore'], function(fileName) { const hiddenFile = project.destinationDir + '/' + fileName; if (fileUtils.exists(hiddenFile)) { fileUtils.rename(hiddenFile, project.destinationDir + '/.' + fileName); } }); } module.exports = cloneBoilerplate; // ********************************* PROTECTED ********************************* function fail(message) { console.error(message); process.exit(1); } function processFile(projectName, newFile) { newFile.path = newFile .path .replace(projectName.boilerplateName.snakeCase, projectName.snakeCase); newFile.path = newFile .path .replace(projectName.boilerplateName.kebabCase, projectName.kebabCase); if (newFile.contents) { newFile.contents = projectName.replaceBoilerplateName(newFile.contents, projectName); } }
/** * Created by rs on 12/03/17. */ import MemberListView from '../Components/view-all/MemberListView' import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import {getMembers} from '../ActionCreators/membersActionCreator' const mapDispatchToProps = (dispatch) => { return bindActionCreators({getMembers, dispatch}, dispatch); }; const mapStateToProps = (state) => { return { members: state.members.get("members") } }; const MembersListViewContainer = connect(mapStateToProps, mapDispatchToProps)(MemberListView); export default MembersListViewContainer;
import MagazineCard from "./MagazineCard"; const cards = [ { img: "https://images.unsplash.com/photo-1596760020480-3b330a990539?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=935&q=80", title: "This is TITLE", user: { name: "Seol", category: "photographer", }, meta: { like: 213, view: 12123, bookmark: 123, }, }, { img: "https://images.unsplash.com/photo-1616740386718-6a4e42e3cf02?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80", title: "This is TITLE", user: { name: "Seol", category: "photographer", }, meta: { like: 213, view: 12123, bookmark: 123, }, }, { img: "https://images.unsplash.com/photo-1615537572530-4c76817865c6?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80", title: "This is TITLE", user: { name: "Seol", category: "photographer", }, meta: { like: 213, view: 12123, bookmark: 123, }, }, { img: "https://images.unsplash.com/photo-1614788466123-1ec2a5833087?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80", title: "This is TITLE", user: { name: "Seol", category: "photographer", }, meta: { like: 213, view: 12123, bookmark: 123, }, }, { img: "https://images.unsplash.com/photo-1618278096912-d14cda36d45b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1651&q=80", title: "This is TITLE", user: { name: "Seol", category: "photographer", }, meta: { like: 213, view: 12123, bookmark: 123, }, }, ]; document.getElementsByClassName("RandomMagazine")= function RandomMagazine() { cards.map((card, index) => { return ( <div className={`card_container-${index}`}> <MagazineCard key={index} {...card} /> </div> ); })}
const Events = require('../models/events'); let eventsController = {}; eventsController.createEvent = (body) => { return new Promise(async (res, rej) => { let event = { calendarid: body.calendarid, foreignid: body.foreignid || null, start: {dateTime: body.start.dateTime}, end: {dateTime: body.end.dateTime}, summary: body.summary } Events.create(event).then((newEvent) => { res(newEvent); }) .catch((e) => { console.log(e); rej(e); }) }) } eventsController.saveGoogleEvents = (calendarid, events) => { return new Promise(async (res, rej) => { let promiseArr = []; events.events.forEach(event => { promiseArr.push(eventsController.createEvent({ calendarid: calendarid, start: {dateTime: event.start.dateTime}, end: {dateTime: event.end.dateTime}, summary: event.summary })); }); Promise.all(promiseArr) .then((data) => { // console.log(data); res(data); }) .catch((e) => { console.log(e); rej(e); }) }) } eventsController.saveMicrosoftEvents = (calendarid, events) => { return new Promise(async (res, rej) => { let savedEvents = await Events.find({calendarid: calendarid}); let newEvents = events.filter(item => { let index = savedEvents.findIndex((el) => { return el.foreignid === item.id; }) return index == -1; }); let promiseArr = []; newEvents.forEach((event) => { promiseArr.push(eventsController.createEvent({ calendarid: calendarid, start:{dateTime: event.start.dateTime}, end: {dateTime: event.end.dateTime}, summary: event.summary, foreignid: event.id })) }); Promise.all(promiseArr) .then((success) => { console.log(success); res(success); }) .catch((e) => { console.log('ERROR'); console.log(e); rej(e); }) }) } module.exports = eventsController;
import Colors from '@Colors/colors' import { horizontalAbsolutePosition } from '../../util/StyleUtils' import commonStyle from '../style' const styles = { outerContainer: { ...horizontalAbsolutePosition(0, 0), height: 244 }, loginContainer: { backgroundColor: 'white', ...commonStyle.shadow, flexDirection: 'column' }, loginButton: { height: 68, padding: 20, alignItems: 'center', justifyContent: 'center' }, loginButtonText: { fontSize: 24, textAlign: 'center' }, input: { height: 68, fontSize: 20, color: Colors.primaryBlue, backgroundColor: 'white', textAlign: 'center' }, separator: { height: 1, backgroundColor: Colors.gray5 }, storePasswordContainer: { height: 40, backgroundColor: 'white', flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }, checkbox: { height: 50, flex: 1, paddingHorizontal: 30, justifyContent: 'center', alignItems: 'center' }, checkboxLeftText: { fontSize: 14, justifyContent: 'center', color: Colors.primaryBlue }, checkboxImage: { tintColor: Colors.primaryBlue } } export default styles
import React, { useState } from "react" import blogService from "../services/blogs" import Notification from "../components/Notification" import Togglable from "../components/Togglable" import { useField } from "../hooks" const Newblog = () => { const title = useField("text") const resetTitle = title.resetValue const author = useField("text") const resetAuthor = author.resetValue const url = useField("text") const resetUrl = url.resetValue const [successMsg, setSuccessMsg] = useState("") const [errorMsg, setErrorMsg] = useState("") delete title.resetValue delete author.resetValue delete url.resetValue const blogFormRef = React.createRef() const handlePost = async event => { event.preventDefault() blogFormRef.current.toggleVisibility() try { await blogService.create({ title: title.value, author: author.value, url: url.value }) setSuccessMsg( "Successfully posted " + title + ", with author " + author + " and a url of " + url ) resetTitle() resetAuthor() resetUrl() } catch (err) { setErrorMsg(err.response.data.message) console.log(err) } } return ( <div> <Notification successMsg={successMsg} setSuccessMsg={setSuccessMsg} errorMsg={errorMsg} setErrorMsg={setErrorMsg} /> <Togglable buttonLabel="new blog" ref={blogFormRef}> <div> <form onSubmit={handlePost}> <h2>Make a new blog</h2> <div> title <input {...title} /> </div> <div> author <input {...author} /> </div> <div> url <input {...url} /> </div> <button type="submit">post</button> </form> </div> </Togglable> </div> ) } export default Newblog
// let item = document.querySelectorAll("button"); let background = document.getElementsByTagName("body"); let buttons = document.querySelectorAll("button"); let theme0btn = document.getElementById("theme0"); let theme1btn = document.getElementById("theme1"); let theme2btn = document.getElementById("theme2"); let theme3btn = document.getElementById("theme3"); let theme4btn = document.getElementById("theme4"); let theme5btn = document.getElementById("theme5"); // Salt.addEventListener("click",function(){ // item.innerHTML = "hidden"; // }); function theme(a){ for(let i=0;i<buttons.length;i++){ // buttons[i].style.backgroundColor="var(--theme"+a+"--)"; // buttons[i].style.boxShadow="0 6px var(--theme"+a+"shadow--)"; buttons[i].className="button"+a; } background[0].style.backgroundColor="var(--them"+a+"background--)"; } theme0btn.addEventListener("click",function(){ theme(0); }); theme1btn.addEventListener("click",function(){ theme(1); }); theme2btn.addEventListener("click",function(){ theme(2); }); theme3btn.addEventListener("click",function(){ theme(3); }); theme4btn.addEventListener("click",function(){ theme(4); }); theme5btn.addEventListener("click",function(){ theme(5); }); // buttons[0].addEventListener("click",function(){ // buttons[0].style.backgroundColor= "var(--theme1--)"; // });
#! /usr/bin/env node if (process.argv.length > 2 && process.argv[2] == '--help') { console.log('Usage: node ' + process.argv[1] + ' [PORT]'); console.log(' PORT is by default 8080'); process.exit(0); } var port = 8080; if (process.argv.length > 2) { port = +process.argv[2]; } var express; try { var express = require('express'); } catch (err) { console.error("Please install express first: npm install express"); console.error(err); process.exit(1); } var http = require('http') , path = require('path') , KIARA = require('./static/scripts/kiara.js'); // Register additional MIME types express.static.mime.define({'text/plain': ['kiara', 'idl']}); // Create KIARA service var context = KIARA.createContext(); var calcService = context.createService('calc', 'http://localhost:'+port+'/rpc/calc'); calcService.registerMethod('calc.add', null, function (a, b, callback) { callback(null, ((a | 0) + (b | 0)) | 0); }); calcService.registerMethod('calc.sub', null, function (a, b, callback) { callback(null, ((a | 0) - (b | 0)) | 0); }); calcService.registerMethod('calc.addf', null, function (a, b, callback) { callback(null, a+b); }); calcService.registerMethod('calc.stringToInt32', null, function (s, callback) { console.log("calc.stringToInt32("+s+");"); callback(null, s|0); }); calcService.registerMethod('calc.int32ToString', null, function (i, callback) { console.log("calc.int32ToString("+i+");"); callback(null, i.toString()); }); var endpointInfo = { info : "test server", idlURL : "/idl/calc.kiara", // absolute or relative URL // idlContents : "...", // IDL contents servers : [ { services : "*", protocol : { name : "jsonrpc" }, transport : { name : "http", url : "/rpc/calc" } }, { services : "*", protocol : { name : "xmlrpc" }, transport : { name : "http", url : "/xmlrpc/calc" } } ] }; var app = express(); app.configure(function() { app.set('port', port); app.use(express.favicon()); app.use(express.logger('dev')); // CORS support app.all('/*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); // Serve index.html when root is specified '/' app.get('/', function(req, res) { res.sendfile('static/kiara_test.html') // res.sendfile('static/index.html') }); // Deliver configuration informations app.get('/service', function(req, res) { res.format({ 'application/json' : function() { res.send(endpointInfo); } }); }); // For direct access to the raw data stream KIARA.node.serve must be called // before express.bodyParser app.use(KIARA.node.serve("/rpc/calc", "jsonrpc", calcService)); app.use(KIARA.node.serve("/xmlrpc/calc", "xmlrpc", calcService)); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.directory(path.join(__dirname, 'static'))); // serve directories app.use(express.static(path.join(__dirname, 'static'))); // static content }); app.configure('development', function() { app.use(express.errorHandler()); }); // Run server http.createServer(app).listen(app.get('port'), function() { console.log("KIARA server listening on http://localhost:" + app.get('port')); }); // Run jsonrpc server var jayson = require("jayson"); // create a server var jsonrpcServer = jayson.server({ 'calc.add': function(a, b, callback) { callback(null, ((a | 0) + (b | 0)) | 0); }, 'calc.addf': function(a, b, callback) { callback(null, a + b); } }); // Bind a http interface to the server and let it listen to localhost:3000 jsonrpcServer.http().listen(3000, function() { console.log("KIARA JSON-RPC server listening on http://localhost:" + 3000); }); // Run xmlrpc server var xmlrpc = require('xmlrpc'); // Creates an XML-RPC server to listen to XML-RPC method calls var server = xmlrpc.createServer({ host: 'localhost', port: 3001 }) // Handle methods not found server.on('NotFound', function(method, params) { console.log('Method ' + method + ' does not exist'); }) // Handle method calls by listening for events with the method call name server.on('calc.add', function (err, params, callback) { console.log('Method call params for \'calc.add\': ' + params); var a = params[0]; var b = params[1]; // ...perform an action... var result = ((a | 0) + (b | 0)) | 0; // Send a method response with a value callback(null, result); }) console.log('XML-RPC server listening on port 3001') // Local Variables: // tab-width:2 // c-basic-offset: 2 // espresso-indent-level: 2 // indent-tabs-mode: nil // End: // vim: set expandtab tabstop=2 shiftwidth=2:
/** * Created by yineng on 2017/2/16. */ $(document).ready(function(){ $('#button').click(function(){ //console.log('124'); $.ajax({ type:"GET", url:"ztree.json", dataType:"json", success:function(data){ console.log('1234'); var song="<ul>"; //i表示在data中的索引位置,n表示包含的信息的对象 $.each(data,function(i,n){ //获取对象中属性为optionsValue的值 song+="<li>"+n["optionValue"]+"</li>"; }); song+="</ul>"; $('#result').append(song); } }); return false; }); });
const chai = require('chai'); const chaiAsPromised = require('chai-as-promised'); const helpers = require('../server/controllers/helpers'); const Album = require('../database/models/album'); const Song = require('../database/models/song'); const expect = chai.expect; chai.use(chaiAsPromised); describe('Helper methods', () => { resetDb(); describe('findOrCreate', () => { it('should create a record if it does not exist', () => { const attributes = { name: 'this is a test name', artist_id: 1 }; return expect(helpers.findOrCreate(Album, attributes, { slug: helpers.createSlug('a') }) .then(album => album.attributes.name)).to.eventually.equal('this is a test name'); }); it('should find a record if it already exists', () => { const attributes = { id: 1 }; return expect(helpers.findOrCreate(Song, attributes).then(song => song.attributes.name)).to.eventually.equal('Fantasy in D'); }); }); describe('createSlug', () => { it('should create an 8 character unique identifier', () => { return expect(helpers.createSlug('a').length).to.equals(9); }); it('should create an 8 character unique identifier', () => { return expect(helpers.createSlug).to.throw(Error); }); }); describe('isMatch', () => { it('should return a confidence score >= 80% for two strings that are more than 80% similar', () => { expect(helpers.isMatch('Art Blakey & The Jazz Messengers', 'Art Blakey and The Jazz Messengers')).to.be.at.least(0.8); }); it('should return a confidence score of 50% for two strings that are more than 50% similar', () => { expect(helpers.isMatch('0000011111', '1111111111')).to.equal(0.5); }); it('should return a confidence score of 0% for two strings with 0 similar characters', () => { expect(helpers.isMatch('12345', '67890')).to.equal(0); }); it('should return a confidence score of 20% for two strings with 1 similar characters and a length of 5', () => { expect(helpers.isMatch('12345', '17890')).to.equal(0.2); }); it('should return a confidence score of xx% for two strings that are more than xx% similar', () => { expect(helpers.isMatch('12345', '67890')).to.equal(0); }); it('should return a confidence score of 60% for two strings that are more than 60% similar', () => { expect(helpers.isMatch('1101', '11111')).to.equal(0.6); }); it('should return a confidence score < 80% for two strings that are less than 80% similar', () => { expect(helpers.isMatch('Art Blakey & The Jazz Messengers', 'Mingus Big Band')).to.be.below(0.8); }); it('should return 0 if the method doesn\'t take two strings', () => { expect(helpers.isMatch(null, 'test')).to.equal(0); }); }); describe('removeParensContent', () => { it('should remove the content in parenthesis within a string', () => { return expect(helpers.removeParensContent('People Time (Live Copenhagen 1991)')).to.equal('People Time'); }); }); });
import React from "react"; import Logo from "../images/Twitter-Logo.png"; import { useSelector, useDispatch } from "react-redux"; import { Link } from "react-router-dom"; import { logOutAction } from "../Actions/userActions"; const SideBar = () => { const dispatch = useDispatch(); const userLoginAndRegister = useSelector( (state) => state.userLoginAndRegister ); const { user, loggedIn } = userLoginAndRegister; const onLogOut = (e) => { e.preventDefault(); dispatch(logOutAction()); }; return ( <> <div className='hidden lg:flex lg:flex-shrink-0'> <div className='flex flex-col w-64'> <div className='flex flex-col h-0 flex-1 border-r border-gray-200 bg-white-100'> <div className='flex-1 flex flex-col pt-5 pb-4 overflow-y-auto'> <div className='flex items-center flex-shrink-0 px-4'> <img className='h-8 w-auto' src={Logo} alt='Workflow' /> </div> <nav className='mt-5 flex-1' aria-label='Sidebar'> <div className='px-2 space-y-1'> {/* Current: "bg-gray-200 text-gray-900", Default: "text-gray-600 hover:bg-gray-50 hover:text-gray-900" */} <Link to='/' className='bg-gray-200 text-gray-900 group flex items-center px-2 py-2 text-sm font-medium rounded-md' > {/* Current: "text-gray-500", Default: "text-gray-400 group-hover:text-gray-500" */} <i className='fas fa-house-user mr-3' style={{ fontSize: "1.3rem" }} ></i> Home </Link> <Link to='/' className='text-gray-600 hover:bg-gray-50 hover:text-gray-900 group flex items-center px-2 py-2 text-sm font-medium rounded-md' > <i className='far fa-bell mr-4' style={{ fontSize: "1.3rem" }} ></i> Notifications </Link> <Link to='/' className='text-gray-600 hover:bg-gray-50 hover:text-gray-900 group flex items-center px-2 py-2 text-sm font-medium rounded-md' > <i className='far fa-envelope mr-3' style={{ fontSize: "1.3rem" }} ></i> Messenger </Link> <Link to={`/profile/${user.id}`} className='text-gray-600 hover:bg-gray-50 hover:text-gray-900 group flex items-center px-2 py-2 text-sm font-medium rounded-md' > <i className='far fa-user mr-4' style={{ fontSize: "1.3rem" }} ></i> Profile </Link> {loggedIn ? ( <Link onClick={onLogOut} className='text-gray-600 hover:bg-gray-50 hover:text-gray-900 group flex items-center px-2 py-2 text-sm font-medium rounded-md' > <i className='fas fa-door-open mr-2' style={{ fontSize: "1.3rem" }} ></i> Log Out </Link> ) : ( <Link to='/login' className='text-gray-600 hover:bg-gray-50 hover:text-gray-900 group flex items-center px-2 py-2 text-sm font-medium rounded-md' > <i className='fas fa-door-open mr-2' style={{ fontSize: "1.3rem" }} ></i> Sign In </Link> )} </div> </nav> </div> {loggedIn && ( <div className='flex-shrink-0 flex border-t border-gray-200 p-4'> <Link to={`/profile/${user.id}`} className='flex-shrink-0 w-full group block' > <div className='flex items-center'> <div> <img className='inline-block h-9 w-9 rounded-full' src={user.profileImage} alt='' /> </div> <div className='ml-3'> <p className='text-sm font-medium text-gray-700 group-hover:text-gray-900'> {user.name} </p> <p className='text-xs font-medium text-gray-500 group-hover:text-gray-700'> View profile </p> </div> </div> </Link> </div> )} </div> </div> </div> </> ); }; export default SideBar;
import Phaser from "phaser"; // import './lib/jquery.js' import './lib/codemirror.css' import './lib/index.css' import './lib/bootstrap.css' import { config, watchState } from './GameEngine' import { CodeEditor } from './CodeEditor' $('#lesson-modal').modal('show') window.myFunction = function () { var divId = event.target.dataset.id var divCClass = `intro-${divId}` var currentDiv = document.querySelector(`.${divCClass}`) if (event.target.dataset.type === "next") { let divNClass = `intro-${++divId}` let nextDiv = document.querySelector(`.${divNClass}`) currentDiv.style.display = "none" nextDiv.style.display = "block" } else if (event.target.dataset.type === "back") { let divPClass = `intro-${--divId}` let prevDiv = document.querySelector(`.${divPClass}`) currentDiv.style.display = "none" prevDiv.style.display = "block" } else { $('#lesson-modal').modal('hide') } } new Phaser.Game(config); //new game let code = new CodeEditor(document.querySelector('.code-editor')) watchState( scope => code.scope = scope ) let runButton = document.querySelector('.run') runButton.addEventListener( 'click', () => { code.scope.reset() setTimeout( () => code.execute(), 250) })
import React, { useContext } from 'react' import { CountContext } from '.' import { getBg } from '../getColor' export const Count = () => { const count = useContext(CountContext) return <div style={getBg('255,1,1')}>{count?.count}</div> }
'use strict'; angular.module('web3D.Classes').factory('Map', function () { function Map(container) { this.map = L.map(container); // add an OpenStreetMap tile layer L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(this.map); }; Map.prototype.locate = function() { this.map.locate({setView: true, maxZoom: 16}); }; return Map; });
import {request} from '../../../services/api' import { loadingConnections, fetchConnectionsSuccess, fetchConnectionsFail, connectionAdded, connectionEdited, connectionRemoved } from './index' export const fetchConnections = () => { return async dispatch => { try { dispatch(loadingConnections()) const data = await request({type:'get', path: '/ligacoes'}) dispatch(fetchConnectionsSuccess(data)) } catch(e) { dispatch(fetchConnectionsFail(e)) } } } export const addConnection = (connection) => { return async dispatch => { const data = await request({type:'post', path: '/ligacoes/', requestData: connection}) dispatch(connectionAdded(data)) } } export const editConnection = (oldId, connection) => { return async dispatch => { const data = await request({type: 'patch', path: `/ligacoes/${oldId}/`, requestData: connection}) dispatch(connectionEdited({ id: oldId, data })) } } export const deleteConnection = (id) => { return async dispatch => { await request({type: 'delete', path: `/ligacoes/${id}/`}) dispatch(connectionRemoved(id)) } }
exports.normal = function (bot, message) { const content = message.content.split(' ') if (content.length === 1) return content.shift() let username = content.join(' ') bot.user.setUsername(username).catch(err => console.log(`Bot Controller: Unable to set username. (${err})`)) } exports.sharded = exports.normal
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); exports.default = createCommand; var _prosemirrorState = require('prosemirror-state'); var _prosemirrorTransform = require('prosemirror-transform'); var _prosemirrorView = require('prosemirror-view'); var _UICommand2 = require('./ui/UICommand'); var _UICommand3 = _interopRequireDefault(_UICommand2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createCommand(execute) { var CustomCommand = function (_UICommand) { (0, _inherits3.default)(CustomCommand, _UICommand); function CustomCommand() { var _ref; var _temp, _this, _ret; (0, _classCallCheck3.default)(this, CustomCommand); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = CustomCommand.__proto__ || (0, _getPrototypeOf2.default)(CustomCommand)).call.apply(_ref, [this].concat(args))), _this), _this.isEnabled = function (state) { return _this.execute(state); }, _this.execute = function (state, dispatch, view) { var tr = state.tr; var endTr = tr; execute(state, function (nextTr) { endTr = nextTr; dispatch && dispatch(endTr); }, view); return endTr.docChanged || tr !== endTr; }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret); } return CustomCommand; }(_UICommand3.default); return new CustomCommand(); }
const assert = require('assert') const utils = require('../..') assert(utils.isDefined(true)) assert(!utils.isDefined(undefined))
'use strict'; var winston = require('winston'); var _ = require('lodash'); var utils = require('../utils'); var logger = require('../logger'); var customerSuccessList = require('./customerSuccess'); var customerList = require('./customer'); var socketAdapter = require('./socketAdapter'); var messageAdapter = require('./messageAdapter'); var message = require('../database/message'); var chatHistory = require('../database/chatHistory'); var SocketCustomerSuccessEvents = {}; SocketCustomerSuccessEvents.setup = function(socket) { var session = socket.request.session; if (!session) return ; var csid = session.csid; winston.info('customer success id is : %s', csid); if (_.isUndefined(csid)) { logger.error('csid is null , need Login again!'); socket.emit('uu error', 'csid is null, need login again!'); return ; } var customerSuccess = customerSuccessList.get(csid); //system to start and reconnect if (_.isEmpty(customerSuccess)) { winston.info('system has restart'); // if synchronous create and customerSuccess.socket, there is no lock for customerSuccess // so customerSuccess.socket not success; customerSuccessList.create({csid: csid, socket: socket, name: session.csName, photo: session.photo}); messageAdapter.listOfflineMessage(csid); return ; } if (!_.isEmpty(customerSuccess.socket)) { customerSuccess.socket.emit('cs.need.login', function (success) { if (success) { setTimeout(function(){ setupAfter(customerSuccess, socket, csid); }, 1000); } } ); } else { winston.info('customer success login or refresh browser'); setupAfter(customerSuccess, socket, csid); } }; function setupAfter(customerSuccess, socket, csid) { customerSuccess.socket = socket; socketAdapter.emitCustomerList(csid); messageAdapter.listOfflineMessage(csid); } SocketCustomerSuccessEvents.refreshOnlineInfo = function() { if (global.env === 'development') { customerSuccessList.dataInfoLog(); customerList.dataInfoLog(); } if (customerSuccessList.onlineNum() === 0) return; var list = customerSuccessList.list(); var result = {}; //contains own customer num _.forIn(list, function (value, key) { var customerOnlineNum = 0; if (value.users) { customerOnlineNum = value.users.length; } result[key] = [value.name, value.photo, customerOnlineNum]; }); _.forIn(list, function (value, key) { if (!_.isEmpty(list[key].socket)) { list[key].socket.emit("cs.online.info", result); } }); }; SocketCustomerSuccessEvents.message = function(cid, msg, fn) { // null check ; if (_.isUndefined(msg) || _.isNull(msg) || msg.length === 0) { winston.info("message is empty!"); fn(false); return; } //and max length if (Buffer.byteLength(msg, 'utf8') > 512) { winston.info("message is too long!"); fn(false); return; } var customer = customerList.get(cid); if (!_.isEmpty(customer)) { customer.socket.emit('cs.message', customer.csid, msg); // add message to DB; var data = {}; data.cid = cid; data.csid = customer.csid; data.msg = msg; data.type = 1; message.create(data, function(success){ if (!success) { logger.error('customer success message insert to DB error: '); logger.error(data); } }); fn(true); } else { winston.info("customer is offline;"); fn(false); } }; SocketCustomerSuccessEvents.marked = function(cid, csid, marked, fn) { if (_.isUndefined(marked)) { winston.info("marked is empty!"); fn(false); return; } chatHistory.updateMarked(cid, csid, marked, function(success) { fn(success); }); }; SocketCustomerSuccessEvents.rate = function(cid, fn) { var customer = customerList.get(cid); if (!_.isEmpty(customer)) { customer.socket.emit("cs.action.rate"); fn(true); } else { fn(false); } }; SocketCustomerSuccessEvents.offlineMessage = function(cid, csid, msg, fn) { try { logger.info("offline message to: " + cid); // add offline message to DB; var data = {}; data.cid = cid; data.csid = csid; data.msg = msg; data.type = 2; message.create(data, function(success){ if (!success) { logger.error('customer message insert to DB error '); logger.error(data); } }); } catch (err) { logger.error("send offline message error is : " + err); fn(false); } finally { } fn(true); }; SocketCustomerSuccessEvents.dispatch = function(to, cid, fn) { var customerSuccess = customerSuccessList.get(to); var customer = customerList.get(cid); if (!_.isEmpty(customerSuccess) && !_.isEmpty(customer)) { //add db dispatch message var data = {}; data.cid = cid; data.csid = customer.csid; data.msg = "dispatch from: name = " + customerSuccess.name; data.type = 3; message.create(data, function(success){ if (!success) { logger.error('dispatch message insert to DB error '); logger.error(data); } }); var userInfo = socketAdapter.reqParamsFormSocket(cid); //to server customerSuccess.socket.emit('cs.dispatch', cid, customer.name, userInfo); //to client customer.socket.emit('c.dispatch', to, customerSuccess.name, customerSuccess.photo); logger.info("dispatch customer cid = %s to customer success = %s", cid, to); customerSuccessList.userPull(customer.csid, cid); customer.csid = to; chatHistory.createOrUpdate(cid, to, function(success){ if (!success) { logger.error("chat history operation error. cid = %s and csid = %s", cid, csid); } }); customerSuccessList.userPush(to, cid); fn(true); } else { fn(false); } }; SocketCustomerSuccessEvents.changeOnOff = function(csid, stat, fn) { var customerSuccess = customerSuccessList.get(csid); if (_.isEmpty(customerSuccess)) fn(false) ; customerSuccess.status = stat; fn(true); }; // typing SocketCustomerSuccessEvents.status = function(cid, status, fn) { var customer = customerList.get(cid); if (!_.isEmpty(customer)) { fn(true); customer.socket.emit('cs.status', status); } else { fn(false); } }; SocketCustomerSuccessEvents.close = function(cid, fn) { var customer = customerList.get(cid); if (!_.isEmpty(customer)) { customer.socket.emit("cs.close.dialog"); customerSuccessList.userPull(customer.csid, cid); customerList.delete(cid); fn(true); } else { fn(false); } }; SocketCustomerSuccessEvents.logout = function(socket, csid, fn) { disconnect(csid); customerSuccessList.delete(csid); this.refreshOnlineInfo(); delete socket.request.session.csid; fn(true); }; SocketCustomerSuccessEvents.disconnect = function(csid) { logger.info("customer success = %s disconnect start!", csid); disconnect(csid); customerSuccessList.delete(csid); //customerSuccessList.get(csid).socket = {}; // set socket null; logger.info("refresh online info"); this.refreshOnlineInfo(); logger.info("customer success disconnected!"); }; function disconnect(csid) { var customerSuccess = customerSuccessList.get(csid); if (_.isEmpty(customerSuccess)) return ; var list = customerSuccess.users; if (!_.isEmpty(list)) { _.forEach(list, function (value) { var customer = customerList.get(value); if (customer) { customer.socket.emit("cs.disconnect"); } }); customerSuccess.users = []; } } module.exports = SocketCustomerSuccessEvents;