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
85106dc79099436733fa8ceb1c4a7b2570c3f617
JavaScript
MarcosParengo/CoderHouse
/Curso react js/zClase 1 pre/Funcion Flecha/main.js
UTF-8
335
3.953125
4
[]
no_license
var num1= prompt("numero1") while (isNaN(num1)) { num1= prompt(num1+ " no es un numero") } var num2= prompt("numero2") while (isNaN(num2)) { num2= prompt(num2+ " no es un numero") } num1=parseInt(num1) num2=parseInt(num2) var miFuncion = (numero1,numero2) => numero1+numero2; alert(miFuncion(num1,num2)+" es el resultado");
true
e8294fc1254307440d4e3c7dc1eb5264ea70e316
JavaScript
nikolas-virionis/Javascript
/small-projects-js/Ex13 - cpf-express/modules/geraCPF.js
UTF-8
401
3.0625
3
[]
no_license
import { CPF } from "./CPF.js"; export class GeraCPF { rand(min = 100000000, max = 999999999) { return String(Math.floor(Math.random() * (max - min) + min)); } geraNovoCpf() { let algo; const semDigito = this.rand(); algo = new CPF(semDigito).CPFCompleto(); return algo; } } let i = new GeraCPF(); let cpf = i.geraNovoCpf(); console.log(cpf);
true
f8d71f73894701c2ba671742c6de7d4aade6ba02
JavaScript
ikabir21/Frontend-Mentor-Challanges
/FAQ Accordion Card/script.js
UTF-8
303
3.109375
3
[]
no_license
const inputs = document.querySelectorAll("input"); inputs.forEach(input => { input.addEventListener("click", (e) => { inputs.forEach(input => { if (input.checked){ input.checked = false; e.target.checked = true; } }) }) })
true
003d4e5e2ce7e9a84f47d1ed04eecac54af864d1
JavaScript
mralexsatur/thermostat_js
/spec/ThermostatSpec.js
UTF-8
1,802
3.21875
3
[ "MIT" ]
permissive
describe('Thermostat', function(){ var thermostat; beforeEach(function(){ thermostat = new Thermostat(); }); it('is initialized at 20 degrees', function() { expect(thermostat.getCurrentTemperatur()).toEqual(20); }); it('allows the temperature to be increased by 1 degree', function(){ thermostat.increase(); expect(thermostat.getCurrentTemperatur()).toEqual(21); }) it('allows the temperature to be decreased by 1 degree', function(){ thermostat.decrease(); expect(thermostat.getCurrentTemperatur()).toEqual(19); }) it('will not allow the temperatur to go below 10 degrees', function(){ expect(function() { thermostat.decrease(11); }).toThrowError('That is too cold, brrrr!'); }); it('has power save mode switched on by default', function() { expect(thermostat.powerSaving).toEqual(true); }); it('has capability to turn power saving mode off', function() { thermostat.switchPowerSaving(); expect(thermostat.powerSaving).toEqual(false); }); it('limits temperature to 25 degrees under power saving mode', function() { expect(function() { thermostat.increase(6); }).toThrowError('That is too much!'); }); it('limits temperature to 32 degrees under regular mode', function() { thermostat.switchPowerSaving(); expect(function() {thermostat.increase(13);}).toThrowError('That is too much!'); expect(function() {thermostat.increase(6);}).not.toThrowError('That is too much!'); }); it('temperature can be reset back to 20', function() { thermostat.increase(4); thermostat.reset(); expect(thermostat.getCurrentTemperatur()).toEqual(20); }); it('returns current energy usage', function(){ expect(thermostat.currentEnergyUsage()).toEqual('medium-usage'); }); });
true
c721306bb0a10a4ee705c0d56a956818bac250b4
JavaScript
zkbswgs/RealTimeLogs
/public/js/graphing.js
UTF-8
1,255
2.578125
3
[]
no_license
"use strict"; jQuery(function($) { var lastLineNum = 0; function graphData(name) { var value = 0, values = [], i = 0, last; return context.metric(function(start, stop, step, callback) { start = +start, stop = +stop; if (isNaN(last)) last = start; while (last < stop) { last += step; value = window.linenum - lastLineNum; lastLineNum = window.linenum; if (window.graphEnabled) values.push(value); } callback(null, values = values.slice((start - stop) / step)); }, name); } var topbarSize = $(".topbarWrapper").width() var autoWidth = Math.round(window.innerWidth - topbarSize - 200) var context = cubism.context() .serverDelay(0) .clientDelay(0) .step(1e3) .size(autoWidth); var foo = graphData("foo"); d3.select("#graphBar").call(function(div) { div.datum(foo); div.append("div") .attr("class", "horizon") .call(context.horizon() .height(40) .colors(["#FFFFFF","#FFFFFF","#FFFFFF","#FFFFFF","#00CC33","#BBFF66","#FFBB00","#FF0000"]) .title(" ")); }); // On mousemove, reposition the chart values to match the rule. context.on("focus", function(i) { d3.selectAll(".value").style("right", i == null ? null : context.size() - i + "px"); }); });
true
97a7976beb18227da8a546bc48db25b07f29762c
JavaScript
alejandrochang/Algorithms
/InterviewPrep/CTCI/2.2-kthToLast.js
UTF-8
981
4.5
4
[]
no_license
// Implement an algorithm to find the kth last element // of a singly linked list class Node { constructor(data, next = null) { this.data = data; this.next = next; } } class LinkedList { constructor() { this.head = null; // this.size } insertFirst(data) { this.head = new Node(data, this.head); } } const ll = new LinkedList(); ll.insertFirst(5); ll.insertFirst(1); ll.insertFirst(135); ll.insertFirst(72); ll.insertFirst(23); const kthFromLast = (head, k) => { if (!head) return null; if (!head.next) return head; let slow = head; let fast = head; while (k > 0) { fast = fast.next; k--; } while (fast.next) { slow = slow.next; fast = fast.next; } return slow; } console.log(JSON.stringify(ll, null, 4)); console.log(kthFromLast(ll.head, 2)); // 135 // [pseudo] // decrease the next element from k-- elements away, // iterate while theres a next and a next of a next // return the element when there isnt
true
601ea594913e7c16782b8e490a28d06fd6962c82
JavaScript
jayyei/prueba-skydropx
/components/Card/components/button/button.js
UTF-8
496
2.515625
3
[ "MIT" ]
permissive
import styles from './button.module.css'; // button for generic card const Button = ({ name = 'add', label = 'Hello', isFavorite = false, handleClick = ()=>{} }) => { return( <button className={`${styles.button} ${isFavorite ? styles.active : ''}`} onClick={handleClick} > <i className="material-icons">{name}</i> <span> {label} </span> </button> ); } export default Button;
true
f8e29e15b37b0776ce7f6797e76165c88fe402b6
JavaScript
gheredia90/reAuctions
/app/assets/javascripts/auction.js
UTF-8
4,107
2.53125
3
[]
no_license
var lastSegment = window.location.pathname.split('/').pop(); var matches = lastSegment.match(/\d+/g); var supplier, lowest_bid = ""; window.setInterval(getAuctionData, 1000); window.setInterval(checkAuctionTime, 500); window.setInterval(updateBuyerColors, 1000); function checkAuctionTime(){ if (window.location.pathname.includes("auctions/") && (matches != null)){ currentTime = new Date().getTime(); msLeft = gon.end_date - currentTime; if (msLeft > 0){ updateTime(msLeft); } else { closeAuction(); } } } function updateTime(msLeft){ minLeft = Math.floor((msLeft / 1000)/60); segLeft = Math.floor((msLeft / 1000)%60); $("#countdown").html("<h3>"+ minLeft + " minutes and " + segLeft + " seconds</h3>"); } function closeAuction(){ $.ajax({ type: "POST", url: "/auctions/" + lastSegment }); $("#countdown").html('<div class="alert alert-success" role="alert">Auction finished!</div>'); $("#bid-options").empty(); $('#results-supplier').html( '<button class="btn btn-default btn-lg" type="button"> Lowest bid: <span class="badge">' + lowest_bid + '</span></button>' + '<button class="btn btn-default btn-lg" type="button"> Supplier: <span class="badge">' + supplier + '</span></button>' ); } function getAuctionData(){ if (window.location.pathname.includes("auctions/") && (matches != null)){ $.ajax({ type: "GET", url: window.location.pathname, data: '', success: displayData, error: handleError, dataType: "json" }); } } function handleError (error) { console.log(error); } function displayData (response) { var dataset = response.dataset; var names = response.names; diplayBidsData(response); displayBarChart(dataset); } function diplayBidsData(response){ $('.jumbotron.all-bids').empty(); $('#results').html( '<button class="btn btn-default btn-lg" type="button"> Lowest bid: <span class="badge">' + response.lowest_bid + '</span></button>' + '<button class="btn btn-default btn-lg" type="button"> Supplier: <span class="badge">' + response.supplier + '</span></button>' ); $('#info').html( 'Lowest bid: <span class="badge">' + response.lowest_bid + '</span></button>' ); lowest_bid = response.lowest_bid; supplier = response.supplier; } function displayBarChart(dataset, names){ var svg = d3.select(".jumbotron.all-bids") .selectAll("div") .data(dataset) .enter() .append("div") .attr("class", "bar") .style("background-color", stringToHexNumber) .style("height", function(d) { return d.value*8 + "px"; }) .on("mouseover", function(d) { $("#tip").empty() $("#tip").addClass("alert alert-info"); $("#tip").html(d.name + ': ' + d. value ); }) .on("mouseout", function(d) { $("#tip").empty(); $("#tip").removeClass("alert alert-info"); }); } function stringToHexNumber(d){ var stringHexNumber = (parseInt(parseInt(d.name, 36) .toExponential() .slice(2,-5) , 10) & 0xFFFFFF ).toString(16).toUpperCase(); return '#' + ('000000' + stringHexNumber).slice(-6); } function updateBuyerColors(){ if (gon.role === "Supplier"){ $(".change-element").css("background-color", "#149c82"); $("a.change-element").css("height", "-2px") $(".change-element").css("color", "#F8F8F8"); } else { $(".navbar-fixed-top").addClass("back"); $("#footer").addClass("back"); } } $(document).ready(updateBuyerColors); $(document).load(updateBuyerColors); $(document).load(getAuctionData); $(window).load = function(){ updateBuyerColors(); } $(window).load = function(){ getAuctionData(); } $(window).bind("load", function() { updateBuyerColors(); }); $(window).bind('page:change', function() { updateBuyerColors(); }); $(window).bind('page:change', function() { updateBuyerColors(); }); $(window).bind('page:change', function() { getAuctionData(); }); $(function() { updateBuyerColors(); });
true
21c78206c4ebc2aa2fa8fec9e5b852af828398dc
JavaScript
andela/codepirates-ah-backend
/src/middlewares/tag.middleware.js
UTF-8
1,947
2.6875
3
[]
no_license
/* eslint-disable require-jsdoc */ // import isEmpty from 'utils'; import TagService from '../services/tag.service'; import Util from '../helpers/util'; const util = new Util(); const notFound = (msg) => { util.setError(404, `${msg} not found`); return util; }; const { checkItem, checkTagName, checkArticleTags } = TagService; let found; class TagWare { static async checkArticle(req, res, next) { if (!/^\d+$/.test(req.params.articleId)) { return res.status(400).json({ error: 'articleId must be an integer' }); } const article = await checkItem(req.params.articleId, 'Article'); if (!article) { return notFound('article').send(res); } found = article; next(); } static async checkTagName(req, res, next) { const accepted = /^[\w\s]+$/; if (!accepted.test(req.params.name) || !accepted.test(req.body.name)) { return res.status(400).json({ error: 'tag name must be descriptive' }); } const tag = await checkTagName(req.params.name); if (!tag) { return notFound(`tag ${req.params.name}`).send(res); } next(); } static async tagLimit(req, res, next) { const tags = await checkArticleTags(found); if (tags.length >= 5) { return res.status(200).json({ message: 'this article already has the maximum number of tags, delete or update one', data: found }); } if ((tags.length + req.body.name.split(', ').length) > 5) { return res.status(200).json({ message: `article already has ${tags.length} tags, you ca only add ${5 - tags.length} more`, data: found }); } next(); } static tagLength(req, res, next) { const longTag = req.body.name.split(', ').some(tag => tag.split(' ').length > 3); if (longTag) { return res.status(400).json({ error: 'tag name must be maximum three words' }); } next(); } } export default TagWare;
true
94feda59c9205f49c43b245e9ff56fe2c162ab9d
JavaScript
flasco/problem-shoot
/AC自动机/167.两数之和-ii-输入有序数组.js
UTF-8
514
3.609375
4
[]
no_license
/* * @lc app=leetcode.cn id=167 lang=javascript * * [167] 两数之和 II - 输入有序数组 */ /** * @param {number[]} numbers * @param {number} target * @return {number[]} */ var twoSum = function(numbers, target) { let p1 = 0; let p2 = numbers.length - 1; // 主要利用升序对称的思维,减少无用的遍历 while (p1 < p2) { const sux = target - numbers[p1]; while (numbers[p2] > sux) p2--; if (numbers[p2] === sux) return [p1 + 1, p2 + 1]; p1++; } return []; };
true
09064c11bd59159bc20a871ce5942d983cd82b8e
JavaScript
tomdionysus/moondial
/game/commands/exit.js
UTF-8
732
2.59375
3
[]
no_license
const Command = require('../../lib/Command') module.exports = class ExitCommand extends Command { constructor(gameEngine, actor) { super('exit',gameEngine,actor) } execute() { switch(this.gameEngine.getRandomInt(10)) { case 0: this.gameEngine.writeLine('Come back soon, Gallagher will miss you!') break default: this.gameEngine.writeLine('Shutting your eyes, you tell yourself you will wake on the count of 3.') } process.exit() } static help(gameEngine, actor) { if(!actor.isPlayer()) return gameEngine.writeLine('help: exit - exits the game') } static parse(gameEngine, actor, params) { if(params.length!=0) return module.exports.help() return new module.exports(gameEngine, actor) } }
true
7645cf85e1ffbc842303fe23ed48af27ee8410f0
JavaScript
Ronin-max/Digital-search
/src/unit/createDom.js
UTF-8
1,239
3.15625
3
[]
no_license
import { getRandom } from "./getColor.js"; const container = document.getElementById("container"); //创建dom元素 export default function createDom(n, color) { const span = document.createElement("span"); span.innerText = n; num.innerText = n; //判断是否是素数 if (isPrime(n)) { const div = document.createElement("div"); span.style.color = color; container.appendChild(span); div.style.color = color; div.className = "item"; div.innerText = n; document.body.appendChild(div); getComputedStyle(div).left; //只要读取某个元素的位置或尺寸信息,就会导出触发重绘(reflow) div.style.transform = `translate(${getRandom(-200, 200)}px,${getRandom(-200, 200)}px)`; div.style.opacity = "0"; div.ontransitionend = tEnd; } else { container.appendChild(span); } } //动画结束 function tEnd() { document.body.removeChild(this); } //判断是否是素数 function isPrime(n) { if (n < 2) { return false; } for (let i = 2; i < n; i++) { if (n % i === 0) { return false; } } return true; }
true
a9c36431be81b2ad1db7fd4302c1af067e9ee3ae
JavaScript
RobinTournier/formation_front_wf3
/javascript/assets/js/12.js
UTF-8
2,040
3.125
3
[]
no_license
/*---------------------------------------------------------\ / LE DOM \ / _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \ | Le dom est une interface de developpement | | en JS pour HTML, | | Grâce au DOM, je vais etre en mesure d'acceder / | | modifier mon HTML. | | | | l'objet "document" : c'est le point d'entrée vers mon | | contenu HTML. | | | | Chaque page chargée dans mon navigateur | | à un objet "document" | |_________________________________________________________| /* ------------------------------------------------\ | document.getElementById() est une fonction qui | | va permettre de récupérer un élément en HTML à | | partir de son identifiant unique : ID | \------------------------------------------------*/ var bonjour = document.getElementById('bonjour'); console.log(bonjour); /* document.getElementsByClassName() est une fonction qui va permettre de récupérer un ou plusieurs éléments (une liste) HTML à partir de leur classe. */ var contenu = document.getElementsByClassName('contenu'); console.log(contenu); // Me renvoi un tableau JS avec mes éléments HTML (collection HTML) /* -------------------------------------------------------\ | document.getElementsByTagName () est une fonction qui | | va permettre de récupérer un ou plusieurs éléments | | (une liste) HTML à | | partir de leur nom de balise. | \--------------------------------------------------------*/ var span = document.getElementsByTagName('span'); console.log(span);
true
ab103450211a8fe928923a6ff23129e1d9042b5f
JavaScript
radomely/node-practice
/06_DB/Mongo/001_Connection/main.js
UTF-8
1,150
2.765625
3
[ "MIT" ]
permissive
// для работы с mongodb необходимо подключить модуль. Для этого используйте комманду - npm i mongodb // MongoClient основной клас для работы с БД, через него происходят все взаимодействия с БД var MongoClient = require("mongodb").MongoClient; var format = require("util").format; // Путь, по которому устанавливается соединение c БД, test - имя базы к которой подключаемся var url = "mongodb://localhost:27017/test"; // Используем метод connect для подключения к серверу, функция которая передается в метод, принимает два параетра // err - ошибка, которая возникла при установке соединения с БД // db - ссылка на объект БД MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("Connection established!"); // Закрываем подключение с БД db.close(); });
true
ecb4ed0c70ba7ea75f7857a44e201b1266802889
JavaScript
huyle93/javascript-bible-huyle
/src/array/methods.js
UTF-8
2,786
4.875
5
[ "MIT" ]
permissive
/* Let’s clear up the confusion around the slice( ), splice( ), & split( ) methods in JavaScript */ let arrayDefinition = []; // Array declaration in JS let arrayMess = [1, 2, 3, "hello world", 4.12, true]; /** * Slice() * The slice( ) method copies a given part of an array and returns that copied part as a new array. It doesn’t change the original array. */ // let newArrayMess = arrayMess.slice(0, 3); // console.log(newArrayMess); /** * Splice() * The splice( ) method changes an array, by adding or removing elements from it. * Index is the starting point for removing elements. Elements which have a smaller index number from the given index won’t be removed * array.splice(index, number of elements); */ /* Removing Elements - For removing elements, we need to give the index parameter, and the number of elements to be removed */ // arrayMess.splice(2,1); // remove anything at index of 2, 1 time // console.log(arrayMess); // for (let i = 0; i < 4; i++) { // arrayMess.splice(1,1); // console.log(arrayMess); // } /* Adding Elements - For adding elements, we need to give them as the 3rd, 4th, 5th parameter (depends on how many to add) to the splice ( ) method * array.splice(index, number of elements, element, element); */ arrayMess.splice(0, 0, 'a', 'b'); // add a b to beginning of array arrayMess.splice(4, 0, 'a', 'b'); // add a b to specific index location arrayMess.splice(arrayMess.length, 0, 'a', 'b'); // add a b to end of array console.log(arrayMess); /** * Split() * Use to deal with string, return an array * Slice( ) and splice( ) methods are for arrays. The split( ) method is used for strings. It divides a string into substrings and returns them as an array. It takes 2 parameters, and both are optional. * string.split(separator, limit); * Separator: Defines how to split a string… by a comma, character etc. Limit: Limits the number of splits with a given number */ let myString = arrayMess.toString(); let newArray = myString.split(",", 3); console.log(newArray) /* Summary: Slice ( ) Copies elements from an array Returns them as a new array Doesn’t change the original array Starts slicing from … until given index: array.slice (from, until) Slice doesn’t include “until” index parameter Can be used both for arrays and strings Splice ( ) Used for adding/removing elements from array Returns an array of removed elements Changes the array For adding elements: array.splice (index, number of elements, element) For removing elements: array.splice (index, number of elements) Can only be used for arrays Split ( ) Divides a string into substrings Returns them in an array Takes 2 parameters, both are optional: string.split(separator, limit) Doesn’t change the original string Can only be used for strings */
true
56a36098f0a7ac08a9a89688d870a09b52b2cbf8
JavaScript
liuchaosun/leetcode-training
/code/58.最后一个单词的长度.js
UTF-8
545
3.390625
3
[]
no_license
/* * @lc app=leetcode.cn id=58 lang=javascript * * [58] 最后一个单词的长度 */ // @lc code=start /** * @param {string} s * @return {number} */ var lengthOfLastWord = function (s) { s = s.trim(); if (!s) { return 0; } // 从右往左 s = s.split(''); let right = s.length - 1; let start = 0; while (right) { if (s[right] !== ' ') { if (start === 0) { start = right; } } else if (start > 0) { return start - right; } right--; } return s.length; }; // @lc code=end
true
c25244526c88d36e187b9ca50efdd7b1dddbc678
JavaScript
oshkbello/haus-party-be
/src/middlewares/checkIfNumberIsAlreadyVerified.js
UTF-8
727
2.546875
3
[]
no_license
import user from '../models/User'; const checkThatNumberIsNotVerified = async (req, res, next) => { try { const { username } = req.decoded; const foundUser = await user.findByUsername(username); if (!foundUser) { return res.status(404).json({ // eslint-disable-next-line max-len message: 'You do not seem to be registered, please sign up or try again', // prettier-ignore }); } if (foundUser.verified) { return res.status(401).json({ message: 'Your number has already been verified', }); } next(); } catch (error) { return res.status(500).json({ message: "An error occurred", error }); } }; export default checkThatNumberIsNotVerified;
true
25efe01a42401ba84c22fff10a00ee116f352a1c
JavaScript
whdlrghks/Moaa
/test/upload/app_upload.js
UTF-8
3,028
2.78125
3
[]
no_license
var express = require('express'); var app = express(); var java = require('java'); var path = require('path'); java.classpath.push(path.resolve(__dirname,'zip4j-1.3.2.jar')); console.log(__dirname); java.classpath.push("./"); var multer = require('multer'); // express에 multer모듈 적용 (for 파일업로드) // var upload = multer({ dest: 'uploads/' }); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/org/') // cb 콜백함수를 통해 전송된 파일 저장 디렉토리 설정 }, filename: function (req, file, cb) { cb(null, Date.now()+file.originalname) // cb 콜백함수를 통해 전송된 파일 이름 설정 } }); var upload = multer({ storage: storage }).single('userfile') app.set('views', './view'); // New!! app.set('view engine', 'ejs'); app.get('/upload', function(req, res){ res.render('upload'); }); app.post('/upload', //upload.single('userfile'), function(req, res){ upload(req,res,(function(err){ if(err){ return res.end("Error uploading file."); } res.end("File is uploaded"); })) //65536 Bytes 이상만 분할가능 // var size=0; // //연동된 드라이브 수 / 남은 용량에 맞게 분할시킬 사이즈 정해야한다. // if(req.file.size>65536*3){ // size = parseInt(req.file.size/3); // } // else{ // if(req.file.size>65536*2){ // size = parseInt(req.file.size/2); // // } // else{ // size= req.file.size; // } // } // console.log("split size : "+size); // //분리될 파일이 저장될곳 // var zipFile = java.newInstanceSync("net.lingala.zip4j.core.ZipFile",__dirname+"/uploads/dis/"+req.file.filename+".zip"); // var filesToAdd = java.newInstanceSync("java.util.ArrayList"); // //원래 파일 저장 // var orgFile =java.newInstanceSync("java.io.File",__dirname+"/"+req.file.path); // var parameters = java.newInstanceSync("net.lingala.zip4j.model.ZipParameters"); // parameters.setCompressionMethod(8, function(err, result){ // if(err){ // console.log(err); // } // }); // parameters.setCompressionLevel(5, function(err, result){ // if(err){ // console.log(err); // } // }); // // filesToAdd.addSync(orgFile); // zipFile.createZipFile(filesToAdd, parameters, true, size ,function(err, result){ // if(err){ // console.log(err); // }else { // zipFile.getSplitZipFiles(function(err, results){ // if(err){ // console.log("Split error : "+err); // } // else{ // console.log("Complete Zip4J from " +req.file.filename); // console.log(results.sizeSync()); // console.log(results.getSync(0)); // } // }); // } // }); // res.send('Uploaded! : '+req.file); // object를 리턴함 // console.log(req.file); // 콘솔(터미널)을 통해서 req.file Object 내용 확인 가능. }); app.listen(3000, function () { console.log('Example app listening on port 3000!'); });
true
a304c2bd871f441314c16886427c53dece99f22c
JavaScript
carlleon/-widget
/assets/js/script.js
UTF-8
503
2.5625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
$(document).ready(function() { $('.form-control').change(function() { var hey = $('.val-check-1').val(); console.log(hey); var empty = false; $('.form-control').each(function() { if ($(this).val().length == 0) { empty = true; } }); if (empty) { $('.button-sbmit').attr('disabled', 'disabled'); } else { $('.button-sbmit').removeAttr('disabled'); } }); });
true
be484e13e6eeffb4f8b29951db3a975142254234
JavaScript
qubard/plot-my-location
/public/src/map.js
UTF-8
2,597
2.6875
3
[ "MIT" ]
permissive
mapboxgl.accessToken = 'pk.eyJ1IjoidGFyYXNncml0c2Vua28iLCJhIjoiY2pueG84OWR3MTMydDNwcndkc2Nla3JzcyJ9.o08Y0fXney9VoeqmdAI-bg'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/dark-v9', center: [-122.43, 37.76], // San Franciso :sobbing: zoom: 2 }); var GEOJSON_URL = "/geojson"; var POLL_RATE = 5000; // polling rate in milliseconds var PING_RATE = 60000; function pingGeolocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = { lat: position.coords.latitude, lng: position.coords.longitude }; handleLocation(pos); }, function() { handleLocationError(true, null); }); } else { // Browser doesn't support Geolocation handleLocationError(false, null); } console.log("Pinged geolocation."); } function initMap() { map.on('load', () => { pingGeolocation(); window.setInterval(pingGeolocation, PING_RATE); // Add the source first map.addSource('agents', { "type": "geojson", data: GEOJSON_URL }); // Add the visual layer map.addLayer({ "id": "agent-markers", "source": "agents", "type": "circle", "paint": { "circle-radius": 10, "circle-color": "#007cbf" } }); console.log("Setting load interval."); // Every 5 seconds reload for new points window.setInterval(loadPoints, POLL_RATE); }); } function panTo(pos) { // Move to the actual [lng, lat] if (pos) { map.flyTo({ center: [pos.lng, pos.lat], zoom: 14, speed: 2, curve: 1 }); } else { setTimeout(1000, () => { map.setCenter([pos.lng, pos.lat]) }); console.log("Error panning, trying again."); } } function moveTo(ele) { var uuid = $(ele)[0].innerText; var pos = loadedAgents[uuid]; panTo(pos); } function loadPoints() { console.log("Queried for points"); if (map.loaded()) { var src = map.getSource('agents'); if (src) { src.setData(GEOJSON_URL); } } } function handleLocation(pos) { map.on('load', () => { panTo(pos) }); // Send the position to the server socket.emit('position', pos); } function handleLocationError(browserHasGeolocation, pos) { console.log(browserHasGeolocation, pos); handleLocation({ lat : 0, lng : 0 }); // send dummy lat data }
true
14526970fd89c8ad0ace4c7cfd0e1952676638a7
JavaScript
amirreza888/movie-rater-web-reactjs
/src/components/movie-list.js
UTF-8
1,517
2.53125
3
[]
no_license
import React from "react"; import FontAwesome from 'react-fontawesome' function MovieList(props) { const movieClicked = movie => evt =>{ props.movieClicked(movie); }; const editClicked = movie => { props.editClicked(movie); } const removeClicked = movie => { fetch(`${process.env.REACT_APP_API_URL}/api/movies/${movie.id}/`, { method:"DELETE", headers: { 'Content-Type' : 'application/json', 'Authorization':`Token ${this.props.token}` }, }).then(resp=> props.movieDeleted(movie)) .catch(error => console.log(error)) }; const mm={ cursor: "pointer", } const newMovie = ()=>{ props.newMovie(); }; return( <div> {props.movies.map(movie => { return ( <div key={movie.id}> <h3 key={movie.id} className="movie-item" > <span style={mm} onClick={movieClicked(movie)}>{movie.title}</span> <FontAwesome style={mm} className="movieicon" name="edit" onClick={()=>editClicked(movie)}/> <FontAwesome style={mm} className="movieicon" name="trash" onClick={()=>removeClicked(movie)}/> </h3> </div> ) })} <button onClick={newMovie}>Add new</button> </div> ) } export default MovieList;
true
f885bb1b63d5431e55dcf45bd507811974680108
JavaScript
ErenCelik96/weather-website-JS
/script.js
UTF-8
1,252
3.484375
3
[]
no_license
async function data() { let input = document.getElementById("myText").value; let newInput = input.toString().toLowerCase().replaceAll(" ", "-"); let temperature = document.querySelector(".span1"); let city = document.querySelector(".span2"); let wind = document.querySelector(".span3"); let card1Temp = document.querySelector(".span4"); let card1Wind = document.querySelector(".span5"); let card2Temp = document.querySelector(".span6"); let card2Wind = document.querySelector(".span7"); let card3Temp = document.querySelector(".span8"); let card3Wind = document.querySelector(".span9"); const data = await fetch(`https://goweather.herokuapp.com/weather/${newInput}`); const newData = await data.json(); temperature.innerHTML = `${newData.temperature}`; city.innerHTML = `${input}`; wind.innerHTML = `${newData.wind}`; card1Temp.innerHTML = `${newData.forecast[0].temperature}`; card1Wind.innerHTML = `${newData.forecast[0].wind}`; card2Temp.innerHTML = `${newData.forecast[1].temperature}`; card2Wind.innerHTML = `${newData.forecast[1].wind}`; card3Temp.innerHTML = `${newData.forecast[2].temperature}`; card3Wind.innerHTML = `${newData.forecast[2].wind}`; };
true
13a0f9309555c6e85de5917d8c6cb6c5207d22e4
JavaScript
phpmastermind/notes
/app.js
UTF-8
993
2.578125
3
[]
no_license
var express = require('express') var speech = require('./recognize') var app = express() var filename = './resources/audio.raw'; app.get('/', function (req, res) { res.send('Hello World!') }) app.get('/sync', function (req, res){ // res.send("Transcripting... Please wait."); speech.syncRecognize(filename, function(data){ console.log("Transcription", transcription); }); }) app.get('/stream', function (req, res) { // res.send("Transcripting... Please wait."); speech.streamingRecognize(filename, function(data){ res.send(`Transcsiption ${data}`); //console.log("Transcription", transcription); }); }) /*app.get('/async', function (req, res) { res.send("Transcripting... Please wait."); var transcription = speech.syncRecognize(filename, function(data){ res.send(`Transcription ${data}`); console.log("Transcription", transcription); }); })*/ app.listen(3000, function () { console.log('Example app listening on port 3000!') console.log(speech); })
true
df262542088dcea79fde96a3fbb88646a63ebf9e
JavaScript
drmatt13/portfoliobackend
/data/apps/collection1/Interactive_Pricing/script.js
UTF-8
536
2.984375
3
[]
no_license
const pageviews = document.querySelector(".pageviews"); const price = document.querySelector(".price"); // range slider const slider = document.getElementsByName("price-range")[0]; slider.oninput = e => { pageviews.innerHTML = `${(e.target.value * 6.25).toFixed(0)}K PAGEVIEWS`; price.innerHTML = `$${e.target.value}`; } // toggle button const toggleBtn = document.querySelector(".toggle-btn"); const circle = document.querySelector(".circle"); toggleBtn.addEventListener("click", () => { circle.classList.toggle("yearly"); });
true
7a95bef63da1a0c020fcfb86f81157a5d0e411b3
JavaScript
sbimochan/js-immutable
/test/index.test.js
UTF-8
9,370
3.03125
3
[ "MIT", "CC-BY-SA-4.0", "CC-BY-4.0" ]
permissive
import { expect } from 'chai'; import reduce from '../src/index'; describe('React State Reducer', () => { context('#React State Reducer Function', () => { it('should be a function', () => { expect(reduce) .to.be.a('function'); }); it('should throw an error with undefined selector', () => { expect(reduce) .to.throw(Error); }); it('should throw an error with array selector', () => { expect(() => reduce([])) .to.throw(Error); }); it('should not throw an error with the object as a parameter to reduce', () => { const selector = { someKey: {}, }; expect(() => reduce(selector)) .to.not.throw(); }); it('should throw an error with empty object as a parameter to reduce', () => { const selector = {}; expect(() => reduce(selector)) .to.throw(Error); }); it('should return a function with valid selector', () => { const selector = { someKey: '#', }; expect(() => reduce(selector)) .to.be.a('function'); }); }); context('#React State Reducer Usage', () => { let originalState; beforeEach(() => { originalState = { detail: { address: { permanent: 'Kathmandu', temporary: 'Pokhara', }, friends: ['Robus', 'Rahul', 'Ishan'], age: 23, }, }; }); it('should return the same original state when selector is invalid', () => { const selector = { invalidKey: '#', }; const randomReducer = reduce(selector); const newState = randomReducer(originalState) .set('new value') .apply(); expect(originalState) .to.equal(newState); }); it('should return the shallow state when a level deep selector is invalid', () => { const selector = { detail: { wrongKey: '#', }, }; const randomReducer = reduce(selector); const newState = randomReducer(originalState) .set('some new value') .apply(); expect(originalState) .deep .equal(newState); }); it('should return the new value when applying set to the valid selector', () => { const selector = { detail: { address: { permanent: '#', }, }, }; const permanentReducer = reduce(selector); const actualState = permanentReducer(originalState) .set('New Permanent Location') .apply(); const expectedState = { detail: { address: { permanent: 'New Permanent Location', temporary: 'Pokhara', }, friends: ['Robus', 'Rahul', 'Ishan'], age: 23, }, }; expect(actualState) .to.deep.equal(expectedState); }); it('should append new friend in the list and set a new age using the multiple selector', () => { const multipleSelector = { detail: { friends: '#1', age: '#2', }, }; const ageFriendReducer = reduce(multipleSelector); const newState = ageFriendReducer(originalState) .of('#1') .append('Chumlung') .of('#2') .set(24) .apply(); const expectedState = { detail: { address: { permanent: 'Kathmandu', temporary: 'Pokhara', }, friends: ['Robus', 'Rahul', 'Ishan', 'Chumlung'], age: 24, }, }; expect(newState) .deep.equal(expectedState); }); it('should not set new value when there is undefined or null', () => { const state = { a: 'someValue', }; const reducer = reduce({ a: '#', }); const result = reducer(state) .set(undefined) .apply(); expect(state) .deep .equal(result); }); it('should not append if the value is undefined or null', () => { const selector = { detail: { friends: '#', }, }; const reducer = reduce(selector); const result = reducer(originalState) .append(undefined) .apply(); expect(originalState) .deep.equal(result); }); it('should not append if the selected value is not array', () => { const selector = { detail: { age: '#', }, }; const reducer = reduce(selector); const result = reducer(originalState) .append('try new value') .apply(); expect(result) .deep.equal(originalState); }); it('should not alter the original State when the value is appended to an array', () => { const selector = { detail: { friends: '#', }, }; const reducer = reduce(selector); const result = reducer(originalState) .append('new value is appended') .apply(); expect(result.detail.friends.length) .equal(4); }); it('should merge the new key: value pair', () => { const selector = { detail: { address: '#', }, }; const reducer = reduce(selector); const result = reducer(originalState) .merge({ newKey: 'newValue', }) .apply(); expect(result.detail.address) .deep .equal({ ...originalState.detail.address, newKey: 'newValue', }); }); it('should not merge if undefined or null is passed', () => { const selector = { detail: { address: '#', }, }; const reducer = reduce(selector); const result = reducer(originalState) .merge(undefined) .apply(); expect(result) .deep.equal(originalState); }); it('should delete a key: value from the object', () => { const selector = { detail: { address: '#', }, }; const reducer = reduce(selector); const result = reducer(originalState) .delete('temporary') .apply(); expect(result) .deep .equal({ ...originalState, detail: { ...originalState.detail, address: { permanent: originalState.detail.address.permanent, }, }, }); }); it('should return the same state when key is undefined while deleting', () => { const selector = { detail: { adress: '#', }, }; const reducer = reduce(selector); const result = reducer(originalState) .delete(undefined) .apply(); expect(result) .deep .equal(originalState); }); it('should delete a value in an index when deleting in an array', () => { const selector = { detail: { friends: '#', }, }; const reducer = reduce(selector); const result = reducer(originalState) .delete(1) .apply(); expect(result.detail.friends) .deep .equal(['Robus', 'Ishan']); }); context('JS Immutable pipe method', () => { let state = { name: 'Robus', age: 24, friends: ['Ruby', 'King'], address: { permanent: 'Kathmandu', temporary: 'Pokhara' } } it('should return back the original state when the predicate to the pipe method is null', () => { const selector = { name: '#' } const reducer = reduce(selector) const newState = reducer(state) .pipe(null) .apply(); expect(newState) .deep.equal(state); }) it('should return back the original state when predicate to the pipe method is undefined', () => { const selector = { name: '#' } const reducer = reduce(selector); const newState = reducer(state) .pipe(undefined) .apply(); expect(newState) .deep .equal(state); }) it('should return back the original state when predicate to the pipe method is not a function', () => { const selector = { ages: '#' } const reducer = reduce(selector); const newState = reducer(state) .pipe('Random String') .apply(); expect(newState) .deep .equal(state); }); it('should return list of keys when predicate to the method applies the following transformation', () => { const selector = { address: '#' }; const reducer = reduce(selector); const newState = reducer(state) .pipe(object => Object.keys(object)) .apply() expect(newState.address) .to.deep.equal(['permanent', 'temporary']) }) it('should return new value to the name when predicate to the method applies following transformation', () => { const selector = { name: '#' }; const reducer = reduce(selector); const newState = reducer(state) .pipe(value => value.toUpperCase()) .apply() expect(newState.name) .to.equal(state.name.toUpperCase()) }) }) }); });
true
8fbd1d8ad1d973bbb03699ecef1c98587eb47bed
JavaScript
Jonhks/Ejercicios-eventos-ada
/js/app.js
UTF-8
6,563
3.859375
4
[]
no_license
// playlist // Crear un documento html con un título que diga Mis canciones favoritas y una lista desordenada. Pedir mediante prompts por cinco canciones (una a la vez), y agregar esas canciones como ítems de la lista desordenada // 1.- Poner un titulo con mis canciones favoritas x // 2.- Crear una lista desordenada x // 3.- Pedirle al usuario 5 canciones (1 por 1) x // 4.- Agregar las canciones a la lista (1 por 1) // 4.1 Traer el ul a js x // 4.2 Usar Template string para generar los li con las canciones // 4.3 Pintar las li en el ul // const lista = document.getElementById('lista'); // const cancion1 = prompt('Dame tu primer canción'); // const cancion2 = prompt('Dame tu segunda canción'); // const cancion3 = prompt('Dame tu tercera canción'); // const cancion4 = prompt('Dame tu cuarta canción'); // const cancion5 = prompt('Dame tu quinta canción'); // const canciones = ` // <li>${cancion1}</li> // <li>${cancion2}</li> // <li>${cancion3}</li> // <li>${cancion4}</li> // <li>${cancion5}</li> // `; // lista.innerHTML = canciones; // Ejercico 2 // contador // Crear un documento html que muestre un número (empezando en 0) y 6 botones con los siguientes valores: -1, +1, -5, +5, -10, +10. Cuando se clickea un botón, se tiene que sumar o restar la cantidad correspondiente, y actualizar el número mostrado. // 1.- en el html poner un numero que inicie en 0 x // 2.- Generar 6 botones en el html // 3.- Darles valores a esos 6 botones -1, +1, -5, +5, -10, +10. c/u // 4.- tenemos que hacer la operación que nos dice el boton // ¿Como detectamos a que boton le damos click? // id // ¿Como detecto cual es el valor de ese boton? // - Programar el evento click // - acceder al valor del boton // 5.- Actualizar el numero inicial en html // const menos1 = document.getElementById('-1'); // const mas1 = document.getElementById('+1'); // const menos5 = document.getElementById('-5'); // const mas5 = document.getElementById('+5'); // const menos10 = document.getElementById('-10'); // const mas10 = document.getElementById('+10'); // let count = document.getElementById('count'); // // console.log(count); // // console.log( typeof count.innerHTML); // menos1.addEventListener('click', () => { // // console.log(count.innerHTML) // count.innerText = parseInt(count.innerHTML) - 1; // }); // mas1.addEventListener('click', () => { // count.innerText = parseInt(count.innerHTML) + 1; // }); // menos5.addEventListener('click', () => { // count.innerText = parseInt(count.innerHTML) - 5; // }); // mas5.addEventListener('click', () => { // count.innerText = parseInt(count.innerHTML) + 5; // }); // menos10.addEventListener('click', () => { // count.innerText = parseInt(count.innerHTML) - 10; // }); // mas10.addEventListener('click', () => { // count.innerText = parseInt(count.innerHTML) + 10; // }); // const buttons = document.getElementsByTagName('button'); // Array.from(buttons).forEach(buton => { // buton.addEventListener('click', () => { // console.log(buton.id); // count.innerHTML = parseInt(count.innerHTML) + parseInt(buton.id) // }); // }); // Crear un documento html con // una barra de progreso (con un div dentro de otro) // un elemento de texto que indique el progreso (p. ej. 50%) // dos botones, uno para incrementar y otro para dismininuir la barra (- y +) // cuando se apretan los botones, la barra de progreso tiene que aumentar o disminuir respectivamente y el texto que indica el porcentaje de progreso tiene que actualizarse // lo mismo tiene que pasar cuando se apreta la flecha derecha (aumentar progreso) y la flecha izquierda (disminuir progreso) // el incremento/decremento es del 10% // 1.- Generar dos div, uno dentro de otro // 2.- darles estilos // 3.- Crear los botones // 4.- lograr que avance la barra // const menos = document.getElementById('menos'); // const mas = document.getElementById('mas'); // const chica = document.getElementById('chica'); // const titulo = document.getElementById('titulo'); // let count = 50; // chica.style.width = `${count}%`; // titulo.innerHTML = count; // mas.addEventListener('click', () =>{ // if(count < 100){ // // count = count + 10; // count += 10; // // count = count + 1 // // coun += 1 // // count++ // chica.style.width = `${count}%`; // titulo.innerHTML = count; // } // }) // menos.addEventListener('click', () =>{ // if(count > 0){ // count = count - 10; // chica.style.width = `${count}%`; // titulo.innerHTML = count; // } // }) // const restar = () => { // if(count > 0){ // count = count - 10; // chica.style.width = `${count}%`; // titulo.innerHTML = count; // } // } // menos.addEventListener('click', restar); // kilometros a millas // Kilómetros a Millas // Crear una página que: // Tenga dos inputs, uno para el valor de kilómetros y otro para el de millas. // Cuando se modifica alguno de los dos inputs, el otro cambie automáticamente, realizando la conversión adecuada. Tener en cuenta que ki´lómetro es 0.62 millas, y una milla es 1.61 kilómetros. // 1 km = 0.62 millas // 1 milla 1.61km // const km = document.getElementById('km'); // const millas = document.getElementById('millas'); // const resultado = document.getElementById('resultado'); // km.addEventListener('keyup', (event) => { // const kilo = (event.target.value) * 0.62; // millas.value = kilo // resultado.innerHTML = kilo // }) // millas.addEventListener('keyup', (event) => { // const milla = (event.target.value) * 1.61; // km.value = milla // resultado.innerHTML = milla // }) // for (let index = 0; index < lista.length; index++) { // const element = lisnta[index]; // if(element.innerText.toloWerCase().includes(palabra.tolowercase())){ // element.classList.add('cambios'); // } else { // return null; // } // } // const lista = document.getElementsByTagName('li'); // const palabra = prompt('Busca una palabra'); // for (let index = 0; index < lista.length; index++) { // const element = lista[index]; // element.innerText.toLowerCase().includes(palabra.toLowerCase()) ? element.classList.add('cambios') : null // } // for (const index of lista) { // index.innerText.toLowerCase().includes(palabra.toLowerCase()) ? index.classList.add('cambios') : null // } // const array = Array.from(lista); // array.forEach( index => index.innerText.toLowerCase().includes(palabra.toLowerCase()) ? index.classList.add('cambios') : null); // Estas son las 3 opciones que encontre para resolverlo
true
080f240b61a6303477d8b5c8f10b08372df0650d
JavaScript
amir-the6th/WEB222-Seneca-College
/Assignment 1/src/problem-3.test.js
UTF-8
2,227
3.265625
3
[]
no_license
const { extractFSA } = require('./solutions'); describe('Problem 3 - extractFSA() function', function() { test('valid FSA from valid postal codes', function() { // King Campus expect(extractFSA('L7B 1B3')).toBe('L7B'); // Markham Campus expect(extractFSA('L3R 5Y1')).toBe('L3R'); // Newnham Campus expect(extractFSA('M2J 2X5')).toBe('M2J'); }); test('should throw an Error if there are not enough letters', function() { expect(() => extractFSA('L')).toThrowError('invalid FSA'); expect(() => extractFSA('L7')).toThrowError('invalid FSA'); }); test('invalid FSA should throw an Error if first letter is invalid', function() { // Can't start with a D expect(() => extractFSA('D7B 1B3')).toThrowError('invalid FSA'); // Can't start with an F expect(() => extractFSA('F7B 1B3')).toThrowError('invalid FSA'); // Can't start with a I expect(() => extractFSA('I7B 1B3')).toThrowError('invalid FSA'); // Can't start with an O expect(() => extractFSA('O7B 1B3')).toThrowError('invalid FSA'); // Can't start with a Q expect(() => extractFSA('Q7B 1B3')).toThrowError('invalid FSA'); // Can't start with a U expect(() => extractFSA('U7B 1B3')).toThrowError('invalid FSA'); // Can't start with a W expect(() => extractFSA('W7B 1B3')).toThrowError('invalid FSA'); }); test('invalid FSA should throw an Error if second character is not a number', function() { // Can't have letter in second position expect(() => extractFSA('LAB 1B3')).toThrowError('invalid FSA'); // Can't have space in second position expect(() => extractFSA('L B 1B3')).toThrowError('invalid FSA'); // Can't have . in second position expect(() => extractFSA('L.B 1B3')).toThrowError('invalid FSA'); }); test('invalid FSA should throw an Error if third character is not a letter', function() { // Can't have a number in third position expect(() => extractFSA('L79 1B3')).toThrowError('invalid FSA'); // Can't have space in second position expect(() => extractFSA('L7 1B3')).toThrowError('invalid FSA'); // Can't have . in second position expect(() => extractFSA('L7. 1B3')).toThrowError('invalid FSA'); }); });
true
65b1ef550254e4f5188cef98914d3aa43612da1c
JavaScript
vboluda/DirectDebit
/test/DirectDebitFactory-test.js
UTF-8
3,755
2.640625
3
[]
no_license
const { expect, assert } = require("chai"); //THIS TESTS ARE NOT ENOUGHT. SHOULD BE MUCH MORE DETAILED describe("DirectDebitFactory", function() { it("test owner", async function() { const DirectDebitFactory = await ethers.getContractFactory("DirectDebitFactory"); const instance = await DirectDebitFactory.deploy(); const [owner, addr1] = await ethers.getSigners() await instance.deployed(); await instance.createNewDirectDebitContract(); console.log("LOG - GETOWNER "+await instance.getOwner()); console.log("LOG - OWNER "+(await owner.getAddress())) expect(await instance.getOwner()).equal(await owner.getAddress()); }); it("test balance", async function() { const [owner] = await ethers.getSigners(); const DirectDebit = await ethers.getContractFactory("DirectDebitFactory"); const instance = await DirectDebit.deploy(); await instance.deployed(); await instance.createNewDirectDebitContract(); //console.log("LOG - DEPLOYED "); await owner.sendTransaction({ to: (await instance.getContractAddress()), value: 1000 }); //console.log("LOG - TX SENT"); let balance=(await instance.getBalance()); //console.log("LOG - CONTRACT BALANCE "+balance); expect(""+balance).equals("1000"); //await directdebit.returnFunds(2000); //expect(""+balance).equals("1000"); await instance.returnFunds(500); balance=(await instance.getBalance()); expect(""+balance).equals("500"); }); it("test allow&deny", async function() { const [owner,address1,address2] = await ethers.getSigners(); const DirectDebit = await ethers.getContractFactory("DirectDebitFactory"); const instance = await DirectDebit.deploy(); await instance.deployed(); await instance.createNewDirectDebitContract(); //console.log("LOG - DEPLOYED "); let allowedRecipient=await instance.getAllowed(await address1.getAddress()); //console.log("LOG - allowed "+JSON.stringify(allowedRecipient)); assert.isNotTrue(allowedRecipient[0]); await instance.allow(await address1.getAddress(),10000); allowedRecipient=await instance.getAllowed(await address1.getAddress()); //console.log("LOG - allowed "+JSON.stringify(allowedRecipient)); assert.isTrue(allowedRecipient[0]); expect(""+allowedRecipient[1]).equals("10000"); allowedRecipient=await instance.getAllowed(await address2.getAddress()); //console.log("LOG - allowed "+JSON.stringify(allowedRecipient)); assert.isNotTrue(allowedRecipient[0]); }); it("test process orders", async function() { const [owner,address1] = await ethers.getSigners(); const DirectDebit = await ethers.getContractFactory("DirectDebitFactory"); const instance = await DirectDebit.deploy(); await instance.deployed(); await instance.createNewDirectDebitContract(); console.log("LOG - DEPLOYED "); let _address1=await address1.getAddress(); let order=await instance.getOrder(_address1,1); //console.log("LOG - GetOrder "+JSON.stringify(order)); await instance.allow(_address1,2000); await instance.addOrder( _address1, 1, "0x9944615dfc9c3a705f4363e6659196a61eaa140ab72922df3ac1f7814f050164", 1000 ); order=await instance.getOrder(_address1,1); //console.log("LOG - GetOrder "+JSON.stringify(order)); expect(order[0]).equals("0x9944615dfc9c3a705f4363e6659196a61eaa140ab72922df3ac1f7814f050164"); await owner.sendTransaction({ to: (await instance.getContractAddress()), value: 3000 }); await instance.orderAprobal(_address1,1); balance=(await instance.getBalance()); //console.log("LOG - Balance "+balance); expect(""+balance).equals("2000"); }); });
true
b2f585286d7319d7e239ac8fb66b0fd86d394d29
JavaScript
cristinarojas/checkOutReactProject
/src/app/weather/actions/weatherActions.js
UTF-8
2,258
3.171875
3
[]
no_license
// Action Types. import { SEARCH_WEATHER_REQUEST, SEARCH_WEATHER_SUCCESS, SEARCH_WEATHER_ERROR, SHOW_INFO } from './actionTypes'; // Consuming a service. import axios from 'axios'; // Base Actions - invented by carlos functions // where you can pass type of action or a payload // and will be return object format. import { request, received, error } from '@shared/redux/baseActions'; // Action creators are functions that WE use in our components // that also are injected in the props of that component // - this functions dispatch actions (objects) that have // type and payload. export const searchWeather = (city) => dispatch => { // is a closure of bindActionCreator. // ey! redux here is happening this action...and call the reducer. dispatch(request(SEARCH_WEATHER_REQUEST, city)); // dispatch({type: 'SEARCH_WEATHER_REQUEST'}) const apiKey = '6844b24412a14adf733d233afead26d8'; const apiUrl = `http://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=${apiKey}`; return fetch(apiUrl) .then((response) => response.json()) .then((result) => { console.log('1 ACTION CREATOR-->', result); dispatch(received(SEARCH_WEATHER_SUCCESS, result)) // AQUI MANDO EL OBJETO CON EL PAYLOAD (datos que vienen del servicio) dispatch({type: 'SEARCH_WEATHER_REQUEST', payload: {coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 1609, …}}) }); // Axios Data. /*const axiosData = { method: 'GET', url: 'https://jsonplaceholder.typicode.com/users', headers: { Accept: 'application/json', 'Content-Type': 'application/json' } }; return axios(axiosData) .then(response => dispatch(received(SEARCH_WEATHER_SUCCESS, // ey! redux here is happening this action...and call the reducer. response.data))) // and Im passing the object and payload dispatch({type: 'SEARCH_WEATHER_REQUEST', payload: {…}, weather: Array(3), base: "stations", main: {…}, visibility: 805, …}) .catch(err => { console.log('AXIOS ERROR', err.response); dispatch(error(SEARCH_WEATHER_ERROR)); });*/ } export const showInfo = (show) => dispatch => { console.log('1.- showInfo ACTION CREATOR', show) dispatch(received(SHOW_INFO, show)); }
true
151b2fe90b59cf239c18d241c5706e84250b9156
JavaScript
mbeamen2014/quiz
/app.js
UTF-8
4,219
3.25
3
[]
no_license
$(document).ready(function() { //var questionList = getQuestions(); // init vars var currentQuestion = 0, score = 0, askingQuestion = true; var linebreak = document.createElement("br"); var content = document.getElementById('space'), questionContainer = document.getElementById('questionText'), choicesContainer = document.getElementById('answerList'), scoreContainer = document.getElementById('score'), submitBtn = document.getElementById('submit'); var question = [ {text:'Which U.S. President is the only one from Pennsylvania?', answers: ['James Buchanan', 'Abraham Lincoln', 'Franklin Roosevelt'], right: 'James Buchanan'}, {text:'How many states did the U.S. have during World War II?', answers: ['48', '47', '50'], right: '48'}, {text:'During which year were the Articles of Confederation ratified?', answers: ['1781', '1789', '1776'], right: '1781'}, {text:'During which Civil War battle included a duel between two ironclad warships?', answers: ['Battle of Hampton Roads', 'The Battle of Port Royal', 'The Seige of Charleston Harbor'], right: 'Battle of Hampton Roads'}]; askQuestion(); //function $(id) { // shortcut for document.getElementById //return document.getElementById(id); //} function askQuestion() { var choices = question[currentQuestion].answers, choicesHtml = ""; var length = choices.length; // loop through choices, and create radio buttons for (var i = 0; i < length; i++) { var rand = Math.floor(Math.random() * choices.length); console.log(rand); choicesHtml += "<input type='radio' name='question" + currentQuestion + "' id='choice" + (i + 1) + "' value='" + choices[rand] + "'>" + " <label for='choice" + (i + 1) + "'>" + choices[rand] + "</label><br><br>"; choices.splice(rand,1); } // load the question questionContainer.textContent = "Q" + (currentQuestion + 1) + ". " + question[currentQuestion].text; // load the choices choicesContainer.innerHTML = choicesHtml; // setup for the first time if (currentQuestion === 0) { scoreContainer.textContent = "0 \/ " + question.length; submitBtn.textContent = "Submit Answer"; } } function checkAnswer() { // are we asking a question, or proceeding to next question? if (askingQuestion) { submitBtn.textContent = "Next Question"; askingQuestion = false; // determine which radio button they clicked var userpick, correctIndex, radios = document.getElementsByName("question" + currentQuestion); for (var i = 0; i < radios.length; i++) { if (radios[i].checked) { // if this radio button is checked userpick = radios[i].value; console.log('user pick is ' + userpick); } // get index of correct answer if (radios[i].value == question[currentQuestion].right) { correctIndex = i; console.log('correct index is ' + correctIndex); } } // setup if they got it right, or wrong var labelStyle = document.getElementsByTagName("label")[correctIndex].style; if (userpick == question[currentQuestion].right) { score++; labelStyle.color = "green"; labelStyle.fontWeight = "bold"; } else { labelStyle.color = "red"; console.log(userpick); labelStyle.fontWeight = "bold"; } scoreContainer.textContent = score + " \/ " + question.length; }else { // move to next question // setting up so user can ask a question askingQuestion = true; // change button text back to "Submit Answer" submitBtn.textContent = "Submit Answer"; // if we're not on last question, increase question number if (currentQuestion < question.length - 1) { currentQuestion++; askQuestion(); } else { showFinalResults(); } } } function showFinalResults() { questionContainer.innerHTML = '<h1>Game Over!</h1>'; submitBtn.disabled = true; scoreContainer.innerHTML = "<h2>You've completed the quiz!</h2>" + "<h2>Below are your results:</h2>" + "<h2>" + score + " out of " + question.length + " questions, " + Math.round(score / question.length * 100) + "%<h2>"; } submitBtn.addEventListener("click", checkAnswer, false); });
true
7340b403d59409e9496839652a07fe086ea4b366
JavaScript
lalbricenov/finanzasVolta
/src/cotizar.js
UTF-8
3,810
3.15625
3
[]
no_license
const axios = require('axios'); const apiKey = require('./config/keys').API_KEY; const Company = require('./models/Company'); const cotizarFull = async function(symbol){ let response; try{ response = await axios.get(`https://cloud.iexapis.com/stable/stock/${symbol}/quote?token=${apiKey}`); } catch(err){ console.log(err.data); return undefined; } // console.log("Full:" ,response.data); // Si el programa llega hasta este punto quiere decir que no hubo error let answer = { "name": response.data.companyName, "price": response.data.iexRealtimePrice, "symbol": response.data.symbol } // console.log("Full: ", answer); return answer; } const cotizarFree = async function(symbol) { let response; try{ response = await axios.get(`https://cloud.iexapis.com/stable/tops/last?token=${apiKey}&symbols=${symbol}`); } catch(err){ console.log(err); return undefined; } response = response.data[0]; // console.log(response2.data) // console.log(response); // Si el programa llega hasta este punto quiere decir que no hubo error let answer = { "price": response.price, "symbol": response.symbol } // console.log("Free:" ,response); // console.log("Free: ", answer); return answer; } const cotizar = async function(symbol){ symbol = symbol.toUpperCase(); // Check if the symbol is already in the database of symbols let company; try { company = await Company.findOne({"symbol":symbol}).exec() } catch (error) { console.log("No fue posible buscar la compañía en la base de datos"); } // console.log(company); if(company === null || company === undefined)// si no se encontró la compañía en la base de datos { let quote; try{ quote = await cotizarFull(symbol);// Se debe usar una cotización que incluya el nombre de la compañía } catch (error) { console.log("Error en cotizarFull", error); return undefined } if(quote === undefined || quote.name === undefined)// si no se pudo obtener la cotización de IEX, o está incompleta { return quote; } // Si se llegó a este punto quiere decir que la IEX dió una respuesta // add the company to the database let newCompany = new Company(); newCompany.symbol = symbol; newCompany.companyName = quote.name try { await newCompany.save() } catch (error) { console.log("No fue posible añadir la nueva compañía a la base de datos", error); } // Devolver la cotización a la aplicación principal sin importar si se logró o no guardar la nueva compañía en la base de datos // console.log("Justo antes de responder, después de tratar de añadir la nueva compañía", quote); return quote; } else { // Si la compañía ya está en la base de datos de la aplicación try { quote = await cotizarFree(symbol);// Price and symbol from the IEX api for free } catch (error) { console.log("Error en cotizarFree", error); return undefined } if(quote === undefined)// si no se pudo obtener la cotización de IEX { return quote } // Si se llegó a este punto quiere decir que la IEX dió una respuesta quote.name = company.companyName;// Company name from the applicacion database // console.log("Justo antes de responder, después de NO tratar de añadir la nueva compañía", quote); return quote; } } module.exports = cotizar;
true
b0f2156fb87dc45a3b774b7c6d961770cc4f0bc7
JavaScript
aashirwad01/custom-translator
/server.js
UTF-8
619
2.546875
3
[]
no_license
const express = require('express'); var cors = require('cors') var app = express() app.use(cors()) function translate(text){ return text +" | " + text.split("").reverse().join(""); } app.get("/", (req, res) => { res.send(" Go to translate") }) app.get('/translate/mirror.json', (req, res) => { console.log(req.query.text) res.json({ "success": { "total": 1 }, "contents": { "translated": translate(req.query.text), "text": req.query.text || "text missing", "translation": "mirror image" } }) }); app.listen(3000, () => { console.log('server started'); });
true
e64dc908c9781527ee6f739f08417d336c0c7444
JavaScript
andyruwruw/enhanced-spotify-api
/src/lib/models/Show.js
UTF-8
13,747
2.859375
3
[ "MIT" ]
permissive
const Models = require('../../index'); /** * Creates a new Show Instance for a given show * * @param {object | string} data Data to be preloaded, * Must either be a string of the show ID or contain an `id` property */ function Show(data) { if (typeof (data) === 'string') { this.id = data; this._episodes = new Models.Episodes(); } else if (typeof (data) === 'object') { if ('id' in data) { this.id = data.id; } else { throw new Error('Show.constructor: No ID Provided'); } this._episodes = '_episodes' in data ? data._episodes : new Models.Episodes(); this.loadConditionally(data); } else { throw new Error('Show.constructor: Invalid Data'); } this.episodesRetrieved = false; if ('total_episodes' in this && this.total_episodes !== undefined && this.total_episodes === this._episodes.size()) { this.episodesRetrieved = true; } this.type = 'show'; } Show.prototype = { /** * Plays show on user's active device * * @param {object} [options] (Optional) Additional options * @param {object} [options.offset] Where from the context to play * (Only valid with albums and Shows) * @param {number} [options.offset.position] Index of item to start with in context * @param {string} [options.offset.uri] URI of item to start with in context * @returns {object} Response from request. */ play(options) { const _options = options || {}; _options.context_uri = `spotify:show:${this.id}`; return Models.wrapperInstance.play(_options); }, /** * Returns whether a show is saved to the user's library * * @returns {boolean} Whether show is saved to the user's library */ async isLiked() { const response = await Models.wrapperInstance.containsMySavedShows([this.id]); return response.body[0]; }, /** * Adds show to the user's library * * @returns {object} Response to request */ like() { return Models.wrapperInstance.addToMySavedShows([this.id]); }, /** * Removes show from the user's library * * @returns {object} Response to request */ unlike() { return Models.wrapperInstance.removeFromMySavedShows([this.id]); }, /** * Returns boolean whether full object data is present * * @returns {boolean} Whether full object is loaded */ containsFullObject() { return ((this.name != null) && (this.available_markets != null) && (this.copyrights) && (this.description != null) && (this.explicit != null) && (this.episodes) && (this.external_urls != null) && (this.href != null) && (this.images != null) && (this.languages != null) && (this.media_type != null) && (this.publisher != null) && (this.uri != null)); }, /** * Returns boolean whether simplified object data is present * * @returns {boolean} Whether simplified object is loaded */ containsSimplifiedObject() { return ((this.name != null) && (this.available_markets != null) && (this.copyrights) && (this.description != null) && (this.explicit != null) && (this.external_urls != null) && (this.href != null) && (this.images != null) && (this.languages != null) && (this.media_type != null) && (this.publisher != null) && (this.uri != null)); }, /** * Returns full show data, * Retrieves from Spotify API if necessary * * @returns {object} Show full object data. */ async getFullObject() { if (!(this.containsFullObject())) { await this.retrieveFullObject(); } return { id: this.id, name: this.name, available_markets: this.available_markets, copyrights: this.copyrights, description: this.description, explicit: this.explicit, episodes: this.episodes, external_urls: this.external_urls, href: this.href, images: this.images, is_externally_hosted: this.is_externally_hosted, languages: this.languages, media_type: this.media_type, publisher: this.publisher, uri: this.uri, type: 'show', }; }, /** * Returns simplified show data, * Retrieves from Spotify API if necessary * * @returns {object} Show simplified object data. */ async getSimplifiedObject() { if (!(this.containsSimplifiedObject())) { await this.retrieveFullObject(); } const data = { id: this.id, name: this.name, available_markets: this.available_markets, copyrights: this.copyrights, description: this.description, explicit: this.explicit, external_urls: this.external_urls, href: this.href, images: this.images, is_externally_hosted: this.is_externally_hosted, languages: this.languages, media_type: this.media_type, publisher: this.publisher, uri: this.uri, type: 'show', }; return data; }, /** * Just returns whatever the show object currently holds * * @returns {object} Any show data */ getCurrentData() { const data = { id: this.id, type: 'album', }; const properties = [ 'name', 'available_markets', 'copyrights', 'description', 'explicit', 'episodes', 'external_urls', 'href', 'images', 'is_externally_hosted', 'languages', 'media_type', 'publisher', 'uri', '_episodes', ]; for (let i = 0; i < properties.length; i += 1) { if (this[properties[i]] != null) { data[properties[i]] = this[properties[i]]; } } return data; }, /** * Returns Episodes object of all show's episodes * * @returns {Episodes} Episodes instance with all show's episodes */ async getAllEpisodes() { if (!this.episodesRetrieved) { await this.retrieveEpisodes(); } return this._episodes; }, /** * Returns Episodes object of show's episodes * * @param {object} [options] (Optional) Additional Options * @param {number} [options.limit=20] Maximum number of episodes to return (Max: 50) * @param {number} [options.offset=0] The index of the first episode to return * @param {string} [options.market] Country code * @returns {Episodes} Episodes instance with all show's episodes. */ async getEpisodes(options) { if (!this.episodesRetrieved) { const response = await Models.wrapperInstance.getShowEpisodes(this.id, options || {}); const episodes = new Models.Episodes(response.body.items); await this.loadEpisodes(episodes); return episodes; } const offset = options !== undefined && 'offset' in options ? options.offset : 0; const limit = options !== undefined && 'limit' in options ? options.limit : 20; return this._episodes.slice(offset, offset + limit); }, /** * Retrieves full show data from Spotify API */ async retrieveFullObject() { const response = await Models.wrapperInstance.getShow(this.id); await this.loadFullObject(response.body); }, /** * Retrieves all episodes in show from Spotify API */ async retrieveEpisodes() { if (this.episodesRetrieved) { return; } const options = { limit: 50, offset: 0, }; let response; do { response = await Models.wrapperInstance.getShowEpisodes(this.id, options); await this.loadEpisodes(response.body.items); options.offset += 50; } while (!(response.body.items.length < 50)); this.episodesRetrieved = true; }, /** * Sets full data (outside constructor) * * @param {object} data Object with show full object data */ async loadFullObject(data) { this.name = data.name; this.available_markets = data.available_markets; this.copyrights = data.copyrights; this.description = data.description; this.explicit = data.explicit; this.episodes = data.episodes; this.external_urls = data.external_urls; this.href = data.href; this.images = data.images; this.is_externally_hosted = data.is_externally_hosted; this.languages = data.languages; this.media_type = data.media_type; this.publisher = data.publisher; this.uri = data.uri; if ('episodes' in data) { if (typeof (data.episodes) === 'object' && 'items' in data.episodes) { this.loadEpisodes(data.episodes.items); } else if (data.episodes instanceof Array) { this.loadEpisodes(data.episodes); } } if ('total_episodes' in data) { this.total_episodes = data.total_episodes; } }, /** * Sets simplified data (outside constructor) * * @param {object} data Object with show simplified object data */ async loadSimplifiedObject(data) { this.name = data.name; this.available_markets = data.available_markets; this.copyrights = data.copyrights; this.description = data.description; this.explicit = data.explicit; this.external_urls = data.external_urls; this.href = data.href; this.images = data.images; this.is_externally_hosted = data.is_externally_hosted; this.languages = data.languages; this.media_type = data.media_type; this.publisher = data.publisher; this.uri = data.uri; if ('total_episodes' in data) { this.total_episodes = data.total_episodes; } }, /** * Sets all data conditionally * * @param {object} data Object with show data */ loadConditionally(data) { const properties = [ 'name', 'available_markets', 'copyrights', 'description', 'explicit', 'episodes', 'external_urls', 'href', 'images', 'is_externally_hosted', 'languages', 'media_type', 'publisher', 'total_episodes', 'uri', 'total_episodes', ]; for (let i = 0; i < properties.length; i += 1) { if (properties[i] in data) { this[properties[i]] = data[properties[i]]; } } if ('episodes' in data) { if (typeof (data.episodes) === 'object' && 'items' in data.episodes) { this.loadEpisodes(data.episodes.items); } else if (data.episodes instanceof Array) { this.loadEpisodes(data.episodes); } } }, /** * Helper method to add episodes to shows's internal Episodes item * * @param {Array | Episode | object | string} episodes */ async loadEpisodes(episodes) { if (episodes instanceof Models.Episodes || episodes instanceof Array) { this._episodes.concat(episodes); } else if (typeof (tracks) === 'object' || typeof (tracks) === 'string') { this._episodes.push(episodes); } else { throw new Error('Show.loadEpisodes: Invalid Parameter "episodes"'); } }, }; /** * Returns Show object of ID * * @param {string} showID Id of Show * @returns {Show} Show from id */ Show.getShow = async function getShow(showID) { const response = await Models.wrapperInstance.getShow(showID); return new Models.Show(response.body); }; /** * Adds functionality to Class * * @param {object} methods Object containing new methods to be added as properties */ Show.addMethods = function addMethods(methods) { const methodNames = Object.keys(methods); for (let i = 0; i < methodNames.length; i += 1) { this.prototype[methodNames[i]] = methods[methodNames[i]]; } }; /** * Replaces a method within the Class * * @param {string} name Name of the method to replace * @param {function} method Function to replace with */ Show.override = function override(name, method) { if (name in this.prototype) { this.prototype[name] = method; } else { throw new Error('Show.override: \'name\' does not exist.'); } }; Show.setCredentials = function setCredentials(credentials) { Models.wrapperInstance.setCredentials(credentials); }; Show.getCredentials = function getCredentials() { return Models.wrapperInstance.getCredentials(); }; Show.resetCredentials = function resetCredentials() { Models.wrapperInstance.resetCredentials(); }; Show.setClientId = function setClientId(clientId) { Models.wrapperInstance.setClientId(clientId); }; Show.setClientSecret = function setClientSecret(clientSecret) { Models.wrapperInstance.setClientSecret(clientSecret); }; Show.setAccessToken = function setAccessToken(accessToken) { Models.wrapperInstance.setAccessToken(accessToken); }; Show.setRefreshToken = function setRefreshToken(refreshToken) { Models.wrapperInstance.setRefreshToken(refreshToken); }; Show.setRedirectURI = function setRedirectURI(redirectUri) { Models.wrapperInstance.setRedirectURI(redirectUri); }; Show.getRedirectURI = function getRedirectURI() { return Models.wrapperInstance.getRedirectURI(); }; Show.getClientId = function getClientId() { return Models.wrapperInstance.getClientId(); }; Show.getClientSecret = function getClientSecret() { return Models.wrapperInstance.getClientSecret(); }; Show.getAccessToken = function getAccessToken() { return Models.wrapperInstance.getAccessToken(); }; Show.getRefreshToken = function getRefreshToken() { return Models.wrapperInstance.getRefreshToken(); }; Show.resetClientId = function resetClientId() { return Models.wrapperInstance.resetClientId(); }; Show.resetClientSecret = function resetClientSecret() { return Models.wrapperInstance.resetClientSecret(); }; Show.resetAccessToken = function resetAccessToken() { return Models.wrapperInstance.resetAccessToken(); }; Show.resetRefreshToken = function resetRefreshToken() { return Models.wrapperInstance.resetRefreshToken(); }; Show.resetRedirectURI = function resetRedirectURI() { return Models.wrapperInstance.resetRedirectURI(); }; module.exports = Show;
true
4f376e8b35c1b7900c8390cb9bc52ac848fad2dc
JavaScript
Ulysses31/react-reduxtoolkit-hooks
/src/state/actions/post-actions.js
UTF-8
202
2.625
3
[ "MIT" ]
permissive
const apiurl = 'https://jsonplaceholder.typicode.com/posts'; export const fetchApi = () => { return fetch(apiurl) .then((data) => data.json()) .then((resp) => { return resp; }); };
true
a054e559554de0fdd7354b15099d29dba2ef1ae3
JavaScript
AndreiMoiceanu29/expensify-app
/src/playground/counter.js
UTF-8
1,898
3.171875
3
[]
no_license
/*let count=0; const addOne =()=>{ count++; renderCouterApp(); } const minusOne =()=>{ count--; renderCouterApp(); } const reset =()=>{ count=0; renderCouterApp(); } const renderCouterApp =()=>{ const templateTwo=( <div> <h1>Count :{count}</h1> <button onClick={addOne}>+1</button> <button onClick={minusOne}>-1</button> <button onClick={reset}>reset</button> </div> ); ReactDOM.render(templateTwo, appRoot); }*/ class Counter extends React.Component{ constructor(props){ super(props) this.handleAddOne=this.handleAddOne.bind(this) this.handleMinusOne=this.handleMinusOne.bind(this) this.handleReset=this.handleReset.bind(this) this.state={count:props.count} } componentDidMount(){ const num=parseInt(localStorage.getItem('count')) if(num) { this.setState(()=>({count:num})) } } componentDidUpdate(){ localStorage.setItem('count',this.state.count) } handleAddOne(){ this.setState((prevState)=>{ return{ count:prevState.count+1 } }) } handleMinusOne(){ this.setState((prevState)=>{ return{ count:prevState.count-1 } }) } handleReset(){ this.setState(()=>{ return{ count:0 } }) } render() { return( <div> <h1>Count:{this.state.count}</h1> <button onClick={this.handleAddOne}>+1</button> <button onClick={this.handleMinusOne}>-1</button> <button onClick={this.handleReset}>reset</button> </div> ) } } Counter.defaultProps={ count:0 } ReactDOM.render(<Counter/>,document.getElementById('app'))
true
032a32678ba10dfa618e9fb68440c52d943f6624
JavaScript
harshalitalele/DataStructure
/linkedlist.js
UTF-8
984
3.796875
4
[ "MIT" ]
permissive
function node(val) { this.val = val; this.next = null; } function linkedList() { this.head = null; } linkedList.prototype.addNode = function(node) { node.next = this.head; this.head = node; } linkedList.prototype.get = function(i) { var curNode = this.head, index = 0; while(curNode != null) { if(index == i) { return curNode; } else { index++; curNode = curNode.next; } } } var ll1 = new linkedList(), node1 = new node(1), node2 = new node(2), node3 = new node(3), node4 = new node(4), node5 = new node(7), node6 = new node(6), node7 = new node(5); ll1.addNode(node1); ll1.addNode(node2); ll1.addNode(node3); ll1.addNode(node4); ll1.addNode(node5); ll1.addNode(node6); ll1.addNode(node7); var currentNode = ll1.head; while(currentNode != null) { //console.log(currentNode.val); currentNode = currentNode.next; } console.log(ll1.get(0));
true
1fe271fbae6211b3d0a18ccd16c83f955bb0ef97
JavaScript
urmastalimaa/interactive_frontend_development_2018
/lecture_5/src/async_process_basics/actions/CommentServerActions.js
UTF-8
2,260
2.890625
3
[ "MIT" ]
permissive
// Note that the Fetch API is not supported in every browser and may need to be // polyfilled in production code: // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API import { getCommentsRequested, getCommentsFailed, getCommentsSucceeded, postCommentRequested, postCommentFailed, postCommentSucceeded } from './index'; const SERVER_ADDRESS = 'http://localhost:8081'; // Define one method which executes the asynchronous process export const postComment = ({author, text, localId}, fetch = window.fetch) => { return (dispatch) => { const requestAction = postCommentRequested({author, text}); dispatch(requestAction); const localId = requestAction.payload.localId; return fetch( SERVER_ADDRESS + '/comments', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({author, text}) }, ).then((response) => { if (response.ok) { response.json().then( ({id}) => dispatch(postCommentSucceeded({localId, id})), (error) => dispatch(postCommentFailed({localId, error: 'Unparseable response'})) ); } else { response.json().then( ({error}) => dispatch(postCommentFailed({localId, error: error})), (error) => dispatch(postCommentFailed({localId, error: 'Unparseable response'})) ); } }).catch((error) => { dispatch(dispatch(postCommentFailed({localId, error: 'Service unreachable'}))); }); }; }; export const getComments = (fetch = window.fetch) => { return (dispatch) => { dispatch(getCommentsRequested()); return fetch(SERVER_ADDRESS + '/comments') .then((response) => { if (response.ok) { response.json().then( (comments) => dispatch(getCommentsSucceeded(comments)), (error) => dispatch(getCommentsFailed('Unparseable response')) ); } else { response.json().then( ({error}) => dispatch(getCommentsFailed(error)), (error) => dispatch(getCommentsFailed('Unparseable response')) ); } }).catch((error) => { dispatch(dispatch(getCommentsFailed('Service unreachable'))); }); }; };
true
f1d24f427708a3af8db5c8b91f951b774a9e4dcd
JavaScript
whitingba/mongo-news-scrape
/server.js
UTF-8
4,757
2.703125
3
[]
no_license
//Require node packages const express = require('express'); const logger = require('morgan'); const mongoose = require('mongoose'); const axios = require('axios'); const cheerio = require('cheerio'); //Require the models from my models folder const db = require('./models'); //connection to port var PORT = process.env.PORT || 8060; //Initialize Express const app = express(); //Use morgan logger for logging requests app.use(logger('dev')); //Parse the request body as JSON app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(express.static('public')); //set handlebars const exphbs = require('express-handlebars'); app.engine('handlebars', exphbs({ defaultLayout: 'main' })); app.set('view engine', 'handlebars'); //Connect to Mongo DB //mongoose.connect('mongodb://localhost/articledb', { useNewUrlParser: true }); var MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/articledb"; mongoose.connect(MONGODB_URI); //Routes app.get("/", function (req, res) { db.Article.find({}, null, function (err, data) { if (data.length === 0) { res.render('message', { message: "Hit the scrape button above to see fresh news!" }); } else { res.render('index', { articles: data }); } }); }); //GET route to scrap website of choice app.get('/scrape', function (req, res) { //grab body of HTML using axios axios.get('https://www.sciencedaily.com/news/computers_math/computer_programming/').then(function (response) { //loan into cheerio and save it into a shorthand selector of $ const $ = cheerio.load(response.data); $('.latest-head').each(function (i, element) { //create an empty object to save the data to be scraped var result = {}; result.title = $(this) .children('a') .text(); //console.log(result.title); result.link = $(this) .children('a') .attr('href'); // console.log(result.title + result.link); db.Article.create(result) .then(function (dbArticle) { console.log(dbArticle); }) .catch(function (err) { console.log(err); }); }); console.log("Scrape Complete"); res.redirect('/'); }); }); app.get('/saved', function (req, res) { db.Article.find({ issaved: true }, function (err, saved) { if (saved.length === 0) { res.render('message', { message: "Try saving some articles first, then come back" }); } else { res.render('savedArticles', { saved }) } }); }); // //Route to view all the saved articles // app.get('/saved', function (req, res) { // db.Article.find({ issaved: true }, null, function (err, data) { // if (data.length === 0) { // res.render('message', { message: "Try saving some articles first, then come back" }); // } // else { // res.render('notsaved', { save: data }); // } // }); // }); // Route to save an article app.put('/update/:id', function (req, res) { db.Article.updateOne({ _id: req.params.id }, { $set: { issaved: true } }, function (err, result) { if (result.changedRows == 0) { return res.status(404).end(); } else { res.status(200).end(); } }); }); //Route to unSave an article app.put('/unsave/:id', function (req, res) { db.Article.updateOne({ _id: req.params.id }, { $set: { issaved: false } }, function (err, result) { if (result.changedRows == 0) { return res.status(404).end(); } else { res.status(200).end(); } }); }); //Route to save/update the article's note app.post('/articles/:id', function (req, res) { //create a new note and pass the req.body to the note entry db.Note.create(req.body) .then(function (dbNote) { return db.Article.findOneAndUpdate({ _id: req.params.id }, { note: dbNote._id }, { new: true }); }) .then(function (dbArticle) { res.json(dbArticle); }) .catch(function (err) { res.json(err); }) }) app.get('/clear', function (req, res) { db.Article.deleteMany({}, function (error, response) { if (error) { console.log(error); res.send(error); } else { console.log('articles cleared'); res.redirect('/'); } }); }); //start server app.listen(PORT, function () { console.log(`App running on http://localhost:${PORT}`) })
true
2972859d91cb256c7473d68f42701f6e12ce3b9d
JavaScript
mihar-22/preact-hooks-event
/src/__tests__/index.test.js
UTF-8
1,389
2.515625
3
[ "MIT" ]
permissive
/** @jsx h */ import { h } from 'preact' import { render } from '@testing-library/preact' import useEventListener from '..' describe('useEventListener', () => { const mouseMoveEvent = { clientX: 100, clientY: 200 } let mockHandler = null const mockElement = { addEventListener: (eventName, handler) => { mockHandler = handler }, removeEventListener: () => { mockHandler = null }, dispatchEvent: (event) => { mockHandler(event) } } it('should call `addEventListener` and `handler`', () => { const handler = jest.fn() const spy = jest.spyOn(mockElement, 'addEventListener') function Comp () { useEventListener('foo', handler, mockElement) } render(<Comp />) expect(spy).toBeCalled() mockElement.dispatchEvent(mouseMoveEvent) expect(handler).toBeCalledWith(mouseMoveEvent) spy.mockRestore() }) it('should default to `window/global` given no element', () => { const handler = jest.fn() const spy = jest.spyOn(global, 'addEventListener') function Comp () { useEventListener('foo', handler) } render(<Comp />) expect(spy).toBeCalled() spy.mockRestore() }) it('should fail safe given no window (SSR)', () => { const handler = jest.fn() function Comp () { useEventListener('foo', handler, {}) } render(<Comp />) }) })
true
cf1b518c3d5f7e756885d508d53f23e0149b1442
JavaScript
leomos/hyp
/public/assets/js/CartModel.js
UTF-8
3,115
2.796875
3
[]
no_license
var CartModel = function() { this.bookQuantities = []; this.books = []; this.error = null; this.fetchCartEvent = new Event(this); }; CartModel.prototype = { getBookQuantities: function() { return this.bookQuantities; }, getBooks: function() { return this.books; }, putBook: function (bookId, quantity) { $.ajax({ method: 'PUT', url: '/cart', data: JSON.stringify({ book_id: bookId, quantity: quantity || 1, }), contentType : 'application/json', processData : false }) .done(this.fetchCart.bind(this)) .fail(function(jqXHR, textStatus, errorThrown) { this.error = errorThrown; }.bind(this)); }, changeBookQuantity: function (bookId, quantity) { $.ajax({ method: 'PATCH', url: '/cart', data: JSON.stringify({ book_id: bookId, quantity: quantity }), contentType : 'application/json', processData : false }) .done(this.fetchCart.bind(this)) .fail(function(jqXHR, textStatus, errorThrown) { this.error = errorThrown; }.bind(this)); }, decrementBookQuantity: function(bookId) { var actualBookQuantity = this.bookQuantities.find(function(bookQuantity) { return bookQuantity.book_id === bookId; }); console.log(actualBookQuantity); if(actualBookQuantity) { this.changeBookQuantity(bookId, actualBookQuantity.quantity - 1); } }, incrementBookQuantity: function(bookId) { var actualBookQuantity = this.bookQuantities.find(function(bookQuantity) { return bookQuantity.book_id === bookId; }); console.log(actualBookQuantity); if(actualBookQuantity) { this.changeBookQuantity(bookId, actualBookQuantity.quantity + 1); } }, deleteBook: function(bookId) { this.changeBookQuantity(bookId, 0); }, deleteAllBooks: function() { $.ajax({ method: 'DELETE', url: '/cart' }) .done(this.fetchCart.bind(this)) .fail(function(jqXHR, textStatus, errorThrown) { this.error = errorThrown; }.bind(this)); }, fetchCart: function() { $.get('/cart') .done(function(bookQuantities) { this.bookQuantities = bookQuantities.books_quantities; this.books = []; var booksRequestsPromises = this.bookQuantities.map(function(bookQuantity){ return $.get('/books/'+bookQuantity.book_id); }); $.when.apply(null, booksRequestsPromises) .done(function() { if(arguments.length === 3 && (typeof arguments[1])==="string") { this.books.push(arguments[0]); } else { for (var i = 0; i < arguments.length; i++) { this.books.push(arguments[i][0]); } } this.fetchCartEvent.notify(); }.bind(this)); this.error = null; }.bind(this)) .fail(function(jqXHR, textStatus, errorThrown) { this.bookQuantities = []; this.error = errorThrown; this.fetchCartEvent.notify(); }.bind(this)); }, };
true
f626fc94619c09a9d75f6d26fdcc983ae176ee60
JavaScript
faizkhan12/LeetCode
/2. Add Two Numbers.js
UTF-8
1,338
3.875
4
[]
no_license
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var addTwoNumbers = function (l1, l2) { let tail, head = null; let prevTenth = 0; while (l1 || l2) { // continue until any of l1 and l2 is not NULL let sum = 0; sum += l1 ? l1.val : 0; // Get value from l1 node, or 0 if l1 is NULL sum += l2 ? l2.val : 0; // Get value from l2 node, or 0 if l1 is NULL l1 = l1 ? l1.next : l1; // Move l1 pointer to next node l2 = l2 ? l2.next : l2; // Move l2 pointer to next node let curVal = (sum + prevTenth) % 10; // Store curVal prevTenth = Math.floor((sum + prevTenth) / 10); // Get tenth of curVal if (!head) { tail = head = new ListNode(curVal); // since head and tail were empty, we need to set to new ListNode } else { tail.next = new ListNode(curVal); tail = tail.next; } } if (prevTenth > 0) { // if after itetaion, we have prevTenth, which is not added to our list yet, ex: 9+9 => 8 -> 1 (1 is this prevTenth) tail.next = new ListNode(prevTenth); } return head; };
true
8b0b94da2328a9e61099d6da0eb6465d16bd5035
JavaScript
heyork/D-Dsim
/Player Creator/js/scripts.js
UTF-8
41,170
2.609375
3
[]
no_license
var PlayerName; var PlayerRace; var PlayerClass; var PlayerGender; var PlayerLevel; var PlayerStrength; var PlayerConstitution; var PlayerDexterity; var PlayerIntelligence; var PlayerWisdom; var PlayerCharisma; var PlayerAlignment; var PlayerBackground; var PlayerGold; var PlayerExperience; var availablePowers; var chosenPowerNumbers=[0,0,0,0]; var AllChosenPowers=[]; function Race(Name, Modifiers){ this.name=Name; this.modifiers=Modifiers; // Modifiers should be an array of ints in this order [str,con,dex,int,wis,char] } function Class(Name, powerArray){ this.name=Name; this.powers=powerArray; } var Races = [new Race("Dragonborn",[2,0,0,0,0,2]), new Race("Dwarf", [0,2,0,0,2,0]), new Race("Eladrin",[0,0,2,2,0,0]), new Race("Elf",[0,0,2,0,2,0]), new Race("Half-Elf",[0,2,0,0,0,2]), new Race("Halfling",[0,0,2,0,0,2]), new Race("Human", [0,0,0,0,0,0]), new Race("Tiefling",[0,0,0,2,0,2])]; var clericPowers= [new Power("Lance of Faith","cleric","At-Will",1), new Power("Priest's Shield","cleric","At-Will",1), new Power("Righteous Brand","cleric","At-Will",1), new Power("Sacred Flame","cleric","At-Will",1), new Power("Cause Fear","cleric","Encounter",1), new Power("Divine Glow","cleric","Encounter",1), new Power("Healing Strike","cleric","Encounter",1), new Power("Wrathful Thunder","cleric","Encounter",1), new Power("Avenging Flame","cleric","Daily",1), new Power("Beacon of Hope","cleric","Daily",1), new Power("Cascade of Light","cleric","Daily",1), new Power("Guardian of Faith","cleric","Daily",1), new Power("Bless","cleric","Utility",2), new Power("Cure Light Wounds","cleric","Utility",2), new Power("Divine Aid","cleric","Utility",2), new Power("Sanctuary","cleric","Utility",2), new Power("Shield of Faith","cleric","Utility",2), new Power("Blazing Beacon","cleric","Encounter",3), new Power("Command","cleric","Encounter",3), new Power("Daunting Light","cleric","Encounter",3), new Power("Split the Sky","cleric","Encounter",3), new Power("Consecrated Ground","cleric","Daily",5), new Power("Rune of Peace","cleric","Daily",5), new Power("Spiritual Weapon","cleric","Daily",5), new Power("Weapon of the Gods","cleric","Daily",5), new Power("Bastion of Health","cleric","Utility",6), new Power("Cure Sacrifice Wounds","cleric","Utility",6), new Power("Divine Vigor","cleric","Utility",6), new Power("Holy Lantern","cleric","Utility",6), new Power("Awe Strike","cleric","Encounter",7), new Power("Break the Spirit","cleric","Encounter",7), new Power("Searing Light","cleric","Encounter",7), new Power("Strengthen the Faithful","cleric","Encounter",7), new Power("Astral Defenders","cleric","Daily",9), new Power("Blade Barrier","cleric","Daily",9), new Power("Divine Power","cleric","Daily",9), new Power("Flame Strike","cleric","Daily",9), new Power("Astral Refuge","cleric","Utility",10), new Power("Knights of Unyielding Valor","cleric","Utility",10), new Power("Mass Cure Light Wounds","cleric","Utility",10), new Power("Shielding Word","cleric","Utility",10), new Power("Arc of the Righteous","cleric","Encounter",13), new Power("Inspiring Strike","cleric","Encounter",13), new Power("Mantle of Glory","cleric","Encounter",13), new Power("Plague of Doom","cleric","Encounter",13), new Power("Holy Spark","cleric","Daily",15), new Power("Purifying Fire","cleric","Daily",15), new Power("Seal of Warding","cleric","Daily",15), new Power("Astral Shield","cleric","Utility",16), new Power("Cloak of Peace","cleric","Utility",16), new Power("Divine Armor","cleric","Utility",16), new Power("Hallowed Ground","cleric","Utility",16), new Power("Binding Light","cleric","Encounter",17), new Power("Enthrall","cleric","Encounter",17), new Power("Sentinal Strike","cleric","Encounter",17), new Power("Thunderous Word","cleric","Encounter",17), new Power("Fire Storm", "cleric","Daily",19), new Power("Holy Wrath","cleric","Daily",19), new Power("Indomitable Spirit","cleric","Daily",19), new Power("Knight of Glory","cleric","Daily",19), new Power("Angel of Eleven Winds","cleric","Utility",22), new Power("Clarion Call of the Astral Sea","cleric","Utility",22), new Power("Cloud Chariot","cleric","Utility",22), new Power("Purify","cleric","Utility",22), new Power("Spirit of Health","cleric","Utility",22), new Power("Astral Blades of Death","cleric","Encounter",23), new Power("Divine Censure","cleric","Encounter",23), new Power("Haunting Strike","cleric","Encounter",23), new Power("Healing Touch","cleric","Encounter",23), new Power("Nimbus of Doom","cleric","Daily",25), new Power("Sacred Word","cleric","Daily",25), new Power("Seal of Binding","cleric","Daily",25), new Power("Seal of Protection","cleric","Daily",25), new Power("Punishing Strike","cleric","Encounter",27), new Power("Scourge of the Unworthy","cleric","Encounter",27), new Power("Sunblast","cleric","Encounter",27), new Power("Astral Storm","cleric","Daily",29), new Power("Godstrike","cleric","Daily",29)]; var fighterPowers = [new Power("Cleave","fighter","At-Will",1), new Power("Reaping Strike","fighter","At-Will",1), new Power("Sure Strike","fighter","At-Will",1), new Power("Tide of Iron","fighter","At-Will",1), new Power("Covering Attack","fighter","Encounter",1), new Power("Passing Attack","fighter","Encounter",1), new Power("Spinning Sweep","fighter","Encounter",1), new Power("Steel Serpent Strike","fighter","Encounter",1), new Power("Brute Strike","fighter","Daily",1), new Power("Comeback Strike","fighter","Daily",1), new Power("Villian's Menace","fighter","Daily",1), new Power("Boundless Endurance","fighter","Utility",2), new Power("Get Over Here","fighter","Utility",2), new Power("No Opening","fighter","Utility",2), new Power("Unstoppable","fighter","Utility",2), new Power("Armor-Piercing Thrust","fighter","Encounter",3), new Power("Crushing Blow","fighter","Encounter",3), new Power("Dance of Steel","fighter","Encounter",3), new Power("Precise Strike","fighter","Encounter",3), new Power("Rain of Blows","fighter","Encounter",3), new Power("Sweeping Blow","fighter","Encounter",3), new Power("Crack the Shell","fighter","Daily",5), new Power("Dizzying Blow","fighter","Daily",5), new Power("Rain of Steel","fighter","Daily",5), new Power("Battle Awareness","fighter","Utility",6), new Power("Defensive Training","fighter","Utility",6), new Power("Unbreakable","fighter","Utility",6), new Power("Come and Get It","fighter","Encounter",7), new Power("Griffon's Wrath","fighter","Encounter",7), new Power("Iron Bulwark","fighter","Encounter",7), new Power("Reckless Strike","fighter","Encounter",7), new Power("Sudden Surge","fighter","Encounter",7), new Power("Shift the Battlefield","fighter","Daily",9), new Power("Thicket of Blades","fighter","Daily",9), new Power("Victorious Surge","fighter","Utility",9), new Power("Into the Fray","fighter","Utility",10), new Power("Last Ditch Evasion","fighter","Utility",10), new Power("Stalwart Guard","fighter","Utility",10), new Power("Anvil of Doom","fighter","Encounter",13), new Power("Chains of Sorrow","fighter","Encounter",13), new Power("Giant's Wake","fighter","Encounter",13), new Power("Silverstep","fighter","Encounter",13), new Power("Storm of Blows","fighter","Encounter",13), new Power("Talon of the Roc","fighter","Encounter",13), new Power("Dragon's Fangs","fighter","Daily",15), new Power("Serpent Dance Strike","fighter","Daily",15), new Power("Unyielding Avalanche","fighter","Daily",15), new Power("Iterposing Shield","figher","Utility",16), new Power("Iron Weather","fighter","Utility",16), new Power("Suprise Step","fighter","Utility",16), new Power("Exacting Strike","fighter","Ecnounter",17), new Power("Exorcism of Steel","fighter","Encounter",17), new Power("Harrying Assault","fighter","Encounter",17), new Power("Mountain Breaking Blow","fighter","Encounter",17), new Power("Vorpal Tornado","fighter","Encounter",17), new Power("Warrior's Challenge","fighter","Encounter",17), new Power("Devastation's Wake","fighter","Daily",19), new Power("Reaving Strike","fighter","Daily",19), new Power("Strike of the Watchful Guard","fighter","Daily",19), new Power("Act of Desperation","fighter","Utility",22), new Power("No Surrender","fighter","Utility",22), new Power("Cage of Chains","fighter","Encounter",23), new Power("Fangs of Steel","fighter","Encounter",23), new Power("Hack 'n' Slash","fighter","Encounter",23), new Power("Paralyzing Strike","fighter","Encounter",23), new Power("Skullcrusher","fighter","Encounter",23), new Power("Warrior's Urging","fighter","Encounter",23), new Power("Reaper's Stance","fighter","Daily",25), new Power("Reign of Terror","fighter","Daily",25), new Power("Supremecy of Steel","fighter","Daily",25), new Power("Adamantine Strike","fighter","Encounter",27), new Power("Cruel Reaper","fighter","Encounter",27), new Power("Diamond Shield Defense","fighter","Encounter",27), new Power("Indomitable Battle Strike","fighter","Encounter",27), new Power("Force the Battle","fighter","Daily",29), new Power("No Mercy","fighter","Daily",29), new Power("Storm of Destruction","fighter","Daily",29)]; var paladinPowers = [new Power("Bolstering Strike","paladin","At-Will",1), new Power("Enfeebling Strike","paladin","At-Will",1), new Power("Holy Strike","paladin","At-Will",1), new Power("Valiant Strike","paladin","At-Will",1), new Power("Fearsome Smite","paladin","Encounter",1), new Power("Piercing Smite","paladin","Encounter",1), new Power("Radiant Smite","paladin","Encounter",1), new Power("On Pain of Death","paladin","Daily",1), new Power("Paladin's Judgemnt","paladin","Daily",1), new Power("Radiant Delirium","paladin","Daily",1), new Power("Astral Speech","paladin","Utility",2), new Power("Martyr's Blessing","paladin","Utility",2), new Power("Sacred Circle","paladin","Utility",2), new Power("Arcing Smite","paladin","Encounter",3), new Power("Invigorating Smite","paladin","Encounter",3), new Power("Rigteous Smite","paladin","Encounter",3), new Power("Staggering Smite","paladin","Encounter",3), new Power("Hallowed Circle","paladin","Daily",5), new Power("Martyr's Retribution","paladin","Daily",5), new Power("Sign of Vulnerability","paladin","Daily",5), new Power("Divine Bodyguard","paladin","Utility",6), new Power("One Heart, One Mind","paladin","Utility",6), new Power("Wrath of the Gods","paladin","Utility",6), new Power("Beckon Foe","paladin","Encounter",7), new Power("Benign Transportation","paladin","Encounter",7), new Power("Divine Reverence","paladin","Encounter",7), new Power("Thunder Smite","paladin","Encounter",7), new Power("Crown of Glory","paladin","Daily",9), new Power("One Stands Alone","paladin","Daily",9), new Power("Radiant Pulse","paladin","Daily",9), new Power("Cleansing Spirit","paladin","Utility",10), new Power("Noble Shield","paladin","Utility",10), new Power("Turn the Tide","paladin","Utility",10), new Power("Entangling Smite","paladin","Encounter",13), new Power("Radiant Charge","paladin","Encounter",13), new Power("Renewing Smite","paladin","Encounter",13), new Power("Whirlwind Smite","paladin","Encounter",13), new Power("Bloodied Retribution","paladin","Daily",15), new Power("Break the Wall","paladin","Daily",15), new Power("True Nemesis","paladin","Daily",15), new Power("Angelic Intercession","paladin","Utility",16), new Power("Death Ward","paladin","Utility",16), new Power("Enervating Smite","paladin","Encounter",17), new Power("Fortifying Smite","paladin","Encounter",17), new Power("Hand of the Gods","paladin","Encounter",17), new Power("Terrifying Smite","paladin","Encounter",17), new Power("Corona of Blinding Radiance","paladin","Daily",19), new Power("Crusader's Boon","paladin","Daily",19), new Power("Righteous Inferno","paladin","Daily",19), new Power("Angelic Rescue","paladin","Utility",22), new Power("Cleansing Burst","paladin","Utility",22), new Power("Gift of Life","paladin","Utility",22), new Power("United in Faith","paladin","Utility",22), new Power("Here Waits Thy Doom","paladin","Encounter",23), new Power("Martyr's Smite","paladin","Encounter",23), new Power("Resounding Smite","paladin","Encounter",23), new Power("Sublime Transposition","paladin","Encounter",23), new Power("Exalted Retribution","paladin","Daily",25), new Power("To the Nine Hells with You","paladin","Daily",25), new Power("Blinding Smite","paladin","Encounter",27), new Power("Brand of Judgement","paladin","Encounter",27), new Power("Deific Vengeance","paladin","Encounter",27), new Power("Restricitng Smite","paladin","Encounter",27), new Power("Stunning Smite","paladin","Encounter",27), new Power("Even Hand of Justice","paladin","Daily",29), new Power("Powerful Faith","paladin","Daily",29)]; var rangerPowers = [new Power("Careful Attack","ranger","At-Will",1), new Power("Hit and Run","ranger","At-Will",1), new Power("Nimble Strike","ranger","At-Will",1), new Power("Twin Strike","ranger","At-Will",1), new Power("Dire Wolverine Strike","ranger","Encounter",1), new Power("Evasive Strike","ranger","Encounter",1), new Power("Fox's Cunning","ranger","Encounter",1), new Power("Two-Fanged Strike","ranger","Encounter",1), new Power("Hunter's Bear Trap","ranger","Daily",1), new Power("Jaws of the Wolf","ranger","Daily",1), new Power("Split the Tree","ranger","Daily",1), new Power("Sudden Strike","ranger","Daily",1), new Power("Crucial Advice","ranger","Utility",2), new Power("Unbalancing Parry","ranger","Utility",2), new Power("Yield Ground","ranger","Utility",2), new Power("Cut and Run","ranger","Encounter",3), new Power("Disruptive Strike","ranger","Encounter",3), new Power("Shadow Wasp Strike","ranger","Encounter",3), new Power("Thundertusk Boar Strike","ranger","Encounter",3), new Power("Excrutiating Shot","ranger","Daily",5), new Power("Frenzied Skirmish","ranger","Daily",5), new Power("Splintering Shot","ranger","Daily",5), new Power("Two-Wolf Pounce","ranger","Daily",5), new Power("Evade Ambush","ranger","Utility",6), new Power("Skilled Companion","ranger","Utility",6), new Power("Weave through the Fray","ranger","Utility",6), new Power("Claws of the Griffon","ranger","Encounter",7), new Power("Hawk's Talon","ranger","Encounter",7), new Power("Spikes of the Manticore","ranger","Encounter",7), new Power("Sweeping Whirlwind","ranger","Encounter",7), new Power("Attacks on the Run","ranger","Daily",9), new Power("Close Quarters Shot","ranger","Daily",9), new Power("Spray of Arrows","ranger","Daily",9), new Power("Swirling Leaves of Steel","ranger","Daily",9), new Power("Expeditious Stride","ranger","Utility",10), new Power("Open the Range","ranger","Utility",10), new Power("Undaunted Stride","ranger","Utility",10), new Power("Armor Splinter","ranger","Encounter",13), new Power("Knockdown Shot","ranger","Encounter",13), new Power("Pinning Strike","ranger","Encounter",13), new Power("Blade Cascade","ranger","Daily",15), new Power("Bleeding Wounds","ranger","Daily",15), new Power("Confounding Arrows","ranger","Daily",15), new Power("Stunning Steel","ranger","Daily",15), new Power("Evade the Bow","ranger","Utility",16), new Power("Longstrider","ranger","Utility",16), new Power("Momentary Respite","ranger","Utility",16), new Power("Arrow of Vengenace","ranger","Encounter",17), new Power("Cheetah's Rake","ranger","Encounter",17), new Power("Triple Shot","ranger","Encounter",17), new Power("Two-Weapon Eviscerate","ranger","Encounter",17), new Power("Cruel Cage of Steel","ranger","Daily",19), new Power("Great Ram Arrow","ranger","Daily",19), new Power("Two-in-One Shot","ranger","Daily",19), new Power("Wounding Whirlwind","ranger","Daily",19), new Power("Forest Ghost","ranger","Utility",22), new Power("Hit the Dirt","ranger","Utility",22), new Power("Master of the Hunt","ranger","Utility",22), new Power("Safe Stride","ranger","Utility",22), new Power("Blade Ward","ranger","Encounter",23), new Power("Cloak of Thorns","ranger","Encounter",23), new Power("Hammer Shot","ranger","Encounter",23), new Power("Manticore's Volley","ranger","Encounter",23), new Power("Bloodstorm","ranger","Daily",25), new Power("Tiger's Reflex","ranger","Daily",25), new Power("Death Rend","ranger","Encounter",27), new Power("Hall of Arrows","ranger","Encounter",27), new Power("Lightning Shot","ranger","Encounter",27), new Power("Wandering Tornado","ranger","Enncounter",27), new Power("Follow-Up Blow","ranger","Daily",29), new Power("Three-In-One Shot","ranger","Daily",29), new Power("Weave a Web of Steel","ranger","Daily",29)]; var roguePowers = [new Power("Deft Strike","rogue","At-Will",1), new Power("Piercing Strike","rogue","At-Will",1), new Power("Diposta Strike","rogue","At-Will",1), new Power("Sly Flourish","rogue","At-Will",1), new Power("Dazing Strike","rogue","Encounter",1), new Power("King's Castle","rogue","Encounter",1), new Power("Positioning Strike","rogue","Encounter",1), new Power("Torturous Strike","rogue","Encounter",1), new Power("Blinding Barrage","rogue","Daily",1), new Power("Easy Target","rogue","Daily",1), new Power("Trick Strike","rogue","Daily",1), new Power("Fleeting Ghost","rogue","Utility",2), new Power("Great Leap","rogue","Utility",2), new Power("Master of Deceit","rogue","Utility",2), new Power("Tumble","rogue","Utility",2), new Power("Bait and Switch","rogue","Encounter",3), new Power("Setup Strike","rogue","Encounter",3), new Power("Topple Over","rogue","Encounter",3), new Power("Trickster's Blade","rogue","Encounter",3), new Power("Clever Riposte","rogue","Daily",5), new Power("Deep Cut","rogue","Daily",5), new Power("Walking Wounded","rogue","Daily",5), new Power("Chameleon","rogue","Utility",6), new Power("Ignoble Escape","rogue","Utility",6), new Power("Mob Mentality","rogue","Utility",6), new Power("Nimble Climb","rogue","Utility",6), new Power("Slippery Mind","rogue","Utility",6), new Power("Cloud of Steel","rogue","Encounter",7), new Power("Imperiling Strike","rogue","Encounter",7), new Power("Rogue's Luck","rogue","Encounter",7), new Power("Send in the Eyes","rogue","Encounter",7), new Power("Crimson Edge","rogue","Daily",9), new Power("Deadly Positioning","rogue","Daily",9), new Power("Knockout","rogue","Daily",9), new Power("Certain Freedom","rogue","Utility",10), new Power("Close Quarters","rogue","Utility",10), new Power("Dangerous Theft","rogue","Utility",10), new Power("Shadow Stride","rogue","Utility",10), new Power("Fool's Opportunity","rogue","Encounter",13), new Power("Stunning Strike","rogue","Encounter",13), new Power("Tornado Strike","rogue","Encounter",13), new Power("Unbalancing Attack","rogue","Encounter",13), new Power("Bloody Path","rogue","Daily",15), new Power("Garrote Grip","rogue","Daily",15), new Power("Slaying Stirke","rogue","Daily",15), new Power("Foil the Lock","rogue","Utility",16), new Power("Hide in Plain Sight","rogue","Utility",16), new Power("Leaping Dodge","rogue","Utility",16), new Power("Raise the Stakes","rogue","Utility",16), new Power("Dragon Tail Strike","rogue","Encounter",17), new Power("Hounding Strike","rogue","Encounter",17), new Power("Stab and Grab","rogue","Encounter",17), new Power("Feiting Flurry","rogue","Daily",19), new Power("Flying Foe","rogue","Daily",19), new Power("Snake's Retreat","rogue","Daily",19), new Power("Cloud Jump","rogue","Utility",22), new Power("Dazzling Acrobatics","rogue","Utility",22), new Power("Hide from the Light","rogue","Utility",22), new Power("Knave's Gambit","rogue","Encounter",23), new Power("Scorpion Strike","rogue","Encounter",23), new Power("Steel Entrapment","rogue","Encounter",23), new Power("Biting Assault","rogue","Daily",25), new Power("Ghost on the Wind","rogue","Daily",25), new Power("Hamstring","rogue","Daily",25), new Power("Dance of Death","rogue","Encounter",27), new Power("Hurricane of Blood","rogue","Encounter",27), new Power("Perfect Strike","rogue","Encounter",27), new Power("Assassin's Point","rogue","Daily",29), new Power("Immobilizing Strike","rogue","Daily",29), new Power("Moving Target","rogue","Daily",29)]; var warlockPowers = [new Power("Dire Radiance","warlock","At-Will",1), new Power("Eldritch Blast","warlock","At-Will",1), new Power("Eyebite","warlock","At-Will",1), new Power("Hellish Rebuke","warlock","At-Will",1), new Power("Diabolic Grasp","warlock","Encounter",1), new Power("Dreadul Word","warlock","Encounter",1), new Power("Vampiric Embrace","warlock","Encounter",1), new Power("Witchfire","warlock","Encounter",1), new Power("Armor of Agathys","warlock","Daily",1), new Power("Curse of the Drak Dream","warlock","Daily",1), new Power("Dread Star","warlock","Daily",1), new Power("Flames of Phlegethos","warlock","Daily",1), new Power("Beguiling Tongue","warlock","Utility",2), new Power("Ethereal Stride","warlock","Utility",2), new Power("Fiendish Resilience","warlock","Utility",2), new Power("Shadow Veil","warlock","Utility",2), new Power("Eldritch Rain","warlock","Encounter",3), new Power("Fiery Bolt","warlock","Encounter",3), new Power("Frigid Darkness","warlock","Encounter",3), new Power("Otherwind Stride","warlock","Encounter",3), new Power("Avernian Eruption","warlock","Daily",5), new Power("Crown of Madness","warlock","Daily",5), new Power("Curse of the Bloody Fangs","warlock","Daily",5), new Power("Hunger of Hadar","warlock","Daily",5), new Power("Dark One's Luck","warlock","Utility",6), new Power("Fey Switch","warlock","Utility",6), new Power("Shroud of Black Steel","warlock","Utility",6), new Power("Spider Blimb","warlock","Utility",6), new Power("Howl of Doom","warlock","Encounter",7), new Power("Infernal Moon Curse","warlock","Encounter",7), new Power("Mire the Mind","warlock","Encounter",7), new Power("Sign of Ill Omen","warlock","Encounter",7), new Power("Curse of the Black Frost","warlock","Daily",9), new Power("Iron Spike of Dis","warlock","Daily",9), new Power("Summons of Khired","warlock","Daily",9), new Power("Theif of Five Fates","warlock","Daily",9), new Power("Ambassador Imp","warlock","Utility",10), new Power("Shadow Form","warlock","Utility",10), new Power("Shielding Shades","warlock","Utility",10), new Power("Warlock's Leap","warlock","Utility",10), new Power("Bewitching Whispers","warlock","Encounter",13), new Power("Coldfire Vortex","warlock","Encounter",13), new Power("Harrowstorm","warlock","Encounter",13), new Power("Soul Flaying","warlock","Encounter",13), new Power("Curse of the Golden Mist","warlock","Daily",15), new Power("Fireswarm","warlock","Daily",15), new Power("Tendrils of Thuban","warlock","Daily",15), new Power("Thirsting Maw","warlock","Daily",15), new Power("Cloak of Shadow","warlock","Utility",16), new Power("Eye of the Warlock","warlock","Utility",16), new Power("Infuriating Elusiveness","warlock","Utility",16), new Power("Strand of Date","warlock","Encounter",17), new Power("Thristing Tendrils","warlock","Encounter",17), new Power("Warlock's Bargain","warlock","Encounter",17), new Power("Delusions of Loyalty","warlock","Daily",19), new Power("Minions of Malbolge","warlock","Daily",19), new Power("Wrath of Acamar","warlock","Daily",19), new Power("Entropic Ward","warlock","Utility",22), new Power("Raven's Glamor","warlock","Utility",22), new Power("Wings of the Fiend","warlock","Utility",22), new Power("Dark Transport","warlock","Encounter",23), new Power("Spitefull Darts","warlock","Encounter",23), new Power("Thorns of Venom","warlock","Encounter",23), new Power("Curse of the Twin Princes","warlock","Daily",25), new Power("Tartareen Tomb","warlock","Daily",25), new Power("Thirteen Baleful Stars","warlock","Daily",25), new Power("Banish to the Void","warlock","Encounter",27), new Power("Curse of the Fey King","warlock","Encounter",27), new Power("Hellfire Curse","warlock","Encounter",27), new Power("Curse of the Dark Delirium","warlock","Daily",29), new Power("Doom of Delban","warlock","Daily",29), new Power("Hurl through Hell","warlock","Daily",29)]; var warlordPowers = [new Power("Commander's Strike","warlord","At-Will",1), new Power("Furious Smash","warlord","At-Will",1), new Power("Viper's Smash","warlord","At-Will",1), new Power("Wolf Pack Tactics","warlord","At-Will",1), new Power("Guarding Attack","warlord","Encounter",1), new Power("Hammer and Anvil","warlord","Encounter",1), new Power("Leaf on the Wind","warlord","Encounter",1), new Power("Warlord's Favor","warlord","Encounter",1), new Power("Bastion of Defense","warlord","Daily",1), new Power("Lead the Attack","warlord","Daily",1), new Power("Pin the Foe","warlord","Daily",1), new Power("White Raven Onslaught","warlord","Daily",1), new Power("Aid the Injured","warlord","Utility",2), new Power("Crescendo of Violence","warlord","Utility",2), new Power("Knight's Move","warlord","Utility",2), new Power("Shake it Off","warlord","Utility",2), new Power("Hold the Line","warlord","Encounter",3), new Power("Inspiring War Cry","warlord","Encounter",3), new Power("Steel Monsoon","warlord","Encounter",3), new Power("Warlord's Strike","warlord","Encounter",3), new Power("Stand the Fallen","warlord","Daily",5), new Power("Turning Point","warlord","Daily",5), new Power("Villian's Nightmare","warlord","Daily",5), new Power("Guide the Charge","warlord","Utility",6), new Power("Inspiring Reaction","warlord","Utility",6), new Power("Quick Step","warlord","Utility",6), new Power("Stand Tough","warlord","Utility",6), new Power("Lion's Roar","warlord","Encounter",7), new Power("Sunder Armor","warlord","Encounter",7), new Power("Suprise Attack","warlord","Encounter",7), new Power("Surround Foe","warlord","Encounter",7), new Power("Iron Dungeon Charge","warlord","Daily",9), new Power("Knock Them Down","warlord","Daily",9), new Power("White Raven Strike","warlord","Daily",9), new Power("Defensive Rally","warlord","Utility",10), new Power("Ease Suffering","warlord","Utility",10), new Power("Tactical Shift","warlord","Utility",10), new Power("Beat Them Into the Ground","warlord","Encounter",13), new Power("Bolstering Blow","warlord","Encounter",13), new Power("Denying Strike","warlord","Encounter",13), new Power("Fury of the Sirocco","warlord","Encounter",13), new Power("Make Them Bleed","warlord","Daily",15), new Power("Renew the Troops","warlord","Daily",15), new Power("Warlord's Gambit","warlord","Daily",15), new Power("Hero's Defense","warlord","Utility",16), new Power("Warlord's Banner","warlord","Utility",16), new Power("White Raven Formation","warlord","Utility",16), new Power("Battle On","warlord","Encounter",17), new Power("Hall of Steel","warlord","Encunter",17), new Power("Thunderous Cry","warlord","Encounter",17), new Power("Warlord's Rush","warlord","Encounter",17), new Power("Break the Tempo","warlord","Daily",19), new Power("Victory Suge ","warlord","Daily",19), new Power("Windmill of Doom","warlord","Daily",19), new Power("Heart of the Titan","warlord","Utility",22), new Power("Heroic Surge","warlord","Utility",22), new Power("Own the Battlefield","warlord","Utility",22), new Power("Great Dragon War Cry","warlord","Encounter",23), new Power("Pillar to Post","warlord","Encounter",23), new Power("Rabbits and Wolves","warlord","Encounter",23), new Power("Sudden Assault","warlord","Encounter",23), new Power("Relentles Assault","warlord","Daily",25), new Power("Stir the Hornet's Nest","warlord","Daily",25), new Power("White Raven's Call","warlord","Daily",25), new Power("Chimera Battlestrike","warlord","Encounter",27), new Power("Devastating Charge","warlord","Encounter",27), new Power("Incite Heroism","warlord","Encounter",27), new Power("Warlord's Doom","warlord","Encounter",27), new Power("Defy Death","warlord","Daily",29), new Power("Stand Invincible","warlord","Daily",29)]; // var wizardPowers = []; var Classes= [new Class("Cleric",clericPowers), new Class("Fighter",fighterPowers), new Class("Paladin",paladinPowers), new Class("Ranger",rangerPowers), new Class("Rogue",roguePowers), new Class("Warlock",warlockPowers), new Class("Warlord",warlordPowers), // new Class("Wizard",wizardPowers) ]; function Power(Name, classReq, type,level){ this.name=Name; this.classReq=classReq; this.level=level; this.type=type; } function rollD6(){ return Math.floor((Math.random()*6)+1); } function rollForAbility(){ var rolls = [4]; for(var i=0;i<4;i++){ rolls[i]=rollD6(); } var lowest=6; for(var i=0;i<4;i++){ if(rolls[i]<lowest){ lowest=[i]; } } rolls.splice(lowest,1); var score=0; for(var i=0;i<rolls.length;i++){ score=score+rolls[i]; } return score; } $(".abilityButton").click(function(){ $(this).prev(".input-group").children("input").val(rollForAbility()); // The Following disbales the inputs so you can't reroll // $(this).prev("input").prop("disabled",true); // $(this).prop("disabled",true); }); function listPowers(){ $(".powerdiv").empty(); var classNumber; for(var i=0;i<Classes.length;i++){ if(PlayerClass.toUpperCase()==Classes[i].name.toUpperCase()){ classNumber=i; } } for(var i=0; i<Classes[classNumber].powers.length;i++){ if(Classes[classNumber].powers[i].level<=PlayerLevel){ var descriptor; if(Classes[classNumber].powers[i].type=="Utility"){ descriptor="Utility"; } else{ descriptor="Attack"; } var color; if(descriptor=="Utility"){ color="success"; } else{ color="danger"; } $(".powerdiv").append("<div class='col-md-4'><div class='panel panel-"+color+"'><div class='panel-heading'><input type='checkbox' data-type='"+Classes[classNumber].powers[i].type+"' class='PowerCheckBox' data-i='"+i+"'> "+Classes[classNumber].powers[i].name+" </div><div class='panelbody text-right'>Level "+Classes[classNumber].powers[i].level+" "+Classes[classNumber].powers[i].type+" </div></div></div>"); $("input").change(gatherInfo()); } } } function updateEverything(){ gatherInfo(); updateEXP(); listPowers(); setAvailablePowers(); addAbilModifier(); } $("input").change(function(){ updateEverything(); }); $("select").change(function (){ updateEverything() }); function gatherInfo(){ PlayerName=$("input#Name").val(); PlayerRace=$("#race").val(); PlayerClass=$("select#class").val(); PlayerGender=$("select#gender").val(); PlayerLevel=$("input#level").val(); PlayerStrength=$("input#strength").val(); PlayerConstitution=$("input#constitution").val(); PlayerDexterity=$("input#dexterity").val(); PlayerIntelligence=$("input#intelligence").val(); PlayerWisdom=$("input#wisdom").val(); PlayerCharisma=$("input#charisma").val(); PlayerAlignment=$("select#alignment").val(); // PlayerBackground=$("textarea#backgroundInfo").val(); PlayerGold=$("input#gold").val(); PlayerExperience=$("input#exp").val(); hideUnnecesary(); AllChosenPowers=chosenPowersAtWill.concat(chosenPowersEncounter); AllChosenPowers=AllChosenPowers.concat(chosenPowersDaily); AllChosenPowers=AllChosenPowers.concat(chosenPowersUtility); AllChosenPowers=AllChosenPowers.sort(function(a,b){return a - b}); } $('span').tooltip({placement: 'right'}); function hideUnnecesary(){ if(PlayerLevel==1){ $(".goldDiv").hide(); $(".expDiv").hide(); } else{ $(".goldDiv").show(); $(".expDiv").show(); } } function setEXP(EXP){ $("#exp").val(EXP); } function updateEXP(){ if(PlayerLevel==1){ setEXP(0); } else if(PlayerLevel==2){ setEXP(1000); } else if(PlayerLevel==3){ setEXP(2250); } else if(PlayerLevel==4){ setEXP(3750); } else if(PlayerLevel==5){ setEXP(5500); } else if(PlayerLevel==6){ setEXP(7500); } else if(PlayerLevel==7){ setEXP(10000); } else if(PlayerLevel==8){ setEXP(13000); } else if(PlayerLevel==9){ setEXP(16500); } else if(PlayerLevel==10){ setEXP(20500); } else if(PlayerLevel==11){ setEXP(26000); } else if(PlayerLevel==12){ setEXP(32000); } else if(PlayerLevel==13){ setEXP(39000); } else if(PlayerLevel==14){ setEXP(47000); } else if(PlayerLevel==15){ setEXP(57000); } else if(PlayerLevel==16){ setEXP(69000); } else if(PlayerLevel==17){ setEXP(83000); } else if(PlayerLevel==18){ setEXP(99000); } else if(PlayerLevel==19){ setEXP(119000); } else if(PlayerLevel==20){ setEXP(143000); } else if(PlayerLevel==21){ setEXP(175000); } else if(PlayerLevel==22){ setEXP(210000); } else if(PlayerLevel==23){ setEXP(255000); } else if(PlayerLevel==24){ setEXP(310000); } else if(PlayerLevel==25){ setEXP(375000); } else if(PlayerLevel==26){ setEXP(450000); } else if(PlayerLevel==27){ setEXP(550000); } else if(PlayerLevel==28){ setEXP(675000); } else if(PlayerLevel==29){ setEXP(825000); } else if(PlayerLevel==30){ setEXP(1000000); } } function setAvailablePowers(){ //At-Will,Encounter,Daily,Utility if(PlayerLevel==1){ availablePowers=[2,1,1,0]; } else if(PlayerLevel==2){ availablePowers=[2,1,1,1]; } else if(PlayerLevel==3){ availablePowers=[2,2,1,1]; } else if(PlayerLevel==4){ availablePowers=[2,2,1,1]; } else if(PlayerLevel==5){ availablePowers=[2,2,2,1]; } else if(PlayerLevel==6){ availablePowers=[2,2,2,2]; } else if(PlayerLevel==7){ availablePowers=[2,3,2,2]; } else if(PlayerLevel==8){ availablePowers=[2,3,2,2]; } else if(PlayerLevel==9){ availablePowers=[2,3,3,2]; } else if(PlayerLevel==10){ availablePowers=[2,3,3,3]; } else if(PlayerLevel==11){ availablePowers=[2,4,3,3]; } else if(PlayerLevel==12){ availablePowers=[2,4,3,4]; } else if(PlayerLevel==13){ availablePowers=[2,4,3,4]; } else if(PlayerLevel==14){ availablePowers=[2,4,3,4]; } else if(PlayerLevel==15){ availablePowers=[2,4,3,4]; } else if(PlayerLevel==16){ availablePowers=[2,4,3,5]; } else if(PlayerLevel==17){ availablePowers=[2,4,3,5]; } else if(PlayerLevel==18){ availablePowers=[2,4,3,5]; } else if(PlayerLevel==19){ availablePowers=[2,4,3,5]; } else if(PlayerLevel==20){ availablePowers=[2,4,4,5]; } else if(PlayerLevel==21){ availablePowers=[2,4,4,5]; } else if(PlayerLevel==22){ availablePowers=[2,4,4,6]; } else if(PlayerLevel==23){ availablePowers=[2,4,4,6]; } else if(PlayerLevel==24){ availablePowers=[2,4,4,6]; } else if(PlayerLevel==25){ availablePowers=[2,4,4,6]; } else if(PlayerLevel==26){ availablePowers=[2,4,4,7]; } else if(PlayerLevel==27){ availablePowers=[2,4,4,7]; } else if(PlayerLevel==28){ availablePowers=[2,4,4,7]; } else if(PlayerLevel==29){ availablePowers=[2,4,4,7]; } else if(PlayerLevel==30){ availablePowers=[2,4,4,7]; } } function listRaces(){ for(var i=0;i<Races.length;i++){ $("select#race").append("<option value='"+Races[i].name+"'>"+Races[i].name+"</option>") } } function listClasses(){ for(var i=0;i<Classes.length;i++){ $("select#class").append("<option value='"+Classes[i].name+"'>"+Classes[i].name+"</option>") } } $(document).ready(function (){ listRaces(); listClasses(); gatherInfo(); listPowers(); setAvailablePowers(); addAbilModifier(); }); var chosenPowersAtWill=[]; var chosenPowersEncounter=[]; var chosenPowersDaily=[]; var chosenPowersUtility=[]; function addAbilModifier(){ Race=$("select#race").val(); Race = Race.toUpperCase(); var num; for (var i = 0; i < Races.length; i++) { if(Races[i].name.toUpperCase()==Race){ num=i; } } $(".abilityDiv").each(function(index){ $(this).children(".input-group").children("span").text("+"+Races[num].modifiers[index]); }); } $(".powerdiv").on('change', 'input:checked', function(){ if(this.checked){ if($(this).attr("data-type")==="At-Will"){ if(chosenPowerNumbers[0]<availablePowers[0]){ chosenPowerNumbers[0]++; chosenPowersAtWill[chosenPowersAtWill.length]=$(this).attr("data-i"); //Stores the i value of the chosen power in the highest spot in the array } else{ // console.log("input[data-i="+chosenPowersAtWill[0]+"]"); $("input[data-i="+chosenPowersAtWill[0]+"]").prop('checked', false); chosenPowersAtWill.shift(); chosenPowersAtWill[chosenPowersAtWill.length]=$(this).attr("data-i"); } } else if($(this).attr("data-type")==="Encounter"){ if(chosenPowerNumbers[1]<availablePowers[1]){ chosenPowerNumbers[1]++; chosenPowersEncounter[chosenPowersEncounter.length]=$(this).attr("data-i"); //Stores the i value of the chosen power in the highest spot in the array } else{ // console.log("input[data-i="+chosenPowersEncounter[0]+"]"); $("input[data-i="+chosenPowersEncounter[0]+"]").prop('checked', false); chosenPowersEncounter.shift(); chosenPowersEncounter[chosenPowersEncounter.length]=$(this).attr("data-i"); } } else if($(this).attr("data-type")==="Daily"){ if(chosenPowerNumbers[2]<availablePowers[2]){ chosenPowerNumbers[2]++; chosenPowersDaily[chosenPowersDaily.length]=$(this).attr("data-i"); //Stores the i value of the chosen power in the highest spot in the array } else{ // console.log("input[data-i="+chosenPowersDaily[0]+"]"); $("input[data-i="+chosenPowersDaily[0]+"]").prop('checked', false); chosenPowersDaily.shift(); chosenPowersDaily[chosenPowersDaily.length]=$(this).attr("data-i"); } } else if($(this).attr("data-type")==="Utility"){ if(chosenPowerNumbers[3]<availablePowers[3]){ chosenPowerNumbers[3]++; chosenPowersUtility[chosenPowersUtility.length]=$(this).attr("data-i"); //Stores the i value of the chosen power in the highest spot in the array } else{ // console.log("input[data-i="+chosenPowersUtility[0]+"]"); $("input[data-i="+chosenPowersUtility[0]+"]").prop('checked', false); chosenPowersUtility.shift(); chosenPowersUtility[chosenPowersUtility.length]=$(this).attr("data-i"); } } } }); function saveAlltheThings(){ gatherInfo(); var finalPlayerArray=[]; finalPlayerArray[0]=PlayerName; finalPlayerArray[1]=PlayerRace; finalPlayerArray[2]=PlayerClass; finalPlayerArray[3]=PlayerLevel; finalPlayerArray[4]=PlayerStrength; finalPlayerArray[5]=PlayerConstitution; finalPlayerArray[6]=PlayerDexterity; finalPlayerArray[7]=PlayerIntelligence; finalPlayerArray[8]=PlayerWisdom; finalPlayerArray[9]=PlayerCharisma; finalPlayerArray[10]=PlayerAlignment; finalPlayerArray[11]=PlayerGold; finalPlayerArray[12]=PlayerExperience; //Item 12 is the number of Powers (n) //n items after that are the Powers (as Strings) finalPlayerArray[13]=AllChosenPowers.length; var classNumber; for(var i=0;i<Classes.length;i++){ if(PlayerClass.toUpperCase()==Classes[i].name.toUpperCase()){ classNumber=i; } }; for(var i=0; i<AllChosenPowers.length;i++){ var powerNumber=AllChosenPowers[i] finalPlayerArray[finalPlayerArray.length]=Classes[classNumber].powers[AllChosenPowers[i]].name; }; console.log(finalPlayerArray); var blob = new Blob([finalPlayerArray], {type: 'text/plain'}); $('#DoIt').attr("href", window.URL.createObjectURL(blob)); $('#DoIt').attr("download",PlayerName.replace(/\s/g, '')+".player"); }
true
395629663a2375f67de71301b6b0e6a775861cfc
JavaScript
devendraprasad1984/PHP_APIs
/codes/StateMemo.js
UTF-8
2,538
2.515625
3
[]
no_license
import React, {useState} from 'react'; import {Accordion} from 'semantic-ui-react'; import ReduxTodo from "./ReduxTodo"; import BackNext from "./BackNext"; import ReduxMailExample from "./ReduxMailExample"; import QRApp from "./QR"; export const StateMemo = () => { const [activeIndex, setActiveIndex] = useState(0); let arrIndex = [1, 2, 3, 4, 5]; let handleAccordClick = (index) => { setActiveIndex(index); } let next = (e, {index}) => { console.log('next is called', index) setActiveIndex(index + 1) } let back = (e, {index}) => { console.log('back is called', index) setActiveIndex(index - 1) } //if on child compoent conditions are put in to render, it will not maintain state of child components // and there concept memoization comes to maintain states of child return ( <div> <h1 className="ribbon">ReactJs Child Component State Memoization</h1> <Accordion fluid styled> <Accordion.Title active={activeIndex === arrIndex[0]} onClick={() => handleAccordClick(arrIndex[0])}> {arrIndex[0]} - Redux Test App</Accordion.Title> <Accordion.Content active={activeIndex === arrIndex[0]}> <div> <BackNext index={arrIndex[0]} next={next} back={back}/> <ReduxTodo/> </div> </Accordion.Content> <Accordion.Title active={activeIndex === arrIndex[1]} onClick={() => handleAccordClick(arrIndex[1])}> {arrIndex[1]} - QR App</Accordion.Title> <Accordion.Content active={activeIndex === arrIndex[1]}> <div> <BackNext index={arrIndex[1]} next={next} back={back}/> <QRApp/> </div> </Accordion.Content> <Accordion.Title active={activeIndex === arrIndex[2]} onClick={() => handleAccordClick(arrIndex[2])}> {arrIndex[2]} - Redux Mail</Accordion.Title> <Accordion.Content active={activeIndex === arrIndex[2]}> <div> <BackNext index={arrIndex[2]} next={next} back={back}/> <ReduxMailExample/> </div> </Accordion.Content> </Accordion> </div> ) }
true
32f1d4601aaabf683861526b3b2ea0f26ea05701
JavaScript
CodingCarlos/modelate
/lib/validators/required.js
UTF-8
259
2.546875
3
[ "MIT" ]
permissive
/** * Required validator * * { * required: Boolean * } */ function isValid(data, model) { if (!model.required) { return true; } if(model.required && typeof data !== 'undefined') { return true; } return false; } module.exports = isValid;
true
6b9c556ec7881c63aecdda4768d482d336535733
JavaScript
tblane88/unit-4-game
/assets/javascript/hiddenGame.js
UTF-8
8,659
2.765625
3
[]
no_license
$(document).ready(function() { // global variables var opponentPicked = false; var heroPicked = false; var hero = ""; var defender = ""; var heroScore = 0; var defenderScore = 0; var heroAttack = 0; var defenderAttack = 0; var defenderID = ""; var defenderAmt = 0; var addScore = 0; function reset() { $("#HanHero").removeClass("hidden"); $("#RickHero").removeClass("hidden"); $("#MalcolmHero").removeClass("hidden"); $("#DoctorHero").removeClass("hidden"); $("#HanOpponent").addClass("hidden"); $("#RickOpponent").addClass("hidden"); $("#MalcolmOpponent").addClass("hidden"); $("#DoctorOpponent").addClass("hidden"); $(defenderID).addClass("hidden"); $("#HanScore").text("120"); $("#RickScore").text("100"); $("#MalcolmScore").text("150"); $("#DoctorScore").text("180"); $("#fightText").empty(); defenderAmt = 0; heroPicked = false; opponentPicked = false; } // initial click me for heros $("#HanHero").on("click", function () { if (!heroPicked) { // hide the other heros $("#RickHero").addClass("hidden"); $("#MalcolmHero").addClass("hidden"); $("#DoctorHero").addClass("hidden"); // unhide the opponents $("#RickOpponent").removeClass("hidden"); $("#MalcolmOpponent").removeClass("hidden"); $("#DoctorOpponent").removeClass("hidden"); // set hero name hero = "Han Solo"; heroScore = 120; heroAttack = 8; addScore = heroAttack; heroPicked = true; }; }); $("#RickHero").on("click", function () { if (!heroPicked) { // hide the other heros $("#HanHero").addClass("hidden"); $("#MalcolmHero").addClass("hidden"); $("#DoctorHero").addClass("hidden"); // unhide the opponents $("#HanOpponent").removeClass("hidden"); $("#MalcolmOpponent").removeClass("hidden"); $("#DoctorOpponent").removeClass("hidden"); // set hero name hero = "Rick Sanchez"; heroScore = 100; heroAttack = 10; addScore = heroAttack; heroPicked = true; }; }); $("#MalcolmHero").on("click", function () { if (!heroPicked) { // hide the other heros $("#RickHero").addClass("hidden"); $("#HanHero").addClass("hidden"); $("#DoctorHero").addClass("hidden"); // unhide the opponents $("#RickOpponent").removeClass("hidden"); $("#HanOpponent").removeClass("hidden"); $("#DoctorOpponent").removeClass("hidden"); // set hero name hero = "Captain Mal Reynolds"; heroScore = 150; heroAttack = 6; addScore = heroAttack; heroPicked = true; }; }); $("#DoctorHero").on("click", function () { if (!heroPicked) { // hide the other heros $("#RickHero").addClass("hidden"); $("#MalcolmHero").addClass("hidden"); $("#HanHero").addClass("hidden"); // unhide the opponents $("#RickOpponent").removeClass("hidden"); $("#MalcolmOpponent").removeClass("hidden"); $("#HanOpponent").removeClass("hidden"); // set hero name hero = "The Doctor"; heroScore = 180; heroAttack = 7; addScore = heroAttack; heroPicked = true; }; }); // opponent click handlers $("#HanOpponent").on("click", function () { if (!opponentPicked) { $("#HanDefender").removeClass("hidden"); $("#HanOpponent").addClass("hidden"); // set Defender defender = "Han Solo"; defenderScore = 120; defenderID = "#HanDefender"; defenderAttack = 8; opponentPicked = true; $("#fightText").empty(); defenderAmt++; $(".defenderScore").text(defenderScore); }; }); $("#RickOpponent").on("click", function () { if (!opponentPicked) { $("#RickDefender").removeClass("hidden"); $("#RickOpponent").addClass("hidden"); // set Defender defender = "Rick Sanchez"; defenderScore = 100; defenderID = "#RickDefender"; defenderAttack = 5; opponentPicked = true; $("#fightText").empty(); defenderAmt++; $(".defenderScore").text(defenderScore); }; }); $("#MalcolmOpponent").on("click", function () { if (!opponentPicked) { $("#MalcolmDefender").removeClass("hidden"); $("#MalcolmOpponent").addClass("hidden"); // set Defender defender = "Captain Mal Reynolds"; defenderScore = 150; defenderID = "#MalcolmDefender"; defenderAttack = 12; opponentPicked = true; $("#fightText").empty(); defenderAmt++; $(".defenderScore").text(defenderScore); }; }); $("#DoctorOpponent").on("click", function () { if (!opponentPicked) { $("#DoctorDefender").removeClass("hidden"); $("#DoctorOpponent").addClass("hidden"); // set Defender defender = "The Doctor"; defenderScore = 180; defenderID = "#DoctorDefender"; defenderAttack = 15; opponentPicked = true; $("#fightText").empty(); defenderAmt++; $(".defenderScore").text(defenderScore); }; }); // Attack Button click function $("#attack").on("click", function() { // check to see a hero has been picked if (heroPicked) { // check to see if an opponent has been picked if(opponentPicked) { if ((heroScore > 0) && (defenderScore > 0)) { $("#fightText").html("<h4>You attacked " + defender + " for " + heroAttack + " damage.</h4> <h4>" + defender + " attacked you back for " + defenderAttack + " damage.</h4>"); defenderScore = defenderScore - heroAttack; heroScore = heroScore - defenderAttack; $(".heroScore").text(heroScore); $(".defenderScore").text(defenderScore); heroAttack = heroAttack + addScore; if (heroScore <= 0){ $("#fightText").html("<h4>GAME OVER! Sorry You lose!</h4> <button id='reset'>Reset Game</button>"); } else if (defenderScore <= 0) { if (defenderAmt < 3) { $(defenderID).addClass("hidden"); $("#fightText").html("<h4>You have defeated " + defender + "! Choose another opponent</h4>"); opponentPicked = false; } else { $("#fightText").html("<h4>You have Defeated everyone!!</h4> <button id='reset'>Reset Game</button>"); } } } else if (heroScore <= 0){ $("#fightText").html("<h4>GAME OVER! Sorry You lose!</h4> <button id='reset'>Reset Game</button>"); } else if (defenderScore <= 0) { if (defenderAmt < 3) { $(defenderID).addClass("hidden"); $("#fightText").html("<h4>You have defeated " + defender + "! Choose another opponent</h4>"); opponentPicked = false; } else { $("#fightText").html("<h4>You have Defeated everyone!!</h4> <button id='reset'>Reset Game</button>"); } } } else { $("#fightText").html("<h4>You need to choose an opponent!</h4>"); } } else { $("#fightText").html("<h4>You need to choose a Hero!</h4>"); } // Reset Function $("#reset").on("click", function(){ reset(); }); }); });
true
d1a265762f35cfc41c013d498af61c4382ba6681
JavaScript
devinupreti/web-dev-exercises
/learnyounode/fileExt.js
UTF-8
1,068
3.265625
3
[]
no_license
/* Program Number : 5 Problem Description : Get files in path with extension Date : May 28, 2019 Author : Devin Upreti */ const fs = require("fs"); const path = require("path"); const filePath = process.argv[2]; const extension = "." + process.argv[3]; function withoutModular() { fs.readdir(filePath, (err, files) => { if (err) { return console.error(err); } for (var i = 0; i < files.length; i++){ if (path.extname(files[i]) == extension) { console.log(files[i]); } } }); } // withoutModular(); // Making it modular function readFiles(dirPath, ext, callback) { fileExtension = "." + ext; fs.readdir(dirPath, (err, files) => { if (err) { return callback(err); } var myList = []; for (var i = 0; i < files.length; i++){ if (path.extname(files[i]) == fileExtension) { //console.log(files[i]); myList.push(files[i]); } } callback(null, myList); // implementation for user according to usage }); } module.exports = readFiles;
true
54c5bfd2927fbce54eeb0cdc2b36f38d17e2680b
JavaScript
simonswain/ratsofthemaze
/server/app/js/actors/king.js
UTF-8
9,969
2.71875
3
[]
no_license
/* global Actors, Actor, Vec3, VecR */ Actors.King = function (env, refs, attrs) { this.env = env; this.refs = refs; this.opts = this.genOpts(); this.attrs = this.genAttrs(attrs); this.init(attrs); }; Actors.King.prototype = Object.create(Actor.prototype); Actors.King.prototype.title = 'King'; Actors.King.prototype.init = function (attrs) { this.pos = new Vec3( this.refs.cell.opts.max_x / 2, this.refs.cell.opts.max_y / 2 ); this.velo = new VecR( Math.PI * 2 * Math.random(), this.attrs.speed ).vec3(); }; Actors.King.prototype.genAttrs = function (attrs) { var hp = 200 + (100 * Math.random()); var speed = this.opts.speed_base + (Math.random() * this.opts.speed_flux); return { phase: Math.random() * 2 * Math.PI, phase_v: Math.random() * 0.5, speed: speed, dead: false, hp: hp, hp_max: hp }; }; Actors.King.prototype.defaults = [{ key: 'speed_base', info: '', value: 4, min: 1, max: 100 }, { key: 'speed_flux', info: '', value: 2, min: 0, max: 50 }, { key: 'velo_scale', info: '', value: 1, min: 0.1, max: 1, step: 0.1 }, { key: 'separation_range', info: '', value: 160, min: 10, max: 500 }, { key: 'reflect_force', info: '', value: 1, min: 0, max: 10 }, { key: 'chase_force', info: '', value: 1, min: 0.1, max: 1.0 }, { key: 'intent_scale', value: 2, min: 0, max: 100 }]; Actors.King.prototype.update = function (delta, intent) { this.attrs.phase += this.attrs.phase_v; if (this.attrs.phase > 2 * Math.PI) { this.attrs.phase - 2 * Math.PI; } var vec = new Vec3(); vec.add(this.chase().scale(1)); vec.add(this.separation().scale(1)); vec.add(this.reflect()); var intents = [[0, -1], [1, 0], [0, 1], [-1, 0]]; var scale = this.opts.intent_scale; if (typeof intent !== 'undefined' && intent !== null) { vec.add(new Vec3(intents[intent][0], intents[intent][1]).scale(scale)); if (intent === 1 || intent === 3) { if (this.pos.y < this.refs.cell.opts.max_y * 0.4) { vec.add(new Vec3(0, 1).scale(scale)); } if (this.pos.y > this.refs.cell.opts.max_y * 0.6) { vec.add(new Vec3(0, -1).scale(scale)); } } if (intent === 0 || intent === 2) { if (this.pos.x < this.refs.cell.opts.max_x * 0.4) { vec.add(new Vec3(1, 0).scale(scale)); } if (this.pos.x > this.refs.cell.opts.max_x * 0.6) { vec.add(new Vec3(-1, 0).scale(scale)); } } } this.velo.add(vec); this.velo.limit(this.attrs.speed); this.pos.add(this.velo); // exit var other, cell; if (this.pos.x < 0) { other = this.refs.cell.exits[3]; if (other) { this.pos.x += this.refs.cell.opts.max_x; } else { this.velo = new Vec3(-this.velo.x, this.velo.y, 0); this.pos.x = 0; } } else if (this.pos.x > this.refs.cell.opts.max_x) { other = this.refs.cell.exits[1]; if (other) { this.pos.x = this.pos.x - this.refs.cell.opts.max_x; } else { this.velo = new Vec3(-this.velo.x, this.velo.y, 0); this.pos.x = this.refs.cell.opts.max_x; } } else if (this.pos.y < 0) { other = this.refs.cell.exits[0]; if (other) { this.pos.y += this.refs.cell.opts.max_y; } else { this.velo = new Vec3(this.velo.x, -this.velo.y, 0); this.pos.y = 0; } } else if (this.pos.y > this.refs.cell.opts.max_y) { other = this.refs.cell.exits[2]; if (other) { this.pos.y = this.pos.y - this.refs.cell.opts.max_y; } else { this.velo = new Vec3(this.velo.x, -this.velo.y, 0); this.pos.y = this.refs.cell.opts.max_y; } } cell = this.refs.cell; if (other) { for (var i = 0, ii = cell.kings.length; i < ii; i++) { if (cell.kings[i] === this) { cell.kings[i] = null; break; } } this.refs.cell = other; other.kings.push(this); } }; Actors.King.prototype.separation = function () { var i, ii; var other; var range; var vec = new Vec3(); for (i = 0, ii = this.refs.cell.kings.length; i < ii; i++) { other = this.refs.cell.kings[i]; if (!other) { continue; } if (other === this) { continue; } range = this.pos.rangeXY(other.pos); if (range === 0) { continue; } if (range > this.opts.separation_range) { continue; } vec.add(this.pos.minus(other.pos).normalize().scale(1 / range)); } return vec.normalize(); }; Actors.King.prototype.chase = function () { var xx = 0; var yy = 0; var c = 0; if (this.refs.cell.humans.length === 0) { return new Vec3(); } var human; for (var i = 0, ii = this.refs.cell.humans.length; i < ii; i++) { human = this.refs.cell.humans[i]; if (!human) { continue; } xx += human.pos.x; yy += human.pos.y; c++; } var target = new Vec3(xx / c, yy / c); return target.minus(this.pos).normalize(); }; Actors.King.prototype.center = function () { var i, ii; var other; var range; var c; var center = new Vec3(); c = 0; for (i = 0, ii = this.refs.cell.kings.length; i < ii; i++) { other = this.refs.cell.kings[i]; if (!other) { continue; } if (other === this) { continue; } c++; center.add(other.pos); } if (c === 0) { return new Vec3(); } center.div(c); range = this.pos.rangeXY(center); if (range === 0) { return new Vec3(); } if (range < 56) { return new Vec3(); } // return this.pos.minus(center).normalize();; return this.pos.minus(center).normalize().scale(128 / range); }; Actors.King.prototype.separation = function () { var i, ii; var other; var range; var vec = new Vec3(); for (i = 0, ii = this.refs.cell.kings.length; i < ii; i++) { other = this.refs.cell.kings[i]; if (!other) { continue; } if (other === this) { continue; } range = this.pos.rangeXY(other.pos); if (range === 0) { continue; } if (range > 100) { continue; } vec.add(this.pos.minus(other.pos).normalize().scale(1 / range)); } return vec.normalize(); }; Actors.King.prototype.reflect = function () { var reflect = new Vec3(); if (this.pos.y < this.refs.cell.opts.max_y * 0.1) { reflect.y = ((this.refs.cell.opts.max_y * 0.1) - this.pos.y) / (this.refs.cell.opts.max_y * 0.1); } if (this.pos.x > this.refs.cell.opts.max_x * 0.9) { reflect.x = -(this.pos.x - (this.refs.cell.opts.max_x * 0.9)) / (this.refs.cell.opts.max_x * 0.1); } if (this.pos.x < this.refs.cell.opts.max_x * 0.1) { reflect.x = ((this.refs.cell.opts.max_x * 0.1) - this.pos.x) / (this.refs.cell.opts.max_x * 0.1); } if (this.pos.y > this.refs.cell.opts.max_y * 0.9) { reflect.y = -(this.pos.y - (this.refs.cell.opts.max_y * 0.9)) / (this.refs.cell.opts.max_y * 0.1); } return reflect; }; Actors.King.prototype.damage = function (hp) { if (!hp) { hp = 1; } this.attrs.hp -= hp; this.attrs.hit = true; if (this.attrs.hp > 0) { return; } if (this.attrs.dead) { return; } this.kill(); }; Actors.King.prototype.kill = function (terminal) { if (this.attrs.dead) { return; } this.attrs.dead = true; var i, ii; if (this.refs.cell) { for (i = 0, ii = this.refs.cell.kings.length; i < ii; i++) { if (this.refs.cell.kings[i] === this) { this.refs.cell.kings[i] = null; break; } } } this.refs.cell.booms.push(new Actors.Boom( this.env, { }, { style: '', radius: 16, x: this.pos.x, y: this.pos.y, color: '255,0,0' } )); if (terminal) { return; } }; Actors.King.prototype.paint = function (view) { view.ctx.save(); view.ctx.rotate(this.velo.angleXY()); var ccc = '#c00'; if (this.attrs.hit) { this.attrs.hit = false; ccc = '#ff0'; } view.ctx.fillStyle = '#c00'; view.ctx.strokeStyle = '#c00'; view.ctx.lineWidth = 1; var z = 16; // for tails var q1 = (Math.sin(this.attrs.phase / 2) % (2 * Math.PI)); var q2 = (Math.sin(this.attrs.phase / 3) % (2 * Math.PI)); // tail view.ctx.fillStyle = ccc; view.ctx.strokeStyle = ccc; view.ctx.save(); view.ctx.translate(-1.5 * z, 0); view.ctx.beginPath(); view.ctx.moveTo(0, 0.5 * z); view.ctx.quadraticCurveTo(-5 * z, z * q1, -5 * z, 0); view.ctx.quadraticCurveTo(-5 * z, z * q1, 0, -0.5 * z); view.ctx.closePath(); view.ctx.stroke(); view.ctx.fill(); view.ctx.restore(); // body view.ctx.fillStyle = ccc; view.ctx.lineWidth = 1; view.ctx.beginPath(); view.ctx.ellipse(0, 0, z * 2.5, z * 1.2, 0, 2 * Math.PI, 0); view.ctx.closePath(); view.ctx.fill(); // head view.ctx.save(); view.ctx.translate(2.2 * z, 0); view.ctx.rotate(q2 * 0.3); // whiskers view.ctx.strokeStyle = ccc; view.ctx.lineWidth = 0.5; view.ctx.beginPath(); view.ctx.moveTo(z * 0.8, 0); view.ctx.lineTo(z * 0.7, -z); view.ctx.stroke(); view.ctx.beginPath(); view.ctx.moveTo(z * 0.8, 0); view.ctx.lineTo(z * 0.9, -z); view.ctx.stroke(); view.ctx.beginPath(); view.ctx.moveTo(z * 0.8, 0); view.ctx.lineTo(z * 0.7, z); view.ctx.stroke(); view.ctx.beginPath(); view.ctx.moveTo(z * 0.8, 0); view.ctx.lineTo(z * 0.9, z); view.ctx.stroke(); // skull view.ctx.fillStyle = ccc; view.ctx.beginPath(); view.ctx.ellipse(0, 0, z * 1.2, z * 0.7, 0, 2 * Math.PI, 0); view.ctx.closePath(); view.ctx.fill(); // eyes view.ctx.fillStyle = '#ff0'; // blink if (Math.random() < 0.1) { view.ctx.fillStyle = '#000'; } view.ctx.beginPath(); view.ctx.ellipse(z * 0.8, -z * 0.2, z * 0.1, z * 0.05, 0, 2 * Math.PI, 0); view.ctx.closePath(); view.ctx.fill(); view.ctx.beginPath(); view.ctx.ellipse(z * 0.8, z * 0.2, z * 0.1, z * 0.05, 0, 2 * Math.PI, 0); view.ctx.closePath(); view.ctx.fill(); view.ctx.restore(); // end head view.ctx.restore(); };
true
f0b7014e68a175ad5bf002c833c31bc27d486f9b
JavaScript
zhetian9527/mysys
/js/users.js
UTF-8
2,728
2.75
3
[]
no_license
$(function() { getList(); $("#search").click(function() { var Search_box = $("#Search_box").val(); $.post( "http://127.0.0.1:3000/api/user/Search", { Search_box: Search_box }, function(res) { if (res.code == 0) { var list = res.data[0]; var str = ""; str += "<tr><td>" + list.username + "</td> <td>" + list.nickname + "</td><td>" + list.age + "</td> <td>" + list.sex + "</td><td>" + list.isAdmin + "</td> <td><a class='remove' >删除</a></td> </tr>"; $("#tbody").html(str); } } ); return false; }); }); // 获取用户列表 function getList(page, pageSize) { if (location.search) { page1 = location.search .split("?")[1] .split("&")[0] .split("=")[1]; } else { page1 = 1; } page = page || page1; pageSize = pageSize || 5; $.get( "http://127.0.0.1:3000/api/user/list", { page: page, pageSize: pageSize }, function(res) { if (res.code === 0) { var list = res.data.list; var str = ""; for (var i = 0; i < list.length; i++) { str += "<tr><td>" + list[i].username + "</td> <td>" + list[i].nickname + "</td><td>" + list[i].age + "</td> <td>" + list[i].sex + "</td><td>" + list[i].isAdmin + "</td> <td><a class='remove' >删除<a/></td> </tr>"; } $("#tbody").append(str); var str1 = ""; for (var i = 0; i < res.data.totalPage; i++) { str1 += "<li><a class='page1' href = 'users.html?page=" + (i + 1) + "&pageSize=5' >" + (i + 1) + "</a></li>"; } $(".page li:eq(0)").after(str1); $(".page1").click(function() { var page = location.search .split("?")[1] .split("&")[0] .split("=")[1]; getList(page); }); $(".remove").click(function() { var username = $(this) .parent() .parent() .children() .eq(0) .text(); $.post( "http://127.0.0.1:3000/api/user/list/remove", { username: username }, function(res) { if (res.code == 0) { window.location.reload(); } } ); }); } else { alert(res.msg); } } ); }
true
fca8839ee663465b0fa1ead5b29e86d5dfa30a24
JavaScript
LeonardoRios/react-google-charts
/src/docs/Animations/generate-data.js
UTF-8
1,512
2.9375
3
[ "MIT" ]
permissive
const rand = n => { return Math.random() * 8 * n; }; export const generateData = () => { return [ ["Age", "Weight"], [rand(8), rand(12)], [rand(4), rand(5.5)], [rand(1), rand(14)], [rand(4), rand(5)], [rand(3), rand(3.5)], [rand(6), rand(7)], [rand(8), rand(12)], [rand(4), rand(5.5)], [rand(1), rand(14)], [rand(4), rand(5)], [rand(3), rand(3.5)], [rand(6), rand(7)], [rand(4), rand(5.5)], [rand(1), rand(14)], [rand(4), rand(5)], [rand(3), rand(3.5)], [rand(6), rand(7)] ]; }; google.charts.load("current", { packages: ["corechart", "table", "gauge", "controls"] }); google.charts.setOnLoadCallback(drawStringFilter); function drawStringFilter() { var dashboard = new google.visualization.Dashboard( document.getElementById("stringFilter_dashboard_div") ); var control = new google.visualization.ControlWrapper({ controlType: "StringFilter", containerId: "stringFilter_control_div", options: { filterColumnIndex: 0 } }); var chart = new google.visualization.ChartWrapper({ chartType: "Table", containerId: "stringFilter_chart_div", options: { height: "100%", width: "100%" } }); var data = google.visualization.arrayToDataTable([ ["Name", "Age"], ["Michael", 12], ["Elisa", 20], ["Robert", 7], ["John", 54], ["Jessica", 22], ["Aaron", 3], ["Margareth", 42], ["Miranda", 33] ]); dashboard.bind(control, chart); dashboard.draw(data); }
true
babd9f741d2fec5968f34c994bb37552aa007945
JavaScript
MizuBishi/p2p
/test/unit/middleware/calculateProgress.test.js
UTF-8
3,083
2.625
3
[]
no_license
/* eslint-env mocha */ import { assert } from 'chai'; import calculateProgress from '../../../src/middleware/utils/calculateProgress.js'; describe('middleware/utils/calculateProgress', () => { it('empty', () => { assert.equal(calculateProgress({ name: 'Test Person', categories: [], }), 0); assert.equal(calculateProgress({ name: 'Test Person', categories: [{ title: 'Test 1', criteriaRatings: [{ label: '', }, { label: '', }, { label: '', }], }, { title: 'Test 2', criteriaRatings: [{ label: '', }, { label: '', }, { label: '', }], }, { title: 'Test 3', criteriaRatings: [], }], comment: '', }), 0); }); it('all filled', () => { assert.equal(calculateProgress({ name: 'Test Person', categories: [{ title: 'Test 1', criteriaRatings: [{ label: '', rating: 1, }, { label: '', rating: 1, }, { label: '', rating: 1, }], }, { title: 'Test 2', criteriaRatings: [{ label: '', rating: 1, }, { label: '', rating: 1, }, { label: '', rating: 1, }], }, { title: 'Test 3', criteriaRatings: [{ label: '', rating: 1, }, { label: '', rating: 1, }, { label: '', rating: 1, }], }], comment: 'Kommentar', }), 100); }); it('partially filled (no comment)', () => { assert.equal(calculateProgress({ name: 'Test Person', categories: [{ title: 'Test 1', criteriaRatings: [{ label: '', rating: 1, }, { label: '', rating: 1, }, { label: '', }], }, { title: 'Test 2', criteriaRatings: [{ label: '', rating: 1, }, { label: '', }, { label: '', }], }, { title: 'Test 3', criteriaRatings: [{ label: '', rating: 1, }, { label: '', rating: 1, }, { label: '', rating: 1, }], }], }), 60); }); it('comment only', () => { assert.equal(calculateProgress({ name: 'Test Person', categories: [{ title: 'Test 1', criteriaRatings: [{ label: '', }, { label: '', }, { label: '', }], }, { title: 'Test 2', criteriaRatings: [{ label: '', }, { label: '', }, { label: '', }], }, { title: 'Test 3', criteriaRatings: [{ label: '', }, { label: '', }, { label: '', }], }], comment: 'Kommentar', }), 10); }); });
true
0cea8cf57ba2b54862de1c811547a6f1ef115771
JavaScript
dgan11/gm-app
/scripts/run.js
UTF-8
2,035
2.984375
3
[]
no_license
const main = async () => { const [owner, randomPerson] = await hre.ethers.getSigners(); // Compile our contract // hre (hardhat runtime environment) -- built on the fly when you run `npx hardhat` in terminal const GmContractFactory = await hre.ethers.getContractFactory("GmPortal"); // Deploy our contract to our local Ethereum network -- which will be destroyed at the end const gmContract = await GmContractFactory.deploy({ value: hre.ethers.utils.parseEther("0.01"), }); // Wait for our contract to be mined -- Hardhat creates local miners await gmContract.deployed(); // Log the address our contract was deployed to console.log("Contract address: ", gmContract.address); console.log("Contract deployed by: ", owner.address); // ~~~ Call the functions we created let gmCount; /* * Get Contract balance */ let contractBalance = await hre.ethers.provider.getBalance( gmContract.address ); console.log( "Contract balance:", hre.ethers.utils.formatEther(contractBalance) ); gmCount = await gmContract.getTotalGms(); console.log("Number of Waves: ", gmCount.toNumber()); /** Update Testing sending a few gms with messages */ let gmTxn = await gmContract.sayGm("gmmm"); await gmTxn.wait(); // Find some random addresses gmTxn = await gmContract.connect(randomPerson).sayGm("GM ser!"); await gmTxn.wait(); let allGms = await gmContract.getAllGms(); console.log("all gms: ", allGms); /* * Get Contract balance at end to see what happened! */ contractBalance = await hre.ethers.provider.getBalance(gmContract.address); console.log( "Contract balance:", hre.ethers.utils.formatEther(contractBalance) ); let lastPerson = await gmContract.getLastPerson(); console.log("last person to say gm: ", lastPerson); gmCount = await gmContract.getTotalGms(); } const runMain = async () => { try { await main(); process.exit(0); } catch (error) { console.log("error: ", error); process.exit(1); } }; runMain()
true
3a4b7a00f8542df567165a45a0cf564ee1c0ff1a
JavaScript
Sonnax-Transmission-Company/project_management_react
/src/App.js
UTF-8
3,405
2.546875
3
[]
no_license
import React, { Component } from 'react'; import axios from 'axios' import './App.css'; import ProjectsContainer from './components/ProjectsContainer' import InProgressContainer from './components/InProgressContainer' import CompleteContainer from './components/CompleteContainer' class App extends Component { constructor(props) { super(props); this.state = { email: '', password: '', message: '', token: localStorage.getItem("jwt") }; } componentDidMount() { let config = {headers: {'Authorization': "bearer " + localStorage.getItem("jwt")}}; axios.get('https://sonnax-project-management.herokuapp.com/api/v1/steps/current.json', config) .catch(error => { this.setState({token: null}); localStorage.removeItem("jwt"); }) } handleLogInInput = (e) => { const target = e.target; const name = target.name; const value = target.type === 'checkbox' ? target.checked : target.value; this.setState({[name]: value}) } logIn = (e) => { const auth = { email: this.state.email, password: this.state.password } e.preventDefault(); axios.post( 'https://sonnax-project-management.herokuapp.com/user_token', { auth: auth } ) .then(response => { console.log(response) localStorage.setItem("jwt", response.data.jwt) this.setState({token: response.data.jwt, message: ''}) }) .catch((error) => { if (error.response) { console.log(error.response); this.setState({message: 'There was an issue logging in, please try re-entering your information.'}) } else { this.setState({message: ''}) } }); } logOut = () => { this.setState({token: null}); localStorage.removeItem("jwt"); } renderLogIn = (e) => { if (!this.state.token || !localStorage.getItem("jwt")) { return ( <div> <h3>Log In</h3> <form onSubmit={this.logIn}> <label htmlFor="email">Email: </label> <br /> <input name="email" id="email" type="email" placeholder='Email' value={this.state.email} onChange={this.handleLogInInput} /> <br /><br /> <label htmlFor="password">Password:</label> <br /> <input name="password" id="password" type="password" placeholder='Password' value={this.state.password} onChange={this.handleLogInInput} /> <br /> <input type="submit" value="Submit" className="logButton" /> </form> </div> ) } else { return (<button className="logButton" onClick={this.logOut}>Log Out</button>) } } renderMessage = (e) => { return ( this.state.message && <p>{this.state.message}</p> ); } renderProjects = (e) => { if (localStorage.getItem("jwt")) { return (<ProjectsContainer />) } } renderSteps = (e) => { if (localStorage.getItem("jwt")) { return ( <div> <InProgressContainer /> <hr /> <CompleteContainer /> </div> ) } } render() { return ( <div className="App"> {this.renderProjects()} <aside className="sidebar"> {this.renderSteps()} {this.renderLogIn()} {this.renderMessage()} </aside> </div> ); } } export default App;
true
18e5f071256825c23ef25ef2cdaca38293a4ed46
JavaScript
rafikis23/PlayStoreSinAngular
/js/controlador.js
UTF-8
11,989
2.796875
3
[]
no_license
var aplicaciones = []; // var localStorage = window.localStorage; var indiceAppSeleccionada = null; if(localStorage.getItem('aplicaciones') == '') { localStorage.setItem('aplicaciones', JSON.stringify(aplicaciones)); //de JSON a cadena; } else { aplicaciones = JSON.parse(localStorage.getItem('aplicaciones')); }// de cadena a JSON; for (let i=1; i<=32; i++) { document.getElementById('lista-imagenes').innerHTML += `<option value="img/app-icons/${i}.webp">Imagen ${i}</option>`; } for (let i=1; i<=3; i++) { document.getElementById('lista-screens').innerHTML += `<option value="img/app-screenshots/${i}.webp"> Screens ${i}</option>`; } function generarAplicaciones() { document.getElementById('aplicaciones').innerHTML = ''; aplicaciones.forEach(function(app, i){ let estrellas = ''; for(let i=0; i<app.calificacion; i++){ estrellas += '<i class="fas fa-star"></i>'; } for(let i=0; i<(5-app.calificacion); i++){ estrellas += '<i class="far fa-star"></i>'; } document.getElementById('aplicaciones').innerHTML += `<div class=" col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2"> <div class="card border border-warning" > <img src="${app.urlImagen}" class="card-img-top app-img" onclick="instalarApp(${i})"> <div class="card-body app-body "> <h5 class="card-title">${app.nombreAplicacion}</h5> <p class="card-text">${app.desarrollador}</p> <div> ${estrellas} </div> <h5 class="card-title">$${app.precio}</h5> <button class="btn-outline-warning btn-sm" style="float:left" onclick="editarApp(${i})"><i class="far fa-edit"></i></button> <button class="btn-outline-primary btn-sm" style="float:center" onclick="comentarApp(${i})"><i class="fas fa-comments"></i></button> <button class="btn-outline-danger btn-sm" style="float:right" onclick="eliminar(${i})"><i class="fas fa-trash-alt"></i></button> </div> </div> </div>`; }); } generarAplicaciones(); function validarCampoVacio (id) { let campo = document.getElementById(id); if (campo.value == '') { campo.classList.remove('input-success'); campo.classList.add('input-error'); } else { campo.classList.remove('input-error'); campo.classList.add('input-success'); } } function guardar(){ const app = { categoria: document.getElementById('categoria-app').value, codigo: document.getElementById('codigo-app').value , nombreAplicacion: document.getElementById('nombre-app').value , precio: document.getElementById('precio-app').value , descripcion: document.getElementById('descripcion-app').value , urlImagen: document.getElementById('lista-imagenes').value , apk: document.getElementById('apk-app').value , calificacion: document.getElementById('calificacion-app').value , numeroDescargas: document.getElementById('descargas-app').value , desarrollador: document.getElementById('desarrollador-app').value, urlScreens: document.getElementById('lista-screens').value , comentarios:[{ usuario: '', fecha: '', calificacionComentario: '', comentario: '', }] }; aplicaciones.push(app); localStorage.setItem('aplicaciones', JSON.stringify(aplicaciones)); generarAplicaciones(); console.log(aplicaciones); $('#modalNuevaApp').modal('hide'); } function eliminar(indice) { console.log('Eliminar aplicacion con el indice', indice); aplicaciones.splice(indice, 1); generarAplicaciones(); localStorage.setItem('aplicaciones', JSON.stringify(aplicaciones)); } function editarApp(indice) { console.log('Editar la aplicacion', indice); indiceAppSeleccionada = indice; $('#modalNuevaApp').modal('show'); let app = aplicaciones[indice]; document.getElementById('categoria-app').value = app.categoria; document.getElementById('codigo-app').value = app.codigo; document.getElementById('nombre-app').value = app.nombreAplicacion; document.getElementById('precio-app').value = app.precio; document.getElementById('descripcion-app').value = app.descripcion; document.getElementById('lista-imagenes').value = app.urlImagen; document.getElementById('apk-app').value = app.apk; document.getElementById('calificacion-app').value = app.calificacion; document.getElementById('descargas-app').value = app.numeroDescargas; document.getElementById('desarrollador-app').value = app.desarrollador; document.getElementById('lista-screens').value = app.urlScreens; document.getElementById('btn-guardar').style.display = 'none'; document.getElementById('btn-actualizar').style.display = 'block'; } function comentarApp(indice) { console.log('Comentar la aplicacion', indice); indiceAppSeleccionada = indice; $('#modalComentario').modal('show'); } function actualizar(){ console.log('Se actualizo el app con indice', indiceAppSeleccionada); aplicaciones[indiceAppSeleccionada] = { categoria: document.getElementById('categoria-app').value, codigo: document.getElementById('codigo-app').value , nombreAplicacion: document.getElementById('nombre-app').value , precio: document.getElementById('precio-app').value , descripcion: document.getElementById('descripcion-app').value , urlImagen: document.getElementById('lista-imagenes').value , apk: document.getElementById('apk-app').value , calificacion: document.getElementById('calificacion-app').value , numeroDescargas: document.getElementById('descargas-app').value , desarrollador: document.getElementById('desarrollador-app').value, urlScreens: document.getElementById('lista-screens').value , } generarAplicaciones(); localStorage.setItem('aplicaciones', JSON.stringify(aplicaciones)); $('#modalNuevaApp').modal('hide'); } function nuevaApp() { indiceAppSeleccionada = null; document.getElementById('categoria-app').value = null; document.getElementById('codigo-app').value = null; document.getElementById('nombre-app').value = null; document.getElementById('precio-app').value = null; document.getElementById('descripcion-app').value = null; document.getElementById('lista-imagenes').value = null; document.getElementById('apk-app').value = null; document.getElementById('calificacion-app').value = null; document.getElementById('descargas-app').value = null; document.getElementById('desarrollador-app').value = null; document.getElementById('lista-screens').value = null; document.getElementById('btn-guardar').style.display = 'block'; document.getElementById('btn-actualizar').style.display = 'none'; } function enviarComentario(indice){ indiceAppSeleccionada = indice; /*document.getElementById('usuario-comentario-app').value = aplicaciones[indice].comentarios[usuario]; document.getElementById('fecha-comentario-app').value = aplicaciones[indice].comentarios[fecha]; document.getElementById('calificacion-comentario-app').value = aplicaciones[indice].comentarios[calificacionComentario]; document.getElementById('comentario-app').value = aplicaciones[indice].comentarios[comentario]; */ //comentario = app.comentarios; //aplicaciones[indice].push(app); //localStorage.setItem('aplicaciones', JSON.stringify(aplicaciones)); //generarAplicaciones(); //console.log('Los comentarios listados son:', comentarios); $('#modalComentario').modal('hide'); } function instalarApp(indice){ indiceAppSeleccionada = indice; document.getElementById('aplicaciones').innerHTML = ''; $('#modalInstalarApp').modal('show'); aplicaciones.forEach(function(app, i){ let estrellas = ''; for(let i=0; i<app.calificacion; i++){ estrellas += '<i class="fas fa-star"></i>'; } for(let i=0; i<(5-app.calificacion); i++){ estrellas += '<i class="far fa-star"></i>'; } document.getElementById('aplicaciones').innerHTML += //<!-- Modal Instalar App --> `<div class="modal fade" id="modalInstalarApp" tabindex="-1" aria-labelledby="modalInstalarAppLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="img/app-screenshots/1.webp" class="d-block w-100" > </div> <div class="carousel-item"> <img src="img/app-screenshots/2.webp" class="d-block w-100" > </div> <div class="carousel-item"> <img src="img/app-screenshots/3.webp" class="d-block w-100" > </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <h5 class="modal-title" id="modalInstalarAppLabel"></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="card mb-3" style="max-width: 540px;"> <div class="row no-gutters"> <div class="col-md-4"> <img src="img/app-icons/${i}.webp" class="card-img" > </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">${app.nombreAplicacion}</h5> <p class="card-text">${app.desarrollador}</p> <p class="card-text"><small class="text-muted">${app.descripcion}</small></p> <h6 class="card-title">${app.precio}</h6> </div> <div> ${estrellas} </div> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button> <button type="button" class="btn btn-primary">Instalar</button> </div> </div> </div> </div>`; $('#modalInstalarApp').modal('show'); }) }
true
e9887e665c0fce6780dcb6983800c1bd3485615c
JavaScript
leey56522/SPR_Project
/index.js
UTF-8
3,218
3.765625
4
[]
no_license
const body = document.querySelector('body'); const rock = document.querySelector('#Rock'); const paper = document.querySelector('#Paper'); const scissors = document.querySelector('#Scissors'); const playerPick = document.getElementById('player'); const computerPick = document.getElementById('computer'); const playerOutput = document.getElementById('playerOutput'); const computerOutput = document.getElementById('computerOutput'); const roundsLeft = document.getElementById('roundsLeft'); const roundResult = document.getElementById('roundResult'); var x = 0; var y = 5; playerOutput.innerHTML = x; computerOutput.innerHTML = x; roundsLeft.innerHTML = y; const computerPlay = () => { let computerHand = "" let randomNum = Math.floor(Math.random()*3); if(randomNum === 0) { computerHand = 'Rock' } else if (randomNum === 1) { computerHand = 'Paper' } else { computerHand = 'Scissors' } return computerHand; }; const playTime = (human) => { let humanHand = human; let compHand = computerPlay(); playerPick.textContent = `Player picks: ${humanHand}`; computerPick.textContent = `Computer picks: ${compHand}`; if (humanHand === compHand) { roundsLeft.innerHTML = --y; roundResult.innerHTML = 'Tie'; } else if (humanHand === 'Rock' && compHand === 'Paper') { computerOutput.innerHTML = ++x; roundsLeft.innerHTML = --y; roundResult.innerHTML = 'Computer wins this round'; } else if (humanHand === 'Rock' && compHand === 'Scissors') { playerOutput.innerHTML = ++x; roundsLeft.innerHTML = --y; roundResult.innerHTML = 'Player wins this round'; } else if (humanHand === 'Paper' && compHand === 'Scissors') { computerOutput.innerHTML = ++x; roundsLeft.innerHTML = --y; roundResult.innerHTML = 'Computer wins this round'; } else if (humanHand === 'Paper' && compHand === 'Rock') { playerOutput.innerHTML = ++x; roundsLeft.innerHTML = --y; roundResult.innerHTML = 'Player wins this round'; } else if (humanHand === 'Scissors' && compHand === 'Rock') { computerOutput.innerHTML = ++x; roundsLeft.innerHTML = --y; roundResult.innerHTML = 'Computer wins this round'; } else if (humanHand === 'Scissors' && compHand === 'Paper') { playerOutput.innerHTML = ++x; roundsLeft.innerHTML = --y; roundResult.innerHTML = 'Player wins this round'; } if (roundsLeft.innerHTML < 0 && playerOutput.innerHTML > computerOutput.innerHTML) { alert('Congratulation! You beat the computer!!') location.reload(); } else if (roundsLeft.innerHTML < 0 && playerOutput.innerHTML < computerOutput.innerHTML) { alert('Oh no, the computer wins!') location.reload(); } else if (roundsLeft.innerHTML < 0 && playerOutput.innerHTML === computerOutput.innerHTML) { alert('Tie! Try again') location.reload(); } }; rock.addEventListener('click', function() { playTime('Rock'); }); paper.addEventListener('click', function() { playTime('Paper'); }); scissors.addEventListener('click', function() { playTime('Scissors'); });
true
26e22497a37f7c7955e375be8f27de3ab2a1e284
JavaScript
xiayefeng/cli3_demo
/src/utils/observer.js
UTF-8
527
3.359375
3
[]
no_license
/** * 观察者模式 */ // 定义一个主体对象 export class Subject { constructor () { this.Observer = [] } add (observer) { this.Observer.push(observer) } remove (observer) { this.Observer.filter(item => item === observer) } notify () { this.Observer.forEach(item => { item.update() }) } } // 定义观察着对象 export class Observer { constructor (props) { this.props = props } update () { typeof this.props.cb === 'function' && this.props.cb() } }
true
85a763d6fd8aa72b7962d9cf83761f5db80f1fbc
JavaScript
g4l/mailbox-app
/src/components/Contacts/createContact/createContact.controller.js
UTF-8
752
2.796875
3
[]
no_license
class CreateContact{ constructor() { this.fullName = ""; this.email = ""; this.birthdate = ""; this.gender = ""; this.address = ""; this.avatarUrl = ""; } create() { let contactToSave = { fullName: this.fullName, email: this.email, birthdate: isFinite( new Date(this.birthdate) ) ? this.birthdate : "", address:this.address, avatarUrl:this.avatarUrl } if(this.gender) { contactToSave.gender = this.gender; } this.saveContact({user:contactToSave}); this.fullName = ""; this.email = ""; this.birthdate = ""; this.gender = ""; this.address = ""; this.avatarUrl = ""; this.createContactForm.$setPristine(); this.createContactForm.$setUntouched(); } } export default CreateContact;
true
314752d1082f2ecc9b85cf711365277dd3d6d051
JavaScript
sudo-javabot/Scritch-streaming-service
/main.js
UTF-8
1,956
3.34375
3
[]
no_license
const Scratch = require("scratch3-api"); var fs = require("fs"); var session; var cloud; async function main() { session = await Scratch.UserSession.create("username", "password"); cloud = await session.cloudSession("572117964"); } main(); let FRAME1 = name("@frame"); let FRAME2 = name("@frame"); let FRAME3 = name("@frame"); let FRAME4 = name("@frame"); let FRAME5 = name("@frame"); let FRAME6 = name("@frame"); let FRAME7 = name("@frame"); let FRAME8 = name("@frame"); async function name(variable){ return cloud.name(variable); } const width = 64; const height = 32; async function set(variable, value){ cloud.set(variable, value); } async function get(variable){ return cloud.get(variable); } var data; async function update(){ var f1 = data.substring(256 * 0, 256 * 1); var f2 = data.substring(256 * 1, 256 * 2); var f3 = data.substring(256 * 2, 256 * 3); var f4 = data.substring(256 * 3, 256 * 4); var f5 = data.substring(256 * 4, 256 * 5); var f6 = data.substring(256 * 5, 256 * 6); var f7 = data.substring(256 * 6, 256 * 7); var f8 = data.substring(256 * 7, 256 * 8); set(FRAME2, f2); set(FRAME3, f3); set(FRAME4, f4); set(FRAME5, f5); set(FRAME6, f6); set(FRAME7, f7); set(FRAME8, f8); set(FRAME1, f1); } let FPS = 20 while(true){ /* * capture a frame from the desktop and convert it to 3-bit RGB (r = 1/0, g = 1/0, b = 1/0) and 64 by 32 pixels, and run through each pixel row by row * COLORS: * (0, 0, 0) = 0 * (0, 0, 1) = 1 * (0, 1, 0) = 2 * (1, 0, 0) = 3 * (0, 1, 1) = 4 * (1, 1, 0) = 5 * (1, 0, 1) = 6 * (1, 1, 1) = 7 * after each pixel the output color should be added to the data variable * after the convertion the update function will run and set the variables */ update(); // I'm not the best at javascript and don't know what function to call to wait, but can you call it here for a time of (1000 / FPS)? }
true
c8fa25431b33c9958786f4fd8f99a536979c8e39
JavaScript
icezeros/out-pressure
/service/serialPort/pressure.js
UTF-8
879
2.75
3
[ "Apache-2.0" ]
permissive
const moment = require('dayjs'); const _ = require('lodash'); const iconv = require('iconv-lite'); // 引入数据编码格式转换模块 let flag; function analyData({ time, data }) { const tmpMessage = iconv.decode(data, 'ascii'); if (!flag) { flag = { start: 100, end: 0, }; _.forEach(tmpMessage, (v, k) => { if (v === '\r' && k < flag.start) { flag.start = k; } if (v === '\n' && k > flag.end) { flag.end = k; } }); flag.start += 2; flag.end -= 1; return flag; } const message = tmpMessage.substring(flag.start, flag.end); const arr = message.split(','); const result = { tag1: arr[0], tag3: arr[1], time, value: Number(arr[2]), }; console.log('============ result ============='); console.log(result); console.log(); } module.exports = { analyData, };
true
61db5f2075e8fae02e78c7e5e6327f875eb47cd7
JavaScript
agodi/cs498-narrative-visualization
/initial-scene.js
UTF-8
6,530
2.78125
3
[]
no_license
const width = 500; const height = 500; const margin = 50; const yearStatsMap = new Map(); const commitsUrl = "https://api.github.com/repos/washingtonpost/data-police-shootings/commits"; const dataUrl = "https://raw.githubusercontent.com/washingtonpost/data-police-shootings/master/fatal-police-shootings-data.csv"; var data; var yearStatsXBand; var yearStatsYBand; var yearStatsYears; var yearStatsUpperLimit; var lastCommitDate; function YearStats() { this.totalCount = 0; this.statesCounts = new Map(); } function processRow(row) { row.date = new Date(row.date); year = row.date.getFullYear(); if (!yearStatsMap.has(year)) { yearStatsMap.set(year, new YearStats()) } incrementYearCounters(row.state, yearStatsMap.get(year)); return row; } function incrementYearCounters(state, yearStats) { yearStats.totalCount += 1; if (!yearStats.statesCounts.has(state)) { yearStats.statesCounts.set(state, 0); } yearStats.statesCounts.set(state, yearStats.statesCounts.get(state) + 1); } function showTooltip(d) { d3.select("#tooltip") .attr("font-family", "Arial, Helvetica, sans-serif") .style("opacity", 1) .html("Total count: " + d[1].totalCount); showYearStats(d); } function hideTooltip(d) { d3.select("#tooltip") .style("opacity", 0); d3.select("svg").selectAll(".stats").remove(); } function moveTooltip(d) { d3.select("#tooltip") .style("left", (d3.event.pageX - 40) + "px") .style("top", (d3.event.pageY - 45) + "px"); } async function loadData() { data = await d3.csv(dataUrl, processRow); getChartParams(); await getLastCommitDate(); createBarChart(); } function showYearStats(d) { const svg = d3.select("svg"); const stats = Array.from(d[1].statesCounts.entries()).sort((a, b) => b[1] - a[1]); const top5 = stats.slice(0, 5); const yearStatsLegend = svg.append("g") .attr("transform", "translate(" + 500 + "," + 60 + ")"); yearStatsLegend.selectAll("rect").data([true]).enter() .append("rect") .attr("x", 40) .attr("y", 200) .attr("width", 155) .attr("height", 135) .attr("class", "stats"); yearStatsLegend.selectAll("legends").data([1]).enter() .append("text") .text("Top 5 states in " + d[0]) .attr("x", 45) .attr("y", 220) .attr("font-family", "Arial, Helvetica, sans-serif") .attr("fill", "black") .attr("class", "stats"); yearStatsLegend.selectAll("dots").data(top5).enter() .append("circle") .attr("cx", 50) .attr("cy", (d, i) => 238 + i * 20) .attr("r", 4) .attr("fill", "black") .attr("class", "stats"); yearStatsLegend.selectAll("legends").data(top5).enter() .append("text") .text((d) => statesAbbr[d[0]] + ": " + d[1]) .attr("x", 60) .attr("y", (d, i) => 243 + i * 20) .attr("font-family", "Arial, Helvetica, sans-serif") .attr("fill", "black") .attr("class", "stats"); } async function getLastCommitDate() { response = await fetch(commitsUrl); commits = await response.json(); lastCommitDate = new Date(commits[0].commit.committer.date).toDateString(); return true; } function getChartParams() { let maxValue = 0; let years = Array.from(yearStatsMap.keys()); yearStatsMap.forEach(function(value) { if (value.totalCount > maxValue) { maxValue = value.totalCount; } }); yearStatsUpperLimit = Math.ceil(maxValue / 100) * 100; yearStatsXBand = d3 .scaleBand() .domain(years.sort()) .range([0, width - margin * 2]); yearStatsYBand = d3 .scaleLinear() .domain([0, yearStatsUpperLimit]) .range([width - margin * 2, 0]); } function createBarChart() { const svg = d3.select("svg") .attr("width", width + 200) .attr("height", height); svg.append("text") .attr("x", (width + 200) / 2) .attr("y", 30) .attr("text-anchor", "middle") .attr("font-family", "Arial, Helvetica, sans-serif") .attr("class", "title") .text("Number of deaths per year"); svg.append("g") .attr("transform", "translate(" + margin + "," + margin + ")") .selectAll("rect").data(Array.from(yearStatsMap.entries())).enter().append("rect") .attr("x", function(d) { return yearStatsXBand(d[0]) }) .attr("y", function(d) { return yearStatsYBand(0) }) .attr("width", function(d) { return yearStatsXBand.bandwidth() - 2 }) .attr("height", function(d) { return (width - margin * 2) - yearStatsYBand(0) }) .on("mouseover", showTooltip) .on("mousemove", moveTooltip) .on("mouseout", hideTooltip); svg.selectAll("rect") .transition() .duration(2000) .attr("y", function(d) { return yearStatsYBand(d[1].totalCount) }) .attr("height", function(d) { return (width - margin * 2) - yearStatsYBand(d[1].totalCount) }) .delay((d, i) => i * 200); d3.select("svg").append("g") .attr("transform", "translate(" + margin + "," + margin + ")") .call(d3.axisLeft(yearStatsYBand)); d3.select("svg").append("g") .attr("transform", "translate(" + margin + "," + (width - margin) + ")") .call(d3.axisBottom(yearStatsXBand)); svg.append('line') .style("stroke", "black") .style("stroke-width", 1) .attr("x1", 425) .attr("y1", 240) .attr("x2", 425) .attr("y2", 240) .transition() .duration(500) .attr("x2", 480) .attr("y2", 150) .delay(() => 2000); svg.append('line') .style("stroke", "black") .style("stroke-width", 1) .attr("x1", 480) .attr("y1", 150) .attr("x2", 480) .attr("y2", 150) .transition() .duration(500) .attr("x2", 520) .attr("y2", 150) .delay(() => 2350); svg.append('text') .transition() .delay(() => 2350) .attr("x", 500) .attr("y", 147) .attr("font-family", "Arial, Helvetica, sans-serif") .attr("font-size", "12") .text("Data current as of " + lastCommitDate); }
true
72c24ff6d3664b3aa50aa92bd0bfb6181ad6d4c6
JavaScript
adams549659584/nodejs-book-samples
/samples/stream-demo/stream-finish.js
UTF-8
254
2.765625
3
[]
no_license
const fs = require('fs'); const writable = fs.createWriteStream('write-data.txt'); for (let i = 0; i < 10; i++) { writable.write(`写入 #${i}!\n`); } writable.end('写入结尾\n'); writable.on('finish', () => { console.log('写入已完成'); })
true
b7dd6426ac5fecfb639844ea02102a288379405b
JavaScript
liteshotv3/codingTests
/public_html/6-21-17javascript/reverseNumber.js
UTF-8
218
3.671875
4
[]
no_license
var number = 12345; function reverseNumber(number) { var answer = 0; while (number > 0) { answer = answer * 10 + (number % 10); number = Math.floor(number / 10); } return answer; }
true
d3e9cd72b71f6d68a235c2b5bcc6d9c8109cf6e1
JavaScript
jackytck/sha1-file-web
/example/src/index.js
UTF-8
2,065
3.078125
3
[ "MIT" ]
permissive
import sha1sum from 'sha1-file-web' const input = document.querySelector('input') const preview = document.querySelector('.preview') const time = document.getElementById('time') function validFileType (file) { const fileTypes = [ 'image/jpeg', 'image/pjpeg', 'image/png' ] for (let i = 0; i < fileTypes.length; i++) { if (file.type === fileTypes[i]) { return true } } return false } function returnFileSize (number) { if (number < 1024) { return number + 'bytes' } else if (number > 1024 && number < 1048576) { return (number / 1024).toFixed(1) + 'KB' } else if (number > 1048576) { return (number / 1048576).toFixed(1) + 'MB' } } async function updateImageDisplay () { const startTime = new Date() while (preview.firstChild) { preview.removeChild(preview.firstChild) } const curFiles = input.files if (curFiles.length === 0) { const para = document.createElement('p') para.textContent = 'No files currently selected' preview.appendChild(para) } else { const list = document.createElement('ol') preview.appendChild(list) for (let i = 0; i < curFiles.length; i++) { const listItem = document.createElement('li') const para = document.createElement('p') const file = curFiles[i] if (validFileType(file)) { para.textContent = `Name: ${file.name}, Hash: ${await sha1sum(file)}, Size: ${returnFileSize(file.size)}` // const image = document.createElement('img') // image.src = window.URL.createObjectURL(curFiles[i]) // listItem.appendChild(image) listItem.appendChild(para) } else { para.textContent = `File name ${curFiles[i].name}: Not a valid file type. Update your selection.` listItem.appendChild(para) } list.appendChild(listItem) } } const endTime = new Date() const elapsed = (endTime - startTime) / 1000 time.innerHTML = `Elapsed: ${elapsed.toFixed(4)} seconds.` } // input.style.opacity = 0 input.addEventListener('change', updateImageDisplay)
true
a2093173d9e4b8e85d78cfc3f8f94d1312fde6a8
JavaScript
AnantVishwakarma/medico-healthcare
/js/register.js
UTF-8
3,748
3.359375
3
[]
no_license
const displayError = document.querySelector(".display-error"); const sex = document.getElementById("registration-form").sex; sex.style.color = "gray"; sex.options[1].style.color = "black"; sex.options[2].style.color = "black"; sex.addEventListener("change", function (event) { if (sex.value != "") sex.style.color = "black"; }); const dateOfBirth = document.getElementById("registration-form").dob; dateOfBirth.addEventListener("focus", function (event) { if (this.value == "") { this.type = "date"; let today = new Date(); let dd = String(today.getDate()).padStart(2, "0"); let mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0! let yyyy = today.getFullYear(); today = yyyy + "-" + mm + "-" + dd; //console.log(today); this.max = today; } }); dateOfBirth.addEventListener("focusout", function (event) { if (this.value == "") { this.type = "text"; } }); function validateForm(form) { let name = form.name; let dob = form.dob; let sex = form.sex; let phno = form.phno; let email = form.email; let password = form.password; let confirm_password = form.confirm_password; if ( validateName(name, 1, 50) && validateDOB(dob) && validateSex(sex) && validateNumber(phno) && validateEmail(email) && validatePassword(password, confirm_password) ) { return true; } return false; } function validateName(name, min_length, max_length) { if (min_length <= name.value.length && name.value.length <= max_length) { return true; } else { displayError.innerHTML = `Name should be between ${min_length} and ${max_length} characters`; name.focus(); return false; } } function validateDOB(dob) { if (dob.value) { return true; } else { displayError.innerHTML = "Please enter your date of birth"; dob.focus(); return false; } } function validateSex(sex) { if (sex.value == "") { displayError.innerHTML = "Please enter your sex"; sex.focus(); return false; } else { return true; } } function validateNumber(num) { const numberPattern = /^(\+91|0)?[7-9]{1}[0-9]{9}$/; if (num.value.match(numberPattern)) return true; else { displayError.innerHTML = `Not a valid Phone Number`; num.focus(); return false; } } function validateEmail(email) { const emailPattern = /[a-z0-9.]+@[a-z0-9.-]+\.[a-z]{2,}$/; if (email.value.match(emailPattern)) return true; else { displayError.innerHTML = "Not a valid email"; email.focus(); return false; } } function validatePassword(password, confirm_password) { //Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character: const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/; if (password.value == "" && confirm_password.value == "") { displayError.innerHTML = "Please type the password"; password.focus(); return false; } if (password.value.match(passwordPattern)) { if(password.value == confirm_password.value) { return true; } else { displayError.innerHTML = "Passwords do not match"; confirm_password.focus(); return false; } } else { displayError.innerHTML = "Password must contain<br>minimum eight characters<br>an uppercase letter<br>a lowercase letter<br>a digit<br>a special character"; password.focus(); return false; } }
true
d43b09ac3e70f55cdc39b8d1f0b139166db33cad
JavaScript
silentmatt/utils.js
/src/utils/DateUtil.js
UTF-8
1,300
2.9375
3
[ "MIT" ]
permissive
var DateUtil = { clone: function(date) { return new Date(date.getTime()); }, /* delta: function(info, now) { // info = { days:-1, hours:0, minutes:0, milliseconds:0 } }, */ /* hhmm: function(hours, minutes, separator) { var hh = StringUtil.padZeros(hours, 2); var mm = StringUtil.padZeros(minutes, 2); var sep = (separator || ':'); return (hh + sep + mm); }, */ /* normalize: function(ms) { var time = { milliseconds: (ms % 1000), seconds: (Math.floor(ms / 1000) % 60), minutes: (Math.floor(ms / 1000 / 60) % 60), hours: (Math.floor(ms / 1000 / 60 / 60) % 24), days: (Math.floor(ms / 1000 / 60 / 60 / 24)) }; return time; }, */ timestamp: function() { return new Date().getTime(); }, yyyymmdd: function(date, separator) { var d = (date || new Date()); var yy = d.getFullYear(); var mm = d.getMonth() + 1; // getMonth() is zero-based var dd = d.getDate(); var sep = (separator || ''); return (String(yy) + sep + StringUtil.padZeros(mm, 2) + sep + StringUtil.padZeros(dd, 2)); } };
true
a7ce9528db6c7b358d548aa7770c54acdbfed532
JavaScript
AnasBInRiaz123/fb-post
/src/index.js
UTF-8
1,029
2.625
3
[]
no_license
import React from 'react'; import ReactDOM from 'react-dom'; import "./index.css" import ava1 from "./image/ava1.png" import ava2 from "./image/ava2.png" import ava3 from "./image/ava3.png" import avatar from "./image/whatisavatar.jpg" import avatar1 from "./image/whatisavatar1.jpg" import avatar2 from "./image/whatisavatar2.jpg" function Hi(props) { return <div id="main"> <p> <img className="prof" src={props.prof} /> <strong>{props.name}!</strong> <br /> {props.date} </p> <p style={{color:"white"}}> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown ... </p> <img className="img" src={props.img} /> </div>; } ReactDOM.render( <div> <Hi prof={ava1} name="Ghost1" date="3/8/2021" img={avatar}/> <Hi prof={ava2} name="Ghost2" date="6/9/2021" img={avatar1} /> <Hi prof={ava3} name="Ghost3" date="16/11/2021" img={avatar2} /> </div>, document.querySelector('#root'));
true
7ff7752fe1c99c4c7fc56a6a4e30c64b90ebd29a
JavaScript
AlvertosFIorantis/single_page_bootsrap
/js/app.js
UTF-8
723
2.625
3
[ "MIT" ]
permissive
function LivaTranslateUK() { document.getElementById('livaCard').classList.add('rotate-sinergates') } function LivaTranslateGreek() { document.getElementById('livaCard').classList.remove('rotate-sinergates') } function KolivakisTranslateUK() { document.getElementById('kolivakisCard').classList.add('rotate-sinergates') } function KolivakisTranslateGreek() { document.getElementById('kolivakisCard').classList.remove('rotate-sinergates') } function BaziotopoulosTranslateUK() { document .getElementById('BaziotopoulosCard') .classList.add('rotate-sinergates') } function BaziotopoulosTranslateGreek() { document .getElementById('BaziotopoulosCard') .classList.remove('rotate-sinergates') }
true
3d0bbef2a34f8a7037c4f8c3dc044a9c4ca55a1d
JavaScript
lmaran/matemaraton
/src/controllers/exercise.controller.js
UTF-8
11,530
2.6875
3
[]
no_license
const exerciseService = require("../services/exercise.service"); const idGeneratorMongoService = require("../services/id-generator-mongo.service"); const autz = require("../services/autz.service"); const markdownService = require("../services/markdown.service"); const { availableExerciseTypes } = require("../constants/constants"); exports.getOneById = async (req, res) => { const exercise = await exerciseService.getOneById(req.params.id); if (exercise && exercise.question) { if (exercise.question.statement) { const statement = `**E.${exercise.code}.** ${exercise.question.statement.text}`; // const statement = `**[Problema ${++i}.](/exercitii/${exercise._id})** ${exercise.question.statement.text}`; const alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); if (exercise.question.answerOptions) { exercise.question.answerOptions.forEach((answerOption, idx) => { // insert a label (letter) in front of each option: "a" for the 1st option, "b" for the 2nd a.s.o. answerOption.textPreview = markdownService.render(`${alphabet[idx]}) ${answerOption.text}`); if (answerOption.isCorrect) { exercise.question.correctAnswerPreview = markdownService.render(`**Răspuns:** ${answerOption.text}`); } }); } exercise.question.statement.textPreview = markdownService.render(statement); } if (exercise.question.answer) exercise.question.answer.textPreview = markdownService.render(`**Răspuns:** ${exercise.question.answer.text}`); if (exercise.question.solution?.text) exercise.question.solution.textPreview = markdownService.render(exercise.question.solution.text); if (exercise.question.hints) { exercise.question.hints.forEach((hint, idx) => { hint.textPreview = markdownService.render(`**Indicația ${idx + 1}:** ${hint.text}`); }); } } const data = { exercise, canCreateOrEditExercise: await autz.can(req.user, "create-or-edit:exercise"), canDeleteExercise: await autz.can(req.user, "delete:exercise"), }; //res.send(data); res.render("exercise/exercise", data); }; exports.createOrEditGet = async (req, res) => { const canCreateOrEditExercise = await autz.can(req.user, "create-or-edit:exercise"); if (!canCreateOrEditExercise) { return res.status(403).send("Lipsă permisiuni!"); // forbidden } const isEditMode = !!req.params.id; const data = { isEditMode, availableExerciseTypes, }; if (isEditMode) { const exercise = await exerciseService.getOneById(req.params.id); exercise.question.statement.textPreview = markdownService.render(exercise.question.statement.text); if (exercise.question.answer && exercise.question.answer.text) { exercise.question.answer.textPreview = markdownService.render(exercise.question.answer.text); } if (exercise.question.solution && exercise.question.solution.text) { exercise.question.solution.textPreview = markdownService.render(exercise.question.solution.text); } if (exercise.question.hints) { exercise.question.hints.forEach((hint) => { hint.textPreview = markdownService.render(hint.text); }); } if (exercise.question.answerOptions) { exercise.question.answerOptions.forEach((answerOption) => { answerOption.textPreview = markdownService.render(answerOption.text); }); } data.exercise = exercise; } else { data.exercise = { exerciseType: "1" }; // Set 'open answer' as a default exercise type } //res.send(data); res.render("exercise/exercise-create-or-edit", data); }; exports.createOrEditPost = async (req, res) => { try { const canCreateOrEditExercise = await autz.can(req.user, "create-or-edit:exercise"); if (!canCreateOrEditExercise) { return res.status(403).send("Lipsă permisiuni!"); // forbidden } const { id, grade, contestName, exerciseType, sourceName, author, statement, answer, solution } = req.body; const isEditMode = !!id; const exercise = { question: { statement: { text: statement }, solution: { text: solution }, answer: { text: answer }, }, grade, exerciseType, contestName, sourceName, author, }; const hints = req.body.hints; if (hints) { exercise.question.hints = []; if (Array.isArray(hints)) { hints.forEach((hint) => { if (hint.trim()) { exercise.question.hints.push({ text: hint.trim() }); } }); } else { // an object with a single option if (hints.trim()) { exercise.question.hints.push({ text: hints.trim() }); } } } const answerOptions = req.body.answerOptions; if (answerOptions) { exercise.question.answerOptions = []; if (Array.isArray(answerOptions)) { answerOptions.forEach((answerOption, idx) => { if (answerOption.trim()) { const newAnswerOption = { text: answerOption.trim() }; // set isCorrectAnswer (if apply) const isCorrectAnswerChecks = req.body.isCorrectAnswerChecks; if (isCorrectAnswerChecks) { if (Array.isArray(isCorrectAnswerChecks)) { if (isCorrectAnswerChecks.includes(String(idx + 1))) { newAnswerOption.isCorrect = true; } } else { if (isCorrectAnswerChecks === String(idx + 1)) { newAnswerOption.isCorrect = true; } } } exercise.question.answerOptions.push(newAnswerOption); } }); } else { // an object with a single option if (answerOptions.trim()) { const newAnswerOption = { text: answerOptions.trim() }; // set isCorrectAnswer (if apply) const isCorrectAnswerChecks = req.body.isCorrectAnswerChecks; if (isCorrectAnswerChecks && isCorrectAnswerChecks === "1") { newAnswerOption.isCorrect = true; } exercise.question.answerOptions.push(newAnswerOption); } } } if (isEditMode) { exercise._id = id; exerciseService.updateOne(exercise); } else { exercise.code = await idGeneratorMongoService.getNextId("exercises"); const result = await exerciseService.insertOne(exercise); exercise._id = result.insertedId; } //res.send(exercise); res.redirect(`/exercitii/${exercise._id}/modifica`); } catch (err) { return res.status(500).json(err.message); } }; exports.getAll = async (req, res) => { // const exercises = await exerciseService.getAll(); const pageSizes = [ { text: "10 pe pagină", value: "10" }, { text: "30 pe pagină", value: "30" }, { text: "50 pe pagină", value: "50" }, ]; const currentPage = parseInt(req.query.page) || 1; let limit = parseInt(req.query.limit) || 10; if (limit > 100) limit = 50; const startIndex = (currentPage - 1) * limit; let endIndex = currentPage * limit; const query = { skip: startIndex, limit, }; const [exercises, totalExercises] = await Promise.all([await exerciseService.getAll(query), await exerciseService.count()]); if (endIndex > totalExercises) endIndex = totalExercises; // fix endIndex for the last page exercises.forEach((exercise) => { let statement = `**[E.${exercise.code}.](/exercitii/${exercise._id})** ${exercise.question.statement?.text}`; if (exercise.question.answerOptions) { exercise.question.answerOptions.forEach((answerOption) => { statement = statement + "\n" + "* " + answerOption.text; }); } const alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); if (exercise.question.answerOptions) { exercise.question.answerOptions.forEach((answerOption, idx) => { // insert a label (letter) in front of each option: "a" for the 1st option, "b" for the 2nd a.s.o. answerOption.textPreview = markdownService.render(`${alphabet[idx]}) ${answerOption.text}`); if (answerOption.isCorrect) { exercise.question.correctAnswerPreview = markdownService.render(`**Răspuns:** ${answerOption.text}`); } }); } if (exercise.question.statement) { exercise.question.statement.textPreview = markdownService.render(statement); } if (exercise.question.solution?.text) { exercise.question.solution.textPreview = markdownService.render(exercise.question.solution.text); } if (exercise.question.hints) { exercise.question.hints.forEach((hint, idx) => { hint.textPreview = markdownService.render(`**Hint ${idx + 1}:** ${hint.text}`); }); } }); const totalPages = Math.ceil(totalExercises / limit); const pageResults = { totalExercises, pageSizes, pageSize: limit, startIndex: startIndex + 1, endIndex, previousPageBtn: { page: currentPage - 1, isDisabled: currentPage === 1, }, nextPageBtn: { page: currentPage + 1, isDisabled: currentPage === totalPages, }, }; const data = { exercises, canCreateOrEditExercise: await autz.can(req.user, "create-or-edit:exercise"), pageResults, }; // res.send(data); res.render("exercise/exercise-list", data); }; exports.deleteOneById = async (req, res) => { const exerciseId = req.body.exerciseId; const canDeleteExercise = await autz.can(req.user, "delete:exercise"); if (!canDeleteExercise) { return res.status(403).send("Lipsă permisiuni!"); // forbidden } exerciseService.deleteOneById(exerciseId); res.redirect("/exercitii"); }; exports.addMySolution = async (req, res) => { // TODO // 1. check if authenticcated // 2. check if student or teacher // 3. check if submission belongs to a homework // 4. validate input const mySolution = req.body; mySolution.submittedById = req.user._id.toString(); mySolution.submittedOn = new Date(); //onsole.log(mySolution); await exerciseService.insertSolution(mySolution); const data = { mySolution, }; res.json(data); //res.render("exercise/exercise-print", data); };
true
a1f4da0216adca35f7c8e1f7cd4dc8f9a814f3a2
JavaScript
PirialMersus/codewars
/js/main1.js
UTF-8
22,915
3.71875
4
[]
no_license
// function alphabetPosition(text) { // let result = ""; // let arr = text.toLowerCase().split(""); // let filtered = arr.filter( // (currentValue) => // currentValue.charCodeAt(0) > 96 && currentValue.charCodeAt(0) < 123 // ); // for (let i = 0; i < filtered.length; i++) { // if (i !== filtered.length - 1) { // let letterIndexByAscii = filtered[i].charCodeAt(0); // result += `${letterIndexByAscii - 96} `; // } else { // let letterIndexByAscii = filtered[i].charCodeAt(0); // result += `${letterIndexByAscii - 96}`; // } // } // return result; // } // Your task is to sort a given string. Each word in the string will contain a single number. // This number is the position the word should have in the result. // Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0). // If the input string is empty, return an empty string. The words in the input String will // only contain valid consecutive numbers. // Examples // "is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est" // "4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople" // "" --> "" // function order(str) { // const wordsObject = {}; // let answer = ""; // const words = str.split(" "); // if (words.length === 0) return wordsObject; // for (let i = 0; i < words.length; i++) { // const splitNameArr = words[i].split(""); // for (let j = 0; j < splitNameArr.length; j++) { // if (isNaN(splitNameArr[j]) === false) { // wordsObject[splitNameArr[j]] = words[i]; // } // } // } // for (let i = 1; i <= Object.keys(wordsObject).length; i++) { // if (i === Object.keys(wordsObject).length) { // answer += wordsObject[i]; // } else answer += `${wordsObject[i]} `; // } // return answer; // } // order("is2 Thi1s T4est 3a"); // let quantityX = 0, // quantityO = 0; // let arr = str.toLowerCase().split(""); // for (let i = 0; i < arr.length; i++) { // if (arr[i].charCodeAt(0) === 111) { // quantityO++; // } else if (arr[i].charCodeAt(0) === 120) { // quantityX++; // } // } // if (quantityX === quantityO) { // return true; // } else if (quantityX === 0 && quantityO === 0) { // return true; // } else { // return false; // // function isPrime(num) { // //TODO // if (num < 2) { // return false; // } // for (let i = 2; i < num; i++) { // const divisionResult = num / i; // const simbolsAfterComma = (result) => // result.toString().includes(".") // ? result.toString().split(".").pop().length // : 0; // if (simbolsAfterComma(divisionResult) === 0) { // return false; // } // } // return true; // } // function humanReadable(seconds) { // const countDigits = (n) => { // for (let i = 0; n > 1; i++) { // n /= 10; // } // return i; // }; // TODO // let resultHours = 0, // resultMinutes = 0, // tempSeconds = seconds, // resultSeconds = 0; // resultHours = seconds / 3600; // if (resultHours > 99) { // return `99 59 59`; // } // if (resultHours >= 1) { // tempSeconds = seconds - resultHours * 3600; // } // resultMinutes = tempSeconds / 60; // if (resultMinutes >= 1) { // tempSeconds = tempSeconds - resultMinutes * 60; // } // resultSeconds = tempSeconds; // console.log( // "resultHours", // resultHours, // "resultMinutes", // resultMinutes, // "resultSeconds", // resultSeconds // ); // if (seconds <= 60) { // if (countDigits(seconds) < 2) { // return `00 00 0${seconds}`; // } else { // return `00 00 ${seconds}`; // } // } // } // humanReadable(58); // console.log(humanReadable(5)); // const even_or_odd = (number) => { // if (number % 2 === 0) return "Even"; // else return "Odd"; // }; // console.log(even_or_odd(676)); // console.log(even_or_odd(7)); // function positiveSum(arr) { // let sum = 0; // arr.forEach((el) => { // if (el > 0) { // sum += el; // } // }); // return sum; // } // console.log(positiveSum([1, 2, 3, 4, 5])); // function findShort(s) { // const worlds = s.split(" "); // let shortest = worlds[0].split("").length; // console.log(worlds); // console.log(shortest); // for (let index = 0; index < worlds.length; index++) { // const element = worlds[index]; // if (element.split("").length < shortest) { // shortest = element.split("").length; // } // } // return shortest; // } // console.log(findShort("bitcoin take over the world maybe who knows perhaps")); // function solution(str) { // console.log(str.split("").reverse().join("")); // return str.split("").reverse().join(""); // } // arr1 = [1, 2, 3, 4, 5]; // arr2 = [6, 7, 8, 9, 10]; // mergeArrays(arr1, arr2); // function mergeArrays(arr1, arr2) { // let tempValue; // const arr3 = arr1 // .concat(arr2) // .sort((a, b) => a - b) // .filter((item) => { // if (item !== tempValue) { // tempValue = item; // return true; // } else { // tempValue = item; // return false; // } // }); // console.log(arr3); // return arr3; // } // function getCount(str) { // let vowelsCount = 0; // const arr = str.split(""); // for (let i = 0; i <= arr.length; i++) { // if ( // arr[i] === "a" || // arr[i] === "e" || // arr[i] === "i" || // arr[i] === "o" || // arr[i] === "u" // ) { // vowelsCount++; // } // } // console.log(vowelsCount); // // enter your majic here // return vowelsCount; // } // getCount("abracadabra"); // const numbers = [21, 0, 12, 1, 3]; // const sum = numbers.reduce((acc, el) => acc + el); // console.log(sum); // function dirReduc(arr) { // let arrCopy = [...arr]; // let itemsNumbers = []; // let flag = true; // const compareFunction = (a, b) => { // switch (a) { // case "WEST": // if (b === "EAST") { // return true; // } // break; // case "EAST": // if (b === "WEST") { // return true; // } // break; // case "NORTH": // if (b === "SOUTH") { // return true; // } // break; // case "SOUTH": // if (b === "NORTH") { // return true; // } // break; // default: // return false; // } // }; // for (let i = 0; i < arrCopy.length; i++) { // if (arrCopy[i + 1]) { // if (flag) { // if (compareFunction(arrCopy[i], arrCopy[i + 1])) { // itemsNumbers = [...itemsNumbers, i, i + 1]; // flag = false; // } else { // flag = true; // } // } // } // } // if (itemsNumbers.length > 0) { // for (let i = itemsNumbers.length - 1; i >= 0; i--) { // arrCopy.splice(itemsNumbers[i], 1); // } // return dirReduc(arrCopy); // } else { // return arrCopy; // } // } // console.log( // dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]) // ); // console.log(dirReduc(["NORTH", "SOUTH", "EAST", "WEST", "EAST", "WEST"])); // console.log(dirReduc(["NORTH", "WEST", "SOUTH", "EAST"])); // const students = [ // { name: "gena", age: 35 }, // { name: "alena", age: 25 }, // { name: "kay", age: 37 }, // { name: "olya", age: 15 }, // { name: "step", age: 125 }, // { name: "kris", age: 9 }, // { name: "julia", age: 45 }, // { name: "serg", age: 383 }, // ]; // function addNewField(arr) { // const newArray = [...arr]; // // newArray.map((st) => { // // [...st, friends: [...newArray.filter((student) => student.name !== st.name)], // // ]}); // // }); // const friends = newArray.map((st) => st.name); // console.log(friends); // return newArray.map((el) => ({ // ...el, // friends: friends.filter((friend) => friend !== el.name), // })); // } // console.log(addNewField(students)); // function zero(b) { // if (b) { // switch (b[0]) { // case "plus": // return Math.floor(0 + b[1]); // break; // case "minus": // return Math.floor(0 - b[1]); // break; // case "times": // return Math.floor(0 * b[1]); // break; // case "divide": // return Math.floor(0 / b[1]); // break; // default: // alert("Нет таких значений"); // } // } else { // return 0; // } // } // function one(b) { // if (b) { // switch (b[0]) { // case "plus": // return Math.floor(1 + b[1]); // break; // case "minus": // return Math.floor(1 - b[1]); // break; // case "times": // return Math.floor(1 * b[1]); // break; // case "divide": // return Math.floor(1 / b[1]); // break; // default: // alert("Нет таких значений"); // } // } else { // return 1; // } // } // function two(b) { // if (b) { // switch (b[0]) { // case "plus": // return Math.floor(2 + b[1]); // break; // case "minus": // return Math.floor(2 - b[1]); // break; // case "times": // return Math.floor(2 * b[1]); // break; // case "divide": // return Math.floor(2 / b[1]); // break; // default: // alert("Нет таких значений"); // } // } else { // return 2; // } // } // function three(b) { // if (b) { // switch (b[0]) { // case "plus": // return Math.floor(3 + b[1]); // break; // case "minus": // return Math.floor(3 - b[1]); // break; // case "times": // return Math.floor(3 * b[1]); // break; // case "divide": // return Math.floor(3 / b[1]); // break; // default: // alert("Нет таких значений"); // } // } else { // return 3; // } // } // function four(b) { // if (b) { // switch (b[0]) { // case "plus": // return Math.floor(4 + b[1]); // break; // case "minus": // return Math.floor(4 - b[1]); // break; // case "times": // return Math.floor(4 * b[1]); // break; // case "divide": // return Math.floor(4 / b[1]); // break; // default: // alert("Нет таких значений"); // } // } else { // return 4; // } // } // function five(b) { // if (b) { // switch (b[0]) { // case "plus": // return Math.floor(5 + b[1]); // break; // case "minus": // return Math.floor(5 - b[1]); // break; // case "times": // return Math.floor(5 * b[1]); // break; // case "divide": // return Math.floor(5 / b[1]); // break; // default: // alert("Нет таких значений"); // } // } else { // return 5; // } // } // function six(b) { // if (b) { // switch (b[0]) { // case "plus": // return Math.floor(6 + b[1]); // break; // case "minus": // return Math.floor(6 - b[1]); // break; // case "times": // return Math.floor(6 * b[1]); // break; // case "divide": // return Math.floor(6 / b[1]); // break; // default: // alert("Нет таких значений"); // } // } else { // return 6; // } // } // function seven(b) { // if (b) { // switch (b[0]) { // case "plus": // return Math.floor(7 + b[1]); // break; // case "minus": // return Math.floor(7 - b[1]); // break; // case "times": // return Math.floor(7 * b[1]); // break; // case "divide": // return Math.floor(7 / b[1]); // break; // default: // alert("Нет таких значений"); // } // } else { // return 7; // } // } // function eight(b) { // if (b) { // switch (b[0]) { // case "plus": // return Math.floor(8 + b[1]); // break; // case "minus": // return Math.floor(8 - b[1]); // break; // case "times": // return Math.floor(8 * b[1]); // break; // case "divide": // return Math.floor(8 / b[1]); // break; // default: // alert("Нет таких значений"); // } // } else { // return 8; // } // } // function nine(b) { // if (b) { // switch (b[0]) { // case "plus": // return Math.floor(9 + b[1]); // break; // case "minus": // return Math.floor(9 - b[1]); // break; // case "times": // return Math.floor(9 * b[1]); // break; // case "divide": // return Math.floor(9 / b[1]); // break; // default: // alert("Нет таких значений"); // } // } else { // return 9; // } // } // function plus(a) { // return ["plus", a]; // } // function minus(a) { // return ["minus", a]; // } // function times(a) { // return ["times", a]; // } // function dividedBy(a) { // return ["divide", a]; // } // .................................................. // function validParentheses(parens) { // if (parens.length % 2 > 0) { // return false; // } // const arr = parens.split(""); // for (let i = 0; i < arr.length - 1; i++) { // if (arr[i] === ")") { // return false; // } else { // for (let j = i + 1; j < arr.length; j++) { // if (arr[j] === ")") { // arr.splice(j, 1); // arr.splice(i, 1); // break; // } // if (j === arr.length - 1) { // return false; // } // } // break; // } // } // if (arr.length > 0) { // return validParentheses(arr.join("")); // } // return true; // } // console.log(validParentheses("(())((()())())")); // console.log(validParentheses("())")); // console.log(validParentheses("(())))")); // console.log(validParentheses("()((()))()()()()()()()()()()()()()()((()")); // console.log(validParentheses("()()()()()()()()()()()()()()()()()()()((")); // console.log(validParentheses("(())))")); // ////////////////............................................ // function validParentheses(parens) { // // debugger; // if (parens.length % 2 > 0) { // return false; // } // const arr = parens.split(""); // const tempArr = []; // let flag = true; // for (let i = 0; i < arr.length - 1; i++) { // flag = true; // if (tempArr.length) { // tempArr.map((el) => { // if (i === el) { // flag = false; // } // }); // } // if (flag) { // if (arr[i] === ")") { // return false; // } // if (arr[i] === "(") { // for (let j = i + 1; j < arr.length; j++) { // flag = true; // if (tempArr.length) { // tempArr.map((el) => { // if (j === el) { // flag = false; // } // }); // } // if (flag) { // if (arr[j] === ")") { // tempArr.push(j); // break; // } // if (j === arr.length - 1) { // return false; // } // } // } // } // } // } // return true; // } // console.log(validParentheses("()((()))()()()()()()()()()()()()()()((()")); // console.log(validParentheses("()()()()()()()()()()()()()()()()()()()((")); // console.log(validParentheses("(())))")); //////////////////////////////////////......................................... // function task(w, n, c) { // let name = ""; // if (w === "Monday") { // name = "James"; // } // if (w === "Tuesday") { // name = "John"; // } // if (w === "Wednesday") { // name = "Robert"; // } // if (w === "Thursday") { // name = "Michael"; // } // if (w === "Friday") { // name = "William"; // } // // your code // return `It is ${w} today, ${name}, you have to work, you must spray ${n} trees and you need ${ // n * c // } dollars to buy liquid`; // } // function evenLast(numbers) { // if (numbers.length === 0) return 0; // let sum = 0; // for (let i = 0; i < numbers.length; i++) { // if (i % 2 === 0) { // sum = sum + numbers[i]; // } // if (i === numbers.length - 1) { // sum = sum * numbers[i]; // } // } // return sum; // } // console.log(evenLast([2, 3, 4, 5])); // function solution(str) { // let tempValue = ""; // let solutionArr = []; // const lettersArr = str.split(""); // if (!lettersArr.length) return []; // for (let i = 0; i < lettersArr.length; i++) { // tempValue += lettersArr[i]; // if (i % 2 !== 0) { // solutionArr.push(tempValue); // tempValue = ""; // } // if (i === lettersArr.length - 1 && i % 2 === 0) { // solutionArr.push(tempValue + "_"); // } // } // return solutionArr; // } // console.log(solution("abc")); // console.log(solution("abcdef")); // function validSpacing(s) { // console.log(s.split(" ")); // const tempArr = s.split(" "); // if (tempArr[0] === "" || tempArr[tempArr.length - 1] === "") return false; // for (let i = 0; i < tempArr.length; i++) { // if (i === tempArr.length - 1) return true; // if (tempArr[i] === "") { // return false; // } // } // return true; // } // console.log(validSpacing("Hello world")); // console.log(validSpacing("Hello world")); // console.log(validSpacing("Hello world ")); // console.log(validSpacing(" Hello world")); // function validSpacing(s) { // console.log(s.split(" ")); // const tempArr = s.split(""); // if (tempArr[0] === "" || tempArr[tempArr.length - 1] === "") return false; // for (let i = 0; i < tempArr.length; i++) { // if (tempArr[i] === "") { // return // } // } // return true; // } // function makeArmy() { // let shooters = []; // let i = 0; // while (i < 10) { // let j = i; // let shooter = function () { // // функция shooter // alert(j); // должна выводить порядковый номер // }; // shooters.push(shooter); // i++; // } // return shooters; // } // let army = makeArmy(); // army[0](); // у 0-го стрелка будет номер 10 // army[5](); // и у 5-го стрелка тоже будет номер 10 // ... у всех стрелков будет номер 10, вместо 0, 1, 2, 3... // Напишите функцию sumTo(n), которая вычисляет сумму чисел 1 + 2 + ... + n. // Например: // sumTo(1) = 1 // sumTo(2) = 2 + 1 = 3 // sumTo(3) = 3 + 2 + 1 = 6 // sumTo(4) = 4 + 3 + 2 + 1 = 10 // ... // sumTo(100) = 100 + 99 + ... + 2 + 1 = 5050 // Сделайте три варианта решения: // С использованием цикла. // Через рекурсию, т.к. sumTo(n) = n + sumTo(n-1) for n > 1. // С использованием формулы арифметической прогрессии. // Пример работы вашей функции: // function sumTo(n) { /*... ваш код ... */ } // alert( sumTo(100) ); // 5050 // P.S. Какой вариант решения самый быстрый? Самый медленный? Почему? // P.P.S. Можно ли при помощи рекурсии посчитать sumTo(100000)? // function sumTo(n) { // if (n > 1) { // return n + sumTo(n - 1); // } else { // return n; // } // } // console.log(sumTo(100)); // function flatMethod(arr) { // let arrResult = []; // let flag = false; // for (let i = 0; i < arr.length; i++) { // if (Array.isArray(arr[i])) { // for (let j = 0; j < arr[i].length; j++) { // if (Array.isArray(arr[i][j])) { // arrResult.push(...flatMethod(arr[i][j])); // } else { // arrResult.push(arr[i][j]); // } // } // } else { // arrResult.push(arr[i]); // } // } // return arrResult; // } // function flatMethod(arr) { // return arr.reduce( // (acc, item) => // Array.isArray(item) ? [...acc, ...flatMethod(item)] : [...acc, item], // [] // ); // } // console.log(flatMethod([1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]])); // function firstNonConsecutive(arr) { // let width = (function () { // for (let i = 0; i < arr.length; i++) { // if (i !== arr.length - 2) { // if (arr[i + 1] - arr[i] === arr[i + 2] - arr[i + 1]) { // return arr[i + 1] - arr[i]; // } // } // } // })(); // debugger; // let result; // for (let i = 0; i < arr.length; i++) { // if (i !== arr.length - 1) { // if (arr[i + 1] - arr[i] !== width) { // return arr[i + 1]; // } // } // } // return null; // } // console.log(firstNonConsecutive([1, 2, 3, 4, 6, 7, 8])); // let i = 0; // function count() { // // делаем часть крупной задачи (*) // do { // i++; // progress.innerHTML = i; // } while (i % 1e3 != 0); // if (i < 1e6) { // queueMicrotask(count); // } // } // count(); // function highestRank(arr) { // //Your Code logic should written here // const count = arr.reduce((tally, elem) => { // tally[elem] = (tally[elem] || 0) + 1; // return tally; // }, {}); // const newArr = Object.entries(count); // console.log(newArr); // newArr.sort((a, b) => b[1] - a[1]); // console.log(newArr); // return newArr[0][1]; // // let answer = 0; // // let biggestCount = 0; // // for (let key in count) { // // if (count[key] >= biggestCount) { // // let biggestCount = count[key]; // // answer = key; // // } // // } // // return answer; // } // const arr = [12, 10, 8, 12, 7, 6, 4, 10]; // console.log(highestRank(arr)); // function solution(str, ending) { // const sourceArray = str.split(""); // const endingArray = ending.split(""); // if (endingArray.length === 0) { // return true; // } // console.log(sourceArray); // console.log(endingArray); // let flag = false; // for (let i = 0; i < endingArray.length; i++) { // const endingArray = ending.split(""); // if ( // endingArray[endingArray.length - i - 1] === // sourceArray[sourceArray.length - i - 1] // ) { // flag = true; // } else { // return false; // } // } // return flag; // } // console.log(solution("abc", "bc")); // console.log(solution("abc", "")); function bmi(weight, height) { const bmi = weight / (height * height); return bmi <= 30.0 ? "Overweight" : bmi <= 25.0 ? "Normal" : bmi <= 18.5 ? "Underweight" : "Obese"; } console.log(bmi(80, 1.8));
true
9045dc0542331527d7471104fab93bbabb642721
JavaScript
ElenaTrehub/well-fed-home
/public/js/updateRecipe.js
UTF-8
4,116
2.921875
3
[ "MIT" ]
permissive
let ingredients = []; let i = 0; window.onload = function() { let ingredientsStr = document.getElementById('ingredients').value; if(ingredientsStr.length > 0){ ingredients = ingredientsStr.split(';'); for(let i =0; i<ingredients.length-1; i++){ ingredients[i] = ingredients[i] + ';'; } i = ingredients.length - 1; console.log(ingredients); } }; function AddIngredient(){ let title = document.getElementById('titleIngredient').value; let count = document.getElementById('countIngredient').value; let unit = document.getElementById('units').value; let error = document.getElementById('errorIngredient'); document.getElementById('titleIngredient').value = ""; document.getElementById('countIngredient').value = ""; document.getElementById('units').value = ""; //console.log(title); if(title === '' || count ===''){ error.style.display = 'block'; } else{ error.style.display = 'none'; let strIngredient = title + " - " + count + " " + unit + ";"; ingredients.push(strIngredient); let sendField = document.getElementById('ingredients'); let str = ''; for(let i =0; i<ingredients.length; i++){ str += ingredients[i]; } sendField.value = str; console.log(sendField.value); let tableIngredients = document.getElementById('editIngredientTable'); let tbody = tableIngredients.getElementsByTagName("TBODY")[0]; let row = document.createElement("TR"); let td1 = document.createElement("TD"); td1.appendChild(document.createTextNode(i+1)); let td2 = document.createElement("TD"); td2.appendChild(document.createTextNode(strIngredient)); let td3 = document.createElement("TD"); let delInput = document.createElement("input"); delInput.type = "button"; delInput.value = "Remove"; delInput.dataset.index = i; //console.log(i); i = i + 1; delInput.onclick = deleteIngredient; td3.appendChild(delInput); row.appendChild(td1); row.appendChild(td2); row.appendChild(td3); tbody.appendChild(row); tableIngredients.style.display='block'; } //console.log(sendField.value); } function deleteIngredient(btn) { let index = btn.dataset.index; //sconsole.log(btn); ingredients.splice(index-1, 1); let sendField = document.getElementById('ingredients'); let str = ''; for(let i =0; i<ingredients.length; i++){ str += ingredients[i]; } sendField.value = str; let tableIngredients = document.getElementById('editIngredientTable'); let row = btn.parentElement.parentElement; let tbody = tableIngredients.getElementsByTagName("TBODY")[0]; tbody.removeChild(row); console.log(sendField.value); if(ingredients.length === 0){ tableIngredients.style.display = 'none'; } }; function AddStep () { let listStep = document.getElementsByClassName("btn btn-danger"); let stepCounter = listStep.length-1; stepCounter++; console.log(stepCounter); let template = $("#stepTemplate").clone(); template.css('visibility', 'visible'); let inputList = template.find("input"); console.log(template); console.log(inputList); inputList[0].setAttribute("name", "step["+ stepCounter +"][StepDescription]"); inputList[1].setAttribute("name", "step["+ stepCounter +"][StepPhoto]"); inputList[0].value = ""; inputList[1].value = ""; //for (let index = 0; index < inputList.length; index++) { // console.log(inputList[index]); //inputList[index].setAttribute("name", "step["+ stepCounter +"][StepDescription]"inputList[index].name.substring(0, inputList[index].name.lastIndexOf('_')+1) + stepCounter +"]"); //inputList[index].name = inputList[index].name + visitCounter; //console.log(inputList[index]); // } $("#stepPlaceholder").append(template); }; function DeleteStep(btn) { $(btn).closest(".create-step-short").remove(); }
true
3aae5ae3487a008eb9c677090929b69a56581953
JavaScript
shermanhui/frontend-nanodegree-arcade-game
/js/app.js
UTF-8
6,131
3.265625
3
[ "MIT" ]
permissive
// TODO: ADD MENU SCREEN // TODO: ADD CHARACTER, LEVEL, DIFFICULTY SETTING // TODO: REDESIGN LEVEL LAYOUT // TODO: REDESIGN CHARACTERS var TILE_WIDTH = 101; var TILE_HEIGHT = (171/2); var ENEMY_START = -100; var XPOS = [-2, 99, 200, 301, 402]; var YPOS = [58, 143.5, 229]; var GEM_IMAGES = ['images/gem-orange.png', 'images/gem-blue.png', 'images/gem-blue.png']; var GAME_OVER = false; //FINITE STATE MACHINE // var fsm = StateMachine.create({ // initial: 'menu', // events: [ // {name: 'play', from: 'menu', to: 'game'}, // {name: 'quit', from: 'game', to: 'menu'}, // ], // callbacks: { // onentermenu: function() {$('#menu').show();}, // onentergame: function() {$('#game').show();} // } // }) // CREATE GLOBAL GAMEOBJ OBJECT TO MANIPULATE// var gameObj = function () { this.sprite = ''; }; // Global render function for all game objects gameObj.prototype.render = function() { ctx.drawImage(Resources.get(this.sprite), this.x, this.y); }; // Enemies our player must avoid var Enemy = function() { // calls gameObj to be used as reference for "this" gameObj.call(this); // Variables applied to each of our instances go here, // we've provided one for you to get started // The image/sprite for our enemies, this uses // a helper we've provided to easily load images this.sprite = 'images/enemy-bug.png'; this.x = ENEMY_START; this.y = YPOS[Math.floor(Math.random() * 3)]; this.speed = Math.floor((Math.random() * 200) + 110); }; // All objects created here fall back to gameObj for render property Enemy.prototype = Object.create(gameObj.prototype); Enemy.prototype.constructor = Enemy; // Update the enemy's position, required method for game // Parameter: dt, a time delta between ticks Enemy.prototype.update = function(dt) { // You should multiply any movement by the dt parameter // which will ensure the game runs at the same speed for // all computers. if (this.x <= 490) { this.x += this.speed * dt; } else { this.x = ENEMY_START; //Shifts the bugs a row, to add randomness; also keeps the bugs within the rock rows this.y = this.y + 83.5; if (this.y > 229) { this.y = 58; } this.x += this.speed * dt; } // Collision case, Player will reset and lose one life if (player.x >= this.x - 25 && player.x <= this.x + 25) { if (player.y >= this.y -25 && player.y <= this.y + 25){ player.reset(); lives.decrease(); } } }; // Now write your own player class // This class requires an update(), render() and // a handleInput() method. var Player = function() { gameObj.call(this); this.sprite = 'images/char-boy.png'; this.x = 200; this.y = 400; this.score = 0; }; // Falls onto gameObj for render property Player.prototype = Object.create(gameObj.prototype); Player.prototype.constructor = Player; Player.prototype.update = function(dt){ if (this.downKey === 'left' && this.x > 0){ this.x -= TILE_WIDTH; } else if(this.downKey === 'right' && this.x != 402){ this.x += TILE_WIDTH; } else if(this.downKey === 'up'){ this.y -= TILE_HEIGHT; } else if(this.downKey === 'down' && this.y != 400){ this.y += TILE_HEIGHT; } this.downKey = null; // If player hits water, life will decrease and will respawn if (this.y < 25){ this.reset(); lives.decrease(); } }; // reset player sprite when hit by bug or out of bounds Player.prototype.reset = function() { this.x = 200; this.y = 400; }; Player.prototype.handleInput = function(e) { this.downKey = e; }; // Creates Gems var Gem = function() { gameObj.call(this); // chooses random gem image to use this.sprite = GEM_IMAGES[Math.floor(Math.random() * 3)]; // generate random position for gem to spawn this.x = XPOS[Math.floor(Math.random() * 5)]; this.y = YPOS[Math.floor(Math.random() * 3)]; }; // fall back on gameObj for render function and make the constructor Gem Gem.prototype = Object.create(gameObj.prototype); Gem.prototype.constructor = Gem; Gem.prototype.update = function(){ // Gem collision mechanic and respawn if (player.x == this.x && player.y == this.y){ this.sprite = GEM_IMAGES[Math.floor(Math.random() * 3)]; this.x = XPOS[Math.floor(Math.random() * 5)]; this.y = YPOS[Math.floor(Math.random() * 3)]; player.score += 100; } }; var Lives = function() { gameObj.call(this); this.sprite = 'images/Heart.png'; this.lives = 5; }; Lives.prototype = Object.create(gameObj.prototype); Lives.prototype.constructor = Lives; // Render life points Lives.prototype.render = function(){ var x = 455; for (var i = 0; i < this.lives; i++) { ctx.drawImage(Resources.get(this.sprite), x, -15, 50, 75); x -= 50; } }; // Life point system Lives.prototype.decrease = function() { if (this.lives > 1) { this.lives -= 1; } else { GAME_OVER = true; } }; // HELPER FUNCTIONS // Draws Score Text onto screen function drawText() { ctx.fillText('score: ' + player.score, 0, 40); ctx.fillStyle = "black"; } // Reset Button changes states back to init state function reset() { GAME_OVER = false; player.score = 0; player.reset(); lives.lives = 5; ctx.clearRect(0, 0, 505, 716); drawText(); } // Now instantiate your objects. // Place all enemy objects in an array called allEnemies // Place the player object in a variable called player var gem = new Gem(); var lives = new Lives(); var allEnemies = []; var numEnemies = 6; for (var i = 0; i < numEnemies; i++){ allEnemies.push(new Enemy()); } var player = new Player(); // This listens for key presses and sends the keys to your // Player.handleInput() method. You don't need to modify this. document.addEventListener('keyup', function(e) { var allowedKeys = { 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; player.handleInput(allowedKeys[e.keyCode]); });
true
f9269981c1db22a7bc898307996dbb2ada2a687e
JavaScript
ShiShiXu/nodejs
/stream/pipe/pipe.js
UTF-8
1,034
3.109375
3
[]
no_license
/** * Created by KidSirZ4i on 2016/5/5. */ //加载fs模块 var fs = require("fs"); // 创建一个可读流 var readerStream = fs.createReadStream(__dirname+'/from.txt'); // 创建一个可写流 var writerStream = fs.createWriteStream(__dirname+'/to.txt'); // 管道读写操作 // 读取 from.txt 文件内容,并将内容写入到 to.txt 文件中 readerStream.pipe(writerStream); console.log("程序执行完毕"); //管道流 (管道流其实就是从一个文件读出然后写入另一个文件,实质就是复制) //管道提供了一个输出流到输入流的机制。通常我们用于从一个流中获取数据并将数据传递到另外一个流中。 /* 我们把文件比作装水的桶,而水就是文件里的内容。 我们用一根管子(pipe)连接两个桶使得水从一个桶流入另一个桶,这样就慢慢的实现了大文件的复制过程。 以下实例我们通过读取一个文件内容并将内容写入到另外一个文件中。 设置 input.txt 文件内容如下: */
true
b33878685d57d87f71b6914918efa6df04029510
JavaScript
Qazzian/tasklist
/server/lib/util.js
UTF-8
724
2.9375
3
[]
no_license
var _ = require('lodash'); module.exports = { /** * Check that all the keys in the first object (testobj) are defined in the second object (authorityObj). * Does not look at inherited attributes of either object. * * @param testObj - the object that needs to be checked. * @param authorityObj - The objct that defines the list of valid keys. * @return true if all the keys in testObj are also defined in authorityObj. * @return false if any key in testObj is not defined in authorityObj. */ validateKeys: function(testObj, authorityObj){ var result = true; testObj.keys().forEach(function(keyName){ if (!authorityObj.hasOwnProperty(keyName)) { result = false; } }); return result; } }
true
820af2f71858c57b22b0e6c12594f1b80e350873
JavaScript
jmedina16/SMH_API_APPS
/apps/scripts/lib/js/kmc1common.js
UTF-8
2,386
2.53125
3
[]
no_license
// cookie functions function getCookie (name) { var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) return getCookieVal (j); i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return null; } function getCookieVal (offset) { var endstr = document.cookie.indexOf (";", offset); if (endstr == -1) endstr = document.cookie.length; return unescape(document.cookie.substring(offset, endstr)); } function setCookie (name,value,expiry_in_seconds,path,domain,secure) { if ( expiry_in_seconds ) { // set time, it's in milliseconds var today = new Date(); today.setTime( today.getTime() ); var expires = new Date( today.getTime() + (expiry_in_seconds*1000) ); // milliseconds } else { expires = null; } document.cookie = name + "=" + escape (value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : ""); } function deleteCookie (name,path,domain) { if (getCookie(name)) { cookie_name = "" + document.cookie; setCookie ( name , "" , 0 , path , domain , "" ); } } function empty(str) { return (str==null || str == "" ); } function createEmbedCode ( src , div_id , width , height , flashvars_string ) { } /* copy to clipboard */ function copyToClipboard(inElement){ //var inElement = document.getElementById(inElement); inElement.select(); if (inElement.createTextRange) { var range = inElement.createTextRange(); if (range) range.execCommand('Copy'); } else { var flashcopier = 'flashcopier'; if(!document.getElementById(flashcopier)) //jQuery("body").log("body").append("<div id='flashcopier'></div>"); jQuery("body").append("<div id='flashcopier'></div>"); document.getElementById(flashcopier).innerHTML = ''; var divinfo = '<embed src="/lib/flash/_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>'; document.getElementById(flashcopier).innerHTML = divinfo; } };
true
44366bbf3cfa8692bbb940574ffe5be5d70af4de
JavaScript
goldsmith/diff-eq-grapher
/graph.js
UTF-8
3,116
3.3125
3
[]
no_license
//http://staff.washington.edu/grigg/ scale = 50 function Point (x, y) { this.x = x this.y = y } function DrawLine(point1, point2, color) { ctx.strokeStyle = color ctx.beginPath() ctx.moveTo(point1.x, point1.y) ctx.lineTo(point2.x, point2.y) if (color === "purple") { ctx.lineWidth=3.0 ctx.stroke() ctx.lineWidth=1.0 } else { ctx.stroke() } } function DrawPoint (point, r) { ctx.beginPath() ctx.arc(point.x, point.y, r, 0, Math.PI*2, true) ctx.closePath() ctx.fill() } function DrawWithSlope(point, slopeFunction, n) { //draw a line with length n centered around point //convert javascript points to real points real = new realPoint(point) //calculate stuff m = slopeFunction(real.x/scale, real.y/scale) deltax = n/(Math.sqrt(1 + Math.pow(m, 2))) newRealUp = new Point(real.x + deltax, real.y + m*deltax) newRealDown = new Point(real.x - deltax, real.y - m*deltax) //convert back to javascript points up = new fakePoint(newRealUp) down = new fakePoint(newRealDown) //DrawPoint(point, 1) DrawLine(up, down, 'black') } function DrawFromSlope(point, slopeFunction, stepSize) { //draw a line from point with slope DrawPoint(point, 1.5) p0 = new realPoint(point) x1 = p0.x + stepSize y1 = p0.y + stepSize*slopeFunction(p0.x/scale, p0.y/scale) p1 = new fakePoint(new Point(x1, y1)) DrawLine(point, p1, 'blue') return p1 } function realPoint(point) { return new Point(point.x-context.width/2, context.height/2-point.y) } function fakePoint(point) { return new Point(point.x+context.width/2, context.height/2-point.y) } function DrawDirectionField(n, slopeFunction) { for (var x=0; x<context.width; x+=10) { for (var y=0; y<context.height; y+=10) { DrawWithSlope(new Point(x, y), slopeFunction, n) } } } function EulerApprox(y0, slopeFunction, stepSize) { point = new Point(context.width/2, context.height/2 - y0) left = new Point(context.width/2, context.height/2 - y0) for (var x=0; x<context.width/2; x+=stepSize) { point = new DrawFromSlope(point, slopeFunction, stepSize) left = new DrawFromSlope(left, slopeFunction, -stepSize) } // for (var x=context.width/2; x<context.width; x+=stepSize) { // point = new DrawFromSlope(point, slopeFunction, stepSize) // } } function DrawAxes(n) { DrawLine(new Point(0, context.height/2), new Point(context.width, context.height/2), 'red') DrawLine(new Point(context.width/2, 0), new Point(context.width/2, context.height), 'red') DrawTickMarks(n) } function DrawTickMarks(n) { for (var x=0; x<context.width/2; x+=n) { DrawLine(new Point(context.width/2 + x, context.height/2-5), new Point(context.width/2 + x, context.height/2+5), 'purple') DrawLine(new Point(context.width/2 - x, context.height/2-5), new Point(context.width/2 - x, context.height/2+5), 'purple') DrawLine(new Point(context.width/2 - 5, context.height/2-x), new Point(context.width/2 + 5, context.height/2-x), 'purple') DrawLine(new Point(context.width/2 - 5, context.height/2+x), new Point(context.width/2 + 5, context.height/2+x), 'purple') } } function slopeFunc(x, y) { return x*(1-x)//temporary should be changed }
true
a87786c96236e27c1568ed75f8eaed4321d3375f
JavaScript
carlosprointersl/Preventa
/PreventaDroid/Resources/ui/common/views/Informes/Tables/ClientsData.js
UTF-8
2,792
2.578125
3
[ "Apache-2.0" ]
permissive
/** * @fileOverview En este archivo se crean las filas para la tabla de clientes. Estas filas contienen los datos relacionados con los clientes editados. * * @author <a href="mailto:[email protected]">Juan Carlos Matilla</a> * @version 1.0 */ /** * Consulta los clientes editados, según los parámetros, y retorna una "sección" válida para una tabla. * @class * @param {Date} start La fecha de inicio. * @param {Date} end La fecha de fin. * @return Ti.UI.TableViewSection */ function ClientsData(start, end) { /** * La varible "Global". * @private * @type Namespace */ var Global = require('/global/class/ReturnGlobal')(); /** * Genera una fila para este tipo de dato. * @private * @type Function */ var row = require(Global.Path.VIEW + 'Informes/Tables/Rows/ClientsRow'); /** * El controlador de los "Clientes". * @private * @type Controller */ //var clients = new Global.Controller.Clientes("nothing"); /** * El modelo de la tabla "Clientes". * @private * @type Model */ var model = new Global.Model.ClientesSend(); /** * La query para el WHERE de la consulta de los clientes. * @private * @type String */ var where = (function() { var dateStart = start != null ? "FechaCambio >= '" + Global.Functions.dateTimeSQliteFormat(start) + "'" : ""; var dateEnd = end != null ? (start != null ? " AND " : "") + "FechaCambio <= '" + Global.Functions.dateTimeSQliteFormat(end) + "'" : ""; var send = Global.Parameters.Configuracion.getMostrarEnviados() == "N" ? (start != null || end != null ? " AND " : "") + "send = 0" : ""; // Ti.API.info(dateStart != "" || dateEnd != "" || send != "" ? "WHERE " + dateStart + dateEnd + send : ""); return dateStart != "" || dateEnd != "" || send != "" ? "WHERE " + dateStart + dateEnd + send : ""; })(); /** * Recuperamos todos los clientes. * @private * @type Object[] */ var clients = model.select(where + " ORDER BY FechaCambio DESC"); //Ti.API.info("****************************** WHERE *******************************\n" + where); /** * La sección principal. * @private * @type Ti.UI.TableViewSection */ var section = Ti.UI.createTableViewSection(); //Añadimos la cabecera de la sección. section.add(row('title')); //Recorremos todos los clientes, si hay. if(clients.length > 0) { for (var i=0; i < clients.length; i++) { section.add(row(clients[i])); }; section.enabled = true; } else { section.add(row(null)); section.enabled = false; }; return section; }; module.exports = ClientsData;
true
3e21277e751d4d917ae728415ab773f512a95479
JavaScript
justBboy/tictactoe-android
/js/index.js
UTF-8
2,909
3.484375
3
[]
no_license
var Game = { huPlayer : "O", aiPlayer : "X", winCombos : [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [6, 4, 2] ], cells : document.querySelectorAll(".cell"), init: function(){ document.querySelector(".endgame").style.display = "none"; this.origBoard = Array.from(Array(9).keys()); for(var i=0; i<this.cells.length; i++){ this.cells[i].innerText = ""; this.cells[i].style.removeProperty('background-color'); this.turnClickHandler = this.turnClick.bind(this) this.cells[i].addEventListener("click", this.turnClickHandler, false) } }, turnClick : function(ev){ if(typeof this.origBoard[ev.target.id] == "number"){ this.turn(ev.target.id, this.huPlayer); if (!this.checkTie()) this.turn(this.bestSpot(), this.aiPlayer); } }, turn : function(squareId, player){ this.origBoard[squareId] = player; console.log(this.origBoard); document.getElementById(squareId).innerText = player; var gameWon = this.checkWin(this.origBoard, player); if (gameWon) this.gameOver(gameWon) }, checkWin: function(board, player){ var plays = board.reduce((a, e, i) => (e===player) ? a.concat(i) : a, []) var gameWon = null for (var [index, win] of this.winCombos.entries()){ if (win.every(elem => plays.indexOf(elem) > -1)){ gameWon = {index: index, player: player} break; } } return gameWon; }, gameOver: function(gameWon){ for (var index of this.winCombos[gameWon.index]){ document.getElementById(index).style.backgroundColor = gameWon.player == this.huPlayer ? "blue" : "red"; } for (var i=0; i<this.cells.length; i++){ this.cells[i].removeEventListener("click", this.turnClickHandler, false); } this.declareWinner(gameWon.player == this.huPlayer ? "You win" : "You Lose"); }, declareWinner: function(who){ document.querySelector(".endgame").style.display = "block"; document.querySelector(".endgame .text").innerText = who; }, emptySquares: function(){ return this.origBoard.filter(s => typeof s == "number"); }, bestSpot: function(){ return this.emptySquares()[0]; }, checkTie: function(){ if(this.emptySquares().length==0){ for(var i=0; i< this.cells.length; i++){ this.cells[i].style.backgroundColor = "green"; this.cells[i].removeEventListener('click', this.turnClickHandler, false); } declareWinner("Tie Game"); return true; } return false; } } Game.init();
true
4099ce680534a9bc90a27c5adfd3d280f9d5b0ae
JavaScript
amituuush/cats
/src/components/CardContainer/CardContainer.js
UTF-8
3,339
2.640625
3
[]
no_license
import React, { Component, PropTypes } from 'react'; import Card from '../Card/Card'; import './card-container.scss'; class CardContainer extends Component { constructor(props) { super(props); this.handleSortedChange = this.handleSortedChange.bind(this); } handleSortedChange(e) { this.props.sortCards(e.target.value); } render() { let cards; if (this.props.sorted === 'default') { cards = this.props.catsAndFacts.map(catAndFact => { return ( <Card key={catAndFact.id} id={catAndFact.id} url={catAndFact.url} fact={catAndFact.fact} deleteCard={this.props.deleteCard} userInput={this.props.userInput} /> ); }); } else if (this.props.sorted === 'fact-length-ascend') { let sortedCards = this.props.catsAndFacts.sort((a, b) => { return a.fact.length - b.fact.length; }); cards = sortedCards.map(catAndFact => { return ( <Card key={catAndFact.id} id={catAndFact.id} url={catAndFact.url} fact={catAndFact.fact} deleteCard={this.props.deleteCard} userInput={this.props.userInput} /> ); }); } else if (this.props.sorted === 'fact-length-descend') { let sortedCards = this.props.catsAndFacts.sort((a, b) => { return b.fact.length - a.fact.length; }); cards = sortedCards.map(catAndFact => { return ( <Card key={catAndFact.id} id={catAndFact.id} url={catAndFact.url} fact={catAndFact.fact} deleteCard={this.props.deleteCard} userInput={this.props.userInput} /> ); }); } else if (this.props.sorted === 'alphabetical') { let sortedCards = this.props.catsAndFacts.sort((a, b) => { if(a.fact < b.fact){ return -1; } else if(a.fact > b.fact) {return 1; } return 0; }); cards = sortedCards.map(catAndFact => { return ( <Card key={catAndFact.id} id={catAndFact.id} url={catAndFact.url} fact={catAndFact.fact} deleteCard={this.props.deleteCard} userInput={this.props.userInput} /> ); }) } return ( <div> <form> <label>Sort by:</label> <select name="sort" onChange={this.handleSortedChange} value={this.props.sorted || 'default'} className="sort-select"> <option value="default">Default</option> <option value="fact-length-ascend">Fact Length - Ascending</option> <option value="fact-length-descend">Fact Length - Descending</option> <option value="alphabetical">Alphabetical</option> </select> <br /> </form> <div className="card-container-container"> {cards} </div> </div> ); } }; CardContainer.propTypes = { catsAndFacts: React.PropTypes.arrayOf(React.PropTypes.shape({ url: React.PropTypes.string, fact: React.PropTypes.string, id: React.PropTypes.string, })), sorted: React.PropTypes.string, deleteCard: React.PropTypes.func, sortCards: React.PropTypes.func, userInput: React.PropTypes.func }; export default CardContainer;
true
c0b74269d9d15481ca9f00ddcdd373a4079b3928
JavaScript
Coder2100/NodeJS-Notes
/node_file_upload.js
UTF-8
2,916
3.375
3
[]
no_license
/*Node.js Upload Files There is a very good module for working with file uploads, called "Formidable". The Formidable module can be downloaded and installed using NPM: //npm install formidable */ // usage /* var formidable = require('formidable'); // steps to use the package and successfully upload file //Step 1: Create an Upload Form //Create a Node.js file that writes an HTML form, with an upload field: var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<form action="fileupload" method="post" enctype="multipart/form-data">'); res.write('<input type="file" name="filetoupload"><br>'); res.write('<input type="submit">'); res.write('</form>'); return res.end(); }).listen(8000); */ /*Step 2: Parse the Uploaded File Include the Formidable module to be able to parse the uploaded file once it reaches the server. When the file is uploaded and parsed, it gets placed on a temporary folder on your computer.*/ /* var http = require('http'); var formidable = require('formidable'); http.createServer(function (req, res) { if (req.url == '/fileupload') { var form = new formidable.IncomingForm(); form.parse(req, function (err, fields, files) { res.write('File uploaded'); res.end(); }); } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<form action="fileupload" method="post" enctype="multipart/form-data">'); res.write('<input type="file" name="filetoupload"><br>'); res.write('<input type="submit">'); res.write('</form>'); return res.end(); } }).listen(8080); */ /*Step 3: Save the File When a file is successfully uploaded to the server, it is placed on a temporary folder. The path to this directory can be found in the "files" object, passed as the third argument in the parse() method's callback function. To move the file to the folder of your choice, use the File System module, and rename the file:*/ var http = require('http'); var formidable = require('formidable'); var fs = require('fs'); http.createServer(function (req, res) { if (req.url == '/fileupload') { var form = new formidable.IncomingForm(); form.parse(req, function (err, fields, files) { var oldpath = files.filetoupload.path; var newpath = 'C:/Users/Your Name/' + files.filetoupload.name; fs.rename(oldpath, newpath, function (err) { if (err) throw err; res.write('File uploaded and moved!'); res.end(); }); }); } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<form action="fileupload" method="post" enctype="multipart/form-data">'); res.write('<input type="file" name="filetoupload"><br>'); res.write('<input type="submit">'); res.write('</form>'); return res.end(); } }).listen(8000); //output: //file upload option and button
true
01c59ff1651029ca4959caa442ab2f2f5feb0061
JavaScript
arnondao/lapland_code
/resources/js/reducers/videos.js
UTF-8
2,223
2.546875
3
[]
no_license
import { fromJS } from 'immutable'; import * as types from '../constants/actionTypes'; const videosInitialState = fromJS( [] ); export default function videos ( state = videosInitialState, action ) { switch ( action.type ) { case types.ADD_INLINE_VIDEO: return state.push( fromJS( { id: action.vimeoId, isPlaying: false, isReady: false, isTouched: false, shouldLoadPoster: false, isPosterLoaded: false } ) ); case types.LOAD_INLINE_VIDEO_POSTER: const loadIndex = state .findIndex( video => video.get( 'id' ) === action.vimeoId ); return state.setIn( [ loadIndex, 'shouldLoadPoster' ], true ); case types.SET_INLINE_VIDEO_POSTER_LOADED: const loadedIndex = state .findIndex( video => video.get( 'id' ) === action.vimeoId ); return state .setIn( [ loadedIndex, 'isPosterLoaded' ], true ) .setIn( [ loadedIndex, 'shouldLoadPoster' ], true ); case types.SET_INLINE_VIDEO_READY: const readyIndex = state .findIndex( video => video.get( 'id' ) === action.vimeoId ); return state.setIn( [ readyIndex, 'isReady' ], true ); case types.SET_INLINE_VIDEO_TOUCHED: const touchedIndex = state .findIndex( video => video.get( 'id' ) === action.vimeoId ); return state.setIn( [ touchedIndex, 'isTouched' ], action.touched ); case types.TOGGLE_PLAY_INLINE_VIDEO: return state.map( video => { if ( video.get( 'id' ) === action.vimeoId ) { const state = video .set( 'isPlaying', action.play ); if ( action.play ) { return state.set( 'isTouched', true ); } return state; } else if ( action.play ) { return video.set( 'isPlaying', false ); } return video; } ); default: return state; } }
true
f15bf46b38fa506a9105e417c565266e97762765
JavaScript
spinorial/react-basic
/src/js/Testing/test-store.js
UTF-8
1,538
2.90625
3
[]
no_license
import {createStore} from 'redux'; //TODO: Export these to a separate file that can be easily changed for different servers const baseURL = 'https://guidelines.joe:8890/'; const guidelinesURL = 'wp-json/guideline/filter/title=notitle'; const routeURL = baseURL + guidelinesURL; /* * Defualt State to be used in the reducer. * * */ const guidelinesInitialState = { route: routeURL, guidelines: [] } /* * Reducer. * Takes in state and an action, returns a new state based on the old. * Is a pure function */ const guidelinesReducer = (state = guidelinesInitialState, action) => { if(action.type=='UPDATE_GUIDELINES'){ return { ...state, guidelines: action.payload }; }; if(action.type=='SORT_GUIDELINES_BY_TITLE'){ //TODO: function to sort the guidelines by the title } if(action.type=='SORT_GUIDELINES_BY_AUTHOR'){ //TODO: function to sort the guidelines by the author } if(action.type=='SORT_GUIDELINES_BY_DATE'){ //TODO: function to sort the guidelines by the date } return state; } /* * Store. * The store is created using the reducer. * Using the store we can dispach actions and subscribe. * */ const guidelinesStore = createStore(guidelinesReducer); const subscription = guidelinesStore.subscribe(()=>{ console.log('guidelineStore ', guidelinesStore.getState()); }); guidelinesStore.dispatch({type:'UPDATE_GUIDELINES',payload:[{title:'something'},{title: 'else'},{title:'here'} ]}); guidelinesStore.dispatch({type:'UPDATE_GUIDELINES',payload:['a','b','c' ]});
true
875f595a5ddc41febf83e91dc143c7b28fe3758c
JavaScript
shaurya3007/shaurya07
/Slingshot.js
UTF-8
1,529
2.640625
3
[]
no_license
class Slingshot { constructor(b1, p2) { var options = {'bodyA':b1,'pointB': p2, 'stiffness': 0.04, 'length': 10}; this.sling = Constraint.create(options); World.add(myWorld, this.sling); this.sling1 = loadImage("sprites/sling1.png"); this.sling2 = loadImage("sprites/sling2.png"); this.sling3 = loadImage("sprites/sling3.png"); } fly() { this.sling.bodyA = null; } attach(body) { this.sling.bodyA = body; } display() { image(this.sling1, 200, 20); image(this.sling2, 170, 20); if(this.sling.bodyA) { strokeWeight(3); if(this.sling.bodyA.position.x < 230) { line(this.sling.bodyA.position.x -20, this.sling.bodyA.position.y, this.sling.pointB.x -10, this.sling.pointB.y); line(this.sling.bodyA.position.x -20, this.sling.bodyA.position.y, this.sling.pointB.x +30, this.sling.pointB.y); image(this.sling3, this.sling.bodyA.position.x - 25, this.sling.bodyA.position.y - 10, 7, 20); } else { line(this.sling.bodyA.position.x +20, this.sling.bodyA.position.y, this.sling.pointB.x -10, this.sling.pointB.y); line(this.sling.bodyA.position.x +20, this.sling.bodyA.position.y, this.sling.pointB.x +30, this.sling.pointB.y); image(this.sling3, this.sling.bodyA.position.x + 25, this.sling.bodyA.position.y - 10, 7, 20); } } } };
true
3aa4a8f0d5bf397f8faf1fc30261570bbf0dade3
JavaScript
jdoleary/SymptomCorrelator
/js/util.js
UTF-8
598
2.90625
3
[ "LicenseRef-scancode-unknown-license-reference", "CC0-1.0" ]
permissive
const util = { autoComplete: function autoComplete(input,list){ if(!input || input.length == 0){ return null; } const results = []; const inList = JSON.parse(JSON.stringify(list)); inList.sort(); for(var i = 0; i < inList.length; i++){ if(inList[i].startsWith(input)){ results.push(inList[i]); } } return results; }, formatMMDDYYYY: function formatMMDDYYYY(date){ return (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear(); } } module.exports = util;
true
aa03b8782054649374f3761f4be6af828430bd3a
JavaScript
greatgy/Code
/Proj-supergenius-life/Web/src/main/webapp/js/pages/comment-1.0.0.js
UTF-8
5,462
2.84375
3
[]
no_license
/**************************************************************************************** *天财评论为例: 评论回复是通过js—comment.js实现,该js会在页面加载完毕后,调用id以btncomment开头的元素,通过传入Echanel(板块finance)_oid(用户oid)_uid(详细财经uid)并通过异步方法, *将数据组织为html在指定区域中显示 * *详细: *1、这是一个加在jQuery原型上的插件,规定页面上连接标签,如果是以btncomment开头的话,点击后则会触发此插件功能 *2、触发连接后,将会触发ajax请求,向服务器发送的数据是连接的id值,形式为: <a id="btncommentfinance_${me.oid}_${bean.uid}"> *3、控制器为 CommentController ,控制器将解析出请求的板块枚举类型,用户的oid,以及评论对象的uid,处理完毕后将会转到apicomment.ftl页面 *4、apicomment.ftl组织填充数据后显示评论板块 *评论计数的即时显示功能: *var countervalue = $(this).attr("counterclass"); *vars.counter = $("."+countervalue); *即:当前连接将会有一个属性来标识计数的标签 */ /**************************************************************************************** * 赞 */ ;(function ($) { $.fn.prize = function(options) { $(this).blur(); var uid = $(this).attr("id"); var temp = $(this); var json = {}; json.href=href; var uri = base + "/ajax/prize/" + uid; $.get(getNoCachePath(uri), json, function(data){ if(data){ dataparams.prize = dataparams.prize + 1; prizePlusAjaxHandler(temp); }else{ dataparams.prize = dataparams.prize - 1; prizeMinusAjaxHandler(temp); } }); prizeBindEvent(); }; /** * 赞ajax处理 */ function prizePlusAjaxHandler(obj) { updatePrizeCount(obj, true); $(obj).children("img").each(function(){ //$(this).data("isprize", true); $(this).attr("data-isprize", true); prizeBindEvetEach(this); }); } /** * 取消赞ajax处理 */ function prizeMinusAjaxHandler(obj) { updatePrizeCount(obj, false); $(obj).children("img").each(function(){ //$(this).data("isprize",false); $(this).attr("data-isprize",false); prizeBindEvetEach(this); }); } })(jQuery); /** * 为赞的图标绑定事件 */ function prizeBindEvent(){ $("a[id^='btnprize'] img").each(function(){ prizeBindEvetEach(this); }); } /** * 为某个赞注册事件 * @param obj */ function prizeBindEvetEach(obj){ var isprize = $(obj).attr("data-isprize"); if(isprize == "true") { $(obj).attr("title", "取消赞"); if ($(obj).data("notcomment")){ $(obj).attr("src", baseimg + "/imgs/default/redheart.png"); } else { $(obj).attr("src", baseimg + "/imgs/default/zaned.png"); } }else{ if ($(obj).data("notcomment")){ $(obj).attr("src", baseimg + "/imgs/default/heart.png"); } else { $(obj).attr("src", baseimg + "/imgs/default/zan.png"); } $(obj).attr("title", "点击赞"); } } /** * 更新赞的数量 * @param obj * @param isprize */ function updatePrizeCount(obj, isprize){ var countstr = $(obj).children("span").html(); if (isprize) { $(obj).children("span").html(parseInt(countstr)+1); } else { $(obj).children("span").html(parseInt(countstr)-1); } } /******************************************************************************************** * 收藏 */ ;(function($){ $.fn.collect = function(options) { var defauts = { uid : "", collectClickHandler : defaultCollectClickHandler } var vars = $.extend({}, defauts, options); if ($(this).length >0 ) { vars.uid = $(this).attr("id").replace("btncollect", ""); vars.obj = this; $(this).bind("click", vars, vars.collectClickHandler); } } function defaultCollectClickHandler(e){ var vars = e.data; var json = {}; var uri = base + "/my/ajax/collect/" + vars.uid; $.get(getNoCachePath(uri), json, function(data){ console.log(data); if (data) { dataparams.collect = 1; collectPlusAjaxHandler(vars); } else { dataparams.collect = 0; collectMinusAjaxHandler(vars); } updateCollect(data); }); } })(jQuery); function collectMinusAjaxHandler(vars) { $(vars.obj).find(".liwaysimg02").attr("src", baseimg + "/imgs/default/collect.png"); $(vars.obj).data("iscollect", false); } function collectPlusAjaxHandler(vars) { $(vars.obj).find(".liwaysimg02").attr("src", baseimg + "/imgs/default/collects.png"); $(vars.obj).data("iscollect", true); } function updateCollect(isadd){ var collectcount = $("#articlecollectcount").html(); if(isadd){ $("#articlecollectcount").html(parseInt(collectcount)+1); }else{ $("#articlecollectcount").html(parseInt(collectcount)-1); } } $(function($){ $(".shareBox a[id^='btncollect']").each(function(){$(this).collect();}); }); function registerPraise(){ $(".reply a[id^='btnprize']").each(function(){$(this).prize()}); prizeBindEvent(); } /** * 解除点赞事件绑定 */ function unRegisterPraise(){ $(".reply a[id^='btnprize']").each(function(){ $(this).unbind("click"); }); } function collectBindEvet(){ $("a[id^='btncollect'] img").each(function(){ collectBindEvetEach(this); }); } /** * 为某个取消收藏注册事件 * @param obj */ function collectBindEvetEach(obj){ var iscollect = $(obj).data("iscollect"); if(iscollect) { $(obj).attr("src", baseimg + "/imgs/default/collects.png"); } else { $(obj).attr("src", baseimg + "/imgs/default/collect.png"); } }
true
4085491a916b073475a59669d822294ddcba0cd6
JavaScript
NBALAJI95/Jamakkol-Prasannam
/src/Components/supplementaryPlanets.js
UTF-8
1,999
2.546875
3
[]
no_license
const rahuKalam = { கதிரவன்: { day: 180, night: 84 }, மதி: { day: 36, night: 108 }, சேய்: { day: 154, night: 60 }, மால்: { day: 108, night: 180 }, பொன்: { day: 132, night: 36 }, புகர்: { day: 84, night: 154 }, மந்தன்: { day: 60, night: 132 } }; const mrthyu = { கதிரவன்: { day: 60, night: 312 }, மதி: { day: 36, night: 288 }, சேய்: { day: 12, night: 264 }, மால்: { day: 156, night: 240 }, பொன்: { day: 132, night: 216 }, புகர்: { day: 108, night: 192 }, மந்தன்: { day: 84, night: 336 } }; const yemakandam = { கதிரவன்: { day: 108, night: 12 }, மதி: { day: 84, night: 154 }, சேய்: { day: 60, night: 132 }, மால்: { day: 36, night: 108 }, பொன்: { day: 12, night: 84 }, புகர்: { day: 154, night: 60 }, மந்தன்: { day: 132, night: 36 } }; const mandhi = { கதிரவன்: { day: 156, night: 240 }, மதி: { day: 132, night: 216 }, சேய்: { day: 108, night: 192 }, மால்: { day: 84, night: 336 }, பொன்: { day: 60, night: 312 }, புகர்: { day: 36, night: 288 }, மந்தன்: { day: 12, night: 264 } }; export const supplementaryPlanets = (sunPos, choice, dayType, day) => { let result = 0; switch (choice) { case 'rahuKalam': result = (sunPos + rahuKalam[day][dayType]) % 360; break; case 'yemakandam': result = (sunPos + yemakandam[day][dayType]) % 360; break; case 'mrthyu': result = (sunPos + mrthyu[day][dayType]) % 360; break; case 'mandhi': result = (sunPos + mandhi[day][dayType]) % 360; break; } if (dayType === 'night') { result = (result + 180) % 360; } return result; };
true
ed0934f47af672e74282505d5a73f10c66c833fa
JavaScript
amwebexpert/grails-react-app
/client/app/containers/About/saga.js
UTF-8
1,059
2.75
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
/** * Gets the App About info from backend server */ import { call, put, takeLatest, delay } from 'redux-saga/effects'; import request from 'utils/request'; import { aboutInfoLoaded, aboutInfoLoadingError } from './actions'; import { LOAD_ABOUT_INFO } from './constants'; export function* getAboutInfo() { const requestURL = `http://localhost:8080/application/`; try { // Call our request helper (see 'utils/request') const aboutInfo = yield call(request, requestURL); yield delay(1000); yield put(aboutInfoLoaded(aboutInfo)); } catch (err) { yield put(aboutInfoLoadingError(err)); } } /** * Root saga manages watcher lifecycle */ export default function* aboutInfo() { // Watches for LOAD_ABOUT_INFO actions and calls getAboutInfo when one comes in. // By using `takeLatest` only the result of the latest API call is applied. // It returns task descriptor (just like fork) so we can continue execution // It will be cancelled automatically on component unmount yield takeLatest(LOAD_ABOUT_INFO, getAboutInfo); }
true
34d3193583bfa20587d1f3b129be09ee8bc63517
JavaScript
woodheadlucy/hangman
/src/components/WrongLetters/WrongLetters.js
UTF-8
800
2.96875
3
[]
no_license
import React, { Component } from 'react'; import './WrongLetters.css'; class WrongLetters extends Component { getWrongLetters() { const wrong = this.props.guessedLetters.filter(letter => { return !this.props.word.split('').includes(letter) }) return wrong } render() { return ( <div className="WrongLetters"> {this.getWrongLetters} </div> ); } } export default WrongLetters; //random choose a word //display the correctly guessed letters //underscores for missing letters //display the letters not yet guessed //let the user guess a letter (form) //check the letter is in the word //update guess state //repeat until the game is over //game over: word is guessed or out of guesses
true
a8fb144f6b0b61cf4fabcd0eb589c5e36e236496
JavaScript
dxc1995/shandiqikes.github.io
/No-delay-menu/js/megadropdown.js
UTF-8
3,317
2.6875
3
[ "MIT" ]
permissive
$(function(){ var sub=$('#sub'); var activeRow;//选中的行 var activeMenu;//选中的行对应的二级菜单 var timer;//setTimeout返回的计时器id var mouseInSub=false;//当前鼠标是否在子菜单里 sub.on('mouseenter',function(e){ mouseInSub=true; }).on('mouseleave',function(e){ mouseInSub=false; }); //创建数组,记录 var mouseTrack=[];//数组跟踪记录鼠标的位置 var moveHandler=function(e){//鼠标离开菜单时,需要对绑定在document上的mousemove事件解绑,以免影响页面中其他组件,所以将事件监听函数独立出来,方便后续解绑操作 mouseTrack.push({ x:e.pageX, y:e.pageY }); if(mouseTrack.length>3){ mouseTrack.shift(); } }; $('#test') .on('mouseenter',function(e){ //sub.removeClass('none'); $(document).bind('mousemove',moveHandler);//mousemove事件一般绑定在document上 }) .on('mouseleave',function(e){ sub.addClass('none');//鼠标移动到一级菜单时,二级菜单隐藏 if(activeRow){//鼠标离开一级菜单,如果存在激活的行,样式要去掉,并把变量置空 activeRow.removeClass('active'); activeRow=null; } if(activeMenu){ activeMenu.addClass('none'); activeMenu=null; } $(document).unbind('mousemove',moveHandler); }) .on('mouseenter','li',function(e){//一级菜单的列表项绑定事件 sub.removeClass('none');//鼠标移动到一级菜单时,二级菜单显示 if(!activeRow){//移过去没有激活的一级菜单 activeRow=$(e.target); activeRow.addClass('active'); activeMenu=$('#'+activeRow.data('id')); activeMenu.removeClass('none'); return; } //debounce:mouseenter频繁触发时,只执行最后一次 if(timer){ clearTimeout(timer); } console.log(mouseTrack) var currMousePos=mouseTrack[mouseTrack.length-1]; var leftCorner=mouseTrack[mouseTrack.length-2]; var delay=needDelay(sub,leftCorner,currMousePos);//是否需要延迟 if(delay){//如果在三角形内,需要延迟 timer=setTimeout(function(){ if(mouseInSub){ return; } activeRow.removeClass('active'); activeMenu.addClass('none'); activeRow=$(e.target); activeRow.addClass('active'); activeMenu=$('#'+activeRow.data('id')); activeMenu.removeClass('none'); timer=null;//事件触发时,如果计时器并没有执行,就把它清掉,这样能保证事件触发停止时,会执行最后一次,而其他的都会被忽略 },300); }else{ var prevActiveRow=activeRow; var prevActiveMenu=activeMenu; activeRow=$(e.target); activeMenu=$('#'+activeRow.data('id')); prevActiveRow.removeClass('active'); prevActiveMenu.addClass('none');//上一次二级菜单隐藏 activeRow.addClass('active'); activeMenu.removeClass('none');//上一次二级菜单显示 } }); });
true
06e13ca9c32c14e781e152e8f82c6425dd86407a
JavaScript
qq377677616/wc190528lvzhan
/ch_pc/js/typewriter.js
UTF-8
1,494
2.953125
3
[ "MIT" ]
permissive
$(function(){ var self;//当前文本 var text;//当前文本内容 var index=0;//下标 var speed=200;//打字速率 var typewriters=null;//定时打字器 var isCursor=false;//是否显示光标 var isEndCursor=true;//打字完毕后是否显示光标 var cursorStyle="#000";//光标颜色 function autoAdd(){ self.find("b").remove(); self.append(text.substr(index,1)); if(isCursor){self.append('<b style="border-color:'+cursorStyle+'"></b>');} index++; if(index>=text.length){ self.html(text); if(isCursor){self.append('<b style="border-color:'+cursorStyle+'"></b>');} clearInterval(typewriters); if(isEndCursor){self.find("b").addClass("end");} else{self.find("b").remove();} } } $.fn.extend({ typewriter:function(configure){ self=$(this);//当前文本 text=self.html();//当前文本内容 self.html(''); if(typeof(configure.speed)=="number"){speed=configure.speed;} if(typeof(configure.cursor)=="boolean"){isCursor=configure.cursor;} if(typeof(configure.endCursor)=="boolean"){isEndCursor=configure.endCursor;} if(configure.cursorCategory=="level"){self.addClass("level");} else if(configure.cursorCategory=="vertical"){self.removeClass("level");} if(configure.cursorStyle){cursorStyle=configure.cursorStyle;} typewriters=setInterval(autoAdd,speed); } }); });
true
668ea6b5453bbfad61330337dd17ed7bc3f8e026
JavaScript
chiel/scols
/index.js
UTF-8
4,847
2.78125
3
[ "MIT" ]
permissive
'use strict'; var getScrollTop = function() { return (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop; }; /** * SCols * * @param {Element} container * @param {Object} options * @param {Object} options.colSelector - Column selector * @param {Object} options.fromTop - Determine how far from the top of the viewport columns should stick */ var SCols = function(container, options) { if (!container) return; this.container = container; this.options = options || {}; if (!this.options.colSelector) { this.options.colSelector = '[data-scols-col]'; } if (this.options.fromTop === undefined) { this.options.fromTop = 0; } this.cols = this.container.querySelectorAll(this.options.colSelector); if (!this.cols.length) return; this.bound = { scroll: this.scroll.bind(this), position: this.position.bind(this) }; this.attach(); }; require('microevent').mixin(SCols); /** * Attach SCols behaviour to container */ SCols.prototype.attach = function() { if (this.attached) return; this.attached = true; this.initialRects = this.getColRects(); this.setContainerHeight(); window.addEventListener('scroll', this.bound.scroll); }; /** * */ SCols.prototype.detach = function() { if (!this.attached) return; this.attached = false; this.container.style.height = ''; for (var i = 0; i < this.cols.length; i++) { var col = this.cols[i]; col.style.position = ''; col.style.top = ''; col.style.left = ''; col.style.right = ''; col.style.width = ''; } window.removeEventListener('scroll', this.bound.scroll); }; /** * Get rects for all columns */ SCols.prototype.getColRects = function() { return [].map.call(this.cols, function(col) { return col.getBoundingClientRect(); }); }; /** * Get the tallest rect * * @param {Array} rects * * @return {Object} */ SCols.prototype.getTallestRect = function(rects) { var heights = [].map.call(rects, function(r) { return r.bottom - r.top; }); var tallest = { height: 0 }; for (var i = 0; i < heights.length; i++) { if (heights[i] > tallest.height) { tallest = { index: i, height: heights[i] }; } } return tallest; }; /** * Make sure container is as tall as the tallest column */ SCols.prototype.setContainerHeight = function() { var heights = [].map.call(this.getColRects(), function(r) { return r.bottom - r.top; }); var height = Math.max.apply(Math, heights); this.container.style.height = height + 'px'; }; /** * Fired on scroll */ SCols.prototype.scroll = function() { if (!this.rAFQueued) { requestAnimationFrame(this.bound.position); this.rAFQueued = true; } }; /** * Calculate column positions */ SCols.prototype.position = function() { this.rAFQueued = false; this.lastDirection = this.lastDirection || 'down'; var scrollTop = getScrollTop(); var direction = scrollTop === this.lastScrollTop ? this.lastDirection : (!this.lastScrollTop || scrollTop > this.lastScrollTop) ? 'down' : 'up'; var cr = this.container.getBoundingClientRect(); var rects = this.getColRects(); var tallest = this.getTallestRect(rects); var iW = window.innerWidth; var iH = window.innerHeight; var col, r, ir, pos, top; for (var i = 0; i < this.cols.length; i++) { if (i === tallest.index) continue; col = this.cols[i]; r = rects[i]; ir = this.initialRects[i]; pos = undefined; top = undefined; if (direction === this.lastDirection) { if (direction === 'down') { if (cr.top >= this.options.fromTop) { pos = 'absolute'; top = 0; } else if (r.top <= this.options.fromTop && r.height < iH) { pos = 'fixed'; top = this.options.fromTop; } else if (r.bottom <= iH) { pos = 'fixed'; top = iH - r.height; } } else if (direction === 'up') { if (r.top >= this.options.fromTop && cr.top < this.options.fromTop) { pos = 'fixed'; top = this.options.fromTop; } else if (r.top <= cr.top) { pos = 'absolute'; top = 0; } else { pos = 'absolute'; top = r.top - cr.top; } } } else { pos = 'absolute'; top = r.top - cr.top; } if (r.bottom >= cr.bottom && r.top <= this.options.fromTop) { pos = 'absolute'; top = cr.height - r.height; } if (pos !== undefined && top !== undefined) { col.style.position = pos; col.style.top = top + 'px'; if (pos === 'fixed') { col.style.left = ir.left + 'px'; col.style.right = 'auto'; col.style.width = (ir.right - ir.left) + 'px'; } else { col.style.left = ''; col.style.right = ''; col.style.width = ''; } } } col = this.cols[tallest.index]; col.style.position = 'absolute'; col.style.top = 0 + 'px'; this.lastDirection = direction; this.lastScrollTop = scrollTop; this.trigger('position'); }; module.exports = SCols;
true
d419df8f5e4fa01eb740c0f991620159d47bc0a0
JavaScript
Srkinator/BitVezbe
/bit/bit-web/Projekat Ajax week 5/js/single.js
UTF-8
1,238
2.8125
3
[]
no_license
var id = localStorage.getItem('key'); var singleShow = $.ajax({ url: 'http://api.tvmaze.com/shows/' + id, method: 'GET', data: { embed: ['seasons', 'cast'] } }); singleShow.done(e => { console.log(e); let title = $("<h1>"); let img = $("<img>"); let titleMovie = e.name; let imageLink = e.image.original; title.text(titleMovie); img.attr('src', imageLink); let season = $("<ul>"); let numberOfSeasons = e._embedded.seasons.length; e._embedded.seasons.forEach(function (element) { let seasonItem = $("<li>"); seasonItem.text(`Premiere date: ${element.premiereDate}`); season.append(seasonItem); }, this); let cast = $('<ul>'); e._embedded.cast.forEach(function (element) { let castItem = $("<li>"); castItem.text(`${element.character.name}`); cast.append(castItem); }, this); let summaryDiv = $('<div>'); let summary = e.summary; summaryDiv.append(summary); $('.display').append(summaryDiv); $('#seasons-number').append(numberOfSeasons); $('.seasons-div').append(season); $('.cast-div').append(cast); $('.display').prepend(title); $('.image-div').append(img); });
true
6857833acd570a79b870c7d65999af7127357f95
JavaScript
xxristoskk/curation-station-2
/bandmapV2/static/js/map.js
UTF-8
5,166
2.578125
3
[]
no_license
function closeNav() { $('#sideFeats').css('width', '0'); $('#map-container').css('left', '0'); $('#topnav').css('display','none'); } /* Using this in the future to utilize APIView // get geoJSON document.getElementById('geojson').onload = function {getGeoJson()}; let geojson; function getGeoJson() { fetch('/make-map') .then((response) => response.json()) .then((data) => { geojson=data; }); }; */ mapboxgl.accessToken = JSON.parse(document.getElementById('token').textContent).token; var initialZoom = 9; var initialCenter = JSON.parse(document.getElementById('center').textContent).center; // create an object to hold the initialization options for a mapboxGL map var initOptions = { container: 'map-container', // put the map in this container style: 'mapbox://styles/mapbox/dark-v10', // use this basemap center: initialCenter, // initial view center zoom: initialZoom, // initial view zoom level (0-18) } // create the new map var map = new mapboxgl.Map(initOptions); const geojson = JSON.parse(document.getElementById('geojson').textContent); // add zoom and rotation controls to the map. map.addControl(new mapboxgl.NavigationControl()); var circleRadius = ['step',['get','num_of_artists'],7,5,15,8,20,25,25,50,30,150,35]; // wait for the initial style to Load map.on('style.load', function() { map.addSource('local-map', { type: 'geojson', data: geojson, }); // let's make sure the source got added by logging the current map state to the console console.log(map.getStyle().sources); map.addLayer({ id: 'clusters', type: 'circle', source: 'local-map', filter: ['has', 'num_of_artists'], paint: { 'circle-radius': circleRadius, 'circle-color': '#536dfe', 'circle-opacity': 0.7, } }); map.addSource('feature-highlight', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } }); map.addLayer({ id: 'clusters-highlight', type: 'circle', source: 'feature-highlight', paint: { 'circle-radius': circleRadius, 'circle-color': '#8B2635', 'circle-opacity': 0.7, 'circle-stroke-color': '#536dfe', 'circle-stroke-width': 2 } }); // Create a popup, but don't add it to the map yet. var popup = new mapboxgl.Popup({ closeButton: false, closeOnClick: false, className: 'popup' }); map.on('click', 'clusters', function (e) { var features = map.queryRenderedFeatures(e.point, { layers: ['clusters'], }); let selectedFeat = e.features[0]; var artists = JSON.parse(selectedFeat.properties.artists); artist_html = ` <div class='row'> <div class='col s6 left'> <h4 class='header white-text'>${selectedFeat.properties.city}</h4> </div> <div class='col s6 right'> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a> </div> </div> <div class='divider'></div><br>` builder = (artist) => { artist_html += ` <div class='row valign-wrapper'> <div class='col s6'> <a href='${artist.bc_url}'>${artist.name}</a> </div> <div class='col s6'> <span class='right'>${artist.genre}</span> </div> </div> ` }; artists.forEach(builder); $('#artists').html(artist_html); $('#sideFeats').css('width', '300px'); $('#map-container').css('left', '300px'); }); // listen for the mouse moving over the map and react when the cursor is over our data map.on('mouseenter','clusters', function (e) { // query for the features under the mouse, but only in the lots layer var features = map.queryRenderedFeatures(e.point, { layers: ['clusters'], }); map.getCanvas().style.cursor = 'pointer'; // make the cursor a pointer var coordinates = features[0].geometry.coordinates.slice(); let selectedFeat = e.features[0]; let popup_html = ` <div class='popup-feature'> <div class='popup-header'> <h4>${selectedFeat.properties.city}</h4><span class='artist-count'>${selectedFeat.properties.num_of_artists} artists</span> </div> <div class='custom-content'> Most Popular Genres: </div> <div class='top-genres'><span class='primary'><em>${selectedFeat.properties.top_genres}</em></span></div> </div> `; map.getSource('feature-highlight').setData(selectedFeat); popup.setLngLat(coordinates).setHTML(popup_html).addTo(map); }); map.on('mouseleave', 'clusters', function () { map.getCanvas().style.cursor = ''; popup.remove(); // reset the highlight source to an empty featurecollection map.getSource('feature-highlight').setData({ type: 'FeatureCollection', features: [] }); }); });
true
4f68459fd7ce9182d170d97d79b1c1867936cd9d
JavaScript
fndos/Control-de-Visitas-Web
/educate/accounts/static/accounts/js/color.js
UTF-8
432
2.6875
3
[ "MIT" ]
permissive
$(document).ready(function () { changeColor(); console.log("Running Fundación Educate & Colors...") }); $(document).bind("DOMSubtreeModified", changeColor); function changeColor() { var colors = ['#fff5e0', '#f9ffbe', '#e1ffce', '#d7e8e6', '#fbe8ff'] var i = 0; $(".item").each(function() { $(this).css("background-color", colors[i++]); // increment here if(i == 5) i = 0; // reset the counter here }); }
true
89dd1fd8d09b4d5be19f19d613215b0b19e87369
JavaScript
juliakhryst/mongoDB_HW
/controllers/user.js
UTF-8
1,838
2.671875
3
[]
no_license
const User = require('../models/user'); const Article = require('../models/article'); module.exports = {createUser, getUser, updateUser, deleteUser,getUserArticles}; function createUser(req, res) { let newUser = new User({ firstName: req.body.firstName, lastName:req.body.lastName, role: req.body.role, nickname: req.body.nickname }); User.create(newUser, function(err,user) { if(err) { res.status(400).send(err); } else { console.log("Insert: " + newUser); res.status(200).send('User has been added sucesfully'); } }); } function updateUser(req, res) { User.findByIdAndUpdate(req.params.id, {$set: req.body}, function (err) { if (err) { res.status(400).send(err); } else { res.send('User was successfully updated.'); } }); } function getUser(req, res) { User.findById(req.params.id).lean().exec( function(err, user){ if(err) console.log(err); else { if (user.numberOfArticles > 0){ Article.find({owner: req.params.id}).lean().exec( function(err,articles){ user.articles = articles; res.status(200).send(user); }) } } }); } function deleteUser(req, res) { User.findByIdAndRemove(req.params.id, function (err,user) { if (err) { res.status(400).send(err); } else { Article.deleteMany({owner: user.id},function (err) { if (err) { res.status(400).send(err); } }); res.send('User was successfully deleted!'); } }) } function getUserArticles (req, res) { Article.find({owner: req.params.id},function(err, articles){ if(err){ res.status(400).send("This user does not have any articles"); } else { res.status(200).send(articles); } }); }
true
afaa5fbe8dfc2c5c225301b9c54809e8fd81fb37
JavaScript
JS00001/js-util
/lib/functions/hashString.js
UTF-8
278
2.515625
3
[]
no_license
'use strict' /** * Module Exports */ module.exports = hashString /** * @param {String} string * @param {String} digest */ function hashString(string, digest) { const crypto = require('crypto'); return crypto.createHash('sha256').update(string).digest(digest); }
true
80335a90e65bb6db031806ffec301385fe86ee40
JavaScript
IsseiMori/CMPS160
/Programming/Prog1/Prog1.js
UTF-8
5,112
2.796875
3
[]
no_license
var VSHADER_SOURCE = 'attribute vec4 a_Position;\n' + 'void main(){\n' + ' gl_Position = a_Position;\n' + '}\n'; var FSHADER_SOURCE = 'void main(){\n' + ' gl_FragColor = vec4(0.0,0.0,0.0,1.0);\n' + '}\n'; function main(){ var canvas = document.getElementById('webgl'); if(!canvas){ console.log("failed to retrive <canvas> element"); return; } var gl = getWebGLContext(canvas); if(!gl){ console.log("failed to get rendering context for WebGL"); return; } if(!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)){ console.log("Failed to initialize shaders"); return; } var indexBuffer = gl.createBuffer(); var verticesBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, verticesBuffer); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); var a_Position = gl.getAttribLocation(gl.program, 'a_Position'); makeCircle(canvas); canvas.onmousedown = function(ev){ click(ev, gl, canvas, a_Position); } gl.clearColor(0.5,0.5,0.5,1.0); gl.clear(gl.COLOR_BUFFER_BIT); //gl.drawArrays(gl.LINE_STRIP, 0, vertices.length / 3); } //make an array of 12 sided circle located at origin var circle = []; function makeCircle(canvas){ var r; var rad = Math.PI / 180.0; if(canvas.width < canvas.height) r = canvas.width * 0.05; else r = canvas.height * 0.05; for(i = 0; i < 36; i+=3){ circle[i] = 0.05 * Math.sin(30.0 * (i/3) * rad); circle[i+1] = 0; circle[i+2] = 0.05 * Math.cos(30 * (i/3) * rad); } } var prevAngle; var prevprevAngle; var vertices = []; //center point and 12 vertices -> pair of 39 vertices var prevPoint = []; var indices = []; function click(ev, gl, canvas, a_Position){ //convert canvas coordinate to webgl coordinate var x = ev.clientX; var y = ev.clientY; var rect = ev.target.getBoundingClientRect(); x = ((x - rect.left) - (canvas.width)/2)/(canvas.width/2); y = ((canvas.height)/2 - (y - rect.top))/(canvas.height/2); var circleRotateMatrix = new Matrix4(); var v3; var tmpPoints = []; var tmp = []; var angle; //move the circle to the clicked point and push vertices to vertices array if(prevAngle == null){ prevAngle = 0; angle = 0; }else{ //calculate the angle between current point and previous point angle = 180 / Math.PI * -Math.atan2(x - prevPoint[0], y - prevPoint[1]); //change the rotation of previous circle based on prevprevAngle and the current angle circleRotateMatrix.setRotate((angle + prevprevAngle) / 2.0 - prevAngle , 0, 0, 1); prevAngle = (angle + prevprevAngle) / 2.0; for(i = -36; i < 0; i+=3){ tmpPoints[0] = vertices[vertices.length + i] - vertices[vertices.length - 39]; tmpPoints[1] = vertices[vertices.length + i + 1] - vertices[vertices.length - 38]; tmpPoints[2] = vertices[vertices.length + i + 2] - vertices[vertices.length - 37]; v3 = new Vector3(tmpPoints); v3 = circleRotateMatrix.multiplyVector3(v3); tmp = new Float32Array(v3.elements); vertices[vertices.length + i] = tmp[0] + vertices[vertices.length - 39]; vertices[vertices.length + i + 1] = tmp[1] + vertices[vertices.length - 38]; vertices[vertices.length + i + 2] = tmp[2] + vertices[vertices.length - 37]; } } //store the ceter point into vertices vertices.push(x); vertices.push(y); vertices.push(0); //modify the previous angle circleRotateMatrix.setRotate(angle, 0, 0, 1); console.log(angle, prevAngle); for(i = 0; i < 36; i+=3){ tmpPoints[0] = circle[i]; tmpPoints[1] = circle[i+1]; tmpPoints[2] = circle[i+2]; v3 = new Vector3(tmpPoints); v3 = circleRotateMatrix.multiplyVector3(v3); tmp = new Float32Array(v3.elements); vertices.push(tmp[0]+x); vertices.push(tmp[1]+y); vertices.push(tmp[2]); } //make polygon indeces if(prevprevAngle != null){ for(i = 0; i < 11; i++){ indices.push(vertices.length / 3 - 26 + 14 + i); indices.push(vertices.length / 3 - 26 + 1 + i); indices.push(vertices.length / 3 - 26 + 1 + i); indices.push(vertices.length / 3 - 26 + 2 + i); indices.push(vertices.length / 3 - 26 + 2 + i); indices.push(vertices.length / 3 - 26 + 15 + i); indices.push(vertices.length / 3 - 26 + 15 + i); indices.push(vertices.length / 3 - 26 + 14 + i); } indices.push(vertices.length / 3 - 26 + 25); indices.push(vertices.length / 3 - 26 + 12); indices.push(vertices.length / 3 - 26 + 12); indices.push(vertices.length / 3 - 26 + 1); indices.push(vertices.length / 3 - 26 + 1); indices.push(vertices.length / 3 - 26 + 14); indices.push(vertices.length / 3 - 26 + 14); indices.push(vertices.length / 3 - 26 + 25); } //store the center point prevPoint[0] = x; prevPoint[1] = y; //store the angle prevprevAngle = prevAngle; prevAngle = angle; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint8Array(indices), gl.STATIC_DRAW); gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(a_Position); //console.log(vertices); //console.log(indices); gl.clearColor(0.5,0.5,0.5, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawElements(gl.LINES, indices.length, gl.UNSIGNED_BYTE, 0); }
true
e655cb5143cbea2de16104ebd56d0619ab271074
JavaScript
iaroslavnikitin/Codewars-Katas-1
/katas/javascript/string-transformer.js
UTF-8
791
3.84375
4
[]
no_license
function stringTransformer(str) { let arr = str.split(' '); let reversedArr = []; for(let i = arr.length - 1; i >= 0; i--){ reversedArr.push(arr[i]); } for(let i = 0; i < reversedArr.length; i++){ reversedArr[i] = reversedArr[i].split(''); } for(let i = 0; i < reversedArr.length; i++){ for(let j = 0; j < reversedArr[i].length; j++){ if(reversedArr[i][j] == reversedArr[i][j].toUpperCase()){ reversedArr[i][j] = reversedArr[i][j].toLowerCase(); } else { reversedArr[i][j] = reversedArr[i][j].toUpperCase(); } } } for (let i = 0; i < reversedArr.length; i++) { reversedArr[i] = reversedArr[i].join(''); } return reversedArr.join(' '); } console.log(stringTransformer('Example string'), 'STRING eXAMPLE');
true
c8d68c09749f4eb15022f62532af067ea20d0949
JavaScript
reneesarley/sudoku
/spec/game-spec.js
UTF-8
4,613
2.90625
3
[]
no_license
import {Game} from '../src/game'; describe ('Game', function() { let winningGame; let incompleteGameBoard; let twoRowGameBoard; let twoRowGameBoardFail; let oneRowGameBoard; let oneRowGameBoardFail; let testNewGame = new Game(); beforeEach(function() { winningGame = new Game(); winningGame.usersSolution = [ 4,2,6,5,7,1,3,9,8, 8,5,7,2,9,3,1,4,6, 1,3,9,4,6,8,2,7,5, 9,7,1,3,8,5,6,2,4, 5,4,3,7,2,6,8,1,9, 6,8,2,1,4,9,7,5,3, 7,9,4,6,3,2,5,8,1, 2,6,5,8,1,4,9,3,7, 3,1,8,9,5,7,4,6,2] winningGame.arrayToCheck = [1, 2, 3, 4, 5, 6, 7, 8, 9]; incompleteGameBoard = new Game(); incompleteGameBoard.gameBoard = [4,2,6,5,7,1,3,9,8, 8,5,7,2,9,3,1,4,6, 1,3,9,4,6,8,2,7,5, 9,7,1,3,8,5,6,2,4, 5,4,3,7,2,6,8,1,9, 6,8,2,1,4,9,7,5,3, 7,9,4,6,3,2,5,8,1, 2,6,5,8,1,4,9,3,7] twoRowGameBoard= new Game(); twoRowGameBoard.gameBoard = [4,2,6,5,7,1,3,9,8, 8,5,7,2,9,3,1,4,6] twoRowGameBoardFail= new Game(); twoRowGameBoardFail.gameBoard = [4,2,6,5,7,1,3,9,8, 8,5,7,2,9,3,1,4,8] oneRowGameBoard= new Game(); oneRowGameBoard.gameBoard = [4,2,6,5,7,1,3,9,8] oneRowGameBoardFail= new Game(); oneRowGameBoardFail.gameBoard = [4,2,6,5,7,1,3,9,9] }); // it ('should test if set numbers does not contain any duplicates', function() { // let failingArray = new Game(); // failingArray.arrayToCheck = [9, 9, 1]; // let passingArray = new Game(); // passingArray.arrayToCheck = [9, 8, 7, 6]; // expect(failingArray.arrayCheck()).toEqual(false); // expect(passingArray.arrayCheck()).toEqual(true); // }); // // it ('should cycle through each row until it finds a failing combo of numbers', function() { // var result = winningGame.getAllRows(winningGame.usersSolution); // expect (result).toEqual(true); // // }); // // it ('should cycle through each column until it finds a failing combo of numbers ', function() { // var result = winningGame.checkAllColumns(winningGame.usersSolution); // expect (result).toEqual(true); // }); // it ('should cycle through each column until it finds a failing combo of numbers, even if gameboard/solution isnt complete', function() { // var result = incompleteGameBoard.checkAllColumns(incompleteGameBoard.gameBoard); // let failResult = twoRowGameBoardFail.checkAllColumns(twoRowGameBoardFail.gameBoard); // expect (result).toEqual(true); // expect(failResult).toEqual(false); // }); // // it ('should check each box for a failing combo of numbers', function() { // var result = winningGame.getAllBoxes(winningGame.usersSolution); // let failResult = twoRowGameBoardFail.getAllBoxes(twoRowGameBoardFail.gameBoard); // expect (result).toEqual(true); // expect (failResult).toEqual(false); // }); // // it ('should check each box even if only 1 row of the box are filled out', function() { // var result = oneRowGameBoard.getAllBoxes(oneRowGameBoard.gameBoard); // expect (result).toEqual(true); // var resultFail = oneRowGameBoardFail.getAllBoxes(oneRowGameBoardFail.gameBoard); // expect (resultFail).toEqual(false); // }); // // it ('should check each box even if only 2 row of the box are filled out', function() { // var result = twoRowGameBoard.getAllBoxes(twoRowGameBoard.gameBoard); // expect (result).toEqual(true); // var resultFail = twoRowGameBoardFail.getAllBoxes(twoRowGameBoardFail.gameBoard); // expect (resultFail).toEqual(false); // }); // // it ('should test array to see if all rows, columns and boxes are 1-9 with no duplicates', function(){ // let result = winningGame.solution(winningGame.usersSolution); // expect(result).toEqual(true); // }); it ('should create an array of 81 numbers, with no duplicates in every row and column', function() { testNewGame.makeGameBoard(); // expect (testNewGame.gameBoard.length).toEqual(81); expect (testNewGame.solution(testNewGame.gameBoard)).toEqual(true); }); // });
true
91d8e007e40d00a9dfe654a8c1f77cf37c8fe2d7
JavaScript
leyi0924/Multi-User-Social-Web
/Backend/spec/articles.spec.js
UTF-8
3,317
2.703125
3
[]
no_license
/* * Test suite for articles */ const fetch = require('isomorphic-fetch'); const url = path => `https://protected-earth-75479.herokuapp.com${path}` const Article = require('../src/model.js').Article describe('Validate Article functionality', () => { it('GET /articles (should return at least 5 articles if test user is logged in user)', (done) => { myHeader = new Headers(); myHeader.append('Content-Type','application/json') fetch(url('/login'),{ method:"POST", headers: myHeader, body: JSON.stringify({ username: "John", password: "123456" }), credentials: "include" }).then(r=>{ const cookie = r.headers._headers['set-cookie'] myHeader.append('cookie',cookie) fetch(url('/articles'), { method: "GET", headers: myHeader, credentials: "include" }).then(r=>r.json()).then(r=>{ expect(r.articles.length).toBeGreaterThan(4); fetch(url('/logout'), { method: "PUT", headers: myHeader, credentials: "include" }).then(r=>{ done() }) }) }) }); it('GET /articles/id (where id is a valid or invalid article id)', (done) => { myHeader = new Headers(); myHeader.append('Content-Type','application/json') fetch(url('/login'),{ method:"POST", headers: myHeader, body: JSON.stringify({ username: "John", password: "123456" }), credentials: "include" }).then(r=>{ const cookie = r.headers._headers['set-cookie'] myHeader.append('cookie',cookie) fetch(url('/articles/1'), { method: "GET", headers: myHeader, credentials: "include" }).then(r=>r.json()).then(r=>{ expect(r.articles.length).toBe(1); expect(r.articles[0]._id).toBe(1); fetch(url('/articles/20'), { method: "GET", headers: myHeader, credentials: "include" }).then(r=>r.json()).then(r=>{ expect(r.articles.length).toBe(0); fetch(url('/logout'), { method: "PUT", headers: myHeader, credentials: "include" }).then(r=>{ done() }) }) }) }) }); it('POST /article (adding an article for logged in user returns list of articles with new article, validate list increased by one and contents of the new article)', (done) => { myHeader = new Headers(); myHeader.append('Content-Type','application/json') fetch(url('/login'),{ method:"POST", headers: myHeader, body: JSON.stringify({ username: "John", password: "123456" }), credentials: "include" }).then(r=>{ const cookie = r.headers._headers['set-cookie'] myHeader.append('cookie',cookie) Article.find().exec(function(err, items) { let originArticleNum=0 items.forEach(function(a) { originArticleNum += 1 }) fetch(url('/article'), { method: "POST", headers: myHeader, body: JSON.stringify({ text: "This is a new article." }), credentials: "include" }).then(r=>r.json()).then(r=>{ expect(r.articles.length).toBe(originArticleNum+1); let newArticle = r.articles.filter(x=>x.text === "This is a new article.") expect(newArticle.length).toBeGreaterThan(0) fetch(url('/logout'), { method: "PUT", headers: myHeader, credentials: "include" }).then(r=>{ done() }) }) }) }) }); });
true
5b7ae4a9c547b3b0d79ae6d24b98cce181cd4ea4
JavaScript
anguyenkn/py4web-vue
/grader/hw8grader/CSE_183_Spring_2020_Assignment_8_Submission_2/static/js/index.js
UTF-8
6,849
2.734375
3
[]
no_license
// This will be the object that will contain the Vue attributes // and be used to initialize it. let app = {}; // Given an empty app object, initializes it filling its attributes, // creates a Vue instance, and then initializes the Vue instance. let init = (app) => { // This is the Vue data. app.data = { posts: [], // See initialization. //is_any_post_in_edit_mode: false, }; app.index = (a) => { // Adds to the posts all the fields on which the UI relies. let i = 0; for (let p of a) { p._idx = i++; // TODO: Only make the user's own posts editable. p.editable = true; //user_email == p.email; TODO============== p.readonly = "readonly" p.edit = false; p.is_pending = false; p.error = false; p.original_content = p.content; // Content before an edit. p.server_content = p.content; // Content on the server. } return a; }; app.reindex = () => { // Adds to the posts all the fields on which the UI relies. let i = 0; for (let p of app.vue.posts) { p._idx = i++; } }; app.is_any_post_getting_edited = () => { let returnValue = false; for (let p of app.vue.posts) { //console.log(`NEEL edit value ${p.edit }`); if( p.edit == true) { return true; } } return returnValue; }; app.do_edit = (post_id) => { // Handler for button that starts the edit. // TODO: make sure that no OTHER post is being edited. // If so, do nothing. Otherwise, proceed as below. if(app.is_any_post_getting_edited() == false) { //console.log("NEEL OK to edit"); //console.log("NEEL OK to edit"); post_index = app.post_id_to_index(post_id); let p = app.vue.posts[post_index]; p.edit = (p.editable == true) ? true : false; //app.vue.is_any_post_in_edit_mode = p.edit; p.is_pending = false; } }; app.post_id_to_index = (post_id) => { let index = 0; for (p of app.vue.posts) { if(p.id == post_id) { return index; } index++; } return 0; }; app.is_any_post_getting_edited = () => { let returnValue = false; for (let p of app.vue.posts) { //console.log(`NEEL edit value ${p.edit }`); if( p.edit == true) { return true; } } return returnValue; }; app.do_cancel = (post_idx) => { app.repopulate_form(); } app.do_save = (post_id) => { //console.log(`Neel in do_save js row id ${post_id} `); post_index = app.post_id_to_index(post_id); let p = app.vue.posts[post_index]; axios.post(update_post_url, { post_id: p.id, content: p.content, title: p.title, //background_color: p.background_color, //rating: p.rating, }); app.repopulate_form(); }; app.set_stars = function (post_id, new_rating) { // Sets and sends to the server the number of stars. //console.log("NEEL in set starts"); //console.log(post_id); //console.log(new_rating); axios.post(set_star_url, { post_id: post_id, rating: new_rating, }); app.repopulate_form(); }; app.set_background = function (post_id, new_background) { //console.log("NEEL in set_background"); //console.log(new_background); axios.post(set_color_url, { post_id: post_id, background_color: new_background, }); app.repopulate_form(); }; app.add_post = () => { // TODO: this is the new post we are inserting. // You need to initialize it properly, completing below, and ... //console.log("Neel add_post called"); // We send the data to the server, from which we get the id. axios.post(add_post_url, { content: "", title: "", background_color:"has-background-yellow-neel", rating: 1, }) app.repopulate_form(); }; app.do_delete = (post_id) => { if(confirm("Delete?") == false) { return; } console.log("Neel do_delete called"); axios.post(delete_url, { post_id: post_id,}); app.repopulate_form(); }; app.upload_file = function (event,post_id) { //console.log("NEELLLLLLLLLLLLLL upload file handler"); // Reads the file. let input = event.target; let file = input.files[0]; //console.log("NEELLLLLLLLLLLLLL upload file handler"); //console.log(file); if (file) { let formData = new FormData(); formData.append('file', file); formData.set('post_id',post_id); axios.post(image_url, formData, {headers: {'Content-Type': 'multipart/form-data'}}) .then(function () { console.log("Uploaded"); }) .catch(function () { alert("Failed to upload file, please select valid image file to upload"); console.log("Failed to upload"); }); } }; // We form the dictionary of all methods, so we can assign them // to the Vue app in a single blo. app.methods = { do_edit: app.do_edit, do_cancel: app.do_cancel, do_save: app.do_save, add_post: app.add_post, do_delete: app.do_delete, set_stars: app.set_stars, set_background: app.set_background, upload_file: app.upload_file, }; app.repopulate_form = () => { axios.get(posts_url).then((result) => { //app.vue.posts = [] //if(result.data.posts.length > 0) { app.vue.posts = app.index(result.data.posts); } }) }; // This creates the Vue instance. app.vue = new Vue({ el: "#vue-target", data: app.data, methods: app.methods }); // And this initializes it. app.init = () => { // TODO: Load the posts from the server instead. // We set the posts. axios.get(posts_url).then((result) => { app.vue.posts = app.index(result.data.posts); //console.log(app.vue.posts ); }) }; // Call to the initializer. app.init(); }; // This takes the (empty) app object, and initializes it, // putting all the code i init(app);
true
0a76da9ab187f238e3f32f318d48245f6af4bbc1
JavaScript
haru-programming/coding_practice--2
/js/fixed-header.js
UTF-8
322
2.765625
3
[]
no_license
$(function () { //fvを超えたらスクロールでheaderに色を付ける var mainPos = $(".header").height(); $(window).scroll(function () { if ($(window).scrollTop() > mainPos) { $(".header__top").addClass("transform"); } else { $(".header__top").removeClass("transform"); } }); });
true