text
stringlengths
7
3.69M
a = 123 // console.log(global.URL) console.log(require.main === module)
var myArray = []; myArray.push("abc"); myArray.push("mnt"); myArray.unshift("sdcard"); console.log("The length of myArray: %d", myArray.length); myArray.forEach(function(item, index, myArray){ console.log(index + ':' + item + ':' + myArray); }); var obj = {}; obj['name'] = 'Treant'; obj['age'] = 27; obj['gender'] = 'male'; console.log(obj.hasOwnProperty('name')); console.log('%s', obj.hasOwnProperty('age')); console.log(obj.hasOwnProperty('gender')); console.log(obj['daddg']);
$(function() { var dataPie = [ { label: "叶-广发", data: 76}, { label: "叶-华泰", data: 24}, ]; // DONUT $.plot($(".sm-pie"), dataPie, { series: { pie: { innerRadius: 0.7, show: true, stroke: { width: 0.1, color: '#ffffff' } } }, legend: { show: true }, grid: { hoverable: true, clickable: true }, colors: ["#b2def7", "#efb3e6"] }); }); /*Slim Scroll*/ $(function () { $('.event-list').slimscroll({ height: '305px', wheelStep: 20 }); $('.conversation-list').slimscroll({ height: '360px', wheelStep: 35 }); $('.to-do-list').slimscroll({ height: '300px', wheelStep: 35 }); }); /*Knob*/ var opts = { lines: 12, // The number of lines to draw angle: 0, // The length of each line lineWidth: 0.48, // The line thickness pointer: { length: 0.6, // The radius of the inner circle strokeWidth: 0.03, // The rotation offset color: '#464646' // Fill0 color }, limitMax: 'true', // If true, the pointer will not go past the end of the gauge colorStart: '#fa8564', // Colors colorStop: '#fa8564', // just experiment with them strokeColor: '#F1F1F1', // to see which ones work best for you generateGradient: true }; var target = document.getElementById('gauge'); // your canvas element var gauge = new Gauge(target).setOptions(opts); // create sexy gauge! gauge.maxValue = 1578; // set max gauge value gauge.animationSpeed = 32; // set animation speed (32 is default value) gauge.set(1475); // set actual value gauge.setTextField(document.getElementById("gauge-textfield"));
import { Dimensions } from 'react-native'; export const SCREEN_WIDTH = Dimensions.get('window').width; export const COLOR_WHITE = '#ffffff'; export const COLR_OFFLINE = '#b52424'; export const COLOR_ONLINE = '#2ecc71'; export const TOP_POSITION = 'top'; export const DEFAULT_OFFLINE_TEXT = 'No Connection'; export const DEFAULT_ONLINE_TEXT = 'Back Online'; export const DEFAULT_TIMEOUT_SECONDS = 3000;
let router = require("express").Router(); let mongo = require("../../common/mongo"); router.get("/",(req,res)=>{ mongo({ collection:'banner', callback:(collection,client,ObjectId)=>{ collection.find({},{sort:{'time':-1},limit:5}).toArray((err,result)=>{ if(!err){ res.send({error:0,data:result}) }else{ res.send({error:1,msg:'获取失败'}) } }); } }); }); module.exports = router;
function deletePhotos() { var q; for(q=0;q<my_photo_count;q++) { var DelRef = storageRef.child('images'+'/'+arr[q]); DelRef.delete().then(function() { // File deleted successfully console.log("Images Deleted") }).catch(function(error) { // Uh-oh, an error occurred! }); } } function deletePhotosDatabase() { firebase.database().ref('/images').once('value', function(snapshot) { snapshot.forEach(function(childSnapshot) { var childKey = childSnapshot.key; var childData = childSnapshot.val(); console.log("Entry :"+childSnapshot.key); console.log("Entry :"+childSnapshot.val().author); if(childSnapshot.val().author == firebase.auth().currentUser.uid) { firebase.database().ref('/images/'+childSnapshot.key).remove(); console.log("Deleted"+childSnapshot.val().name); } }); }); setTimeout(function() { location.reload(); }, 1000); }
import React, { Component } from "react"; import { withRouter } from "react-router-dom"; import { Consumer } from "../../context"; class Search extends Component { constructor(props) { super(props); this.state = { query: "" }; this.searchPosters = this.searchPosters.bind(this); this.onChange = this.onChange.bind(this); } searchPosters = e => { e.preventDefault(); this.props.history.push(`/search/${this.state.query}`); }; onChange = e => { this.setState({ [e.target.name]: e.target.value }); }; render() { return ( <div> <h1 className="display-4 text-center">Search For A Poster</h1> <p className="lead text-center">Morressier</p> <div className="mx-auto"> <form className="form-inline " onSubmit={this.searchPosters}> <div className="form-group"> <input className="form-control form-control-lg mr-sm-2" type="search" placeholder="Search" name="query" value={this.state.query} onChange={this.onChange} /> <button className="btn btn-outline-success my-2 my-sm-0" type="submit" > Search </button> </div> </form> </div> <hr /> </div> ); } } export default withRouter(Search);
/** * Created by Mac on 1/30/2016. */ buildPage = function(){ input = $("#divInput") input.append("State <input type='text' id='state'><br>"); input.append("County <input type='text' id='county'><br>"); input.append("Order Amount <input type='number' id='amount'><br>"); input.append("<button onclick='doStuff()'>Calc tax</button>"); } buildPage() //Learned i needed to put the <script at the bottom of the HTML, because //it was calling this at the beginning, when //there wasn't any elements on the page doStuff = function(){ orderAmt = parseFloat( $("#amount").val()) state = $("#state").val() county = $("#county").val() tax = 0 if (state == "WI") { if (county == "1") tax = orderAmt * 0.05 else if (county == "2") tax = orderAmt * 0.10 else tax = orderAmt * 0.025 } output = "Subtotal " + orderAmt + "<br>" + " Tax " + tax + "<br>" + "Total " + (tax + orderAmt) $("#output").append(output) }
const Web3 = require('web3'); const BigNumber = require('bignumber.js'); require('./env'); // "Web3.givenProvider" will be set if in an Ethereum supported browser. const web3 = new Web3(new Web3.providers.WebsocketProvider(`wss://${getNetwork()}.infura.io/ws/v3/${process.env.NODE}`)); /** * watch ethereum network for particular account * and send cancel tx if any unauthorised tx occurs */ async function watch(address){ const subscription = web3.eth.subscribe('pendingTransactions', function(error, result){ if (!error) console.log("res :: " + result); }) console.log(`Subscribed to the ${getNetwork()} network...`); subscription.on("data", async function(transaction){ console.log(transaction) const tx = await web3.eth.getTransaction(transaction); console.log(tx); if(tx && tx.from === address){ //TODO: filters for selections of unauthorised txs await sendCancelTx(tx, process.env.INCREASED_GAS_PRICE, process.env.KEY); } }); } /** * prepare and send cancel transaction to ethereum network * @param {*} txToCancel - tx to cancel * @param {*} increaseGasBy - % increase in gasPrice (min - 10) * @param {*} key - private key to sign tx offchain */ async function sendCancelTx(txToCancel, increaseGasBy, key){ let privKey = new Buffer.from(key, 'hex'); //check if address has enough balance let gasPriceFactor = 1 + Number(increaseGasBy) * 0.01; let hasGas = await hasEnoughGas(txToCancel, gasPriceFactor); if(!hasGas){ throw new Error('not enough balance to send cancel tx...'); } //prepare tx let gasPrice = new BigNumber(txToCancel.gasPrice); let newGasPrice = gasPrice.multipliedBy(gasPriceFactor); let cancelTx = { "from": txToCancel.from, "nonce": txToCancel.nonce, "gasPrice": web3.utils.toHex(newGasPrice), "gasLimit": web3.utils.toHex(txToCancel.gasLimit), "to": txToCancel.from, "value": 0, "chainId": process.env.CHAIN_ID //1 for mainnet, 3 for ropsten, 4 for rinkeby }; let tx = new Tx(cancelTx); //sign tx tx.sign(privKey); //send tx let serializedTx = tx.serialize(); let signedTx = web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')) console.log('Sent cancel tx to network'); //wait for tx confirmation signedTx.on('transactionHash',function(hash){ console.log(`Cancel tx sent to network with tx hash - ${hash}`); }) signedTx.on('confirmation', function(confirmation, receipt){ console.log(receipt) //on 12th confirmation, its relatively safe that tx is processed //so we start another tx if(parseInt(confirmation) > 12){ //stop listening to this tx events signedTx.off('confirmation'); console.log('TRANSACTION CANCELLED SUCCESSFULLY...'); } }) .on('error', console.error); } /** * throws if account doesn't have enough gas to process cancel tx * @param {*} tx - tx to be cancelled * @param {*} gasPriceFactor - increase in % for gas price */ async function hasEnoughGas(tx, gasPriceFactor){ //get balance of current account let balance = await web3.eth.getBalance(tx.from); let bal = new BigNumber(balance); let gasPrice = new BigNumber(tx.gasPrice); let gasLimit = new BigNumber(tx.gasLimit); return bal.minus(gasLimit).isLessThan(gasPrice.multipliedBy(gasPriceFactor)); } /** * select network based on chainId */ function getNetwork(){ let networkId = process.env.CHAIN_ID; switch(Number(networkId)){ case 1: return 'mainnet'; default: return 'rinkeby'; } } try{ watch(process.env.ACCOUNT_TO_WATCH); } catch(error){ console.error(error.message); }
'use strict' const msgpack = require('msgpack-lite') const platform = require('../../src/platform') const codec = msgpack.createCodec({ int64: true }) const id = require('../../src/id') const { Int64BE } = require('int64-buffer') // TODO: remove dependency describe('encode 0.5', () => { let encode let makePayload let writer beforeEach(() => { platform.use(require('../../src/platform/node')) const encoder = require('../../src/encode/0.5') encode = encoder.encode makePayload = encoder.makePayload encoder.init() }) it('should encode to msgpack', () => { const data = [{ trace_id: id('1234abcd1234abcd'), span_id: id('1234abcd1234abcd'), parent_id: id('1234abcd1234abcd'), name: 'test', resource: 'test-r', service: 'test-s', type: 'foo', error: 0, meta: { bar: 'baz' }, metrics: { example: 1 }, start: 123, duration: 456 }] let buffer = Buffer.alloc(1024) const offset = encode(buffer, 5, data, writer) buffer = buffer.slice(0, offset) const traceData = platform.msgpack.prefix(buffer, 1) const [payload] = makePayload(traceData) const decoded = msgpack.decode(payload, { codec }) const stringMap = decoded[0] const trace = decoded[1][0] expect(trace).to.be.instanceof(Array) expect(trace[0]).to.be.instanceof(Array) expect(stringMap[trace[0][0]]).to.equal(data[0].service) expect(stringMap[trace[0][1]]).to.equal(data[0].name) expect(stringMap[trace[0][2]]).to.equal(data[0].resource) expect(trace[0][3].toString(16)).to.equal(data[0].trace_id.toString()) expect(trace[0][4].toString(16)).to.equal(data[0].span_id.toString()) expect(trace[0][5].toString(16)).to.equal(data[0].parent_id.toString()) expect(trace[0][6]).to.be.instanceof(Int64BE) expect(trace[0][6].toString()).to.equal(data[0].start.toString()) expect(trace[0][7]).to.be.instanceof(Int64BE) expect(trace[0][7].toString()).to.equal(data[0].duration.toString()) expect(trace[0][8]).to.equal(0) expect(trace[0][9]).to.deep.equal({ [stringMap.indexOf('bar')]: stringMap.indexOf('baz') }) expect(trace[0][10]).to.deep.equal({ [stringMap.indexOf('example')]: 1 }) expect(stringMap[trace[0][11]]).to.equal(data[0].type) }) it('should truncate long IDs', () => { const data = [{ trace_id: id('ffffffffffffffff1234abcd1234abcd'), span_id: id('ffffffffffffffff1234abcd1234abcd'), parent_id: id('ffffffffffffffff1234abcd1234abcd'), name: 'test', resource: 'test-r', service: 'test-s', type: 'foo', error: 0, meta: { bar: 'baz' }, metrics: { example: 1 }, start: 123, duration: 456 }] let buffer = Buffer.alloc(1024) const offset = encode(buffer, 0, data, writer) buffer = buffer.slice(0, offset) const decoded = msgpack.decode(buffer, { codec }) expect(decoded[0][3].toString(16)).to.equal('1234abcd1234abcd') expect(decoded[0][4].toString(16)).to.equal('1234abcd1234abcd') expect(decoded[0][5].toString(16)).to.equal('1234abcd1234abcd') }) })
let isEmpty = (value) => { if (value === null || value === undefined || value === "") return true; else return false; } /* Returns true if any property of the object is empty, false otherwise. */ let isObjectEmpty = (object) => { for (let property in object) { if (isEmpty(object[property])) return true; } return false; } let isEmailValid = (email) => { let emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/; return email.match(emailRegex) ? true : false; } /* Minimum 8 characters which contain only characters,numeric digits, underscore and first character must be a letter */ let isPasswordValid = (password) => { let passwordRegex = /^[A-Za-z0-9]\w{7,}$/; return password.match(passwordRegex) ? true : false; } /* Returns true if two Objects/values are same, otherwise false */ let isEqual = (object1, object2) => { // if either of them is not an Object if (typeof object1 !== "object" || typeof object2 !== "object") return object1 === object2; // if both are Objects if (Object.keys(object1).length !== Object.keys(object2).length) return false; for (let property in object1) { if(property === '_id') continue; // exclude certain properties here if reqd. if (!object2.hasOwnProperty(property)) return false; if (object1[property] !== object2[property]) return false; } return true; } /* Remove a specified key from an array */ let spliceWithKey = (arr, key) => { for (let i = 0; i < arr.length; i++) { if (isEqual(arr[i], key)) { arr.splice(i, 1); i--; } } } /* Remove a specified key from an array of objects based on a particular property */ let spliceWithKeyAndProperty = (arr, key, property) => { for (let i = 0; i < arr.length; i++) { if (arr[i][property] === key) { arr.splice(i, 1); i--; } } } /* Finds a key within an array of objects. Returns the first index if found, '-1' otherwise. */ let findObjectByProperty = (arr, property, key) => { for (let i = 0; i < arr.length; i++) { if(arr[i][property] === key) return i; } return -1; } /* Finds a key within an array of elements. Returns the first index if found, '-1' otherwise. */ let findKey = (arr, key) => { for (let i = 0; i < arr.length; i++) { if(arr[i] === key) return i; } return -1; } module.exports = { isEmpty: isEmpty, isObjectEmpty: isObjectEmpty, isEmailValid: isEmailValid, isPasswordValid: isPasswordValid, spliceWithKey: spliceWithKey, spliceWithKeyAndProperty: spliceWithKeyAndProperty, isEqual: isEqual, findObjectByProperty: findObjectByProperty, findKey: findKey }
import React, {Component} from 'react'; class Logout extends Component{ constructor(){ super(); } logoutF = async () =>{ try { const logout = await fetch('http://localhost:9000/auth/logout', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' } }) const parsedResponse = await logout.json(); console.log(parsedResponse, ' Dattaa'); if(parsedResponse.data === 'logout successful'){ this.props.history.push('/'); alert('logout successful'); }else { this.props.history.push('/'); alert('logout unsuccessful'); } } catch (err) { console.log(err, 'error in logoutF'); } } conponentDidMount(){ this.logoutF(); } render(){ return( null ) } } export default Logout;
/* * cipher/crypto.js * * @author zhou * * Contains all encode/decode-related functions. */ /* * Encodes a single character rotation by a specified shift value. */ function charShift(character, shift) { var intValue = character.charCodeAt(); var isLowerCase = intValue >= 97 && intValue <= 122; var isUpperCase = intValue >= 65 && intValue <= 90; if (isUpperCase) { if (shift < 0) { return String.fromCharCode((intValue - 65 + shift) % 26 + 91); } else { return String.fromCharCode((intValue - 65 + shift) % 26 + 65); } } else if (isLowerCase) { if (shift < 0) { return String.fromCharCode((intValue - 97 + shift) % 26 + 123); } else { return String.fromCharCode((intValue - 97 + shift) % 26 + 97); } } else { return character; } } /* * Encodes rotation of a string by a specified shift value, which is the same * for all characters in the string. */ function caesar(plaintext, shift) { var ciphertext = ""; for (var i = 0; i < plaintext.length; i++) { ciphertext += charShift(plaintext.charAt(i), shift); } return ciphertext; } /* * Cleans up a keyword string such that only uppercase alphabetic characters * remain. */ function keywordStrip(keyword) { return keyword.toUpperCase().replace(/[^A-Z]+/g, ""); } /* * Encodes the Vigenere cipher of a plaintext string. Does not distinguish * between upper/lowercase in the keyword string. */ function vigenere(plaintext, keyword) { keyword = keywordStrip(keyword); var ciphertext = ""; var setbacks = 0; for (var i = 0; i < plaintext.length; i++) { var shift = (keyword.charAt((i - setbacks) % keyword.length).charCodeAt() - 65); ciphertext += charShift(plaintext.charAt(i), shift); // Set back the keyword index if the current plaintext character is // non-alphabetic. if (plaintext.substring(i, i + 1).replace(/[^a-zA-Z]+/g, "") !== plaintext.substring(i, i + 1)) { setbacks++; } } return ciphertext; }
/* Al presionar el botón, se debe mostrar un mensaje como el siguiente "Esto funciona de maravilla"*/ function mostrar() { var mensaje = "esto funcona de maravilla"; alert (mensaje); }
import React from 'react'; import { Link, Redirect } from 'react-router-dom' import Box from '../boxComponent/box'; export default class Favorites extends React.Component { constructor(props) { super(props); this.state = { Favorites: [] }; this.removeFavorite = this.removeFavorite.bind(this); } // REMOVER DOS FAVORITOS removeFavorite(idMusic) { let user = JSON.parse(sessionStorage.getItem('userData')); if (user) { fetch('http://localhost:8080/api/users/' + user.id + '/musics/' + idMusic, { method: 'DELETE' }) .then((response) => response.json()) .then((responseJson) => { alert(responseJson.message); this.fetchData(); return responseJson; }) } } // BUSCAR FAVORITOS fetchData() { let user = JSON.parse(sessionStorage.getItem('userData')); if (user) { fetch('http://localhost:8080/api/users/' + user.id + '/musics') .then((response) => { if (response.ok) { if (response.status === 204) { return []; } else { return response.json(); } } else { throw new Error("Server response wasn't OK"); } }) .then((responseData) => { this.setState({ Favorites: responseData }); }) } else { return (<Redirect to={'/'} />); } } componentDidMount() { this.fetchData(); } render() { let favorites = this.state.Favorites.map((music) => ( <li key={music.id}> <Link className="music" to={"/show/" + music.id}> <span className="track">{music.track}</span> <span className="artist">{music.artist} - <i>{music.album}</i></span> </Link> <a className="removeFavorites" onClick={() => this.removeFavorite(music.id)}>♥</a> </li> )); let user = JSON.parse(sessionStorage.getItem('userData')); let title = "Músicas favoritas de " + user.username; return ( <div className="favorites"> <Box title={title} closeBtn={true} content={<ul>{favorites}</ul>} /> </div> ); } }
var express = require('express') var router = express.Router() var user = require('../api/user.routes') var chatbot = require('../api/pet.routes') // let verifyToken = require('../api/verifyToken'); let authApi = require('../api/authApi'); var ChatbotController = require('../controller/pet.controller'); //Public Apis--------------------------------------- router.use('/app/users', authApi, user); //Auth Apis--------------------------------------- router.use('/app/pets', authApi, verifyToken, chatbot); module.exports = router;
import React, {Component} from 'react'; // import Button from 'material-ui/Button'; import LoginForm from './LoginForm'; import {withRouter} from 'react-router-dom'; import * as routes from '../constants/routes'; import firebase from 'firebase'; class LandingPage extends Component { handleAuth() { let that=this; const provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider) .then(function (result) { console.log(result.user.email + ' ha iniciado sesion'); that.props.history.push(routes.HOME); }) .catch(error => console.log('Error ' + error.code + ': ' + error.message)) } render() { return ( /*<Button color="primary" variant="raised" onClick={this.handleAuth.bind(this)}>Login con Google</Button>*/ <LoginForm/> ); } } export default withRouter(LandingPage);
var request = require("request"); // gets the userid of the current access token function getUserID(access_token, callback) { var options = { url: "https://api.spotify.com/v1/me", headers: { Authorization: "Bearer " + access_token }, json: true }; request.get(options, function(error, response, body) { var parsedBody = JSON.stringify(body); parsedBody = parsedBody.toString(); parsedBody = JSON.parse(parsedBody); current_user_id = parsedBody.id; console.log("UserID retreived: " + current_user_id); return callback(current_user_id, error); }); } // this gets the playlist ids function getPlaylistIDs( access_token, user_id, ignore_playlists, playlistURL, ids, origCallback, callback ) { // variables var playlistIDS = []; var next = ""; var options = { url: playlistURL, headers: { Authorization: "Bearer " + access_token }, json: true }; // request to get playlists request.get(options, function(error, response, body) { try { if (error) { console.log(error); } var str = JSON.stringify(body); str = str.toString(); var playlists = JSON.parse(str); // loop through playlists for (i = 0; i < playlists.items.length; i++) { playlistDict = {}; x = playlists.items[i]; //console.log(x.name); playlistDict.name = x.name; // if the name of the playlist doesn't exist in the ignore playlists // and the owner of the playlist is the current_user if (!ignore_playlists.includes(x.name) && x.owner.id == user_id) { playlistDict.id = x.id; playlistIDS.push(playlistDict); } } // if the response has a value next then apply it if (playlists.next) { next = playlists.next; } // if ids is populated then we concat if (ids.length > 0) { playlistIDS = playlistIDS.concat(ids); } // callback time return callback( access_token, next, playlistIDS, user_id, ignore_playlists, error, origCallback ); } catch (err) { console.log(err.message); return callback( null, null, null, null, null, "something fucked up", origCallback ); } }); } function getAllPlaylistIDs( access_token, next, ids, user_id, ignore_playlists, error, callback ) { if (next && !error) { getPlaylistIDs( access_token, user_id, ignore_playlists, next, ids, callback, getAllPlaylistIDs ); } else if (error) { return callback([], error); } else { // we have gotten all of our playlistIDs and now we need to go through if (callback) { return callback(ids, null); } else { console.log("An error occured"); } } } function getTrackDataFromPlaylist( access_token, playlistID, trackDataArray, origCallback, callback ) { var next = ""; var tracks = []; var options = { url: playlistID, headers: { Authorization: "Bearer " + access_token }, json: true }; request.get(options, function(error, response, body) { try { if (error) { console.log("error: " + error); } var trackData = JSON.stringify(body); trackData = trackData.toString(); trackData = JSON.parse(trackData); for (i = 0; i < trackData.items.length; i++) { var item = trackData.items[i]; var trackID = item.track.id; if (trackID) { var date_added = item.added_at; var track = { id: trackID, date_added: date_added }; //console.log(track) tracks.push(track); } } trackDataArray.push(tracks); return callback( access_token, trackData.next, trackDataArray, error, origCallback ); } catch (err) { console.log(err.message); return callback( null, null, null, null, null, "something fucked up in track", origCallback ); } }); } function getAllTrackDataFromPlaylist( access_token, next, trackDataArray, error, callback ) { if (next && !error) { getTrackDataFromPlaylist( access_token, next, trackDataArray, callback, getAllTrackDataFromPlaylist ); } else if (error) { console.log("ERROR: " + error); return callback([], error); } else { if (callback) { return callback(trackDataArray, null); } } } function getAllTrackDataFromMultiplePlaylists( access_token, playlistIDs, playlistTrackDataArray, callback ) { if (playlistIDs.length > 0) { // then we get all the track data from that playlist dict = playlistIDs.pop(); id = dict.id; name = dict.name; next = `https://api.spotify.com/v1/playlists/${id}/tracks`; getAllTrackDataFromPlaylist(access_token, next, [], null, function( trackDataArray, error ) { if (error) { return callback(null, error); } //console.log("PlaylistTrackData Length: " + playlistTrackDataArray.length); playlistTrackDataArray = playlistTrackDataArray.concat(trackDataArray); getAllTrackDataFromMultiplePlaylists( access_token, playlistIDs, playlistTrackDataArray, callback ); }); } else { //console.log(playlistTrackDataArray); return callback(playlistTrackDataArray); } } function getTrackIDsViaDateFilter(trackDataArray, days) { next = ""; trackIDs = []; count = 0; for (index = 0; index < trackDataArray.length; index++) { var trackData = trackDataArray[index]; for (i = 0; i < trackData.length; i++) { var track = trackData[i]; var id = track.id; var dateAdded = new Date(track.date_added.toString()); var targetDate = new Date(); targetDate.setDate(targetDate.getDate() - days); if (dateAdded > targetDate && !trackIDs.includes(id)) { console.log("Recently added track found!"); count = count + 1; trackIDs.push(id); } } } console.log("Total Tracks After Filter: " + count); return trackIDs; } function getTrackIDsViaDateFilterLibrary(trackArray, days) { var trackIDs = []; var count = 0; for (i = 0; i < trackArray.length; i++) { var track = trackArray[i]; var id = track.id; var dateAdded = new Date(track.date_added.toString()); var targetDate = new Date(); targetDate.setDate(targetDate.getDate() - days); if (dateAdded > targetDate && !trackIDs.includes(id)) { //console.log("Recently added track found!"); count++; trackIDs.push(id); } } console.log("Total Tracks After Filter: " + count); return trackIDs; } function getAllRecentlyAddedTrackIdsFromPlaylists( access_token, ids, days, callback ) { getAllTrackDataFromMultiplePlaylists(access_token, ids, [], function( trackData ) { var ids = getTrackIDsViaDateFilter(trackData, days); return callback(ids); }); } //function getAllTrackIDsFromMultiplePlaylists(access_token, ) function playlistExists(playlistName, playlistDicts) { //console.log(playlistDicts); for (i = 0; i < playlistDicts.length; i++) { var dict = playlistDicts[i]; var name = dict.name; //console.log(dict["name"]) if (playlistName == name) { return dict.id; } } return null; } function createPlaylist(access_token, playlistName, user_id, callback) { request.post( { headers: { Authorization: "Bearer " + access_token, "Content-Type": "application/json" }, url: `https://api.spotify.com/v1/users/${user_id}/playlists`, body: `{"name": "${playlistName}", "description":"description", "public": false}` }, function(error, response, body) { return callback(body); } ); } function addSongsToPlaylist(access_token, playlistID, tracks, callback) { var uri_body = '{"uris": ['; var second_set = []; if (tracks.length > 100) { second_set = tracks.slice(101, tracks.length); tracks = tracks.slice(0, 100); } for (i = 0; i < tracks.length; i++) { uri_body = uri_body + `"spotify:track:${tracks[i]}"`; if (i != tracks.length - 1) { uri_body = uri_body + ","; } } uri_body = uri_body + "]}"; var options = { headers: { Authorization: "Bearer " + access_token, "Content-Type": "application/json" }, url: `https://api.spotify.com/v1/playlists/${playlistID}/tracks`, body: uri_body }; request.post(options, function(error, response, body) { console.log("ERROR IN UPDATE" + error); console.log("UPDATE BODY" + body); if (second_set.length > 0) { addSongsToPlaylist(access_token, playlistID, second_set, callback); } else { return callback(); } }); } function updatePlaylist(access_token, playlistID, tracks, callback) { var uri_body = '{"uris": ['; var second_set = []; if (tracks.length > 100) { second_set = tracks.slice(101, tracks.length); tracks = tracks.slice(0, 100); } for (i = 0; i < tracks.length; i++) { uri_body = uri_body + `"spotify:track:${tracks[i]}"`; if (i != tracks.length - 1) { uri_body = uri_body + ","; } } uri_body = uri_body + "]}"; var options = { headers: { Authorization: "Bearer " + access_token, "Content-Type": "application/json" }, url: `https://api.spotify.com/v1/playlists/${playlistID}/tracks`, body: uri_body }; request.put(options, function(error, response, body) { console.log("ERROR IN UPDATE" + error); console.log("UPDATE BODY" + body); if (second_set.length > 0) { addSongsToPlaylist(access_token, playlistID, second_set, function() { return callback(); }); } else { console.log("CALLBACK"); return callback(); } }); } // callback return trackArray, next, error function getSavedTracksFromLibrary(access_token, next_url, callback) { var trackArray = []; var options = { headers: { Authorization: "Bearer " + access_token }, url: next_url }; request.get(options, function(error, response, body) { try { if (error) { console.log("Error occured getting saved library tracks: " + error); return callback(null, null, error); } var trackData = JSON.parse(body); for (i = 0; i < trackData.items.length; i++) { var track = trackData.items[i]; var trackDict = { id: track.track.id, date_added: track.added_at }; trackArray.push(trackDict); } return callback(trackArray, trackData.next, null); } catch (err) { console.log( "An error occured within the request for library tracks " + err.message ); return callback(null, null, err); } }); } // callback returns trackArray and error function getAllSavedTracksFromLibrary( access_token, masterTrackArray, next, error, callback ) { if (next && !error) { getSavedTracksFromLibrary(access_token, next, function( trackArray, next, error ) { if (trackArray) { masterTrackArray = masterTrackArray.concat(trackArray); } getAllSavedTracksFromLibrary( access_token, masterTrackArray, next, error, callback ); }); } else if (error) { return callback(null, error); } else { return callback(masterTrackArray, null); } } function createRecentlyAddedLibraryPlaylist( access_token, playlistName, daysBack, callback ) { try { console.log("Starting recently added library creation..."); var next = "https://api.spotify.com/v1/me/tracks?offset=0&limit=50"; getAllSavedTracksFromLibrary(access_token, [], next, null, function( trackArray, error ) { console.log(trackArray.length); if (!error) { var recentlyAddedIDs = getTrackIDsViaDateFilterLibrary( trackArray, daysBack ); getUserID(access_token, function(user_id, error) { if (!error) { next = "https://api.spotify.com/v1/me/playlists?limit=50"; getAllPlaylistIDs( access_token, next, [], user_id, [], null, function(playlistDicts, error) { if (!error) { var id = playlistExists(playlistName, playlistDicts); if (!id) { console.log("Creating playlist: " + playlistName); createPlaylist( access_token, playlistName, user_id, function(body) { var parsed = JSON.parse(body); var returnID = parsed.id; console.log("Return ID" + returnID); updatePlaylist( access_token, returnID, recentlyAddedIDs, function() { return callback("success"); } ); } ); } else { console.log("Playlist exists, updating tracks..."); updatePlaylist( access_token, id, recentlyAddedIDs, function() { return callback("success"); } ); } } } ); } }); } }); } catch (error) { console.log( "An error occured when trying to create recently added library playlist: " + error ); return callback("error"); } } function createRecentlyAddedPlaylist( access_token, ignore_playlists, playlistName, weeksBack, callback ) { try { console.log("Starting recently added creation..."); getUserID(access_token, function(user_id, error) { if (!error) { // userID retrieved, we now get playlists var ids = []; var next = "https://api.spotify.com/v1/me/playlists?limit=50"; var ignorePlaylists = ignore_playlists.split(","); console.log("Getting playlists..."); getAllPlaylistIDs( access_token, next, ids, user_id, ignorePlaylists, false, function(playlistDicts, error) { console.log( "Playlists found. Getting Tracks... this may take a moment..." ); if (error) { return callback("error"); } var playlistDictsCopy = JSON.parse(JSON.stringify(playlistDicts)); var id = playlistExists(playlistName, playlistDictsCopy); if (id) { index = 0; for (i = 0; i < playlistDicts.length; i++) { if (playlistDicts[i].id == id) { playlistDicts.splice(i, 1); break; } } } getAllTrackDataFromMultiplePlaylists( access_token, playlistDicts, [], function(trackData, error) { console.log( "Tracks obtained... Filtering by days back: " + weeksBack ); var recentlyAddedIDs = getTrackIDsViaDateFilter( trackData, weeksBack ); console.log(recentlyAddedIDs); if (!id) { console.log("Creating playlist: " + playlistName); createPlaylist(access_token, playlistName, user_id, function( body ) { var parsed = JSON.parse(body); var returnID = parsed.id; console.log("Return ID" + returnID); updatePlaylist( access_token, returnID, recentlyAddedIDs, function() { return callback("success"); } ); }); } else { console.log("Playlist exists, updating tracks..."); updatePlaylist( access_token, id, recentlyAddedIDs, function() { return callback("success"); } ); } } ); } ); } }); } catch (err) { console.log(err); return callack("failure"); } } // exports exports.getUserID = getUserID; exports.createRecentlyAddedPlaylist = createRecentlyAddedPlaylist; exports.createRecentlyAddedLibraryPlaylist = createRecentlyAddedLibraryPlaylist;
var fgm = { on: function(element,sEventType,handler) { return element.addEventListener?element.addEventListener(sEventType,handler,false):element.attachEvent("on"+sEventType,handler) }, bind: function(object,handler) { return function(){ return handler.apply(object, arguments) } }, pageX: function(element) { return element.offsetLeft + (element.offsetParent ? arguments.callee(element.offsetParent):0) }, pageY: function(element) { return element.offsetTop + (element.offsetParent ? arguments.callee(element.offsetParent):0) }, hasClass: function(element,className) { return new RegExp("(^|\\s)"+className+"(\\s|$)").test(element.className) }, attr: function(element,attr,value) { if(arguments.length == 2){ return element.attributes[attr]?element.attributes[attr].nodeValue: undefined }else if(arguments.length == 3){ element.setAttribute(attr, value) } } }; //延时加载 function LazyLoad(obj) { this.lazy = typeof obj === "string"?document.getElementById(obj):obj; this.aImg = this.lazy.getElementsByTagName("img"); this.fnLoad = fgm.bind(this,this.load); this.load(); fgm.on(window,"scroll",this.fnLoad); fgm.on(window,"resize",this.fnLoad); } LazyLoad.prototype = { load: function() { var iScrollTop = document.documentElement.scrollTop || document.body.scrollTop; var iChientHeight = document.documentElement.clientHeight + iScrollTop; var aParent = []; var oParent = null; var iTop = 0; var iBottom = 0; var aNotLoaded = this.loaded(0); if(this.loaded(1).length != this.aImg.length){ for (var i = 0; i < aNotLoaded.length; i++) { oParent = aNotLoaded[i].parentElement || aNotLoaded[i].parentNode; iTop = fgm.pageY(oParent); iBottom = iTop + oParent.offseiHeight; if((iTop > iScrollTop && iTop <iChientHeight) || (iBottom > iScrollTop && iBottom < iChientHeight) ){ aNotLoaded[i].src = fgm.attr(aNotLoaded[i],"data-img") || aNotLoaded[i].src; aNotLoaded[i].className = "loaded" } }; } }, loaded: function(status) { var array = []; var i = 0; for (i = 0; i < this.aImg.length; i++) eval("fgm.hasClass(this.aImg[i],\"loaded\")"+(!!status?"&&":"||")+"array.push(this.aImg[i])") return array } }; //应用 fgm.on(window,"load",function(){new LazyLoad("box")})
import React from "react"; import { NavLink } from "react-router-dom"; import { MenuList, MenuItem, Typography, ListItemIcon, Divider, } from "@material-ui/core"; import PersonAddIcon from "@material-ui/icons/PersonAdd"; import PeopleAltIcon from "@material-ui/icons/PeopleAlt"; import logo from "./logo-colorida.png"; export const NavMenu = () => { return ( <MenuList> <img src={logo} alt="Logo" width="80%" /> <Divider /> <Typography variant="h6" align="center"> Menu </Typography> <MenuItem component={NavLink} to="/"> <ListItemIcon> <PeopleAltIcon fontSize="small" /> </ListItemIcon> <Typography variant="inherit">Produtores</Typography> </MenuItem> <MenuItem component={NavLink} to="/produtor/adicionar"> <ListItemIcon> <PersonAddIcon fontSize="small" /> </ListItemIcon> <Typography variant="inherit">Adicionar Produtor</Typography> </MenuItem> </MenuList> ); };
//Variables const qwerty = document.getElementById('qwerty'); const phrase = document.getElementById('phrase'); const startGame = document.querySelector('.btn__reset'); const overlay = document.getElementById("overlay"); const visbilePhrase = document.querySelector('#phrase ul'); //phrase hidden letters const show = document.getElementsByClassName('show'); // visible letters const letters = document.getElementsByClassName('letter'); // phrase letters const liveHearts = document.querySelectorAll('.tries img'); // liveHeart.png image const title = document.querySelector('.title'); // "Wheel of Success" title let missed = 0; //Missed guesses //Phrases phrases = [ 'come on down', 'can i buy a vowel', 'big bucks no wammies', 'deal or no deal', 'you are the weakest link goodbye' ]; //Event listener to the “Start Game” button to hide the start screen overlay startGame.addEventListener("click", () => { overlay.style.display = "none"; }); //getRandomPhraseAsArray function function getRandomPhraseAsArray(arr) { const randomPhrase = arr[Math.floor(Math.random() * arr.length)]; return randomPhrase.split(""); } //display random phrase function addPhraseToDisplay(arr) { for (i = 0; i < arr.length; i++) { const listItem = document.createElement("li"); listItem.textContent = arr[i]; visbilePhrase.appendChild(listItem); if (arr[i] !== " " ) { listItem.className = "letter"; } else { listItem.className = "space"; } } } const phraseArray = getRandomPhraseAsArray(phrases); addPhraseToDisplay(phraseArray); //checkLetter function function checkLetter (guess) { let match = null; for (i = 0; i < letters.length; i++) { if (guess.textContent == letters[i].textContent) { letters[i].classList.add("show"); guess.style.background = '#5ed163'; match = true; } } return match; } //Event listener to the keyboard qwerty.addEventListener( "click", (e) => { if(e.target.tagName == 'BUTTON') { const clickedLetter = e.target; clickedLetter.classList.add("chosen"); clickedLetter.disabled = 'true'; const letterFound = checkLetter(clickedLetter); if( letterFound === null){ let currentMissed = missed; liveHearts[currentMissed].setAttribute("src", "images/lostHeart.png"); missed += 1; } } checkWin(); }); //checkWin function function checkWin() { if(show.length === letters.length) { overlay.style.display = 'flex'; overlay.className = 'win'; title.textContent = 'You won!!'; startGame.textContent = 'Play again'; } else if (missed >= 5) { overlay.style.display = 'flex'; overlay.className = 'lose'; title.textContent = 'You lost!!'; startGame.textContent = 'Play again'; } } window.addEventListener ( "click", (e) => { if(e.target.textContent === 'Play again'){ missed = 0; window.location.reload(true); } });
import './components/clips'; import './components/filters'; import './store/reducers/clips'; import './store/reducers/filters';
function logAllClickPosition() { document.addEventListener("click", event => { console.log(event); console.log("event.clientX :", event.clientX); console.log("event.clientY :", event.clientY); console.log("event.screenX :", event.screenX); console.log("event.screenY :", event.screenY); console.log("event.pageX :", event.pageX); console.log("event.pageY :", event.pageY); }); } function paragraphClickListener(event) { if (event.target.nodeName === "P") { let position = Number(event.target.getAttribute("data-position")); console.log(`paragraph #${position} was clicked`); } } function buildContainingDiv() { const paragraphsDiv = document.createElement("div"); paragraphsDiv.addEventListener("click", paragraphClickListener); return paragraphsDiv; } function buildParagraphTemplate() { return document.createElement("p"); } function buildParagraphFromTemplate(template, index) { const paragraph = template.cloneNode(); paragraph.textContent = `This is paragraph #${index}`; paragraph.setAttribute("data-position", index); paragraph.classList.add("paragraph"); return paragraph; } const params = { paragraphsPerGroup: 1000, triesForEachVersion: 100, only: [ "containingDiv_cloneTemplate_appendInTheLoop", "noContainingDiv_cloneTemplate_appendInTheLoop", "documentFragmentInsteadOfContainingDiv_cloneTemplate_appendInTheLoop" ] }; const versions = { containingDiv_createNewElementEachTime() { const allParagraphsDiv = buildContainingDiv(); const paragraphs = new Array(); for (let i = 0; i < params.paragraphsPerGroup; ) { const paragraph = document.createElement("p"); paragraph.textContent = `This is paragraph #${++i}`; paragraph.setAttribute("data-position", i); paragraph.classList.add("paragraph"); paragraphs.push(paragraph); } allParagraphsDiv.append(...paragraphs); document.body.append(allParagraphsDiv); }, containingDiv_cloneTemplate_appendAllAtOnce() { const allParagraphsDiv = buildContainingDiv(); const template = buildParagraphTemplate(); const paragraphs = []; for (let i = 0; i < params.paragraphsPerGroup; ) { paragraphs.push(buildParagraphFromTemplate(template, ++i)); } allParagraphsDiv.append(...paragraphs); document.body.append(allParagraphsDiv); }, containingDiv_cloneTemplate_appendInTheLoop() { const allParagraphsDiv = buildContainingDiv(); const template = buildParagraphTemplate(); for (let i = 0; i < params.paragraphsPerGroup; ) { allParagraphsDiv.appendChild(buildParagraphFromTemplate(template, ++i)); } document.body.append(allParagraphsDiv); }, noContainingDiv_cloneTemplate_appendInTheLoop() { const template = buildParagraphTemplate(); for (let i = 0; i < params.paragraphsPerGroup; ) { document.body.appendChild(buildParagraphFromTemplate(template, ++i)); } }, documentFragmentInsteadOfContainingDiv_cloneTemplate_appendInTheLoop() { const allParagraphsFragment = document.createDocumentFragment(); const template = buildParagraphTemplate(); for (let i = 0; i < params.paragraphsPerGroup; ) { allParagraphsFragment.appendChild( buildParagraphFromTemplate(template, ++i) ); } document.body.appendChild(allParagraphsFragment); } }; function clean() { const paragraphs = []; for (p of document.getElementsByClassName("paragraph")) { paragraphs.push(p); } for (paragraphDiv of paragraphs) { paragraphDiv.remove(); } console.log(`Cleaned ${paragraphs.length} paragraphs`); } function testAllVersions() { for (version in versions) { if (params.only && params.only.includes(version)) { let durationSum = 0; for (let i = 0; i < params.triesForEachVersion; i++) { const start = performance.now(); versions[version](); const end = performance.now(); durationSum += end - start; } const avgDuration = durationSum / params.triesForEachVersion; console.log(`${version}\n-> ${avgDuration}`); } } clean(); } const n = 30000; function buildHugeAmountOfParagraphs() { const template = buildParagraphTemplate(); for (let i = 0; i < n; ++i) { document.body.appendChild(buildParagraphFromTemplate(template, i)); } } function buildHugeAmountOfParagraphs_inAsyncBlocks() { function doBuild() { const template = buildParagraphTemplate(); for (let i = 0; i < chunk; ++i) { built += 1; document.body.appendChild(buildParagraphFromTemplate(template, built)); if (built >= n) { return; } } setTimeout(doBuild, 0); } let chunk = 10; let built = 0; setTimeout(doBuild, 0); } const nanodegreeSection = document.getElementById("individual-nanodegree-programs"); nanodegreeSection.addEventListener("mouseenter", () => { nanodegreeSection.style.backgroundColor = "red"; }); nanodegreeSection.addEventListener("mouseleave", () => { nanodegreeSection.style.backgroundColor = ""; }); // testAllVersions();
import React, { Component } from "react"; import { HeaderWidget } from "../widgets/HeaderWidget"; import { auth } from 'firebase'; import { Switch, Route, Redirect } from "react-router-dom"; import QuizContainer from "../components/QuizContainer"; import Leaderboard from './LeaderBoard'; export class ApplicationHome extends Component { constructor(props) { super(props); } render() { return ( <div> <HeaderWidget /> <Switch> <Route path="/home/leaderboard" component={Leaderboard} /> <Route path="/home/quiz" component={QuizContainer} /> <Route path="/home/guidelines"> <h1>Yaha Guidelines</h1> </Route> <Redirect from="/" to="/home/leaderboard" /> </Switch> </div> ); } }
// /.netlify/functions/get_posts let firebase = require('./firebase') exports.handler = async function(event) { console.log('inside get_destinationPoints.js') let db = firebase.firestore() let destinationPointData = [] let destinationPointQuery = await db.collection('destinationPoint') //.orderBy('created') .get() let destinationPoints = destinationPointQuery.docs // loop through the post documents for (let i=0; i<destinationPoints.length; i++) { //let destinationPointId = destinationPoints[i].id let destinationPoint = destinationPoints[i].data() let destinationId = destinationPoint.destinationId let destinationImageUrl = destinationPoint.imageUrl let destinationClassId = destinationPoint.destinationClassId // add a new Object to the postsData Array destinationPointData.push({ id: destinationId, imageUrl: destinationImageUrl, classId: destinationClassId }) } console.log(destinationPointData) // return an Object in the format that a Netlify lambda function expects return { statusCode: 200, body: JSON.stringify(destinationPointData) } }
/* eslint no-console: "off" */ const path = require('path') const express = require('express') const cookieParser = require('cookie-parser') const config = require('./config/environment') const app = express() app.use(express.static(path.join(__dirname, 'public'))) if (config.env === 'production') { app.use('/assets', express.static(path.resolve(__dirname, '../build'))) } app.use('/', require('./routes')) app.set('trust proxy') app.use(cookieParser()) app.set('views', path.join(__dirname, 'templates')) app.set('view engine', 'hbs') if (config.env === 'development') { const webpack = require('webpack') const webpackConfig = require('../webpack.config') const compiler = webpack(webpackConfig) app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath })) app.use(require("webpack-hot-middleware")(compiler, { log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000 })) } app.listen(config.port, () => { console.log(`App listening on port ${config.port}`) })
import React, { Component } from "react"; import { Route, Link, Redirect } from "react-router-dom"; const axios = require("axios"); class TodoPage extends Component { constructor(props) { super(props); this.state = { newItem: '', } } componentDidMount() { axios({ method: 'get', url: 'api/todo-item', headers: { Authorization: this.props.cookies.cookies.token, } }) .then(response => { const items = response.data; let itemsHTML = []; items.map(item => { if (item.deleted) { } else { if (item.completed) { itemsHTML.push(<li><del>{item.content}</del></li>) } else { itemsHTML.push(<li>{item.content}</li>) } itemsHTML.push( <div> <form> <input type="button" value="Complete" onClick={() => this.updateToDo(item.id)} /> </form> <form> <input type="button" value="Delete" onClick={() => this.deleteToDo(item.id)} /> </form> </div> ) } }) this.setState({ items: itemsHTML }) }) } addToDo() { const item = this.state.newItem; axios({ method: 'post', url: 'api/todo-item', headers: { Authorization: this.props.cookies.cookies.token, 'content-type': 'application/json', }, data: { "content": item } }) .then(response => { console.log("adding new todo items..."); window.location.reload(); }) } updateToDo(id) { axios({ method: 'put', url: `api/todo-item/${id}`, headers: { Authorization: this.props.cookies.cookies.token, 'content-type': 'application/json', }, data: { "completed": true } }) .then(response => { console.log("UPDATE todo items..."); window.location.reload(); }) } deleteToDo(id) { axios({ method: 'delete', url: `api/todo-item/${id}`, headers: { Authorization: this.props.cookies.cookies.token, }, }) .then(response => { console.log("DELETE todo items..."); window.location = "/home"; }) } logout() { this.props.cookies.remove('token'); console.log(this.props.cookies); window.location = "/"; } handleChange(event) { const name = event.target.name; const value = event.target.value; this.setState({ [name]: value }); }; render() { const { newItem } = this.state; return ( <div align="left"> <br/> <input type="button" value="Logout" onClick={this.logout.bind(this)} /> {/* <form> */} <br/><br/> <label>Insert item to add to the list:</label><br /> <input type="text" name="newItem" placeholder="Enter a new item" value={newItem} onChange={this.handleChange.bind(this)} /> <input type="button" value="Add Item" onClick={this.addToDo.bind(this)} /> <br/><br/> <h1>To-do list:</h1> {/* </form> */} {this.state.items} <br /> </div> ) } } export default TodoPage;
// sticky navbar $(document).ready(function () { $(".navbar").sticky({ topSpacing: 0 }); }); // smooth scroll $(document).ready(function () { $('.scrollto a[href*=#]:not([href=#])').click(function () { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top - 50 }, 1000); return false; } } }); }); // scroll to top $(document).ready(function(){ //Check to see if the window is top if not then display button $(window).scroll(function(){ if ($(this).scrollTop() > 800) { $('.scrollToTop').fadeIn(); } else { $('.scrollToTop').fadeOut(); } }); //Click event to scroll to top $('.scrollToTop').click(function(){ $('html, body').animate({scrollTop : 0},800); return false; }); }); // parallax $(function() { $.stellar(); }); // main flex slider $(window).load(function() { $('.main-flex-slider').flexslider({ slideshowSpeed: 5000, directionNav: false, animation: "fade", controlNav: false }); }); // owl carousel $(document).ready(function() { $("#testi-carousel").owlCarousel({ items: 1, loop:true, autoplay:true, autoplayTimeout:5000, autoplayHoverPause:true }); }); // counter up jQuery(document).ready(function($) { $('.counter').counterUp({ delay: 100, time: 800 }); }); // magnific popup jQuery(document).ready(function($) { $('.show-image').magnificPopup({ type: 'image' }); }); // wow animate var wow = new WOW( { boxClass: 'wow', // animated element css class (default is wow) animateClass: 'animated', // animation css class (default is animated) offset: 100, // distance to the element when triggering the animation (default is 0) mobile: false // trigger animations on mobile devices (true is default) } ); wow.init();
import React from 'react'; export default function Pagination({postsPerPage, totalPosts, paginate, currentPage}) { const pageNumber = []; for(let i = 1; i <= Math.ceil(totalPosts/postsPerPage); i++ ) { pageNumber.push(i); } return ( <nav className="paginate"> <ul className="paginate-list"> {pageNumber.map(number => ( <li key={number}> <button className={number === currentPage ? "btn active-btn" : "btn" } onClick={() => paginate(number)} >{number}</button> </li> ))} </ul> </nav> ) }
import styled from 'styled-components/native'; export const BoxAction = styled.View` flex-direction: row; text-align: center; height: 72px; background-color: #cfe9e5; elevation: 5; `; export const BoxForm = styled.View` justify-content: flex-start; align-items: flex-start; margin-left: 16px; margin-right: 16px; `; export const BoxInput = styled.View` background-color: transparent; border-bottom-width: 0.8px; width: 340px; padding: 5px; border-color: #bdbdbd; `; export const BoxNav = styled.StatusBar.attrs({ barStyle: 'light-content', backgroundColor: '#88c9bf', })``; export const Container = styled.View` flex: 1; background-color: #fafafa; align-items: center; text-align: center; `; export const ContainerLogin = styled.View` justify-content: flex-start; align-items: center; `; export const InputUser = styled.TextInput.attrs({ placeholderTextColor: '#bdbdbd', })` align-items: center; justify-content: center; font-size: 16px; font-family: 'Roboto-Regular'; margin-top: 64px; padding-bottom: 8px; margin-bottom: 20px; width: 321px; border: 2px solid #e6e7e8; border-radius: 3px; `; export const InputPassword = styled(InputUser)` font-family: 'Roboto-Regular'; margin-top: 0px; margin-bottom: 52px; `; export const TextButton = styled.Text` font-size: 12px; font-family: 'Roboto-Regular'; color: ${(props) => props.color || '#f7f7f7'}; `; export const TextTitle = styled.Text` font-size: 20px; font-family: 'Roboto-Medium'; margin: auto 10px; color: #434343; `;
'use strict'; // load modules const express = require('express'); const bodyParser = require('body-parser'); const morgan = require('morgan'); const mongoose = require('mongoose'); // Create express app const app = express(); const url = `mongodb://localhost:27017/course-api`; mongoose.connect(`${url}`); const db = mongoose.connection; // Mongo error catch db.on('error', console.error.bind(console, 'connection error:')); // MandoDB connection db.once("open", () => { console.log("db connection successful"); }); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); // serve static files from /public app.use(express.static(__dirname + '/public')); // view engine setup app.set('view engine', 'pug'); app.set('views', __dirname + '/views'); // set our port app.set('port', process.env.PORT || 5000); // morgan gives us http request logging app.use(morgan('dev')); // API routes = /api. const routes = require('./routes/index'); app.use('/api', routes); // send 404 if no other route matched app.use((req, res) => { res .status(404) .json({message: 'Route Not Found'}) }) // global error handler app.use((err, req, res, next) => { console.error(err.stack); res .status(err.status || 500) .json({message: err.message, error: {}}); }); // start listening on our port const server = app.listen(app.get('port'), () => { console.log(`Express server is listening on port ${server.address().port}`); });
var express = require('express'); var mongoose = require('mongoose'); var router = express.Router(); var Student = mongoose.model('Student'); router.post('/addStudent', function(req,res, next){ var studentData = req.body; Student.findOne({lrn : studentData.lrn}, function(err, student){ if(err){return next(err);}; if(student && student.length > 0){ res.json({ message : "Student already exists!", status : "error"}); }else{ var newStudent = new Student(studentData); newStudent.save(function(err,newStudent){ if(err) {return next(err);} if(newStudent){ newStudent.message = "success"; res.json(newStudent); } }); } }); }); router.get('/',function(req,res,next){ Student.find({},function(err,users){ if(err){return next(err);}; res.json({status : 'success', users : users}); }); }); router.get('/getStudent/:id',function(req,res,next){ var studentID = req.params.id; Student.findOne({lrn : studentID},function(err,users){ if(err){return next(err);}; res.json(users); }); }); module.exports = router;
const express = require('express'); const router = require('express-promise-router')(); const CarsController = require('../controllers/cars'); const { validateBody, validateParam, schemas, checkAuthentication } = require('../helpers/routeHelpers'); router.route('/') .get(CarsController.get_cars) .post(checkAuthentication, validateBody(schemas.carSchema), CarsController.create_car); router.route('/:carId') .get(validateParam(schemas.idSchema, 'carId'), CarsController.get_car) .put(checkAuthentication, validateParam(schemas.idSchema, 'carId'), validateBody(schemas.userCarSchema), CarsController.replace_car) .patch(checkAuthentication, validateParam(schemas.idSchema, 'carId'), validateBody(schemas.carOptionalSchema), CarsController.update_car) .delete(checkAuthentication, validateParam(schemas.idSchema, 'carId'), CarsController.delete_car); module.exports = router;
//CHANGING KEYBOARD.JPG TO SPACE.JPG //document.querySelector("#ima").style.display = 'none' // no image document.querySelector("#ima").src = "space.jpg" //CHNGING IMAGE
var features = {}; var users, servers, sources, libraries; var config, config_text; var user_selected, server_selected, source_selected, library_selected; var selectUser = function() { var selected = []; var options = document.getElementById('user_listing').options; for (var idx = 0; idx < options.length; idx++) { if (options[idx].selected) selected.push(options[idx].value); } user_selected = selected; if (selected.length > 0) { var user; users.forEach(function(user_element) { if (user_element.username === user_selected[0]) { user = user_element; return; } }); document.getElementById('user_modify_button').disabled = false; document.getElementById('user_destroy_button').disabled = false; document.getElementById('user_modify_username').value = user.username; document.getElementById('user_modify_password').value = ''; document.getElementById('user_modify_key').value = ''; document.getElementById('user_modify_admin').checked = user.admin; document.getElementById('user_modify_active').checked = user.active; var select = document.createElement('select'); servers.forEach(function(server) { var option = document.createElement('option'); option.value = server.server; option.innerHTML = server.server; user.servers.forEach(function(user_server) { if (server.server === user_server) option.setAttribute('selected', 'selected'); }); select.appendChild(option); }); document.getElementById('user_modify_servers').innerHTML = select.innerHTML; } else { document.getElementById('user_modify_button').disabled = true; document.getElementById('user_destroy_button').disabled = true; document.getElementById('user_modify_username').value = ''; document.getElementById('user_modify_password').value = ''; document.getElementById('user_modify_key').value = ''; document.getElementById('user_modify_admin').checked = false; document.getElementById('user_modify_active').checked = false; document.getElementById('user_modify_servers').innerHTML = ''; } }; var generateKey = function() { var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var key = ''; for (var i = 0; i < 24; i++) key += chars.charAt(Math.floor(Math.random() * chars.length)); return key; }; var submitUser = function() { var servers = []; var options = document.getElementById('user_create_servers').options; for (var idx = 0; idx < options.length; idx++) { if (options[idx].selected) servers.push(options[idx].value); } createUser(document.getElementById('user_create_username').value, document.getElementById('user_create_password').value, document.getElementById('user_create_key').value, servers, document.getElementById('user_create_admin').checked, document.getElementById('user_create_active').checked, function() { document.getElementById('user_create_username').value = ''; document.getElementById('user_create_password').value = ''; document.getElementById('user_create_key').value = ''; document.getElementById('user_create_admin').checked = false; document.getElementById('user_create_active').checked = true; document.getElementById('user_create_servers').innerHTML = ''; }); }; var submitModifyUser = function() { var servers = []; var options = document.getElementById('user_modify_servers').options; for (var idx = 0; idx < options.length; idx++) { if (options[idx].selected) servers.push(options[idx].value); } modifyUser(document.getElementById('user_modify_username').value, document.getElementById('user_modify_password').value, document.getElementById('user_modify_key').value, servers, document.getElementById('user_modify_admin').checked, document.getElementById('user_modify_active').checked); }; var submitDestroyUser = function() { user_selected.forEach(function(user) { destroyUser(user); }); }; var selectServer = function() { var selected = [] var options = document.getElementById('server_listing').options; for (var idx = 0; idx < options.length; idx++) { if (options[idx].selected) selected.push(options[idx].value); } server_selected = selected; if (selected.length > 0) { document.getElementById('server_upgrade_button').disabled = false; document.getElementById('server_destroy_button').disabled = false; } else { document.getElementById('server_upgrade_button').disabled = true; document.getElementById('server_destroy_button').disabled = true; } }; var submitServer = function() { createServer(document.getElementById('server_name').value, document.getElementById('server_source').value, document.getElementById('server_library').value, function() { document.getElementById('server_name').value = ''; document.getElementById('server_source').value = ''; document.getElementById('server_library').value = ''; }); }; var submitUpgradeServer = function() { server_selected.forEach(function(server) { upgradeServer(server); }); }; var upgradeAllServers = function() { servers.forEach(function(server) { upgradeServer(server.server); }); }; var submitDestroyServer = function() { server_selected.forEach(function(server) { destroyServer(server); }); }; var selectSource = function() { var selected = []; var options = document.getElementById('source_listing').options; for (var idx = 0; idx < options.length; idx++) { if (options[idx].selected) selected.push(options[idx].value); } source_selected = selected; if (selected.length > 0) { document.getElementById('source_update_button').disabled = false; document.getElementById('source_remove_button').disabled = false; } else { document.getElementById('source_update_button').disabled = true; document.getElementById('source_remove_button').disabled = true; } }; var submitSource = function() { addSource(document.getElementById('source_name').value, document.getElementById('source_bzr').value, function() { document.getElementById('source_name').value = ''; document.getElementById('source_bzr').value = ''; }); }; var submitUpdateSource = function() { source_selected.forEach(function(source) { updateSource(source); }); }; var updateAllSources = function() { sources.forEach(function(source) { updateSource(source.source) }); }; var submitRemoveSource = function() { source_selected.forEach(function(source) { removeSource(source); }); }; var selectLibrary = function() { var selected = []; var options = document.getElementById('library_listing').options; for (var idx = 0; idx < options.length; idx++) { if (options[idx].selected) selected.push(options[idx].value); } library_selected = selected; if (selected.length > 0) { document.getElementById('library_update_button').disabled = false; document.getElementById('library_remove_button').disabled = false; } else { document.getElementById('library_update_button').disabled = true; document.getElementById('library_remove_button').disabled = true; } }; var submitLibrary = function() { addLibrary(document.getElementById('library_name').value, document.getElementById('library_bzr').value, function() { document.getElementById('library_name').value = ''; document.getElementById('library_bzr').value = ''; }); }; var submitUpdateLibrary = function() { library_selected.forEach(function(library) { updateLibrary(library); }); }; var updateAllLibraries = function() { libraries.forEach(function(library) { updateLibrary(library.library) }); }; var submitRemoveLibrary = function() { library_selected.forEach(function(library) { removeLibrary(library); }); }; var saveConfig = function() { updateConfig(config.getValue(), function() { alert('Config successfully saved'); }); }; var restartDaemon = function() { restart(function() { alert('Daemon successfully restarted'); }); }; var refresh = function(force) { if (typeof force !== 'boolean') force = false; if (count > 0 && !force) { setTimeout(refresh, 200); return; } getFeatures(function(response) { if (response === features) return; features = response; if (features.creation) { document.getElementById('config_button').disabled = false; if (isVisible(document.getElementById('server_button')) || force) document.getElementById('server_button').disabled = false; } else { document.getElementById('config_button').disabled = true; if (isVisible(document.getElementById('server_button')) || force) document.getElementById('server_button').disabled = true; } }); getUsers(function(response) { if (response === users) return; users = response; if (isVisible(document.getElementById('user_listing')) || force) { var select = document.createElement('select'); users.forEach(function(user) { var option = document.createElement('option'); option.value = user.username; option.innerHTML = user.username + (user.admin ? ' (Admin)' : '') + (user.active ? '' : ' (Inactive)') + (user.servers.length > 0 ? ' - ' + user.servers.join(', ') : ''); select.appendChild(option); }); if (document.getElementById('user_listing').innerHTML !== select.innerHTML) { document.getElementById('user_listing').innerHTML = select.innerHTML; selectUser(); } } }); getServers(function(response) { if (response === servers) return; servers = response; if (isVisible(document.getElementById('server_listing')) || force) { var select = document.createElement('select'); servers.forEach(function(server) { var option = document.createElement('option'); option.value = server.server; option.innerHTML = server.server + ' - ' + server.source + ' (r' + server.revision + ')'; select.appendChild(option); }); if (document.getElementById('server_listing').innerHTML !== select.innerHTML) { document.getElementById('server_listing').innerHTML = select.innerHTML; selectServer(); } } if (isVisible(document.getElementById('user_create_servers')) || force) { var select = document.createElement('select'); servers.forEach(function(server) { var option = document.createElement('option'); option.value = server.server; option.innerHTML = server.server; select.appendChild(option); }); if (document.getElementById('user_create_servers').innerHTML !== select.innerHTML) document.getElementById('user_create_servers').innerHTML = select.innerHTML; } }); getSources(function(response) { if (response === sources) return; sources = response; if (isVisible(document.getElementById('source_listing')) || force) { var select = document.createElement('select'); sources.forEach(function(source) { var option = document.createElement('option'); option.value = source.source; option.innerHTML = source.source + ' - r' + source.revision; select.appendChild(option); }); if (document.getElementById('source_listing').innerHTML !== select.innerHTML) { document.getElementById('source_listing').innerHTML = select.innerHTML; selectSource(); } } if (isVisible(document.getElementById('server_source')) || force) { var select = document.createElement('select'); sources.forEach(function(source) { var option = document.createElement('option'); option.value = source.source; option.innerHTML = source.source; select.appendChild(option); }); if (document.getElementById('server_source').innerHTML !== select.innerHTML) document.getElementById('server_source').innerHTML = select.innerHTML; } }); getLibraries(function(response) { if (response === libraries) return; libraries = response; if (isVisible(document.getElementById('library_listing')) || force) { var select = document.createElement('select'); libraries.forEach(function(library) { var option = document.createElement('option'); option.value = library.library; option.innerHTML = library.library + ' - r' + library.revision; select.appendChild(option); }); if (document.getElementById('library_listing').innerHTML !== select.innerHTML) { document.getElementById('library_listing').innerHTML = select.innerHTML; selectLibrary(); } } if (isVisible(document.getElementById('server_library')) || force) { var select = document.createElement('select'); var option = document.createElement('option'); option.value = ''; option.innerHTML = 'None'; select.appendChild(option); libraries.forEach(function(library) { var option = document.createElement('option'); option.value = library.library; option.innerHTML = library.library; select.appendChild(option); }); if (document.getElementById('server_library').innerHTML !== select.innerHTML) document.getElementById('server_library').innerHTML = select.innerHTML; } }); if ((isVisible(document.getElementById('config_editor')) || force) && features.creation) { getConfig(function(response) { if (config_text === response) return; config_text = response; config.setValue(config_text); }); } if (isVisible(document.getElementById('loading'))) { document.getElementById('loading').className = 'none'; document.getElementById('users').className = ''; document.getElementById('servers').className = 'none'; document.getElementById('sources').className = 'none'; document.getElementById('config').className = 'none'; } setTimeout(refresh, 500); }; var load = function() { document.getElementById('users_button').addEventListener('click', function(ev) { change('users'); ev.preventDefault(); }, false); document.getElementById('servers_button').addEventListener('click', function(ev) { change('servers'); ev.preventDefault(); }, false); document.getElementById('sources_button').addEventListener('click', function(ev) { change('sources'); ev.preventDefault(); }, false); document.getElementById('libraries_button').addEventListener('click', function(ev) { change('libraries'); ev.preventDefault(); }, false); document.getElementById('config_button').addEventListener('click', function(ev) { change('config'); config.refresh(); ev.preventDefault(); }, false); document.getElementById('restart_button').addEventListener('click', function(ev) { restartDaemon(); ev.preventDefault(); }, false); document.getElementById('server_button').addEventListener('click', function(ev) { goto('/server'); ev.preventDefault(); }, false); document.getElementById('user_button').addEventListener('click', function(ev) { goto('/user'); ev.preventDefault(); }, false); document.getElementById('logout_button').addEventListener('click', function(ev) { unsetCookie(); goto('/'); ev.preventDefault(); }, false); document.getElementById('user_create_button').addEventListener('click', function(ev) { change('users', 'user_create'); ev.preventDefault(); }, false); document.getElementById('user_modify_button').addEventListener('click', function(ev) { change('users', 'user_modify'); ev.preventDefault(); }, false); document.getElementById('user_destroy_button').addEventListener('click', function(ev) { submitDestroyUser(); ev.preventDefault(); }, false); document.getElementById('user_listing').addEventListener('change', function(ev) { selectUser(); ev.preventDefault(); }, false); document.getElementById('user_create_generate').addEventListener('click', function(ev) { document.getElementById('user_create_form').elements['key'].value = generateKey(); ev.preventDefault(); }, false); document.getElementById('user_create_cancel').addEventListener('click', function(ev) { change('users', 'user_list'); ev.preventDefault(); }, false); document.getElementById('user_create_form').addEventListener('submit', function(ev) { submitUser(); change('users', 'user_list'); ev.preventDefault(); }, false); document.getElementById('user_modify_generate').addEventListener('click', function(ev) { document.getElementById('user_modify_form').elements['key'].value = generateKey(); ev.preventDefault(); }, false); document.getElementById('user_modify_cancel').addEventListener('click', function(ev) { change('users', 'user_list'); ev.preventDefault(); }, false); document.getElementById('user_modify_form').addEventListener('submit', function(ev) { submitModifyUser(); change('users', 'user_list'); ev.preventDefault(); }, false); document.getElementById('server_create_button').addEventListener('click', function(ev) { change('servers', 'server_create'); ev.preventDefault(); }, false); document.getElementById('server_upgrade_button').addEventListener('click', function(ev) { submitUpgradeServer(); ev.preventDefault(); }, false); document.getElementById('server_destroy_button').addEventListener('click', function(ev) { submitDestroyServer(); ev.preventDefault(); }, false); document.getElementById('server_upgrade_all_button').addEventListener('click', function(ev) { upgradeAllServers(); ev.preventDefault(); }, false); document.getElementById('server_listing').addEventListener('change', function(ev) { selectServer(); ev.preventDefault(); }, false); document.getElementById('server_cancel').addEventListener('click', function(ev) { change('servers', 'server_list'); ev.preventDefault(); }, false); document.getElementById('server_create_form').addEventListener('submit', function(ev) { submitServer(); change('servers', 'server_list'); ev.preventDefault(); }, false); document.getElementById('source_add_button').addEventListener('click', function(ev) { change('sources', 'source_add'); ev.preventDefault(); }, false); document.getElementById('source_update_button').addEventListener('click', function(ev) { submitUpdateSource(); ev.preventDefault(); }, false); document.getElementById('source_remove_button').addEventListener('click', function(ev) { submitRemoveSource(); ev.preventDefault(); }, false); document.getElementById('source_update_all_button').addEventListener('click', function(ev) { updateAllSources(); ev.preventDefault(); }, false); document.getElementById('source_listing').addEventListener('change', function(ev) { selectSource(); ev.preventDefault(); }, false); document.getElementById('source_cancel').addEventListener('click', function(ev) { change('sources', 'source_list'); ev.preventDefault(); }, false); document.getElementById('source_add_form').addEventListener('submit', function(ev) { submitSource(); change('sources', 'source_list'); ev.preventDefault(); }, false); document.getElementById('library_add_button').addEventListener('click', function(ev) { change('libraries', 'library_add'); ev.preventDefault(); }, false); document.getElementById('library_update_button').addEventListener('click', function(ev) { submitUpdateLibrary(); ev.preventDefault(); }, false); document.getElementById('library_remove_button').addEventListener('click', function(ev) { submitRemoveLibrary(); ev.preventDefault(); }, false); document.getElementById('library_update_all_button').addEventListener('click', function(ev) { updateAllLibraries(); ev.preventDefault(); }, false); document.getElementById('library_listing').addEventListener('change', function(ev) { selectLibrary(); ev.preventDefault(); }, false); document.getElementById('library_cancel').addEventListener('click', function(ev) { change('libraries', 'library_list'); ev.preventDefault(); }, false); document.getElementById('library_add_form').addEventListener('submit', function(ev) { submitLibrary(); change('libraries', 'library_list'); ev.preventDefault(); }, false); document.getElementById('config_submit').addEventListener('click', function(ev) { saveConfig(); ev.preventDefault(); }, false); config = CodeMirror(document.getElementById('config_codemirror'), { mode: 'settings', lineNumbers: true, lineWrapping: true, showTrailingSpace: true, theme: 'mcp', placeholder: 'Here you can specify configuration global to every server. Generally GLOBAL_ID and TALK_TO_MASTER are turned on here but you should also specify a SERVER_DNS.' }); refresh(true); }; window.addEventListener('load', load, false);
function status(state = [], action) { switch(action.type) { case 'UPDATE_STATUS': return action.status default: return state; } } export default status;
'use strict'; const Reflect = require( 'harmony-reflect' ); const actions = [ 'del', 'get', 'head', 'opts', 'post', 'put', 'patch' ]; module.exports = function( server ) { const middlewares = Reflect.apply( Array.prototype.slice, arguments, [ 1 ] ); const callback = middlewares.pop(); if( typeof callback !== 'function' ) { throw new Error( 'Last argument must be a callback function' ); } function callServer( method, args ) { const callArgs = Reflect.apply( Array.prototype.slice, args, [ 0 ] ); Reflect.apply( callArgs.splice, callArgs, [ 1, 0 ].concat( middlewares ) ); return Reflect.apply( server[ method ], server, callArgs ); } const innerServer = {}; actions.forEach( action => { innerServer[ action ] = function() { callServer( action, arguments ); }; } ); return callback( innerServer ); }; module.exports.inline = function() { const middlewaresAndCallback = []; for( let i = 0; i < arguments.length; i++ ) { middlewaresAndCallback.push( arguments[ i ] ); } return function( server ) { const args = [ server ].concat( middlewaresAndCallback ); return Reflect.apply( module.exports, null, args ); }; };
function solve(n) { function printTriangle(count) { for(let i = 1; i <= count; i++){ console.log('*'.repeat(i)); } for(let i = count - 1; i >= 1; i--){ console.log('*'.repeat(i)); } } printTriangle(n); } solve(1); solve(2); solve(5);
const mongoose = require('mongoose'); const chats = mongoose.Schema({ conversationId: { conv_Id : mongoose.Schema.ObjectId }, author : String, to : String, body : String, date : Date }); module.exports = mongoose.model('chats', chats);
angular.module('AppEmpleo', []) .controller('empleoTrimestralCtrl', ['$scope', 'OfertaEmpleoServi', '$state',function ($scope, OfertaEmpleoServi, $state){ OfertaEmpleoServi.cargando(); $scope.empleo = {}; $scope.id = $state.params.id; OfertaEmpleoServi.cargarDatosEmplMensual($scope.id, $state.params.offline) .then(function (data) { $scope.empleo = data.empleo; $scope.tipo_cargo = data.tipo_cargo; OfertaEmpleoServi.cerrarCargando(); }).catch(function () { alert("Error"); OfertaEmpleoServi.cerrarCargando(); }); $scope.guardar = function (form) { $scope.empleo.Encuesta = $scope.id; if (form.$valid && $scope.validacion()) { OfertaEmpleoServi.cargando(); OfertaEmpleoServi.guardarEmpleoMensual($scope.id,$scope.empleo, $state.params.offline) .then(function (data) { if (data.success == true) { $state.go( "app.empleadosCaracterizacion" , {id:$scope.id, offline: $state.params.offline} ); } else { $scope.errores = data.errores; } OfertaEmpleoServi.cerrarCargando(); }).catch(function () { alert("Error"); OfertaEmpleoServi.cerrarCargando(); }); } else { OfertaEmpleoServi.showAlertError(); } } $scope.cargo = function(tipo){ if($scope.empleo.Sexo){ for(var i = 0; i < $scope.empleo.Sexo.length ; i ++){ if($scope.empleo.Sexo[i].tipo_cargo_id == tipo ){ return $scope.empleo.Sexo[i]; } } var obj = {}; obj.tipo_cargo_id = tipo; obj.hombres = 0; obj.mujeres = 0; $scope.empleo.Sexo.push(obj); return obj; } } $scope.Totalcargo = function(){ if($scope.empleo.Sexo){ var total = 0; for(var i = 0; i < $scope.empleo.Sexo.length ; i ++){ total = total + $scope.empleo.Sexo[i].hombres + $scope.empleo.Sexo[i].mujeres; } } else{ return 0; } return total; } $scope.Total = function(item,item2){ if($scope.empleo[item]){ var total = 0; for(var i = 0; i < $scope.empleo[item].length ; i ++){ total = total + ($scope.empleo[item][i][item2] == null ? 0 : ($scope.empleo[item][i][item2] == undefined ? 0 : $scope.empleo[item][i][item2])); } }else{ return 0; } return total; } $scope.totalfila = function(obj,tipo,sexo){ if(obj){ for(var i = 0; i < obj.length ; i ++){ if(obj[i].tipo_cargo_id == tipo && obj[i].sexo == sexo ){ var suma = 0; for (var item in obj[i]) { if(!(item == "id" || item == "sexo" || item == "tipo_cargo_id" || item == "encuestas_id" || item == "encuesta_id")) suma = suma + (obj[i][item] == null ? 0 : (obj[i][item] == undefined ? 0 :obj[i][item])); } return suma; } } } return 0; } $scope.edadempleado = function(tipo,sexo){ if($scope.empleo.Edad){ for(var i = 0; i < $scope.empleo.Edad.length ; i ++){ if($scope.empleo.Edad[i].tipo_cargo_id == tipo && $scope.empleo.Edad[i].sexo == sexo ){ return $scope.empleo.Edad[i]; } } var obj = {}; obj.tipo_cargo_id = tipo; obj.sexo = sexo == 1 ? true : false ; obj.docea18 = 0; obj.diecinuevea25 = 0; obj.ventiseisa40 = 0; obj.cuarentayunoa64 = 0; obj.mas65 = 0; $scope.empleo.Edad.push(obj); return obj; } } $scope.eduacionempleado = function(tipo,sexo){ if($scope.empleo.Educacion){ for(var i = 0; i < $scope.empleo.Educacion.length ; i ++){ if($scope.empleo.Educacion[i].tipo_cargo_id == tipo && $scope.empleo.Educacion[i].sexo == sexo ){ return $scope.empleo.Educacion[i]; } } var obj = {}; obj.tipo_cargo_id = tipo; obj.sexo = sexo == 1 ? true : false; obj.ninguno = 0; obj.posgrado = 0; obj.bachiller = 0; obj.universitario = 0; obj.tecnico = 0; obj.tecnologo = 0; $scope.empleo.Educacion.push(obj); return obj; } } $scope.ingleempleado = function(tipo,sexo){ if($scope.empleo.ingles){ for(var i = 0; i < $scope.empleo.ingles.length ; i ++){ if($scope.empleo.ingles[i].tipo_cargo_id == tipo && $scope.empleo.ingles[i].sexo == sexo ){ return $scope.empleo.ingles[i]; } } var obj = {}; obj.tipo_cargo_id = tipo; obj.sexo = sexo == 1 ? true : false ; obj.sabeningles = 0; $scope.empleo.ingles.push(obj); return obj; } } $scope.vinculacionempleado = function(tipo,sexo){ if($scope.empleo.Vinculacion){ for(var i = 0; i < $scope.empleo.Vinculacion.length ; i ++){ if($scope.empleo.Vinculacion[i].tipo_cargo_id == tipo && $scope.empleo.Vinculacion[i].sexo == sexo ){ return $scope.empleo.Vinculacion[i]; } } var obj = {}; obj.sexo = sexo == 1 ? true : false ; obj.tipo_cargo_id = tipo; obj.sexo = sexo == 1 ? true : false ; obj.contrato_direto = 0; obj.personal_permanente = 0; obj.personal_agencia = 0; obj.trabajador_familiar = 0; obj.propietario = 0; obj.aprendiz = 0; obj.cuenta_propia = 0; $scope.empleo.Vinculacion.push(obj); return obj; } } $scope.tiempoempleado = function(tipo,sexo){ if($scope.empleo.Empleo){ for(var i = 0; i < $scope.empleo.Empleo.length ; i ++){ if($scope.empleo.Empleo[i].tipo_cargo_id == tipo && $scope.empleo.Empleo[i].sexo == sexo ){ return $scope.empleo.Empleo[i]; } } var obj = {}; obj.tipo_cargo_id = tipo; obj.sexo = sexo == 1 ? true : false ; obj.tiempo_completo = 0; obj.medio_tiempo = 0; $scope.empleo.Empleo.push(obj); return obj; } } $scope.remuneracion = function(tipo,sexo){ if($scope.empleo.Remuneracion){ for(var i = 0; i < $scope.empleo.Remuneracion.length ; i ++){ if($scope.empleo.Remuneracion[i].tipo_cargo_id == tipo && $scope.empleo.Remuneracion[i].sexo == sexo ){ return $scope.empleo.Remuneracion[i]; } } obj = {}; obj.tipo_cargo_id = tipo; obj.sexo = sexo == 1 ? true : false ; obj.valor = 0; $scope.empleo.Remuneracion.push(obj); return obj; } } $scope.promedio = function(){ if( $scope.remuneracion(1,1) == null){ return 0; } var valor = ($scope.remuneracion(1,1).valor*$scope.cargo(1).hombres) + ($scope.remuneracion(1,0).valor*$scope.cargo(1).mujeres) + ($scope.remuneracion(2,1).valor*$scope.cargo(2).hombres) + ($scope.remuneracion(2,0).valor*$scope.cargo(2).mujeres) + ($scope.remuneracion(3,1).valor*$scope.cargo(3).hombres) + ($scope.remuneracion(3,0).valor*$scope.cargo(3).mujeres) ; var valor2 = ( $scope.cargo(1).mujeres + $scope.cargo(1).hombres + $scope.cargo(2).mujeres + $scope.cargo(2).hombres + $scope.cargo(3).mujeres + $scope.cargo(3).hombres) if (valor2 != 0){ return valor / valor2 } return 0 } $scope.vacantesSi = function(){ var vacante = ( $scope.empleo.VacanteOperativo == null ? 0 : ($scope.empleo.VacanteOperativo == undefined ? 0 :$scope.empleo.VacanteOperativo )); var vacante2 = ( $scope.empleo.VacanteAdministrativo == null ? 0 : ($scope.empleo.VacanteAdministrativo == undefined ? 0 :$scope.empleo.VacanteAdministrativo )); var vacante3 = ( $scope.empleo.VacanteGerencial == null ? 0 : ($scope.empleo.VacanteGerencial == undefined ? 0 :$scope.empleo.VacanteGerencial )); if(( vacante + vacante2 + vacante3 ) > 0){ return true; }else{ if($scope.empleo != null){ $scope.empleo.Razon = {}; $scope.empleo.Razon.apertura = 0; $scope.empleo.Razon.crecimiento = 0; $scope.empleo.Razon.remplazo = 0; } return false; } } $scope.validacion = function(){ return true; } }]) .controller('empleoCaracterizacionCtrl', ['$scope', 'OfertaEmpleoServi', '$state',function ($scope, OfertaEmpleoServi,$state) { OfertaEmpleoServi.cargando(); $scope.empleo = {}; $scope.id = $state.params.id; OfertaEmpleoServi.cargarDatosEmplCaract($scope.id, $state.params.offline) .then(function (data) { $scope.empleo = data.empleo; $scope.data = data.data; OfertaEmpleoServi.cerrarCargando(); }).catch(function () { alert("Error"); OfertaEmpleoServi.cerrarCargando(); }); $scope.agregar = function(){ var obj = {}; obj.realizada_empresa = 0; $scope.empleo.tematicas.push(obj); } $scope.quitar = function(obj){ $scope.empleo.tematicas.splice($scope.empleo.tematicas.indexOf(obj),1); } $scope.existeOpcion = function(obj){ for (var i = 0; i < $scope.empleo.medios.length; i++) { if($scope.empleo.medios[i] == obj){ return true; } } return false; } $scope.existeTipo = function(obj){ for (var i = 0; i < $scope.empleo.tipos.length; i++) { if($scope.empleo.tipos[i] == obj){ return true; } } return false; } $scope.validar = function(){ if($scope.empleo.capacitacion == 1 && $scope.empleo.tematicas.length == 0){ return true; } } $scope.guardar = function (form) { $scope.empleo.Encuesta = $scope.id; if (form.$valid || $scope.validar()) { OfertaEmpleoServi.cargando(); OfertaEmpleoServi.guardarEmpCaracterizacion($scope.id,$scope.empleo, $state.params.offline) .then(function (data) { if (data.success == true) { $state.go( "app.listadoEncuestasSinLLenar" , { id: data.idsitio, offline: $state.params.offline } ); } else { $scope.errores = data.errores; OfertaEmpleoServi.showAlertError(); } }).catch(function () { alert("Error"); OfertaEmpleoServi.cerrarCargando(); }) } else { OfertaEmpleoServi.showAlertError(); } } }]) .controller('empleoMensualCtrl', ['$scope', 'OfertaEmpleoServi', '$state',function ($scope, OfertaEmpleoServi,$state){ OfertaEmpleoServi.cargando(); $scope.empleo = {}; $scope.id = $state.params.id; OfertaEmpleoServi.cargarDatosEmpleo($scope.id, $state.params.offline) .then(function (data) { $scope.empleo = data.empleo; OfertaEmpleoServi.cerrarCargando(); }).catch(function () { alert("Error"); OfertaEmpleoServi.cerrarCargando(); }); $scope.cargo = function(tipo){ if($scope.empleo.Sexo){ for(i = 0; i < $scope.empleo.Sexo.length ; i ++){ if($scope.empleo.Sexo[i].tipo_cargo_id == tipo ){ return $scope.empleo.Sexo[i]; } } obj = {}; obj.tipo_cargo_id = tipo; obj.hombres = 0; obj.mujeres = 0; $scope.empleo.Sexo.push(obj); return obj; } } $scope.validacion = function(){ return true; } $scope.guardar = function (empleoForm) { $scope.empleo.Encuesta = $scope.id; if (empleoForm.$valid && $scope.validacion()) { OfertaEmpleoServi.cargando(); OfertaEmpleoServi.guardarempleo($scope.id,$scope.empleo, $state.params.offline) .then(function (data) { if (data.success == true) { $state.go( "app.listadoEncuestasSinLLenar" , { id: data.sitio, offline: $state.params.offline } ); } else { $scope.errores = data.errores; } OfertaEmpleoServi.cerrarCargando(); }).catch(function () { alert("Error"); OfertaEmpleoServi.cerrarCargando(); }) } else { OfertaEmpleoServi.showAlertError(); } } }])
import React, { Component } from 'react'; import { NavLeft, Link, Page, Navbar, Icon, Row, Col, Card } from 'framework7-react'; import { dict } from '../../Dict'; import ModelStore from "../../stores/ModelStore"; import * as MyActions from "../../actions/MyActions"; import Framework7 from 'framework7/framework7.esm.bundle' import HomeContent from "../../containers/home/index" export default class HomePage extends Component { constructor() { super(); this.getMutipleList = this.getMutipleList.bind(this); this.sortChange = this.sortChange.bind(this); this.loadData = this.loadData.bind(this); this.loadCalender = this.loadCalender.bind(this); this.pageAfterIn = this.pageAfterIn.bind(this); this.state = { token: window.localStorage.getItem('token'), tasks: null, works: null, notifications: null, reports: null, events: null, statusChanges: null, taskPage: 1, taskPp: 10, } } componentWillMount() { ModelStore.on("got_multiple_list", this.getMutipleList); } componentWillUnmount() { ModelStore.removeListener("got_multiple_list", this.getMutipleList); } loadCalender() { // this.$$('.page-content').scrollTop(this.$$('#status-card')[0].offsetTop) const self = this; const app = self.$f7; var events = [] if (self.state.events) { self.state.events.map((ev) =>{ events.push({date: new window.ODate(ev.date), color: ev.color}) }) } console.log(events) var monthNames = ['فروردين', 'ارديبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'] var calendarInline = app.calendar.create({ containerEl: '#demo-calendar-inline-container', value: [new Date()], weekHeader: false, events: events, renderToolbar: function () { return '<div class="toolbar calendar-custom-toolbar no-shadow">' + '<div class="toolbar-inner">' + '<div class="left">' + '<a href="#" class="link icon-only"><i class="icon icon-back ' + (app.theme === 'md' ? 'color-black' : '') + '"></i></a>' + '</div>' + '<div class="center"></div>' + '<div class="right">' + '<a href="#" class="link icon-only"><i class="icon icon-forward ' + (app.theme === 'md' ? 'color-black' : '') + '"></i></a>' + '</div>' + '</div>' + '</div>'; }, on: { init: function (c) { self.$$('.calendar-custom-toolbar .center').text(monthNames[c.currentMonth] + ', ' + c.currentYear); self.$$('.calendar-custom-toolbar .left .link').on('click', function () { calendarInline.prevMonth(); }); self.$$('.calendar-custom-toolbar .right .link').on('click', function () { calendarInline.nextMonth(); }); }, monthYearChangeStart: function (c) { self.$$('.calendar-custom-toolbar .center').text(monthNames[c.currentMonth] + ', ' + c.currentYear); }, dayClick: function (calendar, dayEl, year, month, day) { console.log(year, month, day) } } }); } pageAfterIn() { } componentDidMount() { this.loadData(); } loadData() { const f7: Framework7 = Framework7.instance; f7.toast.show({ text: dict.receiving, closeTimeout: 2000, position: 'top' }); var data = {task_page: this.state.taskPage, task_pp: this.state.taskPp} MyActions.getMultipleList('home', this.state.page, data, this.state.token); } getMutipleList() { var multiple = ModelStore.getMutipleList() var klass = ModelStore.getKlass() console.log(multiple) if (multiple && klass === 'Home') { this.setState({ tasks: multiple.tasks, works: multiple.works, notifications: multiple.notifications, reports: multiple.reports, tasksVisits: multiple.tasks_visits, events: multiple.events, statusChanges: multiple.status_change, }, () => this.loadCalender()); } } sortChange(i) { MyActions.getList('tasks', this.state.page, { order: i.title }, this.state.token); } render() { const { tasks, works, notifications, reports, tasksVisits,statusChanges } = this.state; return (<HomeContent notifications={notifications} tasksVisits={tasksVisits} reports={reports} tasks={tasks} works={works} sortChange={this.sortChange} pageAfterIn={this.pageAfterIn} statusChanges={statusChanges} />) } }
import React from 'react'; import { FormattedMessage } from 'react-intl'; export const languages = [ { name: <FormattedMessage id="Language.dutch" description="Dutch" defaultMessage="Dutch" />, locale: 'nl' }, { name: <FormattedMessage id="Language.english" description="English" defaultMessage="English" />, locale: 'en' }, { name: <FormattedMessage id="Language.french" description="French" defaultMessage="French" />, locale: 'fr' }, { name: <FormattedMessage id="Language.german" description="German" defaultMessage="German" />, locale: 'de' }, { name: <FormattedMessage id="Language.spanish" description="Spanish" defaultMessage="Spanish" />, locale: 'es' } ];
//= require widgit/vendors //= require widgit/components //= require widgit/admin
import _ from 'lodash'; import test from 'ava'; import Datastore from 'nedb'; import Domainer from 'baiacu'; import promisify from 'promisify-node'; import Manager from 'baiacu-managers-mongodb'; import { IdentityTransmutter } from 'baiacu/middleware'; import * as models from './models'; const collections = {} const connection = { databaseName: 'in-memory', collection: name => { if (!collections[name]) collections[name] = new Datastore({ inMemoryOnly: true, autoload: true, }) return collections[name] }, }; const { Person, Author } = new Domainer(models) .use(new IdentityTransmutter()) .use({ get(source, property, response) { if (property !== 'collection') return response; return source.name.toLowerCase(); } }) .use(new Manager({ connection })) .export; test.before(async t => { await promisify(Person.objects.insert).call(Person.objects, { firstName: 'Carlos', lastName: 'Silva', }); await promisify(Author.objects.insert).call(Author.objects, { firstName: 'Richard', lastName: 'Dawkins', }); }); test('it should load the inserted data', async t => { const people = await promisify(Person.objects.find).call(Person.objects, {}); const authors = await promisify(Author.objects.find).call(Author.objects, {}); t.is(people.length, 1); t.is(authors.length, 1); t.is(people[0].firstName, 'Carlos'); t.is(authors[0].firstName, 'Richard'); });
//alert("Helo a script fájlból!"); //alert("Helló Világ!"); console.log("cosolra írunk a sectionben!!"); document.write("Hello Volvo a sectionben"); //document.getElementById("a").value()="halihó"; document.getElementById("a").value = 2; document.getElementById("b").value = 3; var valtozoA = document.getElementById("a").value; var valtozoB = document.getElementById("b").value; document.write("<p style='color:red'> Első érték:" + valtozoA + "</p>"); document.write("<p>Első változó:" + valtozoA + "</p>"); document.write("<p>Második változó:" + valtozoB + "</p>"); var osszeg = Number(valtozoA) + Number(valtozoB); document.write("<p>A kétszám összege:" + osszeg + "</p>"); document.write("<p>1,2,3,4,5,6,7,8,9,10</p>"); var szoveg = ""; //var seged = 0; //for (var i = 1; i < 101; i++) { // szoveg += i + ", "; // seged++; // if (seged === 10) // { // szoveg += "<br>"; // seged = 0; // } //} // //for (var i = 1; i < 101; i++) { // szoveg += i + ", "; // if (i % 10 === 0) // { // szoveg += "<br>"; // } //} kiir(); function kiir() { for (var i = 1; i < 101; i++) { szoveg += i + ", "; if (i % 10 === 0) { szoveg += "<br>"; } } } document.write("<p>" + szoveg + "</p>");
var fs = require('fs'), path = require('path'), couchbase = require('couchbase'), // cluster definition can also be defined in a json file with at the key/namespace 'url' cluster = (function(){ var configStr, clusterURL = 'couchbase://cfo-pet-adoption.eastus.cloudapp.azure.com'; try{ configStr = fs.readFileSync(path.resolve(__dirname, 'couchbase.config')); clusterURL = JSON.parse(configStr)['url']; } catch (err){ console.error(err); } return new couchbase.Cluster(clusterURL); })(); module.exports = cluster;
define([ // Basic dependencies 'underscore', 'app', 'marionette', './views/layout' ], function(_, app, Marionette, LayoutView) { return Marionette.Controller.extend({ initialize: function(options) { this.layoutView = new LayoutView(); }, getView: function() { return this.layoutView; } }); });
export { default } from './dot-nav';
import authService from "../../services/authService.js"; import { registerTemplate } from "./registerTemplate.js"; async function getView(context) { let boundSubmitHandler = submitHandler.bind(null, context); let form = { submitHandler: boundSubmitHandler } let templateResult = registerTemplate(form); context.renderView(templateResult); } async function submitHandler(context, e) { e.preventDefault(); let form = e.target; let formData = new FormData(form); let user = { email: formData.get("email"), password: formData.get("password") } let repeatPassword = formData.get("rePass"); if (user.email.trim() == "" || user.password.trim() == "" || repeatPassword.trim() == "") { return alert("All fields are required!"); } if (user.password != repeatPassword) { form.reset(); return alert("The passwords do not match!"); } let registerResult = await authService.register(user); context.page.redirect("/dashboard"); } export default { getView }
/*Add list items*/ function Add () { /*Add item is the id of the input text*/ var itemValue = $('#newItem').val(); //dynamicaly create one row inside the shopping list var row = $('<li><button class="checkbox">&#x2713;</button><span class="list">' + itemValue + '</span><button class="delete" id="remove-button">x</button></li>'); //add each row to the previous ones /* #List id is the id of the UL element*/ $('#itemList').append(row); // body... } /*Delete list items*/ function DeleteAll () { $('#itemList').empty(); } /*Delete individual item*/ function Delete () { $(this).parent().remove(); // body... } /*Check off item*/ function Check () { /*function to select an item to cross out Note: create the 'checked' class in CSS first! */ $(this).parent().toggleClass('checked'); // body... } $(document).ready(function() { //*Add list items should be in document ready*// $('#addItem').on('click', Add); //*Delete all items should be in document ready*// $('#resetButton').on('click', DeleteAll); }); //*Delete individual item should be after document ready*// $(document).on('click', '#remove-button', Delete); //*Check off item should be after document ready*// $(document).on('click', '.checkbox', Check); $(document).on('keypress', function(key) { if (key.keyCode == 13) { Add(); } });
var myImages =["https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQAlqvmkMotb6pazK3sw7gWlJLt5DMcVJfT4QJac0ABuMRzGvqLDQ", "http://images.all-free-download.com/images/graphicthumb/pigeon_birds_macro_215473.jpg", "http://www.photographyblogger.net/wp-content/uploads/2010/08/birds2.jpg", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTZ7GKzTqVecdu66rDf6SVuGU0CblA2_8w1iz9tfcZDWbfvSt70hg", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT0Hio_u-c7H99BsyrsiL0RQ6s2mlVOaA1_usp3T33oGCJqlcVM4A"]; var captionImages =["Bird Image 1","Bird Image 2","Bird Image 3","Bird Image 4","Bird Image 5"]; var index=0; function updateImage(){ document.getElementById("show").src = myImages[index]; document.getElementById("show").alt= captionImages[index]; document.getElementById("caption").textContent = captionImages[index]; } function next(){ if (myImages.length == index+1) index=0; else index++; updateImage(); } function back(){ if (index===0) index=myImages.length-1; else index--; updateImage(); } function autoSlide(){ if (document.getElementById("auto1").checked) next(); } setInterval(autoSlide,2000); // Next var nextButton = document.getElementById("next"); var previousButton = document.getElementById("previous"); previousButton.addEventListener("click",back,false); nextButton.addEventListener("click",next,false);
function area(length, width) { return length * width; } var rectangles = []; rectangles.push(area(10,15)); rectangles.push(area(25,12)); rectangles.push(area(4,5)); console.log(rectangles);
MyApp.service('Utils', function($ionicPopup) { this.classListOptions = {}; this.selectedName = {}; this.names = [ { "number": 233, "rider": "Carolyn Smith", "horse": "ZZ", "owner": "Carolyn Smith", "trainer": "Don Stewart" }, { "number": 234, "rider": "Carolyn Smith", "horse": "Sebastian", "owner": "Carolyn Smith", "trainer": "Don Stewart" } ]; this.classList = [ { number: "1", name: "Short Stirrup Equitation Flat, 11 & under", count: "17" }, { number: "2", name: "Short Stirrup Equitation 2', 11 & under", count: "13" }, { number: "3", name: "Short Stirrup Pleasure, 11 & under", count: "18" }, { number: "4", name: "Short Stirrup Hunter 2', 11 & under", count: "13" }, { number: "5", name: "Short Stirrup Hunter 2', 11 & under", count: "17" }, { number: "6", name: "Short Stirrup Hunter 2', 11 & under", count: "13" }, { number: "7", name: "Short Stirrup Hunter U/S, 11 & under", count: "12" }, { number: "15", name: "Long Stirrup Equitation Flat, 12 - 17", count: "9" }, { number: "16", name: "Long Stirrup Equitation 2', 12 - 17", count: "6" }, { number: "17", name: "Long Stirrup Pleasure, 12 - 17", count: "8" }, ]; this.scratchList = [ { number: "145", name: "Adult Amateur Hunter 31 - 49 3'", rider: "Marcy Wehde", count: "16", placing: "0" }, { number: "201", name: "NorCal 3ft Medal Class", rider: "Marcy Wehde", count: "30", placing: "0" }, { number: "217", name: "PCHA Victor Hugo-Vidal Adult Horsemanship", rider: "Marcy Wehde", count: "5", placing: "2" }, { number: "218", name: "Ariat National Adult Medal Class", rider: "Marcy Wehde", count: "18", placing: "8" }, { number: "219", name: "M & S Adult Medal Class", rider: "Marcy Wehde", count: "11", placing: "0" }, { number: "223", name: "Amateur Hunter Seat Equitation Over Fences 31 - 49", rider: "Marcy Wehde", count: "15", placing: "5" }, { number: "229", name: "Amateur Hunt Seat Equitation, Flat 31 - 49", rider: "Marcy Wehde", count: "19", placing: "1" }, { number: "234", name: "Best Adult Amateur Rider Award", rider: "Marcy Wehde", count: "22", placing: "0" }, { number: "250", name: "$1,000 .95m Open Jumper Classic (Sponsored By: Sponsored by Suzanne Rischman)", rider: "Marcy Wehde", count: "21", placing: "0" }, { number: "4147", name: "USHJA Zone 10 Adult Amateur 31 - 49 HOTY Finals", rider: "Marcy Wehde", count: "11", placing: "0" }, { number: "4148", name: "USHJA Zone 10 Adult Amateur 31 - 49 HOTY Finals", rider: "Marcy Wehde", count: "11", placing: "0" }, { number: "4149", name: "USHJA Zone 10 Adult Am 31 - 49 U/S HOTY Finals", rider: "Marcy Wehde", count: "11", placing: "0" }, ]; this.horses = [ "Duet", "Easton", "Play by Play", "Saluut D 99", "Lightning Z ", "Apropos", "Johnny Drum", "Lennon", "Kingston", "Boss", "Hennepin County", "Star Quality", "Carinja 14", "Connotation", "Spot On", "Saphir", "Zaretina", "Capital Elegance", "Sun Flight", "Press to Play", "Capria", "Dinner for Two", "Dealmaker", "Citation", "Moonrise Kingdom", "Le Cavalier", "Center Court", "Ninja", "Papillon", "Quintano 25", "Houston", "Cindarco", "Cristiano", "L. Alta Vida", "Balou Grand", "Bryant Park", "King Lion Heart", "Splendido", "Callistus 4", ]; this.riders = [ "Virginia Fout", "Laura Owens", "Kelsey Brooks", "Kaili Pelzer", "Aimee LaFayette", "Rachel Van Allen", "Georgia Dillon", "Mandy Porter", "Tara Kennedy", "Jim Ifko", "Camilla Bennett", "Kathy Nolan", "Robin Kellogg", "Caroline Delehanty", "Stacey Bacheller", "Katelin Mack", "Anita Dawson", ]; this.closeOutInfo = {}; this.isValidEmailFormat = function(_email) { var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (!filter.test(_email)) { return false; } return true; }; this.isNumeric = function(n) { return !isNaN(parseFloat(n)) && isFinite(n); }; this.isNULL = function(data) { if (typeof data === 'undefined' || data === null) return true; return false; } // check if string is empty. this.isEmptyString = function(str) { if (typeof str === "undefined" || str === null || str === "") return true; return false; }; this.isEmptyArray = function(obj) { if (typeof obj === "undefined" || obj === null || obj.length === 0) return true; return false; }; this.get2DigitNumber = function(number) { if (number < 10) return "0" + number; else return "" + number; }; this.getName = function(nameId) { for (var i = this.names.length - 1; i >= 0; i--) { if (this.names[i].number == nameId) { return this.names[i]; return; } }; }; this.getClass = function(classNumber) { for (var i = this.classList.length - 1; i >= 0; i--) { if(parseInt(this.classList[i].number) === parseInt(classNumber)) { return this.classList[i]; } }; }; this.getScratch = function(scratchNumber) { for (var i = this.scratchList.length - 1; i >= 0; i--) { if(parseInt(this.scratchList[i].number) === parseInt(scratchNumber)) { return this.scratchList[i]; } }; }; this.getRandomInt = function(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // display confirm popup with Yes/No button. this.confirmPopupYesNo = function(title, message, yesCallback, noCallback) { this.displayConfirmPopup(title, message, 'Yes', 'button-positive', 'No', 'button-negative', yesCallback, noCallback); }; // display confirm popup with Yes/No button. this.confirmPopupOKCancel = function(title, message, okCallback, cancelCallback) { this.displayConfirmPopup(title, message, 'OK', 'button-positive', 'Cancel', 'button-negative', okCallback, cancelCallback); }; // display normal confirm popup. this.displayConfirmPopup = function(title, message, okText, okType, cancelText, cancelType, okCallback, cancelCallback) { var confirmPopup = $ionicPopup.confirm({ title: '<h4>' + title + '</h4>', template: '<div style="text-align: center; color:#333">' + message + '</div>', okText: okText, okType: okType, cancelText: cancelText, cancelType: cancelType, }); confirmPopup.then(function(res) { if (res) { if (angular.isFunction(okCallback)) okCallback(); } else { if (angular.isFunction(cancelCallback)) cancelCallback(); } }); }; // display selection popup such as Camera/Gallery. this.selectPopup = function(title, message, firstText, secondText, firstCallback, secondCallback) { this.displayConfirmPopup(title, message, firstText, 'button-positive', secondText, 'button-positive', firstCallback, secondCallback); }; // display normal alert popup with title and message contents. this.alertPopup = function(title, message) { $ionicPopup.alert({ title: '<h4>' + title + '</h4>', template: '<div style="text-align: center; color:#333">' + message + '</div>' }); }; // display normal alert popup with message contents. this.alertMessage = function(message) { $ionicPopup.alert({ title: '', template: '<div style="text-align: center; color:#333">' + message + '</div>' }); }; // display popup when there is no connection to server. this.alertPopupForNoConnection = function(resp, isDisplayPopup) { // 404 - Not Found var message = 'Unable to connect to server. Please try again later.'; if (resp === 500) { // 500 - Internal Server Error message = 'Unexpected error on server.'; } else if (typeof resp !== 'number') { if (!this.isNULL(resp.message)) message = resp.message; else if (!this.isNULL(resp.error)) message = resp.error; } if (isDisplayPopup !== false) { $ionicPopup.alert({ title: '', template: '<div style="text-align: center; color:#333">' + message + '</div>' }); } return message; }; // display popup form server response. this.alertPopupFromResponse = function(response, isDisplayPopup) { var message = 'Unexpected Error'; if (!this.isNULL(response)) { if (!this.isEmptyString(response.error_message)) message = response.error_message; else if (!this.isNULL(response.error_code)) message = 'Code : ' + response.error_code; } if (isDisplayPopup !== false) this.alertMessage(message); return message; }; // convert JSON data to URL-encoded string. this.JSONToURLEncoded = function(json_data) { var encoded_data = ""; for (var p in json_data) { encoded_data = encoded_data + p + "=" + json_data[p] + "&"; } if (encoded_data === "") return ""; else return encoded_data.substr(0, encoded_data.length - 1); }; this.parseFloat = function(str) { str = str.substr(1).replace(',', ''); return parseFloat(str); } this.cloneObject = function(obj) { return $.extend(true, {}, obj); }; });
import './App.css'; import { CreateTaskComponent } from './components/CreateTask/CreateTaskComponent'; import { TaskComponent } from './components/TaskComponent'; import { TaskContextProvider } from './context/TaskContext'; import 'bootstrap/dist/css/bootstrap.min.css'; import { Container, Row, Col } from 'react-bootstrap'; import { MainRoutes } from './Routes/MainRoutes'; function App() { return ( <TaskContextProvider> <Container> <Row className="justify-content-center"> <Col xs={3}> <MainRoutes /> </Col> </Row> </Container> </TaskContextProvider> ); } export default App;
import React, {Component} from "react"; import TitleBar from "./TitleBar/TitleBar"; import SyntaxBlock from "./SyntaxBlock/SyntaxBlock"; import "./ReactTerminal.css"; class ReactTerminal extends Component { constructor(props) { super(props); this.state = { content: "" }; } render() { const {title, language, height = 350, width = 600} = this.props; const {content} = this.state; return ( <div className="editor" style={{height, width}}> <TitleBar title={title}/> <SyntaxBlock content={content} language={language}/> </div> ); }; componentDidMount() { const {content = " ", cursorSpeed = 1} = this.props; this.typeMessage(content, cursorSpeed); } typeMessage = (message, cursorSpeed) => this.typeDelay(message.length, message, cursorSpeed); typeDelay = (length, message, speed) => { setTimeout(() => { this.setState(prev => ({ content: (prev.content += message[message.length - length]) })); if (--length > 0) { this.typeDelay(length, message, speed); } }, speed); }; } export default ReactTerminal;
/// <reference name="MicrosoftAjax.debug.js" /> /// <reference name="MicrosoftAjaxTimer.debug.js" /> /// <reference name="MicrosoftAjaxWebForms.debug.js" /> /// <reference name="AjaxControlToolkit.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit" /> /// <reference name="AjaxControlToolkit.Common.Common.js" assembly="AjaxControlToolkit" /> /// <reference path="../Common.js" /> /// <reference path="../jQuery.js" /> (function () { var scriptName = "GridView"; function execute() { Type.registerNamespace('VitalShining.Galaxy.Web'); //#region Constructor VitalShining.Galaxy.Web.GridView = function (element) { VitalShining.Galaxy.Web.GridView.initializeBase(this, [element]); this._showHeader = true; this._showFooter = false; this._isEmpty = false; this._autoPostBackId = null; this._selectedRowStyle = null; this._hoverRowStyle = null; this._detailSettings = null; this._detailLoadingTemplate = null; this._selectedIndex = -1; this._rows = []; this._row$delegates = { click: Function.createDelegate(this, this._onRowClick), dblclick: Function.createDelegate(this, this._onRowDblClick), mouseover: Function.createDelegate(this, this._onRowMouseOver), mouseout: Function.createDelegate(this, this._onRowMouseOut) }; this._dragStartHandler = null; this._draggable = false; this._dragHistory = []; this._dragContext = {}; this._dragRadius2 = 100; this._drag_document$delegates = null; this._filters = {}; this._onShowFilterJson = null; this._onHideFilterJson = null; this._filter_clicked = false; this._filterPopupBehavior = null; this._filterItemBehaviors = []; this._filterDropDownContainer = null; this._filterDropDown_clicked = false; this._filterDropDownContainer$delegates = { contextmenu: Function.createDelegate(this, this._filterDropDownContainer_oncontextmenu) }; this._document$delegates = null; this._allowResizing = true; this._header$delegates = null; this._resizer = null; this._resizing = false; this._resizing_header = null; this._resizer$delegates = { mousedown: Function.createDelegate(this, this._resizer_mousedown) }; this._resizeContext = {}; this._resize_document$delegates = null; this._columnsWidth = null; }; //#endregion VitalShining.Galaxy.Web.GridView.prototype = { //#region System initialize: function () { VitalShining.Galaxy.Web.GridView.callBaseMethod(this, 'initialize'); this._correctTableSections(); var table = this.get_element(); if (this._showHeader && this._draggable && table.tHead.rows.length > 0) { var headers = table.tHead.rows[0].cells; // make the grid view headers draggable. this._dragStartHandler = Function.createDelegate(this, this._dragStart); for (var i = 0, l = headers.length; i < l; i++) $addHandler(headers[i], 'mousedown', this._dragStartHandler); } // replay drag history and restore the column orders before postback or asyn call back. if (this._dragHistory && this._dragHistory.length > 0) this._replayDrags(this._dragHistory); this._filterDropDownContainer = $common.createElementFromTemplate({ nodeName: "div", visible: false, cssClasses: ["ajax__gridview_filterpanel"] }); $addHandlers(this._filterDropDownContainer, this._filterDropDownContainer$delegates); $common.appendElementToFormOrBody(this._filterDropDownContainer); this._filterPopupBehavior = $create(Sys.Extended.UI.PopupBehavior, { positioningMode: Sys.Extended.UI.PositioningMode.BottomLeft, y: -1 }, { hidden: Function.createDelegate(this, this._filterHideEnded), shown: Function.createDelegate(this, this._filterShown) }, null, this._filterDropDownContainer); // Create the animations (if they were set before initialize was called) if (this._onShowFilterJson) { this._filterPopupBehavior.set_onShow(this._onShowFilterJson); var behavior = this._filterPopupBehavior.get_onShowBehavior(); if (behavior) { var animation = behavior.get_animation(); if (animation) { animation.add_step(Function.createDelegate(this, this._filterShowStep)); } } } if (this._onHideFilterJson) { this._filterPopupBehavior.set_onHide(this._onHideFilterJson); } this._document$delegates = { click: Function.createDelegate(this, this._document_onclick), contextmenu: Function.createDelegate(this, this._document_onclick) }; $addHandlers(document, this._document$delegates); if (this._showHeader && table.tHead.rows.length > 0) { this._header$delegates = { mouseover: Function.createDelegate(this, this._header_mouseover), mouseout: Function.createDelegate(this, this._header_mouseout) }; var headers = table.tHead.rows[0].cells; for (var i = 0, l = headers.length; i < l; i++) { if (this._column_resizable(headers[i])) { $addHandlers(headers[i], this._header$delegates); } if (this._columnsWidth && this._columnsWidth[i]) { headers[i].style.width = this._columnsWidth[i]; } } } if (this._isEmpty) return; for (var i = 0, l = table.tBodies.length; i < l; i++) { var tbody = table.tBodies[i]; for (var j = 0, J = tbody.rows.length; j < J; j++) { var row = tbody.rows[j]; this._backupStyle(row); row.setAttribute('DetailLoaded', 'false'); this._rows.push(row); $addHandlers(row, this._row$delegates); } } // restore the selected row style if (this._selectedIndex !== -1) { if (this._selectedIndex >= this._rows.length) this._selectedIndex = -1; else if (this._selectedRowStyle) { var row = this._rows[this._selectedIndex]; $common.applyProperties(row, this._selectedRowStyle); if (row.oldStyle.className) row.className = row.oldStyle.className + ' ' + this._selectedRowStyle.className; } } }, dispose: function () { var table = this.get_element(); if (this._row$delegates) { for (var i = 0, I = this._rows.length; i < I; i++) { $common.removeHandlers(this._rows[i], this._row$delegates); } this._row$delegates = null; } if (this._dragStartHandler && table.tHead.rows.length > 0) { var headers = table.tHead.rows[0].cells; for (var i = 0, l = headers.length; i < l; i++) { $removeHandler(headers[i], 'mousedown', this._dragStartHandler); } this._dragStartHandler = null; } if (this._drag_document$delegates) { $common.removeHandlers(document, this._drag_document$delegates); this._drag_document$delegates = null; } this._dragContext = null; this._dragHistory = null; if (this._filterPopupBehavior) { this._filterPopupBehavior.dispose(); this._filterPopupBehavior = null; } if (this._filterDropDownContainer) { $common.removeHandlers(this._filterDropDownContainer, this._filterDropDownContainer$delegates); this._filterDropDownContainer$delegates = null; $common.removeElement(this._filterDropDownContainer); this._filterDropDownContainer = null; } if (this._document$delegates) { $common.removeHandlers(document, this._document$delegates); this._document$delegates = null; } this._filters = null; if (this._showHeader && this._header$delegates && table.tHead.rows.length > 0) { var headers = table.tHead.rows[0].cells; for (var i = 0, l = headers.length; i < l; i++) { if (this._column_resizable(headers[i])) { $common.removeHandlers(headers[i], this._header$delegates); } } } this._header$delegates = null; if (this._resizer) { $common.removeHandlers(this._resizer, this._resizer$delegates); this._resizer$delegates = null; $common.removeElement(this._resizer); this._resizer = null; } if (this._resize_document$delegates) { $common.removeHandlers(document, this._resize_document$delegates); this._resize_document$delegates = null; } this._resizeContext = null; VitalShining.Galaxy.Web.GridView.callBaseMethod(this, 'dispose'); }, loadClientState: function (value) { if (value) { var state = Sys.Serialization.JavaScriptSerializer.deserialize(value); this._showHeader = state["ShowHeader"]; this._showFooter = state["ShowFooter"]; this._selectedIndex = state["SelectedIndex"]; this._isEmpty = state["IsEmpty"]; this._dragHistory = state["ColumnMovingHistory"] || []; this._columnsWidth = state["ColumnsWidth"] || []; var gridWidth = state["GridWidth"]; if (gridWidth) { this.get_element().style.width = gridWidth; } var filters = state["FilterExpressions"] || {}; for (var name in filters) { var filter = this._filters[name]; if (filter) { filter.value = filters[name].Value; filter.display = filters[name].Display; } else { this._filters[name] = { value: filters[name].Value, display: filters[name].Display }; } } } }, saveClientState: function () { var filters = {}; for (var name in this._filters) { var filter = this._filters[name]; if (filter.value) { filters[name] = { Value: filter.value, Display: filter.display }; } } var table = this.get_element(); var columnsWidth = null; if (this._showHeader && table.tHead.rows.length > 0) { columnsWidth = []; var headers = table.tHead.rows[0].cells; for (var i = 0, l = headers.length; i < l; i++) { columnsWidth.push(headers[i].style.width); } } return Sys.Serialization.JavaScriptSerializer.serialize({ SelectedIndex: this._selectedIndex, ColumnMovingHistory: this._dragHistory, FilterExpressions: filters, ColumnsWidth: columnsWidth, GridWidth: table.style.width }); }, _correctTableSections: function () { var table = this.get_element(); // Internet Explorer cannot create thead, tbody and tfoot sections automatically // So we have to fix it programmatic if (this._showHeader) { if (table.getElementsByTagName('thead').length == 0) { var thead = document.createElement('thead'); if (table.rows.length > 0) thead.appendChild(table.rows[0]); table.insertBefore(thead, table.firstChild); } // Safari doesn't support table.tHead, sigh if (table.tHead == null) { table.tHead = table.getElementsByTagName('thead')[0]; } } if (this._showFooter) { if (table.getElementsByTagName('tfoot').length == 0) { var tfoot = document.createElement('tfoot'); if (table.rows.length > 0) tfoot.appendChild(table.rows[table.rows.length - 1]); table.appendChild(tfoot); } // Safari doesn't support table.tFoot, sigh if (table.tFoot == null) { table.tFoot = table.getElementsByTagName('tfoot')[0]; } } }, //#endregion //#region Row Actions _onRowClick: function (evt) { var row = $common.queryAncestor(evt.target, 'tr', true); if (row) { var selectedRow = this.get_selectedRow(); // Restore the style of previouse selected row. if (selectedRow && selectedRow.oldStyle) $common.applyProperties(selectedRow, selectedRow.oldStyle); this._selectedIndex = Array.indexOf(this._rows, row); // Set the current selected row style to be selectedRowStyle if (this._selectedRowStyle) { $common.applyProperties(row, this._selectedRowStyle); if (row.oldStyle.className) row.className = row.oldStyle.className + ' ' + this._selectedRowStyle.className; } } }, _onRowDblClick: function () { /// <seealso cref="http://www.webreference.com/js/column12/crossbrowser.html">Cross-Browser Selection Handling</seealso> if (window.getSelection) { var selection = window.getSelection(); if (selection) selection.removeAllRanges(); } else if (document.getSelection) { document.getSelection().empty(); } else if (document.selection) { document.selection.empty(); } this.raiseRowDblClick(); }, _onRowMouseOver: function (evt) { var row = $common.queryAncestor(evt.target, 'tr', true); if (row && this.get_selectedRow() != row && this._hoverRowStyle) $common.applyProperties(row, this._hoverRowStyle); }, _onRowMouseOut: function (evt) { var row = $common.queryAncestor(evt.target, 'tr', true); if (row && this.get_selectedRow() != row && row.oldStyle) $common.applyProperties(row, row.oldStyle); }, _backupStyle: function (element) { element.oldStyle = { className: element.className, style: { color: $common.getCurrentStyle(element, 'color'), backgroundColor: $common.getCurrentStyle(element, 'backgroundColor'), borderColor: $common.getCurrentStyle(element, 'borderColor'), borderWidth: $common.getCurrentStyle(element, 'borderWidth'), borderStyle: $common.getCurrentStyle(element, 'borderStyle'), fontFamily: $common.getCurrentStyle(element, 'fontFamily'), fontSize: $common.getCurrentStyle(element, 'fontSize'), fontWeight: $common.getCurrentStyle(element, 'fontWeight'), fontStyle: $common.getCurrentStyle(element, 'fontStyle'), textDecoration: $common.getCurrentStyle(element, 'textDecoration'), height: $common.getCurrentStyle(element, 'height'), width: $common.getCurrentStyle(element, 'width') } }; }, get_selectedRow: function () { if (this._selectedIndex < 0 || this._selectedIndex >= this._rows.length) { return null; } else { return this._rows[this._selectedIndex]; } }, //#endregion //#region Show Detail showDetail: function (rowIndex, button, eventCallback, context, errorCallback) { var row = this._rows[rowIndex]; // Send the request for row details only when it has not been loaded from server. if (row.getAttribute('DetailLoaded') === "false") { row.setAttribute('DetailLoaded', 'loading'); // Create the DIV containter to wrap detail content. var detailContainer = this._createDetailRow(rowIndex); // show 'loading' content this._showLoadingContent(detailContainer, rowIndex); this._invalidateExpandButton(button, true); var detailRow = $common.queryAncestor(detailContainer, 'tr', true); detailRow.button = button; // Initialize and send callback to server __theFormPostData = ''; WebForm_InitCallback(); WebForm_DoCallback(this._autoPostBackId, 'd' + rowIndex, Function.createDelegate(this, this._onDetailCallbackComplete), { container: detailContainer, eventCallback: eventCallback, errorCallback: errorCallback, context: context }, Function.createDelegate(this, this._onDetailCallbackFailed), false); } else { // Show the details information directly if the details content has been loaded before. var detailRow = this._findDetailRow(row); var visible = !$common.getVisible(detailRow); $common.setVisible(detailRow, visible); this._invalidateExpandButton(button, visible); } }, clearDetail: function (rowIndex) { var dataRow = this._rows[rowIndex]; if (dataRow.getAttribute('DetailCreated') === 'true') { var detailRow = this._findDetailRow(dataRow); $common.removeElement(detailRow); this._invalidateExpandButton(detailRow.button, false); } dataRow.setAttribute('DetailLoaded', 'false'); }, _onDetailCallbackComplete: function (result, context) { context.innerHTML = result; var detailRow = $common.queryAncestor(context.container, 'tr', true); // Apply the style for details content. if (this._detailSettings.DetailStyle) $common.applyProperties(detailRow, this._detailSettings.DetailStyle); // Set the flag to indicate the details has been loaded successfully. var dataRow = this._findDataRow(detailRow); dataRow.setAttribute('DetailLoaded', 'true'); if (context.eventCallback) context.eventCallback(result, context.context); }, _onDetailCallbackFailed: function (result, context) { // Remove loading content while the call back failed. var detailRow = $common.queryAncestor(context.container, 'tr', true); $common.removeElement(detailRow); var dataRow = this._findDataRow(detailRow); dataRow.setAttribute('DetailCreated', 'false'); if (context.errorCallback) context.errorCallback(result, context.context); else $alert(result); }, _createDetailRow: function (rowIndex) { var dataRow = this._rows[rowIndex]; if (dataRow.getAttribute('DetailCreated') !== 'true') { var tbody = $common.queryAncestor(dataRow, 'tbody', true); var detailRow = document.createElement('TR'); if (tbody.rows[tbody.rows.length - 1] === dataRow) tbody.appendChild(detailRow); else tbody.insertBefore(detailRow, dataRow.nextSibling); dataRow.setAttribute('DetailCreated', 'true'); return $common.createElementFromTemplate( { nodeName: 'DIV' }, $common.createElementFromTemplate({ nodeName: 'TD', properties: { colSpan: $('TD', this._rows[rowIndex]).length } }, detailRow)); } else { var detailRow = this._findDetailRow(dataRow); return detailRow.getElementsByTagName('DIV')[0]; } }, _findDetailRow: function (row) { var dataRow; if (typeof rowIndex === "number") dataRow = this._rows[row]; else if (Sys._isDomElement(row) && row.tagName.toLowerCase() == 'tr') dataRow = row; if (dataRow) { while (dataRow = dataRow.nextSibling) { if (Sys._isDomElement(dataRow) && dataRow.nodeType === 1 && dataRow.tagName.toLowerCase() == 'tr') return dataRow; } } return null; }, _findDataRow: function (detailRow) { if (detailRow) { var row = detailRow; while (row = row.previousSibling) { if (Sys._isDomElement(row) && row.nodeType === 1 && row.tagName.toLowerCase() == 'tr') return row; } } return null; }, _showLoadingContent: function (container, rowIndex) { // Apply the style for loading content. if (this._detailSettings.LoadingStyle) { var detailRow = $common.queryAncestor(container, 'tr', true); $common.applyProperties(detailRow, this._detailSettings.LoadingStyle); } if (this._detailLoadingTemplate) { container.innerHTML = this._detailLoadingTemplate; } else { $(container).text(this._detailSettings.LoadingText); } }, _invalidateExpandButton: function (button, expanded) { var buttonText = expanded ? this._detailSettings.CollapseText : this._detailSettings.ExpandText; if (button.tagName == 'A') { $(button).text(buttonText); } else if (button.tagName == 'INPUT' && button.type == 'image') { button.src = expanded ? this._detailSettings.CollapseImageUrl : this._detailSettings.ExpandImageUrl; button.alt = buttonText; } }, //#endregion //#region Move Column _dragStart: function (evt) { var cell = $common.queryAncestor(evt.target, ["td", "th"], true); var table = this.get_element(); var startCol = this._findColumn(table, evt.clientX); if (startCol == -1) return; var bounds = $common.getBounds(cell); this._dragContext.startColumn = startCol; this._dragContext.cursorStartLocation = new Sys.UI.Point(evt.clientX, evt.clientY); this._dragContext.elementStartLocation = new Sys.UI.Point(bounds.x, bounds.y); this._dragContext.addedNode = false; var maxLevel = $common.getMaxLevel(); var cloneTable = this._cloneNode(table, false); cloneTable.style.margin = '0'; // clone table header if (table.tHead) cloneTable.appendChild(this._copyColumn(table.tHead, startCol, false)); // clone table body for (var i = 0, l = table.tBodies.length; i < l; i++) cloneTable.appendChild(this._copyColumn(table.tBodies[i], startCol, true)); // clone table footer if (table.tFoot) cloneTable.appendChild(this._copyColumn(table.tFoot, startCol, false)); $common.setBounds(cloneTable, bounds); $common.setElementOpacity(cloneTable, 0.7); // Update element's z-index. cloneTable.style.zIndex = maxLevel + 1; this._dragContext.cloneTable = cloneTable; this._drag_document$delegates = { mousemove: Function.createDelegate(this, this._dragMove), mouseup: Function.createDelegate(this, this._dragEnd) }; $addHandlers(document, this._drag_document$delegates); evt.preventDefault(); }, _dragMove: function (evt) { var dx = evt.clientX - this._dragContext.cursorStartLocation.x; var dy = evt.clientY - this._dragContext.cursorStartLocation.y; if (!this._dragContext.addedNode && dx * dx + dy * dy > this._dragRadius2) { $common.appendElementToFormOrBody(this._dragContext.cloneTable); this._dragContext.addedNode = true; } $common.setLocation(this._dragContext.cloneTable, { x: this._dragContext.elementStartLocation.x + dx, y: this._dragContext.elementStartLocation.y + dy }); evt.preventDefault(); }, _dragEnd: function (evt) { if (this._drag_document$delegates) { $common.removeHandlers(document, this._drag_document$delegates); this._drag_document$delegates = null; } if (!this._dragContext.addedNode) return; $common.removeElement(this._dragContext.cloneTable); var elt = this.get_element(); var bounds = $common.getBounds(elt); if (evt.clientY < bounds.y || evt.clientY > bounds.y + bounds.height) return; var targetCol; if (evt.clientX < bounds.x) targetCol = 0; else if (evt.clientX > bounds.x + bounds.width) targetCol = elt.tHead.rows[0].length - 1; else targetCol = this._findColumn(elt, evt.clientX); var start = this._dragContext.startColumn; if (targetCol != -1 && targetCol != start) { this._moveColumn(start, targetCol); this._dragHistory.push(start + ',' + targetCol); } this._dragContext = {}; evt.preventDefault(); }, _copyColumn: function (tableSection, columnIndex, isBody) { var cloneSection = this._cloneNode(tableSection, false); for (var i = 0, l = tableSection.rows.length; i < l; i++) { var row = tableSection.rows[i], cell = row.cells[columnIndex]; if (isBody && !Array.contains(this._rows, row)) continue; var cloneRow = this._cloneNode(row, false); if (row.offsetHeight) cloneRow.style.height = row.offsetHeight + "px"; var cloneCell = this._cloneNode(cell, true); if (cell.offsetWidth) cloneCell.style.width = cell.offsetWidth + "px"; cloneRow.appendChild(cloneCell); cloneSection.appendChild(cloneRow); } return cloneSection; }, _cloneNode: function (element, deep) { var dest = element.cloneNode(deep); if (Sys.Browser.agent === Sys.Browser.InternetExplorer) { this._cloneFixAttributes(element, dest); if (deep) { var srcElements = element.getElementsByTagName("*"); var destElements = dest.getElementsByTagName("*"); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for (i = 0; srcElements[i]; ++i) { this._cloneFixAttributes(srcElements[i], destElements[i]); } } } return dest; }, _cloneFixAttributes: function (src, dest) { // We do not need to do anything for non-Elements if (dest.nodeType !== 1) return; // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if (dest.clearAttributes) dest.clearAttributes(); // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if (dest.mergeAttributes) dest.mergeAttributes(src); var nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if (nodeName === "object") { dest.outerHTML = src.outerHTML; } else if (nodeName === "input" && (src.type === "checkbox" || src.type === "radio")) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if (src.checked) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if (dest.value !== src.value) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if (nodeName === "option") { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if (nodeName === "input" || nodeName === "textarea") { dest.defaultValue = src.defaultValue; } }, _replayDrags: function (dragHistory) { for (var i = 0, l = dragHistory.length; i < l; i++) { var h = dragHistory[i].split(','); this._moveColumn(parseInt(h[0], 10), parseInt(h[1], 10)); } }, // Which column does the x value fall inside of? x should include scrollLeft. _findColumn: function (table, x) { var header = table.tHead.rows[0].cells; for (var i = 0; i < header.length; i++) { var bounds = $common.getBounds(header[i]); if (bounds.x <= x && x <= bounds.x + bounds.width) { return i; } } return -1; }, _moveColumn: function (srcIndex, destIndex) { var moveCell = function (row, srcIndex, destIndex) { var cell = row.removeChild(row.cells[srcIndex]); if (destIndex < row.cells.length) { row.insertBefore(cell, row.cells[destIndex]); } else { row.appendChild(cell); } }; var table = this.get_element(); if (table.tHead) { for (var i = 0, l = table.tHead.rows.length; i < l; i++) moveCell(table.tHead.rows[i], srcIndex, destIndex); } if (table.tBodies) { for (var i = 0, l = table.tBodies.length; i < l; i++) { var tbody = table.tBodies[i]; for (var j = 0, J = tbody.rows.length; j < J; j++) { var row = tbody.rows[j]; if (Array.contains(this._rows, row)) { moveCell(row, srcIndex, destIndex); } } } } if (table.tFoot) { for (var i = 0, l = table.tFoot.rows.length; i < l; i++) moveCell(table.tFoot.rows[i], srcIndex, destIndex); } }, //#endregion //#region Filter showFilter: function (column, target) { this._filter_clicked = true; var filter = this._filters[column]; if (!filter || !filter.items) { var that = this; __theFormPostData = ''; WebForm_InitCallback(); WebForm_DoCallback(this._autoPostBackId, 'f' + column, function (result) { var items = Sys.Serialization.JavaScriptSerializer.deserialize(result); if (!filter) { that._filters[column] = filter = { items: items }; } else { filter.items = items; } that._showFilter(column, filter, target); }, null, function (result) { that._filterPopupBehavior.hide(); }, false); } else { this._showFilter(column, filter, target); } }, _showFilter: function (column, filter, target) { while (this._filterItemBehaviors.length > 0) { this._filterItemBehaviors[0].dispose(); this._filterItemBehaviors.shift(); } var container = this._filterDropDownContainer; while (container.hasChildNodes()) container.removeChild(container.childNodes[0]); var that = this; // Clear Filter Option this._createFilterItem({ DisplayText: VitalShining.Galaxy.GridViewResources.ClearFilter }, function () { if (filter.value) { filter.value = null; filter.display = null; filter.changed = true; } that._filterPopupBehavior.hide(); }, false); // Populated Options if (filter && filter.items) { for (var i = 0, l = filter.items.length; i < l; i++) { var item = filter.items[i]; this._createFilterItem(item, function (value, context) { if (!(filter.value && Array.contains(filter.value, context.Expression))) { if (value === null) { filter.value = [context.Expression]; filter.display = [context.DisplayText]; filter.changed = true; that._filterPopupBehavior.hide(); } else if (value === true) { if (filter.value) { filter.value.push(context.Expression); } else { filter.value = [context.Expression]; } if (filter.display) { filter.display.push(context.DisplayText); } else { filter.display = [context.DisplayText]; } filter.changed = true; } } else if (value === false) { Array.remove(filter.value, context.Expression); Array.remove(filter.display, context.DisplayText); if (filter.value.length == 0) { filter.value = null; filter.display = null; } filter.changed = true; } }, !!filter.value && Array.contains(filter.value, item.Expression)); } } this._filterPopupBehavior.set_parentElement(target); this._filterPopupBehavior.show(); }, _createFilterItem: function (item, callback, selected) { var e = $common.createElementFromTemplate({ nodeName: "div", children: [{ nodeName: 'input', properties: { type: 'checkbox', style: { visibility: item.CheckBox ? 'visible' : 'hidden' } }, events: { click: function () { if (item.CheckBox) { this._clicked = true; } } } }, { nodeName: "span", properties: { innerText: item.DisplayText, textContent: item.DisplayText } }] }, this._filterDropDownContainer); // The checked property has to be set after the element appended to the DOM tree in Internet Explorer e.firstChild.checked = selected; var that = this; var behavior = $create(Page.DialogButton, { className: 'ajax__gridview_filteritem' }, { click: function () { if (!item.CheckBox) { callback(null, item); } else { var input = e.getElementsByTagName('input')[0]; if (!input._clicked) { input.checked = !input.checked; } else { input._clicked = false; } callback(input.checked, item); } }, mouseover: function () { for (var i = 0, l = that._filterItemBehaviors.length; i < l; i++) { var b = that._filterItemBehaviors[i]; if (b !== behavior) b.mouseout(); } } }, null, e); this._filterItemBehaviors.push(behavior); if (selected && item.CheckBox) behavior.mouseover(); }, _onFilterChanged: function () { __doPostBack(this._autoPostBackId, 'Filter'); }, _filterDropDownContainer_oncontextmenu: function (evt) { this._filter_clicked = true; evt.preventDefault(); }, _filterShowStep: function () { $common.setVisible(this._filterDropDownContainer, true); }, _filterHideEnded: function () { $common.setVisible(this._filterDropDownContainer, false); for (var name in this._filters) { if (this._filters[name].changed) { this._onFilterChanged(); break; } } var e = this._filterDropDownContainer; if (e.style.removeAttribute) { e.style.removeAttribute("width"); e.style.removeAttribute("height"); } else { e.style.removeProperty("width"); e.style.removeProperty("height"); } }, _filterShown: function () { }, _document_onclick: function (evt) { if (this._filter_clicked) { this._filter_clicked = false; return false; } this._filterPopupBehavior.hide(); }, //#endregion //#region Resize _header_mouseover: function (evt) { if (this._resizing) return; var cell = $common.queryAncestor(evt.target, ["td", "th"], true); if (this._resizer && !Sys.Extended.UI.DomUtility.isDescendantOrSelf(cell, this._resizer)) { $common.removeHandlers(this._resizer, this._resizer$delegates); $common.removeElement(this._resizer); this._resizer = null; } else if (this._resizing_header == null) { this._resizing_header = cell; } if (!this._resizer) { var bounds = $common.getBounds(cell); this._resizer = $common.createElementFromTemplate({ nodeName: "div", cssClasses: ["ajax__gridview_resizehandler"] }, cell); this._resizer.style.height = bounds.height + 'px'; $common.setLocation(this._resizer, { x: bounds.x + bounds.width - this._resizer.offsetWidth, y: bounds.y }); $addHandlers(this._resizer, this._resizer$delegates); this._resizing_header = cell; } }, _header_mouseout: function (evt) { if (this._resizing) return; var that = this; this._resizing_header = null; setTimeout(function () { if (that._resizer && (!that._resizing_header || !Sys.Extended.UI.DomUtility.isDescendantOrSelf(that._resizing_header, that._resizer))) { $common.removeHandlers(that._resizer, that._resizer$delegates); $common.removeElement(that._resizer); that._resizer = null; } }, 0); }, _resizer_mousedown: function (evt) { var cell = $common.queryAncestor(evt.target, ["td", "th"], true); var grid = this.get_element(); this._resizeContext.cursorStartX = evt.clientX; this._resizeContext.headerStartWidth = cell.offsetWidth; this._resizeContext.tableStartWidth = grid.offsetWidth; this._resize_document$delegates = { mousemove: Function.createDelegate(this, this._resize_move), mouseup: Function.createDelegate(this, this._resize_end) } $addHandlers(document, this._resize_document$delegates); this._resizing = true; if (!this._allowResizing) { grid.style.width = this._resizeContext.tableStartWidth + 'px'; } evt.preventDefault(); evt.stopPropagation(); }, _resize_move: function (evt) { var dx = evt.clientX - this._resizeContext.cursorStartX; this._resizing_header.style.width = (this._resizeContext.headerStartWidth + dx) + 'px'; if (this._allowResizing) this.get_element().style.width = (this._resizeContext.tableStartWidth + this._resizing_header.offsetWidth - this._resizeContext.headerStartWidth) + 'px'; var bounds = $common.getBounds(this._resizing_header); $common.setLocation(this._resizer, { x: bounds.x + bounds.width - this._resizer.offsetWidth, y: bounds.y }); evt.preventDefault(); }, _resize_end: function (evt) { if (this._resize_document$delegates) { $common.removeHandlers(document, this._resize_document$delegates); this._resize_document$delegates = null; } this._resizing = false; }, _column_resizable: function (header) { var resizable = header.getAttribute('resizable'); if (resizable) { resizable = resizable.toLowerCase(); return resizable == 'resizable' || resizable == 'true'; } return false; }, //#endregion //#region Properties //#region detailSettings get_detailSettings: function () { return this._detailSettings; }, set_detailSettings: function (value) { this._detailSettings = value; }, //#endregion //#region detailLoadingTemplate get_detailLoadingTemplate: function () { return this._detailLoadingTemplate; }, set_detailLoadingTemplate: function (value) { this._detailLoadingTemplate = value; }, //#endregion //#region showHeader get_showHeader: function () { return this._showHeader; }, set_showHeader: function (value) { this._showHeader = value; }, //#endregion //#region selectedRowStyle get_selectedRowStyle: function () { return this._selectedRowStyle; }, set_selectedRowStyle: function (value) { this._selectedRowStyle = value; }, //#endregion //#region hoverRowStyle get_hoverRowStyle: function () { return this._hoverRowStyle; }, set_hoverRowStyle: function (value) { this._hoverRowStyle = value; }, //#endregion //#region autoPostBackId get_autoPostBackId: function () { return this._autoPostBackId; }, set_autoPostBackId: function (value) { this._autoPostBackId = value; }, //#endregion //#region minDragDistance set_minDragDistance: function (value) { this._dragRadius2 = value * value; }, //#endregion //#region draggable get_draggable: function () { return this._draggable; }, set_draggable: function (value) { this._draggable = value; }, //#endregion //#region onShowFilter get_onShowFilter: function () { /// <value type="String" mayBeNull="true"> /// Generic show filter Animation's JSON definition /// </value> return this._filterPopupBehavior ? this._filterPopupBehavior.get_onShow() : this._onShowFilterJson; }, set_onShowFilter: function (value) { if (this._filterPopupBehavior) { this._filterPopupBehavior.set_onShow(value) var behavior = this._filterPopupBehavior.get_onShowBehavior(); if (behavior) { var animation = behavior.get_animation(); if (animation) { animation.add_step(Function.createDelegate(this, this._filterShowStep)); } } } else { this._onShowFilterJson = value; } this.raisePropertyChanged('onShowFilter'); }, //#endregion //#region onHideFilter get_onHideFilter: function () { /// <value type="String" mayBeNull="true"> /// Generic hide filter Animation's JSON definition /// </value> return this._filterPopupBehavior ? this._filterPopupBehavior.get_onHide() : this._onHideFilterJson; }, set_onHideFilter: function (value) { if (this._filterPopupBehavior) { this._filterPopupBehavior.set_onHide(value) } else { this._onHideFilterJson = value; } this.raisePropertyChanged('onHideFilter'); }, //#endregion //#region allowResizing get_allowResizing: function () { return this._allowResizing; }, set_allowResizing: function (value) { this._allowResizing = value; }, //#endregion //#endregion //#region Events add_rowDblClick: function (handler) { this.get_events().addHandler("RowDblClick", handler); }, remove_rowDblClick: function (handler) { this.get_events().removeHandler("RowDblClick", handler); }, raiseRowDblClick: function () { var onRowDblClickHandler = this.get_events().getHandler("RowDblClick"); if (onRowDblClickHandler) { onRowDblClickHandler(this, Sys.EventArgs.Empty); } } //#endregion }; VitalShining.Galaxy.Web.GridView.registerClass('VitalShining.Galaxy.Web.GridView', Sys.Extended.UI.ControlBase); } // execute if (window.Sys && Sys.loader) { Sys.loader.registerScript(scriptName, ["ExtendedCommon", "ExtendedBase"], execute); } else { execute(); } })();
import styled from 'styled-components' import { SERVER_URL } from '../../Constants/api' import {ReactComponent as EmptyIcon} from '../../imgs/empty.svg' const MediaList = ({items}) => { return items?.length>0 ?( <StyledGrid> {items ?.map(item =><img src={item.content.startsWith('http')?item.content: SERVER_URL+item.content}/>)} </StyledGrid> ) : (<StyledEmpty> <EmptyIcon/> <p>No Media</p> </StyledEmpty>) } const StyledGrid = styled.div` display:grid; grid-template-columns: repeat(3,1fr); align-self: stretch; overflow: hidden; gap: 1em; padding: 1em; img{ width:100%; aspect-ratio: 1; object-fit: cover; border-radius: var(--border-radius); } ` const StyledEmpty = styled.div` display:flex; flex-direction: column; justify-content: center; align-items: center; gap: 1em; flex-grow:1; svg{ fill: var(--text-color); } ` export default MediaList
import React, { Component, Fragment} from 'react'; import {Provider} from 'react-redux' import Routes from './routes' import GlobalStyle from './styles/global'; import store from './store' class App extends Component { render() { return ( <Fragment> <Provider store={store}> <GlobalStyle /> <Routes /> </Provider> </Fragment> ); } } export default App;
require('number-to-locale-string-polyfill'); import React from 'react'; import { useDispatch } from 'react-redux'; import { View,StyleSheet,Text,Image,TouchableOpacity } from 'react-native'; import {incrementCreator,decrementCreator} from '../redux/actions/menu'; const ItemCart = ({item}) => { const regex = /localhost/; const newUrlImage = item.images.replace(regex,'192.168.43.73'); let price = item.price * item.quantity; price = price.toLocaleString('id',{style:'currency',currency:'IDR'}); const dispatch = useDispatch(); return ( <View style={Styles.card}> <View style={Styles.cardContent}> <View style={Styles.contentLeft}> <Image source={{uri:newUrlImage}} style={Styles.imageMenu}/> <View style={Styles.textCard}> <Text style={Styles.menuName}>{item.menu}</Text> <Text style={Styles.description}>{item.description}</Text> <Text style={Styles.menuPrice}>{price}</Text> </View> </View> <View style={Styles.contentRight}> <View style={Styles.counterButton}> <TouchableOpacity style={Styles.buttonDecrease} onPress={()=>dispatch(decrementCreator(item.id))}> <Text style={Styles.textButton}>-</Text> </TouchableOpacity> <View style={Styles.counter}> <Text style={Styles.textCounter}>{item.quantity}</Text> </View> <TouchableOpacity style={Styles.buttonIncrease} onPress={()=>dispatch(incrementCreator(item.id))}> <Text style={Styles.textButton}>+</Text> </TouchableOpacity> </View> </View> </View> </View> ); }; const Styles = StyleSheet.create({ card :{ marginVertical:6, marginHorizontal:10, }, cardContent :{ flexDirection:'row', margin:10, alignItems:'center', marginHorizontal:5, justifyContent:'space-between', }, contentLeft:{ flexDirection:'row', width:'40%', }, imageMenu:{ width : 80, height:80, borderRadius:10, marginLeft:5, }, textCard:{ marginLeft:10, justifyContent:'center', }, menuName:{ fontWeight:'bold', fontSize:15, color:'black', }, description:{ color:'grey', marginVertical:5, }, menuPrice :{ fontSize:12, fontWeight:'bold', }, contentRight:{ alignContent:'center', elevation:10, }, counterButton :{ flexDirection:'row', }, buttonDecrease:{ backgroundColor:'#f75252', width:30, height:30, alignItems:'center', justifyContent:'center', borderBottomLeftRadius:7, borderTopLeftRadius:7, }, buttonIncrease:{ backgroundColor:'#f75252', width:30, height:30, alignItems:'center', justifyContent:'center', borderBottomRightRadius:7, borderTopRightRadius:7, }, textButton:{ color:'white', fontSize:25, }, counter:{ backgroundColor:'white', width:30, height:30, alignItems:'center', justifyContent:'center', }, textCounter:{ fontSize:18, }, }); export default ItemCart;
/* * * modalFactory.js * * Copyright (c) 2017 MagRabbit * All rights reserved. * * This software is the confidential and proprietary information * of MagRabbit. */ 'use strict'; /** * The modal factory is used to generate dialog as notification modal, ... * * @author vn70529 ~ @since 2.12 */ (function() { angular.module('productMaintenanceUiApp').factory('ModalFactory', modalFactory); modalFactory.$inject = ['$uibModal']; /** * Constructs for modalFactory. * * @param $uibModal uid modal service. * @returns {modalFactory} */ function modalFactory($uibModal) { var self = this; /** * Show notification modal. * * @param config holds the title and message to show on modal. */ self.showNotificationModal = function(config) { return $uibModal.open({ templateUrl: 'src/utils/modals/notificationModal.html', backdrop: 'static', windowClass: 'modal', controller: 'NotificationModalController', controllerAs: 'notificationModalController', size: 'sm', resolve: { title: function () { return config.title; }, message: function () { return config.message; }, isShowConfirmDialog: function(){ return false; } } }); }; self.showConfirmModal = function(config) { return $uibModal.open({ templateUrl: 'src/utils/modals/notificationModal.html', backdrop: 'static', windowClass: 'modal', controller: 'NotificationModalController', controllerAs: 'notificationModalController', size: 'sm', resolve: { title: function () { return config.title; }, message: function () { return config.message; }, isShowConfirmDialog: function(){ return true; } } }).result; }; return self; } })();
import Goal from './Goal.jsx' export default class GoalsList extends React.Component{ render(){ let goals = this.props.goals.map( goal => <Goal key={goal.id} {...goal}/> ); return( <div className="row"> Goals: <ul className="collection with-header"> {goals} { goals.length == 0 ? <li className="collection-item">No Goals Added!</li> : null} </ul> </div> ); } }
$(function () { $.ajax({ url: window.apiPoint + 'tasks', type: 'GET', async: true, dataType: 'json', success: function (data) { if (data) { var result = {}; result["tasks"] = data; var tpl = [ '<option value=""></option>', '{@each tasks as it,index}', '<option value="${it.id}">${it.taskName}</option>', '{@/each}'].join(''); var html = juicer(tpl, result); $('#tContent').html(html); $('.chosen-select').chosen({}); } }, }); });
var app = require('../index.js').app, mysql = require('../../mysql'); var util = require('../../../bin/util'); app.get('/v2/forums', function(req, res) { mysql.getConnection(function(err, connection) { if (err) throw err; connection.query('SELECT * from `nf_forums`;', function(err, rows) { if (rows.length < 1) { connection.release(); return res.json({ message: 'No Forums Found', error: 'Not Found', status: 404 }); } if (err) throw err; var forums = []; for (var i = 0; i < rows.length; i++) { forums.push({id: rows[i].id, name: rows[i].name, description: rows[i].description, created_at: rows[i].created_at, status: rows[i].status }); } connection.release(); return res.json({ forums: forums, total: forums.length}); }); }); }); app.put('/v2/forums', function(req, res) { if (!(req.body.id)) { return res.json({ message: 'Missing Parameter \'id\'.', error: 'Unprocessable Entity', status: 422 }); } if (!(req.body.name)) { return res.json({ message: 'Missing Parameter \'name\'.', error: 'Unprocessable Entity', status: 422 }); } if (!(req.body.description)) { return res.json({ message: 'Missing Parameter \'description\'.', error: 'Unprocessable Entity', status: 422 }); } if (!(req.body.status)) { return res.json({ message: 'Missing Parameter \'status\'.', error: 'Unprocessable Entity', status: 422 }); } mysql.getConnection(function(err, connection) { if (err) throw err; connection.query('SELECT * from `nf_forums` WHERE ?', {id: req.body.id}, function(err, rows) { if (err) throw err; if (rows.length < 1) { connection.release(); return res.json({ message: 'Forum Does Not Exist', error: 'Not Found', status: 404 }); } connection.query('UPDATE `nf_forums` SET name = ?, description = ?, status = ? WHERE id = ?', [req.body.name, req.body.description, req.body.status, req.body.id], function(err, result) { if (err) throw err; connection.query('SELECT * from `nf_forums` WHERE ?', {id: req.body.id}, function(err, rows) { if (err) throw err; connection.release(); return res.json({ id: rows[0].id, name: rows[0].name, description: rows[0].description, created_at: rows[0].created_at, status: rows[0].status }); }); }); }); }); }); app.post('/v2/forums', function(req, res) { if (!(req.body.name)) { return res.json({ message: 'Missing Parameter \'name\'.', error: 'Unprocessable Entity', status: 422 }); } if (!(req.body.description)) { return res.json({ message: 'Missing Parameter \'description\'.', error: 'Unprocessable Entity', status: 422 }); } if (!(req.body.status)) { return res.json({ message: 'Missing Parameter \'status\'.', error: 'Unprocessable Entity', status: 422 }); } mysql.getConnection(function(err, connection) { if (err) throw err; connection.query('INSERT INTO `nf_forums` SET ?', {name: req.body.name, description: req.body.description, created_at: util.getISOStamp(), status: req.body.status}, function(err, result) { if (err) throw err; connection.query('SELECT * from `nf_forums` WHERE ?', {id: result.insertId}, function(err, rows) { if (err) throw err; connection.release(); return res.json({ id: rows[0].id, name: rows[0].name, description: rows[0].description, created_at: rows[0].created_at, status: rows[0].status }); }); }); }); }); app.delete('/v2/forums', function(req, res) { if (!(req.body.id)) { return res.json({ message: 'Missing Parameter \'id\'.', error: 'Unprocessable Entity', status: 422 }); } mysql.getConnection(function(err, connection) { if (err) throw err; connection.query('SELECT * from `nf_forums` WHERE ?', {id: req.body.id}, function(err, rows) { if (err) throw err; if (rows.length < 1) { connection.release(); return res.json({ message: 'Forum Does Not Exist', error: 'Not Found', status: 404 }); } connection.query('DELETE FROM `nf_forums` WHERE id = ?', [req.body.id], function(err, result) { if (err) throw err; connection.release(); return res.send(''); }); }); }); });
'use strict'; const scss = require('./razzle.scss.plugin.js'); module.exports = { plugins: ['typescript', scss], };
import React,{Component} from 'react'; import { connect } from 'dva'; import { Route, routerRedux,withRouter } from 'dva/router'; import { Layout,Select,Input,LocaleProvider } from 'antd'; import zhCN from 'antd/lib/locale-provider/zh_CN'; import Config from '../../config/index'; import styles from "./EosBasicLayout.css"; //import logo from '../../assets/logo.png'; const { Header, Content } = Layout; const Search = Input.Search; const Option = Select.Option; class MyHeader extends Component{ constructor(props){ super(props); console.log('========', this.props); let _netType = 'mainnet'; let url = this.props.match.url; let a = url.split('/'); if(a.length > 1){ let netType = Config.netType.getInstance(); if(a[1] === 'testnet'){ _netType = 'testnet'; netType.setName('testnet'); }else{ netType.setName('mainnet'); } } this.state = { keyword: '', netType:_netType }; } handleChange = (v)=>{ console.log('网络切换',v); let netType = Config.netType.getInstance(); netType.setName(v); window.location = window.location.origin + '/' + v; }; getNetType = ()=>{ let netType = Config.netType.getInstance(); return netType.getName(); }; search = (value)=>{ /** 地址:以EOS开头的字符串且长度为53位 区块:纯数字就认为是区块的高度 如果以至少3个0开头且长度为64位的字符串就认为是区块hash 账户:长度不超过12位的字符串 交易:剩下的且长度为64位当作交易的hash来处理 长度介于12到64位 或者超过64位的字符串 我们直接给他跳转到谷歌搜索吧 哈哈哈 */ let prefix = '/' + this.getNetType(); if(value && value.trim()!=''){ value = value.trim(); let len = value.length; let flag = 0; if(len == 53){ if(value.toLowerCase().indexOf("eos") === 0){ window.location = window.location.origin + prefix + '/address/'+value; flag = 1; } }else if(len == 64){ flag = 1; if(value.toLowerCase().indexOf('000') === 0){ window.location = window.location.origin + prefix + '/block/'+value; }else{ window.location = window.location.origin + prefix + '/tx/'+value; } } else if(len <= 12){ flag = 1; if(!isNaN(value)){ window.location = window.location.origin + prefix + '/block/'+value; }else{ window.location = window.location.origin + prefix + '/account/'+value; } } this.setState({ keyword: '' }); } }; toIndex = ()=>{ let netType = this.getNetType(); this.props.dispatch(routerRedux.push('/' + netType)); }; onChange = (e) => { this.setState({ keyword: e.target.value }); }; render(){ return ( <Header style={{background: 'white',paddingLeft:2}}> <div className={styles.headerContent}> <a href="javascript:void(0)" onClick={this.toIndex}> <img src="http://eospark.com/logo.png" style={{height:50}}/> </a> <Search placeholder="区块/交易/地址/账户" value={this.state.keyword} onChange={this.onChange} onSearch={value => this.search(value)} enterButton="搜索" size="large" style={{width: 600, marginRight:200}} /> <Select value={this.state.netType} defaultValue="mainnet" style={{ width: 80 }} onChange={this.handleChange}> <Option value="mainnet">主网</Option> <Option value="testnet">测试网</Option> </Select> </div> </Header> ); } } const EosHeader = withRouter(connect()(MyHeader)); const EosBasicLayout = ({component:Component, ...rest})=>{ return ( <Route {...rest} render= { matchProps => ( <div style={{height:'100%'}}> <Layout style={{height:'100%'}}> <EosHeader/> <Content style={{background: '#f0f2f5'}}> <div className={styles.content}> <LocaleProvider locale={zhCN}> <Component {...matchProps}/> </LocaleProvider> </div> </Content> </Layout> </div> )}/> ); }; export default EosBasicLayout;
const redux = require("redux"); const createStore = redux.createStore; const applyMiddleware = redux.applyMiddleware; const axios = require("axios"); const thunkMiddleware = require("redux-thunk").default; const FETCH_USER_REQUEST = "FETCH_USER_REQUEST"; const FETCH_USER_SUCCESS = "FETCH_USER_SUCCESS"; const FETCH_USER_FAILURE = "FETCH_USER_FAILURE"; const initialState = { users: [], loading: false, error: "" }; const fetchUserRequest = () => { return { type: FETCH_USER_REQUEST }; }; const fetchUserSuccess = user => { return { type: FETCH_USER_SUCCESS, payload: user }; }; const fetchUserFailure = error => { return { type: FETCH_USER_FAILURE, payload: error }; }; const asynReducer = (state = initialState, action) => { switch (action.type) { case FETCH_USER_REQUEST: return { ...state, loading: true }; case FETCH_USER_SUCCESS: return { loading: false, users: action.payload, error: "" }; case FETCH_USER_FAILURE: return { loading: false, users: [], error: action.payload }; default: return state; } }; const fetchData = () => { return function(dispatch) { dispatch(fetchUserRequest()); axios .post("https://jsonplaceholder.typicode.com/posts", { userId: 109, id: 94, title: "qui qui voluptates illo iste minima", body: "aspernatur expedita soluta quo ab ut similique\nexpedita dolores amet\nsed temporibus distinctio magnam saepe deleniti\nomnis facilis nam ipsum natus sint similique omnis" }) .then(res => { const user = res.data; console.log(user); dispatch(fetchUserSuccess(user)); }) .catch(err => dispatch(fetchUserFailure(err))); }; }; const store = createStore(asynReducer, applyMiddleware(thunkMiddleware)); store.dispatch(fetchData()); setTimeout(() => console.log(store.getState()), 3000);
const Ajax = Object.assign(Object.create({}), { METHOD_HTTP: 'http', METHOD_HTTPS: 'https', baseUrl: null, method: 'http', jsonResponse: {}, setBaseUrl(baseUrl){ this.baseUrl = baseUrl; return this; }, setMethod(method){ this.method = method; return this; }, get(url, params = ''){ const that = this; return new Promise(function (resolve, reject) { const xhttp = new XMLHttpRequest(); xhttp.open('GET', `${that.method}://${that.baseUrl}${url}?${params}`, true); xhttp.onload = function () { if (xhttp.status === 200) { resolve(JSON.parse(xhttp.responseText)); } else { reject(Error(xhttp.statusText)); } }; xhttp.onerror = function () { reject(Error('network problem')); }; xhttp.send(); }); }, post(url, params = '', type = 'application/x-www-form-urlencoded'){ const that = this; return new Promise(function (resolve, reject) { const xhttp = new XMLHttpRequest(); xhttp.open('POST', `${that.method}://${that.baseUrl}${url}`, true); xhttp.onload = function () { if (xhttp.status === 200) { resolve(JSON.parse(xhttp.responseText)); } else { reject(Error(xhttp.statusText)); } }; xhttp.onerror = function () { reject(Error('network problem')); }; xhttp.setRequestHeader('Content-Type', type); xhttp.send(params); }); }, put(url, json = '{}'){ const that = this; return new Promise(function (resolve, reject) { const xhttp = new XMLHttpRequest(); xhttp.open('PUT', `${that.method}://${that.baseUrl}${url}`, true); xhttp.onload = function () { if (xhttp.status === 200) { resolve(JSON.parse(xhttp.responseText)); } else { reject(Error(xhttp.statusText)); } }; xhttp.onerror = function () { reject(Error('network problem')); }; xhttp.setRequestHeader('Accept', 'application/json'); xhttp.send(json); }); }, httpBuildQuery(params = {}){ let query = ''; for(let idx in params){ if(params.hasOwnProperty(idx)){ query += `${idx}=${params[idx]}&`; } } query = query.substring(0, query.length - 1); return query; } }); Ajax.setBaseUrl('localhost:3001');
/* * 时间格式化 */ exports.filterTime = (timestamp,format) => { let date = new Date(timestamp ? (parseInt(timestamp)/1000000) : new Date().getTime()); let FORMAT = new Object(); FORMAT = { 'Y': "date.getFullYear()", 'M': "date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1", 'D': "date.getDate() < 10 ? '0' + date.getDate() : date.getDate()", 'h': "date.getHours() < 10 ? '0' + date.getHours() : date.getHours()", 'm': "date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()", 's': "date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()" } for (let i in FORMAT) { if (format.indexOf(i) != -1) { format = format.replace(i, eval(FORMAT[i])); } } return format; } exports.filterStr=(value,length)=>{ value=value.toFixed(length); return value; } exports.filterNumHide=(val,state)=>{ if(val){ if(state=='email'){ val=val.split('@')[0].substr(0,1)+'**@'+val.split('@')[1]; } else{ val=val.substr(0,3)+'****'+val.substr(-4); } return val; } }
import axios from 'axios'; import * as actionTypes from './actionTypes' /*** CARD CREATE ACTIONS ***/ export const cardCreateStart = () => { return { type: actionTypes.CARD_CREATE_START }; }; export const cardCreateSuccess = () => { return { type: actionTypes.CARD_CREATE_SUCCESS }; }; export const cardCreateFailure = (error) => { return { type: actionTypes.CARD_CREATE_FAILURE, error: error }; }; /*** CARD UPDATE ACTIONS ***/ export const cardUpdateStart = () => { return { type: actionTypes.CARD_UPDATE_START }; }; export const cardUpdateSuccess = () => { return { type: actionTypes.CARD_UPDATE_SUCCESS }; }; export const cardUpdateFailure = (error) => { return { type: actionTypes.CARD_UPDATE_FAILURE, error: error }; }; /*** Fetch a single card ***/ export const cardReadStart = () => { return { type: actionTypes.CARD_READ_START }; }; export const cardReadSuccess = (card) => { return { type: actionTypes.CARD_READ_SUCCESS, card: card }; }; export const cardReadFailure = (error) => { return { type: actionTypes.CARD_READ_FAILURE, error: error }; }; /*** Fetch all cards for a single group ***/ export const groupCardReadStart = () => { return { type: actionTypes.GROUP_CARD_READ_START }; }; export const groupCardReadSuccess = (cards) => { return { type: actionTypes.GROUP_CARD_READ_SUCCESS, cards: cards }; }; export const groupCardReadFailure = (error) => { return { type: actionTypes.GROUP_CARD_READ_FAILURE, error: error }; }; /*read the card for displaying on card edit page*/ export const readCard = (groupId, cardId, withGroup) => { return dispatch => { dispatch(cardReadStart()); let resourceUrl = `https://beyond-bookmarks-api.herokuapp.com/api/v1/groups/cards/${cardId}`; axios.get(resourceUrl, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } }).then(response => { console.log(response.data); dispatch(cardReadSuccess(response.data)); }).catch(err => { dispatch(cardReadFailure(err)); }); }; }; export const readGroupCard = (groupId) => { return dispatch => { dispatch(groupCardReadStart()); let resourceUrl = `https://beyond-bookmarks-api.herokuapp.com/api/v1/groups/${groupId}/cards`; axios.get(resourceUrl, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } }).then(response => { console.log(response); dispatch(groupCardReadSuccess(response.data)); }).catch(err => { dispatch(groupCardReadFailure(err)); }); }; }; function extractCardData(title, description, url, groupId, prefix) { return { title: title, description: description, url: url, groupId: groupId, prefix: prefix }; } function extractCardDataForUpdate(title, description, url, cardId) { return { title: title, description: description, url: url, cardId: cardId }; } export const updateCard = (title, description, url, cardId, groupId) => { return dispatch => { dispatch(cardUpdateStart()); const cardData = extractCardDataForUpdate(title, description, url, cardId); let resourceUrl = `https://beyond-bookmarks-api.herokuapp.com/api/v1/groups/${groupId}/cards`; axios.put(resourceUrl, cardData, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } }).then(response => { dispatch(cardUpdateSuccess()); }).catch(err => { dispatch(cardUpdateFailure(err)); }); }; }; export const createCard = (title, description, url, groupId, prefix) => { return dispatch => { dispatch(cardCreateStart()); const cardData = extractCardData(title, description, url, groupId, prefix); let resourceUrl = `https://beyond-bookmarks-api.herokuapp.com/api/v1/groups/${groupId}/cards`; axios.post(resourceUrl, cardData, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } }).then(response => { dispatch(cardCreateSuccess()); }).catch(err => { console.log(JSON.stringify(err)); dispatch(cardCreateFailure(err)); }); }; };
import NetworkStatus from './notifier'; module.exports = NetworkStatus;
import types from 'rdx/modules/auth/types'; import createAction from 'rdx/utils/create-action'; export default { setAuthToken: authToken => createAction(types.SET_AUTH_TOKEN, authToken), requestLogin: payload => createAction(types.REQUEST_LOGIN, payload), requestLogout: payload => createAction(types.REQUEST_LOGOUT, payload), };
$(function () { checkUserSignIn(); }) const checkUserSignIn = () => { firebase.auth().onAuthStateChanged(function (user) { if (user) { profileUser(user); getBasketForUser(user); // user.updateProfile({ // location: "32/11 หมู่ 1 ถ.วิชิตสงคราม ต.กะทู้ อ.กะทู้ จ.ภูเก็ต" // }).then(function () { // console.log("add Location"); // }).catch(function (error) { // // An error happened. // }); } else { window.location.href = "Login.html" } }); } const profileUser = (user) => { $("#showProfile").empty(); const result = ` <ons-row class="d-flex justify-content-start"> <img src="${user.photoURL}" alt="" class="imgprofile"> <div class="profileName">${user.displayName}</div> </ons-row> ` $("#showProfile").append(result) }
angular .module('more') .component('moreRight', { templateUrl: 'app/page/more/more-right.html', controller: MoreRightController }); /** @ngInject */ function MoreRightController() { // var vm = this; }
import Vue from 'vue'; import VueQuill from 'vue-quill'; import { BootstrapVue, BootstrapVueIcons } from 'bootstrap-vue'; import VueExcelXlsx from 'vue-excel-xlsx'; import App from './App.vue'; import router from './router'; import VueCtkDateTimePicker from 'vue-ctk-date-time-picker'; import registerLoginApiListeners from './registerLoginApiListeners'; import 'bootstrap/dist/css/bootstrap.css'; import 'bootstrap-vue/dist/bootstrap-vue.css'; import 'vue-ctk-date-time-picker/dist/vue-ctk-date-time-picker.css'; import { mainMixin } from './main'; import './styles/global.scss'; Vue.use(VueQuill); Vue.use(BootstrapVue); Vue.use(BootstrapVueIcons); Vue.use(VueExcelXlsx); Vue.component('VueCtkDateTimePicker', VueCtkDateTimePicker); Vue.config.productionTip = false; Vue.mixin(mainMixin); if (window.LoginAPI.isModuleInited()) { window.LoginAPI.getUserProfile(() => { const vm = new Vue({ router, render: h => h(App), }).$mount('#app'); registerLoginApiListeners(vm); }); } else { window.addEventListener('login_api_init', () => { const vm = new Vue({ router, render: h => h(App), }).$mount('#app'); registerLoginApiListeners(vm); }); } window.handleRedirect = (options = {}) => { if (options.action && options.action !== '') { options.action(); } else if (options.link && options.link !== '') { window.location.replace(options.link); } };
import React from "react"; import { Link } from "react-router-dom"; import Card from "react-bootstrap/Card"; export default function Pokecard(props) { return ( <Card style={{ width: "18rem" }}> <Link to={`/pokemon/${props.id}`}> <Card.Img variant="top" src={props.image} /> </Link> <Card.Body> <Card.Title> {props.name} #{props.id} </Card.Title> </Card.Body> </Card> ); }
/* eslint-disable no-undef */ import messagesReducer from '../MessagesReducer' const initialFakeState = { ABCDE123435: [ { _type: 'Message', id: 'GHJJYYF7654343', createdAt: new Date().toISOString(), body: { text: 'Ciao Amici', }, from: { _type: 'User', id: 'TTRREE555FGG', userName: 'Aethiss', }, to: { _type: 'Group', id: 'ABCDE123435', }, }, { _type: 'Message', id: 'GHJJAAAAA654343', createdAt: new Date().toISOString(), body: { text: 'Ciao Stronzo !', }, from: { _type: 'User', id: 'TTRREE55AAAA', userName: 'DbPass', }, to: { _type: 'Group', id: 'ABCDE123435', }, }, ], } describe('@Messages Reducer', () => { it('GET - Get all messages from group', () => { const testReducer = messagesReducer( initialFakeState, { type: 'GET_ALL_MESSAGES_FROM_GROUP', groupId: 'ABCDE123435', }, ) expect(testReducer.length).toBe(2) }) it('ADD - Add new message from group', () => { const newMsg = { _type: 'Message', id: 'GHJJA44443AA654343', createdAt: new Date().toISOString(), body: { text: 'Porkamadonna !', }, from: { _type: 'User', id: 'TTRREE55AAAA', userName: 'DbPass', userPicture: 'c://home/ios', }, to: { _type: 'Group', id: 'ABCDE123435', }, } const testReducer = messagesReducer( initialFakeState, { type: 'ADD_NEW_MESSAGE_TO_GROUP', message: newMsg, }, ) expect(testReducer.ABCDE123435.length).toBe(3) }) it('Remove All messages from group (Group Delete ??)', () => { const testReducer = messagesReducer( initialFakeState, { type: 'REMOVE_ALL_MESSAGE_FROM_GROUP', groupId: 'ABCDE123435', }, ) expect(testReducer.ABCDE123435.length).toBe(0) }) it('ADD GROUP CHAT : add empty new group', () => { const testReducer = messagesReducer( {}, { type: 'CREATE_NEW_GROUP_MESSAGES', groupId: 'ABCDE123435', }, ) expect(testReducer.ABCDE123435.length).toBe(0) }) it.skip('SET all group messages', () => { const testAllReducer = messagesReducer( {}, { type: 'SET_ALL_GROUP_MESSAGES', store: initialFakeState, }, ) console.log(testAllReducer) expect(testAllReducer.ABCDE123435.length).toBe(2) }) })
import app from './app'; export default module.exports; export { app, }
import React from 'react'; import {ReactPageClick} from 'react-page-click'; import { browserHistory } from 'react-router'; import ReactTooltip from 'react-tooltip'; import {NewBookmarkBtn} from './new-bookmark-btn'; import {LinkGrabberBtn} from './link-grabber-btn'; import FolderMembers from '../containers/folder-members'; import Bookmarks from '../../api/bookmarks/bookmarks'; import {removeBookmarksInFolder} from '../../api/bookmarks/methods'; import {can} from '/imports/modules/permissions.js'; import { removeFolder, renameFolder, setFolderPrivacy, incFolderViews } from '../../api/folders/methods'; export class BookmarksHeader extends React.Component { constructor(props) { super(props); this.state = { isEditingFolderName: false }; this._handleFolderNameClick = this._handleFolderNameClick.bind(this); this._handleCancelClick = this._handleCancelClick.bind(this); this._handleFolderNameFormSubmit = this._handleFolderNameFormSubmit.bind(this); this._handlePrivacyBtnClick = this._handlePrivacyBtnClick.bind(this); this._handleDeleteBtnClick = this._handleDeleteBtnClick.bind(this); } componentWillMount(){ if(!can.view.folder(this.props.currentFolderId)){ browserHistory.push('/not-found'); } } componentDidMount(){ incFolderViews.call({folderId: this.props.folder._id}, null); } _isOwnFolder() { return this.props.folder.createdBy === Meteor.userId(); } _isInvitedFolder() { return _.contains(this.props.folder.invitedMember, Meteor.userId()); } _handleFolderNameClick(e) { e.preventDefault(); this.setState({ isEditingFolderName: true }); } _handleCancelClick(e) { e.preventDefault() this.setState({ isEditingFolderName: false }); } _handleFolderNameFormSubmit(e) { e.preventDefault(); renameFolder.call({ folderId: this.props.folder._id, newName: this.refs.folderName.value }, null); this.setState({ isEditingFolderName: false }); } _handlePrivacyBtnClick(e) { e.preventDefault(); setFolderPrivacy.call({ folderId: this.props.folder._id, isPrivate: !this.props.folder.private }, null); } _handleDeleteBtnClick(e) { e.preventDefault(); const message = "Are you sure you want to delete the folder " + this.props.folder.name + "?"; if (confirm(message)) { // Remove all bookmarks in folder, then remove folder, then go to folders removeBookmarksInFolder.call({folderId: this.props.folder._id}, (error) => { if (error) { Bert.alert(error.reason, 'danger'); } else { removeFolder.call({folderId: this.props.folder._id}, (error) => { if (error) { Bert.alert(error.reason, 'danger'); } else { browserHistory.push('/folders'); } }); } }); } } _renderNewFolderForm() { return ( <ReactPageClick notify={this._handleCancelClick}> <span> <ul className="drop-down active"> <li> <form onSubmit={this._handleFolderNameFormSubmit}> <h4>Edit Folder Name</h4> <input ref="folderName" type="text" required={true} defaultValue={this.props.folder.name} /> <button type="submit">Rename Folder</button> or <a onClick={this._handleCancelClick} href="#">cancel</a> </form> </li> </ul> </span> </ReactPageClick> ); } _renderPrivacyBtn() { const iconClass = this.props.folder.private ? 'fa fa-lock' : 'fa fa-unlock'; const tip = this.props.folder.private ? 'Private. Visible only by you and \ invited members.<br /> Click to make folder public (visible by anyone).' : 'Public. \ This folder is visible by anyone.<br /> \ Click to make folder private (Visible only by you and invited members.)'; return( <a ref="privacyBtn" onClick={this._handlePrivacyBtnClick} data-tip={tip} className="add-new header-btn" href="#"> <i className={iconClass}></i> </a> ); } _renderDeleteBtn() { const tip = "Delete this folder."; return( <a onClick={this._handleDeleteBtnClick} data-tip={tip} className="add-new header-btn" href="#"> <i className="fa fa-trash"></i> </a> ); } render() { const headerTitle = () => ( <span> <h3 id="folderName" className="clickable" onClick={this._handleFolderNameClick} > {this.props.folder.name} </h3> <NewBookmarkBtn folderId={this.props.folder._id} /> {can.create.multipleBookmarks(this.props.currentFolderId) ? <LinkGrabberBtn folderId={this.props.folder._id} /> : ''} </span> ); const staticHeaderTitle = () => ( <span> <h3 id="folderName">{this.props.folder ? this.props.folder.name : ''}</h3> </span> ); const headerContents = () => ( <span> { this.state.isEditingFolderName ? this._renderNewFolderForm() : headerTitle() } { !this.state.isEditingFolderName && can.edit.privacy(this.props.currentFolderId) ? this._renderPrivacyBtn() : '' } { !this.state.isEditingFolderName && can.delete.folder(this.props.currentFolderId) ? this._renderDeleteBtn() : '' } </span> ); const bookmarksHeader = () => { if(this._isOwnFolder() || this._isInvitedFolder()){ return headerContents(); } else{ return headerTitle(); } } return ( <header className="view-header"> { this.props.folder && can.edit.folder(this.props.currentFolderId) ? headerContents() : staticHeaderTitle() } { can.edit.folder(this.props.currentFolderId) ? <FolderMembers folder={this.props.folder} /> : '' } <ReactTooltip place="right" multiline={true} effect="solid" /> </header> ); } }
/** * FileName: img-compress.js * Author: 复制网上的代码改写的 * Date: 2019.10.11 17:26:55 * Description:图片压缩,将base64编码格式的图片使用canval绘制后获取,按需求设置绘制大小,绘制质量。 * @param {*} path 图片路径base64 * @param {*} params 压缩图片的参数 * @params.width: 生成图片宽度,默认原图宽度,最大宽度1024 * @params.height: 生成图片高度,默认原图高度 * @params.quality: 生成图片质量,默认值0.7,取值范围0-1,取值过低图片会很模糊 * @params.maxSize: 限制图片大小,默认值1024*1024字节,即(1MB),单位字节,生成图片后的,超出限制值会返回状态 * @params.ignoredArr: 忽略的格式,不压缩此格式图片,默认值['gif'],不压缩gif格式的图片 * 返回值:code: 成功:0,失败:1 msg: 消息 size: 图片压缩后的大小,单位B format: 图片格式 base64: 图片压缩后的base64 KB: 图片大小,单位kb */ function compress(path, params = '') { return new Promise((resolve, reject) => { try { let quality = params.quality ? parseFloat(params.quality) : 0.7; let maxSize = Number.isFinite(params.maxSize) ? params.maxSize : 1024 * 1024, width = params.width ? params.width : '', height = params.height ? params.height : '', img = new Image(), base64, format = getFormat(path), ignoredArr = params.ignoredArr || ['gif']; if (format !== null && ignoredArr.indexOf(format) >= 0) { let pathFile = convertBase64UrlToBlob(path); // 获取图片字节 let bool = pathFile.size < maxSize, // 是否小于限制字节大小 KB = Number.parseFloat((pathFile.size / 1024).toFixed(2)), value = { code: bool ? 0 : 1, msg: bool ? "ok" : "图片过大", size: pathFile.size, format, base64: path, KB }; !bool && reject(value) || resolve(value); } quality = Number.isFinite(quality) && quality > 0 && quality < 1 ? quality : 0.7; img.src = path; img.onload = function () { // 默认按比例压缩 let w = this.width, h = this.height, scale = w / h; w = width || (!width && w >= 1024 ? 1024 : w); h = height || (w / scale); //生成canvas let canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'); // 创建属性节点 let anw = document.createAttribute("width"), anh = document.createAttribute("height"); // 设置canval宽高 anw.nodeValue = w; anh.nodeValue = h; canvas.setAttributeNode(anw); canvas.setAttributeNode(anh); // 绘制图片 ctx.drawImage(this, 0, 0, w, h); base64 = canvas.toDataURL(`image/${format}`, quality); // 获取base64 let urlFile = convertBase64UrlToBlob(base64), KB = Number.parseFloat((urlFile.size / 1024).toFixed(2)), bool = urlFile.size < maxSize, value = { code: bool ? 0 : 1, msg: bool ? "ok" : "图片过大", size: urlFile.size, format, base64, KB }; !bool && reject(value) || resolve(value); } } catch (err) { console.log("err", err) reject({ code: 1, msg: "发生错误", err }) } }); // base64转为file(Blob),计算真实大小,获取图片格式,返回{size, type} function convertBase64UrlToBlob(urlData) { var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); } // 获取格式 function getFormat(base64) { let reg = /^data:image\/(\w+);base64,/i; let result = reg.exec(base64); if (result !== null) { return result[1] } return result; } } export default compress
var loadHeader = ` <header id='mainHeader'> <!--MenuIcon--> <span id="menuIcon" onclick="menu_sidebar(this)"><div class="bar1"></div><div class="bar2"></div><div class="bar3"></div></span> <!--Logo--> <h1 id="logo"><a href='#' target='_self' onclick="loadPage('main.html')"> EasyDownloading</a> </h1> <!-- Main Navbar --> <nav id="mainMenu"> <div class="menu"><a href="#home" onclick="loadPage('main.html')">Home</a> </div> <div class="menu mdrop"><a href="#reference" onclick="loadPage('ref.html')">Referencias</a><input class="Obtn" type="button" name="OpenMenu"> <nav class="submenu"> <a href="page/pes6.html">PES6</a> <a href="">outros</a> </nav> </div> <div class="menu"><a href="#music" onclick="loadPage('musics')">Musicas</a> </div> <div class="menu mdrop"><button onclick="loadPage('page/examples.html')">Programas</button><input class="Obtn" type="button" name="Mais"> <nav class="submenu"> <a href="#" onclick="loadPage('page/slide.html')">Slide</a> </div> <div class="menu"><button onclick="loadPage('about.html')">Sobre Nós</button> </div> </nav> <!-- Social --> <div id="social"> <a href="https://web.facebook.com/groups/easydown.pes6" target="_blank" title="Nosso grupo no Facebook"> <i class="fab fa-facebook-square" style="color: #374480"></i> </a> </div> <!-- Dark Mode --> <div id="darkmode" title="Mudar Tema" onclick="darkMode('#light')" draggble="false"> <i class="far fa-lightbulb"></i> <span>Light Mode</span> </div> </header> ` var loadSidebar = ` <aside id="mainSidebar"> <div class="topsidebar" style="position: relative;"> <form action="http://www.google.com/" target="_blank" method="GET"> <input class="searchTxt" name="q" type="seacrh" placeholder="Pesquisar..." autocomplete="true"> <button class="searchBtn" type="submit" autofocus="true"></button> </form> </div> <div class='fLogo'> <img src='theme/ico.jpg' alt='EasyDownloading' name='EasyDownloading'> </div> <div class='fText'> Um mini-projeto desenvolido por <br> Eril Tavares ® 2019-2020 EasyDownloading. <br> <a href="LICENSE">All rights reserved</a>. </div> <div class='fContact'> <span class='links'> <a href='mailto:erilandocarvalho@gmail.com' style='background-image:url(theme/mail.svg);' title='Gmail'>Gmail</a> <a href='https://easydownloading.github.io/' title='GitHub'>GitHub</a> </span> </div> </aside> `// END OF LOADS window.onload = function () { // Import // include /* var allTags = document.getElementsByTagName("*"); for (let z = 0; z < allTags.length; z++) { var theTag = allTags[z]; elmnt = theTag.hasAttribute("include") if (elmnt) { var atrName=theTag.getAttribute('include'); includes(theTag,atrName); } } */ $("body").prepend(loadHeader); $("body").prepend(loadSidebar); // set theme var hourTheme = new Date().getHours(); if(hourTheme >= 21 || hourTheme <= 6){ setTimeout(darkMode, 0, '#light') } // set page var pageID = sessionStorage.getItem('IDpage') || "main.html"; loadPage(pageID);// setTimeout(loadPage, 100, pageID); // set head // var _head = document.getElementsByTagName('head')[0]; // var _icon = document.createElement("link");_icon.rel="icon";_icon.href="main/icon.jpg"; // _head.appendChild(_icon); //set refH var allTags = document.getElementsByTagName("a"); for (let z = 0; z < allTags.length; z++) { var theTag = allTags[z]; elmnt = theTag.hasAttribute("href") if (elmnt) { theTag.setAttribute("target", "_parent") }} } function menu_sidebar(icon) { icon.classList.toggle('close'); let sbar = document.getElementById('mainSidebar');let container = document.getElementById('main'); if (window.innerWidth > 800) { //DESKTOP if (sbar.style.width == "300px") { sbar.style.width = "0px"; sbar.style.padding = "5px 0px"; container.style.filter = "brightness(100%) blur(0px)"; // container.style.marginLeft = '0px'; //-> Off-canvas turned off } else { sbar.style.width = "300px"; sbar.style.padding = "5px"; container.style.filter = "brightness(50%)blur(0px)"; // container.style.marginLeft = '310px'; // -> Off-canvas turned off } } else { // MOBILE if (sbar.style.width == "100%") { sbar.style.width = "0px"; sbar.style.padding = "5px 0px"; container.style.filter = "blur(0px)brightness(100%)"; // container.style.marginLeft = '0px'; -> Off-canvas turned off } else { sbar.style.width = "100%"; sbar.style.padding = "5px"; container.style.filter = "blur(2px)brightness(100%)"; // container.style.marginLeft = '310px'; -> Off-canvas turned off } } } function sidebarClose() { var micon = document.getElementById('menuIcon'); let sbar = document.getElementById('mainSidebar');let container = document.getElementById('main'); if (micon.className == "close") { micon.classList.toggle('close'); } sbar.style.width = "0px"; sbar.style.padding = "5px 0px"; container.style.filter = "blur(0px)brightness(100%)"; // container.style.marginLeft = '0px'; -> Off-canvas turned off } function loadPage(IDP) { var cont = document.getElementById('mainContent');var titl = document.getElementById('mainContent').title; cont.src = IDP; sessionStorage.setItem('IDpage', IDP); window.reload(); } function includeHTML() { var z, i, elmnt, file, xhttp; /* Loop through a collection of all HTML elements: */ z = document.getElementsByTagName("*"); for (i = 0; i < z.length; i++) { elmnt = z[i]; /*search for elements with a certain atrribute:*/ file = elmnt.getAttribute("w3-include-html"); if (file) { /* Make an HTTP request using the attribute value as the file name: */ xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4) { if (this.status == 200) {elmnt.innerHTML = this.responseText;} if (this.status == 404) {elmnt.innerHTML = "Page not found.";} /* Remove the attribute, and call this function once more: */ elmnt.removeAttribute("w3-include-html"); includeHTML(); } } xhttp.open("GET", file, true); xhttp.send(); /* Exit the function: */ return; } } }
/** * @Name setting.controller.js * * @Description Setting Operations * * @package * @subpackage * @author Suhaib <muhammad.suhaib@shifa.com.pk> * @Created on December 01, 2020 */ const Common = require("./../model/common.model"); const User = require("./../model/user.model"); const h = require("../utils/helper"); const utility = require("./../utils/utility"); const SettingController = {}; SettingController.externalLinks = async (req, res) => { let code = 500, message = "Error! Retrieving External Links", returnObj = {}; try { let result = await Common.getExternalLinks(); if (h.exists(result)) { code = 200; returnObj = h.resultObject(result, true, code); } else { code = 404; returnObj = h.resultObject([], false, code, 'External Links Not Found'); } } catch (e) { returnObj = h.resultObject([], false, code, message); throw e; } finally { res.status(code).send(returnObj); } }; SettingController.profilePicture = async (req, res) => { let code = 500, message = "Error! Retrieving Profile Picture", returnObj = {}; try { let result = await User.getProfilePicture(req.user); if (h.exists(result)) { code = 200; returnObj = h.resultObject(result, true, code); } else { code = 404; returnObj = h.resultObject([], false, code, 'Profile Picture Not Found'); } } catch (e) { returnObj = h.resultObject([], false, code, message); throw e; } finally { res.status(code).send(returnObj); } }; SettingController.getPrescriptionSettings = async (req, res) => { let code = 500, message = "Error! Retrieving Prescription Settings", returnObj = {}; try { let result = await Common.getPrescriptionSettings(req.user); if (h.exists(result)) { code = 200; returnObj = h.resultObject(result, true, code); } else { code = 404; returnObj = h.resultObject([], false, code, 'Prescription Settings Not Found'); } } catch (e) { returnObj = h.resultObject([], false, code, message); throw e; } finally { res.status(code).send(returnObj); } }; SettingController.savePrescriptionSettings = async (req, res) => { let code = 500, message = "Error! Saving Prescription Settings", returnObj = {}; try { const postData = h.getProps2(req); let result = await Common.getPrescriptionSettings(postData); let singleObj = utility._prescriptionTemplateObject(postData); if (h.checkExistsNotEmpty(result, 'doctor_id')) { const updated = await Common.update(singleObj, 'emr.doctor_prescription', { doctor_id: singleObj.doctor_id }, req.user); code = 200; returnObj = h.resultObject(updated, true, code, 'Prescription Settings Updated Successfully'); } else { code = 200; const inserted = await Common.insert(singleObj, 'emr.doctor_prescription', user); returnObj = h.resultObject(inserted, true, code, 'Prescription Settings Added Successfully'); } } catch (e) { returnObj = h.resultObject([], false, code, message); throw e; } finally { res.status(code).send(returnObj); } }; module.exports = SettingController;
import React from "react"; import classes from "./Login.modules.css"; import { reduxForm } from "redux-form"; import { Input, createField } from "../common/FormsControls/FormsControls"; import { required } from "../../utills/validators/validators"; import { connect } from "react-redux"; import { login } from "../../Redux/authReducer"; import { Redirect } from "react-router-dom"; import styles from "../common/FormsControls/FormControls.module.css"; const LoginForm = ({ handleSubmit, error, captchaUrl }) => { return ( <form onSubmit={handleSubmit}> {createField("E-mail", "email", [required], Input)} {createField("Пароль", "password", [required], Input, { type: "password", })} {createField( null, "rememberMe", null, Input, { type: "checkbox" }, "Запомнить" )} {captchaUrl && <img src={captchaUrl} />} {captchaUrl && createField("Symbols from image", "captcha", [required], Input, {})} {error && <div className={styles.formError}>{error}</div>} <div> <button>Войти</button> </div> </form> ); }; const LoginReduxFrom = reduxForm({ //unique name for form form: "login", })(LoginForm); const Login = (props) => { const onSubmit = (formData) => { props.login( formData.email, formData.password, formData.rememberMe, formData.captcha ); }; if (props.isAuth) { return <Redirect to={"/profile"} />; } return ( <div> <h1 className={classes.Login}>Войти в учетную запись</h1> <LoginReduxFrom onSubmit={onSubmit} captchaUrl={props.captchaUrl}/> </div> ); }; const mapStateToProps = (state) => ({ captchaUrl: state.auth.captchaUrl, isAuth: state.auth.isAuth, }); export default connect(mapStateToProps, { login })(Login);
import test from 'ava'; import Fifo from '../src/fifo.js'; import LocalStorage from '../src/localStorage.js'; // NOTE: Browser test only. test.skip('#constructor: will set noLS to true if there is localStorage', (t) => { const collection = new Fifo({ namespace: 'fifo:test' }); t.false(collection.noLS); }); test("#constructor: sets the default namespect to 'fifo'", (t) => { const collection = new Fifo(); t.is(collection.namespace, 'fifo'); }); test('#constructor: accepts an option to set the namespace', (t) => { const collection = new Fifo({ namespace: 'pizza' }); t.is(collection.namespace, 'pizza'); }); test('#constructor: sets the default console function to be NOOP', (t) => { const collection = new Fifo(); t.is(typeof collection.console, 'function'); }); test('#constructor: accepts an option to set the console function', (t) => { const newFunction = (data) => data; const collection = new Fifo({ console: newFunction }); t.is(collection.console, newFunction); }); test('#constructor: inits the data object', (t) => { const collection = new Fifo(); t.is(typeof collection.data, 'object'); t.true(Array.isArray(collection.data.keys)); t.is(typeof collection.data.items, 'object'); }); test('#constructor: can load data from locaStorage values', (t) => { const LS = new LocalStorage(); LS.setItem('fifo:test', JSON.stringify({ keys: ['test'], items: { test: 'VALID' } })); const collection = new Fifo({ namespace: 'fifo:test', shim: LS }); t.is(typeof collection.data, 'object'); t.deepEqual(collection.data.keys, ['test']); t.deepEqual(collection.data.items, { test: 'VALID' }); });
module.exports = function() { this.Given(/^I filter active$/, function() { const main = this.page.main(); main.click('@active'); }); this.When(/^I filter completed$/, function() { const main = this.page.main(); main.click('@completed'); }); this.Then(/^I see todos$/, function() { const main = this.page.main(); const todoList = main.section.todoList; todoList.expect.section('@all').to.be.present; }); this.Then(/^I don't see todos$/, function() { const main = this.page.main(); const todoList = main.section.todoList; todoList.expect.section('@all').not.to.be.present; }); this.Then(/^I see the route "([^"]*)"$/, function(route) { this.assert.urlContains(route); }); };
$(document).ready(function() { $("#submit").click(function() { var first = $("#que1").val(); event.preventDefault(); $(".card").hide(); if (first === "ye") { $("#L5").show(); } else if (first === "no") { $("#L3").show(); } else { alert('Please select if you like coffee?'); } }); $("#submit").click(function() { var second = $("#que2").val(); event.preventDefault(); if (second === "hi") { $("#L5").show(); } else if (second === "lo") { $("#L6").show(); } else if (second === "mo") { $("#L4").show(); } else { alert('Please select your stress level?'); } }); $("#submit").click(function() { var third = $("#que3").val(); event.preventDefault(); if (third === "es") { $("#L5").show(); } else if (third === "on") { $("#L2").show(); } else { alert('Please select if you like computers?'); } }); $("#submit").click(function() { var four = $("#que4").val(); event.preventDefault(); if (four === "Fd") { $("#L1").show(); } else if (four === "hd") { $("L6").show(); } else { alert('Please select your time prefrences?'); } }); $("#submit").click(function() { var five = $("#que5").val(); event.preventDefault(); if (five === "NW") { $("#L1").show(); } else if (five === "OD") { $("#L5").show(); } else { alert('Please select if you like to meet new people or not?'); } }); $("#submit").click(function() { $("#text").show(); }); $("#submit2").click(function() { var textNew = $("#exampleFormControlTextarea4").val(); alert('Thank for providing feedback!!'); }); });
import Vue from "vue"; import Router from "vue-router"; import Login from "./components/Login/login.vue"; import User from "./components/user/Home.vue"; import FindPswd from "./components/Findpswd/findpswd.vue"; Vue.use(Router); export default new Router({ mode: "history", base: process.env.BASE_URL, routes: [ { path: "/", redirect: "/login" }, { path: "/login", name: "login", component: Login }, { path: "/user", name: "user", component: User, children: [ // 当 /user/:id 匹配成功, // UserHome 会被渲染在 User 的 <router-view> 中 /* { path: "", component: UserHome } */ ] }, { path: "/findpswd", name: "findpswd", component: FindPswd } ] });
var _viewer = this; ////返回按钮 //_viewer.getBtn("goback").unbind("click").bind("click", function() { // window.location.href ="stdListView.jsp?frameId=TS_XMGL-tabFrame&sId=TS_XMGL&paramsFlag=false&title=项目管理"; //}); //列表需建一个code为BUTTONS的自定义字段,没行增加1个按钮 var qz_id = ""; var kslbk_id = ""; qz_id = $("#TS_XMGL_BM_KSLB_ADMIT-KSQZ_ID").val(); kslbk_id =$("#TS_XMGL_BM_KSLB_ADMIT-KSLBK_ID").val(); var kslb_id =$("#TS_XMGL_BM_KSLB_ADMIT-KSLB_ID").val(); $("#TS_XMGL_BM_KSLB_ADMIT_GRADE .rhGrid").find("tr").each(function(index, item) { if(index != 0){ var dataId = item.id; $(item).find("td[icode='buttons']").append( '<a class="rhGrid-td-rowBtnObj rh-icon" id="TS_XMGL_BM_FZGKS_delete" rowpk="'+dataId+'"><span class="rh-icon-inner">删除</span><span class="rh-icon-img btn-delete"></span></a>' ); // 为按钮绑定卡片 bindCard(); } }); /* * 删除前方法执行 */ rh.vi.listView.prototype.beforeDelete = function(pkArray) { showVerify(pkArray,_viewer); } //绑定的事件 function bindCard(){ //当行删除事件 jQuery("td [id='TS_XMGL_BM_KSLB_ADMIT_GRADE_delete']").unbind("click").bind("click", function(){ var pkCode = jQuery(this).attr("rowpk"); rowDelete(pkCode,_viewer); }); } _viewer.getBtn("add").unbind("click").bind("click",function() { //1.构造查询选择参数,其中参数【HTMLITEM】非必填,用以标识返回字段的值为html标签类的 var configStr = "TS_XMGL_BM_KSLBK,{'TARGET':'','SOURCE':'KSLBK_NAME~KSLBK_CODE~KSLBK_XL~KSLBK_XL_CODE~KSLBK_MK~KSLBK_MKCODE~KSLBK_TYPE_NAME~KSLBK_TYPE~KSLBK_ID~KSLBK_TIME'," + "'HIDE':'KSLBK_CODE~KSLBK_XL_CODE~KSLBK_MKCODE~KSLBK_TYPE~KSLBK_TIME','EXTWHERE':'','TYPE':'multi','HTMLITEM':''}"; /*and KSLBK_CODE!=^023001^*/ var options = { "config" :configStr, "parHandler":_viewer, "formHandler":_viewer.form, "replaceCallBack":function(idArray) {//回调,idArray为选中记录的相应字段的数组集合 var ids = idArray.KSLBK_ID.split(","); var xlcodes = idArray.KSLBK_XL_CODE.split(","); var mkcodes = idArray.KSLBK_MKCODE.split(","); var type = idArray.KSLBK_TYPE.split(","); var lbcodes = idArray.KSLBK_CODE.split(","); var paramjson={}; var paramlist = []; for(var i=0;i<ids.length;i++){ var param = {}; param["KSLBK_ADMIT_ID"] = kslb_id; param["KSQZ_ID"] = qz_id; param["KSLBK_ID"]=kslbk_id; param["KSLB_XL"]=xlcodes[i]; param["KSLB_MK"]=mkcodes[i]; param["KSLB_TYPE"]=type[i]; param["KSLB_LB"]=lbcodes[i]; paramlist.push(param); } paramjson["BATCHDATAS"]= paramlist; var result =FireFly.batchSave(_viewer.servId,paramjson,"",false,false); // if(result._DATA_.length >0){ // for(var j=0;j<result._DATA_.length;j++){ // var paramKssj = {}; // // paramKssj["KSSJ_KSNUM"]=result._DATA_[j].KSLB_KSNUM; // paramKssj["KSSJ_KSNAME"]=result._DATA_[j].KSLB_KSNAME; // paramKssj["XM_ID"]=result._DATA_[j].XM_ID; // //paramKssj["XM_SZ_ID"]=result._DATA_[j].XM_SZ_ID; // paramKssj["KSLB_ID"]=result._DATA_[j].KSLB_ID; // paramKsList.push(paramKssj); // } // paramKsJson["BATCHDATAS"]= paramKsList; // // FireFly.batchSave("TS_XMGL_KSSJ",paramKsJson,"",false,false);//保存到考试试卷中 // } //console.log(result); //_viewer.listBarTip("保存成功"); //_viewer.listBarTipError("选择失败");*/ _viewer.refresh(); } } //2.用系统的查询选择组件 rh.vi.rhSelectListView() var queryView = new rh.vi.rhSelectListView(options); queryView.show(event,[],[0,495]); });
/* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. * File Name : class_methods.js * Created at : 2017-08-03 * Updated at : 2020-06-02 * Author : jeefo * Purpose : * Description : .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.*/ // ignore:start "use strict"; /* globals*/ /* exported*/ // ignore:end const extend_member = require("@jeefo/utils/class/extend_member"); module.exports = JeefoElement => { // ClassList if (Element.prototype.hasOwnProperty("classList")) { extend_member(JeefoElement, "add_class", function () { this.DOM_element.classList.add.apply( this.DOM_element.classList, arguments ); }); extend_member(JeefoElement, "remove_class", function () { this.DOM_element.classList.remove.apply( this.DOM_element.classList, arguments ); }); extend_member(JeefoElement, "toggle_class", function (name) { this.DOM_element.classList.toggle(name); }); extend_member(JeefoElement, "has_class", function (name) { return this.DOM_element.classList.contains(name); }); } else { // IE8/9, Safari const generate_class_regex = name => new RegExp(`(^| )${ name }( |$)`); extend_member(JeefoElement, "has_class", function (class_name) { const class_regex = generate_class_regex(class_name); return class_regex.test(this.DOM_element.className); }); extend_member(JeefoElement, "add_class", function () { const dom_element = this.DOM_element; for (let i = 0; i < arguments.length; ++i) { const class_name = arguments[i]; const class_regex = generate_class_regex(class_name); if (! class_regex.test(dom_element.className)) { if (dom_element.className) { dom_element.className += ` ${ class_name }`; } else { dom_element.className = class_name; } } } }); extend_member(JeefoElement, "remove_class", function () { const dom_element = this.DOM_element; for (let i = 0; i < arguments.length; ++i) { const class_name = arguments[i]; const class_regex = generate_class_regex(class_name); const class_names = dom_element.className; dom_element.className = class_names.replace(class_regex, ''); } }); extend_member(JeefoElement, "toggle_class", function (class_name) { if (this.has_class(class_name)) { this.remove_class(class_name); return false; } this.add_class(class_name); return true; }); } extend_member(JeefoElement, "replace_class", function (old_class_name, new_class_name) { this.remove_class(old_class_name); this.add_class(new_class_name); }); };
/// <reference name="MicrosoftAjax.debug.js" /> function appendPreOrPostMatch(preMatch, strings) { // appends pre- and post- token match strings while removing escaped characters. // Returns a single quote count which is used to determine if the token occurs // in a string literal. var quoteCount = 0; var escaped = false; for (var i = 0, il = preMatch.length; i < il; i++) { var c = preMatch.charAt(i); switch (c) { case '\'': if (escaped) strings.push("'"); else quoteCount++; escaped = false; break; case '\\': if (escaped) strings.push("\\"); escaped = !escaped; break; default: strings.push(c); escaped = false; break; } } return quoteCount; } Sys.CultureInfo.prototype._getTimeFormats = function CultureInfo$getTimeFormats() { var formats = this._timeFormats; if (!formats) { var dtf = this.dateTimeFormat; this._timeFormats = formats = [dtf["ShortTimePattern"], dtf["LongTimePattern"]]; } return formats; } function outOfRange(value, low, high) { return (value < low) || (value > high); } $type = Time = function () { this._seconds = 0; if (arguments.length == 1) { switch (typeof (arguments[0])) { case 'object': this._ctor$Time(arguments[0]); break; case 'string': this._ctor$String(arguments[0]); break; case 'number': this._ctor$Number(arguments[0]); break; } } else if (arguments.length == 2 && typeof (arguments[0]) == 'number' && typeof (arguments[1]) == 'number') { this._ctor2(arguments[0], arguments[1]); } else if (arguments.length == 3 && typeof (arguments[0]) == 'number' && typeof (arguments[1]) == 'number' && typeof (arguments[2]) == 'number') { this._ctor3(arguments[0], arguments[1], arguments[2]); } else if (arguments.length == 0) { this._ctor(); } } //#region parse $type._expandFormat = function Time$expandFormat(dtf, format) { // expands unspecified or single character time formats into the full pattern. format = format || "T"; var len = format.length; if (len === 1) { switch (format) { case "t": return dtf["ShortTimePattern"]; case "T": return dtf["LongTimePattern"]; } } return format; } $type._getTokenRegExp = function Time$getTokenRegExp() { // regular expression for matching time tokens in format strings. return /\/|hh|h|HH|H|mm|m|ss|s|tt|t/g; } $type._getParseRegExp = function Time$getParseRegExp(dtf, format) { // converts a format string into a regular expression with groups that // can be used to extract date fields from a time string. // check for a cached parse regex. var re = dtf._parseTimeRegExp; if (!re) { dtf._parseTimeRegExp = re = {}; } else { var reFormat = re[format]; if (reFormat) { return reFormat; } } // expand single digit formats, then escape regular expression characters. var expFormat = Time._expandFormat(dtf, format); expFormat = expFormat.replace(/([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g, "\\\\$1"); var regexp = ["^"]; var groups = []; var index = 0; var quoteCount = 0; var tokenRegExp = Time._getTokenRegExp(); var match; // iterate through each date token found. while ((match = tokenRegExp.exec(expFormat)) !== null) { var preMatch = expFormat.slice(index, match.index); index = tokenRegExp.lastIndex; // don't replace any matches that occur inside a string literal. quoteCount += appendPreOrPostMatch(preMatch, regexp); if (quoteCount % 2) { regexp.push(match[0]); continue; } // add a regex group for the token. var m = match[0], len = m.length, add; switch (m) { case 'tt': case 't': add = "(\\D*)"; break; case 'HH': case 'H': case 'hh': case 'h': case 'mm': case 'm': case 'ss': case 's': add = "(\\d\\d?)"; break; case '/': add = "(\\" + dtf.TimeSeparator + ")"; break; } if (add) { regexp.push(add); } groups.push(match[0]); } appendPreOrPostMatch(expFormat.slice(index), regexp); regexp.push("$"); // allow whitespace to differ when matching formats. var regexpStr = regexp.join('').replace(/\s+/g, "\\s+"); var parseRegExp = { 'regExp': regexpStr, 'groups': groups }; // cache the regex for this format. re[format] = parseRegExp; return parseRegExp; } $type._parseExact = function Time$parseExact(value, format, cultureInfo) { // try to parse the time string value by matching against the format string // while using the specified culture for time field names. value = value.trim(); var dtf = cultureInfo.dateTimeFormat, // convert time formats into regular expressions with groupings. // use the regexp to determine the input format and extract the date fields. parseInfo = Time._getParseRegExp(dtf, format), match = new RegExp(parseInfo.regExp).exec(value); // Return null to avoid Firefox warning "does not always return a value" if (match === null) return null; // found a time format that matches the input. var groups = parseInfo.groups, hour = 0, min = 0, sec = 0, pmHour = false; // iterate the format groups to extract and set the date fields. for (var j = 0, jl = groups.length; j < jl; j++) { var matchGroup = match[j + 1]; if (matchGroup) { var current = groups[j], clength = current.length, matchInt = parseInt(matchGroup, 10); switch (current) { case 'h': case 'hh': // Hours (12-hour clock). hour = matchInt; if (hour === 12) hour = 0; if (outOfRange(hour, 0, 11)) return null; break; case 'H': case 'HH': // Hours (24-hour clock). hour = matchInt; if (outOfRange(hour, 0, 23)) return null; break; case 'm': case 'mm': // Minutes. min = matchInt; if (outOfRange(min, 0, 59)) return null; break; case 's': case 'ss': // Seconds. sec = matchInt; if (outOfRange(sec, 0, 59)) return null; break; case 'tt': case 't': // AM/PM designator. var upperToken = matchGroup.toUpperCase(); pmHour = (upperToken === dtf.PMDesignator.toUpperCase().substr(0, clength)); if (!pmHour && (upperToken !== dtf.AMDesignator.toUpperCase().substr(0, clength))) return null; break; } } } // if pm designator token was found make sure the hours fit the 24-hour clock. if (pmHour && (hour < 12)) { hour += 12; } return new Time(hour, min, sec); } $type._parse = function Time$_parse(value, cultureInfo, args) { // args is a params array with value as the first item, followed by custom formats. // try parse with custom formats. var i, l, time, format, formats, custom = false; for (i = 1, l = args.length; i < l; i++) { format = args[i]; if (format) { custom = true; time = Time._parseExact(value, format, cultureInfo); if (time) return time; } } // try parse with culture formats. if (!custom) { formats = cultureInfo._getTimeFormats(); for (i = 0, l = formats.length; i < l; i++) { time = Time._parseExact(value, formats[i], cultureInfo); if (time) return time; } } return null; } $type.parseInvariant = function Time$parseInvariant(value, formats) { /// <summary locid="M:J#Time.parseInvariant">Creates a time from its string representation.</summary> /// <param name="value" type="String">A string that can parse to a time.</param> /// <param name="formats" parameterArray="true" optional="true" mayBeNull="true">Custom formats to match.</param> /// <returns type="Time"></returns> //#if DEBUG var e = Function._validateParams(arguments, [ { name: "value", type: String }, { name: "formats", mayBeNull: true, optional: true, parameterArray: true } ]); if (e) throw e; //#endif return Time._parse(value, Sys.CultureInfo.InvariantCulture, arguments); } $type.parseLocale = function Time$parseLocale(value, formats) { /// <summary locid="M:J#Time.parseLocale">Creates a time from a locale-specific string representation.</summary> /// <param name="value" type="String">A locale-specific string that can parse to a time.</param> /// <param name="formats" parameterArray="true" optional="true" mayBeNull="true">Custom formats to match.</param> /// <returns type="Time"></returns> //#if DEBUG var e = Function._validateParams(arguments, [ { name: "value", type: String }, { name: "formats", mayBeNull: true, optional: true, parameterArray: true } ]); if (e) throw e; //#endif return Time._parse(value, Sys.CultureInfo.CurrentCulture, arguments); } //#endregion $type.__typeName = 'Time'; $type.__class = true; $prototype = $type.prototype; //#region constructors $prototype._ctor = function () { var date = new Date(); this._seconds = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds(); } $prototype._ctor$Time = function (time) { var e = Function._validateParams(arguments, [ { name: "time", type: Time, mayBeNull: false } ]); if (e) throw e; this._seconds = time._seconds; } $prototype._ctor$String = function (text) { var e = Function._validateParams(arguments, [ { name: "text", type: String, mayBeNull: false } ]); if (e) throw e; var time = Time.parseInvariant(text) || Time.parseLocale(text); if (time) { this._seconds = time._seconds || 0; } else { throw Error.argument('value', "Invalid time format pattern"); } } $prototype._ctor$Number = function (seconds) { var e = Function._validateParams(arguments, [ { name: "seconds", type: Number, mayBeNull: false } ]); if (e) throw e; seconds = parseInt(seconds.toString()); if (86399 < seconds || seconds < 0) { throw Error.argumentOutOfRange('seconds', "Seconds must be between 0 and 86399"); } this._seconds = seconds; } $prototype._ctor2 = function (hours, minutes) { var e = Function._validateParams(arguments, [ { name: "hours", type: Number, mayBeNull: false }, { name: "minutes", type: Number, mayBeNull: false } ]); if (e) throw e; hours = parseInt(hours.toString()) || 0; minutes = parseInt(minutes.toString()) || 0; if (hours < 0 || hours >= 24) { throw Error.argumentOutOfRange('hours', "Hour describes an un-representable time."); } if (minutes < 0 || minutes >= 60) { throw Error.argumentOutOfRange('hours', "Minute describes an un-representable time."); } this._seconds = hours * 3600 + minutes * 60; } $prototype._ctor3 = function (hours, minutes, seconds) { var e = Function._validateParams(arguments, [ { name: "hours", type: Number, mayBeNull: false }, { name: "minutes", type: Number, mayBeNull: false }, { name: "seconds", type: Number, mayBeNull: false } ]); if (e) throw e; this._ctor2(hours, minutes); seconds = parseInt(seconds.toString()) || 0; if (seconds < 0 || seconds >= 60) { throw Error.argumentOutOfRange('seconds', "Second describe an un-representable time."); } this._seconds += seconds; } //#endregion //#region get methods $prototype.getHours = function Time$getHours() { /// <summary locid="M:J#Time.getHours">Gets the hours (from 0-23).</summary> /// <returns type="Number">Returns the hours (from 0-23).</returns> if (arguments.length !== 0) throw Error.parameterCount(); return (this._seconds - (this._seconds % 3600)) / 3600; } $prototype.getMinutes = function Time$getMinutes() { /// <summary locid="M:J#Time.getMinutes">Gets the minutes (from 0-59).</summary> /// <returns type="Number">Returns the minutes (from 0-59).</returns> if (arguments.length !== 0) throw Error.parameterCount(); return ((this._seconds - this.getSeconds()) % 3600) / 60; } $prototype.getSeconds = function Time$getSeconds() { /// <summary locid="M:J#Time.getMinutes">Gets the seconds (from 0-59).</summary> /// <returns type="Number">Returns the seconds (from 0-59).</returns> if (arguments.length !== 0) throw Error.parameterCount(); return this._seconds % 60; } //#endregion //#region add methods $prototype.addSeconds = function Time$addSeconds(seconds) { /// <summary locid="M:J#Time.addSeconds">Adds seconds to the time.</summary> /// <param name="seconds" type="Number" mayBeNull="false">The seconds.</param> var e = Function._validateParams(arguments, [ { name: "seconds", type: Number, mayBeNull: false } ]); if (e) throw e; seconds = this._seconds + parseInt(seconds.toString()); if (86399 < seconds || seconds < 0) { throw Error.argumentOutOfRange('value', "The added or subtracted value results in an un-representable time."); } return new Time(seconds); } $prototype.addMinutes = function Time$addMinutes(minutes) { /// <summary locid="M:J#Time.addMinutes">Adds minutes to the time.</summary> /// <param name="minutes" type="Number" mayBeNull="false">The minutes.</param> var e = Function._validateParams(arguments, [ { name: "minutes", type: Number, mayBeNull: false } ]); if (e) throw e; minutes = parseInt(minutes.toString()); return this.addSeconds(minutes * 60); } $prototype.addHours = function Time$addHours(hours) { /// <summary locid="M:J#Time.addHours">Adds hours to the time.</summary> /// <param name="hours" type="Number" mayBeNull="false">The hours.</param> var e = Function._validateParams(arguments, [ { name: "hours", type: Number, mayBeNull: false } ]); if (e) throw e; hours = parseInt(hours.toString()); return this.addSeconds(hours * 3600); } //#endregion //#region format $prototype._toFormattedString = function Time$_toFormattedString(format, cultureInfo) { var dtf = cultureInfo.dateTimeFormat, convert = dtf.Calendar.convert; if (!format || !format.length || (format === 'i')) { if (cultureInfo.name.length) { return this._toFormattedString(dtf.LongTimePattern, cultureInfo); } else { cultureInfo = Sys.CultureInfo.InvariantCulture; return this._toFormattedString(cultureInfo.dateTimeFormat.LongTimePattern, cultureInfo); } } format = Time._expandFormat(dtf, format); // Start with an empty string var ret = []; var hour; var zeros = ['0', '00', '000']; function padZeros(num, c) { var s = num + ''; return ((c > 1) && (s.length < c)) ? (zeros[c - 2] + s).substr(-c) : s; } var quoteCount = 0, tokenRegExp = Time._getTokenRegExp(); for (; ; ) { // Save the current index var index = tokenRegExp.lastIndex; // Look for the next pattern var ar = tokenRegExp.exec(format); // Append the text before the pattern (or the end of the string if not found) var preMatch = format.slice(index, ar ? ar.index : format.length); quoteCount += appendPreOrPostMatch(preMatch, ret); if (!ar) break; // do not replace any matches that occur inside a string literal. if (quoteCount % 2) { ret.push(ar[0]); continue; } var current = ar[0], clength = current.length; switch (current) { case "h": // Hours with no leading zero for single-digit hours, using 12-hour clock case "hh": // Hours with leading zero for single-digit hours, using 12-hour clock hour = this.getHours() % 12; if (hour === 0) hour = 12; ret.push(padZeros(hour, clength)); break; case "H": // Hours with no leading zero for single-digit hours, using 24-hour clock case "HH": // Hours with leading zero for single-digit hours, using 24-hour clock ret.push(padZeros(this.getHours(), clength)); break; case "m": // Minutes with no leading zero for single-digit minutes case "mm": // Minutes with leading zero for single-digit minutes ret.push(padZeros(this.getMinutes(), clength)); break; case "s": // Seconds with no leading zero for single-digit seconds case "ss": // Seconds with leading zero for single-digit seconds ret.push(padZeros(this.getSeconds(), clength)); break; case "t": // One character am/pm indicator ("a" or "p") case "tt": // Multicharacter am/pm indicator var part = (this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator; ret.push(clength === 1 ? part.charAt(0) : part); break; case "/": ret.push(dtf.TimeSeparator); break; } } return ret.join(''); } $prototype.format = function Time$format(format) { /// <summary locid="M:J#Time.format">Format a time using the invariant culture.</summary> /// <param name="format" type="String" mayBeNull="true">Format string.</param> /// <returns type="String">Formatted date.</returns> //#if DEBUG var e = Function._validateParams(arguments, [ { name: "format", type: String, mayBeNull: true } ]); if (e) throw e; //#endif return this._toFormattedString(format, Sys.CultureInfo.InvariantCulture); } $prototype.localeFormat = function Time$localeFormat(format) { /// <summary locid="M:J#Time.localeFormat">Format a time using the current culture.</summary> /// <param name="format" type="String" mayBeNull="true">Format string.</param> /// <returns type="String">Formatted date.</returns> //#if DEBUG var e = Function._validateParams(arguments, [ { name: "format", type: String, mayBeNull: true } ]); if (e) throw e; //#endif return this._toFormattedString(format, Sys.CultureInfo.CurrentCulture); } $prototype.toString = function (format) { /// <summary locid="M:J#Time.toString">Converts a time object to a string.</summary> /// <param name="format" type="String" mayBeNull="true">Format string.</param> /// <returns type="String">Formatted time.</returns> return this.localeFormat(format); } //#endregion //#region compare $prototype.equals = function (other) { if (typeof (other) === 'undefined' || other === null) { return false; } if (Object.getType(other) != Time) { return false; } return this._seconds === other._seconds; } $prototype.compare = function (other) { if (typeof (other) === 'undefined' || other === null) { return 1; } if (Object.getType(other) != Time) { throw Error.argument('other', 'The comparing data must be a time.'); } if (this._seconds > other._seconds) return 1; if (this._seconds < other._seconds) return -1; return 0; } //#endregion $type.maxValue = new Time(86399); (function () { // The activeElement property is only supported by Internet Explorer, Firefox 3+ and Opera, as it is included in the HTML5 draft. // So it has to be fixed in the other browsers before access it. if (!("activeElement" in document)) { document.addEventListener("focus", function (evt) { if (evt && evt.target) document.activeElement = evt.target == document ? null : evt.target; }, true); document.addEventListener("blur", function (evt) { document.activeElement = null; }, true); } if (window.WebForm_FireDefaultButton) { // Fix bug: while the default button of Panel is LinkButton, it cannot be fired correctly. window.WebForm_FireDefaultButton = function (event, target) { if (event.keyCode == 13) { var src = event.srcElement || event.target; if (!src || (src.tagName.toLowerCase() != "textarea")) { var defaultButton; if (__nonMSDOMBrowser) { defaultButton = document.getElementById(target); } else { defaultButton = document.all[target]; } if (defaultButton) { if (typeof (defaultButton.click) != "undefined") { defaultButton.click(); event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); return false; } else if (typeof (defaultButton.href) != "undefined") { // for LinkButton in browsers except IE eval(decodeURIComponent(defaultButton.href.substr(11))); event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); return false; } } } } return true; }; } if (window.WebForm_SaveScrollPositionSubmit) { // Fix bug: While the browser is not Internet Explorer, // the functions to calculate scrollX and scrollY positions cannot be overrided. window.WebForm_SaveScrollPositionSubmit = function () { if (__nonMSDOMBrowser) { theForm.elements['__SCROLLPOSITIONY'].value = WebForm_GetScrollY(); theForm.elements['__SCROLLPOSITIONX'].value = WebForm_GetScrollX(); } else { theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX(); theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY(); } if ((typeof (this.oldSubmit) != "undefined") && (this.oldSubmit != null)) { return this.oldSubmit(); } return true; }; } if (window.WebForm_RestoreScrollPosition) { // Override the restore scroll position function so that the scroll function can be overrided easier. window.WebForm_RestoreScrollPosition = function () { if (__nonMSDOMBrowser) { window.WebForm_ScrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value); } else { window.WebForm_ScrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value); } if ((typeof (theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) { return theForm.oldOnLoad(); } return true; }; window.WebForm_ScrollTo = function(x, y) { window.scrollTo(x, y); }; } Sys.UI.DomElement.getBounds = function (element) { /// <summary locid="M:J#Sys.UI.DomElement.getBounds">Gets the coordinates, width and height of an element.</summary> /// <param name="element" domElement="true"></param> /// <returns type="Sys.UI.Bounds">A Bounds object with four fields, x, y, width and height, which contain the pixel coordinates, width and height of the element.</returns> var e = Function._validateParams(arguments, [ { name: "element", domElement: true } ]); if (e) throw e; var offset = Sys.UI.DomElement.getLocation(element); var size = $common.getSize(element); return new Sys.UI.Bounds(offset.x, offset.y, size.width, size.height); }; Sys.Extended.UI._CommonToolkitScripts.prototype.getSize = function (element) { /// <summary>Gets the size of an element.</summary> /// <param name="element" domElement="true"></param> /// <returns>A object with width and height, which contain the pixel width and height of the element.</returns> var e = Function._validateParams(arguments, [ { name: "element", domElement: true } ]); if (e) throw e; if (document.documentElement.getBoundingClientRect) { // window? if (element.self) { if (document.compatMode == "CSS1Compat") { // Standards-compliant mode return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }; } else { // Quirks mode return { width: document.body.clientWidth, height: document.body.clientHeight }; } } // document? if (element.nodeType === 9 || // documentElement? element === document.documentElement) { return { width: Math.max(document.documentElement.clientWidth, document.documentElement.scrollWidth) || 0, height: Math.max(document.documentElement.clientHeight, document.documentElement.scrollHeight) || 0 }; } } else { if (element.window && element.window === element) { return { width: window.innerWidth || 0, height: window.innerHeight || 0 }; } // document? if (element.nodeType === 9 || // documentElement? element === document.documentElement) { return { width: Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth) || 0, height: Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight) || 0 }; } } return { width: element.offsetWidth, height: element.offsetHeight }; }; function isSystemElement(element) { return element.self || // windows? element.nodeType === 9 || // document? element === document.documentElement || //documentElement? (element.window && element.window === element); // window? } var original_isBorderVisible = Sys.Extended.UI._CommonToolkitScripts.prototype.isBorderVisible; Sys.Extended.UI._CommonToolkitScripts.prototype.isBorderVisible = function (element, boxSide) { if (!element) { throw Error.argumentNull('element'); } if (boxSide < Sys.Extended.UI.BoxSide.Top || boxSide > Sys.Extended.UI.BoxSide.Left) { throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'Sys.Extended.UI.BoxSide')); } if (isSystemElement(element)) { return false; } return original_isBorderVisible.call(this, element, boxSide); }; var original_getMargin = Sys.Extended.UI._CommonToolkitScripts.prototype.getMargin; Sys.Extended.UI._CommonToolkitScripts.prototype.getMargin = function (element, boxSide) { if (!element) { throw Error.argumentNull('element'); } if (boxSide < Sys.Extended.UI.BoxSide.Top || boxSide > Sys.Extended.UI.BoxSide.Left) { throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'Sys.Extended.UI.BoxSide')); } if (isSystemElement(element)) { return 0; } return original_getMargin.call(this, element, boxSide); }; var original_getPadding = Sys.Extended.UI._CommonToolkitScripts.prototype.getPadding; Sys.Extended.UI._CommonToolkitScripts.prototype.getPadding = function (element, boxSide) { if (!element) { throw Error.argumentNull('element'); } if (boxSide < Sys.Extended.UI.BoxSide.Top || boxSide > Sys.Extended.UI.BoxSide.Left) { throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'Sys.Extended.UI.BoxSide')); } if (isSystemElement(element)) { return 0; } return original_getPadding.call(this, element, boxSide); }; })(); /// <reference name="MicrosoftAjax.debug.js" /> /// <reference name="MicrosoftAjaxTimer.debug.js" /> /// <reference name="MicrosoftAjaxWebForms.debug.js" /> /// <reference name="AjaxControlToolkit.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit" /> /// <reference name="AjaxControlToolkit.Common.Common.js" assembly="AjaxControlToolkit" /> function preventDefaultEvent(eventArgs) { eventArgs.preventDefault(); } function stopEventPropagation(eventArgs) { eventArgs.stopPropagation(); } function WebForm_FireCancelButton(event, target) { if ((event.keyCode || event.charCode) == 27) { var defaultButton; if (__nonMSDOMBrowser) { defaultButton = document.getElementById(target); } else { defaultButton = document.all[target]; } if (defaultButton && typeof (defaultButton.click) != "undefined") { defaultButton.click(); event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); event.preventDefault(); return false; } } return true; } (function () { function execute() { Type.registerNamespace('VitalShining.Galaxy'); if (!String.prototype.padLeft) { String.prototype.padLeft = function (len, ch) { ch = typeof (ch) === 'undefined' ? ' ' : ch; var s = String(this); while (s.length < len) s = ch + s; return s; }; } if (!String.prototype.padRight) { String.prototype.padRight = function (len, ch) { ch = typeof (ch) === 'undefined' ? ' ' : ch; var s = String(this); while (s.length < len) s += ch; return s; }; } if (!Array.map) { Array.map = function (arr, callback, arg) { var ret = []; Sys._foreach(arr, function (e, i) { ret[i] = callback(e, i); return true; }); return ret; }; } Sys._merge($common = $common || {}, { getMaxLevel: function (container, excludes) { container = container || document.body; var maxLevel = 0; for (var i = 0, l = container.childNodes.length; i < l; i++) { var element = container.childNodes[i]; if (excludes && Array.contains(excludes, element)) continue; if (element.nodeType == 1 && $common.getVisible(element)) { var zIndex = 0; if (element.style.zIndex) { if (typeof (element.style.zIndex) == String) { zIndex = parseInt(element.style.zIndex); } else { zIndex = element.style.zIndex; } } maxLevel = Math.max(maxLevel, Math.max(zIndex, $common.getMaxLevel(element))); } } return maxLevel; }, getScrollBounds: function () { var x, y, width, height; // in Opera the client size not equals body size, this is a bug of Sys.Extended.UI if (Sys.Browser.agent == Sys.Browser.Opera) { var htmlElement = document.getElementsByTagName('html')[0]; x = htmlElement.scrollLeft; y = htmlElement.scrollTop; width = htmlElement.clientWidth; height = htmlElement.clientHeight; } else if (Sys.Browser.agent == Sys.Browser.InternetExplorer) { x = document.documentElement.scrollLeft; y = document.documentElement.scrollTop; width = document.documentElement.clientWidth || document.body.offsetWidth; height = document.documentElement.clientHeight || document.body.offsetHeight; } else if (Sys.Browser.agent == Sys.Browser.Firefox) { // In the firefox 3.5 and above version, the value of body scroll left and scroll top cannot indicate the browser actual scroll position // So it should be alternatived with documentElement scroll left and scroll top. x = document.body.scrollLeft || document.documentElement.scrollLeft; y = document.body.scrollTop || document.documentElement.scrollTop; var viewportwidth = window.innerWidth; var viewportheight = window.innerHeight; var offsetWidth = document.documentElement.offsetWidth; var offsetHeight = document.documentElement.offsetHeight; width = offsetWidth < viewportwidth ? viewportwidth : offsetWidth; height = offsetHeight < viewportheight ? viewportheight : offsetHeight; } else { // Sys.Browser.Safari, etc. var viewportwidth = window.innerWidth; var viewportheight = window.innerHeight; var offsetWidth = document.documentElement.offsetWidth; var offsetHeight = document.documentElement.offsetHeight; x = document.body.scrollLeft; y = document.body.scrollTop; width = offsetWidth < viewportwidth ? viewportwidth : offsetWidth; height = offsetHeight < viewportheight ? viewportheight : offsetHeight; } return new Sys.UI.Bounds(x, y, width, height); }, setSelectionRange: function (element, selectionStart, selectionEnd) { if (element.setSelectionRange) { element.setSelectionRange(selectionStart, selectionEnd); } else if (element.createTextRange) { var range = element.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } }, getSelectionRange: function (element) { if (element.setSelectionRange) { return { start: parseInt(element.selectionStart, 10), end: parseInt(element.selectionEnd, 10) }; } else if (document.selection) { function getSelectionPosition(e, sType) { var selection = document.selection.createRange(), dummy = e.createTextRange(), position; for (position = 0; dummy.compareEndPoints("StartTo" + sType, selection) != 0; position++) { dummy.moveStart('character'); } return position; } return { start: getSelectionPosition(element, "Start"), end: getSelectionPosition(element, "End") }; } return null; }, queryAncestor: function (elt, selector, single) { var found = [], finders = [], selectors, simpleNonTag = /^([\$#\.])((\w|[$:\.\-])+)$/, tag = /^((\w+)|\*)$/; ; if (typeof (selector) === "string") { selectors = [selector]; } else { selectors = selector; } Array.forEach(selectors, function (sel) { if (typeof (sel) === "string") { var finder = null; var match = simpleNonTag.exec(sel); if (match && match.length === 4) { sel = match[2]; finder = match[1] === "#" ? // find by ID function (element, s) { return element.id == s; } : // find by className function (element, s) { var className = element.className; return className && (className === s || className.indexOf(' ' + s) >= 0 || className.indexOf(s + ' ') >= 0); }; } else if (tag.test(sel)) { finder = function (element, s) { return element.nodeType === 1 && (s === '*' || element.tagName.toLowerCase() === s); }; } if (finder) finders.push({ selector: sel, finder: finder }); } }); if (finders.length > 0) { do { for (var i = 0, l = finders.length; i < l; i++) { if (finders[i].finder(elt, finders[i].selector)) { if (single) return elt; else found.push(elt); } } } while (elt = elt.parentNode); if (single) return null; else return found; } return null; }, _hexchars: '0123456789ABCDEF'.split(''), uuid: function () { /// <summary> /// Generate a random uuid. /// </summary> var id = new Array(32), rnd = 0, r; for (var i = 0; i < 32; i++) { if (i == 12) { id[i] = '4'; } else { if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0; r = rnd & 0xf; rnd = rnd >> 4; id[i] = this._hexchars[(i == 16) ? (r & 0x3) | 0x8 : r]; } } return id.join(''); } }); } if (Sys.loader) { Sys.loader.registerScript("GalaxyCommon", null, execute); } else { execute(); } })(); Type.registerNamespace('Page'); //#region FloatingBehavior Page.FloatingBehavior = function (element) { Page.FloatingBehavior.initializeBase(this, [element]); this.enabled = true; this.get_dropTargetElement = function() { return window; }; this.checkCanDrag = function (e) { if (this.enabled) { var undraggableTagNames = ["input", "button", "select", "textarea", "label"]; var tagName = e.tagName; if (tagName.toLowerCase() == "a" && e.href) { return false; } if (Array.indexOf(undraggableTagNames, tagName.toLowerCase()) > -1) { return false; } return true; } else { return false; } }; }; Page.FloatingBehavior.registerClass('Page.FloatingBehavior', Sys.Extended.UI.FloatingBehavior); //#endregion //#region DialogButton behavior Page.DialogButton = function(element) { /// <summary> /// The DialogButton is used to manage the css class changes and event handlers for the dialog controlling button. /// </summary> /// <param name="element" type="Sys.UI.DomElement" domElement="true"> /// DOM Element the behavior is associated with /// </param> Page.DialogButton.initializeBase(this, [element]); this.className = null; this._mousedown = false; this._mouseover = false; this._mousedownHandler = null; this._mouseupHandler = null; this._mouseoverHandler = null; this._mouseoutHandler = null; this._clickHandler = null; }; Page.DialogButton.prototype = { //#region System initialize: function () { /// <summary> /// Initialize the behavior /// </summary> Page.DialogButton.callBaseMethod(this, 'initialize'); var element = this.get_element(); Sys.UI.DomElement.addCssClass(element, this.className); this._mousedownHandler = Function.createDelegate(this, this._onMouseDown); $addHandler(element, 'mousedown', this._mousedownHandler); this._mouseupHandler = Function.createDelegate(this, this._onMouseUp); $addHandler(element, 'mouseup', this._mouseupHandler); this._mouseoverHandler = Function.createDelegate(this, this._onMouseOver); $addHandler(element, 'mouseover', this._mouseoverHandler); this._mouseoutHandler = Function.createDelegate(this, this._onMouseOut); $addHandler(element, 'mouseout', this._mouseoutHandler); this._clickHandler = Function.createDelegate(this, this._onClick); $addHandler(element, 'click', this._clickHandler); }, dispose: function () { /// <summary> /// Dispose the behavior /// </summary> var element = this.get_element(); if (this._mousedownHandler) { $removeHandler(element, 'mousedown', this._mousedownHandler); this._mousedownHandler = null; } if (this._mouseupHandler) { $removeHandler(element, 'mouseup', this._mouseupHandler); this._mouseupHandler = null; } if (this._mouseoverHandler) { $removeHandler(element, 'mouseover', this._mouseoverHandler); this._mouseoverHandler = null; } if (this._mouseoutHandler) { $removeHandler(element, 'mouseout', this._mouseoutHandler); this._mouseoutHandler = null; } if (this._clickHandler) { $removeHandler(element, 'click', this._clickHandler); this._clickHandler = null; } Page.DialogButton.callBaseMethod(this, 'dispose'); }, //#endregion //#region Properties get_className: function () { /// <value type="String"> /// Gets the CSS class name to apply to the button. /// </value> return this.className; }, set_className: function (className) { /// <value type="String"> /// Sets the CSS class name to apply to the button. /// </value> if (this.className != className) { if (this.get_isInitialized()) { var element = this.get_element(); $common.removeCssClasses(element, [this.className, this.className + '-mouseover', this.className + '-mousedown']); Sys.UI.DomElement.addCssClass(element, className); if (this.mousedown) { Sys.UI.DomElement.addCssClass(element, className + '-mousedown'); } if (this.mouseover) { Sys.UI.DomElement.addCssClass(element, className + '-mouseover'); } this.raisePropertyChanged('className'); } this.className = className; } }, //#endregion //#region Handlers _onMouseDown: function (eventArgs) { /// <summary> /// Handler for button mousedown event. /// </summary> this.mousedown(); eventArgs.stopPropagation(); }, _onMouseOver: function (eventArgs) { /// <summary> /// Handler for button mouseover event. /// </summary> this.mouseover(); }, _onMouseOut: function (eventArgs) { /// <summary> /// Handler for button mouseout event. /// </summary> this.mouseout(); }, _onMouseUp: function (eventArgs) { /// <summary> /// Handler for button mouseup event. /// </summary> this.mouseup(); }, _onClick: function (eventArgs) { /// <summary> /// Handler for button click event. /// </summary> this.click(); eventArgs.stopPropagation(); }, //#endregion //#region Events add_click: function (handler) { /// <summary> /// Add an event handler for the click event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler("click", handler); }, remove_click: function (handler) { /// <summary> /// Remove an event handler from the click event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler("click", handler); }, raiseClick: function (arg) { /// <summary> /// Raise the click event /// </summary> /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false"> /// Event arguments for the click event /// </param> /// <returns /> var handler = this.get_events().getHandler("click"); if (handler) handler(this, arg); }, add_mouseover: function (handler) { /// <summary> /// Add an event handler for the mouseover event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler("mouseover", handler); }, remove_mouseover: function (handler) { /// <summary> /// Remove an event handler from the mouseover event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler("mouseover", handler); }, raiseMouseover: function (arg) { /// <summary> /// Raise the mouseover event /// </summary> /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false"> /// Event arguments for the mouseover event /// </param> /// <returns /> var handler = this.get_events().getHandler("mouseover"); if (handler) handler(this, arg); }, add_mouseout: function (handler) { /// <summary> /// Add an event handler for the mouseout event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler("mouseout", handler); }, remove_mouseout: function (handler) { /// <summary> /// Remove an event handler from the mouseout event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler("mouseout", handler); }, raiseMouseout: function (arg) { /// <summary> /// Raise the mouseout event /// </summary> /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false"> /// Event arguments for the mouseout event /// </param> /// <returns /> var handler = this.get_events().getHandler("mouseout"); if (handler) handler(this, arg); }, add_mousedown: function (handler) { /// <summary> /// Add an event handler for the mousedown event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler("mousedown", handler); }, remove_mousedown: function (handler) { /// <summary> /// Remove an event handler from the mousedown event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler("mousedown", handler); }, raiseMousedown: function (arg) { /// <summary> /// Raise the mousedown event /// </summary> /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false"> /// Event arguments for the mouseDown event /// </param> /// <returns /> var handler = this.get_events().getHandler("mousedown"); if (handler) handler(this, arg); }, add_mouseup: function (handler) { /// <summary> /// Add an event handler for the mouseup event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler("mouseup", handler); }, remove_mouseup: function (handler) { /// <summary> /// Remove an event handler from the mouseup event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler("mouseup", handler); }, raiseMouseup: function (arg) { /// <summary> /// Raise the mouseup event /// </summary> /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false"> /// Event arguments for the mouseup event /// </param> /// <returns /> var handler = this.get_events().getHandler("mouseup"); if (handler) handler(this, arg); }, //#endregion //#region Methods show: function () { /// <summary> /// Show the button /// </summary> $common.setVisible(this.get_element(), true); }, hide: function () { /// <summary> /// Hide the button /// </summary> $common.setVisible(this.get_element(), false); }, mouseover: function () { /// <summary> /// Mouse over the button /// </summary> if (!this._mouseover) { this._mouseover = true; Sys.UI.DomElement.addCssClass(this.get_element(), this.className + '-mouseover'); this.raiseMouseover(Sys.EventArgs.Empty); } }, mouseout: function () { /// <summary> /// Mouse out the button /// </summary> if (this._mouseover) { this._mouseover = false; Sys.UI.DomElement.removeCssClass(this.get_element(), this.className + '-mouseover'); this.raiseMouseout(Sys.EventArgs.Empty); } }, mousedown: function () { /// <summary> /// Press mouse down to the button /// </summary> if (!this._mousedown) { this._mousedown = true; Sys.UI.DomElement.addCssClass(this.get_element(), this.className + '-mousedown'); this.raiseMousedown(Sys.EventArgs.Empty); } }, mouseup: function () { /// <summary> /// Release mouse up from the button /// </summary> if (this._mousedown) { this._mousedown = false; Sys.UI.DomElement.removeCssClass(this.get_element(), this.className + '-mousedown'); this.raiseMouseup(Sys.EventArgs.Empty); } }, click: function () { /// <summary> /// Click the button /// </summary> this.raiseClick(Sys.EventArgs.Empty); } //#endregion }; Page.DialogButton.registerClass('Page.DialogButton', Sys.UI.Behavior); //#endregion Page.Dialog = function() { this._window = null; this._backgroundElement = null; this._contentElement = null; this._drag = null; this._buttonClose = null; this._buttonFullScreen = null; this._buttonRestore = null; this._position = null; this._computedSize = null; this._computedPosition = null; this._widthOffset = null; this._heightOffset = null; this._shown = false; this._initialized = false; this._fullSize = false; this._repositioning = false; this._id = null; // Handlers this.body$delegates = { selectstart: preventDefaultEvent, contextmenu: preventDefaultEvent, scroll: Function.createDelegate(this, this._layout) }; this.window$delegates = { resize: Function.createDelegate(this, this._layout), scroll: Function.createDelegate(this, this._layout) }; this._saveTabIndexes = []; this._saveDisableSelect = []; this._tagWithTabIndex = ['A', 'AREA', 'BUTTON', 'INPUT', 'OBJECT', 'SELECT', 'TEXTAREA', 'IFRAME']; }; Page.Dialog.prototype = { //#region initialize & dispose initialize: function () { this._id = $common.uuid(); Page.Dialog.__cache[this._id] = this; }, dispose: function () { this.hide(); if (this._drag) { this._drag.dispose(); this._drag = null; } if (this._buttonClose) { this._buttonClose.dispose(); this._buttonClose = null; } if (this._buttonFullScreen) { this._buttonFullScreen.dispose(); this._buttonFullScreen = null; } if (this._buttonRestore) { this._buttonRestore.dispose(); this._buttonRestore = null; } if (this._window) { $common.removeElement(this._window); this._window = null; } if (this._backgroundElement) { $common.removeElement(this._backgroundElement); this._backgroundElement = null; } delete Page.Dialog.__cache[this._id]; }, //#endregion //#region properties get_id: function () { return this._id; }, get_isInitialized: function () { return this._initialized; }, get_isShown: function () { return this._shown; }, get_resizable: function () { /// <summary> /// Gets value indicating whether the popup window resizable. /// </summary> throw Error.notImplemented(); }, //#endregion //#region representation _create: function () { // Creates mask element, so that the background elements can be hidden while populating the window. $(document.body).append(String.format('<div id="mask{0}" class="DialogMask" style="display:none"></div>', this._id)); this._backgroundElement = $get('mask' + this._id); // Creates the basic dom elements for the popup window. $(document.body).append(String.format( '<div id="dialog{0}" class="Dialog" style="border-width: 0px;position: absolute;display:none">' + '<div id="handler{0}" class="handler">' + '<div id="title{0}" class="title"></div>' + '<div class="buttonContainer">' + '<table border="0px" cellspacing="0px" cellpadding="0px">' + '<tr>' + // The minimize button is not available in the current version, // since I don't know how to handle the behavior when the client user clicks this button, '<td>' + '<div class="minimize" title="Minimize" style="display:none"></div>' + '</td>' + '<td>' + '<div class="restore" title="Normalization" style="display:none"></div>' + '</td>' + '<td>' + '<div class="fullscreen" title="full screen"></div>' + '</td>' + '<td>' + '<div class="close" title="close"></div>' + '</td>' + '</tr>' + '</table>' + '</div>' + '</div>' + // Creates table with 6 cells so that we can show the cubic border effect and round corners. '<table border="0px" cellspacing="0px" cellpadding="0px" class="ContentTable" style="border-width: 0px">' + '<tr>' + '<td class="ContentLeft"></td>' + '<td class="ContentMiddle"></td>' + '<td class="ContentRight"></td>' + '</tr>' + '<tr class="BottomRow">' + '<td class="BottomLeft"></td>' + '<td class="BottomMiddle"></td>' + '<td class="BottomRight"></td>' + '</tr>' + '</table>' + '</div>', this._id)); this._window = $get('dialog' + this._id); this._buttonClose = $create(Page.DialogButton, { className: 'close' }, { click: Function.createDelegate(this, this._onClose) }, null, $('div.close', this._window).get(0)); this._buttonFullScreen = $create(Page.DialogButton, { className: 'fullscreen' }, { click: Function.createDelegate(this, this._onFullScreen) }, null, $('div.fullscreen', this._window).get(0)); this._buttonRestore = $create(Page.DialogButton, { className: 'restore' }, { click: Function.createDelegate(this, this._onRestore) }, null, $('div.restore', this._window).get(0)); this._contentElement = this.createContent($('td.ContentMiddle', this._window).get(0)); this._widthOffset = $('td.ContentLeft', this._window).width() + $('td.ContentRight', this._window).width(); this._heightOffset = $('.handler', this._window).height() + $('td.BottomMiddle', this._window).height(); this._drag = $create(Page.FloatingBehavior, { handle: $get('handler' + this._id) }, null, null, this._window); Sys.Extended.UI.DragDropManager.add_dragStop(Function.createDelegate(this, this._savePosition)); if (!this.get_resizable()) { this._buttonFullScreen.hide(); } }, createContent: function (parent) { throw Error.notImplemented(); }, //#endregion //#region controlling methods setTitle: function (title) { $('#title' + this._id).text(title); }, show: function (title, position) { if (!this._initialized) { this._create(); this._initialized = true; } this.onShowing(); if (this._shown) return; this.setTitle(title||''); this._shown = true; var zIndex = $common.getMaxLevel(null, [this._backgroundElement, this._window]); // 显示蒙板遮盖 this._backgroundElement.style.zIndex = zIndex + 1; $common.setVisible(this._backgroundElement, true); this._window.style.zIndex = zIndex + 2; $common.setVisible(this._window, true); $addHandlers(document.body, this.body$delegates); $addHandlers(window, this.window$delegates); this._position = position || 'center'; this.onShown(); // 内容显示完成之后,可能各个元素的大小会发生变化。因此需要重新设置窗口的大小和位置。 this.onresize(); this._disableTab(); }, onresize: function () { var contentSize = $common.getSize(this._contentElement); $common.setSize(this._window, { width: contentSize.width + this._widthOffset, height: contentSize.height + this._heightOffset }); this._layout(); }, hide: function () { if (!this._shown) return; this.onHiding(); $common.setVisible(this._window, false); $common.setVisible(this._backgroundElement, false); $common.removeHandlers(document.body, this.body$delegates); $common.removeHandlers(window, this.window$delegates); this._shown = false; if (document.documentElement.style.removeAttribute) { this._window.style.removeAttribute("width"); this._window.style.removeAttribute("height"); } else { this._window.style.removeProperty("width"); this._window.style.removeProperty("height"); } this._computedPosition = null; this._restoreTab(); this.onHidden(); }, //#endregion //#region methods for extending onShowing: function () { }, onShown: function () { }, onHiding: function () { }, onHidden: function () { }, onResize: function () { }, //#endregion //#region manipulate dialog location and size _layout: function () { if (this._repositioning || !this._shown) return; this._repositioning = true; if (this._fullSize) { // If the popup window is in full size mode, set the window bounds to the browser window client bounds. // It's useful when the browser window resizes. $common.setBounds(this._window, $common.getClientBounds()); this._invalidateSize(); } else { // Reposition the popup window according to the drag position or configured position, // so that the popup window can be the same position when the browser scroll bars are moved. this._layoutWindow(); this._invalidateDragLimit(); $common.setBounds(this._backgroundElement, $common.getBounds(document)); this._repositioning = false; } }, _invalidateDragLimit: function () { var bounds = $common.getScrollBounds(); var windowSize = $common.getSize(this._window); // this._drag.get_limit().top = bounds.y; // this._drag.get_limit().bottom = bounds.y + bounds.height + windowSize.height - this._heightOffset; // this._drag.get_limit().left = bounds.x - windowSize.width + this._widthOffset; // this._drag.get_limit().right = bounds.x + bounds.width + windowSize.width - this._widthOffset; }, _layoutWindow: function () { var bounds = $common.getScrollBounds(); var windowSize = $common.getSize(this._window); var x = 0; var y = 0; var position = this._computedPosition || this._position; if (typeof (position) === 'string' && position.toLowerCase() === 'center') { x = bounds.x + Math.max(0, Math.floor(bounds.width / 2.0 - windowSize.width / 2.0)); y = bounds.y + Math.max(0, Math.floor(bounds.height / 2.0 - windowSize.height / 2.0)); } else { if (typeof (position.x) === 'number') { x = bounds.x + position.x; } else if (typeof (position.x) === 'undefined' || position.x === null || (typeof (position.x) === 'string' && position.x.toLowerCase() === 'center')) { x = bounds.x + Math.max(0, Math.floor(bounds.width / 2.0 - windowSize.width / 2.0)); } if (typeof (position.y) === 'number') { y = bounds.y + position.y; } else if (typeof (position.y) === 'undefined' || position.y === null || (typeof (position.y) === 'string' && position.y.toLowerCase() === 'middle')) { y = bounds.y + Math.max(0, Math.floor(bounds.height / 2.0 - windowSize.height / 2.0)); } } $common.setLocation(this._window, new Sys.UI.Point(x, y)); }, _invalidateSize: function () { var size = $common.getSize(this._window); $common.setSize(this._contentElement, { height: size.height - this._heightOffset, width: size.width - this._widthOffset }); }, _savePosition: function () { var bounds = $common.getScrollBounds(); var location = $common.getLocation(this._window); this._computedPosition = new Sys.UI.Point(location.x - bounds.x, location.y - bounds.y); }, //#endregion //#region event handlers _onClose: function (evt) { /// <summary> /// Handler for close button click event. /// </summary> this.hide(); }, _onFullScreen: function (evt) { /// <summary> /// Handler for full screen button click event. /// </summary> this._buttonFullScreen.hide(); this._buttonRestore.show(); // Disable the drag behavior to prevent the popup window moved in the full screen mode. this._drag.enabled = false; // Saves the window size and position before switching to full screen mode, so that we can restore them. this._computedSize = $common.getSize(this._window); this._computedPosition = $common.getLocation(this._window); $common.setBounds(this._window, $common.getClientBounds()); this._invalidateSize(); this._fullSize = true; }, _onRestore: function (evt) { /// <summary> /// Handler for restore button click event. /// </summary> this._buttonFullScreen.show(); this._buttonRestore.hide(); // Enable the drag behavior so that the popup window can be moved in normalize mode. this._drag.enabled = true; $common.setSize(this._window, this._computedSize); this._computedSize = null; this._invalidateSize(); $common.setLocation(this._window, this._computedPosition); this._fullSize = false; }, //#endregion //#region tab indices manipulation _disableTab: function (parentElement) { /// <summary> /// Change the tab indices so we only tab through the modal popup /// (and hide SELECT tags in IE6) /// </summary> parentElement = parentElement || document; var _this = this; // Saves the tab indices in the current document. $(this._tagWithTabIndex.join(','), parentElement).each(function () { if (this.tabIndex != "-1" && !$.contains(_this._window, this)) { Array.add(_this._saveTabIndexes, { e: this, i: this.tabIndex }); this.tabIndex = "-1"; } }); //IE6 Bug with SELECT element always showing up on top if ($.browser.msie && parseInt($.browser.version, 10) < 7) { $('select', parentElement).each(function () { var visibility = $(this).css('visibility'); // Hidden the visible elements that are not in the popup window , // and store their previous visiblity so that we can restore them when closing the popup window. if (visibility != 'hidden' && !$.contains(_this._window, this)) { Array.add(_this._saveDisableSelect, { e: this, v: visibility }); $(this).css('visibility', 'hidden'); } }); } // Find all the iframe elements and process them recursively, since the dom selector. $('iframe', parentElement).each(function () { if (!$.contains(_this._window, this)) { _this._disableTab(this.contentWindow.document); } }); }, _restoreTab: function () { /// <summary> /// Restore the tab indices so we tab through the page like normal /// (and restore SELECT tags in IE6) /// </summary> // Restore the tab indices $.each(this._saveTabIndexes, function () { this.e.tabIndex = this.i; }); Array.clear(this._saveTabIndexes); // Restore the SELECT elements while the browse is IE6 to fix Bug with SELECT element always showing up on top if ($.browser.msie && parseInt($.browser.version, 10) < 7) { $.each(this._saveDisableSelect, function () { this.e.style.visibility = this.v; }); Array.clear(this._saveDisableSelect); } } //#endregion }; Page.Dialog.registerClass('Page.Dialog'); Page.Dialog.__cache = {}; Page.Dialog.close = function (id) { var dialog = Page.Dialog.__cache[id]; if (dialog) { dialog.hide(); } } Page.Dialog.resize = function(id, size) { var dialog = Page.Dialog.__cache[id]; if (dialog && dialog.resize) { dialog.resize(size); } } Type.registerNamespace('Page'); Page.Message = function () { Page.Message.initializeBase(this); this._container = null; this._buttonContainer = null; this._contentDiv = null; this._textDiv = null; this._buttonOk = null; this._buttonCancel = null; this._context = null; this._queue = []; this._cancelClickHandler = null; this._okClickHandler = null; } Page.Message.prototype = { initialize: function () { Page.Message.callBaseMethod(this, 'initialize'); $(document).ready(Function.createDelegate(this, this._showQueue)); }, dispose: function () { if (this._cancelClickHandler) { $removeHandler(this._buttonCancel, 'click', this._cancelClickHandler); this._cancelClickHandler = null; } if (this._okClickHandler) { $removeHandler(this._buttonOk, 'click', this._okClickHandler); this._okClickHandler = null; } Page.Message.callBaseMethod(this, 'dispose'); }, get_resizable: function () { return false; }, createContent: function (parent) { // $(parent).append( // '<div>' + // '<div>' + // '<div></div>' + // '</div>' + // '<div class="MessageButton">' + // '<input type="submit" class="messageButton" value="OK">' + // '<input type="submit" class="messageButton" value="NO">' + // '</div>' + // '</div>') this._container = $common.createElementFromTemplate({ nodeName: 'Div' }, parent); this._contentDiv = $common.createElementFromTemplate({ nodeName: 'Div' }, this._container); this._textDiv = $common.createElementFromTemplate({ nodeName: 'Div' }, this._contentDiv); this._buttonContainer = $common.createElementFromTemplate({ nodeName: 'DIV', properties: { className: 'MessageButton' } }, this._container); this._buttonOk = $common.createElementFromTemplate({ nodeName: 'INPUT', properties: { type: 'submit', value: 'OK', className: 'messageButton' } }, this._buttonContainer); this._buttonCancel = $common.createElementFromTemplate({ nodeName: 'INPUT', properties: { type: 'submit', value: 'No', className: 'messageButton' } }, this._buttonContainer); this._cancelClickHandler = Function.createDelegate(this, this._onCancel); $addHandler(this._buttonCancel, 'click', this._cancelClickHandler); this._okClickHandler = Function.createDelegate(this, this._onOk); $addHandler(this._buttonOk, 'click', this._okClickHandler); return this._container; }, onShowing: function () { // show the message content var message = typeof (this._context.message) === 'undefined' || this._context.message === null ? '' : this._context.message; var array = message.split('\n'); var encodedMessage = new Sys.StringBuilder(); for (var i = 0, l = array.length; i < l; i++) { if (i > 0) encodedMessage.append('<br/>'); encodedMessage.append(array[i].replace(/\r/, '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')); } $(this._textDiv).html(encodedMessage.toString()); // 设置消息内容的样式,样式名称与类型名称完全相同,可以在以后的改进过程中增加其他的样式从而支持新的消息类型 this._contentDiv.className = this._context.type; if (Sys.Browser.agent == Sys.Browser.Firefox) { // 在firefox中使用minHeight和minWidth使DIV的高度和宽度随着内容的多少而变化,直接使用width和height的话则不会自动调整。 $common.setStyle(this._contentDiv, { minWidth: '250px', minHeight: '60px' }); } else { $common.setStyle(this._contentDiv, { width: '250px', height: '60px' }); } // 只有在“确认”窗口中才需要显示取消按钮,其他情况只需要一个确定按钮即可 setTimeout(Function.createDelegate(this, function () { $common.setVisible(this._buttonCancel, this._context.type == 'Confirm'); }), 0); }, onShown: function () { // 当消息内容的行数过多时,消息的显示高度或宽度将会超过预设的大小 // 因此需要在设置了消息内容和默认的消息显示大小之后,重新调整显示高度和宽度 $common.setSize(this._contentDiv, { width: Math.max(this._contentDiv.scrollWidth, this._contentDiv.offsetWidth), height: Math.max(this._contentDiv.offsetHeight, this._contentDiv.scrollHeight) }); this._layout(); var clientBounds = $common.getClientBounds(); // 显示消息之后需要重新调整消息容器的大小,以便在显示完成之后调整窗口大小时的提供依据。 var maxWidth = Math.max(Math.floor(clientBounds.width / 2), 500); var maxHeight = Math.max(Math.floor(clientBounds.height / 2), 400); // 消息窗口的高度和宽度都不能超过窗口可显示内容大小的一半。 if (this._textDiv.offsetWidth > maxWidth || this._textDiv.offsetHeight > maxHeight) { var size = { width: Math.min(maxWidth, this._textDiv.offsetWidth), height: Math.min(maxHeight, this._textDiv.offsetHeight) } $common.setSize(this._textDiv, size); this._textDiv.style.overflow = 'auto'; $common.setContentSize(this._contentDiv, size); } $common.setSize(this._container, { width: this._contentDiv.offsetWidth, height: this._contentDiv.offsetHeight + this._buttonContainer.offsetHeight }); // 在消息窗口显示的时候直接使确定按钮获得焦点,以方便使用Enter键直接关闭消息 this._buttonOk.focus(); }, onHidden: function () { if (this._context.callback) { if (this._context.type == 'Confirm') { this._context.callback(this._context.result); } else { this._context.callback(); } } if (document.documentElement.style.removeAttribute) { this._container.style.removeAttribute("width"); this._container.style.removeAttribute("height"); this._contentDiv.style.removeAttribute("width"); this._contentDiv.style.removeAttribute("height"); this._textDiv.style.removeAttribute("width"); this._textDiv.style.removeAttribute("height"); this._textDiv.style.removeAttribute("overflow"); } else { this._container.style.removeProperty("width"); this._container.style.removeProperty("height"); this._contentDiv.style.removeProperty("width"); this._contentDiv.style.removeProperty("height"); this._textDiv.style.removeProperty("width"); this._textDiv.style.removeProperty("height"); this._textDiv.style.removeProperty("overflow"); } this._context = null; this._position = null; this._showQueue(); }, show: function (type, message, callback, config) { var context = { type: type, message: message, config: config, callback: callback, result: false }; if (this.get_isShown() || !jQuery.isReady) { Array.add(this._queue, context); return; } this._context = context; Page.Message.callBaseMethod(this, 'show', [config.title]); }, _showQueue: function () { var next = Array.dequeue(this._queue); if (next) { this.show(next.type, next.message, next.callback, next.config); } }, _onCancel: function (evt) { evt.preventDefault(); this._context.result = false; this.hide(); }, _onOk: function (evt) { evt.preventDefault(); this._context.result = this._context.type == 'Confirm'; this.hide(); } } Page.Message.registerClass('Page.Message', Page.Dialog); Type.registerNamespace('Page'); Page.ModalDialog = function () { Page.ModalDialog.initializeBase(this); this._contentFrame = null; this._context = null; this._closed = false; this._loaded = false; this._frameLoadedHandler = null; this._frameSize = null; } Page.ModalDialog.prototype = { initialize: function () { Page.ModalDialog.callBaseMethod(this, 'initialize'); this._frameLoadedHandler = Function.createDelegate(this, this._onFrameLoaded); }, dispose: function () { this._frameLoadedHandler = null; Page.ModalDialog.callBaseMethod(this, 'dispose'); }, get_resizable: function () { return true; }, createContent: function (parent) { return this._contentFrame = $common.createElementFromTemplate({ nodeName: 'IFRAME', properties: { frameBorder: '0px', marginHeight: '0px', marginWidth: '0px', src: 'about:blank', style: { borderWidth: '0px' } } }, parent); }, show: function (url, bounds, callback, dialogArguments) { this._context = { url: url, callback: callback, bounds: bounds, dialogArguments: dialogArguments }; Page.ModalDialog.callBaseMethod(this, 'show', [null, bounds ? { x: bounds.x || bounds.left, y: bounds.y || bounds.top} : null]); }, onShowing: function () { if (this._context.bounds) { $common.setSize(this._contentFrame, { width: this._context.bounds.width, height: this._context.bounds.height }); } }, onShown: function () { this._contentFrame.src = this._context.url; $addHandler(this._contentFrame, 'load', this._frameLoadedHandler); }, onHiding: function () { if (!this._loaded) { $removeHandler(this._contentFrame, 'load', this._frameLoadedHandler); } }, onHidden: function () { var result = this._contentFrame.contentWindow.returnValue; this._contentFrame.contentWindow.returnValue = null; this._contentFrame.src = 'about:blank'; if (this._context.callback) { this._context.callback(result); } this._context = null; this._closed = true; }, resize: function (size) { if (this._context) { if (!this._context.bounds) this._context.bounds = {}; this._context.bounds.width = size.width; this._context.bounds.height = size.height; $common.setSize(this._contentFrame, { width: size.width, height: size.height }); this.onresize(); } }, _setOverflow: function (overflow) { if (typeof (overflow) != 'undefined') { if (typeof (overflow) == 'string') { if (overflow == 'yes' || overflow == 'scroll') { overflow = 'scroll'; } else if (overflow == 'no' || overflow == 'hidden') { overflow = 'hidden'; } else { overflow = 'auto'; } } else if (typeof (overflow) == 'boolean') { overflow = overflow ? 'scroll' : 'hidden'; } else { overflow = 'auto'; } } else { overflow = 'auto'; } if (Sys.Browser.agent == Sys.Browser.InternetExplorer) { this._contentFrame.scrolling = 'no'; var documentElement = this._contentFrame.contentWindow.document; var htmlElement = documentElement.getElementsByTagName('html')[0]; this._contentFrame.scrolling = 'no'; htmlElement.style.overflow = overflow; documentElement.body.style.overflow = overflow; } else if (Sys.Browser.agent == Sys.Browser.Safari || Sys.Browser.agent == Sys.Browser.Chrome) { if (overflow == 'scroll') { this._contentFrame.setAttribute('scrolling', 'yes'); } else if (overflow == 'hidden') { this._contentFrame.setAttribute('scrolling', 'no'); } else { this._contentFrame.setAttribute('scrolling', 'auto'); } } else { if (overflow == 'scroll') { this._contentFrame.scrolling = 'yes'; } else if (overflow == 'hidden') { this._contentFrame.scrolling = 'no'; } else { this._contentFrame.scrolling = 'auto'; } } }, _onFrameLoaded: function () { if (this._closed) return; this.setTitle(this._contentFrame.contentWindow.document.title||''); $removeHandler(this._contentFrame, 'load', this._frameLoadedHandler); this._setOverflow(this._context.bounds ? this._context.bounds.scrollBar : null); this._contentFrame.contentWindow.dialogArguments = this._context.dialogArguments; this._contentFrame.focus(); this._contentFrame.contentWindow.$get('__WINDOWID').value = this.get_id(); this._contentFrame.contentWindow.__windowId = this.get_id(); this._loaded = true; if (typeof (this._contentFrame.contentWindow.pageInit) === 'function') { this._contentFrame.contentWindow.pageInit(); } } } Page.ModalDialog.registerClass('Page.ModalDialog', Page.Dialog); Type.registerNamespace('Page'); Page.Prompt = function () { Page.Prompt.initializeBase(this); this._container = null; this._buttonContainer = null; this._contentDiv = null; this._buttonOk = null; this._buttonCancel = null; this._captionLabel = null; this._inputText = null; this._context = null; this._cancelClickHandler = null; this._textChangedHandler = null; this._selectStartHandler = null; this._keypressHandler = null; this._okClickHandler = null; } Page.Prompt.prototype = { initialize: function () { if (window.top == window) { Page.Prompt.callBaseMethod(this, 'initialize'); } }, dispose: function () { if (window.top == window) { if (this._cancelClickHandler) { $removeHandler(this._buttonCancel, 'click', this._cancelClickHandler); this._cancelClickHandler = null; } if (this._okClickHandler) { $removeHandler(this._buttonOk, 'click', this._okClickHandler); this._okClickHandler = null; } if (this._textChangedHandler) { $removeHandler(this._inputText, 'keyup', this._textChangedHandler); this._textChangedHandler = null; } if (this._keypressHandler) { $removeHandler(this._inputText, 'keypress', this._keypressHandler); this._keypressHandler = null; } if (this._selectStartHandler) { $removeHandler(this._inputText, 'selectstart', this._selectStartHandler); this._selectStartHandler = null; } Page.Prompt.callBaseMethod(this, 'dispose'); } }, get_resizable: function () { return false; }, onResize: function () { }, createContent: function (parent) { this._container = $common.createElementFromTemplate({ nodeName: 'Div' }, parent); this._contentDiv = $common.createElementFromTemplate({ nodeName: 'Div', properties: { className: 'PromptContent' } }, this._container); this._captionLabel = $common.createElementFromTemplate({ nodeName: 'SPAN' }, $common.createElementFromTemplate({ nodeName: 'Div' }, this._contentDiv)); this._inputText = $common.createElementFromTemplate({ nodeName: 'INPUT', properties: { type: 'text' } }, this._contentDiv); this._buttonContainer = $common.createElementFromTemplate({ nodeName: 'DIV', properties: { className: 'MessageButton' } }, this._container); this._buttonOk = $common.createElementFromTemplate({ nodeName: 'INPUT', properties: { type: 'submit', value: 'OK', className: 'messageButton' } }, this._buttonContainer); this._buttonCancel = $common.createElementFromTemplate({ nodeName: 'INPUT', properties: { type: 'submit', value: 'Cancel', className: 'messageButton' } }, this._buttonContainer); return this._container; }, show: function (caption, value, callback) { this._context = { callback: callback, caption: caption, value: value }; Page.Prompt.callBaseMethod(this, 'show'); }, onShowing: function () { $(this._captionLabel).text(typeof (this._context.caption) === 'undefined' || this._context.caption === null ? '' : this._context.caption); $(this._inputText).val(this._context.value); $common.setStyle(this._contentDiv, { width: '340px', height: '50px' }); if (!this._cancelClickHandler) { this._cancelClickHandler = Function.createDelegate(this, this._onCancel); $addHandler(this._buttonCancel, 'click', this._cancelClickHandler); } if (!this._okClickHandler) { this._okClickHandler = Function.createDelegate(this, this._onOk); $addHandler(this._buttonOk, 'click', this._okClickHandler); } if (!this._textChangedHandler) { this._textChangedHandler = Function.createDelegate(this, this._onTextChange); $addHandler(this._inputText, 'keyup', this._textChangedHandler); } if (!this._keypressHandler) { this._keypressHandler = Function.createDelegate(this, this._onKeyPress); $addHandler(this._inputText, 'keypress', this._keypressHandler); } if (!this._selectStartHandler) { this._selectStartHandler = Function.createDelegate(this, this._onSelectStart); $addHandler(this._inputText, 'selectstart', this._selectStartHandler); } }, onShown: function () { $common.setSize(this._contentDiv, { width: Math.max(this._contentDiv.scrollWidth, this._contentDiv.offsetWidth), height: Math.max(this._contentDiv.offsetHeight, this._contentDiv.scrollHeight) }); this._layout(); $common.setSize(this._container, { width: this._contentDiv.offsetWidth, height: this._contentDiv.offsetHeight + this._buttonContainer.offsetHeight }); this._invalidate(); this._inputText.focus(); $common.setSelectionRange(this._inputText, 0, this._inputText.value.length); }, onHidden: function () { this._context = null; this.dispose(); }, _onCancel: function (evt) { evt.preventDefault(); this.hide(); }, _onOk: function (evt) { evt.preventDefault(); if (!this._context.callback || (this._context.callback && this._context.callback($(this._inputText).val()))) { this.hide(); } }, _onTextChange: function (evt) { this._invalidate(); }, _onKeyPress: function (evt) { if (evt.charCode == 13) { this._buttonOk.click(); } }, _onSelectStart: function (evt) { evt.stopPropagation(); return true; }, _invalidate: function () { $common.applyProperties(this._buttonOk, { disabled: ($(this._inputText).val() ? '' : 'disabled') }); } } Page.Prompt.registerClass('Page.Prompt', Page.Dialog); /// <reference path="jquery.debug.js" /> /// <reference path="Dialog.js" /> /// <reference path="ModalDialog.js" /> /// <reference path="Message.js" /> /// <reference path="Prompt.js" /> $open = function (url, bounds) { /// <summary> /// 打开新的窗口。新窗口隐藏工具栏、菜单栏和状态栏,并且可以通过鼠标拖动改变窗口的大小和位置。 /// </summary> /// <param name="url" type="String">新窗口的地址。</param> /// <param name="bounds" type="Sys.UI.Bounds"> /// 新窗口的大小和位置。如果用户设置新打开的窗口使用 Tab 的形式则参数值无效。 /// </param> /// <example> /// 打开一个位于屏幕中间位置的新窗口,并且指定窗口的大小 /// <code> /// window.$open('http://www.mysite.com/mypage.aspx',{width:600,height:600}); /// </code> /// 打开一个满屏的浏览器窗口 /// <code> /// window.$open('http://www.mysite.com/mypage.aspx'); /// </code> /// </example> /// <returns>新打开的窗口的句柄</returns> var availWidth = screen.availWidth; if (Sys.Browser.agent == Sys.Browser.InternetExplorer) { availWidth -= 12; } else { availWidth -= 7; } var availHeight = screen.availHeight - 38; var left = 0, top = 0, width = availWidth, height = availHeight; if (typeof (bounds) !== 'undefined' && bounds !== null) { width = (bounds.width || bounds.width === 0) ? bounds.width : availWidth; height = (bounds.height || bounds.height === 0) ? bounds.height : availHeight; left = (bounds.x || bounds.x === 0) ? bounds.x : bounds.left; left = ((!left && left !== 0) || left === 'center') ? ((availWidth - bounds.width) / 2) : left; top = (bounds.y || bounds.y === 0) ? bounds.y : bounds.top; top = ((!top && top !== 0) || top === 'middle') ? ((availHeight - bounds.height) / 2) : top; } var features = ''; if (Sys.Browser.agent == Sys.Browser.Firefox) { // in fire fox 3 the location defaults disabled, forcing the presence of the Location Bar much like in IE7. features = "centerscreen=yes,chrome=yes,location=no,menubar=no,toolbar=no,dependent=no,status=no,directories=no,alwaysRaised=no,resizable=yes,minimizable=yes,scrollbars=yes" + ",innerWidth=" + width + ",innerHeight=" + height + ",top=" + top + ",left=" + left; } else { // in IE7 the location is forced to present, and enabled in IE6. features = "menubar=no,toolbar=no,status=no,titlebar=no,location=no,resizable=yes,scrollbars=yes" + ",width=" + width + ",height=" + height + ",top=" + top + ",left=" + left; } var windowObj = window.open(url, '_blank', features, false); // when the browser blocked the new page, return value of open method will be null. // especially in IE8 for default blocks every new window. if (windowObj) { windowObj.moveTo(left, top); } return windowObj; }; $prompt = function (caption, value, callback, context) { if (window.top == window) { var promptObj = new Page.Prompt(); promptObj.initialize(); window.__promptWindowId = promptObj.get_id(); promptObj.show(caption, value, function (result) { var ret = true; if (callback) { ret = callback(result, context); } window.setTimeout(function () { if (ret && !promptObj.get_isShown()) { promptObj.dispose(); } }); return ret; }); } else { window.top.$prompt(caption, value, callback, context); } }; $closePrompt = function () { if (window.top == window) { if (window.__promptWindowId) { Page.Dialog.close(window.__windowId); } } else { window.top.$closePrompt(); } }; $alert = function (message, callback, config, context) { /// <summary> /// Shows the information message window. /// </summary> /// <param name="message" type="String" mayBeNull="false"> /// The message text content. /// </param> /// <param name="callback" type="Function" optional="true" mayBeNull="true"> /// The call back handler after the message window close. /// </param> /// <param name="config" type="Object" optional="true" mayBeNull="true"> /// The configuration parameters to represent message window. There are two parameters can be applied for this function: /// <table> /// <th> /// <td>Name</td> /// <td>Type</td> /// <td>Default Value</td> /// </th> /// <tr> /// <td>title</td> /// <td>String</td> /// <td>Information</td> /// </tr> /// <tr> /// <td>buttonText</td> /// <td>String</td> /// <td>OK</td> /// </tr> /// </table> /// </param> /// <param name="context" optional="true" mayBeNull="true"> /// The context object can be used in the call back handler. /// </param> if (window.top == window) { if (typeof (window._messageObj) == 'undefined' || !window._messageObj) { window._messageObj = new Page.Message(); window._messageObj.initialize(); } config = $.extend({ title: 'Information', buttonText: 'OK' }, config); window._messageObj.show('Information', message, callback ? function () { callback(context); } : null, { title: config.title, okButtonText: config.buttonText, cancelButtonText: 'Cancel' }); } else { window.top.$alert(message, callback, config, context); } }; $error = function (message, callback, config, context) { /// <summary> /// Shows the error message windows. /// </summary> /// <param name="message" type="String" mayBeNull="false"> /// The message text content. /// </param> /// <param name="callback" type="Function" optional="true" mayBeNull="true"> /// The call back handler after the message window close. /// </param> /// <param name="config" type="Object" optional="true" mayBeNull="true"> /// The configuration parameters to represent message window. There are two parameters can be applied for this function: /// <table> /// <th> /// <td>Name</td> /// <td>Type</td> /// <td>Default Value</td> /// </th> /// <tr> /// <td>title</td> /// <td>String</td> /// <td>Error</td> /// </tr> /// <tr> /// <td>buttonText</td> /// <td>String</td> /// <td>OK</td> /// </tr> /// </table> /// </param> /// <param name="context" optional="true" mayBeNull="true"> /// The context object can be used in the call back handler. /// </param> if (window.top == window) { if (typeof (window._messageObj) == 'undefined' || !window._messageObj) { window._messageObj = new Page.Message(); window._messageObj.initialize(); } config = $.extend({ title: 'Error', buttonText: 'OK' }, config); window._messageObj.show('Error', message, callback ? function () { callback(context); } : null, { title: config.title, okButtonText: config.buttonText, cancelButtonText: 'Cancel' }); } else { window.top.$error(message, callback, config, context); } }; $confirm = function (message, callback, config, context) { /// <summary> /// Shows the confirmation message window. /// </summary> /// <param name="message" type="String" mayBeNull="false"> /// The message text content. /// </param> /// <param name="callback" type="Function" optional="true" mayBeNull="true"> /// The call back handler after the message window close. /// </param> /// <param name="config" type="Object" optional="true" mayBeNull="true"> /// The configuration parameters to represent message window. There are three parameters can be applied for this function: /// <table> /// <th> /// <td>Name</td> /// <td>Type</td> /// <td>Default Value</td> /// </th> /// <tr> /// <td>title</td> /// <td>String</td> /// <td>Error</td> /// </tr> /// <tr> /// <td>okButtonText</td> /// <td>String</td> /// <td>OK</td> /// </tr> /// <tr> /// <td>cancelButtonText</td> /// <td>String</td> /// <td>Cancel</td> /// </tr> /// </table> /// </param> /// <param name="context" optional="true" mayBeNull="true"> /// The context object can be used in the call back handler. /// </param> if (window.top == window) { if (typeof (window._messageObj) == 'undefined' || !window._messageObj) { window._messageObj = new Page.Message(); window._messageObj.initialize(); } window._messageObj.show('Confirm', message, callback ? function (result) { callback(result, context); } : null, $.extend({ title: 'Confirm', okButtonText: 'OK', cancelButtonText: 'Cancel' }, config)); } else { window.top.$confirm(message, callback, config, context); } }; $success = function (message, callback, config, context) { /// <summary> /// Shows the success message window. /// </summary> /// <param name="message" type="String" mayBeNull="false"> /// The message text content. /// </param> /// <param name="callback" type="Function" optional="true" mayBeNull="true"> /// The call back handler after the message window close. /// </param> /// <param name="config" type="Object" optional="true" mayBeNull="true"> /// The configuration parameters to represent message window. There are two parameters can be applied for this function: /// <table> /// <th> /// <td>Name</td> /// <td>Type</td> /// <td>Default Value</td> /// </th> /// <tr> /// <td>title</td> /// <td>String</td> /// <td>Success</td> /// </tr> /// <tr> /// <td>buttonText</td> /// <td>String</td> /// <td>OK</td> /// </tr> /// </table> /// </param> /// <param name="context" optional="true" mayBeNull="true"> /// The context object can be used in the call back handler. /// </param> if (window.top == window) { if (typeof (window._messageObj) == 'undefined' || !window._messageObj) { window._messageObj = new Page.Message(); window._messageObj.initialize(); } config = $.extend({ title: 'Success', buttonText: 'OK' }, config); window._messageObj.show('Success', message, callback ? function () { callback(context); } : null, { title: config.title, okButtonText: config.buttonText, cancelButtonText: 'Cancel' }); } else { window.top.$success(message, callback, config, context); } }; $dialog = function (url, bounds, callback, dialogArguments, context) { /// <summary> /// Shows modal dialog for particular location. /// </summary> /// <param name="url" type="String" mayBeNull="false"> /// The location of the modal dialog. /// </param> /// <param name="bounds" type="Sys.UI.Bounds" optional="true" mayBeNull="true"> /// The bounds of the modal dialog. /// </param> /// <param name="callback" type="Function" optional="true" mayBeNull="true"> /// The call back handler after the modal dialog closed. /// </param> /// <param name="dialogArguments" optional="true" mayBeNull="true"> /// The arguments sent to the modal dialog. It can be accessed with window.dialogArguments inside the modal dialog. /// </param> /// <param name="context" optional="true" mayBeNull="true"> /// The context object can be used in the call back handler. /// </param> /// <example> /// Show the dialog without call back handler /// <code> /// $dialog('dialog.htm', { width : 500, height : 400 }); /// </code> /// Show the dialog with inline call back handler /// <code> /// $dialog('dialog.htm', { width : 500, height : 400 }, function(result) { /// $alert(result); /// }) /// </code> /// Show the dialog with call back handler and dialog arguments /// <code> /// $dialog('dialog.aspx', { width : 500, height : 400 }, function(result) { /// $alert(result); /// }, 'hello dialog'); /// </code> /// And access dialog arguments inside the dialog.aspx /// <code> /// function pageLoad() { /// $alert(window.dialogArguments); // popup 'hello dialog' /// } /// </code> /// </example> if (window.top == window) { var dialogObj = new Page.ModalDialog(); dialogObj.initialize(); dialogObj.show(url, bounds, function (result) { // Delay the dialog dispose to avoid unexpected exceptions if any script is executing and referencing the unloaded DOM elements. window.setTimeout(function () { dialogObj.dispose(); }); if (callback) callback(result, context); }, dialogArguments); } else { window.top.$dialog(url, bounds, callback, dialogArguments, context); } }; $close = function () { /// <summary> /// Close the current window. /// </summary> if (window.__windowId) { window.top.Page.Dialog.close(window.__windowId); } else if (window.top == window) { window.close(); } }; $resize = function(size) { /// <summary>Resize the current window.</summary> if (window.__windowId) { window.top.Page.Dialog.resize(window.__windowId, size); } }; $(function () { if (typeof (Sys.WebForms) !== "undefined" && typeof (Sys.WebForms.PageRequestManager) !== "undefined") { var requestManager = Sys.WebForms.PageRequestManager.getInstance(); if (requestManager != null) { requestManager.add_endRequest(function (sender, args) { var error = args.get_error(); if (error && $alert) { $alert(error.message); args.set_errorHandled(true); } }); } } if (window.ValidationSummaryOnSubmit) { window.ValidationSummaryOnSubmit = function (validationGroup) { if (typeof (Page_ValidationSummaries) == "undefined") return; var summary, sums, s; for (sums = 0; sums < Page_ValidationSummaries.length; sums++) { summary = Page_ValidationSummaries[sums]; summary.style.display = "none"; if (!Page_IsValid && IsValidationGroupMatch(summary, validationGroup)) { var i; if (summary.showsummary != "False") { summary.style.display = ""; if (typeof (summary.displaymode) != "string") { summary.displaymode = "BulletList"; } switch (summary.displaymode) { case "List": headerSep = "<br>"; first = ""; pre = ""; post = "<br>"; end = ""; break; case "BulletList": default: headerSep = ""; first = "<ul>"; pre = "<li>"; post = "</li>"; end = "</ul>"; break; case "SingleParagraph": headerSep = " "; first = ""; pre = ""; post = " "; end = "<br>"; break; } s = ""; if (typeof (summary.headertext) == "string") { s += summary.headertext + headerSep; } s += first; for (i = 0; i < Page_Validators.length; i++) { if (!Page_Validators[i].isvalid && typeof (Page_Validators[i].errormessage) == "string") { s += pre + Page_Validators[i].errormessage + post; } } s += end; summary.innerHTML = s; window.scrollTo(0, 0); } if (summary.showmessagebox == "True") { s = ""; if (typeof (summary.headertext) == "string") { s += summary.headertext + "\r\n"; } var lastValIndex = Page_Validators.length - 1; for (i = 0; i <= lastValIndex; i++) { if (!Page_Validators[i].isvalid && typeof (Page_Validators[i].errormessage) == "string") { switch (summary.displaymode) { case "List": s += Page_Validators[i].errormessage; if (i < lastValIndex) { s += "\r\n"; } break; case "SingleParagraph": s += Page_Validators[i].errormessage + " "; break; case "BulletList": default: s += "- " + Page_Validators[i].errormessage; if (i < lastValIndex) { s += "\r\n"; } break; } } } $alert(s, function () { for (i = 0; i <= lastValIndex; i++) { var val = Page_Validators[i]; if (!val.isvalid && Page_InvalidControlToBeFocused == null && typeof (val.focusOnError) == "string" && val.focusOnError == "t") { ValidatorSetFocus(val, null); } } }); } } } }; } }) /** * http://www.openjs.com/scripts/events/keyboard_shortcuts/ * Version : 2.01.B * By Binny V A * License : BSD */ shortcut = { 'all_shortcuts': {}, //All the shortcuts are stored in this array 'add': function (shortcut_combination, callback, opt) { //Provide a set of default options var default_options = { 'type': 'keydown', 'propagate': false, 'disable_in_input': false, 'target': document, 'keycode': false } if (!opt) opt = default_options; else { for (var dfo in default_options) { if (typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo]; } } var ele = opt.target; if (typeof opt.target == 'string') ele = document.getElementById(opt.target); var ths = this; shortcut_combination = shortcut_combination.toLowerCase(); //The function to be called at keypress var func = function (e) { e = e || window.event; if (opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields var element; if (e.target) element = e.target; else if (e.srcElement) element = e.srcElement; if (element.nodeType == 3) element = element.parentNode; if (element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return; } //Find Which key is pressed if (e.keyCode) code = e.keyCode; else if (e.which) code = e.which; var character = String.fromCharCode(code).toLowerCase(); if (code == 188) character = ","; //If the user presses , when the type is onkeydown if (code == 190) character = "."; //If the user presses , when the type is onkeydown var keys = shortcut_combination.split("+"); //Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked var kp = 0; //Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken var shift_nums = { "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ":", "'": "\"", ",": "<", ".": ">", "/": "?", "\\": "|" } //Special Keys - and their codes var special_keys = { 'esc': 27, 'escape': 27, 'tab': 9, 'space': 32, 'return': 13, 'enter': 13, 'backspace': 8, 'scrolllock': 145, 'scroll_lock': 145, 'scroll': 145, 'capslock': 20, 'caps_lock': 20, 'caps': 20, 'numlock': 144, 'num_lock': 144, 'num': 144, 'pause': 19, 'break': 19, 'insert': 45, 'home': 36, 'delete': 46, 'end': 35, 'pageup': 33, 'page_up': 33, 'pu': 33, 'pagedown': 34, 'page_down': 34, 'pd': 34, 'left': 37, 'up': 38, 'right': 39, 'down': 40, 'f1': 112, 'f2': 113, 'f3': 114, 'f4': 115, 'f5': 116, 'f6': 117, 'f7': 118, 'f8': 119, 'f9': 120, 'f10': 121, 'f11': 122, 'f12': 123 } var modifiers = { shift: { wanted: false, pressed: false }, ctrl: { wanted: false, pressed: false }, alt: { wanted: false, pressed: false }, meta: { wanted: false, pressed: false} //Meta is Mac specific }; if (e.ctrlKey) modifiers.ctrl.pressed = true; if (e.shiftKey) modifiers.shift.pressed = true; if (e.altKey) modifiers.alt.pressed = true; if (e.metaKey) modifiers.meta.pressed = true; for (var i = 0; k = keys[i], i < keys.length; i++) { //Modifiers if (k == 'ctrl' || k == 'control') { kp++; modifiers.ctrl.wanted = true; } else if (k == 'shift') { kp++; modifiers.shift.wanted = true; } else if (k == 'alt') { kp++; modifiers.alt.wanted = true; } else if (k == 'meta') { kp++; modifiers.meta.wanted = true; } else if (k.length > 1) { //If it is a special key if (special_keys[k] == code) kp++; } else if (opt['keycode']) { if (opt['keycode'] == code) kp++; } else { //The special keys did not match if (character == k) kp++; else { if (shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase character = shift_nums[character]; if (character == k) kp++; } } } } if (kp == keys.length && modifiers.ctrl.pressed == modifiers.ctrl.wanted && modifiers.shift.pressed == modifiers.shift.wanted && modifiers.alt.pressed == modifiers.alt.wanted && modifiers.meta.pressed == modifiers.meta.wanted) { callback(e); if (!opt['propagate']) { //Stop the event //e.cancelBubble is supported by IE - this will kill the bubbling process. e.cancelBubble = true; e.returnValue = false; //e.stopPropagation works in Firefox. if (e.stopPropagation) { e.stopPropagation(); e.preventDefault(); } return false; } } } this.all_shortcuts[shortcut_combination] = { 'callback': func, 'target': ele, 'event': opt['type'] }; //Attach the function with the event if (ele.addEventListener) ele.addEventListener(opt['type'], func, false); else if (ele.attachEvent) ele.attachEvent('on' + opt['type'], func); else ele['on' + opt['type']] = func; }, //Remove the shortcut - just specify the shortcut and I will remove the binding 'remove': function (shortcut_combination) { shortcut_combination = shortcut_combination.toLowerCase(); var binding = this.all_shortcuts[shortcut_combination]; delete (this.all_shortcuts[shortcut_combination]) if (!binding) return; var type = binding['event']; var ele = binding['target']; var callback = binding['callback']; if (ele.detachEvent) ele.detachEvent('on' + type, callback); else if (ele.removeEventListener) ele.removeEventListener(type, callback, false); else ele['on' + type] = false; } }
(function () { 'use strict'; angular .module('app') .factory('AuthenticationService', AuthenticationService); AuthenticationService.$inject = ['$http', '$cookies', '$rootScope', '$timeout', 'UserService']; function AuthenticationService($http, $cookies, $rootScope, $timeout, UserService) { /////////////////////////////////////////////////////////// // SERVICE API /////////////////////////////////////////////////////////// var service = {}; service.Login = Login; service.SetCredentials = SetCredentials; service.ClearCredentials = ClearCredentials; return service; /////////////////////////////////////////////////////////// // SERVICE IMPLEMENTATION /////////////////////////////////////////////////////////// // Login the user function Login(username, password, callback) { $http.post('/api/v1/authenticate', { username: username, password: password }) .then(function successCallback(response) { callback(response); }, function errorCallback(response) { callback(response); }).catch(function (err) { alert(err); }); } // Set the credentials after successful login function SetCredentials(username, password, token) { $rootScope.globals = { currentUser: { username: username, authdata: token } }; // set default auth header for http requests $http.defaults.headers.common['x-access-token'] = token; // store user details in globals cookie that keeps user logged in for 1 week (or until they logout) var cookieExp = new Date(); cookieExp.setDate(cookieExp.getDate() + 7); $cookies.putObject('globals', $rootScope.globals, { expires: cookieExp }); } // Clear credentials function ClearCredentials() { $rootScope.globals = {}; $cookies.remove('globals'); $http.defaults.headers.common['x-access-token'] = ''; } } })();
import { combineReducers } from "redux"; import team from "./teamReducer"; import championsBrief from "./championsBriefReducer"; const rootReducer = combineReducers({ team: team, championsBrief: championsBrief, }); export default rootReducer;
import React, { Component } from 'react' import { View, Text } from 'react-native'; import { Grid, LineChart, XAxis, YAxis } from 'react-native-svg-charts' import * as scale from 'd3-scale' import styles from './Style_Statistics' import colors from '../../../constants/Colors'; class LineDistribution extends Component { constructor(props) { super(props); this.state = { data: [], axesSvg: { fontSize: 10, fill: 'grey' }, verticalContentInset: { top: 10, bottom: 10 }, xAxisHeight: 30 }; this.MakeGraph = this.MakeGraph.bind(this); } componentDidMount() { this.MakeGraph(); } MakeGraph() { let temp = this.state.data; for (var i = 0; i < this.props.data.category.length; i++) { temp.push({key: this.props.data.category[i], value: this.props.data.amount[i],},) } this.setState({data: temp}) } render() { return( <View style={styles.chart}> <View> <Text style={styles.headline}>{this.props.headline}</Text> <Text style={styles.subHeadline}>{this.props.subHeadline}</Text> </View> <View style={{ height: 400, padding: 20, flexDirection: 'row' }}> <YAxis data={this.props.data.amount} style={{ marginBottom: this.state.xAxisHeight }} contentInset={this.state.verticalContentInset} svg={this.state.axesSvg} /> <View style={{ flex: 1, marginLeft: 10 }}> <LineChart style={{ flex: 1 }} data={this.props.data.amount} contentInset={this.state.verticalContentInset} svg={{ stroke: colors.redColors[0] }} > <Grid/> </LineChart> <XAxis style={{ marginHorizontal: -10, height: this.state.xAxisHeight }} data={this.state.data} xAccessor={({ item }) => item.key} scale={scale.scaleBand} contentInset={{ left: 10, right: 10 }} svg={this.state.axesSvg} /> </View> </View> </View> ) } } export default LineDistribution;
var foo var bar var baz = function(data) { return data + 1 } bar = 1 foo = bar + baz (bar + bar) + baz(bar) console.log(foo) var foo; var bar; var baz = function(data) { return data + 1; }; bar = 1; foo = bar + baz(bar + bar) + baz(bar);
/* * * Cats actions * */ import { generateActionWithBody, generateEmptyAction, generateActionWithId, } from 'utils/generic-saga'; import { fetchCatsActionTypes, addCatActionTypes, deleteCatActionTypes, } from './constants'; const fetchCats = generateEmptyAction(fetchCatsActionTypes.request); const addCat = generateActionWithBody(addCatActionTypes.request); const deleteCat = generateActionWithId(deleteCatActionTypes.request); export { fetchCats, addCat, deleteCat };
const is = require('is-type-of'); let a = { }; const loadsh = require('lodash'); let itis = loadsh.isPlainObject(a); console.log(itis);
const uuid = require('uuid'); class AlexaResponse { constructor(opts) { this.context = {properties: []}; this.event = { header: { namespace: this.checkValue(opts.namespace, "Alexa"), name: this.checkValue(opts.name, "Response"), messageId: this.checkValue(opts.messageId, uuid()), correlationToken: this.checkValue(opts.correlationToken, undefined), payloadVersion: this.checkValue(opts.payloadVersion, "3") }, endpoint: { scope: { type: "BearerToken", token: this.checkValue(opts.token, "INVALID"), }, endpointId: this.checkValue(opts.endpointId, "INVALID") }, payload: this.checkValue(opts.payload, {}) }; if (opts.context) this.context = this.checkValue(opts.context, this.context); if (opts.event) this.event = this.checkValue(opts.event, this.event); // No endpoint in an AcceptGrant or Discover request const headerName = this.event.header.name.toLowerCase(); if (headerName === "acceptgrant.response" || headerName === "discover.response") delete this.event.endpoint; } addContextProperty(opts) { this.context.properties.push(this.createContextProperty(opts)); } addPayloadEndpoint(opts) { this.event.payload.endpoints = this.event.payload.endpoints || []; this.event.payload.endpoints.push(this.createPayloadEndpoint(opts)); } createContextProperty(opts) { return { namespace: this.checkValue(opts.namespace, "Alexa.EndpointHealth"), name: this.checkValue(opts.name, "connectivity"), value: this.checkValue(opts.value, {value: "OK"}), // UNREACHABLE timeOfSample: new Date().toISOString(), uncertaintyInMilliseconds: this.checkValue(opts.uncertaintyInMilliseconds, 0) }; } createPayloadEndpoint(opts) { if (opts === undefined) opts = {}; const endpoint = { capabilities: this.checkValue(opts.capabilities, []), description: this.checkValue(opts.description, "To open / close garage"), displayCategories: this.checkValue(opts.displayCategories, ["SMARTLOCK"]), endpointId: this.checkValue(opts.endpointId, 'endpoint-001'), // "endpointId": this.checkValue(opts.endpointId, 'endpoint_' + (Math.floor(Math.random() * 90000) + 10000)), friendlyName: this.checkValue(opts.friendlyName, "Garage"), manufacturerName: this.checkValue(opts.manufacturerName, "Smart Garage INC") }; if (opts.hasOwnProperty("cookie")) endpoint["cookie"] = this.checkValue('cookie', {}); return endpoint } /** * Creates a capability for an endpoint within the payload. * @param opts Contains options for the endpoint capability. */ createPayloadEndpointCapability(opts) { if (opts === undefined) opts = {}; let capability = {}; capability['type'] = this.checkValue(opts.type, "AlexaInterface"); capability['interface'] = this.checkValue(opts.interface, "Alexa"); capability['version'] = this.checkValue(opts.version, "3"); let supported = this.checkValue(opts.supported, false); if (supported) { capability['properties'] = {}; capability['properties']['supported'] = supported; capability['properties']['proactivelyReported'] = this.checkValue(opts.proactivelyReported, false); capability['properties']['retrievable'] = this.checkValue(opts.retrievable, false); } return capability } /** * Get the composed Alexa Response. * @returns {AlexaResponse} */ get() { return this; } checkValue(value, defaultValue) { if (value === undefined || value === {} || value === "") return defaultValue; return value; } } module.exports = AlexaResponse;
import {getPaddedBinary} from './util'; export function getPatternDecodeFromUrl(url) { const split = url.split('_'); const order = ['threading', 'tie_up', 'treadling']; let data = {}; let section; let numCols; let rowVals; let i; let row; let temp = []; let isValid = true; if (split.length >= 3) { order.forEach(function (type, index) { temp = []; section = split[index].split('-'); if (section.length === 3) { numCols = section[1].split(',')[0]; rowVals = section[2].split('.'); rowVals.forEach(function(val) { row = Array.from(getPaddedBinary(numCols, val).split(''), x => parseInt(x, 10)); temp.push(row.slice(numCols * -1)); }.bind(this)) data[type] = temp; } else { isValid = false; } }.bind(this)); if (!isValid) { return false; } data.patternNumber = split.length === 4 ? split[3].split('-') : false; if (data.patternNumber) { data.patternNumber.shift(); } return data; } return false; } export default getPatternDecodeFromUrl;
export const FETCH_BANNERS = "FETCH_BANNERS";
/* Treehouse FSJS Techdegree * Project 4 - OOP Game App * Phrase.js */ //const phrase; class Phrase { // THE CLASS THAT ALL OF THE FUNCTIONS IN THIS FILE IS UNDER. constructor(phrase) { this.phrase= phrase.toLowerCase(); //Makes all of the phrase letters entered to lowercase, so that there is no misunderstanding when it comes to case sensitivity. } addPhraseToDisplay() { //THE FUNCTION RESPONSIBLE FOR ACTUALLY PLACING A PHRASE TO DISPLAY, OR AT LEAST THE SHELL OF THE PHRASE, THAT THE PLAYER NEEDS TO GUESS. for(let i =0; i < this.phrase.length; i++){ if (this.phrase[i] !== ' ') { //If the phrase is not equal to a space, meaning that there are no spaces that separate letters within the phrase, then append the li with the coinciding letters $('ul').append(`<li class="hide letter ${this.phrase[i]}">${this.phrase[i]}</li>`); } else { $('ul').append(`<li class="hide space">&nbsp;</li>`); //If there are spaces then, just make room for the spaces that seaparates words within a phrase by appending this <li></li> } } } checkLetter(letter) { //FUNCTION RESPONSIBLE FOR CHECKING THE VALIDITY OF THE LETTERS BEING SELECTED. return this.phrase.includes(letter); // Returns the letter of the phrase, if the letter selected is apart of the phrase. } showMatchedLetter(letter) { // FUNCTION RESPONSIBLE FOR SHOWING THE MATCHED LETTER. $('#phrase ul .' + letter).addClass('show'); // Copies the HTML path to the letters, and matches those letters with the letter selected. if they match, show. If they don't hide. $('#phrase ul .' + letter).removeClass('hide'); } }
import { createAction } from "redux-actions"; export const loadStartedBids = createAction("[load] startedBids"); export const loadCompletedBids = createAction("[load] completedBids"); export const loadFinishedBids = createAction("[load] finishedBids"); export const loadOrdersBids = dispatch => { dispatch(loadStartedBids()); fetch("http://localhost:3000/Bids") .then(res => res.json()) .then(product => { dispatch(loadCompletedBids(product)); }) .catch(err => { dispatch(loadFinishedBids(err)); }); };