text
stringlengths 7
3.69M
|
|---|
const request = require('request');
const fetchBreedDescription = function(breedName, callback) {
const qid = breedName.slice(0,2);
const url = "https://api.thecatapi.com/v1/breeds/search?q=" + qid;
//const url = "https://api.thecat123";
request.get(url, (error, res) =>{
if (error !== null) {
callback(error, res);
} else {
const body = res["body"];
//console.log(body);
//console.log(typeof body);
const data = JSON.parse(body);
//console.log(data);
//console.log(typeof data);
const des = data[0]["description"];
callback(error, des);
}
});
};
module.exports = {
fetchBreedDescription
};
/**
const input = process.argv;
const qid = input[2].slice(0,2);
//console.log(qid);
const url = "https://api.thecatapi.com/v1/breeds/search?q=" + qid;
//const url = "https://api.thecat123";
request.get(url, (error, res) => {
if (error !== null) {
console.log(error);
} else if (error === null) {
const body = res["body"];
//console.log(body);
//console.log(typeof body);
if (body === "[]"){
console.log("The requested breed is not found");
} else {
const data = JSON.parse(body);
//console.log(data);
//console.log(typeof data);
console.log(data[0]["description"]);
}
}
});
*/
|
import React from 'react';
import PropTypes from 'prop-types';
import {FiClock} from "react-icons/fi";
const dateToString = date => {
const options = {
year: '2-digit',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
}
return date.toLocaleString('nu', options)
}
const CreationDate = ({date}) => {
return (
<div className='mt-auto user-select-none' style={style}>
<FiClock className='mr-1'/>
{dateToString(date)}
</div>
);
};
const style = {
fontSize: '.6rem'
}
CreationDate.propTypes = {
};
export default CreationDate;
|
import React, { useState } from "react";
import axios from "axios";
import { Controller, useForm } from "react-hook-form";
import { TextField, Container, Button } from "@material-ui/core";
export const AssignStudent = () => {
const { control, handleSubmit } = useForm();
const server = `https://making-apis.herokuapp.com/teacher`;
const localServer = `http://localhost:6969/teacher`;
const [sent, setSent] = useState(false);
const student = async (assignedTeacher, e) => {
console.log(assignedTeacher);
const datat = await axios.put(server, assignedTeacher);
console.log(datat);
if (datat) {
setSent(true);
}
};
return (
<div>
{sent == true && <h6>Student added</h6>}
<form onSubmit={handleSubmit(student)}>
<Container className="d-flex flex-column w-25">
<Controller
control={control}
name="teacherID"
render={({ field }) => <TextField label="Teacher ID" {...field} />}
/>
<Controller
control={control}
name="studentID"
render={({ field }) => (
<TextField placeholder="" label="Student ID" {...field} />
)}
/>
<input type="submit" className="btn btn-dark mt-4 rounded-0" />
</Container>
</form>
</div>
);
};
|
//all the dependencies we need
var http = require('http'); //this is a built in package that comes with node and there is no need to install it
var express = require('express');
var mongoose = require('mongoose');
var airportSchema = new mongoose.Schema({
"id":String,
"ident":String,
"type":String,
"name":String,
"latitude_deg":String,
"longitude_deg":String,
"elevation_ft":String,
"continent":String,
"iso_country":String,
"iso_region":String,
"municipality":String,
"scheduled_service":String,
"gps_code":String,
"iata_code":String,
"local_code":String,
"home_link":String,
"wikipedia_link":String,
"keywords":String
});
mongoose.model( 'Airport', airportSchema );
var Airport = mongoose.model('Airport');
//connect to our mongo database
var db = mongoose.connection;
mongoose.connect('mongodb://localhost:27017/airports');
//if we have any errors, show them in console
db.on('error', function (err) {
console.log('connected ' + err.stack);
});
//when we disconnect from mongo, show this in console
db.on('disconnected', function(){
console.log('disconnected');
});
//when we connect to mongo, show this in console
db.on('connected',function(){
console.log('connected');
});
//new app that will work on port 3000
var app = express();
app.set('port', 3000);
//Simple 404 response because we don't have any routing yet
app.use(function(req,res){
res.status(404);
res.type('text/plain');
res.send('404');
});
//start the application and let node listen for requests on port 3000
http.createServer(app).listen(app.get('port'), function(){
console.log( 'Server started on http://localhost:' + app.get('port') + '; press Ctrl-C to terminate.' );
});
//make sure that we are closing the connection to mongo if something happens to node (like Ctrl + C)
process.on('SIGINT', function() {
mongoose.connection.close(function () {
process.exit(0);
});
});
|
import _ from 'lodash';
const FILTERABLE_ALBUM_PROPS = ['albumName', 'casts', 'musicDirector'];
const albumsFilter = ({ searchString, albumsPayload }) => {
const searchRegex = new RegExp(searchString, 'i');
const filteredAlbums = _.filter(albumsPayload, (album) => (
_.reduce(FILTERABLE_ALBUM_PROPS, (albumMatched, filterableAlbumProp) => (
albumMatched = albumMatched || searchRegex.test(album[filterableAlbumProp])
), false)
));
return filteredAlbums;
};
export default albumsFilter;
|
// require mongoose
const mongoose = require('mongoose')
const movieSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
releaseDate: {
type: Number,
required: true
},
description: {
type: String,
required: false
}
}, {
timestamps: true,
toObject: {
// remove desired fields when we call `.toObject`
transform: (_doc, movie) => {
// delete collection._id
delete movie.createdAt
delete movie.updatedAt
delete movie.__v
return movie
}
}
})
module.exports = movieSchema
|
import React, { useState } from 'react';
import { StyleSheet, Text, View, Image, ScrollView } from 'react-native';
// import Separator from 'components/Separator';
// import Badge from 'components/Badge';
const ProfileDetails = () => {
const detailsArr = ['company', 'location', 'followers', 'following', 'email', 'bio'];
return (null)
};
const styles = StyleSheet.create({
container: {
flex: 1
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
rowContainer: {
padding: 10
},
rowTitle: {
color: '#48BBEC',
fontSize: 16
},
rowContent: {
fontSize: 19
}
});
export default ProfileDetails;
|
(function () {
'use strict'
angular.module('app')
.service("MenuService", MenuService);
MenuService.$inject = [];
function MenuService() {
var vm = this;
vm.selectedIndex = 0;
vm.menu = [
{ id: 0, icon: "", plName: "Strona główna", enName:"Homepage", url: "/" },
{ id: 1, icon: "", plName: "O Mnie", enName: "About me", url: "about-me" },
{ id: 3, icon: "", plName: "Moje projekty", enName: "My projects", url: "#" },
{ id: 4, icon: "", plName: "Kontakt", enName: "Contact", url: "#" },
];
}
})();
|
export default{
RECEIVED_GOALS: 'RECEIVED_GOALS'
}
|
exports.program1 =
`# this is a comment, and this is line 1
GOTO 3
SET x 10
PRINT x`
exports.count =
`SET i 1
SET max_iterations 5000000
SET result 0
# loop starts here
INCRBY result 1
# i++ (like a for loop)
INCRBY i 1
# i < max_iterations (for loop)
LESS_THAN_OR_GOTO max_iterations i 5
PRINT result
`
|
/*
* mimsg - MIme MeSsaGe javascript library / module
* (C) 2020
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
RFC822: "Return-Path", "Received", "Date", "From", "Subject", "Sender", "To", "cc", etc.
RFC2045: "Mime-Version", "Content-Type"
RFC2183: "Content-Disposition" (for multipart items)
RFC1341: "Content-Transfer-Encoding" (base64, quoted-printable, 8Bit, 7bit, binary, x-*)
Rfc3676: Format=flowed; DelSp=yes (TODO)
*/
// Comments should use https://jsdoc.app/
const rfc5322_max_line_length = 998; // excluding CRLF
/**
* Search an array inside an array.
* indexOf can only handle one item at a time on TypedArray.
* Usefull to find boundaries in 8 bits messages.
*
* @param {Array} haystack
* @param {Array} needle
* @param {number} [start=0]
* @return {number}
*/
export function arrayIndexOfArray(haystack, needle, start = 0) {
const lh = haystack.length, ln = needle.length;
while (start <= lh - ln) {
// quick search first item of needle
var i = haystack.indexOf(needle[0], start);
if (i === -1)
return -1; // not found
// good. Now check needle is actually there:
var found = true;
for (var j = 1; j < ln; j++) {
if (haystack[i + j] != needle[j]) {
found = false;
break; // No use looking further
}
}
if (found)
return i;
start = i + 1;
}
return -1;
}
/**
* Converts a string into an html printable string.
* Default is to replace only essential characters "&" and "<".
*
* @param {string} txt
* @param {RegExp} [re=/[&<]/g] Characters to be escaped.
* @return {string}
*/
export function htmlEscape(txt, re=/[&<]/g) {
return txt.replace(re, c => '&#' + c.charCodeAt(0) + ';');
}
/**
* Convert an unicode string into an Uint8Array, using UTF-8 charset.
*/
export function textEncode(str) {
const encoder = new TextEncoder();
return encoder.encode(str);
}
/**
* Decode an Uint8Array into an unicode string.
*/
export function textDecode(u8arr, charset='UTF-8') {
const decoder = new TextDecoder(charset);
return decoder.decode(u8arr);
}
/**
* Convert a base64 string into a Uint8Array.
*/
function base64ToUint8Array(txt) {
// txt is a string
// returns a Uint8Array
var str = window.atob(txt);
var l = str.length;
var arr = new Uint8Array(l);
for (var i = 0; i < l; i++) {
arr[i] = str.charCodeAt(i);
}
return arr;
}
/**
* Convert a Uint8Array into a base64 string.
*/
function uint8ArrayToBase64(u8arr) {
// u8arr is a Uint8Array
// returns a string
var str = '';
var l = u8arr.length;
for (var i = 0; i < l; i++) {
str += String.fromCharCode(u8arr[i]);
}
return window.btoa(str);
}
/**
* Convert a quoted printable string into a Uint8Array
*/
function quotedPrintableDecode(text) {
const l = text.length;
var u8arr = new Uint8Array(l);
var iT /* in text*/, iA /* in array */ = 0;
for (iT = 0; iT < l; iT++) {
let c = text.charCodeAt(iT);
if (c === 61) { // '='
let hexa = text.substr(iT + 1, 2);
c = parseInt(hexa, 16);
iT += 2;
if (isNaN(c))
continue;
}
u8arr[iA++] = c;
}
return u8arr.slice(0, iA);
}
/*
* Returns the first charset in ['us-ascii', 'iso8859-1', 'utf-8'] that can
* encode a string.
* Unused because TextEncoder only supports UTF-8 !
function getShortestCharset(str) {
let is7Bits = true;
let l = str.length;
for (let i = 0; i < l; i++) {
let c = str.charCodeAt(i);
if (c > 255)
return 'utf-8';
if (c > 127)
is7Bits = false;
}
return is7Bits ? 'us-ascii' : 'iso8859-1';
}
*/
/**
* Returns true if string can be ascii7 encoded
*/
function isString7bit(str) {
for (let i = 0, l = str.length; i < l; i++) {
let c = str.charCodeAt(i);
if (c > 127)
return false;
}
return true;
}
/**
* Make sure end of lines use \r\n.
*
* @param {string} str A string using \r\n or \r or \n or \n\r or a single line
* @return {string} String using \r\n
*/
export function normalizeCRLF(str) {
const iN = str.indexOf('\n');
const iR = str.indexOf("\r");
if (iN === -1) {
if (iR !== -1) {
// \r only
return str.replace(/\r/g, '\r\n');
}
// else no \r and no \n : noop
} else {
if (iR === -1) {
// \n only
return str.replace(/\n/g, '\r\n');
} else if (iN < iR) {
return str.replace(/\n\r/g, '\r\n');
}
// else iR < iN : Already using \r\n, noop
}
return str;
}
/**
* Return a random string
*
* @param {number} [len=16] - The length of the result
* @param {string} [alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_'] - The possible letters
* @return {string}
*/
export function randomId(len=16, alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_') {
let res = '';
for (let i = 0; i < len; i++)
res += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
return res;
}
/*
function showRawheaders() {
alert("Show raw clicked");
}
*/
// FIXME: RFC2047 6.2 Display of 'encoded-word's
// Decoding and display of encoded-words occurs *after* a
// structured field body is parsed into tokens. It is therefore
// possible to hide 'special' characters in encoded-words which, when
// displayed, will be indistinguishable from 'special' characters in the
// surrounding text. For this and other reasons, it is NOT generally
// possible to translate a message header containing 'encoded-word's to
// an unencoded form which can be parsed by an RFC 822 mail reader.
// Hint: Kmail decodes
// =?ISO-8859-1?Q?T=3Cest?= <contact@onetime.info>
// into
// "T<est" <contact@onetime.info>
/**
* Header.
* @class
*/
class MiMsgHeader {
constructor(name, value, attrs={}) {
this.name = name; // lower case
this.value = value; // decoded to utf-8
this.attrs = attrs; // only used by Content-* headers
}
/**
* @constructs MiMsgHeader
*/
static parse(line) {
/* line is rfc822 unfolded, but with =?x?x?= encoded fragments */
var i = line.indexOf(':');
if (i === -1) {
console.error('Invalid RFC822 header line without column: ' + line);
return null; // FIXME this will break later...
}
var name = line.substr(0, i).toLowerCase();
var value = line.substr(i + 1);
value = MiMsgHeader.parse_value(value);
var result = new MiMsgHeader(name, value);
if (name.startsWith('content-')) {
const split = result.contentSplit();
result.value = split[0];
result.attrs = split[1];
}
return result;
}
/**
* Decode a rfc2047 encoded fragment in the =?charset?encoding?str?= format
*
* @param {string} - Charset
* @param {string} - Encoding 'B' or 'Q'
* @param {string} - Text to be decoded
* @return {string}
* @example
* // return 'Message chiffré'
* decodeHeaderValueFragment('UTF-8', 'Q', 'Message_chiffr=c3=a9_GnuPG');
*/
static decodeHeaderValueFragment(charset, encoding, str) {
encoding = encoding.toUpperCase();
let decoded;
if (encoding === 'B') {
// base64 encoded
decoded = base64ToUint8Array(str);
} else if (encoding === 'Q') {
// quoted printable
decoded = MiMsgHeader.decodeQuotedPrintable(str);
} else {
console.error("Maformed RFC2047 header: Unsupported encoding '" + encoding + '". Expected "B" or "Q"');
return ''; // Displayed not attempted, see rfc2047 6.3
}
return textDecode(decoded, charset); // Uint8Array -> str
}
static parse_value(raw) {
/*
This decodes the value of a mail header value, according to RFC2047.
raw may be something like
"=?UTF-8?Q?Message_chiffr=c3=a9_GnuPG?="
*/
// This is almost .replace(/=?(.*)?(.*)?(.*)?=/, (orig, x, y, z) => decodeHeaderValueFragment(x, y z));
// But white space is ignored between encoded, also:
// RFC2047 tokens for charset & encoding excludes: CTLs + ' ()<>@,;:"/[]?.='
// RFC2047 tencoded-text alphabet excludes CTLs + ' ?'
const re = /=\?([^\0- ()<>@,;:"/[\]?.=]*)\?([^\0- ()<>@,;:"/[\]?.=]*)\?([^\0- ?]*)\?=/;
let result = '';
let lastIndex = 0;
let found;
while (found = raw.substr(lastIndex).match(re)) {
let inBetween = raw.substr(lastIndex, found.index);
if (!inBetween.match(/^[ \t\r\n]$/gm))
result += inBetween;
result += MiMsgHeader.decodeHeaderValueFragment(found[1], found[2], found[3]);
lastIndex += found.index + found[0].length;
}
result += raw.substr(lastIndex);
/*
var result = '';
var i = 0;
var afterEncoded = false; // rfc2047 6.2: Ignore spaces between encoded words
while (i < raw.length) {
if (raw.substr(i, 2) === '=?') {
if (afterEncoded) {
result = result.replace(/[ \t\r\n]*$/, ''); // remove empty spaces at the end
}
var j = raw.indexOf('?', i + 2);
if (j === -1) {
console.error('Maformed RFC2047 header: Charset not found in ' + raw.substring(i));
result += raw.substr(i);
break;
}
var charset = raw.substring(i + 2, j);
// TODO: remove the language as per rfc2231 section 7 (?)
var k = raw.indexOf('?', j + 1);
if (k === -1) {
console.error('Maformed RFC2047 header: Encoding not found in ' + raw.substring(i));
result += raw.substr(i);
break;
}
var encoding = raw.substring(j + 1, k);
j = k;
k = raw.indexOf('?=', j + 1);
if (k === -1) {
console.error('Maformed RFC2047 header: Encoded text not terminated in ' + raw.substring(i));
result += raw.substr(i);
break;
}
var encoded = raw.substring(j + 1, k);
i = k + 2;
result += MiMsgHeader.decodeHeaderValueFragment(charset, encoding, encoded);
afterEncoded = true;
} else {
var c = raw.charAt(i++);
if (afterEncoded && ' \t\r\n'.indexOf(c) === -1) {
afterEncoded = false;
}
result += c;
}
}
*/
// Cleaup spaces: trim left, deduplicate in the middle, trim right
result = result.replace(/^[ \t\r\n]*/, '').replace(/[ \t\r\n]+/g, ' ').replace(/[ \t\r\n]*$/, '');
return result;
}
/**
* Decode quoted printable text as Uint8Array according to RFC2047, where "_" means space.
*
* @param {string} txt
* @return {Uint8Array}
*/
static decodeQuotedPrintable(txt) {
// txt is a string
// returns a Uint8Array
var l = txt.length, arr = [];
for (var i = 0; i < l;) {
var c = txt.charCodeAt(i);
if (c === 0x3d /*'='*/ && i + 2 < l) {
var hex = parseInt(txt.substr(i + 1, 2), 16);
arr.push(hex);
i += 3;
} else if (c === 0x5f /*'_'*/) {
arr.push(0x20); // ' '
i++;
} else {
arr.push(c);
i++;
}
}
var result = new Uint8Array(arr.length);
result.set(arr);
return result;
}
/**
* Decode attribute value according to RFC2231.
* @example
* // returns 'Gérard'
* MiMsgHeader.attributeDecodeRFC2231("ISO-8859-1''G%E9rard")
*/
static attributeDecodeRFC2231(val) {
var p1 = val.indexOf("'");
var p2 = val.indexOf("'", p1 + 1);
if (p1 === -1 || p2 === -1) {
console.error('Invalid RFC2231 attribute value ' + val);
return 'error';
}
var charset = val.substr(0, p1);
var encoded = val.substr(p2 + 1);
var l = encoded.length;
var result = new Uint8Array(l);
var lres = 0;
for (var i = 0; i < l; i++) {
var c = encoded.charCodeAt(i);
if (c === 37) { // '%'
let cc = encoded.substr(i + 1, 2);
cc = parseInt(cc, 16);
result[lres++] = cc;
i += 2;
} else {
result[lres++] = c;
}
}
result = result.slice(0, lres);
return textDecode(result, charset);
}
/**
* Encode an attribute value according to RFC2231.
* @param {string} - test
* @return {string}
* @example
* // returns "UTF-8''G%C3A9rard"
* MiMsgHeader.attributeEncodeRFC2231('Gérard')
*/
static attributeEncodeRFC2231(str) {
let u8arr = textEncode(str);
let result = "UTF-8''";
for (let i = 0, l = u8arr.length; i < l; i++) {
let c = u8arr[i];
if (c < 128 && c >= 32) {
let cc = String.fromCharCode(c);
// illegal chars: attribute-char in RFC 2231 section 7 + tspecials in RFC 2045 section 5.1
if (!'*\'%()<>@,;\\\"/[]?='.includes(cc)) {
result += cc;
continue;
}
}
result += '%';
let hex = c.toString(16);
if (hex.length === 1)
result += '0';
result += hex;
}
return result;
}
contentSplit() {
// Token are parsed according to rfc2045
// This is only for 'Content-*' headers
// 'multipart/mixed; boundary="NEBIKbUAj980jV2K"' returns [ 'multipart/mixed', { 'boundary': 'NEBIKbUAj980jV2K' } ]
// 'application/x-stuff; title*1*=us-ascii'en'This%20is%20even%20more%20; title*2*=%2A%2A%2Afun%2A%2A%2A%20; title*3="isn't it!"' returns ['application/x-stuff', { 'title': "This is even more ***fun*** isn't it!" }
const l = this.value.length;
var i = this.value.indexOf(';');
if (i === -1) {
return [this.value, {}];
}
var main = this.value.substr(0, i); // the main value
var attrs = {}; // the extra ';' separated attributes
for (i++; i < l; i++) {
var j = this.value.indexOf('=', i + 1);
if (j === -1) {
console.error('Malformed header ' + this.name + ', missing "=" after ";"');
break;
}
var attrname = this.value.substring(i, j);
attrname = attrname.replace(/^ +/, '').replace(/ +/g, '').toLowerCase(); // XXX
var attrvalue = '';
var inquote = false;
for (j++; j < l; j++) {
const c = this.value.charAt(j);
if (c === '"') {
inquote = !inquote;
continue;
}
if (inquote) {
// We are inside double quotes
if (c === '\\')
attrvalue += this.value.charAt(++j);
else
attrvalue += c;
} else {
// We are not insode double quotes
if (c === ';')
break;
attrvalue += c;
}
attrs[attrname] = attrvalue;
}
i = j + 1;
}
// Reassemble RFC2231 multiline encoded attributes
var cleanedAttrs = {};
for (attrname in attrs) {
attrvalue = attrs[attrname];
let found;
if (found = attrname.match(/^(.*\*)([0-9])\*$/)) {
attrname = found[1];
if (!cleanedAttrs.hasOwnProperty(attrname))
cleanedAttrs[attrname] = '';
cleanedAttrs[attrname] += attrvalue;
} else {
cleanedAttrs[attrname] = attrvalue;
}
}
attrs = cleanedAttrs;
// Decode the RFC2231 encoded attributes
for (attrname in attrs) {
let found;
if (found = attrname.match(/^(.*)\*$/)) {
attrvalue = attrs[attrname];
attrname = found[1]; // drop the '*'
attrs[attrname] = MiMsgHeader.attributeDecodeRFC2231(attrvalue);
}
}
return [main, attrs];
}
/*
static test() {
const test = new MiMsgHeader('test', '');
var tmp;
test.value = 'multipart/mixed; boundary="nebikbuaj980jv2k"';
tmp = test.contentSplit();
test.value = 'multipart/mixed; boundary=';
tmp = test.contentSplit();
test.value = 'multipart/mixed; boundary="';
tmp = test.contentSplit();
test.value = 'multipart/mixed; boundary="nebikbuaj980jv2k";';
tmp = test.contentSplit();
test.value = 'attachment; filename="test = \\\\A\\"1234567890';
tmp = test.contentSplit();
test.value = 'attachment; filename="test = \\\\A\\"1234567890"; echo=1';
tmp = test.contentSplit();
//msg.setHeader('test', '=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=\r\n =?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=');
}
*/
/*
* Returns the name with nice cases.
*
* Change the first character of every word to upper case.
*/
nameCaseFormated() {
if (this.name === 'mime-version')
return 'MIME-Version';
// Every character at the begining or after '-'
return this.name.replace(/(^|-)./g, c => c.toUpperCase());
}
/**
* Returns the value and its attributes in a format compatible with RFC822.
* Brutally base64 encode the whole value if it can't be sent as is.
*/
valueWithAttrRfc822() {
let result;
// Quick and ugly
let useUtf = !isString7bit(this.value);
if (!useUtf) {
// Some special character needs to be encoded anyway
if (this.value.match('[?]'))
useUtf = true;
}
if (useUtf) {
let u8arr = textEncode(this.value);
let b64 = uint8ArrayToBase64(u8arr);
result = '=?UTF-8?B?' + b64 + '?=';
} else {
result = this.value;
}
for (let name in this.attrs) {
let value = this.attrs[name];
result += ';';
if (isString7bit(value)) {
let mustQuote = false;
let illegalTokenChars = '()<>@,;:\\"/[]?=';
for (let i = 0, l = value.length; i < l; i++) {
if (value.charCodeAt(i) <= 32 || illegalTokenChars.includes(value.charAt(i))) {
mustQuote = true;
break;
}
}
if (mustQuote)
value = '"' + value.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
result += name + '=' + value;
} else {
// RFC2231, with no language set
result += name + '*=' + MiMsgHeader.attributeEncodeRFC2231(value);
}
}
return result;
}
/**
* Returns the value and attributes in a printable format
*/
valueWithAttr() {
var result = this.value;
for (var attrname in this.attrs) {
result += '; ' + attrname + '="' + this.attrs[attrname].replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
}
return result;
}
toRfc822Lines() {
return this.nameCaseFormated() + ': ' + this.valueWithAttrRfc822();
}
}
/** Message Part.
*
* @class
*/
export class MiMsgPart {
constructor() {
// headers: array of MiMsgHeader
// Multiple header with the same name - like 'received' - are allowed
this.headers = [];
// body can be:
// a string (for text/ messages)
// a Uint8Array (for most attachments)
// an array of MiMsgPart (for multipart/ messages)
// a MiMsgPart (for message/rfc822)
this.body = null;
}
/**
* Returns the first header with that name.
*
* @param {string} - Lower case name of the header
* @returns {MiMsgHeader} The header or null
*/
getHeader(name) {
for (var header of this.headers) {
if (header.name === name)
return header;
}
return null;
}
/**
* Add a new header. Only usefull for Received and a few others, when multiple entries are allowed.
* One should generally use setHeader.
*
* @param {string} - Lower case name of the header
* @param {string} - The parsed value, decoded
* @param {object} [attrs={}] - The extra content- attributes
* @return {MiMsgHeader}
*/
addHeader(name, value, attrs={}) {
const header = new MiMsgHeader(name, value, attrs);
this.headers.push(header);
return header;
}
/**
* Add a new header, changing previous value if it already exists.
* See addHeader if you need duplicate entries.
*
* @param {string} - Lower case name of the header
* @param {string} - The parsed value, decoded
* @param {object} [attrs={}] - The extra content- attributes
* @return {MiMsgHeader}
*/
setHeader(name, value, attrs={}) {
var header = this.getHeader(name);
if (header) {
header.value = value;
header.attrs = attrs;
} else {
header = this.addHeader(name, value, attrs);
}
return header;
}
/**
* Returns the value of a header (first one if there are several by the same name).
* If not found, returns def.
*
* @param {string} - Lower case name of the header
* @param {string} [def=null] - Default value
* @return {string} The value if the header exists, def otherwise
*/
getHeaderValue(name, def=null) {
var header = this.getHeader(name);
if (header)
return header.value;
else
return def;
}
getContentTypeHeader() {
var header = this.getHeader('content-type');
if (!header) {
console.error('Message has no Content-Type.');
// RFC2045 5.2 : defaults to text/plain; charset=us-ascii :
header = new MiMsgHeader('content-type', 'text/plain', {'charset': 'us-ascii'});
}
return header;
}
/**
* Returns the Content-Transfer-Encoding header value
* default value is defined by RFC1341 5.
*/
getContentTransfertEncoding() {
const val = this.getHeaderValue('content-transfer-encoding', '7bit');
return val.toLowerCase();
}
/**
* Used to know whether the message part show be displayed 'inline' or as an 'attachment'
* See RFC2183
*/
getContentDisposition() {
const val = this.getHeaderValue('content-disposition', 'inline');
return val.toLowerCase();
}
/**
* Sets Content-Type to text/plain and initialize the body.
* Text will be output has 7bit if possible, utf-8 quoted-printable otherwise.
*/
setTextBody(text) {
text = normalizeCRLF(text);
// Encode the message using quoted-printable Content-Transfer-Encoding according to RFC1521:
const bodyUint8arr = textEncode(text);
var body = ''; // quoted-printable body
var is7bits = true;
const l = bodyUint8arr.length;
for (var i = 0, x, linelen = 0, xenc; i < l; i++) {
x = bodyUint8arr[i];
if (x < 32 || x >= 128) {
if (x === 13 && bodyUint8arr[i + 1] === 10) {
// Regular \r\n: Don't encode it
body += '\r\n';
i += 1; // Skip next input \n
linelen = 0;
continue; // skip line len overflow
}
if (x === 9) // \t
xenc = '\t';
else {
is7bits = false;
if (x < 16)
xenc = '=0' + x.toString(16).toUpperCase();
else
xenc = '=' + x.toString(16).toUpperCase();
}
}
else {
if (x === 61) { // '='
xenc = '=3D';
} else {
if (x >= 128)
is7bits = false;
xenc = String.fromCharCode(x);
}
}
if (linelen + xenc.length >= 76) {
// We're going to be over 76 char
body += '=\r\n';
linelen = 0;
}
body += xenc;
linelen += xenc.length;
}
// Check whether 7bit encoding is possible after all
var choose7bits = false;
if (is7bits) {
// There was no special character
choose7bits = true;
for (var line of text.split('\r\n')) {
if (line.length > rfc5322_max_line_length) {
choose7bits = false;
break;
}
}
}
if (choose7bits) {
this.setHeader('content-type', 'text/plain', {'charset': 'us-ascii'});
this.setHeader('content-transfer-encoding', '7bit'); // RFC1521
this.body = text; // Original text (with \r\n normalization)
} else {
this.setHeader('content-type', 'text/plain', {'charset': 'utf-8'});
this.setHeader('content-transfer-encoding', 'quoted-printable');
this.body = body;
}
}
/*
* @param {File} file
* @param {String} [disposition='attachment'] - 'attachment' or 'inline'
* @return {MiMsgPart}
*/
static newAttachementFromFile(file, contentDisposition='attachment') {
var attachementMessagePart = new MiMsgPart();
attachementMessagePart.setHeader('content-disposition', contentDisposition, {'filename': file.name});
attachementMessagePart.setHeader('content-transfer-encoding', 'base64');
if (file.type)
attachementMessagePart.setHeader('content-type', file.type, {'name': file.name}); // TODO required?
attachementMessagePart.body = '';
var b64 = file['content'];
b64 = b64.substr(b64.indexOf(',') + 1); // Skip everything before ','
// Cut in lines of 76 characters
while (b64) {
attachementMessagePart.body += b64.substr(0, 76) + '\r\n';
b64 = b64.substr(76);
}
return attachementMessagePart;
}
switchToMultiPart(subType='mixed') {
const oldContentTypeHeader = this.getHeader('content-type');
const oldContentType = oldContentTypeHeader.value;
if (oldContentType.startsWith('multipart/')) {
console.error('switchToMultiPart() called, but already multipart!');
return;
}
var part = new MiMsgPart();
// Move all content- headers to the part:
for (var i = 0; i < this.headers.length; ) {
let header = this.headers[i];
if (header.name.toLowerCase().startsWith('content-')) {
part.headers.push(header);
this.headers.splice(i, 1);
} else {
i++;
}
}
const boundary = 'nextPart' + randomId();
this.setHeader('content-type', 'multipart/' + subType, {'boundary': boundary});
part.body = this.body;
this.body = [part];
}
addAttachement(attachementMessagePart) {
if (this.getHeader('content-type').value.toLowerCase() != 'multipart/mixed')
this.switchToMultiPart();
this.body.push(attachementMessagePart);
}
/**
* Output the message in a format suitable for SMTP transfert (without DATA /^./ line handling)
*/
toRfc822Lines() {
const contentTypeHeader = this.getHeader('content-type');
const contentTransfertEncoding = this.getContentTransfertEncoding();
const contentDisposition = this.getContentDisposition();
var result = '';
// Output the headers first
for (var header of this.headers) {
result += header.toRfc822Lines() + '\r\n';
}
result += '\r\n';
if (typeof(this.body) === 'string') {
result += this.body;
} else if (Array.isArray(this.body)) {
if (!contentTypeHeader.value.toLowerCase().startsWith('multipart/')) {
console.error('Unsupported body type Array for Content-Type:' + contentTypeHeader.value.toLowerCase());
result += 'Unsupported body type Array for Content-Type:' + contentTypeHeader.value.toLowerCase();
} else {
const boundary = contentTypeHeader.attrs['boundary'];
if (!boundary) {
// rfc1341 7.2 boundary is required
result += 'Missing boundary of Content-Type:' + contentTypeHeader.value.toLowerCase();
} else {
result += 'This is a multi-part message in MIME format.\r\n';
result += '\r\n';
for (var part of this.body) {
result += '\r\n--' + boundary + '\r\n';
result += part.toRfc822Lines();
}
result += '\r\n--' + boundary + '--\r\n';
}
}
} else {
console.error('Unsupported body type ' + typeof(this.body));
result += 'Unsupported body type ' + typeof(this.body);
}
return result;
}
/**
* Returns this.body as an Uint8Array
*/
bodyAsBinary() {
switch (this.getContentTransfertEncoding()) {
case '7bit':
if (typeof(this.body) === 'string') {
return textEncode(this.body);
}
if (this.body instanceof Uint8Array) {
return this.body;
}
break;
case '8bit':
case 'binary':
return this.body;
case 'base64':
let b64txt = textDecode(this.body); // base64 is utf-8 compatible
return base64ToUint8Array(b64txt);
case 'quoted-printable':
let qptext;
if (typeof(this.body) === 'string') {
qptext = this.body;
} else if (this.body instanceof Uint8Array) {
qptext = textDecode(this.body); // quoted-printable is utf-8 compatible
} else {
break;
}
return quotedPrintableDecode(qptext);
}
console.error('Unsupported Content-Transfert-Encoding / typeof(this.body)');
return new Uint8Array();
}
/**
* Returns the headers as HTML
*/
headersToHtml() {
const wantedHeaders = ['from', 'to', 'cc', 'bcc', 'date'];
let messageId = this.getHeaderValue("message-id");
let messageRawHeadersId = messageId+"-raw-headers";
var html = '';
html += '<div class="msg-headers">';
let subject = this.getHeaderValue('subject', 'No subject');
let showRawHeaders = '<div class="showraw">'+gettext("Raw headers")+'</div>'
html += '<div>' + showRawHeaders + htmlEscape(subject) + '</div>';
html += '<table class=outer><tbody><tr><td width="100%">';
html += '<table><tbody>';
let from = this.getHeaderValue('from', '');
let resentfrom = this.getHeaderValue('resent-from');
if (resentfrom)
from += ` (resent from: ${resentfrom})`
let organization = this.getHeaderValue('organization');
if (organization)
from += ` (${organization})`;
if (from)
html += `<tr><th>From:<td>${htmlEscape(from)}`;
for (let name of ['to', 'cc', 'bcc', 'sender', 'list-id', 'date']) {
let header = this.getHeader(name);
if (!header)
continue;
html += '<tr>';
html += '<th>' + htmlEscape(header.nameCaseFormated()) + ':';
html += '<td>' + htmlEscape(header.valueWithAttr());
}
html += '</table></table>';
html += '</div>';
html += '<div class="msg-headers-full" id="'+messageRawHeadersId+'"><div>';
html += htmlEscape(this.rawheaders).replace(/\r\n/g, '<br>');
html += '</div></div>';
return html;
}
/**
* Returns the message as HTML
*/
toHtml(showHeaders = true) {
var html = '';
const contentTypeHeader = this.getContentTypeHeader();
const contentType = contentTypeHeader.value;
const contentTransfertEncoding = this.getContentTransfertEncoding();
const contentDisposition = this.getContentDisposition();
if (showHeaders)
html += this.headersToHtml();
let displayedInline = false;
switch (contentDisposition) {
case 'inline':
if (contentType === 'multipart/alternative') {
let bestType, bestI = null;
for (let i in this.body) {
let altType = this.body[i].getContentTypeHeader().value.toLowerCase();
if (!i // First alternative is always better than nothing
|| altType === 'text/plain' // Favor plain
|| (altType === 'text/html' && bestType !== 'text/plain') // html is ok, unless we found plain that is better
) {
bestI = i;
bestType = altType;
}
}
if (bestI === null) {
console.error(`Content-Type:${contentType} but there is no choice.`);
html += '(empty multipart/alternative)<br>';
} else {
html += `<div class=alternative>${ this.body[bestI].toHtml(false) }</div>`;
}
displayedInline = true;
} else if (contentType.startsWith('multipart/')) {
html += '<div class=multipart>';
for (var part of this.body) {
html += part.toHtml(false);
}
html += '</div>';
displayedInline = true;
} else if (contentType.startsWith('text/')) {
let u8arr = this.bodyAsBinary();
let charset = contentTypeHeader.attrs['charset'];
let text = textDecode(u8arr, charset);
let htmlblock = htmlEscape(text);
htmlblock = htmlblock.replace(/([\t\r\n >^])(https?:\/\/[^\t\r\n <"]+)/gi, '$1<a href="$2" target="_blank" rel="noopener noreferrer">$2</a>'); // links
htmlblock = htmlblock.replace(/\n/g, '<br>'); // CR
html += htmlblock + '<br>';
displayedInline = true;
} else if (contentType === 'image/gif' || contentType === 'image/jpeg' || contentType === 'image/png' || contentType === 'image/svg+xml') {
html += '<hr class=preattachment>';
let blob = new Blob([this.bodyAsBinary()],
{type: contentType, endings: 'native'});
let url = URL.createObjectURL(blob);
let contentDescription = this.getHeaderValue('content-description', '');
let alt = '';
if (contentDescription)
alt = ` alt="${ htmlEscape(contentDescription)}"`;
else {
const contentDispositionHeader = this.getHeader('content-disposition');
if (contentDispositionHeader) {
let filename = contentDispositionHeader.attrs['filename'];
alt = ` alt="${ htmlEscape(filename)}"`;
}
}
html += `<img src="${url}"${alt} class="mimsg-inline-image"><br>`;
displayedInline = true;
} else if (contentType === 'message/rfc822') {
html += this.body.toHtml(); // Encapsulated message
displayedInline = true;
} else {
console.error(`Unsupported Content-Type:${ htmlEscape(contentType) } for Content-Disposition:inline. Treating as attachment.`);
}
break;
case 'attachment':
break;
default:
console.error(`Unknown Content-Disposition:${contentDisposition}. Assuming attachment.`);
break;
}
if (!displayedInline) {
const contentDispositionHeader = this.getHeader('content-disposition');
var filename;
if (contentDispositionHeader)
filename = contentDispositionHeader.attrs['filename'];
if (!filename)
filename = 'Unknown';
html += '<hr class=preattachment>';
let blob = new Blob([this.bodyAsBinary()],
{type: contentType, endings: 'native'});
let url = URL.createObjectURL(blob);
filename = htmlEscape(filename, /[&<"]/g);
html += `<a href="${url}" download="${filename}" class=attachment target="_blank">${filename}</a>`;
}
let contentDescription = this.getHeaderValue('content-description', '');
if (contentDescription)
html += `<div>${contentDescription}</div>`;
return html;
}
}
class MultiPartMessagePart extends MiMsgPart {
/* rfc1341: Multipart/mixed -> Displayed serially, Multipart/alternative -> Chose the best for you */
/* see also: digest, parallel */
constructor() {
this.subtype = null;
this.boundary = null;
}
}
/*
* Helper function used in parsing
* Takes a Uint8Array and returns a MiMsgPart where body is still not decoded: It still is a Uint8Array array
*/
function rfc822_split_headers(u8arr) {
const CRLF = new Uint8Array([13, 10]); // \r\n
var start = 0;
var headers = []; // raw headers lines, unfolded, but not base64/quoted-pritable decoded
var rawheaders = ''; // raw headers lines, folded, unparsed
while (true) {
var headerline, i, firstChar;
i = arrayIndexOfArray(u8arr, CRLF, start);
if (i === -1) {
// No more headers! Assume the body is empty
console.error('Malformed RFC822 headers: \\r\\n not found before body.');
headerline = textDecode(u8arr.slice(start));
headers.push(headerline);
start = u8arr.length;
break;
}
headerline = textDecode(u8arr.slice(start, i));
start = i + 2; // skip the line, inluding the \r\n
if (headerline === '') {
break;
}
rawheaders += headerline + '\r\n';
firstChar = headerline.charAt(0);
if (firstChar === ' ' || firstChar === '\t')
// folded multiline header
headers[headers.length - 1] += headerline;
else
headers.push(headerline);
}
var result = new MiMsgPart();
for (var headerLine of headers) {
var header = MiMsgHeader.parse(headerLine);
if (header)
result.headers.push(header);
}
result.rawheaders = rawheaders;
result.body = u8arr.slice(start);
return result;
}
/**
* Parse a Uint8Array into headers and body
* For multipart/ messages, body is an array
* For message/rfc822 messages, body itself is a MiMsgPart
*/
export function parse_message(u8arr) {
var msg = rfc822_split_headers(u8arr);
const contentTypeHeader = msg.getContentTypeHeader();
const contentType = contentTypeHeader.value.toLowerCase();
const contentDisposition = msg.getContentDisposition();
if (contentType.startsWith('multipart/') && contentDisposition === 'inline') {
const boundary = contentTypeHeader.attrs['boundary'];
if (!boundary) {
// RFC1341 7.2 violation
console.error(`Message with Content-Type:${contentType}, but no boundary.`);
msg.body = `Message with Content-Type:${contentType}', but no boundary.`;
} else {
u8arr = msg.body; // now working within the body
msg.body = [];
const uint8boundary = textEncode('--' + boundary);
let i = 0, j;
var prolog = null, epilog = null;
let closedMarker = false;
while (true) { // while there are parts
// First search suitable boundary is not found: At a begining of a line and followed by either '\r\n' or '--'
// j will point at such a marker
// additionnally, closedMarker will be true if this is an end marker
{
let k = i;
while (true) { // while suitable boundary is not found, that is boundary followed by either '\r\n' or '--'
let c1, c2;
j = arrayIndexOfArray(u8arr, uint8boundary, k);
if (j === -1) {
console.error(`Parsing Content-Type:${contentType}, boundary=${boundary}, missing boundary end in body.`);
break;
}
if (j > 1 && (u8arr[j - 2] != 13 || u8arr[j - 1] != 10)) {
console.error(`Found boundary --${boundary} in a middle of a line.`);
k = j + 2;
continue;
}
c1 = u8arr[j + uint8boundary.length];
c2 = u8arr[j + uint8boundary.length + 1];
if (c1 === 13 && c2 === 10) { // CRLF
// Good, we found a boundary
break;
} else if (c1 === 45 && c2 === 45) { // --
// Good, we found the boundary end marker
closedMarker = true;
break;
} else {
console.error(`Parsing Content-Type=${contentType}, boundary=${boundary}, illegal characters ${c1},${c2} found after boundary.`);
k = j + uint8boundary.length;
}
}
}
let chunk;
if (j === -1)
chunk = u8arr.slice(i);
else if (j > 2)
chunk = u8arr.slice(i, j - 2);
else
chunk = u8arr.slice(i, j);
if (prolog === null) {
prolog = textDecode(chunk);
} else {
msg.body.push(parse_message(chunk));
}
if (j != -1) {
i = j + uint8boundary.length + 2;
if (closedMarker) {
chunk = u8arr.slice(i);
epilog = textDecode(chunk);
}
}
if (closedMarker || j === -1)
break;
}
}
} else if (contentType === 'message/rfc822' && contentDisposition === 'inline') {
msg.body = parse_message(msg.body)
} // else
// the body stays Uint8Array
return msg;
}
/**
* Helper function to reduce the size of visible images and having a zoom on
* click behavior.
* That function need to be called after displaying the content of toHtml(); */
export function setupInlineImageZoom() {
for (let elem of document.getElementsByClassName('mimsg-inline-image')) {
elem.addEventListener('click', function(evt) {
let img = evt.target;
img.classList.toggle('mimsg-inline-image-zoomed');
img.classList.toggle('mimsg-inline-image-unzoomed');
});
elem.classList.toggle('mimsg-inline-image-unzoomed');
}
}
/* vim: set et ts=4 ft=javascript: */
|
// TODO
import * as D3NE from 'd3-node-editor'
// import sockets
import { anyTypeSocket } from '../Sockets'
const componentEMA = new D3NE.Component('Buy', {
builder (node, editor) {
let Input = new D3NE.Input('Any', anyTypeSocket)
let Output = new D3NE.Output('Any', anyTypeSocket)
return node
.addInput(candlesticksInput)
.addOutput(indicatorsOutput)
},
worker (node, inputs, outputs) {
console.log(inputs)
}
})
module.exports = {
componentEMA
}
|
;
function click_action_info(id) {
alert("执行中。。请稍等")
$.ajax({
type: "POST",
url: "/xadmin/mobile_test_view/suite_test/",
headers: {"X-CSRFToken": $.cookie("csrftoken")},
data: {
'suite_id': id,
'action': 'exe',
},
success: function (response) {
alert(response)
}
});
}
;
function webclick_action_info(path) {
window.location.href = "/xadmin/web_report_view/" + path;
}
;
function logclick_action_info(path) {
window.location.href = "/xadmin/log_view/"+path
}
;
function imageclick_action_info(path) {
alert("/xadmin/image_view/"+path)
}
|
"use strict";
let http = require('http');
let async = require('async');
let Q = require('q');
const OHL = 'ohl';
const WHL = 'whl';
const QMJHL = 'lhjmq';
const FINAL = 'final';
module = module.exports = Object.freeze({
OHL: OHL,
WHL: WHL,
QMJHL: QMJHL,
LHJMQ: QMJHL,
open: open,
})
function open(game, league, mainCb) // optional callback
{
let uris = createGameUris(game, league);
// Most play data only provides the player ID, so we require a quick lookup
let playerIdToPersonIdMap = {};
// Take CHL Player ID to CHL Person ID, which has a much wider scope
// @param {string} playerId - The official CHL Player ID
// @return {string} The official CHL Person ID
let playerIdToPersonId = playerId => playerIdToPersonIdMap[playerId] || null;
let container = {
home: undefined, // provides home team ID
away: undefined, // provides away team ID
gameId: game,
status: undefined,
date: undefined,
gameLength: 0,
players: {}, // maps player's PERSON ID to a collection of information about the player
headCoaches: {},
goals: [],
shots: [],
penalties: [],
faceoffs: [],
shootout: [],
hits: {}, // Maps personId to hits
shotsOn: {}, // Maps person ID to number of shots_on
};
let deferred = Q.defer();
async.series([
// Get game summary data
function(callback) {
httpGetJson(uris.summary,
function(err, summary) {
if(err) {
callback(err);
}
let gameSummary = summary.GC.Gamesummary;
container.status = gameSummary.status_value.toLowerCase();
container.periods = Object.keys(gameSummary.periods);
container.home = filterTeamInfo(gameSummary.home);
container.away = filterTeamInfo(gameSummary.visitor);
container.date = gameSummary.game_date;
container.gameLength = gameSummary.game_length;
let coaches = determineHeadCoaches(
gameSummary.coaches,
container.home.id,
container.away.id
);
coaches.map(coach => container.headCoaches[coach.id] = {
firstName: coach.firstName,
lastName: coach.lastName,
teamId: coach.teamId,
});
callback(null)
});
},
// Get preview, including rosters
function(callback) {
httpGetJson(uris.preview,
function(err, preview) {
if(err) {
callback(err);
}
container.playoffs = preview.GC.Preview.current_season.playoff === '1';
// Certain information is not provided if the game
// was postponed or for any other reason not "final"
if(container.status.indexOf(FINAL) > -1)
{
let homeRoster = preview.GC.Preview.home_team.lineup;
let awayRoster = preview.GC.Preview.visiting_team.lineup;
[homeRoster, awayRoster].map(roster => {
roster.players.map(player => {
if(player.player_id !== null)
{
container.players[player.person_id] = {
playerId: player.player_id,
number: player.jersey_number,
position: player.position_str,
firstName: player.first_name,
lastName: player.last_name,
teamId: roster === homeRoster ? container.home.id : container.away.id,
starter: player.start !== '0',
};
// WHL does not provide hits
if (!isNaN(parseInt(player.hits))) {
container.hits[player.person_id] = parseInt(player.hits);
}
// WHL does not provide shots_on
if (!isNaN(parseInt(player.shots_on))) {
container.shotsOn[player.person_id] = parseInt(player.shots_on);
}
playerIdToPersonIdMap[player.player_id] = player.person_id;
}
});
});
}
callback(null);
}
)},
// Then get the play by play data
function(callback) {
async.waterfall([
httpGetJson.bind(null, uris.pbp),
function(pbp, cb) {
let events = pbp.GC.Pxpverbose;
for(let e = 0; e < events.length; e++)
{
let event = events[e];
switch(event.event) { // need to apply filters on these
case 'shot': container.shots.push(filterShotInfo(event));
break;
case 'goal': container.goals.push(filterGoalInfo(event));
break;
case 'penalty': container.penalties.push(filterPenaltyInfo(event));
break;
case 'faceoff': container.faceoffs.push(filterFaceoffInfo(event));
break;
case 'shootout':container.shootout.push(filterShootoutInfo(event));
break;
//default: console.log('Missed:', event.event);
// Missing: goalie_change, hit (the Q provides hits with little value), penaltyshot (but penaltyshot goals are counted)
}
}
cb(null);
}
], callback)
},
], function (err) {
if (err) deferred.reject(err);
else deferred.resolve(container);
});
return deferred.promise;
// Internal helper functions, which access some internal data!
// I hate to have to create these functions every time the main one is run,
// but in order to access the internal data it just makes sense
function filterTeamInfo(teamInfo)
{
return {
id: teamInfo.team_id,
//divisionId: teamInfo.division_id,
// TODO: Decide what to do about the fact that the WHL doesn't provide division_id
leagueId: teamInfo.league_id,
code: teamInfo.code,
city: teamInfo.city,
nickname: teamInfo.nickname,
}
}
function filterGoalInfo(goal)
{
return {
state: goal.goal_type || 'EV',
teamFor: goal.team_id,
teamAgainst: container.home.id === goal.team_id ? container.away.id : container.home.id,
time: goal.time_formatted,
period: goal.period_id,
coordinates: {
x: goal.x_location,
y: goal.y_location,
},
penaltyShot: goal.penalty_shot === '1',
playerId: playerIdToPersonId(goal.goal_player_id),
assist1PlayerId: playerIdToPersonId(goal.assist1_player_id),
assist2PlayerId: playerIdToPersonId(goal.assist2_player_id),
plus: goal.plus.map(player => playerIdToPersonId(player.player_id)),
minus: goal.minus.map(player => playerIdToPersonId(player.player_id)),
}
}
function filterShotInfo(shot)
{
return {
playerId: playerIdToPersonId(shot.player_id),
goalieId: playerIdToPersonId(shot.goalie_id),
teamFor: shot.player_team_id,
teamAgainst: shot.goalie_team_id,
goal: shot.game_goal_id !== '0',
time: shot.time_formatted,
period: shot.period_id,
coordinates: {
x: shot.x_location,
y: shot.y_location,
}
};
}
// Filters out extraneous information and stylizes the keys
// @param {Object} shootout - A singular shootout event
// @return {Object} The filtered and stylized information from the event
function filterShootoutInfo(shootout)
{
return {
playerId: playerIdToPersonId(shootout.player_id),
goalieId: playerIdToPersonId(shootout.goalie_id),
teamFor: shootout.team_id,
teamAgainst: shootout.goalie_info.team_id,
score: shootout.goal === '1',
}
}
// Filters out extraneous information and stylizes the keys
// @params {Object} faceoff - A singular faceoff event
// @return {Object} The filtered and stylized information from the event
function filterFaceoffInfo(faceoff)
{
let prospectiveWinningTeamId = faceoff.win_team_id;
let prospectiveLosingTeamId = faceoff.win_team_id === faceoff.player_home.team_id ?
faceoff.player_visitor.team_id
: faceoff.player_home.team_id;
if(prospectiveWinningTeamId !== null || prospectiveLosingTeamId !== null)
{
if(prospectiveWinningTeamId === null) {
prospectiveWinningTeamId = prospectiveLosingTeamId === container.home.id ? container.away.id : container.home.id;
} else if(prospectiveLosingTeamId === null) {
prospectiveLosingTeamId = prospectiveWinningTeamId === container.home.id ? container.away.id : container.home.id;
}
return {
winnerId: playerIdToPersonId(faceoff[faceoff.home_win === '1' ? 'home_player_id' : 'visitor_player_id']),
loserId: playerIdToPersonId(faceoff[faceoff.home_win === '1' ? 'visitor_player_id' : 'home_player_id']),
winningTeamId: prospectiveWinningTeamId,
losingTeamId: prospectiveLosingTeamId,
time: faceoff.time_formatted,
period: faceoff.period,
coordinates: {
x: faceoff.x_location,
y: faceoff.y_location,
},
};
}
}
// Filters out extraneous information and stylizes the keys
// @params {Object} penalty - A singular penalty event
// @return {Object} The filtered and stylized information from the event
function filterPenaltyInfo(penalty)
{
return {
playerId: playerIdToPersonId(penalty.player_id),
playerServed: playerIdToPersonId(penalty.player_served),
teamId: penalty.team_id,
drawingTeamId: penalty.team_id === container.home.id ? container.away.id : container.home.id,
time: penalty.time_off_formatted,
period: penalty.period_id,
class: penalty.penalty_class,
type: penalty.lang_penalty_description,
length: penalty.minutes_formatted,
};
}
}
function httpGetJson(uri, callback)
{
http.get(uri, response => {
let body = '';
response.on('err', callback)
.on('data', data => body += data)
.on('end', () => callback(null, JSON.parse(body)));
});
}
function createGameUris(game, league) {
return {
// For PBP!
pbp: `http://cluster.leaguestat.com/feed/index.php?feed=gc&key=f109cf290fcf50d4&client_code=${league.toLowerCase()}&game_id=${game}&lang_code=en&fmt=json&tab=pxpverbose`,
// For basic game data and coaches
summary: `http://cluster.leaguestat.com/feed/index.php?feed=gc&key=f109cf290fcf50d4&client_code=${league.toLowerCase()}&game_id=${game}&lang_code=en&fmt=json&tab=gamesummary`,
preview: `http://cluster.leaguestat.com/feed/index.php?feed=gc&key=f109cf290fcf50d4&client_code=${league.toLowerCase()}&game_id=${game}&lang_code=en&fmt=json&tab=preview`
}
}
function determineHeadCoaches(coaches, homeId, awayId)
{
return [
determineTeamHeadCoach(coaches.home, homeId),
determineTeamHeadCoach(coaches.visitor, awayId),
].filter(coach => coach); // filter out the undefined;
}
function determineTeamHeadCoach(coaches, teamId)
{
for(let c = 0; c < coaches.length; c++)
{
let coach = coaches[c];
if(coach.coach_type_id === '1' || coach.description === 'Head Coach') {
return {
id: coach.person_id,
teamId: teamId,
firstName: coach.first_name,
lastName: coach.last_name,
};
}
}
}
|
"use strict"
const chalk = require("chalk"),
config = require("./config"),
Drone = require("./drone"),
event = require("./assimilator")
class Queen extends Drone {
constructor(id, token) {
super(id, token)
this.id = id
super.client().on("message", async message => {
const authorId = message.author.id
if (!this.isBanned(authorId) // Not banned from using Schism
&& (this.allowedIn(message.channel.id) // Channel is either whitelisted or is a DM channel
|| message.channel.type === "dm")
&& message.author.id !== super.client().user.id) { // Not self
if (message.content.startsWith(config.PREFIX)){
this.handleCommands(message)
}
}
})
super.client().on("guildCreate", guild => {
this.log(`---------------------------------\nAdded to a new server.\n${guild.name} (ID: ${guild.id})\n${guild.memberCount} members\n---------------------------------`)
})
super.client().on("guildDelete", guild => {
this.log(`---------------------------------\nRemoved from a server.\n${guild.name} (ID: ${guild.id})\n---------------------------------`)
})
}
log(...args) {
console.log(chalk.bold(`[QUEEN] [${this.id}] ${args.join(" ")}`))
}
login() {
super.login()
}
randomUserId() {
const index = ~~(Math.random() * userIdCache.length - 1)
return userIdCache[index]
}
/**
* Parses a message whose content is presumed to be a command
* and performs the corresponding action.
*
* @param {Message} messageObj - Discord message to be parsed
* @return {Promise<string>} Resolve: name of command performed; Reject: error
*/
async handleCommands(message) {
if (message.author.bot) return null // Don't take commands from bots
this.log(`${this.location(message)} Received a command from ${message.author.tag}: ${message.content}`)
const args = message.content.slice(config.PREFIX.length).split(/ +/)
const command = args.shift().toLowerCase()
const admin = this.isAdmin(message.author.id)
switch (command) {
case "allsay":
if (!admin) break
event.emit("say", message.channel.id, args.join(" "))
break
}
return command
}
/**
* Sets the custom nicknames from the config file
*
* @return {Promise<void>} Resolve: nothing (there were no errors); Reject: array of errors
*/
async updateNicknames(nicknameDict) {
const errors = []
for (const serverName in nicknameDict) {
const [ serverId, nickname ] = nicknameDict[serverName]
const server = super.client().guilds.get(serverId)
if (!server) {
this.log(`Nickname configured for a server that Schism is not in. Nickname could not be set in ${serverName} (${serverId}).`)
continue
}
server.me.setNickname(nickname)
.catch(errors.push)
}
if (errors.length > 0)
throw errors
else
return
}
/**
* Get status name from status code
*
* @param {number} code - status code
* @return {string} status name
*/
status(code) {
return ["Playing", "Streaming", "Listening", "Watching"][code]
}
/**
* TODO: make this not comically unreadable
*
* @param {string} mention - a string like "<@1234567891234567>"
* @return {string} user ID
*/
mentionToUserId(mention) {
return (mention.startsWith("<@") && mention.endsWith(">"))
? mention.slice(
(mention.charAt(2) === "!")
? 3
: 2
, -1
)
: null
}
/**
* Is [val] in [obj]?
*
* @param {any} val
* @param {Object} object
* @return {Boolean} True/false
*/
has(val, obj) {
for (const i in obj) {
if (obj[i] === val)
return true
}
return false
}
isAdmin(userId) {
return this.has(userId, config.ADMINS)
}
isBanned(userId) {
return this.has(userId, config.BANNED)
}
allowedIn(channelId) {
return this.has(channelId, config.CHANNELS)
}
/**
* Is Object [obj] empty?
*
* @param {Object} obj
* @return {Boolean} empty or not
*/
isEmpty(obj) {
for (const key in obj) {
if (obj.hasOwnProperty(key))
return false
}
return true
}
/**
* Shortcut to a reusable message location string
*
* @param {Message} message
* @return {string} - "[Server - #channel]" format string
*/
location(message) {
return (message.channel.type == "dm")
? `[Direct message]`
: `[${message.guild.name} - #${message.channel.name}]`
}
}
module.exports = Queen
|
const db = require('./models');
const track = require('./models/song');
const user = require('./models/user');
db.user.findAll().then((user) => {
console.log(user);
})
db.song.findOrCreate({
where:
}).then((song) => {
})
|
import { useState } from 'react';
import './App.css';
import { initialProductList } from './datas'
const App = () => {
const [products, setProducts] = useState(initialProductList)
const [name, setName] = useState("")
const [price, setPrice] = useState(1)
const totalPrice = products.reduce((total, current) => {
const totalPriceForCurrentProduct = current.quantity * current.price
return total + totalPriceForCurrentProduct
}, 0)
// Gestion de l'event onChange sur le name
const onChangeName = event => {
setName(event.target.value)
}
// Gestion de l'event onChange sur le price
const onChangePrice = event => {
setPrice(event.target.value)
}
// On ajoute le nouveau produit saisi dans la liste de produit
const addProduct = () => {
const arrayLength = products.length
const lastElem = products[arrayLength - 1]
const lastId = lastElem.id
setProducts([
...products,
{ id: lastId + 1, name: name, price: price, quantity: 1 }
])
}
const addProductWithPreValue = () => {
// prevValues correspond a la value precedent du state avant sa mise a jour
// uuidv4 permet d'obtenir un random uniq id
setProducts(prevValues => {
const arrayLength = prevValues.length()
const lastElem = prevValues[arrayLength - 1]
const lastId = lastElem.id
return [
...prevValues,
{ id: lastId + 1, name: name, price: price, quantity: 1 }
]
})
}
return (
<div className='App'>
<h1 className='h1'>Ma commande</h1>
<table className='table'>
<thead>
<tr>
<th className='th'>Product</th>
<th className='th'>Price</th>
<th className='th'>Quantity</th>
<th className='th'>Total price</th>
<th className='th'>Action</th>
</tr>
</thead>
<tbody>
{ products.map(product => {
return (
<tr key={product.id}>
<td className='td'>{product.name}</td>
<td className='td'>{product.price}</td>
<td className='td'>{product.quantity}</td>
<td className='td'>{product.quantity * product.price} €</td>
<td className='td'>
<button>Delete</button>
</td>
</tr>
)
}) }
</tbody>
</table>
<p>
Total de la commande : <em>{totalPrice}</em>
</p>
<div className="form">
<h2 className="h2">Add product</h2>
<div>
<label>Name</label>
<input
className='field'
type="text"
required
placeholder="Name"
value={name}
onChange={onChangeName}
/>
</div>
<div>
<label>Price</label>
<input
className='field'
type="number"
required
min="1"
value={price}
onChange={onChangePrice}
/>
</div>
<button onClick={addProduct}>Add</button>
</div>
</div>
);
}
export default App;
|
import React, {Fragment} from "react"
import FontAwesomeIcon from "./FontAwesomeIcon"
import StyledHeader from "../styled/StyledHeader"
import StyledHeaderTitle from '../styled/StyledHeaderTitle'
import { movies } from './staticData'
import StyledHorizontalScroll from '../styled/StyledHorizontalScroll'
import Movie from './Movie'
import StyledFooter from '../styled/StyledFooter'
import StyledLargeBtn from '../styled/StyledLargeButton'
const Movies = () => (
<Fragment>
<StyledHeader>
<FontAwesomeIcon icon='bars' text='help' />
<StyledHeaderTitle>The movie Recommended</StyledHeaderTitle>
<FontAwesomeIcon icon='search' />
</StyledHeader>
<StyledHorizontalScroll>
{ movies.map(movie =>(
<Movie
key={movie.id}
name={movie.name}
poster={movie.poster}
duration={movie.duration}
year={movie.year}
/>
))}
</StyledHorizontalScroll>
<StyledFooter>
<StyledLargeBtn>Recommended Movies</StyledLargeBtn>
</StyledFooter>
</Fragment>
)
export default Movies
|
const express = require('express');
const interviewController = require('../controllers/interviews.js');
const validate = require('express-validation');
const validation = require('../validation/interviews.js');
const router = express.Router();
router.post('/new', validate(validation.insert), interviewController.insert);
router.get('/user', validate(validation.getByUserId), interviewController.getByUserId);
router.get('/candidate', validate(validation.getByCandidateId), interviewController.getByCandidateId);
router.get('/unclosed/user', validate(validation.getUnclosedByUserId), interviewController.getUnclosedByUserId);
router.get('/detailed-view', validate(validation.getById), interviewController.getById);
module.exports = router;
|
'use strict'
// Import user model
const UserSchema = require('../models/user.model')
/**
* List all Users
* @returns {Promise} The find promise
*/
function listUsers (fields) {
return UserSchema
.find()
.select(fields)
.lean()
}
/**
* Get a user info
* @param {String} username - Username of the user
* @returns {Promise} The findOne promise
*/
function getUser (searchObj, fields) {
return UserSchema
.findOne(searchObj)
.select(fields)
.lean()
}
/**
* Create a user
* @param {Object} userData - Object with all user informations
* @returns {Promise} The save promise
*/
function createUser (userData) {
let newUser = new UserSchema(userData)
return newUser.save()
}
/**
* Update a user
* @param {String} username - Username of the user
* @param {Object} userData - Object with all user informations updated
* @returns {Promise} The update promise
*/
function updateUser (username, userData, push) {
return (push === 1)
? UserSchema
.update({ username: username },
{ $push: userData })
: UserSchema
.update({ username: username },
{ $set: userData })
}
// Export all the services functions
module.exports = {
createUser,
listUsers,
getUser,
updateUser
}
|
import mongoose from 'mongoose';
const StudioSchema = new mongoose.Schema({
name: String,
description: String,
}, {
timestamps: true,
});
const StudioModel = mongoose.model('Studio', StudioSchema);
export default StudioModel;
|
import Image from "next/image";
/** 投稿画像をImage化 */
export function PostImage({ title, src, alt }) {
const slimSrc = src.replace("/t_postimage,f_auto/", "/");
return (
<figure className="my-8">
<div className="relative max-h-hero h-screen">
<Image src={slimSrc} alt={alt} layout="fill" objectFit="contain" />
</div>
{title ? (
<figcaption className="max-w-2xl mx-auto p-2 text-center text-gray-600 text-base">
{title}
</figcaption>
) : (
<></>
)}
</figure>
);
}
|
var _viewer = this;
if(_viewer.opts.readOnly){
_viewer.readCard();
}
var mxCol = _viewer.getItem("MX_COL").getValue();
if(mxCol == "KC_ODEPTCODE"){
_viewer.getItem("MX_DATA").hide();
_viewer.getItem("MX_DATA3").show();
}else if(mxCol == "KC_LEVEL"){
_viewer.getItem("MX_DATA").hide();
_viewer.getItem("MX_DATA4").show();
}
_viewer.getItem("MX_COL").change(function(){
mxCol = _viewer.getItem("MX_COL").getValue();
if(mxCol == "KC_ODEPTCODE"){
_viewer.getItem("MX_DATA").hide();
_viewer.getItem("MX_DATA3").show();
_viewer.getItem("MX_DATA4").hide();
}else if(mxCol == "KC_LEVEL"){
_viewer.getItem("MX_DATA").hide();
_viewer.getItem("MX_DATA3").hide();
_viewer.getItem("MX_DATA4").show();
}else{
_viewer.getItem("MX_DATA").show();
_viewer.getItem("MX_DATA3").hide();
_viewer.getItem("MX_DATA4").hide();
}
});
_viewer.afterSave = function(resultData) {
setTimeout(function(){
_viewer._parHandler.refreshGrid();
jQuery("#" + _viewer.dialogId).dialog("close");
}, 100);
};
|
'use strict'
/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use('Schema')
class TransportesSchema extends Schema {
up () {
this.create('transportes', (table) => {
table.increments('id');
table.string('Tipo');
table.string('Marca');
table.string('Nombre');
table.timestamps();
})
}
down () {
this.drop('transportes')
}
}
module.exports = TransportesSchema
|
/* global $ */
//Function to validate details
function validateDetails(){
// declaring and assigning values to variables
var pin = document.getElementById("user_pin").value;
var name = document.forms["details"]["name"].value;
var email = document.forms["details"]["email"].value;
//If statement to validate details
if(pin == ""){
disablebtnPurchase();
alert("Please enter your PIN");
}
else if (String(pin).length < 4){
disablebtnPurchase();
alert("Please ensure your PIN is 4 digits long");
}
else if(name == ""){
alert("Please enter your name");
return false;
}
else if(email == ""){
alert("Please enter your email");
return false;
}
else{
enablebtnPurchase();
return true;
} // end of if
} //end of function
// function to enable next button
function enablebtnPurchase (){
$('#btnPurchase').prop('disabled', false);
} //end of function
// fucntion to disable next button
function disablebtnPurchase() {
$('#btnPurchase').prop('disabled', true);
} //end of function
|
class AnimationManager {
constructor() {
this.test = "pouet";
}
update() {
}
// anim = () => {
// }
}
export default AnimationManager;
|
import React from 'react';
export default function Footer() {
return (
<header className="gf-header">
<h1>Game of Life</h1>
</header>
);
}
|
import { CounterType } from '../types'
const incrCounter = () => ({
type: CounterType.INCR_COUNTER,
})
const decrCounter = () => ({
type: CounterType.DECR_COUNTER,
})
const resetCounter = () => ({
type: CounterType.RESET_COUNTER,
})
export default {
incrCounter,
decrCounter,
resetCounter
}
|
/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/
/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/
/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/
define(function(require){
var $ = require('jquery');
var html = require('text!test/markup/repeater-markup.html');
/* FOR DEV TESTING - uncomment to test against index.html */
//html = require('text!index.html!strip');
//html = $('<div>'+html+'</div>').find('#MyRepeaterContainer');
require('bootstrap');
require('fuelux/repeater');
module('Fuel UX Repeater', {
setup: function(){
this.$markup = $(html);
this.$markup.find('.repeater-views').append('' +
'<label class="btn btn-default active">' +
'<input name="repeaterViews" type="radio" value="test1.view1">' +
'<span class="glyphicon glyphicon-asterisk"></span>' +
'</label>' +
'<label class="btn btn-default">' +
'<input name="repeaterViews" type="radio" value="test2.view2">' +
'<span class="glyphicon glyphicon-asterisk"></span>' +
'</label>');
},
teardown: function(){
delete $.fn.repeater.viewTypes.test1;
}
});
test("should be defined on jquery object", function () {
ok($().repeater, 'repeater method is defined');
});
test("should return element", function () {
var $repeater = $(this.$markup);
ok($repeater.repeater() === $repeater, 'repeater should be initialized');
});
test("should call dataSource correctly", function () {
var $repeater = $(this.$markup);
$repeater.repeater({
dataSource: function(options, callback){
ok(1===1, 'dataSource function called prior to rendering');
equal(typeof options, 'object', 'dataSource provided options object');
equal(typeof callback,'function', 'dataSource provided callback function');
callback({});
}
});
});
test("should handle filtering correctly", function () {
var hasCalledDS = false;
var $repeater = $(this.$markup);
var $filters = $repeater.find('.repeater-filters');
$repeater.repeater({
dataSource: function(options, callback){
if(hasCalledDS){
ok(1===1, 'dataSource called again upon selecting different filter');
equal(options.filter.text, 'Some', 'filter text property correct on change');
equal(options.filter.value, 'some', 'filter value property correct on change');
}else{
equal(typeof options.filter, 'object', 'filter object passed to dataSource');
equal(options.filter.text, 'All', 'filter text property correct initially');
equal(options.filter.value, 'all', 'filter value property correct initially');
callback({});
hasCalledDS = true;
$filters.find('button').click();
$filters.find('li:nth-child(2) a').click();
}
}
});
});
test("should handle itemization correctly", function () {
var hasCalledDS = false;
var $repeater = $(this.$markup);
var $pageSizes = $repeater.find('.repeater-itemization .selectlist');
$repeater.repeater({
dataSource: function(options, callback){
if(hasCalledDS){
ok(1===1, 'dataSource called again upon selecting different page size');
equal(options.pageSize, 5, 'correct pageSize passed after change');
}else{
equal(options.pageIndex, 0, 'correct pageIndex passed to dataSource');
equal(options.pageSize, 10, 'correct pageSize passed to dataSource');
callback({ count: 200, end: 10, start: 1 });
equal($repeater.find('.repeater-count').text(), '200', 'count set correctly');
equal($repeater.find('.repeater-end').text(), '10', 'end index set correctly');
equal($repeater.find('.repeater-start').text(), '1', 'start index set correctly');
hasCalledDS = true;
$pageSizes.find('button').click();
$pageSizes.find('li:first a').click();
}
}
});
});
test("should handle pagination correctly", function () {
var count = -1;
var $repeater = $(this.$markup);
var $primaryPaging = $repeater.find('.repeater-primaryPaging');
var $secondaryPaging = $repeater.find('.repeater-secondaryPaging');
$repeater.repeater({
dataSource: function(options, callback){
count++;
switch (count){
case 0:
equal(options.pageIndex, 0, 'correct pageIndex passed to dataSource');
callback({ page: 0, pages: 2 });
equal($primaryPaging.hasClass('active'), true, 'primary paging has active class');
equal($primaryPaging.find('input').val(), '1', 'primary paging displaying correct page');
equal($primaryPaging.find('li').length, 2, 'primary paging has correct number of selectable items');
$repeater.find('.repeater-next').click();
break;
case 1:
ok(1===1, 'dataSource called again upon clicking next button');
equal(options.pageIndex, 1, 'correct pageIndex passed to dataSource on next click');
callback({ page: 1, pages: 6 });
equal($secondaryPaging.hasClass('active'), true, 'secondary paging has active class');
equal($secondaryPaging.val(), '2', 'secondary paging displaying correct page');
$repeater.find('.repeater-prev').click();
break;
case 2:
ok(1===1, 'dataSource called again upon clicking prev button');
equal(options.pageIndex, 0, 'correct pageIndex passed to dataSource on prev click');
callback({});
break;
}
},
dropPagingCap: 3
});
});
test("should handle search correctly", function () {
var count = -1;
var $repeater = $(this.$markup);
var $search = $repeater.find('.repeater-search');
$repeater.repeater({
dataSource: function(options, callback){
count++;
switch (count){
case 0:
equal(options.search, undefined, 'search value not passed to dataSource initially as expected');
callback({});
$search.find('input').val('something');
$search.trigger('searched.fu.repeater');
break;
case 1:
equal(options.search, 'something', 'correct search value passed to dataSource upon searching');
callback({});
$search.find('input').val('');
$search.trigger('cleared.fu.repeater');
break;
case 2:
equal(options.search, undefined, 'search value not passed to dataSource after clearing');
callback({});
break;
}
},
dropPagingCap: 3
});
});
test("should handle views correctly", function () {
var hasCalledDS = false;
var $repeater = $(this.$markup);
var $views = $repeater.find('.repeater-views');
$repeater.repeater({
dataSource: function(options, callback){
if(hasCalledDS){
equal(options.view, 'test2.view2', 'correct view value passed to dataSource upon selecting different view');
}else{
equal(options.view, 'test1.view1', 'correct view value passed to dataSource initially');
hasCalledDS = true;
callback({});
$views.find('label:last input').trigger('change');
}
},
dropPagingCap: 3
});
});
test("should run view plugin aspects correctly - pt 1", function () {
var ran = 0;
var $repeater = $(this.$markup);
$.fn.repeater.viewTypes.test1 = {
initialize: function(helpers, callback){
equal(ran, 0, 'initialize function correctly ran first');
equal(typeof helpers, 'object', 'initialize function provided helpers object');
equal(typeof callback,'function', 'initialize function provided callback function');
ran++;
callback({});
},
selected: function(helpers){
equal(ran, 1, 'selected function correctly ran upon view select');
equal(typeof helpers, 'object', 'selected function provided helpers object');
ran++;
},
dataOptions: function(options){
equal(ran, 2, 'dataOptions function correctly ran prior to rendering');
equal(typeof options, 'object', 'dataOptions function provided options object');
ran++;
return options;
},
before: function(helpers){
equal(ran, 3, 'before function ran before renderItems function');
equal(typeof helpers, 'object', 'before function provided helpers object');
equal((helpers.container.length>0 && typeof helpers.data==='object'), true, 'helpers object contains appropriate attributes');
ran++;
return { item: '<div class="test1-wrapper" data-container="true"></div>' };
},
renderItem: function(helpers){
equal((ran>3), true, 'renderItem function ran after before function');
equal(typeof helpers, 'object', 'renderItem function provided helpers object');
equal((helpers.container.length>0 && typeof helpers.data==='object' &&
typeof helpers.index==='number' && typeof helpers.subset==='object'), true, 'helpers object contains appropriate attributes');
equal(helpers.container.hasClass('test1-wrapper'), true, 'data-container="true" attribute functioning correctly');
ran++;
return { item: '<div class="test1-item"></div>' };
},
after: function(helpers){
equal(ran, 7, 'after function ran after renderItems function');
equal(typeof helpers, 'object', 'after function provided helpers object');
equal((helpers.container.length>0 && typeof helpers.data==='object'), true, 'helpers object contains appropriate attributes');
return false;
},
repeat: 'data.smileys'
};
$repeater.repeater({
dataSource: function(options, callback){
callback({ smileys: [':)', ':)', ':)'] });
}
});
});
test("should run view plugin aspects correctly - pt 2", function () {
var ran = 0;
var $repeater = $(this.$markup);
$.fn.repeater.viewTypes.test1 = {
render: function(helpers, callback){
equal(1, 1, 'render function ran when defined');
equal(typeof helpers, 'object', 'render function provided helpers object');
equal((helpers.container.length>0 && typeof helpers.data==='object'), true, 'helpers object contains appropriate attributes');
},
resize: function(helpers){
equal(1, 1, 'resize function correctly ran when control is cleared');
equal(typeof helpers, 'object', 'resize function provided helpers object');
},
cleared: function(helpers){
equal(1, 1, 'cleared function correctly ran when control is cleared');
equal(typeof helpers, 'object', 'cleared function provided helpers object');
}
};
$repeater.repeater({
dataSource: function(options, callback){
callback({ smileys: [':)', ':)', ':)'] });
$repeater.repeater('resize');
$repeater.repeater('clear');
}
});
});
test('views config option should function as expected', function(){
var $repeater = $(this.$markup);
var $views = $repeater.find('.repeater-views');
$repeater.repeater({
views: {
view1: {
dataSource: function(options, callback){
equal(options.view, 'test1.view1', 'view-specific configuration honored');
callback({});
$views.find('label:last input').trigger('change');
}
},
'test2.view2': {
dataSource: function(options, callback){
equal(options.view, 'test2.view2', 'view-specific configuration honored');
callback({});
}
}
}
});
});
test("should handle disable / enable correctly", function () {
var $repeater = $(this.$markup);
var $search = $repeater.find('.repeater-header .search');
var $filters = $repeater.find('.repeater-header .repeater-filters');
var $views = $repeater.find('.repeater-header .repeater-views label');
var $pageSize = $repeater.find('.repeater-footer .repeater-itemization .selectlist');
var $primaryPaging = $repeater.find('.repeater-footer .repeater-primaryPaging .combobox');
var $secondaryPaging = $repeater.find('.repeater-footer .repeater-secondaryPaging');
var $prevBtn = $repeater.find('.repeater-prev');
var $nextBtn = $repeater.find('.repeater-next');
var disabled = 'disabled';
$repeater.on('disabled.fu.repeater', function(){
ok(1===1, 'disabled event called as expected');
});
$repeater.on('enabled.fu.repeater', function(){
ok(1===1, 'enabled event called as expected');
});
$repeater.on('rendered.fu.repeater', function(){
setTimeout(function(){
$repeater.repeater('disable');
equal($search.hasClass(disabled), true, 'repeater search disabled as expected');
equal($filters.hasClass(disabled), true, 'repeater filters disabled as expected');
equal($views.attr(disabled), disabled, 'repeater views disabled as expected');
equal($pageSize.hasClass(disabled), true, 'repeater pageSize disabled as expected');
equal($primaryPaging.hasClass(disabled), true, 'repeater primaryPaging disabled as expected');
equal($secondaryPaging.attr(disabled), disabled, 'repeater secondaryPaging disabled as expected');
equal($prevBtn.attr(disabled), disabled, 'repeater prevBtn disabled as expected');
equal($nextBtn.attr(disabled), disabled, 'repeater nextBtn disabled as expected');
equal($repeater.hasClass(disabled), true, 'repeater has disabled class as expected');
$repeater.repeater('enable');
equal($search.hasClass(disabled), false, 'repeater search enabled as expected');
equal($filters.hasClass(disabled), false, 'repeater filters enabled as expected');
equal($views.attr(disabled), undefined, 'repeater views enabled as expected');
equal($pageSize.hasClass(disabled), false, 'repeater pageSize enabled as expected');
equal($primaryPaging.hasClass(disabled), false, 'repeater primaryPaging enabled as expected');
equal($secondaryPaging.attr(disabled), undefined, 'repeater secondaryPaging enabled as expected');
equal($prevBtn.attr(disabled), disabled, 'repeater prevBtn still disabled as expected (no more pages)');
equal($nextBtn.attr(disabled), disabled, 'repeater nextBtn still disabled as expected (no more pages)');
equal($repeater.hasClass(disabled), false, 'repeater no longer has disabled class as expected');
}, 0);
});
$repeater.repeater();
});
asyncTest('should destroy control', function(){
var $repeater = $(this.$markup);
var afterSource = function(){
setTimeout(function(){
start();
equal(typeof( $repeater.repeater('destroy')) , 'string', 'returns string (markup)');
equal( $repeater.parent().length, false, 'control has been removed from DOM');
}, 0);
};
$repeater.repeater({
dataSource: function(options, callback){
callback({ smileys: [':)', ':)', ':)'] });
afterSource();
}
});
});
});
|
// 本机开发时使用
var WxApiRoot = 'http://localhost:8080/wx/';
// 云平台部署时使用
// var WxApiRoot = 'http://3.14.127.134:8080/wx/';
// 云平台上线时使用
// var WxApiRoot = 'https://www.kiwi1.cn/wx/';
module.exports = {
IndexUrl: WxApiRoot + 'home/index', //首页数据接口
AuthLoginByWeixin: WxApiRoot + 'auth/login_by_weixin', //微信登录
StorageUpload: WxApiRoot + 'storage/upload', //图片上传,
UserIndex: WxApiRoot + 'user/index', //个人页面用户相关信息
SubmitIssue: WxApiRoot + 'user/submitIssue', //提交issue
ShowFriendList: WxApiRoot + 'friend/getAll', //获取朋友列表,
GetPrivateCategory: WxApiRoot + 'category/getAll/' + 2, //获取私人目录,
GetPublicCategory: WxApiRoot + 'category/getAll/' + 1, //获取公共目录,
GetPostsAll: WxApiRoot + 'posts/getAll/', //获取所有posts,
GetPostsDetail: WxApiRoot + 'posts/getDetail/', //获取posts详细,
GetPostsInfoDetail: WxApiRoot + 'posts/getInfo/', //获取posts详细,
GetFriendPublicCategory: WxApiRoot + 'friend/getAll/menu/', //获取朋友共有目录,
GetFriendPublicPosts: WxApiRoot + 'friend/getPost/', //获取朋友所有posts,
GetFriendDetail: WxApiRoot + 'friend/getDetail/', //获取朋友posts详细,
DelPosts: WxApiRoot + 'posts/delete', //删除文章,
AddCategory: WxApiRoot + 'category/add', //添加目录,
UpdateCategory: WxApiRoot + 'category/update', //修改目录,
DelCategory: WxApiRoot + 'category/delete', //删除目录,
GetCategoryDetail: WxApiRoot + 'category/detail/', //获取目录详细,
UpdatePosts: WxApiRoot + 'posts/update', //修改文章,
AddPost: WxApiRoot + 'posts/add', //添加文章,
AddComment: WxApiRoot + 'comment/add', //添加文章,
DelComment: WxApiRoot + 'comment/delete', //删除评论,
};
|
(function() {
'use strict';
angular.module('app.controllers')
.controller('PresentersCtrl',
function($scope,
presenters) {
/**
* Init function
* @return
*/
$scope.init = function() {
$scope.presenters = presenters;
}
$scope.init();
}
);
})();
|
const isPrime = require('../isPrime')
test.skip('0 should not be a prime', () => {
expect(isPrime(0)).toBe(false)
})
test.skip('1 should not be a prime', () => {
expect(isPrime(1)).toBe(false)
})
test.skip('2 should be a prime', () => {
expect(isPrime(2)).toBe(true)
})
test.skip('3 should be a prime', () => {
expect(isPrime(3)).toBe(true)
})
test.skip('5 should be a prime', () => {
expect(isPrime(5)).toBe(true)
})
test.skip('6 should not be a prime', () => {
expect(isPrime(6)).toBe(false)
})
test.skip('15 should not be a prime', () => {
expect(isPrime(15)).toBe(false)
})
test.skip('27 should not be a prime', () => {
expect(isPrime(27)).toBe(false)
})
test.skip('97 should be a prime', () => {
expect(isPrime(97)).toBe(true)
})
test.skip('3125 should not be a prime', () => {
expect(isPrime(3125)).toBe(false)
})
|
var BigEvent = require('./app/bigEvent');
new BigEvent($('.trailer-carousel'),$('.trailer-title'));
var Carousel = require('./app/carousel');
new Carousel($('.carousel'));
var ChangeImg = require('./app/change');
new ChangeImg($('.talk img'));
var Move = require('./app/move');
var m1 = new Move($('.header'));
m1.open(
[{
target:'.mountain1',
xFactor:'20',
yFactor:'30'
},{
target:'.mountain2',
xFactor:'30',
yFactor:'40'
},{
target:'.mountain3',
xFactor:'40',
yFactor:'50'
}
]);
var m2 = new Move($('.intro'));
m2.open(
[{
target:'.intro-bg1',
xFactor:'20',
yFactor:'30'
},{
target:'.intro-bg2',
xFactor:'30',
yFactor:'40'
}
]);
var Weather = require('./app/weather');
new Weather($('.weather-detail'));
|
import React, { Component } from 'react';
import { SafeAreaView, ScrollView, Text, View } from 'react-native';
import SeparatorAV from '../../../components/atoms/separator-av';
import ImageTextMV from '../../../components/molecules/image-text-mv';
import InputTextWithIconMV from '../../../components/molecules/input-text-icon-mv';
import BannerTitleSubtitleButton from '../../../containers/organisms/banner-with-title-subtitle-button';
import CardView from '../../organisms/card-view';
import CollectionViewWithTitleMore from '../../organisms/collection-with-title-more';
import DopeSection from '../../organisms/dope-section';
import TabBarController from '../../../containers/organisms/tab-bar';
const dopeItems = ['DOPE 1', 'DOPE 2', 'DOPE 3', 'DOPE 4', 'DOPE 5', 'DOPE 6', 'DOPE 7', 'DOPE 8']
class Home extends Component {
render() {
return (
<SafeAreaView style={{flex: 1}}>
{/* SearchBar Section with NavBar Margin Handling */}
<InputTextWithIconMV placeholder='Search Here!'/>
<ScrollView style={{flex: 1, backgroundColor: 'white'}}>
{/* Header Section */}
<View style={{marginHorizontal: 16, marginTop: 8}}>
{/* Upper Header Section */}
<View style={{borderTopLeftRadius: 4, borderTopRightRadius: 4, backgroundColor: '#2C5FB8', flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 16, alignItems: 'center', paddingVertical: 16}}>
<View style={{width: 72, height: 32, backgroundColor: 'pink'}}></View>
<Text style={{fontWeight: 'bold', fontSize: 16, color: 'white'}}>Rp. 50.000</Text>
</View>
{/* Lower Header Section */}
<View style={{borderBottomLeftRadius: 4, borderBottomRightRadius: 4, backgroundColor: '#2F65BD', flexDirection: 'row', justifyContent: 'space-around', paddingTop: 20, paddingBottom: 12}}>
<ImageTextMV title='Header Menu 1'/>
<ImageTextMV title='Header Menu 2'/>
<ImageTextMV title='Header Menu 3'/>
<ImageTextMV title='Header Menu 4'/>
</View>
</View>
{/* Main DOPE Section */}
<DopeSection dopeItems={dopeItems}/>
{/* Separator */}
<SeparatorAV customHeight={16} customMarginTop={16}/>
{/* Banner Section */}
{/* paddingBottom to add Bottom Border */}
<BannerTitleSubtitleButton title='Banner Title' subtitle='Banner Subtitle' buttonTitle='Banner Button'/>
{/* Card View */}
<CardView title='Card Title' subtitle='Card Subtitle' buttonTitle='Card Button'/>
{/* Horizontal Collection */}
<CollectionViewWithTitleMore title='Collection Title' linkTitle='More'/>
</ScrollView>
{/* TabBar Section */}
<TabBarController onPress={() => this.props.navigation.navigate('Account')}/>
</SafeAreaView>
);
}
}
export default Home;
|
import React, { Component } from 'react'
import {Switch, Route, withRouter} from 'react-router-dom';
import Home from '../components/Home/Home';
import ChatboxUser from '../components/ChatboxUser/ChatboxUser';
import { connect } from 'react-redux';
import Wall from '../components/Wall';
import ProfileUser from '../components/ProfileUser/ProfileUser'
import Congratulation from '../components/Congratulations/Congratulation';
class PublicRouter extends Component {
render() {
return (
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/chatbox/:name" component={ChatboxUser}/>
<Route exact path="/wall" component={Wall}/>
<Route exact path="/user/:name" component={ProfileUser}/>
<Route exact path="/congratulation/:name" component={Congratulation}/>
</Switch>
)
}
}
const mapDispatchToProps = dispatch => ({
})
const mapStateToProps = state => ({
...state
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(PublicRouter));
|
'use strict';
/**
* @ngdoc function
* @name ngloginApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the ngloginApp
*/
var app = angular.module('ngloginApp');
app.controller('MainCtrl',['$scope','APIService','APIConfig','$window','$cookies', function ($scope,APIService,APIConfig,$window,$cookies) {
$scope.user;
var api = APIService;
$scope.prev_url = $cookies.get('url');
// api.service('user').id(49).delete().then();
$scope.goBack = function(){
$window.location.href = $cookies.get('url');
console.log($cookies.get('url'));
}
}]);
|
if(typeof window !== 'undefined') {
var Promise = window.Promise || require('es6-promise').Promise;
} else if(typeof global !== 'undefined') {
var Promise = global.Promise || require('es6-promise').Promise;
}
// BSON Types
var Long = require('./bson/long'),
Binary = require('./bson/binary'),
Code = require('./bson/code'),
DBRef = require('./bson/db_ref'),
Double = require('./bson/double'),
MaxKey = require('./bson/max_key'),
MinKey = require('./bson/min_key'),
ObjectId = require('./bson/objectid'),
BSONRegExp = require('./bson/regexp'),
Symbol = require('./bson/symbol'),
Timestamp = require('./bson/timestamp'),
base64encode = require('./base64').encode;
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if(draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
var nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if(arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if(queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
// Extended JSON
var serialize = function(doc) {
var obj = {};
for(var name in doc) {
if(doc[name] instanceof Binary) {
obj[name] = {
$binary: base64encode(doc[name].buffer),
$type: doc[name].sub_type.toString('hex')
}
} else if(doc[name] instanceof Date) {
obj[name] = {
$date: doc[name].toISOString()
}
} else if(doc[name] instanceof Timestamp) {
obj[name] = {
$timestamp: {
t: doc[name].high_, i: doc[name].low_
}
}
} else if(doc[name] instanceof BSONRegExp) {
obj[name] = {
$regexp: doc[name].pattern, $options: doc[name].options.join('')
}
} else if(doc[name] instanceof ObjectId) {
obj[name] = {
$oid: doc[name].toString()
}
} else if(doc[name] instanceof DBRef) {
obj[name] = {
$ref: doc[name].namespace,
$id: doc[name].oid.toString()
}
} else if(doc[name] == 'undefined') {
obj[name] = {
$undefined: true
}
} else if(doc[name] instanceof MinKey) {
obj[name] = {
$minKey: 1
}
} else if(doc[name] instanceof MaxKey) {
obj[name] = {
$maxKey: 1
}
} else if(doc[name] instanceof Long) {
obj[name] = {
$numberLong: doc[name].toString()
}
} else if(doc[name] instanceof Code) {
obj[name] = {
$code: doc[name].code.toString(),
$scope: serialize(doc[name].scope)
}
} else if(doc[name] instanceof Double) {
obj[name] = {
$double: doc[name].value
}
} else if(doc[name] instanceof Symbol) {
obj[name] = {
$symbol: doc[name].value
}
} else if(Array.isArray(doc[name])) {
// obj[name] = serialize(doc[name]);
var values = serialize(doc[name]);
// Create empty array
obj[name] = new Array(doc[name].length);
// Map the values back into the array
for(var i = 0; i < doc[name].length; i++) {
obj[name][i] = values[i];
}
} else if(doc[name] != null && typeof doc[name] == 'object') {
obj[name] = serialize(doc[name]);
} else {
obj[name] = doc[name];
}
}
return obj;
}
module.exports = {
Promise: Promise,
nextTick: nextTick,
serialize: serialize
};
|
// Controls the logic for determining which membership lists should be synced and
// handles the sequence of events until the lists are in sync.
"use strict";
var Promise = require("bluebird");
var promiseutil = require("../promiseutil");
var matrixToIrc = require("./matrix-to-irc.js");
var ircLib = require("../irclib/irc.js");
var matrixLib = require("../mxlib/matrix");
var MatrixUser = require("../models/users").MatrixUser;
var store = require("../store");
var log = require("../logging").get("membershiplists");
module.exports.sync = function(server) {
if (!server.isMembershipListsEnabled()) {
log.info("%s does not have membership list syncing enabled.", server.domain);
return;
}
if (!server.shouldSyncMembershipToIrc("initial")) {
log.info("%s shouldn't sync initial memberships to irc.", server.domain);
return;
}
log.info("Checking membership lists for syncing on %s", server.domain);
var start = Date.now();
var rooms;
getSyncableRooms(server).then(function(syncRooms) {
rooms = syncRooms;
log.info("Found %s syncable rooms (%sms)", rooms.length, Date.now() - start);
start = Date.now();
log.info("Joining Matrix users to IRC channels...");
return joinMatrixUsersToChannels(rooms, server);
}).then(function() {
log.info("Joined Matrix users to IRC channels. (%sms)", Date.now() - start);
// NB: We do not need to explicitly join IRC users to Matrix rooms
// because we get all of the NAMEs/JOINs as events when we connect to
// the IRC server. This effectively "injects" the list for us.
start = Date.now();
log.info("Leaving IRC users from Matrix rooms (cleanup)...");
return leaveIrcUsersFromRooms(rooms, server);
}).done(function() {
log.info("Left IRC users from Matrix rooms. (%sms)", Date.now() - start);
}, function(err) {
log.error("Failed to sync membership lists: %s", err);
});
};
module.exports.getChannelsToJoin = function(server) {
log.debug("getChannelsToJoin => %s", server.domain);
var defer = promiseutil.defer();
// map room IDs to channels on this server.
getSyncableRooms(server).then(function(rooms) {
var promises = [];
var channels = {}; // object for set-like semantics.
rooms.forEach(function(room) {
promises.push(store.rooms.getIrcChannelsForRoomId(room.roomId).then(
function(ircRooms) {
ircRooms = ircRooms.filter(function(ircRoom) {
return ircRoom.server.domain === server.domain;
});
ircRooms.forEach(function(ircRoom) {
channels[ircRoom.channel] = true;
log.debug(
"%s should be joined because %s real Matrix users are in room %s",
ircRoom.channel, room.reals.length, room.roomId
);
if (room.reals.length < 5) {
log.debug("These are: %s", JSON.stringify(room.reals));
}
});
}));
});
promiseutil.allSettled(promises).then(function() {
var chans = Object.keys(channels);
log.debug(
"getChannelsToJoin => %s should be synced: %s",
chans.length, JSON.stringify(chans)
);
defer.resolve(chans);
});
});
return defer.promise;
};
// map irc channel to a list of room IDs. If all of those
// room IDs have no real users in them, then part the bridge bot too.
module.exports.checkBotPartRoom = function(ircRoom, req) {
if (ircRoom.channel.indexOf("#") !== 0) {
return; // don't leave PM rooms
}
var irc = ircLib.getIrcLibFor(req);
store.rooms.getMatrixRoomsForChannel(ircRoom.server, ircRoom.channel).done(
function(matrixRooms) {
if (matrixRooms.length === 0) {
// no mapped rooms, leave the channel.
irc.partBot(ircRoom);
}
else if (matrixRooms.length === 1) {
// common case, just hit /state rather than slow /initialSync
var roomId = matrixRooms[0].roomId;
var mxLib = matrixLib.getMatrixLibFor(req);
mxLib.roomState(roomId).done(function(res) {
var data = getRoomMemberData(ircRoom.server, roomId, res);
log.debug(
"%s Matrix users are in room %s", data.reals.length, roomId
);
if (data.reals.length === 0) {
irc.partBot(ircRoom);
}
}, function(err) {
log.error("Failed to hit /state for %s", roomId);
});
}
else {
// hit initial sync to get list
getSyncableRooms(ircRoom.server).done(function(syncableRooms) {
matrixRooms.forEach(function(matrixRoom) {
// if the room isn't in the syncable rooms list, then we part.
var shouldPart = true;
for (var i = 0; i < syncableRooms.length; i++) {
if (syncableRooms[i].roomId === matrixRoom.roomId) {
shouldPart = false;
break;
}
}
if (shouldPart) {
irc.partBot(ircRoom);
}
});
}, function(err) {
log.error("Failed to hit /initialSync : %s", err);
});
}
}, function(err) {
log.error(
"Cannot get matrix rooms for channel %s: %s", ircRoom.channel, err
);
});
};
// grab all rooms the bot knows about which have at least 1 real user in them.
function getSyncableRooms(server) {
var mxLib = matrixLib.getMatrixLibFor();
var defer = promiseutil.defer();
// hit /initialSync on the bot to pull in room state for all rooms.
mxLib.initialSync().done(function(res) {
var rooms = res.rooms || [];
rooms = rooms.map(function(room) {
return getRoomMemberData(server, room.room_id, room.state);
});
// filter out rooms with no real matrix users in them.
rooms = rooms.filter(function(room) {
return room.reals.length > 0;
});
defer.resolve(rooms);
});
return defer.promise;
}
function joinMatrixUsersToChannels(rooms, server) {
var d = promiseutil.defer();
// filter out rooms listed in the rules
var filteredRooms = [];
rooms.forEach(function(r) {
if (!server.shouldSyncMembershipToIrc("initial", r.roomId)) {
log.debug(
"Skipping room %s according to config rules (matrixToIrc=false)",
r.roomId
);
return;
}
filteredRooms.push(r);
});
log.debug("%s rooms passed the config rules", filteredRooms.length);
// map the filtered rooms to a list of users to join
// [Room:{reals:[uid,uid]}, ...] => [{uid,roomid}, ...]
var entries = [];
filteredRooms.forEach(function(r) {
r.reals.forEach(function(uid, index) {
entries.push({
roomId: r.roomId,
userId: uid,
// Mark the first real matrix user f.e room so we can inject
// them first to get back up and running more quickly when there
// is no bot.
frontier: (index === 0)
});
});
});
// sort frontier markers to the front of the array
entries.sort(function(a, b) {
if (a.frontier && !b.frontier) {
return -1; // a comes first
}
else if (b.frontier && !a.frontier) {
return 1; // b comes first
}
return 0; // don't care
});
log.debug("Got %s matrix join events to inject.", entries.length);
// take the first entry and inject a join event
function joinNextUser() {
var entry = entries.shift();
if (!entry) {
d.resolve();
return;
}
log.debug(
"Injecting join event for %s in %s (%s left) is_frontier=%s",
entry.userId, entry.roomId, entries.length, entry.frontier
);
injectJoinEvent(entry.roomId, entry.userId).finally(function() {
joinNextUser();
});
}
joinNextUser();
return d.promise;
}
function leaveIrcUsersFromRooms(rooms, server) {
return Promise.resolve();
}
function getRoomMemberData(server, roomId, stateEvents) {
stateEvents = stateEvents || [];
var data = {
roomId: roomId,
virtuals: [],
reals: []
};
stateEvents.forEach(function(event) {
if (event.type !== "m.room.member" || event.content.membership !== "join") {
return;
}
var userId = event.state_key;
if (userId === matrixLib.getAppServiceUserId()) {
return;
}
if (server.claimsUserId(userId)) {
data.virtuals.push(userId);
}
else if (userId.indexOf("@-") === 0) {
// Ignore guest user IDs -- TODO: Do this properly by passing them through
}
else {
data.reals.push(userId);
}
});
return data;
}
function injectJoinEvent(roomId, userId) {
var target = new MatrixUser(userId, null, null);
return matrixToIrc.onJoin({
event_id: "$fake:membershiplist",
room_id: roomId,
state_key: userId,
user_id: userId,
content: {
membership: "join"
},
_injected: true
}, target);
}
|
// Search bar logic
// Tag search bar
const searchBar = document.querySelector("#search-bar");
// Create array of all post containers
const searchArray = Array.from(document.querySelectorAll(".search-container"));
for (let i = 0; i < searchArray.length; i++) {
// Creates empty strings property to hold retrieved values from fields
searchArray[i].strings = [];
const searchTerms = searchArray[i].querySelectorAll(".search-content");
searchTerms.forEach(term => {
const string = term.innerText.toLowerCase();
searchArray[i].strings.push(string);
})
// Combines individual strings into combined searchString value for each record for easy referencing under displayResults
searchArray[i].searchString = searchArray[i].strings.join(" ");
}
// Function for filtering out non-matching results on page
const displayResults = (array, query) => {
// Finds post content that matches
const matchArray = array.filter(item => item.searchString.includes(query));
// Finds post content that doesn't match
const noMatchArray = array.filter(item => !item.searchString.includes(query));
// Displays those that match
matchArray.forEach(item => {
item.classList.add("show");
item.classList.remove("hide");
})
// Hides those that don't match
noMatchArray.forEach(item => {
item.classList.add("hide");
item.classList.remove("show");
})
}
const searchQuery = ({ target }) => {
displayResults(searchArray, target.value.toLowerCase());
}
// Assigns event listener each time key is entered into input
searchBar.addEventListener("input", searchQuery);
|
// @param {number[]} bills
// @return {boolean}
const lemonadeChange = bills => {
const money = {
5: 0,
10: 0
}
if (bills.length === 1 && bills[0] > 5) {
return false;
}
for (let index = 0; index < bills.length; index++) {
if (bills[index] === 5) {
money[5]++;
} else if (bills[index] === 10) {
if (money[5]) {
money[5]--;
money[10]++;
} else {
return false;
}
} else if (bills[index] === 20) {
if (money[5] && money[10]) {
money[5]--;
money[10]--;
} else if (!money[10] && money[5] > 2) {
money[5] -= 3;
} else {
return false;
}
}
}
return true;
};
export default lemonadeChange;
|
import React from 'react';
export const AuthContext = React.useContext();
|
angular.module("starter")
.service("CarsService", function($http){
var url = "http://aluracar.herokuapp.com/";
return {
getList : function(){
return $http.get(url).then(function(res){
return res.data;
});
}
};
});
|
function submitEvent() {
document.addEventListener("submit", (event) => {
event.preventDefault();
const input = document.querySelector(".userName");
const comment = document.querySelector("#userComment");
const commentSection = document.querySelector(".seccionComments");
if (input.value !== "" && comment.value !== "") {
let newComment = document.createElement("div");
newComment.innerHTML += `
<span id="nameP">
${input.value}
<button class="deleteButton">
Delete
</button>
</span>
<p id="commentsTitle">
${comment.value}
</p>
`;
commentSection.appendChild(newComment);
input.value = "";
comment.value = "";
}
});
document.querySelector(".seccionComments").addEventListener("click", (event) => {
if (event.target.matches(".deleteButton")) {
event.target.parentNode.parentNode.remove();
}
});
}
function init() {
submitEvent();
}
init();
|
import m from 'mithril'
export default {
view() {
return m('.access-denied-view', [
m('h2', 'Access Denied')
])
}
}
|
module.exports = {
title: 'ՇՄՅɿՇԹՐԵ',
description: 'Just playing around',
head: [
['link', { rel: 'icon', href: '/logo.png' }],
['link', { rel: 'stylesheet', href: 'https://cdn.jsdelivr.net/gh/rastikerdar/vazir-font@v25.0.0/dist/font-face.css', type: 'text/css' }],
],
themeConfig: {
logo: '/logo.png',
nav: [
{ text: 'Home', link: '/' },
{ text: 'Python', link: '/python/' },
{ text: 'External', link: 'https://google.com' },
{
text: 'Languages',
ariaLabel: 'Language Menu',
items: [
{ text: 'Chinese', link: '/language/chinese/' },
{ text: 'Japanese', link: '/language/japanese/' },
],
},
],
lastUpdated: 'Last Updated',
sidebar: 'auto',
},
}
|
const config = require('config');
const Sequelize = require('sequelize');
const userModel = require('./models/user');
const serviceModel = require('./models/service');
const priceModel = require('./models/price');
const timingModel = require('./models/timing');
const bookingModel = require('./models/booking');
const slotModel = require('./models/slot');
const { logger } = require('./utils');
const dbConfig = config.get('dbConfig');
const db = new Sequelize(
`${dbConfig.dialect}://${dbConfig.username}:${dbConfig.password
}@${dbConfig.host}:${dbConfig.port}/${dbConfig.name}`, {
logging: false,
},
);
const User = userModel(db, Sequelize);
const Service = serviceModel(db, Sequelize);
const Price = priceModel(db, Sequelize);
const Timing = timingModel(db, Sequelize);
const Booking = bookingModel(db, Sequelize);
const Slot = slotModel(db, Sequelize);
db
.authenticate()
.then(() => {
logger.info('DB connection has been established successfully.');
})
.catch((err) => {
logger.error('Unable to connect to the database:', err);
});
module.exports = {
db,
User,
Service,
Price,
Timing,
Booking,
Slot
}
|
/**
* https://postcss.org/
* @type {Object}
*/
module.exports = {
plugins: [
require('postcss-import'),
require('autoprefixer'),
require('postcss-preset-env')({
stage: 3
}),
require('cssnano')({
preset: 'default'
}),
require('postcss-reporter')({
clearReportedMessages: true
})
]
}
|
const path = require("path");
const express = require("express");
const app = express();
const port = process.env.PORT || 3000;
const users = {
1: { name: "Sophie" },
2: { name: "Raya" },
3: { name: "Revital" },
};
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.get("/books/:id", (req, res) => {
const { id } = req.params;
const currentBook = users[id];
if (!currentBook) {
return res.sendStatus(404);
}
res.render("book", {
title: `My book ${currentBook.name}`,
h1: `Welcome`,
h2: `${currentBook.name}!!!!`,
});
});
app.get("/users/:id", (req, res) => {
const { id } = req.params;
const currentUser = users[id];
if (!currentUser) {
return res.sendStatus(404);
}
res.setHeader("Content-Type", "text/html");
res.send(`
<html>
<body>
<h1>
Hello ${currentUser.name}
</h1>
</body>
</html>
`);
});
app.listen(port, () => console.log(`Server listening on port ${port}`));
|
var mobileNav = (function($) {
var self = this;
var init = function() {
_bind();
};
var _bind = function() {
$('.burger-icon').on('click', function() {
$('.burger-icon, .js-mobile-nav').toggleClass('menu-active');
$('body').toggleClass('disabled');
});
};
return {
init: init
};
})(jQuery);
|
var searchData=
[
['evenement',['Evenement',['../classEvenement.html',1,'']]]
];
|
import React, { PureComponent } from 'react';
import App from './component/App';
import Login from "./component/account/Login";
class Start extends PureComponent {
render() {
let Auth = localStorage.getItem('Auth') !== null ?
localStorage.getItem('Auth'): false
return (
<div>
{
Auth === false ?
<Login />:
<App/>
}
</div>
);
}
}
export default Start;
|
import { connect } from "react-redux";
import Search from "../components/Search";
import { fetchVideo, changeSearchText } from "../actions/actions";
const mapStateToProps = state => ({
searchText: state.searchText,
videos: state.videos
});
const mapDispatchToProps = dispatch => ({
fetchYoutubeVideo: searchText => dispatch(fetchVideo(searchText)),
setSearchText: searchText => dispatch(changeSearchText(searchText))
});
export default connect(mapStateToProps, mapDispatchToProps)(Search);
|
var primeraCarga = true;
$(document).ready(function () {
var tabla = $('#tb-clientes');
$('#btn-buscar').button();
$('#btn-limpiar').button();
$('#btn-crear').button();
$('#btn-limpiar').click(function () {
$('#txt-nombre').val("");
$('#txt-carnet').val("");
ObtenerEmpresaPorDefecto();
});
$('#btn-buscar').click(function () {
tabla.table('update');
});
$('#btn-crear').click(function () {
PopUpCrear();
});
///// Combos /////
$('#cbx-empresa').combobox(DefaultCombobox({
url: SiteUrl + 'Parametrico/SimpleSearchEmpresas',
}));
ObtenerEmpresaPorDefecto();
$('#cbx-empresa').combobox('disableText');
//////////// TABLA //////////////////////
tabla.table({
bInfo: true,
bJQueryUI: true,
responsive: {
details: {
type: 'inline'
}
},
aaSorting: [[6, 'asc']],
aoColumns: [
{
sTitle: Globalize.localize('ColumnId'),
sWidth: "70px",
bSortable: false
},
{
sTitle: Globalize.localize('ColumnCarnet'),
sWidth: "50px",
bSortable: false
},
{
sTitle: Globalize.localize('ColumnNombre'),
sWidth: "170px",
bSortable: false
},
{
sTitle: Globalize.localize('ColumnTelefono'),
sWidth: "50px",
bSortable: false
},
{
sTitle: Globalize.localize('ColumnEmail'),
sWidth: "100px",
bSortable: false
},
{
sTitle: Globalize.localize('ColumnActivo'),
sWidth: "50px",
bSortable: false
},
{
sTitle: Globalize.localize('ColumnAcciones'),
sWidth: "100px",
bSortable: false
},
],
bServerSide: true,
sAjaxSource: SiteUrl + 'Cliente/Buscar',
fnRowCallback: function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$('.btn-editar', nRow).click(function () {
PopUpEditar($(nRow).data('data').Cliente.Id);
});
/******************************************************************/
$('.chk-activo', nRow)
.click(function () {
var dataRow = $(nRow).data('data');
var checked = $(this).prop('checked');
var data = $.toJSON({ idCliente: dataRow.Cliente.Id, activo: checked});
tabla.block({ message: null });
$.ajax({
url: SiteUrl + 'Cliente/CambiarActivo',
data: data,
success: function (data) {
if (data.HasErrors) {
showErrors(data.Errors);
} else {
if (data.HasWarnings) {
showCustomErrors({
title: Globalize.localize('TextInformacion'),
warnings: data.Warnings
});
} else {
showMessage(Globalize
.localize('MessageOperacionExitosamente'),
true);
tabla.unblock();
}
}
}
});
});
return nRow;
},
fnServerData: function (sSource, aoData, fnCallback) {
var paramsTabla = {};
$.each(aoData,
function (index, value) {
paramsTabla[value.name] = value.value;
});
var params = {};
params.PageIndex = (paramsTabla.iDisplayStart / paramsTabla.iDisplayLength) + 1;
params.ItemsPerPage = paramsTabla.iDisplayLength;
params.OrderColumnPosition = paramsTabla.iSortCol_0;
params.OrderColumnName = decode(paramsTabla.iSortCol_0 - 2,
[
1, 'id',
2, 'Nombre'
]);
params.OrderDirection = paramsTabla.sSortDir_0;
/******************************************************************/
params.IdEmpresa = $('#cbx-empresa').combobox('getId');
params.Nombre = $('#txt-nombre').val();
params.Carnet = $('#txt-carnet').val();
if (primeraCarga)
return;
/******************************************************************/
tabla.block({ message: null });
$.ajax({
url: sSource,
data: $.toJSON(params),
success: function (data) {
tabla.unblock();
if (data.HasErrors) {
showErrors(data.Errors);
} else {
var rows = [];
$.each(data.Data,
function (index, value) {
var row = [];
var tempAcciones = '<div class="box-icons">';
tempAcciones += '<span title="' +
Globalize.localize('TextEditar') +
'" class="btn-editar ui-icon ui-icon-pencil"></span>';
tempAcciones += '</div>';
row.push(value.Cliente.Id);
row.push(value.Cliente.Carnet);
row.push(value.Cliente.NombreCompleto);
row.push(value.Cliente.Telefono);
row.push(value.Cliente.Email);
row.push('<input class="chk-activo" type="checkbox" ' + (value.Cliente.Activo ? 'checked="checked"' : '')
+ ' >');
row.push(tempAcciones);
rows.push(row);
});
fnCallback({
"sEcho": paramsTabla.sEcho,
"aaData": rows,
"iTotalRecords": data.Pagination.TotalDisplayRecords,
"iTotalDisplayRecords": data.Pagination.TotalRecords
});
tabla.table('setData', data.Data);
}
}
});
}
});
});
/////////////////// PopUp Crear /////////////////////////
function PopUpCrear() {
//$.blockUI({ message: null });
var popup = null;
var buttons = {};
/***************************************************************************/
buttons[Globalize.localize('Guardar')] = function () {
var params = {};
params.IdEmpresa = $('#cbx-empresa-crear').combobox('getId');
params.Carnet = $('#txt-carnet-crear').val().trim();
params.Nombres = $('#txt-nombre-crear').val().trim();
params.Apellidos = $('#txt-apellido-crear').val().trim();
params.Telefono = $('#txt-telefono-crear').val().trim();
params.Direccion = $('#txt-direccion-crear').val().trim();
params.Email = $('#txt-email-crear').val().trim();
var warnings = new Array();
if (isEmpty(params.Carnet))
warnings.push(Globalize.localize('ErrorNoCarnet'));
if (isEmpty(params.Nombres))
warnings.push(Globalize.localize('ErrorNoNombres'));
if (isEmpty(params.Apellidos))
warnings.push(Globalize.localize('ErrorNoApellidos'));
if (isEmpty(params.Telefono))
warnings.push(Globalize.localize('ErrorNoTelefono'));
//if (isEmpty(params.Email))
// warnings.push(Globalize.localize('ErrorNoEmail'));
if (warnings.length > 0) {
showCustomErrors({
title: Globalize.localize('TextInformacion'),
warnings: warnings
});
return false;
} else {
$.blockUI({ message: null });
$.ajax({
url: SiteUrl + 'Cliente/Guardar',
data: $.toJSON(params),
success: function (data) {
$.unblockUI();
if (data.HasErrors) {
showErrors(data.Errors);
} else {
if (data.HasWarnings) {
showCustomErrors({
title: Globalize.localize('TextInformacion'),
warnings: data.Warnings
});
} else {
showMessage(Globalize
.localize('MessageOperacionExitosamente'),
true);
popup.dialog('close');
$('#tb-clientes').table('update');
}
}
}
});
}
};
buttons[Globalize.localize('Cerrar')] = function () {
popup.dialog('close');
};
/***************************************************************************/
showPopupPage({
title: Globalize.localize('TituloPopUp'),
url: SiteUrl + 'Cliente/PopUpCrear',
open: function (event, ui) {
popup = $(this);
//$.unblockUI();
},
buttons: buttons,
heigth: 500,
width: 800
}, false, function () {
///// Combos /////
$('#cbx-empresa-crear').combobox(DefaultCombobox({
url: SiteUrl + 'Parametrico/SimpleSearchEmpresas',
fnSelect: function () {
},
}));
$('#cbx-empresa-crear').combobox('disableText');
$.blockUI();
$.ajax({
url: SiteUrl + 'Parametrico/GetEmpresaPorDefecto',
success: function (res) {
$.unblockUI();
$('#cbx-empresa-crear')
.combobox('setId', res.Data.Empresa.Id)
.combobox('setValue', res.Data.Empresa.Nombre)
.combobox('setData', res.Data.Empresa);
}
});
});
}
/////////////////// PopUp Editar /////////////////////////
function PopUpEditar(idCliente) {
//$.blockUI({ message: null });
var popup = null;
var buttons = {};
/***************************************************************************/
buttons[Globalize.localize('Guardar')] = function () {
var params = {};
params.IdCliente = idCliente;
params.Carnet = $('#txt-carnet-crear').val().trim();
params.Nombres = $('#txt-nombre-crear').val().trim();
params.Apellidos = $('#txt-apellido-crear').val().trim();
params.Telefono = $('#txt-telefono-crear').val().trim();
params.Direccion = $('#txt-direccion-crear').val().trim();
params.Email = $('#txt-email-crear').val().trim();
var warnings = new Array();
if (isEmpty(params.Carnet))
warnings.push(Globalize.localize('ErrorNoCarnet'));
if (isEmpty(params.Nombres))
warnings.push(Globalize.localize('ErrorNoNombres'));
if (isEmpty(params.Apellidos))
warnings.push(Globalize.localize('ErrorNoApellidos'));
if (isEmpty(params.Telefono))
warnings.push(Globalize.localize('ErrorNoTelefono'));
//if (isEmpty(params.Email))
// warnings.push(Globalize.localize('ErrorNoEmail'));
if (warnings.length > 0) {
showCustomErrors({
title: Globalize.localize('TextInformacion'),
warnings: warnings
});
return false;
} else {
$.blockUI({ message: null });
$.ajax({
url: SiteUrl + 'Cliente/Guardar',
data: $.toJSON(params),
success: function (data) {
$.unblockUI();
if (data.HasErrors) {
showErrors(data.Errors);
} else {
if (data.HasWarnings) {
showCustomErrors({
title: Globalize.localize('TextInformacion'),
warnings: data.Warnings
});
} else {
showMessage(Globalize
.localize('MessageOperacionExitosamente'),
true);
popup.dialog('close');
$('#tb-clientes').table('update');
}
}
}
});
}
};
buttons[Globalize.localize('Cerrar')] = function () {
popup.dialog('close');
};
/***************************************************************************/
showPopupPage({
title: Globalize.localize('TituloPopUp'),
url: SiteUrl + 'Cliente/PopUpCrear',
open: function (event, ui) {
popup = $(this);
// $.unblockUI();
},
buttons: buttons,
heigth: 500,
width: 800
}, false, function () {
$.blockUI({ message: null });
///// Combos /////
$('#cbx-empresa-crear').combobox(DefaultCombobox({
url: SiteUrl + 'Parametrico/SimpleSearchEmpresas',
fnSelect: function () {
},
}));
$('#cbx-empresa-crear').combobox('disable');
$.ajax({
url: SiteUrl + 'Cliente/Obtener',
data: $.toJSON({ idCliente: idCliente }),
success: function (data) {
$.unblockUI();
if (data.HasErrors) {
showErrors(data.Errors);
} else {
if (data.HasWarnings) {
showCustomErrors({
title: Globalize.localize('TextInformacion'),
warnings: data.Warnings
});
} else {
$('#txt-carnet-crear').val(data.Data.Cliente.Carnet);
$('#txt-nombre-crear').val(data.Data.Cliente.Nombres);
$('#txt-apellido-crear').val(data.Data.Cliente.Apellidos);
$('#txt-telefono-crear').val(data.Data.Cliente.Telefono);
$('#txt-direccion-crear').val(data.Data.Cliente.Direccion);
$('#txt-email-crear').val(data.Data.Cliente.Email);
$('#cbx-empresa-crear')
.combobox('setId', data.Data.Cliente.Empresa.Id)
.combobox('setValue', data.Data.Cliente.Empresa.Nombre)
.combobox('setData', data.Data.Cliente.Empresa);
}
}
}
});
});
}
function ObtenerEmpresaPorDefecto() {
$.blockUI();
$.ajax({
url: SiteUrl + 'Parametrico/GetEmpresaPorDefecto',
success: function (res) {
$.unblockUI();
$('#cbx-empresa')
.combobox('setId', res.Data.Empresa.Id)
.combobox('setValue', res.Data.Empresa.Nombre)
.combobox('setData', res.Data.Empresa);
if (primeraCarga) {
primeraCarga = false;
$('#tb-clientes').table('update');
}
}
});
}
|
// get img in slider-contrainer
// هجمع كل الصور بتعتي في اراي و علشان فيما بعد ابقي اختار منهم اللي انا عاوزة و لما ازود واحد علي الاندكس بتاع صورة معينة يجبلي اللي بعها و هاكذا
var sliderImages = Array.from(document.querySelectorAll('.slider-container img')); // الارايفروم بتستخدمها علشان تجيب العناصر اللي هتحطها بين الاقواس لو استرنج مثلا هتحولك السترنج ل احرف و هتنفز علي كل عنصر من العناصر اللي هتحطها في الاراي الفانكشن او الايرو فانكشن اللي هتكون بعد الكوما لو انت عاوزتنفز علي كل عنصر من عناصر الاراي حاجة معينة
// get numbers of slides or image in this array
// لازم اجيب عدد العناصر او عدد الصور اللي في الاراي بتعتي علشان اثدر اعرف هعمل كام ال اي في الليست علشان لما ادوس علي الال اي دي او اللي بنسميها البادجينيشن بجبلي صورة معينة من اللي في الاراي دي فلازم علشان اعمل دا كلو اكون عارف عدد الصوراللي انا جبتهم في الاراي دي
var slidesCount = sliderImages.length;
// first slide will show or main slide
// السليدر دا اللي عي اساسو هيجيب الاندكس بتاعو و بعدين يزود واحد لما يضغط علي النيكست فهيجبلو الصورة اللي بعدهاولازم ابدا فلازم احدد السليد اللي هوا اول سليد هيظهر علشان بقي اكمل بعد كدا لما يدوس علي حاجة يجيب السليد دا و يشوف افاندكس بتاعي و يزود علية واحد او يقلل منو واحد او كدا
var currentSlideIndex = parseInt(localStorage.getItem('slideNum')) || 1;
// get slider number element that show the number of current slide or img
var sliderNumberElement = document.getElementById('slide-number');
// previous and next buttons
var nextButton = document.getElementById('next');
var prevButton = document.getElementById('prev');
// handle onclick on previous and next button
nextButton.onclick = nextSlider;
prevButton.onclick = prevSlider;
// create ul pagination list and set id
var paginationElement = document.createElement('ul');
paginationElement.setAttribute('id', 'pagination-ul');
// create lis
for (var i = 1; i <= slidesCount; i++) { // or // var i = 0; i < slidesCount // or i < sliderImages.length
var li = document.createElement('li');
// var fullLi = li.appendChild(document.createTextNode(i)); // dont fo that
li.appendChild(document.createTextNode(i));
li.setAttribute('data-index', i);
paginationElement.appendChild(li); // or // prependChild to set li in the ferst but appendChild set li in the last
} // add the full ul to the span indicators
document.getElementById('indicators').appendChild(paginationElement);
// get the paginationElement ul
var paginationCreatedUl = document.getElementById('pagination-ul');
var paginationBullets = Array.from(document.querySelectorAll('#pagination-ul li'));
// loop through all bullets items
for (var i = 0; i < paginationBullets.length; i++) {
paginationBullets[i].onclick = function() { // we can use addEventListener
currentSlideIndex = parseInt(this.getAttribute('data-index')); /* law makatabtesh this elfanekshan mesh hateshta8al lazem hena tektab this */ // استخدمنا بارس انت علشان الرقم لما يرجع هيكون استرنج و اخنا عاوزين نحولو لقم مش استنرج ممكن منعملهاش بس كدا صح الصح
theChecker();
}
}
// trigger the checker function
/* لازم هنا تشغل الفانكشن علشان تبدا و تظهرلك الصورة علي حسب الكارنت سليد اندكس اللي انت حددتو لانك لو مشغلتش الفانكشن هيكون كل الصور الاوباستي بتاعتها صفر و كمان كل لازم حد يضغط علي النكس او اي زرار علشان الفانكشن تشتغل و يظهر صور و دا مش كويس فانت لازم تشغلها علشان تبدا تاخد الكارنت اندكس و تدي كلاس اكتيف للصورة و كلاس اكتيف للبوليت و كلاس ديسيبول للنكست او للبريفس لو كانت اول او اخر صورة */
theChecker()
// next slide function
function nextSlider() {
if (nextButton.classList.contains('disabled')) {
// do nothing
return false
} else {
currentSlideIndex ++;
theChecker();
}
}
// or
/*function nextSlider() {
if (currentSlideIndex == slidesCount) {
return false
} else {
currentSlideIndex ++;
theChecker()
}
}*/
// previous slide function
function prevSlider() {
if (prevButton.classList.contains('disabled')) {
// do nothing
return false
} else {
currentSlideIndex --;
theChecker();
}
}
// or
/*function prevSlider() {
if (currentSlideIndex == 1) {
return false
} else {
currentSlideIndex --;
theChecker()
}
}*/
// create the checker function
function theChecker() {
// set the slide number
sliderNumberElement.textContent = "slide # " + (currentSlideIndex) + ' of ' + (slidesCount); // sliderImages.length
// remove active class from imf and bullets
removeAllActive();
// set active class on current slide
sliderImages[currentSlideIndex - 1].classList.add('active');
// set active class on the current li or pagination item
paginationCreatedUl.children[currentSlideIndex - 1].classList.add('active'); // or // document.querySelectorAll('li')[currentSlideIndex - 1].classList.add('active');;
// check if the current slide is the first or the last
if (currentSlideIndex == 1) {
// add sisable class on the previous button
prevButton.classList.add('disabled');
} else {
prevButton.classList.remove('disabled');
}
if (currentSlideIndex == slidesCount) { // sliderImages.length
// add sisable class on the previous button
nextButton.classList.add('disabled');
} else {
nextButton.classList.remove('disabled');
}
// or
/* if (currentSlideIndex == 1) {
prevButton.classList.add('disabled');
} else if (currentSlideIndex == slidesCount) {
nextButton.classList.add('disabled');
} else {
prevButton.classList.remove('disabled');
nextButton.classList.remove('disabled');
} */
localStorage.setItem('slideNum', currentSlideIndex);
}
/* كدا الفانكشن بتكتبلي السليدر الحالي رقمو كام و بتضيف للسليدر الحالي كلاس اكتيف و بتضيف للال اي الحالي كلاس اكتف بس لسا المفروض انك تعمل برضو جوا الفانكشن دي اول ما تضغط علي الزرار او الال اي او كدا يبدا يشيل كل الكلاسات الموضودة حاليا لانك لو معملتش كدا هيبدا يضيف كلاس اكتيف علي اللي علية الدور و بالتالي هيكون في 2 ال اي و اتنين صورة عليهم كلاس الاككتف دا و دا مش صح و كمان المفروض تبدا تشيك هل العنصر دا او الال اي دا هوا اخر واحد علشان لو اخر واحد او اول واحد تبدا تحط وية تنسيقال واللي هيا كلاس الديسبلاي علشان فية تنسيقات بتخلي الكارسر يتحول لاكس كدا علاشن مش يعرف يقلب لانو اخر حاجة او اول حاجة */
// remove active classfrom images and bullets
function removeAllActive() {
sliderImages.forEach(function(img) { // we can use arrow function
img.classList.remove('active');
});
// or
// for (img of sliderImages) {
// img.classList.remove('active');
// }
// or
// Array.from(sliderImages,(img) => {img.classList.remove('active');})
var paginationBullets = Array.from(document.querySelectorAll('#pagination-ul li'));
paginationBullets.forEach((bullet) => {bullet.classList.remove('active')}); // we can use arrow function
// or
// document.querySelectorAll('#pagination-ul li').forEach(function(bullets) {
// bullets.classList.remove('active');
// });
// or
// use for of loop or use Array.from
// Array.from(document.querySelectorAll('#pagination-ul li'), (bullet) => bullet.classList.remove('active'))
}
|
// 导入vue文件
import Vue from 'vue'
// 导入路由
import VueRouter from 'vue-router'
// 导入login组件
import Login from '../views/login/index.vue'
// 导入home主页面组件
import Home from '../views/home/home.vue'
// 注册路由
Vue.use(VueRouter)
// 实例化路由
const router = new VueRouter({
// 规定路由规则
routes: [
{ path: '/', name: 'home', component: Home },
{ path: '/login', name: 'login', component: Login }
]
})
// 导出路由
export default router
|
var sum = function(x, y) { return x + y; }
var square = function(x) { return x * x; }
var data = [1, 1, 3, 5, 5];
var mean = data.reduce(sum)/data.length;
var deviations = data.map(function(x){ return x - mean });
var stddev = Math.sqrt(deviations.map(square).reduce(sum)/(data.length-1));
console.log(`mean: ${mean}, stddev: ${stddev}`);
|
import request from '@/utils/request'
// 重点人员列表接口
export function getList(params) {
return request({
url: 'KeyPersonnel/list',
method: 'get',
params: params
})
}
// 打标签(已阅)
export function updateStatus(params) {
return request({
url: `KeyPersonnel/updateStatus/${params}`,
method: 'get',
})
}
|
import {
LOAD_ADMIN_USER_LIST,
} from '@/web-client/actions/constants';
import {
pick,
flow,
isPlainObject,
filter,
uniqBy,
map,
cond,
negate,
constant,
stubTrue,
isArray,
} from 'lodash/fp';
const pickUserFields = pick([
'id', 'name',
]);
const processUserList = flow([
filter(isPlainObject),
uniqBy('id'),
map(pickUserFields),
]);
const userListProcessor = (defaultValue) => cond([
[negate(isArray), constant(defaultValue)],
[stubTrue, processUserList],
]);
const orderUserList = (state = [], {type, payload}) => {
if (type === LOAD_ADMIN_USER_LIST) {
return userListProcessor(state)(payload);
}
return state;
};
export default orderUserList;
|
import React from 'react';
import {
Wrapper,
ArtistName,
ArtworkTitle,
ArtworkMedium,
ArtworkDescription,
ArtworkCopyright
} from './styles';
import dayjs from 'dayjs';
const ArtistInfo = ({
artist,
imageDescription,
dateTime,
copyright,
userComment
}) => (
<Wrapper>
<ArtistName>{artist ? artist : 'Unknown Artist'}</ArtistName>
<ArtworkTitle>
{imageDescription ? imageDescription : 'Untitled'},{' '}
<span>{dayjs(dateTime).format('YYYY')}</span>
</ArtworkTitle>
<ArtworkMedium>Pixel art on 16x16 grid</ArtworkMedium>
{userComment && <ArtworkDescription>{userComment}</ArtworkDescription>}
{copyright && <ArtworkCopyright>{copyright}</ArtworkCopyright>}
</Wrapper>
);
export default ArtistInfo;
|
export const FETCH_REPOS_START= 'FETCH_REPOS_START';
export const FETCH_REPOS_SUCCESS= 'FETCH_REPOS_SUCCESS';
export const FETCH_REPOS_FAIL= 'FETCH_REPOS_FAIL';
export const FETCH_COMMITS_START= 'FETCH_COMMITS_START';
export const FETCH_COMMITS_SUCCESS= 'FETCH_COMMITS_SUCCESS';
export const FETCH_COMMITS_FAIL= 'FETCH_COMMITS_FAIL';
export const GITHUB_DATA_CLEANUP= 'GITHUB_DATA_CLEANUP';
export const FETCH_ERROR_CLEANESE = 'FETCH_ERROR_CLEANESE';
|
/** @jsx jsx */
import { jsx } from "theme-ui"
import { useState } from "react"
import { GiSoccerBall } from "react-icons/gi"
import { IoIosReturnLeft, IoIosReturnRight } from "react-icons/io"
import { FaAngleDown, FaAngleRight, FaRegCalendarCheck } from "react-icons/fa"
const Match = ({ match }) => {
const [selected, setSelected] = useState(false)
const date = new Date(match.start)
const minutes = date.getMinutes() === 0 ? "00" : `${date.getMinutes()}`
const hours = `${date.getHours()}`
return (
<div>
<div
sx={{
display: "grid",
gridTemplateColumns: "10% 30% 20% 30% 10%",
alignItems: "center",
cursor: match.events && match.events.length > 0 ? "pointer" : null,
fontFamily: "body",
fontSize: 4,
borderBottom: "solid 2px",
borderBottomColor: "muted",
fontWeight: "body",
color: selected ? "background" : "text",
bg: selected ? "primary" : "background",
mb: 3,
outline: "none",
}}
role="button"
tabIndex="0"
onClick={() =>
match.events && match.events.length > 0 && setSelected(!selected)
}
onKeyDown={() => match.events && setSelected(!selected)}
>
<div
sx={{
py: 2,
color: match.status !== "ns" ? "primary" : "muted",
textAlign: "center",
}}
>
{match.status && selected ? <FaAngleDown /> : <FaAngleRight />}
</div>
<div>
<div sx={{ textAlign: "right", my: 3, fontSize: 3 }}>
{match.home.team.name || match.home.team.fullName}
</div>
</div>
<div
sx={{
textAlign: "center",
fontWeight: "bold",
fontSize: match.status !== "ns" ? 4 : 2,
}}
>
{match.status !== "ns"
? `${match.home.goals || 0} - ${match.away.goals || 0}`
: `${hours}:${minutes}`}
</div>
<div>
<div sx={{ fontSize: 3 }}>
{match.away.team.name || match.away.team.fullName}
</div>
</div>
<div sx={{ textAlign: "center" }}>
{match.status === "ft" ? (
<FaRegCalendarCheck />
) : match.status === "ht" ? (
match.status
) : match.elapsed ? (
match.elapsed + `'`
) : (
``
)}
</div>
</div>
{selected &&
match.events &&
match.events.map((x, i) => {
const home = x.team._ref === match.home.team.id
return (
<div key={i}>
<div
sx={{
display: "grid",
gridTemplateColumns: "10% 30% 20% 30% 10%",
alignItems: "center",
fontFamily: "body",
fontSize: 3,
}}
>
<div sx={{ textAlign: "center", color: "primary" }}>
{home ? `${x.elapsed} '` : ""}
</div>
<div sx={{ textAlign: "right" }}>
{home ? `${x.player.name || x.player.fullName}` : ""}
</div>
<div
sx={{
textAlign: "center",
pt: 2,
fontSize: 4,
color: "text",
}}
>
<GiSoccerBall />
</div>
<div sx={{ textAlign: "left" }}>
{home ? `` : `${x.player.name || x.player.fullName}`}
</div>
<div sx={{ textAlign: "center", color: "primary" }}>
{" "}
{home ? `` : `${x.elapsed} '`}
</div>
</div>
<div
sx={{
display: "grid",
gridTemplateColumns: "10% 30% 20% 30% 10%",
alignItems: "center",
fontFamily: "body",
fontSize: 3,
borderBottom: "solid 3px",
borderBottomColor:
i + 1 === match.events.length ? "primary" : "muted",
}}
>
<div sx={{ textAlign: "center" }}>{""}</div>
<div sx={{ textAlign: "right" }}>
{home
? `${(x.assist && (x.assist.name || x.assist.fullName)) ||
"-"}`
: ""}
</div>
<div sx={{ textAlign: "center", fontSize: 5 }}>
{home ? <IoIosReturnLeft /> : <IoIosReturnRight />}
</div>
<div sx={{ textAlign: "left" }}>
{home
? ``
: `${(x.assist && (x.assist.name || x.assist.fullName)) ||
"-"}`}
</div>
<div sx={{ textAlign: "center" }}> </div>
</div>
</div>
)
})}
</div>
)
}
export default Match
|
(function () {
'use strict';
/**
* @ngdoc object
* @name archiv2018.controller:Archiv2018Ctrl
*
* @description
*
*/
angular
.module('archiv2018')
.controller('Archiv2018Ctrl', Archiv2018Ctrl);
function Archiv2018Ctrl() {
var vm = this;
vm.ctrlName = 'Archiv2018Ctrl';
}
}());
|
/*
* Origin Builder Project
*
*
*
* Must obtain permission before using this script in any other purpose
*
* or.detect.js
*
*/
( function($){
if( typeof( or ) == 'undefined' ){
console.error('Could not load originbuilder core library');
return;
}
or.detect = {
frame : or.frame !== undefined ? or.frame : {},
holder : null,
ob : null,
locked : false,
clicked : false,
disabled : false,
columnsWidthChanged : false,
bone : ['or_row', 'or_row_inner', 'or_column', 'or_column_inner'],
init : function(){
this.frame.contents = $('#or-live-frame').contents();
this.wrap_node( this.frame.contents.find('body').get(0) );
var main = this.frame.contents.find('#or-element-placeholder');
var get_holder = function( main ){
return{
main : main,
tooltip : main.find('.mpb-tooltip').get(0),
top : main.find('.mpb-top').get(0),
right : main.find('.mpb-right').get(0),
bottom : main.find('.mpb-bottom').get(0),
left : main.find('.mpb-left').get(0)
}
}
this.holder = get_holder( main );
this.holder.row = get_holder( this.frame.contents.find('#or-row-placeholder') );
this.holder.sections = get_holder( this.frame.contents.find('#or-sections-placeholder') );
this.holder.section = get_holder( this.frame.contents.find('#or-section-placeholder') );
this.holder.columns = [];
for( var i = 0; i < 6; i ++ )
this.holder.columns.push( get_holder( this.frame.contents.find('#or-column-'+i+'-placeholder') ) );
this.bone = this.bone.concat( or_maps_views ).concat( or_maps_view );
or.trigger({
el: this.frame.$('.or-boxholder'),
events: {
'[data-action="edit"]:click': function( e ){ or.front.ui.element.edit( or.get.model( e.target ) ); },
'[data-action="double"]:click': function( e ){
if( e.target.getAttribute('data-action') !== undefined && e.target.getAttribute('data-action') == 'copy' )
or.front.ui.element.copy( or.get.model( e.target ) );
else or.front.ui.element.double( or.get.model( e.target ) );
},
'[data-action="add-element"]:click': function( e ){
var pop = or.front.ui.element.add( e.target );
if( $(this).closest('.mpb-bottom').length > 0 )
pop.data({'pos':'bottom'});
else pop.data({'pos':'top'});
},
'.handle-resize:mousedown' : 'col_resize',
'[data-action="col-exchange"]:click' : 'col_exchange',
'[data-action="delete"]:click' : 'delete',
'span.marginer:mousedown': 'marginer'
},
delete : function( e ){
var model = or.get.model( e.target );
if( model !== null && confirm( or.__.sure ) ){
var el = or.detect.frame.$('[data-model="'+model+'"]'),
ob = or.detect.closest( el.parent().get(0) );
el.remove();
if( or.storage[ model ] !== undefined ){
if( or_maps_view.indexOf( or.storage[ model ].name ) > -1 ){
delete or.storage[ model ];
if( ob !== null){
var code = or.front.build_shortcode( ob[1] );
if( code !== '' )
or.front.push( code, ob[1], 'replace' );
}
}else delete or.storage[ model ];
}
or.detect.untarget();
}
},
col_resize : function( e ){
if( e.which !== undefined && e.which !== 1 )
return false;
$('html,body').stop();
var index = $( e.target ).closest('div.or-boxholder').data('col-index'),
holder = or.detect.holder.columns[index],
pholder = or.detect.holder.columns[index-1],
el = or.frame.$('[data-model="'+holder.main.data('model')+'"' ),
width = or.storage[holder.main.data('model')].args.width,
pwidth = or.storage[pholder.main.data('model')].args.width,
mouseUp = function(e){
or.frame.$(or.frame.doc).off('mousemove').off('mouseup');
or.frame.$('html,body').css({cursor:''}).removeClass('noneuser or-resizing-cols');
or.detect.disabled = false;
or.detect.untarget();
or.detect.columns( e.data.el.get(0) );
},
mouseMove = function( e ){
e.preventDefault();
e.data.offset = e.clientX-e.data.left;
var d = e.data,
p1 = (d.width-(d.offset*d.ratio)),
p2 = d.pwidth+(d.offset*d.ratio);
if( p1 > 9 && p2 > 9 ){
// update width of cols
d.el.style.width = p1+'%';
d.pel.style.width = p2+'%';
d.col.style.left = e.data.offset+'px';
d.holder.right.style.height =
d.holder.left.style.height =
d.holder.bottom.style.top =
d.pholder.right.style.height =
d.pholder.left.style.height =
d.pholder.bottom.style.top = d.el.offsetHeight+'px';
// update info
d.einfo.innerHTML = Math.round(p1)+'%';
d.pinfo.innerHTML = Math.round(p2)+'%';
or.storage[d.emodel].args.width = or.tools.nfloat(p1)+'%';
or.storage[d.pmodel].args.width = or.tools.nfloat(p2)+'%';
}
};
$(this).data({ curentWidth: or.storage[holder.main.data('model')].args.width });
or.frame.$('html,body').css({cursor:'col-resize'}).addClass('noneuser or-resizing-cols');
or.detect.disabled = true;
pholder.right.style.display = 'none';
if( width.indexOf('%') > -1 ){
width = parseFloat( width );
}else if( width.indexOf('/') > -1 ){
width = width.split('/');
width = (parseInt(width[0])/parseInt(width[1]))*100;
}
if( pwidth.indexOf('%') > -1 ){
pwidth = parseFloat( pwidth );
}else if( pwidth.indexOf('/') > -1 ){
pwidth = pwidth.split('/');
pwidth = (parseInt(pwidth[0])/parseInt(pwidth[1]))*100;
}
or.frame.$(or.frame.doc)
.on( 'mouseup', {el:el}, mouseUp )
.on( 'mousemove', {
el: el.get(0),
pel: el.prev().get(0),
col: $(e.target).closest('.mpb.mpb-left').get(0),
holder: holder,
pholder: pholder,
einfo: holder.main.find('.col-info').get(0),
pinfo: pholder.main.find('.col-info').get(0),
emodel: holder.main.data('model'),
pmodel: pholder.main.data('model'),
left: e.clientX,
width: width,
pwidth: pwidth,
offset: 1,
ratio: width/el.get(0).offsetWidth
}, mouseMove );
},
col_exchange : function( e ){
var r_col = parseInt( or.detect.frame.$( e.target ).closest('.or-boxholder').data('col-index') ),
r_model = or.detect.holder.columns[ r_col ].model,
l_model = or.detect.holder.columns[ r_col - 1 ].model,
l_el = or.detect.frame.$('[data-model="'+l_model+'"]'),
r_el = or.detect.frame.$('[data-model="'+r_model+'"]'),
cwidth = $(this).closest('.handle-resize').data('curentWidth');;
if( cwidth != or.storage[r_model].args.width )
return;
l_el.stop().animate({ marginLeft: r_el.get(0).offsetWidth, marginRight: -r_el.get(0).offsetWidth });
r_el.stop().animate({ marginLeft: -l_el.get(0).offsetWidth, marginRight: l_el.get(0).offsetWidth }, function(){
l_el.before( r_el );
l_el.css({marginLeft:'',marginRight:''})
r_el.css({marginLeft:'',marginRight:''})
});
or.detect.untarget();
},
marginer : function( e ){
if( e.which !== undefined && e.which !== 1 )
return false;
$('html,body').stop();
var model = or.get.model( e.target ),
el = or.frame.$('[data-model="'+model+'"]'),
value = 0,
direct = $(this).data('direct'),
css = or.detect.get_margin( model, direct ),
mouseUp = function(e){
or.frame.$(or.frame.doc).off('mousemove').off('mouseup');
or.frame.$('html,body').css({cursor:''}).removeClass('noneuser or-resizing-cols');
or.detect.disabled = false;
},
mouseMove = function( e ){
e.preventDefault();
var d = e.data;
d.offset = e.clientY-d.top;
if( d.direct == 'top' ){
or.front.ui.style.element( d.el, d.model, ['margin-top', (d.value+d.offset)+'px'] );
var coor = e.data.el.getBoundingClientRect();
or.detect.holder.main.get(0).style.top = (coor.top+or.detect.frame.window.scrollY)+'px';
$(or.detect.holder.top).find('.marginer').attr({
'data-value': (d.value+d.offset)+'px'
});
}else if( e.data.direct == 'bottom' ){
or.front.ui.style.element( d.el, d.model, ['margin-bottom', (d.value+d.offset)+'px'] );
$(or.detect.holder.bottom).find('.marginer').attr({
'data-value': (d.value+d.offset)+'px'
});
}
};
or.frame.$('html,body').css({cursor:'ns-resize'}).addClass('noneuser or-marginer');
or.detect.disabled = true;
value = parseInt( css.toString().replace(/[^0-9\-]/g,'') );
or.frame.$(or.frame.doc)
.on( 'mouseup', { direct: direct, el: el.get(0), model: model }, mouseUp )
.on( 'mousemove', {
el: el.get(0),
value: value,
direct: direct,
model: model,
top: e.clientY,
offset: 1,
}, mouseMove );
},
});
or.trigger({
el: this.frame.$('#or-footers'),
events: {
'[data-action="browse"]:click' : function( e ){ or.front.ui.element.add( e.target ); },
'[data-action="quick-add"]:click' : function( e ){ or.front.push( $( e.target ).parent().data('content') ); },
'[data-action="custom-push"]:click' : 'custom_push',
'[data-action="paste"]:click' : 'paste',
'[data-action="sections"]:click' : 'sections',
},
custom_push : function(e){
var atts = {
title: or.__.i36,
width: 750,
class: 'push-custom-content',
save_text: 'Push to builder'
},
pop = or.tools.popup.render( e.target, atts );
var copied = or.backbone.stack.get('or_RowClipboard');
if( copied === undefined || copied == '' )
copied = '';
pop.find('.m-p-body').html( or.__.i37+'<p></p><textarea style="width: 100%;height: 300px;">'+copied+'</textarea>');
pop.data({
callback : function( pop ){
var content = pop.find('textarea').val();
if( content !== '' ){
if( content.trim().indexOf('[') !== 0 )
content = '[or_column_text]<p>'+content+'</p>[/or_column_text]';
or.front.push( content );
}
}
});
},
paste : function( e ){
content = or.backbone.stack.get('or_RowClipboard');
if( content === undefined || content == '' || content.trim().indexOf('[') !== 0 ){
content = '[or_column_text]<p>'+or.__.i38+'</p>[/or_column_text]';
}
if( content != '' )
or.front.push( content );
},
sections : function( e ){
or.cfg = $().extend( or.cfg, or.backbone.stack.get('or_Configs') );
var atts = {
title: 'Templates',
width: 950,
class: 'no-footer bg-blur-style section-manager-popup',
},
pop = or.tools.popup.render( e.target, atts ),
arg = {},
sections = $( or.template( 'install-global-sections', arg ) );
if( or.cfg.profile !== undefined )
//pop.find('h3.m-p-header').append( ' - Actived Profile <span class="msg-profile-label-display">'+or.cfg.profile.replace(/\-/g,' ')+'</span>' );
pop.find('.m-p-body').append( sections );
if( typeof arg.callback == 'function' )
arg.callback( sections );
}
});
},
hover : function( e ){
// Disabled inspector
if( or.detect.disabled === true || or.detect.clicked === true || or.detect.trust( e ) === false )
return;
var u = or.detect;
// Find closest or object at target
u.ob = u.closest( e.target );
if( u.ob === null )
return;
// If detect or object at hover target
if( or.storage[ u.ob[1] ] !== undefined && or.detect.bone.indexOf( or.storage[ u.ob[1] ].name ) === -1 ){
u.target( u.ob );
}else{
if( u.ob[1] == '-1' )
this.columns( e.target.parentNode );
else this.columns( e.target );
}
},
click : function( e ){
if( or.detect.disabled === true || or.detect.trust( e ) === false )
return false;
if( e.target === undefined )
return false;
else if( e.target.tagName == 'A' || or.frame.$( e.target ).closest('a').length > 0 )
e.preventDefault();
else if( [ 'INPUT', 'SELECT', 'TEXTAREA' ].indexOf( e.target.tagName ) > -1 ){
return true;
}
if( $(e.target).hasClass('or-add-elements-inner') ){
or.front.ui.element.add( e.target );
return;
}
if( or.detect.locked !== false )
or.detect.locked = false;
or.detect.untarget();
var ob = or.detect.closest( e.target );
if( ob !== null ){
if( ob[1] == '-1' )
var ob = or.detect.closest( ob[0].parentNode );
or.detect.clicked = true;
$('.or-params-popup.wp-pointer-top .m-p-header .sl-close.sl-func').trigger('click');
var name = ( or.storage[ ob[1] ] !== undefined ) ? or.storage[ ob[1] ].name : '';
if( name !== '' ){
var holder;
if( this.bone.indexOf( name ) === -1 )
holder = this.holder;
else if( name == 'or_column' || name == 'or_column_inner' )
holder = this.holder.columns[0];
else if( name == 'or_row' || name == 'or_row_inner' )
holder = this.holder.row;
else if( or_maps_views.indexOf( name ) > -1 )
holder = this.holder.sections;
else if( or_maps_view.indexOf( name ) > -1 )
holder = this.holder.section;
if( this.rect( ob, holder ) === false )
return;
if( or.storage[ ob[1] ] !== undefined && holder.tooltip !== undefined )
holder.tooltip.querySelectorAll('span.label')[0].innerHTML = or.storage[ ob[1] ].name.replace('or_','');
this.build_nav( ob, e );
}
};
return false;
},
dblclick : function( e ){
if( or.detect.disabled === true )
return false;
if( !or.detect.trust( e ) )
return false;
or.detect.click( e );
or.detect.holder.main.find('.sl-pencil').trigger('click');
e.preventDefault();
e.stopPropagation();
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
return false;
},
focus : function( model, hid ){
or.detect.clicked = true;
var ob = [ or.frame.$('[data-model="'+model+'"]').get(0), model ], holder;
if( hid == 'column' )
holder = this.holder.columns[0];
else if( hid == 'element' )
holder = this.holder;
else if( hid == 'row' )
holder = this.holder.row;
else if( hid == 'sections' )
holder = this.holder.sections;
else if( hid == 'section' )
holder = this.holder.section;
holder.main.data({'model':''});
if( this.rect( ob, holder ) === false )
return;
if( or.storage[ ob[1] ] !== undefined )
$(holder.tooltip).find('span.label').html( or.storage[ ob[1] ].name.replace('or_','') );
$(holder.top).find('.marginer').attr({ 'data-value': or.detect.get_margin( ob[1], 'top' ) });
$(holder.bottom).find('.marginer').attr({ 'data-value': or.detect.get_margin( ob[1], 'bottom' ) });
},
trust : function( e ){
if( e.originalEvent === undefined )
return false;
var el = e.target, i,
ignored = [
'or-boxholder',
'wp-core-ui',
'or-params-popup',
'sys-colorPicker',
'or-footers',
'mce-container'
];
while( el !== null && el !== undefined ){
for( i in el.classList ){
if( ignored.indexOf( el.classList[i] ) > -1 )
return false;
}
el = el.parentNode;
}
return true;
},
closest : function( el, tag ){
if( el === null || el === undefined || typeof( el.getAttribute ) != 'function' )
return null;
var model = el.getAttribute('data-model');
if( model !== null ){
if( tag === undefined ||
( tag !== undefined && or.storage[ model ] !== undefined && or.storage[ model ].name == tag )
)return [ el, el.getAttribute('data-model') ];
}
if( el.parentNode !== null )
return or.detect.closest( el.parentNode, tag );
return null;
},
target : function( ob ){
var u = or.detect, itself = false;
if( this.holder === null || this.holder.model === ob[1] )
itself = true;
if( !itself ){
var name = ( or.storage[ ob[1] ] !== undefined ) ? or.storage[ ob[1] ].name : '';
if( name !== '' && this.bone.indexOf( name ) === -1 ){
if( this.rect( ob, this.holder ) === false )
return;
if( or.storage[ ob[1] ] !== undefined )
this.holder.tooltip.querySelectorAll('span.label')[0].innerHTML = or.storage[ ob[1] ].name.replace('or_','');
$(this.holder.top).find('.marginer').attr({ 'data-value': or.detect.get_margin( ob[1], 'top' ) });
$(this.holder.bottom).find('.marginer').attr({ 'data-value': or.detect.get_margin( ob[1], 'bottom' ) });
}
}
if( ob[1] == '-1' )
ob[3] = ob[0].parentNode;
else ob[3] = ob[0];
if( name != 'or_row' && name != 'or_row_inner' ){
this.columns( ob[3] );
return;
}
if( ob[0].querySelectorAll('[data-model]')[0] !== undefined ){
this.columns( ob[0].querySelectorAll('[data-model]')[0] );
}
},
untarget : function(){
or.detect.clicked = false;
or.frame.$('.or-boxholder, .or-boxholder div, #or-overlay-placeholder').attr({style:''});
$('.or-params-popup .button.cancel').trigger('click');
try{
this.holder.model = '';
this.holder.el = null;
this.holder.main.data({'el':'','model':''});
this.holder.row.main.data({'el':'','model':''});
this.holder.sections.main.data({'el':'','model':''});
this.holder.section.main.data({'el':'','model':''});
for( var i=0; i<this.holder.columns.length; i++ ){
this.holder.columns[i].main.data({'el':'','model':''});
}
}catch(ex){}
},
rect : function( ob, holder, padding ){
if( ob[0] === null || typeof( ob[0].getBoundingClientRect ) != 'function' || ob[1] === holder.main.data('model') )
return false;
var pr = 0;
if( padding === undefined ){
padding = 0;
pr = 0;
}
holder.main.data({ el : ob[0], model : ob[1], s : ob[1] });
if( ob[0].tagName == 'or' )
$(ob[0]).addClass('fix-to-get-rect');
ob[0].style.overflow = 'hidden';
var coor = ob[0].getBoundingClientRect(),
top = coor.top+or.detect.frame.window.scrollY,
left = coor.left+or.detect.frame.window.scrollX,
height = Math.round( ( coor.height >= 27 ) ? coor.height : 27 ),
width = coor.width;
ob[0].style.overflow = '';
if( ob[0].tagName == 'or' )
$(ob[0]).removeClass('fix-to-get-rect');
holder.width = width;
holder.height = height;
holder.el = ob[0];
holder.model = ob[1];
holder.main.css({ top: (top-padding)+'px', left: left+'px', width: width+'px' });
holder.top.style.width = (width)+'px';
holder.right.style.left = (width-1)+'px';
holder.right.style.height = (height+padding)+'px';
holder.bottom.style.top = (height+padding)+'px';
holder.bottom.style.width = (width)+'px';
holder.left.style.height = (height+padding)+'px';
return true;
},
wrap_node : function( node ){
if( node !== null && node !== undefined ){
var spc = node.firstChild, spcx;
while( spc !== null ){
spcx = spc.nextSibling;
if( spc.nodeType === 3 && ( spc.data === "\n" || spc.data.trim() === '' ) ){
spc.parentNode.removeChild( spc );
}
spc = spcx;
}
node = node.firstChild;
var wrp,discover, nd, ind;
while( node !== null ){
if( node.nodeType === 8 )
ind = node;
else ind = false;
if(
node.nodeType === 8 &&
node.data.indexOf('or s') === 0 &&
node.nextSibling !== null
){
if( node.nextSibling.nextSibling !== null ){
if( node.nextSibling.nextSibling.nodeType === 8 &&
node.nextSibling.nextSibling.data.indexOf('or e') === 0 ){
if( node.nextSibling.nodeType !== 1 ){
nd = $('<or data-model="'+node.data.replace( /[^0-9]/g, '' )+'"></or>');
$( node.nextSibling ).after( nd );
nd.append( node.nextSibling );
}else node.nextSibling.setAttribute( 'data-model', node.data.replace( /[^0-9]/g, '' ) );
}else{
discover = node.nextSibling;
wrp = document.createElement('or');
node.parentNode.insertBefore( wrp, discover );
wrp.setAttribute( 'data-model', node.data.replace( /[^0-9]/g, '' ) );
while( discover !== null ){
wrp.appendChild( discover );
if( wrp.nextSibling !== null &&
wrp.nextSibling.nodeType === 8 &&
wrp.nextSibling.data.indexOf('or e') === 0
)break;
if( discover.nodeType === 1 )
or.detect.wrap_node( discover );
discover = wrp.nextSibling;
}
node = wrp;
}
}
}else if( node.nodeType === 1 )or.detect.wrap_node( node );
node = node.nextSibling;
if( ind !== false && ind != null && ind.parentNode !== null )
ind.parentNode.removeChild( ind );
}
}
},
is_element : function( model ){
if( or.storage[ model ] === undefined )
return false;
var ignored = [ 'or_row', 'or_column', 'or_column_inner' ]/*.concat( or_maps_views )*/.concat( or_maps_view );
if( ignored.indexOf( or.storage[ model ].name ) > -1 )
return false;
return true;
},
build_nav : function( ob, e ){
or.front.ui.element.edit( ob[1], e );
$('#or-inspect-breadcrumns').html('<ul></ul>');
while( ob !== null ){
ob[2] = or.storage[ob[1]].name;
ob[3] = ob[2].replace(/or\_/g,'').replace(/\_/g,' ');
var acts = [
'<li data-act="focus"><i class="et-focus"></i> Focus</li>',
'<li data-act="edit"><i class="et-tools-2"></i> Edit</li>',
//'<li data-act="copy"><i class="et-clipboard"></i> Copy</li>',
'<li data-act="double"><i class="et-documents"></i> Dublicate</li>',
'<li data-act="delete"><i class="et-caution"></i> Delete</li>'
], holder;
if( ['or_row', 'or_row_inner'].indexOf( ob[2] ) > -1 ){
holder = 'row';
acts.splice( 1, 0, '<li data-act="layout"><i class="et-browser"></i> Layouts</li>' );
}else if( ['or_column', 'or_column_inner'].indexOf( ob[2] ) > -1 ){
acts.splice( 2, 1);
acts.splice( 1, 0, '<li data-act="add"><i class="et-calendar"></i> Add Element</li>' );
holder = 'column';
}else if( or_maps_views.indexOf( ob[2] ) > -1 ){
acts.splice( 1, 0, '<li data-act="section"><i class="et-layers"></i> Add Section</li>' );
holder = 'sections';
}else if( or_maps_view.indexOf( ob[2] ) > -1 ){
acts.splice( 0, 1);
acts.splice( 1, 1);
acts.splice( 1, 0, '<li data-act="add"><i class="et-calendar"></i> Add Element</li>' );
holder = 'section';
}else{
holder = 'element';
}
var li = '<li class="item" data-holder="'+holder+'" data-e-model="'+ob[1]+'" data-e-name="'+ob[2]+'">'+
'<span class="pointer" data-act="edit">'+ob[3]+'</span><ul>'+acts.join('')+'</ul></li>';
$('#or-inspect-breadcrumns>ul').prepend(li+'<li><i class="fa-angle-right"></i></li>');
ob = this.closest( ob[0].parentNode );
}
$('#or-inspect-breadcrumns>ul>li').last().remove();
var cl = 'active';
if( $('.or-sidebar-popup .or-pop-tabs').length === 0 )
cl += ' notab';
$('#or-inspect-breadcrumns>ul>li.item').last().addClass(cl);
if( $('#or-inspect-breadcrumns').data('added-event') !== true ){
$('#or-inspect-breadcrumns').data({ 'added-event': true })
.on('mouseover',function(e){
if( $(e.target).closest('li.item').length > 0 ){
var model = $(e.target).closest('li.item').data('e-model'),
el = or.frame.$('[data-model="'+model+'"]').get(0);
if( el !== undefined && el !== null && typeof el.getBoundingClientRect == 'function' ){
el = el.getBoundingClientRect();
console.log(el);
or.frame.$('#or-overlay-placeholder').css({width:el.width+'px', height:el.height+'px', top:(el.top+or.detect.frame.window.scrollY)+'px', left:el.left+'px', });
}
}
})
.on('mouseout',function(e){
or.frame.$('#or-overlay-placeholder').attr({'style':''});
})
.on('click', function(e){
if( e.target.getAttribute('data-act') !== null ){
var el = $(e.target).closest('li.item'),
model = el.data('e-model'),
holder = el.data('holder');
switch( e.target.getAttribute('data-act') ){
case 'focus':
or.detect.untarget();
or.detect.focus( model, holder );
break;
case 'layout':
or.front.ui.column.layout( el );
break;
case 'add':
var pop = or.front.ui.element.add( or.frame.$('[data-model="'+model+'"]').get(0) );
pop.data({'pos':'bottom'});
break;
case 'edit':
or.front.ui.element.edit( model );
$('#or-inspect-breadcrumns>ul>li.item.active').removeClass('active');
$('#or-inspect-breadcrumns>ul>li.notab').removeClass('notab');
el.addClass('active');
if( $('.or-sidebar-popup .or-pop-tabs').length === 0 )
el.addClass('notab');
or.detect.focus( model, holder );
break;
case 'section':
or.front.ui.element.add_section( model );
break;
case 'copy':
or.front.ui.element.copy( model );
$('#or-inspect-breadcrumns>ul>li.item.active').removeClass('active');
break;
case 'double':
or.front.ui.element.double( model );
$('#or-inspect-breadcrumns>ul>li.item.active').removeClass('active');
break;
case 'delete':
if(confirm( or.__.sure ) ){
var elm = or.detect.frame.$('[data-model="'+model+'"]'),
ob = or.detect.closest( elm.parent().get(0) ),
name = or.storage[ model ].name;
if( ['or_column', 'or_column_inner'].indexOf( name ) > -1 ){
var cols = elm.parent().find('>[data-model]');
if(cols.length === 1){
// if there are only one column
// we will delete the row
model = ob[1];
elm = $(ob[0]);
}else{
cols.each(function(){
var cid = $(this).data('model'), _w = or.tools.nfloat(100/(cols.length-1))+'%';
or.storage[ cid ].args.width = _w;
$(this).css({ width: _w });
});
}
}
elm.find('[data-model]').each(function(){
delete or.storage[ $(this).data('model') ];
});
delete or.storage[ model ];
elm.remove();
if( or_maps_view.indexOf( name ) > -1 ){
if( ob !== null){
var code = or.front.build_shortcode( ob[1] );
if( code !== '' )
or.front.push( code, ob[1], 'replace' );
}
}
or.detect.untarget();
$('#or-inspect-breadcrumns').html('');
}
break;
}
}
});
}
},
get_margin : function( model, direct ){
var css = or.storage[model].css_data?or.storage[model].css_data:'', value = 0;
css = css.split(';');
if( css.length > 0 ){
for( var i = 0; i< css.length; i++ ){
if( css[i].indexOf('margin') > -1 ){
if( direct == 'top' ){
if( css[i].indexOf('margin-top') > -1 )
value = css[i];
else{
css[i] = css[i].split(':')[1].split(' ');
value = css[i][0];
}
value = parseInt(value.replace(/[^0-9]/g,''));
}else if( direct == 'bottom' ){
if( css[i].indexOf('margin-bottom') > -1 )
value = css[i];
else{
css[i] = css[i].split(':')[1].split(' ');
if( css[i].length === 1 || css[i].length === 2 )
value = css[i][0];
else if( css[i].length === 3 || css[i].length === 4 )
value = css[i][2];
}
}
}
}
}
if( value === 0 ){
if( direct == 'top' )
value = or.frame.$('[data-model="'+model+'"]').css('margin-top');
else if( direct == 'bottom' )
value = or.frame.$('[data-model="'+model+'"]').css('margin-bottom');
}
var ext = value.replace(/[0-9\.\-\ ]/g,'');
return parseInt( value )+ext;
},
row : function( el ){
this.ob = or.detect.closest( el );
while( this.ob !== null && or.storage[ this.ob[1] ] !== undefined ){
// we will check is_section while finding row
if( this.section( this.ob ) === true )
return;
if( or.storage[ this.ob[1] ].name == 'or_row' || or.storage[ this.ob[1] ].name == 'or_row_inner' ){
if( this.rect( this.ob, this.holder.row, 28 ) !== false ){
// if target row success
this.holder.row.tooltip.querySelectorAll('.label')[0].innerHTML = or.storage[ this.ob[1] ].name.replace('or_','');
}
break;
}
this.ob = or.detect.closest( this.ob[0].parentNode );
}
},
columns : function( el ){
this.ob = or.detect.closest( el );
var i = 0, el;
while( this.ob !== null && or.storage[ this.ob[1] ] !== undefined ){
if( or.storage[ this.ob[1] ].name == 'or_column' || or.storage[ this.ob[1] ].name == 'or_column_inner' ){
el = this.ob[0].parentNode.firstChild;
i = 0;
while( el !== null ){
this.column( el, i++ );
el = el.nextElementSibling;
}
while( i < 6 ){
this.holder.columns[i++].main.data({'el':'', 'model':''}).attr({style:''}).find('div').attr({style:''});
}
break;
}
this.ob = or.detect.closest( this.ob[0].parentNode );
}
},
column : function( el, index ){
if( this.rect( [ el, el.getAttribute( 'data-model' ) ], this.holder.columns[ index ], 0 ) !== false ){
// if target column success
var st = or.storage[el.getAttribute( 'data-model' )], _w;
if( st !== undefined && st.args !== undefined && st.args.width !== undefined ){
_w = st.args.width;
if( _w.indexOf('%') > -1 ){
_w = Math.round( parseFloat( _w ) )+'%';
}
this.holder.columns[ index ].main.find('.col-info').html( _w );
}
}
},
section : function( ob ){
if(ob === null)
return false;
if( or.storage[ ob[1] ] === undefined )
return false;
if( or_maps_view.indexOf( or.storage[ ob[1] ].name ) > -1 ){
if( this.rect( ob, this.holder.section, 0 ) !== false ){
ob = or.detect.closest( ob[0].parentNode );
// target sections when found a section
if( this.rect( ob, this.holder.sections ) !== false ){
// if target sections success
$(this.holder.sections.tooltip).find('.label').html(
or.storage[ ob[1] ].name.replace('or_','' )
);
}
return true;
}
}else if( or_maps_views.indexOf( or.storage[ ob[1] ].name ) > -1 )
return true;
return false;
},
};
} )( jQuery );
|
export { default } from 'twyr-dsl/modifiers/did-mutate';
|
document.addEventListener("DOMContentLoaded", function(){
if(!window.EventSource) {
alert("No EventSource");
return;
}
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
};
const chatLog = document.querySelector("#chat-log");
const chatMsg = document.querySelector("#chat-msg");
let inputName;
while (isBlank(inputName)) {
inputName = prompt("What is your name?")
if(!isBlank(inputName)){
const userName = document.querySelector("#user-name");
userName.innerHTML = '<b>' + inputName + '</b>'
}
}
const btn = document.querySelector("#btn")
btn.addEventListener("click", () => {
post('/messages', {
msg: chatMsg.value,
name : inputName
});
chatMsg.value = '';
chatMsg.focus();
});
});
function isBlank(string) {
return string == null || string.trim() === "";
};
function post(path, params, method='post') {
const form = document.createElement('form');
form.method = method;
form.action = path;
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = params[key];
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
|
// @flow
import { emptyDisplayCutout } from './TONNativeUtility';
import type { TONNativeUtility } from './TONNativeUtility';
import TONString from './TONString';
export default function TONNativeUtilityNodeJs(): Promise<TONNativeUtility> {
return Promise.resolve({
getLocaleInfo() {
return Promise.resolve(TONString.getLocaleInfo());
},
getAndroidDisplayCutout() {
return Promise.resolve(emptyDisplayCutout);
},
});
}
|
import ReactDOM from 'react-dom';
import React, { Fragment, useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
const MarkerCustom = (props) => {
const [map, setMap] = useState(null);
const customMarke = useRef();
// useEffect(({ google } = props) => {
function CustomMarker(latlng, map, args) {
this.latlng = latlng;
this.args = args;
// this.img = img;
// this.setMap(map);
this.maps = map
setMap(map)
// setGoogle(google)
}
CustomMarker.prototype = new props.google.maps.OverlayView();
CustomMarker.prototype.onAdd = function () {
var self = this;
var div = this.div;
console.log('aa');
if (!div) {
// Generate marker html
div = this.div = customMarke;
div.className = 'custom-marker';
div.style.position = 'absolute';
div.className = 'custom-marker';
// div.style.position = 'absolute';
var innerDiv = document.createElement('div');
innerDiv.className = 'custom-marker-inner';
// var innerDiv = React.createElement('div',
// { className: "custom-marker-inner" },
// props.element !== undefined ? props.element : `<img src="https://img.icons8.com/ios-glyphs/30/000000/user--v1.png" style="border-radius: inherit;width: 20px;height: 20px;margin: 2px;"/>`
// );
// innerDiv.innerHTML = `<img src="${this.img}" style="border-radius: inherit;width: 20px;height: 20px;margin: 2px;"/>`
innerDiv.innerHTML = props.element !== undefined ? props.element : `<img src="https://img.icons8.com/ios-glyphs/30/000000/user--v1.png" style="border-radius: inherit;width: 20px;height: 20px;margin: 2px;"/>`;
// div.appendChild(innerDiv);
// ReactDOM.render(innerDiv, div)
if (typeof (self.args.marker_id) !== 'undefined') {
div.dataset.marker_id = self.args.marker_id;
}
props.google.maps.event.addDomListener(div, "click", function (event) {
props.google.maps.event.trigger(self, "click");
});
var panes = this.getPanes();
panes.overlayImage.appendChild(div);
}
};
CustomMarker.prototype.draw = function () {
// มี bug icon ไม่เกาะ map
if (this.div) {
// กำหนด ตำแหน่ง ของhtml ที่สร้างไว้
let positionA = new props.google.maps.LatLng(this.latlng.lat, this.latlng.lng);
this.pos = this.getProjection().fromLatLngToDivPixel(positionA);
// console.log(this.pos);
this.div.style.left = this.pos.x + 'px';
this.div.style.top = this.pos.y + 'px';
}
};
CustomMarker.prototype.getPosition = function () {
return this.latlng;
};
// get.users.location(me.props.uid).then(function (geo) {
// if (props.location !== undefined) {
// console.log(props.location);
useEffect(() => {
let myLatlng = new props.google.maps.LatLng(props.location.lat, props.location.lng);
let marker_custom = new CustomMarker(
myLatlng,
props.map,
{},
);
let pos = {
lat: props.location.lat,
lng: props.location.lng
};
marker_custom.latlng = { lat: pos.lat, lng: pos.lng };
marker_custom.draw();
if (map.setCenter(pos) !== null) {
map.setCenter(pos);
// console.log(map);
}
})
// })
// })
return (
<div
ref={customMarke}
></div>
)
}
MarkerCustom.propTypes = {
google: PropTypes.object,
map: PropTypes.object,
location: PropTypes.object,
element: PropTypes.string
}
export default MarkerCustom;
|
describe('SVP Modernized Home Page', function() {
it('should have a title', function() {
browser.get('http://localhost:9001/#/');
expect(browser.getTitle()).toEqual('SVP Modernized');
});
});
|
import * as PropTypes from 'prop-types';
import * as React from 'react';
import { uuid4 } from '../../utils/utils';
/**
* @uxpincomponent
*/
function Popover(props) {
const popoverId = `popover-${uuid4()}`;
const referenceId = `button-${uuid4()}`;
const textRender = () => ({ __html: props.popover[0].text.replaceAll('\n', '<br />') });
// eslint-disable-next-line react/no-danger
const text = <p dangerouslySetInnerHTML={textRender()} />;
return (
<>
<div style={{ border: '1px solid #e9e9e9', height: '16px', width: '16px' }} id={referenceId}>
<span className="-sr--only">
i
</span>
</div>
<chi-popover
active={props.active}
arrow={props.arrow}
id={popoverId}
position={props.position}
title={props.popover[0].title || null}
variant="text"
reference={`#${referenceId}`}
closable={props.closeButton}
prevent-auto-hide={props.preventAutoHide}>
{text || ''}
</chi-popover>
</>
);
}
/* eslint-disable */
Popover.propTypes = {
active: PropTypes.bool,
arrow: PropTypes.bool,
position: PropTypes.oneOf(['top', 'right', 'bottom', 'left', 'top-start', 'top-end', 'right-start', 'right-end', 'bottom-start', 'bottom-end', 'left-start', 'left-end']),
popover: PropTypes.array,
closeButton: PropTypes.bool,
preventAutoHide: PropTypes.bool,
};
/* eslint-enable */
Popover.defaultProps = {
active: true,
arrow: true,
position: 'bottom',
popover: [{
title: 'Popover Title',
text: 'Line 1 \nLine 2 \nLine 3',
}],
closeButton: false,
preventAutoHide: true,
};
export default Popover;
|
$(document).ready(function(){
$('nav a').removeClass('selected');
if (window.location.hash){
var currentPage = window.location.hash;
if (currentPage == "#about") {
$('html,body').animate({
scrollTop: $(currentPage).offset().top - 55}, 1000);
} else {
$('html,body').animate({
scrollTop: $(currentPage).offset().top - 55}, 1000);
}
$('a[href='+currentPage+']').addClass('selected');
} else{
currentPage = "#about";
window.location.hash = currentPage;
$('a[href='+currentPage+']').addClass('selected');
$('html,body').animate({
scrollTop: $(currentPage).offset().top - 55}, 1000);
}
$('nav a').click(function(e){
if ( $(this).hasClass("aboutpage") ){
$('html,body').animate({
scrollTop: $(this.hash).offset().top - 55}, 1000);
}else {
$('html,body').animate({
scrollTop: $(this.hash).offset().top - 55}, 1000);
}
//remove the previous selected class
//and put it on the correct nav button
$('nav a').removeClass('selected');
$(this).addClass('selected');
//using the history js api to change
//the url without page reload
window.history.replaceState('Object', 'Title', this.hash);
return false;
});
$(".inline").colorbox({inline:true, width:935, height: 550});
$("a.inline").colorbox({rel: 'gal', title: function(){}});
$(".inline_pic").colorbox({inline:true, width:935, height: 550});
$("a.inline_pic").colorbox({rel: 'win', title: function(){}});
});
$(window).load(function() { //start after HTML, images have loaded
var InfiniteRotator =
{
init: function()
{
//initial fade-in time (in milliseconds)
var initialFadeIn = 0;
//interval between items (in milliseconds)
var itemInterval = 3500;
//cross-fade time (in milliseconds)
var fadeTime = 1500;
//count number of items
var numberOfItems = $('.rotating-item').length;
//set current item
var currentItem = 0;
//show first item
$('.rotating-item').eq(currentItem).fadeIn(initialFadeIn);
//loop through the items
var infiniteLoop = setInterval(function(){
$('.rotating-item').eq(currentItem).fadeOut(fadeTime);
if(currentItem == numberOfItems -1){
currentItem = 0;
}else{
currentItem++;
}
$('.rotating-item').eq(currentItem).fadeIn(fadeTime);
}, itemInterval);
}
};
InfiniteRotator.init();
});
|
/*global _*/
/*global VisaoConteudo*/
/*global VisaoNavegacao*/
(function (contexto) {
"use strict";
var ModeloCategoria = Backbone.Model.extend({
idAttribute: "id_categoria"
});
var ColecaoCategorias = Backbone.Model.extend({
model: ModeloCategoria,
url: "/categorias"
});
var VisaoCardapio = VisaoConteudo.extend({
initialize: function () {
_.bindAll(this,
"receberCategorias"
);
},
obterCategorias: function () {
this.colecaoCategorias = new ColecaoCategorias();
this.colecaoCategorias.fetch({
success: this.receberCategorias
});
},
receberCategorias: function (evento, categorias) {
var template = _.template(this.templateCardapio);
console.log(this.colecaoCategorias.models);
console.log(categorias);
this.$el.html(template({
categorias: categorias
}));
},
render: function (templateCardapio) {
this.templateCardapio = templateCardapio;
this.obterCategorias();
}
});
var VisaoNavegacaoCardapio = VisaoNavegacao.extend({
initialize: function () {
this.fixarTitulo("Cardápio");
}
});
contexto.VisaoCardapio = VisaoCardapio;
contexto.VisaoNavegacaoCardapio = VisaoNavegacaoCardapio;
}(this));
|
export async function GetUsers() {
const result = await fetch(`https://randomuser.me/api/?results=50`)
const data = await result.json()
return data
}
|
function triggerPanelUpdate() {
jQuery.ajax({
url: 'https://cs1100320005fe6c183.blob.core.windows.net/rpisensor/rpisensor/01/2020/06/16/14/37',
datalype: 'json',
success: function (temps) {
var record = temps[0];
_lastRecord = record.Temp;
_panel.removeAllProperties();
_panel.addProperty('temperature', 'humidity');
addCharData(record);
console.log(record);
if (_panel.isVisible()) setTimeout(triggerPanelUpdate, 10 *1000);
}
});
}
function onMouseClick(event) {
var screenPoint = {
x: event.clientX,
y: event.clientY
};
var n = normalizeCoords(screenPoint) ;
var hitTest1 = viewer.impl.hitTest(screenPoint.x, screenPoint.y, true);
//get hit point
var hitTest = viewer.utilities.getHitPoint(
screenPoint.x,
screenPoint.y);
if (hitTest1) {
console.log(hitTest1.intersectPoint) ;
drawPushpin({
x: hitTestl.intersectPoint.x,
y: hitTestl.intersectPoint.y,
z: hitTestl.intersectPoint.z
});
}
}
|
import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:3000/api/v1'
axios.defaults.headers.common['AUTHORIZATION'] = sessionStorage.getItem('jwt')
import { browserHistory } from 'react-router'
import _ from 'lodash'
export default {
fetchNotes: function(){
return axios.get('/notes').then(response => response.data)
},
loginUser: function(loginParams){
return axios.post('/sessions', loginParams)
.then((res) => {
sessionStorage.setItem('jwt', res.data.jwt)
browserHistory.push('/')
return { username: res.data.username }
})
} ,
updateNote: function(noteParams){
return _.debounce(() => {
axios.patch(`/notes/${noteParams.id}`, noteParams.note )
.then(response => response.data )
}, 500)()
} ,
createNote: function(params){
return axios.post(`/notes`, params )
.then( response => response.data )
}
}
|
// const msToDate = (time) => {
// const Y = time.getFullYear();
// const M = (val => (val >= 10 ? val : `0${val}`))(time.getMonth() + 1);
// const D = (val => ((val >= 10) ? val : `0${val}`))(time.getDate());
// const H = (val => ((val >= 10) ? val : `0${val}`))(time.getHours());
// const Mi = (val => ((val >= 10) ? val : `0${val}`))(time.getMinutes());
// const S = (val => ((val >= 10) ? val : `0${val}`))(time.getSeconds());
// const result1 = `${Y}-${M}-${D}`
// const result2 = `${result1} ${H}:${Mi}:${S}`
// return {
// hasTime: result2, // ---> 2017-09-19 08:00:00
// withoutTime: result1
// }
// }
class msToDate {
constructor(t) {
const time = t || new Date()
this.Y = time.getFullYear();
this.M = (val => (val >= 10 ? val : `0${val}`))(time.getMonth() + 1);
this.D = (val => ((val >= 10) ? val : `0${val}`))(time.getDate());
this.H = (val => ((val >= 10) ? val : `0${val}`))(time.getHours());
this.Mi = (val => ((val >= 10) ? val : `0${val}`))(time.getMinutes());
this.S = (val => ((val >= 10) ? val : `0${val}`))(time.getSeconds());
}
format(type) {
const self = this
if (type === 'YYYY-MM-DD') {
return `${self.Y}-${self.M}-${self.D}`
}
return `${self.Y}-${self.M}-${self.D}`
}
}
export {
msToDate
}
|
/*!
* jQuery slideshow plugin SLIM
* Original author: @Yan Zhang
* Version: 1.0.0
* Licensed under the MIT license
*/
(function(factory){
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof exports !== 'undefined') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
}(function($) {
'use strict';
var Slim = window.Slim || {};
Slim = (function(){
function Slim(element, settings) {
var _ = this;
_.defaults = {
initialSlide: 0,
slidesToShow: 2,
slidesToScroll: 2,
arrows: true,
appendArrows: $(element),
prevArrow: '<button type="button" class="slim-prev" aria-label="Previous">Previous</button>',
nextArrow: '<button type="button" class="slim-next" aria-label="Next">Next</button>',
speed: 500,
easing: 'linear',
touchThreshold: 5,
edgeFriction: 0.35
};
_.initials = {
animating: false,
dragging: false,
currentSlide: 0,
listWidth: null,
$slideTrack: null,
$slides: null,
slideCount: null,
$list: null,
$prevArrow: null,
$nextArrow: null,
slideWidth: null,
windowWidth: 0,
touchObject: {}
};
$.extend(_, _.initials);
_.$slider = $(element);
_.options = $.extend({}, _.defaults, settings);
_.currentSlide = _.options.initialSlide;
_.changeSlide = $.proxy(_.changeSlide, _);
_.setDimensions = $.proxy(_.setDimensions, _);
_.swipeHandler = $.proxy(_.swipeHandler, _);
_.resize = $.proxy(_.resize, _);
// A simple way to check for HTML strings
// Strict HTML recognition (must start with <)
// Extracted from jQuery v1.11 source
_.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;
_.init();
}
return Slim;
}());
Slim.prototype.init = function() {
var _ = this;
if (!_.$slider.hasClass('slim-initialized')) {
_.$slider.addClass('slim-initialized');
_.buildOut();
_.startLoad();
_.loadSlider();
_.initializeEvents();
_.updateArrows();
}
};
Slim.prototype.buildOut = function() {
var _ = this;
_.$slides = _.$slider.children().addClass('slim-slide');
_.slideCount = _.$slides.length;
_.$slides.each(function(index, element) {
$(element)
.attr('data-slide-index', index)
.data('originalStyling', $(element).attr('style') || '');
});
_.$slider.addClass('slim-slider');
_.$slideTrack = _.$slides.wrapAll('<div class="slim-track"/>').parent();
_.$list = _.$slideTrack.wrap('<div class="slim-list"/>').parent();
_.$slideTrack.css('opacity', 0).addClass('group');
_.buildArrows();
_.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);
};
Slim.prototype.startLoad = function() {
var _ = this;
_.$slider.addClass('slim-loading');
};
Slim.prototype.loadSlider = function() {
var _ = this;
_.$slideTrack.css({ opacity: 1 });
_.$slider.removeClass('slim-loading');
};
Slim.prototype.buildArrows = function() {
var _ = this;
if (_.options.arrows === true) {
_.$prevArrow = $(_.options.prevArrow).addClass('slim-arrow');
_.$nextArrow = $(_.options.nextArrow).addClass('slim-arrow');
if (_.slideCount > _.options.slidesToShow) {
_.$prevArrow.removeClass('slim-hidden').removeAttr('aria-hidden');
_.$nextArrow.removeClass('slim-hidden').removeAttr('aria-hidden');
if (_.htmlExpr.test(_.options.prevArrow)) {
_.$prevArrow.prependTo(_.options.appendArrows);
}
if (_.htmlExpr.test(_.options.nextArrow)) {
_.$nextArrow.appendTo(_.options.appendArrows);
}
} else {
_.$prevArrow.add(_.$nextArrow)
.addClass('slim-hidden')
.attr({
'aria-disabled': 'true'
});
}
}
};
Slim.prototype.updateArrows = function() {
var _ = this;
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow.removeClass('slim-disabled').attr('aria-disabled', 'false');
_.$nextArrow.removeClass('slim-disabled').attr('aria-disabled', 'false');
if (_.currentSlide === 0) {
_.$prevArrow.addClass('slim-disabled').attr('aria-disabled', 'true');
_.$nextArrow.removeClass('slim-disabled').attr('aria-disabled', 'false');
} else if (_.currentSlide >= _.slideCount - _.options.slidesToShow) {
_.$nextArrow.addClass('slim-disabled').attr('aria-disabled', 'true');
_.$prevArrow.removeClass('slim-disabled').attr('aria-disabled', 'false');
}
}
};
Slim.prototype.setSlideClasses = function(index) {
var _ = this, allSlides;
allSlides = _.$slider
.find('.slim-slide')
.removeClass('slim-active')
.attr('aria-hidden', 'true');
if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) {
_.$slides
.slice(index, index * 1 + _.options.slidesToShow * 1)
.addClass('slim-active')
.attr('aria-hidden', 'false');
}
};
Slim.prototype.setDimensions = function() {
var _ = this,
targetLeft;
_.listWidth = _.$list.width();
_.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow);
_.$slideTrack.width(Math.ceil(_.slideWidth * _.slideCount));
var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width();
_.$slideTrack.children('.slim-slide').width(_.slideWidth - offset);
targetLeft = _.getLeft(_.currentSlide);
_.$slideTrack.css({ left: targetLeft });
};
Slim.prototype.getLeft = function(slideIndex) {
var _ = this,
targetLeft;
targetLeft = slideIndex * _.slideWidth * -1;
return targetLeft;
};
Slim.prototype.changeSlide = function(event) {
var _ = this;
switch (event.data.message) {
case 'previous':
_.slideHandler(-1);
break;
case 'next':
_.slideHandler(1);
break;
default:
return;
}
};
Slim.prototype.slideHandler = function(slideOffset) {
var _ = this,
maxCurrentSlide = _.slideCount - _.options.slidesToShow,
newCurrentSlide = _.currentSlide + _.options.slidesToScroll * slideOffset;
if (_.animating === true) {
return;
}
if (newCurrentSlide < 0) {
_.currentSlide = 0;
} else if (newCurrentSlide > maxCurrentSlide) {
_.currentSlide = maxCurrentSlide;
} else {
_.currentSlide = newCurrentSlide;
}
_.animating = true;
_.animateSlide(_.currentSlide);
_.setSlideClasses(_.currentSlide);
_.updateArrows();
};
Slim.prototype.animateSlide = function(currentSlide) {
var _ = this,
targetLeft = _.getLeft(currentSlide);
_.$slideTrack.animate({
left: targetLeft
}, _.options.speed, _.options.easing, function() {
_.animating = false;
});
};
Slim.prototype.swipeHandler = function(event) {
var _ = this;
_.touchObject.fingerCount = event.originalEvent & event.originalEvent.touches !== undefined ?
event.originalEvent.touches.length : 1;
_.touchObject.minSwipe = _.listWidth / _.options.touchThreshold;
switch (event.data.action) {
case 'start':
_.swipeStart(event);
break;
case 'move':
_.swipeMove(event);
break;
case 'end':
_.swipeEnd(event);
}
};
Slim.prototype.swipeStart = function(event) {
var _ = this, touches;
if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) {
_.touchObject = {};
return false;
}
if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) {
touches = event.originalEvent.touches[0];
}
_.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX;
_.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY;
_.dragging = true;
};
Slim.prototype.swipeMove = function(event) {
var _ = this, curLeft, swipeDirection, swipeLength, swipeLeft, positionOffset, touches;
touches = event.originalEvent !== undefined ? event.originalEvent.touches : null;
if (!_.dragging || touches && touches.length !== 1) {
return false;
}
if (_.animating === true) {
return false;
}
curLeft = _.getLeft(_.currentSlide);
_.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX;
_.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY;
_.touchObject.swipeLength = Math.round(Math.sqrt(
Math.pow(_.touchObject.curX - _.touchObject.startX, 2)));
swipeDirection = _.swipeDirection();
if (swipeDirection === 'stay') {
return;
}
positionOffset = _.touchObject.curX > _.touchObject.startX ? 1 : -1;
swipeLength = _.touchObject.swipeLength;
if ((_.currentSlide === 0 && swipeDirection === 'left') || (_.currentSlide === _.slideCount - _.options.slidesToShow && swipeDirection === 'right')) {
swipeLength = _.touchObject.swipeLength * _.options.edgeFriction;
}
swipeLeft = curLeft + swipeLength * positionOffset;
_.$slideTrack.css({ left: swipeLeft });
};
Slim.prototype.swipeEnd = function(event) {
var _ = this;
_.dragging = false;
if (_.touchObject.swipeLength >= _.touchObject.minSwipe) {
switch (_.swipeDirection()) {
case 'left':
_.slideHandler(-1);
_.touchObject = {};
break;
case 'right':
_.slideHandler(1);
_.touchObject = {};
break;
}
} else {
if (_.touchObject.startX !== _.touchObject.curX) {
_.animateSlide(_.currentSlide);
_.touchObject = {};
}
}
};
Slim.prototype.swipeDirection = function() {
var _ = this, xDist, yDist, r, swipeAngle;
xDist = _.touchObject.startX - _.touchObject.curX;
yDist = _.touchObject.startY - _.touchObject.curY;
r = Math.atan2(yDist, xDist);
swipeAngle = Math.round(r * 180 / Math.PI);
if (swipeAngle < 0) {
swipeAngle = 360 - Math.abs(swipeAngle);
}
if ((swipeAngle >= 0 && swipeAngle <= 45) || (swipeAngle >= 315 && swipeAngle <= 360)) {
return 'right';
} else if (swipeAngle >= 135 && swipeAngle <= 225) {
return 'left';
} else {
return 'stay';
}
};
Slim.prototype.initArrowEvents = function() {
var _ = this;
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow.on('click.slim', {
message: 'previous'
}, _.changeSlide);
_.$nextArrow.on('click.slim', {
message: 'next'
}, _.changeSlide);
}
};
Slim.prototype.initializeEvents = function() {
var _ = this;
_.initArrowEvents();
_.$list.on('touchstart.slim mousedown.slim', {
action: 'start'
}, _.swipeHandler);
_.$list.on('touchmove.slim mousemove.slim', {
action: 'move'
}, _.swipeHandler);
_.$list.on('touchend.slim mouseup.slim', {
action: 'end'
}, _.swipeHandler);
_.$list.on('touchcancel.slim mouseout.slim', {
action: 'end'
}, _.swipeHandler);
$(window).on('resize.slim orientationchange.slim', _.resize);
$(window).on('load.slim', _.setDimensions);
$(document).on('ready.slim', _.setDimensions);
};
Slim.prototype.resize = function() {
var _ = this;
if ($(window).width() !== _.windowWidth) {
clearTimeout(_.windowDelay);
_.windowDelay = window.setTimeout(function() {
_.windowWidth = $(window).width();
_.setDimensions();
}, 50);
}
};
Slim.prototype.cleanUpEvents = function() {
var _ = this;
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow && _.$prevArrow.off('click.slim', _.changeSlide);
_.$nextArrow && _.$nextArrow.off('click.slim', _.changeSlide);
}
_.$list.off('touchstart.slim mousedown.slim', _.swipeHandler);
_.$list.off('touchmove.slim mousemove.slim', _.swipeHandler);
_.$list.off('touchend.slim mouseup.slim', _.swipeHandler);
_.$list.off('touchcancel.slim mouseout.slim', _.swipeHandler);
$(window).off('resize.slim orientationchange.slim', _.resize);
$(window).off('load.slim', _.setDimensions);
$(document).off('ready.slim', _.setDimensions);
};
Slim.prototype.destroy = function() {
var _ = this;
_.touchObject = {};
_.cleanUpEvents();
if (_.$prevArrow && _.$prevArrow.length) {
_.$prevArrow
.removeClass('slim-disabled slim-arrow slim-hidden')
.removeAttr('aria-hidden aria-disabled')
.css("display", "");
if (_.htmlExpr.test(_.options.prevArrow)) {
_.$prevArrow.remove();
}
}
if (_.$nextArrow && _.$nextArrow.length) {
_.$nextArrow
.removeClass('slim-disabled slim-arrow slim-hidden')
.removeAttr('aria-hidden aria-disabled')
.css("display", "");
if (_.htmlExpr.test(_.options.nextArrow)) {
_.$nextArrow.remove();
}
}
if (_.$slides) {
_.$slides
.removeClass('slim-slide slim-active')
.removeAttr('aria-hidden')
.removeAttr('data-slide-index')
.each(function() {
$(this).attr('style', $(this).data('originalStyling'));
});
_.$slideTrack.children().detach();
_.$slideTrack.detach();
_.$list.detach();
_.$slider.append(_.$slides);
}
_.$slider.removeClass('slim-initialized slim-slider');
};
$.fn.slim = function() {
var _ = this,
opt = arguments[0],
args = Array.prototype.slice.call(arguments, 1),
l = _.length,
i = 0,
ret;
for (i; i < l; i++) {
if (typeof opt === 'object' || typeof opt === 'undefined')
_[i].slim = new Slim(_[i], opt);
else
ret = _[i].slim[opt].apply(_[i].slim, args);
if (typeof ret !== 'undefined') return ret;
}
return _;
};
}));
|
const mongoose = require('../mongo')
const router = require('koa-router')()
const db = mongoose.connection
db.on('error', err => {console.log('error: ', err)})
db.on('open', () => {
console.log('mongoose is opend')
// 1. 定义一个 Schema
const personSchema = new mongoose.Schema({
name: String,
age: Number
})
// 2. 将该 Schema发布为 Model
const personModel = db.model('person', personSchema)
// 索引特定的 Model
// const personModel = db.model('person')
// 3. 用 Model创建 Entity
const personEntity = new personModel({
name: 'buleak',
age: 22
})
// 4. 推送数据到数据库
personEntity.save()
// 5. 查询数据
personModel.find((err, data) => {
})
// 6. schema添加方法
// personSchema.methods.speak = () => {
// console.log(`my name is ${this.name}`)
// }
// personEntity.speak()
})
router.get('/', async (ctx, next) => {
ctx.body = 'Hello Koa2'
})
router.get('/string', async (ctx, next) => {
ctx.body = 'koa2 string'
})
router.get('/json', async (ctx, next) => {
ctx.body = {
title: 'koa2 json'
}
})
module.exports = router
|
import React, { useEffect, useState } from 'react';
import { getAccount, updateAccount } from "../../store/actions/account";
import store from "../../store/store";
const Account = () => {
const [editMode, setEditMode] = useState(false);
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
useEffect(() => {
//todo: check if there user in the storage first
const user = store.getState().user;
getAccount(user.uid)
.then(response => {
return response.data();
})
.then(res => {
//todo: validate res object
if (res) {
setFirstName(res.firstName);
setLastName(res.lastName);
}
})
}, []);
const updateAccountHandler = (event) => {
event.preventDefault();
if (!firstName.length || !lastName.length)
return;
const user = store.getState().user;
updateAccount(user.uid, {
firstName,
lastName
})
.then(() => {
setEditMode(false);
})
};
const editButton = editMode ?
null :
<button onClick={() => setEditMode(!editMode)}>Edit</button>;
const account = editMode ? null : (
<div>{firstName} {lastName}</div>
);
const editForm = editMode ? (
<form onSubmit={updateAccountHandler}>
<input
type="text"
placeholder='First name'
value={ firstName }
onChange={e => setFirstName(e.target.value)}
/>
<input
type="text"
placeholder='Last name'
value={ lastName }
onChange={e => setLastName(e.target.value)}
/>
<button>Update</button>
</form>
) : null;
return (
<div>
<h1>Account</h1>
<div>
{ editButton }
</div>
<div>
{ account }
{ editForm }
</div>
</div>
);
};
export default Account;
|
import mongoose from 'mongoose';
import dotenv from 'dotenv';
dotenv.config({ path: 'variables.env' });
//mongodb+srv://cristianmafla:<password>@apiappgraphql-hwc2y.mongodb.net/test?retryWrites=true&w=majority
//mongodb://127.0.0.1:27017/ApiAppGraphql
mongoose.connect(process.env.MONGODB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, '*** ERROR CONNECTION DATABASE MONGODB *** ===> '));
db.once('open', () => console.log('*** OPEN CONNECTION DATABASE MONGODB ***'));
export default mongoose;
|
'use strict';
var fs = require('fs');
var crypto = require('crypto');
fs.readFile('./packlist.txt', function (err, data) {
if (err) throw err;
var md5 = crypto.createHash('md5');
console.log(md5.update('foo'));
console.log(md5.digest('hex'));
});
|
const express = require('express');
const app = express();
const mailer = require('./email');
const admin = require('firebase-admin');
const cors = require('cors');
app.use(cors({ origin: true }));
const functions = require('firebase-functions');
const stripe = require('stripe')('sk_test_4eC39HqLyjWDarjtT1zdp7dc');
const YOUR_DOMAIN = 'https://jamrocktaxi-b40ae.web.app/checkout';
app.post('/ahmad', async (req, res) => {
try {
const { image, fullTotal, name,pickup, dropOf} = req.body
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name,
images: [image],
description: `${pickup} To ${dropOf}`
},
unit_amount: fullTotal.toFixed() * 100,
},
quantity: 1,
},
],
mode: 'payment',
success_url: `${YOUR_DOMAIN}?success=true`,
cancel_url: `${YOUR_DOMAIN}?canceled=true`,
});
res.status(200).send({ id: session.id });
} catch (e) {
res.status(400).send({ error:e });
}
});
app.post('/sendEmail',mailer);
app.post('/createProfile', async (req, res) => {
try {
console.log('comessss here first', req.body)
let user = admin.database().ref('/users').push(
req.body
)
console.log("userrrr", user)
res.status(200).send(user);
} catch (e) {
res.status(400).send({ error:e });
}
});
module.exports = functions.https.onRequest(app);
|
$(document).ready(function () {
var board = $("#board");
var message = $("#message");
var manager = $.connection.blockMove;
var me;
$.connection.hub.start(function () {
manager.initialize(600, 400).done(function (players) {
$.each(players, function () {
drawPlayer(this);
});
});
});
$("#join-btn").click(function () {
var color = $("#join-color").val();
if (color == "") {
alert("Ange färg!");
return;
}
manager.join(color).done(function (p) {
if (!p) {
alert("Det gick inte att joina... Det kanske redan finns en spelare med den färgen?");
return;
}
me = p.Id;
$("body").keypress(function (e) {
//up
if (e.keyCode == 38 || e.which == 119)
manager.move(me, "up");
//right
if (e.keyCode == 39 || e.which == 100)
manager.move(me, "right");
//down
if (e.keyCode == 40 || e.which == 115)
manager.move(me, "down");
//left
if (e.keyCode == 37 || e.which == 97)
manager.move(me, "left");
});
});
});
$("#join-color").focus(function () {
$("#join-color").val("");
});
$("#reset-btn").click(function () {
manager.reset();
Reset();
});
manager.movePlayer = function (player) {
drawPlayer(player);
};
manager.playerJoin = function (player) {
showMessage("<div style=\"width:10px;height:10px;display:inline-block;background-color:" + player.Color + ";\"></div> has joined");
drawPlayer(player);
};
manager.updatePointBlip = function (pointBlip) {
$("#pointblip").remove();
$("<div id=\"pointblip\" style=\"top:" + pointBlip.Cords.Y + ";left:" + pointBlip.Cords.X + ";width:" + pointBlip.Size + "px;height:" + pointBlip.Size + "px;\"></div>").appendTo(board);
};
function drawPlayer(player) {
if (!player)
return;
var p = $(".player#" + player.Id);
if (p.length > 0) {
p.css("top", player.Cords.Y);
p.css("left", player.Cords.X);
} else {
$("<div id=\"" + player.Id + "\" class=\"player\" style=\"background-color:" + player.Color + ";top:" + player.Cords.Y + ";left:" + player.Cords.X + "; width:" + player.Size + "px; height:" + player.Size + "px;\"></div>").appendTo(board);
}
var ps = $("#score-" + player.Id);
if (ps.length > 0) {
ps.find(".score").text(player.Score);
} else {
$("<li class=\"playerscore\" id=\"score-" + player.Id + "\"><div class=\"playerscoredisplay\" style=\" width:" + player.Size + "px; height:" + player.Size + "px; background-color: " + player.Color + ";\"></div>: <span class=\"score\">" + player.Score + "</span></li>").appendTo($("#scoreboard ul"));
}
}
function showMessage(msg) {
message.html(msg);
message.fadeIn("slow", function () { message.fadeOut(3000, function () { message.html(""); }); });
}
function Reset() {
$(".player").remove();
$(".playerscore").remove();
}
});
|
var images = [], $images;
function createImgTemplate(name, uploadDir) {
var url = uploadDir + name;
var col = $('<div/>').addClass('col-sm-3');
var t = $('<div/>').addClass('thumbnail');
var img = $('<img/>').attr('src', url);
var c = $('<div/>').addClass('caption');
var btn = $('<button/>').addClass('btn btn-danger')
.attr('type', "button")
.text('删').attr('onclick', "delete_imgs(this, '" + url + "','"+ uploadDir +"')");
var p = $('<p/>').append(btn);
c.append(p);
t.append(img).append(c);
col.append(t);
return col;
}
function ajaxDel(dir, filename) {
return $.ajax({
type: 'DELETE',
url: '/admin/upload/',
dataType: "json",
data: {
_method: 'delete',
dir: dir,
filename: filename
}
});
}
function delete_imgs(obj, url, uploadDir) {
var rs = url.split(uploadDir);
ajaxDel(uploadDir, rs[1]).then(function (data) {
if (data.success) {
$(obj).parents('.col-sm-3').remove();
images.splice($.inArray(url, images), 1);
$images.trigger('update');
}
});
}
function fileuploadInit(uploadDir, maxFileCount) {
$("#fileuploader").fileupload({
url: "/admin/upload?dir=" + uploadDir,
fileName: "image",
maxFileCount: maxFileCount,
done: function (e, data) {
try {
var rs = data.result;
rs = JSON.parse(rs);
rs = rs.files;
$.each(rs, function (index, file) {
$('#images_box').append(createImgTemplate(file.name, uploadDir));
images.push(uploadDir + file.name);
});
$images.trigger('update');
} catch (e) {
console.warn(e);
}
}
});
}
$(document).ready(function () {
$images = $('#images');
images = $images.val() ? $images.val().split(',') : [];
$images.on('update', function () {
for (var key in images) {
if (!images[key]) delete images[key];
}
$images.val(images.join(','));
});
$images.trigger('update');
});
|
define(function () {
'user strict';
var usageService = function () {
};
usageService.$inject = [];
return usageService;
});
|
ricoApp.controller('MarketAddEditControll',function($scope,$rootScope,IndexedDb){
$scope.$on('readCustomerCache', function (){
readCustomerCache();
});
$scope.cancel = function () {
$rootScope.modal.remove();
if ($scope.orderingPos.id==undefined){
location.assign("#/tab/overview");
}else{
location.assign("#/tab/basket")
};
};
$scope.addPosToOrder=function(){
currentCustomer.changed=true;
if (currentCustomer.ordering=== undefined){
currentCustomer.ordering=[];
}
if(currentCustomer.ordering.length===0){
currentCustomer.ordering.push({comment:"",amount:0.0,status:'create'});
}
var order=currentCustomer.ordering[currentCustomer.ordering.length-1];
if(order.createDate===undefined){
order.createDate=new Date();
}
if(order.orderingPos===undefined){
order.orderingPos=[];
}
for(var i=0;i<order.orderingPos.length;i++){
if(order.orderingPos[i].id==$scope.orderingPos.id){
order.orderingPos[i]=$scope.orderingPos;
$rootScope.$broadcast('initProduct');
IndexedDb.saveCustomer(currentCustomer).then(
function(){
$rootScope.modal.remove();
location.assign("#/tab/basket")
}
);
return;
}
}
$scope.orderingPos.id=Math.floor(Math.random() * 10000);
order.orderingPos.push($scope.orderingPos);
$rootScope.$broadcast('initProduct');
IndexedDb.saveCustomer(currentCustomer).then(
function(){
$rootScope.modal.remove();
location.assign("#/tab/overview");
}
);
};
});
|
export default function test(input) {
const pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(!pattern.test( input )){
//invalid email
return false
}
return true;
}
|
import crypto from 'crypto';
import CryptoJS from 'crypto-js';
import {Toast,MessageBox} from 'mint-ui';
var mixin = {
data: () => {
return {
apiUrl: {
newsPull: '/tt/api/news/pull',
newsRefresh: '/tt/api/news/refresh',
newsGetDetail: '/tt/api/news/getDetail',
newsReport: '/tt/api/news/report',
userGetCode: '/tt/api/user/getcode',
userLogin: '/tt/api/user/login',
userWxLogin: '/tt/api/user/welogin',
userGetUser: '/tt/api/user/getuser',
userUpdateNick: '/tt/api/user/updatenick',
userBindPhone: '/tt/api/user/bindphone',
userUpdateBirthday: '/tt/api/user/updatebirthday',
userUpdateSex: '/tt/api/user/updatesex',
userUpdateImage: '/tt/api/user/updateimage',
userQuit: '/tt/api/user/quit',
taskHour: '/tt/api/task/hour',
taskVisit: '/tt/api/task/visit',
mentorIsmentor: '/tt/api/mentor/ismentor',
taskBalance: '/tt/api/task/balance',
mentorList: '/tt/api/mentor/list',
mentorCreateMentor: '/tt/api/mentor/creatementor',
taskDepsiHistory: '/tt/api/task/depsitHistory',
taskSiginList: '/tt/api/task/siginList',
taskSigin: '/tt/api/task/sigin',
taskMyTaskList: '/tt/api/task/myTaskList',
taskOnce: '/tt/api/task/once',
taskDay: '/tt/api/task/day',
shareApprentice: '/tt/api/share/apprentice',
userBindWechat: '/tt/api/user/bindwechat',
taskDoneDay: '/tt/api/task/done_day',
shareAwaken: '/tt/api/share/awaken',
cashGet: '/tt/api/cash/get',
cashBindAccount: '/tt/api/cash/bindaccount',
cashApply: '/tt/api/cash/apply',
questionSubmit: '/tt/api/question/submit',
newsGetVideoList: '/tt/api/news/getvideolist',
newsGetArticle: '/tt/api/news/getarticle',
newsGetNewsChannels: '/tt/api/news/getnewschannels',
newsGetVideoChannels: '/tt/api/news/getvideochannels',
taskTaskInfo: '/tt/api/task/tasksInfo',
newsGetAccessToken: '/tt/api/news/getaccesstoken',
shareGetCashList: '/tt/api/share/getcashlist',
cashOrders: '/tt/api/cash/orders',
fictionPull: '/tt/api/fiction/pull',
fictionCatalog: '/tt/api/fiction/catalog',
fictionContent: '/tt/api/fiction/content',
taskShare:'/tt/api/task/share',
adCarousel:'/tt/api/ad/carousel',
adDetailad:'/tt/api/ad/detailad',
taskWallList:'/tt/api/task/wallList',
taskDoneWall:'/tt/api/task/done_wall',
taskWall:'/tt/api/task/wall'
}
};
},
methods: {
/*格式化时间*/
formatDateTime(date, format) {
if (!date) {
return '';
}
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
var d = date.getDate();
d = d < 10 ? ('0' + d) : d;
var h = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
minute = minute < 10 ? ('0' + minute) : minute;
second = second < 10 ? ('0' + second) : second;
if (format == 'y-m-d h-m-s') {
return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
} else if (format == 'h-m') {
return ' ' + h + ':' + minute;
} else if (format == 'y-m-d') {
return y + '-' + m + '-' + d;
} else if (format == 'y/m/d') {
return y + '/' + m + '/' + d;
} else if (format == 'ymd') {
return y + '' + m + '' + d;
}
},
/*isLogin*/
isLogin() {
if (JSON.parse(localStorage.getItem('kdtt')) == null) {
// Toast({
// message: '请先登录',
// position: 'bottom',
// duration:1000
// });
this.$router.push({
path: 'login',
});
return false;
} else {
return true;
}
},
/*解密*/
decrypt(encrypted, key) {
if (!encrypted)
return '';
var keys = CryptoJS.enc.Latin1.parse(key);
var decrypted = CryptoJS.AES.decrypt(encrypted, keys, {
iv: keys,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
});
return decrypted.toString(CryptoJS.enc.Utf8);
},
/*加密*/
encrypt(encrypted, key) {
if (!encrypted)
return '';
var keys = CryptoJS.enc.Latin1.parse(key);
var decrypted = CryptoJS.AES.encrypt(encrypted, keys, {
iv: keys,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
}).toString();
return decrypted;
},
/*MD5*/
getmd5(str) {
var md5 = crypto.createHash('md5');
md5.update(str);
return md5.digest('hex');
},
/*token,siagn*/
creatSiagn(uri) {
let timestamp = localStorage.getItem('timestamp') != null ? localStorage.getItem('timestamp') : 0;
this.times = Date.parse(new Date()) / 1000 + parseInt(timestamp);
this.uuid = JSON.parse(localStorage.getItem('kdtt')).uuid;
this.token = JSON.parse(localStorage.getItem('kdtt')).token;
var str1 = uri + '?';
var str2 = `times=${this.times}&`;
var str3 = `uuid=${this.uuid}&`;
var str4 = 'token=' + this.token + '&';
var arr = new Array(str2, str3, str4);
var arr1 = arr.sort();
for (var i = 0; i < arr1.length; i++) {
str1 += arr1[i];
}
this.saign = this.getmd5(str1.substring(0, str1.length - 1)).toUpperCase();
this.userKey = this.token.substring(0, 16);
},
/*删除多个对象属性*/
delKey(obj, ...args) {
args.forEach(v => {
delete obj[v];
});
return obj;
},
//修改popup状态
popupUpdate(state) {
this.$store.dispatch({
type: 'popupChange',
status: state
});
},
/*判断是否安装微信客户端*/
isWeixin() {
let state = plus.runtime.isApplicationExist({pname: 'com.tencent.mm', action: 'weixin://'});
if (!state) {
plus.nativeUI.toast('未安装微信客户端');
}
return state;
},
/*修改状态栏背景颜色为红色*/
statusBarRed() {
plus.navigator.setStatusBarBackground('#e53625');
},
/*修改状态栏背景颜色为浅黑色*/
statusBarBlack() {
plus.navigator.setStatusBarBackground('#333333');
},
/*判断网络状态*/
networkStatus() {
let nt = plus.networkinfo.getCurrentType();
nt != 1 ? this.$store.state.noNetPic = false : this.$store.state.noNetPic = true;
return nt != 1;
},
/*获取网络类型*/
networkType() {
let nt = plus.networkinfo.getCurrentType();
if (nt == 3) {
this.$store.state.network = '2';
} else if (nt > 3) {
this.$store.state.network = '1';
}
},
/*删除指定缓存*/
deleteStorages(arr) {
var array = arr;
array.forEach(function (item) {
localStorage.removeItem(item);
});
},
/*push处理*/
pushMessage(obj) {
if (obj.article) {
let article = obj.article;
this.$router.push({
path: 'pushdetail',
query: {
url: article.url,
topic: article.topic,
imgUrl: article.imgUrl || '',
}
});
}
},
//手机号加密处理
phoneEncrypt(num) {
num = String(num);
return num.substr(0, 3) + '****' + num.substr(7);
},
//刷新、拉取列表上报
refreshUpload(channel, action, category) {
this.pointUpload(this, {
channel: channel,
action: action,
category: category
});
},
//切换频道上报
channelUpload(channel, from_category, to_category) {
this.pointUpload(this, {
channel: channel,
action: 5,
from_category: from_category,
to_category: to_category,
});
},
// 新闻、视频查看详情上报
detailClickUpload(channel, category, title, detail_id) {
this.pointUpload(this, {
channel: channel,
action: 3,
category: category,
title: title,
detail_id: detail_id,
});
},
// 小说查看详情上报
novelClickUpload(category, title, section) {
this.pointUpload(this, {
channel: 5,
action: 3,
category: category,
title: title,
section: section,
});
},
// 小说切换章节
novelContentUpload(category, title, from_channel, to_channel) {
this.pointUpload(this, {
channel: 5,
action: 22,
category: category,
title: title,
from_channel: from_channel,
to_channel: to_channel,
});
},
//我的模块上报
myUpload(category, obj) {
this.pointUpload(this, {
channel: 4,
action: 3,
category: category,
...obj
});
},
//登录上报
loginUpload(category, obj) {
this.pointUpload(this, {
action: 18,
category: category,
...obj
});
},
//任务上报
taskUpload(action, category) {
this.pointUpload(this, {
channel: 3,
action: action,
task: category,
});
},
//小视频上报
smallVideoUpload(category, title, detail_id, page) {
this.pointUpload(this, {
channel: 2,
action: 4,
category: category,
title: title,
detail_id: detail_id,
page: page,
});
},
/*上报服务器埋点*/
pointUpload(Vue, obj) {
let version = localStorage.getItem('version').split('_');
let imei = localStorage.getItem('imei');
let uuid = localStorage.getItem('kdtt') != null ? 'USR_' + JSON.parse(localStorage.getItem('kdtt')).uuid : 'GUEST_' + imei;
Vue.$http({
method: 'get',
url: 'http://api.55duanzi.com/z',
params: {
app_version: version[0],
app_store: version[1],
imei: imei,
uid: uuid, ...obj
},
});
},
//广告上报
adUpload(type,adId,srckey) {
this.adPointUpload(this, {
type: type,
val: adId,
srckey: srckey
});
},
/*广告上报服务器埋点*/
adPointUpload(Vue, obj) {
let version = localStorage.getItem('version').split('_');
let imei = localStorage.getItem('imei');
let uuid = localStorage.getItem('kdtt') != null ? 'USR_' + JSON.parse(localStorage.getItem('kdtt')).uuid : 'GUEST_' + imei;
Vue.$http({
method: 'get',
url: 'http://tuia.55duanzi.com/tuia/api/stat/pv',
params: {
app_version: version[0],
app_store: version[1],
deviceId: imei,
uid: uuid, ...obj
},
});
},
/*路由处理*/
routeBefore(to, from, Vue) {
let _this = this;
// 记录列表页滚动条位置
if (from.meta.title == 'index') {
let scrollTop = [];
$('.page-loadmore-wrapper').each(function (index, item) {
scrollTop.push(($(item).scrollTop()));
});
sessionStorage.setItem('scroll', scrollTop);
}
// 记录视频页滚动条位置
if (from.meta.title == 'videos') {
let scrollTop = [];
$('.page-loadmore-wrapper').each(function (index, item) {
scrollTop.push(($(item).scrollTop()));
});
sessionStorage.setItem('videoScroll', scrollTop);
}
// 记录小说页滚动条位置
if (from.meta.title == 'novels') {
let scrollTop = $('.novel-wrapper').scrollTop();
sessionStorage.setItem('novelScroll', scrollTop);
}
// 记录任务页滚动条位置
if (from.meta.title == 'thetask') {
let scrollTop = $('.thetask-wrapper').scrollTop();
sessionStorage.setItem('thetaskScroll', scrollTop);
}
//上报服务器埋点
let menuList = ['index', 'videos', 'thetask', 'personal', 'novels'];
let fromIndex = menuList.indexOf(from.meta.title);
let toIndex = menuList.indexOf(to.meta.title);
if (fromIndex >= 0 && toIndex >= 0) {
let params = {
action: '6',
from_channel: fromIndex + 1,
to_channel: toIndex + 1,
};
if (localStorage.getItem('version') != null && localStorage.getItem('imei') != null) {
_this.pointUpload(Vue, params);
} else {
document.addEventListener('plusready', function () {
plus.runtime.getProperty(plus.runtime.appid, function (inf) {
localStorage.setItem('version', inf.version);
localStorage.setItem('imei', plus.device.uuid.split(',')[0]);
_this.pointUpload(Vue, params);
});
}, false);
}
}
if (to.meta.category) {
let params = {
category: to.meta.category,
};
if (to.meta.channel)
params.channel = to.meta.channel;
if (to.meta.action)
params.action = to.meta.action;
_this.pointUpload(Vue, params);
}
},
routeAfter(to, from) {
let _this = this;
//修改状态栏颜色
if (window.plus) {
let routeArr = ['detail', 'tuia', 'login', 'setup', 'myname', 'myphone', 'mynews', 'about', 'agreement', 'feedback', 'videodetail', 'alipayInfo'];
if (routeArr.indexOf(to.meta.title) >= 0) {
_this.statusBarBlack();
} else {
_this.statusBarRed();
}
}
},
/*文件下载*/
fileDownLoad(url,pk,srckey) {
let _this=this;
MessageBox.confirm('', {
message: '是否下载该文件',
title: '提示',
confirmButtonText: '下载',
cancelButtonText: '取消'
}).then(action => {
if (action == 'confirm') { //确认的回调
console.log('开始下载');
var dtask = plus.downloader.createDownload(url, {filename: '_doc/download/'+new Date().getTime()+'.apk'}, function (d, status) {
// 下载完成
if (status == 200) {
console.log('下载成功');
_this.adUpload(8,pk,srckey);
plus.runtime.install(d.filename, {}, function () {
console.log('开始安装');
_this.adUpload(10,pk,srckey);
}, function (DOMException) {
console.log('安装失败');
console.log(JSON.stringify(DOMException));
_this.adUpload(11,pk,srckey);
});
} else {
plus.nativeUI.toast('下载失败');
_this.adUpload(9,pk,srckey);
}
});
dtask.start();
}
}).catch(err => {
if (err == 'cancel') { //取消的回调
console.log('取消下载');
this.adUpload(7,pk,srckey);
}
});
},
/*文件下载(已不用)*/
webviewDown(url) {
var w = plus.webview.open(url, '', {left: '100%'});
},
/*跳转链接*/
gowx() {
var url='http://jump.ui879.com/WeChat/?k=cb5ffcbba8e47419e7c8f12254a907f&i=1087';
var w = plus.webview.open(url, 'wx');
},
/*跳转链接*/
gosavemoneypay() {
console.log('跳转链接测试');
let isSaveMoneyPay=plus.runtime.isApplicationExist({pname:'com.rebate.ky',action:'savemoneypay://'});
console.log(isSaveMoneyPay);
if(isSaveMoneyPay){
location.href='savemoneypaydev://';
}else{
this.downInstall('http://s.55duanzi.com/rebate/apk/kdsavemoneypay.apk','下载中请耐心等候');
}
},
/*更新原生包*/
gokoudai() {
let _this=this;
MessageBox.confirm('', {
message: '发现新版本,请升级后进行提现操作',
title: '提示',
confirmButtonText: '确定',
cancelButtonText: '稍后'
}).then(action => {
if (action == 'confirm') { //确认的回调
console.log('开始下载');
_this.downInstall('http://s.55duanzi.com/newsapp/apk/kdtixian_release_v1.4.0_200_20180930.apk','更新中请耐心等候');
}
}).catch(err => {
if (err == 'cancel') { //取消的回调
console.log('取消下载');
}
});
},
/*下载安装文件*/
downInstall(url,tip){
plus.nativeUI.showWaiting(tip);
var dtask = plus.downloader.createDownload(url, {filename: '_doc/download/'}, function (d, status) {
// 下载完成
plus.nativeUI.closeWaiting();
if (status == 200) {
plus.runtime.install(d.filename, {}, function () {
}, function (DOMException) {
console.log(JSON.stringify(DOMException));
});
} else {
plus.nativeUI.toast('Download failed: ' + status);
}
});
dtask.start();
}
}
};
export default mixin;
|
[
{
"creatDate": "2018-09-04",
"id": "10918",
"image": "/d/file/whmm/2018-09-04/e1a50040533c2af0cfa3c7f18fa6adee.jpg",
"longTime": "00:16:22",
"title": "CB氣賍美女直播給男友服務",
"video": "https://play.cdmbo.com/20180903/jh20R9id/index.m3u8"
},
{
"creatDate": "2018-09-04",
"id": "10912",
"image": "/d/file/whmm/2018-09-04/a6dfcdca281e79a80bcdf7659ea767dd.jpg",
"longTime": "00:26:17",
"title": "小耳朵露臉制服絲襪,皮膚白皙極品翹臀第二季_",
"video": "https://play.cdmbo.com/20180903/UCNdPSKs/index.m3u8"
},
{
"creatDate": "2018-09-04",
"id": "10913",
"image": "/d/file/whmm/2018-09-04/826d63ef99680dafbe3f52e067efcebf.jpg",
"longTime": "00:42:33",
"title": "白膚性感情趣內衣美少婦和粉絲直播啪對白清晰0",
"video": "https://play.cdmbo.com/20180903/aYVF9LCd/index.m3u8"
},
{
"creatDate": "2018-09-04",
"id": "10915",
"image": "/d/file/whmm/2018-09-04/24a3e18aa229b02bba2cdfb39bd6c5a1.jpg",
"longTime": "00:15:38",
"title": "UT高顏值美女020",
"video": "https://play.cdmbo.com/20180903/H6NtoKg2/index.m3u8"
}
]
|
import { REVIEW_ITEM } from "../actions/actions_customer_review";
const customerReview = (state = {}, action) => {
let output;
let data;
switch (action.type) {
case REVIEW_ITEM:
data = action.payload.success ? action.payload.data : action.payload.message;
output = { reviewItem: data };
break;
default:
output = state;
break;
}
return output;
};
export default customerReview;
|
module.exports = {
'Replace': require('./Replace'),
'Transform': require('./Transform'),
}
|
if ( typeof(tests) != "object" ) {
tests = [];
}
var setupTest = function (collection) {
collection.drop();
for ( var i = 0; i < 4800; i++ ) {
collection.insert( { x : i, a : i } );
}
collection.getDB().getLastError();
}
var setupTestFiltered = function (collection) {
setupTest(collection);
collection.createIndex( { x : 1 }, { filter : { a : { $lt : 500 } } } );
}
var setupTestFilteredNonSelective = function (collection) {
setupTest(collection);
collection.createIndex( { x : 1 }, { filter : { a : { $lt : 4800 } } } );
}
var setupTestIndexed = function (collection) {
setupTest(collection);
collection.createIndex( { x : 1 });
}
tests.push( { name : "Queries.PartialIndex.v1.FilteredRange",
tags: ['partial_index','query','daily','weekly','monthly'],
pre: function( collection ) {
setupTestFiltered(collection);
},
ops : [
{ op: "find", query: { x : {"#RAND_INT" : [ 0, 500 ]}, a : {$lt : 500 } } }
] } );
tests.push( { name : "Queries.PartialIndex.v1.NonFilteredRange",
tags: ['partial_index','query','daily','weekly','monthly'],
pre: function( collection ) {
setupTestFiltered(collection);
},
ops : [
{ op: "find", query: { x : {"#RAND_INT" : [ 500, 4800 ]}, a : {$gte : 500 } } }
] } );
tests.push( { name : "Queries.PartialIndex.v1.FullRange",
tags: ['partial_index','query','daily','weekly','monthly'],
pre: function( collection ) {
setupTestFiltered(collection);
},
ops : [
{ op: "find", query: { x : {"#RAND_INT" : [ 0, 4800 ]}, a : {$lt : 4800 } } }
] } );
tests.push( { name : "Queries.PartialIndex.v1.FilteredRange.Inequality",
tags: ['partial_index','query','daily','weekly','monthly'],
pre: function( collection ) {
setupTestFiltered(collection);
},
ops : [
{ op: "findOne", query: { x : {$lte : {"#RAND_INT" : [ 0, 500 ]}}, a : {$lt : 500 } } }
] } );
tests.push( { name : "Queries.PartialIndex.v1.NonFilteredRange.Inequality",
tags: ['partial_index','query','daily','weekly','monthly'],
pre: function( collection ) {
setupTestFiltered(collection);
},
ops : [
{ op: "findOne", query: { x : {$lte : {"#RAND_INT" : [ 500, 4800 ]}}, a : {$gte : 500 } } }
] } );
tests.push( { name : "Queries.PartialIndex.v1.FullRange.Inequality",
tags: ['partial_index','query','daily','weekly','monthly'],
pre: function( collection ) {
setupTestFiltered(collection);
},
ops : [
{ op: "findOne", query: { x : {$lte : { "#RAND_INT" : [ 0 , 4800 ]}}, a : {$lt : 4800 } } }
] } );
// Compare to the selective. How much does the selective help?
tests.push( { name : "Queries.PartialIndex.AllInFilter.v1.FilteredRange",
tags: ['partial_index','query','weekly','monthly'],
pre: function( collection ) {
setupTestFilteredNonSelective(collection);
},
ops : [
{ op: "find", query: { x : {"#RAND_INT" : [ 0, 500 ]}, a : {$lt : 500 } } }
] } );
// Compare to the regular index case
tests.push( { name : "Queries.PartialIndex.AllInFilter.v1.FullRange",
tags: ['partial_index','query','weekly','monthly'],
pre: function( collection ) {
setupTestFilteredNonSelective(collection);
},
ops : [
{ op: "find", query: { x : { "#RAND_INT" : [ 0 , 4800 ] }, a : {$lt : 4800 } } }
] } );
// compare to the filtered selective case. Any difference?
tests.push( { name : "Queries.PartialIndex.AllInFilter.v1.FilteredRange.Inequality",
tags: ['partial_index','query','weekly','monthly'],
pre: function( collection ) {
setupTestFilteredNonSelective(collection);
},
ops : [
{ op: "findOne", query: { x : {$lte : {"#RAND_INT" : [ 0, 500 ]}}, a : {$lt : 500 } } }
] } );
// compare to regular index
tests.push( { name : "Queries.PartialIndex.AllInFilter.v1.FullRange.Inequality",
tags: ['partial_index','query','weekly','monthly'],
pre: function( collection ) {
setupTestFilteredNonSelective(collection);
},
ops : [
{ op: "findOne", query: { x : {$lte : { "#RAND_INT" : [ 0 , 4800 ] }}, a : {$lt : 4800 } } }
] } );
|
/**
* Created by Mac on 1/30/2016.
*/
doStuff = function(){
p = parseFloat(document.getElementById("txtPrincipal").value)
r = parseFloat(document.getElementById("txtInterestRate").value) / 100
t = parseFloat(document.getElementById("txtYears").value)
a = p*(1 + r*t)
document.getElementById("txtOutput").innerHTML = ["Accrued", a].join(" ")
}
|
import React from 'react';
//Old Syntax
// export default class AddOption extends React.Component {
// constructor(props){
// super(props);
// this.onSubmitHandle = this.onSubmitHandle.bind(this);
// this.state = {
// error: undefined
// }
// }
// onSubmitHandle(event) {
// event.preventDefault();
// const option = event.target.elements.option.value.trim();
// const error = this.props.handleAddOption(option);
// this.setState (() => ({ error }));
// if(!error){
// event.target.elements.option.value = "";
// }
// }
// render(){
// return (
// <div>
// {this.state.error && <p>{this.state.error}</p>}
// <form onSubmit={this.onSubmitHandle}>
// <input type="text" placeholder="new option" name="option"/>
// <button>Submit</button>
// </form>
// </div>
// );
// }
// }
//New Syntax with babel plugin which removes the need for this binding
export default class AddOption extends React.Component {
state = {
error: undefined
}
handleAddOption = (event) => {
event.preventDefault();
const option = event.target.elements.option.value.trim();
const error = this.props.handleAddOption(option);
this.setState (() => ({ error }));
if(!error){
event.target.elements.option.value = "";
}
};
render(){
return (
<div>
{this.state.error && <p className="add-option-error">{this.state.error}</p>}
<form className="add-option" onSubmit={this.handleAddOption}>
<input className="add-option__input" type="text" name="option"/>
<button className="button">Submit</button>
</form>
</div>
);
}
}
|
import React from 'react';
import {render, screen, cleanup} from '@testing-library/react'
import userEvent from '@testing-library/user-event';
import {act} from 'react-dom/test-utils'
import BooleanInput from '../BooleanInput';
import * as questionnaireTemplate from '../../assets/questionnaire.json'
afterEach(() => {
cleanup()
});
test('Check that label is rendered', async () => {
let formData = {}
let setFormData = (data)=>{
formData = data
}
render(<BooleanInput
formData={formData}
setFormData={setFormData}
item={{
linkId:'1',
text:"test text"
}}
/>)
expect(screen.getByText('test text')).toBeVisible()
});
test('Check that "Yes" means true and "No" means false', async () => {
let formData = {}
let setFormData = (data)=>{
formData = data
}
render(<BooleanInput
formData={formData}
setFormData={setFormData}
item={{
linkId:'1',
text:"test text"
}}
/>)
let TrueButton = screen.getByLabelText(/Yes/i)
userEvent.click(TrueButton)
expect(formData['1']).toBe('true')
let FalseButton = screen.getByLabelText(/No/i)
userEvent.click(FalseButton)
expect(formData['1']).toBe('false')
});
|
var app = getApp()
Page({
data: {
remain: 12,
bag: 2,
list: [{
'id': 1,
'img': '../../images/widthdraw.png',
'name': "审核管理",
'url': 'examine_list',
'bg': '#34ff74'
},
{
'id': 2,
'img': '../../images/remain.png',
'name': "收入记录",
'url': 'remain',
'bg': '#ff5c71'
},
{
'id': 3,
'img': '../../images/tixian.png',
'name': "提现",
'url': 'widthdraw',
'bg': '#5c9cff'
},
{
'id': 4,
'img': '../../images/user_info.png',
'name': "个人信息",
'url': 'user_info',
'bg': '#ffa15c'
}
],
},
onLoad: function () {
wx.setNavigationBarTitle({
title: '个人中心'
})
},
onShareAppMessage: function () {
return {
title: app.globaldata.ShareAppTitle,
desc: app.globaldata.ShareAppDesc,
path: '/pages/index/index'
}
}
})
|
import React from 'react'
import Subcribe from '../components/Subcribe'
import Title from '../components/Title'
export default function Contact() {
return (
<div className='hero pt-6'>
<div className='mx-4'>
{/* Title */}
<h1 className='is-size-1 has-text-weight-bold has-text-link'>
Contact
</h1>
<p
className='is-size-6 has-text-link ml-6 mb-5'
style={{ maxWidth: 300 }}
>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit
tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
</p>
{/* End Title */}
<div className='columns is-vcentered mb-6'>
<div className='column is-5-desktop'>
<Questions />
</div>
<div className='column is-7-desktop'>
<Form />
</div>
</div>
</div>
<Subcribe />
</div>
)
}
export const Questions = () => {
return (
<div className='menu mt-6'>
<Title subtitle='Have a question ?'>
<p className='subtitle has-text-link'>
Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin,
lorem quis bibendum auctor, nisi elit consequat.
</p>
</Title>
<ul className='menu-list ml-6' style={{ lineHeight: 2 }}>
<li className='mb-2'>
<h4 className='is-size-4 has-text-weight-bold has-text-link '>
Emergency? Call Us:
</h4>
<p className='subtitle has-text-link'>+1 234 567 890</p>
</li>
<li className='mb-2'>
<h4 className='is-size-4 has-text-weight-bold has-text-link '>
Send us Email
</h4>
<p className='subtitle has-text-link'>info@exaple.com</p>
</li>
</ul>
</div>
)
}
export const Form = () => {
return (
<form className='box has-background-primary-light'>
<input
type='text'
className='input m-1 has-background-grey-light'
placeholder='Name'
/>
<input
type='email'
className='input m-1 has-background-grey-light'
placeholder='Email'
/>
<input
type='text'
className='input m-1 has-background-grey-light'
placeholder='Text'
/>
<textarea
className='textarea has-background-grey-light'
placeholder='Your Message'
/>
<button className='button is-primary mt-3'>Send Message</button>
</form>
)
}
|
function applyFilters( args ) {
var pattern_pagination = /\/page\/[0-9]*/;
var pathname = window.location.pathname;
pathname = pathname.replace(pattern_pagination, "");
var url = window.location.protocol + '//' + window.location.host + pathname;
for (var k in args){
if ( (k !== null && k !== '') && (args[k] !== null && args[k] !== '')) {
if (url.indexOf('?') > -1)
url += '&'+k+'='+args[k];
else
url += '?' + k + '=' + args[k];
}
window.location.href = url;
}
}
|
'use strict';
$(document).ready(function() {
window.addEventListener('resize', onResize);
// 사이드 네비
el('#nav-btn').addEventListener('click', openSidenav);
el('#close-nav-btn').addEventListener('click', closeSidenav);
// 상단바
el('#topbar-btn').addEventListener('click', openTopbar);
el('#close-topbar-btn').addEventListener('click', closeTopbar);
el('#find-teacher-btn').addEventListener('click', closeTopbar);
// 사이드 네비 닫기 -> 상단바 열기 (강사진 찾기)
el('#close-open-btn').addEventListener('click', function() {
closeSidenav();
openTopbar();
});
// 배경
el('#mask').addEventListener('click', function() {
closeSidenav();
closeTopbar();
});
/****** 모달 *******/
// 모달 닫기 이벤트
$('#modal-wrap').on('click', function(e) {
e = window.event || e;
if (this === e.target) {
closeModal();
}
return false;
});
$('#modal-wrap').on('click', '.close-btn', function() {
closeModal();
return false;
});
// 모달 열기
$(document).on('click', '[data-modal]', function() {
var modal = $(this).attr('data-modal');
openModal(modal);
return false;
});
$('#modal-wrap').on('click', '[data-modal]', function() {
var modal = $(this).attr('data-modal');
openModal(modal);
return false;
});
})();
/*********************** functions *************************/
// element
function el(selector) {
return document.querySelector(selector);
}
// 사이드네비, 상단바 보일때 body 어둡게
function setMask(isActive) {
if (isActive) {
document.querySelector('#mask').classList.add('active');
document.body.classList.add('active-mask');
} else {
document.querySelector('#mask').classList.remove('active');
document.body.classList.remove('active-mask');
}
}
// 사이드 네비 열고 닫기
function openSidenav() {
document.querySelector('#sidenav').classList.add('active');
setMask(true);
}
function closeSidenav() {
document.querySelector('#sidenav').classList.remove('active');
setMask(false);
}
// 상단바 열고 닫기
function openTopbar() {
document.querySelector('#topbar').classList.add('active');
setMask(true);
}
function closeTopbar() {
document.querySelector('#topbar').classList.remove('active');
setMask(false);
}
// 사이드 메뉴바
function onResize() {
if (isNotMobile()) {
if (document.querySelector('#sidenav').classList.contains('active')) {
closeSidenav();
}
if (document.querySelector('#topbar').classList.contains('active')) {
closeTopbar();
}
}
}
// width 판별
function isNotMobile() {
return window.innerWidth > 991;
}
/*
* 모달
*
* 모달창 html 만들고 ajax로 호출하게 개발했습니다.
*/
function openModal(modal) {
$.ajax({
url: 'modals/' + modal + '.html',
dataType: 'html',
success: function(data) {
$('body').addClass('active-mask');
var $modal = $('#modal-wrap');
$modal.html(data);
$modal.addClass('active');
},
error: function(xhr, status, error) {
console.error(error);
return false;
}
});
}
function closeModal() {
var $modal = $('#modal-wrap');
$modal.removeClass('active');
$modal.empty();
$('body').removeClass('active-mask');
}
|
describe('Core config', () => {
jest.mock('../../server/config/mq-config', () => ({}))
test('throws error for invalid port', async () => {
let caughtError
process.env.PORT = 'invalid'
try {
require('../../server/config')
} catch (error) {
caughtError = error
}
expect(caughtError.message).toBe(
'The server config is invalid. "port" must be a number'
)
})
})
|
function compact(ary) {
return ary.filter(it => it)
}
function flatten(ary) {
return [].concat(...ary.slice())
}
function flattenDeep(ary) {
let flatted = []
for (let i = 0; i < ary.length; i++) {
let item = ary[i]
if (Array.isArray(item)) {
flatted = flatted.concat(flattenDeep(item))
} else {
flatted.push(item)
}
}
return flatted
}
function flattenDepth(ary, depth = 0) {
for (let i = 0; i < depth; i++) {
ary = flatten(ary)
}
return ary
}
function flip(func) {
return function (...args) {
return func(...args.reverse())
}
}
function before(n, func) {
let count = 0
let lastResult
return function (...args) {
count += 1
if (count < n) {
lastResult = func(...args)
return lastResult
} else {
return lastResult
}
}
}
function negate(f) {
return function () {
return !f.apply(null, arguments)
}
}
function memorize(f) {
let cache = {}
return function (arg) {
if (arg in cache) {
return cache[arg]
} else {
return cache[arg] = f(...arg)
}
}
}
function spread(func, start = 0) {
return function (argsAry) {
let spreadArgs = argsAry.slice(start)
return func(...spreadArgs)
}
}
// 必须使用 var
// 函数变量名小写
var thxiami = {
compact,
flatten,
flattenDeep,
flattenDepth,
flip,
before,
// every,
// some,
spread,
// ary,
// unary,
// memorize,
// curry,
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.