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
9d742bb1a973e8f849bb448350a22788ab3dd76b
JavaScript
codebot-caffeine/currency-conversion
/src/Components/SignUp/index.js
UTF-8
3,657
2.75
3
[]
no_license
import { Component } from "react"; import Header from "../Header"; import "./index.css"; class SignUp extends Component { state = { firstName: "", password: "", email: "", userData: [], errorMessage: "", }; componentDidUpdate() { this.storingInLocalStorage(); } storingInLocalStorage = () => { const { userData } = this.state; let userdata = JSON.stringify(userData); localStorage.setItem("data", userdata); }; handleEvent = (event) => { event.preventDefault(); const { firstName, password, email } = this.state; if (firstName === "" || password === "" || email === "") { this.setState({ errorMessage: "*All the fields are required" }); } const data = { name: firstName, password: password, email: email, }; const personalData = localStorage.getItem("data"); const parsedData = JSON.parse(personalData); const identifyUsername = parsedData.filter( (each) => each.name === firstName && each.email === email ); const identifyPassword = parsedData.filter( (each) => each.password === password ); const identifyMail = parsedData.filter((each) => each.email === email); if (identifyPassword.length > 0) { this.setState({ errorMessage: "*change password" }); } else if (identifyUsername.length > 0) { this.setState({ errorMessage: "*Username & email already taken" }); } else if (identifyMail.length > 0) { this.setState({ errorMessage: "*email already taken" }); } else if (firstName === "" || password === "" || email === "") { this.setState({ errorMessage: "*All the fields are required" }); } else { this.setState((prevState) => ({ userData: [...prevState.userData, data], })); this.setState({ errorMessage: "" }); } }; changeEmail = (e) => { this.setState({ email: e.target.value }); }; changeFirstName = (e) => { this.setState({ firstName: e.target.value }); }; changePassword = (e) => { this.setState({ password: e.target.value }); }; render() { const { errorMessage } = this.state; return ( <> <Header /> <div className="background"> <form className="form-container" onSubmit={this.handleEvent}> <h1 className="heading">Sign Up</h1> <div className="label-item"> <label htmlFor="Email" className="heading-1"> E-Mail </label> <input type="text" id="Email" placeholder="Type E-mail" onChange={this.changeEmail} /> </div> <div className="label-item"> <label htmlFor="FirstName" className="heading-1"> User Name </label> <input type="text" id="FirstName" placeholder="User name" onChange={this.changeFirstName} /> </div> <div className="label-item"> <label htmlFor="Password" className="heading-1"> Password </label> <input type="password" id="Password" placeholder="Type password" onChange={this.changePassword} /> </div> <button type="submit" className="submit-button"> Sign Up </button> <p className="error-message">{errorMessage}</p> </form> </div> </> ); } } export default SignUp;
true
539703a83fc90603ca715d9b8278d508c75ee855
JavaScript
flibbles/tw5-relink
/plugins/relink/js/filteroperators/references.js
UTF-8
1,211
2.765625
3
[ "BSD-3-Clause" ]
permissive
/*\ module-type: relinkfilteroperator Given a title as an operand, returns all non-shadow tiddlers that have any sort of updatable reference to it. `relink:backreferences[]]` `relink:references[]]` Returns all tiddlers that reference `fromTiddler` somewhere inside them. Input is ignored. Maybe it shouldn't do this. \*/ var LinkedList = $tw.utils.LinkedList; if (!LinkedList) { /* If the linked list isn't available, make a quick crappy version. */ LinkedList = function() {this.array=[];}; LinkedList.prototype.pushTop = function(array) { $tw.utils.pushTop(this.array, array); }; LinkedList.prototype.toArray = function() { return this.array; }; }; exports.backreferences = function(source,operator,options) { var results = new LinkedList(); source(function(tiddler,title) { results.pushTop(Object.keys(options.wiki.getTiddlerRelinkBackreferences(title,options))); }); return results.toArray(); }; exports.references = function(source,operator,options) { var results = new LinkedList(); source(function(tiddler,title) { var refs = options.wiki.getTiddlerRelinkReferences(title,options); if (refs) { results.pushTop(Object.keys(refs)); } }); return results.toArray(); };
true
0ca95bde4ecd710566a065745cdf4f6b2aafd036
JavaScript
ryan-sherman/SDD-Preferate
/WebDocs/js/group.js
UTF-8
998
3.0625
3
[ "Apache-2.0", "MIT" ]
permissive
//Javascript for make/edit group $(document).ready(function(){ //localhost;8080/createGroup?owner_id=_&group_name=Hello&members=1-2-3 //when the user clicks create group $("#CreateGroup").click(function(){ var friends = []; $.each($("input[name='friend']:checked"), function(){ friends.push($(this).val()); }); //alert("My friends are: " + friends.join(", ")); friend_str = friends.join("-"); friend_str += "-" + user_id; //make API call var createURL = "http://localhost:8080/createGroup?owner_id=" + encodeURIComponent(user_id) + "&group_name=" + encodeURIComponent($("#gname").val()) + "&members=" + encodeURIComponent(friend_str); $.ajax({ url: createURL }).then(function(data, status, jqxhr){ console.log(data); getGroups(); }); }); });
true
0528618eb89d32a95268d40bcdda27e3a680421e
JavaScript
letsgot/gitScrap
/gitScrapper/repo'sUrl.js
UTF-8
1,326
2.578125
3
[]
no_license
const request = require("request"); const cheerio = require("cheerio"); const fs = require("fs"); request("https://github.com/topics",callback); let gitTopics = []; function callback(err,res,html){ if(err){ console.log(err); } else{ const $ = cheerio.load(html); let topicAnchorTag = $(".no-underline.d-flex.flex-column.flex-justify-center"); // console.log(topicAnchorTag.length); for(let i= 0;i<topicAnchorTag.length;i++){ let topicUrl = "https://github.com" + $(topicAnchorTag[i]).attr("href"); gitTopics.push( { topicUrl : topicUrl, repo : [] } ) request(topicUrl,fetchRepoUrl.bind(this,i)) } } } let count = 0; function fetchRepoUrl(index,err,res,html){ count++; const $ = cheerio.load(html); // console.log(html); let repoAnchorTags = $(".wb-break-word.text-bold"); // console.log(repoAnchorTags.length); for(let i =0;i<repoAnchorTags.length;i++){ gitTopics[index].repo.push( { repoUrl : "https://github.com" + $(repoAnchorTags[i]).attr("href") } ) } if(count==3){ fs.writeFileSync("temp3.json",JSON.stringify(gitTopics)); } }
true
43b1ccfdb27df20b794fd9bae029e9a28ed83c08
JavaScript
thinkful-ei-emu/DSA-Searching-Nick
/App.js
UTF-8
3,351
3
3
[]
no_license
import React from 'react'; import './App.css'; class App extends React.Component { constructor() { super() this.state = { searchNum: 0, searchedFor: null, searchType: null, dataSet: [89, 30, 25, 32, 72, 70, 51, 42, 25, 24, 53, 55, 78, 50, 13, 40, 48, 32, 26, 2, 14, 33, 45, 72, 56, 44, 21, 88, 27, 68, 15, 62, 93, 98, 73, 28, 16, 46, 87, 28, 65, 38, 67, 16, 85, 63, 23, 69, 64, 91, 9, 70, 81, 27, 97, 82, 6, 88, 3, 7, 46, 13, 11, 64, 76, 31, 26, 38, 28, 13, 17, 69, 90, 1, 6, 7, 64, 43, 9, 73, 80, 98, 46, 27, 22, 87, 49, 83, 6, 39, 42, 51, 54, 84, 34, 53, 78, 40, 14, 5].sort((a, b) => a - b) } } indexOf(array, value) { //linear for (let i = 0; i < array.length; i++) { if (array[i] == value) { return i; } } return -1; } binarySearch = (array, value, start, end, numTimes = 0) => { numTimes++; start = start === undefined ? 0 : start; end = end === undefined ? array.length : end; if (start >= end) { return -1; } const index = Math.floor((start + end) / 2); const item = array[index]; // console.log(start, end); if (item == value) { return numTimes; } else if (item < value) { return this.binarySearch(array, value, index + 1, end, numTimes); } else if (item > value) { return this.binarySearch(array, value, start, index - 1, numTimes); } }; onSubmitLinear = ev => { ev.preventDefault(); const { lsearch } = ev.target; let value = parseInt(lsearch.value); this.setState({ searchType: 'Linear', searchedFor: value, }) let result = this.indexOf(this.state.dataSet, value); if(result === -1){ result = 'Number not found in data set'; } else { result = result + 1; } this.setState({ searchNum: result, }) lsearch.value = ''; } onSubmitBinary = ev => { ev.preventDefault(); const { bsearch } = ev.target; let value = parseInt(bsearch.value); this.setState({ searchType: 'Binary', searchedFor: value, }) let result = this.binarySearch(this.state.dataSet, value); console.log('result',result, typeof result) if(result === -1){ result = 'Number not found in data set'; } this.setState({ searchNum: result, }) bsearch.value = ''; } render() { return ( <> <form className='linear' onSubmit={this.onSubmitLinear}> <label htmlFor='lsearch'>Enter Number: </label> <input type='text' id='lsearch'></input> <button type='submit'>Linear Search</button> </form> <br></br> <form className='binary' onSubmit={this.onSubmitBinary}> <label htmlFor='bsearch'>Enter Number: </label> <input type='text' id='bsearch'></input> <button type='submit'>Binary Search</button> </form> <p>Times Searched: {this.state.searchNum} </p> {this.state.searchType && <p>Search method: {this.state.searchType}</p>} {this.state.searchedFor && <p>Searched for: {this.state.searchedFor}</p>} <p style={{maxWidth: '30em'}}><strong>Data Set: </strong> {this.state.dataSet.join(' ')}</p> </> ) } } export default App;
true
1a19cdbcfcef10107bd2bbfa310b23498c59f277
JavaScript
Aquamenthol/jscsshtmlstudy
/WebContent/script.js
UTF-8
268
3.296875
3
[]
no_license
const content = "최수현의 포트폴리오" const text = document.querySelector(".text") let index = 0; function typing(){ text.textContent += content[index++] if(index > content.length){ text.textContent = "" index = 0; } } setInterval(typing, 500)
true
119be0bb70e69479ded6a72061cf4f60a6d7dee1
JavaScript
ATHULKNAIR/30-Days-0f-code-MySolutions
/Day-9-Recursions.js
UTF-8
167
3.90625
4
[]
no_license
function factorial(n){ var fact =1 ; for(let i = n;i>0;i--){ // Get factorial of the number fact = fact * i } return fact; }
true
bfa076eff567840df4a12d6cca002ccfdb351d8f
JavaScript
mengyliu/turtle
/script.js
UTF-8
2,535
3.1875
3
[]
no_license
$(document).ready(function() { console.log( "ready!" ); init() }); var color = '#FF0000' function init() { var paint = true; canvas = document.getElementById('canvas') canvas.setAttribute("width", window.innerWidth * 0.8) canvas.setAttribute("height", window.innerHeight * 0.8) ctx = canvas.getContext("2d"); w = canvas.width; h = canvas.height; canvas.addEventListener("mouseover", function (e) { if (paint) { currX = e.clientX - canvas.offsetLeft; currY = e.clientY - canvas.offsetTop; draw() } }); canvas.addEventListener("mousemove", function (e) { if (paint) { currX = e.clientX - canvas.offsetLeft; currY = e.clientY - canvas.offsetTop; draw() } }); // on mobile phone canvas.addEventListener("touchover", function (e) { if (paint) { prevX = currX; prevY = currY; currX = e.touches[0].clientX - canvas.offsetLeft; currY = e.touches[0].clientY - canvas.offsetTop; draw() } }); canvas.addEventListener("touchmove", function (e) { if (paint) { currX = e.touches[0].clientX - canvas.offsetLeft; currY = e.touches[0].clientY - canvas.offsetTop; draw() } }); document.addEventListener("keypress", function (e) { switch (e.code) { case "Space": erase(); break; case "KeyB": color = "#0000FF"; break; case "KeyG": color = "#008000"; break; case "KeyR": color = "#FF0000"; break; case "KeyY": color = "#FFFF00"; break; } document.getElementById("picker").value = color; }); document.onkeydown = function(e) { e = e || window.event; if (e.keyCode == '38') { paint = false; } // down arrow else if (e.keyCode == '40') { paint = true; } } document.getElementById('picker').addEventListener("input", function(e) { color = this.value; }) window.addEventListener("orientationchange", function() { var w = screen.width; var h = screen.height; canvas.width = w*0.8; canvas.height = h*0.8; erase(); }); } function draw() { ctx.beginPath(); ctx.fillStyle = color; ctx.rect(currX-15, currY-15, 30, 30); ctx.fill(); } function erase() { ctx.clearRect(0, 0, w, h); }
true
0974db050b632d1687f8ac21cfa13e0a5023443a
JavaScript
glomotion/tesseract-js
/test/notifications.js
UTF-8
2,185
2.84375
3
[ "MIT" ]
permissive
var tesseract = require('../src/Tesseract.js'); // Tests for listening to notifications. function connectAndRun(test, body) { test.expect(2); tesseract.connect(null, function (err, client) { test.equals(err, null); body(client); }); } var insertInterval; function fireInserts(client) { insertInterval = setInterval(function () { client.insert('people', { 'name': 'Joe Bloggs' }); }, 100); } exports.testListenToAll = function(test) { connectAndRun(test, function(client) { var listener = client.listen('people') .then(function (data) { clearInterval(insertInterval); listener.stop(); test.equals(JSON.stringify(data), '{"name":"Joe Bloggs"}'); test.done(); client.close(); }); fireInserts(client); }); }; exports.testListenWithFilterThatMatches = function(test) { connectAndRun(test, function(client) { var listener = client.listen('people') .where('name like "Joe %"') .then(function (data) { clearInterval(insertInterval); listener.stop(); test.equals(JSON.stringify(data), '{"name":"Joe Bloggs"}'); test.done(); client.close(); }); fireInserts(client); }); }; exports.testListenWithFilterThatDoesNotMatch = function (test) { connectAndRun(test, function(client) { function testDone() { test.done(); client.close(); } var listener = client.listen('people') .where('name like "Bob %"') .then(function (data) { test.ok(false, "We didn't want to receive this notification."); testDone(); }); fireInserts(client); // With all the notifications firing 10 times a second, we shouldn't // hear anything for a whole second. setTimeout(function() { clearInterval(insertInterval); listener.stop(); test.ok(true); testDone(); }, 1000); }); };
true
86919046e69926f2d3372a2f6b1f5a6e55eec4d3
JavaScript
dennis/bombermanjs
/public/js/canvas_manager.js
UTF-8
463
2.765625
3
[ "MIT" ]
permissive
"use strict"; function CanvasManager() { this.mapWidth = 0; this.mapHeight = 0; } CanvasManager.prototype.init = function(canvasId, mapWidth, mapHeight) { this.canvas = document.getElementById(canvasId); if(this.canvas.getContext) { this.context = this.canvas.getContext('2d'); this.canvas.width = this.mapWidth = mapWidth; this.canvas.height = this.mapHeight = mapHeight; } else { throw new "No canvas support for element " + canvasId; } };
true
299704dcba1602061edd878b2ffc9eea77248524
JavaScript
aleksanderbrymora/sei-36
/warmups/week10/day2/withInquirer.js
UTF-8
2,280
4.09375
4
[]
no_license
const inquirer = require('inquirer'); // Reverse a string const revStr = (str) => { // str.split('').reverse().join(''); let out = ''; for (let i = str.length - 1; i >= 0; i--) { out += str[i]; } return out; }; // console.log('Reverse a string:', revStr('stuff')); // Print odd numvers from 1 to 99 const odds = () => { const out = []; let i = 1; while (i <= 99) { out.push(i); i += 2; } return out.join(', '); }; // console.log('\nOdds:', odds()); // Largest in array const largest = (arr) => arr.sort()[arr.length - 1]; // console.log('\nlargest in array:', largest([1, 2, 3, 89, 2, 6, 6, 4])); const fib = (left, now = 1, last = 1) => { if (left === 1 || left === 2) return now; return fib(left - 1, now + last, now); }; // console.log('\nfibonacci:', fib(6)); inquirer .prompt([ { name: 'yegge', type: 'list', message: 'Pick one', choices: [ 'Reverse a string', 'Print all the odds up to 99', 'Find the largest number in an array', 'Find nth Fibonnacci number', 'All of them', ], }, ]) .then(async (answer) => { let res; switch (answer.yegge) { case 'Reverse a string': res = await inquirer.prompt([ { name: 'string', type: 'input', message: 'What string do you want to reverse', }, ]); console.log('Reverse a string:', revStr(res.string)); break; case 'Print all the odds up to 99': console.log('\nOdds:', odds()); break; case 'Find the largest number in an array': res = await inquirer.prompt([ { name: 'numbers', type: 'input', message: 'Type in numbers separated by a space', }, ]); console.log('\nlargest in array:', largest(res.numbers.split(' '))); break; case 'Find nth Fibonnacci number': res = await inquirer.prompt([ { name: 'number', type: 'number', message: 'What number would you like to check', }, ]); console.log('\nfibonacci:', fib(res.number)); break; case 'All of them': console.log('Reverse a string:', revStr('stuff')); console.log('\nOdds:', odds()); console.log('\nlargest in array:', largest([1, 2, 3, 89, 2, 6, 6, 4])); console.log('\nfibonacci:', fib(6)); break; default: break; } });
true
25c3d04c5f5a1f07c26dfda4b552fb14a3c829a2
JavaScript
holynova/algorithm
/速算24/getAllSolutions.js
UTF-8
346
3.21875
3
[]
no_license
const log = console.log.bind(console) const Combinatorics = require('js-combinatorics'); function range(start = 1, end = 13) { let arr = [] for (let i = start; i <= end; i++) { arr.push(i) } return arr } log(range(1, 4)) let cmb = Combinatorics.combination(range(1, 13), 4) log(cmb.toArray()) function getAll(start=1,end=13){ }
true
6a7c07b3cfd2e7ff2150dfae932a69adf8f3786a
JavaScript
ehgoodenough/jumpdude
/source/scripts/models/Hero.js
UTF-8
5,054
2.65625
3
[]
no_license
var Keyboard = require("<scripts>/functions/Keyboard") var Hero = function() { var protohero = { width: 1, height: 1.5, color: "#FC0", position: { x: 3, y: 148 }, velocity: { x: 0, y: 0 }, direction: { x: "left", y: null }, jump: { height: 0, }, maximum: { velocity: { "-x": -0.25, "+x": 0.25, "-y": -0.7, "+y": 0.7 }, jump: { height: 3 } }, savepoint: { position: { x: 3, y: 148, } }, } for(var key in protohero) { this[key] = protohero[key] } } Hero.prototype.update = function(tick) { // this responds to keyboard input if(Keyboard.isJustDown("W")) { if(this.jump.height < this.maximum.jump.height) { this.velocity.y = this.maximum.velocity["-y"] } } if(Keyboard.isDown("A")) { this.velocity.x -= 3.5 * tick this.direction.x = "left" } if(Keyboard.isDown("D")) { this.velocity.x += 3.5 * tick this.direction.x = "right" } // this is affected by gravity this.velocity.y += 2.5 * tick // this is limited by maximum velocity if(this.velocity.y < this.maximum.velocity["-y"]) { this.velocity.y = this.maximum.velocity["-y"] } if(this.velocity.y > this.maximum.velocity["+y"]) { this.velocity.y = this.maximum.velocity["+y"] } if(this.velocity.x < this.maximum.velocity["-x"]) { this.velocity.x = this.maximum.velocity["-x"] } if(this.velocity.x > this.maximum.velocity["+x"]) { this.velocity.x = this.maximum.velocity["+x"] } // this collides with the world var tiles = game.world.getTiles({ "x1": this.position.x - (this.width / 2), "x2": this.position.x + (this.width / 2), "y1": this.position.y - (this.height / 2), "y2": this.position.y + (this.height / 2), "dy": this.velocity.y }) for(var index in tiles) { var tile = tiles[index] if(tile.hasCollision) { if(this.velocity.y > 0) { this.position.y = tile.position.y this.position.y -= this.height / 2 this.velocity.y = 0 this.jump.height = 0 if(this.position.y < game.camera.position.y + game.frame.height) { game.camera.setFocus(this.position) } } else if(this.velocity.y < 0) { this.position.y = tile.position.y + 1 this.position.y += this.height / 2 this.velocity.y = 0 this.jump.height = this.maximum.jump.height } } } var tiles = game.world.getTiles({ "x1": this.position.x - (this.width / 2), "x2": this.position.x + (this.width / 2), "y1": this.position.y - (this.height / 2), "y2": this.position.y + (this.height / 2), "dx": this.velocity.x }) for(var index in tiles) { var tile = tiles[index] if(tile.hasCollision) { if(this.velocity.x > 0) { this.position.x = tile.position.x this.position.x -= this.width / 2 this.velocity.x = 0 } else if(this.velocity.x < 0) { this.position.x = tile.position.x + 1 this.position.x += this.width / 2 this.velocity.x = 0 } } } // this is moved by velocity this.position.x += this.velocity.x this.position.y += this.velocity.y // this wraps around the world if(this.position.x < 0) { this.position.x = game.world.getWidth() } if(this.position.x > game.world.getWidth()) { this.position.x = 0 } // this tracks height of jumps if(this.velocity.y < 0) { this.jump.height -= this.velocity.y } // this decelerates from friction if(this.velocity.x > 0) { this.velocity.x -= 1.5 * tick if(this.velocity.x < 0) { this.velocity.x = 0 } } else if(this.velocity.x < 0) { this.velocity.x += 1.5 * tick if(this.velocity.x > 0) { this.velocity.x = 0 } } // this tracks the world this.tiles = game.world.getTiles({ "x1": this.position.x - (this.width / 2), "x2": this.position.x + (this.width / 2), "y1": this.position.y - (this.height / 2), "y2": this.position.y + (this.height / 2) }) if(this.position.y - (this.height / 2) > game.camera.position.y + game.frame.height) { this.position.x = this.savepoint.position.x this.position.y = this.savepoint.position.y game.camera.setFocus(this.position, true) console.log("You died!!") } } module.exports = Hero
true
797a9491dc24a555a4766840c91b11df18f62ca4
JavaScript
pashkovorg/es6
/src/destructuring/1.js
UTF-8
147
3.65625
4
[]
no_license
//destructuring arrays let [firstName, lastName] = ["Tyrion", "Lannister"]; console.log(firstName); // Tyrion console.log(lastName); // Lannister
true
4375bbd8313d70b4ce8a3159bca7a45fc283930a
JavaScript
bgoonz/UsefulResourceRepo2.0
/MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_JavaScript/minOfThreeNums7.js
UTF-8
245
4.03125
4
[ "MIT" ]
permissive
//7. Write a JS Program to get minimum of three numbers function minOfThreeNums(a, b, c) { console.log(a < b < c ? a : b < c ? b : c); } minOfThreeNums(1, 2, 3); minOfThreeNums(1, 20, 3); minOfThreeNums(-1, 12, 30); minOfThreeNums(0, 0, 0);
true
4e524b41855b2f78aeca5fb1030cdafda70e46d3
JavaScript
Derlys/javascript1
/Curso JS Moderno - Fin/13-DOM/js/05-scripts.js
UTF-8
1,069
3.453125
3
[]
no_license
// en este video estaremos viendo querySelectorAll // la buena noticia es que la sintaxis para selectores es la misma, es decir similar a CSS, con el punto para las classes y el numeral o signo de gato para los ID's, también puedes añadir un selector especifico.. // Pero la diferencia principal, es que querySelectorAll va a retornar todos los elementos que concuerden con el selector y no va a limitarte al primero como querySelector. // En nuestro HTML hay muchos cards, cuando utilizamos querySelector vimos que retornaba unicamente el primero.. const cards = document.querySelectorAll('.card'); console.log(cards); // si recuerdas tenemos dos elementos con el id de formulario const formularios = document.querySelectorAll('#formulario'); console.log(formularios); // Puedes ver quue eso si funciona, sin embargo recuerda que no rescomendable tener el mismo ID más de una vez por docuemnto... // Si no hay elementos no va a retornar nada // Si un selector no existe, const noExiste = document.querySelectorAll('#no-existe'); console.log(noExiste);
true
3e937fac92d9a551d691b908bf31616f40b63224
JavaScript
ilqarilyasov/typescript
/main.js
UTF-8
1,309
3.65625
4
[]
no_license
"use strict"; exports.__esModule = true; var message = 'Welcome back!'; console.log(message); var x = 10; // can be without init value var y = 20; // always init value var sum; var title = 'Learn Typescript'; // boolean, number, string - primitive type // Boolean, Number, String - object type var isBeginner = true; var total = 0; var name = 'Bernie'; var sentence = "My name is " + name + ",\nI am a beginner in Typescript"; console.log(sentence); var n = null; var u = undefined; var isNew = null; var myName = undefined; var list1 = [1, 2, 3]; var list2 = [1, 2, 3]; var person1 = ['Chris', 22]; // tuple var Color; (function (Color) { Color[Color["Red"] = 5] = "Red"; Color[Color["Green"] = 6] = "Green"; Color[Color["Blue"] = 7] = "Blue"; })(Color || (Color = {})); ; var c = Color.Green; console.log(c); // Any type. Compiler doesn't check its type until we access it var randomValue = 10; randomValue = true; randomValue = 10; randomValue = 'value'; // Typescript won't trow any errors var myVariable = 10; function hasName(obj) { return !!obj && typeof obj === "object" && "name" in obj; } if (hasName(myVariable)) { console.log(myVariable.name); } myVariable.toUpperCase; // Type assertion - casting var a; a = 10; a = true; var b = 20; b = true; console.log(b);
true
c3d18a7552aded779a895b9408b83ba9d64bc7fd
JavaScript
ManasviBendigeri/Compiler
/compiler.js
UTF-8
1,141
4.125
4
[]
no_license
//User input for calcution let input = ['sum',200,200] //Lexical Analysis let operArr = [] let numberArr = [] //Tokenization for(let i = input.length-1; i >=0;i--){ if(typeof input[i] === 'string'){ operArr.push(input[i]) }else{ numberArr.push(input[i]) } }; //Intializing value let value = 0 //Actions switch(operArr[0]){ case 'sum': if(operArr[0] === 'sum'){ for(let i = 0; i <= numberArr.length-1;i++){ value = numberArr[i] + value; } } break; case 'sub': if(operArr[0] === 'sub'){ value = 0; for(let i = 0; i <= numberArr.length-1;i++){ value = value - numberArr[i]; } } break; case 'mul': if(operArr[0] === 'mul'){ value = 1; for(let i = 0; i <= numberArr.length-1;i++){ value = numberArr[i] * value; } } break; case 'div': if(operArr[0] === 'div'){ value = 1; for(let i = 0; i <= numberArr.length-1;i++){ value = numberArr[i] / value; } } break; } //Results console.log("Numbers: ", numberArr); console.log("Operand: ", operArr); console.log("Result:", value);
true
18c3bb3f1ca374fa3f3f0caffe84ae58122c0a1d
JavaScript
LearnChemE/LearnChemE.github.io
/lab-experiments/garage_door/src/js/svg/SVG.js
UTF-8
1,321
2.84375
3
[]
no_license
const SVGObject = require("./SVGObject"); /** Creates an SVG object for the <svg> element. */ class SVG extends SVGObject { /** * @constructor * @param {object} options - Default options * @property {element} parent - The SVGObject parent (default {element: document.body}) * @property {string} id - Id of the element * @property {SVGobject[]} children - The child SVG objects of the group * @property {string[]} classList - ["string", "string2", ...] List of classes for line. (default []) * @property {number[]} viewBox - [0, 0, number, number2] Size of the viewbox (default [0, 0, 100, 100]) */ constructor(options) { super({ ...options, objectName: "svg" }); this.viewBox = options.viewBox ?? [0, 0, 100, 20]; this.element.setAttribute("xmlns", "http://www.w3.org/2000/svg"); this.element.setAttribute("viewBox", `${this.viewBox[0]} ${this.viewBox[1]} ${this.viewBox[2]} ${this.viewBox[3]}`); } /** * Function to resize the viewbox * @param {number} width - third value of viewbox * @param {number} height - fourth value of viewbox */ resizeViewbox(width, height) { this.viewBox = [ 0, 0, width, height ]; this.element.setAttribute("viewBox", `${this.viewBox[0]} ${this.viewBox[1]} ${this.viewBox[2]} ${this.viewBox[3]}`); } } module.exports = SVG;
true
b424141858ed239abe31fe3ea5183a6fb33fe59f
JavaScript
jocelynlozano/calculadora
/app.js
UTF-8
2,977
3.90625
4
[]
no_license
{var opcion = parseInt(prompt("elija una de las siguientes opciones \n" + "1. Calculadora Aritmetica \n" + "2. Caluladora Relacional")); switch(opcion){ case 1: var opcionElegida1 = parseInt(prompt("ingrese la operacion deseada \n" + "1. Suma \n" + "2. Resta \n" + "3. Multiplicacion \n" + "4. Division \n" + "5. Resto")); switch (opcionElegida1){ case 1: var num1 = parseInt(prompt("ingrese el numero 1")); var num2 = parseInt(prompt("ingrese el numero 2")); var suma = num1 + num2; window.alert("la suma es:" + suma); break; case 2: var num1 = parseInt(prompt ("ingrese el numero 1")); var num2 = parseInt(prompt ("ingrese el numero 2")); var resta = num1 + num2; window.alert("la resta es:" + resta); break; case 3: var num1 = parseInt(prompt ("ingrese el numero 1")); var num2 = parseInt(prompt ("ingrese el numero 2")); var multiplicacion = num1 * num2; window.alert("el producto es:" + multiplicacion); break; case 4: var num1 = parseInt(prompt ("ingrese el numero 1")); var num2 = parseInt(prompt ("ingrese el numero 2")); var cociente = num1 / num2; window.alert("el cociente es:" + cociente); break; case 5: var num1 = parseInt(prompt ("ingrese el numero 1")); var num2 = parseInt(prompt ("ingrese el numero 2")); var residuo = num1 / num2; window.alert("el residuo es:" + residuo); break; default: window.alert("no es una opcion valida"); break; } break; case 2: var opcionElegida2 = parseInt(prompt("ingrese la operacion deseada \n" + "1. Menor que \n" + "2. Mayor que \n" + "3. Menor o igual que \n" + "4. Mayor o igual que \n")); switch(opcionElegida2){ case 1: var num1 = parseInt(prompt("ingrese el numero 1")); var num2 = parseInt(prompt("ingrese el numero 2")); var menor = num1 < num2; window.alert("El numero " + num1+ " es menor que " + num2+ " : " + menor); break; case 2: var num1 = parseInt(prompt("ingrese el numero 1")); var num2 = parseInt(prompt("ingrese el numero 2")); var mayor = num1 > num2; window.alert("El numero " + num1+ " es mayor que " + num2+ " : " +mayor); break; case 3: var num1 = parseInt(prompt("ingrese el numero 1")); var num2 = parseInt(prompt("ingrese el numero 2")); var menorIgual = num1 <= num2; window.alert("El numero " + num1+ " es menor o igual que " + num2+ " : " + menorIgual); break; case 4: var num1 = parseInt(prompt("ingrese el numero 1")); var num2 = parseInt(prompt("ingrese el numero 2")); var mayorIgual = num1 >= num2; window.alert("El numero " + num1+ " es mayor o igual que " + num2+ " : " +mayorIgual); break; default: window.alert("no es una opción valida"); break; } break; } }
true
e3a425d028c6b09d108f0136bbcc0ce4c80b8d24
JavaScript
mrako/todo-nodejs-server
/app/routes.js
UTF-8
1,899
2.546875
3
[]
no_license
'use strict'; var Todo = require('./models/todo'); module.exports = function(app) { // GET ALL ==================================================================== app.get('/api/todos', function(req, res) { Todo.find(function(err, todos) { if (err) { res.send(err); } res.json(todos); }); }); // FIND BY ID ================================================================= app.get('/api/todos/:todoId', function(req, res) { Todo.findById(req.params.todoId ,function(err, todo) { if (err) { res.send(err); } res.json(todo); }); }); // CREATE ===================================================================== app.post('/api/todos', function(req, res) { Todo.create({ text : req.body.text, done : false }, function(err) { if (err) { res.send(err); } Todo.find(function(err, todos) { if (err) { res.send(err); } res.json(todos); }); }); }); // UPDATE ===================================================================== app.put('/api/todos/:todoId', function(req, res) { Todo.update({ _id: req.params.todoId },{ text : req.body.text, done : req.body.done }, function(err) { if (err) { res.send(err); } Todo.find(function(err, todos) { if (err) { res.send(err); } res.json(todos); }); }); }); // DELETE ===================================================================== app.delete('/api/todos/:todoId', function(req, res) { Todo.remove({ _id : req.params.todoId }, function(err) { if (err) { res.send(err); } Todo.find(function(err, todos) { if (err) { res.send(err); } res.json(todos); }); }); }); };
true
7ec2ca4e4cdbd27d144ce26db3a520c217ad7941
JavaScript
codingbits/MindMap
/es6/structs/AbstractGraph.js
UTF-8
4,078
3.046875
3
[ "MIT" ]
permissive
"use strict"; load.provide("mm.structs.emptyGraph", (function() { /** Just a simple, emtpy graph * * For use when a graph is needed, but none is provided. * @type object */ return { "version":1, "nodes":[], "edges":[], "canvas":{ "height":200, "width":200, } }; })); load.provide("mm.structs.AbstractGraph", (function() { let TypesFile = load.require("mm.structs.TypesFile"); let ObjectsData = load.require("mm.structs.ObjectsData"); let getfile = load.require("mm.utils.getfile"); let emptyGraph = load.require("mm.structs.emptyGraph"); /** This represents a graph. */ return class AbstractGraph { constructor(objectsUrl, typesUrl) { /** True if this object is ready for use (that is, the files have been downloaded) * * @type boolean */ this.ready = false; /** When downloaded, the types file object. * * @type mm.structs.TypesFile * @private */ this.types = null; /** When downloaded, the objects data object. * * @type mm.structs.ObjectsData * @private */ this.objects = null; /** The url of the types file * @type string * @private */ this._typesUrl = typesUrl; /** The url of the objects file * @type string * @private */ this._objectsUrl = objectsUrl; } /** Downloads the data from the files passed in the constructor * * @async */ async load() { // If it is an object, return it. If it is a string, JSON.parse it. let jsonMaybe = function(o) { if(typeof o === "string") return JSON.parse(o); return o; } if(this._objectsUrl) { // We have an objects file to download return Promise.all([ getfile(this._typesUrl), getfile(this._objectsUrl) ]).then((contents) => { this.types = new TypesFile(jsonMaybe(contents[0])); this.objects = new ObjectsData(jsonMaybe(contents[1]), this.types); this.ready = true; }); }else{ // We only have a types file let typesf = await getfile(this._typesUrl); this.types = new TypesFile(jsonMaybe(typesf)); this.objects = new ObjectsData(emptyGraph, this.types); this.ready = true; } } /** Deletes the node with the given id, and any edges that happen to link it. * * Then returns a special object that can be used to recover them. * * You can either specify one node, or multiple nodes. If specifying multiple, they all get deleted. * * @param {int|node|array<node>} id The node(s) to delete. * @return {object} A recovery object */ cascadingRemoveNode(nodes) { // Object used to recover let recovery = {edges:[], nodes:[]}; // Make sure the input is an array of node ids, rather than anything else if(!Array.isArray(nodes)) nodes = [nodes]; nodes = nodes.map((x) => typeof(x) == "number" ? x : x.id); // And loop through them for(let n of nodes) { // Make sure to delete and collect the edges as well let edges = this.objects.getEdgesConnectedToNode(n); recovery.edges = recovery.edges.concat(edges.map((e) => e.toJson())); edges.forEach((e) => this.objects.removeEdge(e.id)); let node = this.objects.getNode(n); recovery.nodes.push(node.toJson()); this.objects.removeNode(n); } return recovery; } /** Recovers the nodes and edges deleted by cascadingRemoveNode * * @param {object} recover The recovery object. */ cascadingRemoveNodeRecovery(recover) { for(let n of recover.nodes) { this.objects.insertNode(n); } for(let e of recover.edges) { this.objects.insertEdge(e); } } /** Returns an array of links where both ends are connected to a node in the given set. * * @param {array<mm.structs.ObjectNode>} nodes The set of nodes to find edges for. * @return {array<mm.structs.ObjectEdge>} All edges connected between any nodes. */ connectedEdges(nodes) { return this.objects.edges.filter((e) => nodes.some((n) => e.origin == n.id) && nodes.some((n) => e.dest == n.id) ); } }; }));
true
7446a88555d8fa8bd7e066cbce9f55c7d7914d3f
JavaScript
drewthedev9-tech/API-server
/server.js
UTF-8
1,949
2.609375
3
[]
no_license
const express = require('express'); const bodyParser = require('body-parser'); const bcrypt = require('bcrypt-nodejs'); const cors = require('cors'); const knex = require ('knex'); const register = require('./controllers/register'); const signin = require('./controllers/signin'); const profile = require('./controllers/profile'); const image = require('./controllers/image'); // connecting to database: const db = knex({ client: 'pg', connection: { connectionString : process.env.DATABASE_URL, ssl: true } }); // usual format knex.select('title', 'author', 'year').from('books') db.select('*').from ('users').then(data =>{ console.log(data); }); const app = express(); // nodyParser is a middleware // req.body is getting things from the body of HTML and and parsing, also in JSON format. app.use(bodyParser.json()); // cors is middle ware for connecting API to front end security. app.use(cors()); // get request to see if front end is talking to server. app.get('/', (req, res)=>{ // respnding with the user database after they are updated. res.send('it is working') }) //sign -- POST successful/fail. // sign in to handle the sign inswith the database above. app.post('/signin', (req, res)=> {signin.handleSignin(req, res,db, bcrypt)}) // register --> POST = user. // registering to a new user so adding to the database. // register function is in teh controllers file pushing these parameters to to the // function. app.post('/register', (req, res)=>{register.handleRegister(req, res,db, bcrypt)}) // matching id endpoint to get user. app.get('/profile/:id', (req, res)=>{profile.handelProfileGet(req, res,db)}) // increse their entries count app.put('/image',(req,res)=> {image.handleImage(req,res,db)}) app.post('/imageUrl',(req,res)=> {image.handleApiCall(req,res)}) app.listen (process.env.PORT || 3000, ()=> { console.log(`app is running on port ${process.env.PORT}`) })
true
5e0d0e5b1486b9d69b356d7e5ceca5b4306b1dd0
JavaScript
Swethad98761/ReactAssignment-ToDoApp-
/src/containers/MyTasks/MyTasks.js
UTF-8
1,999
2.59375
3
[]
no_license
import React, { Component } from "react"; import "./MyTasks.css"; import MyTask from "./MyTask/MyTask"; class MyTasks extends Component { constructor() { super(); this.state = { reminder: "", toggleTasks: false }; } handleToggleTask(currentReminder) { var toggleTasks = !this.state.toggleTasks; var reminder = ""; if (toggleTasks) { reminder = currentReminder; } this.setState({ reminder: reminder, toggleTasks: toggleTasks }); } handleDeleteTask(index) { this.props.handleDeleteTask(this.state.reminder, index); } render() { let tasks = { Today: [], Tomorrow: [], Someday: [] }; let currentReminder = this.state.reminder; if (currentReminder !== "") { tasks[currentReminder] = this.props.tasks[currentReminder]; } return ( <div className="MyTasks"> <strong> {this.props.list} <div className="Card"> <div className="Tasks"> <div onClick={this.handleToggleTask.bind(this, "Today")}> Today </div> <MyTask handleDeleteTask={this.handleDeleteTask.bind(this)} myTasks={tasks["Today"]} /> </div> <div className="Tasks"> <div onClick={this.handleToggleTask.bind(this, "Tomorrow")}> Tomorrow </div> <MyTask handleDeleteTask={this.handleDeleteTask.bind(this)} myTasks={tasks["Tomorrow"]} /> </div> <div className="Tasks"> <div onClick={this.handleToggleTask.bind(this, "Someday")}> Someday </div> <MyTask handleDeleteTask={this.handleDeleteTask.bind(this)} myTasks={tasks["Someday"]} /> </div> </div> </strong> </div> ); } } export default MyTasks;
true
4f51c29a1540cc6758fb8aac9d0c1fd19bb61100
JavaScript
josephBenjaminDeveloper/todolist
/src/App.js
UTF-8
1,625
2.625
3
[]
no_license
import Header from "./componentes/Header"; import ContainerTask from "./componentes/Container"; import React,{ useEffect,useState } from "react"; import "../src/styles/app.css" function App() { const [taskTodolist,setTaskTodolist] = useState(null) const [datafilter,setDatafilter] = useState(null) useEffect(()=>{ const funcionfetch=async()=>{ const response =await fetch("https://jsonplaceholder.typicode.com/todos") const result =await response.json() const result20 = result.slice(0,20); setTaskTodolist(result20); } funcionfetch(); },[]) const todas = (joseph)=>{ setDatafilter(taskTodolist) console.log(joseph) } const completas = (completas)=>{ setDatafilter(taskTodolist.filter((x)=>x.completed === completas )) console.log(completas) } const incompletas = (incompletas)=>{ setDatafilter(taskTodolist.filter((x)=>x.completed === incompletas)) console.log(incompletas) } // console.log(taskTodolist[0]) const cambioboton = (id)=>{ setTaskTodolist(taskTodolist.map((x)=>x.id === id ? {...x,completed: !x.completed}:x)) setDatafilter(datafilter.map((x)=>x.id === id ? {...x,completed: !x.completed}:x)) } return( <div className="all"> <Header todas = {todas} completas = {completas} incompletas = {incompletas} /> <div className="contenedor"> {datafilter && datafilter.map((x)=> <ContainerTask key = {x.id} user = {x.userId} id = {x.id} title = {x.title} completed = {x.completed} cambio = {cambioboton} /> )} </div> </div> ) } export default App;
true
78ba5d63db76d554e2633eae855f707ea9fef077
JavaScript
gsc229/typescript-with-react
/simple-typescript/dist/utility-types2.js
UTF-8
652
3.828125
4
[]
no_license
"use strict"; const myObject = { sayHello() { return this.helloWorld(); } }; myObject.sayHello = myObject.sayHello.bind({ helloWorld() { return "Hello World"; } }); console.log(myObject.sayHello()); function makeObject(desc) { let data = desc.data || {}; let methods = desc.methods || {}; return Object.assign(Object.assign({}, data), methods); } let obj = makeObject({ data: { x: 0, y: 0 }, methods: { moveBy(dx, dy) { this.x += dx; // Strongly typed this this.y += dy; // Strongly typed this }, }, }); obj.x = 10; obj.y = 20; obj.moveBy(5, 5); console.log({ obj });
true
2fa8618433cfefd440269daa69c1a696ce4969eb
JavaScript
jordandivyansh/gradient_bg
/script.js
UTF-8
760
2.96875
3
[]
no_license
var c1 = document.querySelector(".c1"); var c2 = document.querySelector(".c2"); var css= document.querySelector("h3"); var body= document.getElementById("gradient"); var buttonl = document.getElementById("buttonl"); var buttonr = document.getElementById("buttonr"); function bgchange(){ body.style.background= "radial-gradient( " + c1.value +","+c2.value+")"; css.textContent = body.style.background + ";"; } function linear() { body.style.background= "linear-gradient(to right, " + c1.value +","+c2.value+")"; css.textContent = body.style.background + ";"; } c1.addEventListener("input", bgchange); c2.addEventListener("input", bgchange); buttonl.addEventListener("click", linear); buttonr.addEventListener("click", bgchange);
true
2f4b61e44f598855a2589f2aecf3e2abac4550b4
JavaScript
HuyckS/C-.NET-Core
/algos/day4.js
UTF-8
3,414
4.40625
4
[]
no_license
class Queue { constructor() { this.values = []; } /** * Adds a value and returns the new size. * * @param {any} val * @returns {number} the new size */ enqueue(val) { this.values.push(val); return this.values.length; } /** * @returns {any} the removed (front) value */ dequeue() { return this.values.shift(); } /** * @returns {boolean} */ isEmpty() { return this.values.length === 0; } /** * @returns {number} */ size() { return this.values.length; } /** * Determines whether the first half's sum equals the second half's sum * DO NOT manually index the queue items, * only use the provided queue methods, * use no additional arrays or objects for storage * Restore the queue to its original state. * * @returns {boolean} */ sumOfHalvesEqual() { // your code here } } const queue = new Queue(); queue.enqueue(1); // 1 queue.enqueue(2); // 1 - 2 queue.enqueue(3); // 1 - 2 - 3 queue.enqueue(3); // 1 - 2 - 3 - 3 queue.enqueue(2); // 1 - 2 - 3 - 3 - 2 queue.enqueue(1); // 1 - 2 - 3 - 3 - 2 - 1 console.log(queue.sumOfHalvesEqual()); // should log true (6 and 6) class Stack { constructor() { this.values = []; } /** * Adds a new value to the top. * * @param {any} val the value to add * @returns {number} the new size of the stack */ push(val) { this.values.push(val); return this.size(); } /** * Removes and returns the top value. * * @returns {any} the removed top value */ pop() { return this.values.pop(); } /** * Returns whether the stack is empty. * * @returns {boolean} */ isEmpty() { return this.size() === 0; } /** * @returns {number} the number of items in the stack */ size() { return this.values.length; } /** * Returns, but doesn't remove, the top value. * * @returns {any} the top value */ peek() { return this.size() === 0 ? null : this.values.slice(-1)[0]; } } class QueueWithStacks { constructor() { this.stack1 = new Stack(); this.stack2 = new Stack(); } /** * Adds a value and returns the new size of the queue * Only use the two stacks and their methods * How do you make a FIFO (First In First Out) structure from * two LIFO (Last In First Out) structures? * * @param {any} val the value to add * @returns {number} the new size of the queue */ enqueue(val) { // your code here } /** * Removes the value at the front of the queue * Only use the two stacks and their methods * * @returns {any} the front value or null if empty */ dequeue() { // your code here } } const stacksQueue = new QueueWithStacks(); console.log(stacksQueue.enqueue('a')); // should log 1 // a console.log(stacksQueue.enqueue('b')); // should log 2 // a - b console.log(stacksQueue.enqueue('c')); // should log 3 // a - b - c console.log(stacksQueue.dequeue()); // should log 'a' // b - c console.log(stacksQueue.dequeue()); // should log 'b' // c console.log(stacksQueue.dequeue()); // should log 'c' // empty // EXTRA: NextQueue // Design a Queue class that automatically sends every 3rd dequeued person object to a next queue that can be specified // Imagine a security queue where every 3rd person is randomly sent to an additional security queue
true
f79ec9864879e51d174bf074808b9a77e511b27a
JavaScript
timcritt/updated-learn-redux
/src/index.js
UTF-8
2,103
2.859375
3
[]
no_license
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; //import App from './App'; import * as serviceWorker from './serviceWorker'; import { Provider, connect } from 'react-redux'; //redux imports import {createStore } from 'redux'; // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister(); //REDUX FROM HERE DOWN //reducer: A pure function that accepts 2 parameters: state and action. const countReducer = function ( state = 0, action) { switch (action.type) { case "INCREMENT": return state + 1; case "DECREMENT": return state -1; case "RESET": return 0; default: return state; } }; //store: holds the state for the whole application let store = createStore(countReducer); //map state to props const mapStateToProps = state => { return { count: state }; }; // Map actions (dispatches) to props const mapDispatchToProps = dispatch => { return { handleIncrementClick: () => dispatch({type: 'INCREMENT'}), handleDecrementClick: () => dispatch({type: 'DECREMENT'}), handleResetClick: () => dispatch({type: 'RESET'}) } } //a react, presentational (aka dumb) component (presentational means isn't directly connected to store) const Component = ({count, handleIncrementClick, handleDecrementClick, handleResetClick}) => ( <div> <h1>HelloWorld React and Redux {count}</h1> <button onClick={handleDecrementClick}>Decrement</button> <button onClick={handleIncrementClick}>Increment</button> <button onClick={handleResetClick}>Reset</button> </div> ); //smart components have the state connected to them with connect const Container = connect(mapStateToProps, mapDispatchToProps)(Component); //provider supplies the component tree with the global state const App = () => ( <Provider store={store}> <Container></Container> </Provider> ); ReactDOM.render(<App />, document.getElementById('root'));
true
9e16c0bdb797e382d5ed28e904a5d6b0a56317da
JavaScript
kporcelainluv/100_days_of_JS
/avgAlth.js
UTF-8
580
3.171875
3
[]
no_license
function orbitalPeriod(arr) { let getOrbPeriod = obj => { var GM = 398600.4418; var earthRadius = 6367.4447; let avgAlth = obj["avgAlt"]; let pi = Math.PI; let res = 2 * pi * Math.sqrt((earthRadius + avgAlth) ** 3 / GM); delete obj["avgAlt"]; obj["orbitalPeriod"] = Math.round(res); return obj; }; for (var index in arr) { arr[index] = getOrbPeriod(arr[index]); } return arr; } console.log( orbitalPeriod([ { name: "iss", avgAlt: 413.6 }, { name: "hubble", avgAlt: 556.7 }, { name: "moon", avgAlt: 378632.553 } ]) );
true
5cf4f732a0c74edbc40d118db1e35b88eba954b8
JavaScript
O-Liruk/JS
/homework_17/script.js
UTF-8
2,990
3.328125
3
[]
no_license
'use strict'; const TODOS_URL = 'https://jsonplaceholder.typicode.com/todos/'; const DONE_CLASS = 'done'; const DELETE_BTN_CLASS = 'delete-btn'; const TASK_ITEM_CLASS = 'task-item'; const TASK_ITEM_SELECTOR = '.' + TASK_ITEM_CLASS; const taskInput = document.getElementById('taskNameInput'); const taskTemplate = document.getElementById('newTaskTemplate').innerHTML; const listEl = document.getElementById('taskList'); let todoList = []; // document.getElementById('newTaskForm').addEventListener('submit', onFormSubmit); listEl.addEventListener('click', onListClick); init(); function init() { fetchTodos () } function onListClick(e) { const taskEl = getTaskElement(e.target); switch (true) { case e.target.classList.contains(DELETE_BTN_CLASS): return deleteTask(+taskEl.dataset.id); case e.target.classList.contains(TASK_ITEM_CLASS): return toggleTodo(+taskEl.dataset.id); } } function getTaskElement(el) { return el.closest(TASK_ITEM_SELECTOR); } function fetchTodos () { fetch(TODOS_URL) .then((res) => res.json()) .then(setTodos) .then(renderTodos) } function setTodos(list){ return todoList = list } function renderTodos(list) { const html = list.map(getTodoHtml).join('') listEl.innerHTML = html } function getTodoHtml (todo) { return taskTemplate .replace('{{doneClass}}', todo.completed ? DONE_CLASS :'') .replace('{{text}}', todo.title) .replace('{{id}}', todo.id) } function deleteTask(todoId) { const todo = todoList.findIndex((todo) => todo.id === todoId) todoList.splice(todo, 1) renderTodos(todoList) } function toggleTodo(todoId) { const todo = todoList.find((todo) => todo.id === todoId) todo.completed = !todo.completed renderTodos(todoList) } // function onFormSubmit(e) { // e.preventDefault(); // const title = taskInput.value; // if (isValid(title)) { // addNewTask(title); // clearInput(); // } else { // alert('task is invalid'); // } // } // function onListClick(e) { // const taskEl = getTaskElement(e.target); // switch (true) { // case e.target.classList.contains(DELETE_BTN_CLASS): // return deleteTask(taskEl); // case e.target.classList.contains(TASK_ITEM_CLASS): // return toggleTask(taskEl); // } // } // function isValid(text) { // return !!text; // } // function addNewTask(title) { // const newTaskHtml = getTaskHtml(title); // listEl.insertAdjacentHTML('beforeend', newTaskHtml); // } // function getTaskHtml(title) { // return taskTemplate.replace('{{text}}', title); // } // function clearInput() { // taskInput.value = ''; // } // function getTaskElement(el) { // return el.closest(TASK_ITEM_SELECTOR); // } // function toggleTask(el) { // el.classList.toggle(DONE_CLASS); // } // function deleteTask(el) { // el.remove(); // }
true
7130b8f4f2a03ddda71e72c61b04bc9cff6c82d9
JavaScript
prakhar-161/-Registration-Form
/src/app.js
UTF-8
2,110
2.59375
3
[]
no_license
const express = require('express'); const path = require('path'); const hbs = require('hbs'); const app = express(); require('./database/connect'); const Register = require('./models/students'); const port = process.env.PORT || 3000; //important const static_path = path.join(__dirname,"../public"); const template_path = path.join(__dirname,"../templates/views"); const partials_path = path.join(__dirname,"../templates/partials"); //last app.use(express.json()); app.use(express.urlencoded({extended:false})); app.use(express.static(static_path)); //hbs partial files hbs.registerPartials(partials_path); //setting up view engine app.set("view engine","hbs"); //since views path is changed app.set("views",template_path); app.get('/',(req,res) => { res.render('index'); }); app.get('/register',(req,res) => { res.render('register'); }); app.get('/login',(req,res) => { res.render('login'); }); //create a new user in our database app.post('/register',async (req,res) => { try{ const registerStudent = new Register({ name: req.body.name, phone: req.body.phone, email: req.body.email, password: req.body.password }); const registered = await registerStudent.save(); res.status(201).render("index"); }catch(error){ res.status(400).send(error); }; }); //check login // app.post('/login',async(req,res) => { // try{ // const email = req.body.email; // const password = req.body.password; // const userEmail = await Register.findOne({email}) //object destructuring can also be applied here. // if(userEmail.password === password){ // alert("Welcome!"); // res.status(201).render("index"); // }else{ // alert("Password not matching"); // } // }catch(error){ // res.status(400).send("Invalid Email"); // }; // }); app.listen(port,(err) => { if(err){ console.log(`Error in listening to port ${port}`); } console.log(`Listening to port ${port}`); });
true
fd90befde9ae698de95ed55ed3f86957b5aef83b
JavaScript
CHOEJANGHYEOK/quantcash
/front/src/store/reducers/algo.js
UTF-8
785
2.75
3
[]
no_license
const initialState = { allAlgorithmList: [], ownedAlgorithmList: [], }; const algoReducer = (state = initialState, action) => { switch (action.type) { case 'RESET': console.log(state); return initialState; case 'GET_OWNED_ALGORITHM': return {...state, ownedAlgorithmList: action.data}; case 'GET_ALL_ALGORITHM': return {...state, allAlgorithmList: action.data}; case 'DELETE_ALGORITHM': const deletedAlgorithmList = state.ownedAlgorithmList.filter( (algo) => algo.id !== action.data, ); return {...state, ownedAlgorithmList: deletedAlgorithmList}; default: break; } return state; }; export default algoReducer;
true
e5584ecd4810ec538f3e8812b92d6ec76edb9c8e
JavaScript
campeon19/Lab10_Web_Calculadora
/src/componentes/util/calcular.js
UTF-8
2,557
2.890625
3
[]
no_license
/* eslint-disable no-alert */ import Big from "big.js"; import operate from "./operar"; import isNumber from "./isNumber"; export default function calculate(obj, buttonName) { Big.DP = 7; if (buttonName === "AC") { return { total: null, siguiente: null, operacion: null, }; } if (isNumber(buttonName)) { if (buttonName === "0" && obj.siguiente === "0") { return {}; } if (obj.operacion) { if (obj.siguiente) { if(obj.siguiente.length < 9){ return { siguiente: obj.siguiente + buttonName }; } alert("Error numero maximo de digitos sobrepasado"); } return { siguiente: buttonName }; } if (obj.siguiente) { if(obj.siguiente.length < 9){ const siguiente = obj.siguiente === "0" ? buttonName : obj.siguiente + buttonName; return { siguiente, total: null, }; } alert("Error numero maximo de digitos sobrepasado"); } return { siguiente: buttonName, total: null, }; } if (buttonName === "%") { if (obj.operacion && obj.siguiente) { const result = operate(obj.total, obj.siguiente, obj.operacion); return { total: Big(result) .div(Big("100")) .toString(), siguiente: null, operacion: null, }; } if (obj.siguiente) { return { siguiente: Big(obj.siguiente) .div(Big("100")) .toString(), }; } return {}; } if (buttonName === ".") { if (obj.siguiente) { if (obj.siguiente.includes(".")) { return {}; } return { siguiente: `${obj.siguiente }.` }; } return { siguiente: "0." }; } if (buttonName === "=") { if (obj.siguiente && obj.operacion) { return { total: operate(obj.total, obj.siguiente, obj.operacion), siguiente: null, operacion: null, }; } return {}; } if (buttonName === "+/-") { if (obj.siguiente) { return { siguiente: (-1 * parseFloat(obj.siguiente)).toString() }; } if (obj.total) { return { total: (-1 * parseFloat(obj.total)).toString() }; } return {}; } if (obj.operacion) { return { total: operate(obj.total, obj.siguiente, obj.operacion), siguiente: null, operacion: buttonName, }; } if (!obj.siguiente) { return { operacion: buttonName }; } return { total: obj.siguiente, siguiente: null, operacion: buttonName, }; }
true
79b46651685bad27c0c80aedbe8cb74cd64ce5a2
JavaScript
YehorZapara/Ucode
/Sprint_04/ezapara/t01_elements/js/script.js
UTF-8
714
2.921875
3
[]
no_license
let li = document.getElementsByTagName('li'); for (let i = 0; i < li.length; i++) { if (li[i].className !== 'good' && li[i].className !== 'evil' && li[i].className !== 'unknown') { li[i].className = 'unknown'; } if (!li[i].hasAttribute('data-element')) { li[i].setAttribute('data-element', 'none'); } let data = li[i].getAttribute('data-element').split(' '); li[i].insertAdjacentHTML('beforeend', '<br/>'); data.forEach(function (el) { if (el.length > 0) { li[i].insertAdjacentHTML('beforeend', '<div class="elem ' + el + '">' + (el === 'none' ? '<div class="line"></div>' : ' ') + '</div>'); } }); }
true
4ef3354ad704f2707e312b6abbba516a38be324a
JavaScript
Mitch-Kenward/Lotide
/test/tailTest.js
UTF-8
770
3.453125
3
[]
no_license
const { assert } = require("chai"); const tail = require("../tail"); describe("#tail", () => { const words = ["bright", "Lighthouse", "Labs"]; it("returns 3 for words.length", () => { assert.strictEqual((words.length), 3); }); it("returns 2 for tail(words).length", () => { assert.strictEqual(tail(words).length, 2); }); it("returns ['Lighthouse', 'Labs'] for tail(words)", () => { assert.deepEqual(tail(words), ['Lighthouse', 'Labs']); }); }); //const result = tail(["Hello", "Lighthouse", "Labs"]); //assertEqual(result.length, 2); // ensure we get back two elements //assertEqual(result[0], "Lighthouse"); // ensure first element is "Lighthouse" //assertEqual(result[1], "Labs"); // ensure second element is "Labs" module.exports = tail;
true
efc99910f82b0a645883948f829e161d56464546
JavaScript
Subhadeep-sm/bmi-calculator
/js/bmi.js
UTF-8
2,216
3.609375
4
[]
no_license
function weightunit(){ if (document.getElementById('weight-unit').value == "Pounds"){ let x = parseFloat(document.getElementById('weight').value); document.getElementById('weight').value= 0.45359237 * x; } else{ let x = parseFloat(document.getElementById('weight').value); } } function heightunit(){ if (document.getElementById('height-unit').value == "Centimeters"){ let x = parseFloat(document.getElementById('height').value); document.getElementById('height').value= 0.01 * x ; } if (document.getElementById('height-unit').value == "Feet"){ let x = parseFloat(document.getElementById('height').value); document.getElementById('height').value= 0.3048 * x ; } if (document.getElementById('height-unit').value == "Inches"){ let x = parseFloat(document.getElementById('height').value); document.getElementById('height').value= 0.0254 * x ; } else{ let x = parseFloat(document.getElementById('height').value); document.getElementById('height').value= x ; } } function bmi(){ let weight= parseFloat(document.getElementById('weight').value); let height= parseFloat(document.getElementById('height').value); let bmi= weight/ height**2 ; document.getElementById('result').style.visibility = "visible"; document.getElementById('weight').value=null; document.getElementById('height').value=null; if (bmi.toFixed(1) < 18.5){ document.getElementById('result').innerHTML= "BMI : " + bmi.toFixed(1) + " (Underweight)"; } if (bmi.toFixed(1) >= 18.5 && bmi.toFixed(1) <= 25){ document.getElementById('result').innerHTML= "BMI : " + bmi.toFixed(1) + " (Normal)"; } if (bmi.toFixed(1) > 25){ document.getElementById('result').innerHTML= "BMI : " + bmi.toFixed(1) + " (Overweight)"; } else{ document.getElementById('result').innerHTML= "-No Input-" ; } } function allclear(){ document.getElementById('weight').value=null; document.getElementById('height').value=null; document.getElementById('result').innerHTML= null; document.getElementById('result').style.visibility = "hidden"; }
true
6b1e2c2e6c877b281efac46d7a9e5e2ef1169283
JavaScript
fullmontis/fullmontis.github.io
/monster-girl-diaries/menu.js
UTF-8
1,700
3.375
3
[]
no_license
"use strict"; var stories = document.getElementsByClassName("story"); var story_buttons = document.getElementsByClassName("monster-button"); var story_close = document.getElementById("button-close"); var story_close_container = document.getElementsByClassName("button-close-container")[0]; function jump_to( id ) { window.location.href="#" + id; } // open button callback function open_story( id ) { return function () { story_id = id; story_elems[id].button.classList.add("hidden"); story_elems[id].story.classList.remove("hidden"); story_close_container.classList.remove("hidden"); }; } // create events for each button var story_elems = {}; for( var i=0; i < story_buttons.length; i++ ) { var b = story_buttons[i]; if( b.id != "button-close" ) { var story_name = b.dataset.monster; story_elems[story_name] = {}; story_elems[story_name].button = b; b.addEventListener("click", open_story(story_name)); } } for( var i=0; i < stories.length; i++ ) { var s = stories[i]; var story_name = s.dataset.monster; story_elems[story_name].story = s; s.classList.add("hidden"); } // close button var story_id = "index"; function close_all() { for( var monster in story_elems ) { var e = story_elems[monster]; e.story.classList.add("hidden"); e.button.classList.remove("hidden"); } story_close_container.classList.add("hidden"); jump_to(story_id); } story_close.addEventListener( "click", close_all); story_close_container.classList.add("hidden"); // create index function capitalize( string ) { return string[0].toUpperCase() + string.slice(1); }
true
b8ccf33ff7b82d9aafc9cd61392517ff43146156
JavaScript
vladstepway/english-for-kids
/src/js/utils/router.js
UTF-8
2,824
2.6875
3
[]
no_license
// const main = <h1>Categories</h1>; // const animals = <h1>Animals</h1>; // const countries = <h1>Countries</h1>; // const emotions = <h1>Emotions</h1>; // const fairyTales = <h1>Fairy Tales</h1>; // const food = <h1>Food</h1>; // const halloween = <h1>Halloween</h1>; // const weather = <h1>Weather</h1>; // const hospital = <h1>Hospital</h1>; // const routes = { // '/': main, // '/animals': animals, // '/countries': countries, // '/emotions': emotions, // '/fairy-tales': fairyTales, // '/food': food, // '/halloween': halloween, // '/weather': weather, // '/hospital': hospital, // }; // export default class Router { // routes = []; // mode = null; // root = '/'; // constructor(options) { // this.mode = window.history.pushState ? 'history' : 'hash'; // if (options.mode) { // this.mode = options.mode; // } // if (options.root) { // this.root = options.root; // } // this.listen(); // } // addRoute = (path, cb) => { // this.routes.push({ path, cb }); // return this; // }; // remove = (path) => { // for (let i = 0; i < this.routes.length; i++) { // if (this.routes[i].path === path) { // this.routes.slice(i, 1); // return this; // } // } // return this; // }; // flush = () => { // this.routes = []; // return this; // }; // clearSlashes = (path) => // path.toString().replace(/\/$/, '').replace(/^\//, ''); // getFragment = () => { // let fragment = ''; // if (this.mode === 'history') { // fragment = this.clearSlashes( // decodeURI(window.location.pathname + window.location.search) // ); // fragment = fragment.replace(/\?(.*)$/, ''); // fragment = this.root !== '/' ? fragment.replace(this.root, '') : fragment; // } else { // const match = window.location.href.match(/#(.*)$/); // fragment = match ? match[1] : ''; // } // return this.clearSlashes(fragment); // }; // navigate = (path = '') => { // if (this.mode === 'history') { // window.history.pushState(null, null, this.root + this.clearSlashes(path)); // } else { // window.location.href = `${window.location.href.replace( // /#(.*)$/, // '' // )}#${path}`; // } // }; // listen = () => { // clearInterval(this.interval); // this.interval = setInterval(this.interval, 50); // }; // interval = () => { // if (this.current === this.getFragment()) { // return; // } // this.current = this.getFragment(); // this.routes.some((r) => { // const match = this.current.match(r.path); // if (match) { // match.shift(); // r.cb.apply({}, match); // return match; // } // return false; // }); // }; // }
true
3b2e3b8d7e68985a1f4ee10343ecd6a9e52cfc32
JavaScript
Jstewart3313/headcount2.0
/src/Card.js
UTF-8
873
2.65625
3
[]
no_license
import React from 'react'; import PropTypes from 'prop-types'; const Card = ({stats, location, compareCards}) => { let years = Object.keys(stats); let cardCounter = 0; const schoolData = years.map( year => { return <p className={(stats[year] > .5) ? 'data-above' : 'data-below'} name={location} key={cardCounter++} > {year} : {stats[year]}</p>; }); this.handleClick = (event) => { let name = event.target.getAttribute('name'); compareCards(name); }; return ( <div className='card' name={location} onClick={this.handleClick} > <h3 name={location} className='location'>{location}</h3> {schoolData}; </div> ); }; Card.propTypes = { stats: PropTypes.object.isRequired, location: PropTypes.string.isRequired, compareCards: PropTypes.func }; export default Card;
true
ea5101d58267ba5283ebc3853473d0dd133b29ea
JavaScript
simtemple/industry
/WebApp/src/admin/pages/home/approveActions.jsx
UTF-8
2,498
2.53125
3
[]
no_license
import { toastr } from 'react-redux-toastr'; // Accept company method export const acceptUser = (ID) => async (dispatch, getState, {getFirestore}) => { const firestore = getFirestore(); try { await firestore.update(`users/${ID}`, { approved: true, approvalStatus: 'accepted' }) // Toastr message toastr.success('Success', 'Successfully accepted user'); } catch (error) { console.log(error); toastr.error('Error', 'Something went wrong'); } } // Reject company method export const rejectUser = (ID) => async (dispatch, getState, {getFirestore}) => { const firestore = getFirestore(); try { await firestore.update(`users/${ID}`, { approved: false, approvalStatus: 'rejected' }) // Toastr message toastr.success('Success', 'Successfully rejected user'); } catch (error) { console.log(error); toastr.error('Error', 'Something went wrong'); } } // Accept candidate method export const acceptCandidate = (ID) => async (dispatch, getState, {getFirestore}) => { const firestore = getFirestore(); try { await firestore.update(`users/${ID}`, { approved: true, approvalStatus: 'accepted' }) // Toastr message toastr.success('Success', 'Successfully accepted user'); } catch (error) { console.log(error); toastr.error('Error', 'Something went wrong'); } } // Reject candidate method export const rejectCandidate = (ID) => async (dispatch, getState, {getFirestore}) => { const firestore = getFirestore(); try { await firestore.update(`users/${ID}`, { approved: false, approvalStatus: 'rejected' }) // Toastr message toastr.success('Success', 'Successfully rejected user'); } catch (error) { console.log(error); toastr.error('Error', 'Something went wrong'); } } // Submit skills method export const submitSkills = (skillsScores, ID, user) => async (dispatch, getState, {getFirestore}) => { const firestore = getFirestore(); let updatedUser = { ...user, skillsScores } try { console.log(updatedUser) await firestore.update(`users/${ID}`, updatedUser) // Toastr message toastr.success('Success', 'Successfully rejected user'); } catch (error) { console.log(error); toastr.error('Error', 'Something went wrong'); } }
true
da8be7d7bdce6a898b8f2eef2503733186ac6db3
JavaScript
danuzclaudes/COMP426-F14-A2
/js/minesweeper.js
UTF-8
382
2.5625
3
[ "MIT" ]
permissive
/** * Created by chongrui on 2014/9/25 0025. */ $(document).ready(function (){ // Initially has 10 bombs and 8*8 table var bombSize = 10; var row = 8; var col = 8; buildBoard(row,col); setBomb(row,col,bombSize); myEvent(row,col,bombSize); // if GameOptions are reset, will invoke step 1,2,3 again setGameOptions(row, col, bombSize); });
true
aa5e9f2cd150afeb42bec555837956876c351799
JavaScript
Hiro-mackay/react-nagoya-learning-4
/src/components/Form.jsx
UTF-8
1,321
3.078125
3
[]
no_license
import React, { useState } from "react"; import firestore from "../config/firestore"; // This one is new const Form = () => { // Initial item const initialItemValues = { name: "", message: "" }; const [item, setItem] = useState(initialItemValues); // Formが牛んされると実行 // 名前とメッセージに文字が入っていれば、 // オブジェクトをドキュメントとしてfirestoreコレクションに送信 const onSubmit = event => { event.preventDefault(); if (item.name.length && item.message.length) { firestore .collection("messages") .doc() .set(item) .then(() => setItem(initialItemValues)) .catch(error => console.error(error)); } }; // inputの値が変わるたびに、更新 const onChange = ({ target }) => { setItem({ ...item, [target.name]: target.value }); }; return ( <form onSubmit={onSubmit}> <input type="text" name="name" placeholder="Name" value={item.name} onChange={onChange} /> <textarea name="message" placeholder="Message" value={item.message} onChange={onChange} /> <button type="submit">Send</button> </form> ); }; export default Form;
true
1513a31161b48bfad628724d2e261388cfd23e0a
JavaScript
stefanus1292/h8-p0-w4
/w4-ex 9.js
UTF-8
508
3.375
3
[]
no_license
function checkAB(num) { var A, B; for (let i = 0; i < num.length; i++) { if (num[i] === 'a') { A = i; } else if (num[i] === 'b') { B = i; } var jarak = Math.abs(B - A) - 1; } if (jarak === 3) { return true; } else { return false; } } // TEST CASES console.log(checkAB('lane borrowed')); // true console.log(checkAB('i am sick')); // false console.log(checkAB('you are boring')); // true console.log(checkAB('barbarian')); // true console.log(checkAB('bacon and meat')); // false
true
01010a58049fdb9b7b9789358b7057ccf98e1f07
JavaScript
andogq/rts
/server.js
UTF-8
5,813
2.59375
3
[]
no_license
// Imports const http = require("http"); const url = require("url"); const fs = require("fs"); class Server { constructor(port, staticDir) { this.port = port == undefined ? 8000 : port; this.staticDir = staticDir == undefined ? "static" : staticDir; this.server = http.createServer(this.incomingRequest.bind(this)); this.functions = {}; } start() { return new Promise((resolve, reject) => { console.log(`Searching for static files in directory ${this.staticDir}`); this.findStaticFiles().then(() => { console.log(`Starting server on port ${this.port}`); this.server.listen(this.port); }).catch((err) => { reject(err); }); }); } findFiles(directory) { return new Promise((resolve, reject) => { fs.readdir(directory, {withFileTypes: true}, (err, contents) => { if (err) reject(err); let files = []; let promises = []; // Go through all the returned files contents.forEach((file) => { let fileName = `${directory}/${file.name}` // Add it to the list if it's a normal file if (file.isFile()) files.push(fileName); // If it's a directory search it for files else if (file.isDirectory()) promises.push(this.findFiles(fileName)); }); // If there's directories being searched if (promises.length > 0) { promises.forEach((promise) => { // For new files in each directory promise.then((newFiles) => { files = files.concat(newFiles.files); }); }); Promise.all(promises).then(() => { resolve({files: files, dir: directory}); }); } else resolve({files: files, dir: directory}); }); }); } findStaticFiles() { return new Promise((resolve, reject) => { this.findFiles(this.staticDir).then(({files}) => { // Remove static directory from start of string this.staticFiles = files.map((file) => { return file.replace(/^[^\s/\\]+\/(.+)$/, "$1"); }); resolve(); }).catch(reject); }); } // Adds a function to an end point addFunction(name, func) { this.functions[name] = func; } incomingRequest(request, response) { request.url = url.parse(request.url); request.url.pathname = request.url.pathname == "/" ? "index.html" : request.url.pathname.slice(1); // Promise allows asynchronous actions to take place and response to be sent in one place new Promise((resolve, reject) => { if (this.staticFiles.indexOf(request.url.pathname) > -1) { // Static file requested fs.readFile(`${this.staticDir}/${request.url.pathname}`, (err, file) => { if (err) reject(err); let fileType = request.url.pathname.match(/^.+?\.([\w\d]+)$/)[1]; let contentType; switch (fileType) { case "ttf": contentType = "font/ttf"; break; case "jpg": case "jpeg": contentType = "image/jpeg"; break; case "svg": contentType = "image/svg+xml"; break; case "js": contentType = "text/javascript"; break; default: contentType = `text/${fileType}`; break; } fileType = fileType == "js" ? "javascript" : fileType; resolve({statusCode: 200, data: file, headers: {"Content-Type": contentType}}); }); } else if (Object.keys(this.functions).indexOf(request.url.pathname) > -1) { this.functions[request.url.pathname](request).then(resolve); } else { // 404 resolve({statusCode: 404}); } }).then(({statusCode, data, cookies, headers}) => { // Send response console.log(`${statusCode}: ${request.url.path}`); response.statusCode = statusCode; // Adds any cookies that need to be added if (cookies != undefined) { let cookieArray = [] for (let cookie of cookies) { let expireString = cookie.expires != undefined ? `expires=${cookie.expires}` : ""; cookieArray.push(`${cookie.name}=${cookie.value}; ${expireString}`); } response.setHeader("Set-Cookie", cookieArray); } // Add any other headers if (headers != undefined) { Object.keys(headers).forEach((header) => { response.setHeader(header, headers[header]); }); } response.end(data); }).catch((err) => { throw err; }); } } module.exports = Server;
true
7a0e0101755df1b0be6770b4acde82647bbda7df
JavaScript
YuryRegis/StarKid
/comandos/tags.js
UTF-8
5,477
2.734375
3
[]
no_license
const { MessageEmbed } = require("discord.js"); const getID = require('../funcoes/ids.json'); const { promptMessage } = require("../funcoes.js"); const { verificaPerm } = require('../funcoes/members'); const opcoes = [`👤`,`👥`,`👑`,`🤠`,`🎹`,`🎨`,`🔰`,`🗺️`,`🧢`,`🧚`,`🤳`,`🎒`,`❤️`,`💍`,`💍`,`😄`,`💋`, `💙`,`🧓`,`🃏`] exports.help = { name: "tags" } exports.run = async (client, message, args) => { const flood = client.channels.cache.get(getID.sala.FLOOD), salaLogs = client.channels.cache.get(getID.sala.LOGS); const perm = await verificaPerm(message.member); if(message.channel.id != flood.id && !perm){ return message.channel.send(`Este comando não é permitido nesse canal. Use o canal ${flood} , por gentileza.`) } const embed = new MessageEmbed(); embed.setTitle("**ThatSkyGameBrasil - TAGS**"); embed.setColor("RANDOM"); embed.setThumbnail("https://image.freepik.com/vetores-gratis/tag-neon-verde-noite-brilhante-elemento-de-propaganda_1262-13490.jpg"); embed.setFooter(message.guild.me.displayName, client.user.displayAvatarURL); embed.setDescription("Escolha **uma** TAG clicando na reação correspondente:\n") embed.addField("**Tags Customizáveis**","👤 - Jogador Solo \n👥 - Formador de grupos \n" + "👑 - Colecionador \n🤠 - Explorador \n🎹 - Músico Skyniano \n🎨 - Desenhista / Pintor \n" + "🔰 - Veterano \n🗺️ - Guia Turístico \n🧢 - Turista \n🧚 - Ajudante \n🎒 - Carregado \n" + "❤️ - Trocador \n🤳 - YouTuber\n💍 - Casado\n😄 - Solteiro\n💋 - Namorando\n💙 - Capa azul\n"+ "🧓 - Elder \n🃏 - UNO") embed.setTimestamp(); //Envia mensagem richEmbed const m = await message.channel.send(embed); //Adiciona reações e aguarda 30 segundos por uma escolha do usuário const cargoEscolhido = await promptMessage(m, message.author, 30, opcoes); if (cargoEscolhido === `👤`) { var chave = "Jogador Solo" } else if (cargoEscolhido === `👥`) { var chave = "Formador de Grupos" } else if (cargoEscolhido === `👑`) { var chave = "Colecionador" } else if (cargoEscolhido === `🤠`) { var chave = "Explorador" } else if (cargoEscolhido === `🤠`) { var chave = "Músico Skyniano" } else if (cargoEscolhido === `🎨`) { var chave = "Desenhista / Pintor" } else if (cargoEscolhido === `🔰`) { var chave = "Veterano" } else if (cargoEscolhido === `🗺️`) { var chave = "Guia Turístico" } else if (cargoEscolhido === `🧢`) { var chave = "Turista" } else if (cargoEscolhido === `🧚`) { var chave = "Ajudante" } else if (cargoEscolhido === `🎒`) { var chave = "Carregado" } else if (cargoEscolhido === `❤️`) { var chave = "Trocador" } else if (cargoEscolhido === `🤳`) { var chave = "🚩 🆈🅾🆄🆃🆄🅱🅴🆁" } else if (cargoEscolhido === "💍") { var chave = "Casado" } else if (cargoEscolhido === "😄") { var chave = "Solteiro" } else if (cargoEscolhido === "💋") { var chave = "Namorando" } else if (cargoEscolhido === "💙") { var chave = "Capa azul" } else if (cargoEscolhido === `🧓`) { var chave = "Elder" } else if (cargoEscolhido === `🃏`) { var chave = "UNO" } else { embed.addField("**TAG NÃO DEFINIDA**",`Use o comando \`!tags\` novamente.`); m.edit(embed); message.delete(); return m.delete(15000) }; // retorna nada para caso de emoji diferente var cargo = await message.guild.roles.cache.find(role => role.name.toLowerCase() === chave.toLowerCase()); var member = await message.guild.members.cache.find(member => member.id === message.author.id); if (cargo == null) { // Caso não exista o cargo com o valor de chave passado embed.addField(`TAG ${chave.toUpperCase()} NÃO ENCONTRADA`) m.edit(embed) message.delete() return m.delete(15000) } // se o membro ja tiver o cargo selecionado, apague o mesmo if (member.roles.cache.some(x => x.name === cargo.name)) { member.roles.remove(cargo.id) .then(member => { console.log(`${member.user.username} removeu o cargo ${cargo.name}`); salaLogs.send(`${member.displayName} removeu o cargo ${cargo.name}`); }) .catch(err => console.log(err)); embed.addField("**\nREMOVIDO**", `${member.user.username} removeu o cargo ${cargo.name}\n` + `Use o comando \`!cargo\` novamente para adicionar ou remover outro cargo.`); } else { // caso contrario, adicione cargo selecionado member.roles.add(cargo.id) .then(member => { var nome = member.user.username; console.log(`${nome} adicionou o cargo ${chave}`); salaLogs.send(`${nome} adicionou o cargo ${chave}`); }) .catch(err => console.error); embed.addField("**\nADICIONADO**", `${member.user.username} adicionou a tag ${cargo.name}\n` + `Use o comando \`!tags\` novamente para adicionar ou remover outra tag.`); } m.edit(embed); message.delete(); m.delete({timeout:40000}); return }
true
83407c4f014c30ef74a309c35e2a0d198b120b05
JavaScript
alok-singh/leetcode
/backtracking/letterCasePermutation.js
UTF-8
1,457
4.09375
4
[]
no_license
// https://leetcode.com/problems/letter-case-permutation/ /** * @param {string} S * @return {string[]} */ // const letterCasePermutation = (S, currentString = '') => { // if(currentString.length === S.length) { // return ['']; // } // let currentChar = S[currentString.length]; // if(currentChar.toUpperCase() === currentChar.toLowerCase()) { // let resultCapital = letterCasePermutation(S, currentString + currentChar.toUpperCase()); // resultCapital = resultCapital.map(string => `${currentChar.toUpperCase()}${string}`); // return resultCapital; // } else { // let resultCapital = letterCasePermutation(S, currentString + currentChar.toUpperCase()); // let resultSmall = letterCasePermutation(S, currentString + currentChar.toLowerCase()); // resultCapital = resultCapital.map(string => `${currentChar.toUpperCase()}${string}`); // resultSmall = resultSmall.map(string => `${currentChar.toLowerCase()}${string}`); // return [...resultCapital, ...resultSmall]; // } // }; const letterCasePermutation = (S, currentString = '') => { const retList = []; for(let i = 0; i < S.length - 1; i++) { if(isNaN(parseInt(S[i]))) { retList.push(`${S.substring(0, i)}${S[i].toUpperCase()}${S.substring(i + 1)}`); retList.push(`${S.substring(0, i)}${S[i].toLowerCase()}${S.substring(i + 1)}`); } } return retList; } console.log(letterCasePermutation('abc'));
true
3f33349ac2985b60e2eae2e8d8ec3b023d517a3d
JavaScript
Badjessa-git/vr-engine
/Engine/Entities/zoneScript.js
UTF-8
835
2.84375
3
[]
no_license
//This entity script will be attached to zones (function() { //set up entity id storage var _selfEntityID; //Subscribe to channel to listen to notices Messages.subscribe("zoneNotice"); //Stores entity id on creation this.preload = function(entityID) { _selfEntityID = entityID; }; Messages.messageReceived.connect(function (channel, message, senderID, localOnly) { if(message === "deleteZone") { //Self delete Entities.deleteEntity(_selfEntityID); } }); //Upon entering, sends message to engine that zone has been entered this.enterEntity = function() { //Send message to engine to confirm selection var textProp = Entities.getEntityProperties(_selfEntityID, ["name"]); textProp = JSON.stringify(textProp.name); Messages.sendMessage("engine",textProp); }; });
true
5ca05f949d376cab668425b21163ddb68104c7f1
JavaScript
danielcawen/buggy-todomvc
/cypress/integration/todo_list_spec.js
UTF-8
7,436
2.875
3
[]
no_license
context('TODO List', () => { beforeEach(() => { cy.visit('http://qa-challenge.gopinata.com/') cy.get('body').then($element => { if ($element.find("[type='checkbox']").length > 0) { cy.get('.todo-list li') .each(function($el, index, $list){ $el.find('.destroy').click() }) } }) }) it('User is able to add an item into the TODOs list', () => { var max = 30 var min = 5 var text = '' var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz !@#$%^&*()_+=-`~{}[]ñ|\':;/.,<>?" var random = Math.floor(Math.random() * (max - min)) + min for (var i = 0; i < random; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)) cy.get('.new-todo') .type(text).should('have.value', text) .type('{enter}') cy.get('.todo-list').find('label') .should('have.length', 1) .should('have.text', text) }) it('XSS verification', () => { var text = "<script>alert('hello there');</script>" const stub = cy.stub() cy.on ('window:alert', stub) cy.get('.new-todo') .type(text).should('have.value', text) .type('{enter}') .then(() => { expect(stub.getCall(0)).to.be.null }) cy.get('.todo-list').find('label') .should('have.length', 1) .should('have.text', text) }) it('Digits are allowed and correctly displayed in the tasks', () => { cy.get('.new-todo') .type('123').should('have.value', '123') .type('{enter}') cy.get('.todo-list').find('label') .should('have.length', 1) .should('have.text', '123') }) it('Special characters are allowed and correctly displayed in the tasks', () => { cy.get('.new-todo') .type('!@#$%^&*()_+`~=-{}|][";:?><,./\'\\').should('have.value', '!@#$%^&*()_+`~=-{}|][";:?><,./\'\\') .type('{enter}') cy.get('.todo-list').find('label') .should('have.length', 1) .should('have.text', '!@#$%^&*()_+`~=-{}|][";:?><,./\'\\') }) it('User is able to mark an item as completed', () => { cy.get('.new-todo') .type('coffee!').should('have.value', 'coffee!') .type('{enter}') cy.get('.todo-list').find('[type=\'checkbox\']') .check().should('be.checked') cy.get('.todo-list') .find('.completed') .find('label') .should('have.text', 'coffee!') }) it('User is able to remove completed items', () => { cy.get('.new-todo') .type('coffee!').should('have.value', 'coffee!') .type('{enter}') cy.get('.todo-list').find('[type=\'checkbox\']') .check().should('be.checked') cy.get('.clear-completed') .click() cy.get('.todo-list').find('label') .each(($el, index, $list) => { expect($list).to.have.length(0) }) }) it('Only tasks with text are allowed', () => { cy.get('.new-todo') .click() .type('{enter}') cy.get('.todo-list').find('label') .should('have.length', 0) }) it('Verify that long text is displayed inside the label box', () => { let before let after cy.document() .then((doc) => { before = doc.documentElement.scrollWidth }) .then(() => cy.get('.new-todo') .type('qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty .123 qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty qwerty .123!') .type('{enter}') .then(() => { cy.document() .then((doc) => { after = doc.documentElement.scrollWidth expect(before).to.equal(after) }) }) ) }) it('Verify item count', () => { cy.get('.new-todo') .type('coffee!').should('have.value', 'coffee!') .type('{enter}') .type('hamburgers').should('have.value', 'hamburgers') .type('{enter}') .type('asado').should('have.value', 'asado') .type('{enter}') cy.get('.todo-count') .should('have.text', '3 items left') }) it('Verify filter: completed items', () => { cy.get('.new-todo') .type('item 1').should('have.value', 'item 1') .type('{enter}') .type('item 2').should('have.value', 'item 2') .type('{enter}') .type('item 3').should('have.value', 'item 3') .type('{enter}') cy.get('.todo-list').find('[type=\'checkbox\']').first() .check().should('be.checked') cy.get('.filters li').contains('Completed') .click() cy.get('.todo-list').find('label') .should('have.length', 1) }) it('Verify filter: active items', () => { cy.get('.new-todo') .type('item 1').should('have.value', 'item 1') .type('{enter}') .type('item 2').should('have.value', 'item 2') .type('{enter}') .type('item 3').should('have.value', 'item 3') .type('{enter}') cy.get('.todo-list').find('[type=\'checkbox\']').first() .check().should('be.checked') cy.get('.filters li').contains('Active') .click() cy.get('.todo-list').find('label') .should('have.length', 2) }) it('Verify that all items are completed when they are marked as completed', () => { cy.get('.new-todo') .type('item 1').should('have.value', 'item 1') .type('{enter}') .type('item 2').should('have.value', 'item 2') .type('{enter}') .type('item 3').should('have.value', 'item 3') .type('{enter}') cy.get('.todo-list').find('[type=\'checkbox\']') .check().should('be.checked') cy.get('.todo-count') .should('have.text', 'No items left') }) it('User is able to edit an option', () => { cy.get('.new-todo') .type('coffee!').should('have.value', 'coffee!') .type('{enter}') cy.get('.todo-list').find('label') .dblclick() cy.get('.todo-list').find('.editing').find('.edit') .clear() .type('a lot of coffee!').should('have.value', 'a lot of coffee!') .type('{enter}') cy.get('.todo-list').find('label') .should('not.have.text', 'coffee!') cy.get('.todo-list').find('label') .should('have.text', 'a lot of coffee!') }) it('Verify that the label is the same on view mode and edit mode', () => { cy.get('.new-todo') .type('a lot of space') .type('{enter}') cy.get('.todo-list').find('label') .should('have.text', 'a' + '\xa0\xa0\xa0' + 'lot' + '\xa0\xa0\xa0\xa0' + 'of' + '\xa0\xa0\xa0\xa0\xa0' + 'space') cy.get('.todo-list').find('label') .dblclick() cy.get('.todo-list').find('.editing').find('.edit') .should('have.value', 'a' + '\xa0\xa0\xa0' + 'lot' + '\xa0\xa0\xa0\xa0' + 'of' + '\xa0\xa0\xa0\xa0\xa0' + 'space') }) // LOAD TEST: // it('Add 1000 elements and verify the user can remove items', () => { // var number = 0; // var max = 1000 // var min = 0 // while (number < max) { // cy.get('.new-todo') // .type(number) // .type('{enter}') // cy.get('.todo-count') // .should('contain', (number + 1).toString()) // number++ // } // var random = Math.floor(Math.random() * (max - min)) + min // cy.log(random) // cy.get('.todo-list').find('[type=\'checkbox\']') // .eq(random) // .check().should('be.checked') // }) })
true
d3ac87f1e26dcd782c1aa3d0af9dc28cc220eef9
JavaScript
nch0w/uprising
/commands/draw.js
UTF-8
2,364
2.796875
3
[]
no_license
const { games, backup } = require("../models"); const { deepCopier } = require("../helpers"); function execute(message, args, user) { if (message.channel.id in games) { let person = message.author; if (message.mentions.members.first()) { person = message.mentions.members.first().user; } const player = games[message.channel.id].players.find( (element) => element.user === person ); if (player) { if (args.length > 0 && "cc" === args[0].toLowerCase()) { if (["Russia", "ROK"].includes(player.revealed)) { const newcard = games[message.channel.id].deck.shift(); player.specialcards.push(newcard); person.send( `You drew a ${newcard} and placed it on your Country Card.\nYour hand is: ${player.cards.join( ", " )}` ); message.channel.send( `<@${player.id}> drew a card and placed it on their Country Card!` ); backup[message.channel.id].push({ state: deepCopier(games[message.channel.id]), action: "draw", user: person, }); } else { return message.channel.send( `<@${player.id}> not allowed to draw to Country Card.` ); } } else { const newcard = games[message.channel.id].deck.shift(); player.cards.push(newcard); if (player.death === "~~") { player.death = ""; } if (player.specialcards.length > 0) { person.send( `You drew a ${newcard}.\nYour hand is now: ${player.cards.join( ", " )}\nThe card on your Country Card is ${player.specialcards}` ); } else { person.send( `You drew a ${newcard}.\nYour hand is now: ${player.cards.join( ", " )}` ); } message.channel.send(`<@${player.id}> drew a card!`); backup[message.channel.id].push({ state: deepCopier(games[message.channel.id]), action: "draw", user: person, }); } } else { return message.channel.send("User not a player in game."); } } else { return message.channel.send("No game to draw a card in."); } } module.exports = { name: "draw", aliases: ["d"], execute, };
true
e4dbefde452e7b13a3ad0d2b9e122d2a329bdc86
JavaScript
DetlefDmann/dentist_react
/src/components/Patients.js
UTF-8
2,495
2.796875
3
[]
no_license
import React, { useContext, useState } from 'react' import { GlobalContext } from '../GlobalContext' import { v4 as uuid } from "uuid" const Patients = () => { const [state, setState] = useContext(GlobalContext); const [newPatient, setNewPatient] = useState({ firstName:"", lastName:"", phoneNr:"", eMail:"", gender:"", isSick:false, birthYear:"" }) const handleChange = (e) => { const {value , name} = e.target; console.log(value); console.log(name); setNewPatient({ ...newPatient,[name]:value, id:uuid(), }); } const setNewVictim = (e) => { e.preventDefault(); setState({ ...state, patients:[...state.patients, newPatient] }) } return ( <form> <h3>Voeg een nieuwe patient toe.</h3><br/> <label htmlFor="firstName">Voornaam</label><br/> <input type="text" name="firstName" id="firstName" onChange={handleChange} /><br/> <label htmlFor="lastName">Achternaam</label><br/> <input type="text" name="lastName" id="lastName" onChange={handleChange} /><br/> <label htmlFor="phoneNr">Telefoonnummer</label><br/> <input type="tel" name="phoneNr" id="phoneNr" onChange={handleChange}/><br/> <label htmlFor="eMail">E-mail</label><br/> <input type="email" name="eMail" id="eMail" onChange={handleChange}/><br/> <label htmlFor="gender">Geslacht</label><br/> <input type="text" name="gender" id="gender" onChange={handleChange}/><br/> <label htmlFor="birthYear">Geboorte jaar</label><br/> <input type="text" name="birthYear" id="birthYear" onChange={handleChange}/><br/> <p>De volgende gegevens zijn ingevuld: <br/><br/> {newPatient.firstName} <br/> {newPatient.lastName} <br/> {newPatient.phoneNr} <br/> {newPatient.eMail}<br/> {newPatient.birthYear} <br/> Geslacht is: {newPatient.gender}<br/> <br/> Kloppen deze gegevens? </p><br/><br/> <p>Het e-mail adres is als volgt: {newPatient.eMail} <br/><br/> Als alles klopt kunnen we de patient nu toevoegen aan de database. </p><br/> <button onClick={setNewVictim}>Voeg toe</button> </form> ) } export default Patients
true
1f463b5ca58ad1612ffa3973754f905f28710113
JavaScript
inkyysleeves/cruise-shipz
/__tests__/port.test.js
UTF-8
327
2.625
3
[]
no_license
const Port = require("../src/port.js"); describe("port", () => { it("returns a port object", () => { const port = new Port("dover"); expect(new Port()).toBeInstanceOf(Object); }); it("can see a port has a name", () => { const port = new Port("Dover"); expect(port.name).toEqual('Dover'); }); });
true
c925ca636006a74596e6f1e81a535d336e214a26
JavaScript
Project-AirPods/booking-module
/database/index.js
UTF-8
4,369
2.53125
3
[]
no_license
const config = require('./config.js'); const { Pool, Client } = require('pg'); const client = new Client(config); client.connect(); module.exports.getCoreData = function getBaseDataForListing(listingId, callback) { const query = `SELECT l.*, ROUND(AVG(p.cost_per_night), 0) as avg_cost_per_night FROM listings l JOIN listing_daily_prices p ON l.id = p.listing_id WHERE l.id = ${listingId} GROUP BY 1,2,3,4,5,6,7`; client.query(query, (err, results) => { if (err) { callback(err, null); } else { results.rows[0].avg_rating = parseFloat(results.rows[0].avg_rating); results.rows[0].cleaning_fee = parseFloat(results.rows[0].cleaning_fee); results.rows[0].service_fee_perc = parseFloat(results.rows[0].service_fee_perc); results.rows[0].occ_tax_rate_perc = parseFloat(results.rows[0].occ_tax_rate_perc); results.rows[0].additional_guest_fee = parseFloat(results.rows[0].additional_guest_fee); results.rows[0].avg_cost_per_night = parseFloat(results.rows[0].avg_cost_per_night); callback(null, results.rows); } }); }; module.exports.getReservationData = function getReservationDataForDateRange(listingId, startDate, endDate, callback) { const query = `SELECT id, start_date, end_date FROM reservations WHERE listing_id = ${listingId} AND (start_date BETWEEN '${startDate}' AND '${endDate}' OR end_date BETWEEN '${startDate}' AND '${endDate}');`; client.query(query, (err, results) => { if (err) { callback(err, null); } else { callback(null, results.rows); } }); }; const getMaxPrice = function getMaxPrice(listingId, callback) { const maxQuery = `SELECT id, start_date, cost_per_night FROM listing_daily_prices WHERE listing_id = ${listingId} ORDER BY start_date DESC LIMIT 1;`; client.query(maxQuery, (err, results) => { if (err) { callback(err, null); } else { for (var i = 0; i < results.rows.length; i++) { results.rows[i].cost_per_night = parseFloat(results.rows[i].cost_per_night); } callback(null, results.rows); } }); }; module.exports.getPricingData = function getPricingDataForDateRange(listingId, startDate, endDate, callback) { const query = `SELECT id, start_date, cost_per_night FROM listing_daily_prices WHERE listing_id = ${listingId} AND start_date < '${endDate}';`; client.query(query, (err, results) => { if (err) { callback(err, null); } else if (results.length > 0) { console.log(results.rows); callback(null, results); } else { // if no results in date range, just get most recent price getMaxPrice(listingId, callback); } }); }; // POST module.exports.postReservationData = function postReservationDataForDateRange(listingId, startDate, endDate, callback) { const idquery = `SELECT id FROM reservations ORDER BY id DESC LIMIT 1;`; client.query(idquery, (err, results) => { if (err) { callback(err, null); } else { const query = `INSERT INTO reservations (id, listing_id, start_date, end_date) VALUES (${results.rows[0].id + 1}, ${listingId}, (to_date('${startDate}', 'YYYY-MM-DD')), (to_date('${endDate}', 'YYYY-MM-DD')));`; client.query(query, (err, results) => { if (err) { callback(err, null); } else { callback(null, results.rows); } }); } }); }; // DELETE module.exports.deleteReservationData = function deleteReservationDataForDateRange(listingId, startDate, endDate, callback) { const query = `DELETE FROM reservations WHERE listing_id = ${listingId} AND start_date = '${startDate}' AND end_date = '${endDate}';`; client.query(query, (err, results) => { if (err) { callback(err, null); } else { callback(null, results.rows); } }); }; // PUT module.exports.putReservationData = function putReservationDataForDateRange(listingId, startDate, endDate, newStartDate, newEndDate, callback) { const query = `UPDATE reservations SET start_date = '${newStartDate}', end_date = '${newEndDate}' WHERE listing_id = ${listingId} AND start_date = '${startDate}' AND end_date = '${endDate}';`; client.query(query, (err, results) => { if (err) { callback(err, null); } else { callback(null, results.rows); } }); };
true
d7ba186688c36ecdf5243163fc2e3c0a7ea1b29e
JavaScript
KhangNguyen007/cliexa
/public/javascripts/Rectangle.js
UTF-8
1,293
3.15625
3
[]
no_license
class Rectangle{ constructor() { } //Create without onClick create(x,y,height,width,fill,zIndex){ let svgns = "http://www.w3.org/2000/svg" var rect = document.createElementNS(svgns, 'rect'); //Create a path in SVG's namespace rect.setAttributeNS(null, 'x', x.toString()); rect.setAttributeNS(null, 'y', y.toString()); rect.setAttributeNS(null, 'height', height.toString()); rect.setAttributeNS(null, 'width', width.toString()); rect.setAttributeNS(null, 'fill', fill); rect.setAttributeNS(null, 'z-index', zIndex); $("svg").append(rect); } //Create with onClick createWithOnClick(x,y,height,width,fill,zIndex,onclick){ let svgns = "http://www.w3.org/2000/svg" var rect = document.createElementNS(svgns, 'rect'); //Create a path in SVG's namespace rect.setAttributeNS(null, 'x', x.toString()); rect.setAttributeNS(null, 'y', y.toString()); rect.setAttributeNS(null, 'height', height.toString()); rect.setAttributeNS(null, 'width', width.toString()); rect.setAttributeNS(null, 'fill', fill); rect.setAttributeNS(null, 'z-index', zIndex); rect.setAttributeNS(null, 'onclick', onclick); $("svg").append(rect); } }
true
8f3da745544be5303a2bdda2ae19d04196d29c16
JavaScript
enodi/phone-number-generator
/client/src/pages/DetailsPage/index.js
UTF-8
2,037
2.625
3
[]
no_license
import React, { Fragment, useEffect, useState } from "react"; import Header from "../../components/Header"; import SubHeader from "../../components/SubHeader"; import Button from "../../components/Button"; import { getPhoneNumbers, downloadPhoneNumbers } from "../../../helpers/config"; import "./style.scss"; const DetailsPage = () => { const [phoneNumber, setPhoneNumbers] = useState({}); useEffect(() => { async function fetchData() { const response = await getPhoneNumbers(); setPhoneNumbers(response.data.data); } fetchData(); }, []); const handleDownload = async () => { const response = await downloadPhoneNumbers(); const numbers = (response.data.randomPhoneNumbers).join("\n"); const url = window.URL.createObjectURL(new Blob([numbers])); const link = document.createElement("a"); link.href = url; link.setAttribute("download", "phone-numbers.txt"); document.body.appendChild(link); link.click(); }; const redirectToHomePage = () => { window.location.href = "/"; }; return ( <Fragment> <Header /> <SubHeader title="View the largest and smallest number generated"/> <div className="number-display"> <div className="content"> <h2>Largest Phone Number: <span>{phoneNumber.largestNumber}</span></h2> <h2>Smallest Phone Number: <span>{phoneNumber.smallestNumber}</span></h2> <h2>Total Phone Numbers Generated: <span>{phoneNumber.totalPhoneNumbersGenerated}</span></h2> </div> <div className="content__button"> <Button id="btn" className="download__button" text="Download File" type="button" onClick={handleDownload} /> <Button id="btn" className="return__button" text="Return to Home Page" type="button" onClick={redirectToHomePage} /> </div> </div> </Fragment> ); }; export default DetailsPage;
true
0c4d6095764791b473043167bcec505a3e8cd7db
JavaScript
dlevenson44/blockchallenge-2
/client/src/components/BtcController.jsx
UTF-8
2,524
2.765625
3
[]
no_license
// import dependency import React, { Component } from 'react'; class BtcController extends Component { constructor(props) { super(props) // bind functions this.sendToDb = this.sendToDb.bind(this) } sendToDb() { // do not sent to DB until all API calls are ran, prevent 0 values from being entered console.log(this.props.fetched) if ((this.props.fetched === true)) { fetch('/crypto', { headers: { 'Content-Type': 'application/json', }, method: 'POST', // convert props to JSON string body: JSON.stringify({ usd: this.props.btc.usd, us_high: this.props.btc.usHigh, us_low: this.props.btc.usLow, eur: this.props.btc.eur, eur_high: this.props.btc.eurHigh, eur_low: this.props.btc.eurLow, trades: this.props.btc.trades, one_hour: this.props.btc.oneHour, one_day: this.props.btc.oneDay, one_week: this.props.btc.oneWeek, crypto_id: 1 }), // send JSON response }).then(res => res.json()) // catch errors .catch(err => console.log(err)) } } render() { this.sendToDb() return( <div className="crypto-container"> <h5>Trends:</h5> <p>{this.props.btc.trades} trades in the last 24 hours</p> <p>{this.props.btc.oneHour}% change in last hour</p> <p>{this.props.btc.oneDay}% change in last 24 hours</p> <p>{this.props.btc.oneWeek}% change in last 7 days</p> <h5>BTC US Market Info</h5> <p>${(this.props.btc.usd).substring(0, 8)} per BTC</p> <p>${(this.props.btc.usHigh).substring(0, 8)} is the 24 hour high</p> <p>${(this.props.btc.usLow).substring(0, 8)} is the 24 hour low</p> <h5>BTC EU Market Info</h5> <p>€{(this.props.btc.eur).substring(0, 8)} per BTC</p> <p>€{(this.props.btc.eurHigh).substring(0, 8)} is the 24 hour high</p> <p>€{(this.props.btc.eurLow).substring(0, 8)} is the 24 hour low</p> </div> ) } } export default BtcController
true
99a57f9f1d56fc424169677997299e2f47fdc221
JavaScript
grayson073/lab10-BusMall
/js/app.js
UTF-8
1,705
2.953125
3
[]
no_license
/* globals ImageDisplay ResultsDisplay imageArray getRandomImage */ /*exported App */ const appTemplate = document.getElementById('app-template'); class App { constructor() { this.products = imageArray; this.totalVotes = 0; } getThreeRandomImages() { const displayImages = []; const copy = this.products.slice(); for(var i = 0; i < 3; i++) { const randomImage = getRandomImage(copy); randomImage.timesShown++; displayImages.push(randomImage); } return displayImages; } render() { const dom = appTemplate.content; // Image Display rendering const addDisplaySection = dom.getElementById('image-display'); const addDisplayComponent = new ImageDisplay(this.getThreeRandomImages(), (image) => { // Anonymous functions becomes userVoted inside of ImageDisplay.js this.totalVotes++; image.timesVoted++; if(this.totalVotes >= 25) { alert('Thanks for voting!'); window.location.href = 'results.html'; } else { addDisplayComponent.update(this.getThreeRandomImages()); addResultsComponent.update(this.products); } }); addDisplaySection.appendChild(addDisplayComponent.render()); // Results Display rendering const addResultsSection = dom.getElementById('results-display'); const addResultsComponent = new ResultsDisplay(); addResultsSection.appendChild(addResultsComponent.render()); return dom; } }
true
9e063b7282b0917ccd420d0dad97e510d01bde25
JavaScript
SonavAgarwal/java-swing-component-creator
/src/components/JavaComponents/ScreenClassMaker.js
UTF-8
3,139
3.0625
3
[]
no_license
import { getJavaClass, getJavaTextAlignConstant } from "./JComponentData"; export function makeClassText(components) { let componentDeclarations = ""; components.forEach((element) => { componentDeclarations += "private " + getJavaClass(element.type) + " " + element.variableName + ";\n"; }); console.log(componentDeclarations); let componentInitializations = []; components.forEach((element) => { let initString = ""; initString += `${element.variableName} = new ${getJavaClass(element.type)}();\n`; initString += `${element.variableName}.setFont(new Font("Arial", ${element.font.bolded ? "Font.BOLD" : "Font.PLAIN"}, ${element.font.size}));\n`; initString += `${element.variableName}.setHorizontalAlignment(${getJavaTextAlignConstant(element.type)});\n`; initString += `${element.variableName}.setBounds(${element.x + 5}, ${element.y + 5}, ${element.width}, ${element.height});\n`; initString += `this.add(${element.variableName});\n`; if (element.type === "button") initString += `${element.variableName}.addActionListener(this);\n`; componentInitializations.push(initString); }); componentInitializations.forEach((element) => { console.log(element + "\n"); }); } export function makeComponentDeclarations(components) { let componentDeclarations = "// Remember to change your frame dimensions\n\n// Add to your screen class \n\n"; components.forEach((element) => { componentDeclarations += "private " + getJavaClass(element.type) + " " + element.variableName + ";\n"; }); return componentDeclarations; } export function makeComponentInitializations(components) { // let componentInitializations = []; let componentInitializations = "// Add to your screen class constructor \n\n"; components.forEach((element) => { let initString = ""; console.log(element); console.log(getJavaTextAlignConstant(element.textAlign)); initString += `${element.variableName} = new ${getJavaClass(element.type)}();\n`; initString += `${element.variableName}.setFont(new Font("Arial", ${element.font.bolded ? "Font.BOLD" : "Font.PLAIN"}, ${element.font.size}));\n`; if (element.type !== "comboBox") initString += `${element.variableName}.setHorizontalAlignment(${getJavaTextAlignConstant(element.textAlign)});\n`; initString += `${element.variableName}.setBounds(${element.x + 5}, ${element.y + 5}, ${element.width}, ${element.height});\n`; if (element.type !== "comboBox") initString += `${element.variableName}.setText("${element.text}");\n`; initString += `this.add(${element.variableName});\n`; if (element.type === "button") initString += `${element.variableName}.addActionListener(this);\n`; if (element.type == "comboBox") initString += `${element.variableName}.addItem("${element.text}"); // Remeber to add more options\n`; initString += `\n`; // componentInitializations.push(initString); componentInitializations += initString; }); return componentInitializations; }
true
ddac26efc7861b698a3d9a4edc543770655e62a3
JavaScript
Gitkat91/Level_0_Coding_Challenge
/Task4.js
UTF-8
165
3.359375
3
[]
no_license
function evenOrOdd(numb) { if (numb % 2 == 0) { rtnString = "even"; } else { rtnString = "odd"; } return console.log(rtnString); } evenOrOdd(781);
true
e54e4034c251db113a558c76cc138ecc1c0fbfce
JavaScript
levythu/encloure.io
/utils/lock.js
UTF-8
908
2.90625
3
[]
no_license
// Multiple-Lock, use queue to maintain holder. Each lock instance could be held by // at most k functions. The rests have to wait. // // Author: Levy (levythu) // Date: 2016/04/02 (function() { var Queue=require("./queue"); function Lock(maxHolder) { if (maxHolder==null) this.rest=1; else this.rest=maxHolder; this.waitingQueue=new Queue(); } Lock.prototype.Lock=function(callback) { if (this.rest==0) { // No more lock to use, stuck it. this.waitingQueue.EnQueue(callback); return; } this.rest--; callback(); } Lock.prototype.Unlock=function() { if (this.waitingQueue.len>0) { process.nextTick(this.waitingQueue.DeQueue()); return; } this.rest++; } module.exports=Lock; })();
true
58f2744039b975404e315a87bbf77cc3f0252e6f
JavaScript
DWL321/Web2.0_homework
/web第七次作业/优化/修改后/js/Whac-a-mole.js
UTF-8
2,277
2.9375
3
[]
no_license
/*19335040 丁维力*/ /*打地鼠小游戏脚本文件*/ /*初始化全局变量*/ var time_ = 30; var timer = null; var score_ = 0; var mole = -1;//纪录地鼠出现位置,-1表示未出现地鼠 var hit = -2;//记录打击位置,-2表示地鼠未出现,-1表示未击打 var playing = false; /*添加当玩家鼠标点击元素时触发的事件监听器*/ $(function () { $('#start').click(game_start); $('#stop').click(game_over); $('[name="hole"]').click(check); }); // 重置控制游戏的全局变量 function reset_control(){ hit=-2; time_=30; score_=0; playing=true; if(timer!==null)clearInterval(timer); } /*游戏开始,倒计时重置*/ function game_start() { reset_control(); $('#time_value').text(time_); $('#score_value').text(score_); timer=setInterval(countdown,1000); $("#over").text("Game Start"); appear(); } /*检测上一个地鼠出现的时间段内玩家是否落下锤子*/ function check_last(){ if(hit==-1&&mole!==-1){ score_--; $('#score_value').text(score_); } } /*地鼠每秒随机出现一次*/ function appear(){ if(playing==true){ check_last(); var next=$('[name="hole"]')[_.random(59)].value; mole=(next==mole)? (next+1)%60:next;//防止连续两次地鼠在同一个地方出现 $('[name="hole"]')[mole].checked="true"; hit=-1; } }setInterval("appear()",1000); /*游戏倒计时*/ function countdown(){ time_--; $('#time_value').text(time_); if(playing==false||time_<=0){ clearInterval(timer); game_over(); } } /*游戏结束,倒计时停止,输出结束提示*/ function game_over() { playing=false; $("#over").text("Game Over"); } /*玩家点击洞,检测是否砸中地鼠*/ function check() { if(playing==true&&hit<0) for(hit=0;hit<$('[name="hole"]').length;hit++) if($('[name="hole"]')[hit].checked){ $('[name="hole"]')[hit].checked=false; score_=($('[name="hole"]')[hit].value==$('[name="hole"]')[mole].value)? score_+1:score_-1; $('#score_value').text(score_); return ; } }
true
e0eb70b81969e71d1556820f05336ef5cf6b2384
JavaScript
apparition47/LeetCode
/124 - Binary Tree Maximum Path Sum.js
UTF-8
785
3.328125
3
[]
no_license
// https://leetcode.com/problems/binary-tree-maximum-path-sum/ /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var maxPathSum = function(root) { const dfs = node => { if (!node) return 0 let left=0,right=0 if (node.left) left=Math.max(dfs(node.left),0) if (node.right) right=Math.max(dfs(node.right),0) opt = Math.max(opt, left+right+node.val) return node.val + Math.max(left,right) } let opt = Number.MIN_SAFE_INTEGER dfs(root) return opt };
true
bba4af331d6baeba98be0898157d585ee1ee66b9
JavaScript
floraxue/TextThresher
/app/components/quiz/QuizContext.js
UTF-8
1,019
2.578125
3
[ "Apache-2.0" ]
permissive
import React from 'react'; export default React.createClass({ displayName: 'QuizContext', propTypes: { context: React.PropTypes.object.isRequired }, render() { var text = this.props.context.text; var highlights = this.props.context.highlights; var start = 0; var tail = ''; var l = highlights.length; if (highlights[l - 1][1] !== text.length) { tail = <span>{text.substring(highlights[l - 1][1], text.length)}</span>; } return ( <p className='quiz__context'> {Array(highlights.length * 2).fill().map((_,i) => { var curHL = highlights[i / 2 | 0]; if (i % 2 === 0) { // render normal text return (<span key={i}>{text.substring(start, curHL[0])}</span>); } else { // render highlight start = curHL[1]; return (<span key={i} className='highlighted'>{text.substring(curHL[0], curHL[1])}</span>); } })} { tail } </p> ); } });
true
1acffb274176662e4b0935b2e239ad8b63eb478e
JavaScript
CaliZam/skylab-bootcamp-202004
/staff/albert-manzano/web-components/app-custom/logic/search-users.js
UTF-8
870
3.125
3
[]
no_license
function searchUsers(query) { debugger query=query.toLowerCase() const _users = users.filter(function(user){ const {name, surname,email}= user return name.toLowerCase().includes(query)||surname.toLowerCase().includes(query)||email.toLowerCase().includes(query) }) //sanitaze //???? mirar debugger // _users = _users.map(function(user){ // const {name,surname,email}=user // return {name,surname,email} // }) const __users = _users.map(function ({ name, surname, email }) { return { name, surname, email } }) return __users } // const result = Result(user) // const resultList = document.getElementById('resultslist') // if(resultList !== null) resultList.remove() // if(result !== null) container.appendChild(result)
true
eac6e79a7494e10df0b29e24a4fa2081dfdcb6ba
JavaScript
HirokoAB/visitor_hp
/umi/js/map-env.js
UTF-8
13,429
2.5625
3
[]
no_license
/***************** Google Map API ******************/ // //function initialize() { // var latlng1 = new google.maps.LatLng(38.824771, 141.586855); // var latlng2 = new google.maps.LatLng(38.814585, 141.567160); // var latlng3 = new google.maps.LatLng(38.824771, 141.586855); // // var opts1 = { // zoom: 13, // center: latlng1, // mapTypeId: google.maps.MapTypeId.ROADMAP // }; // // var opts2 = { // zoom: 13, // center: latlng2, // mapTypeId: google.maps.MapTypeId.ROADMAP // }; // // var opts3 = { // zoom: 13, // center: latlng3, // mapTypeId: google.maps.MapTypeId.ROADMAP // }; // // var map1 = new google.maps.Map(document.getElementById("map_canvas1"), opts1); // var marker1 = new google.maps.Marker({ // position: latlng1, //マーカーの位置 // map: map1, //表示する地図 // title: "東京本社" //ロールオーバー テキスト // }); // var map2 = new google.maps.Map(document.getElementById("map_canvas2"), opts2); // var marker2 = new google.maps.Marker({ // position: latlng2, //マーカーの位置 // map: map2, //表示する地図 // title: "大阪支店" //ロールオーバー テキスト // }); // var map3 = new google.maps.Map(document.getElementById("map_canvas3"), opts3); // var marker3 = new google.maps.Marker({ // position: latlng3, //マーカーの位置 // map: map3, //表示する地図 // title: "福岡営業所" //ロールオーバー テキスト // }); //} //function initialize() { // var latlng = new google.maps.LatLng(38.634281, 141.528421); // var myOptions = { // zoom: 14, /*拡大比率*/ // center: latlng,/*表示枠内の中心点*/ // scrollwheel: false, // mapTypeControlOptions: { mapTypeIds: ['msmvc', google.maps.MapTypeId.ROADMAP] }/*表示タイプの指定*/ // }; // var map = new google.maps.Map(document.getElementById('map_canvas1'), myOptions); // // var icon = new google.maps.MarkerImage('img/ico.png', // new google.maps.Size(72,72),/*アイコンサイズ*/ // new google.maps.Point(0,0) // ); // var markerOptions = { // position: latlng, // map: map, // icon: icon, // title: '南三陸・海のビジターセンター' // }; // var marker = new google.maps.Marker(markerOptions); // // var mapStyle = [ // { // "stylers": [ //// { "hue": "#009AE0" }, // { "saturation": -100 } // ] // } // ]; // var mapType = new google.maps.StyledMapType(mapStyle); // map.mapTypes.set('GrayScaleMap', mapType); // map.setMapTypeId('GrayScaleMap'); //} // //google.maps.event.addDomListener(window, 'load', initialize); function googleMap() { var latlng = new google.maps.LatLng(38.824771, 141.586855);/* 座標 */ var myOptions = { zoom: 14, /*拡大比率*/ center: latlng, mapTypeControlOptions: { mapTypeIds: ['style', google.maps.MapTypeId.ROADMAP] } }; var map = new google.maps.Map(document.getElementById('map1'), myOptions); /*アイコン設定*/ var icon = new google.maps.MarkerImage('https://maps.google.com/mapfiles/ms/icons/blue-dot.png',/*画像url*/ new google.maps.Size(32,32),/*アイコンサイズ*/ new google.maps.Point(0,0)/*アイコン位置*/ ); var markerOptions = { position: latlng, map: map, icon: icon, title: 'お伊勢浜',/*タイトル*/ }; var marker = new google.maps.Marker(markerOptions); /*取得スタイルの貼り付け*/ var styleOptions = [ { "stylers": [ { "saturation": -100 } ] } ]; var styledMapOptions = { name: ' ' }/*地図右上のタイトル*/ var sampleType = new google.maps.StyledMapType(styleOptions, styledMapOptions); map.mapTypes.set('style', sampleType); map.setMapTypeId('style'); }; function googleMap2() { var latlng = new google.maps.LatLng(38.814585, 141.567160);/* 座標 */ var myOptions = { zoom: 14, /*拡大比率*/ center: latlng, mapTypeControlOptions: { mapTypeIds: ['style', google.maps.MapTypeId.ROADMAP] } }; var map = new google.maps.Map(document.getElementById('map2'), myOptions); /*アイコン設定*/ var icon = new google.maps.MarkerImage('https://maps.google.com/mapfiles/ms/icons/blue-dot.png',/*画像url*/ new google.maps.Size(32,32),/*アイコンサイズ*/ new google.maps.Point(0,0)/*アイコン位置*/ ); var markerOptions = { position: latlng, map: map, icon: icon, title: '大谷海岸',/*タイトル*/ animation: google.maps.Animation.DROP/*アニメーション*/ }; var marker = new google.maps.Marker(markerOptions); /*取得スタイルの貼り付け*/ var styleOptions = [ { "stylers": [ { "saturation": -100 } ] } ]; var styledMapOptions = { name: ' ' }/*地図右上のタイトル*/ var sampleType = new google.maps.StyledMapType(styleOptions, styledMapOptions); map.mapTypes.set('style', sampleType); map.setMapTypeId('style'); }; function googleMap3() { var latlng = new google.maps.LatLng(38.781610, 141.517811);/* 座標 */ var myOptions = { zoom: 14, /*拡大比率*/ center: latlng, mapTypeControlOptions: { mapTypeIds: ['style', google.maps.MapTypeId.ROADMAP] } }; var map = new google.maps.Map(document.getElementById('map3'), myOptions); /*アイコン設定*/ var icon = new google.maps.MarkerImage('https://maps.google.com/mapfiles/ms/icons/blue-dot.png',/*画像url*/ new google.maps.Size(32,32),/*アイコンサイズ*/ new google.maps.Point(0,0)/*アイコン位置*/ ); var markerOptions = { position: latlng, map: map, icon: icon, title: '赤崎海岸',/*タイトル*/ animation: google.maps.Animation.DROP/*アニメーション*/ }; var marker = new google.maps.Marker(markerOptions); /*取得スタイルの貼り付け*/ var styleOptions = [ { "stylers": [ { "saturation": -100 } ] } ]; var styledMapOptions = { name: ' ' }/*地図右上のタイトル*/ var sampleType = new google.maps.StyledMapType(styleOptions, styledMapOptions); map.mapTypes.set('style', sampleType); map.setMapTypeId('style'); }; function googleMap4() { var latlng = new google.maps.LatLng(38.750453, 141.466874);/* 座標 */ var myOptions = { zoom: 14, /*拡大比率*/ center: latlng, mapTypeControlOptions: { mapTypeIds: ['style', google.maps.MapTypeId.ROADMAP] } }; var map = new google.maps.Map(document.getElementById('map4'), myOptions); /*アイコン設定*/ var icon = new google.maps.MarkerImage('https://maps.google.com/mapfiles/ms/icons/blue-dot.png',/*画像url*/ new google.maps.Size(32,32),/*アイコンサイズ*/ new google.maps.Point(0,0)/*アイコン位置*/ ); var markerOptions = { position: latlng, map: map, icon: icon, title: '田束山',/*タイトル*/ animation: google.maps.Animation.DROP/*アニメーション*/ }; var marker = new google.maps.Marker(markerOptions); /*取得スタイルの貼り付け*/ var styleOptions = [ { "stylers": [ { "saturation": -100 } ] } ]; var styledMapOptions = { name: ' ' }/*地図右上のタイトル*/ var sampleType = new google.maps.StyledMapType(styleOptions, styledMapOptions); map.mapTypes.set('style', sampleType); map.setMapTypeId('style'); }; function googleMap5() { var latlng = new google.maps.LatLng(38.692021, 141.559893);/* 座標 */ var myOptions = { zoom: 14, /*拡大比率*/ center: latlng, mapTypeControlOptions: { mapTypeIds: ['style', google.maps.MapTypeId.ROADMAP] } }; var map = new google.maps.Map(document.getElementById('map5'), myOptions); /*アイコン設定*/ var icon = new google.maps.MarkerImage('https://maps.google.com/mapfiles/ms/icons/blue-dot.png',/*画像url*/ new google.maps.Size(32,32),/*アイコンサイズ*/ new google.maps.Point(0,0)/*アイコン位置*/ ); var markerOptions = { position: latlng, map: map, icon: icon, title: '歌津崎',/*タイトル*/ animation: google.maps.Animation.DROP/*アニメーション*/ }; var marker = new google.maps.Marker(markerOptions); /*取得スタイルの貼り付け*/ var styleOptions = [ { "stylers": [ { "saturation": -100 } ] } ]; var styledMapOptions = { name: ' ' }/*地図右上のタイトル*/ var sampleType = new google.maps.StyledMapType(styleOptions, styledMapOptions); map.mapTypes.set('style', sampleType); map.setMapTypeId('style'); }; function googleMap6() { var latlng = new google.maps.LatLng(38.709175, 141.535738);/* 座標 */ var myOptions = { zoom: 14, /*拡大比率*/ center: latlng, mapTypeControlOptions: { mapTypeIds: ['style', google.maps.MapTypeId.ROADMAP] } }; var map = new google.maps.Map(document.getElementById('map6'), myOptions); /*アイコン設定*/ var icon = new google.maps.MarkerImage('https://maps.google.com/mapfiles/ms/icons/blue-dot.png',/*画像url*/ new google.maps.Size(32,32),/*アイコンサイズ*/ new google.maps.Point(0,0)/*アイコン位置*/ ); var markerOptions = { position: latlng, map: map, icon: icon, title: '館崎',/*タイトル*/ animation: google.maps.Animation.DROP/*アニメーション*/ }; var marker = new google.maps.Marker(markerOptions); /*取得スタイルの貼り付け*/ var styleOptions = [ { "stylers": [ { "saturation": -100 } ] } ]; var styledMapOptions = { name: ' ' }/*地図右上のタイトル*/ var sampleType = new google.maps.StyledMapType(styleOptions, styledMapOptions); map.mapTypes.set('style', sampleType); map.setMapTypeId('style'); }; function googleMap7() { var latlng = new google.maps.LatLng(38.668042, 141.462263);/* 座標 */ var myOptions = { zoom: 14, /*拡大比率*/ center: latlng, mapTypeControlOptions: { mapTypeIds: ['style', google.maps.MapTypeId.ROADMAP] } }; var map = new google.maps.Map(document.getElementById('map7'), myOptions); /*アイコン設定*/ var icon = new google.maps.MarkerImage('https://maps.google.com/mapfiles/ms/icons/blue-dot.png',/*画像url*/ new google.maps.Size(32,32),/*アイコンサイズ*/ new google.maps.Point(0,0)/*アイコン位置*/ ); var markerOptions = { position: latlng, map: map, icon: icon, title: '荒島',/*タイトル*/ animation: google.maps.Animation.DROP/*アニメーション*/ }; var marker = new google.maps.Marker(markerOptions); /*取得スタイルの貼り付け*/ var styleOptions = [ { "stylers": [ { "saturation": -100 } ] } ]; var styledMapOptions = { name: ' ' }/*地図右上のタイトル*/ var sampleType = new google.maps.StyledMapType(styleOptions, styledMapOptions); map.mapTypes.set('style', sampleType); map.setMapTypeId('style'); }; function googleMap8() { var latlng = new google.maps.LatLng(38.651827, 141.489248);/* 座標 */ var myOptions = { zoom: 14, /*拡大比率*/ center: latlng, mapTypeControlOptions: { mapTypeIds: ['style', google.maps.MapTypeId.ROADMAP] } }; var map = new google.maps.Map(document.getElementById('map8'), myOptions); /*アイコン設定*/ var icon = new google.maps.MarkerImage('https://maps.google.com/mapfiles/ms/icons/blue-dot.png',/*画像url*/ new google.maps.Size(32,32),/*アイコンサイズ*/ new google.maps.Point(0,0)/*アイコン位置*/ ); var markerOptions = { position: latlng, map: map, icon: icon, title: '椿島',/*タイトル*/ animation: google.maps.Animation.DROP/*アニメーション*/ }; var marker = new google.maps.Marker(markerOptions); /*取得スタイルの貼り付け*/ var styleOptions = [ { "stylers": [ { "saturation": -100 } ] } ]; var styledMapOptions = { name: ' ' }/*地図右上のタイトル*/ var sampleType = new google.maps.StyledMapType(styleOptions, styledMapOptions); map.mapTypes.set('style', sampleType); map.setMapTypeId('style'); }; function googleMap9() { var latlng = new google.maps.LatLng(38.630306, 141.527859);/* 座標 */ var myOptions = { zoom: 14, /*拡大比率*/ center: latlng, mapTypeControlOptions: { mapTypeIds: ['style', google.maps.MapTypeId.ROADMAP] } }; var map = new google.maps.Map(document.getElementById('map9'), myOptions); /*アイコン設定*/ var icon = new google.maps.MarkerImage('https://maps.google.com/mapfiles/ms/icons/blue-dot.png',/*画像url*/ new google.maps.Size(32,32),/*アイコンサイズ*/ new google.maps.Point(0,0)/*アイコン位置*/ ); var markerOptions = { position: latlng, map: map, icon: icon, title: '神割崎',/*タイトル*/ animation: google.maps.Animation.DROP/*アニメーション*/ }; var marker = new google.maps.Marker(markerOptions); /*取得スタイルの貼り付け*/ var styleOptions = [ { "stylers": [ { "saturation": -100 } ] } ]; var styledMapOptions = { name: ' ' }/*地図右上のタイトル*/ var sampleType = new google.maps.StyledMapType(styleOptions, styledMapOptions); map.mapTypes.set('style', sampleType); map.setMapTypeId('style'); }; google.maps.event.addDomListener(window, 'load', function() { googleMap(); googleMap2(); googleMap3(); googleMap4(); googleMap5(); googleMap6(); googleMap7(); googleMap8(); googleMap9(); });
true
28df1b78e45a38743a573f5cb65863146690c4a8
JavaScript
DeLaChance/TravelApp
/backend/test/unit-tests/FileBasedRepositoryUnitTest.js
UTF-8
2,564
2.578125
3
[]
no_license
const common = require('../common'); const expect = common.expect; const FileBasedRepository = require('../../domain/TravelDestination/FileBasedRepository'); const User = require('../../domain/TravelDestination/User'); const ErrorMessage = require('../../utils/ErrorMessage'); const uuid = require('uuid/v4'); const fs = require('fs-extra') describe('FileBasedRepository', function() { const TMP_DIRECTORY = './tmp/repository/'; var repository; beforeEach('before each test build the repository', function() { repository = new FileBasedRepository(TMP_DIRECTORY); }); afterEach('after each test clear the repository', function() { repository.clear(); }); describe('#persist()', function() { it('when a user is persisted to the repository, it is added to the file system', function(done) { // Given var userId = uuid(); var travelId = uuid(); var user = new User('foo', userId, [travelId]); // When var promise = repository.persist(user); // Then promise.then(returnedUser => { expect(fs.pathExistsSync(TMP_DIRECTORY + userId + "/user.json")).to.be.true; expect(returnedUser.userId).to.be.a('string'); expect(returnedUser.userId).to.equal(userId); expect(returnedUser.userName).to.be.a('string'); expect(returnedUser.userName).to.be.equal('foo'); expect(returnedUser.travelDestinationIds).to.have.lengthOf(1); expect(returnedUser.travelDestinationIds[0]).to.be.a('string'); expect(returnedUser.travelDestinationIds[0]).to.be.equal(travelId); done(); }) .catch(error => expect(error).fail()); }); }); describe('#persist()', function() { it('test that when a user is persisted to the repository twice, that the' + '\n first time it is added to the file system' + '\n and the second time an error is thrown', function(done) { // Given var userId = uuid(); var travelId = uuid(); var user = new User('foo', userId, [travelId]); // When repository.persist(user).then(returnedUser => { var promise = repository.persist(user); expect(Promise.all([ // The user should be there expect(fs.pathExists(TMP_DIRECTORY + userId + "/user.json")).to.eventually.be.true, // But the promise result of the second attempt should be rejected expect(promise).to.be.rejected ])) .and.notify(done); }).catch(error => done(error)); }) }); });
true
dc4ef8c35f7af0d2a265819935efc8b6734b2945
JavaScript
khmais93/myreads-app
/src/SearchBookInput.js
UTF-8
1,189
2.671875
3
[]
no_license
import React, { useState, useEffect } from "react"; import { search } from "./BooksAPI"; function SearchBookInput(props) { const { onSearch } = props; const [searchValue, setSearchValue] = useState(""); const changeHandler = (e) => { setSearchValue(e.target.value); }; useEffect( () => { async function searchData() { try { if (searchValue.length > 0) { { const response = await search(searchValue); if (response.error) { onSearch([]); } else { onSearch(response); } } } else { onSearch([]); } } catch (e) { console.error(e); } } const timeOutId = setTimeout(() => { searchData(); }, 1000); return () => { clearTimeout(timeOutId); }; }, [searchValue] ); return ( <div className="search-books-input-wrapper"> <input value={searchValue} type="text" placeholder="Search by title or author" onChange={changeHandler} /> </div> ); } export default SearchBookInput;
true
47e011225b2332e33af43abdf6edfdf67c24c975
JavaScript
internetfriendsforever/Wireframes.sketchplugin
/Contents/Sketch/wireframes.js
UTF-8
5,210
2.515625
3
[]
no_license
function writeTextToFile (filePath, text) { const t = [NSString stringWithFormat:@"%@", text] const f = [NSString stringWithFormat:@"%@", filePath] return [t writeToFile:f atomically:true encoding:NSUTF8StringEncoding error:nil] } function chooseFolder () { const openPanel = [NSOpenPanel openPanel] [openPanel setTitle: "Choose a location…"] [openPanel setMessage: "Select the export location…"] [openPanel setPrompt: "Export"] [openPanel setCanCreateDirectories: true] [openPanel setCanChooseFiles: false] [openPanel setCanChooseDirectories: true] [openPanel setAllowsMultipleSelection: false] [openPanel setShowsHiddenFiles: false] [openPanel setExtensionHidden: false] const openPanelButtonPressed = [openPanel runModal] if (openPanelButtonPressed == NSFileHandlingPanelOKButton) { return [openPanel URL] } else { exit() } } function createFolder (name) { var fileManager = [NSFileManager defaultManager] [fileManager createDirectoryAtPath:name withIntermediateDirectories:true attributes:nil error:nil] } function deleteFile (name) { var fileManager = [NSFileManager defaultManager] [fileManager removeItemAtPath:name error:nil] } function map (array, fn) { const result = [] array.forEach(item => { result.push(fn(item)) }) return result } function filter (array, fn) { const result = [] array.forEach(item => { if (fn(item)) { result.push(item) } }) return result } function slug (text) { return text.toString().toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') .replace(/\-\-+/g, '-') .replace(/^-+/, '') .replace(/-+$/, '') } function findLayersUsingPredicate (predicate, object, container) { const scope = container.children() const layerPredicate = NSPredicate.predicateWithFormat(predicate, object, container) return [scope filteredArrayUsingPredicate:layerPredicate] } function getLinkLayers (container) { return findLayersUsingPredicate('name BEGINSWITH %@', '->', container) } function onExportWireframes (context) { const document = context.document const exportPath = chooseFolder().path() + '/wireframes' deleteFile(exportPath) createFolder(exportPath) // index.html writeTextToFile(`${exportPath}/index.html`, ` <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <h1>Pages</h1> <ul> ${map(document.pages().reverse(), page => ` <li> <a href="${slug(page.name())}/index.html"> ${page.name()} </a> </li> `).join('\n')} </ul> </body> `) // [page]/index.html document.pages().forEach(page => { const folder = `${exportPath}/${slug(page.name())}` createFolder(folder) page.artboards().forEach(artboard => { const boardIndexPath = `${folder}/${slug(artboard.name())}.html` const boardImageName = `${slug(artboard.name())}.png` const boardImagePath = `${folder}/${boardImageName}` const slice = MSSliceLayer.sliceLayerFromLayer(artboard) const rect = artboard.absoluteRect() slice.absoluteRect().setX(rect.origin().x) slice.absoluteRect().setY(rect.origin().y) slice.absoluteRect().setWidth(rect.size().width) slice.absoluteRect().setHeight(rect.size().height) slice.exportOptions().exportFormats().lastObject().setScale(2) document.saveArtboardOrSlice_toFile(slice, boardImagePath) slice.removeFromParent() const scope = artboard.children() const layerPredicate = NSPredicate.predicateWithFormat('name BEGINSWITH %@', '->') const linkLayers = [scope filteredArrayUsingPredicate:layerPredicate] writeTextToFile(boardIndexPath, ` <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { margin: 0; } img { width: 100%; display: block; } a { position: absolute; background: rgba(0, 255, 255, 0.1); outline: 2px rgba(0, 255, 255, 1) solid; } .container { position: relative; } </style> </head> <body> <div class="container"> ${map(linkLayers, layer => { const stripped = layer.name().replace('->', '') const layerRect = layer.rect() const left = (layerRect.origin.x / rect.size().width) * 100 + '%' const top = (layerRect.origin.y / rect.size().height) * 100 + '%' const width = (layerRect.size.width / rect.size().width) * 100 + '%' const height = (layerRect.size.height / rect.size().height) * 100 + '%' const style = `left: ${left}; top: ${top}; width: ${width}; height: ${height};` return `<a href="${slug(stripped)}.html" style="${style}"></a>` }).join('\n')} <img src="${boardImageName}" /> </div> <script> document.addEventListener('touchstart', e => { if (e.touches.length >= 3) { window.location.href = '../' } }) </script> </body> `) }) }) }
true
87ef23747aa0e3b2300d6dab4d27837f0a235eae
JavaScript
phandeeyar/malicious-users-dashboard
/dashboard/static/vendor/sb-admin-2/js/demo/chart/bar.js
UTF-8
2,599
2.546875
3
[]
no_license
'use strict'; // Set new default font family and font color to mimic Bootstrap's default styling Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif'; Chart.defaults.global.defaultFontColor = '#858796'; const fbRootURL = 'https://www.facebook.com/profile.php?id='; // Bar Chart const domElement = document.getElementById('maliciousUsersChart'); console.log(top20MostMaliciousUsers); const chartConfig = { type: 'bar', data: { labels: top20MostMaliciousUsers.map((user) => user.user_id), datasets: [{ label: 'Malicious Score ', backgroundColor: '#4e73df', hoverBackgroundColor: '#2e59d9', borderColor: '#4e73df', data: top20MostMaliciousUsers.map((user) => user.malicious_score) }] }, options: { maintainAspectRatio: false, layout: { padding: { left: 10, right: 25, top: 25, bottom: 0 } }, scales: { xAxes: [{ gridLines: { display: false, drawBorder: false }, ticks: { maxTicksLimit: 20 }, maxBarThickness: 25 }], yAxes: [{ ticks: { min: 0, max: 20, maxTicksLimit: 10, padding: 5 }, gridLines: { color: 'rgb(234, 236, 244)', zeroLineColor: 'rgb(234, 236, 244)', drawBorder: false, borderDash: [2], zeroLineBorderDash: [2] } }] }, legend: { display: false }, onClick: barChartEventClick, tooltips: { titleMarginBottom: 10, titleFontColor: '#6e707e', titleFontSize: 14, backgroundColor: 'rgb(255,255,255)', bodyFontColor: '#858796', borderColor: '#dddfeb', borderWidth: 1, xPadding: 15, yPadding: 15, displayColors: false, caretPadding: 10, callbacks: { label: function(tooltipItem, chart) { let str = `${chart.datasets[tooltipItem.datasetIndex].label}: ${tooltipItem.value} \n` || ''; str += `\n Targeted Groups: ${top20MostMaliciousUsers.find((ele) => ele.user_id === tooltipItem.label).targeted_groups.join(', ')}`; return str; } } } } }; const myBarChart = new Chart(domElement, chartConfig); function barChartEventClick(event) { const activeElement = myBarChart.getElementAtEvent(event); if (activeElement[0]) { const [lastItem] = chartConfig.data.labels[activeElement[0]._index].split(' ').slice(-1); // Thanks to: https://stackoverflow.com/a/37123117 let profileURL = fbRootURL + lastItem; openInNewTab(profileURL); } } function openInNewTab(href) { Object.assign(document.createElement('a'), { target: '_blank', href: href }).click(); }
true
65ae3e1eceb337b9fda4f327a48af335456415ea
JavaScript
matthewwolfe/Soundcloud-Client
/src/js/actions/users.js
UTF-8
878
2.703125
3
[]
no_license
import { getUserById } from '../core/soundcloud/soundCloudSDK'; /* * Action types */ export const ADD_USER = 'ADD_USER'; export const REMOVE_USER = 'REMOVE_USER'; /* * Action creators */ export function addUser(user){ return {type: ADD_USER, user: user}; } export function removeUser(id){ return {type: REMOVE_USER, id: id}; } export function getUser(id){ return function(dispatch, getState){ if(shouldFetchUser(getState(), id)){ return dispatch(fetchUser(id)); } } } function shouldFetchUser(state, id){ let users = state.users; for(var i = 0; i < users.length; i++){ if(users[i].id === id){ return false; } } return true; } function fetchUser(id){ return function(dispatch){ getUserById(id, function(user){ dispatch(addUser(user)); }); } }
true
94ab9e4c8ceba796596711d6a39f3c3d9cf52c95
JavaScript
santoshbaggam/cli-qpg
/src/questions.js
UTF-8
1,592
3.203125
3
[]
no_license
"use strict"; // import fs module for interacting with the filesystem const fs = require('fs'); const questionsFilePath = __dirname + '/../data.json'; // check if the questions file exists or not // throw error if it doesn't if (! fs.existsSync(questionsFilePath)) throw new Error('Questions file is required for your application.'); const questions = JSON.parse(fs.readFileSync(questionsFilePath)); const Questions = { // assumed marks for each difficulty allotedMarks: { easy: 2, medium: 3, hard: 5 }, // set the questions questions: questions, // get all the questions get: function() { return this.questions; }, // get easy questions based on the limit passed getEasy: function(limit) { return applyLimit(this.questions.filter(question => { return question.difficulty == 'easy'; }), limit); }, // get medium questions getMedium: function(limit) { return applyLimit(this.questions.filter(question => { return question.difficulty == 'medium'; }), limit); }, // get hard questions getHard: function(limit) { return applyLimit(this.questions.filter(question => { return question.difficulty == 'hard'; }), limit); } }; // seperate function to limit the results // moving out of the class as we want to hide this functionality function applyLimit(questions, limit) { // return all the questions if no limit is specified if (limit === 'undefined') return questions; return questions.filter((question, index) => { return index <= (limit - 1); }); } module.exports = Questions;
true
e2f00423bf240350638d8004de6a0f4c59b92bd4
JavaScript
kolbeypruitt/oo_warmupSuper8Camera
/camera.js
UTF-8
371
2.796875
3
[]
no_license
function Camera() { this.loaded = false; this.totalFrames = 0; this.fps = 18; } Camera.prototype.shoot = function(rate){ if (rate === 'fast'){ this.fps = 9 } else if(rate === 'slow'){ this.fps = 36 } else this.fps = 18 } Camera.prototype.addFilm = function() { this.loaded = true; this.totalFrames = 3600; }; module.exports = Camera;
true
fd1efd57dd671faacee214c2ed8065aa3cd3f59f
JavaScript
foaex/react
/14_src_search参数传递/pages/Home/Message/Detail/index.jsx
UTF-8
1,195
2.84375
3
[]
no_license
import React, { Component } from 'react' import qs from 'querystring' // let obj = { // name: 'zhangsan', // age:18 // } // console.log(qs.stringify(obj)) // name=zhangsan&age=18 // let carName = "name=奔驰&price=199" // console.log(qs.parse(carName)) //{name: "奔驰", price: "199"} export default class Detail extends Component { state = { detailMessage:[{ id:'01', title:'消息01', content:"你好,中国" },{ id:'02', title:'消息02', content:"你好,自己" },{ id:'03', title:'消息03', content:"你好,未来的自己" }] } render() { // console.log(this.props); // 拿到从Message组件传过来的params参数 // const {id} = this.props.match.params // 拿到search方式传递过来的参数 const {search} = this.props.location //拿到的是 ?id=01 这种形式的 所以要引入 querystring 模块 const {id} = qs.parse(search.slice(1)) // 遍历 detailMessage 找到合适的id渲染消息 const showBoj = this.state.detailMessage.find((item)=>{ return item.id === id }) return ( <ul> <li>ID: {id}</li> <li>TITLE: {showBoj.title}</li> <li>CONTENT: {showBoj.content}</li> </ul> ) } }
true
91f978dbba67f7016d692d7688ebff4ef369d48e
JavaScript
KaicPierre/React-e-Next.js-Cod3r
/exercicios/pages/render/repeticao1.jsx
UTF-8
599
3.359375
3
[ "MIT" ]
permissive
export default function repeticao1() { const listaAprovados = [ 'Kaic', 'David', 'Joao', 'Felipe', 'Luiz' ] function renderizarLista(){ return listaAprovados.map((nome, index)=> <li key={ index }>{ nome }</li>) } return ( <ul> {renderizarLista()} </ul> ) } // function renderizarLista() { // const itens = []; // for (let i = 0; i < listaAprovados.length; i++){ // itens.push(<li key={i}>{listaAprovados[i]}</li>) // } // return itens; // }
true
cae606df39fc914bf34e322c167f62f06324ba8c
JavaScript
lerayj/tag
/app/selectionHelpers.js
UTF-8
2,327
2.671875
3
[]
no_license
import Sizzle from 'sizzle'; import * as log from 'loglevel'; //Track select change event from config //TODO: move into selectAttrValue pour avoir une methode generique function selectValueAttrHandler(config, configKeyName, selectDom, callback){ var selector = config[configKeyName]; if(config[configKeyName][0] == '@') selector = selector.substr(1).split(':'); if(typeof selector == 'object'){ var selectSelection = Sizzle(selector[0])[0], attr = selector[1]; } else{ var selectSelection = Sizzle(selector)[0], attr = 'textContent'; } if(selectSelection.nodeName.toLowerCase() === "select"){ function handleOptionSelect(selector, callback){ var optionSelection = Sizzle(":selected", this), result = optionSelection[0].textContent; if(typeof selector == 'object') result = optionSelection[0][selector[1]]; //log.info("[DEBUG] Tracking select: ", selector, "with value: ", result); callback(result); } handleOptionSelect(selector, callback); selectSelection.addEventListener("change", function(e){ handleOptionSelect(selector, callback); }); } } function radioValueAttrHandler(config, configKeyName, selectDom){ } //Si l'id_product est un attribut: @selector:attribut (eg RdC: @.cartProduct:id) function attributeValue(config, configKeyName, line){ var configRule = config[configKeyName], result = null; if(!configRule){ log.warn("[WARNING] No ", configKeyName, " on config."); return false; } if(configRule[0] == '@'){ var options = configRule.substr(1).split(':'); var selection = Sizzle(options[0], line); if(selection.length == 0 && Sizzle.matchesSelector(line, options[0])){ result = line[options[1]]; } else{ var value = Sizzle(options[0], line)[0]; result = value[options[1]]; } } else{ result = Sizzle(configRule, line)[0]; if(!result) return false; result = result.textContent; } return result.replace(/(\r\n\t|\n|\r\t)/gm,"").replace(/^\s+|\s+$/g, ""); } export default {selectValueAttrHandler, radioValueAttrHandler, attributeValue};
true
6ab065bc0f794928518e8b5669f88e9df7a6c634
JavaScript
Sergey-Zhestovsky/ScanUP
/src/classes/Validator.js
UTF-8
5,082
2.921875
3
[]
no_license
export default class Validator { constructor(config = {}) { this.config = null; this.init(config); } init(config) { this.config = walkThroughConfig(config, {}); function walkThroughConfig(currentConfig, object) { for (let fieldName in currentConfig) { let fieldConfig = currentConfig[fieldName]; if (fieldConfig instanceof Object && !Array.isArray(fieldConfig)) { walkThroughConfig(fieldConfig, object[fieldName] = {}); } else { if (typeof fieldConfig === typeof "") fieldConfig = [fieldConfig]; if (fieldConfig instanceof Array) fieldConfig = prepareRules(fieldConfig) } object[fieldName] = fieldConfig; } return object; } function prepareRules(confArray) { return confArray.map(config => { if (Array.isArray(config)) return setRule(...config); return config; }); function setRule(rule, value = null, name = null) { return { rule, value, name, toString() { return this.rule; } } } } } validate(validationData, validationCore = this.validationCore) { let errors = {}, isValid = walkThroughConfig(this.config, errors, validationData); function walkThroughConfig(config, errors, dataContext) { let isValid = true; for (let fieldName in config) { let fieldConfig = config[fieldName]; if (fieldConfig instanceof Object && !Array.isArray(fieldConfig)) { isValid = isValid && walkThroughConfig(fieldConfig, errors[fieldName] = {}, dataContext[fieldName]); } else { let temp = validationByRules(dataContext[fieldName], fieldConfig); errors[fieldName] = temp.errors; isValid = isValid && temp.isValid; } } return isValid; function validationByRules(data, fieldConfigArray) { let errors = [], isValid = true; for (let i = 0; i < fieldConfigArray.length; i++) { let result = validationCore(data, fieldConfigArray[i]); if (result === false) { isValid = false; errors.push(fieldConfigArray[i].toString()); } } return { isValid, errors } } } return isValid || errors; } validationCore(data, rule) { const func = { required, length, maxLength, minLength, min, max, email, password, number, test, backTest }; return func[rule.toString()](data, rule.value); function required(value) { return value !== null && value !== undefined && value !== ""; } function length(data, size) { if (data === null) return; return data.toString().length === size; } function maxLength(data, size) { if (data === null) return; return data.toString().length <= size; } function minLength(data, size) { if (data === null) return; return data.toString().length >= size; } function min(data, size) { return Number(data) >= size; } function max(data, size) { return Number(data) <= size; } function email(data) { let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(data).toLowerCase()); } function password(pass, rePass) { return pass === rePass; } function number(string) { return (parseInt(string) === Number(string)); } function test(str, regExp) { return regExp.test(str); } function backTest(str, regExp) { return !regExp.test(str); } } } // { // name: "val" // name2: { // subName1: "val" // subName2: { // subSubName1: "val" // subSubName2: "val" // } // } // } // { // name: ["setting1"] // name2: { // subName1: ["setting1", ["setting2", "additionalData"]] // subName2: { // subSubName1: ["setting1", ["setting2", "additionalData"]] // subSubName2: [["setting1", "additionalData", "name2.newSubName1"]] // } // } // } // // rules [rule] > "str" // // rule {name: rules} > [r] > "str" // // [r] = [validationF, additionalData, newName] // { // // name: true // name2: { // // subName1: true // subName2: { // subSubName1: ["setting1"] // } // newSubName1: ["setting1"] // } // } // { // name: ["setting", ["setting", "additionalData"]] // name2: { // property: ["subName1", { // property: ["subSubName1"], // rules: [["setting", ["setting", "additionalData"]]] // }] // rules: [ // ["setting", ["setting", "additionalData"]], // ["setting", ["setting", "additionalData"]] // ] // } // } // // rule {property, rules} > [] > "str" // // property ["str"] > "str" // // rules [rule] > rule
true
a2ab86c036d7b7da2c3e1ca98221499369e0dc02
JavaScript
wiiickedlady/web-to-plex
/src/sites/couchpotato/index.js
UTF-8
1,737
2.71875
3
[ "ISC" ]
permissive
/* global wait, modifyPlexButton, parseOptions, findPlexMedia */ function init() { wait( () => document.querySelector('.media-body .clearfix').children.length > 1, () => initPlexThingy(isMovie()? 'movie': 'show') ); } function isMovie() { return /^\/movies?\//.test(window.location.pathname); } function isShow() { return /^\/shows?\//.test(window.location.pathname); } function initPlexThingy(type) { let $button = renderPlexButton(); if (!$button) return; let $title = document.querySelector('[itemprop="description"]'), $date = $title.previousElementSibling; if (!$title || !$date) return modifyPlexButton( $button, 'error', 'Could not extract title or year from CouchPotato' ); let title = $title.textContent.trim(), year = $date.textContent.trim(), IMDbID = getIMDbID(); findPlexMedia({ title, year, button: $button, type, IMDbID }); } function renderPlexButton() { let $actions = document.querySelector('[href*="imdb.com/title/tt"]').parentElement; if (!$actions) return; let pa = document.createElement('span'), el = document.createElement('a'), ch = document.createElement('img'); ch.setAttribute('src', chrome.extension.getURL('img/16.png')); pa.classList.add('web-to-plex--container'); el.textContent = 'W2P'; el.title = 'Loading...'; el.classList.add('web-to-plex-button'); pa.appendChild(ch); pa.appendChild(el); $actions.appendChild(pa); return el; } function getIMDbID() { let $link = document.querySelector( '[href*="imdb.com/title/tt"]' ); if ($link) { let link = $link.href.replace(/^.*imdb\.com\/title\//, ''); return link.replace(/\/(?:maindetails\/?)?$/, ''); } } parseOptions().then(init);
true
d09516bcb01061ca3fef396345740d5a15d00f7f
JavaScript
carl-rasmus/cackaa
/js/socket.js
UTF-8
955
2.703125
3
[]
no_license
// $(function () { // var socket = io(); // $('#lid').click(function(e){ // socket.emit('chat message'); // }); // socket.on('chat message', function(msg){ // $('#lid').toggleClass('lid-rotate'); // $('.birdSound').trigger("play"); // }); // }); $(function () { var socket = io(); $('#lid').click(function(e){ socket.emit('chat message'); }); socket.on('chat message', function(msg){ setTimeout(function () { $('#lid').removeClass('lid-rotate'); $('#bird').removeClass('lean-in'); }, 2000); $('#lid').addClass('lid-rotate'); $('.birdSound').trigger('play'); $('#bird').addClass('lean-in'); }); }); // NEED VANILLA // function birdChime(){ // var socket = io(); // var lid = document.getElementById('lid'); // function clickLid(){ // socket.emit('chat message'); // } // socket.on('chat message', function moveLid(){ // lid.classList.add("lid-rotate"); // }); // }
true
0a06a48771bcb7f7a9ed110f1ff35895b0aa98ca
JavaScript
Colinkai/JS_FIP_CN
/curriculum/Js/script.js
UTF-8
836
2.671875
3
[]
no_license
"use strict"; const styles = { border: "0", cellpadding: "0", cellspacing: "0", id: "table-data-wrap", }; // const divDom = $("table-data-wrap"); const divDom = window.Colin.$("table-data-wrap"); const tableDome = window.Colin.createEl("table"); //creatElement 创建dom对象 tableDome.width = "100%"; //setAttribute 设置属性 window.Colin.setAttr(tableDome, styles); //array let theadHtml = `<thead><tr>`; tableTheadData.forEach(function (item) { //检测是否存在width let width = item.width ? ` width="${item.width}"` : ""; theadHtml += `<th${width}>${item.label}</th>`; }); theadHtml += `</tr></thead>`; /** * 表格内容 */ let tbodyHtml = `<tbody>`; tbodyHtml += createTbodyDate(); tbodyHtml += `</tbody>`; tableDome.innerHTML = theadHtml + tbodyHtml; console.log(theadHtml); divDom.appendChild(tableDome);
true
e00b5ef5ec67f411f994979c63b36db06e2d92f3
JavaScript
makkoli/wiki_viewer
/wiki.js
UTF-8
1,090
3.203125
3
[]
no_license
$(document).ready(function() { // Begin search for new item $("#container").on('click', '.search', function() { getWikiPages(); }); }); // Grabs the first 8 wikipedia titles and summaries using wikipedia api // @term: term to search wikipedia for function getWikiPages(term) { // Get the results from the search $.ajax({ url: "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" + document.getElementById("query").value + "&namespace=0&limit=8&callback=?", dataType: 'json', type: 'POST', success: function(data) { console.log(data); var list = ""; // Construct the results list for (var i = 1; i < data[1].length; i++) { list += '<a href="' + data[3][i] + '" target="_blank"><div class="result"><h4><u>' + data[1][i] + '</u></h4>'; list += "<p>" + data[2][i] + "</p></div></a>"; } // Update the results list $("#results").html(list); }, error: function(jqXHR, status, error) { console.log("Status: " + status); console.log("Error: " + error); } }); }
true
c1f353853ebe661597d9bede2e7dc221f056d1b0
JavaScript
AndreyChernykh/redux-presentation-examples-2018-06-14
/src/example7/App.js
UTF-8
895
2.703125
3
[]
no_license
import React, { Component, PureComponent } from 'react'; import './../App.css'; const SubChild = ({ name }) => ( <div>|______<b>{name}</b></div> ); const Child = ({ name }) => ( <div> |__ Child <SubChild name={name} /> </div> ); const SubChildWithAction = ({ changeName }) => ( <div> |______<button onClick={changeName}>Change the name</button> </div> ); const ChildWithAction = ({ changeName }) => ( <div> |__ Child With Action <SubChildWithAction changeName={changeName} /> </div> ); class App extends Component { state = { name: 'Bob' } changeName = () => { this.setState({ name: 'John Doe' }); } render() { return ( <div className="App"> App <Child name={this.state.name}/> <div>|</div> <ChildWithAction changeName={this.changeName}/> </div> ); } } export default App;
true
1e735b1c8df21efcfc7f4bdf8abf090bb0f6051f
JavaScript
steveamorris/gt-bootcamp-connect
/public/js/dashboard.js
UTF-8
224
2.578125
3
[ "MIT" ]
permissive
$(document).ready(function () { $(".catBtn").on("click", function () { console.log($(this)); let catId = $(this).data("value"); console.log(catId); window.location.replace("/dashboard/" + catId) }); });
true
36e7401cb5887f3b66c02573d7fcc78512d1f706
JavaScript
luismigeek/bootcamp
/js/main.js
UTF-8
1,939
3.578125
4
[ "MIT" ]
permissive
function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } var efect = "tada"; var gift = document.getElementById('gift'); var preload = document.getElementById('preload'); var loading = document.getElementById('loading'); var code = document.getElementById('code'); var fullname = document.getElementById('fullname'); var institution = document.getElementById('institution'); var genera = document.getElementById('generar'); var reiniciar = document.getElementById('reiniciar'); genera.onclick = () => { var x = document.getElementById("myAudio"); x.play(); // the code you're looking for var number = getRandomInt(1, 90); console.log('Numero: ', number); preload.classList.add("preloader"); loading.classList.add("loading-circle"); loading.classList.add("fa-spin"); setTimeout(() => { preload.classList.remove("preloader"); loading.classList.remove("loading-circle"); loading.classList.remove("fa-spin"); gift.classList.add(efect); code.innerHTML = list[number - 1].code; fullname.innerHTML = list[number - 1].fullname; institution.innerHTML = list[number - 1].institution; }, 7500); } /** genera.onclick = () => { // the code you're looking for var number = getRandomInt(1, 90); // iterate over each element in the array for (var i = 0; i < list.length; i++) { // look for the entry with a matching `code` value if (list[i].code == number) { console.log(list[i].code); code.innerHTML = list[i].code; fullname.innerHTML = list[i].fullname; institution.innerHTML = list[i].institution; } } } */ reiniciar.onclick = () => { code.innerHTML = ' xx '; fullname.innerHTML = 'xx - xx - xx - xx '; institution.innerHTML = 'xx - xx'; gift.classList.remove(efect); }
true
fab12a187ea6f26b7f35b609abc786302cc2edc5
JavaScript
TomDiaz/GameT-shirts
/js/main.js
UTF-8
9,895
2.578125
3
[]
no_license
//Variables var canvas, cx, objetos, objetoActual, barra, pos ; var incioX = 0, incioY = 0, cont=0; var ropa = new Image(); var caja = new Image(); var conRemeras = 0, remeras, total, sumar = false, color=1, r=0, id=1; var rojo = new Image(); var naranja = new Image(); var amarillo = new Image(); var verde = new Image(); var azul = new Image(); var violeta = new Image(); var velocidad = 1, dificultad=0; let remerasV = []; let nivel = [5,10,15,20,25,30]; var segundos = 400; //sonido var sonido = new Audio("bounce.mp3"); var error = new Audio("error.mp3"); var gameover = new Audio("game-over.mp3"); const lista = document.getElementById('remera'); const elemento = document.createElement('div'); const lista2 = document.getElementById('reloj'); const elemento2 = document.createElement('div'); ropa.src = "img/amarillo.png"; caja.src = "img/caja.png"; function ColoresRemeras(valor){ color = valor; switch(color){ case 1: rojo.src = "img/rojo.png"; naranja.src = "img/naranja.png"; amarillo.src = "img/amarillo.png"; verde.src = "img/verde.png"; azul.src = "img/azul.png"; violeta.src = "img/violeta.png"; remerasV = ["img/rojo.png","img/naranja.png","img/amarillo.png", "img/verde.png", "img/azul.png", "img/violeta.png" ]; MostrarRopa(); break; case 2: rojo.src = "img/protanopia/rojo.png"; naranja.src = "img/protanopia/naranja.png"; amarillo.src = "img/protanopia/amarillo.png"; verde.src = "img/protanopia/verde.png"; azul.src = "img/protanopia/azul.png"; violeta.src = "img/protanopia/violeta.png"; remerasV = ["img/protanopia/rojo.png","img/protanopia/naranja.png","img/protanopia/amarillo.png", "img/protanopia/verde.png", "img/protanopia/azul.png", "img/protanopia/violeta.png" ]; MostrarRopa(); break; case 3: rojo.src = "img/deuteranopia/rojo.png"; naranja.src = "img/deuteranopia/naranja.png"; amarillo.src = "img/deuteranopia/amarillo.png"; verde.src = "img/deuteranopia/verde.png"; azul.src = "img/deuteranopia/azul.png"; violeta.src = "img/deuteranopia/violeta.png"; remerasV = ["img/deuteranopia/rojo.png","img/deuteranopia/naranja.png","img/deuteranopia/amarillo.png", "img/deuteranopia/verde.png", "img/deuteranopia/azul.png", "img/deuteranopia/violeta.png" ]; MostrarRopa(); break; case 4: rojo.src = "img/tritanopia/rojo.png"; naranja.src = "img/tritanopia/naranja.png"; amarillo.src = "img/tritanopia/amarillo.png"; verde.src = "img/tritanopia/verde.png"; azul.src = "img/tritanopia/azul.png"; violeta.src = "img/tritanopia/violeta.png"; remerasV = ["img/tritanopia/rojo.png","img/tritanopia/naranja.png","img/tritanopia/amarillo.png", "img/tritanopia/verde.png", "img/tritanopia/azul.png", "img/tritanopia/violeta.png" ]; MostrarRopa(); break; } } function actualizar(){ cx.fillStyle = '#09a8f1'; cx.fillRect(0,0,1000,650); for(var i=1; i < objetos.length; i++){ if(objetos[i].mov){ objetos[i].x += velocidad; if( objetos[i].x > canvas.width){ objetos[i].x = 0; } } /*cx.fillStyle = objetos[i].color; cx.fillRect(objetos[i].x,objetos[i].y,objetos[i] .width,objetos[i].height) ; */ cx.drawImage(objetos[i].image,objetos[i].x,objetos[i].y ,objetos[i].width,objetos[i].height ); } cx.drawImage(objetos[0].image,objetos[0].x,objetos[0].y ,objetos[0].width,objetos[0].height ); } function mover(){ actualizar(); } function guardar(){ if(objetoActual.y<=0 ){ objetos[pos].x = 0; objetos[pos].y = 0; objetos[pos].mov = true; } if(objetoActual.y >= 400 && objetoActual.x >= 400 && objetoActual.x <= 600 && objetoActual.id-1 == r){ /*alert("paso");*/ sonido.play(); incioX = 0; incioY = 0; objetoActual = null; objetos[pos].x = -1000; objetos[pos].y = 0; objetos[pos].mov = true; sumar = true; } else if(objetoActual.y >= 400 && objetoActual.x >= 400 && objetoActual.x <= 600 && objetoActual.id-1 != r){ error.play(); } setInterval(validarPunto, 3000); } setInterval(mover, 1); setInterval(cuantaRegresiva, 1000); window.onload = function(){ objetos = []; canvas = document.getElementById("miCanvas"); cx = canvas.getContext('2d'); ColoresRemeras(color); //Agregar objetos de prueba objetos.push({ x: -100, y: 500, width: 1500, height:150, color: 'red', image: caja, mov: true }); //REMERAS objetos.push({ x: 0, y: 0, width: 150, height:200, color: 'red', image: rojo, mov: true, id: 1 }); objetos.push({ x: 300, y: 0, width: 150, height:200, color: 'blue', image: naranja, mov: true, id: 2 }); objetos.push({ x: 600, y: 0, width: 150, height:200, color: 'red', image: amarillo, mov: true, id: 3 }); objetos.push({ x: 700, y: 0, width: 150, height:200, color: 'blue', image: verde, mov: true, id: 4 }); objetos.push({ x: 900, y: 0, width: 150, height:200, color: 'red', image: azul, mov: true, id: 5 }); objetos.push({ x: 980, y: 0, width: 150, height:200, color: 'blue', image: violeta, mov: true, id: 6 }); objetos.push({ x: 680, y: 0, width: 150, height:200, color: 'red', image: rojo, mov: true, id: 1 }); objetos.push({ x: 600, y: 0, width: 150, height:200, color: 'blue', image: naranja, mov: true, id: 2 }); objetos.push({ x: 900, y: 0, width: 150, height:200, color: 'red', image: amarillo, mov: true, id: 3 }); objetos.push({ x: 380, y: 0, width: 150, height:200, color: 'blue', image: verde, mov: true, id: 4 }); objetos.push({ x: 80, y: 0, width: 150, height:200, color: 'red', image: azul, mov: true, id: 5 }); objetos.push({ x: 800, y: 0, width: 150, height:200, color: 'blue', image: violeta, mov: true, id: 6 }); actualizar(); MostrarRopa(); //Funciones para Usar el Mous canvas.onmousedown = function(event){ for(var i=1; i < objetos.length; i++){ if(objetos[i].x <= event.clientX && (objetos[i].width + objetos[i].x >= event.clientX) && objetos[i].y <= event.clientY && (objetos[i].width + objetos[i].y >= event.clientY)){ pos = i; objetos[i].mov = false; id = objetos[i].id; objetoActual = objetos[i]; incioY = event.clientY - objetos[i].y; incioX = event.clientX - objetos[i].x; console.log(incioX); break; } } }; canvas.onmousemove = function(event){ if(objetoActual != null){ objetoActual.x = event.clientX - incioX; objetoActual.y = event.clientY - incioY; actualizar(); guardar(); } }; canvas.onmouseup = function(event){ objetoActual = null; }; }; function validarPunto(){ if(sumar){ sumar = false; elemento.innerHTML = ""; SumarPunto(true); MostrarRopa(); } else{ SumarPunto(false); } } function SumarPunto(valor){ if(valor){ conRemeras++; if(conRemeras >= total ){ r++; if(conRemeras==30){ alert("GANASTE REY, Tu tiempo fue de: "+segundos); window.location.href='http://wolftech.space/gotogamejam-Equipo-11-Mandalorians'; } conRemeras = 0; } } } function MostrarRopa(){ total = nivel[r]; elemento.innerHTML = ` <div class="remera-a-guardar"> <span id="contador">${total}/${conRemeras}</span> <br> <img src="${remerasV[r]}" alt=""> </div> `; lista.appendChild(elemento); } function tiempo(){ elemento2.innerHTML = ` <div class="tiempo"> <span>${segundos}s</span> </div> `; lista2.appendChild(elemento2); } function cuantaRegresiva(){ if(segundos!=0){ segundos--; dificultad ++; if(dificultad ==120 && velocidad>=4){ velocidad++; dificultad = 0; console.log(velocidad); } tiempo(); } else{ gameover.play(); alert("GAME OVER"); window.location.href='http://wolftech.space/gotogamejam-Equipo-11-Mandalorians'; } } ///Configuracion const menu = document.getElementById("configuarar"); $(".abrir").click(function(){ menu.style.left = '0'; menu.style.transition = '1s'; }); $(".cerrar").click(function(){ menu.style.left = '-800px'; menu.style.transition = '1s'; }); $(".op1").click(function(){ ColoresRemeras(1); }); $(".op2").click(function(){ ColoresRemeras(2); }); $(".op3").click(function(){ ColoresRemeras(3); }); $(".op4").click(function(){ ColoresRemeras(4); });
true
fc816ae647444a2c83dd62ec511718c42cd857b3
JavaScript
fcordon/elans2019
/client/src/components/Top.js
UTF-8
10,396
2.59375
3
[]
no_license
import React, { useState, useEffect } from 'react' import axios from 'axios' import { Row, Col, Card, Table } from 'react-bootstrap' const Top = () => { const [pointeurs, setPointeurs] = useState([]) useEffect(() => { let isSubscribed = true getJoueur() .then(res => { let joueurTable = [] const data = [...res] data.sort((a,b) => { const compA = a.points const compB = b.points let comparison = 0; if (compA < compB) { comparison = 1; } else if (compA > compB) { comparison = -1; } return comparison; }) data.map((joueur, index) => { if (index <= 4) { let ratio = isNaN(parseInt(joueur.points) / parseInt(joueur.match)) ? 0 : (parseInt(joueur.points) / parseInt(joueur.match)).toFixed(2) let joueurObjet = {nom:joueur.nom,prenom:joueur.prenom,numero:joueur.numero,ratio:ratio,points:joueur.points} joueurTable.push(joueurObjet) } return joueurTable }) return isSubscribed && setPointeurs(joueurTable) }) .catch(err => console.log(err)) return () => isSubscribed = false }, []) const [buteurs, setButeurs] = useState([]) useEffect(() => { let isSubscribed = true getJoueur() .then(res => { let joueurTable = [] const data = [...res] data.sort((a,b) => { const compA = a.buts const compB = b.buts let comparison = 0; if (compA < compB) { comparison = 1; } else if (compA > compB) { comparison = -1; } return comparison; }) data.map((joueur, index) => { if (index <= 4) { let ratio = isNaN(parseInt(joueur.buts) / parseInt(joueur.match)) ? 0 : (parseInt(joueur.buts) / parseInt(joueur.match)).toFixed(2) let joueurObjet = {nom:joueur.nom,prenom:joueur.prenom,numero:joueur.numero,ratio:ratio,buts:joueur.buts} joueurTable.push(joueurObjet) } return joueurTable }) return isSubscribed && setButeurs(joueurTable) }) .catch(err => console.log(err)) return () => isSubscribed = false }, []) const [assists, setAssists] = useState([]) useEffect(() => { let isSubscribed = true getJoueur() .then(res => { let joueurTable = [] const data = [...res] data.sort((a,b) => { const compA = a.assists const compB = b.assists let comparison = 0; if (compA < compB) { comparison = 1; } else if (compA > compB) { comparison = -1; } return comparison; }) data.map((joueur, index) => { if (index <= 4) { let ratio = isNaN(parseInt(joueur.assists) / parseInt(joueur.match)) ? 0 : (parseInt(joueur.assists) / parseInt(joueur.match)).toFixed(2) let joueurObjet = {nom:joueur.nom,prenom:joueur.prenom,numero:joueur.numero,ratio:ratio,assists:joueur.assists} joueurTable.push(joueurObjet) } return joueurTable }) return isSubscribed && setAssists(joueurTable) }) .catch(err => console.log(err)) return () => isSubscribed = false }, []) const [penalites, setPenalites] = useState([]) useEffect(() => { let isSubscribed = true getJoueur() .then(res => { let joueurTable = [] const data = [...res] data.sort((a,b) => { const compA = a.penalites const compB = b.penalites let comparison = 0; if (compA < compB) { comparison = 1; } else if (compA > compB) { comparison = -1; } return comparison; }) data.map((joueur, index) => { if (index <= 4) { let ratio = isNaN(parseInt(joueur.penalites) / parseInt(joueur.match)) ? 0 : (parseInt(joueur.penalites) / parseInt(joueur.match)).toFixed(2) let joueurObjet = {nom:joueur.nom,prenom:joueur.prenom,numero:joueur.numero,ratio:ratio,penalites:joueur.penalites} joueurTable.push(joueurObjet) } return joueurTable }) return isSubscribed && setPenalites(joueurTable) }) .catch(err => console.log(err)) return () => isSubscribed = false }, []) const getJoueur = async () => { const response = await axios.get('/joueurs') const body = await response.data if (response.status !== 200) { throw Error(body.message) } return body } return ( <Row className="justify-content-center"> <Col xs={12} sm={12} lg={4} xl={4} className='topFive-card'> <Card className='topFive-pointeurs'> <Card.Header>Les Meilleurs Pointeurs</Card.Header> <Card.Body> <Table responsive striped hover size='sm'> <thead> <tr> <th>#</th> <th>Nom</th> <th>Prénom</th> <th className='text-center'>Points</th> <th className='text-center'>Ratio</th> </tr> </thead> <tbody> {pointeurs.map((joueur, i) => { return ( <tr key={i}> <td> {joueur.numero} </td> <td> {joueur.nom} </td> <td> {joueur.prenom} </td> <td className='text-center'> {joueur.points} </td> <td className='text-center'> {joueur.ratio} </td> </tr> ) })} </tbody> </Table> </Card.Body> </Card> </Col> <Col xs={12} sm={12} lg={4} xl={4} className='topFive-card'> <Card className='topFive-buteurs'> <Card.Header>Les Meilleurs Buteurs</Card.Header> <Card.Body> <Table responsive striped hover size='sm'> <thead> <tr> <th>#</th> <th>Nom</th> <th>Prénom</th> <th className='text-center'>Buts</th> <th className='text-center'>Ratio</th> </tr> </thead> <tbody> {buteurs.map((joueur, i) => { return ( <tr key={i}> <td> {joueur.numero} </td> <td> {joueur.nom} </td> <td> {joueur.prenom} </td> <td className='text-center'> {joueur.buts} </td> <td className='text-center'> {joueur.ratio} </td> </tr> ) })} </tbody> </Table> </Card.Body> </Card> </Col> <Col xs={12} sm={12} lg={4} xl={4} className='topFive-card'> <Card className='topFive-assists'> <Card.Header>Les Meilleurs Assists</Card.Header> <Card.Body> <Table responsive striped hover size='sm'> <thead> <tr> <th>#</th> <th>Nom</th> <th>Prénom</th> <th className='text-center'>Assists</th> <th className='text-center'>Ratio</th> </tr> </thead> <tbody> {assists.map((joueur, i) => { return ( <tr key={i}> <td> {joueur.numero} </td> <td> {joueur.nom} </td> <td> {joueur.prenom} </td> <td className='text-center'> {joueur.assists} </td> <td className='text-center'> {joueur.ratio} </td> </tr> ) })} </tbody> </Table> </Card.Body> </Card> </Col> <Col xs={12} sm={12} lg={4} xl={4} className='topFive-card'> <Card className='topFive-penalites'> <Card.Header>Les plus pénalisés</Card.Header> <Card.Body> <Table responsive striped hover size='sm'> <thead> <tr> <th>#</th> <th>Nom</th> <th>Prénom</th> <th className='text-center'>Pénalités</th> <th className='text-center'>Ratio</th> </tr> </thead> <tbody> {penalites.map((joueur, i) => { return ( <tr key={i}> <td> {joueur.numero} </td> <td> {joueur.nom} </td> <td> {joueur.prenom} </td> <td className='text-center'> {joueur.penalites + ' min'} </td> <td className='text-center'> {joueur.ratio} </td> </tr> ) })} </tbody> </Table> </Card.Body> </Card> </Col> </Row> ) } export default Top
true
8dea24686aaaf6cf9946452e130def352b2ccc85
JavaScript
Enirate/unit-test-101
/age-guard.test.js
UTF-8
411
2.875
3
[]
no_license
const ageGuard = require('./age-guard'); it('There should be function named ageGuard', () => { expect(ageGuard).toBeDefined(); }); it('Persons under 18 should not be granted access', () => { expect(ageGuard(14)).toBe('You are not old enough to access this site'); }); it('Persons 18 and above should be granted access', () => { expect(ageGuard(18)).toBe('You\'ve been granted access to this site'); });
true
ce1f282b5b06ded8ece430d2bddd8b53aeb23d0c
JavaScript
hhernan83/Hernans-repo
/07_Node/SuperProject/App.js
UTF-8
445
3.1875
3
[]
no_license
var marvel = require('marvel-characters') console.log(marvel()) console.log(`# of characters in the db: `+marvel.characters.length) let names = marvel.characters.filter(function(el){ return el.substring(0,3) == "Man" }) console.log(names) let IronMan = marvel.characters.filter(el=>{ return el == "Iron Man" }) let result = IronMan.length !=0 ? IronMan: "No matches found" console.log(result) console.log(IronMan)
true
0dfad7f8a5189a8e7f213b551650ed8c63c223e5
JavaScript
landonbar/muta
/src/pathResolver.js
UTF-8
965
2.828125
3
[]
no_license
// the PathResolver is a namespace that uses a browser hack to generate an // absolute path from a url string -- using an anchor tag's href. // it combines the aliasMap with a file and possible base directory. const PathResolver = {}; const ANCHOR = document.createElement('a'); PathResolver.resolveFile = function resolveFile(aliasMap, file, dir) { file = aliasMap ? (aliasMap[file] || file) : file; if(dir && file.indexOf('http') !== 0) { dir = aliasMap ? (aliasMap[dir] || dir) : dir; const lastChar = dir.substr(-1); file = (lastChar !== '/') ? dir + '/' + file : dir + file; } ANCHOR.href = file; return ANCHOR.href; }; PathResolver.resolveDir = function resolveDir(aliasMap, file, dir){ return toDir(PathResolver.resolveFile(aliasMap, file, dir)); }; function toDir(path){ const i = path.lastIndexOf('/'); return path.substring(0, i + 1); } export default PathResolver;
true
308fcf4490edba61bc9f6732510d399a950ce21c
JavaScript
rlong/javascript.lib.dinky_require
/dinkyRequire.js
UTF-8
3,644
2.640625
3
[ "MIT" ]
permissive
// Copyright (c) 2017 Richard Long // // Released under the MIT license ( http://opensource.org/licenses/MIT ) // "use strict"; var microRequireModules = {}; { var loadResource = function( path, callback, errorCallback ) { var xhr = new XMLHttpRequest(); var finished = false; xhr.onabort = xhr.onerror = function xhrError() { finished = true; if( errorCallback ) { errorCallback( xhr ); } else { console.error( xhr ); } }; xhr.onreadystatechange = function xhrStateChange() { if (xhr.readyState === 4 && !finished) { finished = true; var section; try { callback( xhr.responseText ); } catch (e) { if( errorCallback ) { errorCallback( xhr ); } else { console.error( e ); } } } }; xhr.open('GET', path); xhr.send(); } var setupModule = function( cursor, moduleConfig ) { // console.info( "loading lib: " + moduleConfig.name ); loadResource( moduleConfig.src, function (scriptText) { moduleConfig.scriptText = scriptText; if( moduleConfig === cursor.current() ) { do { { window.exports = {}; eval.apply( window, [moduleConfig.scriptText]); // did the module `export` anything if( 0 < Object.keys(window.exports).length ) { microRequireModules[moduleConfig.name] = window.exports; } delete window.exports; console.info( "loaded lib: " + moduleConfig.name ); } moduleConfig = cursor.next(); } while( null != moduleConfig && null != moduleConfig.scriptText ); } else { // we are still waiting for an earlier library to load ... no-op } }); } var setup = function( config ) { for( var i = 0, count = config.length; i < count; i++ ) { var moduleConfig = config[i]; if( !moduleConfig.src ) { moduleConfig.src = moduleConfig.name + ".js" } } var cursor = { index: 0, next: function () { cursor.index++; if( cursor.index == config.length ) { return null; } var answer = config[cursor.index]; return answer; }, current: function () { return config[cursor.index]; } } for( var i = 0, count = config.length; i < count; i++ ) { setupModule( cursor, config[i] ); } } loadResource( "./dinkyConfig.json", function (jsonText) { var config = JSON.parse( jsonText ); setup( config ); }, function ( error ) { console.error( "failed to load './dinkyConfig.json'"); console.error( error ); }); } function require( lib ) { var answer = microRequireModules[lib]; if( undefined == answer ) { // take a punt ... answer = window[lib]; } if( undefined == answer ) { console.error( "'"+lib+"' not found!" ); } return answer; }
true
5f54739fbb20393801a634a6f42369f1455b1a3f
JavaScript
Hugovarellaa/verificador-de-idade
/app.js
UTF-8
1,805
3.515625
4
[]
no_license
const button = document.querySelector('button'); button.addEventListener('click', () => { const data = new Date(); const anoAtual = data.getFullYear() const ano = document.querySelector('input#txtano').value; const hoje = Number(anoAtual) - Number(ano) const sexo = document.getElementsByName('radsexo'); const resultado = document.querySelector('div#res'); const img = document.createElement('img'); img.setAttribute('id', 'foto') if (ano == '') { resultado.textContent = `Preencha os campos e veja o resultado` } else { genero = '' if (sexo[0].checked) { genero = 'Homen' if (hoje < 10) { //foto da criança homem img.src = './_Imagens/H1.png' } else if (hoje < 21) { //foto do jovem homem img.src = './_Imagens/H2.png' } else if (hoje < 50) { //foto do adulto homem img.src = './_Imagens/H3.png' } else { //foto do idoso homem img.src = './_Imagens/H4.png' } } else if (sexo[1].checked) { genero = 'Mulher' if (hoje < 10) { //foto da criança mulher img.src = './_Imagens/M1.png' } else if (hoje < 21) { //foto da jovem mulher img.src = './_Imagens/M2.png' } else if (hoje < 50) { //foto da adulto mulher img.src = './_Imagens/M3.png' } else { //foto da idosa mulher img.src = './_Imagens/M4.png' } } resultado.textContent = `Detectamos... ${genero} com a ${hoje} anos` } resultado.appendChild(img) })
true
a1be1505f57d90778b773c69daed8aab9eafcdb7
JavaScript
VOXearch/Grow-IoT
/tests/test-grow-hub.js
UTF-8
6,157
2.5625
3
[ "BSD-2-Clause-Views", "BSD-3-Clause", "BSD-2-Clause" ]
permissive
const Thing = require('Grow.js'); var inquirer = require('inquirer'); var _ = require('underscore') const growfile = require('./tomato.js') var args = process.argv.slice(2); var uuid = args[0]; var token = args[1]; var questions = [ { type: 'input', name: 'uuid', message: 'Enter device UUID (you are given this when you create a new thing)', }, { type: 'input', name: 'token', message: 'Enter token', }, ]; if(_.isUndefined(uuid) || _.isUndefined(token)) { inquirer.prompt(questions).then(function (answers) { uuid = answers.uuid; token = answers.token; createGrowHub(uuid, token); }); } else { createGrowHub(uuid, token); } // Create a new growHub instance and connect to https://growHub.commongarden.org function createGrowHub(u, t) { const growHub = new Thing({ uuid: u, token: t, component: 'BioReactor', // Properties can be updated by the API properties: { state: 'off', light_state: 'off', fan_state: 'off', pump_state: 'off', threshold: 300, interval: 3000, currently: null, lightconditions: null, growfile: { phases: { vegetative: { targets: { ph: { min: 6.0, ideal: 6.15, max: 6.3, }, ec: { min: 1400, ideal: 1500, max: 1700, }, humidity: { min: 51, max: 61 }, }, // You can have more cycles than just day or night. cycles: { day: { start: 'after 6:00am', targets: { temperature: 24, co2: { min: 900, max: 1600 } } }, night: { start: 'after 9:00pm', targets: { temperature: 20, co2: { min: 400, max: 1000 }, } } } }, bloom: { targets: { ph: { min: 6.0, ideal: 6.15, max: 6.3, }, ec: { min: 1400, ideal: 1500, max: 1700, }, humidity: { min: 51, max: 59 }, }, cycles: { day: { start: 'after 7:00am', targets: { temperature: 24, } }, night: { start: 'after 7:00pm', targets: { temperature: 20, co2: 400, }, } } } } } }, start: function () { console.log('Grow-Hub initialized.'); let interval = this.get('interval'); emit_and_analyze = setInterval(()=> { this.temp_data(); this.hum_data(); this.ph_data(); this.ec_data(); this.lux_data(); this.water_temp_data(); // this.power_data(); }, interval); // this.parseCycles(growfile.properties.cycles); }, stop: function () { console.log("Grow-Hub stopped."); clearInterval(emit_and_analyze); this.removeAllListeners(); }, day: function () { console.log('It is day!'); }, night: function () { console.log('It is night!'); }, turn_light_on: function () { console.log('light on'); this.set('light_state', 'on'); }, turn_light_off: function () { console.log('light off'); this.set('light_state', 'off'); }, turn_fan_on: function () { console.log('Fan on'); this.set('fan_state', 'on'); }, turn_fan_off: function () { console.log('Fan off'); this.set('fan_state', 'off'); }, turn_pump_on: function () { console.log('Pump on'); this.set('pump_state', 'on'); }, turn_pump_off: function () { console.log('Pump off'); this.set('pump_state', 'off'); }, ec_data: function () { eC_reading = Math.random() * 1000; this.emit('ec', eC_reading); console.log('Conductivity: ' + eC_reading); }, ph_data: function () { pH_reading = Math.random() * 14; this.emit('ph', pH_reading); console.log('ph: ' + pH_reading); }, temp_data: function () { let currentTemp = Math.random(); this.emit('temperature', currentTemp); console.log('Temp: ' + currentTemp); }, water_temp_data: function () { let currentWaterTemp = Math.random(); this.emit('water_temperature', currentWaterTemp); console.log('Water Temp: ' + currentWaterTemp); }, // power_data: function () { // this.emit({ // type: 'fan_power', // value: { // current: Math.random(), // voltage: Math.random(), // power: Math.random(), // total: Math.random() // } // }); // this.emit({ // type: 'pump_power', // value: { // current: Math.random(), // voltage: Math.random(), // power: Math.random(), // total: Math.random() // } // }); // this.emit({ // type: 'light_power', // value: { // current: Math.random(), // voltage: Math.random(), // power: Math.random(), // total: Math.random() // } // }); // }, lux_data: function () { let lux = Math.random(); this.emit('lux', lux); console.log('Lux: ' + lux); }, hum_data: function () { let currentHumidity = Math.random(); this.emit('humidity', currentHumidity); console.log("Humidity: " + currentHumidity); } }).connect(); console.log(growHub); }
true
5f4f9b1ab3743f11acda465fa1261aa2b4549b9f
JavaScript
alexpower1/man-utd
/src/components/Pages/OldTrafford/OldTrafford.js
UTF-8
2,332
2.984375
3
[]
no_license
import React, { Component } from "react"; import Spinner from "../../Layout/Spinner/Spinner"; class OldTrafford extends Component { state = { latitude: null, longitude: null, distance: "00.00KM", errorMessage: "", calculated: false }; componentDidMount() { // On mount, use Geolocate API to determine user position window.navigator.geolocation.getCurrentPosition( position => this.setState({ latitude: position.coords.latitude, longitude: position.coords.longitude }), err => this.setState({ distance: "", errorMessage: "Error: " + err.message + ". Make sure you have provided access to your location." }) ); } calculateDistance = () => { console.log(this.state); // Set Old Trafford position const OTLAT = 53.4631; const OTLON = -2.2913; let deg2rad = deg => { return deg * (Math.PI / 180); }; const R = 6371; // Radius of the earth in km let dLat = deg2rad(OTLAT - this.state.latitude); let dLon = deg2rad(OTLON - this.state.longitude); let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(this.state.latitude)) * Math.cos(deg2rad(OTLAT)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); let d = R * c; // Distance in km let e = Math.round(d * 100) / 100; this.setState({ distance: e + "km", calculated: true }); }; render() { let button = ""; if (this.state.errorMessage === "") { if (this.state.latitude) { button = ( <button onClick={this.calculateDistance} disabled={this.state.calculated} > Calculate </button> ); } else { button = <Spinner />; } } else { button = ( <p> <strong>{this.state.errorMessage}</strong> </p> ); } return ( <div className="OldTrafford"> <h1>Old Trafford</h1> <p>Calculate your distance from Manchester United's stadium.</p> <div className="OldTraffordCalc">{button}</div> <h1>{this.state.distance}</h1> </div> ); } } export default OldTrafford;
true
a93bb1ab2f187e54f8f2ed265361d1fee869ca05
JavaScript
syntax01/music_box
/js/app.js
UTF-8
1,917
2.9375
3
[]
no_license
$(document).ready( function() { const playClass = 'playing'; const playDelay = 300; var clicks = []; const keyCodes = [67, 72, 65, 82, 76, 69]; const keyChars = ["c","d","e","f","g","a","b"]; var eKey = 69; var eFlag = 0; function playAudio(x) { let box = document.getElementById(x); let audio = document.getElementById(x + 'Audio'); audio.currentTime = 0; audio.play(); box.classList.add(playClass); clicks.push(x); } function stopAudio(e) { if (e.propertyName !== 'transform') return; e.target.classList.remove(playClass); } function playClicks() { /* Copy clicks array to new array Each call to playAudio is going to add the key to the clicks array... so we need to clone and empty it before starting the loop */ let c = [...clicks]; resetClicks(); console.table(c); for(var i = 0; i < c.length; i++) { (function(i){ setTimeout(function(){ playAudio(c[i]); }, playDelay * i) })(i); } } function resetClicks() { clicks.length = 0; } function keyAudio(e) { let k = e.keyCode; let i = keyCodes.indexOf(k); if(i > -1) { if(k == eKey) { i += eFlag; eFlag = (eFlag == 0 ? 1 : 0); } playAudio(keyChars[i]); } } const boxes = Array.from(document.querySelectorAll('.box')); boxes.forEach(box => box.addEventListener('mousedown', function(){ playAudio(this.id); }) ); boxes.forEach(box => box.addEventListener('transitionend', stopAudio)); $('#replay').click(playClicks); $('#reset').click(resetClicks); window.addEventListener('keydown', keyAudio); });
true
632637cec3e2673f8d0e16ba92cd3ddd6f9e2636
JavaScript
ControleVersion/DBM_PORTAL
/painel/public/site/js/regDegust.js
UTF-8
618
3.03125
3
[ "MIT" ]
permissive
//recuoera o valor do cookie para colocar no input de email var useremail = document.cookie; var useremail = useremail.split(';'); var getEmail = getCookie('useremail'); $('#form-register-email').attr('value', getEmail); function searchStringInArray (str, strArray) { for (var j=0; j<strArray.length; j++) { if (strArray[j].match(str)){ var emailVal = strArray[j].split('='); $('#form-register-email').val(getEmail); $('#form-register-email').attr('value', getEmail); $('#form-register-nome').focus(); } } } searchStringInArray('useremail',useremail);
true
ea105e38b284d5187d73ae7472cdc4c61507a540
JavaScript
sveem/Vanilla-JavaScript
/Fundamentals/Strings's letters organizer/sortString.js
UTF-8
905
5.09375
5
[]
no_license
/* * Write a JavaScript function sortLetters(string, boolean) that gets as an input a string and a boolean. The function * sorts all letters in the string in alphabetical order and returns the newly formed string. The sorting is ascending if * the boolean is true otherwise the sorting is in descending order. * Note: The sorting is case-insensitive but the output should use the same casing as the input! * Hint: You are allowed to use .sort() function. */ let input = 'HelloWorld'; const sortLetters = (string, boolean) => { let stringToArray = string.split(''); let result; if (boolean) { result = stringToArray.sort((a, b) => a.toLowerCase() > b.toLowerCase()); } else { result = stringToArray.sort((a, b) => a.toLowerCase() < b.toLowerCase()); } return result.join(''); }; console.log(sortLetters(input, true)); console.log(sortLetters(input, false));
true
68f82c8e4306775df973cc84ff9b26ebae212b79
JavaScript
jacobmccaskey/ascend-coding-challenge
/functions.js
UTF-8
5,991
2.890625
3
[]
no_license
const { routes } = require("./data/data"); function findAllRoutes(startPoint, endPoint, startDistance) { let routeChain = { totalDistance: startDistance, start: startPoint, end: endPoint, connections: [], }; if (!routeChain.cache) { routeChain.cache = []; } if (startPoint === endPoint) { console.log( "please help the environment by walking your delivery to the location" ); return routeChain; } const checkIfStartMapped = routes.find( (route) => route.startPoint === startPoint.toLowerCase() ); const checkIfEndMapped = routes.find( (route) => route.startPoint === endPoint.toLowerCase() ); if (!checkIfStartMapped || !checkIfEndMapped) { throw new Error("looks like this city isnt mapped yet"); } for (const route of routes) { if (route.startPoint === startPoint) { const { connectingCities } = route; // checks to see if connecting city is destination and returns routeChain with totalDistance let connectsToEndPoint = connectingCities.filter( (connecting) => connecting.city === endPoint ); // console.log(`${startPoint} ,` + JSON.stringify(connectsToEndPoint)); if (connectsToEndPoint.length !== 0) { routeChain.totalDistance += connectsToEndPoint[0].distance; return routeChain; } if (connectsToEndPoint.length === 0 || connectsToEndPoint === undefined) { routeChain.cache.push(startPoint); let possibleConnects = []; connectingCities.forEach((option) => possibleConnects.push(option.city) ); routeChain.cache.forEach( (city) => (possibleConnects = possibleConnects.filter( (connect) => city !== connect )) ); let routesToCheck = []; for (let i = 0; i < possibleConnects.length; i++) { for (let j = 0; j < routes.length; j++) { // finds next route in routes array to check if that route has connection with destination if (possibleConnects[i] === routes[j].startPoint) { routesToCheck.push(routes[j]); } } } let routeReducer = []; for (let i = 0; i < routesToCheck.length; i++) { for (const opt of routesToCheck[i].connectingCities) { if (opt.city === endPoint) { routeReducer.push(routesToCheck[i]); } } } if (routeReducer.length === 0) { // triggers the recursive function to have another go at finding connections between current city's connections and the final destination return { recurse: true, start: startPoint, end: endPoint, connections: connectingCities, mileCount: startDistance, routes: routesToCheck, cache: routeChain.cache, }; } // the rest of this code constructs return object based on the parameters given one or several connecting cities connect to final destination. // start and end city is returned, totalDistance is calculated, and the last connecting point is returned with object. let shortestRoute = []; for (let i = 0; i < routeReducer.length; i++) { for (let point of routeReducer[i].connectingCities) { if (point.city === endPoint) { shortestRoute.push({ index: i, distance: point.distance }); } } } let shortest = shortestRoute.reduce((a, b) => a.distance < b.distance ? a : b ); let bestConnectingRoute = routeReducer[shortest.index]; let destinationFromBestRoute = bestConnectingRoute.connectingCities.filter( (each) => each.city === endPoint ); let distToConnection = route.connectingCities .map((connecting) => connecting.city === bestConnectingRoute.startPoint ? connecting.distance : null ) .filter((num) => num !== null); let connectionForRouteChain = { city: bestConnectingRoute.startPoint, end: destinationFromBestRoute[0].city, distance: destinationFromBestRoute[0].distance, }; routeChain.totalDistance += distToConnection[0]; routeChain.totalDistance += shortest.distance; routeChain.connections.push(connectionForRouteChain); } } } return routeChain; } function recursive(data, array, cache, start) { let { connections } = data; let result; let shortestRoute; if (cache) { // filters out cached connections from data that will be looped through cache.forEach( (city) => (connections = connections.filter((connect) => city !== connect.city)) ); } for (const connecting of connections) { result = findAllRoutes(connecting.city, data.end, connecting.distance); if (!result.recurse) { result.totalDistance += data.mileCount; array.push(result); } if (array.length > 4) { shortestRoute = array.reduce((a, b) => a.totalDistance < b.totalDistance ? a : b ); shortestRoute.start = data.start; return shortestRoute; } } if (array.length === 0) { return recursive(result, array, cache, start); } if (array.length !== 0) { shortestRoute = array.reduce((a, b) => a.totalDistance < b.totalDistance ? a : b ); shortestRoute.start = start; return shortestRoute; } } function determineShortestRoute(start, end, miles) { let options = []; let cache = []; const routeDiscovery = findAllRoutes(start, end, miles); if (routeDiscovery.recurse) { cache = routeDiscovery.cache; return recursive(routeDiscovery, options, cache, start); } else { return routeDiscovery; } } // let result = determineShortestRoute("miami", "houston", 0); // console.log(result); module.exports = { determineShortestRoute };
true
058cbef916920ec3037cf6b3290e1b8c65880463
JavaScript
TrueMistake/quizVanillaJs
/script.js
UTF-8
2,276
3.234375
3
[]
no_license
const quizData = [ { question: 'How old is Florin', a: '10', b: '17', c: '26', d: '110', correct: 'c' }, { question: 'What is the most programming language in 2019', a: 'Java', b: 'C', c: 'Python', d: 'Javascript', correct: 'd' }, { question: 'How old is Florin', a: '10', b: '17', c: '26', d: '110', correct: 'c' }, { question: 'What is the most programming language in 2019', a: 'Java', b: 'C', c: 'Python', d: 'Javascript', correct: 'd' } ]; const quiz = document.querySelector('.quiz'); const question = document.querySelector('.question'); const radio = document.querySelectorAll('input[type=radio]'); const a_text = document.querySelector('#a'); const b_text = document.querySelector('#b'); const c_text = document.querySelector('#c'); const d_text = document.querySelector('#d'); const btn = document.querySelector('.btn'); let currentQuestion = 0; let score = 0; loadQuiz(); function loadQuiz() { const currentQuiz = quizData[currentQuestion]; question.innerText = currentQuiz.question; a_text.innerText = currentQuiz.a; b_text.innerText = currentQuiz.b; c_text.innerText = currentQuiz.c; d_text.innerText = currentQuiz.d; } function getSelect() { let answer = undefined; radio.forEach(el => { if (el.checked) { answer = el.nextElementSibling.id; } }); return answer; } function clearSelect() { radio.forEach(el => { el.checked = false; }); } btn.addEventListener('click', () => { let answer = getSelect(); if (answer) { if (answer === quizData[currentQuestion].correct) { score++; } currentQuestion++; if (currentQuestion < quizData.length) { loadQuiz(); clearSelect(); } else { quiz.innerHTML = `<h2>You answered correctly at ${score} / ${quizData.length} questions</h2> <button onclick="location.reload()">Reload</button>` } } });
true
5431ed2472a772c1cfac5b82c043ab486758e851
JavaScript
kamilkrol95/JavaScrip-SpaceInvaders
/Alien.js
UTF-8
312
3.03125
3
[]
no_license
function Alien(x, y) { this.x = x; this.y = y; this.r = 15; this.dd = false; this.show = function() { noStroke(); fill(47,79,79); ellipse(this.x, this.y, this.r*2, this.r*2); } this.dead = function() { this.x += 1000; this.dd = true; } this.move = function() { this.y += level*0.3; } }
true
156de92adb6005d9b29585fbf1f73300f3d2b114
JavaScript
Redoxfox/mysite
/app/static/js/todos/sobre-my.js
UTF-8
246
2.578125
3
[]
no_license
var sobre_my = document.getElementById('sobre-my'); var titulo_items = document.getElementById('titulo-items'); sobre_my.addEventListener('mouseout', function(e) { sobre_my.style.background = "white"; titulo_items.background = "white"; })
true
b1d8e3faababbe8949bbe7199ce6964761b0064e
JavaScript
JooLuiz/RotaSeguraAPI
/rotasegura/frontend/src/reducers/tipoDenuncias.js
UTF-8
708
2.59375
3
[]
no_license
import { GET_TIPO_DENUNCIA, DELETE_TIPO_DENUNCIA, ADD_TIPO_DENUNCIA } from "../actions/types"; const initialState = { tipoDenuncias: [] }; export default function(state = initialState, action) { switch (action.type) { case GET_TIPO_DENUNCIA: return { ...state, tipoDenuncias: action.payload }; case DELETE_TIPO_DENUNCIA: return { ...state, tipoDenuncias: state.tipoDenuncias.filter( tipoDenuncias => tipoDenuncias.id !== action.payload ) }; case ADD_TIPO_DENUNCIA: return { ...state, tipoDenuncias: [...state.tipoDenuncias, action.payload] }; default: return state; } }
true