text
stringlengths 7
3.69M
|
|---|
module.exports = function (p) {
'use strict';
var through = require('through2')
, path = require('path')
, fs = require('fs');
function replace(file, cb) {
var string = String(file.contents)
, res = [];
string = string.replace(/\<inline.*?src\=('|")(.*?)\1.*?\/?\>/g, function (all, quz, src) {
src = path.resolve(path.dirname(file.path), src);
fs.readFileSync(src);
}).replace(/\<script.*?src\=('|")(.*?)\?__inline\1.*?\>[\s\S]*?\<\/script\>/g, function (all, quz, src) {
src = path.resolve(path.dirname(file.path), src);
return '<script>' + fs.readFileSync(src) + '</script>';
}).replace(/\<link\s+inline[\s\S]+?href\=('|")(.*?)\1.*?\>/g, function (all, quz, src) {
src = path.resolve('./dist', src);
var basenames = path.basename(src).split('.')
, dirname = path.dirname(src)
, dirs = fs.readdirSync(dirname)
, reg
, res;
dirs.forEach(function (dir) {
var dirs = dir.split('.');
dirs.splice(dirs.length - 2, 1);
var match = true;
for (var i = 0, l = dirs.length; i < l; i++) {
if (dirs[i] !== basenames[i]) {
match = false;
}
}
if (match) {
res = fs.readFileSync(path.join(dirname, dir));
}
});
return '<style>' + res + '</style>';
});
file.contents = new Buffer(string);
cb(file);
}
function htmlInline() {
var stream = through.obj(function (file, enc, callback) {
if (file.isNull()) {
this.push(file);
return callback();
}
if (file.isBuffer()) {
var self = this;
replace(file, function (file) {
self.push(file);
callback();
});
return;
}
if (file.isStream()) {
this.emit('error', new PluginError('Dwarf', 'Streams are not supported!'));
return callback();
}
});
return stream;
}
return htmlInline;
}();
|
//declare variables
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
mongoose = require("mongoose"),
auth = require("./config/auth"),
passport = require("passport"),
GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
addNewUser = require('./addNewUser.js'),
refreshSubscriberChannels = require("./refreshSubscriberChannels.js"),
//models variables
User = require("./models/user"),
//routes variables
videoRoutes = require("./routes/videoRoutes"),
channelRoutes = require("./routes/channelRoutes"),
authRoutes = require("./routes/authRoutes"),
userRoutes = require("./routes/userRoutes"),
locationRoutes = require("./routes/locationRoutes"),
apiRoutes = require("./routes/apiRoutes"),
vlogRoutes = require("./routes/vlogRoutes"),
isLoggedIn = require("./isLoggedIn.js");
//set parameters
mongoose.connect("mongodb://localhost/caseyvlogs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride("_method"));
app.set("view engine", "ejs");
//set session secret key
app.use(require("express-session")({
secret: "teddyisthesleepiestpuppy",
resave: false,
saveUninitialized: false
}));
//passport requirements
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
//load routes
app.use('/videos', isLoggedIn, videoRoutes);
app.use('/channels', isLoggedIn, channelRoutes);
app.use('/vlogs', isLoggedIn, vlogRoutes);
app.use('/users', isLoggedIn, userRoutes);
app.use(authRoutes);
app.use(apiRoutes);
app.use(locationRoutes);
passport.use(new GoogleStrategy({
clientID: auth.googleAuth.clientID,
clientSecret: auth.googleAuth.clientSecret,
callbackURL: auth.googleAuth.callbackURL,
},
function(accessToken, refreshToken, profile, done) {
process.nextTick(function(){
User.findOne({'google.id' : profile.id}, function(err, user){
console.log("auth running");
if(err) {
return done(err);
} else if(user) {
user.google.accessToken = accessToken;
user.save();
refreshSubscriberChannels(user, function(err, status) {
if(err) return err;
user.save();
return done(null, user);
});
} else {
console.log("creating new user");
addNewUser(accessToken, refreshToken, profile, function(err, newUser) {
if(err) return err;
refreshSubscriberChannels(newUser, function(err, status) {
newUser.save();
return done(null, newUser);
})
})
}
});
});
}
));
// server listen
app.listen(process.env.PORT, process.env.IP, function() {
console.log("Casey's Vlogs are Now Live!");
});
|
(function() {
'use strict';
var app = angular.module('app', [ 'smart-table', 'lrDragNDrop' ]);
app.factory('DOMUtilService', function($rootScope) {
var domUtils = {
getElementBox: getElementBox,
adjustExpandedRows: adjustExpandedRows
};
return domUtils;
function getElementBox(element, orientation) {
var elementPadBorder = { border: 0, padding: 0 };
var elementComputedStyle = window.getComputedStyle(element);
var orientKeys = orientation === 'vertical' ? [ 'top', 'bottom' ] : [ 'left', 'right' ];
angular.forEach(orientKeys, function(pos, i) {
var borderKey = 'border-' + pos + '-width';
var borderValue = parseFloat(elementComputedStyle.getPropertyValue(borderKey));
elementPadBorder[borderKey] = borderValue;
elementPadBorder.border += borderValue;
var padKey = 'padding-' + pos;
var paddingValue = parseFloat(elementComputedStyle.getPropertyValue(padKey));
elementPadBorder[padKey] = paddingValue;
elementPadBorder.padding += paddingValue;
});
var widthOrHeight = orientation === 'vertical' ? 'height' : 'width';
elementPadBorder[widthOrHeight] = parseFloat(elementComputedStyle.getPropertyValue(widthOrHeight));
return elementPadBorder;
}
function adjustExpandedRows(table) {
var expandedRows = table.find('tbody')[0].querySelectorAll('.expanded');
if (expandedRows.length > 0) {
var hasSelection = table.hasClass('select-table');
var summaryFirstCell = expandedRows[0].previousSibling.previousSibling.querySelector('td:first-child');
var summaryRowCell = hasSelection ? summaryFirstCell.nextElementSibling : summaryFirstCell;
var summaryRowCellBox = getElementBox(summaryRowCell, 'vertical');
var summaryRowCellHeight = summaryRowCellBox.height + summaryRowCellBox.border;
angular.forEach(expandedRows, function(expandedRow) {
var summaryRow = expandedRow.previousSibling.previousSibling;
var expandedFirstCell = expandedRow.querySelector('td:first-child');
var expandedCell = hasSelection ? expandedFirstCell.nextElementSibling : expandedFirstCell;
var expandedCellBox = getElementBox(expandedCell, 'vertical');
var actionColHeight = summaryRowCellHeight + expandedCellBox.height + expandedCellBox.border;
summaryRow.querySelector('td:last-child').style.height = actionColHeight + 'px';
});
}
}
});
function MainCtrl($scope) {
$scope.rowCollection = [
{ name: 'm1.nano', vcpus: '2', ram: '64 MB', totalDisk: '0 GB', rootDisk: '0 GB', ephemeralDisk: '0 GB', isPublic: 'Yes' },
{ name: 'm1.small', vcpus: '1', ram: '2048 MB', totalDisk: '20 GB', rootDisk: '20 GB', ephemeralDisk: '0 GB', isPublic: 'Yes' },
{ name: 'm1.medium', vcpus: '1', ram: '4096 MB', totalDisk: '40 GB', rootDisk: '40 GB', ephemeralDisk: '0 GB', isPublic: 'Yes' },
{ name: 'm1.nano', vcpus: '2', ram: '64 MB', totalDisk: '0 GB', rootDisk: '0 GB', ephemeralDisk: '0 GB', isPublic: 'Yes' },
{ name: 'm1.small', vcpus: '1', ram: '2048 MB', totalDisk: '20 GB', rootDisk: '20 GB', ephemeralDisk: '0 GB', isPublic: 'Yes' },
{ name: 'm1.medium', vcpus: '1', ram: '4096 MB', totalDisk: '40 GB', rootDisk: '40 GB', ephemeralDisk: '0 GB', isPublic: 'Yes' }
];
$scope.addRow = function() {
var large = { name: 'm1.large', vcpus: '1', ram: '4096 MB', totalDisk: '40 GB', rootDisk: '40 GB', ephemeralDisk: '0 GB', isPublic: 'Yes' };
$scope.rowCollection.push(large);
}
};
app.controller('MainCtrl', [ '$scope', MainCtrl ]);
app.directive('responsiveSmartTable', [ '$window', '$timeout', 'DOMUtilService', function($window, $timeout, DOMUtilService) {
var directive = {
restrict: 'A',
link: link
};
return directive;
function link(scope, element, attrs) {
angular.element($window).bind('resize', function() {
resizeTableHeights();
scope.$apply();
});
var dataUnwatch = scope.$watch(attrs.stTable, initTable, true);
scope.$on('$destroy', function() {
angular.element($window).off('resize', resizeTableHeights);
dataUnwatch();
});
$timeout(initTable, 0);
function initTable() {
scope.lastWidth = $window.innerWidth;
if (element.hasClass("action-table")) {
var actionCol = element.find('tbody')[0].querySelector('tr:first-child td:last-child');
var actionColBox = DOMUtilService.getElementBox(actionCol, 'horizontal');
var rightBorderWidth = actionColBox['border-right-width'];
var actionColWidth = actionCol.scrollWidth;
var actionColHeader = element.find('thead')[0].querySelector('tr:last-child th:last-child');
var actionColHeaderBox = DOMUtilService.getElementBox(actionColHeader, 'horizontal');
var actionColHeaderWidth = actionColHeader.scrollWidth;
var largerWidth = Math.max(actionColHeaderWidth, actionColWidth) - rightBorderWidth;
element.css('padding-right', largerWidth + 'px');
if (actionColHeaderWidth < actionColWidth) {
actionColHeader.style.width = (actionColBox.width + actionColBox.border) + 'px';
} else {
var actionCols = element.find('tbody')[0].querySelectorAll('tr td:last-child');
angular.forEach(actionCols, function(col) {
col.style.width = (actionColHeaderBox.width - rightBorderWidth) + 'px';
});
}
}
}
function resizeTableHeights() {
if (element.hasClass('action-table')) {
var curWidth = $window.innerWidth;
if (curWidth !== scope.lastWidth) {
DOMUtilService.adjustExpandedRows(element);
scope.lastWidth = curWidth;
}
}
}
}
}]);
app.directive('rstExpandable', [ 'DOMUtilService', function(DOMUtilService) {
var directive = {
restrict: 'A',
link: link
};
return directive;
function link(scope, element) {
element.on('click', function() {
var summaryRow = element.parent().parent();
var detailRow = summaryRow.next();
var table = summaryRow.parent().parent();
element.toggleClass('fa-chevron-right').toggleClass('fa-chevron-down');
detailRow.toggleClass('expanded');
if (table.hasClass('action-table')) {
var summaryRowElt = summaryRow[0];
if (!detailRow.hasClass('expanded')) {
summaryRowElt.querySelector('td:last-child').style.height = 'inherit';
}
DOMUtilService.adjustExpandedRows(table);
}
});
}
}]);
})();
|
var app = angular.module("setPoints", []);
//app.controller("points", function($http, $scope) {
// var controller = this;
//
// controller.updatePoints = [];
// $scope.updatePoints = function() {
// };
//
// $http.post("/rating", Userpoints);
//
//});
app.controller("score", function($http, $scope) {
var controller = this;
controller.users = [];
$scope.getScore = function() {
$http.get("/getScore").then(function(value) {
controller.users = value.data;
}, function(reason) {
window.alert("Error");
},function($scope){
$scope.users;
})
};
});
|
import React, { Component } from 'react'
export default class UserContainer extends Component {
render() {
console.log('userC: ',this.props)
return (
<>
<p className='user-name'>{this.props.details.first_name} {this.props.details.last_name}</p>
{/* <p onClick={this.handleSubmit} className='user-logout'>log out</p> */}
</>
)
}
}
|
var twttr = {
"txt": {
"regexen": {
"spaces_group": function () {},
"spaces": function () {},
"invalid_chars_group": function () {},
"punct": function () {},
"rtl_chars": function () {},
"nonLatinHashtagChars": function () {},
"latinAccentChars": function () {},
"hashSigns": function () {},
"hashtagAlpha": function () {},
"hashtagAlphaNumeric": function () {},
"endHashtagMatch": function () {},
"hashtagBoundary": function () {},
"validHashtag": function () {},
"validMentionPrecedingChars": function () {},
"atSigns": function () {},
"validMentionOrList": function () {},
"validReply": function () {},
"endMentionMatch": function () {},
"validUrlPrecedingChars": function () {},
"invalidUrlWithoutProtocolPrecedingChars": function () {},
"invalidDomainChars": {},
"validDomainChars": function () {},
"validSubdomain": function () {},
"validDomainName": function () {},
"validGTLD": function () {},
"validCCTLD": function () {},
"validPunycode": function () {},
"validDomain": function () {},
"validAsciiDomain": function () {},
"invalidShortDomain": function () {},
"validPortNumber": function () {},
"validGeneralUrlPathChars": function () {},
"validUrlBalancedParens": function () {},
"validUrlPathEndingChars": function () {},
"validUrlPath": function () {},
"validUrlQueryChars": function () {},
"validUrlQueryEndingChars": function () {},
"extractUrl": function () {},
"validTcoUrl": function () {},
"cashtag": function () {},
"validCashtag": function () {},
"validateUrlUnreserved": function () {},
"validateUrlPctEncoded": function () {},
"validateUrlSubDelims": function () {},
"validateUrlPchar": function () {},
"validateUrlScheme": function () {},
"validateUrlUserinfo": function () {},
"validateUrlDecOctet": function () {},
"validateUrlIpv4": function () {},
"validateUrlIpv6": function () {},
"validateUrlIp": function () {},
"validateUrlSubDomainSegment": function () {},
"validateUrlDomainSegment": function () {},
"validateUrlDomainTld": function () {},
"validateUrlDomain": function () {},
"validateUrlHost": function () {},
"validateUrlUnicodeSubDomainSegment": function () {},
"validateUrlUnicodeDomainSegment": function () {},
"validateUrlUnicodeDomainTld": function () {},
"validateUrlUnicodeDomain": function () {},
"validateUrlUnicodeHost": function () {},
"validateUrlPort": function () {},
"validateUrlUnicodeAuthority": function () {},
"validateUrlAuthority": function () {},
"validateUrlPath": function () {},
"validateUrlQuery": function () {},
"validateUrlFragment": function () {},
"validateUrlUnencoded": function () {}
},
"htmlEscape": function () {},
"regexSupplant": function () {},
"stringSupplant": function () {},
"addCharsToCharClass": function () {},
"tagAttrs": function () {},
"linkToText": function () {},
"linkToTextWithSymbol": function () {},
"linkToHashtag": function () {},
"linkToCashtag": function () {},
"linkToMentionAndList": function () {},
"linkToUrl": function () {},
"linkTextWithEntity": function () {},
"autoLinkEntities": function () {},
"autoLinkWithJSON": function () {},
"extractHtmlAttrsFromOptions": function () {},
"autoLink": function () {},
"autoLinkUsernamesOrLists": function () {},
"autoLinkHashtags": function () {},
"autoLinkCashtags": function () {},
"autoLinkUrlsCustom": function () {},
"removeOverlappingEntities": function () {},
"extractEntitiesWithIndices": function () {},
"extractMentions": function () {},
"extractMentionsWithIndices": function () {},
"extractMentionsOrListsWithIndices": function () {},
"extractReplies": function () {},
"extractUrls": function () {},
"extractUrlsWithIndices": function () {},
"extractHashtags": function () {},
"extractHashtagsWithIndices": function () {},
"extractCashtags": function () {},
"extractCashtagsWithIndices": function () {},
"modifyIndicesFromUnicodeToUTF16": function () {},
"modifyIndicesFromUTF16ToUnicode": function () {},
"convertUnicodeIndices": function () {},
"splitTags": function () {},
"hitHighlight": function () {},
"getTweetLength": function () {},
"isInvalidTweet": function () {},
"isValidTweetText": function () {},
"isValidUsername": function () {},
"isValidList": function () {},
"isValidHashtag": function () {},
"isValidUrl": function () {}
}
}
|
app.controller("myCtrl", function($scope) {
$scope.name = "";
$scope.getName = function() {
if($scope.name === "")
return $scope.name;
else
return("Hello " + $scope.name);
}
$scope.alertName = function() {
window.alert("Hello " + $scope.name);
}
});
|
import React, { useState, useEffect } from "react";
const EditUser = ({ user, index, updateUser }) => {
const { name, share, paid } = user;
const [userName, setUserName] = useState(name);
const [userShare, setUserShare] = useState(share);
const [userPaid, setUserPaid] = useState(paid);
useEffect(() => {
updateUser(index, { name: userName, share: userShare, paid: userPaid });
}, [userName, userShare, userPaid]);
return (
<div className="flex justify-between items-center h-16 p-4 my-6 rounded-lg border border-gray-100 shadow-md">
<div className="flex items-center">
<img
className="rounded-full h-12 w-12"
src="https://static-cdn.jtvnw.net/jtv_user_pictures/27fdad08-a2c2-4e0b-8983-448c39519643-profile_image-70x70.png"
alt="Logo"
/>
<div className="ml-2">
<input
placeholder="Person Name"
value={userName}
onChange={(e) => {
setUserName(e.target.value);
}}
className="text-sm font-semibold text-gray-600 focus:outline-none"
/>
</div>
</div>
<div className="text-xl font-bold text-gray-700">
<span className="text-red-400 text-base">
<input
value={userPaid}
onChange={(e) => {
setUserPaid(e.target.value);
}}
type="text"
className="w-20 py-2 pl-2 text-green-400 font-bold rounded-lg border-2 border-gray-200 outline-none focus:border-indigo-500"
placeholder="Paid"
/>
</span>
<span className="ml-2 text-red-400 text-base">
<input
value={userShare}
onChange={(e) => {
setUserShare(e.target.value);
}}
type="text"
className="w-20 py-2 pl-2 rounded-lg border-2 font-bold border-gray-200 outline-none focus:border-indigo-500"
placeholder="Share"
/>
</span>
</div>
</div>
);
};
export default EditUser;
|
"use strict";
/* packages
========================================================================== */
var Busboy = require("busboy");
var mongoose = require("mongoose");
var fs = require("fs");
var zlib = require("zlib");
/* controllers and models
========================================================================== */
var Parser = require("./parser.js");
var Geometry = require("./geometryModel.js");
/* API
========================================================================== */
exports.upload = function(req, res) {
var form = new Busboy({headers: req.headers});
req.pipe(form);
form.on("file", function(fieldname, file, filename, encoding, mimetype) {
var dataChunks = [];
var dataLength = 0;
file.on("data", function(chunk) {
dataChunks.push(chunk);
dataLength += chunk.length;
}).on("end", function() {
writeLog(4, "All chunks of the file captured", {origin: req.connection.remoteAddress, fileName: filename, chunksCount: dataChunks.length});
/* File assembly */
var data = new Buffer.alloc(dataLength);
for (var i=0, pos=0; i<dataChunks.length; i++) {
dataChunks[i].copy(data, pos);
pos += dataChunks[i].length;
}
writeLog(4, "File assembled", {origin: req.connection.remoteAddress, fileName: filename});
/* File processing */
fileProcessing(filename, data);
});
}).on("error", function(err) {
writeLog(1, "Error at file reading", {origin: req.connection.remoteAddress, fileName: filename, error: err.message});
res.sendStatus(500);
});
function fileProcessing(fileName, data) {
try {
/* File parse */
var plotData = Parser.parse(fileName, data);
writeLog(4, "File parsed", {origin: req.connection.remoteAddress, fileName: fileName});
/* Response to client */
res.status(201).send(plotData);
/* Geometry storage */
if (mongoose.connection.readyState === 1) {
var uuid = function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)};
var deflated = zlib.deflateSync(JSON.stringify(plotData));
Geometry.create({
name: fileName,
path: "./files/" + uuid()
}, function(err, query) {
if (err) {
writeLog(1, "Error at geometry storage", {origin: req.connection.remoteAddress, fileName: fileName, error: err.message});
res.sendStatus(500);
} else {
fs.writeFileSync(query.path, deflated);
writeLog(3, "Geometry stored", {origin: req.connection.remoteAddress, fileName: fileName, path: query.path});
}
});
} else {
writeLog(1, "Database disconnected", {origin: req.connection.remoteAddress});
res.sendStatus(500);
}
} catch (err) {
writeLog(1, "Error at file procesing", {origin: req.connection.remoteAddress, fileName: fileName, error: err.message});
res.sendStatus(500);
}
}
function writeLog(type, msg, meta) {
msg = "Upload File: " + msg;
switch (type) {
case 1:
req.app.locals.logger.error(msg, {meta: meta});
break;
case 2:
req.app.locals.logger.warn(msg, {meta: meta});
break;
case 3:
req.app.locals.logger.info(msg, {meta: meta});
break;
default:
req.app.locals.logger.debug(msg, {meta: meta});
}
}
};
exports.getAll = function(req, res) {
if (mongoose.connection.readyState === 1) {
Geometry.find({}, {
_id: 1,
name: 1,
date: 1
}, function(err, query) {
if (err) {
writeLog(1, "Error at getting files list", {origin: req.connection.remoteAddress, error: err.message});
res.sendStatus(500);
} else {
writeLog(3, "Files list obtained", {origin: req.connection.remoteAddress, fileListCount: query.length});
res.status(200).json(query);
}
});
} else {
writeLog(1, "Database disconnected", {origin: req.connection.remoteAddress});
res.sendStatus(500);
}
function writeLog(type, msg, meta) {
msg = "Get Files List: " + msg;
switch (type) {
case 1:
req.app.locals.logger.error(msg, {meta: meta});
break;
case 2:
req.app.locals.logger.warn(msg, {meta: meta});
break;
case 3:
req.app.locals.logger.info(msg, {meta: meta});
break;
default:
req.app.locals.logger.debug(msg, {meta: meta});
}
}
};
exports.getById = function(req, res) {
if (mongoose.connection.readyState === 1) {
Geometry.findOne({
_id: req.params.id
}, {
_id: 0,
path: 1
}, function(err, query) {
if (err) {
writeLog(1, "Error at getting geometry", {origin: req.connection.remoteAddress, fileId: req.params.id, error: err.message});
res.sendStatus(500);
} else if (query) {
if (fs.existsSync(query.path)) {
let data = fs.readFileSync(query.path);
let inflated = zlib.inflateSync(new Buffer.from(data));
let geometry = JSON.parse(inflated);
writeLog(3, "Geometry obtained", {origin: req.connection.remoteAddress, fileId: req.params.id});
res.status(200).json(geometry);
} else {
removeLostFile();
}
} else {
writeLog(2, "File to retrieve not found", {origin: req.connection.remoteAddress, fileId: req.params.id});
res.sendStatus(404);
}
});
} else {
writeLog(1, "Database disconnected", {origin: req.connection.remoteAddress});
res.sendStatus(500);
}
function removeLostFile() {
Geometry.findOneAndRemove({
_id: req.params.id
}, {
select: {
_id: 0
}
}, function(err, query) {
if (err) {
writeLog(1, "Error at removing lost geometry", {origin: req.connection.remoteAddress, fileId: req.params.id, error: err.message});
res.sendStatus(500);
} else if (query) {
writeLog(3, "Geometry lost and removed", {origin: req.connection.remoteAddress, fileId: req.params.id});
res.sendStatus(200);
} else {
writeLog(2, "File to remove not found", {origin: req.connection.remoteAddress, fileId: req.params.id});
res.sendStatus(404);
}
});
}
function writeLog(type, msg, meta) {
msg = "Get File: " + msg;
switch (type) {
case 1:
req.app.locals.logger.error(msg, {meta: meta});
break;
case 2:
req.app.locals.logger.warn(msg, {meta: meta});
break;
case 3:
req.app.locals.logger.info(msg, {meta: meta});
break;
default:
req.app.locals.logger.debug(msg, {meta: meta});
}
}
};
exports.deleteById = function(req, res) {
if (mongoose.connection.readyState === 1) {
Geometry.findOneAndRemove({
_id: req.params.id
}, {
select: {
_id: 0,
path: 1
}
}, function(err, query) {
if (err) {
writeLog(1, "Error at removing geometry", {origin: req.connection.remoteAddress, fileId: req.params.id, error: err.message});
res.sendStatus(500);
} else if (query) {
if (fs.existsSync(query.path)) {
fs.unlinkSync(query.path);
}
writeLog(3, "Geometry removed", {origin: req.connection.remoteAddress, fileId: req.params.id});
res.sendStatus(200);
} else {
writeLog(2, "File not found", {origin: req.connection.remoteAddress, fileId: req.params.id});
res.sendStatus(404);
}
});
} else {
writeLog(1, "Database disconnected", {origin: req.connection.remoteAddress});
res.sendStatus(500);
}
function writeLog(type, msg, meta) {
msg = "Delete File: " + msg;
switch (type) {
case 1:
req.app.locals.logger.error(msg, {meta: meta});
break;
case 2:
req.app.locals.logger.warn(msg, {meta: meta});
break;
case 3:
req.app.locals.logger.info(msg, {meta: meta});
break;
default:
req.app.locals.logger.debug(msg, {meta: meta});
}
}
};
exports.checkStatus = function(req, res) {
checkDatabase(0);
function checkDatabase(attempt) {
if (mongoose.connection.readyState === 1) {
Geometry.find({}, {
_id: 0,
date: 1
}, function(err, query) {
if (err) {
if (attempt < 2) {
setTimeout(() => {
checkDatabase(++attempt);
}, 5000);
} else {
writeLog(1, "Error accessing Geometries collection", {origin: req.connection.remoteAddress, error: err.message});
res.sendStatus(500);
}
} else {
writeLog(3, "Database connected and Geometries collection accessible", {origin: req.connection.remoteAddress});
res.sendStatus(200);
}
});
} else {
if (attempt < 2) {
setTimeout(() => {
checkDatabase(++attempt);
}, 5000);
} else {
writeLog(1, "Database disconnected", {origin: req.connection.remoteAddress});
res.sendStatus(500);
}
}
}
function writeLog(type, msg, meta) {
switch (type) {
case 1:
req.app.locals.logger.error(msg, {app: 'Status Check', meta: meta});
break;
case 2:
req.app.locals.logger.warn(msg, {app: 'Status Check', meta: meta});
break;
case 3:
req.app.locals.logger.info(msg, {app: 'Status Check', meta: meta});
break;
default:
req.app.locals.logger.debug(msg, {app: 'Status Check', meta: meta});
}
}
};
|
import React, { useState } from "react";
import {
Button,
Layout,
Row,
Col,
Typography,
Card,
Input,
Divider,
Carousel,
} from "antd";
import ExternalLink from "./components/ExternalLink";
import RightCardPages from "./components/RightCardPages";
import "./App.scss";
function onChange(a, b, c) {
console.log(a, b, c);
}
const { Header, Footer, Content } = Layout;
const { Title } = Typography;
// Created with https://dev.to/jose1897/how-to-create-a-react-app-without-create-react-app-command-1fgc
const App = () => {
return (
<div className="App">
<Layout className="content">
<Header className="centerMargin" className="title">
<Title className="center">Power Hour</Title>
</Header>
<br />
<Content>
<Row>
<Col md={{ span: 12, order: 1 }} xs={{ span: 24, order: 2 }}>
{" "}
<Carousel autoplay autoplaySpeed={5000}>
<div>
<Card
title="How to play Power Hour"
className="centerMargin"
extra={
<ExternalLink
title="Learn More"
link="https://en.wikipedia.org/wiki/Power_hour"
/>
}
style={{ width: 350, height: 320 }}
>
<p>
Drink to your favorite songs for a whole hour (or other
specified amount of time)!
<br />
<br />
If you have a join code, choose "Join an Hour" on the
right and enter the code.
<br />
<br />
If you’re creating a new lobby, choose "Host an Hour".
</p>
</Card>
</div>
<div>
<Card
title="Second Page"
className="centerMargin"
extra={
<ExternalLink
title="Learn More"
link="https://en.wikipedia.org/wiki/Power_hour"
/>
}
style={{ width: 350, height: 320 }}
>
<p>
Drink to your favorite songs for a whole hour (or other
specified amount of time)!
<br />
<br />
If you have a join code, choose "Join an Hour" on the
right and enter the code.
<br />
<br />
If you’re creating a new lobby, choose "Host an Hour".
</p>
</Card>
</div>
<div>
<Card
title="Third Page"
className="centerMargin"
extra={
<ExternalLink
title="Learn More"
link="https://en.wikipedia.org/wiki/Power_hour"
/>
}
style={{ width: 350, height: 320 }}
>
<p>
Drink to your favorite songs for a whole hour (or other
specified amount of time)!
<br />
<br />
If you have a join code, choose "Join an Hour" on the
right and enter the code.
<br />
<br />
If you’re creating a new lobby, choose "Host an Hour".
</p>
</Card>
</div>
<div>
<Card
title="Fourth Page"
className="centerMargin"
extra={
<ExternalLink
title="Learn More"
link="https://en.wikipedia.org/wiki/Power_hour"
/>
}
style={{ width: 350, height: 320 }}
>
<p>
Drink to your favorite songs for a whole hour (or other
specified amount of time)!
<br />
<br />
If you have a join code, choose "Join an Hour" on the
right and enter the code.
<br />
<br />
If you’re creating a new lobby, choose "Host an Hour".
</p>
</Card>
</div>
</Carousel>
</Col>
<Col md={{ span: 12, order: 2 }} xs={{ span: 24, order: 1 }}>
<RightCardPages></RightCardPages>
</Col>
</Row>
</Content>
<br />
<br />
<Divider />
<Footer className="content center">
© 2021. Developed with hate by the Dumpster.
</Footer>
</Layout>
</div>
);
};
export default App;
|
import sharedParams from './sharedPlaylistParams';
export default class PlaylistDynamic {
constructor(echonest) {
this.echonest = echonest;
}
create(params, callback) {
const filter = sharedParams.slice();
filter.push('session_catalog');
const filteredParams = this.echonest.network._filterParams(params, filter);
if (Array.isArray(filteredParams.session_catalog) && filteredParams.session_catalog.length > 5) {
return callback(new Error('Cannot specify more than 5 session catalogs'), null);
}
const query = this.echonest.network._buildQuery(filteredParams);
const uri = 'playlist/dynamic/create?' + query;
this.echonest.network.get(uri, (err, data) => {
if (err) return callback(err, null);
callback(null, data);
});
}
restart(params, callback) {
const filter = sharedParams.slice();
filter.push('session_catalog');
filter.push('session_id');
const filteredParams = this.echonest.network._filterParams(params, filter);
if (Array.isArray(filteredParams.session_catalog) && filteredParams.session_catalog.length > 5) {
return callback(new Error('Cannot specify more than 5 session catalogs'), null);
}
const query = this.echonest.network._buildQuery(filteredParams);
const uri = 'playlist/dynamic/restart?' + query;
this.echonest.network.get(uri, (err, data) => {
if (err) return callback(err, null);
callback(null, data);
});
}
next(params, callback) {
const filteredParams = this.echonest.network._filterParams(params, [
'session_id',
'results',
'lookhead',
]);
if (!params.session_id) {
return callback(new Error('Must specify a session id'), null);
}
const query = this.echonest.network._buildQuery(filteredParams);
const uri = 'playlist/dynamic/next?' + query;
this.echonest.network.get(uri, (err, data) => {
if (err) return callback(err, null);
callback(null, data);
});
}
feedback(params, callback) {
const filteredParams = this.echonest.network._filterParams(params, [
'session_id',
'ban_artist',
'favorite_artist',
'ban_song',
'skip_song',
'favorite_song',
'play_song',
'unplay_song',
'rate_song',
'update_catalog',
'invalidate_song',
'invalidate_artist',
]);
if (!params.session_id) {
return callback(new Error('Must specify a session id'), null);
}
const query = this.echonest.network._buildQuery(filteredParams);
const uri = 'playlist/dynamic/feedback?' + query;
this.echonest.network.get(uri, (err, data) => {
if (err) return callback(err, null);
callback(null, data);
});
}
steer(params, callback) {
const filteredParams = this.echonest.network._filterParams(params, [
'session_id',
'min_tempo',
'max_tempo',
'target_tempo',
'min_loudness',
'max_loudness',
'target_loudness',
'min_danceability',
'max_danceability',
'target_danceability',
'min_energy',
'max_energy',
'target_energy',
'min_liveness',
'max_liveness',
'target_liveness',
'min_speechiness',
'max_speechiness',
'target_speechiness',
'min_acousticness',
'max_acousticness',
'target_acousticness',
'min_song_hotttnesss',
'max_song_hotttnesss',
'target_song_hotttnesss',
'min_artist_hotttnesss',
'max_artist_hotttnesss',
'target_artist_hotttnesss',
'min_artist_familiarity',
'max_artist_familiarity',
'target_artist_familiarity',
'more_like_this',
'less_like_this',
'adventurousness',
'variety',
'description',
'style',
'song_type',
'mood',
'reset',
]);
const query = this.echonest.network._buildQuery(filteredParams);
const uri = 'playlist/dynamic/steer?' + query;
this.echonest.network.get(uri, (err, data) => {
if (err) return callback(err, null);
callback(null, data);
});
}
info(params, callback) {
const filteredParams = this.echonest.network._filterParams(params, [
'session_id',
]);
if (!params.session_id) {
return callback(new Error('Must specify a session id'), null);
}
const query = this.echonest.network._buildQuery(filteredParams);
const uri = 'playlist/dynamic/info?' + query;
this.echonest.network.get(uri, (err, data) => {
if (err) return callback(err, null);
callback(null, data);
});
}
delete(params, callback) {
const filteredParams = this.echonest.network._filterParams(params, [
'session_id',
]);
if (!params.session_id) {
return callback(new Error('Must specify a session id'), null);
}
const query = this.echonest.network._buildQuery(filteredParams);
const uri = 'playlist/dynamic/delete?' + query;
this.echonest.network.get(uri, (err, data) => {
if (err) return callback(err, null);
callback(null, data);
});
}
}
|
const {User, Transaction, TransactionItem, Item} = require("../models")
const bcrypt = require("bcryptjs")
const convertDate = require("../helpers/convertDate")
class UserController {
static register (req, res) {
res.render("pages/user/register.ejs")
}
static create (req, res) {
User.findOne({where: {username: req.body.username}})
.then(user => {
if(user) {
let err = "Username already exist. Please change your username"
throw new Error(err)
} else {
let data = {
username: req.body.username,
email: req.body.email,
password: req.body.password
}
return User.create(data)
}
})
.then(() => {
res.redirect("/")
})
.catch(err => {
res.locals.error = err
res.render("pages/user/register.ejs")
})
}
static login (req, res) {
res.render("pages/user/login.ejs")
}
static loggedIn (req, res) {
let userLogin
User.findOne({where: {username: req.body.username}})
.then(user => {
if (user){
userLogin = user
return bcrypt.compare(req.body.password, user.password)
} else {
throw new Error (`User with username ${req.body.username} not found`)
}
})
.then(output => {
if(output) {
req.session.user = {
id : userLogin.id,
username: userLogin.username
}
res.redirect("/")
} else {
throw new Error ("Password mismatch")
}
})
.catch(err => {
res.locals.error = err
res.render("pages/user/login.ejs")
})
}
static logout (req, res) {
req.session.destroy(err => {
if(err){
res.locals.error = err
return res.render("pages/home.ejs")
} else {
return res.render("pages/home.ejs")
}
})
}
static profile (req, res) {
User.findOne({where: {username: req.params.username}})
.then(user => {
let data = {
username: user.username,
email: user.email
}
res.render("pages/user/profile.ejs", {
user: data
})
})
.catch(err => {
res.locals.error = err
res.render("pages/home.ejs")
})
}
static profileEdit (req, res){
User.findOne({where: {username: req.params.username}})
.then(user => {
let data = {
username: user.username,
password: user.password,
email: user.email
}
res.render("pages/user/edit.ejs", {
user: data
})
})
.catch(err => {
res.locals.error = err
res.render("pages/home.ejs")
})
}
static profileUpdate (req, res) {
let data
User.findOne({where: {username: req.params.username}})
.then(user => {
user.username = req.body.username
user.email = req.body.email
if (req.body.password !== "set new password"){
user.password = req.body.password
} else {
User.removeHook("beforeSave", "encryptPassword")
}
data = user
return user.save()
})
.then(() => {
res.redirect(`/user/${data.username}/profile`)
})
.catch(err => {
res.locals.error = err
res.render("pages/home.ejs")
})
}
static profileDelete(req, res){
User.destroy({where: {username: req.params.username}})
.then(() => {
req.session.destroy(err => {
if(err){
res.locals.error = err
return res.render("pages/home.ejs")
} else {
return res.render("pages/home.ejs")
}
})
})
.catch(err => {
res.locals.error = err
res.render("pages/home.ejs")
})
}
static transactionHistory (req, res){
User.findOne({where: {username: req.params.username}})
.then(user => {
return Transaction.findAll({
attributes: ["timestamp"],
include: [{
model: Item,
attributes: ["price"],
through: {
attributes: ["quantity"]
}
}],
where: {UserId: user.id},
raw: true
})
})
.then(transactions => {
transactions.forEach(transaction => {
transaction.timestamp = convertDate(transaction.timestamp)
})
let time = []
for(let i = 0; i < transactions.length; i++){
if (i === 0){
time.push(transactions[i].timestamp)
} else {
let found = false
for (let j = 0; j < time.length; j++){
if (transactions[i].timestamp === time[j]){
found = true
}
}
if (!found){
time.push(transactions[i].timestamp)
}
}
}
let total = []
for(let i = 0; i < transactions.length; i++){
for (let j = 0; j < time.length; j++){
if (transactions[i].timestamp === time[j]){
if (!total[j] && total[j] != 0){
total[j] = 0
}
total[j] += Transaction.getTotal(transactions[i]['Items.price'], transactions[i]['Items.TransactionItem.quantity'])
}
}
}
res.locals.user = {
username: req.params.username
}
res.render("pages/user/purchaseHistory.ejs", {
data: total,
labels: time
})
})
.catch(err => {
res.locals.error = err
res.redirect("/")
})
}
}
module.exports = UserController
|
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import Spinner from './Spinner';
import { getTagCloud } from '../utils/api';
import './TagCloud.css';
function TagCloud() {
const tags = useTags();
const width = useWindowWidth();
function getLabel(id) {
return tags.ids.length > 0 && tags.byIds[id].label;
}
function getFontSize(id) {
const resolution = ((width / 1920) * 100) ^ 0;
const score = tags.byIds[id].sentimentScore;
return (score < 50 ? 0.7 : 1) + (((score * resolution) / 100) ^ 0) / 100;
}
if (tags.ids.length === 0) {
return <Spinner />;
}
return (
<div className='cloud'>
{tags.ids &&
tags.ids.map((tagId, i) => (
<Link
className='grow'
to={`/home/${tagId}`}
style={{
fontSize: `${getFontSize(tagId)}em`,
lineHeight: '0.8em',
color: `#${getRandomColor()}`
}}
key={i}
>
{getLabel(tagId)}
</Link>
))}
</div>
);
}
function useTags() {
const [state, setState] = useState({
ids: [],
byIds: {}
});
useEffect(() => {
getTagCloud()
.then(tagsByIds => {
setState({
...state,
ids: Object.keys(tagsByIds),
byIds: tagsByIds
});
})
// eslint-disable-next-line
.catch(console.log.bind(console));
}, []);
return state;
}
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => {
if (Math.abs(window.innerWidth - width) > 50) {
setWidth(window.innerWidth);
}
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [width]);
return width;
}
function getRandomColor() {
return Math.floor(Math.random() * 16777215).toString(16);
}
export default TagCloud;
|
import React from 'react'
import './PanelsWrapper.css'
const PanelsWrapper = ({ children }) => {
return <section className="PanelsWrapper">{children}</section>
}
export default PanelsWrapper
|
function toggleClassOnHover(selector, klass){
$(selector).hover(function(){
$(this).addClass(klass);
}, function(){
$(this).removeClass(klass);
});
}
function activateSectionToggler(box_selector, toggle_selector, content_selector){
$(toggle_selector).click(function(e){
e.preventDefault();
if($(this).attr('href') === 'close_section'){
$(this).closest(box_selector).find(content_selector).hide(400);
$(this).attr('href', 'open_section').html('+');
} else{
$(this).closest(box_selector).find(content_selector).show(400);
$(this).attr('href', 'close_section').html('-');
}
});
}
function activateSectionCloser(box_selector, toggle_selector, speed){
speed = typeof speed !== 'undefined' ? speed : 400;
$(toggle_selector).click(function(e){
e.preventDefault();
$(box_selector).hide(400);
});
}
|
const connection = require('../config/database.js');
var Payments = function (params) {
// console.log('params',params);
this.BankFailedReason = params.BankFailedReason ;
this.BankReceiptID = params.BankReceiptID ;
this.BankReturnCode = params.BankReturnCode ;
this.CustomerName = params.CustomerName ;
this.DebitDate = params.DebitDate ;
this.EzidebitCustomerID = params.EzidebitCustomerID ;
this.InvoiceID = params.InvoiceID ;
this.PaymentAmount = params.PaymentAmount ;
this.PaymentID = params.PaymentID ;
this.PaymentMethod = params.PaymentMethod ;
this.PaymentReference = params.PaymentReference ;
this.PaymentSource = params.PaymentSource ;
this.PaymentStatus = params.PaymentStatus ;
this.ScheduledAmount = params.ScheduledAmount ;
this.TransactionFeeClient = params.TransactionFeeClient ;
this.TransactionFeeCustomer = params.TransactionFeeCustomer ;
this.YourGeneralReference = params.YourGeneralReference ;
this.YourSystemReference = params.YourSystemReference ;
};
Payments.prototype.addPayments = function () {
const that =this;
return new Promise((resolve, reject) => {
connection.getConnection((error, connection) => {
if (error) {
reject(error);
} else {
const values = [
that.BankFailedReason,
that.BankReceiptID,
that.BankReturnCode,
that.CustomerName,
that.DebitDate,
that.EzidebitCustomerID,
that.InvoiceID,
that.PaymentAmount,
that.PaymentID,
that.PaymentMethod,
that.PaymentReference,
that.PaymentSource,
that.PaymentStatus,
'',
that.ScheduledAmount,
that.TransactionFeeClient,
that.TransactionFeeCustomer,
'',
that.YourGeneralReference,
that.YourSystemReference,
];
connection.query(
`INSERT INTO payments(bankFailedReason, bankReceiptID, bankReturnCode, customerName, debitDate, eziDebitCustomerID, invoiceID, paymentAmount, paymentID, paymentMethod, paymentReference, paymentSource, paymentStatus, settlementDate, scheduledAmount, transactionFeeClient, transactionFeeCustomer, transactionTime, yourGeneralReference, yourSystemReference) VALUES (?)`,
[values],
(error, rows, fields) => {
if (error) {
console.log('Error...', error);
reject(error);
} else {
resolve(rows);
}
}
);
}
});
});
};
module.exports = Payments;
|
/// <reference path="snake.ts"/>
'use strict';
var Game;
(function (Game) {
var start = document.getElementById('start');
var score = document.getElementById('score');
var floor = new Game.Floor({
parent: document.getElementById('container')
});
floor.initialize();
var snake = new Game.Snake(floor);
start.onclick = function () {
snake.born();
this.setAttribute('disabled', true);
};
var observer = function (changes) {
changes.forEach(function (change) {
if (change.name === 'score') {
score.textContent = change.object[change.name];
}
});
};
Object.observe(snake, observer);
})(Game || (Game = {}));
|
import React from "react";
import pDefer from "p-defer";
import Portal from "../../src";
const styles = {
fontFamily: "sans-serif",
textAlign: "center",
};
function Hello({ name }) {
return <h1 className="t">Hello {name}!</h1>;
}
export default function App() {
let [v, refresh] = React.useState(1);
let [container] = React.useState(pDefer());
let [container2] = React.useState(pDefer());
let refContainer2 = React.useRef();
React.useEffect(() => {
container2.resolve(refContainer2.current);
setTimeout(() => {
container.resolve(document.getElementById("ct"));
}, 2000);
}, []);
return (
<div style={styles} id="ct">
<button onClick={() => refresh(v + 1)}>refresh {v}</button>
<div ref={refContainer2}></div>
<Portal
key="a"
container={document.body}
onChildrenMount={() => console.log("Portal1 mounted")}
>
<Hello name="Portal1" />
</Portal>
<Portal
key="b"
container={container2.promise}
onChildrenMount={() => console.log("Portal2 mounted")}
>
<Hello name="Portal2" />
</Portal>
<Portal
key="c"
container={container.promise}
onChildrenMount={() => console.log("Portal3 mounted")}
>
<Hello name="Portal3" />
</Portal>
</div>
);
}
|
import React, { useContext, useEffect } from 'react';
import BillsContext from '../../context/bills-context'
import BillList from '../BillList.jsx'
const Home = () => {
const { state, dispatch } = useContext(BillsContext);
useEffect(() => {
fetch('/bills')
.then(res => res.json())
.then(json => {
let bills = json.filter(bill => bill.username === state.username);
dispatch({ type: 'GET_BILLS', bills })
})
}, [state.loggedIn])
return (
<div>
<h1>Home page</h1>
<BillList />
</div>
)
}
export default Home;
|
import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
// import { Message } from 'element-ui'
import { getSessionId, getUserId } from '@/utils/auth'
// import { getToken } from '@/utils/auth' // 验权
// import { navigationMenu } from './api/system/dept' // 引用接口文件--获取菜单列表接口
import { logOut } from '@/utils/path' // 登出
router.beforeEach((to, from, next) => {
NProgress.start()
// setLoca()
// var status = false
// navigationMenu({})
// .then(res => {
// console.log(res)
// status = true
// })
// .catch(() => {
// })
// setLoca()
//
// if ((getSessionId() && getUserId()) || (getSessionId() && !store.state.permissionRouter.getPermissionRoutes)) {
if (true) {
// if (to.path === '/dashboard') {
// next()
// } else {
// if (getUserId()) {
// next()
// } else {
// logoOut()
// }
// }
next()
} else {
// console.log('登出')
logOut()
}
})
router.afterEach(() => {
NProgress.done() // 结束Progress
})
|
const axios = require("axios");
const router = require("express").Router();
const cheerio = require("cheerio");
router.get("/recipes", (req, res) => {
axios
.get("http://www.recipepuppy.com/api/", { params: req.query })
.then(({ data: { results } }) => res.json(results))
.catch(err => res.status(422).json(err));
});
router.get("/articles",(req, res) =>{
axios
.get("https://www.charlotteagenda.com/")
.then((response) => {
let $ = cheerio.load(response.data);
let kurs = [];
$("div.indexstory").each(function (i, element) {
kurs.push({
title: $(this).find("h1.entry-title").text(),
link: $(this).find("h1.entry-title").children("a").attr("href"),
// tag: $(this).find("div.entry-item").find("a.indextag").text()
image: $(this).find("div.thumbnail_image").children("a").children("img").attr("src")
// blurb: $(this).find("div.excerpt.fullview").text()
// res.json(element)
})
})
// res.json($("div.indexstory"[0]))
console.log(kurs);
res.json(kurs);
})
.catch(err => res.status(422).json(err));
});
module.exports = router;
|
export { RedirectToHome } from './redirect-to-home';
|
$("a").click(function(){
$("body,html").animate({
scrollTop:$("#" + $(this).data('value')).offset().top-100
},1500)
})
$(document).ready(function () {
$(".navbar-nav a").click(function (e) {
e.preventDefault();
$('.navbar-collapse.show').collapse('hide');
});
});
/* ..............................................
BaguetteBox
................................................. */
baguetteBox.run('.tz-gallery', {
animation: 'fadeIn',
noScrollbars: true
});
|
import React, { Component } from 'react';
import ExternalClick from 'ExternalClick';
const Item = (isExternalClick) => (
<div className={`item ${isExternalClick && 'external'}`}>
{`${isExternalClick ? 'Click Me' : 'Click Outside'}`}
</div>
);
class Menu extends Component {
render() {
const { show } = this.props;
return (
<div className="menu-wrapper">
<div className="menu-head">Menu {show ? '-' : '+'}</div>
<div className={`menu-list ${!show ? 'menu-list-closed' : ''}`}>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
</div>
);
}
}
class App extends Component {
render() {
return (
<div className="app">
<ExternalClick render={Item} />
<ExternalClick>
{isExternalClick => (<Menu show={!isExternalClick} />)}
</ExternalClick>
</div>
);
}
}
export default App;
|
import React from 'react';
import Link from 'gatsby-link';
import Base from '../layouts/base';
import MainContent from '../layouts/main_content';
class PageNotFound extends React.Component {
render() {
const { location } = this.props;
return (
<Base location={location}>
<MainContent>
<h2 style={{ padding: '0', margin: '0' }}>Hmmm... think we got lost finding that page yo.</h2>
<h3 style={{ padding: '0', margin: '0', textDecoration: 'underline' }}> <Link to="/">Go home 🏠</Link> </h3>
{/* <br/> */}
{/* <br/> */}
{/* <br/> */}
<br/>
<img src="https://media1.tenor.com/images/a828888852e708d9afaaad06c7f9513f/tenor.gif?itemid=10251428"/>
</MainContent>
</Base>
);
}
}
export default PageNotFound;
|
import React, { useState } from "react";
import { Vcharts } from "~components";
import "echarts-gl";
import getOption from "../options/line3D";
const GeneratorLine3D = ({ uniqueId, value, options, onChange }) => {
// if (isEmpty(value?.dataConfig?.data)) return null;
const [stauts, setStauts] = useState(false);
return <Vcharts refresh={false} options={getOption()} theme="dark" />;
};
export default GeneratorLine3D;
|
import React from 'react';
import { FaRegUserCircle } from 'react-icons/fa';
import { Link } from 'react-router-dom';
import styled from 'styled-components';
import {useDispatch, useSelector} from 'react-redux';
import { startLogout } from './actions/auth';
const MenuContainer = styled.nav`
.ul-menu{
display:grid;
grid-template-columns: repeat(4, 1fr);
justify-content: center;
align-items: center;
}
.li-menu{
display: inherit;
vertical-align: middle;
width: 100%;
text-align: center;
a{
font-size: .7rem;
svg{
font-size: 1.4em;
float: right;
}
}
}
.login__menu{
display: flex;
justify-content: center;
align-items: center;
a{
padding-right: 5px;
}
}
.login__icon{
float: right;
}
.login__container{
opacity: 0;
position: absolute;
transition: all .5s ease;
width: 100%;
background-color: white;
height: 0;
right: 0;
a{
display: flex;
flex-direction: row;
padding: 10px 0 10px 0;
border-bottom: 1px solid #2A2C42;
}
}
.login{
position: relative;
display: inline-block;
text-align: center;
&:hover .login__container{
position: absolute;
background-color: #DDE3EA;
height: 200px;
padding: 20px 10px 20px 10px;
opacity: 1;
transform: translateY(0);
top: 10px;
z-index: -1;
}
}
`;
const Menu = () => {
return (
<MenuContainer className="font-culum text-dark-fit-500 menu uppercase">
{/* <ul className="ul-menu">
<li className="li-menu">
<Link to="/quien-soy"> Quien soy </Link>
</li>
<li className="li-menu">
<Link to="/que-hago"> Que hago </Link>
</li>
</ul> */}
</MenuContainer>
)
}
export default Menu;
|
import { profileAPI } from './ProfileApi'
const FETCH = 'profile/Fetch'
const CHANGE_STATUS = 'profile/CHANGE_STATUS'
const initiaState = {
status: null,
profile: {},
}
export const ProfileReducer = (state = initiaState, action) => {
switch (action.type) {
case CHANGE_STATUS:
return { ...state, status: action.payload }
case FETCH:
return { ...state, profile: action.payload }
default:
return state
}
}
export const fetchAction = (data) => ({ type: FETCH, payload: data })
export const changeStatusAction = (status) => ({ type: CHANGE_STATUS, payload: status })
export const fetchProfile = (id) => async dispatch => {
try {
dispatch(changeStatusAction('LOADING'))
const { data } = await profileAPI.get(id)
dispatch(changeStatusAction('LOADED'))
dispatch(fetchAction(data))
} catch (e) {
dispatch(changeStatusAction('ERROR'))
console.log(e)
}
}
|
let Managers = require('./ManagerSchema');
// default data
let managers = ['anikshen', 'danzha', 't-jucheng', 'v-jelu'];
let team = 'AZURE PAAS APP SERVICE';
// create default manager
exports.createManager = async (ctx, next) => {
const manager = new Managers(
{
Team: ctx.params.manager || team,
Alias: managers
}
);
ctx.body = await manager.save()
.then(data => {
console.log('add manager success');
return data;
})
.catch(err => {
console.log('add manager fail' + err);
return err;
})
};
// add manager
// team + alias
exports.addManager = async (ctx, next) => {
ctx.body = await Managers.updateOne(
{
Team: ctx.query.team || team
},
{
$push: {
Alias: [
ctx.query.alias
]
}
}, { upsert : true })
.then(data => {
console.log('add manager success');
return data;
})
.catch(err => {
console.log('add manager fail' + err);
return err;
})
};
// find manager and return team name
exports.findmanager = async (ctx, next) => {
ctx.body = await Managers.findOne({ Alias: ctx.query.alias || "v-jelu" }, { Team: 1 })
.then(data => {
console.log('findmanager success ' + ctx.query.alias);
// add teamname in session
return data.Team;
})
.catch(err => {
console.log('findmanager error');
return err;
})
}
|
import {connect} from 'react-redux';
const Dashboard = ({tasksDone,tasksNotDone}) => (
<div className="p-2 m-2">
<span className="badge badge-primary p-2 mr-2">Complete: <strong>{tasksDone}</strong></span>
<span className="badge badge-danger p-2 mr-2">InComplete: <strong>{tasksNotDone}</strong></span>
<span className="badge badge-secondary p-2 mr-2">Total: <strong>{tasksDone+tasksNotDone}</strong></span>
</div>
);
const mapStateToProps = (state) => ({
tasksDone:state.tasksDone,
tasksNotDone:state.tasksNotDone
});
const mapDispatchToProps = null;
const connectToStore = connect(mapStateToProps,mapDispatchToProps);
export default connectToStore(Dashboard);
|
import types from 'Actions/types';
const { ADD_FLASH_MESSAGE, REMOVE_FLASH_MESSAGE } = types;
/**
* @description This handles flash message reducers
* @param {object} state - redux state
* @param {object} action - action creator
* @returns {object} new state
*/
const flashMessages = (state = {}, action) => {
switch (action.type) {
case ADD_FLASH_MESSAGE:
return {
type: action.message.type,
text: action.message.text
};
break;
case REMOVE_FLASH_MESSAGE:
return {};
break;
default:
return state;
}
};
export default flashMessages;
|
/* global malarkey:false, moment:false */
(function() {
'use strict';
angular
.module('template')
.constant('STATES', {
kHomeState:'home',
kContactsState: 'contacts',
kStoreState: 'store',
kCEOState: 'contacts.ceo',
kPresidentState: 'contacts.president',
kFounderState: 'contacts.founder',
kShoesState: 'contacts.ceo',
kPantsState: 'contacts.president',
kShirtsState: 'contacts.founder'
});
})();
|
import React from 'react';
import HitElement from './HitElement';
export default function HitList(props) {
if (props.showNoResults) {
return (
<div className="result-error">
{props.noHitsMessage}
</div>
);
}
if (!props.hits.length || !props.displayHits) {
return null;
}
return (
<div className="result-list">
{props.hits.map(function (hit, idx) {
return (
<HitElement
key={hit.Id}
text={hit.Text}
index={idx}
hover={idx === props.hoverIndex}
selected={idx === props.selectedIndex}
onEnter={props.setHoverIndex}
hitSelected={props.hitSelected}/>
);
})}
</div>
);
}
|
/**
* Copyright (C) 2009 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
function UIColorPicker() {
}
UIColorPicker.prototype.show = function(obj){
document.onmousedown = new Function("eXo.webui.UIColorPicker.hide()") ;
this.tableColor = eXo.core.DOMUtil.findNextElementByTagName(obj, "div");
this.title = eXo.core.DOMUtil.findFirstDescendantByClass(obj, "span", "DisplayValue");
this.input = eXo.core.DOMUtil.findFirstDescendantByClass(obj.parentNode, "input", "UIColorPickerValue");
this.showHide();
this.getSelectedValue() ;
}
UIColorPicker.prototype.setColor = function(color) {
if (eXo.core.DOMUtil.hasClass(this.title, color)) {
this.hide() ;
return ;
}
var className = "DisplayValue " + color ;
this.title.className = className ;
this.input.value = color ;
this.hide() ;
} ;
UIColorPicker.prototype.clearSelectedValue = function() {
var selectedValue = this.input.value ;
var colorCell = eXo.core.DOMUtil.findDescendantsByTagName(this.tableColor, "a") ;
var len = colorCell.length ;
for(var i = 0 ; i < len ; i ++) {
if(eXo.core.DOMUtil.hasClass(colorCell[i],"SelectedColorCell")) {
colorCell[i].className = colorCell[i].className.replace("SelectedColorCell","") ;
break ;
}
}
} ;
UIColorPicker.prototype.getSelectedValue = function() {
var selectedValue = this.input.value ;
var colorCell = eXo.core.DOMUtil.findDescendantsByTagName(this.tableColor, "a") ;
var len = colorCell.length ;
this.clearSelectedValue() ;
for(var i = 0 ; i < len ; i ++) {
if(eXo.core.DOMUtil.hasClass(colorCell[i],selectedValue)) {
eXo.core.DOMUtil.addClass(colorCell[i],"SelectedColorCell") ;
break ;
}
}
} ;
UIColorPicker.prototype.hide = function() {
if(eXo.webui.UIColorPicker.tableColor) {
eXo.webui.UIColorPicker.tableColor.style.display = "none" ;
eXo.webui.UIColorPicker.tableColor = null ;
eXo.webui.UIColorPicker.title = null ;
eXo.webui.UIColorPicker.input = null ;
document.onmousedown = null ;
}
} ;
UIColorPicker.prototype.showHide = function() {
var obj = this.tableColor ;
if(obj.style.display != "block") {
obj.style.display = "block" ;
} else {
obj.style.display = "none" ;
}
} ;
eXo.webui.UIColorPicker = new UIColorPicker() ;
|
import { useNavigation } from "@react-navigation/native";
import axios from "axios";
import React, { useState, useContext, useEffect, useRef } from "react";
import {
ActivityIndicator,
Image,
KeyboardAvoidingView,
Platform,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
View,
} from "react-native";
import RBSheet from "react-native-raw-bottom-sheet";
import StarRating from "react-native-star-rating-new";
import { PRIMARY_COLOR, PRIMARY_FONT } from "../../constants";
import Comment from "../components/Comment";
import RatingBottomModal from "../components/RatingBottomModal";
import TopBar from "../components/TopBar";
import UserContext from "../contexts/UserContext";
const BookDetail = (props) => {
const [comment, setComment] = useState([]);
const [givingRate, setGivingRate] = useState(0);
const navigation = useNavigation();
const state = useContext(UserContext);
const ratingRef = useRef();
if (!props.route.params.item) {
return;
}
const {
_id,
cover,
category,
description,
isbn,
publisher,
rating,
release_date,
title,
} = props.route.params.item;
const { isForeign } = props.route.params;
useEffect(() => {
if (isForeign) {
try {
axios
.get(
`https://bookappapi.herokuapp.com/api/v1/books/${_id}/foreignbookComments`,
{
headers: { Authorization: `Bearer ${state.token}` },
}
)
.then((res) => {
res.data.data.forEach((el) => {
setComment((comment) => [...comment, el]);
});
})
.catch((err) => console.log("err", err));
} catch (error) {
console.log("error", error);
}
}
}, []);
const rate = () => {
ratingRef.current.open();
};
const handleRating = (val) => {
setGivingRate(val);
};
return (
<KeyboardAvoidingView
behavior={Platform.OS == "ios" ? "position" : "padding"}
style={css.container}
>
<TopBar
leftIconName="arrow-back-outline"
middleText="Номын дэлгэрэнгүй"
leftIconEvent={() => navigation.goBack()}
/>
<ScrollView showsVerticalScrollIndicator={false}>
<View style={css.top}>
<Image
source={{ uri: cover }}
style={css.image}
resizeMode="contain"
/>
<View style={css.info}>
<Text style={css.title}>{title}</Text>
<Text style={css.title}>{publisher.name}</Text>
<Text style={css.title}>
{category.includes(",") ? category.split(", ")[1] : category}
</Text>
<Text style={css.title}>{isbn ? isbn : "ISBN:"}</Text>
<Text style={css.title}>{release_date.slice(0, 10)}</Text>
<Text style={css.title}>Үнэлгээ:</Text>
<StarRating
disabled={true}
rating={rating}
fullStarColor={"#E8BD0D"}
starSize={20}
/>
</View>
</View>
<View style={css.desc}>
<Text style={css.title}>Тайлбар</Text>
<Text style={css.description}>{description}</Text>
</View>
<TouchableOpacity onPress={rate}>
<Text style={css.rating}>Үнэлгээ өгөх</Text>
<RBSheet
ref={ratingRef}
height={250}
animationType="fade"
closeOnDragDown={true}
closeOnPressMask={false}
customStyles={{
container: {
borderTopRightRadius: 40,
borderTopLeftRadius: 40,
},
}}
>
<RatingBottomModal
id={_id}
rating={givingRate}
onSelectStar={handleRating}
onHide={() => ratingRef.current.close()}
/>
</RBSheet>
</TouchableOpacity>
<Comment comments={comment} id={_id} isForeign={isForeign} />
</ScrollView>
</KeyboardAvoidingView>
);
};
export default BookDetail;
const css = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
top: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "flex-start",
},
info: {
justifyContent: "flex-start",
alignItems: "flex-start",
width: "55%",
},
image: {
width: 100,
height: 200,
borderRadius: 10,
},
title: {
fontFamily: PRIMARY_FONT,
fontSize: 15,
paddingVertical: 5,
},
desc: {
paddingTop: 10,
},
description: {
textAlign: "justify",
},
rating: {
alignSelf: "flex-end",
marginTop: "5%",
color: PRIMARY_COLOR,
fontSize: 15,
fontFamily: PRIMARY_FONT,
},
});
|
/**
* 员工档案,分页
*
*/
export default {
path: '/perArchives',
component: resolve=>require(["@/page/perArchives/index"],resolve),
meta: {
requiresAuth: true
},
redirect: '/perArchives/main',
children: [
//分页
{
path: '/perArchives/main',
component: resolve => require(["@/page/perArchives/main"], resolve),
redirect: '/perArchives/main/right',
children: [{
path: '/perArchives/main/right',
component: resolve => require(["@/page/perArchives/show/right"], resolve),
}
]
},
//添加
{
path:'/perArchives/add',
component: resolve => require(["@/page/perArchives/add"], resolve),
redirect:'/perArchives/add/information',
children: [
{
path: '/perArchives/add/information',
component: resolve => require(["@/page/perArchives/adds/information"], resolve),
}
]
},
//展示
{
path:'/perArchives/personal',
component:resolve => require(["@/page/perArchives/personal/personal"], resolve),
redirect:'/perArchives/personal/basic',
children:[
{
//详细信息
path: '/perArchives/personal/basic',
component: resolve => require(["@/page/perArchives/personal/basic"], resolve),
},
{
//人事变动
path:'/perArchives/personal/change',
component: resolve => require(["@/page/perArchives/personal/change"], resolve),
},
{
//工作评定
path:'/perArchives/personal/evaluate',
component: resolve => require(["@/page/perArchives/personal/evaluate"], resolve),
},
{
//个人考勤
path:'/perArchives/personal/attendance',
component: resolve => require(["@/page/perArchives/personal/attendance"], resolve),
}
]
}
]
}
|
import { withRouter } from "react-router";
import React from "react";
import "../CSS/Store-Syuppin.css";
import SuperKlass from './DefineConst';
import axios from 'axios';
class StoreSyuppin extends React.Component {
constructor(props){
super(props);
this.state = {
isConfirm:false,
foodInfo:{
id: 1,//仮
name: this.props.location.state.itemName,
originalPrice: this.props.location.state.originalprice,
salePrice:this.props.location.state.saleprice,
startTime: this.props.location.state.startTime.value,
endTime: this.props.location.state.endTime.value,
amount: this.props.location.state.amount,
allergys:this.props.location.state.allergys,
s3url: this.props.location.state.s3url,//S3から帰ってきたURl入れる
storeId: 2,//ストア情報を取得して更新するように変更予定
storeName: "滝川パン"//ストア情報を取得して更新するように変更予定
},
}
}
handleToStorefinPage = () => {
this.props.history.push("/store-fin");
};
handleToStorePreview = () =>{
console.log(this.state.foodInfo.name);
this.props.history.push({
pathname: "/store-preview",
state:{
itemName: this.state.foodInfo.name,
amount: this.state.foodInfo.amount,
startTime: this.state.foodInfo.startTime,
endTime: this.state.foodInfo.endTime,
originalprice: this.state.foodInfo.originalPrice,
saleprice: this.state.foodInfo.salePrice,
allergys:this.state.foodInfo.allergys,
s3url:this.state.foodInfo.s3url,
}
});
};
handlePostFoodInfo(){
axios
.post( SuperKlass.CONST.DOMAIN + '/food/', this.foodInfo)
.then((res) => {
console.dir('succces'+this.state.foodInfo);
})
.catch( (error) => {
alert("「" + this.foodInfo.name + "」登録失敗");
console.log(error, this.foodInfo);
});
}
render() {
return (
<div className='mainarea'>
<div className='check-area'>
<p>販売商品:{this.props.location.state.itemName}</p>
<p>販売個数:{this.props.location.state.amount}</p>
<p>受け取り開始時間:{this.props.location.state.startTime.label}</p>
<p>受け取り終了時間:{this.props.location.state.endTime.label}</p>
<p>定価:{this.props.location.state.originalprice}円</p>
<p>販売価格:{this.props.location.state.saleprice}円</p>
<p>アレルギー:</p>
<p>{this.props.location.state.allergys.map((e)=>e.name+' ')}</p>
</div>
<button className='storeconfirm'
onClick={ () =>{
this.handlePostFoodInfo();
this.handleToStorefinPage();
}}>出品</button>
<button className='storepreview'
onClick={this.handleToStorePreview}>プレビュー</button>
</div>
);
}
}
export default withRouter(StoreSyuppin);
|
import { useStaticQuery, graphql } from 'gatsby';
export const useSiteImages = () => {
const { avatar, icon } = useStaticQuery(
graphql`
query SiteImages {
avatar: file(relativePath: { eq: "raphadeluca-avatar.png" }) {
childImageSharp {
fixed(width: 400) {
base64
width
height
src
srcSet
}
}
}
icon: file(relativePath: { eq: "icon-raphadeluca.png" }) {
childImageSharp {
fixed(width: 400) {
base64
width
height
src
srcSet
}
}
}
}
`,
);
return {avatar, icon}
};
|
import { ADD_ORDER, REMOVE_ORDER, SET_ORDER } from "../actions/orders";
import Order from "../../models/orderItem";
import { v4 as uuidv4 } from "uuid";
import "react-native-get-random-values";
const initialState = {
orders: [],
};
const orderReducer = (state = initialState, action) => {
switch (action.type) {
case SET_ORDER:
state.orders = action.orderData;
return state;
case ADD_ORDER:
const newOrder = new Order(
uuidv4(),
action.orderData.items,
action.orderData.amount,
new Date(),
action.orderData.address
);
state.orders = state.orders.concat(newOrder);
return state;
case REMOVE_ORDER:
const updatedList = state.orders.filter((e) => e.id !== action.orderId);
state.orders = updatedList;
return state;
default:
return state;
}
};
export default orderReducer;
|
// build the numbers
function makeNum(event){
if (gotTotal === true){
displayClear();
}
display.appendChild(document.createTextNode(event.target.textContent));
var number = event.target.textContent;
if (gotFirst){
secondNumb = parseFloat(secondNumb + number);
gotSecond = true;
} else {
firstNumb = parseFloat(firstNumb + number);
}
}
// clear the display and reset all values
function displayClear(){
var keyTarget = document.createTextNode("");
display.textContent = "";
firstNumb = "";
secondNumb = "";
gotFirst = false;
gotTotal = false;
gotSecond = false;
gotOperator = false;
}
// get the operator
function getOperator(event){
if (gotOperator === false && firstNumb != ""){
operator = event.target.textContent;
display.appendChild(document.createTextNode(" "));
display.appendChild(document.createTextNode(event.target.textContent));
display.appendChild(document.createTextNode(" "));
gotFirst = true;
gotOperator = true;
}
}
// do the math!
function getVal(event){
if (gotSecond === true && gotFirst === true && gotTotal === false){
var getOp = document.createTextNode(event.target.textContent);
getOp = event.target.textContent;
var doIt = 0;
switch (operator){
case "*":
var doIt = firstNumb * secondNumb;
break;
case "-":
var doIt = firstNumb - secondNumb;
break;
case "/":
var doIt = firstNumb / secondNumb;
break;
case "+":
var doIt = firstNumb + secondNumb;
}
display.appendChild(document.createTextNode(" = "));
display.appendChild(document.createTextNode(doIt));
gotTotal = true;
}
}
// variable declarations and settings
var getNum = "";
var getKey = 0;
var firstNumb = "";
var secondNumb = "";
var gotFirst = false;
var gotSecond = false;
var gotTotal = false;
var gotOperator = false;
var operator = "";
var display = document.getElementById("display");
display.textContent = "";
// clear the display
varClear = document.getElementById("clear");
varClear.addEventListener('click', displayClear, false);
// build the number buttons
for (i = 1; i <= 10; i++){
varKey = document.getElementById("key" + i);
varKey.addEventListener('click', makeNum, false);
}
// //build the zero button
// varKey = document.getElementById("zero");
// varKey.addEventListener('click', makeNum, false);
// build the operator buttons
varAdd = document.getElementById("key11");
varAdd.addEventListener('click', getOperator, false);
varSub = document.getElementById("key12");
varSub.addEventListener('click', getOperator, false);
varMult = document.getElementById("key13");
varMult.addEventListener('click', getOperator, false);
varDiv = document.getElementById("key14");
varDiv.addEventListener('click', getOperator, false);
// evaluate the equation
varProcess = document.getElementById("process");
varProcess.addEventListener('click', getVal, false);
|
import React from 'react'
import {Grid, Row, Col, Panel} from 'react-bootstrap';
export default class HomePage extends React.Component {
render() {
let imgUrl = "http://static.tumblr.com/43467ee80971d8a4e52f15fd80a50539/nvi0dip/QCwnybas4/tumblr_static_afdblu9pkhkwosgckkcsocc4.jpg";
return (
<div>
<div style={{
width: "100%",
height: "100%",
bottom: 0,
filter: "grayscale(50%)",
position: "absolute",
background: 'url(' + imgUrl + ') no-repeat center center fixed',
backgroundSize: "cover"
}}/>
<div style={{
width: "100%",
height: "100%",
bottom: 0,
position: "absolute",
}}>
<div style={{
height: "45%",
display: "flex",
justifyContent: "center",
alignItems: "center"
}}>
<span style={{color: "#FFFFFF", fontSize: 80, marginTop: 50}}>QUERY APP</span>
</div>
<div className="topShadow" style={{
height: "55%",
display: "flex",
justifyContent: "center",
backgroundColor: "#FFFFFF",
alignItems: "center"
}}>
<Grid>
<Row className="show-grid">
<Col sm={7} md={4} style={{textAlign: "center"}}>
<h1 style={{textAlign: "center"}}>GraphQL queries</h1>
<br/>
<p>Use GraphQL queries language to
get data from local database:</p>
<Panel>
<code>
{'mutation\n' +
'{\n' +
'addWorkplace(_id: "id")\n' +
'{\n' +
'_id, name, address\n' +
'}\n' +
'}'}
</code>
</Panel>
<Panel>
<code>
{'{\n' +
'getEmployees{\n' +
'_id, name, surname, listNumber\n' +
'}\n' +
'}'}
</code>
</Panel>
</Col>
<Col sm={7} md={4} style={{textAlign: "center"}}>
<h1 style={{textAlign: "center"}}>SQL queries</h1>
<br/>
<p>Use SQL queries language to
get data from local database:</p>
<Panel>
<code>
{'SELECT LAT_N, CITY, TEMP_F ' +
'FROM STATS, STATION ' +
'WHERE MONTH = 7 ' +
'AND STATS.ID = STATION.ID ' +
'ORDER BY TEMP_F'}
</code>
</Panel>
</Col>
<Col sm={7} md={4} style={{textAlign: "center"}}>
<h1>Relay technology</h1>
<br/>
<p>
Relay is a new framework from Facebook that
provides data-fetching functionality for React
applications.
</p>
</Col>
</Row>
</Grid>
</div>
</div>
</div>
)
}
}
|
const test = require('tape');
const shuffle = require('./shuffle.js');
test('Testing shuffle', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof shuffle === 'function', 'shuffle is a Function');
const arr = [1,2,3,4,5,6];
t.notEqual(shuffle(arr), arr, 'Shuffles the array');
t.true(shuffle(arr).every(x => arr.includes(x)), 'New array contains all original elements');
t.deepEqual(shuffle([]),[],'Works for empty arrays');
t.deepEqual(shuffle([1]),[1],'Works for single-element arrays');
//t.deepEqual(shuffle(args..), 'Expected');
//t.equal(shuffle(args..), 'Expected');
//t.false(shuffle(args..), 'Expected');
//t.throws(shuffle(args..), 'Expected');
t.end();
});
|
function sellsByMonth(sells) {
if (typeof(sells) === 'string') {
sells = JSON.parse(sells);
}
var month = [];
var values = [];
for (var sell in sells.Sell) {
month[sell] = sells.Sell[sell].Sell.created;
values[sell] = parseFloat(sells.Sell[sell][0].total);
}
$('#sellsByMonth').highcharts({
title: {
text: 'Vendas Mensal',
x: -20 //center
},
subtitle: {
text: 'Total Vendido Por Mês',
x: -20
},
xAxis: {
categories: month
},
tooltip: {
valuePrefix: 'R$'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Vendas',
data: values
}]
});
}
function sellsByWeek(sells) {
if (typeof(sells) === 'string') {
sells = JSON.parse(sells);
}
var month = [];
var values = [];
for (var sell in sells.Sell) {
month[sell] = sells.Sell[sell].Sell.created;
values[sell] = parseFloat(sells.Sell[sell][0].total);
}
$('#sellsByWeek').highcharts({
title: {
text: 'Vendas da última semana',
x: -20 //center
},
subtitle: {
text: 'Total Vendido',
x: -20
},
xAxis: {
categories: month
},
tooltip: {
valuePrefix: 'R$'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Vendas',
data: values
}]
});
}
function bestProducts(bestProducts) {
if (typeof(bestProducts) === 'string') {
bestProducts = JSON.parse(bestProducts);
}
var products = [];
var values = [];
var i = 0;
for (var data in bestProducts) {
products[i] = data;
values[i] = bestProducts[data];
i++;
}
$('#bestProducts').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Produtos mais vendidos'
},
xAxis: {
categories: products
},
yAxis: {
min: 0,
title: {
text: 'Total Produtos'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black, 0 0 3px black'
}
}
}
},
series: [{
name: "Quantidade",
data: values
}]
});
}
function worstProducts(worstProducts) {
if (typeof(worstProducts) === 'string') {
worstProducts = JSON.parse(worstProducts);
}
var products = [];
var values = [];
var i = 0;
for (var data in worstProducts) {
products[i] = data;
values[i] = worstProducts[data];
i++;
}
$('#worstProducts').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Produtos menos vendidos'
},
xAxis: {
categories: products
},
yAxis: {
min: 0,
title: {
text: 'Total Produtos'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black, 0 0 3px black'
}
}
}
},
series: [{
name: "Quantidade",
data: values
}]
});
}
function bestClients(clients) {
if (typeof(clients) === 'string') {
clients = JSON.parse(clients);
}
var products = [];
var values = [];
var i = 0;
for (var data in clients) {
products[i] = data;
values[i] = clients[data];
i++;
}
$('#bestClients').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Clientes que mais compraram'
},
xAxis: {
categories: products
},
yAxis: {
min: 0,
title: {
text: 'Total Produtos'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black, 0 0 3px black'
}
}
}
},
series: [{
name: "Quantidade",
data: values
}]
});
}
function worstClients(clients) {
if (typeof(clients) === 'string') {
clients = JSON.parse(clients);
}
var products = [];
var values = [];
var i = 0;
for (var data in clients) {
products[i] = data;
values[i] = clients[data];
i++;
}
$('#worstClients').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Clientes que menos compraram'
},
xAxis: {
categories: products
},
yAxis: {
min: 0,
title: {
text: 'Total Produtos'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black, 0 0 3px black'
}
}
}
},
series: [{
name: "Quantidade",
data: values
}]
});
}
|
export const GET_ADS = 'app/AllAds/GET_ADS';
|
/*jslint browser: true*/
/*global $, window, WOW, particlesJS, Typed*/
(function ($) {
'use strict';
var win = $(window),
navbar = $('.navbar'),
scrollUp = $(".scroll-up"),
sideMenu = $(".side-menu");
/*========== Start Wow Js ==========*/
new WOW().init();
/*========== Start Navbar Auto Change ==========*/
win.on('scroll', function () {
if (win.scrollTop() > 50) {
navbar.addClass('nav-fixed').removeClass('fixed-top');
} else {
navbar.addClass('fixed-top').removeClass('nav-fixed');
}
});
/*========== Start Scroll For Navigation Menu ==========*/
navbar.on('click', '.nav-item>a', function (e) {
e.preventDefault();
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - 85
}, 1000);
});
$('#contact-form').submit(function(e) {
e.preventDefault();
var _this = $(this);
_this.find('.status').show();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data) {
var errorBox = '<div class="alert alert-danger" role="alert">The email could not be sent.</div>';
var successBox = '<div class="alert alert-success" role="alert">Your message has been sent.</div>';
data = JSON.parse(data);
var msg = data.length > 0 ? errorBox : successBox;
_this.find('.status').html(msg);
setTimeout(function(){
_this.find('.status').fadeOut();
}, 3000);
}
});
});
// Sync Navbar Links With Section
$('body').scrollspy({
target: '#navtoggler',
offset: 100
});
//// COLLAPSED MENU CLOSE ON CLICK
navbar.on('click', '.navbar-collapse', function (e) {
if ($(e.target).is('a')) {
$(this).collapse('hide');
}
});
/*========== Side Menu ==========*/
$(".side-menu-btn").on('click', function (e) {
e.preventDefault();
sideMenu.addClass('open-menu');
});
$(".close-side-menu").on('click', function (e) {
e.preventDefault();
sideMenu.removeClass('open-menu');
});
win.on('scroll', function () {
sideMenu.removeClass('open-menu');
});
//// PARTICLES TRIGGER
if ($("#particles-js")[0]) {
particlesJS("particles-js", {
"particles": {
"number": {
"value": 60,
"density": {
"enable": true,
"value_area": 800
}
},
"color": {
"value": "#FFF"
},
"shape": {
"type": "circle",
"stroke": {
"width": 0,
"color": "#FFF"
},
"polygon": {
"nb_sides": 5
},
"image": {
"src": "img/github.svg",
"width": 100,
"height": 100
}
},
"opacity": {
"value": 0.5,
"random": false,
"anim": {
"enable": false,
"speed": 1,
"opacity_min": 0.1,
"sync": false
}
},
"size": {
"value": 3,
"random": true,
"anim": {
"enable": false,
"speed": 40,
"size_min": 0.1,
"sync": false
}
},
"line_linked": {
"enable": true,
"distance": 150,
"color": "#FFF",
"opacity": 0.4,
"width": 1
},
"move": {
"enable": true,
"speed": 6,
"direction": "none",
"random": false,
"straight": false,
"out_mode": "out",
"bounce": false,
"attract": {
"enable": false,
"rotateX": 600,
"rotateY": 1200
}
}
},
"interactivity": {
"detect_on": "canvas",
"events": {
"onhover": {
"enable": true,
"mode": "grab"
},
"onclick": {
"enable": true,
"mode": "push"
},
"resize": true
},
"modes": {
"grab": {
"distance": 140,
"line_linked": {
"opacity": 1
}
},
"bubble": {
"distance": 400,
"size": 40,
"duration": 2,
"opacity": 8,
"speed": 3
},
"repulse": {
"distance": 200,
"duration": 0.4
},
"push": {
"particles_nb": 4
},
"remove": {
"particles_nb": 2
}
}
},
"retina_detect": true
});
}
/*========== Start Counter To Js Statistics ==========*/
if ($(".count")[0]) {
win.on('scroll.statistics', function () {
var stat = $('.statistics');
if ($(this).scrollTop() >= stat.offset().top - win.height() + 220) {
$('.count').countTo();
win.off('scroll.statistics');
}
});
}
/*========== Start Portfolio Trigger Filterizr Js ==========*/
$("#control li").on('click', function () {
$(this).addClass('active').siblings().removeClass('active');
});
// The Filterizr
if ($("#filtr-container")[0]) {
$('#filtr-container').filterizr({
animationDuration: 0.4
});
}
/*========== Start Header Typed Js ========== */
if ($("#type")[0]) {
var element = new Typed('#type', {
strings: ["build Best Digital products that function", "helps to grow your business", "Is a Creating Awesome Websites"],
typeSpeed: 60,
backSpeed: 10,
loop: true
});
}
/*========== End Header Typed Js ==========*/
/*========== Start Magnigic Popup Js ==========*/
if ($('.my-work')[0]) {
/* $('.my-work').magnificPopup({
delegate: 'a',
type: 'image',
gallery: {
enabled: true
}
}); */
}
/*========== Start OWL Carousel Js testimonial ==========*/
if ($('.slider-hero')[0]) {
$(".slider-hero").owlCarousel({
items: 1,
nav: true,
dots: true,
smartSpeed: 1000,
autoplay: 2000,
loop: true,
navText: ["<i class='fas fa-angle-left'></i>", "<i class='fas fa-angle-right'></i>"],
mouseDrag: false,
touchDrag: false,
responsive: {
0: {
items: 1
},
768: {
items: 1
},
1200: {
items: 1
}
}
});
}
$(".slider-hero").on("translate.owl.carousel", function () {
$(".info-header h1").removeClass("animated fadeInUp").css("opacity", "0");
$(".info-header .text-header").removeClass("animated fadeInDown").css("opacity", "0");
$(".info-header .banner-btn").removeClass("animated fadeInDown").css("opacity", "0");
});
$(".slider-hero").on("translated.owl.carousel", function () {
$(".info-header h1").addClass("animated fadeInUp").css("opacity", "1");
$(".info-header .text-header").addClass("animated fadeInDown").css("opacity", "1");
$(".info-header .banner-btn").addClass("animated fadeInDown").css("opacity", "1");
});
/* ========== Start OWL Carousel Js testimonial ==========*/
if ($('.testimonial')[0]) {
$('.testimonial').owlCarousel({
loop: true,
margin: 30,
smartSpeed: 1000,
autoplay: 2000,
responsive: {
0: {
items: 1
},
768: {
items: 2
},
1200: {
items: 3
}
}
});
}
/*========== Start OWL Carousel Js sponsor ==========*/
if ($('.sponsor')[0]) {
$('.sponsor').owlCarousel({
loop: true,
margin: 30,
smartSpeed: 1000,
autoplay: 2000,
responsive: {
0: {
items: 2
},
768: {
items: 3
},
1200: {
items: 5
}
}
});
}
function animateProgressBar() {
$('.skill-box .progress-line > span').each(function () {
var percent = $(this).data('percent');
$(this).css({
width: percent + '%',
transition: 'width 1.7s linear'
});
});
}
if ($(".about")[0]) {
$(window).on('scroll', function () {
if ($(window).scrollTop() > $('.about').offset().top + 200) {
animateProgressBar();
}
});
if ($(window).scrollTop() > $('.about').offset().top + 200) {
animateProgressBar();
}
}
/*========== Start Scroll Up ==========*/
// Show And Hide Buttom Back To Top
win.on('scroll', function () {
if ($(this).scrollTop() >= 600) {
scrollUp.show(300);
} else {
scrollUp.hide(300);
}
});
// Back To 0 Scroll Top body
scrollUp.on('click', function () {
$("html, body").animate({
scrollTop: 0
}, 1000);
});
}($));
|
import React, { Component } from 'react'
import { withStyles } from 'material-ui/styles'
import { connect } from 'react-redux'
import compose from 'recompose/compose'
import { reduxForm } from 'redux-form'
import Grid from 'material-ui/Grid'
import Card, { CardContent } from 'material-ui/Card'
import Typography from 'material-ui/Typography'
import Chip from 'material-ui/Chip'
const styles = theme => ({
tags: {
marginTop: 4,
},
})
export class EventTags extends Component {
constructor(props) {
super(props)
this.state = {}
}
render() {
const { classes, tags } = this.props
if (tags.length === 0) return null
else {
return (
<Grid item xs={12}>
<Card className={classes.card}>
<CardContent>
<Typography type="headline" component="h2">
Tags
</Typography>
<Grid container direction="row" spacing={8} className={classes.tags}>
{tags.map(function(chip, index) {
return (
<Grid item>
<Chip label={chip} key={index} />
</Grid>
)
})}
</Grid>
</CardContent>
</Card>
</Grid>
)
}
}
}
function mapStateToProps(state) {
return { tags: state.form.AddEventForm.values.tags }
}
export default compose(
withStyles(styles),
connect(mapStateToProps, null),
reduxForm({ form: 'AddEventForm', destroyOnUnmount: false })
)(EventTags)
|
window.onload=function (){
function g(id){return document.getElementById(id);}
// 获得按钮
var pre_btn=g('prev');
var next_btn=g('next');
// 获得图片框
var imgBox_left=g('imgBox_left');
var imgBox_right=g('imgBox_right');
//获得图片内容和说明文字等
var img_left=imgBox_left.getElementsByTagName('img')[0];
var img_detail_left=imgBox_left.getElementsByTagName('p')[0];
var img_left_index=imgBox_left.getElementsByTagName('p')[1];
// 定义图片以及文字资源
var img_series_left=['images/1.jpg','images/2.jpg','images/3.jpg','images/4.jpg'];
var left_length=img_series_left.length;
var img_detail_lfwords=['湖边小屋','森林长廊','临安城','艺术大桥'];
var img_series_right=['images/5.jpg','images/6.jpg','images/7.jpg'];
var right_length=img_series_right.length;
var img_detail_rgwords=['bleach','animation','Janpanese'];
// var right
//初始化页面结构
//定义控制参数control_argument并初始化为0
var control_argument=0;
nextPic();
// 按钮控制
next_btn.onclick=nextPic;
pre_btn.onclick=lastPic;
// 函数定义
function nextPic(){
if(control_argument>left_length-1){
control_argument=0;
}
content_change(control_argument);
control_argument++;
}
function lastPic(){
// 注意因为初始化时候参数增加了1的缘故,这里应该从1开始
if(control_argument<=1){
control_argument=left_length-1;
}
// alert(control_argument);
content_change(control_argument);
control_argument--;
}
function content_change(index){
img_left.src=img_series_left[index];
img_detail_left.innerHTML=img_detail_lfwords[index];
img_left_index.innerHTML=index+1+'/'+left_length;
}
}
|
import React, { Component } from 'react'
import FormSalidas from '../animals/FormSalida';
import {Card, List, Divider} from 'antd'
import {Link} from 'react-router-dom'
import MainLoader from '../../common/Main Loader';
//import {bindActionCreators} from "redux";
import {connect} from "react-redux";
class SaleNoteDetail extends Component {
state={
list:[],
disabled:true,
}
render() {
let {match, saleNote, fetched} = this.props;
let {list, disabled} = this.state;
console.log(saleNote)
if(!fetched)return <MainLoader/>
return (
<div style={{display:'flex', justifyContent:'space-around'}}>
<div style={{width:'40%'}}>
<div style={{marginBottom:10, color:'rgba(0, 0, 0, 0.65)' }}>
<Link to={'/admin/saleNotes'}>
Notas de Venta
</Link>
<Divider type="vertical" />
Nota {match.params.id}
</div>
<FormSalidas clients={list} disabled={disabled} {...saleNote}/>
</div>
<Card style={{width:'40%'}}>
<List
itemLayout="horizontal"
dataSource={saleNote.animals}
renderItem={item => (
<List.Item>
<List.Item.Meta
title={<Link to={`/admin/animals/${item.id}`}>{item.arete_siniga}</Link>}
description={item.arete_rancho}
/>
</List.Item>
)}
/>
</Card>
</div>
)
}
}
function mapStateToProps (state, ownProps) {
let saleNote = state.saleNotes.list.find(s=>{return ownProps.match.params.id==s.id})
return {
saleNote,
fetched:saleNote!==undefined
}
}
function mapDispatchToProps(dispatch){
return{
//saleNotesActions:bindActionCreators(saleNotesActions, dispatch)
}
}
SaleNoteDetail = connect(mapStateToProps, mapDispatchToProps)(SaleNoteDetail);
export default SaleNoteDetail
|
//! AUTH
export const OTP_REQUEST = 'OTP_REQUEST';
export const OTP_SUCCESS = 'OTP_SUCCESS';
export const OTP_ERROR = 'OTP_ERROR';
export const RESEND_OTP_REQUEST = 'RESEND OTP REQUEST';
export const RESEND_OTP_SUCCESS = 'RESEND OTP SUCCESS';
export const OTP_VERIFY_REQUEST = 'OTP_VERIFY_REQUEST';
export const OTP_VERIFY_SUCCESS = 'OTP_VERIFY_SUCCESS';
export const OTP_VERIFY_ERROR = 'OTP_VERIFY_ERROR';
// ! On-Board
export const ONBOARD_REQUEST = 'ONBOARD_REQUEST';
export const ONBOARD_SUCCESS = 'ONBOARD_SUCCESS';
export const ONBOARD_ERROR = 'ONBOARD_ERROR';
// ! Dashboard
export const DASHBOARD_REQUEST = 'DASHBOARD_REQUEST';
export const DASHBOARD_SUCCESS = 'DASHBOARD_SUCCESS';
export const DASHBOARD_ERROR = 'DASHBOARD_ERROR';
// ! Jobs
export const FETCHED_JOBS_REQUEST = 'FETCHED_JOBS_REQUEST';
export const FETCHED_JOBS_SUCCESS = 'FETCHED_JOBS_SUCCESS';
export const FETCHED_JOBS_ERROR = 'FETCHED_JOBS_ERROR';
export const ADD_JOB_REQUEST = 'ADD_JOB_REQUEST';
export const ADD_JOB_SUCCESS = 'ADD_JOB_SUCCESS';
export const ADD_JOB_ERROR = 'ADD_JOB_ERROR';
// ! Candidates
export const ADD_CANDIDATES_REQUEST = 'ADD_CANDIDATES_REQUEST';
export const ADD_CANDIDATES_SUCCESS = 'ADD_CANDIDATES_SUCCESS';
export const ADD_CANDIDATES_ERROR = 'ADD_CANDIDATES_ERROR';
|
import cart from '@/web-client/reducers/shop/cart';
import productList from '@/web-client/reducers/shop/productList';
import ui from '@/web-client/reducers/shop/ui';
export default (state = {}, action) => ({
cart: cart(state.cart, action),
productList: productList(state.productList, action),
ui: ui(state.ui, action),
});
|
import React, { Fragment } from 'react';
import { storiesOf } from '@storybook/react';
import { pluck } from 'ramda';
import Filters from './Filters';
import Quarter from './Filters.Quarter';
import Cuisine from './Filters.Cuisine';
import Bar from './Filters.Bar';
import Price from './Filters.Price';
import withSearch from '../../hocs/withSearch';
import { withRedux } from '../../stories/decorators';
import { algoliaItems, mockApi } from '../../stories/stories.shared';
import { cuisineTestdata } from './Filters.test';
import { FIRESTORE_COLLECTION_CATEGORY_GROUPS } from '../../settings';
storiesOf('Filters', module)
.addDecorator(withRedux())
// .add('default', _ => {
// mockApi(FIRESTORE_COLLECTION_CATEGORY_GROUPS, cuisineTestdata);
// const Enhanced = withSearch(() => <Filters />);
// return <Enhanced />;
// })
.add('Filters.Quarter', _ => {
return <Quarter items={algoliaItems()} />;
})
.add('Filters.Price', _ => {
return <Price items={algoliaItems(['1', '2', '3', '4'])} />;
})
.add('Filters.Bar', _ => {
return <Bar items={false} />;
})
.add('Filters.Cuisine', _ => {
mockApi(FIRESTORE_COLLECTION_CATEGORY_GROUPS, cuisineTestdata);
return (
<Cuisine items={algoliaItems(pluck('group', cuisineTestdata))} />
);
});
|
/* Copyright (c) 2020 Red Hat, Inc. */
/// <reference types="cypress" />
import { getDefaultSubstitutionRules, getViolationsPerPolicy, getViolationsCounter } from './views'
import { getConfigObject } from '../config'
export const test_genericPolicyGovernance = (confFilePolicy, confFileViolationsInform, confFileViolationsEnforce=null, confFileClusters='clusters.yaml', filteredClusterList=null) => {
const confClusters = getConfigObject(confFileClusters)
const clusterList = filteredClusterList ? filteredClusterList : Object.keys(confClusters)
const substitutionRules = [ [/\[ID\]/g, Cypress.env('RESOURCE_ID')] ]
// policy-config is used for policy creation and validation
const confPolicies = getConfigObject(confFilePolicy, 'yaml', substitutionRules)
for (const policyName in confPolicies) {
it(`Create new policy ${policyName} using the form`, () => {
cy.FromGRCToCreatePolicyPage()
.createPolicyFromSelection(policyName, true, confPolicies[policyName])
})
it(`Check that policy ${policyName} is present in the policy listing`, () => {
cy.verifyPolicyInListing(policyName, confPolicies[policyName])
})
it(`Wait for policy ${policyName} status to become available`, () => {
cy.waitForPolicyStatus(policyName)
})
it(`Disable policy ${policyName}`, () => {
cy.actionPolicyActionInListing(policyName, 'Disable')
})
it(`Check disabled policy ${policyName}`, () => {
cy.verifyPolicyInListing(policyName, confPolicies[policyName], 'disabled')
})
it(`Enable policy ${policyName}`, () => {
cy.actionPolicyActionInListing(policyName, 'Enable')
})
}
for (const policyName in confPolicies) {
// we need to do the substitution per policy - probably we could do this once for whole test
const confClusterViolations = getConfigObject(confFileViolationsInform, 'yaml', getDefaultSubstitutionRules({policyname:policyName}))
const clusterViolations = getViolationsPerPolicy(policyName, confPolicies[policyName], confClusterViolations, clusterList)
const violationsCounter = getViolationsCounter(clusterViolations)
it(`Wait for policy ${policyName} status to become available`, () => {
cy.waitForPolicyStatus(policyName, violationsCounter)
})
it(`Check enabled policy ${policyName}`, () => {
cy.verifyPolicyInListing(policyName, confPolicies[policyName], 'enabled', violationsCounter)
})
}
for (const policyName in confPolicies) {
// we need to do the substitution per policy
const confViolationPatterns = getConfigObject('violation-patterns.yaml', 'yaml', getDefaultSubstitutionRules({policyname:policyName}))
const confClusterViolations = getConfigObject(confFileViolationsInform, 'yaml', getDefaultSubstitutionRules({policyname:policyName}))
const clusterViolations = getViolationsPerPolicy(policyName, confPolicies[policyName], confClusterViolations, clusterList)
const violationsCounter = getViolationsCounter(clusterViolations)
it(`Verify policy ${policyName} details at the detailed page`, () => {
cy.visit(`/multicloud/policies/all/${confPolicies[policyName]['namespace']}/${policyName}`).waitForPageContentLoad()
.verifyPolicyInPolicyDetails(policyName, confPolicies[policyName], 'enabled', violationsCounter)
})
it(`Verify policy ${policyName} template details at the detailed page`, () => {
cy.verifyPolicyInPolicyDetailsTemplates(policyName, confPolicies[policyName])
})
it(`Verify policy ${policyName} placement binding details at the detailed page`, () => {
cy.verifyPlacementBindingInPolicyDetails(policyName, confPolicies[policyName])
})
it(`Verify policy ${policyName} placement rule at the detailed page`, () => {
cy.waitForClusterPolicyStatus(clusterViolations) // since it could happen that some clusters do not have the status yet
.verifyPlacementRuleInPolicyDetails(policyName, confPolicies[policyName], clusterViolations)
})
it(`Verify policy ${policyName} violations at the Status - Clusters page`, () => {
cy.visit(`/multicloud/policies/all/${confPolicies[policyName]['namespace']}/${policyName}/status`).waitForPageContentLoad()
// verify all violations per cluster
cy.waitForClusterTemplateStatus(clusterViolations)
.verifyViolationsInPolicyStatusClusters(policyName, confPolicies[policyName], clusterViolations, confViolationPatterns)
})
it(`Verify policy ${policyName} violations at the Status - Templates page`, () => {
// open the Templates tab - we should have a command for this
cy.get('#policy-status-templates').click()
// verify violations per template
.verifyViolationsInPolicyStatusTemplates(policyName, confPolicies[policyName], clusterViolations, confViolationPatterns)
})
for (const clusterName of clusterList) {
it(`Verify policy details & templates on cluster ${clusterName} detailed page`, () => {
cy.visit(`/multicloud/policies/all/${confPolicies[policyName]['namespace']}/${policyName}`).waitForPageContentLoad()
cy.goToPolicyClusterPage(policyName, confPolicies[policyName], clusterName)
.verifyPolicyDetailsInCluster(policyName, confPolicies[policyName], clusterName, clusterViolations, confViolationPatterns)
.verifyPolicyTemplatesInCluster(policyName, confPolicies[policyName], clusterName, clusterViolations)
.verifyPolicyViolationDetailsInCluster(policyName, confPolicies[policyName], clusterName, clusterViolations, confViolationPatterns)
})
}
}
// run the test for enforced policy only if the config file was given
if (confFileViolationsEnforce) {
for (const policyName in confPolicies) {
it(`Enforce policy ${policyName}`, () => {
cy.visit('/multicloud/policies/all').waitForPageContentLoad()
.actionPolicyActionInListing(policyName, 'Enforce')
})
it(`Check that enforced policy ${policyName} is present in the policy listing`, () => {
confPolicies[policyName]['enforce'] = true
cy.verifyPolicyInListing(policyName, confPolicies[policyName])
})
}
for (const policyName in confPolicies) {
// we need to do the substitution per policy
const confViolationPatterns = getConfigObject('violation-patterns.yaml', 'yaml', getDefaultSubstitutionRules({policyname:policyName}))
const confClusterViolations = getConfigObject(confFileViolationsEnforce, 'yaml', getDefaultSubstitutionRules({policyname:policyName}))
const clusterViolations = getViolationsPerPolicy(policyName, confPolicies[policyName], confClusterViolations, clusterList)
const violationsCounter = getViolationsCounter(clusterViolations)
it(`Wait for policy ${policyName} status to become available`, () => {
cy.visit('/multicloud/policies/all').waitForPageContentLoad()
cy.waitForPolicyStatus(policyName, violationsCounter)
})
it(`Check enabled policy ${policyName}`, () => {
cy.verifyPolicyInListing(policyName, confPolicies[policyName], 'enabled', violationsCounter)
})
it(`Verify policy ${policyName} details at the detailed page`, () => {
cy.visit(`/multicloud/policies/all/${confPolicies[policyName]['namespace']}/${policyName}`).waitForPageContentLoad()
.verifyPolicyInPolicyDetails(policyName, confPolicies[policyName], 'enabled', violationsCounter)
})
it(`Verify policy ${policyName} template details at the detailed page`, () => {
cy.verifyPolicyInPolicyDetailsTemplates(policyName, confPolicies[policyName])
})
it(`Verify policy ${policyName} placement binding details at the detailed page`, () => {
cy.verifyPlacementBindingInPolicyDetails(policyName, confPolicies[policyName])
})
it(`Verify policy ${policyName} placement rule at the detailed page`, () => {
cy.waitForClusterPolicyStatus(clusterViolations) // since it could happen that some clusters do not have the status yet
.verifyPlacementRuleInPolicyDetails(policyName, confPolicies[policyName], clusterViolations)
})
it(`Verify policy ${policyName} violations at the Status - Clusters page`, () => {
cy.visit(`/multicloud/policies/all/${confPolicies[policyName]['namespace']}/${policyName}/status`).waitForPageContentLoad()
// verify all violations per cluster
cy.waitForClusterTemplateStatus(clusterViolations)
.verifyViolationsInPolicyStatusClusters(policyName, confPolicies[policyName], clusterViolations, confViolationPatterns)
})
it(`Verify policy ${policyName} violations at the Status - Templates page`, () => {
// open the Templates tab - we should have a command for this
cy.get('#policy-status-templates').click()
// verify violations per template
.verifyViolationsInPolicyStatusTemplates(policyName, confPolicies[policyName], clusterViolations, confViolationPatterns)
})
for (const clusterName of clusterList) {
it(`Verify policy details & templates on cluster ${clusterName} detailed page`, () => {
cy.visit(`/multicloud/policies/all/${confPolicies[policyName]['namespace']}/${policyName}`).waitForPageContentLoad()
cy.goToPolicyClusterPage(policyName, confPolicies[policyName], clusterName)
.verifyPolicyDetailsInCluster(policyName, confPolicies[policyName], clusterName, clusterViolations, confViolationPatterns)
.verifyPolicyTemplatesInCluster(policyName, confPolicies[policyName], clusterName, clusterViolations)
.verifyPolicyViolationDetailsInCluster(policyName, confPolicies[policyName], clusterName, clusterViolations, confViolationPatterns)
})
}
}
}
// verify the History page for each policy, cluster and template used
// this would be a bit more complicated as history is split per policy, cluster, template
for (const policyName in confPolicies) {
// read the configuration for each policy
const confViolationPatterns = getConfigObject('violation-patterns.yaml', 'yaml', getDefaultSubstitutionRules({policyname:policyName}))
const confClusterViolationsInform = getConfigObject(confFileViolationsInform, 'yaml', getDefaultSubstitutionRules({policyname:policyName}))
const clusterViolationsInform = getViolationsPerPolicy(policyName, confPolicies[policyName], confClusterViolationsInform, clusterList)
let confClusterViolationsEnforce
let clusterViolationsEnforce
if (confFileViolationsEnforce) {
confClusterViolationsEnforce = getConfigObject(confFileViolationsEnforce, 'yaml', getDefaultSubstitutionRules({policyname:policyName}))
clusterViolationsEnforce = getViolationsPerPolicy(policyName, confPolicies[policyName], confClusterViolationsEnforce, clusterList)
}
// now for each cluster get a merged list of cluster violations (from both Inform and Enforce violations)
for (const clusterName of clusterList) {
const allClusterViolations = confFileViolationsEnforce ? clusterViolationsInform[clusterName].concat(clusterViolationsEnforce[clusterName]) : clusterViolationsInform[clusterName]
const templateDict = {}
// now I need to split violations per template name
for (const violation of allClusterViolations) {
const templateName = violation.replace(/-[^-]*$/, '')
if (!(templateName in templateDict)) {
templateDict[templateName] = []
}
templateDict[templateName].push(violation)
}
// now iterate through template names and check all violations are listed
for (const [templateName, violations] of Object.entries(templateDict)) {
const url = `/multicloud/policies/all/${confPolicies[policyName]['namespace']}/${policyName}/status/${clusterName}/templates/${templateName}/history`
it(`Verify the History page for policy ${policyName} cluster ${clusterName} template ${templateName}`, () => {
cy.visit(url).waitForPageContentLoad()
.verifyPolicyViolationDetailsInHistory(templateName, violations, confViolationPatterns)
})
}
}
}
// delete created policies at the end
for (const policyName in confPolicies) {
it(`Policy ${policyName} can be deleted in the policy listing`, () => {
// we could use a different way how to return to this page
cy.visit('/multicloud/policies/all').waitForPageContentLoad()
.actionPolicyActionInListing(policyName, 'Remove')
})
it(`Deleted policy ${policyName} is not present in the policy listing`, () => {
cy.verifyPolicyNotInListing(policyName)
})
}
}
export const test_applyPolicyYAML = (confFilePolicy, substitutionRules=null) => {
if (substitutionRules === null) {
substitutionRules = getDefaultSubstitutionRules()
}
const rawPolicyYAML = getConfigObject(confFilePolicy, 'raw', substitutionRules)
const policyName = rawPolicyYAML.replace(/\r?\n|\r/g, ' ').replace(/^.*?name:\s*/m, '').replace(/\s.*/m,'')
it('Create the clean up policy using the YAML', () => {
cy.visit('/multicloud/policies/create')
cy.log(rawPolicyYAML)
.createPolicyFromYAML(rawPolicyYAML, true)
})
it(`Check that policy ${policyName} is present in the policy listing`, () => {
cy.verifyPolicyInListing(policyName, {})
})
it(`Wait for ${policyName} status to become available`, () => {
cy.waitForPolicyStatus(policyName, '0/')
})
it(`Delete policy ${policyName}`, () => {
cy.actionPolicyActionInListing(policyName, 'Remove')
})
it(`Verify that policy ${policyName} is not present in the policy listing`, () => {
cy.verifyPolicyNotInListing(policyName)
})
}
|
import Link from '@docusaurus/Link';
import Layout from '@theme/Layout';
import React from 'react';
const Help = () => {
return (
<Layout>
<section>
<div className="container help-container">
<h1>Need help?</h1>
<div className="help-two-col">
<p>
If your questions are not answered in the docs and various readmes, reach out to us
through <Link to="https://github.com/openfun/richie/issues">Github Issues</Link> or by
email at fun.dev@fun-mooc.fr.
</p>
<p>
We also have a regular video-chat meetup with the stakeholders of Richie, (some)
Thursdays in the afternoon, UTC time. Reach out to us to know when the next one takes
place and come introduce yourself!
</p>
</div>
<div className="help-three-col">
<div>
<h2>Browse Docs</h2>
<p>
Learn more in the <Link to="docs/discover">documentation</Link>. Please tell us if
anything is missing or out-of-date.
</p>
</div>
<div>
<h2>Stay up to date</h2>
<p>
Keep up with the latest updates on Richie by reading the{' '}
<Link to="https://github.com/openfun/richie/blob/master/CHANGELOG.md">
changelog
</Link>
.
</p>
</div>
<div>
<h2>Join the community</h2>
<p>
This project is maintained by a dedicated group of people led by the team at{' '}
<Link to="https://github.com/openfun">France Université Numérique</Link>.
</p>
</div>
</div>
</div>
</section>
</Layout>
);
};
export default Help;
|
var checkRelQ = function () {
if (populatedRelQ) {
displayFirstDataRelQ();
} else {
setTimeout(checkRelQ, 100);
}
}
function displayFirstDataRelQ() {
document.getElementById("addMultipleRelQ").checked = true;
$('#sprintReleaseQ option:last').prop('selected', true);
var dropdown = document.getElementById("scrumTeamReleaseQ");
for (var i = 0; i < dropdown.options.length; i++) {
dropdown.value = dropdown.options[i].value;
displayReleaseQ();
}
document.getElementById("scrumTeamReleaseQ").value = "All";
}
function showTeamHistoryRelQ() {
clearAddedRelQ();
document.getElementById("addMultipleRelQ").checked = true;
var dropdown = document.getElementById("sprintReleaseQ");
var temp = dropdown.value;
for (var i = 0; i < dropdown.options.length; i++) {
dropdown.value = dropdown.options[i].value;
displayReleaseQ();
}
dropdown.value = temp;
}
function showSprintRelQ() {
clearAddedRelQ();
document.getElementById("addMultipleVel").checked = true;
clearAddedRelQ();
document.getElementById("addMultipleRelQ").checked = true;
var dropdown = document.getElementById("scrumTeamReleaseQ");
var temp = dropdown.value;
for (var i = 0; i < dropdown.options.length; i++) {
dropdown.value = dropdown.options[i].value;
displayReleaseQ();
}
dropdown.value = temp;
}
function checkBoxClearAddedRelQ() {
if (document.getElementById("addMultipleRelQ").checked) {
return;
} else {
clearAddedRelQ();
}
}
function clearAddedRelQ() {
d3.selectAll("#releaseQSvg").remove();
}
function displayReleaseQModal(d) {
var modal = document.getElementById('myModal')
if (d.lastYearMonth) {
var allPercentChange = Math.round(((d.monthDefects - d.lastYearMonth.monthDefects) / d.monthDefects) * 10000) / 100;
var urgentPercentChange = Math.round(((d.monthUrgentDefects - d.lastYearMonth.monthUrgentDefects) / d.monthUrgentDefects) * 10000)/100;
if (allPercentChange < 0) {
var allColor = "darkgreen";
allPercentChange = "<span class=\"downarrow\">⇮</span> " + allPercentChange;
} else {
var allColor = "red";
allPercentChange = "<span class=\"uparrow\">⇮</span> " + allPercentChange;
}
if (urgentPercentChange < 0) {
var urgentColor = "darkgreen";
urgentPercentChange = "<span class=\"downarrow\">⇮</span> " + urgentPercentChange;
} else {
var urgentColor = "red";
urgentPercentChange = "<span class=\"uparrow\">⇮</span> " + urgentPercentChange;
}
document.getElementById('modal-text').innerHTML = "<strong style=\"font-size:16px;\"> " + reformatMonthVal(d.lastYearMonth.month) + "</strong><br/><p style = \"font-weight:600;color:" + allColor + "\"> Defects: " + d.lastYearMonth.monthDefects + "<p style = \"font-weight:600;font-size:24px;color:" + allColor + "\"<br/> YOY: " + allPercentChange + "%</p>" +
"<br/><p style = \"font-weight:600;color:" + urgentColor + "\">Urgent Defects: " + d.lastYearMonth.monthUrgentDefects+ "<p style = \"font-weight:600;font-size:24px;color:" + allColor + "\"<br/> YOY: " + urgentPercentChange + "%</p>";
} else {
document.getElementById('modal-text').innerHTML = "<strong style=\"color:#55555\"> No data found for previous month. </strong>";
}
modal.style.display = "block";
}
function displayReleaseQ() {
var teamVal = document.getElementById("scrumTeamReleaseQ").value;
var monthVal = document.getElementById("sprintReleaseQ").value;
var addMultipleVal = document.getElementById("addMultipleRelQ").checked;
var w = 150;
var h = 200;
var bordercolor = "gray";
var strokewidth = "5px";
var startYear = 2015;
var add = 0;
var mo = "April"
var sprintsLeft = sprintsInMonth[mo];
d3.csv(pathToCsv, function (error, dataset) {
dataset.forEach(function (d) {
sprint: "Sprint " + d.sprint;
team: d.team;
urgent: d.urgentdefects;
all: d.alldefects;
d.prevSprint = (dataset.filter(function (e) {
return (e.sprint == +d.sprint - 1 && e.team == teamVal);
}))[0];
d.nextSprint = (dataset.filter(function (e) {
return (e.sprint == +d.sprint + 1 && e.team == teamVal);
}))[0];
if (d.prevSprint == null) {
add = 0;
mo = "April";
sprintsLeft = sprintsInMonth[mo];
}
if (sprintsLeft == 1) {
d.month = mo + (startYear + add);
if (!(monthSprints[d.sprint])) {
monthSprints[d.sprint] = d.month;
}
}
if (sprintsLeft == 0) {
sprintsLeft = sprintsInMonth[mo];
mo = months[(months.indexOf(mo) + 1) % 12];
if (mo == "January") {
add += 1;
}
}
sprintsLeft--;
d.mo = mo;
if (d.prevSprint) {
if (d.prevSprint.prevSprint && sprintsInMonth[d.mo] == 3) {
d.monthDefects = +d.alldefects + +d.prevSprint.alldefects + +d.prevSprint.prevSprint.alldefects;
} else {
d.monthDefects = +d.alldefects + +d.prevSprint.alldefects;
}
} else {
d.monthDefects = +d.alldefects;
}
if (sprintsInMonth[d.mo] == 3) {
d.monthUrgentDefects = +d.urgentdefects + +d.prevSprint.urgentdefects + +d.nextSprint.urgentdefects;
} else {
if (d.prevSprint) {
d.monthUrgentDefects = +d.urgentdefects + +d.prevSprint.urgentdefects;
} else {
d.monthUrgentDefects = +d.urgentdefects;
}
}
if (d.month) {
var digit = +(d.month.charAt(d.month.length - 1));
var lastYear = d.month.substr(0, d.month.length-1) + (digit -1);
d.lastYearMonth = (dataset.filter(function (e) {
return (e.month == lastYear && e.team == teamVal);
}))[0];
}
});
if (!addMultipleVal) {
d3.select("#releaseQsvg").remove();;
}
var allR;
var urgentR;
var defectsSvg = d3.select("#releaseQVis").append("svg")
.attr("id", "releaseQSvg")
.attr("width", w)
.attr("height", h);
var defects = defectsSvg
.selectAll("circle")
.data(dataset
.filter(function (d) { return (d.month == monthVal && d.team == teamVal); })
)
.enter();
var borderPath = defects.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("height", w)
.attr("width", h)
.style("stroke", bordercolor)
.style("fill", function (d) {
if (d.team == "All") {
if (d.monthDefects > 10) {
return "#E77471";
} else if (d.monthDefects > 10) {
return "pink";
}
else {
return "none";
}
}
else if (d.monthDefects > 5) {
return "pink";
} else {
return "none";
}
})
.style("strokewidth", strokewidth);
var d1 = defects.append("circle")
.attr("r", function (d) {
if (d.monthDefects > 40) {
allR = 40
} else {
allR = d.monthDefects;
}
return allR;
})
.attr("cx", 75)
.attr("cy", 75)
.attr("cursor", "pointer")
.attr("fill", "orange")
.on("click", function (d) {
displayReleaseQModal(d)
});
defects.append("circle")
.filter(function (d) { return (d.month == monthVal && d.team == teamVal); })
.attr("r", function (d) {
if (d.monthUrgentDefects > 40) {
urgentR = 40;
} else {
urgentR = d.monthUrgentDefects;
}
return urgentR;
})
.attr("cx", 75)
.attr("cy", 75)
.attr("cursor", "pointer")
.attr("fill", "red")
.on("click", function (d) {
displayReleaseQModal(d)
});
defects.append("foreignObject")
.attr("x", "0")
.attr("y", function (d) {
if ((d.monthDefects == 0) && (d.monthUrgentDefects == 0)) {
return "50";
}
else {
return "115";
}
})
.attr("width", 150)
.append("xhtml")
.style("font", "12px 'Helvetica Neue'")
.style("color", function (d) {
if (d.monthUrgentDefects > 0) {
return "red";
} else if (d.monthDefects > 0) {
return "#FF4500";
} else {
return "green";
}
})
.html(function (d) {
if ((d.monthUrgentDefects == 0) && (d.monthDefects == 0)) {
return "<h4 style=\"text-align:center\"><span style=\"font-size:50px\">✔</span><br>No defects found</h4>"
} else {
return "<h4 style=\"text-align:center;font-size:15px;font-weight:bold;\">Urgent Defect(s): " + d.monthUrgentDefects + "<br>Total Defect(s): " + d.monthDefects + "</h4>";
}
})
defects.append("text")
.attr("x", 3)
.attr("y", 20)
.attr("font-family", "sans-serif")
.attr("fill", "black")
.attr("font-size", "15px")
.attr("font-weight", 700)
.text(function (d) {
var retStr = teamVal;
return retStr;
})
defects.append("text")
.attr("x", 3)
.attr("y", 40)
.attr("font-family", "sans-serif")
.attr("fill", "black")
.attr("font-size", "14px")
.text(function () {
return reformatMonthVal(monthVal);
})
})
};
function reformatMonthVal(monthVal) {;
return monthVal.replace(/[^a-z]/gi, "") + " " + monthVal.replace(/\D/g, "");
}
|
import React, { useState } from 'react';
export function CaraBuena() {
return <div style={{
border: '1px solid #F4D03F',
borderRadius: 100,
fontSize: '3rem',
width: 60,
height: 60,
backgroundColor: '#F4D03F',
margin: "10px 20px 10px 20px",
textAlign: "center"
}}>
<span>
:)
</span>
</div>
}
|
import React, { useState, useCallback, useEffect } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, ImageBackground, Alert, SafeAreaView, } from 'react-native';
import { Appbar, Button, TextInput, ActivityIndicator } from 'react-native-paper';
import { FancyAlert } from 'react-native-expo-fancy-alerts';
import { Icon } from 'react-native-elements'
import { ScrollView } from 'react-native-gesture-handler';
export default function Signup(props) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
//const [type, setType] = useState('');
const [name, setName] = useState('');
const [phone, setPhone] = useState('');
const [cnic, setCnic] = useState('');
const [error, setError] = useState(false);
const [statusType, setStatusType] = useState('');
const [clicked, setClicked] = useState(false)
const [visible, setVisible] = useState(true);
const [errMsg, setErrMsg] = useState('')
const toggleAlert = useCallback(() => {
setVisible(!visible);
}, [visible]);
useEffect(() => {
}, [statusType, errMsg, visible])
const ShowAlert = () => {
if (statusType == "error") {
return (
<View>
<FancyAlert
visible={visible}
icon={<View style={{
flex: 1,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'red',
borderRadius: 50,
width: '100%',
}}><Icon
reverse
name='x'
type='feather'
color="red"
size={20}
/>
</View>}
style={{ backgroundColor: 'white' }}
>
<Text style={{ marginTop: -16, marginBottom: 32, textAlign: "center", }}>{errMsg}</Text>
<Button
style={{ marginBottom: "5%", backgroundColor: "red" }}
onPress={toggleAlert}
mode="contained">
Close
</Button>
</FancyAlert>
</View>
)
}
else if (statusType == "success") {
return (
<View>
<FancyAlert
visible={visible}
icon={<View style={{
flex: 1,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'green',
borderRadius: 50,
width: '100%',
}}><Icon
reverse
name='check'
type='feather'
color="green"
size={20}
/>
</View>}
style={{ backgroundColor: 'white' }}
>
<Text style={{ marginTop: -16, marginBottom: 32, textAlign: "center", }}>{errMsg}</Text>
<Button
style={{ marginBottom: "5%", backgroundColor: "green" }}
onPress={() => {
props.navigation.replace('Login');
toggleAlert
}}
mode="contained">
Close
</Button>
</FancyAlert>
</View>
)
}
else {
return (
null
)
}
}
const errSet = (msg, type) => {
//console.log(msg, type)
setVisible(true)
setError(true)
setStatusType(type)
setErrMsg(msg)
ShowAlert()
}
/*
const createErrorAlert = (err) =>
Alert.alert(
"Error",
err,
[
{ text: "OK", onPress: () => console.log("OK Pressed") }
],
{ cancelable: false }
);
*/
function sendCredentials() {
setError(false)
if (!email) {
errSet("Email is required", "error")
}
else if (!password) {
errSet("Password is required", "error")
}
else if (!name) {
errSet("Name is required", "error")
}
else if (!phone || phone.length != 11) {
errSet("Enter valid phone number", "error")
}
else if (!cnic || cnic.length != 13) {
errSet("Enter valid CNIC", "error")
}
else {
setClicked(true)
setError(false)
fetch("http://192.168.43.145:3000/vendors/signup", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
name: name,
phone: phone,
cnic: cnic,
}),
})
.then(res => res.json())
.then(async (data) => {
//console.log(data)
try {
if (data.Error) {
setError(true);
console.log(data.Error)
if (data.Error.includes("E11000")) {
if (data.Error.includes("email"))
errSet(`Already an account exists with email: ${email}`, "error")
if (data.Error.includes("cnic"))
errSet(`Already an account exists with CNIC: ${cnic}`, "error")
}
}
else if (!data.Error) {
setError(false);
//console.log("Inside")
errSet("Signup successfull, Now login with your credentials", "success")
}
} catch (e) {
console.log("Error: ", e)
}
})
.catch((error) => {
console.error("Error" + error);
});
}
}
return (
<View style={styles.container}>
<ImageBackground source={require('../assets/bg-login-signup.png')} style={styles.im_bg}>
{error ?
<ShowAlert />
:
<></>
}
{(clicked && !error)
?
<View style={styles.container}>
<ShowAlert />
<ActivityIndicator size="large" color="#14213D" />
<Text style={{ marginTop: 20 }}>Validating the data...</Text>
</View>
:
<ScrollView contentContainerStyle={{ flexGrow: 1, justifyContent: 'center' }}>
<View style={{
borderRadius: 40,
backgroundColor: "#ededed",
marginLeft: "10%",
marginRight: "10%",
}}>
<Text style={{ fontSize: 28, textAlign: "center", marginTop: "8%", color: "#14213D" }}>
Signup as
</Text>
<Text style={{ fontSize: 30, fontWeight: "bold", textAlign: "center", marginBottom: "2%", color: "#14213D" }}>
Vendor
</Text>
<Text style={{ fontSize: 20, textAlign: "center", color: "grey" }}>
Want to signup as Customer?
</Text>
<TouchableOpacity>
<Text style={{ fontSize: 20, textAlign: "center", marginBottom: "6%", color: "grey", fontWeight: 'bold' }}
onPress={() => props.navigation.navigate("SignupCustomer")}
>
Click here
</Text>
</TouchableOpacity>
<TextInput
style={styles.textInput}
label='Email'
underlineColor="transparent"
placeholder="Enter your Email"
theme={{ colors: { primary: "#14213D" } }}
value={email}
onChangeText={text => setEmail(text)}
/>
<TextInput
style={styles.textInput}
label='Password'
underlineColor="transparent"
placeholder="Enter your Password"
secureTextEntry={true}
theme={{ colors: { primary: "#14213D" } }}
value={password}
onChangeText={text => setPassword(text)}
/>
<TextInput
style={styles.textInput}
label='Name'
underlineColor="transparent"
placeholder="Enter your Full Name"
theme={{ colors: { primary: "#14213D" } }}
value={name}
onChangeText={text => setName(text)}
/>
<TextInput
style={styles.textInput}
label='Phone Number'
underlineColor="transparent"
keyboardType='numeric'
maxLength={11}
placeholder="Enter your Mobile Number"
theme={{ colors: { primary: "#14213D" } }}
value={phone}
onChangeText={text => setPhone(text)}
/>
<TextInput
style={styles.textInput}
label='CNIC'
underlineColor="transparent"
keyboardType='numeric'
maxLength={13}
placeholder="Enter your CNIC"
theme={{ colors: { primary: "#14213D" } }}
value={cnic}
onChangeText={text => setCnic(text)}
/>
<Button style={styles.button}
onPress={sendCredentials}
mode="contained">
Sign Up
</Button>
<Text style={{ fontSize: 20, textAlign: "center", marginTop: "3%", color: "grey" }}
>Already have an account?</Text>
<TouchableOpacity>
<Text style={{ fontSize: 20, textAlign: "center", marginBottom: "8%", color: "grey", fontWeight: 'bold' }}
onPress={() => props.navigation.navigate("Login")}
>
Sign In
</Text>
</TouchableOpacity>
</View>
</ScrollView>
}
</ImageBackground>
</View>
);
}
const styles = StyleSheet.create({
avatar: {
alignItems: 'center',
justifyContent: 'center',
marginTop: 10
},
textInput: {
marginLeft: 15, marginRight: 15, marginBottom: 15,
borderTopStartRadius: 30, borderTopEndRadius: 30,
borderRadius: 30, overflow: 'hidden', height: 50,
backgroundColor: "#dedede"
},
button: {
marginLeft: 15, marginRight: 15, backgroundColor: "#FF9F00", borderRadius: 30
},
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
im_bg: {
width: '100%', height: '100%'
}
});
|
/* Common Exercise Functions */
// tick users howler.js - http://goldfirestudios.com/blog/104/howler.js-Modern-Web-Audio-Javascript-Library
var tick = new Howl({
urls: ['/media/audio/click03.ogg', '/media/audio/click03.mp3'],
autoplay: false
});
function playTick(){
tick.pos(.04);
tick.play();
}
function setGamesAreaHeight(){
var body_h = $('body').height();
var set_body_h = parseFloat(body_h*2/100);
var game_footer_h = $('body').find('.games-footer').height();
var set_h = body_h-game_footer_h;
var get_top_val = $('body').find('.games-inner-container').offset().top;
set_h = set_h-get_top_val;
set_h = set_h-10;
$('.games-inner-container').height(set_h);
$('.games-inner-container').find('.exercise-area').height(set_h);
}
setGamesAreaHeight();
$(window).resize(function(){
setGamesAreaHeight();
});
$.fn.disableSelection = function() {
return this
.attr('unselectable', 'on')
.css('user-select', 'none')
.on('selectstart', false);
};
function moveTextToDynamic(mainDiv, dynamicDiv)
{
$(mainDiv).show();
$(dynamicDiv).hide();
$('.games-inner-container').css('width',$(".games-inner-container").width());
var mWidth = $('.games-inner-container').width();
var mHeight = $(mainDiv).height();
$(mainDiv).css('width',mWidth+'px');
$(dynamicDiv).css('width',mWidth+'px');
$(dynamicDiv).css('height',mHeight+'px');
var fontsSelectedValue = 47;
if (mWidth < 1200)
fontsSelectedValue = 44;
if (mWidth < 460)
fontsSelectedValue = 20;
$(dynamicDiv).css('font-size',fontsSelectedValue+'px');
$(mainDiv).css('font-size',fontsSelectedValue+'px');
var totalWords = $(mainDiv).text().split(/\b\S+\b/g).length-1;
var split = new SplitText($(mainDiv),{type:"lines",linesClass:"line_++"});
var totalLines = split.lines.length;
$(dynamicDiv).html(split.lines)
$(mainDiv).html('');
return {
fontSize : fontsSelectedValue,
words : totalWords,
lines : totalLines
};
}
function centerMeFromMyParent(mParent, mChild, width)
{
$(mChild).css({position: 'absolute'});
$(mParent).css({position: 'relative'});
var parent = $(mParent);
var child = $(mChild);
if (width)
child.css({top: parent.height()/2 - child.height()/2 , left: parent.width()/2 - child.width()/2 });
child.css({top: parent.height()/2 - child.height()/2});
}
|
X.define("model.blogModel",function () {
var api = X.config.blog.api,
model = X.model.create("model.blogModel");
//删除某个文章
model.del = function(data, callback) {
var option = {
url: api.articleEdit + data.postId,
type: 'DELETE',
callback: callback
};
X.loadData(option)
};
//获取id文章数据
model.getIdArticle = function(data, callback) {
var option = {
url: api.articleEdit + data.postId,
type: 'GET',
callback: callback
};
X.loadData(option)
};
//保存/发布文章数据
model.postIdArticle = function(data, callback) {
var option = {
url: api.articleEdit,
type: 'POST',
data: data,
callback: callback
};
X.loadData(option)
};
//更新文章数据
model.putIdArticle = function(data, callback) {
var option = {
url: api.articleEdit,
type: 'PUT',
data: data,
callback: callback
};
X.loadData(option)
};
model.renderStaticPage = function(id) {
$.ajax({
url: X.config.PATH_FILE.path.weInTdUrl + 'blog/create/' + id + '.html',
dataType: 'jsonp',
type: 'GET'
})
}
model.statusconst = {
postStatus: {
SAVE: {key: "0", text: "未发布"},
PUBLISH: {key: "1", text: "已发布"}
}
};
return model;
});
|
/**
* Created by rhett on 5/20/14.
*/
angular.module('2048Game', ['cfp.hotkeys']);
|
import React, { Component } from 'react';
import Board from './screens/Board'
import { Provider } from 'react-redux'
import store from './redux/store/store.js'
import { BrowserRouter as Router, Route,Redirect,Switch} from 'react-router-dom';
import './style/default.less'
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div>
<Switch>
<Route path="/home" component={Board}/>
<Redirect path="/" to={{pathname: '/home'}} />
</Switch>
</div>
</Router>
</Provider>
);
}
}
export default App;
|
import React from 'react';
import {StyleSheet, Text, View, Slider, ScrollView, Image} from 'react-native';
import { Container, Card, CardItem, Header, Left, Body, Thumbnail, Right, Button, Icon, Title, Segment, Content, Item} from 'native-base';
export default class Profile extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 50,
};
}
change(value) {
this.setState(() => {
return {
value: parseFloat(value),
};
});
}
render() {
const {value} = this.state;
return (
<ScrollView style={{flex:1}}>
<View style={{flex:1, flexDirection:'column', justifyContent: 'center'}}>
<Container>
<Content>
<Card transparent style={{flex:1,flexDirection: 'column', marginTop: 30}}>
<CardItem>
<Left>
<Thumbnail source={require('../img/dude.jpg')}/>
<Body style={{flex:1, flexDirection: 'column', justifyContent: 'space-evenly', marginLeft: 40}}>
<Text>Hamzah</Text>
<Text note >25 Years Old</Text>
<View style={{flex:1, flexDirection:'row'}}>
<Icon name="pin" style={{marginRight: 3}}/>
<Text note >Gombak,</Text>
<Text note > Selangor, </Text>
<Text note >Malaysia</Text>
</View>
</Body>
</Left>
</CardItem>
</Card>
<Card style={{flex:1,flexDirection: 'column', margin: 8}}>
<CardItem header>
<Text style={{alignSelf: 'center', padding: 2}}>Portfolio</Text>
</CardItem>
<CardItem cardBody style={{flex:1, flexDirection: 'row', padding: 10, margin: 5, alignContent: 'space-around', justifyContent: 'space-between', alignItems:'center', marginLeft: 5}}>
<Image source={require('../img/dude.jpg')} style={{padding: 10, width: 60, height: 60}}/>
<Image source={require('../img/dude.jpg')} style={{padding: 10, width: 60, height: 60}}/>
<Image source={require('../img/dude.jpg')} style={{padding: 10, width: 60, height: 60}}/>
<Image source={require('../img/dude.jpg')} style={{padding: 10, width: 60, height: 60}}/>
<Image source={require('../img/dude.jpg')} style={{padding: 10, width: 60, height: 60}}/>
</CardItem>
</Card>
<Card style={{marginTop: 3}}>
<CardItem header>
<Text style={{alignSelf:'center'}}>Current Availability</Text>
</CardItem>
<CardItem cardBody>
<Left>
<Thumbnail source={require('../img/dude.jpg')}/>
</Left>
<Body>
<Text>Monica</Text>
<Text note numberOfLines={1}>Its time to build a difference . .</Text>
<Icon name='calendar'/><Text note style={{flex:1, flexDirection: 'row',justifyContent:'space-evenly'}}></Text>
</Body>
</CardItem>
<CardItem>
<Right>
<Icon name="ios-arrow-forward"/>
</Right>
</CardItem>
</Card>
</Content>
</Container>
<Container>
<Text style={Style.slider}>{String(value)}</Text>
<Slider
step={1}
maximumValue={100}
onValueChange={this.change.bind(this)}
value={value}
/>
<Text style={Style.slider}>{String(value)}</Text>
<Left><Text>Job Location</Text></Left>
<Slider
step={1}
maximumValue={100}
onValueChange={this.change.bind(this)}
value={value}
/>
</Container>
</View>
</ScrollView>
);
}
}
const Style = StyleSheet.create({
slider:{
fontSize: 20,
width: 50,
textAlign: 'left'
}
})
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Button, Typography, InputText } from "components";
import { CopyText } from '../../copy';
import { connect } from "react-redux";
import { getAppCustomization } from "../../lib/helpers";
import loading from 'assets/loading-circle.gif';
import "./index.css";
class LoginForm extends Component {
static propTypes = {
onSubmit: PropTypes.func.isRequired,
error: PropTypes.number,
has2FA: PropTypes.bool,
error: PropTypes.string,
onClose: PropTypes.func
};
static defaultProps = {
error: null,
has2FA: false
};
state = {
username: "",
password: "",
token: "",
isLoading: false
};
handleSubmit = async event => {
this.setState({...this.state, isLoading : true });
event.preventDefault();
const { onSubmit } = this.props;
if (onSubmit && this.formIsValid()) {
await onSubmit(this.state);
}
this.setState({...this.state, isLoading : false});
};
resetPasswordClick = () => {
const { onClose, onHandleResetPassword } = this.props;
onClose();
onHandleResetPassword({ mode: "reset" });
};
on2FATokenChange = event => {
this.setState({ token: event.target.value });
};
onUsernameChange = event => {
this.setState({ username: event.target.value });
};
onPasswordChange = event => {
this.setState({ password: event.target.value });
};
onUserChange = event => {
this.setState({ username_or_email: event.target.value });
};
formIsValid = () => {
const { username, password, token } = this.state;
const { has2FA } = this.props;
return (username !== "" && password !== "" && !has2FA) || (token.length === 6 && has2FA);
};
renderStageOne() {
const { username, password } = this.state;
const { has2FA } = this.props;
const {ln} = this.props;
const copy = CopyText.loginFormIndex[ln];
return (
<div styleName={has2FA ? "disabled" : null}>
<div styleName="username">
<InputText
name="username"
placeholder= {copy.INDEX.INPUT_TEXT.LABEL[0]}
onChange={this.onUsernameChange}
value={username}
disabled={has2FA}
/>
</div>
<InputText
name="password"
placeholder= {copy.INDEX.INPUT_TEXT.LABEL[1]}
type="password"
onChange={this.onPasswordChange}
value={password}
disabled={has2FA}
/>
</div>
);
}
renderStageTwo() {
const { has2FA } = this.props;
const { token } = this.state;
const {ln} = this.props;
const copy = CopyText.loginFormIndex[ln];
if (!has2FA) { return null };
return (
<div>
<div styleName="token2FA">
<InputText
name="token2fa"
onChange={this.on2FATokenChange}
value={token}
maxlength="6"
placeholder={`${copy.INDEX.INPUT_TEXT.LABEL[2]} - ${copy.INDEX.INPUT_TEXT.PLACEHOLDER[0]}`}
/>
</div>
<div styleName="token2FA-info">
<Typography color={'grey'} variant={'small-body'}>
{copy.INDEX.TYPOGRAPHY.TEXT[0]}
</Typography>
</div>
</div>
);
}
renderError(error) {
const {ln} = this.props;
const copy = CopyText.loginFormIndex[ln];
return (
<div styleName="error">
{error && error !== 37 ? (
<Typography color="red" variant="small-body" weight="semi-bold">
{error === 4 || error === 55
? copy.INDEX.TYPOGRAPHY.TEXT[1]
:
error === 36
? copy.INDEX.TYPOGRAPHY.TEXT[2]
: copy.INDEX.TYPOGRAPHY.TEXT[3]}
</Typography>
) : null}
</div>
)
}
render() {
const { error, has2FA } = this.props;
const { isLoading } = this.state;
const {ln} = this.props;
const copy = CopyText.loginFormIndex[ln];
const { skin } = getAppCustomization();
return (
<form onSubmit={this.handleSubmit}>
{this.renderStageOne()}
{has2FA ? this.renderStageTwo() : null}
<div styleName="error">
{error && error !== 37 ? (
<Typography color="red" variant="small-body" weight="semi-bold">
{error === 4
? copy.INDEX.TYPOGRAPHY.TEXT[1]
:
error === 36
? copy.INDEX.TYPOGRAPHY.TEXT[2]
: copy.INDEX.TYPOGRAPHY.TEXT[3]}
</Typography>
) : null}
</div>
<div styleName="button">
<Button
size="medium"
theme="primary"
disabled={!this.formIsValid() || isLoading}
type="submit"
>
{isLoading
?
<img src={loading} />
:
<Typography color={skin.skin_type == "digital" ? 'secondary' : 'fixedwhite'}>{copy.INDEX.TYPOGRAPHY.TEXT[4]}</Typography>
}
</Button>
</div>
<div styleName="forgot">
<a href="#" onClick={this.resetPasswordClick}>
<Typography color="casper" variant="small-body">
{copy.INDEX.TYPOGRAPHY.TEXT[5]}
</Typography>
</a>
</div>
</form>
);
}
}
function mapStateToProps(state){
return {
profile : state.profile,
ln: state.language
};
}
export default connect(mapStateToProps)(LoginForm);
|
import { RESPONSES_GET, RESPONSES_RESULT, RESPONSE_SEND } from '../constants/ActionTypes';
import ResponseAPI from '../api/responses'
import { fetchNext } from './next';
const api = new ResponseAPI();
function getResponses(data) {
return {
type: RESPONSES_GET
};
};
function receiveResponses(responses) {
return {
type: RESPONSES_RESULT,
responses
};
};
export function fetchAll() {
return function(dispatch) {
dispatch(getResponses());
api.getAllResponses( inkblots => {
dispatch(receiveResponses({inkblots}));
});
};
};
function sendResponse(data) {
return {
type: RESPONSE_SEND,
data
};
};
export function saveResponse(response) {
return function(dispatch) {
dispatch(sendResponse(response));
api.saveResponse(response, () => {
dispatch(fetchNext());
dispatch(fetchAll());
});
};
};
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 6);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tile_js__ = __webpack_require__(2);
// purpose of this class:
// set of method created and use through all the different classes of the game
const Util = {
merge: (left, right) => {
const merged = [];
while (left.length > 0 && right.length > 0) {
let nextItem = (left[0] < right[0]) ? left.shift() : right.shift();
merged.push(nextItem);
}
return merged.concat(left, right);
},
mergeSort: (arr) => {
if (arr.length < 2) {
return arr;
} else {
const middle = Math.floor(arr.length / 2);
const left = Util.mergeSort(arr.slice(0, middle));
const right = Util.mergeSort(arr.slice(middle));
return Util.merge(left, right);
}
},
uniq: (arr) => {
var hash = {}, uniq = [];
for ( let i = 0; i < arr.length; i++ ) {
if ( !hash.hasOwnProperty(arr[i]) ) {
hash[ arr[i] ] = true;
uniq.push(arr[i]);
}
}
return uniq;
},
similar: (arr1, arr2) => {
arr1.forEach((val, index)=> {
if(arr2[index] !== val){
return false;
}
})
return true;
},
transpose: (grid) => {
const newGrid = [];
grid.forEach((line, rowIdx) => {
let newRow = [];
line.forEach((val, colIdx)=> {
newRow.push(grid[colIdx][rowIdx])
})
newGrid.push(newRow);
})
return newGrid;
},
flatten: (arr) => {
let result = [];
arr.forEach( el => {
if( el instanceof Array){
result = result.concat(Util.flatten(el))
} else {
result.push(el)
}
})
return result;
},
deepDup: (grid) => {
let newGrid = [];
grid.forEach(line => {
let newLine = [];
line.forEach(tile => {
let val = tile.val;
let blocked = tile. blocked;
let newTile = new __WEBPACK_IMPORTED_MODULE_0__tile_js__["a" /* default */](val, blocked);
newLine.push(newTile);
})
newGrid.push(newLine);
})
return newGrid;
},
randomPos: (val) => {
const row = Math.floor(val * Math.random());
const col = Math.floor(val * Math.random());
return [row, col];
},
deleteVal: (arr, val) => {
let index = arr.indexOf(val);
if(index !== -1){
arr.splice(index, 1);
}
},
shuffle: (arr) => {
let count = arr.length;
while (count > 0) {
let index = Math.floor(Math.random() * count);
count--;
let temp = arr[count];
arr[count] = arr[index];
arr[index] = temp;
}
return arr;
},
update: (positions1, positions2) => {
let result = [];
let hash = {};
positions2.forEach(pos2 => {
hash[`${pos2}`] = true;
});
positions1.forEach(pos1 => {
if(!hash[`${pos1}`]){
result.push(pos1);
}
});
return result;
}
}
let positions1 = [[0,0], [1,2]];
/* harmony default export */ __webpack_exports__["a"] = (Util);
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__grid_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__util_js__ = __webpack_require__(0);
// purpose of this class:
// 1) Build a grid ( take an existing grid or build a new one is none)
// 2) save difficulty (number of tile with a value of 0)
// and the inputsVal( hash: {1: 2, 3: 4 etc..})
// 2) Provide a solved method to check if the grid is solved
// 3) update the grid according to correct input => val is a number and a num between 0 and 9
class Board {
constructor(difficulty, grid = null){
this.difficulty = difficulty;
this.boardGrid = new __WEBPACK_IMPORTED_MODULE_0__grid_js__["a" /* default */](difficulty, grid);
this.inputsVal = this.boardGrid.inputsVal;
}
getValues(){
return this.boardGrid.getValues();
}
updateVal(pos, val){
let tile = this.getTile(pos);
if(!tile.blocked && this.valid(val)){
tile.val = val;
}
}
getTile(pos){
let x = pos[0];
let y = pos[1];
return this.boardGrid.grid[x][y];
}
valid(val){
return Number.isInteger(val) && val >= 0 && val <= 9;
}
// method to divide the grid values into squares
getAllSquares(){
let squares = [];
[0, 3, 6].forEach((indexCol) => {
this.getThreeSquaresIndexCol(indexCol).forEach((square) => {
squares.push(square);
})
})
return squares;
}
getThreeSquaresIndexCol(indexCol){
let squares = [];
let square = [];
this.boardGrid.getValues().forEach((line, index)=> {
square.push( line.slice(indexCol, indexCol+3));
if((index + 1) % 3 === 0){
squares.push(square);
square = [];
}
})
return squares;
}
//methods to check if the board is solved!
solved(){
return this.checkLinesColsBoard() && this.checkSquares();
}
checkSquares(){
let result = true;
this.getAllSquares().forEach(square => {
if (!this.checkSquare(square)){
result = false;
}
})
return result;
}
checkSquare(square){
let line = __WEBPACK_IMPORTED_MODULE_1__util_js__["a" /* default */].flatten(square);
return this.check(line);
}
checkLinesColsBoard(){
let grid = this.boardGrid.getValues();
let transposeGrid = __WEBPACK_IMPORTED_MODULE_1__util_js__["a" /* default */].transpose(grid);
return this.checkLines(grid) && this.checkLines(transposeGrid);
}
check(line){
const b = __WEBPACK_IMPORTED_MODULE_1__util_js__["a" /* default */].mergeSort(line);
if (b[0] === 0) {
return false;
}
return __WEBPACK_IMPORTED_MODULE_1__util_js__["a" /* default */].similar(b , [1,2,3,4,5,6,7,8,9]);
}
checkLines(grid1){
grid1.forEach((line) => {
if (!this.check(line)) {
return false;
}
})
return true;
}
}
/* harmony default export */ __webpack_exports__["a"] = (Board);
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// purpose of this class:
// Well it s a tile object which hold three characteristics:
// 1) tile is blocked (meaning we can t change the value of the tile)
// 2) the value of the tile
// 3) possible values of this tile according to the grid (this.marks)
class Tile {
constructor(val, blocked = true){
this.val = val;
this.blocked = val === null ? false : blocked ;
this.marks = [];
}
}
/* harmony default export */ __webpack_exports__["a"] = (Tile);
/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__sudoku_select_level_view_js__ = __webpack_require__(9);
class SudokuGridView extends __WEBPACK_IMPORTED_MODULE_0__sudoku_select_level_view_js__["a" /* default */] {
constructor(game){
super(game);
this.buildGrid();
this.$inputs = $(".sudoku-grid input[type= text]");
this.$inputs.change(this.handleChange.bind(this));
// method coming from SudokuHintView class
this.$inputs.on("click", this.handleSelect.bind(this));
//
}
// method to build a new Grid (ul => lis).
buildGrid(){
const $sudokuGrid = $(".sudoku-grid");
this.game.board.getValues().forEach( (line, row) => {
let $ul = $("<ul></ul>");
this.buildLis(line, $ul, row);
$sudokuGrid.append($ul);
});
}
buildLis(line, ul, row){
line.forEach( (value, col)=> {
let $li = $("<li></li>");
$li.addClass(`li-${row}-${col} sudoku-grid-tile`);
if(value !==0 ){
$li.append(`${value}`);
$li.addClass("tile-blocked");
} else{
let $input = $("<input></input>");
$input.attr({type:"text", value:"", maxlength:"1" });
$li.append($input);
}
ul.append($li);
})
}
handleChange(event){
let $input = $(event.target);
let className = $input.parent().attr("class");
this.checkInput($input.val());
let pos = this.getPos(className);
let previousVal = this.game.board.getTile(pos).val;
let value = parseInt($input.val());
this.updateInputsVal(previousVal, value);
value = value !== value ? 0 : value;
this.game.board.updateVal(pos, value);
// method coming from SudokuHintView class
this.updateHint();
//
this.game.board.solved() ? this.printWinMessage() : false
}
getPos(className){
let x = parseInt(className[3]);
let y = parseInt(className[5]);
return [x, y];
}
updateInputsVal(previousVal, value){
if( value !== value ){
this.game.inputsVal[previousVal] += 1;
} else if(this.game.board.valid(previousVal) && this.game.board.valid(value)){
this.game.inputsVal[previousVal] += 1;
this.game.inputsVal[value] -= 1;
}else if(this.game.board.valid(value)){
this.game.inputsVal[value] -= 1;
}
}
checkInput(val){
let correctValues = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
if( val === ""){
return
} else if( !correctValues.includes(val) ){
alert("Please, enter a value between 0 and 9.");
}
}
printWinMessage(){
alert("Well played! You finished the grid!");
}
// methods to render a new BoardGrid from a new game created according to the level.
render(grid){
grid.forEach((line, row)=> {
this.updateLis(line,row);
});
}
updateLis(line, row){
line.forEach((value, col) => {
let $li = $(`.li-${row}-${col}`);
$li.removeClass("tile-blocked tile-selected");
$li.html('');
if(value !== 0 ){
$li.html(`${value}`);
$li.addClass("tile-blocked");
} else{
let $input = $("<input></input>");
$input.attr({type:"text", value: "", maxlength: "1" });
$input.change(this.handleChange.bind(this));
// method coming from SudokuHintView class
$input.on("click", this.handleSelect.bind(this));
//
$li.append($input);
}
})
}
}
/* harmony default export */ __webpack_exports__["a"] = (SudokuGridView);
/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__board_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__solver_board_solver_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__solver_sudoku_solver_js__ = __webpack_require__(13);
// purpose of this class:
// 1) Get one board
// 2) Get the solution of the board
// 3) save the inputsVal to display the hint (ex: {1: 3, 2:0, 3: 2})
class Sudoku {
constructor(difficulty = 15){
this.board = new __WEBPACK_IMPORTED_MODULE_0__board_js__["a" /* default */](difficulty);
this.inputsVal = this.board.inputsVal;
const boardSolver = new __WEBPACK_IMPORTED_MODULE_1__solver_board_solver_js__["a" /* default */](this.board);
this.solution = new __WEBPACK_IMPORTED_MODULE_2__solver_sudoku_solver_js__["a" /* default */](boardSolver).solve();
}
}
/* harmony default export */ __webpack_exports__["a"] = (Sudoku);
/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__game_util_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__game_board_js__ = __webpack_require__(1);
// purpose of this class:
// 1) take the existing board and create a new Board with a deep copy of the previous grid
// 2) update the board by calculating the possible values for each tile of value 0(the marks):
// loop through each available positions and update the tile with possible values
// 3) update the board if there is a unique possible value on one tile
// (tile is updated and available positions as well)
// 4) Check after update if the board has a solution through (this.solvable)
class BoardSolver{
constructor(board, availablePositions = null){
this.availablePositions = availablePositions === null ? board.boardGrid.availablePosistions : availablePositions;
this.board = new __WEBPACK_IMPORTED_MODULE_1__game_board_js__["a" /* default */]( board.difficulty, __WEBPACK_IMPORTED_MODULE_0__game_util_js__["a" /* default */].deepDup(board.boardGrid.grid));
this.solvable = true;
this.updateDatas();
}
updateDatas(){
this.lines = this.board.boardGrid.getValues();
this.columns = __WEBPACK_IMPORTED_MODULE_0__game_util_js__["a" /* default */].transpose(this.board.boardGrid.getValues());
this.squares = this.board.getAllSquares();
}
updateTile(pos, val){
this.board.updateVal(pos, val);
this.updateDatas();
this.updateMarks();
}
solved(){
return this.board.solved();
}
updateMarks(){
let positions = [];
let update = false;
for(let index=0; index < this.availablePositions.length; index++){
let pos = this.availablePositions[index];
let tile = this.board.getTile(pos);
tile.marks = this.possibleMarks(pos);
if(tile.marks.length === 0){
this.solvable = false;
break;
} else if (tile.marks.length === 1){
this.board.updateVal(pos, tile.marks.pop());
positions.push(pos);
update = true;
}
}
this.updateAvailablePositions(update, positions);
}
updateAvailablePositions(update, positions){
if(update){
this.availablePositions = __WEBPACK_IMPORTED_MODULE_0__game_util_js__["a" /* default */].update(this.availablePositions, positions);
}
}
possibleMarks(pos){
let values = this.getLine(pos).concat(this.getCol(pos)).concat(this.getSquare(pos));
let uniqValues = __WEBPACK_IMPORTED_MODULE_0__game_util_js__["a" /* default */].uniq(values);
let result = [];
[1,2,3,4,5,6,7,8,9].forEach(val => {
if(!uniqValues.includes(val)){
result.push(val)
}
})
return result;
}
getLine(pos){
let x = pos[0];
return this.lines[x];
}
getCol(pos){
let y = pos[1];
return this.columns[y];
}
getSquare(pos){
let index = this.getIndexSquare(pos);
return __WEBPACK_IMPORTED_MODULE_0__game_util_js__["a" /* default */].flatten(this.squares[index]);
}
getLineIndexSquare(pos){
let line = pos[0];
switch(line){
case 0:
case 1:
case 2:
return [0,3,6];
case 3:
case 4:
case 5:
return [1,4,7];
case 6:
case 7:
case 8:
return [2,5,8];
}
}
getIndexSquare(pos){
let col = pos[1];
let indexes = this.getLineIndexSquare(pos);
switch(col){
case 0:
case 1:
case 2:
return indexes[0];
case 3:
case 4:
case 5:
return indexes[1];
case 6:
case 7:
case 8:
return indexes[2];
}
}
}
/* harmony default export */ __webpack_exports__["a"] = (BoardSolver);
/***/ }),
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__view_sudoku_view_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__game_sudoku_js__ = __webpack_require__(4);
$(()=> {
let game = new __WEBPACK_IMPORTED_MODULE_1__game_sudoku_js__["a" /* default */]();
new __WEBPACK_IMPORTED_MODULE_0__view_sudoku_view_js__["a" /* default */](game);
});
/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__sudoku_hint_view_js__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__sudoku_grid_view_js__ = __webpack_require__(3);
// chain inheritance explanations:
// 1) SudokuHintView extends from SudokuGridView
// 2) SudokuGridView extends from SudokuSelectLevelView
// 3) SudokuSelectLevelView extends from SudokuCalculateSolutionView
class SudokuView {
constructor(game){
this.SudokuHintView = new __WEBPACK_IMPORTED_MODULE_0__sudoku_hint_view_js__["a" /* default */](game);
}
}
/* harmony default export */ __webpack_exports__["a"] = (SudokuView);
/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__sudoku_grid_view_js__ = __webpack_require__(3);
class SudokuHintView extends __WEBPACK_IMPORTED_MODULE_0__sudoku_grid_view_js__["a" /* default */] {
constructor(game){
super(game);
this.$displayHint = $(".display-hint");
this.$displayHint.on("click", this.displayHint.bind(this));
}
updateHint(){
const check = $(".display-hint").children().html();
if(check === "Hide Hint"){
let $ul = $(".hint");
$ul.remove();
this.buildHint();
}
}
buildHint(){
const $sudokuGrid = $(".sudoku-grid");
let $ul = $("<ul></ul>");
$ul.addClass("hint");
for(let i = 1; i < 10; i++){
let $li = $("<li></li>");
$li.addClass("sudoku-grid-tile");
let num = this.game.inputsVal[i];
$li.html(`num${i} ${num}`)
$ul.append($li);
}
$sudokuGrid.append($ul);
}
displayHint(event){
const $a = $(event.currentTarget).children();
this.handleHint($a.html());
if($a.html() === "Display Hint"){
$a.html("Hide Hint");
} else {
$a.html("Display Hint");
}
}
handleHint(value){
if(value === "Display Hint"){
this.buildHint();
this.buildCheckValuesButton();
} else {
let $ul = $(".hint");
let $button =$(".check-values");
$button.remove();
$ul.remove()
}
}
// check value button methods:
// ( update the backgoung color tile in red if false input value)
buildCheckValuesButton(){
const $footer = $(".footer");
let $button = $("<button></button>")
$button.html("Check values");
$button.addClass("check-values");
$button.on("click", this.checkValues.bind(this));
$footer.append($button);
}
checkValues(event){
this.updateConflictValues();
setTimeout(function(){
let $liConflict = $(".conflict-value");
$liConflict.removeClass("conflict-value");
}, 3000);
}
updateConflictValues(){
this.game.solution.forEach((line, row)=>{
line.forEach((value, col)=> {
let pos = [row, col];
let boardVal= this.game.board.getTile(pos).val;
if( boardVal !== 0 && boardVal !== value ){
let $li = $(`.li-${row}-${col}`);
$li.addClass("conflict-value");
}
});
});
}
//method to update tile color backgroung (green) when an input is selected
// buildSelectTileButton(){
// let $button = $("<button> </button>");
// $button.html("Viewer helper");
// $button.addClass("viewer-helper");
// $button.on("click", () => {
// let allInputs = $(":input");
// allInputs.on("click", this.handleSelect.bind(this)) ;
// });
// const $footer = $(".footer");
// $footer.append($button);
// }
handleSelect(event){
this.removeSelectedLis();
const $li = $(event.currentTarget).parent();
const col = $li.attr("class")[5];
const $ul = $li.parent();
const $liLines = $ul.children();
$liLines.addClass("tile-selected");
for(let index=0; index < 9; index++){
const $li = $(".sudoku-grid").find(`.li-${index}-${col}`)
$li.addClass("tile-selected");
}
}
removeSelectedLis(){
const $selectedLi = $(".tile-selected");
if($selectedLi.length !== 0){
$selectedLi.removeClass("tile-selected");
}
}
}
/* harmony default export */ __webpack_exports__["a"] = (SudokuHintView);
/***/ }),
/* 9 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__sudoku_calculate_solution_view_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__game_sudoku_js__ = __webpack_require__(4);
class SudokuSelectLevelView extends __WEBPACK_IMPORTED_MODULE_0__sudoku_calculate_solution_view_js__["a" /* default */] {
constructor(game){
super(game)
this.$headerLevel = $(".header-level");
this.$headerLevel.on("click", "li", this.selectLevel.bind(this));
}
// select level and create a new game event method:
selectLevel(event){
const content = $(event.currentTarget).text();
switch(content){
case "Super Easy":
this.game = new __WEBPACK_IMPORTED_MODULE_1__game_sudoku_js__["a" /* default */](15);
break;
case "Easy":
this.game = new __WEBPACK_IMPORTED_MODULE_1__game_sudoku_js__["a" /* default */](25);
break;
case "Medium":
this.game = new __WEBPACK_IMPORTED_MODULE_1__game_sudoku_js__["a" /* default */](35);
break;
case "Hard":
this.game = new __WEBPACK_IMPORTED_MODULE_1__game_sudoku_js__["a" /* default */](45);
break;
case "Super Hard":
this.game = new __WEBPACK_IMPORTED_MODULE_1__game_sudoku_js__["a" /* default */](55);
break;
case "Nightmare":
this.game = new __WEBPACK_IMPORTED_MODULE_1__game_sudoku_js__["a" /* default */](65);
break;
case "Demo solver":
this.game = new __WEBPACK_IMPORTED_MODULE_1__game_sudoku_js__["a" /* default */](77);
break;
}
this.cleanAfterSelectLevel(event);
// render() comes from SudokuGridView class.
this.render(this.game.board.getValues());
//
}
cleanAfterSelectLevel(event){
const $ulHeaderLevel = $(event.currentTarget).parent();
$ulHeaderLevel.addClass("no-display");
this.cleanNoDisplayHeaderLevel();
this.cleanHint()
}
cleanNoDisplayHeaderLevel(){
setTimeout(function(){
let $ul = $(".no-display");
$ul.removeClass("no-display");
}, 200);
}
cleanHint(){
let $ulHint = $(".hint");
let $button =$(".check-values");
$button.remove();
$ulHint.remove();
let $li = $(".display-hint");
$li.children().html("Display Hint");
}
}
/* harmony default export */ __webpack_exports__["a"] = (SudokuSelectLevelView);
/***/ }),
/* 10 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
class SudokuCalculateSolutionView {
constructor(game){
this.game = game;
this.$calculateSolution = $(".calculate-solution");
this.$calculateSolution.on("click", this.calculateSolution.bind(this));
}
// calculateSolution of the grid event method:
calculateSolution(){
// render() comes from SudokuGridView class.
this.render(this.game.solution);
}
}
/* harmony default export */ __webpack_exports__["a"] = (SudokuCalculateSolutionView);
/***/ }),
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__existing_sudoku_solved_sudokus_js__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__existing_sudoku_solved_sudokus_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__existing_sudoku_solved_sudokus_js__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__tile_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__util_js__ = __webpack_require__(0);
// Purpose of this class:
// 1) Select a grid solved ( grid form: "1233434534...") if none provided
// 2) Build tile: ( grid form: [Tile1, Tile2, etc...])
// 3) change grid form to get lines (grid form: [[line1], [line2], etc...])
// 4) Insert inputsVal (which is a tile of value 0) according to
// the number of inputs we want( which define the difficulty of the game)
// then save the previous val to display the hint (this.inputsVal = {1: 2, 3:0, 7:3 etc...})
// At this step: we also save the available positions
// (which are the positions of the tile of value 0)
// 5) Provide a getValues() to get the grid form: [[1,3,4,..], [9,4,3, ...], ...]
class Grid {
constructor(difficulty, grid = null){
if(grid !== null){
this.grid = grid;
} else {
this.availablePosistions = [];
this.inputsVal = {
"1": 0,
"2": 0,
"3": 0,
"4": 0,
"5": 0,
"6": 0,
"7": 0,
"8": 0,
"9": 0
};
this.grid = this.buildOneLineGrid();
this.grid = this.getLines();
this.insertInputTile(difficulty);
}
}
randomIndex(val){
return Math.floor(val * Math.random());
}
buildOneLineGrid(){
const index = this.randomIndex(200);
let gridString = __WEBPACK_IMPORTED_MODULE_0__existing_sudoku_solved_sudokus_js___default.a[index];
let gridTile = [];
gridString.split("").forEach((string) => {
let val = parseInt(string);
let newTile = new __WEBPACK_IMPORTED_MODULE_1__tile_js__["a" /* default */](val);
gridTile.push(newTile);
});
return gridTile;
}
// set the difficulty of the game
insertInputTile(number){
let positions = this.allPositions();
let inputPos = []
for(let val = 0; val < number; val++){
let pos = positions.pop();
let currentVal = this.grid[pos[0]][pos[1]].val;
this.inputsVal[currentVal] += 1;
this.grid[pos[0]][pos[1]] = new __WEBPACK_IMPORTED_MODULE_1__tile_js__["a" /* default */](0, false)
inputPos.push(pos)
}
this.availablePosistions = inputPos;
}
getValues(){
let gridValues = [];
this.grid.forEach( line => {
let newLine = []
line.forEach((tile) => {
newLine.push(tile.val);
})
gridValues.push(newLine);
});
return gridValues;
}
getLines(){
let index = 0;
let lineGrid = [];
for(let i =0; i< 9; i++){
lineGrid.push(this.grid.slice(index, index+9))
index += 9
}
return lineGrid;
}
// provide a set of all positions of the grid
allPositions(){
let positions = [];
for(let row=0; row< 9; row++){
for(let col= 0; col<9; col++){
positions.push([row, col])
}
}
return __WEBPACK_IMPORTED_MODULE_2__util_js__["a" /* default */].shuffle(positions);
}
}
/* harmony default export */ __webpack_exports__["a"] = (Grid);
/***/ }),
/* 12 */
/***/ (function(module, exports) {
const solvedSudokus = ["123456789547819362968273154219645873684732591375198426451967238792381645836524917",
"123456789478192536956873241381245967547369128269781354794528613835617492612934875",
"123456789657938214849721536318279645275164398496583127581692473734815962962347851",
"123456789596837214847192635735281946684379152912645378451963827379528461268714593",
"123456789468973125795821436542739618839612547671584392284167953317295864956348271",
"123456789947381625586927431672819543859634172314275896495762318768193254231548967",
"123456789685719243479823651854631927931247865267985134798364512542198376316572498",
"123456789869732145574189623395274816781563294642891537217945368938627451456318972",
"123456789457893621689127534261978453895234167734615892948762315572381946316549278",
"123456789469718235857932416531624897274893651698175324312567948785349162946281573",
"123456789769182435584937162918265347246379851357814296472598613891623574635741928",
"123456789679832154845179326531697248984213567267548913712364895498725631356981472",
"123456789649871235857329146962734851375618492418592673736185924281943567594267318",
"123456789984372516765891324347589162816234957259617438632745891498123675571968243",
"123456789864179523957823614539761842641982375782345196318694257475238961296517438",
"123456789586279431794381625451792863962813547837564192375628914649137258218945376",
"123456789458937261796812435287594613941673852635281974374169528562348197819725346",
"123456789687319425549287613365142897298763154714895236952671348471938562836524971",
"123456789568279431794318256487195623912683547356742918875921364239864175641537892",
"123456789864793152579218463248971635795632841316584297637825914981347526452169378",
"123456789684379215579128346435892167812637594796541832267983451948215673351764928",
"123456789756983421849217653687532194234891576915674832568349217491725368372168945",
"123456789576981234984723615741238956865149372392567148657394821219875463438612597",
"123456789586917342497283165875149623312865974964732851258691437631574298749328516",
"123456789894217356567389241736928415459631827281574963672895134315742698948163572",
"123456789876923514459781632265349871918672345734815926647298153592137468381564297",
"123456789695278431847391652719685243532914867486723915371849526254167398968532174",
"123456789496782351785391426867149235351627894249835617938564172514273968672918543",
"123456789485179362769823415846791253391542678257638941672915834914387526538264197",
"123456789569783142784291635412369578958127463376548291841635927697812354235974816",
"123456789694178523857329146471962358536784912289531674912645837745893261368217495",
"123456789946728315785139462834697251269514837571382946658273194497861523312945678",
"123456789847921365659873142435198627918267453762345918296534871371682594584719236",
"123456789659187432874923615961248573532671894487395126795862341346719258218534967",
"123456789794283516586971324672198453941635278835742691267319845418567932359824167",
"123456789458379162976821534761542398892137645534968217389715426247683951615294873",
"123456789657189324894237165519623847238741596476895213345912678781564932962378451",
"123456789798123465546978321365789142472531896819264537281395674934617258657842913",
"123456789584937261679821534496375812851642397237189456948763125712598643365214978",
"123456789965378214784129356692837541478591632351264897549682173237915468816743925",
"123456789846179235795382164362598417451723896987641352578914623234865971619237548",
"123456789678392541945187623786243915419765832352918467591634278867521394234879156",
"123456789574981623896327145945172836732869451681534297219645378458713962367298514",
"123456789685917324947832516534298671862371495791564238476129853259683147318745962",
"123456789576819243948732651659378124234691875781524936862145397417983562395267418",
"123456789574983162869217435987364251416592378235178694642835917751649823398721546",
"123456789854197362967832451472968135391245678685371294238719546549623817716584923",
"123456789859172463746938251634295178218764395597381624482517936375649812961823547",
"123456789748392156695871432314285697956734821872619345239168574581947263467523918",
"123456789576289134498173526289361475715842963364597218637915842852734691941628357",
"123456789879213564654879321367581492491732856285964173512648937746395218938127645",
"123456789846179325975832461652948173719365842384721956537694218291587634468213597",
"123456789875239641964178325641582973738941256259763418416325897397814562582697134",
"123456789986127354475839126258974613317265948649318275862743591591682437734591862",
"123456789476198532589372416617523948895741263234869157768915324341287695952634871",
"123456789574982316896173452347615298951827634682349175468791523219534867735268941",
"123456789698271354574398612761845293352967841849123567936784125487512936215639478",
"123456789459827316678139524264571938397284651581693247715368492836942175942715863",
"123456789564789312987123546479215638235864971816937425752391864391648257648572193",
"123456789459738261876912534794685312238147695615329847987264153541873926362591478",
"123456789479183526856279341764321958591864237238597164612738495387945612945612873",
"123456789945287316867913524718392645692845173354671892486139257279568431531724968",
"123456789648729135795318426954173862286594371371862594439685217567231948812947653",
"123456789975218364648397152369542871482761935751983246297634518836125497514879623",
"123456789849317562657982431295164378761538924384729156912675843478293615536841297",
"123456789475298613968173245754832961619547328832961574347619852586324197291785436",
"123456789957281436864379152389765241615842973742913865431628597276594318598137624",
"123456789478912635695837124567184293934625817812793456356278941249561378781349562",
"123456789645789231879321564716534892234978156958162473481695327567243918392817645",
"123456789679183425854927361382569174946271853517834296298345617465718932731692548",
"123456789849172365765839124698724531512963847437518692954687213276391458381245976",
"123456789954817263678392145587621394316974528249538617865143972492765831731289456",
"123456789645789132987321546231675894768194253594238617456917328319862475872543961",
"123456789796821453584739621972613548615984237438572916259168374361247895847395162",
"123456789547829613689731452894672531312945867765183924938264175271598346456317298",
"123456789796832514584791632438965271671324958259178463342587196867219345915643827",
"123456789546897321789321456698542137312678594457139862831264975965713248274985613",
"123456789569871243487923615942637158375148962618592374231785496896314527754269831",
"123456789846937512795128364519284673274613895638579241952761438361842957487395126",
"123456789659278413784319265392861574476592831815734692567143928938625147241987356",
"123456789695718243748932516254691378986347152317825964471269835839574621562183497",
"123456789946837512587192463471529638235648197869371254758964321692713845314285976",
"123456789675819234849372165481527693736194528592683471358261947217948356964735812",
"123456789468927153597381624276145398384269517951738462712593846845672931639814275",
"123456789867129534459873612615734928342985167798612453984361275576248391231597846",
"123456789679183524845927631532741968784569312961238457316894275457612893298375146",
"123456789584972136967138425631547892492681357875293641746829513359714268218365974",
"123456789468792351759318642371925468586134927942687135817563294695241873234879516",
"123456789765983142849712536251368497397124865486597213534879621618235974972641358",
"123456789478912536695387142861594273734128965952673418389745621546231897217869354",
"123456789685379214974128563841265397597843126362791458736912845419587632258634971",
"123456789475983261968217453596872134781364925342591678254639817819725346637148592",
"123456789985237461467981523519328674276514938348679152631792845854163297792845316",
"123456789867139254954278136379861425486527913215394867531942678648713592792685341",
"123456789658179423947823651276384915481295376395617842832761594769542138514938267",
"123456789954782631876391254789623415641579328235814976492135867567248193318967542",
"123456789784192653596873124315624978249718536867935412672589341431267895958341267",
"123456789859172346647398521982743165365219478714685932478921653596837214231564897",
"123456789746891253985723461562174398814639527379285146438912675291567834657348912",
"123456789847219356965837124214583697598674231736921845472365918351798462689142573",
"123456789459827136876391542964782351587613924231549867342978615718265493695134278",
"123456789968723541574918632735892164286147395419635278347281956692574813851369427",
"123456789549817236687932145762184953415329867398675421851293674976548312234761598",
"123456789658719243974832651597321468861594372342678195736185924489263517215947836",
"123456789986317254547928316478563192291874563365291847714635928659782431832149675",
"123456789985327461746981235578132694462598317391764528257619843614873952839245176",
"123456789895273614674189523358917246746328951219564378581632497932741865467895132",
"123456789859127634647398152468735291395214876712689543974861325536972418281543967",
"123456789958173624674829513249561837815397246367248195592614378781935462436782951",
"123456789975382641846197532357869124689241375214735968592674813731528496468913257",
"123456789478913256956872341249781635361295478587364912634128597892537164715649823",
"123456789498723516576918432712849365964531278385672941837195624649287153251364897",
"123456789549871326678239541962514837385967214714328965857642193491783652236195478",
"123456789875391624946728513398645172217839465564172938482567391759213846631984257",
"123456789546897123879312456495128637618739245732645891367584912281963574954271368",
"123456789958732614476918253241863597569174328837529461384295176792641835615387942",
"123456789964873125857219364578634912391782456246591837432968571685147293719325648",
"123456789486927153759183264645791832297538416318642975874369521562814397931275648",
"123456789697823154458197326586241973279365418314978265965714832841532697732689541",
"123456789597238614648719235361942578952871346874563921736194852489325167215687493",
"123456789687912534594738621715864293862593417439127865258379146341685972976241358",
"123456789698237541457198236372519864869724153541863972716945328935682417284371695",
"123456789569817342748293165285369471476125938931748526854932617397681254612574893",
"123456789964782153578139624619547832357218496842963517296875341435621978781394265",
"123456789495871263867239154672193548538764921941528376356947812784312695219685437",
"123456789756289134498731265569842371847913652231675948615328497972564813384197526",
"123456789867912543594783216245137968376829154918645372432561897781394625659278431",
"123456789567928413489317256634781925912534867875692341341869572298175634756243198",
"123456789658197243479382156892643571761925834534871962947238615315769428286514397",
"123456789847329651965718342538691427214873965796542813359164278472985136681237594",
"123456789748931256569827134957318462632549817814762593381294675275683941496175328",
"123456789867392451594718623456289317782134965931675248678921534219543876345867192",
"123456789756918243849327156932541678675832914481769325398175462567294831214683597",
"123456789948271635576398214857619342294837561361542897485923176619785423732164958",
"123456789975382614486971532541297863897635241362148975234769158759813426618524397",
"123456789467829351985173462714695823639218574852347916298764135341582697576931248",
"123456789967318524485792163652931847794685231318247695841563972236179458579824316",
"123456789569871243874392561237918456958643172416725398682537914741269835395184627",
"123456789485179326796328451918764235572813694364295817249537168851642973637981542",
"123456789598173462476829351845297136917638245362541897231985674754362918689714523",
"123456789568279143947138652651843297289761435374925816835617924712594368496382571",
"123456789856729314974381526698217435531694278742538961369842157217965843485173692",
"123456789569873421874192653392745168781269534645381972236514897917638245458927316",
"123456789854917362769283145678521493315649827492378516581762934237894651946135278",
"123456789876293514459817236741932865538764921692581473384125697967348152215679348",
"123456789967821543458793621319572468782964135546318972231645897874139256695287314",
"123456789549871263867932415712398654958164372634527891485613927296745138371289546",
"123456789479812536586937124864125973712369458395748261258691347641573892937284615",
"123456789694873521587912346458329617712568493369147852846231975275694138931785264",
"123456789847291653695378421216749538379685214458123976962837145781564392534912867",
"123456789598372641764819352487693215916528473352147968231784596849265137675931824",
"123456789549872613867913245296347851415628397378591426654789132931264578782135964",
"123456789847219653659837412512984367968173245734562891375641928286795134491328576",
"123456789854971623976328154268734915539612478741589362612843597385197246497265831",
"123456789475839162968172453892713546347965218651248937716324895584697321239581674",
"123456789586927314497183625835619247619274853742835196378542961264391578951768432",
"123456789684197532579382146237649851941825367865713924316574298752968413498231675",
"123456789879132564465978231237861495594723816681594372318645927946287153752319648",
"123456789948731526567982341481675293356298174279314865892163457615847932734529618",
"123456789759821346648739215512364978374598162896217453965172834287643591431985627",
"123456789694187325785923641936712458572864193418395276357648912869271534241539867",
"123456789574983126698172345985347261731268594462519873817695432249731658356824917",
"123456789796318524845792163354867291279134658618925437531679842982541376467283915",
"123456789758139264469782351672841935391527846584963172947315628235698417816274593",
"123456789748932561659817324815729436364581972972643815237195648491368257586274193",
"123456789589173642647829531362581974894762315715934826238645197451397268976218453",
"123456789458791263769823541834275196512964837697318425376582914245139678981647352",
"123456789687319254954287631231698475876541923549723816768134592392865147415972368",
"123456789495178362768239415217694538589713624346825971874961253651342897932587146",
"123456789498173652765982341354729816687315924912864537839641275271598463546237198",
"123456789867219354945738621316982475284375916579641832792563148638124597451897263",
"123456789784139265965827431419675328652348917837291654546913872278564193391782546",
"123456789897312456564897231479685312381279645256134897738561924612948573945723168",
"123456789498273615675189423384967152517342968269815374831724596952631847746598231",
"123456789894371265765289413972635841346718952581924637638597124459162378217843596",
"123456789895372146674819325941765832362148597587293461218637954456981273739524618",
"123456789847913562956827341684379125791265438235184976572631894418792653369548217",
"123456789859327416764198325386971542975284163412563897631742958548639271297815634",
"123456789769318542485927136548269317972183654316745928851672493297534861634891275",
"123456789856793124947182635479518263312967548568324917735241896284679351691835472",
"123456789796813524854927613678594132345162897219378465937641258481235976562789341",
"123456789896172534745389612672514893581937246439628157958263471367841925214795368",
"123456789947318526685927143819632457756149832432785961271864395364591278598273614",
"123456789469781523587329164398572641674198235251643897712834956945267318836915472",
"123456789845917632976823451281679543457138296639542817792385164564291378318764925",
"123456789859317462674289315947528136386791254512634978231965847768142593495873621",
"123456789846179325597823641935648172761532894284791536358214967479365218612987453",
"123456789654879231978312456342961578791285364586743192219637845867524913435198627",
"123456789457893162986721453764218395895347216312569874241685937638974521579132648",
"123456789857239416469178523385697241216345897974812635792581364538964172641723958",
"123456789746893251589721436692175348374982165815364927261539874458217693937648512",
"123456789458917263796283154365891427941572836872634915619348572537129648284765391",
"123456789749283651865917243316879524492561378587342916674135892238794165951628437",
"123456789948372516675981234587269341319845672264713895756134928891527463432698157",
"123456789584793261796128453879315642345672918261849537652981374917534826438267195",
"123456789795238164684971352271685493958314276436792815542167938819543627367829541",
"123456789875932416469781325218365974954278163736194258647513892592847631381629547",
"123456789794238516586791243659142378248367195371985624837624951462519837915873462",
"123456789549872631786319452671238945854791263392564178265187394437925816918643527",
"123456789468397251597821364285943176371268945649715823956172438734689512812534697"]
module.exports = solvedSudokus;
/***/ }),
/* 13 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__board_solver_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__game_board_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__game_tile_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__game_util_js__ = __webpack_require__(0);
// Purpose of this class:
// 1) Accept a boardSolver
// 2) define the children of this boardSolver:
// 2.1) get the next available position of the current boardSolver
// (position with less possible values)
// 2.2) get the tile on the position
// 2.3) Loop through each available marks of the tile
// 2.4) Create a new boardSolver for each mark
// and update the tile of the new board Solver with the mark
// 2.5) If the new boardSolver has a solution: push to children
// 3) build a stack with initial value: boardSolver at creation
// 4) pop one element of the stack: return the board if board is solved
// if not get the children of the current board and push on the stack
// 5) keep going while the stack is not empty or if we find a solution
// Pros and cons:
// Pros: boardSolver are already simplified (singeton value updated)
// which accelerate the process of finding a solution.
// Cons: we create new board for each tile.marks
// which could be a lot of boards on high difficulty (bad space complexity and
// time complexity on the worse case scenario)
// checking if the board is solved add a lot of extra step:
// there should be a way to do that faster
class SudokuSolver {
constructor(boardSolver){
this.positions = boardSolver.availablePositions;
this.root = boardSolver;
this.root.updateMarks();
}
solve(){
let stack = [this.root];
while(stack.length > 0){
let currentBoard = stack.pop();
if( currentBoard.availablePositions.length === 0){
return currentBoard.board.getValues();
}
this.children(currentBoard).forEach( board => stack.push(board))
}
return null;
}
children(boardSolver){
let children = [];
let nextAvailablePosition = this.getNextPos(boardSolver);
let positions = this.updatePositions(boardSolver, nextAvailablePosition);
let tile = boardSolver.board.getTile(nextAvailablePosition);
tile.marks.forEach((mark) => {
let newBoardSolver = new __WEBPACK_IMPORTED_MODULE_0__board_solver_js__["a" /* default */](boardSolver.board, positions);
newBoardSolver.updateTile(nextAvailablePosition, mark);
if(newBoardSolver.solvable){
children.push(newBoardSolver)
}
});
return children;
}
getNextPos(boardSolver){
let min = 10;
let result = [];
boardSolver.availablePositions.forEach((pos,idx) => {
let tile = boardSolver.board.getTile(pos);
if ( tile.marks.length !== 0 && tile.marks.length <= min){
min = tile.marks.length;
result = pos;
}
});
return result;
}
updatePositions( boardSolver, pos){
return __WEBPACK_IMPORTED_MODULE_3__game_util_js__["a" /* default */].update(boardSolver.availablePositions, [pos]);
}
}
/* harmony default export */ __webpack_exports__["a"] = (SudokuSolver);
/***/ })
/******/ ]);
|
Writer = Class.extend({
recorder: null,
drawingAgent: null,
modeAgent: null,
init: function() {
console.log("init writer");
this.drawingAgent = new DomAgent("#char-matrix");
this.modeAgent = new ModeAgent();
//this.strokeHandler = new StrokeHandler();
this.recorder = new Recorder();
this.animation = new Animation();
this.scroller = new Scrolling("#scroller");
this.setUpModes();
},
// Allokerar stroke handlers för alla modes, kanske inte bra.
setUpModes: function() {
this.modes = {
RECORD_MODE: new RecordMode(),
MENU_MODE: new MenuMode()
}
},
// Called from default.js
start: function() {
this.startScroller();
if (typeof(_strokes) !== 'undefined') {
this.playbackSaved();
}
else {
this.modeAgent.setMode(this.modes.RECORD_MODE);
}
this.listen();
},
clearDisplay: function() {
this.drawingAgent.reset();
},
getRecorder: function() {
return this.recorder;
},
startScroller: function() {
this.scroller.setText("HEJ, DETTA AR EN SCROLLTEXT FOR ATT TESTA HUR DET FUNKAR MED SCROLLTEXTER PA ETT UNGEFAR");
this.scroller.start();
},
playbackSaved: function() {
for (i=0; i<_strokes.length; i++) {
var stroke = _strokes[i];
this.recorder.strokes.push(new Stroke({
keyCode: stroke.keyCode,
shifted: stroke.shifted,
ctrld: stroke.ctrld,
alted: stroke.alted,
eventType: stroke.eventType,
time: stroke.time
}));
}
this.recorder.startPlayback();
},
saveDocument: function() {
var strokeString = JSON.stringify(this.recorder.strokes);
//document.location = "/save/" + strokeString;
var me = this;
$.ajax({
type: 'POST',
url: '/save',
data: { strokes: strokeString }
}).done(function(message) {
//console.log("done", message);
document.location = "/load/" + message;
});
},
listen: function() {
var me = this;
$("#playback").click(function() {
me.drawingAgent.reset();
me.recorder.startPlayback();
});
$("#dump").click(function() {
me.drawingAgent.matrix.dump();
});
$("#undump").click(function() {
me.drawingAgent.matrix.unDump(staticLetters.test);
});
$("#save").click(function() {
me.saveDocument();
});
}
});
|
$(document).ready(function(){
$(".pregunta-laberintos").change(function(){
valor = parseInt($('input[name=pregunta-laberintos-3]').val());
valor2= parseInt($('input[name=pregunta-laberintos-1]').val());
valor3 = parseInt($('input[name=pregunta-laberintos-2]').val());
suma = valor +valor2+valor3;
if(suma >10)
{
sobrante = suma - (2*valor);
if(sobrante >10)
{
restarvalue1 = 10 - valor3 - valor2;
restarvalue2 = valor3;
if(restarvalue1 < 0)
{
restarvalue1 = 10- valor - valor3;
}
}
else
{
restarvalue2 = 10 - valor -valor2;
restarvalue1 = 10 -restarvalue2 - valor;
if(restarvalue2 <0)
{
restarvalue2 = 0;
restarvalue1 = 10 - valor
}
}
$('input[name=pregunta-laberintos-1]').val(restarvalue1);
$('#laberintosp1').text(restarvalue1);
$('input[name=pregunta-laberintos-2]').val(restarvalue2);
$('#laberintosp2').text(restarvalue2);
//alert(suma);
}
});
});
|
window.b=function(f,h){function c(){var d=g.length;if(0<d)for(var a=0;a<d;a++){var k=g[a],e;if(e=k)e=k.getBoundingClientRect(),e=(0<=e.top&&0<=e.left&&e.top)<=(window.innerHeight||h.documentElement.clientHeight)+200;e&&(k.src=k.getAttribute("data-src"),g.splice(a,1),d=g.length,a--)}else h.removeEventListener?f.removeEventListener("scroll",c):f.detachEvent("onscroll",c)}var g=[];return{a:function(){for(var d=h.querySelectorAll("[data-src]"),a=0;a<d.length;a++)d[a].src="",g.push(d[a]);
c();h.addEventListener?(f.addEventListener("scroll",c,!1),f.addEventListener("load",c,!1)):(f.attachEvent("onscroll",c),f.attachEvent("onload",c))},c:c}}(this,document);b.a();
!function(a,c,e,d,f){this.$=function(b){return new $[e].i(b)};f={length:0,i:function(b){c.push.apply(this,b&&b.nodeType?[b]:""+b===b?c.slice.call(a.querySelectorAll(b)):/^f/.test(typeof b)?$(a).r(b):null)},r:function(b){/c/.test(a.readyState)?b():$(a).on("DOMContentLoaded",b);return this},on:function(b,c){return this.each(function(a){a["add"+d](b,c)})},off:function(b,c){return this.each(function(a){a["remove"+d](b,c)})},each:function(b,a){c.forEach.call(a=this,b);return a},text:function(b){return b===
[]._?this[0].textContent:this[0].textContent=b},rmClass:function(b){return this[0].className=this[0].className.replace(RegExp("\\b"+b+"\\b"),"")},addClass:function(b){this[0].className=this[0].className+" "+b+"";return this},hasClass:function(cN){el=this[0];if(el.classList)return el.classList.contains(cN);else return new RegExp('(^| )' + cN + '( |$)', 'gi').test(el.className);}};
$[e]=f.i[e]=f}(document,[],"prototype","EventListener");
$.ajax=function(a,c,e){if(this.r=new XMLHttpRequest){var d=this.r;e=e||"";d.onreadystatechange=function(){4==d.readyState&&200==d.status&&c(d.responseText)};""!==e?(d.open("POST",a,!0),d.setRequestHeader("Content-type","application/x-www-form-urlencoded")):d.open("GET",a,!0);d.setRequestHeader("X-Requested-With","XMLHttpRequest");d.send(e)}};
$.prototype.hide=function(){
return this.each(function(b){
b.style.display = 'none'
})
}
$.prototype.show=function(){
return this.each(function(b){
b.style.display = ''
})
}
$.param = function(obj, prefix) {
var str = [];
for(var p in obj) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ? $.param(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
};
$("a.vote-link").on("click",votelistener)
function votelistener(e) {
e.preventDefault();
$("a.vote-link").off("click",votelistener)
var url = this.href + "&ajax=true"
var node = this
$(this).addClass("disabled")
$.ajax(url,function(a){
a=JSON.parse(a);
if ("undefined"!=typeof a.error) {
show_message(a.error,true)
$(this).rmClass("disabled")
}
else {
show_message(a.response,false)
}
$("a.vote-link").on("click",votelistener)
var el = $(node.parentNode)
el.addClass("c33 shadow-border text-center")
var sum = a.Behind + a.Against
el.text(sum)
var parent = el[0].parentNode
var bars = parent.querySelectorAll(".progress-bar")
console.log(bars)
bars[0].style.width = a.widthB + "%"
bars[1].style.width = a.widthA + "%"
$(bars[0]).text(a.Behind)
$(bars[1]).text(a.Against)
})
}
function show_message(m,error) {
console.log(m)
}
var search = $(".search")
var input = $(".search input[type=search]")[0]
var list = $(".ajax-search-results")[0]
search.on("keyup", function(){
var q = input.value
if (q === "" ){
return
}
q = parseLatin(q)
$.ajax("/prepodavateli/poisk?ajax=true&q="+q, function(r){
var listcontent = ""
var json = JSON.parse(r)
if (json.length >5)
length = 5
else
length = json.length
for (i = 0; i < length; i++) {
listcontent += "<li><a href=\"/prepodavateli/"+json[i].Slug+"\"><img height='40px' src='"+json[i].Img+"'>"+json[i].PrettyName+"</a>"
}
list.innerHTML = listcontent
})
})
function parseLatin(text){
var outtext = text;
var lat2 = 'F<DULT~:PBQRKVYJGHCNEA{WXIOMS}">Zf,dult`;pbqrkvyjghcnea[wxioms]\'.z';
var rus2 = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯабвгдеёжзийклмнопрстуфхцчшщьыъэюя';
for (var i = 0, l = lat2.length; i < l; i++) {
outtext = outtext.split(lat2.charAt(i)).join(rus2.charAt(i));
}
return outtext;
}
$(".to-top").hide()
function totop() {
window.scrollTo(0,100);
var offset_top = 100
function frame() {
offset_top = offset_top - 10 // update parameters
window.scrollBy(0,-10); // show frame
if (offset_top == 0) // check finish condition
clearInterval(id)
}
var id = setInterval(frame, 10) // draw every 10ms
}
$(".to-top").on("click",function(){
totop()
})
window.onscroll=function(){
var a=Math.round(window.pageYOffset||document.documentElement.scrollTop);
650>=a&&($(".to-top").hide());
650<a&&($(".to-top").show())
};
$("#libsearch-val").on("change",function(){
var val = $("#libsearch-val")[0].value
$("#lib-search-form")[0].action=getRuslanLink(val)
})
|
module.exports = [{
id: 0,
name: 'John Cena',
phone: '8845579923',
email: 'johncena@example.com',
relation: ' ',
invited: ' ',
}, {
id: 1,
name: 'Tommy Curtin',
phone: '7044439912',
email: 'tommycurtin@example.com',
relation: ' ',
invited: ' ',
}, {
id: 2,
name: 'Reece Belmondo',
phone: '8675309911',
email: 'reecebelmondo@example.com',
relation: ' ',
invited: ' ',
}, {
id: 3,
name: 'Marshall Mathers',
phone: '1234449955',
email: 'marshallmathers@example.com',
relation: ' ',
invited: ' ',
}, {
id: 4,
name: 'Steve Ballmer',
phone: '8850912444',
email: 'steveballmer@example.com',
relation: ' ',
invited: ' ',
}, {
id: 5,
name: 'Mark Cuban',
phone: '7046671896',
email: 'markcuban@example.com',
relation: ' ',
invited: ' ',
}, {
id: 6,
name: 'Johnny Ive',
phone: '9802216529',
email: 'johnnyive@example.com',
relation: ' ',
invited: ' ',
}, {
id: 7,
name: 'Tim Cook',
phone: '1127440915',
email: 'timcook@example.com',
relation: ' ',
invited: ' ',
}, {
id: 8,
name: 'Steve Goebel',
phone: '7752180032',
email: 'stevegoebel@example.com',
relation: ' ',
invited: " "
}, {
id: 9,
name: 'Yogi Berra',
phone: '3825410938',
email: 'yogitheberra@example.com',
relation: ' ',
invited: ' ',
}, {
id: 10,
name: 'Carl Carlson',
phone: '3405337834',
email: 'carlcarlson@example.com',
relation: ' ',
invited: ' ',
}, {
id: 11,
name: 'Barry Allen',
phone: '2104378228',
email: 'fastestmanalive@example.com',
relation: ' ',
invited: ' ',
}, {
id: 12,
name: 'Michael Scott',
phone: '5703249385',
email: 'michaelscott@example.com',
relation: ' ',
invited: ' ',
}, {
id: 13,
name: 'Bruce Banner',
phone: '3894223722',
email: 'greenmonster@example.com',
relation: ' ',
invited: ' ',
}, {
id: 14,
name: 'Clark Griswold',
phone: '2104831865',
email: 'clarkgriswold@example.com',
relation: ' ',
invited: ' ',
}, {
id: 15,
name: 'Marshall Teach',
phone: '3284309123',
email: 'marshallteach@example.com',
relation: ' ',
invited: ' ',
}, {
id: 16,
name: 'Luke Skywalker',
phone: '3258940343',
email: 'lukeskywalker@example.com',
relation: ' ',
invited: ' ',
}, {
id: 17,
name: 'Linnea Alvinquist',
phone: '2343549565',
email: 'linneaalvinquist@example.com',
relation: ' ',
invited: ' ',
}, {
id: 18,
name: 'Sheldon Cooper',
phone: '7403943821',
email: 'sheldoncooper@example.com',
relation: ' ',
invited: ' ',
}, {
id: 19,
name: 'Luke Segars',
phone: '8432385340',
email: 'luke@example.com',
relation: ' ',
invited: ' ',
}];
|
import React from 'react'
import { observer, inject } from 'mobx-react';
@inject('kiwoomStore') @observer
class ConnectAndLogin extends React.Component {
constructor(props) {
super(props)
}
render() {
const { connectionInfo, cls } = this.props.kiwoomStore
return (
<div>
{ connectionInfo.connected === 'connecting' &&
<div className='d-flex flex-column align-items-center bg-light jumbotron'>
<p className='lead text-dark'>에이전트 연결 중입니다.</p>
</div>
}
{ connectionInfo.connected === 'disconnected' &&
<div className='d-flex flex-column align-items-center bg-light jumbotron'>
<p className='lead text-dark'>에이전트를 실행한 후 연결 버튼을 클릭하세요</p>
<div className="input-group connection-info">
<span className="input-group-addon">에이전트 주소</span>
<input type="url" className="form-control" placeholder="0.0.0.0" aria-label="agent address"
value={connectionInfo.address}
onChange={(event) => {cls.setAddress(event.target.value)}}
/>
<span className="input-group-btn">
<button className="btn btn-success" onClick={() => cls.connect()}>연결</button>
</span>
</div>
</div>
}
{
connectionInfo.connected === 'connected' &&
!connectionInfo.loggedIn &&
<div className='d-flex flex-column align-items-center bg-light jumbotron'>
<button className="btn btn-success btn-lg p-4" onClick={() => cls.login()}>키움증권 로그인</button>
</div>
}
</div>
)
}
}
export default ConnectAndLogin
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Car = /** @class */ (function () {
/*
private make:string;
private model:string;
private color:string;
private regNo:string;
*/
function Car(_make, _model, _color, _regNo) {
this._make = _make;
this._model = _model;
this._color = _color;
this._regNo = _regNo;
this._make = _make;
this._model = _model;
this._color = _color;
this._regNo = _regNo;
}
Object.defineProperty(Car.prototype, "make", {
get: function () {
return this._make;
},
set: function (make) {
this._make = make;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Car.prototype, "color", {
get: function () {
return this._color;
},
set: function (color) {
this._color = color;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Car.prototype, "model", {
get: function () {
return this._model;
},
set: function (model) {
this._model = model;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Car.prototype, "regNo", {
get: function () {
return this.regNo;
},
set: function (regNo) {
this.regNo = regNo;
},
enumerable: true,
configurable: true
});
Car.prototype.toString = function () {
return "{make: " + this._make + ", model:" + this._model + ", color:" + this._color + ", regNo:" + this._regNo + "}";
};
return Car;
}());
exports.Car = Car;
/*
1. No need to declare private fields, if declared in constructor.
2. Can make the setters and getters as property
3.
*/
|
const form = document.querySelector('form')
const emailError = document.querySelector('.email.error')
const hourlyRateError = document.querySelector('.Hourly.rate.error')
const noJobsType = document.querySelector('.noJobTypes.error')
const noLanguages = document.querySelector('.noLanguages.error')
const sucNew = document.querySelector('.suc.new')
form.addEventListener('submit', async (e) => {
e.preventDefault()
emailError.textContent = ''
hourlyRateError.textContent = ''
noJobsType.textContent = ''
noLanguages.textContent = ''
sucNew.textContent = ''
// get values
const email = form.email.value
const password = form.password.value
const firstName = form.firstName.value
const lastName = form.lastName.value
const phoneNumber = form.phoneNumber.value
const city = form.city.value
const street = form.street.value
const houseNumber = form.houseNumber.value
const hourlyRate = form.hourlyRate.value
const experience = form.experience.value
const gender = form.gender.value
const aboutMe = form.aboutMe.value
const education = form.education.value
const smoker = form.smoker.value
const form101 = form.form101.value
const picture = form.picture.value
const bankName = form.bankName.value
const branch = form.branch.value
const accountNumber = form.accountNumber.value
const birthday = form.birthday.value
if(hourlyRate<17 || hourlyRate>500){
hourlyRateError.textContent = 'Please enter salary in the following range: [17,500]'
return
}
var hebrew = document.getElementById('hebrew')
var english = document.getElementById('english')
var arabic = document.getElementById('arabic')
var russian = document.getElementById('russian')
var amharic = document.getElementById('amharic')
var chinese = document.getElementById('chinese')
var portuguese = document.getElementById('portuguese')
var french = document.getElementById('french')
var romanian = document.getElementById('romanian')
var polish = document.getElementById('polish')
var spanish = document.getElementById('spanish')
flag=0
var arrLang = []
if (hebrew.checked == true){
arrLang.push('hebrew')
flag=1
}
if (english.checked == true){
arrLang.push('english')
flag=1
}
if(arabic.checked == true){
arrLang.push('arabic')
flag=1
}
if (russian.checked == true){
arrLang.push('russian')
flag=1
}
if (amharic.checked == true){
arrLang.push('amharic')
flag=1
}
if(chinese.checked == true){
arrLang.push('chinese')
flag=1
}
if(portuguese.checked == true){
arrLang.push('portuguese')
flag=1
}
if (french.checked == true){
arrLang.push('french')
flag=1
}
if (romanian.checked == true){
arrLang.push('romanian')
flag=1
}
if(polish.checked == true){
arrLang.push('polish')
flag=1
}
if(spanish.checked == true){
arrLang.push('spanish')
flag=1
}
if (flag==0){
noLanguages.textContent = 'Please select at least one language'
return
}
var babysitting = document.getElementById('babysitting')
var cleaning = document.getElementById('cleaning')
var ironing = document.getElementById('ironing')
var gardening = document.getElementById('gardening')
var cooking = document.getElementById('cooking')
var petCare = document.getElementById('pet care')
var arrTypeJob = []
var flag=0
if (babysitting.checked == true){
arrTypeJob.push('babysitting')
flag=1
}
if (cleaning.checked == true){
arrTypeJob.push('cleaning')
flag=1
}
if(ironing.checked == true){
arrTypeJob.push('ironing')
flag=1
}
if (gardening.checked == true){
arrTypeJob.push('gardening')
flag=1
}
if(cooking.checked == true){
arrTypeJob.push('cooking')
flag=1
}
if(petCare.checked == true){
arrTypeJob.push('pet care')
flag=1
}
if (flag==0){
noJobsType.textContent = 'Please select at least one job type'
return
}
try {
const res = await fetch('/addAContractorHR', {
method: 'POST',
body: JSON.stringify({ email, password,firstName,lastName,phoneNumber,city,street,houseNumber,branch,accountNumber,bankName,
gender,arrLang,education,smoker,experience,hourlyRate,picture,form101,birthday,aboutMe, arrTypeJob}),
headers: {'Content-Type': 'application/json'}
})
const data = await res.json()
console.log(data)
if (data.errors) {
emailError.textContent = data.errors.email
}
if(data.user){
var msg='A new contractor worker: '+data.user.email+' is added to the system an email on its way to him/her.'
// sucNew.textContent = msg
form.reset()
// eslint-disable-next-line no-undef
swal(msg)
//res.send('<h3>YOU ARE ADD A NEW EMPLOYER TO THE SYSTEM</h3>')
}
}
catch (err) {
console.log(err)
}
})
|
import React from 'react';
import PropTypes from 'prop-types';
import { Box } from '../Box';
import { Text } from '../Text';
const shortDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
function Weekday({ className, weekday, localeUtils = {} }) {
return (
<Box
flex="1 0 0"
minWidth="650"
textAlign="center"
role="columnheader"
className={className}
py="300"
>
<Text
as="abbr"
color="gray.800"
title={localeUtils.formatWeekdayLong(weekday)}
fontWeight="medium"
fontSize="200"
lineHeight="200"
color="gray.700"
textAlign="center"
style={{ textDecoration: 'none' }}
>
{shortDays[weekday]}
</Text>
</Box>
);
}
Weekday.displayName = 'Weekday';
// Props come from react-day-picker
Weekday.propTypes = {
className: PropTypes.string,
weekday: PropTypes.number,
};
export default Weekday;
|
var searchData=
[
['logger',['logger',['../classspatial__driver_1_1spatial__driver.html#a5d9fcdf9d8185cb89fb1941038cfbbc8',1,'spatial_driver::spatial_driver']]]
];
|
//=====================9_11=====================
function change(number) {
let inch = (Number(number) / 254) * 100;
console.log(inch);
///254*100;
let feet = inch / 12;
console.log(inch, feet);
return inch, feet;
}
//=====================9_12=====================
function cal_volume(radius, height) {
let volume = Number(radius) * 2 * 3.141592 * Number(height);
console.log(volume);
return volume;
}
//=====================9_13=====================
function seperate_number(number) {
let first = parseInt(number / 1000);
let second = parseInt((number % 1000) / 100);
let third = parseInt((number % 100) / 10);
let fourth = parseInt(number % 10);
console.log(first, second, third, fourth);
}
//=====================9_14=====================
function year(number) {
let yearDic = {
0: "원숭이띠",
1: "닭띠",
2: "개띠",
3: "돼지띠",
4: "쥐띠",
5: "소띠",
6: "범띠",
7: "토끼띠",
8: "용띠",
9: "뱀띠",
10: "말띠",
11: "양띠",
};
let year = yearDic[number % 12];
console.log(year);
return year;
}
function year2() {
var ddi = prompt("년도를 입력하세요.");
var result = ddi % 12;
switch (result) {
case 0:
document.write("원숭이띠");
break;
case 1:
document.write("닭띠");
break;
}
}
function year3() {
var ddi = [
"원숭이",
"닭",
"개",
"돼지",
"쥐",
"소",
"범",
"토끼",
"용",
"뱀",
"말",
"양",
];
var input = parseInt(prompt("태어난 연도를 입력하세요."));
document.write(ddi[input % 12]);
}
//=====================9_15=====================
/*
var output = '';
for (var i = 0; i < 10; i++) {//row
for (var j = 0; j < i+1; j++){//col
output += "*";
}
output += '\n';
}
alert(output);
for (var i = 0; i < 10; i++){
for (var j = 0; j < 10 - i; i++){
output += "*"
}
output +="\n"
}
alert(output);
function factorial(num){
var output=1;
for(var i=1; i<num;i++){
output*=i;
}
return output;
}
*/
//================증가
function tree0() {
let star = "";
for (let i = 0; i < 10; i++) {
for (let j = 9 - i; j < 10; j++) {
star += "*";
}
console.log(star);
star = "";
}
}
//===============감소
function tree1() {
//===1th
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10 - i; j++) {
document.write("*");
}
document.write("<br>");
}
//====2th
for (var i = 10; i > 0; i--) {
for (var j = i; j > 0; j--) {
document.write("*");
}
document.write("<br>");
}
}
//===============3중 test
function tree2() {
for (let i = 1; i <= 10; i++) {
for (let j = 1; j <= i; j++) {
for (let k = 1; k <= j; k++) {
document.write("*");
}
document.write("<br>");
}
document.write("<br>");
}
}
function tree3() {
for (var i = 0; i < 10; i++) {
for (var j = 9 - i; j < 10; j++) {
for (var k = j; k < 10; k++) {
document.write("*");
//document.write(`3_${i}${j}${k}`, "\t");
}
document.write("<br>");
//document.write(`2_${i}${j}${k}`, "\t");
}
document.write("<br>");
//document.write(`1_${i}${j}${k}`, "\t");
}
}
//=====================9_16=====================
function factorial(num) {
let number = num;
let res = num;
while (number != 1) {
number -= 1;
res *= number;
}
console.log(res);
return res;
}
output = "";
function square(number) {
number = 5;
for (var i = 0; i < number; i++) {
for (var j = 0; j < number; j++) {
output += "*";
//document.write("*");
}
output += "\n";
// document.write("<br>");
}
console.log(output);
//alert(output);
}
function treeplus(number) {
number = 5;
for (var i = 0; i < number; i++) {
for (var j = 0; j < i + 1; j++) {
output += "*";
//document.write("*");
}
output += "\n";
//document.write("<br>");
}
console.log(output);
}
function trianglePlusSpace(number) {
number = 5;
for (var i = 0; i < number; i++) {
for (var j = 0; j < number; j++) {
if (j < number - i - 1) {
output += " ";
} else {
output += "*";
}
}
output += "\n";
}
console.log(output);
}
function treeminus(number) {
number = 5;
for (var i = 0; i < number; i++) {
for (var j = 0; j < number - i; j++) {
output += "*";
document.write("*");
}
output += "\n";
document.write("<br>");
}
console.log(output);
}
function triangleMinusSpace(number) {
number = 5;
for (var i = 0; i < number; i++) {
for (var j = 0; j < number; j++) {
if (j < i) {
output += " ";
} else {
output += "*";
}
}
output += "\n";
}
console.log(output);
}
function e_trianglePlus(height) {
height = 5;
width = height * 2 + 1;
for (var i = 1; i < height + 1; i++) {
occupy_s = i * 2 - 1; //******** */
empty_s = width - occupy_s;
left_p = empty_s / 2;
right_p = empty_s / 2 + occupy_s - 1;
for (var j = 0; j < width; j++) {
if (j < left_p || j > right_p) {
output += "_";
} else {
output += "*";
}
}
output += "\n";
}
console.log(output);
}
function e_triangleMinus(height) {
height = 5;
width = height * 2 + 1;
for (var i = 1; i < height + 1; i++) {
occupy_s = width - i * 2 + 1; //********** */
empty_s = width - occupy_s;
left_p = empty_s / 2;
right_p = empty_s / 2 + occupy_s - 1;
for (var j = 0; j < width; j++) {
if (j < left_p || j > right_p) {
output += "_";
} else {
output += "*";
}
}
output += "\n";
}
console.log(output);
}
|
define(function() {
var Index = {
init: function() {
console.log('Module Index loaded!');
}
};
return Index;
});
|
// create by hjKim. KOOKMIN UNIV.
// Annotorious Coustom version.
// + auto_selector.js <-- applied prototype annotorious.
/* Annotorious Initialize */
//annotorious module extending
//add Module name = "changeLabelBoxUI"
anno.addUIModule = function(moduleName, activate) { // no prototype.
// you have to input string of function name
const func = window[moduleName];
if (typeof func == "function" && activate["activate"] == true)
func();
else
console.log("Invaild module");
}
//annotation configure.
function init(){
anno.makeAnnotatable(document.getElementById('preview'));
anno.addPlugin('autoSelector', { activate: true });
anno.addUIModule('changeLabelBoxUI',{ activate: true });
anno.addHandler('onAnnotationCreated', function(annotation){
//console.log(annotation.text);
getData(annotation);
});
anno.addHandler('onAnnotationUpdated', function(annotation){
deleteData(annotation);
getData(annotation);
});
};
/* delete annotation data */
function deleteData(annotation){
text = annotation.text
sourceImage = annotation.src;
geometry = annotation.shapes[0].geometry;
name = sourceImage.split("/");
url = deljsonPath + name[name.length - 1].split(".")[0] + ".json";
const delparm = delete_json_parm(url);
$.getJSON(delparm);
}
/* get annotation data */
function getData(annotation){
text = $("#selectTagName option:checked").text();
annotation.text = text;
sourceImage = annotation.src;
geometry = annotation.shapes[0].geometry; // annotation shanpes is array form.
// and you want to get the geometry, must be toget previous row.
changeJson(text, sourceImage, geometry);
};
/* add gemotry to json or chnage */
function changeJson(text, sourceImage, geometry){
// get TagName from removed blank string.
removeToLeftBracket = text.split('[')[1];
removeToRightBracket = removeToLeftBracket.split(']')[0];
const tagName = removeBlank(removeToRightBracket); // renaming
var annotationInfo = new Object();
annotationInfo.tag = tagName;
annotationInfo.timeStamp = new Date().getTime();
annotationInfo.anno = geometry;
annotationInfo.imageLocation = sourceImage;
var name = sourceImage.split("/");
console.log(name[name.length-1].split(".")[0]);
var toJson = JSON.stringify(annotationInfo);
var addJson = addJsonData(toJson, name[name.length-1].split(".")[0]);
}
/* For create json file, this function post for php */
function addJsonData(toJson, name){
var req = new XMLHttpRequest();
// POST send
const addjson = add_json_parm(toJson, name);
$.ajax(addjson);
}
|
import { handleActions } from 'redux-actions'
import {
ADD_TO_CART,
REDUCE_FROM_CART,
} from 'actions/cart'
const cache = localStorage.getItem('cache_cart');
const initialState = cache ?
JSON.parse(cache) :
{
products: {},
total: 0,
};
export const handlers = {
REMOVE_FROM_CART: (state, action) => {
const {
productId,
} = action;
const product = state.products[productId];
if (!product) return state;
const newProducts = Object.assign({}, state.products)
const count = newProducts[productId];
delete newProducts[productId];
return Object.assign({}, state, {
products: newProducts,
total: state.total - count,
})
},
DECREASE_FROM_CART: (state, action) => {
const {
productId,
} = action;
const product = state.products[productId];
if (!product) return state;
const newProducts = Object.assign({}, state.products, {
[productId]: product - 1,
})
return Object.assign({}, state, {
products: newProducts,
total: state.total - 1,
})
},
ADD_TO_CART: (state, action) => {
const {
productId,
} = action;
const product = state.products[productId];
if (product) {
const newProducts = Object.assign({}, state.products, {
[productId]: product + 1,
})
return Object.assign({}, state, {
products: newProducts,
total: state.total + 1,
})
}
else {
const newProducts = Object.assign({}, state.products, {
[productId]: 1,
})
return Object.assign({}, state, {
products: newProducts,
total: state.total + 1,
})
}
},
}
export default handleActions(handlers, initialState);
|
import React from 'react';
import './styles.css';
export default function FilmCard({ film }) {
const { title, rating } = film;
return (
<div className="film-card">
{title}
{rating}
</div>
);
}
|
const config = require("config");
const express = require("express");
const Users = require("../../services/users");
const router = express.Router();
const jwt = require("jsonwebtoken");
const Joi = require("joi");
router.post("/login", (req, res) => {
console.log(req.body);
const { error } = validateLogin(req.body);
if (error) return res.status(400).send(error.details[0].message);
const username = Users.some(user => user.username === req.body.username);
if (!username) return res.status(400).send("invalid username");
const password = Users.some(
password => password.password === req.body.password
);
if (!password) return res.status(400).send("invalid password");
const user = Users.find(user => user.username === req.body.username);
const token = jwt.sign({ user }, config.get("jwtPrivateKey"), {
expiresIn: 86400
});
console.log(token);
res
.header("x-auth-token", token)
.header("access-control-expose-headers", "x-auth-token")
.status(200)
.send({ auth: true, token });
});
function validateLogin(login) {
const schema = {
username: Joi.string().required(),
password: Joi.string().required()
};
return Joi.validate(login, schema);
}
module.exports = router;
|
import React from 'react';
import 'antd/dist/antd.css';
import '../Components/DashboardComponents/index1.css';
import '../Components/DashboardComponents/Dashboard/Dashboard.css';
import { Layout } from 'antd';
import {
MenuFoldOutlined,
} from '@ant-design/icons';
import MediaQuery from "react-responsive";
import { useGlobalState } from '../globalStateContext';
const { Header } = Layout;
export default function HeaderComponent () {
const [{collapsed1}, setGlobalState] = useGlobalState()
const onCollapse = () => {
setGlobalState({collapsed1: !collapsed1})
}
return (
<>
<MediaQuery minDeviceWidth = {481}>
<Header className="site-layout-background" style={{ fontWeight: "bold"}}>
<img src = {require("../Assets/Images/Rectangle.png")} alt = "none" style = {{display: "inline", marginLeft: "-30px"}}/>
<div style = {{display: "flex", flexDirection: "column", alignItems: "baseline"}}>
<p className = "class" style = {{marginTop: "-47px", marginLeft: "20px"}}>Credits</p>
<p className = "class" style = {{marginTop: "-10px", marginLeft: "20px"}}>Remaining</p>
</div>
<p className = "one">1</p>
<MediaQuery minDeviceWidth = {575}>
<p className = "MyAccount" style = {{marginTop: "-35px", marginRight: "20px"}}>My Account</p>
</MediaQuery>
{collapsed1 === true ?
<MediaQuery maxDeviceWidth = {574}>
<i className="fas fa-user-alt" style = {{float: "right", marginTop: "-40px", marginRight: "20px"}}></i>
</MediaQuery>
:
collapsed1 === false ?
<MediaQuery minDeviceWidth = {500} maxDeviceWidth = {574}>
<i className="fas fa-user-alt" style = {{float: "right", marginTop: "-40px", marginRight: "20px"}}></i>
</MediaQuery>
: null}
<MediaQuery minDeviceWidth = {500}>
<img src = {require("../Assets/Images/Arrow.png")} alt = "none" style = {{float: "right", marginTop: "-40px", marginRight: "-30px"}}/>
</MediaQuery>
{collapsed1 === true ?
<MediaQuery minDeviceWidth = {360} maxDeviceWidth = {574}>
<img src = {require("../Assets/Images/Arrow.png")} alt = "none" style = {{float: "right", marginTop: "-40px", marginRight: "-30px"}}/>
</MediaQuery>
: null}
</Header>
</MediaQuery>
<MediaQuery maxDeviceWidth = {480}>
<Header className="site-layout-background" style={{ fontWeight: "bold"}}>
<div>
{collapsed1 === true ?
<MenuFoldOutlined style = {{marginLeft: "-30px"}} onClick = {onCollapse}/>
: null}
<img src = {require("../Assets/Images/Rectangle.png")}
style = {collapsed1 ? {marginLeft: "10px"} : {marginLeft: "-30px"}} alt = "none"/>
</div>
<div style = {{display: "flex", flexDirection: "column", alignItems: "baseline"}}>
<p className = "class"
style = {collapsed1 ? {marginTop: "-47px", marginLeft: "35px"} : {marginTop: "-47px", marginLeft: "20px"}}>Credits</p>
<p className = "class" style = {collapsed1 ? {marginTop: "-10px", marginLeft: "35px"} : {marginTop: "-10px", marginLeft: "20px"}}>Remaining</p>
</div>
{collapsed1 === true ?
<p className = {collapsed1 ? "collapsed-one" : "one"}>1</p>
: null}
<MediaQuery minDeviceWidth = {575}>
<p className = "MyAccount" style = {{marginTop: "-35px", marginRight: "20px"}}>My Account</p>
</MediaQuery>
{collapsed1 === true ?
<MediaQuery maxDeviceWidth = {574}>
<i className="fas fa-user-alt" style = {{float: "right", marginTop: "-40px", marginRight: "20px"}}></i>
</MediaQuery>
:
collapsed1 === false ?
<MediaQuery minDeviceWidth = {500} maxDeviceWidth = {574}>
<i className="fas fa-user-alt" style = {{float: "right", marginTop: "-40px", marginRight: "20px"}}></i>
</MediaQuery>
: null}
<MediaQuery minDeviceWidth = {500}>
<img src = {require("../Assets/Images/Arrow.png")} alt = "none" style = {{float: "right", marginTop: "-40px", marginRight: "-30px"}}/>
</MediaQuery>
{collapsed1 === true ?
<MediaQuery minDeviceWidth = {360} maxDeviceWidth = {574}>
<img src = {require("../Assets/Images/Arrow.png")} alt = "none" style = {{float: "right", marginTop: "-40px", marginRight: "-30px"}}/>
</MediaQuery>
: null}
</Header>
</MediaQuery>
</>
);
}
|
window.JSON = window.JSON || require('json3');
/**
* A User Data Loader API that can load user data from any provider using the {@link UserDataProvider.js}
* API to expose user data.
*
* This function has a prototype that exposes two methods for loading user data:
* <li>loadUserData(request) - get user data from a single provider</li>
* <li>loadAllUserData(request) - get user data from a collection of providers in parallel</li>
*
* Example usage:
* <pre><code>
* var udl =new UserDataLoader().loadUserData({
* url: 'http://bidder.com/csud/userDataProvider.html',
* timeout: 75,
* responseHandler: function(error, result){
* if(error){
* throw new Error('Could not get user data from bidder:' + error);
* }
* var bidderUserId = result.id;
* ...
* }
* });
* </code></pre>
*
* <pre><code>
* var udl = new UserDataLoader().loadAllUserData({
* timeout: 100,
* partners: {
* 'dbm': { url: '//dbm.com/csud/userDataProvider.html' },
* 'iponweb': { url: '//bidswitch.com/csud/udp.html'}
* },
* responseHandler: function(error, results){
* if(error){
* throw new Error('Could not get user data from any partners:' + error);
* }
* if(!results['dbm'].error){
* var dbmUserData = results['dbm'].result,
* dbmUserId = dbmUserData.id;
* ...
* }
* ...
* }
* });
* </code></pre>
*
* @constructor
*/
var UserDataLoader = function UserDataLoader(){
/* initialize a collection of iframes used for user data requests at any moment in time */
this.iframes = {};
/* initialize any relevant listensers */
this.init();
};
/**
* A global counter used for generating message identifiers
*/
UserDataLoader.counter = 0;
UserDataLoader.prototype = {
/**
* Handle a user data response payload by
* <li>invoking the requested response handler</li>
* <li>clearing any set timeouts for request</li>
* <li>removing iframe related to request from iframes object</li>
* <li>removing iframe related to request from the DOM</li>
*
* @param {Object} payload object - must contain an "id" property and either a "result" or "error"
*/
handleResponse: function handleResponse(payload){
if(payload && payload.id){
var iframe = this.iframes[payload.id];
if(iframe){
try{
iframe.handleResponse(payload.error,payload.result);
}catch(clientHandlerExecutionError){
/*ignore*/
}
try{
clearTimeout(iframe.timeoutFn);
}catch(timeoutClearError){
/* ignore */
}
delete this.iframes[payload.id];
this.removeDomElement(iframe);
}
}
},
/**
* Initialize any relevant event listeners
*/
init: function init(){
var me = this;
if(me.hasPostMessage()){
me.windowEventListener = function(event) {
try{
me.handleResponse(JSON.parse(event.data));
}catch(handlerError){
/*ignore*/
}
};
if(window.addEventListener){
window.addEventListener('message', me.windowEventListener);
}else{
window.attachEvent('onmessage', me.windowEventListener);
}
}
},
/**
* Check whether browser has window.postMessage support
* @returns {Boolean} true if browser has window.postMessage support
*/
hasPostMessage: function hasPostMessage(){
return window.postMessage ? true: false;
},
/**
* Load user data from a single csud partner. Expects a request object that contains the following
* properties:
* <li>url {string}
* - mandatory URL of html page running {@link UserDataProvider.js}</li>
* <li>responseHandler {function}
* - mandatory node-compatible response handler function (function(error,result)); results
* are Objects containing a mandatory "id":{string} property</li>
* <li>timeout {number}
* - optional timeout in milliseconds; timeouts will result in 'timeout' errors</li>
* <li>payload {object}
* - optional payload to send along with a user data request</li>
*
* Example usage:
* <pre><code>
* var udl = new UserDataLoader().loadUserData({
* url: 'http://bidder.com/csud/userDataProvider.html',
* timeout: 75,
* responseHandler: function(error, result){
* if(error){
* throw new Error('Could not get user data from bidder:' + error);
* }
* var bidderUserId = result.id;
* ...
* }
* });
* </code></pre>
*
* Example responseHandler result:
* <pre><code>
* {
* id: 'mandatory-user-id',
* ext: {
* opt: 'optional extra data'
* }
* }
* </code></pre>
*
* @param {object} request - a request containing url,responseHandler,timeout, and payload properties
* @return {function} this
*/
loadUserData: function loadUserData(request){
var me = this,
id = ++UserDataLoader.counter,
message = escape(JSON.stringify({
id: id,
payload: request.payload
})),
iframe = document.createElement('iframe');
iframe.style.width = '0px';
iframe.style.height = '0px';
iframe.style.display = 'none';
iframe.handleResponse = request.responseHandler;
this.iframes[id] = iframe;
if(request.timeout){
iframe.timeoutFn = setTimeout(function(){
me.handleResponse({error:'timeout',id:id});
},request.timeout);
}
iframe.src = request.url + '#' + message;
if(!this.hasPostMessage()){
var onload = function () {
try{
if(iframe.contentWindow.name){
me.handleResponse(JSON.parse(iframe.contentWindow.name));
}
}catch(couldNotAccessWindowName){
/* ignore */
iframe.onload = onload;
}
};
var onerror = function () {
/* ignore */
/* TODO: consider failfast */
};
iframe.onload = onload;
iframe.onerror = onerror;
if(iframe.attachEvent){
iframe.attachEvent('onload',onload);
iframe.attachEvent('onerror',onerror);
}
}
document.body.appendChild(iframe);
return this;
},
/**
* Load user data from a multiple csud partners. Expects a request object that contains the following
* properties:
* <li>timeout {number}
* - mandatory timeout in milliseconds; timeouts will result in 'timeout' errors</li>
* <li>partners {object}
* - mandatory object containing partner objects with url {string}, optional timeout {number},
* optional payload {object} properties (e.g. {url:'http://...',timeout:130,payload:{}})
* timeouts specified by-partner take priority over global timeout for all requests.
* <li>responseHandler {function}
* - mandatory node-compatible response handler function (function(error,result)); results
* is an object with a 'partnerResponses' property which is an object with keys representing partner
* names from the partners object and values containing either "result" Object properties
* or "error" strings</li>
*
* Example usage:
* <pre><code>
* var udl = new UserDataLoader().loadAllUserData({
* timeout: 100,
* partners: {
* 'dbm': { url: '//dbm.com/csud/userDataProvider.html' },
* 'iponweb': { url: '//bidswitch.com/csud/udp.html'}
* },
* responseHandler: function(error, results){
* if(error){
* throw new Error('Could not get user data from any partners:' + error);
* }
* var totalResponseTime = results.rtime,
* partnerResponses = results.partnerResponses;
*
* if(!partnerResponses['dbm'].error){
* var dbmUserData = partnerResponses['dbm'].result,
* dbmUserId = dbmUserData.id;
* ...
* }
* ...
* }
* });
* </code></pre>
*
* Example responseHandler results:
* <pre><code>
* {
* partnerResponses: {
* 'test-dsp': {
* result: {
* id: 'test-dsp-user-id',
* ext: {}
* },
* rtime: 14
* },
* 'another-partner': {
* error: 'timeout',
* rtime: 25
* }
* },
* rtime: 26
* }
* </code></pre>
*
* @param {object} request - a request containing timeout,responseHandler, and partner properties
* @return {function} this
*/
loadAllUserData: function loadAllUserData(request){
var results = {},
requestStartMs = new Date().getTime(),
outstandingRequests = 1,
completionHandler = function(){
if(--outstandingRequests === 0){
/* all requests completed */
request.responseHandler(undefined,{
rtime: new Date().getTime() - requestStartMs,
partnerResponses: results
});
}
},
createHandler = function(partnerId){
return function(error,result){
var partnerResult = {};
if(error){
partnerResult.error = error;
}
if(result){
partnerResult.result = result;
}
partnerResult.rtime = new Date().getTime() - requestStartMs;
results[partnerId] = partnerResult;
completionHandler();
};
};
for(var partnerId in request.partners){
var partnerConfig = request.partners[partnerId];
outstandingRequests++;
this.loadUserData({
url: partnerConfig.url,
timeout: partnerConfig.timeout || request.timeout,
payload: partnerConfig.payload,
responseHandler: createHandler(partnerId)
});
}
completionHandler();
},
/**
* Close this UserDataLoader, cleaning up any iframes and event listeners created during
* the UseerDataLoader's lifetime
*/
close: function close(){
if(this.windowEventListener){
if(window.removeEventListener){
window.removeEventListener('message', this.windowEventListener);
}else{
window.detachEvent('message', this.windowEventListener);
}
}
for(var id in this.iframes){
var iframe = this.iframes[id];
delete this.iframes[id];
this.removeDomElement(iframe);
}
},
/**
* Remove a DOM element from the document
*/
removeDomElement: function removeDomElement(domElement){
try{
if(domElement && domElement.parentNode){
domElement.parentNode.removeChild(domElement);
}
}catch(domRemovalError){
/* ignore */
}
}
};
module.exports = UserDataLoader;
|
const gulp = require('gulp');
const path = require('path');
const os = require('os');
const del = require('del');
const packager = require('electron-packager');
const zip = require('gulp-zip');
const { argv } = require('yargs');
const packageJson = require('../package.json');
const config = require('./config');
const platform = argv.platform || os.platform();
const outputFolder = path.join(config.outputPackagePath, platform);
module.exports = function package(callback) {
const toDelete = [
path.join(outputFolder, '**', '*')
];
del(toDelete)
.then(() => {
const productName = packageJson.productName;
const appVersion = packageJson.version;
const electronVersion = packageJson.devDependencies['electron'].replace('^', '');
let arch;
let icon;
if(platform === 'darwin') {
arch = 'x64';
icon = 'resources/icon.icns';
} else if (platform === 'win32') {
arch = 'ia32';
icon = 'resources/icon.ico';
} else {
throw new Error(`Platform not supported: ${platform}`);
}
const options = {
asar: true,
dir: '.',
name: productName,
overwrite: true,
out: outputFolder,
platform,
arch,
electronVersion,
prune: true,
icon,
ignore: [
'/src($|/)',
'/tasks($|/)',
'/style($|/)',
'/package($|/)',
'/resources($|/)'
]
};
packager(options, (error, appPaths) => {
if(error) {
console.log('electron-packager failed with the following error:');
console.log(error);
process.exit(1);
} else {
const appPath = appPaths[0];
console.log(`electron-packager finished packaging ${productName}`);
console.log(`App path: ${appPath}`);
console.log(`Platform: ${platform}`);
console.log(`Arch: ${arch}`);
gulp.src(path.join(appPath, '**', '*'))
.pipe(zip(`${productName}-v${appVersion}-${platform}-ev${electronVersion}.zip`))
.pipe(gulp.dest(outputFolder))
.on('error', (gulpErr) => callback(gulpErr))
.on('end', () => callback());
}
});
})
.catch(error => callback(error));
};
|
module.exports.formulario_inclusao_noticia = function(app, req, res){
res.render('admin/form_add_noticia', {validacao : {}, noticia : {}});
}
module.exports.noticias_salvar = function(app, req, res){
var noticia = req.body;
//res.send(noticias);
req.assert('titulo','O Titulo é obrigatorio').notEmpty();
req.assert('resumo','O resumo é obrigatorio').notEmpty();
req.assert('resumo','O resumo deve conter entre 10 e 100').len(10,100);
req.assert('autor', 'O autor é obrigatorio').notEmpty();
req.assert('data_noticia','A data é obrigatorio').notEmpty().isDate({fomrat: 'YYYY-MM-DD'});
req.assert('noticia', 'A noticia é obrigatorio').notEmpty();
var erros = req.validationErrors();
if (erros) {
console.log(erros);
res.render('admin/form_add_noticia', {validacao : erros , noticia: noticia});
return;
}
//Conexao com banco de dados
var connection = app.config.dbConnection();
//Implementar o model
var noticiasModel = new app.app.models.NoticiasDAO(connection);
//Salvar a noticia
noticiasModel.salvarNoticia(noticia, function(error, result){
//res.render("noticias/noticias", {noticias : result});
res.redirect('/noticias');
});
}
|
'use strict';
/**
* This project is written in the spirit of literate programming.
*/
var dir = {
/**
* Documentation is handwritten.
*/
doc: 'doc/',
/**
* Sources are generated from the documentation.
*/
src: 'src/',
/**
* Vanilla HTML, CSS and JavaScript are built from sources.
*/
build: 'dist/',
};
var files = {
setup: [
'setup.sh',
],
config: [
'.writ.config.js',
'.writ.gulpfile.js',
'gulpfile.js',
],
doc: [
dir.doc +'*.md',
],
css: [
dir.src +'*.scss',
],
js: [
dir.src +'*.js',
],
deps: [
'node_modules/hyper-text-slider/lib/**/*',
],
};
module.exports = {
dir: dir,
files: files,
};
/*
eslint-env node
*/
|
(function() {
angular.module('itibrasil')
.controller('EditarPerfilController', EditarPerfilController);
function EditarPerfilController($state, Notify, Loading, UsuarioService) {
var vm = this;
// public
vm.alterarSenha = function alterarSenha(senhaAtual, novaSenha) {
var usuario = JSON.parse(localStorage.getItem('usuario'));
Loading.show();
UsuarioService.senha.alterar({
senhaAtual: senhaAtual,
novaSenha: novaSenha,
id: usuario.id
}).then(function exibirSucesso(retorno) {
if (retorno.status) {
Notify.show('Senha alterada com sucesso!');
} else {
Notify.show(retorno.data.mensagem);
}
}, function erroAoLogar() {
Notify.show('Ocorreu um erro ao tentar alterar a senha!');
})
.finally(Loading.hide);
};
}
})();
|
import 'angular';
import './ors-star/ors-star.js';
import './ors-route/ors-route.js';
import 'angular/angular-csp.css';
import './style.scss';
const app = angular.module('main', ['ors-star', 'ors-route']);
app.directive('orsHeader', function () {
return {
restrict: 'E',
templateUrl: 'tmpl/ors-header.html'
};
});
app.directive('orsBody', function () {
return {
restrict: 'E',
templateUrl: 'tmpl/ors-body.html'
};
});
app.directive('orsFooter', function () {
return {
restrict: 'E',
templateUrl: 'tmpl/ors-footer.html'
};
});
|
import { grey4, blue3, alert } from '../private/palette';
export default {
'.standard': { borderColor: grey4 },
'.formAccent': { borderColor: blue3 },
'.critical': { borderColor: alert }
};
|
'use strict'
class S3 {
generateTags (params, operation, response) {
const tags = {}
if (!params || !params.Bucket) return tags
return Object.assign(tags, {
'resource.name': `${operation} ${params.Bucket}`,
'aws.s3.bucket_name': params.Bucket
})
}
}
module.exports = S3
|
var moment = require('moment')
, crypto = require('crypto');
var getExpiryTime = function () {
var _date = new Date((new Date()).getTime() + 100*60000);
return moment.utc(_date).toISOString();
};
module.exports = function (app) {
app.server.get("/s3/policy", function(req, res, next){
var mode = 'public-read';
var date = new Date();
var config =
{
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION,
bucket: process.env.AWS_BUCKET
};
var s3Policy = {
'expiration': getExpiryTime(),
'conditions': [
['starts-with', '$key', req.query.folder],
{ 'bucket': config.bucket },
{ 'acl': mode },
['starts-with', '$Content-Type', req.query.type],
{ 'success_action_status': '201' }
]
};
// stringify and encode the policy
var stringPolicy = JSON.stringify(s3Policy);
var base64Policy = new Buffer(stringPolicy, 'utf-8').toString('base64');
// sign the base64 encoded policy
var signature = crypto.createHmac('sha1', config.secretAccessKey)
.update(new Buffer(base64Policy, 'utf-8')).digest('base64');
// build the results object
var s3Credentials = {
s3Policy: base64Policy,
s3Signature: signature,
AWSAccessKeyId: config.accessKeyId
};
res.send(200, s3Credentials);
});
}
|
'use strict'
const logger = require('./logger')
module.exports = {
splitX,
delay,
resolveable,
sortById,
sortByDate,
sortBySemver,
shortDateString,
retry,
times,
arrayFrom,
}
/**
* @template T
* @type { (times: number, waitSeconds: number, name: string, fn: () => Promise<T>) => Promise<T>}
**/
async function retry(times, waitSeconds, name, fn) {
try {
return await fn()
} catch (err) {
if (times === 0) {
logger.log(`error ${name}, exceeded retries: ${err}`)
throw err
}
logger.log(`error ${name}, retry in ${waitSeconds} seconds, ${times} retries left: ${err}`)
await delay(waitSeconds * 1000)
return await retry(times - 1, waitSeconds, name, fn)
}
}
/** @type { (spec: string) => [number, number] | null } */
function splitX(spec) {
spec = spec.replace(/\s+/g, '')
spec = spec.replace(/GB$/i, '')
const match = spec.match(/^(\d+)x(\d+)$/)
if (match == null) return null
const n1 = parseInt(match[1])
const n2 = parseInt(match[2])
return [n1, n2]
}
/** @type { (ms: number) => Promise<void> } */
async function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
/** @type { () => { promise: Promise<any>; resolve: (value: any) => void; reject: (reason: any) => void } } */
function resolveable() {
let resolve, reject
const promise = new Promise((r, e) => { resolve = r; reject = e })
return { promise, resolve, reject }
}
/** @type { (a: { id: string }, b: { id: string }) => number } */
function sortById(a, b) {
return a.id.localeCompare(b.id)
}
/** @type { (a: { date: string }, b: { date: string }) => number } */
function sortByDate(a, b) {
return a.date.localeCompare(b.date)
}
/** @type { (a: string, b: string) => number } */
function sortBySemver(a, b) {
if (a === b) return 0
const pattern = /^(\d+)\.(\d+)\.(\d+)(-.*)?$/
const [, majA, minA, patA, bldA = ''] = a.match(pattern)
const [, majB, minB, patB, bldB = ''] = b.match(pattern)
const majAn = parseInt(majA, 10)
const minAn = parseInt(minA, 10)
const patAn = parseInt(patA, 10)
const majBn = parseInt(majB, 10)
const minBn = parseInt(minB, 10)
const patBn = parseInt(patB, 10)
if (majAn > majBn) return 1
if (majAn < majBn) return -1
if (minAn > minBn) return 1
if (minAn < minBn) return -1
if (patAn > patBn) return 1
if (patAn < patBn) return -1
return bldA.localeCompare(bldB)
}
/** @type { (date: Date) => string } */
function shortDateString(date) {
return date.toISOString()
.substr(2,17) // yy-mm-ddThh:mm:ss
.replace(/-/g,'') // yymmddThh:mm:ss
.replace(/:/g,'') // yymmddThhmmss
.replace('T','-') // yymmdd-hhmmss
}
/** @type { (n: number, fn: (n?: number) => void) => void } */
function times(n, fn) {
for (let i = 0; i < n; i ++) {
fn(i)
}
}
/**
* @template O
* @type { (n: number, fn: (n: number) => O) => O[] }
*/
function arrayFrom(n, fn) {
/** @type { O[] } */
const result = []
times(n, (i) => {
result.push(fn(i))
})
return result
}
// @ts-ignore
if (require.main === module) test()
function test() {
console.log(`shortDateString(): ${shortDateString(new Date())}`)
const splitXtests = ['1x1', '2 x 2', '3 x 3GB', ' 4 x 4 gb ']
for (const splitXtest of splitXtests) {
console.log(`splitX("${splitXtest}"): ${splitX(splitXtest).join(',')}`)
}
}
|
import React from 'react'
import { Header, Footer } from 'blk'
import Intro from './Intro.jsx'
import ModularScaleDemo from './ModularScaleDemo.jsx'
import GridDemo from './GridDemo.jsx'
import TypographyDemo from './TypographyDemo.jsx'
import NestedGrid from './NestedGrid.jsx'
import RatiosDemo from './RatiosDemo.jsx'
import CellDemo from './CellDemo.jsx'
import Social from './Social.jsx'
import Cta from './Cta.jsx'
import css from './base.css'
class App extends React.Component {
constructor () {
super ()
this.state = {
base: 16,
}
this.handleChange = this.handleChange.bind(this)
}
handleChange (e) {
let state = this.state
state[e.target.name] = parseFloat(e.target.value)
this.setState(state)
}
render () {
let props = this.props
let state = this.state
return (
<div>
<Header {...props} />
<Social {...props} />
<Intro />
<ModularScaleDemo {...state} />
<TypographyDemo {...props} {...state} />
<NestedGrid {...props} {...state} />
<RatiosDemo {...props} {...state} />
<CellDemo />
<Cta />
<Footer {...props} />
</div>
)
}
}
export default App
|
import NewRoomForm from './../components/NewRoomForm/NewRoomForm';
const NewRoom = () => {
return <NewRoomForm />;
};
export default NewRoom;
|
"use strict";
/// <reference path="../../scene/ComponentConfig.d.ts" />
Object.defineProperty(exports, "__esModule", { value: true });
const LightConfig_1 = require("./LightConfig");
SupCore.system.registerPlugin("componentConfigs", "Light", LightConfig_1.default);
|
import Home from "@containers/Home.vue";
import JoinRoom from "@containers/JoinRoom.vue";
import Login from "@containers/Login.vue";
import Register from "@containers/Register.vue";
import Questions from "@containers/Questions.vue";
import Quizzes from "@containers/Quizzes.vue";
import QuizzesStart from "@containers/QuizzesStart.vue";
import NotFound from "@containers/NotFound.vue";
import { createRouter, createWebHistory } from "vue-router";
const routes = [
{
path: "/",
name: "Home",
component: Home,
},
{
path: "/quiz/:quiz_code/:player_username",
name: "JoinRoom",
component: JoinRoom,
props: true,
},
{
path: "/admin",
name: "Admin",
redirect: { name: "Quizzes" },
},
{
path: "/auth",
name: "Authentication",
redirect: { name: "Login" },
},
{
path: "/auth/login",
name: "Login",
component: Login,
},
{
path: "/auth/register",
name: "Register",
component: Register,
},
{
path: "/admin/quizzes",
name: "Quizzes",
component: Quizzes,
},
{
path: "/admin/quizzes/:quiz_id",
name: "Questions",
component: Questions,
props: true,
},
{
path: "/admin/quizzes/:quiz_code/start",
name: "Quizzes-Start",
component: QuizzesStart,
props: true,
},
{ path: "/:catchAll(.*)", component: NotFound },
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
export default router;
|
db.vendas.aggregate([
{$match:{
status:{$in:["EM SEPARACAO","ENTREGUE"]}
}},
{$group:{
_id:"$clienteId",
valorTotal:{
$sum:"$valorTotal"
}
}},
{$sort:{"valorTotal": -1}},
{$limit:5}
])
|
fis.config.merge({
namespace: 'spa'
});
|
const linkifyIt = require("linkify-it")();
const linkifyText = (text) => {
let linkifiedText = text;
if (linkifyIt.test(text)) {
linkifyIt.match(text).forEach(({ url }) => {
linkifiedText = text.replace(
url,
`<a href="${url}" target="_blank">${url}</a>`
);
});
}
return linkifiedText;
};
export default linkifyText;
|
import React from 'react'
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faGithub} from "@fortawesome/free-brands-svg-icons";
import Image from'../project.jpg'
const Project=(props)=>{
const {project}=props
const card=project?(
project.map(proj=>{
return(
<div className="col s9 l6" key={proj.id}>
<div className="card">
<div className="card-image">
<img src={Image}/>
<span className="card-title">{proj.name}</span>
</div>
<div className="card-content">
<p>{proj.description}</p>
</div>
<div className="card-action">
<a href="https://www.github.com">
<FontAwesomeIcon icon={faGithub} size="2x"/>
</a>
</div>
</div>
</div>
)
}
)
)
:(<div>I have no Project yet </div>);
return(
<div className="section-inner">
<h1 className="blue-grey-text ">Projects</h1>
<div className="row">
{card}
</div>
</div>
)
}
export default Project;
|
var bio = {
"name" : "Hamish Williams",
"role" : "Graphic Designer",
"welcomeMessage" : "Swag normcore Helvetica plaid messenger bag. Vinyl odd Future narwhal. Sustainable Pinterest PBR&B Tumblr. Seitan polaroid, VHS cliche literally hella flexitarian Tumblr. Vinyl fingerstache DIY, cred kale chips seitan 90's street art.",
"contacts" : [
{
"mobile" : "123-456-789",
"email" : "hello@hamishw.com",
"location" : "Sydney, Australia",
"github" : "HamishMW",
"twitter" : "@hamishMW"
}
],
"skills" : ["Hashtags", "Knitted Sweaters", "Moustache Waxing", "Craft Beer", "Tumblr Posting"],
"pic" : "images/photo.jpg"
},
work = {
"jobs" : [
{
"employer" : "Design Studio",
"title" : "Graphic Designer",
"location" : "Hamilton, New Zealand",
"dates" : "2013",
"description" : "Swag normcore Helvetica plaid messenger bag. Vinyl sartorial plaid pop-up, Pitchfork cliche chambray meggings small batch shabby chic American Apparel drinking vinegar trust fund umami raw denim. Odd Future narwhal skateboard"
},
{
"employer" : "Tech Startup",
"title" : "UX and Interaction Designer",
"location" : "Sydney, Australia",
"dates" : "2014-2015",
"description" : "Blue Bottle cred synth, meditation artisan chambray beard salvia yr meh lumbersexual gastropub chillwave. Occupy Marfa health goth, Schlitz gastropub kogi gluten-free High Life. Synth wayfarers meditation locavore butcher."
}
]
},
projects = {
"projects" : [
{
"title" : "Wayfarers Banjo Organic",
"dates" : "1998-2008",
"description" : "Schlitz gastropub kogi gluten-free High Life. Synth wayfarers meditation locavore butcher. Blue Bottle cred synth, meditation artisan chambray beard salvia yr meh lumbersexual gastropub chillwave. Occupy Marfa health goth, Schlitz gastropub kogi gluten-free High Life. Synth wayfarers meditation locavore butcher.",
"images" : [
"images/wayfarer.jpg",
]
},
{
"title" : "Occupy Umami Stumptown",
"dates" : "2012",
"description" : "Schlitz gastropub kogi gluten-free High Life. Synth wayfarers meditation locavore butcher. Blue Bottle cred synth, meditation artisan chambray beard salvia yr meh lumbersexual gastropub chillwave. Occupy Marfa health goth, Schlitz gastropub kogi gluten-free High Life. Synth wayfarers meditation locavore butcher.",
"images" : [
"images/stumptown.jpg",
]
}
]
},
education = {
"schools" : [
{
"name" : "Sapporo University",
"location" : "Sapporo, Japan",
"degree" : "Degree Name",
"majors" : ["Art History", "Architecture"],
"dates" : "2010",
"degree" : "Bachelor of Architectural Design"
},
{
"name" : "University of Waikato",
"location" : "Hamilton, New Zealand",
"degree" : "Degree Name",
"majors" : ["Graphic Design", "Interaction Design"],
"dates" : "2012",
"degree" : "Bachelor of Computer Graphic Design"
}
],
"onlineCourses" : [
{
"title" : "Front End Web Developer Nanodegree",
"school" : "Udacity",
"dates" : "2015",
"url" : "https://www.udacity.com/course/nd001"
}
]
};
bio.display = function() {
var formattedName = HTMLheaderName.replace("%data%", bio.name),
formattedRole = HTMLheaderRole.replace("%data%", bio.role),
formattedPic = HTMLbioPic.replace("%data%", bio.pic),
formattedWelcome = HTMLWelcomeMsg.replace("%data%", bio.welcomeMessage);
$("#header").prepend(formattedRole);
$("#header").prepend(formattedName);
$("#header").prepend(formattedPic);
$("#header").append(formattedWelcome);
var formattedLocation = HTMLlocation.replace("%data%", bio.contacts[0].location),
formattedGithub = HTMLgithub.replace("%data%", bio.contacts[0].github),
formattedMobile = HTMLmobile.replace("%data%", bio.contacts[0].mobile),
formattedEmail = HTMLemail.replace("%data%", bio.contacts[0].email),
formattedTwitter = HTMLtwitter.replace("%data%", bio.contacts[0].twitter);
$("#topContacts").append(formattedMobile);
$("#topContacts").append(formattedLocation);
$("#topContacts").append(formattedGithub);
$("#topContacts").append(formattedTwitter);
$("#topContacts").append(formattedEmail);
$("#footerContacts").append(formattedMobile);
$("#footerContacts").append(formattedLocation);
$("#footerContacts").append(formattedGithub);
$("#footerContacts").append(formattedTwitter);
$("#footerContacts").append(formattedEmail);
if (bio.skills.length > 0) {
$("#header").append(HTMLskillsStart);
for (var skill in bio.skills) {
var formattedSkill = HTMLskills.replace("%data%", bio.skills[skill]);
$("#skills").append(formattedSkill);
}
}
};
bio.display();
work.display = function() {
for (var job in work.jobs) {
$("#workExperience").append(HTMLworkStart);
var formattedEmployer = HTMLworkEmployer.replace("%data%", work.jobs[job].employer),
formattedTitle = HTMLworkTitle.replace("%data%", work.jobs[job].title),
formattedLocation = HTMLworkLocation.replace("%data%", work.jobs[job].location);
formattedDates = HTMLworkDates.replace("%data%", work.jobs[job].dates),
formattedDescription = HTMLworkDescription.replace("%data%", work.jobs[job].description);
$(".work-entry:last").append(formattedEmployer + formattedTitle);
$(".work-entry:last").append(formattedLocation);
$(".work-entry:last").append(formattedDates);
$(".work-entry:last").append(formattedDescription);
}
};
work.display();
projects.display = function() {
for (var project in projects.projects) {
$("#projects").append(HTMLprojectStart);
var formattedTitle = HTMLprojectTitle.replace("%data%", projects.projects[project].title),
formattedDates = HTMLprojectDates.replace("%data%", projects.projects[project].dates),
formattedDescription = HTMLprojectDescription.replace("%data%", projects.projects[project].description);
for (var image in projects.projects[project].images) {
var formattedImage = HTMLprojectImage.replace("%data%", projects.projects[project].images[image]);
$(".project-entry:last").append(formattedImage);
}
$(".project-entry:last").append(formattedTitle);
$(".project-entry:last").append(formattedDates);
$(".project-entry:last").append(formattedDescription);
}
};
projects.display();
education.display = function() {
for (var school in education.schools) {
$("#education").append(HTMLschoolStart);
var formattedName = HTMLschoolName.replace("%data%", education.schools[school].name),
formattedDates = HTMLschoolDates.replace("%data%", education.schools[school].dates),
formattedLocation = HTMLschoolLocation.replace("%data%", education.schools[school].location);
formattedDegree = HTMLschoolDegree.replace("%data%", education.schools[school].degree);
$(".education-entry:last").append(formattedName);
$(".education-entry:last").append(formattedDegree);
$(".education-entry:last").append(formattedDates);
$(".education-entry:last").append(formattedLocation);
for (var major in education.schools[school].majors) {
var formattedMajor = HTMLschoolMajor.replace("%data%", education.schools[school].majors[major]);
$(".education-entry:last").append(formattedMajor);
}
}
$("#education").append(HTMLonlineClasses);
for (var course in education.onlineCourses) {
$("#education").append(HTMLschoolStart);
var formattedTitle = HTMLonlineTitle.replace("%data%", education.onlineCourses[course].title),
formattedSchool = HTMLonlineSchool.replace("%data%", education.onlineCourses[course].school),
formattedOnlineDates = HTMLonlineDates.replace("%data%", education.onlineCourses[course].dates),
formattedURL = HTMLonlineURL.replace("%data%", education.onlineCourses[course].url);
$(".education-entry:last").append(formattedTitle);
$(".education-entry:last").append(formattedSchool);
$(".education-entry:last").append(formattedOnlineDates);
$(".education-entry:last").append(formattedURL);
}
};
education.display();
$("#mapDiv").append(googleMap);
/*header particle code from https://github.com/VincentGarreau/particles.js/*/
particlesJS('aa_particles', {
particles: {
color: '#fff',
shape: 'circle',
opacity: 1,
size: 2.5,
size_random: true,
nb: 100,
line_linked: {
enable_auto: true,
distance: 250,
color: '#fff',
opacity: 0.5,
width: 1,
condensed_mode: {
enable: false,
rotateX: 600,
rotateY: 600
}
},
anim: {
enable: true,
speed: 2.5
}
},
interactivity: {
enable: true,
mouse: {
distance: 250
},
detect_on: 'canvas',
mode: 'grab',
line_linked: {
opacity: 0.5
},
events: {
onclick: {
push_particles: {
enable: true,
nb: 4
}
}
}
},
retina_detect: true
});
|
import CountrySelectModule from './country-select.module';
describe('countrySelect module', () => {
let $rootScope, $state, $location;
beforeEach(window.module(CountrySelectModule));
beforeEach(window.module(($provide) => {
const mock = jasmine.createSpyObj('countrySelectService',
['searchCountries', 'sendSelectedCountries']);
$provide.value('countrySelectService', mock);
}));
beforeEach(inject((_$rootScope_, _$state_, _$location_) => {
$rootScope = _$rootScope_;
$state = _$state_;
$location = _$location_;
}));
describe('Module', () => {
it('default component should be countrySelect', () => {
// Act
$location.url('/');
$rootScope.$digest();
// Assert
expect($state.current.component).toEqual('countrySelect');
});
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.