blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 3
236
| src_encoding
stringclasses 29
values | length_bytes
int64 8
7.94M
| score
float64 2.52
5.72
| int_score
int64 3
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 8
7.94M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
165f9f7dc70e9efba4358948eff67d6c49ff1351
|
JavaScript
|
shiftyfive/portfolio-site
|
/src/js/components/Typewriter.jsx
|
UTF-8
| 2,260
| 2.828125
| 3
|
[] |
no_license
|
import React from 'react';
import '../../css/typewriter.css';
import FontAwesomeIcon from '@fortawesome/react-fontawesome';
import CallToActionButton from './CallToAction';
export default class Typewriter extends React.Component {
constructor(props) {
super(props);
this.tick = this.tick.bind(this);
this.state = {
sentencesArray: [ "Im a developer.", "I love JavaScript.", "I love learning new things.", " Im a big geek"],
currentPhrase: '',
loopNumber: 0,
isDeleting: false,
interval: 150,
}
}
componentDidMount() {
setInterval(() => {
this.tick()
}, this.state.interval)
}
tick() {
const fullPhrase = this.state.sentencesArray[this.state.loopNumber]
if (this.state.currentPhrase === '' && this.state.isDeleting === true) {
this.setState((prevState) => {
return { loopNumber: prevState.loopNumber += 1, isDeleting: false, };
})
}
if (this.state.loopNumber === this.state.sentencesArray.length) {
this.setState(() => {
return { loopNumber: 0 };
})
}
if (this.state.isDeleting) {
this.setState(prevState => {
return { currentPhrase: fullPhrase.slice(0, prevState.currentPhrase.length - 1) };
})
}
if (!this.state.isDeleting){
this.setState(prevState => {
return { currentPhrase: fullPhrase.slice(0, prevState.currentPhrase.length + 1) };
})
}
if (this.state.currentPhrase.length === fullPhrase.length) {
this.setState(() => {
return {isDeleting: true,};
})
}
}
render() {
return (
<div>
<header>
<div className="title">
<h2 className="hi-message">Hello My name is Joshua</h2>
<p className="typewriter-text">{this.state.currentPhrase}<span className="cursor"></span></p>
</div>
<div className="links">
<CallToActionButton className="call-to-action-button" href="#two" text="Let's work together"/>
<p className="chevron-text">Would you like to know more?</p>
<a href="#one"><FontAwesomeIcon className="chevron" icon="chevron-down" size="3x" /></a>
</div>
</header>
</div>
)
}
}
| true
|
181f7b8ea607eedb0a1e2b19604cd66071a00b31
|
JavaScript
|
Toolpark/irma
|
/plugins/kiosk/items.js
|
UTF-8
| 4,470
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
"use strict";
require('datejs');
var path = require('path');
var fs = require('fs');
var revjsion = require('revjsion');
var uuid = require('node-uuid');
var itemIds = [];
var items = {};
var load = function () {
var filePath, data, itemFilePath, itemData, item;
filePath = path.join(exports.dataDir, 'items.json');
if (fs.existsSync(filePath)) {
data = fs.readFileSync(filePath, 'UTF-8');
itemIds = JSON.parse(data);
} else {
itemIds = [];
}
for (var i = 0; i < itemIds.length; i++) {
itemFilePath = path.join(exports.dataDir, 'item-' + itemIds[i] + '.json');
if (fs.existsSync(itemFilePath)) {
itemData = JSON.parse(fs.readFileSync(itemFilePath, 'UTF-8'));
item = new Item(itemData);
items[item.id()] = item;
}
}
};
var persist = function () {
var filePath, data, itemFilePath, itemData, item;
filePath = path.join(exports.dataDir, 'items.json');
data = JSON.stringify(itemIds, null, '\t');
fs.writeFileSync(filePath, data);
for (var i = 0; i < itemIds.length; i++) {
item = items[itemIds[i]];
if (item) {
itemFilePath = path.join(exports.dataDir, 'item-' + itemIds[i] + '.json');
fs.writeFileSync(itemFilePath, JSON.stringify(item.data(), null, '\t'));
}
}
};
var get = function (id) {
if (items[id]) { return items[id]; }
return null;
};
var create = function () {
var item = new Item({
'item' : {
'id' : uuid.v1().substr(0, 12).replace('-', '0')
},
'changes' : []
});
itemIds.push(item.id());
items[item.id()] = item;
return item;
};
var remove = function (id) {
var idx = itemIds.indexOf(id);
itemIds.splice(idx, 1);
delete items[id];
};
var all = function () {
return items;
};
var Item = function (data) {
if (typeof data !== 'undefined') {
this.setData(data);
return;
}
this._data = {
'item' : {},
'changes' : []
};
};
Item.prototype.id = function () {
if (typeof this._data.item.id === 'undefined') { return String(); }
return this._data.item.id;
};
Item.prototype.name = function () {
if (typeof this._data.item.name === 'undefined') { return String(); }
return this._data.item.name;
};
Item.prototype.description = function () {
if (typeof this._data.item.description === 'undefined') { return String(); }
return this._data.item.description;
};
Item.prototype.price = function () {
if (typeof this._data.item.price === 'undefined') { return Number(); }
return this._data.item.price;
};
Item.prototype.displayPrice = function () {
if (typeof this._data.item.displayPrice === 'undefined') { return String(); }
return this._data.item.displayPrice;
};
Item.prototype.unit = function () {
if (typeof this._data.item.unit === 'undefined') { return String(); }
return this._data.item.unit;
};
Item.prototype.ration = function () {
if (typeof this._data.item.ration === 'undefined') { return Number(); }
return this._data.item.ration;
};
Item.prototype.isBuyable = function () {
return (this._data.item.buyable === true);
};
Item.prototype.isStockable = function () {
return (this._data.item.stockable === true);
};
Item.prototype.data = function () { return this._data; };
Item.prototype.itemData = function () { return this._data.item; };
Item.prototype.setData = function (data) {
if (typeof data.item !== 'undefined' && data.changes !== 'undefined') {
this._data = data;
return;
}
this._data.item = data;
};
Item.prototype.updateData = function (data) {
if (typeof this._data.item.name !== 'undefined') {
this.saveDiff(this.itemData(), data);
}
this.setData(data);
};
Item.prototype.saveDiff = function (originalData, newData) {
var diff, changes, update, change, field;
if (typeof this._data.changes === 'undefined') this._data.changes = [];
diff = new revjsion.Diff(originalData, newData);
changes = diff.getChanges();
if (changes.length === 0) { return; }
update = {
'time' : Date.now(),
'changes' : []
};
for (var i = 0; i < changes.length; i++) {
field = changes[i].path.replace('/', '');
change = {
'field' : field,
'originalValue' : originalData[field],
'newValue' : changes[i].value
};
update.changes.push(change);
}
this._data.changes.push(update);
};
Item.prototype.changes = function () {
if (typeof this._data.changes === 'undefined') { return []; }
return this._data.changes;
};
exports.dataDir = null;
exports.Item = Item;
exports.load = load;
exports.persist = persist;
exports.get = get;
exports.create = create;
exports.remove = remove;
exports.all = all;
| true
|
44a8a82d5ceab180a0bc0fcc8a13e9afaf49ff34
|
JavaScript
|
klmanage/expressAppTemplate
|
/routes/topics.js
|
UTF-8
| 1,039
| 2.578125
| 3
|
[] |
no_license
|
var express = require('express');
var router = express.Router();
router.get('/',function(req,res){
res.render('topics');
});
router.get('/serverside',function(req,res){
res.render('serverside');
});
router.get('/javascript',function(req,res){
//do some data based stuff here and pass it to the template.
res.render('items/javascript',{myValue:'my new value'});
});
router.get('/autocomplete',function(req,res){
//present a page with an autocomplete input element for search
res.render('items/autocomplete');
});
router.get('/dynamicdata/:name',function(req,res){
//I want to receive some data in the request, process it and return some
//dynamic data to the client
var incomingValue = req.params.name.toUpperCase();
var qstring = req.query.age;
console.log(incomingValue);
res.render('items/dynamic-data',{nameParam:incomingValue, age:qstring});
});
router.post('/dynamicdata/:name',function(req,res){
var bodyvalue = req.body.occupation;
res.render('items/dynamic-data',{occupation:bodyvalue});
});
module.exports = router;
| true
|
13d2eb37a21f76fca14f23037ca1cde52d968e26
|
JavaScript
|
ninojovic/bit-pp
|
/objekti/practicals-built-in-objects/zadatak9.js
|
UTF-8
| 296
| 3.09375
| 3
|
[] |
no_license
|
var randomEmail = "ninojovic@gmail.com";
function hideEmail(email) {
var newArr = email.split("@");
var username = newArr[0].split("")
username.splice(newArr[0].length/2);
username = username.join("") + "...@";
return username.concat(newArr[1]);
}
console.log(hideEmail(randomEmail));
| true
|
e52feaece1820422cc4b82f87523459d28eee181
|
JavaScript
|
engineerchirag/geekster-april-batch-practice
|
/Class 6/practise.js
|
UTF-8
| 318
| 4.34375
| 4
|
[] |
no_license
|
// function , input = > a string, substring, output = > position of substring, -1
let input_str = "Heloohhlollollo"
let substr = "ll"
function find_position_of_substring(input_str) {
return input_str.search(substr)
}
console.log(`Position of ${substr} in ${input_str} is ${find_position_of_substring(input_str)}`)
| true
|
c895da370a343ffc8f5b6f9192f60e1ce02aae52
|
JavaScript
|
PrivateSky/psk-monitoring-ui
|
/MonitorPage/vendor/swarmcore-logger/lib/index.js
|
UTF-8
| 1,774
| 2.796875
| 3
|
[] |
no_license
|
/**
* Entry point in module
*/
const Log = require('./models/Log');
const send = require('./output');
const config = require('./config');
const path = require('path');
const stackTrace = require('./stackTrace');
const formatters = require('./formatters');
/**
*
* @param {string} type - one of the error types as described in README.md
* @param {*} msg - message, it can also be an object
* @param output - a stream where the log will be written to
*/
function log (type, msg, output) {
// msg can be also a falsy value (like 0) and we might want to accept that
if (msg === null || typeof msg === 'undefined') {
msg = 'Message cannot be undefined or null';
type = 'error';
}
let caller = stackTrace.getStackTraceParsedData();
const timestamp = Date.now();
const fileName = formatters.formatFileName(caller.filePath);
msg = formatters.formatMessage(msg);
let log = new Log(msg, type, timestamp, caller.functionName, fileName, caller.lineNumber);
send(output, log);
}
/**
* Sets all properties in config param to the config file of the module
* @param {object} options
*/
exports.config = function (options) {
"use strict";
if (options) {
Object.keys(options).forEach(key => {
config.set(key, options[key]);
});
}
};
let logTypes = [
'general',
'info',
'warn',
'error'];
for (let i = 0; i < logTypes.length; ++i) {
exports[logTypes[i]] = function (...msg) {
log(logTypes[i], msg);
};
console[logTypes[i]] = exports[logTypes[i]];
}
console.log = exports.general; // because I don't want to have the type log
| true
|
3e3b085fb94d808b83188b22d5a09a2d49635800
|
JavaScript
|
Lockyard/CGProject2019
|
/assignments/Baldasseroni/A03 - Move the starship advanced DONE/A03 - Move the starship advanced/move.js
|
UTF-8
| 3,665
| 2.875
| 3
|
[] |
no_license
|
function move() {
// Rotate 30 degrees around an arbitrary axis passing through (1,1,0). The x-axis can be aligned to the arbitrary axis after a rotation of 15 degrees around the z-axis, and then 45 degrees around the y-axis.
var R1z = [Math.cos(Math.PI/12), -Math.sin(Math.PI/12), 0.0, 0.0,
Math.sin(Math.PI/12), Math.cos(Math.PI/12), 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0];
var R1y = [Math.cos(Math.PI/4), 0.0, Math.sin(Math.PI/4), 0.0,
0.0, 1.0, 0.0, 0.0,
-Math.sin(Math.PI/4), 0.0, Math.cos(Math.PI/4), 0.0,
0.0, 0.0, 0.0, 1.0];
var R1x = [1.0, 0.0, 0.0, 0.0,
0.0, Math.cos(Math.PI/6), -Math.sin(Math.PI/6), 0.0,
0.0, Math.sin(Math.PI/6), Math.cos(Math.PI/6), 0.0,
0.0, 0.0, 0.0, 1.0];
var R1trans = [1.0, 0.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0];
var R1z_inv = utils.invertMatrix(R1z);
var R1y_inv = utils.invertMatrix(R1y);
var R1trans_inv = utils.invertMatrix(R1trans);
var R1 = utils.multiplyMatrices(
utils.multiplyMatrices(
R1trans,
utils.multiplyMatrices(
utils.multiplyMatrices(R1z,R1y),
R1x)),
utils.multiplyMatrices(
utils.multiplyMatrices(
R1y_inv,R1z_inv),
R1trans_inv
)
);
// Double the size of an object, using as fixed point (1,1,0)
var S1 = [2.0, 0.0, 0.0, -1.0,
0.0, 2.0, 0.0, -1.0,
0.0, 0.0, 2.0, 0.0,
0.0, 0.0, 0.0, 1.0];
// Mirror the starship along a plane passing through (1,2,0), and obtained rotating 38 degree around the y axis the xy plane
var S2rot = [Math.cos(utils.degToRad(38)), 0.0, Math.sin(utils.degToRad(38)), 0.0,
0.0, 1.0, 0.0, 0.0,
-Math.sin(utils.degToRad(38)), 0.0, Math.cos(utils.degToRad(38)), 0.0,
0.0, 0.0, 0.0, 1.0];
var S2trans = [1.0, 0.0, 0.0, 1.0,
0.0, 1.0, 0.0, 2.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0];
var S2mirror = [1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, -1.0, 0.0,
0.0, 0.0, 0.0, 1.0];
var S2 = utils.multiplyMatrices(
utils.multiplyMatrices(
utils.multiplyMatrices(S2trans,S2rot),
S2mirror),
utils.multiplyMatrices(utils.invertMatrix(S2rot),utils.invertMatrix(S2trans))
);
// The ship has been doubled in size, rotated 45 degrees around the x axis, 30 degrees around the y axis, and moved to (1,1,-2). Return the ship in its original position
var I1half = [0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.0, 0.0, 0.0, 1.0];
var I1rot_x = [1.0, 0.0, 0.0, 0.0,
0.0, Math.cos(-Math.PI/4), -Math.sin(-Math.PI/4), 0.0,
0.0, Math.sin(-Math.PI/4), Math.cos(-Math.PI/4), 0.0,
0.0, 0.0, 0.0, 1.0];
var I1rot_y = [Math.cos(-Math.PI/6), 0.0, Math.sin(-Math.PI/6), 0.0,
0.0, 1.0, 0.0, 0.0,
-Math.sin(-Math.PI/6), 0.0, Math.cos(-Math.PI/6), 0.0,
0.0, 0.0, 0.0, 1.0];
var I1trans = [1.0, 0.0, 0.0, -1.0,
0.0, 1.0, 0.0, -1.0,
0.0, 0.0, 1.0, 2.0,
0.0, 0.0, 0.0, 1.0];
var I1 = utils.multiplyMatrices(
utils.multiplyMatrices(
I1half, I1rot_x),
utils.multiplyMatrices(I1rot_y,I1trans)
);
return [R1, S1, S2, I1];
}
| true
|
20c098f9f0310fc64baf98c3fb16e4a2d64c1ed2
|
JavaScript
|
BlueOcean090/a2-shortstack
|
/public/js/scripts.js
|
UTF-8
| 3,838
| 3.25
| 3
|
[] |
no_license
|
// Add some Javascript code here, to run on the front end.
console.log("Welcome to assignment 2!")
const showTable = function (e) {
e.preventDefault();
}
const submit = function(e) {
// prevent default form action from being carried out
e.preventDefault();
document.getElementById('insertconf').innerHTML = '';
document.getElementById('remconf').innerHTML = '';
document.getElementById('result').innerHTML = '';
const inputname = document.querySelector("#bookname"),
inputid = document.querySelector("#Identification"),
inputauthor = document.querySelector("#author"),
prior = document.querySelector("#priority"),
letime = Date.now(),
retime = Date.now() + 60480000*prior.value;
let json = {
bookname: inputname.value, Id: inputid.value, author: inputauthor.value, checktime: letime,
returntime: retime, priority: prior.value
};
let body = JSON.stringify(json);
fetch("/submit", {
method: "POST",
body
}).then(function (response) {
return response.json();
})
.then(function (json) {
console.log(json);
});
document.getElementById('insertconf').innerHTML = 'Record successfully saved'
return false;
};
const delRecord = function(e){
e.preventDefault();
document.getElementById('insertconf').innerHTML = '';
document.getElementById('remconf').innerHTML = '';
document.getElementById('result').innerHTML = '';
const body = JSON.stringify({'index' : +document.querySelector("#pointer")});
fetch("/delete", {
method: "POST",
body
}).then(function(response) {
return response.json();
})
.then(function(json) {
console.log(json);
});
document.getElementById('remconf').innerHTML = 'Record successfully deleted'
return false;
}
function fixedDate(seconds) {
const d = new Date(seconds);
let day = d.getDate();
let month = d.getMonth() + 1;
let year = d.getFullYear();
return month + '/' + day + '/' + year;
}
const showRecords = function(e){
e.preventDefault();
document.getElementById('insertconf').innerHTML = '';
document.getElementById('remconf').innerHTML = '';
document.getElementById('result').innerHTML = '';
fetch("/reveal", {
method: "POST"
}).then( function (d) {
return d.json()
}).then(function (arr) {
document.getElementById('result').innerHTML = ''
document.getElementById('result').innerHTML += '<tr>' +
'<th>Name of the Book</th>' +
'<th>ID number of the Book</th>' +
'<th>Author</th>' +
'<th>Weeks out</th>' +
'<th>Date of Checkout</th>' +
'<th>Date of Return</th>' +
'</tr>'
//adding the title row for the table
arr.forEach(fiel => {
const el = JSON.parse(fiel)
document.getElementById('result').innerHTML +=
`<tr>
<td>${el.name}</td>
<td>#${el.Id}</td>
<td>By ${el.author}</td>
<td>${el.priority}</td>
<td>${fixedDate(el.checktime)}</td>
<td>${fixedDate(el.checktime + 604800000*el.priority)}</td>
</tr>`;
});
})
return false;
}
window.onload = function() {
const submitButton = document.querySelector("#submit");
const deleteButton = document.querySelector("#delete");
const revealButton = document.querySelector("#reveal");
submitButton.onclick = submit;
deleteButton.onclick = delRecord;
revealButton.onclick = showRecords;
};
| true
|
7d8c4705d0c70cba7dfae7261cb164226ec1d8ad
|
JavaScript
|
conde-nast-international/autoEdit_2
|
/frontEnd/srt/index.js
|
UTF-8
| 2,160
| 3.6875
| 4
|
[
"MIT"
] |
permissive
|
/**
* @module srt
* @description provides a function to convert srt line object json to srt file content as string
* originally from [srtParserComposer](https://github.com/pietrop/srtParserComposer) and [on npm](https://www.npmjs.com/package/srt_parser_composer)
* Expecting srtJsonContent to be like so
@example <caption>Example USage</catpion>
var srtJsonContent = [
{
"id": "1",
"startTime": "00:00:00,160",
"endTime": "00:00:04,890",
"text": "There’s this door on the 10th floor I just\nhate so much.\n"
},
{
"id": "3",
"startTime": "00:00:05,799",
"endTime": "00:00:11,629",
"text": "Goddammit!\nDo you ever get this door wrong? “pretty\n"
},
{
"text": "regularly.”\nHow often? “like 30% of the time.”\n",
"id": "4",
"startTime": "00:00:11,629",
"endTime": "00:00:12,000"
},
{
"id": "6",
"startTime": "00:00:14,290",
"endTime": "00:00:16,869",
"text": "Have you seen people misuse it?\nAll the time. Every day. Constantly.\n"
}
]
createSrtContent(srtJsonContent, function(resp){
//do something with the srt file content returned as a string
})
* @example <caption> it returns a string content of the srt file like so</caption>
1
00:00:00,160 --> 00:00:04,890
There’s this door on the 10th floor I just
hate so much.
3
00:00:05,799 --> 00:00:11,629
Goddammit!
Do you ever get this door wrong? “pretty
4
00:00:11,629 --> 00:00:12,000
regularly.”
How often? “like 30% of the time.”
6
00:00:14,290 --> 00:00:16,869
Have you seen people misuse it?
All the time. Every day. Constantly.
* @author Pietro Passarelli
*/
/**
* Srt composer from json of lines objets
* @param {json} srtContent
* @param {cb} callback
* @todo add error handling and error.
*/
"use strict";
function createSrtContent(srtJsonContent, cb){
var lines = "";
for(var i=0; i< srtJsonContent.length; i++){
srtLineO = srtJsonContent[i];
lines+=srtLineO.id+"\n";
lines+=srtLineO.startTime+" --> "+srtLineO.endTime+"\n";
lines+=srtLineO.text+"\n";
}
//TODO figure out if callback here is redundant and could just return
if(cb){cb(lines)}else{return lines};
}
| true
|
044ac05cbe9185fd2342f4e476b1047980a71718
|
JavaScript
|
neerajp99/cs_207_e-commerce
|
/routes/api/cart.js
|
UTF-8
| 4,789
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
const mongoose = require("mongoose");
const express = require("express");
const router = express.Router();
const passport = require("passport");
const Cart = require("../../models/Cart");
const Item = require("../../models/Item");
// const object = []
// @route POST /api/wishlist/
// @description post to user wishlist
// @access Private
router.post(
"/",
passport.authenticate("jwt", { session: false }),
(req, res) => {
const updateFields = {};
updateFields.user = req.user.id;
if (req.body.productId) {
updateFields.productId = req.body.productId;
}
if (req.body.quantity) {
updateFields.quantity = req.body.quantity;
}
updateFields.product = {};
if (req.body.name) {
updateFields.product.name = req.body.name;
}
if (req.body.description) {
updateFields.product.description = req.body.description;
}
if (req.body.size) {
updateFields.product.size = req.body.size;
}
if (req.body.category) {
updateFields.product.category = req.body.category;
}
if (req.body.price) {
updateFields.product.price = req.body.price;
}
Cart.findOne({
productId: req.body.productId
})
.then(cart => {
if (cart) {
Cart.findOneAndUpdate(
{
user: req.user.id
},
{
$set: updateFields
},
{
new: true
}
)
.then(carts => {
res.json(carts);
})
.catch(error => {
res.status(400).json(error);
});
} else {
new Cart(updateFields)
.save()
.then(productCart => {
res.json(productCart);
})
.catch(error => {
res.status(400).json(error);
});
}
})
.catch(error => {
res.status(400).json(error);
});
}
);
// @route GET /api/cart/
// @description get user's cart
// @access Private
router.get(
"/",
passport.authenticate("jwt", { session: false }),
(req, res) => {
Cart.find({
user: req.user.id
})
.then(product => {
if (!product) {
return res.status(400).json("No product in the cart!");
} else {
res.json(product);
}
})
.catch(error => {
res.status(400).json(error);
});
}
);
// @route DELETE api/cart/:cart_id
// @description Delete cart item
// @access Private
router.delete(
"/:cart_id",
passport.authenticate("jwt", { session: false }),
(req, res) => {
Cart.deleteOne({ productId: req.params.cart_id }, error => {
if (!error) {
Cart.find({ user: req.user.id }).then(product => {
res.json(product);
});
} else {
return res.status(400).json(error);
}
});
}
);
// @route DELETE api/cart/:cart_id
// @description Move cart item to wishlist and remove from cart
// @access Private
router.delete(
"/moveToWishlist/:cart_id",
passport.authenticate("jwt", { session: false }),
(req, res) => {
Cart.findOne({
productId: req.params.cart_id
}).then(wish => {
const updateFields = {};
updateFields.user = req.user.id;
updateFields.productId = wish.productId;
updateFields.quantity = 1;
updateFields.product = {};
updateFields.product.name = wish.product.name;
updateFields.product.description = wish.product.description;
updateFields.product.size = wish.product.size;
updateFields.product.category = wish.product.category;
updateFields.product.price = wish.product.price;
Wishlist.findOne({
productId: req.params.cart_id
})
.then(cart => {
if (!cart) {
new Wishlist(updateFields)
.save()
.then(productCart => {
res.json(productCart);
})
.then(() => {
Cart.deleteOne({ productId: req.params.cart_id }, error => {
if (!error) {
Cart.find({ user: req.user.id }).then(product => {
return res.json(product);
});
} else {
return res.status(400).json(error);
}
});
})
.catch(error => {
console.log("hahahhaa");
res.status(400).json(error);
});
} else {
return res.status(400).json("Item already present in cart!");
}
})
.catch(error => {
console.log("jajajaajhaa");
res.status(400).json(error);
});
});
}
);
module.exports = router;
| true
|
d3bcf87f839b0b32355b25d0dd9f4658b9581f49
|
JavaScript
|
anickalerner/mister-bitcoin-backend
|
/api/auth/controller.js
|
UTF-8
| 997
| 2.5625
| 3
|
[] |
no_license
|
const authService = require('./service')
async function login(req, res) {
const {name} = req.body
console.log('auth controller', name);
try {
const user = await authService.login(name)
req.session.user = user;
res.send(user);
} catch (err) {
console.log(err);
res.status(401).send({ error: err })
}
}
async function signup(req, res) {
try {
const user = req.body
const account = await authService.signup(user)
const loggedUser = await authService.login(user.name)
req.session.user = loggedUser
res.send(loggedUser)
} catch (err) {
res.status(500).send({ error: 'Could not signup, please try later' })
}
}
async function logout(req, res){
try {
req.session.destroy()
res.send({ message: 'logged out successfully', user: null})
} catch (err) {
res.status(500).send({ error: err })
}
}
module.exports = {
login,
signup,
logout
}
| true
|
1b76505565415a080d850b55eca944983b213ead
|
JavaScript
|
mukesh-n/codejs
|
/aq3_2.js
|
UTF-8
| 256
| 3.453125
| 3
|
[] |
no_license
|
array = [70, 60, 60, 80, 90];
function calcAverage(array){
var total = 0;
var count = 0;
array.forEach(function(item, index){
total = total + item;
count++;
});
return total / count;
}
console.log(clacAverage(array));
| true
|
a28a08de72cea3420c0f7f1602da74c3b31138af
|
JavaScript
|
Sanje04/NodeJSExamples
|
/function-examples/test03.js
|
UTF-8
| 462
| 3.4375
| 3
|
[] |
no_license
|
const Confirm = require('prompt-confirm');
function ifYes() {
console.log("You said yes.");
}
function ifNo() {
console.log("You said no.");
}
function promptUser(message, f_yes, f_no){
const prompt = new Confirm(message);
prompt.ask(function(answer) {
if (answer == true) {
f_yes();
}
else {
f_no();
}
});
}
promptUser("Do you like water", ifYes, ifNo);
| true
|
312de97f4cbb0e077efe324b78830c39bfb2d6b6
|
JavaScript
|
JimmyDewey/MerryChristmas
|
/sketch.js
|
UTF-8
| 2,732
| 3.265625
| 3
|
[] |
no_license
|
let num = 20;
let mixnum;
let gravity = 0.05;
let snows = [];
let i = 0;
function setup() {
mixnum = num;
createCanvas(windowWidth, windowHeight);
createObject();
setInterval("createObject()", 2500);
}
function createObject() {
for (; i < mixnum; i++) {
snows[i] = new Snow(
random(-windowWidth, windowWidth), // 起始点x
random(-60, 0), // 起始点y
random(1, 5), // 宽度
random(-2, 2), // x轴速度
random(2, 4), // y轴速度
0
);
}
mixnum = mixnum + num;
}
function draw() {
background('#181D1E');
snows.forEach(snow => {
snow.move();
snow.display();
snow.delete();
});
}
function Snow(x, y, width, dx, dy, angle) {
this.x = x; //落点横坐标
this.y = y; //落点纵坐标
this.move = function () {
this.x += dx;
this.y += dy;
angle = angle + random(0, 0.02);
};
this.display = function () {
snowflake(this.x, this.y, width, angle);
};
this.delete = function () {
if (this.y >= windowHeight) {
snows.splice(this, 1);
}
}
}
function snowflake(x, y, width, angle) {
push();
stroke('#72ECFF');
strokeWeight(width);
translate(x, y);
rotate(angle);
line(0, 0, 0, 10 * width);
line(-3 * width, 7.5 * width, 0, 5 * width);
line(3 * width, 7.5 * width, 0, 5 * width);
line(-2.5 * width, 5 * width, 0, 3 * width);
line(-1 * width, 3.8 * width, -2 * width, 3 * width);
rotate(PI / 3);
line(0, 0, 0, 10 * width);
line(-3 * width, 7.5 * width, 0, 5 * width);
line(3 * width, 7.5 * width, 0, 5 * width);
line(-2.5 * width, 5 * width, 0, 3 * width);
line(-1 * width, 3.8 * width, -2 * width, 3 * width);
rotate(PI / 3);
line(0, 0, 0, 10 * width);
line(-3 * width, 7.5 * width, 0, 5 * width);
line(3 * width, 7.5 * width, 0, 5 * width);
line(-2.5 * width, 5 * width, 0, 3 * width);
line(-1 * width, 3.8 * width, -2 * width, 3 * width);
rotate(PI / 3);
line(0, 0, 0, 10 * width);
line(-3 * width, 7.5 * width, 0, 5 * width);
line(3 * width, 7.5 * width, 0, 5 * width);
line(-2.5 * width, 5 * width, 0, 3 * width);
line(-1 * width, 3.8 * width, -2 * width, 3 * width);
rotate(PI / 3);
line(0, 0, 0, 10 * width);
line(-3 * width, 7.5 * width, 0, 5 * width);
line(3 * width, 7.5 * width, 0, 5 * width);
line(-2.5 * width, 5 * width, 0, 3 * width);
line(-1 * width, 3.8 * width, -2 * width, 3 * width);
rotate(PI / 3);
line(0, 0, 0, 10 * width);
line(-3 * width, 7.5 * width, 0, 5 * width);
line(3 * width, 7.5 * width, 0, 5 * width);
line(-2.5 * width, 5 * width, 0, 3 * width);
line(-1 * width, 3.8 * width, -2 * width, 3 * width);
pop();
}
| true
|
196311b0d6803bede6abc3695a107426de4ef78b
|
JavaScript
|
AlexanderMykytiuk/goit-js-hw-06
|
/JS/task-number_10.js
|
UTF-8
| 502
| 3.15625
| 3
|
[] |
no_license
|
// Write code under this line
const getSortedUniqueSkills = array => {
let skillsNotUnique = array
.reduce((acc, {skills}) => [...acc, ...skills], []);
skillsNotUnique = skillsNotUnique.sort();
return [...new Arr(skillsNotUnique)];
};
console.log(getSortedUniqueSkills(users));
/* [ 'adipisicing', 'amet',
'anim', 'commodo',
'culpa', 'elit',
'ex', 'ipsum',
'irure', 'laborum',
'lorem', 'mollit',
'non', 'nostrud',
'nulla', 'proident',
'tempor', 'velit',
'veniam' ]; */
| true
|
ecd303645ed98e6e83cc7af58049b81a12e9b2c2
|
JavaScript
|
jfrfonseca/Projeto_Biotecnologia
|
/WebContent/js/cssmacros.js
|
UTF-8
| 14,821
| 2.625
| 3
|
[] |
no_license
|
/**
* This JavaScript "library" lets you use macros
* in CSS files, so that designers don't have to
* rely on classes or secondary locations to group
* elements that share (visual) design properties.
*
* (c) Mike"Pomax" Kamermans, 2011
*/
// these are here mainly to appease JSLint, which
// doesn't know about the W3C CSS DOM API
/*
if (!CSSStyleSheet) { CSSStyleSheet = {}; }
if (!StyleSheetList) { StyleSheetList = {}; }
if (!jQuery) { jQuery = {}; }
*/
(function () {
// if this date-time is after whatever version you're
// using, it's newer, and you'll want to update =)
var VERSION = "2011-12-12.15.55";
// good to have lying around
var undef;
var noop = function () {};
/*
// comment off the second to disable logging
var log = noop;
log = function(string) { window.console.log(string); }
*/
/**
* Helper function - strip comments from a string.
*/
var stripComments = function (data) {
var i, e, chr,
inquote1 = false,
inquote2 = false,
incomment = false,
rewritten = "";
for (i = 0, e = data.length; i < e; i++) {
chr = data[i];
if (!incomment) {
if (!inquote1 && !inquote2 && chr === "'") {
inquote1 = true;
} else if (!inquote1 && !inquote2 && chr === '"') {
inquote2 = true;
} else if (inquote1 && chr === "'") {
inquote1 = false;
} else if (inquote2 && chr === '"') {
inquote2 = false;
}
}
if (!inquote1 && !inquote2 && !incomment && chr === "/" && i + 1 < e && data[i + 1] === "*") {
incomment = true;
} else if (!inquote1 && !inquote2 && incomment && chr === "*" && i + 1 < e && data[i + 1] === "/") {
incomment = false;
i += 1; // we need to skip the "/" in the "*/" pair
continue;
}
if (!incomment) {
rewritten += chr;
}
}
return rewritten;
};
// administrative cache, for deferred CSSStyleSheet property setting
var bindings = [];
/**
* Clear a sheet, and inject the rules based on
* whatever the macros indicate should be the
* replacement text.
*/
var setRulesForSheet = function (child, rules) {
// record the sheet size prior to new rule insertion
if(child.cssRules) {
var cssRules = child.cssRules,
offset = 0;
// replace any rules that require modification
var r, e, ruleCount = cssRules.length, rule, result;
for (r = rules.length-1; r>=0; r--) {
rule = rules[r];
if (rule.trim() === "") { continue; }
rule = rule.replace(/\n/g, '').replace(/\n/g, '');
if(child.deleteRule) { child.deleteRule(r); }
else { child.removeRule(r); }
child.insertRule(rule, r);
}
}
};
/**
* Update a macros object with additional or override entries.
*/
var mergeMacros = function (macros, updates) {
var a, newmacros={};
// copy all global macros
for (macro in macros ) {
newmacros[macro] = macros[macro];
}
// copy all local macros
for (macro in updates) {
newmacros[macro] = updates[macro];
}
// return total to-replace macro list
return newmacros;
};
/**
* Replace all macro instances with the
* corresponding replacement value in a string.
*/
var replaceMacro = function (text, macro, value) {
var re = ":([\\w\\s]*)" + macro + "([\\w\\s]*);";
return text.replace(new RegExp(re, "gi"), ":$1" + value + "$2;");
};
/**
* Replace all macros in CSS (macros only apply to ": value")
*/
var cssReplace = function (cssstring, macros) {
if(cssstring.trim()==="") return "";
var macro;
for (macro in macros) {
cssstring = replaceMacro(cssstring, macro, macros[macro]);
}
return cssstring;
};
/**
* Extract global macro rules.
*/
var processGlobalMacros = function (data) {
var newdata, declarations, i, e, macro, macros = {}, value, legalcss, line;
// step one: get the macro block
newdata = data.replace(/\r/g, "");
newdata = newdata.replace(/\n/g, "");
newdata = newdata.substring(newdata.indexOf("@global-macros")+14);
newdata = newdata.replace(/\}.*/, "").substring(newdata.indexOf("{") + 1);
newdata = stripComments(newdata);
declarations = newdata.split(";");
// FIXME: this will simply remove the first block
legalcss = stripComments(data.substring(data.indexOf("}") + 1));
// step two: get the individual macros
for (i = 0, e = declarations.length; i < e; i++) {
line = declarations[i];
if (line.indexOf(":") < 0) { continue; }
line = line.split(":");
macro = line[0].trim();
value = line[1].trim();
document.styleSheets.globalCSSmacros[macro] = value;
}
return legalcss;
}
/**
* If {data} contains a macro definition (@macro { ... }),
* extract the macros, and then apply them to the data body.
*/
var replaceMacrosInCSSText = function (data) {
var newdata="", declarations, i, e, macro, macros = {}, value, legalcss=data, line, cssrules=false;
if(data.indexOf("@macros")>=0) {
// step one: get the macro block
newdata = data.replace(/\r/g, "");
newdata = newdata.replace(/\n/g, "");
newdata = newdata.substring(newdata.indexOf("@macros")+7);
newdata = newdata.replace(/\}.*/, "").substring(newdata.indexOf("{") + 1);
newdata = stripComments(newdata);
declarations = newdata.split(";");
// step two: get everything after macro block, stripped of comments
// FIXME: this will simply remove the first block
legalcss = stripComments(data.substring(data.indexOf("}") + 1));
// step three: get the individual macros
for (i = 0, e = declarations.length; i < e; i++) {
line = declarations[i];
if (line.indexOf(":") < 0) { continue; }
line = line.split(":");
macro = line[0].trim();
value = line[1].trim();
macros[macro] = value;
}
// step four: perform macro replacement
newdata = cssReplace(legalcss, macros);
// step five: split real CSS text into individual rules and return
newdata = newdata.replace(new RegExp("}", "g"), "}¤");
cssrules = newdata.split("¤");
}
return {rules: cssrules, csstext: legalcss, macros: macros};
};
/**
* Set up macro-replaced CSS rules for this
* stylesheet (provided it needs replacements)
*/
var replaceCSSMacros = function (sheet, css_text) {
// are there any macros to work with? if not, don't do anything
var lc = css_text.toLowerCase()
hasMacros = lc.indexOf("@macros") >= 0;
hasGlobals = lc.indexOf("@global-macros") >= 0,
macros = {};
// are there any global macros declarations?
if (hasGlobals) {
css_text = processGlobalMacros(css_text);
}
// start with whatever the global macros are at this point
macros = document.styleSheets.globalCSSmacros;
// then perform macro replacement, which will grow the macros
// list if local macros are declared as well.
var replacement = replaceMacrosInCSSText(css_text),
rules = replacement.rules,
csstext = replacement.csstext,
macros = mergeMacros(macros, replacement.macros);
if (rules !== false) {
// this replaces the current (possibly broken due to macros)
// rules with macro-replaced (valid) rules.
setRulesForSheet(sheet, rules);
}
return {csstext: csstext, macros: macros};
};
/**
* Process a stylesheet for macro replacement.
* If we're processing a sytlesheet that has
* already been treated, use the cached raw
* text instead.
*/
var processStyleSheet = function (sheet) {
// did we already process this sheet earlier?
if (sheet.macros && sheet.rawCSSText) {
var replaced = cssReplace(sheet.rawCSSText, sheet.macros);
replaced = replaced.replace(new RegExp("}", "g"), "}¤");
var rules = replaced.split("¤");
setRulesForSheet(sheet, rules);
return false;
}
// we did not. Perform full replacement
var macros = {},
csstext = "";
// from file
if(sheet.href && sheet.href !== "") {
var xhr = new XMLHttpRequest();
xhr.open('GET', sheet.href, false);
xhr.send(null);
if (xhr.status === 200) {
var result = replaceCSSMacros(sheet, xhr.responseText);
csstext = result.csstext;
macros = result.macros;
}
}
// inline style
else {
// TODO: implement
return false;
}
return {macros: macros, csstext: csstext};
};
/**
* Bind data so that it's still there after we finish
*/
var bindData = function () {
var i, e=bindings.length, binding, sheet, macros, macro, csstext;
for (i = 0; i < e; i++) {
binding = bindings[i];
if (binding.sheet && binding.csstext && binding.macros) {
sheet = binding.sheet;
csstext = binding.csstext;
sheet.setCSSText(csstext);
macros = binding.macros;
sheet.setMacros(macros);
processStyleSheet(sheet);
}
}
};
/**
* This is the script's entry point. It runs through
* all stylesheets to see if they contain a @macros block,
* and then performs macro replacement for each.
*/
var processStylesheetMacros = function () {
var sheet,
styles = document.styleSheets,
i,
e,
macros,
csstext,
result;
// add a global CSS macros container to the stylesheet list
if(!StyleSheetList.prototype.globalCSSmacros) {
StyleSheetList.prototype.globalCSSmacros = {};
}
// loop through all stylesheets to see if they need replacing
for (i = 0, e = styles.length; i < e; i++) {
macros = {};
csstext = "";
sheet = styles[i];
if (sheet instanceof CSSStyleSheet) {
result = processStyleSheet(sheet);
if (!result) {
continue;
}
macros = result.macros;
csstext = result.csstext;
bindings.push({sheet: sheet, macros: macros, csstext: csstext});
}
}
// after aggregating all data, bind it.
bindData();
};
// ===========================
// CSSStyleSheet modifications
// ===========================
// cached raw CSS text property
if (CSSStyleSheet.prototype.rawCSStext === undef) {
CSSStyleSheet.prototype.rawCSStext = "";
}
// cache macros that are to be applied to the raw CSS text
if (CSSStyleSheet.prototype.macros === undef) {
CSSStyleSheet.prototype.macros = [];
}
// Add if not defined: cache raw CSS text
if (CSSStyleSheet.prototype.setCSSText === undef) {
CSSStyleSheet.prototype.setCSSText = function (css_text) {
this.rawCSSText = css_text;
};
}
// Add if not defined: cache CSS macros
if (CSSStyleSheet.prototype.setMacros === undef) {
CSSStyleSheet.prototype.setMacros = function (macros) {
this.macros = macros;
};
}
// Add if not defined: modify a macro value
if (CSSStyleSheet.prototype.setMacro === undef) {
CSSStyleSheet.prototype.setMacro = function (macro, value) {
this.macros[macro] = value;
processStyleSheet(this);
};
}
// Add if not defined: get a macro value
if (CSSStyleSheet.prototype.getMacro === undef) {
CSSStyleSheet.prototype.getMacro = function (macro) {
return this.macros[macro];
};
}
// ============================
// StyleSheetList modifications
// ============================
// Add if not defined: set a macro value for a named sheet
if (StyleSheetList.prototype.setMacro === undef) {
StyleSheetList.prototype.setMacro = function (sheetname, macro, value) {
var i, e, sheet;
for (i = 0, e = this.length; i < e; i++) {
sheet = this[i];
if (sheet instanceof CSSStyleSheet && sheet.href.replace(/.*\//, '') === sheetname) {
sheet.setMacro(macro, value);
break;
}
}
};
}
// Add if not defined: set a macro value for all sheets
if (StyleSheetList.prototype.setMacroForAll === undef) {
StyleSheetList.prototype.setMacroForAll = function (macro, value) {
var i, e, sheet;
for (i = 0, e = this.length; i < e; i++) {
sheet = this[i];
if (sheet instanceof CSSStyleSheet) {
sheet.setMacro(macro, value);
}
}
};
}
// Add if not defined: get a macro value for a named sheet
if (StyleSheetList.prototype.getMacro === undef) {
StyleSheetList.prototype.getMacro = function (sheetname, macro) {
var i, e, sheet;
for (i = 0, e = this.length; i < e; i++) {
sheet = this[i];
if (sheet instanceof CSSStyleSheet && sheet.href.replace(/.*\//, '') === sheetname) {
return sheet.getMacro(macro);
}
}
};
}
// ================================
// Let's extend jQuery if it exists
// ================================
if (jQuery) {
jQuery.fn.macro = function (macro, value) {
// helper function: get the relevant CSSStyleSheet object
var getSheet = function (link) {
if (link.nodeName.toLowerCase() === "link") {
var href = link.href, i = 0, sheets = document.styleSheets, e = sheets.length, sheet;
for (i = 0; i < e; i++) {
sheet = sheets[i];
if (sheet.href === href) {
return sheet;
}
}
}
return false;
};
// setter function definition
var setMacro = function (link, macro, value) {
if (link.nodeName.toLowerCase() === "link") {
var sheet = getSheet(link);
if (sheet) {
sheet.setMacro(macro, value);
}
}
};
// getter function definition
var getMacro = function (macro) {
if (this.nodeName.toLowerCase() === "link") {
var sheet = getSheet(this);
if (sheet) {
return sheet.getMacro(macro);
}
}
return false;
};
// are we being asked for a macro's value? Find the first instance, or null if !exist.
if (value === undef) {
var i, e, sheet;
for (i = 0, e = this.length; i < e; i++) {
sheet = getSheet(this[i]);
if(!sheet) continue;
value = sheet.getMacro(macro);
if (value) {
return value;
}
}
return null;
}
// no, we're being asked to set it. Set for all, then return a jQuery set.
return this.each(function () { setMacro(this, macro, value); });
};
}
// =============================
// execute on dom content loaded
// =============================
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", processStylesheetMacros, false);
}
}());
| true
|
a260193903eff7b3a1b65ed4c8d93d7d04dd2efe
|
JavaScript
|
ludvigruno/narabotki
|
/src/cursJs/useEffect2.js
|
UTF-8
| 5,156
| 3.375
| 3
|
[] |
no_license
|
import React, {useState, useEffect} from 'react';
/*
Нужен для того бы дать понять что компонент что то сделал, либо был добавлен, либо обновился, либо был удален- liveSacelMethod componentDidMount, componentDidUpdate, componentWillUnmount
*/
//тоже самое функциональный компонент с useEffect
//получает анонимную функцию которая вызывает что либо, когда что то произойдет, что бы обьяснить useEffecte что было какое то событие, то надо пердать зависимость и от этих зависимостей он решает что и как делать,если ни чего не передавать то он будет реагировать на все события, а если []-пустой массив говорит что был didMount и что ни за какими переменными следить не надо, с [var,var,var..]- с переменной или переменными, то он и did моунт, что бы вызвать willUnvount надо что useEffect вернул новую анонимную функцию
const List =()=>{
const [numbers, setNumbers] = useState([1,55,6])
const addNumber =()=>{
const randNumber = Math.floor(Math.random() * 10);
const newArr = [...numbers,randNumber]
setNumbers(newArr)
}
useEffect(()=>{
//console.log('Любое событие')
})
useEffect(()=>{
console.log('Компонент обновился')
},[numbers])
useEffect(()=>{
console.log('Компонент встроился в страницу')
return ()=>{
console.log("Компонент будет удален")
}
},[])
return (
<React.Fragment>
<button onClick={addNumber}>Клик</button>
<ul>
{
numbers.map((num,key)=>(
<li key={key}>{num}</li>
))
}
</ul>
</React.Fragment>
)
}
/////////////////
//тоже самое классовый компонент
// class List extends React.Component{
// constructor(props){
// super(props);
// //внутри моего компонента есть состояние
// this.state={
// numbers: [1,2,3] //это новое свойство компонента(props)
// }
// this.addNumber =this.addNumber.bind(this)
// }
// addNumber(){
// const randNumber = Math.floor(Math.random() * 10);
// this.setState({numbers: [...this.state.numbers, randNumber]})
// }
// componentDidMount(){
// console.log("Компонент встроился в страницу")
// }
// componentDidUpdate(prevProps, prevState){
// console.log("Компонент обновился",prevProps, prevState, this.props, this.state)
// this.state.numbers.length != prevState.numbers.length?console.log('Список чисел обновился'):false
// }
// componentWillUnmount(){
// //на пример отправить запрос на сервер перед тем как компонент удалился
// console.log("Компонент будет удален")
// }
// render(){
// return(
// <React.Fragment>
// <button onClick={this.addNumber}>Клик</button>
// <ul>
// {
// this.state.numbers.map((num,key)=>(
// <li key={key}>{num}</li>
// ))
// }
// </ul>
// </React.Fragment>
// )
// }
// }
//////////////////////////
//Тоже самое только функцилнальный компонент
// const List =()=>{
// const [numbers, setNumbers] = useState([1,55,6])
// const addNumber =()=>{
// const randNumber = Math.floor(Math.random() * 10);
// const newArr = [...numbers,randNumber]
// setNumbers(newArr)
// }
// return (
// <React.Fragment>
// <button onClick={addNumber}>Клик</button>
// <ul>
// {
// numbers.map((num,key)=>(
// <li key={key}>{num}</li>
// ))
// }
// </ul>
// </React.Fragment>
// )
// }
/////////////
/* Только удаление компонента */
const IsHiden=()=>{
const[visible, setVisibli] = useState(true);
const toggleVisibles =()=>{
//первый аргумент это сам visible
setVisibli(visible=>!visible);
}
return <div>
{visible && <List/>}
<button onClick={toggleVisibles}>Показать/скрыть</button>
</div>
}
export default IsHiden;
| true
|
7a15c401debbe96d5ab00a7b5ace1b21823f9134
|
JavaScript
|
renatogm24/op-js-tictactoe
|
/ticTacToe.js
|
UTF-8
| 11,373
| 3.109375
| 3
|
[] |
no_license
|
const gameBoard = (() => {
let gameBoardArr = ["", "", "", "", "", "", "", "", ""];
const getBoardArr = () => gameBoardArr;
const cleanGameBoard = () => {
gameBoardArr = ["", "", "", "", "", "", "", "", ""];
};
const init = () => {
cacheDom();
render();
};
const cacheDom = () => {
this.$content = $('.content');
this.$board = this.$content.find('.tictactoe').find('p');
};
const render = (player) => {
if (player != undefined && player.getPositions().length > 0) {
for (let index = 0; index < player.getPositions().length; index++) {
gameBoardArr[player.getPositions()[index]] = player.getChose();
}
}
for (let index = 0; index < this.$board.length; index++) {
this.$board.eq(index).html(gameBoardArr[index]);
}
};
const endGame = () => {
for (let index = 0; index < gameBoardArr.length; index++) {
if (gameBoardArr[index] == "") {
gameBoardArr[index] = "-";
}
}
};
return { render, init, getBoardArr, cleanGameBoard, endGame }
})();
const Player = (chose) => {
let positions = [];
const getPositions = () => positions;
const cleanPositions = () => {
positions = [];
}
const getChose = () => chose;
const playerTurn = position => {
positions.push(position);
};
return { getPositions, getChose, playerTurn, cleanPositions }
};
const gameFlow = (() => {
let user = Player("X");
let enemy = Player("O");
let cont = 0;
let difficulty = "easy";
const init = () => {
cacheDom();
bindEvents();
gameBoard.init();
this.$playerX.css({
"background-color": "white",
color: "black",
border: "3px solid black",
cursor: "pointer"
});
this.$easy.css({
"background-color": "white",
color: "black",
border: "3px solid black",
cursor: "pointer"
});
};
const restart = () => {
this.$result.css({ display: "none" });
gameBoard.cleanGameBoard();
gameBoard.init();
user.cleanPositions();
enemy.cleanPositions();
if (user.getChose() == "O") {
enemy.playerTurn(machineMovement()); //si player es 0, maquina juega
gameBoard.render(enemy);
cont = 2;
} else {
cont = 0;
}
};
const cacheDom = () => {
this.$content = $('.content');
this.$playerX = this.$content.find('#playerX');
this.$playerO = this.$content.find('#playerO');
this.$board = this.$content.find('.tictactoe').find('button');
this.$start = this.$content.find('.start')
this.$result = this.$content.find('.result')
this.$easy = this.$content.find('#easy')
this.$hard = this.$content.find('#hard')
};
const bindEvents = () => {
this.$board.on('click', turn);
this.$start.on('click', restart);
this.$playerX.on('click', selectPlayer);
this.$playerO.on('click', selectPlayer);
this.$easy.on('click', changeDifficulty);
this.$hard.on('click', changeDifficulty);
};
const turn = (event) => {
let whoPlay = (cont % 2 == 0) ? user : enemy;
if (event.target.id != null) {
whoPlay.playerTurn(event.target.id);
gameBoard.render(whoPlay);
if (checkWinner(whoPlay)) {
this.$result.eq(0).html("YOU WIN!");
this.$result.css({ display: "flex" });
gameBoard.endGame();
gameBoard.render();
}
cont++;
}
enemy.playerTurn(machineMovement());
gameBoard.render(enemy);
if (checkWinner(enemy)) {
this.$result.eq(0).html("YOU LOSE!");
this.$result.css({ display: "flex" });
gameBoard.endGame();
gameBoard.render();
}
cont++;
};
const changeDifficulty = (event) => {
//event.currentTarget.id == "playerX"
if (difficulty == "easy" && event.currentTarget.id == "hard") {
this.$hard.css({
"background-color": "white",
color: "black",
border: "3px solid black",
cursor: "pointer"
});
this.$easy.css({
"background-color": "black",
color: "white",
border: "3px solid white",
cursor: "pointer"
});
difficulty = "hard";
} else if (difficulty == "hard" && event.currentTarget.id == "easy") {
this.$easy.css({
"background-color": "white",
color: "black",
border: "3px solid black",
cursor: "pointer"
});
this.$hard.css({
"background-color": "black",
color: "white",
border: "3px solid white",
cursor: "pointer"
});
difficulty = "easy";
}
};
const machineMovement = () => {
if (difficulty == "easy") {
let boardArrAux = gameBoard.getBoardArr();
let spacesAvailable = [];
for (let index = 0; index < boardArrAux.length; index++) {
if (boardArrAux[index] == "") {
spacesAvailable.push(index);
}
}
let indexChose = Math.floor(Math.random() * spacesAvailable.length);
return String(spacesAvailable[indexChose]);
} else {
let test = minimax(gameBoard.getBoardArr(),enemy.getChose());
return String(test.index);
}
};
function minimax(newBoard, player) { //newBoard es un arreglo
let spacesAvailable = [];
for (let index = 0; index < newBoard.length; index++) {
if (newBoard[index] == "") {
spacesAvailable.push(index);
}
}
if (winning(newBoard, user.getChose())) {
return { score: -10 };
}
else if (winning(newBoard, enemy.getChose())) {
return { score: 10 };
}
else if (spacesAvailable.length === 0) {
return { score: 0 };
}
let moves = [];
// loop through available spots
for (let i = 0; i < spacesAvailable.length; i++) {
//create an object for each and store the index of that spot
let move = {};
move.index = spacesAvailable[i];
let before = newBoard[spacesAvailable[i]]
// set the empty spot to the current player
newBoard[spacesAvailable[i]] = player;
/*collect the score resulted from calling minimax
on the opponent of the current player*/
if (player == enemy.getChose()) {
let result = minimax(newBoard, user.getChose());
move.score = result.score;
}
else {
let result = minimax(newBoard, enemy.getChose());
move.score = result.score;
}
// reset the spot to empty
newBoard[spacesAvailable[i]] = before;
// push the object to the array
moves.push(move);
}
var bestMove;
if (player === enemy.getChose()) {
var bestScore = -10000;
for (var i = 0; i < moves.length; i++) {
if (moves[i].score > bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
} else {
// else loop over the moves and choose the move with the lowest score
var bestScore = 10000;
for (var i = 0; i < moves.length; i++) {
if (moves[i].score < bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
}
// return the chosen move (object) from the moves array
return moves[bestMove];
};
const selectPlayer = (event) => {
let playerSelected;
let enemySelected;
if (event == this.$playerX) {
playerSelected = this.$playerX;
enemySelected = this.$playerO;
enemy = Player("X");
user = Player("X");
cont = 0;
} else if (event.currentTarget.id == "playerX") {
playerSelected = this.$playerX;
enemySelected = this.$playerO;
enemy = Player("O");
user = Player("X");
cont = 0;
} else {
playerSelected = this.$playerO;
enemySelected = this.$playerX;
enemy = Player("X");
user = Player("O");
cont = 1;
}
playerSelected.css({
"background-color": "white",
color: "black",
border: "3px solid black",
cursor: "pointer"
});
enemySelected.css({
"background-color": "black",
color: "white",
border: "3px solid white",
cursor: "pointer"
});
restart();
};
const checkWinner = (player) => {
let newArrChoses = player.getPositions();
//Check rows, columns and diagonals
if (newArrChoses.includes("0") && newArrChoses.includes("1") && newArrChoses.includes("2") ||
newArrChoses.includes("3") && newArrChoses.includes("4") && newArrChoses.includes("5") ||
newArrChoses.includes("6") && newArrChoses.includes("7") && newArrChoses.includes("8")) {
return true;
} else if (newArrChoses.includes("0") && newArrChoses.includes("3") && newArrChoses.includes("6") ||
newArrChoses.includes("1") && newArrChoses.includes("4") && newArrChoses.includes("7") ||
newArrChoses.includes("2") && newArrChoses.includes("5") && newArrChoses.includes("8")) {
return true;
} else if (newArrChoses.includes("0") && newArrChoses.includes("4") && newArrChoses.includes("8") ||
newArrChoses.includes("2") && newArrChoses.includes("4") && newArrChoses.includes("6")) {
return true;
} else {
return false;
}
};
function winning(board, player) {
if (
(board[0] == player && board[1] == player && board[2] == player) ||
(board[3] == player && board[4] == player && board[5] == player) ||
(board[6] == player && board[7] == player && board[8] == player) ||
(board[0] == player && board[3] == player && board[6] == player) ||
(board[1] == player && board[4] == player && board[7] == player) ||
(board[2] == player && board[5] == player && board[8] == player) ||
(board[0] == player && board[4] == player && board[8] == player) ||
(board[2] == player && board[4] == player && board[6] == player)
) {
return true;
} else {
return false;
}
}
return { init, checkWinner, user, enemy }
})();
gameFlow.init();
| true
|
b4bd4893658c40867cc0ab31f2d9c92a6486c118
|
JavaScript
|
PomPom248/lab-react-ironbeers
|
/reactive-beers/src/Components/NewBeer/NewBeer.js
|
UTF-8
| 2,744
| 2.640625
| 3
|
[] |
no_license
|
import React, { Component } from 'react';
import axios from 'axios';
class NewBeer extends Component {
constructor() {
super()
this.state = {
name: "",
tagline: "",
description: "",
first_brewed: "",
brewers_tips: "",
attenuation_level: "",
contributed_by: ""
}
}
addNew(e) {
e.preventDefault()
const name = this.state.name;
const tagline = this.state.tagline;
const description = this.state.description;
const first_brewed = this.state.first_brewed;
const brewers_tips = this.state.brewers_tips;
const attenuation_level = this.state.attenuation_level;
const contributed_by = this.state.contributed_by;
axios.post("https://ironbeer-api.herokuapp.com/beers/new", { name, tagline, description, first_brewed, brewers_tips, attenuation_level, contributed_by })
.then(() => {
this.setState({
name: "",
tagline: "",
description: "",
first_brewed: "",
brewers_tips: "",
attenuation_level: "",
contributed_by: ""
});
})
}
changeValue(e) {
const { name, value } = e.target;
this.setState({ [name]: value });
}
render() {
return (
<div>
<form onSubmit={e => this.addNew(e)}>
<input placeholder="name" type="text" name="name" value={this.state.name} onChange={e => this.changeValue(e)} />
<input placeholder="tagline" type="text" name="tagline" value={this.state.tagline} onChange={e => this.changeValue(e)} />
<input placeholder="description" type="textArea" name="description" value={this.state.description} onChange={e => this.changeValue(e)} />
<input placeholder="first brewed" type="text" name="first_brewed" value={this.state.first_brewed} onChange={e => this.changeValue(e)} />
<input placeholder="brewers tips" type="text" name="brewers_tips" value={this.state.brewers_tips} onChange={e => this.changeValue(e)} />
<input placeholder="attenuation level" type="text" name="attenuation_level" value={this.state.attenuation_level} onChange={e => this.changeValue(e)} />
<input placeholder="contributed by" type="text" name="contributed_by" value={this.state.contributed_by} onChange={e => this.changeValue(e)} />
<button>Add a New Beer</button>
</form>
</div>
);
}
}
export default NewBeer;
| true
|
2a2965a843bc488921ee4d716b350ec79c8ea939
|
JavaScript
|
yanyanJing/telegram-mt-node
|
/lib/net/encrypted-rpc-channel.js
|
UTF-8
| 5,980
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
// telegram-mt-node
// Copyright 2014 Enrico Stara 'enrico.stara@gmail.com'
// Released under the MIT License
// https://github.com/enricostara/telegram-mt-node
// EncryptedRpcChannel class
//
// This class provides an encrypted remote procedure call channel to `Telegram` through a TCP|HTTP connection.
// This channel is encrypted and therefore use the EncryptedMessage objects to wrap the communication.
// Import dependencies
require('requirish')._(module);
var RpcChannel = require('lib/net').RpcChannel;
var message = require('lib/message');
var mtproto = require('lib/mtproto');
var tl = require('telegram-tl-node');
var logger = require('get-log')('net.EncryptedRpcChannel');
// EncryptedRpcChannel extends RpcChannel
require('util').inherits(EncryptedRpcChannel, RpcChannel);
// The constructor require the following:
// - connection (required): the [Http|Tcp]Connection .
// - context (required):
// { authKey, serverSalt, sessionId, sequenceNumber, apiVersion }
// - app (required), the application data required for execute the first API call to Telegram:
// { id, version, langCode, deviceModel, systemVersion }
function EncryptedRpcChannel(connection, context, app) {
this.constructor.super_.call(this, connection);
this._app = {
api_id: app.id,
app_version: app.version,
device_model: app.deviceModel || 'Unknown Device',
system_version: app.systemVersion || 'Unknown System',
lang_code: app.langCode || 'en'
};
this._initialized = false;
this._context = context;
this._callbackMap = {};
this._messageIdsToBeAck = [];
// configure the message-parser
this._parser = new message.MessageParser();
this._parser.on('mtproto.type.New_session_created', this._onNewSessionCreated.bind(this));
this._parser.on('mtproto.type.Rpc_result', this._onRpcResult.bind(this));
this._parser.on('mtproto.type.Msgs_ack', this._onMsgsAck.bind(this));
// the sent messages still waiting for a response (msg-ack or rpc-result)
this.waiting4Response = {};
}
EncryptedRpcChannel.prototype._onRpcResult = function(rpcResult, duration) {
var callback = this._callbackMap[rpcResult.req_msg_id];
if(callback) {
this._callbackMap[rpcResult.req_msg_id] = null;
// add the acknowledgment..
this._messageIdsToBeAck.push(rpcResult._messageId);
callback(null, rpcResult.result, duration);
}
};
EncryptedRpcChannel.prototype._onNewSessionCreated = function(newSession) {
this._context.serverSalt = newSession.server_salt;
logger.info("New session has been created by Telegram: %s", newSession.toPrintable());
// send the acknowledgment..
this._messageIdsToBeAck.push(newSession._messageId);
// ..now!
this.sendMessageAck();
};
EncryptedRpcChannel.prototype._onMsgsAck = function(msgIds) {
logger.info("The server sent a acknowledge for the followings [%s]", msgIds);
for(var i = 0; i < msgIds.length; i++) {
removeFromMap(msgIds[i], this.waiting4Response);
}
};
function removeFromMap(item, map) {
if(map && map[item]) {
map[item] = null;
delete map[item];
}
}
// Send the message acknowledgement for each collected messageId
EncryptedRpcChannel.prototype.sendMessageAck = function(){
if(this._messageIdsToBeAck.length > 0) {
logger.info("The following message ids [%s] will be acknowledged to the server", this._messageIdsToBeAck);
var msgAck = new mtproto.type.Msgs_ack({
props: {
msg_ids: new tl.TypeVector({type: 'long', list: this._messageIdsToBeAck})
}
});
this._messageIdsToBeAck = [];
this.callMethod(msgAck);
}
};
// Execute remotely the given Type function
EncryptedRpcChannel.prototype.callMethod = function (method, callback) {
if (!this._open) {
callback(new Error('Channel is closed'));
return;
}
if (!this._initialized) {
var initData = require('util')._extend({query: method.serialize()}, this._app);
method = new mtproto.service.invokeWithLayer.Type({
props: {
layer: this._context.apiVersion || 23,
query: new mtproto.service.initConnection.Type({
props: initData
}).serialize()
}
});
this._initialized = true;
}
var reqMsg = new message.EncryptedMessage({
message: method,
authKey: this._context.authKey,
serverSalt: this._context.serverSalt,
sessionId: this._context.sessionId,
sequenceNumber: this._context.sequenceNumber
});
if(callback) {
this._callbackMap[reqMsg.messageId] = callback;
if (logger.isDebugEnabled()) {
logger.debug('Register callback, %s: %s', reqMsg.messageId, callback);
}
}
this.waiting4Response[reqMsg.messageId] = true;
this._call(reqMsg);
};
EncryptedRpcChannel.prototype._call = function (reqMsg) {
var self = this;
var callback = this._callbackMap[reqMsg.messageId];
try {
this.constructor.super_.prototype._call.call(this, reqMsg, function (ex, result, duration) {
if(ex) {
logger.error(ex.stack);
if(callback) {
callback(ex);
return;
}
}
logger.info('Call of \'%s\' took %sms', reqMsg.body.typeName, duration);
self._parser.parse(result, duration);
});
} catch (err) {
logger.error(err.stack);
if(callback) {
callback(err);
}
}
};
EncryptedRpcChannel.prototype._deserializeResponse = function (response) {
var resObj = new message.EncryptedMessage({buffer: response, authKey: this._context.authKey}).deserialize();
var result = resObj.body;
result._messageId = resObj.messageId;
return result;
};
// Export the class
module.exports = exports = EncryptedRpcChannel;
| true
|
13dc5f404787d60848923b7b425ed6c7b9a81030
|
JavaScript
|
rishabghosh/arrayPracticeAssignment
|
/mappingLength/lib.js
|
UTF-8
| 162
| 2.828125
| 3
|
[] |
no_license
|
const findLength = function(text){
return text.length;
}
const mapLength = function(list){
return list.map( findLength );
}
exports.mapLength = mapLength;
| true
|
d6c0acfd109a772d6d42a84e027c0bc79bda22ce
|
JavaScript
|
Edunga1/chrome-ext-scrapper
|
/src/scrapper.js
|
UTF-8
| 2,630
| 3.109375
| 3
|
[] |
no_license
|
var scrapper = (function (storage, JSON) {
//- constraints
// Scrap list key name in storage
var _STORAGE_SCRAPS = 'scraps';
// Scrap URL Key name in scrap list
var _STORAGE_SCRAP_URL = 'url';
// Scrap title key name in scrap list
var _STORAGE_SCRAP_TITLE = 'title';
//- privates
/**
* Scrap list
* @type {Array<Object>}
*/
var _scraps = (function () {
var listJSON = storage.getItem(_STORAGE_SCRAPS);
return listJSON ? JSON.parse(listJSON) : [];
})();
/**
* @return {boolean} Index of scrap in list
*/
var _getScrapIndex = function (url) {
var res = -1;
_scraps.find(function (scrap, index) {
if (scrap.url == url) {
res = index;
return true; // break traverse
}
});
return res;
};
/**
* Sync with storage
*/
var _sync = function () {
storage.setItem(_STORAGE_SCRAPS, JSON.stringify(_scraps));
};
/**
* Create new scrap to storage
* @param {string} url scrap url
* @param {string} title scrap title
*/
var _newScrap = function (url, title) {
var scrapIndex = _getScrapIndex(url);
if (scrapIndex == -1) {
scrapIndex = _scraps.length;
}
_scraps[scrapIndex][_STORAGE_SCRAP_URL] = url;
_scraps[scrapIndex][_STORAGE_SCRAP_TITLE] = title;
_sync();
};
//- module implementation
var _Scrapper = function () {};
/**
* Scrap
* @param {string} url scrap url
* @param {string} title scrap title
* @return {boolean} success or fail
*/
_Scrapper.prototype.scrap = function (url, title) {
if (!storage || !JSON) {
return false;
}
_newScrap(url, title);
return this;
};
/**
* @return {boolean} Scrap exists in storage
*/
_Scrapper.prototype.isDuplicate = function () {
return _isDuplicate() != -1;
};
/**
* Attach tag to the scrap
* @param {string} url scrap url
* @param {string} tag tag
*/
_Scrapper.prototype.addTag = function (url, tag) {
var index = _getScrapIndex(url);
if (index != -1 && tag.trim().length > 0) {
scrap = _scraps[index];
if (!scrap.tags) {
scrap.tags = [];
}
if (scrap.tags.indexOf(tag) == -1) {
scrap.tags.push(tag);
_sync();
}
}
return this;
};
return new _Scrapper();
})(localStorage, JSON);
| true
|
b99ea84bf7bd49d66c40661dc925b511ca88e116
|
JavaScript
|
AmoroBG/FizzBuzz
|
/main.js
|
UTF-8
| 1,555
| 3.890625
| 4
|
[] |
no_license
|
// Variables Declarations
let inputBox = document.getElementById("input-box");
let playGame = document.getElementById("play-game")
let resultBoard = document.getElementById("result-board-counts")
let number;
// Add eventListener to the play button
playGame.addEventListener("click", function() {
number = parseInt(inputBox.value)
const validInput = validateInput();
if (!validInput) {
return;
}
// console.log(fizzBuzz())
// resultBoard.innerText = fizzBuzz()
addResultClass()
fizzBuzz()
inputBox.value = ""
})
// Prompt user for the number
// let number = parseInt(prompt("Enter a number"))
//validateInput function
function validateInput() {
if (number < 1 || number > 100) {
alert("Number must be between 1 and 100")
inputBox.value = ""
return false
}
return true
}
// fizzBuzz function
function fizzBuzz() {
let counts = "";
resultBoard.innerText = "";
for (let i = 1; i <= number; i++) {
if ((i % 3 === 0) && (i % 5 == 0)) {
// multiples of both three and five print 'FizzBuzz'
counts = "FizzBuzz"
} else if (i % 3 === 0) {
// multiples of three print 'Fizz'
counts = "Fizz"
} else if (i % 5 === 0) {
// multiples of five print 'Buzz'
counts = "Buzz"
} else {
counts = i
}
resultBoard.innerText += counts + "\u00a0"
}
}
//function addResultClass
function addResultClass() {
resultBoard.classList.add("result")
}
| true
|
e6f68c2deaa8efeaaa67f871d153b6dbff685d1a
|
JavaScript
|
Gerpiili369/web-browser
|
/renderer/src/Components/TitleBar/WindowControl.jsx
|
UTF-8
| 3,618
| 2.546875
| 3
|
[] |
no_license
|
// WindowControl Component
import React, { Component } from 'react';
import Close from '../../Icons/Close';
import Unmaximize from '../../Icons/Unmaximize';
import Maximize from '../../Icons/Maximize';
import Minimize from '../../Icons/Minimize';
const { remote } = window.require('electron');
class WindowControl extends Component {
constructor(props) {
super(props);
this.state = {
get win() {
return remote.getCurrentWindow();
},
maxMove: false,
unmaxSize: remote.getCurrentWindow().getSize(),
maximized: remote.getCurrentWindow().isMaximized(),
};
this.removeListeners = this.removeListeners.bind(this);
this.handleMaximized = this.handleMaximized.bind(this);
this.handleUnmaximized = this.handleUnmaximized.bind(this);
this.handleWillResize = this.handleWillResize.bind(this);
this.handleMove = this.handleMove.bind(this);
this.minimize = this.minimize.bind(this);
this.toggleMaximized = this.toggleMaximized.bind(this);
this.close = this.close.bind(this);
}
componentDidMount() {
this.state.win.on('maximize', this.handleMaximized);
this.state.win.on('unmaximize', this.handleUnmaximized);
this.state.win.on('will-resize', this.handleWillResize);
this.state.win.on('move', this.handleMove);
window.addEventListener('beforeunload', this.removeListeners);
}
componentWillUnmount() {
this.removeListeners();
}
removeListeners() {
this.state.win.removeListener('maximize', this.handleMaximized);
this.state.win.removeListener('unmaximize', this.handleUnmaximized);
this.state.win.removeListener('will-resize', this.handleWillResize);
this.state.win.removeListener('move', this.handleMove);
window.removeEventListener('beforeunload', this.removeListeners);
}
handleMaximized() {
this.setState({
maximized: true,
maxSize: this.state.win.getSize(),
});
}
handleUnmaximized() {
this.setState({
maximized: false,
});
this.state.win.setSize(...this.state.unmaxSize);
}
handleWillResize(evt, newBounds) {
this.setState({
unmaxSize: [
newBounds.width,
newBounds.height,
]
});
}
handleMove() {
// There should be something here to fix the window not resizing after moving out of (button-initialized) maximized mode
}
minimize() {
this.state.win.minimize();
}
toggleMaximized() {
if (this.state.maximized) {
this.state.win.unmaximize();
this.handleUnmaximized();
} else {
this.state.win.maximize();
this.handleMaximized();
}
}
close() {
this.state.win.close();
}
render() {
return (
<div className="window-control">
<Minimize className="window-minimize" onClick={ this.minimize } width="10" height="10" />
{ this.state.maximized ?
<Unmaximize className="window-toggle-unmaximize" onClick={ this.toggleMaximized } width="10" height="10" /> :
<Maximize className="window-toggle-maximize" onClick={ this.toggleMaximized } width="10" height="10" />
}
<Close className="window-close" onClick={ this.close } width="10" height="10" />
</div>
);
}
}
export default WindowControl;
| true
|
431efc69b343277f35a485a6ab4194622b070948
|
JavaScript
|
Giacomo-Antonioli/PFGRAFICA
|
/libs/utils.js
|
UTF-8
| 612
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
var Utils = {
//returns the plaintext contents of a file
loadFileText : function(filename){
var text;
$.ajax({
async: false,
url: filename,
dataType: 'text',
success : function( data ) { text = data; }
});
return text;
},
//loads the json contents of a file as a JS Object
loadJSON : function(filename){
var obj;
$.ajax({ //basically async version of .getJSON
async: false,
url: filename,
dataType: 'json',
success : function( data ) { obj = data; }
});
return obj;
}
};
| true
|
ef0bd02cb18f5b51cf17c9edb1d9a25d189c7d0d
|
JavaScript
|
iluachursin0v/lemonhometask
|
/hometask1/1/script1.js
|
UTF-8
| 705
| 3.734375
| 4
|
[] |
no_license
|
var number;
number = 2;
if( number < 0 || number > 9 ){
console.log("Ошибка")
} else{
if(number == 0){
console.log("Ноль")
}
if(number == 1){
console.log("Один")
}
if(number == 2){
console.log("Два")
}
if(number == 3){
console.log("Три")
}
if(number == 4){
console.log("Четыре")
}
if(number == 5){
console.log("Пять")
}
if(number == 6){
console.log("Шесть")
}
if(number == 7){
console.log("Семь")
}
if(number == 8){
console.log("Восемь")
}
if(number == 9){
console.log("Девять")
}
}
| true
|
2564dbeed03a05d441a057253f983c1c424b87e2
|
JavaScript
|
arleswall/assignments
|
/rock-the-vote/client/src/main/issues/issue/comments/Component.js
|
UTF-8
| 827
| 2.546875
| 3
|
[] |
no_license
|
import React from "react";
function CommentComponent(props){
console.log(props)
return (
<div>
<form onSubmit={props.handleSubmit}>
<label>Name: </label><input onChange={props.handleChange} value={props.newItem.name} name="name" placeholder="Name" type="text"/>
<label> Comment: </label><input onChange={props.handleChange} value={props.newItem.comment} name="comment" placeholder="Comment" type="text"/>
<button>Post</button>
{props.comments.map((item, index)=>{
return (
<div className="comments">
<p>Name: {item.name}</p>
<p>Comment: {item.comment}</p>
</div>
)
})
}
</form>
</div>
)
}
export default CommentComponent;
| true
|
b70ac1a5a4fedb1c6392464cd5888601f4f2751e
|
JavaScript
|
Nash-Villarta/ICS20-Unit7-03
|
/script.js
|
UTF-8
| 582
| 3.5
| 4
|
[] |
no_license
|
// Listener for click
document.getElementById('button').addEventListener('click', calculate)
let userage = 0
// Ranges age to find appropiate age group
function calculate () {
userage = document.getElementById('inputbox').value
userage = parseFloat(userage)
if (userage > 17) {
document.getElementById('textbox').innerHTML = 'You can view a R rated movie'
} else if (userage > 13) {
document.getElementById('textbox').innerHTML = 'You can view a PG 13 rated movie'
} else {
document.getElementById('textbox').innerHTML = 'You can view a G rated movie'
}
}
| true
|
7e35f7eb7c900b8fb90daa012f29dff007465bfd
|
JavaScript
|
XJ-Parker/react-study
|
/src/practice5.js
|
UTF-8
| 1,123
| 2.828125
| 3
|
[] |
no_license
|
import React,{ Component } from "react"
import './index.css'
const lessons = [
{ title: 'Lesson 1: title', description: 'Lesson 1: description' },
{ title: 'Lesson 2: title', description: 'Lesson 2: description' },
{ title: 'Lesson 3: title', description: 'Lesson 3: description' },
{ title: 'Lesson 4: title', description: 'Lesson 4: description' }
]
class Lesson extends Component {
clickHandle(){
if(this.props.onClick){
this.props.onClick()
}
}
render(){
const {lesson} = this.props
return (
<div onClick={this.clickHandle.bind(this)}>
<h1>{lesson.title}</h1>
<p>{lesson.description}</p>
</div>
)
}
}
class LessonsList extends Component {
render(){
return (
<div>
{
lessons.map((lesson,index)=>{
return <Lesson lesson={lesson} key={index} onClick={()=>{ console.log(`${index}-${lesson.title}`)}}/>
})}
</div>
)
}
}
export default LessonsList
| true
|
e8ff9fc97fba4003256d6038f9c9aa09db1d00f5
|
JavaScript
|
phmurphy212/cookie-stand
|
/js/app.js
|
UTF-8
| 4,369
| 3.609375
| 4
|
[
"MIT"
] |
permissive
|
'use strict';
const hours = ['6am', '7am', '8am', '9am', '10am', '11am', '12pm','1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'];
//foothold in the DOM
const salesTable = document.getElementById('salesTable');
const salesHeader = document.getElementById('tHeader');
let newStoreForm = document.getElementById('newStore');
let footer = document.getElementById('tFooter');
let storeDetails = [];
let onlyTotals = [];
let grandTotal = 0;
//constructor method and expected variables
function CookieStore(name, min, max, avg) {
this.name = name;
this.min = min;
this.max = max;
this.avg = avg;
//variables to be used within other methods/functions
this.dailyTotal = 0;
this.cookiesPerHourArray = [];
storeDetails.push(this);
this.renderToSales();
}
//solve for customers using random number
CookieStore.prototype.customerCount = function () {
return Math.floor(Math.random() * (this.max - this.min + 1) + this.min);
};
//calculate total cookies sold and push that number to an array
//and calulate the daily total and total of totals
CookieStore.prototype.salesCalculator = function () {
for (let i = 0; i < hours.length; i ++){
this.cookiesPerHourArray.push(Math.ceil(this.avg * this.customerCount()));
}
for (let i = 0; i < this.cookiesPerHourArray.length; i++){
this.dailyTotal += this.cookiesPerHourArray[i];
}
onlyTotals.push(this.dailyTotal);
let count = 0;
for (let i = 0; i < storeDetails.length; i++){
count += onlyTotals[i];
}
grandTotal = count;
};
//render the main table data to the sales website
CookieStore.prototype.renderToSales = function () {
this.salesCalculator();
//create the first column witht the store names
let tr = document.createElement('tr');
let storeCell = document.createElement('td');
storeCell.textContent = this.name;
tr.appendChild(storeCell);
//create the rest of the table from data passed to the array
for (let i = 0; i < hours.length; i++) {
let td = document.createElement('td');
td.textContent = this.cookiesPerHourArray[i];
tr.appendChild(td);
}
//create the total column using daily total
let tdTotal = document.createElement('td');
tdTotal.textContent = this.dailyTotal;
tr.appendChild(tdTotal);
//append all of this data to the table
salesTable.appendChild(tr);
};
//instantiate new stores for each of the salmon cookie stores
new CookieStore('Seattle', 23, 65, 6.3);
new CookieStore('Tokyo', 3, 24, 1.2);
new CookieStore('Dubai', 11, 38, 3.7);
new CookieStore('Paris', 20, 38, 2.3);
new CookieStore('Lima', 2, 16, 4.6);
//stand alone function to create the header and shift the array over one index
//to include the city name field
function createHeader(){
let hourCells = document.createElement('td');
hourCells.textContent = 'Store';
salesHeader.appendChild(hourCells);
for (let i = 0; i < hours.length; i++){
let hourCells = document.createElement('td');
hourCells.textContent = hours[i];
salesHeader.appendChild(hourCells);
}
let td = document.createElement('td');
td.textContent = 'Daily Location Total';
salesHeader.appendChild(td);
}
//stand alone function to create the footer to include the city name field
function createFooter(){
let tr = document.createElement('tr');
let tf = document.createElement('td');
tf.textContent = 'Totals';
tr.appendChild(tf);
for (let i = 0; i < hours.length; i++){
let columnTotal = document.createElement('td');
let hourlyTotal = 0;
for (let j = 0; j < storeDetails.length; j++){
hourlyTotal += storeDetails[j].cookiesPerHourArray[i];
}
columnTotal.textContent = hourlyTotal;
tr.appendChild(columnTotal);
}
let tot = document.createElement('td');
tot.textContent = grandTotal;
tr.appendChild(tot);
footer.appendChild(tr);
}
//call create header and footer
createHeader();
createFooter();
//looks for a click on my submit button
//when the event happens, it instantiates a new store
//and renders a new footer with correct totals
function handleSubmit(event){
event.preventDefault();
let name = event.target.city.value;
let min = +event.target.min.value;
let max = +event.target.max.value;
let avg = +event.target.avg.value;
new CookieStore(name, min, max, avg);
footer.innerHTML = '';
createFooter();
}
//event listener
newStoreForm.addEventListener('submit', handleSubmit);
| true
|
84985cf29e7863f2239de6029df0f70fff68325f
|
JavaScript
|
Elodie-dev/safetyNet
|
/server/controllers/persons.js
|
UTF-8
| 1,940
| 2.59375
| 3
|
[] |
no_license
|
// On import notre script models qui contient tout nos models
const models = require('../models/models.js');
// Ci-dessous on export des fonction qui nous permettre de gerez toutes les actions liée a notre table user ---->
// [infos] Ces fonction seront accessible a partir de la variable qui require ce fichier [/infos]
exports.getAll = (req, res) => {
models.Person.findAll()
.then((persons) => {
res.status(200).json(persons);
})
}
exports.getById = (req, res) => {
models.Person.findOne({where: {id: req.params.id}})
.then((person) => {
res.status(200).json(person);
})
}
exports.add = (req, res) => {
models.Person.create({firstName: req.body.firstName, lastName: req.body.lastName, address: req.body.address, city: req.body.city, zip: req.body.zip, phone: req.body.phone, email: req.body.email, firestationId: req.body.id_firestation, id_medicalrecord: req.body.id_medicalrecord})
.then((person) => {
res.status(200).json(person);
})
.catch((err, error) => {
res.status(400).json(err + error)
})
}
exports.update = (req, res) => {
models.Person.findOne({where: {id: req.params.id}})
.then((person) => {
if(person){
person.update({firstName: req.body.firstName, lastName: req.body.lastName, address: req.body.address, city: req.body.city, zip: req.body.zip, phone: req.body.phone, email: req.body.email, id_firestation: req.body.id_firestation, id_medicalrecord: req.body.id_medicalrecord})
.then((person) => {
res.status(200).json(person)
})
}
})
.catch((err, error) => {
res.status(400).json(err + error)
})
}
exports.delete = (req, res) => {
models.Person.destroy({where: {id: req.params.id}})
.then((person) => {
res.status(200).json(person);
})
.catch((err, error) => {
res.status(400).json(err + error)
})
}
| true
|
ddd19806d90af44d5eea1932b981c096ac430367
|
JavaScript
|
maleko/node-dash-button
|
/index.js
|
UTF-8
| 3,045
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
// converts a string: "8f:3f:20:33:54:44"
// to a numeric array: [ 143, 63, 32, 51, 84, 68 ]
// for comparison
var hex_to_int_array = function(hex){
var hex_array = hex.split(":");
var int_array = [];
for (var i in hex_array) {
int_array.push( parseInt(hex_array[i], 16));
}
//console.log(hex,int_array)
return int_array;
}
// converts a numeric array: [ 143, 63, 32, 51, 84, 68 ]
// to a string: "8f:3f:20:33:54:44"=
// for comparison
var int_array_to_hex = function (int_array) {
var hex = "";
for (var i in int_array){
var h = int_array[i].toString(16); // converting to hex
if (h.length < 2) h = '0' + h; //adding a 0 for non 2 digit numbers
if (i !== int_array.length) hex+=":"; //adding a : for all but the last group
hex += h;
}
return hex.slice(1);//slice is to get rid of the leading :
}
var pcap = require('pcap');
var stream = require('stream');
var _ = require('underscore');
var create_session = function () {
try {
var session = pcap.createSession();
} catch (err) {
console.error(err);
if (err == "Error: pcap_findalldevs didn't find any devs") {
console.log("Failed to create pcap session: couldn't find devices to listen on.\n" +
"Try running with elevated privileges via 'sudo'");
}
process.exit(1);
}
return session;
}
//Function to register the node button
var register = function(mac_addresses) {
if (Array.isArray(mac_addresses)){
//console.log("array detected")
} else {
//console.log("single element detected")
mac_addresses = [mac_addresses]//cast to array
}
var pcap_session = create_session();
var readStream = new stream.Readable({
objectMode: true
});
var just_emitted = {};
mac_addresses.forEach(function(mac_address){
just_emitted[mac_address] = false;
});
pcap_session.on('packet', function(raw_packet) {
var packet = pcap.decode.packet(raw_packet); //decodes the packet
if(packet.payload.ethertype === 2054) { //ensures it is an arp packet
//for element in the mac addresses array
mac_addresses.forEach(function(mac_address){
if(!just_emitted[mac_address] &&
_.isEqual(packet.payload.payload.sender_ha.addr,
hex_to_int_array(mac_address))) {
readStream.emit('detected', mac_address);
just_emitted[mac_address] = true;
setTimeout(function () { just_emitted = false; }, 3000);
}
});
}
});
return readStream;
};
if (process.env.NODE_ENV === 'test') {
module.exports = { hex_to_int_array: hex_to_int_array,
int_array_to_hex: int_array_to_hex,
create_session: create_session,
register: register
};
} else {
module.exports = register;
}
| true
|
41aa2e1098ccbfb4e447c56f7075df90974b7e2f
|
JavaScript
|
rrrr01012/test
|
/js_course/D16b_ClosuresPart2/Finished/app.js
|
UTF-8
| 912
| 4.40625
| 4
|
[] |
no_license
|
function buildFunctions() {
var arr = [];
for (var i = 0; i < 3; i++) {
arr.push(
function() {
console.log(i);
}
)
}
return arr;
}
var fs = buildFunctions();
//跑完時i=3 存了三個console.log(i)到arr i跟arr都儲存在buildfunctions的記憶體中 再由fs指向
fs[0](); //執行時 找到console.log(i)但不知道i的值,所以去範圍鏈找到i=3
fs[1]();
fs[2]();
//印出三次console.log(i) 因為i=3所以印三次3
function buildFunctions2() {
var arr = [];
for (var i = 0; i < 3; i++) {
arr.push(
(function(j) {
return function() {
console.log(j);
}
}(i)) //iife 會先執行
)
}
return arr;
}
var fs2 = buildFunctions2();
fs2[0]();
fs2[1]();
fs2[2]();
| true
|
b75649e85a880b438c7758dd894184db2f19fcc6
|
JavaScript
|
AvrahamNacher/React-add-to-cart
|
/src/components/CartItem.jsx
|
UTF-8
| 1,095
| 2.671875
| 3
|
[] |
no_license
|
import React from 'react'
import './CartItem.css'
function CartItem(props) {
function updateCart(amountChange) {
let location = props.cart.findIndex( (el) => el.item.id === props.itemInfo.item.id);
props.cart[location].count += amountChange;
// update the cart with the new count. If the count = 0, then remove it from the cart array
props.newList(props.cart.filter( (el) => el.count !== 0));
}
return (
<div className="cart-item">
<img src={props.itemInfo.item.url} alt={props.itemInfo.item.name}/>
<div className="item-name">{props.itemInfo.item.name}</div>
<div className="item-count">Quantity:
<button onClick={ () => updateCart(1)}>+</button>
<span className="item-count__span">{props.itemInfo.count}</span>
<button onClick={ () => updateCart(-1)}>-</button>
<button className="remove-from-cart" onClick={ () => updateCart(props.itemInfo.count * -1)}>X</button>
</div>
</div>
)
}
export default CartItem;
| true
|
a1d906613db3cc6458dda796797c237dc238510d
|
JavaScript
|
instrom/mini-wp
|
/server/helpers/bcryptPassword.js
|
UTF-8
| 352
| 2.59375
| 3
|
[] |
no_license
|
const bcrypt = require('bcrypt')
const saltRounds = 10;
function hashPassword(password) {
var salt = bcrypt.genSaltSync(saltRounds);
var hash = bcrypt.hashSync(password, salt)
return hash
}
function comparePassword(password,hash) {
return bcrypt.compareSync(password,hash)
}
module.exports = {
hashPassword,
comparePassword
}
| true
|
35fcb917bb827bab2cd2b18cd00e7090ea41d0ee
|
JavaScript
|
Cojocari-Ion/Color-flipper
|
/js/script.js
|
UTF-8
| 502
| 3.5
| 4
|
[] |
no_license
|
const colors = ["green", "red", "rgba(133, 122, 200)", "#f15025"];
const btn = document.getElementById('btn');
const colorCode = document.querySelector(".color");
function myFunction() {
const randomNumber = getRandomNumber();
document.body.style.backgroundColor = colors[randomNumber];
colorCode.style.color = colors[randomNumber];
colorCode.textContent = colors[randomNumber]
function getRandomNumber() {
return Math.floor(Math.random() * colors.length);
}
}
| true
|
c49200fe84e93510eb24cfa9b1b5d7cdad109bdb
|
JavaScript
|
bombadillo/backbone-skeleton
|
/js/views/basic-view.js
|
UTF-8
| 4,839
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
var BasicView = Backbone.View.extend(
{
// View variables.
fetchInterval: undefined,
autoRefresh: undefined,
refreshInterval: 10000,
// Default attributes for the view.
defaults:
{
template: 'script#view-template',
},
// DOM events we want to listen for.
events:
{
},
/* Name initialize
* Purpose To carry out processes on view instantation e.g. before view is rendered.
*/
initialize: function(options)
{
// Overwrite defaults with any passed in options.
this.options = _.extend(options, this.defaults);
// Load the template.
app.requireTemplate(this.options.template.replace('script#', ''));
// Define collection for view and set url.
this.collection = new BasicCollection();
this.collection.urlRoot = app.urls.workFlow;
// Define model for view and set url.
this.collection = new BasicModel({ urlRoot: app.urls.workFlow });
// Global event listener.
this.listenTo(Backbone, 'module:eventName', this.fetchData);
// Call function to fetch the data.
this.fetchData();
},
/* Name render
* Purpose To render the template, populated with data, to the view's DOM element.
*/
render: function()
{
// Assign view scope.
var $this = this;
// Populate template with data.
var tpl = _.template($(this.options.template).html(),
{
collection: this.collection.toJSON(),
errors: this.collection.errors
});
// Populate view's DOM element with template.
this.$el.html(tpl);
// Set view variable to true so that we know it has been loaded.
this.loaded = true;
app.log('BasicView', 'viewRender');
},
/* Name fetchData
* Purpose To fetch the data for the main menu.
*/
fetchData: function()
{
// Assign view scope.
var $this = this;
// Fetch the data
this.collection.fetch(
{
cache: false,
success: function(collection, response)
{
// Call function to render view.
$this.render();
},
error: function(collection, response)
{
// Call function to render view.
$this.render();
// Call function to handle error repsonse.
app.requestErrorHandler(response);
}
});
},
// Validate the form.
validateForm: function()
{
// Get the form, create object to hold data.
var form = this.$el.find('form')
, obj = {};
// Loop each of the inputs.
form.find('input.data').each(function()
{
// Assign input object to var.
var $input = $(this);
// If the input is a bool type.
if ($input.data('type') === 'bool')
{
// Check for active state.
obj[$input.attr('name')] = $input.hasClass('active') ? 1 : 0;
}
else
{
// Call function to validate input.
app.validateInput($input);
// Nab the value and add to object.
obj[$input.attr('name')] = $input.val();
}
});
// END input loop.
// If there are no errors.
if (!form.find('.has-error').length)
{
// Call function to submit form.
this.submitForm(obj);
}
},
/* Name submitForm
* Purpose To submit the form.
* Params {object} data Contains the data for user to submit.
*/
submitForm: function(data)
{
// Assign view scope.
var $this = this;
// Set the username for the model.
this.model.set('username', data.username);
// Fetch the data
this.model.save(
null,
{
data: data,
success: function(model, response)
{
// If there were no errors.
if (!model.get('errors'))
{
}
// Otherwise there were errors.
else
{
}
},
error: function(model, response)
{
// Call function to handle error repsonse.
app.requestErrorHandler(response);
}
});
},
/* Name enableRefresh
* Purpose To create a refresh interval which updates the view's data.
*/
enableRefresh: function()
{
// Assign view scope.
var $this = this;
// Initially fetch the data since interval will wait until x amount of time has passed.
this.fetchData();
// If the interval does not exist then create it.
if (!this.fetchInterval)
{
$this.fetchInterval = setInterval(function()
{
$this.fetchData();
}, $this.refreshInterval);
// Set view variable to true.
$this.autoRefresh = true;
}
},
/* Name disableRefresh
* Purpose To disabel the refresh interval which updates the stock market table.
*/
disableRefresh: function()
{
// Assign view scope.
var $this = this;
// If the interval does not exist then create it.
if (this.fetchInterval)
{
clearInterval($this.fetchInterval);
this.autoRefresh = false;
}
},
/* Name softClose
* Purpose To softClose the view, removing it's element.
*/
softClose: function()
{
this.$el.html('');
// Set loaded to false.
this.loaded = false;
}
});
| true
|
233f60182f3455b20f699565bad8a7230830dcb1
|
JavaScript
|
Burning-Shadow/leetcode
|
/largest-rectangle-in-histogram[84].js
|
UTF-8
| 1,447
| 4.03125
| 4
|
[] |
no_license
|
/**
* @param {number[]} heights
* @return {number}
*/
var largestRectangleArea = function (heights) {
const len = heights.length;
if (len === 1) return heights[0];
let result = 0;
let width = 0;
for (let i = 0; i < len; i++) {
let j = i + 1;
while (j < len && heights[j] >= heights[i]) j++;
width = j - i;
result = Math.max(result, (j - i) * heights[i]);
}
return result;
};
/**
* @param {number[]} heights
* @return {number}
*
* 单调栈
* 遍历数组,遇到比当前栈顶大的元素就压入栈(压入的是索引),否则就取出栈顶元素进行计算:以当前栈顶元素为高度的最大矩形面积
*/
var largestRectangleArea = function (heights) {
let i = 0, maxArea = 0;
const stack = [];
for (let i = 0, len = heights.length; i <= len; i++) {
while (stack.length > 0 && (heights[i] < heights[stack[stack.length - 1]] || i === len)) {
const height = heights[stack.pop()];
const width = stack.length > 0 ? i - stack[stack.length - 1] - 1 : i;
// console.log(`height = ${height}, width = ${width}`);
maxArea = Math.max(maxArea, width * height);
}
stack.push(i);
}
return maxArea;
};
console.log(largestRectangleArea([2, 1, 5, 6, 2, 3])); // 10
console.log(largestRectangleArea([2, 4])); // 4
console.log(largestRectangleArea([1])); // 1
console.log(largestRectangleArea([1, 1])); // 2
console.log(largestRectangleArea([0, 9])); // 9
| true
|
f69daca569cb48073a42e472373d00e6268a8af4
|
JavaScript
|
rsingh954/YouTube
|
/V_animated_nav_bar/script.js
|
UTF-8
| 820
| 2.859375
| 3
|
[] |
no_license
|
const upper = document.querySelector(".upper");
const items = document.querySelectorAll(".nav__item");
let activeItem = document.querySelector(".active");
let color = activeItem.classList[1];
let colors = {
red: "#ff0000",
blue: "#1a53ff",
green: "#009933",
purple: "#cc33ff",
orange: "#ac7339",
};
document.body.style.backgroundColor = colors[color];
upper.style.left = `${activeItem.parentElement.offsetLeft - 47.5}px`;
items.forEach((elem) => {
elem.addEventListener("click", (e) => {
upper.style.left = `${e.currentTarget.offsetLeft - 47.5}px`;
activeItem = document.querySelector(".active");
activeItem.classList.remove("active");
elem.children[0].classList.add("active");
color = elem.children[0].classList[1];
document.body.style.backgroundColor = colors[color];
});
});
| true
|
7a53b7eab2ef8e46888174ad29951ab577263f0f
|
JavaScript
|
Yousefalwandi/YousefAlwandi_reactlab
|
/EmployeeList.js
|
UTF-8
| 1,350
| 2.828125
| 3
|
[] |
no_license
|
import { useEffect, useState } from "react";
import Employee from "./Employee";
function EmployeeList() {
const [employees, setEmployess] = useState([
{
name: "Yazeen Jasim",
email: "yazeen.jasim@softhouse.se",
phone: "0700000",
skills: "React, C++, JS",
avatar: "https://i.imgur.com/t9HFQvX.png",
},
{
name: "Yousef Alwandi",
email: "Yousefcm5@gmail.com",
phone: "0763075000",
skills: "Java, JS, HTML&CSS",
avatar: "https://i.imgur.com/Q9qFt3m.png",
}
]);
function handelAddNewEmp() {
setEmployess((prevState) => {
return [
...prevState,
{
name: "Sara Svensson",
email: "sara@hotmail.com",
phone: "07011111",
skills: "None",
avatar: "https://i.imgur.com/TUhCrsY.png",
},
];
});
}
return (
<div>
<h3>EmpolyeeList</h3>
<button onClick={handelAddNewEmp} className="button">Add Employee</button>
{employees.map((employee) => (
<Employee EmployeeData={employee} />
))}
</div>
);
}
export default EmployeeList;
| true
|
bf9cbfe811474fe4b3655f46a827049d235c0a96
|
JavaScript
|
jmtomeX/incioNode_Express_mongo
|
/api/index.js
|
UTF-8
| 769
| 2.546875
| 3
|
[] |
no_license
|
// conexion a mongod y creación del server.
"use strict";
const mongoose = require("mongoose");
const app = require('./app');
const port = 3000;
// utizamos las promesas para conectarnos mediante promesas
mongoose.Promise = global.Promise;
// para conectar a mongoose
mongoose
.connect("mongodb://localhost:27017/curso_mean_social", {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log(
"La conexión a la base de datos se ha realizado correctamente.");
// crear servidor
app.listen(port, () => {
console.log("Servidor corriendo en el puerto http://localhost:3000");
})
})
.catch(err => console.log(err));
// Hasta aquí ya se puede trabajar con lo base de datos
//arrancar npm start
| true
|
1cbace38b06eb2908ad904c022bca7b94a10d0e4
|
JavaScript
|
lemondreamtobe/Js-DesignModel
|
/私有公有属性方法/index.js
|
UTF-8
| 399
| 2.65625
| 3
|
[] |
no_license
|
/**
* Created by feng on 2017/7/25.
*/
var Book = function (id, name, price) {
//私有属性
var num = 1;
//私有方法
function sayId() {
};
//公有方法或者特权方法
this.getName = function () {
}; //this.getPrice, this.setName, this.setPrice
//公有属性
this.id = id;
//构造器
this.setName(name);
this.setPrice(name);
};
| true
|
28f6d59ce581864ddb579c255991866dc96efae2
|
JavaScript
|
toshle/toshle.github.io
|
/freeride/js/ski.js
|
UTF-8
| 8,420
| 2.84375
| 3
|
[] |
no_license
|
function init() {
var canvas = document.getElementById('canvas');
if (canvas !== null && canvas.getContext) {
var ctx = canvas.getContext('2d');
console.log("ctx created");
build(ctx, canvas);
} else {
alert("Problem creating canvas 2D drawing context");
}
}
function build(ctx, canvas) {
var ev = {
player: undefined,
horizontalOffset: 0,
verticalOffset: 0,
time: 0,
speed: 1,
ctx: ctx,
canvas: canvas,
playerImage: "img/player.png",
obstacles: [],
difficulty: 0,
points: 0,
multiplier: 0,
debug: false,
gameOver: false,
}
window.addEventListener("keydown", move, false);
window.addEventListener("keyup", refresh, false);
function refresh(e) {
ev.playerImage = "img/player.png";
//ev.verticalOffset = 0;
}
function move(e) {
if (e.keyCode == 37) {
if (ev.horizontalOffset > -300) {
ev.horizontalOffset -= ev.speed + 4;
}
ev.playerImage = "img/playerLeft.png";
}
if (e.keyCode == 38) {
if (ev.verticalOffset > -30) {
ev.verticalOffset -= 2;
ev.speed += 1;
}
}
if (e.keyCode == 39) {
if (ev.horizontalOffset < 300) {
ev.horizontalOffset += ev.speed + 4;
}
ev.playerImage = "img/playerRight.png";
}
if (e.keyCode == 40) {
if (ev.verticalOffset < 0) {
ev.verticalOffset += 2;
ev.speed -= 1;
}
}
}
gameLoop(ev);
}
function gameLoop(ev) {
var vx = 0;
var vt = 0;
var d = new Date();
var t = d.getTime();
(function renderGame() {
loop = window.requestAnimationFrame(renderGame);
if (!ev.gameOver) {
ev.ctx.clearRect(0, 0, ev.canvas.width, ev.canvas.height);
drawMap(ev.ctx, vx);
spawnPlayer(ev);
createObstacles(ev, ev.speed);
drawGUI(ev);
if (Math.abs(vx) > 64) {
vx = 0;
}
if (Math.abs(vt) > 10) {
vt = 0;
}
vx -= ev.speed;
vt += ev.speed;
ev.points += 1 * (ev.speed / 50) + ev.multiplier;
var date = new Date();
ev.time = date.getTime() - t;
if (ev.time % 7 == 0) {
ev.multiplier += 1;
}
} else {
window.cancelAnimationFrame(loop);
ev.ctx.fillStyle = "#FF0000";
ev.ctx.font = "30px Arial";
ev.ctx.fillText("Game Over", 240, 80);
loop = undefined;
var name = prompt("Please enter your name");
if(name == null || name == "") {
name = "Stranger";
}
var highscore = localStorage.getItem("highscore");
if (highscore == null) {
var highscore = new Array();
highscore.push({
player: name,
points: Math.floor(ev.points)
})
} else {
highscore = JSON.parse(highscore);
highscore.push({
player: name,
points: Math.floor(ev.points)
});
}
localStorage.removeItem("highscore");
var row = 0;
ev.ctx.fillStyle = "#000000";
ev.ctx.font = "30px Arial";
ev.ctx.fillText("Highscore", 250, 130 + row * 30);
highscore.sort(function(a, b) {
return b.points - a.points
}).slice(0, 10).forEach(function(entry) {
ev.ctx.fillText(row + 1, 160, 170 + row * 30);
ev.ctx.fillText(Math.floor(entry.points), 210, 170 + row * 30);
ev.ctx.fillText(entry.player, 370, 170 + row * 30);
row += 1;
});
console.log(highscore);
localStorage.setItem("highscore", JSON.stringify(highscore));
}
}());
}
function spawnPlayer(ev) {
ev.player = entities.create("player", 320 + ev.horizontalOffset, 360 + ev.verticalOffset, 64, 64, ev.playerImage);
ev.player.draw(ev);
}
function createObstacles(ev, offset) {
if (Math.floor((Math.random() * 100) + 1) > 80 && ev.obstacles.length < 60) {
for (i = 0; i < 50; i += 10) {
if (Math.floor((Math.random() * 100) + 1) > 80 && ev.obstacles.length < 60) {
ev.obstacles.push(entities.create("tree", Math.floor((Math.random() * 640) + 1), -64, 32, 32, "img/tree.png"));
}
}
}
spawnObstacles(ev, offset);
}
function spawnObstacles(ev, offset) {
ev.obstacles.forEach(function(entry) {
entry.draw(ev);
detectCollision(entry);
if (entry.y < 640) {
entry.translate(0, offset);
} else {
delete entry;
ev.obstacles.shift();
}
});
function detectCollision(object) {
if (ev.player.x > object.x - 12 && ev.player.x < object.x + 12) {
if (ev.player.y > object.y - 12 && ev.player.y < object.y + 12) {
if (ev.debug) {
ev.ctx.strokeStyle = "#FF0000";
ev.ctx.strokeRect(ev.player.x - 16, ev.player.y - 16, 32, 32);
}
ev.multiplier = 0;
ev.gameOver = true;
}
}
if (ev.player.x > object.x - 22 && ev.player.x < object.x + 22) {
if (ev.player.y > object.y - 22 && ev.player.y < object.y + 22) {
if (ev.debug) {
ev.ctx.strokeStyle = "#FFFF00";
ev.ctx.strokeRect(ev.player.x - 16, ev.player.y - 16, 32, 32);
}
ev.ctx.fillStyle = "#FF0000";
ev.ctx.font = "25px Arial";
ev.ctx.fillText("Too close!", 260, 50);
ev.multiplier += 1;
}
}
}
}
function drawGUI(ev) {
// ev.ctx.fillStyle = "#d3d3d3";
// ev.ctx.fillRect(0, ev.canvas.height - 99, ev.canvas.width, 100);
ev.ctx.fillStyle = "#000000";
// ev.ctx.strokeRect(0, ev.canvas.height - 99, ev.canvas.width, 100);
ev.ctx.font = "16px Arial";
ev.ctx.fillText("Points: " + Math.floor(ev.points), 10, 30);
ev.ctx.fillText("Speed: " + ev.speed, 10, 50);
ev.ctx.fillText("Bonus: +" + ev.multiplier, 10, 70);
ev.ctx.fillText("Time: " + Math.floor(ev.time / 600), 10, 90);
}
function drawMap(ctx, offset) {
var x = 0,
y = -128;
image = new Image();
for (var j = 0; j < 100; j++) {
image.src = 'img/snow.png';
if (x == 640) {
x = 0;
y += 64;
}
ctx.globalAlpha = 0.5;
ctx.drawImage(image, x, y - offset);
ctx.globalAlpha = 1.0;
x += 64;
}
}
function drawMap1(ctx, offset) {
var y = -64;
var x = 0;
image = new Image();
function drawRow() {
for (var j = 0; j < 10; j++) {
image.src = 'img/snow.png';
ctx.globalAlpha = 0.5;
ctx.drawImage(image, x, y - offset);
ctx.globalAlpha = 1.0;
x += 64;
}
x = 0;
}
drawRow();
}
var eventable = function(that) {
var registry = {};
that.fire = function(event) {
var array, func, handler, i,
type = typeof event === 'string' ? event : event.type;
if (registry.hasOwnProperty(type)) {
array = registry[type];
for (i = 0; i < array.length; i++) {
handler = array[i];
func = handler.method;
if (typeof func === 'string') {
func = this[func];
}
func.apply(this, handler.parameters || [event]);
}
}
return this;
};
that.on = function(type, method, parameters) {
var handler = {
method: method,
parameters: parameters
};
if (registry.hasOwnProperty(type)) {
registry[type].push(handler);
} else {
registry[type] = [handler];
}
return this;
};
return that;
};
var entities = function() {
function Entity(name, sx, sy, width, height, imageURL) {
this.name = name || "unnamed";
this.x = sx || 0;
this.y = sy || 0;
this.width = width || 0;
this.height = height || 0;
this.image = imageURL || "";
eventable(this);
}
Entity.prototype.toString = function() {
return this.name + " (x: " + this.x + ", y: " + this.y + ") ";
};
Entity.prototype.translate = function(dx, dy) {
this.x += dx;
this.y += dy;
if (this.fire) {
this.fire({
type: 'translate',
payload: this.toString()
});
}
return this;
};
Entity.prototype.draw = function(ev) {
var img = new Image();
img.src = this.image;
//console.log(this.image);
ev.ctx.drawImage(img, 0, 0, this.width, this.height, this.x - this.width / 2, this.y - this.height / 2, this.width, this.height);
if (ev.debug) {
ev.ctx.strokeStyle = "#00FF00";
ev.ctx.strokeRect(this.x - 16, this.y - 16, 32, 32);
}
};
return {
create: function(name, x, y, width, height, imageURL) {
//console.log(name + " created at (" + x + ", " + y + ")");
return new Entity(name, x, y, width, height, imageURL);
}
};
}();
| true
|
2055f445ec0a8df046061cacc88d6bcbe6cc6078
|
JavaScript
|
gazz9ar/amelia-reciclados
|
/toggleSelected.js
|
UTF-8
| 475
| 3.109375
| 3
|
[] |
no_license
|
const tabs = document.querySelectorAll(".tabs");
for (const tab of tabs) {
tab.addEventListener('click',(e) => {
if (e.target.classList.contains('selected')) {
}
else {
for (const tab of tabs) {
if (tab.classList.contains('selected')) {
tab.classList.remove('selected');
}
}
e.target.classList.add('selected');
}
})
}
| true
|
18014b92cf71245c139056a5fd83eb9dda04d55f
|
JavaScript
|
SNIAPA/prnt.sc-screenshot-scraper
|
/main.js
|
UTF-8
| 1,342
| 2.671875
| 3
|
[] |
no_license
|
const puppeteer = require('puppeteer');
const https = require('https');
const fs = require('fs');
const readline = require("readline-sync");
const { randomInt } = require('crypto');
const numsAndLetters = ['1','2','3','4','5','6','7','8','9','0','m','n','b','v','c','x','z','l','k','j','h','g','f','d','s','a','p','o','i','u','y','t','r','e','w','q',];
let current = ['','','','','',''];
(async() =>{
const browser = await puppeteer.launch();
while(true){
length = current.length;
for(let i = 0; i < current.length;i++){
current[i] = numsAndLetters[randomInt(numsAndLetters.length-1)];
}
console.log(`http://prnt.sc/${current.join('')}`);
page = await browser.newPage();
await page.goto(`http://prnt.sc/${current.join('')}`, {waitUntil: 'load'});
const newPage = await page.evaluate(async () => {
if (document.querySelector("#screenshot-image"))
return document.querySelector("#screenshot-image").src;
return false
});
page.close()
if (newPage){
const file = fs.createWriteStream("file.jpg");
const request = await https.get(newPage, async function(response) {
response.pipe(file);
});
}
}
})()
| true
|
edbbca7532065889abb91eb37edaffe9fecba982
|
JavaScript
|
huangguofei/saas_web
|
/saas/resources/js/customize/cursor.js
|
UTF-8
| 2,460
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
var posPrev = 0;
if(window.attachEvent) {
document.onselectionchange = function(e) {
//判断是否支持document.selection属性
if(document.selection) {
var pos = 0;
var range = document.selection.createRange();
var srcele = range.parentElement();
//新建一个range,焦点在开头
var copy = document.body.createTextRange();
copy.moveToElementText(srcele);
//判断copy的焦点起始部分是否在range的焦点起始部分的后面
for(pos = 0; copy.compareEndPoints("StartToStart", range) < 0; pos++) {
//copy的焦点向后移动一个字符
copy.moveStart("character", 1);
}
posPrev = pos;
}
}
} else {
//绑定文本焦点改变事件 注意:firefox不支持document.onselectionchange,可以换成别的事件来触发比如mouseup什么的
document.onselectionchange = function(e) {
//判断是否支持document.selection属性
if(window.getSelection) {
//获取Selection对象
var se = window.getSelection();
//获取起始位置,这个是字符的序号位置,而不是坐标
var start = se.anchorOffset;
//获取结束位置
var end = se.focusOffset;
//获取起始的dom元素
var startEl = se.anchorNode.parentElement;
//获取结束的dom元素
var endEl = se.focusNode.parentElement;
//获取起始dom元素的文本内容
var startText = startEl.innerText;
var txt = '';
if(startEl == endEl) {
txt = startText.substring(start, end);
}
posPrev = start;
}
}
}
$("#s1").click(function() {
//console.log(51465)
if(window.attachEvent) {
// console.log(1)
$("#d1").focus();
var pos = posPrev;
var range = document.selection.createRange();
var srcele = range.parentElement();
//新建一个range,焦点在开头
var copy = document.body.createTextRange();
copy.moveToElementText(srcele);
//判断copy的焦点起始部分是否在range的焦点起始部分的后面
for(pos = 0; copy.compareEndPoints("StartToStart", range) < 0; pos++) {
//copy的焦点向后移动一个字符
copy.moveStart("character", 1);
}
insertHtmlAfterCursor($("#d1"), "我去");
// document.getElementById('i1').value = pos;
// posPrev=pos;
// document.getElementById('i2').value = range.htmlText;
} else {
dingwei(posPrev);
insertHtmlAfterCursor($("#d1"), "谷歌");
}
});
function dingwei(index) {
console.log(index)
var a = document.getElementById("d1");
a.selectionStart = index;
a.focus();
}
| true
|
4e058799a848b3afe6a447017962b799dd93e894
|
JavaScript
|
marinscode/SoftUni
|
/01. Programming Basics with JavaScript/Pre-Exam Feb 2021/03. Cat Life.js
|
UTF-8
| 1,799
| 3.859375
| 4
|
[] |
no_license
|
function solve(input) {
let cat = input.shift();
let gender = input.shift();
let catsMonths = 0;
let isCorrectCat = true;
if (gender == 'm') {
switch (cat) {
case 'British Shorthair':
catsMonths = (13 * 12) / 6;
break;
case 'Siamese':
catsMonths = (15 * 12) / 6;
break;
case 'Persian':
catsMonths = (14 * 12) / 6;
break;
case 'Ragdoll':
catsMonths = (16 * 12) / 6;
break;
case 'American Shorthair':
catsMonths = (12 * 12) / 6;
break;
case 'Siberian':
catsMonths = (11 * 12) / 6;
break;
default:
isCorrectCat = false;
console.log(`${cat} is invalid cat!`);
}
}
if (gender == 'f') {
switch (cat) {
case 'British Shorthair':
catsMonths = (14 * 12) / 6;
break;
case 'Siamese':
catsMonths = (16 * 12) / 6;
break;
case 'Persian':
catsMonths = (15 * 12) / 6;
break;
case 'Ragdoll':
catsMonths = (17 * 12) / 6;
break;
case 'American Shorthair':
catsMonths = (13 * 12) / 6;
break;
case 'Siberian':
catsMonths = (12 * 12) / 6;
break;
default:
isCorrectCat = false;
console.log(`${cat} is invalid cat!`);
}
}
if (isCorrectCat) {
console.log(`${Math.floor(catsMonths)} cat months`);
}
}
solve(["Tom",
"m"]);
| true
|
dc9671431d0c885066b21abd1f31553786ec8e4e
|
JavaScript
|
gennipher/tp2_jennifer_omena_js
|
/exerc1.js
|
UTF-8
| 625
| 4.1875
| 4
|
[] |
no_license
|
// Contar e imprimir quantos números existem entre 0 e 1.000.000
// (exclusives*) que sejam múltiplos de 2 e 3 simultaneamente
//
// * exclusives - Ou seja, quantos números existem entre 0 e 1.000.000,
// excluindo o 1 e o 1.000.000
let result = 0
let num = 1000000
let i = 1
for (i ; i < num; i ++) {
if (i % 6 == 0) {
result += 1;
}
}
console.log("Existem " + result + " números múltiplos de 2 e 3, simultaneamente, entre 0 e 1.000.000.") // result = 166666
// for (i ; i < num; i ++) {
// if (i % 2 == 0) {
// if (i % 3 == 0) {
// result += 1;
// }
// }
// }
| true
|
a814e49833463c78212b74b68eeee92e8d197f2f
|
JavaScript
|
zebaseta/CentinelaMicroservices
|
/organizations/services/token-service.js
|
UTF-8
| 1,165
| 2.59375
| 3
|
[] |
no_license
|
const jwt = require('jsonwebtoken')
const Logger = require('centinela-logger')
const logger = new Logger(__filename)
const envSecret = process.env.ENVIRONMENT_SECRET
module.exports = class TokenService {
constructor() {}
static newNonExpiringToken(data) {
const metadata = {
data: data
}
return generateToken(metadata)
}
static verifyToken(token) {
try {
logger.debug(`Token verification for token: ${token} initiated`)
let result = jwt.verify(token, envSecret)
logger.debug(`Token verification for token: ${token} completed`)
return result
} catch (err) {
throw new Error(`Error verifying token ${err.message}`)
}
}
}
generateToken = (metadata) => {
try {
logger.debug(
`Initiating token request with data: ${JSON.stringify(metadata.data)}`
)
let token = jwt.sign(metadata, envSecret)
logger.debug(
`Done creating token request with data: ${JSON.stringify(metadata.data)}`
)
return token
} catch (err) {
let errorMessage = `Token creation failed with error ${err.message}`
logger.error(errorMessage)
throw new Error(errorMessage)
}
}
| true
|
36dae7648896b98e5b7445700bb593da033a3866
|
JavaScript
|
Jonalogy/react-rxjs
|
/src/App.js
|
UTF-8
| 1,653
| 2.828125
| 3
|
[] |
no_license
|
import React, {Component} from 'react';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {TodoList} from "./components/todo-list.component"
import logo from './logo.svg';
import './App.css';
let Todos = new BehaviorSubject(['apple', 'pear', 'banana']);
class App extends Component {
constructor() {
super()
this.state = {input: '', todos: []}
this.onChangeHandler = this.onChangeHandler.bind(this)
this.onSubmitHandler = this.onSubmitHandler.bind(this)
}
componentWillMount() {
Todos.asObservable()
.subscribe(x => {
this.setState((prevState) => ({...prevState, todos: x}), () => console.log("Initialising State!"))
})
}
onChangeHandler(e) {
let foo = e.target.value.slice(0);
this.setState(prevState => ({...prevState, input: foo}))
}
onSubmitHandler(e){
this.setState(prevState=>({
...prevState,
input: '',
todos: [...prevState.todos, prevState.input]
}))
e.preventDefault();
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo"/>
<h1 className="App-title">React With RXJS</h1>
</header>
<form onSubmit={this.onSubmitHandler}>
<input type="text" onChange={this.onChangeHandler} value={this.state.input}/>
</form>
<TodoList todos={this.state.todos}/>
</div>
);
}
}
export default App;
| true
|
d957d8a19d3938bf87bddc11266cd48ae0a99c1e
|
JavaScript
|
krasa/EclipseCodeFormatter
|
/src/test/resources/test.js
|
UTF-8
| 663
| 2.96875
| 3
|
[
"Apache-2.0",
"EPL-2.0"
] |
permissive
|
/**
* Plugin used to check the component has at least one of the permissions
* provided.
*
* Usage:
*
* This checks only for one permission
*
* var button = new Ext.Button({ plugins: new
* Abc.security.AnyGranted('PERM_LOGIN') });
*
* This checks only for all permissions
*
* var button = new Ext.Button({ plugins: new
* Abc.security.AnyGranted(['PERM_LOGIN','PERM_DASHBOARD']) });
*
* /
*/
function wait(object) {
var objClazz = java.lang.Class.forName('java.lang.Object');
var waitMethod = objClazz.getMethod('wait', null);
waitMethod.invoke(object, null);
}
wait.docString = "convenient wrapper for java.lang.Object.wait method";
| true
|
e6a104b8d5dfd905ae60bdef700b2eb558b6117a
|
JavaScript
|
kocmoc1985/suw16TrainServerSide
|
/www/js/chat.js
|
UTF-8
| 2,523
| 2.78125
| 3
|
[] |
no_license
|
var FINGER_PRINTS;
var lastMessageNr = 0;
$(document).ready(function () {
FINGER_PRINTS = defineFingerPrint();
$(".my-id").text("my id: " + FINGER_PRINTS);
go();
});
function go() {
addListenerSendBtn();
read();
}
function addListenerSendBtn() {
$("#send-btn").click(function () {
var message = $('.chat-text-input').val();
var reciever = $('.chat-send-to').val();
//
if(reciever.length === 0){
reciever = false;
}
//
nodeServerCall("sendMessage", "POST", FINGER_PRINTS, message, reciever, "", true);
$(".chat-text-input").val('');
});
}
function read() {
console.log("Read!");
$.ajax({
async: true,
type: 'POST',
dataType: 'json',
url: "http://localhost:3000/readMessages",
data: {param1: FINGER_PRINTS, param2: new Date().getTime(), param3: lastMessageNr, param4: ""},
success: function (jsonMessages) {
//
jsonMessages.forEach(function (message) {
var chatEntry = $("<div class='chat-msg'></div>");
$(chatEntry).text(message.text + " / " + message.sentby + " / " + message.nr);
setLastMessageNr(message.nr);
$("body").append(chatEntry);
});
//
read();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("connection dropped");
read();
}
});
}
/**
* To get params in GET use: "req.query.param1"
* To get params in POST use: "req.body.param1"
* @param {String} link - ex 'getUsers'
* @param {String} getPost - 'GET' or 'POST'
* @param {String} par1
* @param {String} par2
* @param {String} par3
* @param {String} par4
* @param {Boolean} isJason
* @returns {jqXHR.responseText}
*/
function nodeServerCall(link, getPost, par1, par2, par3, par4, isJason) {
//
$.ajax({
async: isJason,
type: getPost,
url: "http://localhost:3000/" + link,
data: {param1: par1, param2: par2, param3: par3, param4: par4},
success: function (data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Send message failed");
}
});
}
function defineFingerPrint() {
var client = new ClientJS();
return client.getFingerprint();
}
function setLastMessageNr(nr) {
if (nr > lastMessageNr) {
lastMessageNr = nr;
}
}
| true
|
0a61cb31170b64ba5ff45c007897acfcd29cd750
|
JavaScript
|
henrysnavarro/minesweep-r
|
/src/react/MinesweeperCell.js
|
UTF-8
| 3,390
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
import React, { Component } from 'react';
import bomb from '../media/bomb.svg';
import flag from '../media/flag-red.svg';
/* MinesweeperCell: custom component for the cell
* handles the clicks (left-click to open, right-click to flag/unflag)
* as well as calls handlers for the same events passed on to it from
* the board, and the game components.
* Renders the number of adjacent mined cells in a color- and size-coded
* manner
*/
class MinesweeperCell extends Component {
// expected properties:
// { isMined: boolean, // if the cell has a mine
// opened: boolean, // cell is open
// flagged: boolean, // cell is flagged,
// rowNum: int, // 1-indexed row number of cell
// colNum: int, // 1-indexed column number of cell
// ref: React ref // React DOM/element ref for the cell
// cellID: int, // 1-indexed sequential ID of the cell
// adjacentCount: int // number of adjacent mined cells
// onOpen: handler function for opening cell, passed from parent
// onFlag: handler function for flagging cell, passed from parent
// }
constructor(props) {
super(props);
this.state = {
isMined: this.props.isMined,
flagged: false,
opened: false,
mineRevealed: false
}
this.handleClick = this.handleClick.bind(this);
this.handleRightClick = this.handleRightClick.bind(this);
this.adjacentCountColors = [
{color: 'white', fontSize: '10px'},
{color: 'blue', fontSize: '12px'},
{color: 'green', fontSize: '14px'},
{color: 'red', fontSize: '16px'},
{color: 'purple', fontSize: '18px'},
{color: 'brown', fontSize: '20px'},
{color: 'orange', fontSize: '22px'},
{color: 'cyan', fontSize: '14px'},
{color: 'black', fontSize: '26px'},
];
}
handleClick(e) {
if (!this.state.opened && !this.state.gameFinished) {
this.open();
this.setState({steppedOn: this.state.isMined});
this.props.onOpen(this.props.cellID);
}
}
handleRightClick(e) {
e.preventDefault();
if (!this.state.opened && !this.state.gameFinished) {
this.props.onFlag(this.props.cellID);
this.setState( prevState => ({flagged: !prevState.flagged}));
}
}
open() {
this.setState({opened: true, flagged: false});
}
revealMine() {
this.setState({opened: true, flagged: false, mineRevealed: true});
}
render() {
return (
<div className="cell"
id={this.props.cellId}
onClick={this.handleClick}
onContextMenu={this.handleRightClick}
>
{ this.props.isMined &&
<div className={"mineShell" +
( this.state.steppedOn ? " steppedOn" : (this.state.mineRevealed ? " mineRevealed" : "") )}>
<img src={bomb} className="icon" alt=""/>
</div>
}
{ !this.props.isMined && (this.props.adjacentCount > 0) &&
<div className="adjacentCount"
style={this.adjacentCountColors[this.props.adjacentCount]}>{this.props.adjacentCount}
</div>
}
<div className={ "cellCover " +
( this.state.opened || this.state.mineRevealed ? "cellOpened" + this.props.openmode : "" ) }></div>
{ !this.state.opened && this.state.flagged &&
<div className="cellFlag">
<img src={flag} className="icon flag" alt=""/>
</div>
}
</div>
)
}
}
export default MinesweeperCell;
| true
|
dcf3597be7a57a4e2ab398074c59680f863d4b5f
|
JavaScript
|
factoryfour/cache-utility
|
/src/CacheUtility.js
|
UTF-8
| 6,774
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
class CacheUtility {
static isAvailable(type) {
// Helper method to determine if both the store exists and has space
const storage = window[type];
try {
const x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
} catch (e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage.length !== 0;
}
}
constructor(config) {
this.config = config;
// Determine the target storage entity on the window
this.target = window[config.target];
// Store the desired tiers from longest to shortest expiration
this.sortedTiers = config.tiers
.filter((tier) => {
// We don't want any tiers with white space in the name
if (tier.name.match(/\s/g)) {
console.error(`Invalid tier name "${tier.name}" with whitespace`);
return false;
}
return true;
})
.sort((a, b) => {
if (a.expiration < b.expiration) {
return 1;
}
if (a.expiration > b.expiration) {
return -1;
}
return 0;
});
/* Now that the tiers are sorted in decreasing expiration, we can
generate the map of tier name to key. This key is a concatendated list
of all of the tier names that precede the current tier. This allows us
to filter all tiers that should expire given a particular amount of inactivity */
this.tierMap = {};
this.sortedTiers.forEach((tier, index) => {
if (index === 0) {
this.tierMap[tier.name] = {
key: tier.name,
expiration: tier.expiration,
};
} else {
this.tierMap[tier.name] = {
key: `${this.tierMap[this.sortedTiers[index - 1].name].key}-${tier.name}`,
expiration: tier.expiration,
};
}
});
if (this.isAvailable()) {
// Invalidate based on existing last-change
this.invalidate();
}
// Initialize the map of keys the user has added to the store
this.keyMap = {};
}
/** Retrieves the associated data from storage */
get(key) {
// If target is undefined (storage doesn't exist), return null
if (!this.target) {
return null;
}
// Initiate the removal of invalid tiers
if (this.invalidate()) {
// If this key is in the key map, return it. Else return null
return this.keyMap[key] ? JSON.parse(this.target.getItem(this.keyMap[key])) : null;
}
// If invalidation fails, return null
return null;
}
/** Puts a desired value into the target store. Returns null if unsuccessful */
set(key, value, tier) {
// If the desired tier doesn't exist, print a warning to the console and return false
if (!this.tierMap[tier]) {
console.error(`Tier ${tier} does not exist`);
return false;
} else if (!this.isAvailable()) {
// If no space is available, return false
return false;
} else if (this.keyMap[key] && this.keyMap[key] !== `${this.tierMap[tier].key}-${key}`) {
/* If the user has supplied a different tier than exists for the current key
prevent set and alert the user */
console.error(`Cannot set existing key ${key} new tier ${tier}`);
return false;
}
// Prevent setting if a tier name is present in the key
const invalidKeyName = this.sortedTiers.some(t => key.indexOf(t.name) > -1);
if (invalidKeyName) {
console.error('Cannot include tier name in key name');
return false;
}
// Initiate the removal of invalid tiers
if (this.invalidate()) {
const newValue = JSON.stringify(value);
const newKey = `${this.tierMap[tier].key}-${key}`;
try {
this.target.setItem(newKey, newValue);
this.keyMap[key] = newKey; // Update the map of user to target keys
// Successful set
return true;
} catch (e) {
// Unsuccessful set
console.error(e);
return false;
}
}
// If invalidation fails, do not set
return false;
}
/** Removes the desired key from the desired tier */
remove(key) {
// If target doesn't exist, return false
if (!this.target) {
return false;
} else if (!this.keyMap[key]) {
// If the key doesn't exist, return false
return false;
}
// Remove the target
this.target.removeItem(this.keyMap[key]);
delete this.keyMap[key];
// Invalidate
this.invalidate();
return true;
}
/** Removes all keys in the store */
removeAll() {
// If target doesn't exist , return false
if (!this.target) {
return false;
}
// Simply remove all keys that contain the heighest tier
const filter = `${this.sortedTiers[0].name}-`;
Object.keys(this.target).forEach((key) => {
if (key.indexOf(filter) > -1) {
this.target.removeItem(key);
}
});
this.keyMap = {};
try {
// Manually reset last-change
const now = Date.now();
this.target.setItem('last-change', JSON.stringify(now));
} catch (e) {
console.error(e);
}
return true;
}
invalidate() {
// Determine the amount of inactivity
const now = Date.now();
const lastChange = JSON.parse(this.target.getItem('last-change'));
try {
// Attempt to reset the lastChange
this.target.setItem('last-change', JSON.stringify(now));
} catch (e) {
// If this attempt fails, return false and prevent invalidation
console.error(e);
return false;
}
// Attempt invalidation if lastChange was updated
if (lastChange) {
const inactivity = now - lastChange;
/* Based on the amount of inactivity, determine
which tiers should be removed and remove all of
those tiers */
let filter = '';
/* Here, we generate the filter string, which is a concatenation
of tier names starting from the longest to the first tier that will
expire given the amount of inactivity. If the tiers are sorted C,B,A from longest
to shortest duration and we expect tiers B and A to expire, the filter will be
C-B- because only keys within Tiers B and A will include this substring. */
const invalid = this.sortedTiers.some((tier) => {
if (tier.expiration > inactivity) {
filter = filter.concat(`${tier.name}-`);
return false;
}
filter = filter.concat(`${tier.name}-`);
return true;
});
// If there exists a tier to invalidate, do it
if (invalid) {
Object.keys(this.target).forEach((key) => {
// If filter is present, remove
if (key.slice(0, filter.length) === filter) {
this.target.removeItem(key);
}
});
}
}
return true;
}
// Helper method to determine if both the store exists and has space
isAvailable() {
return CacheUtility.isAvailable(this.config.target);
}
}
export default CacheUtility;
| true
|
e563c04cd7e099de82bbdaa6e1c37dbfc333b842
|
JavaScript
|
ManuPuyol/Recursos-JavaScript
|
/JavaScript/Date.js
|
UTF-8
| 467
| 3.328125
| 3
|
[] |
no_license
|
function diasEntreFechas(fecha1,fecha2){
const unDia = 1000 * 60 *60 *24
const diferencia= Math.abs(fecha1-fecha2)
return Math.floor(diferencia/unDia)
}
const hoy = new Date()
const nacimiento = new Date(1990,7,12)
var date = new Date()
var dateNow = {
anio: date.getFullYear(),
mes: date.getMonth(),
dia: date.getDay()
}
console.log(`Hoy es: ${dateNow.dia}-${dateNow.mes}-${dateNow.anio}`)
setTimeout(() => console.log(3), 0)
console.log(4)
| true
|
dd7c33223d134143e5333c8e5a65fbfa8e0f5ff7
|
JavaScript
|
IgorTorgaiev/jQuery-effects
|
/script/script.js
|
UTF-8
| 4,752
| 3.03125
| 3
|
[] |
no_license
|
// jQuery Effects
// First, let's see what can happen with the text when you click the buttons one by one.
// $(document).ready(function(){
// $("#hide").click(function(){
// $("p").hide();
// });
// $("#show").click(function(){
// $("p").show();
// });
// });
// Slow and Fast
// $(document).ready(function(){
// $("#hide").click(function(){
// $("#first").hide(1000);
// });
// $("#show").click(function(){
// $("#second").show("fast");
// });
// $("#show").click(function(){
// $("#first").show("fast");
// });
// });
// Fade: fadeIn() and fadeOut()
// $(document).ready(function(){
// $("button").click(function(){
// $("#first").fadeIn("slow");
// });
// $("button").click(function(){
// $("#second").fadeIn(1000);
// });
// $("button").click(function(){
// $("#third").fadeIn("fast");
// });
// $("button").click(function(){
// $("#answer").show(3000);
// });
// $("button").click(function(){
// $("#answer").hide("slow");
// });
// });
// $(document).ready(function(){
// $("#clear").click(function(){
// $("#third").fadeOut("fast");
// });
// $("#clear").click(function(){
// $("#second").fadeOut();
// });
// $("#clear").click(function(){
// $("#first").fadeOut("fast");
// });
// });
// fadeToggle()
// $(document).ready(function(){
// $("button").click(function(){
// $("#first").fadeToggle("slow");
// });
// $("button").click(function(){
// $("#second").fadeToggle(1000);
// });
// $("button").click(function(){
// $("#third").fadeToggle("fast");
// });
// });
// $(document).ready(function(){
// $("#smile").click(function(){
// $("img").fadeIn("slow");
// });
// });
// Now, we will substitute all the previous fade-related sub-topics with the fadeTo()
// $(document).ready(function(){
// $("button").click(function(){
// $("#first").fadeTo("slow", 0.3);
// });
// $("button").click(function(){
// $("#second").fadeTo("slow", 0.6);
// });
// $("button").click(function(){
// $("#third").fadeTo("slow", 0.9);
// });
// $("button").click(function() {
// $("img").fadeTo("slow", 0.5);
// });
// });
// Slide: slideDown()
// $(document).ready(function(){
// $("#click").click(function(){
// $("#text").slideDown("slow");
// });
// });
// Slide: slideUp()
// $(document).ready(function(){
// $("#click").click(function(){
// $("#text").slideUp(1000);
// });
// });
// SlideToggle()
// $(document).ready(function(){
// $("#push").click(function(){
// $("img").slideToggle();
// });
// });
// Animations
// $(document).ready(function(){
// $("#right").click(function(){
// $("img").animate({
// left: '400px'
// });
// });
// $("#left").click(function(){
// $("img").animate({
// left: '0px'
// });
// });
// });
// $(document).ready(function(){
// $("#right").click(function(){
// $("img").animate({left: '400px'});
// });
// $("#right").click(function(){
// $("img").animate({left: '0px'});
// });
// });
// Animate: Manipulation
// $(document).ready(function(){
// $("button").click(function(){
// $("div").animate({
// left: '250px',
// opacity: 0.4,
// height: '+=50px',
// width: '+=50px'
// });
// });
// });
// $(document).ready(function(){
// $("button").click(function(){
// $("div").animate({
// height: 'toggle'
// });
// });
// });
// $(document).ready(function(){
// $("button").click(function(){
// var div = $("div");
// div.animate({left: '400px'}, "slow");
// div.animate({fontSize: '3em'}, 3000);
// });
// });
// Stop()
// $(document).ready(function(){
// $("#slide").click(function(){
// $("#text").slideDown(3000);
// });
// $("button").click(function(){
// $("#text").stop();
// });
// });
// Callback
// $(document).ready(function(){
// $("button").click(function(){
// $("p").hide("slow", function(){
// alert('The text has gone away');
// });
// });
// });
// Other option
// $(document).ready(function(){
// $("button").click(function(){
// $("p").hide(1000);
// alert('The text is hidden');
// });
// });
// Chaining
$(document).ready(function(){
$("button").click(function(){
$("p").css("color", "yellow").slideUp(2000).slideDown(2000);
});
});
| true
|
ef1827306cf4ddbf55cb0e858a1efe1038ae6670
|
JavaScript
|
arvarv/pnp
|
/assets/js/index.js
|
UTF-8
| 3,716
| 2.9375
| 3
|
[] |
no_license
|
//user data
var user = {
email: "john.smith@email.com",
password: "12345",
cart: [{name: "Aqua Therapy", quantity: 1},
{name: "Bourbon 150mg", quantity: 2},
{name: "Forever Royal Jelly 60 Tablets", quantity:1},
{name: "Holle Organic Growing-up Milk 3", quantity:1}
]
}
//if user data doesn't exist
if (localStorage.getItem("user") == null ) {
localStorage.setItem("user", JSON.stringify({email: "john.smith@email.com", password: "12345"}));
}
//init default cart values
if (localStorage.getItem("cart") == null) {
initCart();
}
//update nav cart count
updateNavCart();
//Nav Cart Behavior
$(".floating-cart-wrapper").css({opacity: 0, visibility: "hidden"});
$(".my-cart").on("click", function () {
var opacity = $(".floating-cart-wrapper").css("opacity");
if (opacity == 0) {
$(".floating-cart-wrapper").css({visibility: "visible"}).animate({opacity: 1}, 300);
} else {
$(".floating-cart-wrapper").css({visibility: "hidden"}).animate({opacity: 0}, 300);
}
});
$(document).on("click", function () {
var opacity = $(".floating-cart-wrapper").css("opacity");
if (opacity == 1) {
$(".floating-cart-wrapper").css({visibility: "hidden"}).animate({opacity: 0}, 300);
}
});
$("#checkout-btn").on("click", function (e) {
e.preventDefault();
var cart = JSON.parse(localStorage.getItem("cart"));
if (cart.length > 0) {
window.location.href="checkout.html";
} else {
alert("You have no items in your cart.");
}
});
//Stepper +- quantity
$(".minus-btn").on("click", function () {
var itemCount = $(this).siblings(".item-count");
var count = parseInt(itemCount.text());
if (count > 0) {
count -= 1;
}
itemCount.text(count);
});
$(".plus-btn").on("click", function () {
var itemCount = $(this).siblings(".item-count");
var count = parseInt(itemCount.text());
count += 1;
itemCount.text(count);
});
// Functions
function initCart() {
var navCart = [{
name: "Aqua Therapy",
price: 565,
quantity: 1,
image: "assets/images/item1-final.png",
discount: 21
}];
localStorage.setItem("cart", JSON.stringify(navCart));
}
function updateNavCart() {
var storedCart = JSON.parse(localStorage.getItem("cart"));
var quantity = 0;
var navCartList = $(".floating-cart ul");
//remove child elements from Nav Cart
navCartList.empty();
//add udpated child elements
for (let i = 0; i < storedCart.length; i++) {
const element = storedCart[i];
quantity += element.quantity;
var childElement =
'<li>' +
'<div class="floating-item-wrapper d-flex justify-content-start align-items-center mb-2">' +
'<div class="fc-img-holder d-flex justify-content-center align-items-center m-0" >' +
'<img class="img-item" src="' + element.image + '">' +
'</div>'+
'<div class="d-flex flex-column justify-content-center ml-3">' +
'<p class="m-0 small-p text-dark">' + element.name + '<span>('+ element.quantity +')</span>'+'</p>' +
'<p class="mt-2 mb-0 cart-item-price">P ' + element.price.toFixed(2) + '</p>' +
'</div>' +
'</div>' +
'<hr>' +
'</li>'
navCartList.append(childElement);
}
//udpate cart count
$(".cart-count").text(quantity);
}
function numberWithCommas(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
| true
|
6e7f3b709956d99ac64f6458da5845323ab4f962
|
JavaScript
|
tobymackenzie/Web-ClientBehavior
|
/old/elements/elementValueManager.jq.js
|
UTF-8
| 3,038
| 3.171875
| 3
|
[] |
no_license
|
/*
Class: ElementValueManager
Provides uniform interface for getting and (setting) 'values' of an element (or collection of radio buttons), monitoring them for changes
Dependencies:
tmlib
jquery
Parameters:
dataSourceValue(String): value of specified element attribute or data key
elements(jQuery): element(s) this interface provides data for
event(String): event to trigger on change
type(String): type of source this class is, changes what to monitor. Can be one of 'attribute', checked', 'data', or 'value'
Example:
$(document).ready(function(){
var elmValueManagerPrice = new __.classes.elementValueManager({element:elmThis, type: 'attribute', dataSourceValue: 'data-price'})
var elmValueManagerQuantity = new __.classes.elementValueManager({element:elmThis.find('select'), type: 'value'})
}
*/
/* global __ */
__.classes.ElementValueManager = __.core.Classes.create({
'properties': {
'type': 'value'
,'dataSourceValue': null
,'elements': null
,'event': 'change'
,getValue: function(){
var _return = false;
var _type = this.type;
var _elements = (this.elements.length > 1)
? this.elements.filter(':checked')
: this.elements
;
if(_type.substr(0, 7) == 'checked'){
var _newDataSource = _type.substr(7);
if(_return){
_type = (_newDataSource) ? _newDataSource : _type;
}else{
_type = false;
}
}
switch(_type){
case 'attribute':
_return = _elements.attr(this.dataSourceValue);
break;
case 'data':
_return = _elements.data(this.dataSourceValue);
break;
case 'value':
_return = _elements.val();
break;
}
return _return;
}
,on: function(){
this.elements.on.apply(this.elements, arguments);
return this;
}
,setValue: function(_value){
var _type = this.type;
var _elements = (this.elements.length > 1)
? this.elements.filter(':checked')
: this.elements
;
if(_type.substr(0, 7) == 'checked'){
var _newDataSource = _type.substr(7);
_elements.checked = true;
if(_value != 'checked'){
_type = (_newDataSource) ? _newDataSource : _type;
}else{
_type = false;
}
}else{
if(_value == 'checked'){
_elements.attr('checked', 'checked');
}else{
_elements.removeAttr('checked');
}
}
if(this.elements.length > 1 && _type == 'value'){
_elements = this.elements.filter('[value="' + _value + '"]');
_elements.attr('checked', 'checked');
}else{
switch(_type){
case 'attribute':
_elements.attr(this.dataSourceValue, _value);
break;
case 'data':
_elements.data(this.dataSourceValue, _value);
break;
case 'value':
_elements.val(_value);
break;
}
}
//--trigger event for listeners
_elements.trigger(this.event, {value: this.getValue(), manager: this});
return this;
}
,val: function(){
var _args = arguments;
if(_args.length === 0){
return this.getValue.apply(this, _args);
}else{
return this.setValue.apply(this, _args);
}
}
}
});
| true
|
a7604767aa3ef71661a5a57e29e3ce8a5fad7424
|
JavaScript
|
dimaserd/Runtasker
|
/Runtasker/Scripts/MyScripts/ChatScript.js
|
UTF-8
| 2,245
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
//Функции для динамического изменения временной отметки
function T()
{
{
var email = document.getElementById("EmailInput").value;
var re = /^ (([^<> ()[\]\.,;:\s@"]+(\.[^<>()[\]\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(email))
{
WriteError('Email', 'Данное поле не является электронным адресом!');
return false;
}
else
{
HideError('Email');
return true;
}
}
}
function DateCarer()
{
var messages = $('li .mes');
for(i = 0; i < messages.length; i++)
{
id = messages[i].attr('id');
console.log(id);
TimeSpanChanger(id);
}
}
function TimeSpanChanger(id) {
var today = new Date();
var date = $('#' + id).attr('data'); //getting message date
var diffMs = (today - date); // milliseconds between now & message date
$('#' + id + ' .timeSpan').html("<span class='glyphicon glyphicon-time'></span>" + GetTimeSpan());
//Debug purposes
console.log($('#' + id + ' .timeSpan'));
function inDays() {
return Math.round(diffMs / 86400000); // days
}
function inHours() {
return Math.round((diffMs % 86400000) / 3600000); // hours
}
function inMins() {
return Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
}
function GetTimeSpan()
{
var time = "";
if (inMins() < 2)
{
time = "Just now";
}
else if (inHours() < 1)
{
time = inMins() + " mins ago";
}
else if (date.getUTCDate() != today.getUTCDate())
{
time = inHours() + "Yesterday";
}
else if(inHours() < 24)
{
time = inHours() + " hours ago";
}
else
{
var month = date.getUTCMonth() + 1; //months from 1-12
var day = date.getUTCDate();
var year = date.getUTCFullYear();
time = day + "/" + month + "/" + year;
}
return time;
}
}
| true
|
6b4d55beb1971fb482d34b9897172f2a46be8882
|
JavaScript
|
valsui/TicTacToe
|
/src/Components/Board/board.test.js
|
UTF-8
| 823
| 2.546875
| 3
|
[] |
no_license
|
import React from 'react'
import Board from './board'
import { shallow, mount } from 'enzyme'
//shallow rendering is used for isolated unit tests
it('renders without crashing', () => {
shallow(<Board />);
});
//mount for component integration
//not working
it('calls onClick event on click of a board square', () => {
let wrapper = mount(<Board />);
const markSquare = jest.fn();
wrapper.find('button.square').first().simulate('click');
expect(markSquare).toBeCalledWith(0)
})
it('renders game status correctly', () => {
const wrapper = mount(<Board />);
const firstPlayer = wrapper.find('div.status');
// const test = wrapper.find('div.status').children().first();
// console.log(firstPlayer);
expect(firstPlayer).toHaveLength(1);
// expect(test).toEqual('Next player: X')
})
| true
|
315199489f54ad386d4a92b6206df481f490a725
|
JavaScript
|
sing2gather/sentry-sourcemaps
|
/src/App.js
|
UTF-8
| 873
| 2.71875
| 3
|
[] |
no_license
|
import logo from './logo.svg';
import './App.css';
function throwError(text) {
throw new Error(text);
}
function newThrowError() {
throw new Error('Une toute nouvelle erreur !!!');
}
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<button type="button" onClick={() => throwError('Une erreur est survenue !')}>Throw an Error</button>
<button type="button" onClick={() => throwError('Une autre erreur est survenue !')}>Throw an other Error</button>
<button type="button" onClick={() => throwError('Une autre autre erreur est survenue !')}>Throw an other other Error</button>
<button type="button" onClick={() => newThrowError()}>An Other button that generates an Error</button>
</header>
</div>
);
}
export default App;
| true
|
fe3ae50ac66dccb88eb72d030748875e98bba9da
|
JavaScript
|
prakashstha/TwoFactorProject
|
/EventsReader/js/EventsReader.js
|
UTF-8
| 6,090
| 2.65625
| 3
|
[] |
no_license
|
var event_time = 0;
var event_type, eType, code, keyCodeValue, sync_event_time;
var f_id, field_ID=0;
var dataToSend;
/*events file that store events information*/
var inputEventsFile;
/* field to show the events recording info */
var eventsField = 'EVENTS';
/* Messages for UI fields*/
var EventsRecordingStartMessage = "Events Recording: STARTED";
var EventsRecordingStopMessage = "Events Recording: STOPPED";
var EventsNotRecordedMessage = "Events Recording: NOT RECORDED";
//showMessage(eventsField, EventsNotRecordedMessage);
/*************************************
* EVENTS ID *
*************************************/
var eventID = {
KEYDOWN: 1,
KEYUP:2,
MOUSEDOWN:4,
MOUSEUP:5,
MOUSEMOVE:7,
SCROLLDOWN:9,
SCROLLUP:10
};
/**********************************************
* FIELD IN WHICH EVENT IS TRIGGERED *
**********************************************/
var fieldID = {
USERNAME:1,
PASSWORD:2,
OTHER:3
};
// $("body").on("keyup keydown mousedown mouseup mousemove",function(event){
function eventsHandler(event){
//showMessage(eventsField, 'Initiallizing...');
event_time = (new Date()).getTime();
eType = event.type;
f_id = event.target.id;
//keyCodeValue = '';
if(eType == 'keyup' || eType == 'keydown'){
//code =
keyCodeValue = event.which || event.keyCode;
//document.getElementById("div3").innerHTML = keyCodeValue + ": "+ String.fromCharCode(keyCodeValue);
}
//$("#div1").html("Time Diff: " + getAvgTimeDiff() + ": "+ event_time+"<br/>");
/* ==== Assigning event id ===== */
if(eType == 'keydown'){
event_type = eventID.KEYDOWN;
}
else if(eType == 'keyup'){
event_type = eventID.KEYUP;
}
else if(eType == 'mousedown'){
event_type = eventID.MOUSEDOWN;
}
else if(eType == 'mouseup') {
event_type = eventID.MOUSEUP;
}
else if(eType == 'mousemove'){
event_type = eventID.MOUSEMOVE;
}
/* ==== Assigning field id ===*/
if(f_id == 'username'){
field_ID = fieldID.USERNAME;
//$("#div1").html('keydown:' + event_type);
}
else if(f_id == 'password'){
field_ID = fieldID.PASSWORD;
//$("#div1").html('keyup' + event_type);
}
else{
field_ID = fieldID.OTHER;
//$("#div1").html('mousedown' + event_type);
}
if(eType == 'keyup' || eType == 'keydown'){
dataToSend = {
action : 'input_event',
filename : inputEventsFile,
eventType : event_type,
eventTime : event_time,
//syncTime : sync_event_time,
fieldIDent : field_ID,
keyCode : keyCodeValue
};
}else{
dataToSend = {
action : 'input_event',
filename : inputEventsFile,
eventType : event_type,
eventTime : event_time,
//syncTime : sync_event_time,
fieldIDent : field_ID
};
}
/*=== sending to EventsWriter.php to write into files ===*/
//var dataString = event.type;
$.ajax({
type: "POST",
url: "eventsWriter.php",
data: dataToSend,
success: function() {
//$('#div2').html("? Logged!" + event.target.id);
}
});//end of .ajax({})
//});//end of on() function
}//end of function
/*=== Registering mouse wheel events ===*/
$(window).bind('DOMMouseScroll', function(event){
event_time = (new Date()).getTime();
//sync_event_time = event_time - getAvgTimeDiff();
eType = event.type;
f_id = event.target.id;
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
// scroll up
event_type = eventID.SCROLLUP;
//$("#div1").html("Event up: " + eType + ": "+ event_time+"<br/>"+f_id+"<br/>");
}
else {
// scroll down
event_type = eventID.SCROLLDOWN;
//$("#div1").html("Event down: " + eType + ": "+ event_time+"<br/>"+f_id+"<br/>");
}
/* ==== Assigning field id ===*/
if(f_id == 'username'){
field_ID = fieldID.USERNAME;
//$("#div1").html('keydown:' + event_type);
}
else if(f_id == 'password'){
field_ID = fieldID.PASSWORD;
//$("#div1").html('keyup' + event_type);
}
else{
field_ID = fieldID.OTHER;
//$("#div1").html('mousedown' + event_type);
}
/*sending to EventsWriter.php to write into files*/
//var dataString = event.type;
$.ajax({
type: "POST",
url: "eventsWriter.php",
data: {
action : 'input_event',
filename : inputEventsFile,
eventType : event_type,
eventTime : event_time,
//syncTime : sync_event_time
},
success: function() {
//$('#div2').html("? Logged!" + event.target.id)
}
});//end of .ajax({})
});//end of DOMMouseScroll
/**
* Adding supplied events handler
*/
function addEventsHandler(bEventsFile, param_events){
var i;
inputEventsFile = bEventsFile;
for(i = 0; i < param_events.length; i++){
console.log("Events " + i + ": " + param_events[i]);
document.addEventListener(param_events[i], eventsHandler);
showMessage(eventsField, param_events[i] + ' event handler added...');
}
showMessage(eventsField, EventsRecordingStartMessage);
/*document.addEventListener("keyup", eventsHandler);
document.addEventListener("keydown", eventsHandler);
document.addEventListener("mousedown", eventsHandler);
document.addEventListener("mouseup", eventsHandler);
document.addEventListener("mousemove", eventsHandler); */
}
/**
* Removing the events handler
*/
function removeEventsHandler(param_events){
showMessage(eventsField, 'Removing Events Handler...');
var i;
for(i = 0; i < param_events.length; i++){
document.removeEventListener(param_events[i], eventsHandler);
showMessage(eventsField, 'Removing ' + param_events[i] + ' event handler...');
}
showMessage(eventsField, EventsRecordingStopMessage);
}
/* method to show message in the eventsreader message field in UI */
/*function showMessage(message){
eventsField.innerHTML = message;
}*/
| true
|
12aa3cdda334999d8d873b0ff52c7cfddf5de62e
|
JavaScript
|
kevinjiang2016/simon2
|
/js/main.js
|
UTF-8
| 5,134
| 3.703125
| 4
|
[] |
no_license
|
//this is a constructor of a color object that has a string ID
//which is the color name and has an Audio object connected to
//an associated sound file
function Color(ID, audioFile) {
this.ID = ID
this.audioFile = new Audio(audioFile)
}
//variable determines the time between consecutive lights in
//a sequence
var lightTime = 1
var colorArray, stillAlive, correct, sequenceNumber, lose,
buttonPushed
//this variable is an audio object that plays when the player
//loses
lose = new Audio("audio/lose.mp3")
//these initialize all 4 color objects for the buttons on the
//game face
var greenObject = new Color("green", "audio/green.mp3")
var redObject = new Color("red", "audio/red.mp3")
var yellowObject = new Color("yellow", "audio/yellow.mp3")
var blueObject = new Color("blue", "audio/blue.mp3")
//this is a function that takes in a color and turns the light
//on for the corresponding button on the game face
function LightOn(color) {
//shows a picture on top of the game face that looks like
//the button only lit up
document.getElementById(color.ID).style.display = "unset"
//calls the function to turn off the corresponding light
//after 1/2 the time between corresponding lights firing
setTimeout(LightsOff,(lightTime*500),color)
}
//this function plays the sound for the corresponding color
function SoundOn(color) {
color.audioFile.play()
}
//this function turns off the light
function LightsOff(color) {
document.getElementById(color.ID).style.display = "none"
}
//this function returns a random color object
function RandomColor() {
var myRandom = Math.floor(Math.random()*4)+1
if(myRandom < 2) {
return greenObject
}
else if(myRandom < 3) {
return redObject
}
else if(myRandom < 4) {
return yellowObject
}
else if(myRandom < 5) {
return blueObject
}
else {
}
}
//this function plays an array of color objects in order
//this is used to play the sequence before you guess
function Playback(array) {
buttonPushed = true
var i = 0;
LightOn(array[i])
SoundOn(array[i])
buttonPushed = true
setInterval(function() {
i++;
if (i < array.length) {
LightOn(array[i])
SoundOn(array[i])
buttonPushed[i] = true
}
}, lightTime*1000)
buttonPushed = false
setTimeout(TimeLimit, 4000+(array.length*1000),
(function(tempSequenceNumber){return tempSequenceNumber}(sequenceNumber)),
(function(tempCorrect){return tempCorrect}(correct)))
}
//this returns all parts of the game back to the beginning
function NewGame() {
//initially sets the colorArray to empty. This will be filled
//with color objects
colorArray = []
//this variable lets the game know if you lost or not
stillAlive = true
//initially sets which sequence number we are checking to 1
sequenceNumber = 1
//initially sets the counter to 0 and displays it
correct = 0
document.getElementById("counter").innerHTML = correct
//puts the first random color into the sequence array
//and then plays the sequence in order
colorArray.push(RandomColor())
Playback(colorArray)
return
}
//this function ends the game and plays the losing music
function EndGame() {
stillAlive = false
LightOn(greenObject)
LightOn(redObject)
LightOn(yellowObject)
LightOn(blueObject)
lose.play()
return
}
function TimeLimit(myNumber1, myNumber2) {
if((sequenceNumber > myNumber1)||(correct > myNumber2)) {
return
}
else {
EndGame()
}
}
//this function lets the user determine if his choices of
//colors picked are correct with the array sequence of colors
function Check(color) {
buttonPushed = true
// console.log(buttonPushed)
// console.log(sequenceNumber)
LightOn(color); SoundOn(color);
if (stillAlive) {
//if guess is correct
if (color.ID === colorArray[sequenceNumber-1].ID) {
//if the correct guess is the last light in sequence
if (sequenceNumber === colorArray.length) {
//You win this level
correct++
document.getElementById("counter").innerHTML = correct
sequenceNumber = 1
colorArray.push(RandomColor())
setTimeout(Playback, lightTime*1500, colorArray)
return
}
//not the last light in sequence? then we'll check the next
//sequence light in the sequence
else {
sequenceNumber++
buttonPushed = false
setTimeout(TimeLimit, 5000,
(function(tempSequenceNumber){return tempSequenceNumber}(sequenceNumber)),
(function(tempCorrect){return tempCorrect}(correct)))
return
}
}
//guess is incorrect?
else {
EndGame()
return
}
}
else {
return
}
}
//these initialize all buttons and displays on load
document.getElementById("counter").innerHTML = correct
document.getElementById("greenButton").addEventListener("click", function() {Check(greenObject)})
document.getElementById("redButton").addEventListener("click", function() {Check(redObject)})
document.getElementById("yellowButton").addEventListener("click", function() {Check(yellowObject)})
document.getElementById("blueButton").addEventListener("click", function() {Check(blueObject)})
correct = 0
document.getElementById("counter").innerHTML = correct
document.getElementById("newGameButton").addEventListener("click", function() {NewGame()})
| true
|
c6d1af89677f6c0934a0a33846a3dfe26322c038
|
JavaScript
|
Z4rkal/Astroweight-Calculator
|
/main.js
|
UTF-8
| 3,651
| 3.9375
| 4
|
[] |
no_license
|
// Write your JavaScript code here!
var planets = [
['Pluto', 0.06],
['Neptune', 1.148],
['Uranus', 0.917],
['Saturn', 1.139],
['Jupiter', 2.640],
['Mars', 0.3895],
['Moon', 0.1655],
['Earth', 1],
['Venus', 0.9032],
['Mercury', 0.377],
['Sun', 27.9]
];
// We're going to solve this by breaking the problem into three parts.
// Programmers like automating things, we'll populate the HTML drop down options using code,
// instead of having to type out all the values.
// Create a function that does the some math and gives us the new weight.
// Then create a function that responds when the user clicks on the button.
// 1. Populate the dropdown element with the data found in the planets array.
// The value of each option should be the planet's name.
// Use the following built-in methods:
// `.forEach` `document.createElement` `document.getElementById` `.appendChild`
$(document).ready(function(){
//Programmatically creates the dropdown options
planets.forEach(function(element){
var newOption = document.createElement("option");
newOption.id = element[0]; //Not really necessary
var newOptionContent = document.createTextNode(element[0]);
newOption.appendChild(newOptionContent);
var insertPoint = document.getElementById("planets");
var fChild = insertPoint.firstChild;
insertPoint.insertBefore(newOption,fChild);
});
//This feels hacky, but I wanted it to default to Sun and this was the first thing that worked
$('#planets').val('Sun');
//Now that everything is set up wait for a click event and then handle it
$('#calculate-button').click(function(){
handleClickEvent();});
});
function calculateWeight(weight, planetName) {
// 2. Write the code to return the correct weight
var result;
//Checks each entry in planets for a match, and returns the calculated weight when one is found
for(var i = 0; i < planets.length; i++) {
if(planets[i][0] == planetName)
return weight * planets[i][1];
}
//Otherwise something went wrong, and somehow the planetName was invalid
console.log("No match D:");
return('Error');
}
function handleClickEvent(e) {
// 3. Create a variable called userWeight and assign the value of the user's weight.
var userWeight = $('#user-weight').val();
console.log('User weight: ' + userWeight + '\n');
// 4. Create a variable called planetName and assign the name of the selected planet from the drop down.
var planetName = $('#planets').val();
console.log('Selected Planet: ' + planetName + '\n');
// 5. Create a variable called result and assign the value of the new calculated weight.
var result = calculateWeight(userWeight,planetName);
console.log('Result: ' + result + '\n');
// 6. Write code to display the message shown in the screenshot.
// var gCheck = ''; //A variable for correcting grammar if the selected planet would need a 'the ' beforehand
// if(planetName == 'Moon' || planetName == 'Sun')
// gCheck = 'the '; //disabled it because it fails the tests but otherwise it works
$('#output').text("If you were on " /*+ gCheck */+ planetName + ", you would weigh " + result + "lbs!");
}
// 7. Set the #calculate-button element's onclick method to use the handleClickEvent function.
// Bonus Challenges
// 8. Reverse the drop down order so that the sun is first.
// 9. Make it look nice using bootstrap (http://getbootstrap.com/getting-started/)
| true
|
fbca7dc0927e23a8529de1f8f76d4ea822a2a51c
|
JavaScript
|
Lidemy/mentor-program-5th-halloju
|
/homeworks/week13/hw2/src/utils.js
|
UTF-8
| 750
| 2.84375
| 3
|
[] |
no_license
|
export function escapeHtml(str) {
return str.replace(/&/g, 'amp;').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, '"').replace(/'/g, ''')
}
export function appendCommentToDOM(container, comment, isAppend = true) {
const content = `
<div class="card mt-2 mb-1">
<div class="card-body">
<h5 class="card-title">${escapeHtml(comment.nickname)}</h5>
<p class="card-text">${escapeHtml(comment.comment)}</p>
</div>
</div>
`
if (isAppend) {
container.append(content)
} else {
container.prepend(content)
}
}
export function showButton(commentsLength, maxLength, cls) {
if (commentsLength > maxLength) {
cls.show()
} else {
cls.hide()
}
}
| true
|
be87fbfb20d5247f4cdf74540caa9940879c9da2
|
JavaScript
|
PablooHenrique/Sige
|
/ClientSide/Projeto/js/salvarSobrevivente.js
|
UTF-8
| 1,934
| 3.140625
| 3
|
[] |
no_license
|
var botaoSalvarSobrevivente = $('#btnSalvarSobrevivente');
//btnSalvarSobrevivente.addEventListener("click", enviarDados);
btnSalvarSobrevivente.addEventListener("click", salvarDados);
function enviarDados() {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "http://localhost:8080/sobrevivente/salvar",
dataType: "json",
data: formToJSON(),
}).done(function(json){
obtenhaJSON();
});
limparCamposCadastro();
}
function formToJSON() {
sobrevivente.nome = $('#nomeSobrevivente').val();
sobrevivente.latitude = $('#latitudeSobrevivente').val();
sobrevivente.longitude = $('#longitudeSobrevivente').val();
sobrevivente.sexo = $('#sexoSobrevivente').val();
sobrevivente.idade = $('#idadeSobrevivente').val();
sobrevivente.inventario.agua = $('#aguaSobrevivente').val();
sobrevivente.inventario.comida = $('#comidaSobrevivente').val();
sobrevivente.inventario.municao = $('#medicamentoSobrevivente').val();
sobrevivente.inventario.medicamento = $('#municaoSobrevivente').val();
console.log(sobrevivente);
console.log(sobrevivente.inventario);
return JSON.stringify(sobrevivente);
}
function salvarDados(tipoAlteracao){
if (document.getElementById("btnSalvarSobrevivente").textContent == "Salvar") {
enviarDados();
limparCamposCadastro();
}else if (document.getElementById("btnSalvarSobrevivente").textContent == "Alterar"){
alterarLatitudeLongitude();
limparCamposCadastro();
}
}
function limparCamposCadastro(){
$('#nomeSobrevivente').val("");
$('#latitudeSobrevivente').val("");
$('#longitudeSobrevivente').val("");
$('#sexoSobrevivente').val("");
$('#idadeSobrevivente').val("");
$('#aguaSobrevivente').val("");
$('#comidaSobrevivente').val("");
$('#medicamentoSobrevivente').val("");
$('#municaoSobrevivente').val("");
}
| true
|
c382360df80296adafdf30348779bdb286b0d0df
|
JavaScript
|
LibertaliaRepos/GG-CV
|
/symf/public/stylesheets/js/orbit.js
|
UTF-8
| 3,053
| 2.765625
| 3
|
[] |
no_license
|
/**
* Close the zoomed orbit window.
*/
function closeOrbit() {
$('.whiteDiv').each(function(){$(this).remove();});
$('.orbit[data-zoomed=true]').each(function() {
var cssDesabled = ['max-width', 'max-height','top', 'left'];
$(this).attr('data-zoomed', 'false');
$(this).data('zoomed', false);
// $(this).css('max-width', '');
for (var i = 0; i < cssDesabled.length; ++i) {
$(this).css(cssDesabled[i], '');
}
$('#openedOrbitBack').attr('data-status', 'closed');
initOrbit();
});
}
function openOrbit() {
if (!$(this).data('zoomed')) {
var whiteDiv = $('<div></div>');
$(whiteDiv).css('width', $(this).outerWidth(false) + 'px');
$(whiteDiv).addClass('whiteDiv');
$(this).before(whiteDiv);
var windowWidth = $(window).outerWidth();
var windowHeight = $(window).outerHeight();
$(this).attr('data-zoomed', true);
$(this).data('zoomed', true);
positionZoomed();
$('#openedOrbitBack').attr('data-status', 'opened');
$(window).resize(positionZoomed);
$('#openedOrbitBack').click(function (e) {
closeOrbit();
})
var ident = '#' + $(this).attr('id');
$(this).find('.orbit-exit').click(function(e) {
e.stopPropagation();
$('#openedOrbitBack').click();
});
}
}
function initOrbit() {
$('.orbit').each(function(index) {
sizeOrbitBullets();
$(this).click(openOrbit);
});
$('.orbit-next, .orbit-previous').each(function(index) {
var container = $(this).parent().parent().parent();
$(this).mouseenter(function() {
$(container).off('click', openOrbit);
});
$(this).mouseleave(function() {
$(container).click(openOrbit);
});
});
$('.orbit-bullets button').each(function(index) {
var container = $(this).parent().parent();
$(this).mouseenter(function() {
$(container).off('click', openOrbit);
});
$(this).mouseleave(function() {
$(container).click(openOrbit);
});
});
}
function positionZoomed() {
var windowWidth = $(window).outerWidth();
var windowHeight = $(window).outerHeight();
var zoomed = $('[data-zoomed=true]');
$(zoomed).css('max-width', (windowWidth * 0.5) + 'px' );
$(zoomed).css('max-height', (windowHeight * 0.9) + 'px' );
var orbitDim = {
height: $(zoomed).outerHeight(),
width: $(zoomed).outerWidth()
}
var orbitPos = {
left: (windowWidth - orbitDim.width) / 2,
top: (windowHeight - orbitDim.height) / 2
}
$(zoomed).css('left', orbitPos.left + 'px');
$(zoomed).css('top', orbitPos.top + 'px');
}
function sizeOrbitBullets() {
$('.orbit').each(function(index) {
var bullets = $(this).find('.orbit-bullets');
var next = $(this).find('.orbit-next');
var previous = $(this).find('.orbit-previous');
var arrowsWidth = ($(next).outerWidth()) + ($(previous).outerWidth());
$(bullets).css('width', 'calc(100% - '+ arrowsWidth +'px)')
});
}
$(window).ready(initOrbit);
| true
|
f4f7a3bf4813850f34548ad237cea40876b85475
|
JavaScript
|
gygy7151/Vue.js2-Spring5-web-app
|
/chap01/p.13.js
|
UTF-8
| 2,993
| 4.3125
| 4
|
[] |
no_license
|
// 1> User 생성자 함수
function User(name, interests, tasks){
this.name = name;
this.interests = interests;
//1-1 이건 1-2처럼 함수밖에서 User 프로토타입에 greeting 프로퍼티를 생성가능하다.
this.greeting = function() {
console.log('Hi, I\'m ' + _name + '.');
}
// 6> 이후에 eat메소드를 User에 추가하고 -> 53번째코드로 넘어감
// this.eat = function() { //여기에 넣는거 아님.
// console.log(this.interests + "is my love:)")
// }
}
// 1-2>
User.prototype.greeting = function () {
console.log('Hi, I\'m ' + this.name + '.');
}
// 2> TeamMember 생성자 함수 생성
function TeamMember (name, interests, tasks) {
// this.name = name;
// this.interest = interest;
User.call(this, name, interests);
this.tasks = tasks;
}
// 3> User라는 프로퍼티를 상속
TeamMember.prototype = Object.create(User.prototype);
// 4> greeting 메소드를 재정의하기
// this.greeting = function() { //이건 TeamMember 함수내부에서 가능한것으로 예상됨.
// console.log('Hi, I\'m ' + _name + '.');
// }
TeamMember.prototype.greeting = function () {
console.log('I\'m ' + this.name + '.Welcome to the team!');
};
// 5> 새로운 메소드인 work()를 추가한다
TeamMember.prototype.work = function() {
console.log('I\'m working on ' + this.tasks.length + ' tasks');
}
var member = new TeamMember('Sunny', ['Traveling'], ['Buy three tickets', 'Book a hotel']);
member.greeting(); //I'm Sunny. Welcome to the team! 출력
member.work(); // I'm working on 2 tasks 출력
console.log(member instanceof TeamMember); //true출력
console.log(member instanceof User); //true출력
console.log(member instanceof Object); //true출력
// 6> 이후에 eat메소드를 User에 추가하고
User.prototype.eat = function () {
console.log('What will I have for lunch?');
};
member.eat(); //what will I have for lunch? 출력
// 7> move()를 Object(최상위객체)에 추가한다.
// TeamMember.prototype.move = function() {
// console.log(this.name + 'moved to new house');
// }
Object.prototype.move = function () {
console.log('Every object can move now');
};
member.move(); //이제 모든 객체가 move를 호출할 수 있다
var alien = {};
alien.move(); //이제 모든 객체가 move를 호출할 수 있다
User.move(); //생성자 함수 객체도 호출 할 수 있다
console.log(member.__proto__ == TeamMember.prototype); //true출력
console.log(TeamMember.prototype.__proto__ == User.prototype); //ture출력
console.log(User.prototype.__proto__ == Object.prototype); //true출력
User.prototype.__proto__ == null;
member.move(); // Uncaught TypeError: member.move is not a function 출력
console.log(member instanceof Object); //false 출력(이런!)
TeamMember.prototype.isPrototypeOf(member); //true 출력
member.hasOwnProperty('name'); //true출력
member.hasOwnProperty('move'); /// false 출력
| true
|
ace9132213d1947c35c767c9f054c41ef0267623
|
JavaScript
|
susheelpal/javascriptPrograms
|
/dataStructurePrograms/binarySearchTree/binarySearchTreeMain.js
|
UTF-8
| 1,286
| 3.140625
| 3
|
[] |
no_license
|
/******************************************************************************
* Execution : 1. default node cmd> node binarySearchTreeMain.js
* 2. if nodemon installed cmd> nodemon binarySearchTreeMain.js
*
* Purpose : create a binary search tree.
*
* @description : number of binary search tree
* @file : binarySearchTreeMain.js
* @overview : create a binary search tree.
* @module : module_name - This is optional if expeclictly its an npm or local package
* @author : Susheel Pal <sushilk497@gmail.com>
* @version : 1.0
* @since : 06-01-2020
******************************************************************************/
let bst=require('./binarySearchTreeBL')
let BST = new bst.BinarySearchTree();
// Inserting nodes to the BinarySearchTree
BST.insert(15);
BST.insert(25);
BST.insert(10);
BST.insert(7);
BST.insert(22);
BST.insert(17);
BST.insert(13);
BST.insert(5);
BST.insert(9);
BST.insert(27);
// 15
// / \
// 10 25
// / \ / \
// 7 13 22 27
// / \ /
// 5 9 17
let root = BST.getRootNode();
// prints 5 7 9 10 13 15 17 22 25 27
BST.inorder(root);
| true
|
12fa6740a43265551038a10dc2e221d0b6b80746
|
JavaScript
|
rektide/blinker
|
/crx/devtools.js
|
UTF-8
| 1,020
| 2.609375
| 3
|
[] |
no_license
|
'use strict';
var stringEscape= require('js-string-escape')
var tab,
ws,
_ws
function prepWs(url){
url= url || 'ws://localhost:7432/blinkerd'
_ws= new WebSocket(url)
_ws.onopen= (function(){
if(ws){
ws.onmessage= null
ws.close()
}
ws= _ws
})
_ws.onmessage= handleBlinker
}
prepWs()
chrome.tabs.query({active: true}, function(results){
if(results.length)
tab= results[0]
})
function handleBlinker(msg){
if(!tab)
return
if(ws){
// relay the message back
ws.send(JSON.stringify({command:msg}))
}
var code= ['console.log(eval("', stringEscape(msg), '"))'].join('')
tab.executeScript(tab, {code: code}, function(results){
// already returning over console pipe
})
}
function handleConsole(msg){
if(ws)
ws.send(JSON.stringify(msg))
}
if(chrome.experimental && chrome.experimental.devtools && chrome.experimental.devtools.console && chrome.experimental.devtools.console.onMessagesAdded){
chrome.experimental.devtools.console.onMessagesAdded.addEventListener(handleConsole)
}
| true
|
f8bd0fee3a59fb80028816a9b2a8823cf277a9fe
|
JavaScript
|
newwangzhicheng/promise-async
|
/promise/Promisev1.js
|
UTF-8
| 1,418
| 3.96875
| 4
|
[] |
no_license
|
/**
* 初始版本的promise,包含了一下内容
* * status 存储目前的状态,包含:pending,resolved,rejected;初始pending
* * value 存储resolved的值
* * reason 存储rejected的原因
*
* * resolve函数,改变状态为resolved
* * reject函数,改变状态rejected
* * try-catch同步执行传入的函数
*
* * 在原型上实现一个then方法
* * then里面根据目前状态执行onFullfilled或onRejected函数
*
* * 缺陷 无法处理异步的resolve
*/
function Promisev1(constructor) {
const self = this;
self.status = 'pending';
self.value = undefined;
self.reason = undefined;
try {
constructor(resolve, reject);
} catch(e) {
reject(e);
}
function resolve(value) {
if (self.status === 'pending') {
self.value = value;
self.status = 'resolved';
}
}
function reject(reason) {
if (self.status === 'pending') {
self.reason = reason;
self.status = 'rejected'
}
}
}
Promisev1.prototype.then = function(onFullfilled, onRejected) {
switch(this.status) {
case 'resolved':
onFullfilled(this.value);
break;
case 'rejected':
onRejected(this.reason);
break;
default:
break;
}
};
// 使用
const v1 = new Promisev1((resolve, reject) => {
resolve(1);
reject(2);
})
v1.then((e) => {
console.log(`e`, e)
}, (err) => {
console.log(`err`, err)
})
| true
|
645400d84a670444ed1edd2611f61a317377334c
|
JavaScript
|
iamsaikatrahman/product-crud-react
|
/src/pages/ProductDetails/ProductDetails.js
|
UTF-8
| 2,545
| 2.84375
| 3
|
[] |
no_license
|
import React, { useEffect, useState } from "react";
import { useHistory, useParams } from "react-router";
import "./ProductDetails.css";
const ProductDetails = () => {
const { id } = useParams();
const history = useHistory();
const [product, setProduct] = useState({});
useEffect(() => {
fetch(`http://localhost:5000/products/${id}`)
.then((res) => res.json())
.then((data) => setProduct(data));
}, []);
const handleNameChange = (e) => {
const updateName = e.target.value;
const updateProduct = { ...product };
updateProduct.name = updateName;
setProduct(updateProduct);
};
const handlePriceChange = (e) => {
const updatePrice = e.taget.value;
const updateProduct = { ...product };
updateProduct.price = updatePrice;
setProduct(updateProduct);
};
const handleQuantityChange = (e) => {
const updateQnt = e.target.value;
const updateProduct = { ...product };
updateProduct.quantity = updateQnt;
setProduct(updateProduct);
};
const handleUpdateProduct = (e) => {
const url = `http://localhost:5000/products/${id}`;
fetch(url, {
method: "PUT",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify(product),
})
.then((res) => res.json())
.then((data) => {
if (data.modifiedCount > 0) {
alert("Update Successfull");
setProduct({});
e.target.reset();
history.push("/products");
}
});
e.preventDefault();
};
return (
<div>
<h2>Products Details</h2>
<img
src={product.imageUrl}
style={{ width: "200px", height: "150px" }}
alt=""
/>
<p>Id: {id}</p>
<form onSubmit={handleUpdateProduct} className="updateForm">
<label htmlFor="name">Name</label>
<input
type="text"
onChange={handleNameChange}
value={product.name || ""}
/>
<label htmlFor="price">Price</label>
<input
type="number"
onChange={handlePriceChange}
value={product.price || ""}
/>
<label htmlFor="quantity">Quantity</label>
<input
type="number"
onChange={handleQuantityChange}
value={product.quantity || ""}
/>
<input type="submit" value="Update Product" />
</form>
<p>Name: {product.name}</p>
<p>Price: {product.price}</p>
<p>Quantity: {product.quantity}</p>
</div>
);
};
export default ProductDetails;
| true
|
7500f60a10d6466449fe21c55375451647abaa01
|
JavaScript
|
nightmareteam/reviews
|
/client/src/ReviewRating.jsx
|
UTF-8
| 4,743
| 2.796875
| 3
|
[] |
no_license
|
/* eslint-disable camelcase */
import React from 'react';
//import styled from 'styled-components';
import styled from 'styled-components';
import RatingButtons from './RatingButtons.jsx';
import $ from 'jquery';
import CommentModal from './CommentModal.jsx';
/**
* Class representing a review rating
* @extends React.Component
*/
class ReviewRating extends React.Component {
/**
* Initialize all review rating values (yes/no/funny) to false.
* These values will be updated via user interaction.
* Initialize modal display to false. The modal is displayed when
* user clicks to view comments.
* @param {*} props
*/
constructor(props) {
super(props);
this.state = {
helpfulness: {
yes: false,
no: false,
funny: false
},
displayModal: false
};
this.showModal = this.showModal.bind(this);
this.hideModal = this.hideModal.bind(this);
}
/**
* This function toggles the respective review rating to true, and others to false.
* It then makes an API call to update the values in the backend.
* @param {*} e - an event object
* @param {*} val - the selected review rating - yes/no/funny
*/
updateHelpfulness(e, val) {
e.preventDefault();
let status = !this.state.helpfulness[val];
let helpfulness = {
yes: false,
no: false,
funny: false
};
helpfulness[val] = status;
$.ajax({
url: '/review/vote',
method: 'POST',
data: {
// eslint-disable-next-line camelcase
post_id: this.props.post_id,
helpfulness: helpfulness
},
success: () => {
//console.log('PostID ' + this.props.post_id + JSON.stringify(helpfulness));
this.setState({ helpfulness });
},
error: () => console.error('Couldn\'t connect to network.')
});
}
/**
* This function toggles the display of the comment modal
* @param {*} e - an event object
*/
showModal(e) {
e.preventDefault;
const displayModal = true;
this.setState({ displayModal });
}
/**
* This function hides the comment modal. We do a separate function
* rather than !displayModal toggle because we listen for the Escape key,
* and don't want it to toggle the modal back on.
* @param {*} e - an event object
*/
hideModal(e) {
e.preventDefault;
const displayModal = false;
this.setState({ displayModal });
}
/**
* Make an API request to the server for helpfulness rating counts of the current
* review. Eg Yes: X, No: Y, Funny: Z
*/
getReview() {
$.ajax({
url: '/reviews',
method: 'GET',
data: {
where: {
post_id: this.props.post_id
}
},
success: (helpfulness) => {
console.log('PostID ' + this.props.post_id + JSON.stringify(helpfulness));
this.setState({ helpfulness });
},
error: () => console.error('Couldn\'t connect to network.')
});
}
/**
* Render the component with a couple conditions
* Modal: if the source is a modal we hide the comment button
* Mini: if the source is the MiniReview component, we shorten some text
*/
render() {
let reviewCounts;
if (this.props.mini) {
reviewCounts = <div></div>;
} else {
reviewCounts =
<FeedbackWrapper>
<div>
<Feedback>{this.props.yes} found this review helpful</Feedback>
<Feedback>{this.props.funny} found this review funny</Feedback>
</div>
{
this.props.source === 'standard' ? <CommentButton onClick={this.showModal} src='/images/comment_quoteicon_blue.png' /> :
this.props.source === 'modal' ? null : null
}
</FeedbackWrapper>;
}
return (
<Wrapper>
{
this.state.displayModal ? <CommentModal hideModal={this.hideModal} review={this.props.review} /> : null
}
<Text>{this.props.mini ? 'Helpful?' : 'Was this review helpful?'}</Text>
<RatingButtons helpfulness={this.state.helpfulness} updateHelpfulness={this.updateHelpfulness.bind(this)}/>
{reviewCounts}
</Wrapper>
);
}
}
const Wrapper = styled.div`
`;
const Text = styled.div`
color: #8091a2;
font-size: 12px;
line-height: 35px;
display: inline;
padding-top: 5px;
padding-bottom: 5px;
padding-right: 10px;
opacity: 0.6;
`;
const Feedback = styled.div`
color: #647580;
font-size: 12px;
display: block;
padding-top: 0px;
padding-bottom: 0px;
`;
const FeedbackWrapper = styled.div`
display: flex;
justify-content: space-between;
`;
const CommentButton = styled.img`
height: 16px;
margin-right: 10px;
cursor: pointer;
`;
export default ReviewRating;
| true
|
5b0b43af76af8d888a49a452b7d240d6e9df95fb
|
JavaScript
|
JamesKytosaho/chess
|
/src/components/game/__tests__/GameUtils.test.js
|
UTF-8
| 10,098
| 2.859375
| 3
|
[] |
no_license
|
import { pawnRules, knightRules, bishopRules, kingRules, rookRules, checkPath, getStartPosition } from '../GameUtils';
describe("Game rules", () => {
describe("Pawn", () => {
describe("White", () => {
test("should be valid to move one position forward", () => {
//Arrange
const isWhite = true;
const currentPosition = {
y: 5,
x: 1
};
const nextPosition = {
y: 6,
x: 1
};
//Act
const validMove = pawnRules(currentPosition, nextPosition, isWhite);
//Assert
expect(validMove).toBe(true);
});
test("should be valid to move two positions forward if pawn is at starting position", () => {
//Arrange
const isWhite = true;
const currentPosition = {
y: 2,
x: 1
};
const nextPosition = {
y: 4,
x: 1
};
//Act
const validMove = pawnRules(currentPosition, nextPosition, isWhite);
//Assert
expect(validMove).toBe(true);
});
test("should not be valid to move back", () => {
//Arrange
const isWhite = true;
const currentPosition = {
y: 2,
x: 1
};
const nextPosition = {
y: 1,
x: 1
};
//Act
const validMove = pawnRules(currentPosition, nextPosition, isWhite);
//Assert
expect(validMove).toBe(false);
});
test("should not be valid to move sideways in x-axies", () => {
//Arrange
const isWhite = true;
const currentPosition = {
y: 2,
x: 1
};
const nextPosition = {
y: 2,
x: 2
};
//Act
const validMove = pawnRules(currentPosition, nextPosition, isWhite);
//Assert
expect(validMove).toBe(false);
});
});
describe("Black", () => {
test("should be valid to move one position forward", () => {
//Arrange
const isWhite = false;
const currentPosition = {
y: 4,
x: 1
};
const nextPosition = {
y: 3,
x: 1
};
//Act
const validMove = pawnRules(currentPosition, nextPosition, isWhite);
//Assert
expect(validMove).toBe(true);
});
test("should be valid to move two positions forward from starting position", () => {
//Arrange
const isWhite = false;
const currentPosition = {
y: 7,
x: 1
};
const nextPosition = {
y: 5,
x: 1
};
//Act
const validMove = pawnRules(currentPosition, nextPosition, isWhite);
//Assert
expect(validMove).toBe(true);
});
test("should not be valid to move back", () => {
//Arrange
const isWhite = false;
const currentPosition = {
y: 7,
x: 1
};
const nextPosition = {
y: 8,
x: 1
};
//Act
const validMove = pawnRules(currentPosition, nextPosition, isWhite);
//Assert
expect(validMove).toBe(false);
});
test("should not be valid to move sideways in x-axies", () => {
//Arrange
const isWhite = false;
const currentPosition = {
y: 7,
x: 1
};
const nextPosition = {
y: 7,
x: 2
};
//Act
const validMove = pawnRules(currentPosition, nextPosition, isWhite);
//Assert
expect(validMove).toBe(false);
});
})
});
describe("Knight", () => {
test("Should be able to move two steps vertically and one step horizontally", () => {
//Arrange
const yDifference = 2;
const xDifference = 1;
let validMove = false;
//Act
validMove = knightRules(yDifference, xDifference);
//Assert
expect(validMove).toBe(true);
});
test("Should be able to move two steps forward and one to the right", () => {
//Arrange
const yDifference = 1;
const xDifference = 2;
let validMove = false;
//Act
validMove = knightRules(yDifference, xDifference);
//Assert
expect(validMove).toBe(true);
});
});
describe("Bishop", () => {
test("Should be able to move diagonally", () => {
//Arrange
const yDifference = 2;
const xDifference = 2;
let validMove = false;
//Act
validMove = bishopRules(yDifference, xDifference);
//Assert
expect(validMove).toBe(true);
});
});
describe("King", () => {
test("Should be able to move one step vertically", () => {
//Arrange
const yDifference = 1;
const xDifference = 0;
let validMove = false;
//Act
validMove = kingRules(yDifference, xDifference);
//Assert
expect(validMove).toBe(true);
});
test("Should be able to move one step horizontally", () => {
//Arrange
const yDifference = 0;
const xDifference = 1;
let validMove = false;
//Act
validMove = kingRules(yDifference, xDifference);
//Assert
expect(validMove).toBe(true);
});
test("Should be able to move one step diagonally", () => {
//Arrange
const yDifference = 1;
const xDifference = 1;
let validMove = false;
//Act
validMove = kingRules(yDifference, xDifference);
//Assert
expect(validMove).toBe(true);
});
});
describe("Rook", () => {
test("Should be able to move vertically", () => {
//Arrange
const yDifference = 5;
const xDifference = 0;
let validMove = false;
//Act
validMove = rookRules(yDifference, xDifference);
//Assert
expect(validMove).toBe(true);
});
test("Should be able to move horizontally", () => {
//Arrange
const yDifference = 0;
const xDifference = 4;
let validMove = false;
//Act
validMove = rookRules(yDifference, xDifference);
//Assert
expect(validMove).toBe(true);
});
});
});
describe("Path validation", () => {
test("Should not be a valid move if piece is in path and moving vertical", () => {
//Arrange
const absoluteDifferenceY = 2;
const absoluteDifferenceX = 0;
const currentPositionY = 1;
const currentPositionX = 1;
const nextPositionY = 3;
const nextPositionX = 1;
const pieces = [getStartPosition]; // create test senario
let validMove = false;
//Act
validMove = checkPath(absoluteDifferenceY, absoluteDifferenceX, currentPositionY, currentPositionX, nextPositionY, nextPositionX, pieces);
//Assert
expect(validMove).toBe(false);
});
test("Should not be a valid move if piece is in path and moving horizontal", () => {
//Arrange
const absoluteDifferenceY = 0;
const absoluteDifferenceX = 2;
const currentPositionY = 1;
const currentPositionX = 1;
const nextPositionY = 1;
const nextPositionX = 3;
const pieces = [getStartPosition]; // create test senario
let validMove = false;
//Act
validMove = checkPath(absoluteDifferenceY, absoluteDifferenceX, currentPositionY, currentPositionX, nextPositionY, nextPositionX, pieces);
//Assert
expect(validMove).toBe(false);
});
test.skip("Should not be a valid move if piece is in path and moving diagonally", () => {
//Arrange
const absoluteDifferenceY = 2;
const absoluteDifferenceX = 2;
const currentPositionY = 1;
const currentPositionX = 3;
const nextPositionY = 3;
const nextPositionX = 5;
const pieces = [getStartPosition]; //create test senario
let validMove = false;
//Act
validMove = checkPath(absoluteDifferenceY, absoluteDifferenceX, currentPositionY, currentPositionX, nextPositionY, nextPositionX, pieces);
//Assert
expect(true).toBe(false);
});
});
| true
|
0a924eeae23b77033b3f6f7b0aaa565fff4da482
|
JavaScript
|
mattzuzolo/mocha-node-examples
|
/utils/utils.test.js
|
UTF-8
| 1,272
| 3.109375
| 3
|
[] |
no_license
|
const expect = require("expect")
const utils = require("./utils")
describe("Utils", () => {
describe("#add", () => {
it ("should add two numbers", () => {
let result = utils.add(33, 11);
expect(result).toBe(44).toBeA("number");
// if (result != 44){
// throw new Error(`Expected 44, but received ${result}.`)
// }
});
});
it("should async add two numbres", (done) => {
utils.asyncAdd(4, 3, (sum) => {
expect(sum).toBe(7).toBeA("number");
done();
});
})
it ("should square a number", () => {
let result = utils.square(5);
expect(result).toBe(25).toBeA("number");
// if (result != 25){
// throw new Error(`Expected 25, but received ${result}.`)
// };
});
it ("should asnyc square a number", (done) => {
utils.asyncSquare(6, (result) => {
expect(result).toBe(36).toBeA("number");
done();
})
})
it ("should set first and last names", () => {
let user = {};
let result = utils.setName(user, "John Doe");
expect(result).toInclude({
firstName: "John",
lastName: "Doe"
}).toBeA("object")
})
});
//experimenting:
// it("should expect some values", () => {
// expect({name: "Matt"}).toEqual({name: "Matt"});
// });
| true
|
5fd13c7303c544c10309129545afd88867ce8f5e
|
JavaScript
|
heystar/js-algorithm
|
/LinkedList/index.js
|
UTF-8
| 640
| 3.8125
| 4
|
[] |
no_license
|
// import { LinkedList } from './LinkedList'
// let list = new LinkedList()
// list.append(0)
// list.append(1)
// list.append(2)
// console.log(list.toString())
// list.insert(1,3)
// console.log(list.toString())
// list.removeAt(1)
// console.log(list.toString())
// console.log(list.indexOf(0))
import { DoublyLinkedList } from './DoublyLinkedList'
let doublyList = new DoublyLinkedList()
doublyList.append('a')
doublyList.append('b')
doublyList.append('c')
doublyList.append('d')
console.log(doublyList.toString())
doublyList.insert(2, 'e')
console.log(doublyList.toString())
doublyList.removeAt(3)
console.log(doublyList.toString())
| true
|
a37e9a4792034dd01eec0e01d04c3469af281e13
|
JavaScript
|
chromium/chromium
|
/third_party/blink/web_tests/storage/indexeddb/resources/cursor-key-order.js
|
UTF-8
| 5,135
| 2.703125
| 3
|
[
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] |
permissive
|
if (this.importScripts) {
importScripts('../../../resources/js-test.js');
importScripts('shared.js');
}
description("Test IndexedDB keys ordering and readback from cursors.");
indexedDBTest(prepareDatabase, populateStore);
function prepareDatabase()
{
db = event.target.result;
evalAndLog("db.createObjectStore('store')");
}
self.keys = [
"-Infinity",
"-Number.MAX_VALUE",
"-1",
"-Number.MIN_VALUE",
"0",
"Number.MIN_VALUE",
"1",
"Number.MAX_VALUE",
"Infinity",
"new Date(0)",
"new Date(1000)",
"new Date(1317399931023)",
"''",
"'\x00'",
"'a'",
"'aa'",
"'b'",
"'ba'",
"'\xA2'", // U+00A2 CENT SIGN
"'\u6C34'", // U+6C34 CJK UNIFIED IDEOGRAPH (water)
"'\uD834\uDD1E'", // U+1D11E MUSICAL SYMBOL G-CLEF (UTF-16 surrogate pair)
"'\uFFFD'", // U+FFFD REPLACEMENT CHARACTER
"[]",
"[-Infinity]",
"[-Number.MAX_VALUE]",
"[-1]",
"[-Number.MIN_VALUE]",
"[0]",
"[Number.MIN_VALUE]",
"[1]",
"[Number.MAX_VALUE]",
"[Infinity]",
"[new Date(0)]",
"[new Date(1000)]",
"[new Date(1317399931023)]",
"['']",
"['\x00']",
"['a']",
"['aa']",
"['b']",
"['ba']",
"['\xA2']", // U+00A2 CENT SIGN
"['\u6C34']", // U+6C34 CJK UNIFIED IDEOGRAPH (water)
"['\uD834\uDD1E']", // U+1D11E MUSICAL SYMBOL G-CLEF (UTF-16 surrogate pair)
"['\uFFFD']", // U+FFFD REPLACEMENT CHARACTER
"[[]]",
"[[], []]",
"[[], [], []]",
"[[[]]]",
"[[[[]]]]"
];
function compare(a, b)
{
if (typeof a !== typeof b) {
return false;
}
switch (typeof a) {
case 'undefined': // Not valid keys, but compare anyway.
case 'boolean': // Not valid keys, but compare anyway.
case 'string':
return a === b;
case 'number':
if (a === b) {
return (a !== 0) || (1 / a === 1 / b); // 0 isn't -0
} else {
return a !== a && b !== b; // NaN is NaN
}
case 'object':
if (a instanceof Date && b instanceof Date) {
return +a === +b;
} else if (a instanceof Array && b instanceof Array) {
if (a.length !== b.length) {
return false;
}
for (var i = 0; i < a.length; i++) {
if (!compare(a[i], b[i])) {
return false;
}
}
return true;
}
// For the purposes of this test, other objects don't count
return false;
default:
return false;
}
}
function populateStore()
{
debug("");
debug("populating store...");
evalAndLog("trans = db.transaction('store', 'readwrite', {durability: 'relaxed'})");
evalAndLog("store = trans.objectStore('store');");
trans.onerror = unexpectedErrorCallback;
trans.onabort = unexpectedAbortCallback;
var count = 0;
keys.forEach(function(key) {
evalAndLog("store.put(" + (count++) + ", " + key + ")");
});
trans.oncomplete = checkStore;
}
function checkStore()
{
debug("");
debug("iterating cursor...");
evalAndLog("trans = db.transaction('store', 'readonly', {durability: 'relaxed'})");
evalAndLog("store = trans.objectStore('store');");
trans.onerror = unexpectedErrorCallback;
trans.onabort = unexpectedAbortCallback;
evalAndLog("count = 0");
curreq = evalAndLog("curreq = store.openCursor()");
curreq.onerror = unexpectedErrorCallback;
curreq.onsuccess = function() {
if (curreq.result) {
evalAndLog("cursor = curreq.result");
shouldBeTrue("compare(cursor.key, " + keys[count] + ")");
evalAndLog("getreq = store.get(cursor.key)");
getreq.onerror = unexpectedErrorCallback;
getreq.onsuccess = function() {
shouldBe("getreq.result", "count++");
cursor.continue();
};
} else {
shouldBe("count", "keys.length");
finishUp();
}
};
}
function finishUp()
{
testKeyCompare();
finishJSTest();
}
function testKeyCompare()
{
debug("");
debug("validate compare function");
var cases = [
"undefined",
"true",
"false",
"0",
"-0",
"123",
"Infinity",
"-Infinity",
"NaN",
"''",
"'abc'",
"'xyz'",
"new Date(0)",
"new Date(1e3)",
"new Date(1e9)",
"[]",
"[123]",
"['abc']",
"[123, 'abc']",
"['abc', 123]",
"[[]]",
"[[123]]",
"[['abc']]",
"[[123], 'abc']",
"[[123], 123]"
];
for (var i = 0; i < cases.length; ++i) {
for (var j = 0; j < cases.length; ++j) {
if (i === j) {
shouldBeTrue("compare(" + cases[i] + ", " + cases[j] + ")");
} else {
shouldBeFalse("compare(" + cases[i] + ", " + cases[j] + ")");
}
}
}
}
| true
|
0774784a7fe540d4af0679bd3aa7d31e550a0118
|
JavaScript
|
yhakamay/calendar-integration
|
/sync.gs
|
UTF-8
| 2,731
| 3.109375
| 3
|
[] |
no_license
|
/***************************************************************************
- プログラムのコアとなるファイル
- 最上部のsyncForDays()がメインの処理を担い、それ以外は振り分けを行っている
- 例えばsyncToday()に偶数の時間(14時とか)が渡された場合、書換対象はPersonal
- ちなみにGo Visionsカレンダーはほとんど使用しないため、最も頻度の高いsyncToday()では
書換を行わない
- syncToday()系関数は、処理が終わると「どのカレンダーを書き換えたか」をmain()に返す
***************************************************************************/
function syncForDays(targetCalendar, originalCalendar, daysToStartTime, daysToEndTime) {
const today = new Date();
const startTime = new Date(today.getFullYear(), today.getMonth(), today.getDate() + daysToStartTime, 0, 00, 00, 00);
const endTime = new Date(today.getFullYear(), today.getMonth(), today.getDate() + daysToEndTime, 23, 59, 59, 59);
deleteEventsCreatedByGAS(targetCalendar, startTime, endTime);
copyEvents(targetCalendar, originalCalendar, startTime, endTime);
}
// 毎朝1度だけ実行
function syncYesterday() {
let refreshedCalendar = 'nothing';
syncForDays(kCalendarPersonal, kCalendarSoftbank, -1, -1);
syncForDays(kCalendarSoftbank, kCalendarPersonal, -1, -1);
refreshedCalendar = `${kCalendarPersonal.getName()} and ${kCalendarSoftbank.getName()}`;
return refreshedCalendar;
}
function syncLastWeek() {
let refreshedCalendar = 'nothing';
syncForDays(kCalendarPersonal, kCalendarSoftbank, -80, -77);
// syncForDays(kCalendarSoftbank, kCalendarPersonal, -78, -77);
refreshedCalendar = `${kCalendarPersonal.getName()} and ${kCalendarSoftbank.getName()}`;
return refreshedCalendar;
}
function syncToday() {
let refreshedCalendar = 'nothing';
syncForDays(kCalendarPersonal, kCalendarSoftbank, 0, 0);
syncForDays(kCalendarSoftbank, kCalendarPersonal, 0, 0);
refreshedCalendar = `${kCalendarPersonal.getName()} and ${kCalendarSoftbank.getName()}`;
return refreshedCalendar;
}
function syncThisWeek() {
let refreshedCalendar = 'nothing';
syncForDays(kCalendarPersonal, kCalendarSoftbank, 1, 7);
syncForDays(kCalendarSoftbank, kCalendarPersonal, 1, 7);
refreshedCalendar = `${kCalendarPersonal.getName()} and ${kCalendarSoftbank.getName()}`;
return refreshedCalendar;
}
function syncThisMonth() {
let refreshedCalendar = 'nothing';
syncForDays(kCalendarPersonal, kCalendarSoftbank, 8, 30);
syncForDays(kCalendarSoftbank, kCalendarPersonal, 8, 30);
refreshedCalendar = `${kCalendarPersonal.getName()} and ${kCalendarSoftbank.getName()}`;
return refreshedCalendar;
}
| true
|
400a434a701aefcc52d168fbf1a4671df546e3d6
|
JavaScript
|
TheDesolate/testgit2
|
/day31-33/table.js
|
UTF-8
| 4,298
| 3.1875
| 3
|
[] |
no_license
|
// 创建表头,同时将选择的数据渲染到table中
function createTable() {
// 将已经有的数据清除,每次都会出翔
if (tableWrapper.childNodes[0]) {
tableWrapper.removeChild(tableWrapper.childNodes[0])
}
var data = getTableData();
var radioSelect = getData(regionRatio)
var productSelect = getData(productRatio)
// 制作表头
var headTable = ["商品", "地区", "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"];
var table = document.createElement("table")
var thead = table.createTHead();
var tr0 = table.insertRow(0)
for (var i = 0; i < headTable.length; i++) {
var td = tr0.insertCell(i);
td.innerHTML = headTable[i];
}
var regionlen = radioSelect.length
var productlen = productSelect.length
// console.log(regionlen)
// console.log(productlen)
// 分别对选择不同数量商品,不同数量地区时做出不同的渲染
// 难点:表格合并,合并行后 ,下面的表格会少一个
// 注意:多行多列时商品合并,地区不变的情况处理。所以得先循环商品
if (productlen == 1 && regionlen >= 1) {
for (var i = 0; i < regionlen; i++) {
if (i == 0) {
var tr = table.insertRow(table.rows.length);
var td = tr.insertCell(0);
td.innerHTML = data[i].product;
td.rowSpan = regionlen
var td = tr.insertCell(1);
td.innerHTML = data[i].region;
for (var j = 0; j < 12; j++) {
var td = tr.insertCell(j + 2);
td.innerHTML = data[i].sale[j];
}
} else {
var tr = table.insertRow(table.rows.length);
var td = tr.insertCell(0); //合并单元格后,后面行少一个单元格
td.innerHTML = data[i].region;
for (var j = 0; j < 12; j++) {
var td = tr.insertCell(j + 1);
td.innerHTML = data[i].sale[j];
}
}
}
} else if (regionlen == 1 && productlen > 1) {
for (var i = 0; i < productlen; i++) {
if (i == 0) {
var tr = table.insertRow(table.rows.length)
var td = tr.insertCell(0);
td.rowSpan = productlen;
td.innerHTML = data[i].region
var td = tr.insertCell(1);
td.innerHTML = data[i].product;
for (var j = 0; j < 12; j++) {
var td = tr.insertCell(j + 2)
td.innerHTML = data[i].sale[j]
}
} else {
var tr = table.insertRow(table.rows.length)
var td = tr.insertCell(0);
td.innerHTML = data[i].product
for (var j = 0; j < 12; j++) {
var td = tr.insertCell(j + 1)
td.innerHTML = data[i].sale[j]
}
}
}
} else if (regionlen > 1 && productlen > 1) {
for (var i = 0; i < productlen; i++) {
for (var j = 0; j < regionlen; j++) {
if (j == 0) {
var tr = table.insertRow(table.rows.length);
var td = tr.insertCell(0);
td.innerHTML = data[j + i * regionlen].product;
td.rowSpan = regionlen;
var td = tr.insertCell(1);
td.innerHTML = data[j + i * regionlen].region
for (var k = 0; k < 12; k++) {
var td = tr.insertCell(k + 2)
td.innerHTML = data[j + i * regionlen].sale[k]
}
} else {
var tr = table.insertRow(table.rows.length);
var td = tr.insertCell(0);
td.innerHTML = data[j + i * regionlen].region
for (var k = 0; k < 12; k++) {
var td = tr.insertCell(k + 1)
td.innerHTML = data[j + i * regionlen].sale[k]
}
}
}
}
}
tableWrapper.appendChild(table);
}
| true
|
6c0806c7fcb0503ee19fa0b7e16fd5aaa90e3554
|
JavaScript
|
manishkhanna3002/webdriverio
|
/test/specs/functionalscenarios.js
|
UTF-8
| 2,339
| 2.796875
| 3
|
[] |
no_license
|
const expectchai = require("chai")
describe ("Functional testing on application", ()=>
{
it ("Scrolling and Mouse hover", ()=>
{
browser.url("https://www.rahulshettyacademy.com/AutomationPractice/")
$("#mouehover").scrollIntoView()
//browser.pause(3000)
$("#mousehover").moveTo()
//browser.pause(3000)
$("=Top").click()
//browser.pause(3000)
browser.url("http://only-testing-blog-blogspot.com/2014/09/selectable.html")
$(button).doubleClick()
console.log(browser.isAlertOpen()) //It will return true if alert is open else return false
expectchai(browser.isAlertOpen()).to.be.true //If alert is not open this statement will return false and test will hard break here with failure status
console.log(browser.getAlertText())
expectchai(browser.isAlertOpen()).to.equal("'You double clicked me.. Thank You..")
browser.acceptAlert() //Clicks on ok button present on the Alert
//Alert is not a web page alert but a window alert, Selenium and WebdriverIO can't handle it so they
//have written certain wrappers for the same and the wrappers as used in last 3 lines of code are isalertoprn
//getAlertText and acceptAlert
})
it ("Web tables validation", ()=>
{
browser.url("https://www.rahulshettyacademy.com/seleniumPractice/#/offers")
$("tr th:nth-child(1)").click()
const veggieLocators = $$("tr th:nth-child(1)")
const originalveggieNames = veggielocators.map(veggie => veggie.getText())
console.log(originalveggieNames)
Veggies = originalveggirNames.slice()//Slice is used to take copy of Array
console.log(veggieNames)
//Arrays are pass by reference
const sortVeggies = veggieNames.sort()
console.log(sortVeggies)
expectchai(veggieNames).to.equal(sortVeggies)
})
it ("Web tables filter validation", ()=>
{
browser.url("https://www.rahulshettyacademy.com/seleniumPractice/#/offers")
$("input[type='search']").setValue("tomato")
const veggielocators = $$("tr td: nth-child(1)")
expect(veggielocators).toBeElementsArrayOfSize{eq:1}
veggielocators.getText()
expect(veggielocators).toHaveTextContaining("tomato")
})
})
| true
|
b0da823bdbba972e4c6f469b679405846700cff3
|
JavaScript
|
microscopejs/web-parse
|
/controllers/ArticleController.js
|
UTF-8
| 1,875
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
// Import
import {Controller} from 'microscope-web';
import Article from '../models/Article';
class ArticleController extends Controller {
get baseUrl() {
return '/api/articles';
}
get routes() {
return {
'get /': 'index',
'get /:id': 'show',
'post /': 'create',
'put /:id': 'update',
'delete /:id': 'remove'
}
}
// articles list
// GET /api/articles
index(request, response) {
var offset = request.query.offset || null;
var limit = request.query.limit || null;
Article.find().skip(offset).limit(limit).exec((err, articles) => {
if (err) {
response.send(err);
}
response.json(articles);
});
}
// articles details
// GET /api/articles/:id
show(request, response) {
Article.findById(request.params.id, function (err, article) {
if (err) {
response.send(err.message);
}
response.json(article);
});
}
// articles creation
// POST /api/articles
create(request, response) {
var article = new Article();
article.title = request.body.title;
article.description = request.body.description;
console.log(request.body);
article.save((err) => {
if (err) {
response.send(err);
};
response.json({ message: 'Article created!' });
});
}
// article update
// PUT /api/articles
update(request, response) {
Article.findOneAndUpdate({ _id: request.params.id }, request.body, (err, article) => {
if (err) {
response.send(err);
};
response.json({ message: 'Article updated !' });
});
}
// article delete
// DELETE /api/articles/:id
remove(request, response) {
Article.remove({ _id: request.params.id }, function (err) {
if (err) {
response.send(err);
};
response.json({ message: 'Article removed!' });
});
}
}
export default ArticleController;
| true
|
fa5591363cf7be71e1986fec0a91f19989425621
|
JavaScript
|
LeeYelim/MidProjectKongs
|
/WebContent/js/loginPlace.js
|
UTF-8
| 1,782
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
var loginForm = $("#loginForm");
var signUpForm = $("#signUpForm");
var loginDuration = 500;
var visibleDuration = 350;
$( function(){
// hover시 프로필 정보 보여주기
$("#logoutView").mouseover(function(){
$("#profile").css("display", "initial");
$("#profile").slidedown();
});
$("#logoutView").mouseout(function(){
$("#profile").css("display", "none");
});
$("#loginPlace input[type=button]").click(function(){
var btnTmp = $(this).get(0).name;
switch(btnTmp) {
case "cancle" :
$("#loginPlace").hide();
loginForm.css({"right":"50%"});
reset();
break;
case "sign" :
showSignUpView();
break;
case "login" :
showLoginView();
break;
}
});
// 로그인 버튼 클릭
$("#loginView").click(function(){
loginForm.fadeIn(visibleDuration);
signUpForm.fadeOut(0);
$("#loginPlace").fadeIn(visibleDuration);
});
// 로그아웃 버튼 클릭
$("#logoutView").click(function(){
alert('로그아웃합니다.');
location.href="logout.jsp";
});
$("")
});
function showSignUpView(){
loginForm.animate({
right:"60%"
}, {duration:loginDuration, queue:false}).fadeOut(loginDuration);
signUpForm.css({
right:"40%"
}).animate({
right:"50%"
}, {duration:loginDuration, queue:false}).fadeIn(loginDuration);
}
function showLoginView(){
signUpForm.animate({right:"40%"}, {duration:loginDuration, queue:false}).fadeOut(loginDuration);
loginForm.css({right:"60%"}).animate({right:"50%"}, {duration:loginDuration, queue:false}).fadeIn(loginDuration);
}
function reset(){
signUpForm.find("input[type=text]").val('');
signUpForm.find("input[type=password]").val('');
loginForm.find("input[type=text]").val('');
loginForm.find("input[type=password]").val('');
}
| true
|
0fd5cfe56cf45f13433e0e8a1c12c2312a254c78
|
JavaScript
|
appsbychris/enyo2-stuff
|
/enyo-keyframes/ToasterPopup/Slideable3d.js
|
UTF-8
| 1,338
| 2.734375
| 3
|
[] |
no_license
|
*
Slideable3d
Basically just a slideable tweaked to use translate3d() instead of
translateX() and translateY()
Have found it to have better performance on android 4.1 +
*/
enyo.kind({
name: "Slideable3d",
kind: "Slideable",
use3d: true,
valueChanged: function(inLast) {
var v = this.value;
if (this.isOob(v) && !this.isAnimating()) {
this.value = this.overMoving ? this.dampValue(v) : this.clampValue(v);
}
// FIXME: android cannot handle nested compositing well so apply acceleration only if needed
// desktop chrome doesn't like this code path so avoid...
if (enyo.platform.android > 2) {
if (this.value) {
if (inLast === 0 || inLast === undefined) {
enyo.dom.accelerate(this, this.accelerated);
}
} else {
enyo.dom.accelerate(this, false);
}
}
// If platform supports transforms
if (this.canTransform) {
if (this.use3d) {
if (this.transform == "translateX") {
enyo.dom.transformValue(this, "translate3d", this.value + this.unit + ",0,0");
}
else {
enyo.dom.transformValue(this, "translate3d","0," + this.value + this.unit + ",0");
}
}
else {
enyo.dom.transformValue(this, this.transform, this.value + this.unit);
}
// else update inline styles
} else {
this.setInlineStyles(this.value, false);
}
this.doChange();
}
});
| true
|
8609520eda2d54f5769ca6f26fa17fb4f3bebef7
|
JavaScript
|
shsimeonova/Javascript-Fundamentals
|
/12. JS Objects Ex/Cappy Juice.js
|
UTF-8
| 662
| 3.515625
| 4
|
[] |
no_license
|
function cappyJuice(input) {
let juice = {};
let output = {};
for (let line of input) {
let [fruit, quantity] = line.split(/\s*\=\>\s*/);
if (juice[fruit] != undefined) {
juice[fruit] += Number(quantity);
}
else {
juice[fruit] = Number(quantity);
}
if (juice[fruit] >= 1000) {
if (fruit in output) {
output[fruit] += Number(quantity);
}
else {
output[fruit] = juice[fruit]
}
}
}
for (let juice in output){
console.log(`${juice} => ${Math.floor(output[juice]/1000)}`)
}
}
| true
|
95830797fb2cb55a230e588b4c087c8cd37fa0e4
|
JavaScript
|
roseviet/JavaScript-programming
|
/4. Practice problems/Edabit questions + Interview questions/34. Triangular number sequesnce.js
|
UTF-8
| 555
| 4.78125
| 5
|
[
"MIT"
] |
permissive
|
// Triangular Number Sequence
// This Triangular Number Sequence is generated from a pattern of dots that form a triangle. The first 5 numbers of the sequence, or dots, are:
// 1, 3, 6, 10, 15
// This means that the first triangle has just one dot, the second one has three dots, the third one has 6 dots and so on.
// Write a function that gives the number of dots with its corresponding triangle number of the sequence.
// Examples
// triangle(1) ➞ 1
const triangle = (n) => (n * (n + 1)) / 2;
console.log(triangle(1));
console.log(triangle(6));
| true
|
13494d11a143460b1baab4627c165878e95b146b
|
JavaScript
|
KChen8516/practice
|
/scripts/scope/let-scope.js
|
UTF-8
| 220
| 3.4375
| 3
|
[] |
no_license
|
// baz is hoisted but not initialized!
// the var keyword is hoisted AND initialized (undefined)
function foo(bar) {
if(bar) {
console.log(baz); // referenceError
let baz = bar;
}
}
foo('bar');
| true
|
1eebe7953e1d1ffd097ff1f348c920490f6ccb91
|
JavaScript
|
InnocentAnyaele/src-aucc
|
/server/controllers/SeminarController.js
|
UTF-8
| 2,121
| 2.546875
| 3
|
[] |
no_license
|
const Seminar = require('../models/Seminar')
const addSeminar = (req, res, next) => {
const title = req.body.title
const file = req.files.file
// const filename = Date.now() + file.name
const filename = req.body.fileName
const url = req.body.url
// console.log(title)
// console.log(filename)
// console.log(url)
let seminar = new Seminar({
title: title,
file: filename,
url: url
})
seminar.save()
.then(()=>{
res.json({message: 'file saved'})
})
.catch((err)=> {
res.status(400).send(err)
})
// file.mv(`${__dirname}../../../client/src/assets/seminar/${filename}`, err => {
// if(err) {
// console.error(err)
// return res.status(500).send(err)
// }
// let seminar = new Seminar({
// title: title,
// file: filename
// })
// seminar.save()
// .then(()=>{
// res.json({message: 'file saved'})
// })
// .catch((err)=> {
// res.status(400).send(err)
// })
// })
}
const getSeminar = (req, res, next) => {
Seminar.find().sort({ createdAt: -1})
.then(data => {
res.json(data)
})
.catch(err => {
res.status(404).send(err)
})
}
const deleteSeminar = (req, res, next) => {
Seminar.findOneAndDelete({_id: req.params.id}, function(err, result) {
if(err) {
res.status(500).send(err)
}
if(result) {
res.status(200).send()
}
})
// const fs = require('fs')
// fs.unlink(`${__dirname}../../../client/src/assets/seminar/${req.params.file}`, (err) => {
// if (err) throw err
// // console.log('Successful')
// })
}
const searchSeminar = (req, res, next) => {
Seminar.find({title:{ $regex: req.params.id}}, function(err, result) {
if(err) {
res.status(500).send(err)
}
if(result) {
res.json(result)
}
})
}
module.exports = {
addSeminar, getSeminar, deleteSeminar, searchSeminar
}
| true
|
ec6976c852a26862cbc6d1fee4a5fa921b543eb9
|
JavaScript
|
juanPabloEA/redux-oreilly
|
/dataflow/redux-demo.js
|
UTF-8
| 491
| 2.8125
| 3
|
[] |
no_license
|
// dataflow/redux-demo.js
import { dispatch, getState, select, subscribe } from "./redux";
const { addItem } = require("./actions");
subscribe(() => {
console.log("store changed");
});
console.log("initial state", getState());
dispatch(addItem("A book"));
dispatch(addItem("A second book"));
console.log("after dispatch", getState());
console.log("items", select("items"));
/*
this will print the following
state before: { items: [] }
state after: { items: [{ title: 'a new book'}] }
*/
| true
|
d3aa9a52222e166bdf00869208c4d2f199c21552
|
JavaScript
|
YenKaPhuThi/my-profile
|
/app/assets/js/app.js
|
UTF-8
| 692
| 2.578125
| 3
|
[] |
no_license
|
var myProfile = (function() {
'use strict'
var init = (function() {
openNav();
activeNav();
});
var _choice = $('.js-choice');
var _listMenu = $('.menu-item');
var _menuItem = $('.js-item');
var openNav = (function() {
_choice.on('click', function() {
_listMenu.toggleClass('open');
});
});
var activeNav = (function() {
_menuItem.on('click', function() {
_menuItem.removeClass('active');
$(this).addClass('active');
if( $(this).find('active')) {
_listMenu.removeClass('open');
}
});
});
return {
init: init
};
})(window);
$(document).ready(function() {
'use strict'
myProfile.init();
});
| true
|
165ea7d48477240556958a67802e87c881352244
|
JavaScript
|
randomguy069/LearningJavaScript
|
/Day 12/Closures/script.js
|
UTF-8
| 1,433
| 4.125
| 4
|
[] |
no_license
|
//Closures
//Closure Defn : Inner func haS always access to variables and parameters of its outer function even after outer function has returned
function retirement(retirementAge){
var a = ' years left until retirement';
return function (yearOfBirth){
var age = 2018-yearOfBirth;
console.log((retirementAge-age)+a);
}
}
var retirementUS = retirement(66);
retirementUS(1990);
var retirementGer = retirement(65);
var retirementIce = retirement(67);
retirementGer(1980);
retirementIce(1967);
//Closures assignment
function interviewQuestion(job){
var greet = "Greetings, ";
var greet1 = " . How are you doing today?";
if (job === 'developer'){
return function(name){
console.log(greet+name+greet1+"Explain what is Closures?");
}
}
else if(job === 'designer'){
return function(name){
console.log(greet+name+greet1+ " Could you tell what UX is?");
}
}
}
//Closures assignment
var jon = interviewQuestion('designer');
jon("John");
var mich = interviewQuestion('developer')('Michelle');
function intvQ(job){
return function(nam){
if ( job === 'designer'){
console.log("a "+nam);
}
else if(job === 'teacher'){
console.log("b"+nam);
}else{
console.log("c"+nam);
}
}
}
intvQ("designer")("XYZ");
| true
|
a00121d6f2367b63d985f4f8adc0c432c4c4cc51
|
JavaScript
|
PeterBSimmons/BlackJack3
|
/NodejsBlackJackApp/app.js
|
UTF-8
| 6,733
| 4
| 4
|
[] |
no_license
|
'use strict';
var count = 0;
var drawCount = 0;
var value = 0;
var playerValue = 0;
var houseValue = 0;
var playerLost = false;
var houseLost = false;
//Create card deck of 52 cards in an array
var deck = [2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10,
10, 10, 10, "J", "J", "J", "J", "Q", "Q", "Q", "Q", "K", "K", "K", "K", "A", "A", "A", "A"];
//Testdeck
//var deck = ["A", "A", "A", "A", "J", "J", "J", "J"];
//Array for already drawn cards
var drawn = [];
function cc(card) {
switch (card) {
case 2:
count++;
value += 2;
break;
case 3:
count++;
value += 3;
break;
case 4:
count++;
value += 4;
break;
case 5:
count++;
value += 5;
break;
case 6:
count++;
value += 6;
break;
case 7:
value += 7;
break;
case 8:
value += 8;
break;
case 9:
value += 9;
break;
case 10:
count--;
value += 10;
break;
case "J":
count--;
value += 10;
break;
case "Q":
count--;
value += 10;
break;
case "K":
count--;
value += 10;
break;
case "A":
count -= 1;
if (value <= 10) {
value += 11;
}
else {
value++;
}
break;
}
return "Card drawn: " + card + " | Current value: " + value
/*if (value <= 21) {
if (count > 0) {
return "Card drawn: " + card + " | Current value: " + value + " | Current count: " + count + " Bet";
}
else {
return "Card drawn: " + card + " | Current value: " + value + " | Current count: " + count + " Hold";
}
}
else if (value > 21) {
return "YOU LOSE!"
}*/
}
function drawcard() {
//Count number of cards drawn
drawCount++;
//Find the position of the card in the deck array
var cardPos = Math.floor(Math.random() * deck.length);
//Find the actual card in the deck array
var newCard = deck[cardPos];
//console.log("Card drawn: " + newCard);
//Run the Card counting fuction to determine next move
var go = cc(newCard);
//Remove the card from the deck array and place it in temp array "cardRemoved"
var cardRemoved = deck.splice(cardPos, 1);
//console.log("Card removed " + cardRemoved);
//Move the card from the temp array "cardRemoved" to the drawn cards array "drawn"
drawn.unshift(cardRemoved[0]);
"Card placed in the drawn pile: " + drawn;
//Clear up the temp array "cardRemoved" before next runthrough
cardRemoved.shift();
return go;
return drawCount;
}
function runGame() {
for (var i = 0; i < 6; i++) {
if (value < 17 && drawCount < 5) {
console.log(drawcard());
}
else if (drawCount == 5) {
console.log("Congratulations, you drew five cards and stayed below 21!");
}
else if (value < 22) { // <---------- MISSING: Check if 5 cards has been drawn or if value is blackjack!!
if (value == 21) {
console.log("Congratulations, you got Blackjack!");
}
else {
console.log("Player final value: " + value);
}
playerValue = value; //Save the total value in a player value variable, before we reset it
value = 0; //Reset value counter before house draws
break;
}
else {
console.log("You exceeded 21, better luck next time!");
playerLost = true; //Keeping track if the player exceeded 21
playerValue = value;
value = 0;
break;
}
}
if (playerValue < 21 && drawCount < 5) {
for (var i = 0; i < 5; i++) {
if (value <= playerValue && playerLost == false) { //Checks if value is less than or equal to what the play drew
console.log(drawcard());
}
else if (value < 22 && playerLost == false) {
console.log("House final value: " + value);
houseValue = value;
value = 0; //Reset value counter before future second round (to be implemented)
break;
}
else {
console.log("House exceeded 21, player wins!");
houseLost = true;
break;
}
}
}
else {
}
//console.log("Total player value: " + playerValue);
//console.log("Total house value: " + houseValue);
if (playerValue >= houseValue && playerLost == false) {
console.log("Congratulations, you win!");
}
else {
console.log("Sorry, the house wins. Better luck next time!");
}
playerLost == false;
houseLost == false;
drawCount = 0;
}
runGame();
/*//Draw up to five random cards from the deck if the current value of cards drawn is less than 17 and place the card in the drawn array
for (var i = 0; i < 5; i++) {
if (value < 17) {
//Find the position of the card in the deck array
var cardPos = Math.floor(Math.random() * deck.length);
//Find the actual card in the deck array
var newCard = deck[cardPos];
//console.log("Card drawn: " + newCard);
//Run the Card counting fuction to determine next move
console.log(cc(newCard));
//Remove the card from the deck array and place it in temp array "cardRemoved"
var cardRemoved = deck.splice(cardPos, 1);
//console.log("Card removed " + cardRemoved);
//Move the card from the temp array "cardRemoved" to the drawn cards array "drawn"
drawn.unshift(cardRemoved[0]);
console.log("Card placed in the drawn pile: " + drawn);
//Clear up the temp array "cardRemoved" before next runthrough
cardRemoved.shift();
}
else {
console.log("Final value: " + value);
value = playValue;
value = 0;
break;
}
}*/
//Prevent consol from shutting down
const readline = require('readline');
const rl = readline.createInterface(process.stdin, process.stdout);
var answer = "";
rl.question("Type in your name: ", function(answer) {
console.log("Good job, " + answer);
rl.question("Press [Enter] to exit " + answer, function () {
process.exit();
});
});
| true
|
c82c83f2feade9438551488dbe5a86b60ab3e52a
|
JavaScript
|
ShyFidelity/you-can-read-me
|
/utils/generateMarkdown.js
|
UTF-8
| 1,916
| 2.65625
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
// function to render license badge
function renderLicenseBadge(license) {
if (license !== "None") {
return ``;
} return ' ';
}
function renderLicenseLink(license) {
let lApache = '(https://www.apache.org/licenses/LICENSE-2.0)';
let lMIT = '(https://opensource.org/licenses/MIT)';
let lMozilla = '(https://www.mozilla.org/en-US/MPL/2.0/)';
let lArtistic = '(https://opensource.org/licenses/Artistic-2.0)';
let LOliva = '(https://www.youtube.com/watch?v=ZmDBbnmKpqQ)';
switch (license){
case 'ApacheLicense2.0':
return lApache
case 'MIT':
return lMIT
case 'MozillaPublicLicense2.0':
return lMozilla
case 'ArtisticLicense2.0':
return lArtistic
case 'OliviaRodrigoDriversLicense':
return LOliva;
default:
return '';
}
}
function renderLicenseSection(license) {
if (license !== "None") {
return `
Copyright: ${license}
[License link]${renderLicenseLink(license)}`;
}
}
function generateMarkdown(data) {
return `# ${data.title}
${renderLicenseBadge(data.license)}
## GitHub Username and link
## Table of Contents
* [Description](#Description)
* [Motivation](#Motivation)
* [How to Use](#Usage)
* [Contributors](#Contributors)
* [Test](#Test)
* [Dependencies](#dependencies)
* [Questions](#questions)
## [Description](#Description) 📝
${data.description}
## [Motivation](#Motivation) 🤽♂️
${data.motivation}
## [How to Use](#Usage)
${data.usage}
## [Contributors](#Contributors)🏆
${data.contributors}
## [Test](#Test)🎯
${data.test}
## [Dependencies](#dependencies)
${data.dependencies}
## [Questions](#questions)📟
Find me on Github!
[${data.username}](https://github.com/${data.username}/)
or you can email me at ${data.email}
## License
${renderLicenseSection(data.license)}
`;
}
module.exports = generateMarkdown;
| true
|
a071b4ee1f498b506d9f8ff319064e6f84931bc9
|
JavaScript
|
TerminatorP/JSAlgorithms
|
/bubblesort.js
|
UTF-8
| 338
| 3.578125
| 4
|
[] |
no_license
|
function bubblesort(arr) {
let isTrue = false;
while (!isTrue) {
isTrue = true;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > arr[i+1]) {
isTrue = false;
let tmp = arr[i+1];
arr[i+1] = arr[i];
arr[i] = tmp;
}
}
}
return arr;
}
bubblesort([1, 5, 2, 8, 3, 0, 45, 12]);
| true
|
746b56e75a61a5bb735dba72a153d644971e04e3
|
JavaScript
|
luckykaiyi/webpack-init
|
/src/js/modules/hello.js
|
UTF-8
| 448
| 3.453125
| 3
|
[] |
no_license
|
// function Hello(options) {
// this.name = options.name;
// this.container = document.getElementById(options.el);
// this.sayHello = function() {
// this.container.innerText = 'Hello ' + this.name;
// }
// }
class Hello {
constructor(options) {
this.name = options.name;
this.container = document.getElementById(options.el);
}
sayHello() {
this.container.innerText = 'Hello ' + this.name;
}
}
export default Hello;
| true
|
b918b329d598fa074d818a7c8256f04c242f3037
|
JavaScript
|
ZhuPeng/mp-githubtrending
|
/third-party/wux-weapp/helpers/checkIPhoneX.js
|
UTF-8
| 638
| 2.578125
| 3
|
[
"Apache-2.0"
] |
permissive
|
/**
* 获取系统信息
*/
let systemInfo = null
const getSystemInfo = (isForce) => {
if (!systemInfo || isForce) {
try {
systemInfo = wx.getSystemInfoSync()
} catch(e) { /* Ignore */ }
}
return systemInfo
}
// iPhoneX 竖屏安全区域
export const safeAreaInset = {
top: 88, // StatusBar & NavBar
left: 0,
right: 0,
bottom: 34, // Home Indicator
}
const IPHONEX_DEVICE_HEIGHT = 812
const isIPhoneX = ({ model, platform, screenHeight }) => {
return /iPhone X/.test(model) && platform === 'ios' && screenHeight === IPHONEX_DEVICE_HEIGHT
}
export const checkIPhoneX = (isForce) => isIPhoneX(getSystemInfo(isForce))
| true
|
42339610ceca0c7984c1165e9d03a0caa499b219
|
JavaScript
|
amzn/sketch-constructor
|
/models/Swatch/Swatch.test.js
|
UTF-8
| 1,024
| 2.640625
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
const Color = require('../Color');
const Swatch = require('./index');
const json = {
name: 'Test Color',
value: new Color('#c9c'),
};
describe('Swatch', () => {
it('should work from raw JSON', () => {
const swatch = new Swatch(null, json);
expect(swatch._class).toBe('swatch');
});
it('should have a default name when no name is given', () => {
const lime = new Color('limegreen');
const unnamedSwatch = new Swatch({ color: lime });
expect(unnamedSwatch.name).toBe('32CD32');
const namedSwatch = new Swatch({ name: 'Lime', color: lime });
expect(namedSwatch.name).toBe('Lime');
});
it('asColor should work', () => {
const color = new Color('#F00');
const swatch = new Swatch({ color });
const refColor = swatch.asColor();
expect(refColor.swatchID).not.toBeUndefined();
expect(refColor.swatchID).toBe(swatch.do_objectID);
expect(refColor.r).toBe(255);
expect(refColor.g).toBe(0);
expect(refColor.b).toBe(0);
expect(refColor.a).toBe(1);
});
});
| true
|
6fc9d57f85ef042acd5b09c765787f5e03c1044a
|
JavaScript
|
trueproof/test-restaurant
|
/restaurant.test.js
|
UTF-8
| 4,002
| 2.890625
| 3
|
[] |
no_license
|
try {
createWaiter = require('./restaurant').createWaiter
} catch (err) {
}
const defaultMenu = {
1: {
name: 'soup',
spices: ['salt'],
},
2: {
name: 'beef',
spices: ['salt', 'pepper'],
},
3: {
name: 'tea',
spices: ['sugar', 'lemon', 'jasmine'],
},
}
const assert = {
equal (actual, expected, message) {
if (actual !== expected) {
console.log(actual)
throw new Error(message)
}
}
}
let lastMsg
const say = (msg) => {
lastMsg = msg
}
const getTestWaiter = createWaiter(say)
const getDefaultMenuWaiter = (type) => {
return getTestWaiter(type)
.addDish(1, defaultMenu[1].name, ...defaultMenu[1].spices)
.addDish(2, defaultMenu[2].name, ...defaultMenu[2].spices)
.addDish(3, defaultMenu[3].name, ...defaultMenu[3].spices)
}
console.log('#normal operation: add dishes')
assert.equal(
JSON.stringify(getDefaultMenuWaiter(1).getOrder()),
JSON.stringify(defaultMenu),
'waiter 1 failed'
)
assert.equal(
JSON.stringify(getDefaultMenuWaiter(2).getOrder()),
JSON.stringify(defaultMenu),
'waiter 2 failed'
)
console.log('#normal operation: add spices')
assert.equal(
JSON.stringify(getDefaultMenuWaiter(1).addSpices(1, 'pepper', 'garlic').getOrder()),
JSON.stringify(Object.assign(
{},
defaultMenu,
{
1: {
name: 'soup',
spices: ['salt', 'pepper', 'garlic'],
},
}
)),
'waiter 1 failed'
)
assert.equal(
JSON.stringify(getDefaultMenuWaiter(2).addSpices(1, 'pepper', 'garlic').getOrder()),
JSON.stringify(Object.assign(
{},
defaultMenu,
{
1: {
name: 'soup',
spices: ['salt', 'pepper', 'garlic'],
},
}
)),
'waiter 2 failed'
)
console.log('#not allowed dish')
getTestWaiter(1).addDish(4, 'pork')
assert.equal(
lastMsg.includes('not allowed'),
true,
'waiter 1 failed'
)
getTestWaiter(2).addDish(4, 'pork')
assert.equal(
lastMsg.includes('not allowed'),
true,
'waiter 2 failed'
)
console.log('#dish duplicate')
assert.equal(
JSON.stringify(
getDefaultMenuWaiter(1)
.addDish(2, 'pork')
.getOrder()
),
'{}',
'waiter 1 failed'
)
assert.equal(
JSON.stringify(
getDefaultMenuWaiter(2)
.addDish(2, 'pork')
.getOrder()
),
JSON.stringify(defaultMenu),
'waiter 2 failed'
)
console.log('#spice duplicate')
assert.equal(
JSON.stringify(
getDefaultMenuWaiter(1)
.addSpices(2, 'pepper')
.getOrder()
),
'{}',
'waiter 1 failed'
)
assert.equal(
JSON.stringify(
getDefaultMenuWaiter(2)
.addSpices(2, 'pepper')
.getOrder()
),
JSON.stringify(defaultMenu),
'waiter 2 failed'
)
console.log('#spice overflow')
assert.equal(
JSON.stringify(
getDefaultMenuWaiter(1)
.addSpices(3, 'ginger')
.getOrder()
),
'{}',
'waiter 1 failed'
)
assert.equal(
JSON.stringify(
getDefaultMenuWaiter(2)
.addSpices(3, 'ginger')
.getOrder()
),
JSON.stringify(defaultMenu),
'waiter 2 failed'
)
console.log('#add spice to absent dish')
getTestWaiter(1).addSpices(1, 'ginger')
assert.equal(
lastMsg.includes('no dish'),
true,
'waiter 1 failed'
)
getTestWaiter(2).addSpices(1, 'ginger')
assert.equal(
lastMsg.includes('no dish'),
true,
'waiter 2 failed'
)
console.log('#cancel')
getTestWaiter(1).cancel()
assert.equal(
lastMsg.includes('canceled'),
true,
'waiter 1 failed'
)
getDefaultMenuWaiter(1).cancel()
assert.equal(
lastMsg.includes('order is not empty'),
true,
'waiter 1 failed'
)
getDefaultMenuWaiter(2).cancel()
assert.equal(
lastMsg.includes('canceled'),
true,
'waiter 2 failed'
)
| true
|
d5ad74bf377a173010852f05eb119410895e6513
|
JavaScript
|
zlzlzb/EduNodeJS
|
/day2/httpclient.js
|
UTF-8
| 426
| 2.578125
| 3
|
[] |
no_license
|
var net = require('net');
var socket = net.connect({host:'www.naver.com',port:80});
socket.on('connect',function(){
console.log('connected.');
socket.write('GET /index.html HTTPl/1.1\r\n');
socket.write('Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36\r\n');
socket.end('\r\n');
});
socket.on('data',function(data){
console.log(data.toString());
});
| true
|
5eb340edf3cffd6c71bd505db0b1226706de784f
|
JavaScript
|
ms-khann/Challange--Leet-Code
|
/search_insert_position.js
|
UTF-8
| 356
| 3.546875
| 4
|
[] |
no_license
|
// let nums = [1,3,5,6], target = 5;
let nums=[1,3,5,6],target = 2;
var searchInsert = function(nums, target) {
let ind = nums.indexOf(target);
if(ind == -1){
ind = nums.findIndex(ele => ele > target);
}
if(ind == -1){
ind = nums.length;
}
return ind;
};
console.log(searchInsert(nums,target));
// console.log(ind);
| true
|
e5c5ad5df2a18399509e68076e25b5dc65ad2314
|
JavaScript
|
WolaFocusmind/onfocus-webapp
|
/src/Utils/formatHourMinute.js
|
UTF-8
| 400
| 3.078125
| 3
|
[] |
no_license
|
export default function formatHourMinute(durationInSeconds) {
const given_seconds = durationInSeconds;
let timeString;
let dateObj = new Date(given_seconds * 1000);
let hours = dateObj.getUTCHours();
let minutes = dateObj.getUTCMinutes();
return (timeString =
(hours > 0 ? hours.toString().padStart(1, "0") + " hr " : "") +
minutes.toString().padStart(1, "0") +
" min.");
}
| true
|