text
stringlengths
7
3.69M
$(document).ready(function(){ $('#btn1').click(function(){ alert('Hello'); }); $('#btn2').click(function(){ alert('How are you'); }); $('#btn3').click(function(){ alert('These buttons work!'); }); });
angular.module('myModule', []) .controller('firstController', function ($scope) { $scope.status = false; $scope.name = 'A'; $scope.changeStatus = function (e) { $scope.status = !$scope.status; $scope.name = $scope.name + $scope.status + ' '; // 将JS元素转为jQuery元素 angular.element(e.target).html('切换状态为:' + !$scope.status); // console.log(e); }; $scope.defaultStyle = { color: 'red', 'margin-top': '20px', 'margin-left': '100px', 'margin-bottom': '20px', // marginTop: '20px', // marginLeft: '100px', // marginBottom: '20px', }; console.log($scope.defaultStyle); $scope.src = 'https://angularjs.org/img/AngularJS-large.png'; });
/* eslint-disable no-underscore-dangle */ const Evilplan = require('../models/Evilplan'); // we need the Animal models, attached to this are all the mongoose methods to query or create things in our DB. eg Animal.find(), Animal.create() // GET - /evilplans function index(req, res) { Evilplan.find() // finds all the plans .populate('user') .populate('comments.user') .then((plans) => res.status(200).json(plans)) // if found, sends back the plans in an JSON array .catch(() => res.status(404).json({ message: 'Not Found index function' })); // if any error, sends back 404 not found message } // POST - /evilplans function create(req, res, next) { req.body.user = req.currentUser; // attaching a user key to the body, making it values currentUser from secureRoute Evilplan.create(req.body) // creates a new animal based on the JSON object sent as the body of the request .then((plan) => res.status(201).json(plan)) // if it succesfully creates, sends back that new animal .catch(next); // otherwise we send the errors } // GET - /evilplans/:id function show(req, res) { Evilplan.findById(req.params.id) .populate('user') .populate('comments.user') .then((evilplan) => { if (!evilplan) return res.status(404).json({ message: 'Not Found' }); res.status(200).json(evilplan); }) .catch(() => res.status(404).json({ message: 'Not Found ' })); } // PUT - /evilplans/:id function update(req, res, next) { Evilplan.findById(req.params.id) .then((evilplan) => { if (!evilplan) return res.sendStatus(404).json({ message: 'Not Found' }); evilplan.set(req.body); // update the properties with the data from the request // set. merges two objects together }) .then((evilplan) => evilplan.save()) // save is inbuilt) .then((evilplan) => res.status(202).json(evilplan)) .catch(next); } // Delete - /legends/:id function remove(req, res) { Evilplan // .findByIdAndRemove(req.params.id) // find and delete in one go .findById(req.params.id) .then((evilplan) => { if (!evilplan.user.equals(req.currentUser._id)) return res.status(401).json({ message: 'Not Authorised' }); return evilplan.remove(); }) .then((evilplan) => res.status(204).json(evilplan)) .catch((err) => res.status(400).json(err)); } // POST - /evilplans/:id/comments function commentCreate(req, res, next) { req.body.user = req.currentUser; Evilplan.findById(req.params.id) .then((evilplan) => { if (!evilplan) return res.status(404).json({ message: 'not found' }); evilplan.comments.push(req.body); return evilplan.save(); }) .then((evilplan) => res.status(201).json(evilplan)) .catch(next); } // PUT - evilplans/:id/comments/:commentId function commentUpdate(req, res, next) { Evilplan.findById(req.params.id) .then((evilplan) => { // find the evilplan using it's id, if you can't find it then throw 404 if (!evilplan) return res.status(404).json({ message: 'Not Found' }); // find the comment using the comment id const comment = evilplan.comments.id(req.params.commentId); // check that I'm the owner of the comment if (!comment.user.equals(req.currentUser._id)) return res.status(401).json({ message: 'Not Authorised' }); comment.set(req.body); // the .set method comes from mongoose, it merges the old object with our new information for the update evilplan.save(); return comment.save(); }) .then((evilplan) => res.status(202).json(evilplan)) // once that legend has been saved, we send it back to the client to show that is updated. .catch(next); // if anything goes wrong we send back the error response } // DELETE - evilplans/:id/comments/:commentId function commentDelete(req, res) { // console.log(req.body.user) // console.log(req.currentUser) req.body.user = req.currentUser; Evilplan.findById(req.params.id) .then((evilplan) => { if (!evilplan) return res.status(404).json({ message: 'Not found' }); const comment = evilplan.comments.id(req.params.commentId); comment.remove(); return evilplan.save(); }) .then((evilplan) => res.status(202).json(evilplan)) .catch((err) => res.status(400).json(err)); } module.exports = { index, // using es6 object shorthand, same as saying index:index create, show, update, remove, commentCreate, commentUpdate, commentDelete };
var temperatures = [100,90,99,80,70,65,30,10]; for(var i = 0; i <= temperatures.length; i++) { console.log(temperatures[i]); } // var playList = [ // 'I Did it My way', // 'Respect', // 'Imagine', // 'Born to Run', // 'Louie Louie' // ] // // function print(message) { // document.write(message); // } // // function printList(list){ // var listHTML = '<ol>'; // // for(var i = 0; i < list.length; i++){ // listHTML += '<li>' + list[i] + '</li>'; // } // listHTML += '</ol>'; // print(listHTML); // } // // printList(playList); // var playList = []; // playList.push('I did it my way'); // playList.push('Respect'); // playList.push('surf city'); // // var newList = []; // // newList = playList.unshift('Born to run'); // // printList(playList); // // console.log(newList); // // for(var i = 0; i <= playList.length; i++){ // console.log(playList[i]); // }
const express = require("express"); const router = express.Router(); const getMaxLib = require("../library/getMax"); /** * Express.js router for /getMax * * minimum maximum value of rt and m/z for this mzML file */ let getMax = router.get('/getMax', function (req, res) { console.log("Hello, getMax!"); const projectDir = req.query.projectDir; getMaxLib(projectDir, function (err, row) { res.write(JSON.stringify(row)); res.end(); }) }); module.exports = getMax;
define(function(require, exports, module) { var Engine = require('famous/core/Engine'); var AppView = require('views/AppView'); var mainContext = Engine.createContext(); mainContext.setPerspective(500); var size = [window.innerWidth+2, window.innerHeight]; var appView = new AppView(size); mainContext.add(appView); });
function Panel($target){ this.$panel =null; this.$body = null; this.$dimmed = null; this.$btnClse = null; this.init($target); this.initEvent(); } Panel.prototype.init = function($target){ this.$panel =$target; this.$dimmed = this.$panel.find('.backdrop'); this.$body = $('body'); this.$btnClse = this.$panel.find('.panel__btn-clse'); } Panel.prototype.initEvent = function(){ var objThis = this; this.$btnClse.click(function(){ var $panel = $(this).closest('.panel'); objThis.closePanel($panel); }); this.$dimmed.click(function(){ if($('.panel-share').hasClass('open')){ objThis.closePanel($('.panel-share')); }else{ objThis.closePanel($(this)); } }) } Panel.prototype.openPanel = function($panel){ var objThis = this; this.$panel.show(); setTimeout(function(){ objThis.$body.addClass('body--hidden'); },50); if($panel.hasClass('slide-top')){ setTimeout(function(){ objThis.$body.addClass('p-t-open'); },200); }else if ($panel.hasClass('panel--bottom')&&this.$body.hasClass('body--hidden')){ setTimeout(function(){ $panel.addClass('is-open'); },60); } else if($panel.hasClass('panel--bottom')){ setTimeout(function(){ $panel.addClass('is-open'); },60); } $panel.focus(); } Panel.prototype.closePanel = function($panel){ var objThis = this; if($panel.hasClass('slide-top')||$panel.hasClass('dimmed')){ //this.$dimmed.fadeOut(100); this.$body.removeClass('p-t-open'); setTimeout(function(){ setTimeout(function(){ objThis.$body.removeClass('p-open'); },50); objThis.$panel.hide(); },300); }else if($panel.hasClass('panel--bottom') && $('.ly-wrap').hasClass('open')){ $panel.removeClass('is-open'); setTimeout(function(){ objThis.$panel.hide(); },400); }else if($panel.hasClass('panel--bottom') && this.$body.hasClass('p-t-open')){ $panel.removeClass('is-open'); }else if($panel.hasClass('panel--bottom')){ $panel.removeClass('is-open'); this.$body.removeClass('p-open'); setTimeout(function(){ objThis.$panel.hide(); },400); } }
var judgeInfoModule = require('../app/judgeInfo'); var Report = require('../app/model/report').Report; function showReport(studentsInfo,studentsNo){ if(judgeInfoModule.judgeStuNo(studentsNo)){ var stuInfo = getStudentInfoByStuNo(studentsInfo,studentsNo); var report = new Report(stuInfo); report.averageOfAllStudent(); report.medianOfAllStudent(); var result = '成绩单\n姓名|数学|语文|英语|编程|平均分|总分\n========================\n'; stuInfo.forEach(function(student){ result += student.name + getSubject(student.scores, '数学') + getSubject(student.scores, '语文') + getSubject(student.scores, '英语') + getSubject(student.scores, '编程') + '|' + student.average + '|' + student.sumScore + '\n'; }); result += '========================\n全班总分平均数:' + report.averageOfAll + '\n全班总分中位数:' + report.medianOfAll; return result; } return '请按正确的格式输入要打印的学生的学号(格式: 学号, 学号,...),按回车提交:'; } function getSubject(scores, subject){ var result = '|-'; scores.forEach(function(e){ if(e.subject === subject){ result = '|' + e.score; } }); return result; } function getStudentInfoByStuNo(studentsInfo,studentsNo){ var stuInfo = []; var stuNo = studentsNo.split(', '); studentsInfo.forEach(function(e){ if(stuNo.indexOf(e.sno.trim()) >= 0){ stuInfo.push(e); } }); return stuInfo; } module.exports.showReport = showReport; module.exports.getSubject = getSubject; module.exports.getStudentInfoByStuNo = getStudentInfoByStuNo;
export default class Order { constructor(name, val) { this.name = name; this.value = val; } }
var Request={ get_users:function () { $.get('php4578/~micki/users').then(function (response) { console.log(response) }); }, get_user:function (id) { $.get('php4578/~micki/users/'+id); }, post:function (new_user) { $.post('php4578/~micki/users',new_user).then(function (response) { console.log(response); }); }, delete:function (id) { $.delete('php4578/~micki/rest/users/'+id).then(function (response) { console.log(response); }); }, bindEvent:function () { var that=this; var obj={}; $('#post').on('click',function () { $.each($('input'),function (index,value) { obj[$(value).attr('name')]=$(value).val(); }); obj=JSON.stringify(obj); console.log(obj); that.post(obj); }) } }; Request.bindEvent();
import React from 'react'; import { StyleSheet, View,Image, ImageBackground,TouchableOpacity,Alert,Platform,ScrollView } from 'react-native'; import { Container ,Header, StyleProvider,Title, Form,Left,Right,Icon,Thumbnail ,Item, Input, Label,Content,List,CheckBox,Body,ListItem,Text,Button} from 'native-base'; import AsyncStorage from '@react-native-community/async-storage'; import * as COLOR_CONSTS from '../constants/color-consts'; import * as ROUTE_CONSTS from '../constants/route-consts'; import * as APP_CONSTS from '../constants/app-consts'; import * as API_CONSTS from '../constants/api-constants'; import getTheme from '../../native-base-theme/components'; import material from '../../native-base-theme/variables/platform'; import SubmitButton from '../components/submitButton'; import Loader from '../components/loader'; import firebase from 'react-native-firebase'; export default class LoginAccessCode extends React.Component { constructor(props){ super(props); this.state = { loading:false, passwordState:true, email:"", password:"", error: false, remember: false, } //byronprice this.login = this.login.bind(this) this.forgotPassword = this.forgotPassword.bind(this) this.closeButtonTapped = this.closeButtonTapped.bind(this) this.verifyUsername = this.verifyUsername.bind(this) this.signUp = this.signUp.bind(this) } componentDidMount(){ } login(){ if(this.state.email == "" || this.state.password == "" ) { alert("All fields are required and must be valid") } else{ if(this.state.errorUsername == true) { alert("Username is not valid") } else{ this.loginAPi() } } } closeButtonTapped(){ this.props.navigation.goBack() } signUp(){ this.props.navigation.navigate(ROUTE_CONSTS.SIGNUP_INSTRUCTOR_SCREEN,{data: this.state.institute}) } loginAPi(){ var deviceType = 2 if(Platform.OS == "ios") { deviceType = 1 } var self = this; let url = API_CONSTS.API_BASE_URL+API_CONSTS.API_LOGIN_ACCESS_CODE; // alert(url) fetch(url, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ userName : this.state.email, password: this.state.password, deviceType: deviceType, deviceToken: global.notifiToken, }), }).then((response) => response.json()) .then((responseJson) => { console.log(responseJson.body) if(responseJson.code == 200){ this.setState({ user: responseJson.body, password: "" }) firebase.analytics().setUserId(""+responseJson.body.id) firebase.analytics().setUserProperty("email", ""+this.state.email) firebase.analytics().setUserProperty("role", ""+responseJson.body.role) this.storeDataInLocalStorage(responseJson.body) global.token = "Bearer " + responseJson.body.token global.role = responseJson.body.role global.id = responseJson.body.id this.props.navigation.navigate(ROUTE_CONSTS.DASHBOARD_PAGE,{user: this.state.user,isNew: responseJson.body.isNew}) }else{ alert(JSON.stringify(responseJson.message)) } }) .catch((error) => { console.error(error); }); } storeDataInLocalStorage = async (data) => { try { await AsyncStorage.setItem(APP_CONSTS.USER_ID, ""+data.id); await AsyncStorage.setItem(APP_CONSTS.LOGGEDIN_FLAG, "true"); await AsyncStorage.setItem(APP_CONSTS.TOKEN, "Bearer "+data.token); await AsyncStorage.setItem(APP_CONSTS.ROLE, ""+data.role); // await AsyncStorage.setItem(APP_CONSTS.EMAIL, this.state.email); // await AsyncStorage.setItem(APP_CONSTS.GENDER, this.state.gender); } catch (error) { // Error saving data alert(error) } } verifyUsername(){ console.log(this.state.email) var self = this; let url = API_CONSTS.API_BASE_URL+API_CONSTS.API_VERIFY_USERNAME; // alert(url) fetch(url, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ userName: this.state.email }), }).then((response) => response.json()) .then((responseJson) => { console.log(JSON.stringify(responseJson)) if(responseJson.code == 200){ this.setState({ errorUsername:false }) }else{ // alert(JSON.stringify(responseJson.message)) this.setState({ errorUsername:true }) } }) .catch((error) => { console.error(error); }); } showPassword(){ this.setState({ passwordState: !this.state.passwordState }) } forgotPassword(){ this.props.navigation.navigate(ROUTE_CONSTS.FORGOT_PASSWORD) } render() { return ( <StyleProvider style={getTheme(material)}> <Container style={styles.container}> <Loader loading={this.state.loading} /> <Header style={styles.headerStyle}> <Left> <TouchableOpacity onPress={this.closeButtonTapped} > <Image source={require('../../assets/bck.png')} style={{ width: 20, height: 20, resizeMode: 'contain' }} /> </TouchableOpacity> </Left> <Body style={{flex:3}}> <Image source={require('../../assets/logoLogin.png')} style={{ width: 80, height: 50, resizeMode: 'contain' }} /> </Body> <Right> {/* <View style={{ padding: 10, marginTop: 1, alignItems: "flex-start" }}> <TouchableOpacity onPress={this.closeButtonTapped}> <Image source={require('../../assets/cart.png')} style={{ width: 20, height: 20, resizeMode: 'contain' }} /> </TouchableOpacity> </View> */} </Right> </Header> <Content> <View style={{flex:1,marginLeft:20,marginRight:20,marginTop:30,height:APP_CONSTS.SCREEN_HEIGHT}} > <View style={{flex:1}}> {/* <ListItem avatar noBorder style={{marginTop:10}}> <Left> <Thumbnail source={{uri: this.state.institute.image}} style={{width:40,height:40}} resizeMode={'center'}/> </Left> <Body style={{justifyContent:'center',marginTop:10}}> <Text style={{fontWeight:'500',fontSize:20}}>{this.state.institute.title}</Text> </Body> <Right style={{justifyContent:'center',marginRight:10,marginTop:12}}> </Right> </ListItem> */} <View style={{marginTop:30}}> <Form> {this.state.errorUsername == false ? <Item floatingLabel style={{marginLeft:5}} success> <Label>Username</Label> <Input autoCapitalize = 'none' keyboardType={"email-address"} style={{color:COLOR_CONSTS.APP_BLACK_COLOR}} onChangeText={(email) => { this.setState({email:email}) }} onEndEditing={this.verifyUsername} value={this.state.email}/> <Icon name='checkmark-circle' /> </Item> : this.state.errorUsername == true ? <Item floatingLabel style={{marginLeft:5}} error> <Label>Username</Label> <Input autoCapitalize = 'none' keyboardType={"email-address"} style={{color:COLOR_CONSTS.APP_BLACK_COLOR}} onChangeText={(email) => { this.setState({email:email}) }} onEndEditing={this.verifyUsername} value={this.state.email}/> <Icon name='close-circle' /> </Item> : <Item floatingLabel style={{marginLeft:5}} > <Label>Username</Label> <Input autoCapitalize = 'none' keyboardType={"email-address"} style={{color:COLOR_CONSTS.APP_BLACK_COLOR}} onChangeText={(email) => { this.setState({email:email}) }} onEndEditing={this.verifyUsername} value={this.state.email}/> </Item> } <View style={{justifyContent:'flex-end',alignItems:'flex-end',marginTop:-25,marginLeft:25}}> <TouchableOpacity onPress={this.showPassword}> {/* <Image source={require('../../assets/eye.png')} style={{width: 25, height: 13}}></Image> */} </TouchableOpacity> </View> <Item floatingLabel style={{marginLeft:5,marginTop:35}}> <Label>Password</Label> <Input autoCapitalize = 'none' secureTextEntry={this.state.passwordState} style={{marginRight:30}} style={{color:COLOR_CONSTS.APP_BLACK_COLOR}} onChangeText={(password) => { this.setState({password:password}) }}/> </Item> <View style={{justifyContent:'flex-end',alignItems:'flex-end',marginTop:-25,marginLeft:APP_CONSTS.SCREEN_WIDTH - 80}}> <TouchableOpacity onPress={this.showPassword}> {/* <Image source={require('../../assets/eye.png')} style={{width: 25, height: 13}}></Image> */} </TouchableOpacity> </View> </Form> </View> <View style={{ justifyContent: 'space-between',marginTop:55, flexDirection:'row' }}> <TouchableOpacity style={{flexDirection:'row'}}> <CheckBox checked={this.state.remember} color='black' onPress={()=>this.setState({remember: !this.state.remember})}/> <Text style={{fontSize:15,color:COLOR_CONSTS.APP_BLACK_COLOR,marginLeft:20,marginTop:3}}>Remember Me</Text> </TouchableOpacity> <TouchableOpacity onPress={this.forgotPassword} style={{marginTop:3}}> <Text style={{fontSize:15,color:COLOR_CONSTS.APP_GREEN_COLOR,textDecorationLine: 'underline'}}>Forgot password?</Text> </TouchableOpacity> </View> <View style={{alignItems:"center",marginTop:50}}> {/* <SubmitButton title="Log in" buttonTapAction={this.login}/> */} <TouchableOpacity style={styles.button} onPress={this.login}> <Text style={styles.buttonText} >Sign In</Text> </TouchableOpacity> {/* <TouchableOpacity onPress={this.signUp} style={{marginTop:3}}> <Text style={{fontSize:15,color:COLOR_CONSTS.APP_GREEN_COLOR,textDecorationLine: 'underline'}}>Don't have an account? </Text> </TouchableOpacity> */} </View> </View> </View> </Content> </Container> </StyleProvider> ); } } const styles = StyleSheet.create({ container: { backgroundColor:COLOR_CONSTS.APP_OFF_WHITE_COLOR, }, headerStyle:{ backgroundColor:COLOR_CONSTS.APP_BLACK_COLOR }, title:{ color:COLOR_CONSTS.APP_WHITE_COLOR, fontSize: 16, fontWeight:'bold' }, button: { width:APP_CONSTS.SCREEN_WIDTH - 60, backgroundColor:COLOR_CONSTS.APP_GREEN_COLOR, borderRadius: 25, marginVertical: 10, paddingVertical: 7, height: 50, justifyContent:'center' }, buttonText: { fontSize:20, fontWeight:'500', color:'#fff', textAlign:'center', } });
$(document).ready(function(){ $(".slastica-img").mouseover(function(){ var width = (window.innerWidth > 0) ? window.innerWidth : screen.width; if (width > 991) { fadeInCaption($(this).attr('id')); } }); $(".slastica-img").mouseout(function(){ fadeOutCaption($(this).attr('id')); }); }); function fadeInCaption(image) { $('#slastica-' + image).stop().fadeIn(800); } function fadeOutCaption(image) { $('#slastica-' + image).stop().fadeOut(500); }
'use strict'; import request from 'supertest'; import {api} from 'freecodecamp-url-shortener'; describe('api', () => { test('I can pass a URL as a parameter and I will receive a shortened URL in the JSON response', () => request(api().enable('trust proxy')) .get('/new/http://www.google.com') .set('Host', 'example.dev') .expect(200) .expect(({body}) => { expect(body).toHaveProperty('original_url'); expect(body).toHaveProperty('short_url'); expect(body.original_url).toBe('http://www.google.com'); expect(body.short_url).toMatch(/^https?:\/\/example.dev\/\d+$/); }) ); test('If I pass an invalid URL that doesn\'t follow the valid http://www.example.com format, the JSON response will contain an error instead', () => request(api()) .get('/new/test') .expect({error: 'Invalid url'}) ); test('When I visit that shortened URL, it will redirect me to my original link', () => { const app = api(); const url = 'http://www.google.com'; return request(app) .get(`/new/${url}`) .expect(({body}) => expect(body).toHaveProperty('short_url')) .then(({body}) => body.short_url) .then(url => { // get last fragment const parts = url.split('/'); return parts[parts.length-1]; }) .then(uri => request(app) .get('/' + uri) .expect(302) .expect('Location', url) ); }); test('I receive an error on entries that are nonexistent', () => request(api()).get('/3').expect(200, {error: 'url does not exist in database'}) ); });
import React, { Component } from 'react'; class Form extends Component { constructor(){ super(); this.initialState = { name: '', type: '', }; this.state = this.initialState; } render() { const {name ,type} = this.state; return( <form className="form-group"> <div className="form-field"> <label >Name</label> <input className="form-control" type="text" name="name" value={name} onChange={this.handleChange} /> </div> <div className="form-field"> <label >Type</label> <input className="form-control" type="text" name="type" value={type} onChange={this.handleChange} /> </div> <div className="form-field"> <input type="button" value="Submit" onClick={()=>{this.submitForm()}}/> {/* ()=>{this.submitForm()} */} </div> </form> ) } submitForm = ()=>{ this.props.handleSubmit(this.state) this.setState(this.initialState) } handleChange = event => { console.log(event.target) const {name, value} = event.target console.log('[e_n]',name) console.log('[e_v]',value) this.setState({ [name]: value, }) } } export default Form
import React, {Component} from 'react'; import {Table, Button,Alert} from 'reactstrap'; import moment from 'moment'; // import 'react-datepicker/dist/react-datepicker.css' // import DatePicker from 'react-datepicker'; import PopUp from '../popup' class FutsalCourtList extends Component{ constructor(props){ super(props); this.state = { startDate: moment(), }; this.handleChangeDate = this.handleChangeDate.bind(this); } handleChangeDate(Date){ this.setState({ startDate:date }); } // let futsalGround= render(){ let day=this.props.date.format("dddd") let date=this.props.date.format("MMMM Do YYYY") console.log(this.props) return( <div className="fc-booking-table"> <Table> <thead> <tr> <th>#</th> <th>Date</th> <th>Day</th> <th>Time</th> <th>Ground</th> <th>Booking Option</th> </tr> </thead> <OptRow ground="Mates Futsal" day={day} date={date} time={this.props.time} index="1" /> <OptRow ground="Tahachal Futsal" index="2" day={day} date={date} time={this.props.time}/> <OptRow ground="Chaitya Futsal" index="3" day={day} date={date} time={this.props.time}/> <OptRow ground="Lalitpur 5A-side Futsal" index="4" day={day} date={date} time={this.props.time}/> </Table> </div> ) } } export default FutsalCourtList; class OptRow extends Component{ constructor(props){ super(props); // this.timeFunction = this.timeFunction.bind(this); } timeFunction(time){ switch(time){ case "1": return "6-7 am"; break; case "2": return "7-8 am"; break; case "3": return "8-9 am"; break; case "4": return "9-10 am"; break; case "5": return "10-11 am"; break; case "6": return "11-12 am"; break; default: return "error" } } render(){ const time=this.props.time console.log(">>>>>>>>>>>>>>>>...",typeof(time)) return( <tbody> <tr> <th scope="row">{this.props.index}</th> <td>{this.props.date}</td> <td>{this.props.day}</td> <td>{this.timeFunction(time)}</td> <td>{this.props.ground}</td> <td><PopUp/></td> </tr> </tbody> ) } }
import Ember from 'ember'; export default Ember.Component.extend({ location: Ember.inject.service(), click () { var model = this.get('model'); this.get('mixpanel').trackEvent('Get itinary'); window.location = this.get('location').getDirection(model); } });
const Post = require("../models/posts"); class HomeController { home(request, response) { Post.find({}) .populate("user") .exec(function(error, post) { if (error) { console.log("Error while fetching post"); } return response.render("home", { title: "Codeial", posts: post }); }); } createPost(request, response) { Post.create( { content: request.body.content, user: request.user._id }, function(error, new_post) { if (error) { console.log("Error in creating posts"); } console.log(new_post); return response.redirect("back"); } ); } } module.exports = HomeController;
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), browserify: { dev: { files: { 'assets/js/main.js': ['build/scripts/app.js'] }, options: { debug: true } } }, less:{ development: { options: { paths: ["assets/css"] }, files: { "assets/css/main.css": "build/styles/core.less" } } }, watch:{ watchJs: { files: ['build/**/*.js'], tasks: ['browserify:dev'] }, watchCss:{ files: ['build/**/*.less'], tasks: ['less'] } } }); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-browserify'); grunt.registerTask('default', ['watch']); };
// import { useState, useEffect } from "react"; import useStateActions from "../hooks/useStateActions"; import { Wrapper } from "../styles/RightClickMenu.styles"; import { useSpring } from "@react-spring/web"; export default function RightClickMenu() { const { rcm } = useStateActions(); // const [show, setShow] = useState(false); // useEffect(() => { // const mql = window.matchMedia("(max-width: 600px)"); // function handleMobilePhoneResize(e) { // // Check if the media query is true // setShow(e.matches); // if (e.matches) { // // Then log the following message to the console // console.log("Media Query Matched!"); // } // } // // Set up event listener // // mql.addListener(handleMobilePhoneResize); // }, []); const [x, y] = rcm.pos; const [w, h] = [window.innerWidth, window.innerHeight]; const quadrant = x > w / 2 ? (y > h / 2 ? 3 : 2) : y > h / 2 ? 4 : 1; let top, left, right, bottom; switch (quadrant) { case 1: top = y; left = x; break; case 2: top = y; right = w - x; break; case 3: bottom = h - y; right = w - x; break; case 4: bottom = h - y; left = x; break; default: console.error("invalid quadrant"); } const animate = useSpring({ opacity: rcm.isHidden ? 0 : 1, height: rcm.isHidden ? "0rem" : "20rem", }); return ( <Wrapper style={animate} id="right-click-menu" // hidden={rcm.isHidden} top={top} left={left} right={right} bottom={bottom} > {rcm.type} </Wrapper> ); }
import userApi from "../../../api/userApi"; import { useEffect, useState } from "react"; import ReactLoading from "react-loading"; import { fetchCourse } from "../../../redux/action/user"; import { useDispatch } from "react-redux"; import { useSelector } from "react-redux"; export default function YourCourse() { const dispatch = useDispatch(); const { course } = useSelector((state) => state.user); useEffect(() => { dispatch(fetchCourse()); }, []); if (!course) return <ReactLoading type="cylon" color="#00afab" height={30} width={55} />; return ( <div className="tab2"> {course?.map((e, i) => ( <Course key={i} img_course={e.course.thumbnail?.link} name={e.course.title} date={e.course.opening_time} NoVideo={e.course.count_video} time="20 hours" students="30 học viên" rating="40" /> ))} </div> ); } function Course({ img_course, name, date, time, NoVideo, students, rating }) { return ( <div className="item"> <div className="cover"> <img src={img_course} alt="" /> </div> <div className="info"> <a href="#" className="name"> {name} </a> <div className="date">{date}</div> <div className="row"> <div className> <img src="img/clock.svg" alt="" className="icon" /> {time} </div> <div className> <img src="img/play.svg" alt="" className="icon" /> {NoVideo} </div> <div className> <img src="img/user.svg" alt="" className="icon" /> {students} </div> </div> <div className="process"> <div className="line"> <div className="rate" style={{ width: { rating } }} /> </div> {rating}% </div> <div className="btn overlay round btn-continue">Tiếp tục học</div> </div> </div> ); }
//adds my chrome to context menu chrome.contextMenus.create({ "title": "Look up and save!", "id": "save_me", "contexts": ["all"] }); //sends out message "SaveMe" when my extension is clicked in context menu chrome.contextMenus.onClicked.addListener(function (info, tab) { if (info.menuItemId == "save_me") { chrome.tabs.query({active: true, currentWindow: true}, function (tabs) { chrome.tabs.sendMessage(tabs[0].id, {"message": "save_me"}); }); } }); chrome.browserAction.setPopup({ popup: "popup.html" })
export default { 'position': 'sticky', };
import React, { Component } from 'react'; import '../style/form.css'; import MiniClipsBox from './MiniClipsBox.jsx'; class SearchForm extends Component { constructor(props) { super(props); this.state = { searchTerms: [], clips: [] }; } updateSearch = (event) => this.setState( { searchTerms: event.target.value.split(',').map(s => s.trim()) }, () => fetch("/api/search/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(this.state.searchTerms) }).then(response => response.ok ? response.json().then( clips => this.setState({ clips: clips }) ) : () => console.log("failed search")) ); render() { return ( <div className="search-form section"> <form onSubmit={e => e.preventDefault()}> <input className="field input" placeholder="Tag1, Tag2, Tag3, ..." type="search" name="search" value={this.state.searchTerms.join(',')} onChange={this.updateSearch} /> </form> <MiniClipsBox clips={this.state.clips} onIncludeClip={this.props.onIncludeClip} /> </div> ); } } export default SearchForm;
import React from 'react'; import PropTypes from 'prop-types'; const ItemList = ({ item, removeItem }) => ( <li> <span>{item.text}</span> <button className="btn-close" onClick={() => removeItem(item)}>X</button> </li> ); ItemList.propTypes = { item: PropTypes.object.isRequired, removeItem: PropTypes.func.isRequired }; export default ItemList;
/** * 定义数据库实体 */ import mongoose from 'mongoose' let Schema = mongoose.Schema let authorSchema = Schema({ _id: String, name: String, age: Number, stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }] }) let storySchema = Schema({ _creator: { type: String, ref: 'Author' }, title: String, fans: [{ type: String, ref: 'Author' }] }) let Story = mongoose.model('Story', storySchema, 'story') let Author = mongoose.model('Author', authorSchema, 'author') export { Story, Author }
'use strict'; //Enumerados: PlayerState son los estado por los que pasa el player. Directions son las direcciones a las que se puede //mover el player. var map; var cursors; var disparanding; var jumptimer = 0; //GameObjects var winZone; var propulsion1; var propulsion2; var finalZone; var finalZone2; var platforms; var bullets; var nubes; var slimes; //textos var textStart; //Pausa var pKey; var back; //backGround var buttonMenu; var buttonReanudar; var texto; var texto2; //Audio var musica; var salto; //Scena de juego. var PlayScene = { menu: {}, _rush: {}, //player torreta: {}, nube: {}, nube2: {}, nube3: {}, //Método constructor... create: function () { nubes = this.game.add.group(); nubes.enableBody = true; platforms = this.game.add.group(); platforms.enableBody = true; this.CreaPlataforma(2400, 385, 0.8); this.CreaPlataforma(1030, 330, 1.4); this.CreaPlataforma(1550, 1285, 1.4); platforms.alpha = 0; ///BOTONES////////////////////////////////// buttonMenu = this.game.add.button(400, 450, 'button', this.volverMenu, this, 2, 1, 0); buttonMenu.anchor.set(0.5); texto = this.game.add.text(0, 0, "Return Menu"); texto.anchor.set(0.5); buttonMenu.addChild(texto); buttonReanudar = this.game.add.button(400, 450, 'button', this.Reanudar, this, 2, 1, 0); buttonReanudar.anchor.set(0.5); texto2 = this.game.add.text(0, 0, "Resume"); texto2.anchor.set(0.5); buttonReanudar.addChild(texto2); this.map = this.game.add.tilemap('tilemap'); this.map.addTilesetImage('tileset', 'tiles'); //Objetos del mapa creados con Tiled var start = this.map.objects["Objects"][0]; var end = this.map.objects["Objects"][1]; var slimePos = this.map.objects["Objects"][2]; var slimePos2 = this.map.objects["Objects"][3]; var slimePos3 = this.map.objects["Objects"][4]; var setaPos1 = this.map.objects["Objects"][5]; var setaPos2 = this.map.objects["Objects"][6]; var finalPos = this.map.objects["Objects"][7]; var finalPos2 = this.map.objects["Objects"][8]; //NUBES this.nube = this.game.add.sprite(400, slimePos.y, 'clouds'); this.game.physics.arcade.enable(this.nube); this.nube.body.velocity.x = -30; this.nube2 = this.game.add.sprite(1200, start.y-100, 'clouds'); this.game.physics.arcade.enable(this.nube2); this.nube2.body.velocity.x = -30; this.nube3 = this.game.add.sprite(2000, setaPos1.y-100, 'clouds'); this.game.physics.arcade.enable(this.nube3); this.nube3.body.velocity.x = -30; //LAYERS this.backgroundLayer = this.map.createLayer('Capa Fondo'); this.water = this.map.createLayer('Agua'); this.death = this.map.createLayer('death'); //plano de muerte this.decorado = this.map.createLayer('Capa Atravesable'); //Inicializacion de la torreta. this.torreta = this.game.add.sprite(1450, 580, 'torreta'); disparanding = this.torreta.animations.add('stand', [0, 1, 2, 3], 2, true); //Llama al método Dispara en cada vuelta del loop de la animación. disparanding.onLoop.add(this.Dispara, {velX: -120, velY: 40, posX: this.torreta.x -10, posY: this.torreta.y, game: this.game }, this); this.groundLayer = this.map.createLayer('Capa Terreno'); //Redimension this.groundLayer.resizeWorld(); //resize world and adjust to the screen this.backgroundLayer.resizeWorld(); this.death.resizeWorld(); this.decorado.resizeWorld(); this.water.resizeWorld(); //Texto de tutorial this.textStart = this.game.add.text(50, 450, "Bienvenido!, recuerda que" + "\n" + "puedes saltar diferente distancia" + "\n" + "dependiendo de cuanto pulses el botón de salto."); //Elementos de menu de pausa back = this.game.add.sprite(this.game.camera.x, this.game.camera.y, 'back'); back.visible = false; //Personaje this._rush = this.game.add.sprite(start.x, start.y, 'dude');//(start.x, start.y, 'dude'); this._rush.scale.setTo(1.2, 1.2); //animaciones this._rush.animations.add('left', [0, 1, 2, 3], 10, true); this._rush.animations.add('right', [5, 6, 7, 8], 10, true); //Colisiones con el plano de muerte y con el plano de muerte y con suelo. this.map.setCollisionBetween(1, 5000, true, 'death'); this.map.setCollisionBetween(1, 5000, true, 'Capa Terreno'); this.death.visible = false; //Zona de Final del nivel this.winZone = new Phaser.Rectangle(end.x, end.y, end.width, end.height); //Zonas de impulso this.propulsion1 = new Phaser.Rectangle(setaPos1.x, setaPos1.y, setaPos1.width, setaPos1.height); this.propulsion2 = new Phaser.Rectangle(setaPos2.x, setaPos2.y, setaPos2.width, setaPos2.height); //Zonas colision nubes this.finalZone = new Phaser.Rectangle(finalPos.x, finalPos.y, finalPos.width, finalPos.height); this.finalZone2 = new Phaser.Rectangle(finalPos2.x, finalPos2.y, finalPos2.width, finalPos2.height); //tecla de Pausa this.pKey = this.input.keyboard.addKey(Phaser.Keyboard.P); this.pKey.onDown.add(this.togglePause, this); this.configure(); //Inicialización de los slimes slimes = this.game.add.group(); this.CreaSlime(slimePos.x, slimePos.y, this.game); this.CreaSlime(slimePos2.x, slimePos2.y, this.game); this.CreaSlime(slimePos3.x, slimePos3.y, this.game); //Añadido del grupo balas. bullets = this.game.add.group(); bullets.enableBody = true; }, //IS called one per frame. update: function () { //Ocultar la interfaz del menu de pausa if (!this.game.physics.arcade.isPaused){ buttonMenu.visible = false; buttonReanudar.visible = false; back.visible = false; } this.torreta.animations.play('stand'); //Colisión entre el jugador y el terreno. var hitPlatforms = this.game.physics.arcade.collide(this._rush, this.groundLayer); //Llama al método matas o mueres al colisionar con el slime. this.game.physics.arcade.collide(this._rush, slimes, this.MatasOMueres, null, this); //Mata al personaje al tocar una bala. this.game.physics.arcade.collide(this._rush, bullets, this.onPlayerFell, null, this); this.game.physics.arcade.collide(bullets, this.groundLayer, this.MataBala, null, this); this.cursors = this.game.input.keyboard.createCursorKeys(); // Reset the players velocity (movement) this._rush.body.velocity.x = 0; if (this.cursors.left.isDown) { // Move to the left this._rush.body.velocity.x = -150; this._rush.animations.play('left'); } else if (this.cursors.right.isDown) { // Move to the right this._rush.body.velocity.x = 150; this._rush.animations.play('right'); } else { // Stand still this._rush.animations.stop(); this._rush.frame = 4; } if (this.cursors.up.isDown && hitPlatforms && this._rush.body.onFloor()) { //Como el jugador esta en el suelo se le permite saltar. salto.play(false); this.jumptimer = this.game.time.time; this._rush.body.velocity.y = -325; } else if (this.cursors.up.isDown && (this.jumptimer !== 0)) { //El jugador no esta en tierra pero sigue pulsando el botón de salto. if ((this.game.time.time - this.jumptimer) > 600) { //El jugador ya ha recibido más impulso de salto por más de 0'6 segundos que es el máximo que le he puesto. this.jumptimer = 0; } else { // Todavía no ha llegado a los 0'6 segundos así que puede saltar más. this._rush.body.velocity.y = -325-(200/(this.game.time.time - this.jumptimer));//200 partido del tiempo porque hasta 525 era lo máximo que se quería que saltase. } } else if (this.jumptimer !== 0) { //Resetea el contador del tiempo para que el jugador pueda volver a saltar. this.jumptimer = 0; } this.checkPlayerFell(); //Para terminar el nivel: if(this.winZone.contains(this._rush.x + this._rush.width/2, this._rush.y + this._rush.height/2)){ musica.destroy(); this.game.state.start('gravityScene'); //Cargamos siguiente nivel } //Zonas de propulsion if(this.propulsion1.contains(this._rush.x + this._rush.width/2, this._rush.y + this._rush.height/2)){ //this._rush.body.velocity.y = -1200; //(por implementar) //this._rush.body.velocity.x = 500; } if(this.finalZone.contains(this.nube.x + this.nube.width/2, this.nube.y + this.nube.height/2)){ this.nube.x = this.finalZone2.x; } //Hace que el slime recorra la plataforma en la que esté y gire antes de caerse para seguir recorriéndola indefinidamente. this.game.physics.arcade.collide(slimes, platforms, function (slime, platform) { if (slime.body.velocity.x > 0 && slime.x > platform.x + (platform.width - (slime.width + 5)) || slime.body.velocity.x < 0 && slime.x < platform.x) { slime.body.velocity.x *= -1; } slime.body.velocity.y = -80; }); }, //Función que se llama al tocar al slime. Si le tocas por los lados mueres y si saltas encima le matas. MatasOMueres: function(player, slime){ if (this._rush.body.touching.left || this._rush.body.touching.right){ this.game.state.start('gameOver'); } else if (this._rush.body.touching.down){ slime.kill(); } }, MataBala: function(bala, suelo) { bala.kill(); }, //Constructora de la bala Dispara: function (velX, velY, posX, posY, game){ var bullet = this.game.add.sprite(this.posX, this.posY, 'bullet'); this.game.physics.arcade.enable(bullet); bullet.body.bounce.y = 0.2; bullet.body.velocity.y = this.velY; bullet.body.velocity.x = this.velX; bullets.add(bullet); }, CreaSlime: function(x, y, game){ var slime = this.game.add.sprite(x, y, 'slime');//1-(400,215)//2-(650,120)//3-(1200,520)//4-(150,520)//5-(1250,920)//6-(1375,1000) this.game.physics.arcade.enable(slime); slime.body.bounce.y = 0.2; slime.body.gravity.y = 300; slime.body.velocity.x = 80; slime.body.collideWorldBounds = true; slime.animations.add('princi', [0, 1, 2, 3, 4], 5, true); slime.animations.play('princi'); slimes.add(slime); }, CreaPlataforma: function (x, y, scaleX){ var ledge = platforms.create(x, y, 'ground'); ledge.body.immovable = true; ledge.scale.setTo(scaleX, 0.5); platforms.add(ledge); }, togglePause: function(){ buttonMenu.destroy(); buttonReanudar.destroy(); back.visible = false; back = this.game.add.sprite(this.game.camera.x, this.game.camera.y, 'back'); back.visible = true; //Boton 1 buttonMenu = this.game.add.button(this.game.camera.x+400, this.game.camera.y+350, 'button', this.volverMenu, this, 2, 1, 0); buttonMenu.anchor.set(0.5); texto = this.game.add.text(0, 0, "Return Menu"); texto.anchor.set(0.5); buttonMenu.addChild(texto); buttonMenu.visible = true; //Boton 2 buttonReanudar = this.game.add.button(this.game.camera.x+400, this.game.camera.y+250, 'button', this.Reanudar, this, 2, 1, 0); buttonReanudar.anchor.set(0.5); texto2 = this.game.add.text(0, 0, "Resume"); texto2.anchor.set(0.5); buttonReanudar.addChild(texto2); buttonReanudar.visible = true; this.game.physics.arcade.isPaused = (this.game.physics.arcade.isPaused) ? false : true; }, volverMenu: function (){ musica.destroy(); //this.game.state.start('gravityScene'); this.game.state.start('menu'); }, Reanudar: function(){ this.game.physics.arcade.isPaused = (this.game.physics.arcade.isPaused) ? false : true; }, onPlayerFell: function(){ //TODO 6 Carga de 'gameOver'; musica.destroy(); this.game.state.start('gameOver'); }, checkPlayerFell: function(){ if(this.game.physics.arcade.collide(this._rush, this.death)) this.onPlayerFell(); }, //configure the scene configure: function(){ //Start the Arcade Physics systems this.game.world.setBounds(0, 0, 3200, 1600);      this.game.physics.startSystem(Phaser.Physics.ARCADE); this.game.stage.backgroundColor = '#a9f0ff'; this.game.physics.arcade.enable(this._rush); this.game.currentlevel = 1; musica = this.game.add.audio('musicaN1'); musica.loop = true; musica.play(); salto = this.game.add.audio('salto'); this._rush.body.bounce.y = 0.2; this._rush.body.gravity.y = 750; this._rush.body.collideWorldBounds = true; this._rush.body.gravity.x = 0; this._rush.body.velocity.x = 0; this.game.camera.follow(this._rush); }, //move the player movement: function(point, xMin, xMax){ this._rush.body.velocity = point;// * this.game.time.elapseTime; if((this._rush.x < xMin && point.x < 0)|| (this._rush.x > xMax && point.x > 0)) this._rush.body.velocity.x = 0; }, }; module.exports = PlayScene; /* if (this.cursors.up.isDown && hitPlatforms && this._rush.body.onFloor()) { //player is on the ground, so he is allowed to start a jump this.jumptimer = this.game.time.time; this._rush.body.velocity.y = -1000; } else if (this.cursors.up.isDown && (this.jumptimer !== 0)) { //player is no longer on the ground, but is still holding the jump key if ((this.game.time.time - this.jumptimer) > 325) { // player has been holding jump for over 600 millliseconds, it's time to stop him this.jumptimer = 0; } else { // player is allowed to jump higher, not yet 600 milliseconds of jumping //this._rush.body.velocity.y -= 15;//525 this._rush.body.velocity.y = -400-(120/(this.game.time.time - this.jumptimer)); } } else if (this.jumptimer !== 0) { //reset jumptimer since the player is no longer holding the jump key this.jumptimer = 0; } */
import moment from 'moment' import React from 'react' import Currency from 'react-currency-formatter' function Order({id,amount,amountShipping,items,timestamp,images}) { return ( <div className='relative border rounded-md'> <div className='flex items-center space-x-10 bg-gray-100 text-gray-600 p-5 text-sm'> <div> <p className="font-bold text-xs">ORDER PLACED</p> <p>{moment.unix(timestamp).format('MMM DD YYYY')}</p> </div> <div> <p className="font-bold text-xs">TOTAL</p> <p> <Currency quantity={amount} currency="CAD"/> - Next Day Delivery @ <Currency quantity={amountShipping} currency="CAD" /> </p> </div> <p className="text-sm whitespace-nowrap sm:text-lg self-end flex-1 text-right text-blue-500">{items.length} item(s)</p> <p className="absolute top-2 right-2 w-40 lg:w-72 truncate text-xs whitespace-nowrap"> ORDER# {id}</p> </div> <div className="p-5 sm:p-10"> <div className="flex space-x-6 overflow-x-auto"> {images.map(image=>( <img src={image} alt="" className="h-20 object-contain sm:h-32"/> ))} </div> </div> </div> ) } export default Order
// 教程 1 - simple-action-creator.js //我们在上一篇的介绍中讨论了一点actions,但是呢问题来了,“action creators”(action 创造器)究竟是什么东西呢,他是怎样和 action 发生联系的呢 // 他其实非常简单下面几行代码就能解释 // 这个 “action creators” 其实就是一个 function var actionCreator = function() { // 创建一个 action 并将其 return return { type: 'AN_ACTION' } } //这就完了吗??当然咯 //然而,需要注意的这个action的格式。action其实是一个含有一个名为"type"的属性的对象(object), //这样写是flux的一种惯例。 //这个“type”可以让你进一步的操作action,当然,你也可以通过action的属性传递其他你想要传递的数据 //我们稍后还会发现 ,这个action creator 也可以return其他别的东西(比如说return 一个 function)而不是一个action, //这样做对处理异步action是及其有用的(关于异步action的更多详情在dispatch-async-action.js) // 就象我们预料的那样,我们可以执行这个action creator 然后得到 action console.log(actionCreator()) // Output: { type: 'AN_ACTION' } // 好,他运行起来了。。但是这啥也做不了,然而并没有卵用 // 我们需要的是 这个action 能够发送到一个地方,这样的话能够让对他感兴趣的东东知道发生了什么,并让这些东东们做出相应的反应 // 我们称这个过程为 "Dispatching an action" (发出一个action) // 为了能够 "Dispatching an action" (发出一个action) 我们需要一个 dispatch function ("这不是废话嘛"). //另外为了够让对他感兴趣的东东知道发生了什么,我们需要一种机制能够让这些东东注册,这样这个东东就成为了 //这个action的订阅者(action 一旦dispatch,订阅者就能知道 ) // 好,截至目前为止我们已经有这样的数据流了 // ActionCreator -> Action // 想要了解更多有关create action请看下面 // http://rackt.org/redux/docs/recipes/ReducingBoilerplate.html // 转到下一个教程: 02_simple-subscriber.js
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Navbar from './components/Navbar'; import MeetupInfo from './components/MeetupInfo'; import NextMeetups from './components/NextMeetups'; const data = { meetupInfo:{ name: 'JakartJS', photoURL:'', location:'Jakarta', about:'This is meetup for javascript ninjas.' }, members:[ {name:'adib',email:'adib@gmail.com'}, {name:'budi',email:'budi@gmail.com'}, {name:'wati',email:'wati@gmail.com'}, ], organizers:[ {name:'adib',email:'adib@gmail.com'}, {name:'budi',email:'budi@gmail.com'} ], meetups:[ { title:'JakartaJS Workshop', desc:'Workshop FronEnd and BackEnd', status:'next', date: new Date(), location: 'Hactive8' }, { title:'JakartaJS Meetup', desc:'Meetup with Kudo', status:'next', date: new Date(), location: 'Kudo radio dalam' } ] } class App extends Component { constructor(props){ super(props); this.state = data this.handleAddMeetup = this.handleAddMeetup.bind(this) } handleAddMeetup(){ this.setState({meetups: this.state.meetups.concat({title:'New meetup was here'})}) } render() { return ( <div> <Navbar/> <MeetupInfo info ={this.state.meetupInfo}/> <NextMeetups meetups={this.state.meetups} addMeetup={this.handleAddMeetup}/> </div> ); } } export default App;
import React, { useState, useEffect } from 'react'; import ProductItem from './PokemonItem'; import './App.css'; import Loading from './Loading/Loading'; function getPokemon({ url }) { return new Promise((resolve, reject) => { fetch(url).then(res => res.json()) .then(data => { resolve(data) }) }); } async function getAllPokemon(url) { return new Promise((resolve, reject) => { fetch(url).then(res => res.json()) .then(data => { resolve(data) }) }); } function App() { const [pokemonData, setPokemonData] = useState([]) const [nextUrl, setNextUrl] = useState(); const [prevUrl, setPrevUrl] = useState(); const [loading, setLoading] = useState(true); const initialURL = 'https://pokeapi.co/api/v2/pokemon' useEffect(() => { async function fetchData() { let response = await getAllPokemon(initialURL) setNextUrl(response.next); setPrevUrl(response.previous); await loadPokemon(response.results); setLoading(false); } fetchData(); }, []) const getnexturl = async () => { setLoading(true); let data = await getAllPokemon(nextUrl); await loadPokemon(data.results); setNextUrl(data.next); setPrevUrl(data.previous); setLoading(false); } const getprevurl = async () => { if (!prevUrl) return; setLoading(true); let data = await getAllPokemon(prevUrl); await loadPokemon(data.results); setNextUrl(data.next); setPrevUrl(data.previous); setLoading(false); } const loadPokemon = async (data) => { let _pokemonData = await Promise.all(data.map(async pokemon => { let pokemonRecord = await getPokemon(pokemon) return pokemonRecord })) setPokemonData(_pokemonData); } return ( <> <div> {loading ? <Loading/> : ( <> <div class="header"> <h1>Pokemon Types</h1> <button onClick={getprevurl}>Prev</button> <button onClick={getnexturl}>Next</button> </div> <div className="grid-container"> {pokemonData.map((pokemon, i) => { return <ProductItem key={i} pokemon={pokemon} /> })} </div> </> )} </div> </> ); } export default App;
const daysDisplay = document.getElementById('days'); const hoursDisplay = document.getElementById('hours'); const minDisplay = document.getElementById('min'); const secDisplay = document.getElementById('sec'); const button = document.getElementById('btn'); const container = document.getElementById('countdown'); function countdown() { const newYears = document.getElementById('dateSelected').value; const newYearsDate = new Date(newYears); const currentDate = new Date(); const totalSeconds = (newYearsDate - currentDate) / 1000; if(totalSeconds < 0){ alert ('Wrong date selected'); } else { const days = Math.floor(totalSeconds / 3600 / 24); const hours = Math.floor(totalSeconds / 3600) % 24; const minutes = Math.floor(totalSeconds / 60) % 60; const seconds = Math.floor(totalSeconds) % 60; daysDisplay.innerHTML = days; hoursDisplay.innerHTML = hours; minDisplay.innerHTML = formatTime(minutes); secDisplay.innerHTML = formatTime(seconds); button.style.visibility = 'hidden'; container.style.visibility = 'visible'; setInterval(countdown, 1000); } } function formatTime(time) { return time < 10 ? `0${time}` : time; }
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const AbrirCajaScheme = Schema({ Restaurante: String, monto: String }); module.exports = mongoose.model("aperturaCaja", AbrirCajaScheme);
import React, { Component } from 'react'; class Counter extends Component { constructor(props) { super(props) this.state = { count: 0 } } increment() { // its async, so down there is executed before increment // if we want if after, make the callback function // this.setState({ // count: this.state.count + 1, // }, () => { // console.log('inside setState ', this.state.count); // }); // console.log('down there ', this.state.count); // this is based on previous state, check the commented code output this.setState((prevState, props) => ({ count: prevState.count + 1, })); } incrementFive() { this.increment(); this.increment(); this.increment(); this.increment(); this.increment(); } render() { return ( <div> Count - { this.state.count } <button onClick={ () => this.incrementFive() }> Increment </button> </div> ); } } export default Counter;
var app = angular.module('pricing'); app.controller('ModalCtrl', [ '$scope', '$rootScope', '$element', '$http', 'title', 'close', 'tickerID', 'tickerPrice', function($scope, $rootScope, $element, $http, title, close, tickerID, tickerPrice) { $scope.title = title; $scope.tickerID = tickerID; $scope.tickerPrice = tickerPrice; $scope.data = {}; /* Handle the form submit from orderModal.html While compiling the Form angular created the 'order' object which converts the form data to JSON automatically, so return this to the caller */ $scope.handleOpenOrderFormSubmit = function() { var orderData = this.data; var fullOrder = angular.extend({}, { 'ticker': tickerID, 'price': tickerPrice, 'orderType': this.orderType, 'orderDate': new Date() }, orderData); /* post to server*/ if (this.orderType == "Market") { $http.post('/orders/addorder', fullOrder); } else { $http.post('/orders/addpendingorder', fullOrder); } // Manually hide the modal. $element.modal('hide'); //This function is called after the Submit button is clicked and the Modal is about to close. //Here is the opportunity to return values to the calling function close({ order: fullOrder }, 500); // close, but give 500ms for bootstrap to animate }; //Calculated field to hold the total order price $scope.totalOrderPrice = function() { if ($scope.data.currencyAmountToBuy && $scope.tickerPrice) { return $scope.data.currencyAmountToBuy * $scope.tickerPrice; } else { return 0; } }; // This cancel function must use the bootstrap, 'modal' function because // the button doesn't have the 'data-dismiss' attribute. $scope.cancel = function() { // Manually hide the modal. $element.modal('hide'); }; } ]);
import Box from '../Box' import Flex from '../Flex' import { cleanChildren, forwardProps } from '../utils' import Icon from '../Icon' import Text from '../Text' /** * Stat Arrow options */ const arrowOptions = { increase: { name: 'triangle-up', color: 'green.400' }, decrease: { name: 'triangle-down', color: 'red.400' } } /** * Stat component */ const Stat = { name: 'Stat', extends: Box, render (h) { const children = cleanChildren(this.$slots.default) return h(Box, { props: { flex: 1, pr: 4, position: 'relative', ...forwardProps(this.$props) } }, children) } } /** * StatGroup component */ const StatGroup = { name: 'StatGroup', extends: Flex, render (h) { const children = cleanChildren(this.$slots.default) return h(Flex, { props: { flexWrap: 'wrap', justifyContent: 'space-around', alignItems: 'flex-start', ...forwardProps(this.$props) } }, children) } } const StatArrow = { name: 'StatArrow', extends: Icon, props: { type: { type: String, default: 'increase' } }, render (h) { return h(Icon, { props: { mr: 1, size: '14px', verticalAlign: 'middle', ...arrowOptions[this.type], ...forwardProps(this.$props) } }) } } /** * StatNumber compoennt */ const StatNumber = { name: 'StatNumber', extends: Text, render (h) { return h(Text, { props: { fontSize: '2xl', verticalAlign: 'baseline', fontWeight: 'semibold', ...forwardProps(this.$props) } }, this.$slots.default) } } /** * StatHelperText component */ const StatHelperText = { name: 'StatHelperText', extends: Text, render (h) { return h(Text, { props: { fontSize: 'sm', opacity: 0.8, mb: 2, ...forwardProps(this.$props) } }, this.$slots.default) } } /** * StatLabel component */ const StatLabel = { name: 'StatLabel', extends: Text, render (h) { return h(Text, { props: { fontWeight: 'medium', fontSize: 'sm', ...forwardProps(this.$props) } }, this.$slots.default) } } export { Stat, StatGroup, StatArrow, StatNumber, StatHelperText, StatLabel }
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const express = require("express"); const AuthorizationHelper_1 = require("../helpers/AuthorizationHelper"); class Authenticator { constructor() { this.app = express(); this.app.use((req, res, next) => __awaiter(this, void 0, void 0, function* () { try { let userAuth; let token = req.headers['authorization']; if (token && token.length === 128) { userAuth = yield AuthorizationHelper_1.default.userService.getByToken(token).catch(error => { console.log('Authenticator.middleware\n', error); return Promise.resolve(null); }); } req[Authenticator.userKey] = userAuth || null; } catch (err) { console.error(err.message); } next(); })); } getConfig() { return this.app; } static accessDenied(res) { res.status(403); res.send({ error: { message: 'Access denied!' } }); } static setTimeoutRequestAPI() { Authenticator.timeOut = 0; let countTimeOut = setInterval(() => { Authenticator.timeOut = Authenticator.timeOut + 1; if (Authenticator.timeOut === 10) { clearInterval(countTimeOut); } }, 1000); } static isAuthenticated(req, res, next) { return __awaiter(this, void 0, void 0, function* () { if (req[Authenticator.userKey]) { let targetUser = yield AuthorizationHelper_1.default.userService.get(req[Authenticator.userKey]._id).catch(error => { return Promise.resolve(null); }); let dateNowMilisec = new Date().getTime(); let userLastAccessMilisec = targetUser && targetUser.lastAccess ? new Date(targetUser.lastAccess).getTime() : new Date().getTime(); if (dateNowMilisec - userLastAccessMilisec >= 60000) { yield AuthorizationHelper_1.default.userService.updateLastAccessUser(req[Authenticator.userKey]._id).catch(error => { console.log('Authenticator last access\n', error); }); } next(); } else { res.status(401); res.send({ error: { message: 'Unauthorized' } }); } }); } static authenticate(productCode, email, password) { return __awaiter(this, void 0, void 0, function* () { if (productCode && email && password) { let data = { productCode, email, password }; return yield AuthorizationHelper_1.default.post(`/api/user/authenticate`, data).catch(error => { console.log('Authenticator.authenticate\n', error); return Promise.resolve(null); }); } return null; }); } static removeAuthenticator(userId) { return __awaiter(this, void 0, void 0, function* () { if (!userId) return false; return yield AuthorizationHelper_1.default.delete(`/api/user/${userId}`).catch(error => { console.log('Authenticator.removeAuthenticator\n', error); return Promise.resolve(false); }); }); } static checkPermission(claimCode, productCode, fromRoleCode, targetId) { return __awaiter(this, void 0, void 0, function* () { let toRole; if (targetId) { let targetUser = yield AuthorizationHelper_1.default.userService.get(targetId).catch(error => { console.log('Authenticator.checkPermission\n', error); return Promise.resolve(null); }); if (!targetUser) return false; toRole = targetUser.permission && targetUser.permission.role; if (!toRole || !toRole.code) return false; } let data = { product: productCode, claim: claimCode, fromRole: fromRoleCode, }; if (toRole) data.toRole = toRole.code === fromRoleCode ? null : toRole.code; return yield AuthorizationHelper_1.default.post(`/api/permission/check-permission`, data).catch(error => { console.log('Authenticator.checkPermission\n', error); return Promise.resolve(false); }); }); } static filterProductCodesPermission(claimCodes, fromRoleCodes, toRoleCodes) { return __awaiter(this, void 0, void 0, function* () { if (!claimCodes || !claimCodes.length || !fromRoleCodes || !fromRoleCodes.length) return []; return yield AuthorizationHelper_1.default.get(`/api/permission/product-codes-permission?claimCodes=${claimCodes.join(',')}&fromRoleCodes=${fromRoleCodes.join(',')}&toRoleCodes=${toRoleCodes ? toRoleCodes.join(',') : ''}`).catch(error => { console.log('Authenticator.filterProductCodesPermission\n', error); return Promise.resolve([]); }); }); } static filterRoleCodesPermission(claimCodes, productCodes, fromRoleCodes) { return __awaiter(this, void 0, void 0, function* () { if (!claimCodes || !claimCodes.length || !productCodes || !productCodes.length || !fromRoleCodes || !fromRoleCodes.length) return []; return yield AuthorizationHelper_1.default.get(`/api/permission/role-codes-permission?claimCodes=${claimCodes.join(',')}&productCodes=${productCodes.join(',')}&fromRoleCodes=${fromRoleCodes.join(',')}`).catch(error => { console.log('Authenticator.filterRoleCodesPermission\n', error); return Promise.resolve([]); }); }); } static filterProductsPermission(claimCodes, originId, productCodes, toRoleCodes) { return __awaiter(this, void 0, void 0, function* () { if (!claimCodes || !claimCodes.length || !originId) return []; let originUser = yield AuthorizationHelper_1.default.userService.get(originId).catch(error => { console.log('Authenticator.filterProductsPermission.1\n', error); return Promise.resolve(null); }); if (!originUser) return []; let fromRole = originUser.permission && originUser.permission.role; if (!fromRole || !fromRole.code) return []; let productCodesPermission = yield Authenticator.filterProductCodesPermission(claimCodes, [fromRole.code], toRoleCodes); if (productCodes && productCodes.length) productCodesPermission = productCodesPermission.filter(productCode => productCodes.find(code => code === productCode)); if (!productCodesPermission || !productCodesPermission.length) return []; return yield AuthorizationHelper_1.default.get(`/api/product/codes?codes=${productCodesPermission.join(',')}`).catch(error => { console.log('Authenticator.filterProductsPermission.2\n', error); return Promise.resolve([]); }); }); } static filterPermission(claimCodes, originId, productCodes, toRoleCodes) { return __awaiter(this, void 0, void 0, function* () { let result = { products: [], roles: [] }; if (!claimCodes || !claimCodes.length || !originId) return result; let originUser = yield AuthorizationHelper_1.default.userService.get(originId).catch(error => { console.log('Authenticator.filterPermission.1\n', error); return Promise.resolve(null); }); ; if (!originUser) return result; let fromRole = originUser.permission && originUser.permission.role; if (!fromRole || !fromRole.code) return result; let productCodesPermission = yield Authenticator.filterProductCodesPermission(claimCodes, [fromRole.code], toRoleCodes); if (productCodes && productCodes.length) productCodesPermission = productCodesPermission.filter(productCode => productCodes.find(code => code === productCode)); if (!productCodesPermission || !productCodesPermission.length) return result; let roleCodesPermission = yield Authenticator.filterRoleCodesPermission(claimCodes, productCodesPermission, [fromRole.code]); if (toRoleCodes && toRoleCodes.length) roleCodesPermission = roleCodesPermission.filter(roleCode => toRoleCodes.find(code => code === roleCode)); result.products = yield AuthorizationHelper_1.default.get(`/api/product/codes?codes=${productCodesPermission.join(',')}`).catch(error => { console.log('Authenticator.filterPermission.2\n', error); return Promise.resolve([]); }); if (roleCodesPermission && roleCodesPermission.length) { result.roles = yield AuthorizationHelper_1.default.get(`/api/role/codes?codes=${roleCodesPermission.join(',')}`).catch(error => { console.log('Authenticator.filterPermission.3\n', error); return Promise.resolve([]); }); } return result; }); } } Authenticator.userKey = 'authUser'; Authenticator.lastAPI = 0; Authenticator.lastAccess = new Date(); Authenticator.timeOut = 0; Authenticator.invalid = false; Object.seal(Authenticator); exports.default = Authenticator;
/// <reference types="cypress" /> context('Casos de erro', () => { beforeEach(() => { cy.visit('/') }) it('Email invalido', () => { cy.cadastro("Test Bossa","test.com.com","Va654321","Va654321",true) cy.get('button.bbox-button.margin-top-big.bg-blue-base').click() cy.get('.bbox-context-banner > .card').should('have.text','E-mail e/ou senha inválidos') }) it('Senhas distintas', () => { cy.cadastro("Test Bossa","test1@com.com","Va6543a1","Va654321",true) cy.get('button.bbox-button.margin-top-big.bg-blue-base').click() cy.get('.bbox-context-banner > .card').should('have.text','As senhas não correspondem') }) it('Email vazio', () => { cy.cadastro("Test Bossa","","Va654321","Va654321",true) cy.get('button.bbox-button.margin-top-big.bg-blue-base').click() cy.get('.bbox-context-banner > .card').should('have.text','Lembre-se de preencher os campos') }) it('Email duplicate', () => { cy.cadastro("Test Bossa","test@test.com","Va654321","Va654321",true) cy.get('button.bbox-button.margin-top-big.bg-blue-base').click() cy.get('.bbox-context-banner > .card').should('have.text','E-mail já cadastrado!') }) it('Nao aceite aos termos', () => { cy.cadastro("Test Bossa","test@test.com","Va654321","Va654321",false) cy.get('button.bbox-button.margin-top-big.bg-blue-base').click() cy.get('.bbox-context-banner > .card').should('have.text','É necessário aceitar os termos de uso e política de privacidade para prosseguir') }) it('Senha fora dos padroes', () => { cy.cadastro("Test Bossa","test@test.com","V321","V321",false) cy.get('button.bbox-button.margin-top-big.bg-blue-base').click() cy.get('.bbox-context-banner > .card').should('have.text','A senha deve ter pelo menos 8 caracteres') }) // Nome poderia exigir ao menos um sobrenome it('Nome completo', () => { cy.cadastro("Test","test@test.com","Va654321","Va654321",true) cy.get('button.bbox-button.margin-top-big.bg-blue-base').click() cy.get('.bbox-context-banner > .card').should('have.text','Lembre-se de preencher os campos') }) })
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsPending = { name: 'pending', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM7 13.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm5 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm5 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/></svg>` };
'use strict'; angular.module('reports') .service('reportsService', function(pouchDB, config) { var db = pouchDB(config.db); this.getDeliveryRounds = function() { return db.query('reports/delivery-rounds') .then(function(response) { return response.rows.map(function(row) { return { id: row.id, state: row.key[0], startDate: new Date(row.key[1]), endDate: new Date(row.value.endDate), roundCode: row.value.roundCode }; }); }); }; this.getDailyDeliveries = function(roundId) { return db .query('reports/daily-deliveries', { startkey: [roundId], endkey: [roundId, {}, {}, {}] }) .then(function(response) { return response.rows.map(function(row) { return { id: row.id, driverID: row.key[1], date: new Date(row.key[2]), drop: row.key[3], status: row.value.status, window: row.value.window, signature: row.value.signature, facility: row.value.facility }; }); }); }; });
const goodsDao = require("../dao/goodsDao"); const path = require("path"); const goodsUpload = require("../config/goodsUpload"); const fs = require("fs"); const goodsController = { //商品信息 goodsInfo(req,resp){ let sendMsg; goodsDao.searchGoods([]) .then((msg)=>{ // msg.admin = "admin"; // resp.render("goods.ejs",msg); sendMsg = msg; return goodsDao.propInfo({"g_p_prop":1}); }) .then((msg)=>{ sendMsg.color = msg.list; return goodsDao.propInfo({"g_p_prop":2}); }) .then((msg)=>{ sendMsg.size = msg.list; return goodsDao.searchCount([]); }) .then((msg)=>{ sendMsg.pageTotal = msg.pageTotal; resp.render("goods.ejs",sendMsg); }) }, //查询 searchGoods(req,resp){ let sendMsg; goodsDao.searchGoods(req.query) .then((msg)=>{ // console.log(msg); sendMsg = msg; return goodsDao.searchCount(req.query); }) .then((msg)=>{ sendMsg.pageTotal = msg.pageTotal; resp.send(sendMsg); }) }, //新增商品 addGoods(req,resp){ req.body.a_id = req.session.userid; let sendMsg = {}; let filename = req.body.g_model; fs.mkdir("./public/uploadimg/"+filename); goodsDao.addGoods(req.body) .then((msg)=>{ if(msg.result) { let data = req.body; sendMsg.g_id = data.g_id = msg.g_id; goodsUpload.changedestorage(filename); data.state = 1; return goodsDao.addSku(data); } else { resp.send(msg); } }) .then((msg)=>{ if(msg.result) { sendMsg.result = msg.result; } resp.send(sendMsg); }) }, //新增商品图片 addGoodsImg(req,resp){ resp.send({"result":1}); }, //修改商品信息 updateGoods(req,resp){ goodsDao.updateGoods(req.body) .then((msg)=>{ let newFile = req.body.g_model; fs.rename("./public/uploadimg/"+req.body.oldFile,"./public/uploadimg/"+newFile); goodsUpload.changedestorage(newFile); resp.send(msg); }) }, //设置热门 hotGoods(req,resp){ goodsDao.hotGoods(req.query) .then((msg)=>{ resp.send(msg); }); }, //设置上架下架 stateGoods(req,resp){ goodsDao.stateGoods(req.query) .then((msg)=>{ resp.send(msg); }); }, //商品sku信息 skuInfo(req,resp){ goodsDao.searchSku(req.query) .then((msg)=>{ // msg.admin = "admin"; resp.send(msg); }); }, //更新sku信息 updateSku(req,resp){ goodsDao.updateSku(req.body) .then((msg)=>{ if(msg.result) { return goodsDao.searchSku(req.body); } else { return 0; } }) .then((msg)=>{ resp.send(msg); }) }, //新增sku信息 addSku(req,resp){ let sqlData = req.body; sqlData.a_id = req.session.userid; goodsDao.addSku(sqlData) .then((msg)=>{ if(msg.result) { return goodsDao.searchSku(msg); } else { resp.send(msg); } }) .then((msg)=>{ resp.send(msg); }) }, //颜色属性信息 colorInfo(req,resp){ goodsDao.propInfo(req.query) .then((msg)=>{ // msg.admin = "admin"; resp.send(msg); }) }, //商品标签信息 goodsTagsInfo(req,resp){ goodsDao.goodsTagsInfo(req.query) .then((msg)=>{ resp.send(msg); }) }, //标签信息 getTagsInfo(req,resp){ goodsDao.getTagsInfo([]) .then((msg)=>{ resp.send(msg); }) }, //新增商品标签 addGoodsTags(req,resp){ goodsDao.addGoodsTags(req.body) .then((msg)=>{ if(msg.result) { return goodsDao.goodsTagsInfo(msg); } else { resp.send(msg); } }) .then((msg)=>{ resp.send(msg); }) }, //更新商品标签 updateGoodsTags(req,resp){ goodsDao.updateGoodsTags(req.body) .then((msg)=>{ if(msg.result) { return goodsDao.goodsTagsInfo(req.body); } else { resp.send(msg); } }) .then((msg)=>{ resp.send(msg); }) }, //删除商品标签 delGoodsTags(req,resp){ goodsDao.delGoodsTags(req.query) .then((msg)=>{ resp.send(msg); }) } }; module.exports = goodsController;
// This configuration extends the existing Storybook Webpack config. // See https://storybook.js.org/configurations/custom-webpack-config/ for more info. const excludePaths = [/node_modules/, /dist/] module.exports = ({ config }) => { // Use real file paths for symlinked dependencies do avoid including them multiple times config.resolve.symlinks = true Object.assign(config.resolve, { modules: ['node_modules'], descriptionFiles: ['package.json'], mainFiles: ['index', 'main'] }) // HACK: extend existing JS rule to ensure all dependencies are correctly ignored // https://github.com/storybooks/storybook/issues/3346#issuecomment-459439438 const jsRule = config.module.rules.find((rule) => rule.test.test('.jsx')) jsRule.exclude = excludePaths // HACK: Instruct Babel to check module type before injecting Core JS polyfills // https://github.com/i-like-robots/broken-webpack-bundle-test-case const babelConfig = jsRule.use.find(({ loader }) => loader === 'babel-loader') || { options: { presets: [] } } babelConfig.options.sourceType = 'unambiguous' // Add support for TypeScript source code // https://storybook.js.org/configurations/typescript-config/ config.module.rules.push({ test: /\.(ts|tsx)$/, loader: require.resolve('babel-loader'), options: { presets: [require.resolve('@babel/preset-react'), require.resolve('@babel/preset-typescript')] }, exclude: excludePaths }) config.resolve.extensions.push('.ts', '.tsx', '.d.ts') // Add support for styles written with Sass config.module.rules.push({ test: /\.(scss|sass)$/, use: [ { loader: require.resolve('style-loader') }, { loader: require.resolve('css-loader') }, { loader: require.resolve('sass-loader'), options: { // Use `dart-sass` rather than `node-sass` implementation: require('sass'), sassOptions: { includePaths: ['node_modules'] } } } ] }) // HACK: Ensure we only bundle one instance of React config.resolve.alias.react = require.resolve('react') return config }
import { Map } from 'immutable'; import { LOAD_FREE_ACTIVITIES, LOAD_FREE_ACTIVITIES_SUCCESS, LOAD_FREE_ACTIVITIES_FAILURE, GET_FREE_ACTIVITIES, GET_FREE_ACTIVITIES_SUCCESS, GET_FREE_ACTIVITIES_FAILURE, GET_LINK_ACTIVITIE, GET_LINK_ACTIVITIE_SUCCESS, GET_LINK_ACTIVITIE_FAILURE, ACTIVITY_ANSWER, } from '../actions/freeActivity'; const initState = new Map({ isLoading: false, activities: null, activity: null, activityStage: 0, error: false }) /** * * @function * Cette fonction est un 'Reducer' pour stocker le 'State' à chaque 'action' pour des activités libres. */ function freeActivityReducer(state = initState, action) { switch(action.type) { case LOAD_FREE_ACTIVITIES: return state .set('isLoading', true) .set('activity', null) .set('activityStage', 0) .set('error', false) case LOAD_FREE_ACTIVITIES_SUCCESS: return state .set('isLoading', false) .set('activities', action.result) .set('error', false) case LOAD_FREE_ACTIVITIES_FAILURE: return state .set('isLoading', false) .set('activity', null) .set('error', true) case GET_FREE_ACTIVITIES: return state .set('isLoading', true) .set('activities', null) .set('activityStage', 1) .set('error', false) case GET_FREE_ACTIVITIES_SUCCESS: return state .set('isLoading', false) .set('activity', action.result) .set('error', false) case GET_FREE_ACTIVITIES_FAILURE: return state .set('isLoading', false) .set('activity', null) .set('error', true) case GET_LINK_ACTIVITIE: return state .set('isLoading', true) .set('activities', null) .set('activityStage', 1) .set('error', false) case GET_LINK_ACTIVITIE_SUCCESS: return state .set('isLoading', false) .set('activity', action.result) .set('error', false) case GET_LINK_ACTIVITIE_FAILURE: return state .set('isLoading', false) .set('activity', null) .set('error', true) case ACTIVITY_ANSWER: return state .set('isLoading', true) .set('activity', null) .set('activityStage', 0) .set('error', false) default: return state; } } export default freeActivityReducer;
module.exports = { siteMetadata: { title: "Hablando con Máquinas", author: "Jonay Godoy", }, plugins: [ `gatsby-plugin-catch-links`, { resolve: `gatsby-source-filesystem`, options: { path: `${__dirname}/src/pages`, name: "pages", }, }, { resolve: `gatsby-transformer-remark`, options: { plugins: [ { resolve: `gatsby-remark-images`, options: { maxWidth: 590, }, }, { resolve: `gatsby-remark-responsive-iframe`, options: { }, }, "gatsby-remark-prismjs", "gatsby-remark-copy-linked-files", "gatsby-remark-smartypants", ], }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-google-analytics`, options: { trackingId: `UA-102689265-1`, }, }, `gatsby-plugin-offline`, `gatsby-plugin-react-helmet` ], };
import React from "react"; export default function About() { return ( <div className="about" id="about"> <h1 className="dobrodosli">Welcome</h1> <h1 className="naslov2">ABOUT US</h1> <h2 className="podnaslov3">PHILLIP ISLAND RESTORAUNT</h2> <hr className="crni" /> <p className="tekst"> {" "} Dining is more than just food. It is that special combination of hospitality, location and personal touches that allow guest to 'feel at home'. </p> </div> ); }
'use strict'; angular .module('myApp.character') .service('characterServiceJs', Service); angular .module('myApp.character') .constant('charAddress', 'http://localhost:8080/tacs2016c1/personajes'); Service.$inject = ['$rootScope', '$q', '$http', 'charAddress']; function Service($rootScope, $q, $http, charAddress) { return { addFavorite: addFavorite, removeFavorite: removeFavorite, getCharacter: getCharacter, getCharacters: getCharacters }; function getCharacter(characterId) { if (characterId != null) { return $http.get(charAddress + '/' + characterId) .success(function (res) { return res; }) ; } } function getCharacters(request) { if (request.characterName != null) { return $http.get(charAddress, { params: { name: request.characterName } }) .success(function (res) { return res; }) ; } else { if (request.limit != null && request.offset != null) { //Get characters based on limit and offset return $http.get(charAddress, { params: { limit: request.limit, offset: request.offset } }) .success(function (res) { return res; }) ; } else { //Get all the characters return $http.get(charAddress) .success(function (res) { return res; }) ; } } } // /usuarios/{nombreUsuario}/personajesFavoritos/{idPersonaje} function addFavorite(user, char) { var url = 'http://localhost:8080/tacs2016c1/usuarios/' + user + '/personajesFavoritos/' + char; return $http.put(url) .success(function () { $http.get('http://localhost:8080/tacs2016c1/usuarios/' + user + '/personajesFavoritos') .success(function (data) { $rootScope.favorites = data.results; }) ; }) ; } function removeFavorite(user, char) { var url = 'http://localhost:8080/tacs2016c1/usuarios/' + user + '/personajesFavoritos/' + char; return $http.delete(url) .success(function () { $http.get('http://localhost:8080/tacs2016c1/usuarios/' + user + '/personajesFavoritos') .success(function (data) { $rootScope.favorites = data; }) ; }) ; } }
var combineReducers=require("redux").combineReducers; var types=require("../../const/home/IndexTypes"); //初试的redux状态 var initState=[ { text: 'Use Redux', completed: false, id: 0 } ]; var todo= function(state=initState,action){ var newState=Object.assign({},state); switch (action.type) { case types.ADD_TODO: return [ { id: state.reduce(function (maxId, todo) { return Math.max(todo.id, maxId); }, -1) + 1, completed: false, text: action.text } ].concat(state) ; break; case types.DELETE_TODO: return state.filter(function(todo){ return todo.id !== action.id }); break; case types.EDIT_TODO: return state.map(function(todo){ return todo.id === action.id ? Object.assign({}, todo, { text: action.text }) : todo }); break; case types.COMPLETE_TODO: return state.map(function(todo){ return todo.id === action.id ? Object.assign({}, todo, { completed: !todo.completed }) : todo }); break; case types.COMPLETE_ALL: var areAllMarked = state.every(function(todo){ return todo.completed }); return state.map(function(todo){ return Object.assign({}, todo, { completed: !areAllMarked}); }); break; case types.CLEAR_COMPLETED: return state.filter(function(todo){ return todo.completed === false }); break; case types.GET_ALL: return state.concat([]); break; default: return state } }; module.exports=combineReducers({todo:todo});
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import Survey from './Survey/Survey'; import Final from './Final/Final'; import store from '../rootReducer' import './styles.css'; class App extends Component { render() { return ( <Provider store={store}> <div className="app"> <Final /> <Survey /> </div> </Provider> ); } } export default App;
app.controller("flexiAttributeController",function($scope,$http) { $scope.init = function(asJson) { $scope.flexiAttr = asJson; } $scope.addFlexiAttr = function () { $scope.flexiAttr.push({ name:"", type:"", value:"" }); } });
/** * * Null 类型只有一个值的数据类型,这个特殊的值是 null * 从逻辑角度来看, null 值表示一个空对象指针,而这也正是使用 typeof 操作符检测 null 值时会返回"object"的原因 * * 如果定义的变量准备在将来用于保存对象,那么最好将该变量初始化为 null * */ var car = null; console.log(typeof car); if (car != null) { //对car对象执行某些操作 }
/*################################################# For: SSW 322 By: Bruno, Hayden, Madeline, Miriam, and Scott #################################################*/ let mongoose = require('mongoose'); const BookSchema = new mongoose.Schema({ 'bookID' : { type: String, default: '' }, 'title' : { type: String, default: '' }, 'isbn' : { type: String, default: '' }, 'isbn13' : { type: String, default: '' }, 'description' : { type: String, default: '' }, 'shortDescription' : { type: String, default: '' }, 'author' : { type: String, default: '' }, 'pages' : { type: Number, default: 0 }, 'imgURL' : { type: String, default: '' }, 'rate' : { type: Number, default: 0 }, 'numberOfRatings' : { type: Number, default: 0}, 'purchaseURL' : { type: String, default: ''} }); module.exports = BookSchema;
(function () { "use strict"; function $extend(from, fields) { function Inherit() {} Inherit.prototype = from; var proto = new Inherit(); for (var name in fields) proto[name] = fields[name]; if( fields.toString !== Object.prototype.toString ) proto.toString = fields.toString; return proto; } var Main = function() { window.onload = $bind(this,this.init); }; Main.__name__ = true; Main.main = function() { new Main(); }; Main.prototype = { init: function(event) { new vanitas.Setup(); } ,__class__: Main }; var IMap = function() { }; IMap.__name__ = true; Math.__name__ = true; var Std = function() { }; Std.__name__ = true; Std.string = function(s) { return js.Boot.__string_rec(s,""); }; Std["int"] = function(x) { return x | 0; }; Std.random = function(x) { if(x <= 0) return 0; else return Math.floor(Math.random() * x); }; var haxe = {}; haxe.Timer = function(time_ms) { var me = this; this.id = setInterval(function() { me.run(); },time_ms); }; haxe.Timer.__name__ = true; haxe.Timer.delay = function(f,time_ms) { var t = new haxe.Timer(time_ms); t.run = function() { t.stop(); f(); }; return t; }; haxe.Timer.prototype = { stop: function() { if(this.id == null) return; clearInterval(this.id); this.id = null; } ,run: function() { } ,__class__: haxe.Timer }; haxe.ds = {}; haxe.ds.ObjectMap = function() { this.h = { }; this.h.__keys__ = { }; }; haxe.ds.ObjectMap.__name__ = true; haxe.ds.ObjectMap.__interfaces__ = [IMap]; haxe.ds.ObjectMap.prototype = { set: function(key,value) { var id = key.__id__ || (key.__id__ = ++haxe.ds.ObjectMap.count); this.h[id] = value; this.h.__keys__[id] = key; } ,__class__: haxe.ds.ObjectMap }; var js = {}; js.Boot = function() { }; js.Boot.__name__ = true; js.Boot.getClass = function(o) { if((o instanceof Array) && o.__enum__ == null) return Array; else return o.__class__; }; js.Boot.__string_rec = function(o,s) { if(o == null) return "null"; if(s.length >= 5) return "<...>"; var t = typeof(o); if(t == "function" && (o.__name__ || o.__ename__)) t = "object"; switch(t) { case "object": if(o instanceof Array) { if(o.__enum__) { if(o.length == 2) return o[0]; var str = o[0] + "("; s += "\t"; var _g1 = 2; var _g = o.length; while(_g1 < _g) { var i = _g1++; if(i != 2) str += "," + js.Boot.__string_rec(o[i],s); else str += js.Boot.__string_rec(o[i],s); } return str + ")"; } var l = o.length; var i1; var str1 = "["; s += "\t"; var _g2 = 0; while(_g2 < l) { var i2 = _g2++; str1 += (i2 > 0?",":"") + js.Boot.__string_rec(o[i2],s); } str1 += "]"; return str1; } var tostr; try { tostr = o.toString; } catch( e ) { return "???"; } if(tostr != null && tostr != Object.toString) { var s2 = o.toString(); if(s2 != "[object Object]") return s2; } var k = null; var str2 = "{\n"; s += "\t"; var hasp = o.hasOwnProperty != null; for( var k in o ) { if(hasp && !o.hasOwnProperty(k)) { continue; } if(k == "prototype" || k == "__class__" || k == "__super__" || k == "__interfaces__" || k == "__properties__") { continue; } if(str2.length != 2) str2 += ", \n"; str2 += s + k + " : " + js.Boot.__string_rec(o[k],s); } s = s.substring(1); str2 += "\n" + s + "}"; return str2; case "function": return "<function>"; case "string": return o; default: return String(o); } }; js.Boot.__interfLoop = function(cc,cl) { if(cc == null) return false; if(cc == cl) return true; var intf = cc.__interfaces__; if(intf != null) { var _g1 = 0; var _g = intf.length; while(_g1 < _g) { var i = _g1++; var i1 = intf[i]; if(i1 == cl || js.Boot.__interfLoop(i1,cl)) return true; } } return js.Boot.__interfLoop(cc.__super__,cl); }; js.Boot.__instanceof = function(o,cl) { if(cl == null) return false; switch(cl) { case Int: return (o|0) === o; case Float: return typeof(o) == "number"; case Bool: return typeof(o) == "boolean"; case String: return typeof(o) == "string"; case Array: return (o instanceof Array) && o.__enum__ == null; case Dynamic: return true; default: if(o != null) { if(typeof(cl) == "function") { if(o instanceof cl) return true; if(js.Boot.__interfLoop(js.Boot.getClass(o),cl)) return true; } } else return false; if(cl == Class && o.__name__ != null) return true; if(cl == Enum && o.__ename__ != null) return true; return o.__enum__ == cl; } }; js.Boot.__cast = function(o,t) { if(js.Boot.__instanceof(o,t)) return o; else throw "Cannot cast " + Std.string(o) + " to " + Std.string(t); }; var net = {}; net.rsakane = {}; net.rsakane.asset = {}; net.rsakane.asset.Asset = function(src,id) { if(id == null) id = ""; this.src = src; if(id == "") this.id = src; else this.id = id; }; net.rsakane.asset.Asset.__name__ = true; net.rsakane.asset.Asset.prototype = { get: function() { return { id : this.id, src : this.src}; } ,__class__: net.rsakane.asset.Asset }; net.rsakane.asset.AssetManager = function(basePath) { if(basePath == null) basePath = ""; this.basePath = basePath; }; net.rsakane.asset.AssetManager.__name__ = true; net.rsakane.asset.AssetManager.__super__ = createjs.EventDispatcher; net.rsakane.asset.AssetManager.prototype = $extend(createjs.EventDispatcher.prototype,{ get: function(fileName) { return this.loadQueue.getResult(fileName); } ,loadFiles: function(assets) { var _g = this; this.loadQueue = new createjs.LoadQueue(true,this.basePath); this.loadQueue.installPlugin(createjs.Sound); this.loadQueue.on(net.rsakane.asset.AssetManager.COMPLETE,function(event) { if(_g.complete != null) _g.complete(event); }); this.loadQueue.on(net.rsakane.asset.AssetManager.PROGRESS,function(event1) { if(_g.progress != null) _g.progress(event1); }); var files = []; var _g1 = 0; while(_g1 < assets.length) { var asset = assets[_g1]; ++_g1; files.push(asset.get()); } this.loadQueue.loadManifest(files); } ,__class__: net.rsakane.asset.AssetManager }); net.rsakane.paperjs = {}; net.rsakane.paperjs.align = {}; net.rsakane.paperjs.align._Align = {}; net.rsakane.paperjs.align._Align.ItemView_Impl_ = function() { }; net.rsakane.paperjs.align._Align.ItemView_Impl_.__name__ = true; net.rsakane.paperjs.align._Align.ItemView_Impl_._new = function(value) { return value; }; net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem = function(value) { return net.rsakane.paperjs.align._Align.ItemView_Impl_._new(value); }; net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView = function(value) { return net.rsakane.paperjs.align._Align.ItemView_Impl_._new(value); }; net.rsakane.paperjs.align._Align.ItemView_Impl_.fromPoint = function(value) { return net.rsakane.paperjs.align._Align.ItemView_Impl_._new(value); }; net.rsakane.paperjs.align._Align.ItemView_Impl_.get_bounds = function(this1) { return this1.bounds; }; net.rsakane.paperjs.align._Align.ItemView_Impl_.toItem = function(this1) { return this1; }; net.rsakane.paperjs.align._Align.ItemView_Impl_.toView = function(this1) { return this1; }; net.rsakane.paperjs.align._Align.ItemView_Impl_.toPoint = function(this1) { return this1; }; net.rsakane.paperjs.align.Align = function() { }; net.rsakane.paperjs.align.Align.__name__ = true; net.rsakane.paperjs.align.Align.center = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.center,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.top = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.topCenter,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.topCenter = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.topCenter,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.bottom = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.bottomCenter,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.bottomCenter = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.bottomCenter,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.left = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.leftCenter,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.leftCenter = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.leftCenter,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.right = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.rightCenter,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.rightCenter = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.rightCenter,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.topLeft = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.topLeft,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.topRight = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.topRight,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.bottomLeft = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.bottomLeft,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.bottomRight = function(target,base,baseAlign,alignAxis) { return net.rsakane.paperjs.align.Align.align(target,base,net.rsakane.paperjs.align.AlignType.bottomRight,baseAlign,alignAxis); }; net.rsakane.paperjs.align.Align.align = function(target,base,targetAlign,baseAlign,alignAxis) { if(baseAlign == null) baseAlign = net.rsakane.paperjs.align.AlignType.center; if(alignAxis == null) alignAxis = net.rsakane.paperjs.align.AlignAxis.XY; var basePoint = new paper.Point(); if(js.Boot.__instanceof(base,paper.Point)) basePoint = net.rsakane.paperjs.align._Align.ItemView_Impl_.toPoint(base); else switch(baseAlign[1]) { case 4: basePoint = net.rsakane.paperjs.align._Align.ItemView_Impl_.get_bounds(base).center; break; case 2:case 6: basePoint = net.rsakane.paperjs.align._Align.ItemView_Impl_.get_bounds(base).topCenter; break; case 3:case 11: basePoint = net.rsakane.paperjs.align._Align.ItemView_Impl_.get_bounds(base).bottomCenter; break; case 0:case 8: basePoint = net.rsakane.paperjs.align._Align.ItemView_Impl_.get_bounds(base).leftCenter; break; case 1:case 9: basePoint = net.rsakane.paperjs.align._Align.ItemView_Impl_.get_bounds(base).rightCenter; break; case 5: basePoint = net.rsakane.paperjs.align._Align.ItemView_Impl_.get_bounds(base).topLeft; break; case 7: basePoint = net.rsakane.paperjs.align._Align.ItemView_Impl_.get_bounds(base).topRight; break; case 10: basePoint = net.rsakane.paperjs.align._Align.ItemView_Impl_.get_bounds(base).bottomLeft; break; case 12: basePoint = net.rsakane.paperjs.align._Align.ItemView_Impl_.get_bounds(base).bottomRight; break; } var targetPoint; switch(targetAlign[1]) { case 4: targetPoint = target.bounds.center; break; case 2:case 6: targetPoint = target.bounds.topCenter; break; case 3:case 11: targetPoint = target.bounds.bottomCenter; break; case 0:case 8: targetPoint = target.bounds.leftCenter; break; case 1:case 9: targetPoint = target.bounds.rightCenter; break; case 5: targetPoint = target.bounds.topLeft; break; case 7: targetPoint = target.bounds.topRight; break; case 10: targetPoint = target.bounds.bottomLeft; break; case 12: targetPoint = target.bounds.bottomRight; break; } var diff = basePoint.subtract(paperjs.lib._PointEx.PointEx_Impl_.fromXY(targetPoint)); var dest = target.position.add(paperjs.lib._PointEx.PointEx_Impl_.fromXY(diff)); switch(alignAxis[1]) { case 2: target.position = dest; break; case 0: target.position.x = dest.x; break; case 1: target.position.y = dest.y; break; case 3: break; } return target.position; }; net.rsakane.paperjs.align.AlignAxis = { __ename__ : true, __constructs__ : ["X","Y","XY","None"] }; net.rsakane.paperjs.align.AlignAxis.X = ["X",0]; net.rsakane.paperjs.align.AlignAxis.X.__enum__ = net.rsakane.paperjs.align.AlignAxis; net.rsakane.paperjs.align.AlignAxis.Y = ["Y",1]; net.rsakane.paperjs.align.AlignAxis.Y.__enum__ = net.rsakane.paperjs.align.AlignAxis; net.rsakane.paperjs.align.AlignAxis.XY = ["XY",2]; net.rsakane.paperjs.align.AlignAxis.XY.__enum__ = net.rsakane.paperjs.align.AlignAxis; net.rsakane.paperjs.align.AlignAxis.None = ["None",3]; net.rsakane.paperjs.align.AlignAxis.None.__enum__ = net.rsakane.paperjs.align.AlignAxis; net.rsakane.paperjs.align.AlignType = { __ename__ : true, __constructs__ : ["left","right","top","bottom","center","topLeft","topCenter","topRight","leftCenter","rightCenter","bottomLeft","bottomCenter","bottomRight"] }; net.rsakane.paperjs.align.AlignType.left = ["left",0]; net.rsakane.paperjs.align.AlignType.left.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.align.AlignType.right = ["right",1]; net.rsakane.paperjs.align.AlignType.right.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.align.AlignType.top = ["top",2]; net.rsakane.paperjs.align.AlignType.top.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.align.AlignType.bottom = ["bottom",3]; net.rsakane.paperjs.align.AlignType.bottom.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.align.AlignType.center = ["center",4]; net.rsakane.paperjs.align.AlignType.center.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.align.AlignType.topLeft = ["topLeft",5]; net.rsakane.paperjs.align.AlignType.topLeft.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.align.AlignType.topCenter = ["topCenter",6]; net.rsakane.paperjs.align.AlignType.topCenter.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.align.AlignType.topRight = ["topRight",7]; net.rsakane.paperjs.align.AlignType.topRight.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.align.AlignType.leftCenter = ["leftCenter",8]; net.rsakane.paperjs.align.AlignType.leftCenter.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.align.AlignType.rightCenter = ["rightCenter",9]; net.rsakane.paperjs.align.AlignType.rightCenter.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.align.AlignType.bottomLeft = ["bottomLeft",10]; net.rsakane.paperjs.align.AlignType.bottomLeft.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.align.AlignType.bottomCenter = ["bottomCenter",11]; net.rsakane.paperjs.align.AlignType.bottomCenter.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.align.AlignType.bottomRight = ["bottomRight",12]; net.rsakane.paperjs.align.AlignType.bottomRight.__enum__ = net.rsakane.paperjs.align.AlignType; net.rsakane.paperjs.scene = {}; net.rsakane.paperjs.scene.Scene = function() { }; net.rsakane.paperjs.scene.Scene.__name__ = true; net.rsakane.paperjs.scene.Scene.push = function(scene) { net.rsakane.paperjs.scene.SceneManager.instance.push(scene); }; net.rsakane.paperjs.scene.Scene.pop = function() { net.rsakane.paperjs.scene.SceneManager.instance.pop(); }; net.rsakane.paperjs.scene.Scene.change = function(scene) { net.rsakane.paperjs.scene.SceneManager.instance.change(scene); }; net.rsakane.paperjs.scene.SceneManager = function() { this.sceneGroup = new Array(); }; net.rsakane.paperjs.scene.SceneManager.__name__ = true; net.rsakane.paperjs.scene.SceneManager.prototype = { push: function(nextScene) { if(this.sceneGroup.length > 0) this.sceneGroup[this.sceneGroup.length - 1].stop(); this.sceneGroup.push(nextScene); nextScene.enter(); } ,pop: function() { var scene = this.sceneGroup.pop(); scene.deleteDisplayItem(); this.sceneGroup[this.sceneGroup.length - 1].resume(); } ,change: function(nextScene) { if(this.sceneGroup.length > 0) { var curScene = this.sceneGroup.pop(); this.sceneGroup.push(nextScene); curScene.exit(); } else { this.sceneGroup = [nextScene]; this.next(); } } ,next: function() { var _g1 = 0; var _g = this.sceneGroup.length - 1; while(_g1 < _g) { var i = _g1++; var scene = this.sceneGroup[i]; scene.deleteDisplayItem(); } this.sceneGroup[this.sceneGroup.length - 1].enter(); } ,__class__: net.rsakane.paperjs.scene.SceneManager }; net.rsakane.paperjs.scene.SceneSprite = function() { paper.Layer.call(this); }; net.rsakane.paperjs.scene.SceneSprite.__name__ = true; net.rsakane.paperjs.scene.SceneSprite.__super__ = paper.Layer; net.rsakane.paperjs.scene.SceneSprite.prototype = $extend(paper.Layer.prototype,{ enter: function() { this.activate(); this.onFrame = $bind(this,this.update); if(net.rsakane.paperjs.scene.SceneSprite.tool == null) net.rsakane.paperjs.scene.SceneSprite.tool = new paper.Tool(); net.rsakane.paperjs.scene.SceneSprite.tool.onKeyDown = $bind(this,this.onKeyDown); net.rsakane.paperjs.scene.SceneSprite.tool.onKeyUp = $bind(this,this.onKeyUp); net.rsakane.paperjs.scene.SceneSprite.tool.onMouseDown = $bind(this,this.mouseDown); net.rsakane.paperjs.scene.SceneSprite.tool.onMouseUp = $bind(this,this.mouseUp); net.rsakane.paperjs.scene.SceneSprite.tool.onMouseDrag = $bind(this,this.mouseDrag); net.rsakane.paperjs.scene.SceneSprite.tool.onMouseMove = $bind(this,this.mouseMove); } ,update: function(event) { } ,mouseDown: function(event) { } ,mouseUp: function(event) { } ,mouseDrag: function(event) { } ,mouseMove: function(event) { } ,onKeyDown: function(event) { } ,onKeyUp: function(event) { } ,exit: function() { this.next(); } ,resume: function() { this.locked = false; this.activate(); } ,stop: function() { this.locked = true; } ,deleteDisplayItem: function() { this.removeChildren(); this.remove(); } ,next: function() { this.deleteDisplayItem(); net.rsakane.paperjs.scene.SceneManager.instance.next(); } ,__class__: net.rsakane.paperjs.scene.SceneSprite }); var paperjs = {}; paperjs.lib = {}; paperjs.lib._PointEx = {}; paperjs.lib._PointEx.PointEx_Impl_ = function() { }; paperjs.lib._PointEx.PointEx_Impl_.__name__ = true; paperjs.lib._PointEx.PointEx_Impl_._new = function(value) { return value; }; paperjs.lib._PointEx.PointEx_Impl_.fromXY = function(xy) { return paperjs.lib._PointEx.PointEx_Impl_._new(xy); }; paperjs.lib._PointEx.PointEx_Impl_.fromWidthHeight = function(wh) { return paperjs.lib._PointEx.PointEx_Impl_._new(wh); }; paperjs.lib._PointEx.PointEx_Impl_.fromFloatInt = function(values) { return paperjs.lib._PointEx.PointEx_Impl_._new(values); }; paperjs.lib._PointEx.PointEx_Impl_.fromFloatArray = function(values) { return paperjs.lib._PointEx.PointEx_Impl_._new(values); }; var vanitas = {}; vanitas.Gauge = function(width,height,colorFront,colorBack) { this.back = paper.Path.Rectangle([0,0,width,height]); this.front = js.Boot.__cast(this.back.clone() , paper.Path); this.back.fillColor = colorBack; this.front.fillColor = colorFront; paper.Group.call(this,[this.back,this.front]); }; vanitas.Gauge.__name__ = true; vanitas.Gauge.__super__ = paper.Group; vanitas.Gauge.prototype = $extend(paper.Group.prototype,{ update: function() { var total = vanitas.Status.redValue + vanitas.Status.blueValue; var ratio; if(vanitas.Status.redValue == vanitas.Status.blueValue) ratio = 0.5; else if(vanitas.Status.redValue == 0) ratio = 0.0; else ratio = vanitas.Status.redValue / total; var newWidth = this.bounds.size.width * ratio; newWidth = Math.max(newWidth,0.01); createjs.Tween.get(this.front.bounds.size,{ override : true}).to({ width : newWidth},500); } ,__class__: vanitas.Gauge }); vanitas.Screen = function() { }; vanitas.Screen.__name__ = true; vanitas.Setup = function() { var _g = this; paper.PaperScope.call(this); this.setup("canvas"); var bg = paper.Path.Rectangle([0,0,vanitas.Screen.WIDTH,vanitas.Screen.HEIGHT]); bg.fillColor = "black"; var progressBar = paper.Path.Rectangle([0,0,vanitas.Screen.WIDTH,15]); progressBar.fillColor = "#26595A"; net.rsakane.paperjs.align.Align.center(progressBar,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView(this.view)); progressBar.bounds.width = 0.01; createjs.Sound.alternateExtensions = ["mp3"]; var assets = [new net.rsakane.asset.Asset("assets/se/button14.mp3","selectLevel"),new net.rsakane.asset.Asset("assets/se/button56.mp3","cancel"),new net.rsakane.asset.Asset("assets/se/button75.mp3","startGame"),new net.rsakane.asset.Asset("assets/se/click05.mp3","flip"),new net.rsakane.asset.Asset("assets/se/menu.mp3","menu"),new net.rsakane.asset.Asset("assets/se/relief01.mp3","result"),new net.rsakane.asset.Asset("assets/image/player.png","IMAGE_PLAYER"),new net.rsakane.asset.Asset("assets/image/enemy0.png","IMAGE_ENEMY1"),new net.rsakane.asset.Asset("assets/image/enemy1.png","IMAGE_ENEMY2"),new net.rsakane.asset.Asset("assets/image/enemy2.png","IMAGE_ENEMY3")]; vanitas.Setup.assetManager = new net.rsakane.asset.AssetManager(); vanitas.Setup.assetManager.complete = function(event) { progressBar.remove(); _g.view.onFrame = $bind(_g,_g.onFrame); net.rsakane.paperjs.scene.Scene.change(new vanitas.scene.SceneTitle()); }; vanitas.Setup.assetManager.progress = function(event1) { var newWidth = Math.max(0.01,event1.progress * vanitas.Screen.WIDTH); progressBar.bounds.width = newWidth; }; vanitas.Setup.assetManager.loadFiles(assets); }; vanitas.Setup.__name__ = true; vanitas.Setup.__super__ = paper.PaperScope; vanitas.Setup.prototype = $extend(paper.PaperScope.prototype,{ onFrame: function(event) { createjs.Tween.tick(16,false); this.view.update(); } ,__class__: vanitas.Setup }); vanitas.Status = function() { }; vanitas.Status.__name__ = true; vanitas.Status.changeNextValue = function() { vanitas.Status.nextValueGroup.shift(); }; vanitas.Status.initNextValueGroup = function() { vanitas.Status.nextValueGroup = []; var _g1 = 0; var _g = vanitas.Status.maxTurn; while(_g1 < _g) { var i = _g1++; vanitas.Status.nextValueGroup[i] = Std.random(20) + 1; } }; vanitas.Status.turnColor = function(turn) { if(turn % 2 == 0) return "#D41737"; else return "#179ED4"; }; vanitas.Status.changeTurn = function() { if(vanitas.Status.currentTurnColor == "#D41737") vanitas.Status.currentTurnColor = "#179ED4"; else vanitas.Status.currentTurnColor = "#D41737"; }; vanitas.Tile = function(symbol) { this.scale = 1.0; this.symbol = symbol; this.text = new paper.PointText(); this.text.fontSize += 2; this.text.content = "0"; this.text.justification = "center"; this.text.position = symbol.position; this.text.visible = false; this.adjacentTiles = []; this.group = new paper.Group([symbol,this.text]); symbol.onClick = $bind(this,this.onClick); symbol.onMouseEnter = $bind(this,this.onMouseEnter); symbol.onMouseLeave = $bind(this,this.onMouseLeave); this.set_value(0); this.color = "#000000"; }; vanitas.Tile.__name__ = true; vanitas.Tile.prototype = { set_value: function(value) { this.text.content = "" + value; return this.value = value; } ,onMouseEnter: function(event) { vanitas.scene.SceneGame.group.addChild(this.group); this.symbol.strokeWidth = 4; } ,onMouseLeave: function(event) { this.symbol.strokeWidth = 2; } ,setFillColor: function(color) { var from = new paper.Color(color); var to = new paper.Color(color); to.brightness -= 0.1; var gradient = new paper.Gradient([[from,0.0],[to,1.0]],true); this.symbol.fillColor = new paper.Color(gradient,paperjs.lib._PointEx.PointEx_Impl_.fromXY(this.symbol.position),paperjs.lib._PointEx.PointEx_Impl_.fromXY(this.symbol.bounds.rightCenter)); } ,onClick: function(event) { var adjacentTile = vanitas.scene.SceneGame.map.h[this.symbol.__id__]; if(this.text.visible || !vanitas.Tile.clickable && event != null) return; createjs.Sound.play("flip","none",0,0,0,0.3); this.set_value(vanitas.Status.nextValueGroup[0]); this.text.visible = true; if(vanitas.scene.SceneGame.turn) { vanitas.Status.blueValue += this.value; this.color = "#179ED4"; } else { vanitas.Status.redValue += this.value; this.color = "#D41737"; } this.setFillColor(this.color); vanitas.scene.SceneGame.turn = !vanitas.scene.SceneGame.turn; var index = 0; var _g = 0; var _g1 = this.adjacentTiles; while(_g < _g1.length) { var adjacentTile1 = _g1[_g]; ++_g; if(adjacentTile1.color == "#000000") continue; if(adjacentTile1.color == this.color) { var _g2 = adjacentTile1; var _g3 = _g2.value; _g2.set_value(_g3 + 1); _g3; if(adjacentTile1.color == "#D41737") vanitas.Status.redValue++; else vanitas.Status.blueValue++; } else if(adjacentTile1.value < this.value) { adjacentTile1.color = this.color; adjacentTile1.setFillColor(this.color); if(adjacentTile1.color == "#D41737") { vanitas.Status.redValue += adjacentTile1.value; vanitas.Status.blueValue -= adjacentTile1.value; } else { vanitas.Status.blueValue += adjacentTile1.value; vanitas.Status.redValue -= adjacentTile1.value; } } index++; } vanitas.scene.SceneGame.gauge.update(); vanitas.scene.SceneGame.scoreText.content = "" + vanitas.Status.redValue + " - " + vanitas.Status.blueValue; net.rsakane.paperjs.align.Align.center(vanitas.scene.SceneGame.scoreText,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(vanitas.scene.SceneGame.gauge)); if(vanitas.Status.turn + vanitas.Status.nextValueDisplayNum < vanitas.Status.maxTurn) { var text = new paper.PointText(paperjs.lib._PointEx.PointEx_Impl_.fromFloatInt([0,0])); text.justification = "center"; text.fillColor = "white"; text.content = vanitas.Status.nextValueGroup[vanitas.Status.nextValueDisplayNum] + ""; var line = paper.Path.Rectangle([0,0,vanitas.Status.textBounds.width,2]); line.fillColor = vanitas.Status.turnColor(vanitas.Status.turn + vanitas.Status.nextValueDisplayNum); net.rsakane.paperjs.align.Align.center(line,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(text)); line.position.y += text.bounds.height / 2; var last = vanitas.scene.SceneGame.nextValueTextGroup.children.length - 1; var lastItem = vanitas.scene.SceneGame.nextValueTextGroup.children[last]; var group = new paper.Group([line,text]); group.position.x = lastItem.position.x + vanitas.Status.textBounds.width * 2; group.position.y = lastItem.position.y; vanitas.scene.SceneGame.nextValueTextGroup.addChild(group); } if(vanitas.scene.SceneGame.nextValueTextGroup.children.length > 0) { var complete = function() { vanitas.scene.SceneGame.nextValueTextGroup.children[0].remove(); }; var nextX = vanitas.scene.SceneGame.nextValueTextGroup.position.x + vanitas.scene.SceneGame.nextValueTextDefaultLeft - vanitas.scene.SceneGame.nextValueTextGroup.bounds.left - vanitas.Status.textBounds.width * 2; createjs.Tween.get(vanitas.scene.SceneGame.nextValueTextGroup.position).to({ x : nextX},250).call(complete); } vanitas.Status.changeNextValue(); vanitas.Status.changeTurn(); vanitas.Status.turn++; vanitas.scene.SceneGame.playerTurnRect.visible = !vanitas.scene.SceneGame.playerTurnRect.visible; vanitas.scene.SceneGame.enemyTurnRect.visible = !vanitas.scene.SceneGame.enemyTurnRect.visible; if(vanitas.Status.turn == vanitas.Status.maxTurn) { vanitas.scene.SceneGame.playerTurnRect.visible = vanitas.scene.SceneGame.enemyTurnRect.visible = false; haxe.Timer.delay(function() { net.rsakane.paperjs.scene.Scene.push(new vanitas.scene.SceneResult()); },1000); } else if(vanitas.scene.SceneGame.com.available && vanitas.Status.currentTurnColor == vanitas.scene.SceneGame.com.color) { vanitas.Tile.clickable = false; vanitas.scene.SceneGame.com.think(); } else vanitas.Tile.clickable = true; } ,__class__: vanitas.Tile }; vanitas._TileColor = {}; vanitas._TileColor.TileColor_Impl_ = function() { }; vanitas._TileColor.TileColor_Impl_.__name__ = true; vanitas._TileColor.TileColor_Impl_.toString = function(this1) { return this1; }; vanitas.com = {}; vanitas.com.COM = function() { this.color = "#179ED4"; this.available = true; }; vanitas.com.COM.__name__ = true; vanitas.com.COM.prototype = { think: function() { } ,__class__: vanitas.com.COM }; vanitas.com.COMLevel1 = function() { vanitas.com.COM.call(this); }; vanitas.com.COMLevel1.__name__ = true; vanitas.com.COMLevel1.__super__ = vanitas.com.COM; vanitas.com.COMLevel1.prototype = $extend(vanitas.com.COM.prototype,{ think: function() { var best = new paper.Point(); var bestValue = -1; var _g1 = 0; var _g = vanitas.Tile.list.length; while(_g1 < _g) { var y = _g1++; var _g3 = 0; var _g2 = vanitas.Tile.list[y].length; while(_g3 < _g2) { var x = _g3++; var tile = vanitas.Tile.list[y][x]; if(tile.color != "#000000") continue; var value = 0; var _g4 = 0; var _g5 = tile.adjacentTiles; while(_g4 < _g5.length) { var aTile = _g5[_g4]; ++_g4; if(aTile.color == "#000000") continue; if(aTile.color == this.color) value++; else if(aTile.value < vanitas.Status.nextValueGroup[0]) value += aTile.value; } if(bestValue < value) { if(bestValue != -1 && Std.random(3) != 0) continue; best.x = x; best.y = y; bestValue = value; } } } var bestTile = vanitas.Tile.list[best.y | 0][best.x | 0]; if(bestTile != null) haxe.Timer.delay(function() { bestTile.onClick(); },1000); } ,__class__: vanitas.com.COMLevel1 }); vanitas.com.COMLevel2 = function() { vanitas.com.COM.call(this); }; vanitas.com.COMLevel2.__name__ = true; vanitas.com.COMLevel2.__super__ = vanitas.com.COM; vanitas.com.COMLevel2.prototype = $extend(vanitas.com.COM.prototype,{ think: function() { var best = new paper.Point(); var bestValue = -1; var _g1 = 0; var _g = vanitas.Tile.list.length; while(_g1 < _g) { var y = _g1++; var _g3 = 0; var _g2 = vanitas.Tile.list[y].length; while(_g3 < _g2) { var x = _g3++; var tile = vanitas.Tile.list[y][x]; if(tile.color != "#000000") continue; var value = 0; var _g4 = 0; var _g5 = tile.adjacentTiles; while(_g4 < _g5.length) { var aTile = _g5[_g4]; ++_g4; if(aTile.color == "#000000") continue; if(aTile.color == this.color) value++; else if(aTile.value < vanitas.Status.nextValueGroup[0]) value += aTile.value; } if(bestValue < value) { if(bestValue != -1 && Std.random(2) != 0) continue; best.x = x; best.y = y; bestValue = value; } } } var bestTile = vanitas.Tile.list[best.y | 0][best.x | 0]; if(bestTile != null) haxe.Timer.delay(function() { bestTile.onClick(); },1000); } ,__class__: vanitas.com.COMLevel2 }); vanitas.com.COMLevel3 = function() { vanitas.com.COM.call(this); }; vanitas.com.COMLevel3.__name__ = true; vanitas.com.COMLevel3.__super__ = vanitas.com.COM; vanitas.com.COMLevel3.prototype = $extend(vanitas.com.COM.prototype,{ think: function() { var best = new paper.Point(); var bestValue = -1; var _g1 = 0; var _g = vanitas.Tile.list.length; while(_g1 < _g) { var y = _g1++; var _g3 = 0; var _g2 = vanitas.Tile.list[y].length; while(_g3 < _g2) { var x = _g3++; var tile = vanitas.Tile.list[y][x]; if(tile.color != "#000000") continue; var value = 0; var _g4 = 0; var _g5 = tile.adjacentTiles; while(_g4 < _g5.length) { var aTile = _g5[_g4]; ++_g4; if(aTile.color == "#000000") continue; if(aTile.color == this.color) value++; else if(aTile.value < vanitas.Status.nextValueGroup[0]) value += aTile.value; } if(bestValue < value) { best.x = x; best.y = y; bestValue = value; } } } var bestTile = vanitas.Tile.list[best.y | 0][best.x | 0]; if(bestTile != null) haxe.Timer.delay(function() { bestTile.onClick(); },1000); } ,__class__: vanitas.com.COMLevel3 }); vanitas.scene = {}; vanitas.scene.SceneGame = function() { net.rsakane.paperjs.scene.SceneSprite.call(this); }; vanitas.scene.SceneGame.__name__ = true; vanitas.scene.SceneGame.__super__ = net.rsakane.paperjs.scene.SceneSprite; vanitas.scene.SceneGame.prototype = $extend(net.rsakane.paperjs.scene.SceneSprite.prototype,{ enter: function() { net.rsakane.paperjs.scene.SceneSprite.prototype.enter.call(this); vanitas.Status.redValue = vanitas.Status.blueValue = 0; var radius = 20; var baseTileShape = paper.Path.RegularPolygon(paperjs.lib._PointEx.PointEx_Impl_.fromXY(new paper.Point(100,100)),6,radius); baseTileShape.strokeColor = "#26595A"; baseTileShape.strokeWidth = 2; baseTileShape.fillColor = "#111111"; var width = Std["int"](Math.cos(Math.PI / 6) * radius * 2); var height = Std["int"]((2 - Math.sin(Math.PI / 6)) * radius); vanitas.scene.SceneGame.map = new haxe.ds.ObjectMap(); vanitas.scene.SceneGame.group = new paper.Group(); var i = 0; vanitas.Tile.list = new Array(); var _g1 = 0; var _g = vanitas.Tile.HEIGHT; while(_g1 < _g) { var y = _g1++; vanitas.Tile.list[y] = new Array(); var tx; if(y % 2 == 1) tx = width / 2 | 0; else tx = 0; var _g3 = 0; var _g2 = vanitas.Tile.WIDTH - y % 2; while(_g3 < _g2) { var x = _g3++; var tileShape; tileShape = js.Boot.__cast(baseTileShape.clone() , paper.Path); tileShape.position = new paper.Point(x * width + tx,y * height); var tile = new vanitas.Tile(tileShape); vanitas.scene.SceneGame.map.set(tileShape,tile); vanitas.scene.SceneGame.group.addChild(tile.group); vanitas.Tile.list[y][x] = tile; tile.scale = 0.0; createjs.Tween.get(tile).to({ scale : 1.0},500).on("change",function(event) { var tween = event.target; var tile1 = tween.target; tile1.group.scaling = new paper.Point(tile1.scale); }); vanitas.Status.maxTurn++; } } var DIR = [[[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[1,-1]],[[-1,0],[1,0],[0,-1],[0,1],[-1,1],[1,1]]]; var _g11 = 0; var _g4 = vanitas.Tile.list.length; while(_g11 < _g4) { var y1 = _g11++; var _g31 = 0; var _g21 = vanitas.Tile.list[y1].length; while(_g31 < _g21) { var x1 = _g31++; var _g41 = 0; var _g5 = DIR[y1 % 2]; while(_g41 < _g5.length) { var dir = _g5[_g41]; ++_g41; var dy = dir[0]; var dx = dir[1]; if(y1 + dy < 0 || vanitas.Tile.list.length <= y1 + dy || x1 + dx < 0 || vanitas.Tile.list[0].length <= x1 + dx) continue; var tile2 = vanitas.Tile.list[y1 + dy][x1 + dx]; if(tile2 != null) vanitas.Tile.list[y1][x1].adjacentTiles.push(tile2); } } } baseTileShape.remove(); net.rsakane.paperjs.align.Align.center(vanitas.scene.SceneGame.group,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView(this.view)); vanitas.scene.SceneGame.scoreText = new paper.PointText(); vanitas.scene.SceneGame.scoreText.fillColor = "white"; vanitas.scene.SceneGame.scoreText.content = "0 - 0"; vanitas.scene.SceneGame.gauge = new vanitas.Gauge(vanitas.scene.SceneGame.group.bounds.width,vanitas.scene.SceneGame.scoreText.bounds.height * 1.5,"#D41737","#179ED4"); this.insertChild(0,vanitas.scene.SceneGame.gauge); net.rsakane.paperjs.align.Align.center(vanitas.scene.SceneGame.scoreText,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(vanitas.scene.SceneGame.group)); vanitas.scene.SceneGame.scoreText.position.y -= 220; net.rsakane.paperjs.align.Align.center(vanitas.scene.SceneGame.gauge,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(vanitas.scene.SceneGame.scoreText)); vanitas.scene.SceneGame.gauge.update(); vanitas.Status.currentTurnColor = "#D41737"; vanitas.Status.initNextValueGroup(); var nextText = new paper.PointText(); nextText.fillColor = "white"; nextText.content = "NEXT:"; net.rsakane.paperjs.align.Align.topLeft(nextText,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(vanitas.scene.SceneGame.group),net.rsakane.paperjs.align.AlignType.topLeft); nextText.position.y -= 27; var text = new paper.PointText(); text.content = "99"; vanitas.Status.textBounds = text.bounds; vanitas.scene.SceneGame.nextValueTextGroup = new paper.Group(); var _g12 = 0; var _g6 = vanitas.Status.nextValueDisplayNum; while(_g12 < _g6) { var i1 = _g12++; var text1 = new paper.PointText(paperjs.lib._PointEx.PointEx_Impl_.fromFloatInt([0,0])); text1.justification = "center"; text1.fillColor = "white"; text1.content = vanitas.Status.nextValueGroup[i1] + ""; var line = paper.Path.Rectangle([0,0,vanitas.Status.textBounds.width,2]); if(i1 % 2 == 0) line.fillColor = "#D41737"; else line.fillColor = "#179ED4"; net.rsakane.paperjs.align.Align.center(line,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(text1)); line.position.y += text1.bounds.height / 2; var group = new paper.Group([line,text1]); group.position = new paper.Point(i1 * vanitas.Status.textBounds.width * 2,0); vanitas.scene.SceneGame.nextValueTextGroup.addChild(group); } var rectMask = paper.Path.Rectangle([0,0,vanitas.Status.textBounds.width * vanitas.Status.nextValueDisplayNum * 2 - vanitas.Status.textBounds.width,30]); net.rsakane.paperjs.align.Align.leftCenter(rectMask,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(vanitas.scene.SceneGame.nextValueTextGroup),net.rsakane.paperjs.align.AlignType.leftCenter); var textLineGroup = new paper.Group([rectMask,vanitas.scene.SceneGame.nextValueTextGroup]); textLineGroup.clipped = true; net.rsakane.paperjs.align.Align.leftCenter(textLineGroup,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(nextText),net.rsakane.paperjs.align.AlignType.rightCenter); textLineGroup.position.x += 10; vanitas.scene.SceneGame.nextValueTextDefaultLeft = vanitas.scene.SceneGame.nextValueTextGroup.bounds.left; var _g7 = vanitas.scene.SceneGame.level; switch(_g7) { case 1: vanitas.scene.SceneGame.com = new vanitas.com.COMLevel1(); break; case 2: vanitas.scene.SceneGame.com = new vanitas.com.COMLevel2(); break; case 3: vanitas.scene.SceneGame.com = new vanitas.com.COMLevel3(); break; default: vanitas.scene.SceneGame.com = new vanitas.com.COMLevel3(); } var player = new paper.Raster(vanitas.Setup.assetManager.get("IMAGE_PLAYER")); net.rsakane.paperjs.align.Align.topRight(player,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(vanitas.scene.SceneGame.group),net.rsakane.paperjs.align.AlignType.topLeft); player.position.x -= 15; var enemy = new paper.Raster(vanitas.Setup.assetManager.get("IMAGE_ENEMY" + vanitas.scene.SceneGame.level)); net.rsakane.paperjs.align.Align.topLeft(enemy,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(vanitas.scene.SceneGame.group),net.rsakane.paperjs.align.AlignType.topRight); enemy.position.x += 15; vanitas.scene.SceneGame.playerTurnRect = paper.Path.Rectangle([0,0,player.width,6]); vanitas.scene.SceneGame.playerTurnRect.fillColor = "#26595A"; net.rsakane.paperjs.align.Align.top(vanitas.scene.SceneGame.playerTurnRect,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(player),net.rsakane.paperjs.align.AlignType.bottom); vanitas.scene.SceneGame.playerTurnRect.position.y += 10; vanitas.scene.SceneGame.enemyTurnRect = vanitas.scene.SceneGame.playerTurnRect.clone(); net.rsakane.paperjs.align.Align.top(vanitas.scene.SceneGame.enemyTurnRect,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(enemy),net.rsakane.paperjs.align.AlignType.bottom); vanitas.scene.SceneGame.enemyTurnRect.position.y += 10; vanitas.scene.SceneGame.enemyTurnRect.visible = false; var ruleRect = paper.Path.Rectangle([0,0,100,20]); ruleRect.strokeColor = "#26595A"; ruleRect.fillColor = "#111111"; ruleRect.position = new paper.Point(20,20); var ruleText = new paper.PointText(); ruleText.fillColor = "white"; ruleText.content = "ルール"; ruleText.locked = true; net.rsakane.paperjs.align.Align.center(ruleText,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(ruleRect)); var ruleGroup = new paper.Group([ruleRect,ruleText]); net.rsakane.paperjs.align.Align.topRight(ruleGroup,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(vanitas.scene.SceneGame.group),net.rsakane.paperjs.align.AlignType.bottomRight); ruleGroup.position.y += 15; ruleGroup.onMouseEnter = function(event1) { ruleText.fillColor = "black"; ruleRect.fillColor = "#E0E0E0"; }; ruleGroup.onMouseLeave = function(event2) { ruleText.fillColor = "white"; ruleRect.fillColor = "#111111"; }; ruleGroup.onClick = function(event3) { net.rsakane.paperjs.scene.Scene.push(new vanitas.scene.SceneRule()); }; vanitas.Tile.clickable = true; } ,stop: function() { net.rsakane.paperjs.scene.SceneSprite.prototype.stop.call(this); createjs.Tween.get(this).to({ opacity : 0.6},500); } ,resume: function() { net.rsakane.paperjs.scene.SceneSprite.prototype.resume.call(this); createjs.Tween.get(this).to({ opacity : 1.0},500); } ,__class__: vanitas.scene.SceneGame }); vanitas.scene.SceneResult = function() { net.rsakane.paperjs.scene.SceneSprite.call(this); }; vanitas.scene.SceneResult.__name__ = true; vanitas.scene.SceneResult.__super__ = net.rsakane.paperjs.scene.SceneSprite; vanitas.scene.SceneResult.prototype = $extend(net.rsakane.paperjs.scene.SceneSprite.prototype,{ enter: function() { net.rsakane.paperjs.scene.SceneSprite.prototype.enter.call(this); createjs.Sound.play("result","none",0,0,0,0.2); var rect = paper.Path.Rectangle([0,0,vanitas.Screen.WIDTH,56]); rect.fillColor = "#26595A"; var rect2 = paper.Path.Rectangle([0,0,vanitas.Screen.WIDTH,50]); rect2.fillColor = "black"; var text = new paper.PointText(); text.fillColor = "white"; if(vanitas.Status.redValue < vanitas.Status.blueValue) text.content = "敗北した"; else if(vanitas.Status.blueValue < vanitas.Status.redValue) text.content = "勝利した"; else text.content = "引き分けになった"; var _g = 0; var _g1 = [rect,rect2,text]; while(_g < _g1.length) { var item = _g1[_g]; ++_g; net.rsakane.paperjs.align.Align.center(item,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView(this.view)); } var group = new paper.Group([rect,rect2,text]); net.rsakane.paperjs.align.Align.center(group,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView(this.view)); group.position.y -= 150; var rect3 = paper.Path.Rectangle([0,0,vanitas.Screen.WIDTH,56]); rect3.fillColor = "#57898B"; var rect4 = paper.Path.Rectangle([0,0,vanitas.Screen.WIDTH,50]); rect4.fillColor = "#26595A"; var retryShape = paper.Path.Rectangle([0,0,150,50]); retryShape.fillColor = "#26595A"; var retryText = new paper.PointText(); retryText.fillColor = "white"; retryText.content = "同じ難易度でリトライ"; var _g2 = 0; var _g11 = [retryShape,retryText]; while(_g2 < _g11.length) { var item1 = _g11[_g2]; ++_g2; net.rsakane.paperjs.align.Align.center(item1,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView(this.view)); } var retryButton = new paper.Group([retryShape,retryText]); var toTitleShape = retryShape.clone(); var toTitleText = new paper.PointText(); toTitleText.fillColor = "white"; toTitleText.content = "タイトルに戻る"; var _g3 = 0; var _g12 = [toTitleShape,toTitleText]; while(_g3 < _g12.length) { var item2 = _g12[_g3]; ++_g3; net.rsakane.paperjs.align.Align.center(item2,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView(this.view)); } var toTitleButton = new paper.Group([toTitleShape,toTitleText]); var _g4 = 0; var _g13 = [retryText,toTitleText]; while(_g4 < _g13.length) { var item3 = _g13[_g4]; ++_g4; item3.locked = true; } retryShape.onClick = function(event) { createjs.Sound.play("selectLevel"); net.rsakane.paperjs.scene.Scene.change(new vanitas.scene.SceneGame()); }; retryShape.onMouseEnter = function(event1) { retryShape.fillColor = "white"; retryText.fillColor = "#26595A"; createjs.Sound.play("menu","INTERRUPT_NONE",0,0,0,0.1); }; retryShape.onMouseLeave = function(event2) { retryShape.fillColor = "#26595A"; retryText.fillColor = "white"; }; toTitleShape.onClick = function(event3) { createjs.Sound.play("selectLevel"); net.rsakane.paperjs.scene.Scene.change(new vanitas.scene.SceneTitle()); }; toTitleShape.onMouseEnter = function(event4) { toTitleShape.fillColor = "white"; toTitleText.fillColor = "#26595A"; createjs.Sound.play("menu","INTERRUPT_NONE",0,0,0,0.1); }; toTitleShape.onMouseLeave = function(event5) { toTitleShape.fillColor = "#26595A"; toTitleText.fillColor = "white"; }; toTitleButton.position.x += toTitleButton.bounds.width; var buttonGroup = new paper.Group([retryButton,toTitleButton]); var _g5 = 0; var _g14 = [rect3,rect4,buttonGroup]; while(_g5 < _g14.length) { var item4 = _g14[_g5]; ++_g5; net.rsakane.paperjs.align.Align.center(item4,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView(this.view)); } var group2 = new paper.Group([rect3,rect4,buttonGroup]); net.rsakane.paperjs.align.Align.center(group2,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView(this.view)); } ,__class__: vanitas.scene.SceneResult }); vanitas.scene.SceneRule = function() { net.rsakane.paperjs.scene.SceneSprite.call(this); }; vanitas.scene.SceneRule.__name__ = true; vanitas.scene.SceneRule.__super__ = net.rsakane.paperjs.scene.SceneSprite; vanitas.scene.SceneRule.prototype = $extend(net.rsakane.paperjs.scene.SceneSprite.prototype,{ enter: function() { net.rsakane.paperjs.scene.SceneSprite.prototype.enter.call(this); var rect = paper.Path.Rectangle([0,0,390,390]); rect.fillColor = "#111111"; rect.strokeColor = "#26595A"; rect.strokeWidth = 2; net.rsakane.paperjs.align.Align.center(rect,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView(this.view)); var ruleText = new paper.PointText(); ruleText.fillColor = "#3B8B8C"; ruleText.content = "交互に盤面のタイルを開く\n\n" + "開いたタイルには上に表示されているNEXT値が入る\n\n" + "開いたタイルの周りに注目する\n\n" + "同じ色のタイルがあった\n" + " - そのタイルの値を一つ増やす\n" + "相手の色でかつ自分の値より小さい\n" + " - そのタイルを自分の色にする\n\n" + "タイルを全て開いた上で、色の合計数が多いほうが勝利"; net.rsakane.paperjs.align.Align.center(ruleText,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(rect)); this.onClick = function(event) { net.rsakane.paperjs.scene.Scene.pop(); }; } ,__class__: vanitas.scene.SceneRule }); vanitas.scene.SceneSelectLevel = function() { net.rsakane.paperjs.scene.SceneSprite.call(this); }; vanitas.scene.SceneSelectLevel.__name__ = true; vanitas.scene.SceneSelectLevel.__super__ = net.rsakane.paperjs.scene.SceneSprite; vanitas.scene.SceneSelectLevel.prototype = $extend(net.rsakane.paperjs.scene.SceneSprite.prototype,{ createParallelogramShape: function(width,height,rotation) { var hypoWidth = Math.cos(rotation * Math.PI / 180) * height; var frame = new paper.Path(); frame.moveTo(paperjs.lib._PointEx.PointEx_Impl_.fromFloatArray([0,height])); frame.lineTo(paperjs.lib._PointEx.PointEx_Impl_.fromFloatArray([hypoWidth,0])); frame.lineTo(paperjs.lib._PointEx.PointEx_Impl_.fromFloatArray([hypoWidth + width,0])); frame.lineTo(paperjs.lib._PointEx.PointEx_Impl_.fromFloatArray([width,height])); frame.lineTo(paperjs.lib._PointEx.PointEx_Impl_.fromFloatArray([0,height])); return frame; } ,enter: function() { net.rsakane.paperjs.scene.SceneSprite.prototype.enter.call(this); var width = 300; var height = 50; var frame = this.createParallelogramShape(width + 26,vanitas.Screen.HEIGHT,-70); frame.fillColor = "#57898B"; net.rsakane.paperjs.align.Align.center(frame,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView(this.view)); var frame1 = this.createParallelogramShape(width,vanitas.Screen.HEIGHT,-70); frame1.fillColor = "#26595A"; net.rsakane.paperjs.align.Align.center(frame1,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView(this.view)); var cancelMark = new paper.Path(); cancelMark.strokeColor = "#57898B"; cancelMark.strokeWidth = 4; cancelMark.moveTo(0,0); cancelMark.lineTo(40,40); cancelMark.lineTo(20,20); cancelMark.lineTo(40,0); cancelMark.lineTo(0,40); cancelMark.locked = true; var cancelShape = paper.Path.Rectangle([0,0,40,40]); cancelShape.fillColor = new paper.Color(0,0,0,0); cancelShape.addChild(cancelMark); cancelShape.onClick = function(event) { createjs.Sound.play("cancel","none",0,0,0,0.1); net.rsakane.paperjs.scene.Scene.pop(); }; cancelShape.onMouseEnter = function(event1) { cancelMark.strokeColor = "#89D6D9"; }; cancelShape.onMouseLeave = function(event2) { cancelMark.strokeColor = "#57898B"; }; var rect = paper.Path.Rectangle([0,0,vanitas.Screen.WIDTH,40]); rect.fillColor = "#5F9482"; net.rsakane.paperjs.align.Align.center(rect,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromView(this.view)); rect.position.y -= 200; var text = new paper.PointText(); text.fillColor = "white"; text.content = "難易度選択"; net.rsakane.paperjs.align.Align.center(text,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(rect)); var rotation = -70; var menuGroup = new paper.Group(); var textGroup = ["EASY","NORMAL","HARD"]; var _g1 = 0; var _g = textGroup.length; while(_g1 < _g) { var i = _g1++; var rect1 = this.createParallelogramShape(width,height,rotation); rect1.fillColor = "#26595A"; var content = textGroup[i]; var text1 = new paper.PointText(); text1.content = content; text1.fillColor = "white"; text1.justification = "center"; text1.locked = true; net.rsakane.paperjs.align.Align.center(text1,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(rect1)); var hypoWidth = Math.cos(rotation * Math.PI / 180) * height; var group = new paper.Group([rect1,text1]); group.position.x -= i * hypoWidth; group.position.y = i * height; menuGroup.addChild(group); group.name = "level" + (i + 1); group.onMouseEnter = function(event3) { var item = event3.target; item.fillColor = "#E0E0E0"; var group1; group1 = js.Boot.__cast(item.parent , paper.Group); var text2; text2 = js.Boot.__cast(group1.children[1] , paper.PointText); text2.fillColor = "#26595A"; createjs.Sound.play("menu","INTERRUPT_NONE",0,0,0,0.1); }; group.onMouseLeave = function(event4) { var item1 = event4.target; item1.fillColor = "#26595A"; var group2; group2 = js.Boot.__cast(item1.parent , paper.Group); var text3; text3 = js.Boot.__cast(group2.children[1] , paper.PointText); text3.fillColor = "white"; }; group.onClick = function(event5) { var group3; group3 = js.Boot.__cast(event5.target.parent , paper.Group); var _g2 = group3.name; switch(_g2) { case "level1": vanitas.scene.SceneGame.level = 1; break; case "level2": vanitas.scene.SceneGame.level = 2; break; case "level3": vanitas.scene.SceneGame.level = 3; break; default: vanitas.scene.SceneGame.level = 3; } createjs.Sound.play("selectLevel"); net.rsakane.paperjs.scene.Scene.change(new vanitas.scene.SceneGame()); }; } menuGroup.position = this.view.center; vanitas.Tile.clickable = true; } ,__class__: vanitas.scene.SceneSelectLevel }); vanitas.scene.SceneTitle = function() { net.rsakane.paperjs.scene.SceneSprite.call(this); }; vanitas.scene.SceneTitle.__name__ = true; vanitas.scene.SceneTitle.__super__ = net.rsakane.paperjs.scene.SceneSprite; vanitas.scene.SceneTitle.prototype = $extend(net.rsakane.paperjs.scene.SceneSprite.prototype,{ enter: function() { var _g = this; net.rsakane.paperjs.scene.SceneSprite.prototype.enter.call(this); var rect = paper.Path.Rectangle([220,0,380,400]); rect.fillColor = "#592559"; var text = new paper.PointText(); text.fontFamily = "Arial"; text.fillColor = "white"; text.content = "Vanitas"; text.fontSize = 36; net.rsakane.paperjs.align.Align.center(text,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(rect)); var rect1 = paper.Path.Rectangle([0,420,600,180]); rect1.fillColor = "#26595A"; var developNameText = new paper.PointText(); developNameText.fontFamily = "Arial"; developNameText.fillColor = "white"; developNameText.content = "Baroque Engine"; developNameText.fontSize = 20; net.rsakane.paperjs.align.Align.center(developNameText,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(rect1)); var materialAuthorText = new paper.PointText(); materialAuthorText.fontSize = 14; materialAuthorText.fontFamily = "Arial"; materialAuthorText.fillColor = "white"; materialAuthorText.content = "- 素材 -\nくらげ工匠 様\nOryx 様\n\n- 制作 -\nrsakane (BaroqueEngine)"; net.rsakane.paperjs.align.Align.center(materialAuthorText,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(rect1)); materialAuthorText.position.y += 210; var mask = paper.Path.Rectangle([0,420,600,180]); net.rsakane.paperjs.align.Align.center(mask,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(rect1)); var group = new paper.Group([mask,developNameText,materialAuthorText]); group.clipped = true; var rect2 = paper.Path.Rectangle([0,220,200,180]); rect2.fillColor = "#592559"; var text1 = new paper.PointText(); text1.fontFamily = "Arial"; text1.fillColor = "white"; text1.fontSize = 14; text1.content = "CREDIT"; net.rsakane.paperjs.align.Align.center(text1,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(rect2)); text1.locked = true; rect2.onMouseEnter = function(event) { var item = event.target; var color = item.fillColor; color.brightness += 0.2; createjs.Tween.get(developNameText.position).to({ y : 300},200); createjs.Tween.get(materialAuthorText.position).to({ y : 510},200); }; rect2.onMouseLeave = function(event1) { if(_g.locked) return; var item1 = event1.target; var color1 = item1.fillColor; color1.brightness -= 0.2; createjs.Tween.get(developNameText.position).to({ y : 510},200); createjs.Tween.get(materialAuthorText.position).to({ y : 720},200); }; var rect3 = paper.Path.Rectangle([0,0,200,200]); rect3.fillColor = "#26595A"; var text2 = new paper.PointText(); text2.fontFamily = "Arial"; text2.fillColor = "white"; text2.fontSize = 14; text2.content = "あそぶ"; net.rsakane.paperjs.align.Align.center(text2,net.rsakane.paperjs.align._Align.ItemView_Impl_.fromItem(rect3)); rect3.onMouseEnter = function(event2) { var item2 = event2.target; var color2 = item2.fillColor; color2.brightness += 0.2; }; rect3.onMouseLeave = function(event3) { if(_g.locked) return; var item3 = event3.target; var color3 = item3.fillColor; color3.brightness -= 0.2; }; rect3.onClick = function(event4) { var item4 = event4.target; var color4 = item4.fillColor; color4.brightness -= 0.2; createjs.Sound.play("startGame","none",0,0,0,0.1); net.rsakane.paperjs.scene.Scene.push(new vanitas.scene.SceneSelectLevel()); }; } ,stop: function() { net.rsakane.paperjs.scene.SceneSprite.prototype.stop.call(this); createjs.Tween.get(this).to({ opacity : 0.2},500); } ,resume: function() { net.rsakane.paperjs.scene.SceneSprite.prototype.resume.call(this); createjs.Tween.get(this).to({ opacity : 1.0},500); } ,__class__: vanitas.scene.SceneTitle }); var $_, $fid = 0; function $bind(o,m) { if( m == null ) return null; if( m.__id__ == null ) m.__id__ = $fid++; var f; if( o.hx__closures__ == null ) o.hx__closures__ = {}; else f = o.hx__closures__[m.__id__]; if( f == null ) { f = function(){ return f.method.apply(f.scope, arguments); }; f.scope = o; f.method = m; o.hx__closures__[m.__id__] = f; } return f; } Math.NaN = Number.NaN; Math.NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY; Math.POSITIVE_INFINITY = Number.POSITIVE_INFINITY; Math.isFinite = function(i) { return isFinite(i); }; Math.isNaN = function(i1) { return isNaN(i1); }; String.prototype.__class__ = String; String.__name__ = true; Array.__name__ = true; var Int = { __name__ : ["Int"]}; var Dynamic = { __name__ : ["Dynamic"]}; var Float = Number; Float.__name__ = ["Float"]; var Bool = Boolean; Bool.__ename__ = ["Bool"]; var Class = { __name__ : ["Class"]}; var Enum = { }; haxe.ds.ObjectMap.count = 0; net.rsakane.asset.AssetManager.COMPLETE = "complete"; net.rsakane.asset.AssetManager.PROGRESS = "progress"; net.rsakane.paperjs.scene.SceneManager.instance = new net.rsakane.paperjs.scene.SceneManager(); vanitas.Screen.WIDTH = 640; vanitas.Screen.HEIGHT = 640; vanitas.Status.nextValueDisplayNum = 4; vanitas.Status.maxTurn = 0; vanitas.Status.turn = 0; vanitas.Tile.WIDTH = 11; vanitas.Tile.HEIGHT = 11; vanitas._TileColor.TileColor_Impl_.Red = "#D41737"; vanitas._TileColor.TileColor_Impl_.Blue = "#179ED4"; vanitas._TileColor.TileColor_Impl_.None = "#000000"; Main.main(); })();
function avaliar() { }
import * as React from 'react' import Layout from '../../common/components/Layout' import SectionTagDetail from './section-tag-detail' import SectionTagOthers from './section-tag-others' import SectionPostByTags from './section-post-by-tag' function TagDetail(props) { const { match } = props return ( <Layout variant="detail"> <SectionTagDetail list={match.params} /> <SectionTagOthers list={match.params} /> <SectionPostByTags list={match.params} /> </Layout> ) } export default TagDetail
// components/dialog/dialog.js Component({ /** * 组件的属性列表 */ options: { multipleSlots: true // 在组件定义时的选项中启用多slot支持 }, properties: { }, /** * 组件的初始数据 */ data: { act: '' }, /** * 组件的方法列表 */ methods: { show () { this.setData({ act: 'dialog-act-in' }) }, hide () { this.setData({ act: 'dialog-act-out' }) } } })
function mostrar() { //var i; //i=parseInt(i); i=1; while(i<=10) { console.log(i); //Presionar F12 i++; } }//FIN DE LA FUNCIÓN
export const PORT = 8181; // Local MongoDB export const CONN_MONGODB_LOCAL = 'mongodb://localhost:27017/mongoose';
 $(document).ready(function () { // listar(); cargarPais(); cargarTipoDocumento(); cargarTipoPaciente(); cargarIngresoEconomico(); }); /*Limpia los campos*/ function limpiar() { $("#txtId").val(""); $("#txtNombre").val(""); $("#txtApellido").val(""); $("#txtDocumento").val(""); $("#txtCorreo").val(""); $("#dtFechaNacimiento").val(""); $("#selIdTipoDocumento").val("-1"); $("#selIdMunicipio").val("-1"); $("#txtUsuario").val(""); $("#txtPassword").val(""); $("#txtEstrato").val(""); $("#txtSisben").val(""); $("#selIdCotizante").val("-1"); $("#selIdTipoPaciente").val("-1"); $("#selIdIngreso").val("-1"); } /* Guarda informacion */ function guardar() { var id = ($("#txtId").val() == "") ? -1 : $("#txtId").val(); var nombre = $("#txtNombre").val(); var apellido = $("#txtApellido").val(); var documento = $("#txtDocumento").val(); var correo = $("#txtCorreo").val(); var fecha_nacimiento = $("#dtFechaNacimiento").val(); var id_tipo_doc = $("#selIdTipoDocumento").val(); var id_municipio = $("#selIdMunicipio").val(); var usuario = $("#txtUsuario").val(); var password = $("#txtPassword").val(); var estrato = $("#txtEstrato").val(); var sisben = $("#txtSisben").val(); var id_cotizante = 0; var id_tipo_paciente = $("#selIdTipoPaciente").val(); var id_ingreso = $("#selIdIngreso").val(); if (nombre != "" && apellido != "" && documento != "" && correo != "" && fecha_nacimiento != "" && id_tipo_doc != -1 && id_municipio != -1 && usuario != "" && password != "" && estrato != -1 && sisben != -1 && id_cotizante != -1 && id_tipo_paciente != -1 && id_ingreso != -1) { $.ajax({ type: 'POST', url: "/RegistrarPaciente/SaveInfo", data: { id: id, nombre: nombre, apellido: apellido, documento: documento, correo: correo, fecha_nacimiento: fecha_nacimiento, idTipoDoc: id_tipo_doc, idMunicipio: id_municipio, usuario: usuario, password: password, estrato: estrato, sisben: sisben, idCotizante: id_cotizante,idTipoPac: id_tipo_paciente, idIngreso: id_ingreso }, success: function (data) { var response = data.d[1]; switch (response) { case "Success": $('#myModal').modal('show'); info = "<p>Operacion exitosa</p>"; $('#avisos').append(info); limpiar(); listar(); break; case undefined: alert("Error en la operacion."); break; } }, error: function (jqXHR, textStatus, errorThrown) { alert("Error detectado: " + textStatus + "\nExcepcion: " + errorThrown); } }); } else { $('#myModal').modal('show'); info = "<p>Por favor ingresa todos los datos</p>"; $('#avisos').append(info); } } /* Busca informacion por el id de el usuario que este conectado*/ function buscar() { var id = $("#txtId").val(); if (id != "") { $.ajax({ type: 'POST', url: "/RegistrarPaciente/SearchInfo", data: { nombre: nombre }, success: function (data) { if (data.d.length > 0) { $("#txtNombre").val(data.d[0]); $("#txtApellido").val(data.d[1]); $("#txtDocumento").val(data.d[2]); $("#txtCorreo").val(data.d[3]); $("#dtFecha").val(data.d[4]); $("#selTipoDocmento").val(data.d[5]); $("#selPais").val(data.d[6]); cargarDepartamento(data.d[7]); cargarMunicipio(data.d[8]); $("#txtUsuario").val(data.d[9]); $("#txtPassword").val(data.d[10]); $("#txtEstrato").val(data.d[11]); $("#txtSisben").val(data.d[12]); $("#selIdCotizante").val(data.d[13]); $("#selIdTipoPaciente").val(data.d[14]); $("#selIdIngreso").val(data.d[15]); } else { alert("No se encuentra") } }, error: function (jqXHR, textStatus, errorThrown) { alert("Error detectado en buscar: " + textStatus + "\nExcepcion: " + errorThrown); } }); } else { alert("Ingresa el dato de busqueda"); } } function cargarPais() { $.ajax({ type: 'POST', url: "/Departamento/LoadPais", data: "", success: function (data) { if (data.d.length > 0) { var qantity = (data.d.length); var rows = parseInt(data.d[qantity - 1]); var cols = parseInt(data.d[qantity - 2]); qantity -= 2; var select = document.getElementById("selPais"); while (select.length > 1) { select.remove(select.length - 1); } var opt = null; for (var k = 0; k < qantity; k += cols) { opt = new Option(data.d[k + 1], data.d[k]); select.options[select.length] = opt; } select.value = -1; } else { alert("No se encuentra"); } }, error: function (jqXHR, textStatus, errorThrown) { alert("Error detectado: " + textStatus + "\nExcepcion: " + errorThrown); } }); } function cargarDepartamento(seleccion) { var pais = $("#selPais").val(); if (pais != -1) { $.ajax({ type: 'POST', url: "/Municipio/LoadDepartamento", data: { id_pais: pais }, success: function (data) { if (data.d.length > 0) { var qantity = (data.d.length); var rows = parseInt(data.d[qantity - 1]); var cols = parseInt(data.d[qantity - 2]); qantity -= 2; var select = document.getElementById("selDepartamento"); while (select.length > 1) { select.remove(select.length - 1); } var opt = null; for (var k = 0; k < qantity; k += cols) { opt = new Option(data.d[k + 1], data.d[k]); select.options[select.length] = opt; } if (seleccion) { $("#selDepartamento").val(seleccion); } else { select.value = -1; } } else { var select = document.getElementById("selDepartamento"); while (select.length > 1) { select.remove(select.length - 1); } } }, error: function (jqXHR, textStatus, errorThrown) { alert("Error detectado: " + textStatus + "\nExcepcion: " + errorThrown); } }); } } function cargarMunicipio(seleccion) { var depto = $("#selDepartamento").val(); if (depto != -1) { $.ajax({ type: 'POST', url: "/Municipio/LoadMunicipio", data: { id_departamento: depto }, success: function (data) { if (data.d.length > 0) { var qantity = (data.d.length); var rows = parseInt(data.d[qantity - 1]); var cols = parseInt(data.d[qantity - 2]); qantity -= 2; var select = document.getElementById("selIdMunicipio"); while (select.length > 1) { select.remove(select.length - 1); } var opt = null; for (var k = 0; k < qantity; k += cols) { opt = new Option(data.d[k + 1], data.d[k]); select.options[select.length] = opt; } if (seleccion) { $("#selIdMunicipio").val(seleccion); } else { select.value = -1; } } else { var select = document.getElementById("selIdMunicipio"); while (select.length > 1) { select.remove(select.length - 1); } } }, error: function (jqXHR, textStatus, errorThrown) { alert("Error detectado: " + textStatus + "\nExcepcion: " + errorThrown); } }); } } function cargarTipoDocumento() { $.ajax({ type: 'POST', url: "/TipoDocumento/LoadTipoDocumento", data: "", success: function (data) { if (data.d.length > 0) { var qantity = (data.d.length); var rows = parseInt(data.d[qantity - 1]); var cols = parseInt(data.d[qantity - 2]); qantity -= 2; var select = document.getElementById("selIdTipoDocumento"); while (select.length > 1) { select.remove(select.length - 1); } var opt = null; for (var k = 0; k < qantity; k += cols) { opt = new Option(data.d[k + 1], data.d[k]); select.options[select.length] = opt; } select.value = -1; } else { alert("No se encuentra"); } }, error: function (jqXHR, textStatus, errorThrown) { alert("Error detectado: " + textStatus + "\nExcepcion: " + errorThrown); } }); } function cargarTipoPaciente() { $.ajax({ type: 'POST', url: "/TipoAfiliacion/LoadTipoPaciente", data: "", success: function (data) { if (data.d.length > 0) { var qantity = (data.d.length); var rows = parseInt(data.d[qantity - 1]); var cols = parseInt(data.d[qantity - 2]); qantity -= 2; var select = document.getElementById("selIdTipoPaciente"); while (select.length > 1) { select.remove(select.length - 1); } var opt = null; for (var k = 0; k < qantity; k += cols) { opt = new Option(data.d[k + 1], data.d[k]); select.options[select.length] = opt; } select.value = -1; } else { alert("No se encuentra"); } }, error: function (jqXHR, textStatus, errorThrown) { alert("Error detectado: " + textStatus + "\nExcepcion: " + errorThrown); } }); } function cargarIngresoEconomico() { $.ajax({ type: 'POST', url: "/IngresoEconomico/LoadIngresoEconomico", data: "", success: function (data) { if (data.d.length > 0) { var qantity = (data.d.length); var rows = parseInt(data.d[qantity - 1]); var cols = parseInt(data.d[qantity - 2]); qantity -= 2; var select = document.getElementById("selIdIngreso"); while (select.length > 1) { select.remove(select.length - 1); } var opt = null; for (var k = 0; k < qantity; k += cols) { opt = new Option(data.d[k + 1], data.d[k]); select.options[select.length] = opt; } select.value = -1; } else { alert("No se encuentra"); } }, error: function (jqXHR, textStatus, errorThrown) { alert("Error detectado: " + textStatus + "\nExcepcion: " + errorThrown); } }); } /* Acobijar un usuario beneficiario */ function cobijarUsuario() { var idPaciente = 0; var documento = $("#txtDocumento").val(); if (documento != "") { $.ajax({ type: 'POST', url: "/RegistrarPaciente/CobijarUsuario", data: { idPaciente: idPaciente, documento: documento }, success: function (data) { var response = data.d[1]; switch (response) { case "Success": $('#myModal').modal('show'); info = "<p>Operacion exitosa</p>"; $('#avisos').append(info); limpiar(); listar(); break; case undefined: alert("Error en la operacion."); break; } }, error: function (jqXHR, textStatus, errorThrown) { alert("Error detectado: " + textStatus + "\nExcepcion: " + errorThrown); } }); } else { $('#myModal').modal('show'); info = "<p>Por favor ingresa todos los datos</p>"; $('#avisos').append(info); } } //function buscarPacienteNoCotizante() { // console.log('Historial.establecerBuscadorCliente()'); // var documento = $("#criterio-busqueda").val(); // //var options = { // // url: function (phrase) { // // return "/RegistrarPaciente/buscarPacienteNoCotizante/"; // // }, // // getValue: function (element) { // // return element.name; // // }, // // ajaxSettings: { // // dataType: "json", // // method: "POST", // // data: { // // documento: documento // // } // // }, // // preparePostData: function (data) { // // data.phrase = $("#criterio-busqueda").val(); // // return data; // // }, // // requestDelay: 400 // //}; // //$("#criterio-busqueda").easyAutocomplete(options); // var options = { // url: function (phrase) { // return "/RegistrarPaciente/buscarPacienteNoCotizante/"; // }, // getValue: function (element) { // return element.nombre; // }, // ajaxSettings: { // dataType: "json", // method: "POST", // data: { // documento: documento // } // }, // preparePostData: function (data) { // data.criterio = $("#criterio-busqueda").val(); // console.log(data); // return data; // }, // list: { // onSelectItemEvent: function () { // var value = $("#criterio-busqueda").getSelectedItemData().patients_id; // console.log(value); // $("#patients_id").val(value).trigger('input'); // $("#users_id").val($("#criterio-busqueda").getSelectedItemData().users_id).trigger('input'); // $("#identification").val($("#criterio-busqueda").getSelectedItemData().identification).trigger('input'); // } // }, // requestDelay: 400, // //theme: "plate-dark" // }; // $("#criterio-busqueda").easyAutocomplete(options); //} //buscarPacienteNoCotizante();
import {useEffect, useState} from 'react' import Header from '../../components/Header/Header' import './Home.css' import axios from 'axios'; import Select from '../../components/Select/Select'; import Loader from '../../components/Spinner'; import MovieCrawl from '../../components/MovieCrawl'; import Table from '../../components/Table'; import LandingPageImage from '../../components/LandingPageImage/LandingPageImage'; const Home = () => { const [isLoaded, setLoaded] = useState(false); const [spinner, setSpinner] = useState(false); const [movieDetails, setMovieDetails] = useState([]) const [characterDetails, setCharacterDetails] = useState([]) const [initialCharacterDetails, setInitialCharacterDetails] = useState([]) const [movies, setMovies] = useState([]) useEffect(()=> { axios.get("https://swapi.dev/api/films/") .then((res)=> { setLoaded(true) setMovies(res.data.results) }) .catch((error=> { console.log(error) })) }, []) const handleCallback = async (movie_id) =>{ const filteredMovies = movies.filter(item => item.episode_id === parseInt(movie_id)) setMovieDetails(filteredMovies) const characters = await fetchData(filteredMovies && filteredMovies[0]?.characters) setCharacterDetails(characters) setInitialCharacterDetails(characters) } const handleGenderCallback = (gender) =>{ // gender if (gender === 'All') { setCharacterDetails(initialCharacterDetails) } else { const filteredGender = initialCharacterDetails.filter(item => item.gender === gender.toLowerCase()) setCharacterDetails(filteredGender) } } const fetchData = async (characters) => { setSpinner(true) try { const response = await Promise.all( characters.map(url => axios.get(url).then(res => res.data)) ) setSpinner(false) return response } catch (error) { console.log("Error", error) } } return ( <div> <Header/> {isLoaded ? ( <> <LandingPageImage/> <h1 className="text-center mt-4 mb-4">Please select a movie</h1> <Select parentCallback = {handleCallback} movies={movies}/> {movieDetails.length ? <div className="container mt-5 mb-5"> <MovieCrawl movieDetails={movieDetails}/> <div className="m-4"> <Select gender parentCallback = {handleGenderCallback}/> </div> <Table characterDetails={characterDetails} spinner={spinner}/> </div> : '' } </> ) : ( <Loader/> )} </div> ) } export default Home
import logo from './logo.svg' import './App.css' import { useDispatch, useSelector } from 'react-redux' import { fetchPokemonsThunk } from './actions/pokeActions' import { useEffect } from 'react' import PokemonContainer from './components/PokemonContainer' function App () { const pokemons = useSelector(state => state.pokeUrls) const dispatch = useDispatch() useEffect(() => { dispatch(fetchPokemonsThunk('electric')) }, [dispatch]) const list = pokemons.map(value => ( <PokemonContainer url={value.pokemon.url} key={value.pokemon.name} name={value.pokemon.name} /> )) return ( <div className='App'> <header className='App-header'>{list}</header> </div> ) } export default App
import React, { Component } from "react"; import Coin from "../Coin/Coin"; import "./CoinFlipper.css"; const options = ["Yazı", "Tura"]; const getRandomElement = (arr) => { const randomItem = arr[Math.floor(Math.random() * arr.length)]; return randomItem; }; const findTotal = (arr, item) => { const targetItems = arr.filter((arrItem) => { return arrItem === item; }); return targetItems.length; }; class CoinFlipper extends Component { constructor(props) { super(props); // State üzerinde paranın başlangıçtaki durumunu veriyoruz, başlangıçta "tura" olsun. // Daha sonra şu anda paranın dönüp dönmeme durumunu da veriyoruz, başlangıçta para atılmamış olduğundan "false" olarak verdik. this.state = { side: options[0], flipping: false, flipsArray: [], }; } handleClick = () => { // "At!" butonuna tıkladığımızda paranın dönmesini istiyoruz, bu yüzden "flipping" durumunu "true" yapıyoruz. this.setState({ flipping: true }); const randomElement = getRandomElement(options); // 1 saniye kadar dönmesi yeterli, bu yüzden 1 saniye sonra "flipping" durmunu tekrar "false" yapıyoruz. setTimeout( () => this.setState({ flipping: false }, () => { this.setState({ side: randomElement, // flipsArray: [...this.state.flipsArray].concat([randomElement]), flipsArray: this.state.flipsArray.concat(randomElement), }); }), 500 ); }; render() { return ( <div className="CoinFlipper"> <h1>Yazı mı Tura mı?</h1> <Coin side={this.state.side} flipping={this.state.flipping} /> <button onClick={this.handleClick}>At!</button> <p> Toplam <strong> {this.state.flipsArray.length} </strong> atıştan <div> {options.map((option) => { return ( <div key={option}> <strong> {findTotal(this.state.flipsArray, option)} </strong> {option} </div> ); })} </div> </p> </div> ); } } export default CoinFlipper;
import React, { Component } from "react"; import api from "../../api"; import Search from "./Search"; import { Link } from "react-router-dom"; class Projects extends Component { constructor(props) { super(props); this.state = { technologyused: "", projects: [], nbOfLikes: 0, search: "" }; this.colors = ["blue", "green"]; this.handleClick = this.handleClick.bind(this); // this.handleInputChange = this.handleInputChange.bind(this); this.handleSearch = this.handleSearch.bind(this); } handleClick() { this.setState(prevState => ({ nbOfLikes: prevState.nbOfLikes + 1 })); } deleteProject(_creator) { api.deleteProject(_creator).then(data => { this.setState({ _creator: this.state._creator.filter(c => c._id !== _creator), message: data.message }); // Remove the message after 3 seconds setTimeout(() => { this.setState({ message: null }); }, 3000); }); } handleInputChange(e) { this.setState({ [e.target.name]: e.target.value.substr(0, 20) }); } handleSearch(searchValue) { this.setState({ search: searchValue }); } render() { let colorIndex = this.state.nbOfLikes % this.colors.length; let lowerSearch = this.state.search.toLowerCase(); let uppersearch = this.state.search.toUpperCase(); let filteredProjects = this.state.projects; return ( <div className="container col-md-18 mb-12"> <div> <h2 className="m-5 p-3 mb-2 bg-dark text-white rounded"> View All Projects </h2>{" "} <Search value={this.state.search} onSearch={this.handleSearch} /> <hr /> </div> <div className="projects d-flex flex-wrap card-group shadow-lg p-2 mb-3 bg-light rounded"> <div className=" row justify-content-center"> {filteredProjects .filter((project, i) => { {/* if ( project.name.toLowerCase().includes(lowerSearch, uppersearch) ) return true; */} for (let i = 0; i < project.technologyused.length; i++) { if ( project.technologyused[i].includes(lowerSearch, uppersearch) ) return true; } return false; }) .map((p, i) => ( <div className="col-sm-4 justify-content-center card-group"> <div className="p-2 shadow-lg p-3 mb-5 bg-light rounded card"> <img className="grow card-img-top" src={p.projectimage} // width="10px" // height="100px" />{" "} <div className="card-body "> <strong> {" "} <h6 className="card-text font-weight-bold"> {" "} {p.name} </h6> </strong> <strong className="card-text">Brief Description: </strong> <pre className="card-text"> {" "} <i> {p.description} </i> </pre> <strong className="font-weight-bold card-text"> Technology(s) used: </strong>{" "} <pre className="card-text">{p.technologyused} </pre> <a className="card-text" href={p.projectlink} target="_blank" > Demo Link{" "} </a> <br /> <a href={p.githublink} target="_blank" className="grow card-text" > Github </a> <br /> <strong className="card-text">Creator:</strong>{" "} <h6 className="card-text"> {p.username}</h6>{" "} <pre className="card-text"> {" "} <Link to={"/profile/" + p.username}>About Me</Link>{" "} </pre> <pre className="card-text"> <i> {" "} <span className="card-text"> {p.date ? p.date.slice(0, 10) : ""} </span> </i> </pre> </div> <i className="card-text"> <i class="fas fa-code" /> <i class="fas fa-laptop-code" />{" "} <i class="fas fa-code" /> </i> </div> </div> ))} </div> </div> {this.state.message && <div className="info">{this.state.message}</div>} </div> ); } componentDidMount() { api .getProjects() .then(projects => { console.log(projects); this.setState({ projects: projects }); }) .catch(err => console.log(err)); } } export default Projects;
/** * Module dependencies. */ var $ = require('jquery') var utils = require('./utils') /** * Expose `directives`. */ var directives = module.exports = {} /** * Basic directives. */ $.extend(directives, { bind: function ($el, value, props) { $el.text(this.compile(value)) }, show: function ($el, value, props) { if (!this.compile(value)) $el.remove() }, hide: function ($el, value, props) { if (this.compile(value)) $el.remove() }, 'class': function ($el, value, props) { $.each(this.compile(value), function (className, expr) { if (expr) { $el.addClass(utils.kebabCase(className)) } else { $el.removeClass(className) } }) }, style: function ($el, value, props) { $el.css(this.compile(value)) } }) /** * Repeat directive. */ directives.repeat = function ($el, value, props) { var self = this var Template = this.Template var match = value.match(/(.*)\S*in\S*(.*)/) if (!match) throw new Error('Invalid Syntax for :repeat') var needle = match[1].trim() var haystack = this.compile(match[2].trim()) // Make sure the haystack is a collection if (!($.isArray(haystack) || $.isPlainObject(haystack))) { throw new Error('Haystack `' + match[2].trim() + '` must be a collection') } // Make sure the haystack has at least one value var total = $.isArray(haystack) ? haystack.length : Object.keys(haystack).length if (!total) return $el.remove() // Start the loop $el.removeAttr(':repeat') var template = new Template() var $collection = $('<div>') var counter = 0 $.each(haystack, function (key, val) { template.setSource($el.prop('outerHTML')) template.context = self.context template.vars = $.extend(template.vars, self.vars, { $index: counter, $key: key, $total: total, $first: counter === 0, $last: counter === total - 1, $even: counter % 2 === 0, $odd: !(counter % 2 === 0), $middle: counter > 0 && counter < (total - 1) }) template.vars[needle] = val $collection.append(template.parse()) counter += 1 }) $el.replaceWith($collection.html()) } /** * Directives that set its attribute if the given expression is truthy. */ $.each(['selected', 'checked', 'disabled'], function (index, dir) { directives[dir] = function ($el, value, props) { if (this.compile(value)) { $el.attr(dir, true) } else { $el.removeAttr(dir) } } }) /** * Directives that replace the attribute values by the expression given. */ $.each(['href', 'src', 'value', 'title', 'alt'], function (index, dir) { directives[dir] = function ($el, value, props) { $el.attr(dir, this.compile(value)) } }) /** * Directives for events. */ var events = [ // Mouse events 'click', 'dbclick', 'hover', 'contextmenu', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseup', 'toggle', // Keyboard events 'keydown', 'keypress', 'keyup', // Form events 'blur', 'change', 'focus', 'focusin', 'focusout', 'select', 'submit', // Document loading events 'load' ] $.each(events, function (index, eventName) { directives[eventName] = function ($el, value, props) { registerEvent.call(this, $el, eventName, value) } }) function registerEvent ($el, eventName, expression) { var self = this var view = this.context var template = new self.Template() template.context = self.context template.vars = $.extend({}, self.vars) var fn = function eventListener (event) { $.extend(template.vars, { $target: $(event.target), $event: event }) template.compile(expression) } view._directiveEvents.push({ type: eventName, callback: fn }) $el.attr('data-view-event-listener', view._directiveEvents.length - 1) } /** * Transclusion. */ directives.transclude = function ($el, value, props) { if (!this.context.transclusion) return $el.html(this.context.transclusion) } /** * Data directives for create references for form controls. */ directives.data = function ($el, value, props) { var controls = ['input', 'textarea', 'select'] var tagName = $el[0].tagName.toLowerCase() if (controls.indexOf(tagName) === -1) return if (!value) value = $el.attr('name') $el.attr('data-view-reference', value) }
/** * * @author Anass Ferrak aka " TheLordA " <ferrak.anass@gmail.com> * GitHub repo: https://github.com/TheLordA/Instagram-Clone * */ const express = require("express"); const morgan = require("morgan"); const cors = require("cors"); const compression = require("compression"); const helmet = require("helmet"); const connectDB = require("./config/db.config"); /** * -------------- GENERAL SETUP ---------------- */ // Gives us access to variables set in the .env file via `process.env.VARIABLE_NAME` syntax require("dotenv").config(); // Connection to DB connectDB(); // Create the Express application object const app = express(); // Compress the HTTP response sent back to a client app.use(compression()); //Compress all routes // Use Helmet to protect against well known vulnerabilities app.use(helmet()); // use Morgan dep in dev mode app.use(morgan("dev")); // Set up cors to allow us to accept requests from our client app.use( cors({ origin: "http://localhost:3000", // <-- location of the react app were connecting to credentials: true, }) ); // Parsers app.use(express.json({ limit: "50mb" })); app.use(express.urlencoded({ extended: true })); /** * -------------- ROUTES ---------------- */ require("./routes/auth.route")(app); require("./routes/post.route")(app); require("./routes/user.route")(app); /** * -------------- SERVER ---------------- */ // Specify the PORT which will the server running on const PORT = process.env.PORT || 3001; // Disabling Powered by tag app.disable("x-powered-by"); app.listen(PORT, () => { console.log(`Server is running in ${process.env.NODE_ENV} mode, under port ${PORT}.`); });
/* Copyright 2015 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License */ var channel = require('cordova/channel'), utils = require('cordova/utils'), exec = require('cordova/exec'); module.exports = { pictureLocation: null, pictureList: [], getInfo: function (successCallback, errorCallback) { var me = this; exec(function(info) { me.pictureLocation = info.pictureLocation; me.pictureList = info.pictureList; successCallback(); }, errorCallback, "IntelXDKCamera", "getInfo", []); }, takePicture: function(quality, saveToLib, picType) { if(quality == undefined || quality == null) quality = 70; // default else if((quality<1) || (quality>100)) throw(new Error("Error: IntelXDK.camera.takePicture, quality must be between 1-100.")); if(saveToLib == undefined || saveToLib == null) saveToLib = true; if(typeof(picType) == "undefined" || picType == null) picType = "jpg"; else { if(typeof(picType) != "string") throw(new Error("Error: IntelXDK.camera.takePicture, picType must be a string.")); if((picType.toLowerCase() != "jpg") && (picType.toLowerCase() != "png")) throw(new Error("Error: IntelXDK.camera.takePicture, picType must be 'jpg' or 'png'.")); } //IntelXDKCamera.takePicture(quality, saveToLib, picType); exec(function(loc) { //alert('in return'); }, null, "IntelXDKCamera", "takePicture", [quality, saveToLib, picType]); }, takeFrontPicture: function(quality, saveToLib, picType) { if(quality == undefined || quality == null) quality = 70; // default else if((quality<1) || (quality>100)) throw(new Error("Error: IntelXDK.camera.takeFrontPicture, quality must be between 1-100.")); if(saveToLib == undefined || saveToLib == null) saveToLib = true; if(typeof(picType) == "undefined" || picType == null) picType = "jpg"; else { if(typeof(picType) != "string") throw(new Error("Error: IntelXDK.camera.takeFrontPicture, picType must be a string.")); if((picType.toLowerCase() != "jpg") && (picType.toLowerCase() != "png")) throw(new Error("Error: IntelXDK.camera.takeFrontPicture, picType must be 'jpg' or 'png'.")); } //IntelXDKCamera.takePicture(quality, saveToLib, picType); exec(function(loc) { //alert('in return'); }, null, "IntelXDKCamera", "takeFrontPicture", [quality, saveToLib, picType]); }, importPicture: function() { //IntelXDKCamera.importPicture(); exec(function(loc) { //alert('in return'); }, null, "IntelXDKCamera", "importPicture", []); }, deletePicture: function(picURL) { if(picURL == undefined || picURL == null) throw(new Error("Error: intel.xdk.camera.deletePicture, call with a picURL")); if(typeof(picURL) != "string") throw(new Error("Error: intel.xdk.camera.deletePicture, picURL must be a string.")); //IntelXDKCamera.deletePicture(picURL); exec(function(loc) { //alert('in return'); }, null, "IntelXDKCamera", "deletePicture", [picURL]); }, clearPictures: function() { //IntelXDKCamera.clearPictures(); exec(function(loc) { //alert('in return'); }, null, "IntelXDKCamera", "clearPictures", []); }, getPictureList: function() { var list = []; for(var picture in intel.xdk.camera.pictureList) { list.push(intel.xdk.camera.pictureList[picture]); } return list; }, getPictureURL: function(filename) { var localURL = undefined; var found = false; for(var picture in intel.xdk.camera.pictureList) { if(filename == intel.xdk.camera.pictureList[picture]) { found=true; break; } } if(found) localURL = intel.xdk.camera.pictureLocation+'/'+filename; return localURL; }, // Private function to switch the plugin native-code object methods into a "testing" state. // Arguments: // ("off") - Turn off testing mode. // ("ignore") - Methods should do nothing. // ("succeed", t) - Methods should exhibit success behavior after t milliseconds. // ("fail", t) - Methods should exhibit failure behavior after t milliseconds. // ("cancel", t) - Methods should exhibit cancellation behavior after t milliseconds. // _setTestMode: function(mode, delay) { exec(null, null, "IntelXDKCamera", "setTestMode", [mode || "off", delay || 0]); } } //pictureList maintenance var me = module.exports; document.addEventListener('intel.xdk.camera.internal.picture.add', function(e){ me.pictureList.push(e.filename); }, false); document.addEventListener('intel.xdk.camera.internal.picture.remove', function(e){ var index = me.pictureList.indexOf(e.filename); while (index > -1) { me.pictureList.splice(index, 1); index = me.pictureList.indexOf(e.filename); } }, false); document.addEventListener('intel.xdk.camera.internal.picture.clear', function(e){ me.pictureList = []; }, false); channel.createSticky('IntelXDKCamera'); channel.waitForInitialization('IntelXDKCamera'); channel.onCordovaReady.subscribe(function() { me.getInfo(function() { channel.IntelXDKCamera.fire(); },function(e) { utils.alert("[ERROR] Error initializing Intel XDK Camera: " + e); }); });
import React from 'react' const Monthselect = ({jump}) => { return ( <select className="form-control" name="month" id="month" onChange={jump}> <option value='0'>Jan</option> <option value='1'>Feb</option> <option value='2'>Mar</option> <option value='3'>Apr</option> <option value='4'>May</option> <option value='5'>Jun</option> <option value='6'>Jul</option> <option value='7'>Aug</option> <option value='8'>Sep</option> <option value='9'>Oct</option> <option value='10'>Nov</option> <option value='11'>Dec</option> </select> ) } export default Monthselect
"use strict"; const assert = require("assert").strict; const chalk = require("chalk"); const errors = require("lib/errors"); const { testLines } = require("./lib/factorio/lines"); const clusterctl = require("../clusterctl.js"); const mock = require("./mock"); describe("clusterctl", function() { describe("formatOutputColored()", function() { it("should pass the test lines", function() { // Ensure tests get uncoloured output. let old = chalk.level; chalk.level = 0; for (let [reference, output] of testLines) { let line = clusterctl._formatOutputColored(output); assert.deepEqual(line, reference); } chalk.level = old; }); }); let mockConnector = new mock.MockConnector(); mockConnector.on("send", function(message) { if (message.type === "list_instances_request") { this.emit("message", { seq: 1, type: "list_instances_response", data: { seq: message.seq, list: [{ id: 57, assigned_slave: 4, name: "Test Instance" }], }, }); } }); let testControl = new clusterctl._Control(mockConnector); describe("resolveInstance", function() { it("should pass an integer like string back", async function() { assert.equal(await clusterctl._resolveInstance(null, "123"), 123); }); it("should resolve an instance name with the master server", async function() { assert.equal(await clusterctl._resolveInstance(testControl, "Test Instance"), 57); }); it("should throw if instance is not found", async function() { await assert.rejects( clusterctl._resolveInstance(testControl, "invalid"), new errors.CommandError("No instance named invalid") ); }); }); });
var searchData= [ ['querysizeforcapheight',['querySizeForCapHeight',['../classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1helpers_1_1_p_d_e_typeface.html#a91a7cbb3eaeb1593019c1ca650fc8355',1,'de::telekom::pde::codelibrary::ui::helpers::PDETypeface']]] ];
#!/usr/bin/env node import 'source-map-support/register'; import * as cdk from '@aws-cdk/core'; import { BaseStack } from '../lib/base-stack'; import { IngressControllerStack } from '../lib/ingress-controller-stack'; const app = new cdk.App(); new BaseStack(app, 'EKSObservabilityBase', {}); new IngressControllerStack(app, 'EKSObservabilityIngressController', {});
exports.seed = function(knex) { return knex('steps').insert([ { step_number: 1, instructions: 'stir in bricks', recipe_id: 1, } ]); }
const rp = require('request-promise'); const config = require('../config/newsapi.json'); class NewsApiProvider { constructor () { this.API_KEY = config.api_key; } async getTopList (category, limit) { let url = `${config.hostname}/top-headlines?country=pl&apiKey=${this.API_KEY}`; if (category) url += `&category=${category}`; if (limit) url += `&pageSize=${limit}`; let result = await rp(url); result = JSON.parse(result); if (result && result.articles && result.articles.length) { result.articles = result.articles.filter((el) => { return el.title && el.description && el.url && el.urlToImage && el.publishedAt; }); return result; } else { return { status: 0, articles: [] }; } } } module.exports = NewsApiProvider;
// ---[ API ]------------------------------------------------------------------- function mouse() { return [MX,MY,M1,M2] } // ---[ MOUSE ]----------------------------------------------------------------- var MX = -1 var MY = -1 var M1 = 0 // status -> 3210 3:down 2:held 1:up 0:none var M2 = 0 // status -> 3210 3:down 2:held 1:up 0:none var MW = 0 function on_mouse_move(e) { var bcr = cnv.getBoundingClientRect() var bcr_left = bcr.left var bcr_top = bcr.top var bcr_w = bcr.width var bcr_h = bcr.height var ratio = bcr_h/fc.h var width = fc.w * ratio var bcr_left = 0.5*(bcr_w-width) MX = (e.clientX - bcr_left) / ratio MY = (e.clientY - bcr_top) / ratio } function on_mouse_up(e) { if (e.button==0) { M1 = 1 } else if (e.button==2) { M2 = 1 } } function on_mouse_down(e) { if (e.button==0) { M1 = 3 } else if (e.button==2) { M2 = 3 } } function on_wheel(e) { if (e.deltaY > 0) { MW = 1 } else if (e.deltaY < 0) { MW = -1 } else { MW = 0 } } function mouse_after() { switch (M1) { case 3: M1=2; break case 1: M1=0; break } switch (M2) { case 3: M2=2; break case 1: M2=0; break } } _after.push(mouse_after) document.addEventListener('mousemove',on_mouse_move) cnv.addEventListener('mouseup',on_mouse_up) cnv.addEventListener('mousedown',on_mouse_down) cnv.addEventListener('wheel',on_wheel) cnv.addEventListener("contextmenu",function(e){e.preventDefault()})
export default { name: 'themify', mediaPlayer: { play: 'ti-control-play', pause: 'ti-control-pause', volumeOff: 'ti-na', volumeDown: 'ti-volume', volumeUp: 'ti-volume', settings: 'ti-settings', speed: 'ti-dashboard', language: 'ti-layout-media-overlay', selected: 'ti-check', fullscreen: 'ti-fullscreen', fullscreenExit: 'ti-close', bigPlayButton: 'ti-control-play' } }
var express = require("express"); var mysql = require('mysql'); var app = express(); var controllers = require('./controller/index'); var bodyParser = require('body-parser'); var passport = require('passport'); var strategy = require('./passport/strategy'); app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Accept'); next(); }); app.use(bodyParser.json()); app.use(controllers); passport.use(strategy); app.use(passport.initialize()); app.listen(3001, function(){ console.log('Rest API Started on port 3001...'); });
define([ 'jquery', 'underscore', 'backbone', 'prismic', 'prismic-helper', 'prismic-configuration', 'animations', 'toolbar', 'templates', 'moment' ], function($, _, Backbone, Prismic, Helpers, Configuration, Animations, PreviewToolbar, Templates, moment) { var BlogRouter = Backbone.Router.extend({ /** Routes **/ routes: { '(~:ref)' : 'posts', 'categories(~:ref)/*category' : 'posts', 'posts(~:ref)/:id/:slug' : 'postDetail', }, /** Home page **/ posts: Helpers.prismicRoute(function(ctx, category) { ctx.api.form('blog').ref(ctx.ref).query(category ? '[[:d = at(my.blog-post.category, "' + category + '")]]' : '').submit(function(err, posts) { if (err) { Configuration.onPrismicError(err); return; } $('.main').html( Templates.Posts({ posts: posts, moment: moment, ctx: ctx }) ); }); }), /** Post detail **/ postDetail: Helpers.prismicRoute(function(ctx, id, slug) { Helpers.getDocument(ctx, id, function(err, post) { if (err) { Configuration.onPrismicError(err); return; } // Retrieve the related products Helpers.getDocuments(ctx, // Get all related product ids _.chain(post.getAll('blog-post.relatedproduct').map(function(link) { if(link.document.type == "product" && !link.isBroken) { return link.document.id; } }).filter(function(link) { return link; })).value(), // Then function(err, relatedProducts) { if (err) { Configuration.onPrismicError(err); return; } // Retrieve the related posts Helpers.getDocuments(ctx, // Get all related product ids _.chain(post.getAll('blog-post.relatedpost').map(function(link) { if(link.document.type == "blog-post" && !link.isBroken) { return link.document.id; } }).filter(function(link) { return link; })).value(), // Then function(err, relatedPosts) { if (err) { Configuration.onPrismicError(err); return; } $('.main').html( Templates.PostDetail({ post: post, relatedProducts: relatedProducts, relatedPosts: relatedPosts, moment: moment, ctx: ctx }) ); } ); } ); }); }) }); return { run: function() { var blog = new BlogRouter(); // -- Scroll on page change blog.on('route', Animations.scrollTop); /** Called on first route to init the layout **/ Helpers.setupLayout(blog, function(ctx) { $(document.body).html( Templates.BlogLayout({ ctx: ctx, categories: [ "Announcements", "Do it yourself", "Behind the scenes" ] }) ); new PreviewToolbar({ el: $('#toolbar'), ctx: ctx }); }); return Backbone.history.start(); } }; });
const { Stack } = require('./Stack'); function divideBy2(number) { var remStack = new Stack(), rem, binaryString = ''; while (number > 0) { rem = Math.floor(number % 2); remStack.push(rem); number = Math.floor(number / 2); } while ( ! remStack.isEmpty()) { binaryString += remStack.pop().toString(); } return binaryString; } console.log(divideBy2(1024));
import Header from "./views/Header" import Footer from "./views/Footer" import Home from "./views/Home" import About from "./views/About" import Map from "./views/Map" import Teacher from "./views/Teacher" import Teachers from "./views/Teachers" import Class from "./views/Class" import Classes from "./views/Classes" import MatchMe from "./views/MatchMe" import Schedule from "./views/Schedule" import Signup from "./views/Signup" import User from './views/dashboard/User' import Login from "./views/Login" import Register from "./views/Register" import Dashboard from "./views/Dashboard" import EditClass from "./views/dashboard/EditClass" import CreateClass from "./views/dashboard/CreateClass" import EditTeacher from "./views/dashboard/EditTeacher" import CreateTeacher from "./views/dashboard/CreateTeacher" import { createPractice, editPractice, deletePractice, editUser, deleteUser, editTeacher, setActiveNavItem, initDatetimePicker } from './functions'; import { adminCreateTeacher, adminEditTeacher, initUpload } from './functionsAdmin'; const loader = document.getElementById('loader'); const pathToRegex = path => new RegExp("^" + path.replace(/\//g, "\\/").replace(/:\w+/g, "(.+)") + "$"); const getParams = match => { const values = match.result.slice(1); const keys = Array.from(match.route.path.matchAll(/:(\w+)/g)).map(result => result[1]); return Object.fromEntries(keys.map((key, i) => { return [key, values[i]]; })); }; // Navigate to url and initiate router const navigateTo = url => { // Abort if current route is equal to clicked route if (url === location.href) { return; } // Activate loader as long as data is getting fetched loader.classList.add("is-active"); // Use history API history.pushState(null, null, url); router(); }; // Frontend routes const router = async () => { const routes = [ { path: "/", view: Home }, { path: "/login", view: Login, js: 'login' }, { path: "/signup", view: Register, js: 'register' }, { path: "/about", view: About }, { path: "/map", view: Map, js: 'map' }, { path: "/teachers", view: Teachers }, { path: "/teachers/:id", view: Teacher }, { path: "/classes", view: Classes }, { path: "/classes/:id", view: Class }, { path: "/matchme", view: MatchMe, js: 'matchme' }, { path: "/schedule", view: Schedule, js: 'schedule' }, { path: "/signup/:id", view: Signup, js: 'signup' }, { path: "/dashboard", view: Dashboard, js: 'dashboard' }, { path: "/dashboard/classes/create", view: CreateClass, js: 'createClass' }, { path: "/dashboard/classes/:id", view: EditClass, js: 'editClass' }, { path: "/dashboard/teacher/create", view: CreateTeacher, js: 'createTeacher' }, { path: "/dashboard/teacher/:id", view: EditTeacher, js: 'editTeacher' }, ]; // Check if user is loggedIn and if so, which role the user has const isLoggedIn = await new User().isLoggedIn(); let role, token; if (isLoggedIn) { role = await new User().getRole() token = window.localStorage.getItem("auth-token"); }; // Test each route for potential match const potentialMatches = routes.map(route => { return { route: route, result: location.pathname.match(pathToRegex(route.path)) }; }); let match = potentialMatches.find(potentialMatch => potentialMatch.result !== null); // Catch unmatched url // Redirect to first route (Home) if (!match) { // If path is /logout run logout method from User if (location.pathname === '/logout') { new User().logout(token); return; } // Set route to first in routes array, Home in this case match = { route: routes[0], result: [location.pathname] }; } // Create new instance of the view at matched route... const view = new match.route.view(getParams(match)); const header = new Header(); const footer = new Footer(); // ...and call its getHtml class method document.querySelector("#header").innerHTML = await header.getHtml(isLoggedIn, role); document.querySelector("#app").innerHTML = await view.getHtml(isLoggedIn, role); document.querySelector("#footer").innerHTML = await footer.getHtml(); // After html content is set, run needed js for matching route switch (match.route.js) { case 'login': { new Login().initLoginForm(); break; } case 'register': { new Register().initRegisterForm(); break; } case 'map': { new Map().initMap(); break; } case 'matchme': { new MatchMe().initForms(); break; } case 'schedule': { new Schedule().initCalendar(); break; } case 'dashboard': { editUser(token); deleteUser(token); editTeacher(token); deletePractice(token); break; } case 'createClass': { createPractice(token); initDatetimePicker(); break; } case 'editClass': { editPractice(token); initDatetimePicker(); break; } case 'createTeacher': { adminCreateTeacher(token); initUpload(token); break; } case 'editTeacher': { adminEditTeacher(token); initUpload(token); break; } } // Finally, highlight active navigation link setActiveNavItem(); // When everything is loaded, deactivate loader loader.classList.remove("is-active"); }; // Run router if user navigates in browser window.addEventListener("popstate", router); // Fetch all clicks on data-links // Prevent page reload // Let router handle the navigation document.addEventListener("DOMContentLoaded", () => { // Catch all clicks on data-link anchors document.body.addEventListener("click", e => { if (e.target.matches("[data-link]")) { e.preventDefault(); navigateTo(e.target.href); `` } }); document.body.addEventListener("submit", e => { loader.classList.add("is-active"); }); // Initiate router when DOMContentLoaded router(); });
const TelegramBot = require('node-telegram-bot-api'); const { TOKEN } = require('./config'); const bot = new TelegramBot(TOKEN, { polling: true }); const crawler = require('./src/crawlers/reddit'); (async () => { bot.onText(/\/NadaPraFazer (.*)/, async (msg, match) => { try { const subreddits = match[1].split(';'); const res = await Promise.all(subreddits.map(async (subreddit) => crawler(subreddit))); bot.sendMessage(msg.chat.id, res.join('')).catch((error) => { if (error.response.body.description === 'Bad Request: message is too long') { Object.values(res).forEach((elem) => { bot.sendMessage(msg.chat.id, elem).catch((error2) => { console.log(error2.code); console.log(error2.response.body); bot.sendMessage(msg.chat.id, 'Erro. Tente novamente mais tarde.'); }); }); } else { console.log(error.code); console.log(error.response.body); bot.sendMessage(msg.chat.id, 'Erro. Tente novamente mais tarde.'); } }); } catch (err) { console.log(err); bot.sendMessage(msg.chat.id, 'Erro. Tente novamente mais tarde.'); } }); })();
import React from "react" import "../styling/styles.css" import Layout from "../components/layout" import SEO from "../components/seo" const About = () => ( <Layout> <SEO title="about" /> <div className="about-page-container"> <h1 className="about-title"> Hi! I'm Julien 👋 </h1> <h3 className="description-text"> I'm a full stack developer. I've recently graduated from Red Academy's Full Stack Development program where I learned React, Redux, Apollo, GraphQL, PostgreSQL, React Native, and more. </h3> <p> Previously, I've been an intern with CBC where I worked with the interactive team as a developer to build applications and visualizations on the web. I also worked with reporters and journalists to gather and clean data. <br /> <br /> For my first internship, I was a JavaScript developer with Flourish (Flourish is a data visualization software for creating interactive visualizations on the web). At Flourish I used JavaScript and D3 to build, fix, and improve Flourish templates. I was the lead developer for the Chord Diagram and Parliament chart templates. <br /> <br /> In University I studied journalism at Ryerson University. In 2017 I also graduated from the Lede Program for Data Journalism at Columbia University where I learned Python and PostgreSQL. </p> </div> </Layout> ) export default About
var express = require('express'); var app = express(); app.use('/touro', function(req, res, next){ //Middleware function to log request protocol console.log("A request for things received at " + Date.now()); next(); }); app.get('/touro', function(req, res){ // Route handler that sends the response res.send('welcome to Touro College'); }); app.listen(8080);
import React, { useState } from "react"; import { useHistory } from "react-router-dom"; function SignUpForm({ setCurrentUser }) { const API = "http://localhost:3001/" // const [formData, setFormData] = useState({ // username: "", // password: "", // }); const [errors, setErrors] = useState([]); const [username, setUsername] = useState("") const [password, setPassword] = useState("") const [userImage, setUserImage] = useState(null) const history = useHistory(); // function handleChange(e) { // setFormData({ ...formData, [e.target.name]: e.target.value }); // } function handleSubmit(e) { e.preventDefault(); const formData = new FormData(); formData.append('username', username); formData.append('password', password); formData.append('user_image', userImage); console.log(userImage) console.log(formData) fetch(`${API}signup`, { method: "POST", body: formData, }) .then(r => r.json()) .then((data) => { if (data.errors) { setErrors(data.errors); } else { const { user, token } = data; localStorage.setItem("token", token); setCurrentUser(user) console.log(user); history.push(`/user/${user.id}`); } }); } return ( <div className="signup-form-div"> <form className="signup-form" onSubmit={handleSubmit} autoComplete="off"> <h1>Sign Up</h1> <label htmlFor="username">Username</label> <input type="text" name="username" value={username} onChange={(e) => setUsername(e.target.value)} required /> <br/> <label htmlFor="password">Password</label> <input type="password" name="password" value={password} onChange={(e) => setPassword(e.target.value)} /> <br/> <label htmlFor="image">Choose an image</label> <input id="signup-file-input" type="file" name="userImage" accept="image/png, image/jpeg, image/jpg" multiple={false} onChange={(e) => setUserImage(e.target.files[0] )} /> {errors.map((error) => { return <p key={error}>{error}</p>; })} <br/> <button type="submit">Sign Up</button> </form> </div> ); } export default SignUpForm;
import React from 'react'; import './App.css'; import logo from './logo.svg'; export default class Hero extends React.Component { render (){ return( <div class="hero is-large"> <div class="hero-body"> <div class="tile is-ancestor"> <div class="tile is-7 is-parent"> </div> <div class="tile is-parent"> <div class="tile is-child box"> <p class="title">Muhammad Arif Bin Rawi</p> <p class="subtitle">Junior Software Developer, Aspiring Game Developer</p> </div> </div> </div> </div> </div> )}; }
import React, { Component } from 'react'; import MyHeader from './components/Header'; import ColorChooser from './components/ColorChooser'; import './App.css'; class App extends Component { state = { selectedColor: '', } onColorChange = (event) => { this.setState({ selectedColor: event.target.value, }); } render() { return ( <div className="App"> <MyHeader title="Hello React-Demo" color={this.state.selectedColor} /> <div> <ColorChooser selectedColor={this.state.selectedColor} onColorChange={this.onColorChange} /> </div> </div> ); } } export default App;
var x; var y; var tol; localStorage.clear(); document.getElementById("m-inputnum-inp").value=8 allPeople() function allPeople() { var num = document.getElementsByTagName("input")[0]; var btn=document.getElementsByClassName("jiahao")[0] var btn2=document.getElementsByClassName("jianhao")[0] btn.onclick=function bbb(){ tol=parseInt(tol)+1; document.getElementById("m-inputnum-inp").value=tol allPeople() if(tol>17){btn.onclick=function(){}} document.getElementsByTagName("input")[0].value=tol show() } btn2.onclick=function aaa(){ tol=parseInt(tol)-1; document.getElementById("m-inputnum-inp").value=tol allPeople() if(tol<5){btn2.onclick=function(){}} document.getElementsByTagName("input")[0].value=tol show() } tol = document.getElementById("m-inputnum-inp").value; console.log(tol); if (tol <= 8) { x = 1; y = tol - 1; } else if (tol <= 11) { x = 2; y = tol - 2; } else if (tol <= 15) { x = 3; y = tol - 3; } else if (tol <= 18) { x = 4; y = tol - 4; } console.log(x) console.log(y) sz1 = []; for (i = 0; i <x; i++) { sz1[i] = "杀手" } console.log(sz1); sz2 = []; for (i = 0; i <y; i++) { sz2[i] = "平民" } console.log(sz2); if (tol >= 4) { if (tol <= 18) { document.getElementById('xsnum').innerHTML = x; document.getElementById('pmnum').innerHTML = y; } } else { document.getElementById('xsnum').innerHTML = ""; document.getElementById('pmnum').innerHTML = ""; } bh = [] for (i = 0; i < tol; i++) { bh[i] = i + 1 } console.log(bh) localStorage.setItem("ckrs",x) localStorage.setItem("pmrs",y) shengfen = sz1.concat(sz2); console.log(shengfen) shengfen1 =JSON.stringify(shengfen) console.log(shengfen1) localStorage.setItem("sfname",shengfen1); localStorage.setItem("lastname",bh); localStorage.setItem("firstname",tol); console.log(localStorage.sfname) document.getElementsByTagName("input")[0].value=tol r=(parseInt(num.value)-4)/14*100 num.style.background='linear-gradient(to right, #059CFA, white ' + r + '%, white)' } var btn2 = document.getElementById("wjpbtz") btn2.onclick = function () { if(tol<4||tol>18){ alert("请输入正确的人数") } else{ window.location.href = "task3.html"; } } var num = document.getElementsByTagName("input")[0]; num.style.background='linear-gradient(to right, #059CFA, white 28.5%, white)' function show(){ tol = document.getElementById("m-inputnum-inp"); tol.value = num.value; allPeople() r=(parseInt(num.value)-4)/14*100 num.style.background='linear-gradient(to right, #059CFA, white ' + r + '%, white)' }
var fs = require('fs'); fs.readFile('input.txt', 'utf8', function(err, input) { let entries = input.split("\n"); let answer = 0; entries.forEach(function(entry) { let a = parseInt(entry); if (!isNaN(a)) { answer += a; } }) console.log(answer); });
const colors = { primary: "#071e3d", secondary: "#eaa81b", grey: "hsl(0, 0%, 27%)", green: "green", defaultFont: ` -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif` }; export default colors;
const commonDockerPrompt = (oGen) => { return [ { type: "input", name: "dockerImageName", message: "Please input your docker-image-name?", default: "[DOCKER_IMAGE_NAME]", }, { type: "input", name: "dockerOrgName", message: "Please input your docker-org-name?", default: "[DOCKER_ORG_NAME]", }, { type: "input", name: "verPrefix", message: "Please input your version-prefix, will use with folder name and version?", default: "v", }, ]; }; module.exports = commonDockerPrompt;
d3.queue() .defer(d3.csv, "nationRate.csv") .await(function(error, RateData) { var ageSvg = d3.select("#ageSvg"), agemargin = {top: 20, right: 150, bottom: 30, left: 160}, width = +ageSvg.attr("width") - agemargin.left - agemargin.right, height = +ageSvg.attr("height") - agemargin.top - agemargin.bottom, Ag = ageSvg.append("g").attr("transform", "translate(" + agemargin.left + "," + agemargin.top + ")"); var RparseTime = d3.timeParse("%Y [YR%Y]"); RateData.forEach(function(d) { d.Year = RparseTime(d.Year); }); console.log(RateData); var x = d3.scaleTime() .rangeRound([0, width]); var y = d3.scaleLinear() .rangeRound([height, 0]); var Az = d3.scaleOrdinal(d3.schemeRdBu[6]); var Aline = d3.line() .x(function(d) { return x(d.Year); }) .y(function(d) { return y(d.value); }); //AGEDATA var ageData = []; ageData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "20to34", value: d["20to34"] } })); ageData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "35to44", value: d["35to44"] } })); ageData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "45to54", value: d["45to54"] } })); ageData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "55to64", value: d["55to64"] } })); console.log(ageData); ////// //RACEDATA var raceData = []; raceData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "White", value: d.White } })); raceData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "Black", value: d.Black } })); raceData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "Latino", value: d.Latino } })); raceData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "Asian", value: d.Asian } })); //////VETERANDATA var veteranData = []; veteranData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "Veterans", value: d.Veterans } })); veteranData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "Non_Veterans", value: d.Non_Veterans } })); //////NATIVITYDATA var nativityData = []; nativityData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "Native", value: d.Native } })); nativityData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "Immigrant", value: d.Immigrant } })); //////GENDERDATA var genderData = []; genderData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "Male", value: d.Male } })); genderData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "Female", value: d.Female } })); //////EDUCATIONDATA var educationData = []; educationData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "Low", value: d.Low } })); educationData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "HighSchool", value: d.HighSchool } })); educationData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "College", value: d.College } })); educationData.push(RateData.map(function(d) { return { Year: d.Year.getFullYear(), key: "Graduate", value: d.Graduate } })); // console.log(ageData); drawLines(ageData); d3.select('#agebtn').on('click', function(){ drawLines(ageData); }); d3.select('#racebtn').on('click', function(){ drawLines(raceData); }); d3.select('#educationbtn').on('click', function(){ drawLines(educationData); }); d3.select('#nativitybtn').on('click', function(){ drawLines(nativityData); }); function drawLines(data) { x.domain(d3.extent(RateData, function(d) { return d.Year.getFullYear(); })); y.domain([0.1 , 0.7]); // Az.domain(RateData.map(function(d){return d[0].key})); // console.log(data); // console.log('drawLines'); var lines = Ag.selectAll(".linePath") .data(data); // var linesEnter = lines .enter() .append("path") .attr('class','linePath'); linesEnter.merge(lines) .attr("d", Aline) .attr("fill", "none") .style("stroke", function(d) { return Az(d[0].key); }) // .attr("stroke", "steelblue") .attr("stroke-linejoin", "round") .attr("stroke-linecap", "round") .attr("stroke-width", 9) .attr("opacity", 0) .on("mouseover", function(d){ d3.select(this) .transition() .duration(500) .attr("stroke-width", 20) var tooltip= d3.select('.tooltip'); tooltip.transition() .style('opacity',0.7) .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY) + "px") .style("display", "block"); d3.select(this) .transition() .duration(500) tooltip .select('.tipName') .text(d[0].key); }) .on("mouseout", function(d,i){ d3.select(this) .transition() .duration(500) .attr("stroke-width", 9) .style("stroke", function(d) { return Az(d[0].key); }); var tooltip= d3.select('.tooltip'); tooltip.transition() .style('opacity',0); // .attr("stroke", "steelblue"); }) .transition() .duration(2000) .attr("opacity",1); // lines.exit() .remove(); // var linesText = Ag.selectAll("text") // .data(data); // // var linePath = Ag.selectAll("text") // .data(data); // linePath. append("text") // .datum(function(d) { return {key: d[0].key, value: d.value[d.value.length - 1]}; }) // .attr("transform", function(d) { return "translate(" + x(d.value.Year) + "," + y(d.value.value) + ")"; }) // .attr("x", 3) // .attr("dy", "0.35em") // .style("font", "10px sans-serif") // .text(function(d) { return d[0].key; }); } x.domain(d3.extent(RateData, function(d) { return d.Year.getFullYear(); })); y.domain([0.1 , 0.7]); // Az.domain(RateData.map(function(d){return d[0].key})); Ag.append("g") .attr("class", "axis axis-x") .attr("transform", "translate(0," + height + ")") .attr("fill", "#000") .select(".domain") .call(d3.axisBottom(x)); // Ag.append("g") // .attr("transform", "translate(0," + height + ")") // .call(d3.axisBottom(x)) // .remove(); Ag.append("g") .call(d3.axisLeft(y)) .append("text") .attr("fill", "#000") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", "0.71em") .attr("text-anchor", "end") .text("Rate of New Entrepreneurs (%)"); // x.domain(d3.extent(RateData, function(d) { return d.Year.getFullYear(); })); // y.domain([0.1 , 0.7]); // Az.domain(RateData.map(function(d){return d[0].key})); });
import { KeepAwake, registerRootComponent } from 'expo'; import React from 'react'; import {StyleSheet, View} from 'react-native'; import {IsocontentNative} from 'react-isocontent-native'; if (__DEV__) { KeepAwake.activate(); } export default class App extends React.Component { render() { return ( <View style={styles.container}> <IsocontentNative content={[ {type: 'text', value: 'foo'}, { type: 'block', block_type: 'list', arguments: {ordered: false}, children: [ {type: 'block', block_type: 'list_item', children: [{type: 'text', value: 'bar'}]}, {type: 'block', block_type: 'list_item', children: [{type: 'text', value: 'baz'}]}, ], }, {type: 'block', block_type: 'strong', children: [{type: 'text', value: 'qux '}]}, {type: 'text', value: 'foo '}, {type: 'block', block_type: 'strong', children: [{type: 'text', value: 'baz '}]}, {type: 'text', value: 'baz'}, ]} /> <View styles={styles.strong}><Text>Coucou</Text></View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, }); registerRootComponent(App);
import React, {Component} from 'react' import axios from 'axios' import CharacterCard from '../CharacterCard/characterCard' import apiKey from "../../config/apikey"; import apiBase from "../../config/apibase"; class Event extends Component { constructor(props) { super(props); this.state = { id: null, description: null, start: null, characters: [], image: null, firstLoader: true, secondLoader: true, } } componentDidMount() { let id = null; axios.get(`${apiBase.base}/events?apikey=${apiKey.key}&name=${this.props.match.params.name}`) .then((res) => { console.log(res.data.data.results[0]); let rawData = res.data.data.results[0]; const testDate = new Date(rawData.start); const formatDate = testDate.toDateString(); id = rawData.id; this.setState({ start: formatDate, description: rawData.description, image: rawData.thumbnail.path + "." + rawData.thumbnail.extension, id: rawData.id, firstLoader: false }); this.searchForCharacters(rawData.id) }); } searchForCharacters(id) { axios.get(`${apiBase.base}/events/${id}/characters?apikey=${apiKey.key}&limit=100`) .then((res) => { console.log(res.data.data.results); let rawData = res.data.data.results; let newCharactersList = this.state.characters; for (let character of rawData) { let name = character.name; let description = character.description; let image = character.thumbnail.path + "." + character.thumbnail.extension; let newCharacter = {name, description, image}; newCharactersList.push(newCharacter); } this.setState({ characters: newCharactersList, secondLoader: false }); console.log(newCharactersList) }) } render() { return ( <div> { this.state.firstLoader === true ? <div> <h3>Loading Event</h3> <div className="progress"> <div className="indeterminate"/> </div> </div> : <div className="center" style={{ backgroundColor: 'rgba(240, 248, 255, 0.9)', paddingBottom: '2vh', paddingLeft: '2vw', paddingRight: '2vw', maxHeight: '100vh' }}> <h1>{this.props.match.params.name}</h1> <img style={{maxWidth: '40%'}} src={`${this.state.image}`} alt={this.state.name}/> <h6>Started on: {this.state.start}</h6> <p>{this.state.description}</p> <h5>Characters</h5> </div> } { this.state.secondLoader === true ? <div> <h3>Loading Characters</h3> <div className="progress"> <div className="indeterminate"/> </div> </div> : <div className="row"> {this.state.characters.map((character) => { return ( <div className="col s12 m3" key={character.name} style={{height: "40vh"}}> <CharacterCard name={character.name} image={character.image}/> </div> ) }) } </div> } </div> ) } } export default Event; //https://gateway.marvel.com:443/v1/public/events/id/characters?apikey=e997cd1b6f3b91f4713b3ae5b5a8fc74
const chalk = require('chalk') const execa = require('execa') const { hasYarn, request } = require('./common') const inquirer = require('inquirer') const registries = require('./registries') async function ping(registry) { await request.get(`${registry}/react/latest`) return registry } let checked let result module.exports = async function shouldUseTaobao(command) { if (!command) { command = hasYarn() ? 'yarn' : 'npm' } // ensure this only gets called once. if (checked) return result checked = true const save = val => { result = val return val } const userCurrentRegistry = (await execa(command, ['config', 'get', 'registry'])).stdout // const defaultRegistry = registries[command] let faster try { faster = await Promise.race([ping(userCurrentRegistry), ping(registries.taobao)]) } catch (e) { return save(false) } if (faster !== registries.taobao) { // 默认镜像更快,不用淘宝镜像 return save(false) } // 询问源的选择 const { useTaobaoRegistry } = await inquirer.prompt([ { name: 'useTaobaoRegistry', type: 'confirm', message: chalk.yellow( ` Your connection to the default ${command} registry seems to be slow.\n` + ` Use ${chalk.cyan(registries.taobao)} for faster installation?` ) } ]) return save(useTaobaoRegistry) }
import React, { lazy, Suspense, Fragment } from 'react'; import PropTypes from 'prop-types'; import { Switch, Route } from 'react-router-dom'; import { ThemeProvider } from '@material-ui/styles'; import { createTheme } from './styles/theme'; import NavBar from './modules/navbar/navbar.connector'; import Admin from './pages/admin/admin.component'; import UserRoutes from './modules/routes/userRoutes.connector'; const Toaster = lazy(() => import('./modules/toaster/toast.connector')); const App = props => ( <Fragment> <ThemeProvider theme={createTheme(props.theme)}> <NavBar desktop={props.theme.navbar.desktop}> <Switch> <UserRoutes /> </Switch> <Suspense fallback={<div />}> <Toaster /> </Suspense> </NavBar> </ThemeProvider> <Switch> <Route path="/admin/" component={Admin} /> </Switch> </Fragment> ); App.propTypes = { theme: PropTypes.shape({ navbar: PropTypes.shape({ desktop: PropTypes.bool, }), }).isRequired, }; export default App;
const meterify = require('meterify').meterify; const Web3 = require('web3'); const web3 = meterify(new Web3(), 'http://warringstakes.meter.io'); (async ()=>{ const receipt = await web3.eth.getBalance("0x2b6620bd4328e34b437d47b4b33a06ffa5e58c56"); console.log(receipt); })()
import React from 'react'; import App from './App.js'; import Login from './components/auth/login.js'; import AccountInfo from './components/profile/account/account-info.js'; import Mainpage from './components/main/main.js'; import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'; const RouterComponent = () => ( <Switch> <Route exact path='/'> <Mainpage /> </Route> <Route path='/login'> <Login /> </Route> <Route path='/account'> <AccountInfo /> </Route> </Switch> ) export default RouterComponent;
console.log("connect") $( document ).ready(function() { console.log( "document loaded" ); for (var i = 0; i < cool.length; i++) { console.log(cool[i]) $("ul").append('<li>' + cool[i] + '</li>'); } //// $( "li" ).each(function( index ) { console.log( "hello" ); }); })
import React from "react"; import { Row, Col, Container } from "reactstrap"; import { connect } from "react-redux"; class Fmedicalrecords extends React.Component { render() { return this.props.medrec.record !== null ? ( <div className="paging"> <Container className="bordercolor3"> <Row className="bordercolor"> <Col className="center1"> <h2>CONSULTATION RECORDS</h2> </Col> </Row> <Row className="bordercolor"> <Col> <b>Physical Examination Findings</b> </Col> </Row> <Row> <Col className="bordercolor" lg="2"> <b>Vital Signs</b> </Col> <Col className="bordercolor" lg="5"> <Col> Blood Pressure: {this.props.medrec.record.bloodPressure} </Col> <Col>Pulse Rate: {this.props.medrec.record.pulseRate}</Col> </Col> <Col className="bordercolor" lg="5"> <Col> Respiratory Rate: {this.props.medrec.record.respiratoryRate} </Col> <Col>Temperature: {this.props.medrec.record.temperature}</Col> </Col> </Row> <Row> <Col className="bordercolor"> <b>Physical Examination</b> </Col> <Col className="bordercolor" lg="10"> <Row> <Col className="bordercolor" lg="6"> HEENT </Col> <Col className="bordercolor" lg="6"> Heart </Col> <Col className="bordercolor" lg="6"> <div className="divprint"> {this.props.medrec.record.heent} </div> </Col> <Col className="bordercolor" lg="6"> <div className="divprint"> {this.props.medrec.record.heart} </div> </Col> <Col className="bordercolor" lg="6"> Lungs </Col> <Col className="bordercolor" lg="6"> Abdomen </Col> <Col className="bordercolor" lg="6"> <div className="divprint"> {this.props.medrec.record.lungs} </div> </Col> <Col className="bordercolor" lg="6"> <div className="divprint"> {this.props.medrec.record.abdomen} </div> </Col> <Col className="bordercolor" lg="12"> Extremities </Col> <Col className="bordercolor" lg="12"> <div className="divprint1"> {this.props.medrec.record.extremities} </div> </Col> </Row> </Col> </Row> <Row> <Col className="bordercolor"> <b>Laboratory Workups</b> </Col> <Col className="bordercolor" lg="10"> <Row> <Col className="bordercolor" lg="6"> Complete Blood Count(CBC) </Col> <Col className="bordercolor" lg="6"> Urinalysis </Col> <Col className="bordercolor" lg="6"> <div className="divprint"> {this.props.medrec.record.completeBloodCount} </div> </Col> <Col className="bordercolor" lg="6"> <div className="divprint"> {this.props.medrec.record.urinalysis} </div> </Col> <Col className="bordercolor" lg="6"> Fecalysis </Col> <Col className="bordercolor" lg="6"> Chest X-ray(CXR) </Col> <Col className="bordercolor" lg="6"> <div className="divprint"> {this.props.medrec.record.fecalysis} </div> </Col> <Col className="bordercolor" lg="6"> <div className="divprint"> {this.props.medrec.record.chestXray} </div> </Col> <Col className="bordercolor" lg="6"> Ishihara Test </Col> <Col className="bordercolor" lg="6"> Audio </Col> <Col className="bordercolor" lg="6"> <div className="divprint"> {this.props.medrec.record.isihiraTest} </div> </Col> <Col className="bordercolor" lg="6"> <div className="divprint"> {this.props.medrec.record.audio} </div> </Col> <Col className="bordercolor" lg="6"> Psychological Exam </Col> <Col className="bordercolor" lg="6"> Drug Test </Col> <Col className="bordercolor" lg="6"> <div className="divprint"> {this.props.medrec.record.psychologicalExam} </div> </Col> <Col className="bordercolor" lg="6"> <div className="divprint"> {this.props.medrec.record.drugTest} </div> </Col> <Col className="bordercolor" lg="12"> Hepatitis B Test </Col> <Col className="bordercolor" lg="12"> <div className="divprint1"> {this.props.medrec.record.hepatitisBTest} </div> </Col> </Row> </Col> </Row> <Row className="bordercolor"> <Col> <b>Complaints</b> </Col> </Row> <Row className="bordercolor"> <div className="divprint"> {this.props.medrec.record.complaints} </div> </Row> <Row className="bordercolor"> <Col> <b>Diagnosis</b> </Col> </Row> <Row className="bordercolor"> <div className="divprint">{this.props.medrec.record.diagnosis}</div> </Row> <Row className="bordercolor"> <Col> <b>Treatment</b> </Col> </Row> <Row className="bordercolor"> <div className="divprint">{this.props.medrec.record.treatment}</div> </Row> <Row className="bordercolor"> <Col> <b>Remarks</b> </Col> </Row> <Row className="bordercolor"> <div className="divprint">{this.props.medrec.record.remarks}</div> </Row> </Container> </div> ) : null; } } const mapStateToProps = (state) => ({ medrec: state.medrec }); export default connect(mapStateToProps, null)(Fmedicalrecords);
'use strict'; /** * Slave Manager manages all slave connections and dispatches received tasks. * It makes sure all tasks are executed at some point of time, even if some * connections are lost. * * It exposes two methods: enqueue() and dequeue(), which are used by the * scheduler. * * @constructor * @param argv {Object} config dictionary. It may contain: * - debug {bool} - flag that enables debug logs * - listenPort {Number} - the port to listen for incoming * slave connections. */ var SlaveManager = function(argv) { var DEBUG = argv && !!argv.debug; var LISTEN_PORT = argv && argv.listenPort || 9001; var io = require('socket.io'), _ = require('lodash'), Q = require('q'); /** * Forwards its arguments to console.log only if DEBUG flag is set. */ var _debugLog = function() { if (DEBUG) { console.log.apply(console.log, arguments); } }; /** * Finds the index of first Slave in given array that uses given socket. * * @param slaves {Array[Slave]} - array of Slave objects to search. * @param socket {io.Socket} - a socket to search for. * @returns the index of Slave using given socket, or -1. */ var findSlaveIndexBySocket = function(slaves, socket) { return _.findIndex(slaves, function(s) { return s.socket === socket; }); }; /** * A class that matches a socket to id of the task it currently executes. * * @class Scheduler * @constructor * @param socket {io.Socket} slave socket. */ var Slave = function(socket) { /* io.Socket */ this.socket = socket; /* TaskId */ this.taskId = null; }; Slave.prototype = { /** * Assigns a task described by given TaskInfo object to the Slave. * * @method assignTask * @param taskInfo {TaskInfo} task details. */ assignTask: function(taskInfo) { this.taskId = taskInfo ? taskInfo.id : null; if (this.taskId !== null) { taskInfo.executionStarted(); this.socket.emit('task_request', { task_id: taskInfo.id, code: taskInfo.task.code, data: taskInfo.task.data }); } }, /** * Returns the slave address in a host:port format. * * @method getAddressString * @returns slave address, as "host:port" */ getAddressString: function() { return this.socket.handshake.address.address + ':' + this.socket.handshake.address.port; } }; /** * Scheduled task details. * * @class TaskInfo * @constructor * @param task {Task} a task object to wrap. * @param packageId {Number} id of the Package that contains this task. * @param deferred {Q.Deferred} Deferred object of the Package mentioned * above. */ var TaskInfo = function(task, packageId, deferred) { /* TaskId */ this.id = task._id; /* Task */ this.task = task; /* Number */ this.packageId = packageId; /* Q.Deferred */ this.deferred = deferred; }; TaskInfo.prototype = { reset: function() { this.task.status = 'scheduled'; }, executionStarted: function() { this.task.status = 'executing'; }, /** * Marks the task as resolved and stores the calculated result. * * @method resolve * @param result {Object} task result. */ resolve: function(result) { this.task.partial_result = result; this.task.status = 'finished'; } }; /** * A collection of tasks passed to a single SlaveManager.enqueue() call. * * @class Package * @constructor * @param id {Number} arbitrary package id. * @param tasks {Array[Task]} an array of Task objects from the enqueue() * call. */ var Package = function(id, tasks) { /* Number */ this.id = id; /* Task[] */ this.tasks = tasks; /* Number */ this.completedTasks = 0; /* Number */ this.totalTasks = tasks.length; /* Q.Deferred */ this.deferred = Q.defer(); }; Package.prototype = { /** * Updates the Package state by marking one of its Tasks as resolved. * * @method progress * @param taskInfo {TaskInfo} the TaskInfo of completed task. * @param result {Object} task result. */ progress: function(taskInfo, result) { taskInfo.resolve(result); this.completedTasks++; this.deferred.notify(taskInfo.task); _debugLog("completed: %d/%d", this.completedTasks, this.totalTasks); if (this.completedTasks === this.totalTasks) { _debugLog('package completed: ' + taskInfo.packageId); this.deferred.resolve(this.tasks); } }, /** * Chacks if all tasks from this Package are completed. * * @method isCompleted * @returns true if all tasks were completed. */ isCompleted: function() { return this.completedTasks === this.totalTasks; } }; /** * A wrapper around the Deferred object for a Task set which was already * dequeued. * * @class PackageDeferred * @constructor * @param taskIds {Array[TaskId]} array of dequeued TaskIds. * @param deferred {Q.Deferred} a Deferred object for tracking the taskIds * completion progress. */ var PackageDeferred = function(taskIds, deferred) { /* TaskId[] */ this.unresolvedTaskIds = taskIds; /* Task[] */ this.completedTasks = []; /* Q.Deferred */ this.deferred = deferred; }; PackageDeferred.prototype = { containsTaskId: function(id) { return this.unresolvedTaskIds.indexOf(id) !== -1; }, /** * Updates the PackageDeferred object after completion of a Task. * * @method onTaskCompleted * @param task {Task} the task that was just completed. */ onTaskCompleted: function(task) { var idx = this.unresolvedTaskIds.indexOf(task._id); if (idx >= 0) { _debugLog('dequeuedDeferred: %d tasks completed, %d to go', this.completedTasks.length, this.unresolvedTaskIds.length); this.unresolvedTaskIds.splice(idx, 1); this.completedTasks.push(task); if (this.isResolved()) { this.deferred.resolve(this.completedTasks); } } }, isResolved: function() { return this.unresolvedTaskIds.length === 0; } }; /** * Actual SlaveManager class implementation. * * @class SlaveManager * @constructor * @param listenPort {Number} - a port to listen for slave connections on. */ var SlaveManager = function (listenPort) { /* Slaves who are not processing anything */ /* Slave[] */ this.idleSlaves = []; /* Slaves busy executing assigned tasks */ /* Slave[] */ this.busySlaves = []; /* all tasks passed to the SlaveManager */ /* { Id => TaskInfo } */ this.tasks = {}; /* subset of this.tasks - ones that were already completed */ /* { Id => TaskInfo } */ this.completedTasks = {}; /* queue of tasks yet to be executed */ /* TaskInfo[] */ this.taskQueue = []; /* Packages created by enqueue() calls, waiting for execution */ /* { Number => Package } */ this.taskPackages = {}; /* Used for generating unique Package ids */ /* Number */ this.taskPackageIdGenerator = 0; /* A set of PackageDeferreds waiting for completion of some tasks */ /* PackageDeferred[] */ this.dequeuedDeferreds = []; /* A server socket listening for incoming slave connections */ /* io.Socket */ this.serverSocket = io.listen(listenPort, { log: this.debug }); var manager = this; this.serverSocket.on('connection', function(socket) { var addr = socket.handshake.address; _debugLog('slave connected: %s:%d', addr.address, addr.port); manager.idleSlaves.push(new Slave(socket)); manager._assignTasks(); socket.on('task_reply', function(msg) { manager._onTaskCompleted(this, msg.task_id, msg.result); }); socket.on('disconnect', function() { manager._onSlaveDisconnected(socket); }); }); }; SlaveManager.prototype = { /** * Internal function used for SlaveManager debugging. */ _debugPrintStatus: function(funcName) { _debugLog('slave manager: %s called\n' + '- %d tasks in queue\n' + '- %d idle slaves\n' + '- %d busy slaves', funcName, this.taskQueue.length, this.idleSlaves.length, this.busySlaves.length); }, /** * Updates all objects waiting for completion of given Task. * * @param taskId {TaskId} id of the completed task. * @param result {Object} task execution result. */ _markTaskAsCompleted: function(taskId, result) { _debugLog('task completed: %j, result: %j', taskId, result); var taskInfo = this.tasks[taskId]; if (taskInfo === undefined) { console.error('invalid task ID: %j', taskId); return; } var pkg = this.taskPackages[taskInfo.packageId]; if (pkg === undefined) { console.error('task %j is assigned to invalid package %s', taskId, taskInfo.packageId); return; } pkg.progress(taskInfo, result); if (pkg.isCompleted()) { delete this.taskPackages[pkg.id]; } this._updateAllDequeued(taskInfo.task); }, /** * Assigns pending tasks to idle slaves. */ _assignTasks: function() { this._debugPrintStatus('_assignTasks'); while (this.taskQueue.length > 0 && this.idleSlaves.length > 0) { var slave = this.idleSlaves.shift(); var taskInfo = this.taskQueue.shift(); this.busySlaves.push(slave); slave.assignTask(taskInfo); _debugLog('task ' + slave.taskId + ' assigned to ' + slave.getAddressString()); } }, /** * Puts given task back to the task queue after the slave unexpectedly * disconnects while executing a task and attempts to assign it to * someone else. * * @param taskId {TaskId} id of the task to reassign. */ _reassignTask: function(taskId) { var taskInfo = this.tasks[taskId]; taskInfo.reset(); this.taskQueue.unshift(taskInfo); _debugLog('slave disconnected, task ' + taskId + ' added at the start of task queue'); this._assignTasks(); }, /** * Notifies the PackageDeferred objects after a task completion. * * @param completedTask {Task} completed task. */ _notifyDequeued: function(completedTask) { var dequeuesPerTask = 0; var manager = this; _.forEach(this.dequeuedDeferreds, function(pkgDeferred) { if (pkgDeferred.containsTaskId(completedTask._id)) { pkgDeferred.onTaskCompleted(completedTask); delete manager.completedTasks[completedTask._id]; if (++dequeuesPerTask > 1) { console.warn('warning: multiple dequeue() calls ' + 'detected for task %j, it may not work ' + 'as expected', completedTask._id); } } }); }, /** * Updates PackageDeferred object(s) after a task completion. * * @param completedTask {TaskId} - completed task id. If this value is * undefined, the function triggers * updates for all completed tasks. */ _updateAllDequeued: function(completedTask) { var manager = this; if (completedTask === undefined) { for (var id in this.completedTasks) { this._updateAllDequeued(this.completedTasks[id].task); } return; } _debugLog('updateAllDequeuedDeferreds: taskId = %s', completedTask._id); this._notifyDequeued(completedTask); _.remove(this.dequeued, function(pkgDeferred) { return pkgDeferred.isResolved(); }); }, /** * A handler called when a slave finished executing the task. * * @param socket {io.Socket} a socket that received the task result. * @param taskId {TaskId} id of the completed task. * @param result {Object} task result. */ _onTaskCompleted: function(socket, taskId, result) { this._markTaskAsCompleted(taskId, result); var slaveIdx = findSlaveIndexBySocket(this.busySlaves, socket); var slave = this.busySlaves.splice(slaveIdx, 1)[0]; slave.assignTask(null); this.idleSlaves.push(slave); this._assignTasks(); }, /** * A handler called when the slave connection has been lost. * * @param socket {io.Socket} the socket that lost connection. */ _onSlaveDisconnected: function(socket) { var addr = socket.handshake.address; _debugLog('slave %s:%d disconnected', addr.address, addr.port); var idx = findSlaveIndexBySocket(this.idleSlaves, socket); if (idx >= 0) { // idle slave disconnected - ok this.idleSlaves.splice(idx, 1); _debugLog('idle slave disconnected'); return; } idx = findSlaveIndexBySocket(this.busySlaves, socket); if (idx >= 0) { // busy slave disconnected - try to recover var taskId = this.busySlaves[idx].taskId; this.busySlaves.splice(idx, 1); this._reassignTask(taskId); return; } console.error('something weird happened, closed socket should be ' + 'in either waitingSlaves or busySlaves'); }, /** * Schedules execution of given tasks. * * @method enqueue * @param tasks {Array[Task]} an array of tasks mapped with toObject to * remove mongoose boilerplate and leave * properties only * * @returns {Q.Promise} a promise which: * - if a single task completes, emits * process([ task ]), * - if all tasks completes, emits * resolve([ task1, task2, ... ]) with all * enqueued tasks. */ enqueue : function (tasks) { var deferred = Q.defer(); if (tasks.length === 0) { _debugLog('empty array passed to SlaveManager.enqueue()'); deferred.resolve(null); return deferred.promise; } var manager = this; var pkg = new Package(manager.taskPackageIdGenerator++, tasks); this.taskPackages[pkg.id] = pkg; _.forEach(tasks, function(task) { var taskInfo = new TaskInfo(task, pkg.id, deferred); manager.tasks[taskInfo.id] = taskInfo; manager.taskQueue.push(taskInfo); }); this._assignTasks(); return pkg.deferred.promise; }, /** * Returns a Q.Promise that resolves after all given tasks are * completed. * * @method dequeue * @param taskIds {Array[TaskId]} list of TaskIds to wait for. * * @returns {Q.Promise} a promise which resolves after all taskIds are * completed. */ dequeue : function (taskIds) { var manager = this; var deferred = Q.defer(); var pkgDeferred = new PackageDeferred(taskIds, deferred); this._debugPrintStatus('dequeue'); var unknownTasks = _.filter( taskIds, function(id) { return (manager.tasks[id] === undefined) && (manager.completedTasks[id] === undefined); }); if (unknownTasks.length > 0) { deferred.reject('invalid task IDs: ' + unknownTasks); return deferred.promise; } this.dequeuedDeferreds.push(pkgDeferred); this._updateAllDequeued(); return deferred.promise; } }; return new SlaveManager(LISTEN_PORT); }; module.exports = SlaveManager;
import React from 'react'; import styled from 'styled-components'; import { graphql } from 'gatsby'; import Layout from '../components/Layout'; import Navigation from '../components/Navigation'; import PublicationCard from '../components/PublicationCard'; export function PublicationsNavigation() { const links = [ { name: 'Home', url: '/' }, { name: 'Publications', url: '/publications' } ]; return <Navigation links={links} />; } const Wrapper = styled.div` padding: 0 6rem; @media screen and (max-width: 800px) { padding: 0 1rem; } display: grid; grid-gap: 4rem; margin-top: 90px; @media (max-width: 1200px) { grid-gap: 3rem; } @media (max-width: 900px) { grid-gap: 2rem; } `; function Publications({ data }) { const { allPublicationsYaml: publications } = data; return ( <Layout> <PublicationsNavigation /> <Wrapper> {publications.edges.map(({ node }) => ( <PublicationCard {...node} key={node.id} /> ))} </Wrapper> </Layout> ); } export default Publications; export const pageQuery = graphql` query { allPublicationsYaml(sort: { fields: [year], order: DESC }) { edges { node { ...Publication } } } } `;
const Index = (props) => <div>Hello, there.</div>; export default Index;
export default [ { path: '/accounts', name: 'accounts', component: () => import('@/pages/accounts/Accounts'), redirect: '/accounts/information', children: [ { path: 'information', name: 'accounts.information', component: () => import('@/pages/accounts/Information') }, { path: 'following', name: 'accounts.following', component: () => import('@/pages/accounts/Following') }, { path: 'posts', name: 'accounts.posts', component: () => import('@/pages/accounts/Posts') }, ] }, { path: '/posts', name: 'posts.index', component: () => import('@/pages/posts/Index') }, { path: '/posts/:id', name: 'posts.show', component: () => import('@/pages/posts/Show'), props: true //send parameters as properties }, { path: '/todos', name: 'todos.index', component: () => import('@/pages/todos/Todos') }, { path: '/login', name: 'login', component: () => import('@/pages/Login') }, { path:'/home', name: 'home', component: () => import('@/pages/Home') }, { path: '/contact', name: 'contact', component: () => import('@/pages/Contact') }, { path: '/', redirect: '/home' }, { path: '/*', redirect: '/home' } ];
// pages/coin/index.js const api = require('../../request/api.js') Page({ page: 1, pageCount: 1, isLoading: false, /** * 页面的初始数据 */ data: { coins: [] }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.getCoinList() }, async getCoinList () { if (this.isLoading) { return } if (this.page > this.pageCount) { return } // "2020-09-04 09:23:37 签到 , 积分:10 + 3" this.isLoading = true const resp = await api.getCoinList(this.page) const newResp = resp.data.datas.map((value, index, array) => { return ({ desc: value.desc.slice(0, value.desc.indexOf(',')), coinCount: value.coinCount }) }) console.log(resp) ++this.page this.pageCount = resp.data.pageCount this.isLoading = false this.setData({ coins: this.data.coins.concat(newResp) }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })