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
748edcc08ea82c14d34a54d3b0803d8fd42729bb
JavaScript
dillonchanis/pokedex
/profile.js
UTF-8
1,563
3.21875
3
[]
no_license
var http = require("http"); var EventEmitter = require("events").EventEmitter; var util = require("util"); //Function to get Pokemon Info function Profile(pokemon) { EventEmitter.call(this); profileEmitter = this; //Connect to the API var request = http.get("http://pokeapi.co/api/v1/pokemon/" + pokemon.toLowerCase() + "/", function(response){ //Will hold the data that streams in var body = ""; //Connection error, IF NOT SUCCESSFUL if(response.statusCode !== 200){ //abort the request request.abort(); //Give error message + ({statuscode in here}) profileEmitter.emit("error", new Error("There was an error getting the information for" + pokemon + ". (" + http.STATUS_CODES[response.statusCode] + ")")); }//end of connection error //Read the data chunks we recieve back in our 'body' var. //This will be a string response.on('data', function(chunk){ body += chunk; profileEmitter.emit("data", chunk); }); //Use JSON.parse() to convert our body string //To an object so we can access programatically response.on('end', function(){ //if connection is good //TRY to parse the data into JSON object if(response.statusCode === 200){ try { var profile = JSON.parse(body); profileEmitter.emit("end", profile); } catch (error) { profileEmitter.emit("error", error); } } }).on("error", function(error){ profileEmitter.emit("error", error); }); });//end of request }//end of Profile util.inherits( Profile, EventEmitter ); //Export module.exports = Profile;
true
4307c5728aa70f29806c2840cf85245e3ab369cd
JavaScript
yuansheng1989/streampoint-assignment1
/src/redux/cards/reducer.js
UTF-8
1,431
2.59375
3
[]
no_license
import { DUPLICATE_CARD, DELETE_CARD, EDIT_CARD } from "./constants"; import { v4 as uuidv4 } from "uuid"; const initState = { cards: [ { id: uuidv4(), title: "Custom Title", body: "Custom Body Text", titleSize: 36, bodySize: 16, cornerRadius: 16, titleColor: "#000000", bodyColor: "#000000", panelColor: "#ffffff", }, ], }; const CardsReducer = (state = initState, action) => { let newCards; switch (action.type) { case DUPLICATE_CARD: newCards = [...state.cards]; let newCard = { ...newCards.filter((card) => card.id === action.payload.id)[0], id: uuidv4(), }; newCards.splice( newCards.findIndex((card) => card.id === action.payload.id) + 1, 0, newCard ); return { ...state, cards: newCards, }; case DELETE_CARD: newCards = [...state.cards]; newCards.splice( newCards.findIndex((card) => card.id === action.payload), 1 ); return { ...state, cards: newCards, }; case EDIT_CARD: newCards = [...state.cards]; newCards.splice( newCards.findIndex((card) => card.id === action.payload.id), 1, action.payload ); return { ...state, cards: newCards, }; default: return state; } }; export default CardsReducer;
true
82b97f02aa4f19f4bbfa28abd37d19ffb87a0b5b
JavaScript
Balasundararao/ReactJS
/src/components/practicecomponents/react_hooks/HooksCounterTwo.js
UTF-8
917
3.109375
3
[]
no_license
import React, { useState } from 'react' function HooksCounterTwo() { const initialCount = 0; const [count, setCount] = useState(initialCount); const incrementFive = () => { for( let i=0; i<5; i++) { setCount( prevCount => prevCount + 1) } } return( <div> <p>Its a counter from Hooks counter Two........... Counter Value is :: {count}</p> <button className="btn btn-green" onClick={() => setCount( prevCount => prevCount+1)}> Increment Counter </button> <button className="btn btn-green" onClick={()=>setCount( prevCount => prevCount - 1)}> Decrement Counter </button> <button className="btn btn-green" onClick={()=>setCount(initialCount)}> Reset Counter </button> <button className="btn btn-green" onClick={incrementFive}> IncrementFive </button> </div> ) } export default HooksCounterTwo;
true
ca672bca0f4ba69ca1c32b0ae1b2a902870ef576
JavaScript
codeuniversity/ppp-profiler
/example_scripts/running_average.js
UTF-8
432
3.15625
3
[]
no_license
var average = get("average", 0) var count = get("count", 0) average = ((average * count) + message.value) / (count+1) count++ set("average", average) set("current", message.value) set("count", count) var t = "The lifetime average of the CPU temperature is "+ average.toFixed(2) +"C" title(t) description("Its current temperature is "+message.value.toFixed(2) + "C") if (message.value > 60) { action("You should cool it down") }
true
1be4a977c7e98cf758892b4948fbb1a5327bd0b8
JavaScript
braydenwerner/Werntype
/src/Components/AnimatedHeader/AnimatedHeader.js
UTF-8
1,793
2.78125
3
[ "MIT" ]
permissive
import React, { useState, useEffect } from 'react' import PropTypes from 'prop-types' import './AnimatedHeader.scss' export default function AnimatedHeader({ text }) { // this is overall pretty bad, did this a while ago, but its functional const [currentString, updateCurrentString] = useState('') const [currentStringIndex, updateStringIndex] = useState(0) // temp letter is necessary to the page doesnt jump when currentString is first init // set temp letter to nothing once currentString has something rendered const [tempLetter, setTempLetter] = useState('_') // if there are other dependencies causing re-render, this will not work let count = 0 let delayCount = 0 let delay = false let increasing = true const delayCooldown = 90 useEffect(() => { const animateStringTextInterval = setInterval(animateStringText, 50) return () => clearInterval(animateStringTextInterval) }, []) const animateStringText = () => { setTempLetter('') if (delay) delayCount++ if (delayCount > delayCooldown) { delayCount = 0 delay = false } if (!delay) { if (increasing) count++ else count-- if (count === 0 && !increasing) { increasing = true delay = true delayCount = 60 } else if (count === text.length && increasing) { increasing = false delay = true delayCount = 0 } updateStringIndex(currentStringIndex) updateCurrentString(text.substring(0, count)) } } return ( <div id="animated-header-container"> <div id="animated-header"> {tempLetter} {currentString} </div> <span id="animated-header-cursor">_</span> </div> ) } AnimatedHeader.propTypes = { text: PropTypes.string }
true
46ed4ba2568b1edf20d98b9cb4bb66d3b1d314a6
JavaScript
patrickhthomas/real-portfolio
/main.js
UTF-8
3,649
3.25
3
[]
no_license
window.onscroll = function () { moveRotate(); moveRotate2(); moveRotate3(); moveRotate4(); moveRotate5(); moveRotate6(); moveRotate7(); }; window.smoothScroll = function(target) { var scrollContainer = target; do { //find scroll container scrollContainer = scrollContainer.parentNode; if (!scrollContainer) return; scrollContainer.scrollTop += 1; } while (scrollContainer.scrollTop == 0); var targetY = 0; do { //find the top of target relatively to the container if (target == scrollContainer) break; targetY += target.offsetTop; } while (target = target.offsetParent); scroll = function(c, a, b, i) { i++; if (i > 30) return; c.scrollTop = a + (b - a) / 30 * i; setTimeout(function(){ scroll(c, a, b, i); }, 20); } // start scrolling scroll(scrollContainer, scrollContainer.scrollTop, targetY, 0); } // Get the modal var styleGuideWindow = document.getElementById("myModal"); // Get the button that opens the modal var btn = document.getElementById("styleGuideButton"); // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks the button, open the modal btn.onclick = function() { styleGuideWindow.style.display = "block"; } // When the user clicks on <span> (x), close the modal span.onclick = function() { styleGuideWindow.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == styleGuideWindow) { styleGuideWindow.style.display = "none"; } } function moveRotate() { let image = document.getElementById("animateObject"); image.style.transform += "rotate(" + window.pageYOffset/-200 +"deg)"; image.style.transform += "translateX(" + window.pageYOffset/-17 +"px)"; image.style.transform += "translateY(" + window.pageYOffset/-77 +"px)"; } function moveRotate2() { let image = document.getElementById("animateObject2"); image.style.transform += "rotate(" + window.pageYOffset/200 +"deg)"; image.style.transform += "translateX(" + window.pageYOffset/17 +"px)"; image.style.transform += "translateY(" + window.pageYOffset/77 +"px)"; } function moveRotate3() { let image = document.getElementById("animateObject6"); image.style.transform += "rotate(" + window.pageYOffset/130 +"deg)"; image.style.transform += "translateY(" + window.pageYOffset/-70 +"px)"; } function moveRotate4() { let image = document.getElementById("animateObject4"); image.style.transform += "translateY(" + window.pageYOffset/-70 +"px)"; image.style.transform += "translateX(" + window.pageYOffset/-70 +"px)"; } function moveRotate5() { let image = document.getElementById("animateObject5"); image.style.transform += "translateY(" + window.pageYOffset/-70 +"px)"; image.style.transform += "translateX(" + window.pageYOffset/-70 +"px)"; } function moveRotate6() { let image = document.getElementById("animateObject6"); image.style.transform += "translateY(" + window.pageYOffset/-70 +"px)"; image.style.transform += "translateX(" + window.pageYOffset/-70 +"px)"; } function moveRotate7() { let image = document.getElementById("animateObject7"); image.style.transform += "rotate(" + window.pageYOffset/130 +"deg)"; image.style.transform += "translateY(" + window.pageYOffset/-70 +"px)"; }
true
dc2021cb9f43134373ee34122c85623136ffafa1
JavaScript
flow-ai/flowai-js-templates
/src/messenger/templates/products.js
UTF-8
1,201
2.59375
3
[]
no_license
import Template from '../../base/templates/template' /** * Products Template * * @description * The product template can be used to render products that have been uploaded to Facebook catalog. Product details (image, title, price) will automatically be pulled from the product catalog. * * @memberof Messenger * @category Templates * * @property {string[]} productIds - list of product IDs * * @example * // Single product card * const product = new Messenger.Products('11232112332') * * // Carousel of products * const product = new Messenger.Products(['11232112332', '23422224343]) **/ class Products extends Template { /** * @param {string[]} productIds - Required **/ constructor(productIds) { super() if (!Array.isArray(productIds) || !productIds.length) { throw new Error('productIds must be an array and contain at least one product ID') } this.productIds = productIds } toJSON() { const { productIds, delay, fallback } = this return { type: 'messenger_products', payload: { productIds }, delay: delay || undefined, fallback } } } export default Products
true
09c0f31172258bb7ed027b7d29076ea81cf61ec0
JavaScript
Rax4/Warsztaty-Dodatkowe
/templateA/js/addressView.js
UTF-8
1,711
2.78125
3
[]
no_license
document.addEventListener("DOMContentLoaded",function() { function loadUserView() { $.ajax( { type: 'GET', url: '../../router.php/address/', contentType: 'application/json', dataType: 'json', success: function (response) { addContentUser(response); }, error: function (xhr, status, error) { alert("Wystąpił błąd"); } }) } loadUserView(); function addContentUser(responseFromAjax) { $.each(responseFromAjax, function(key, oUser) { tr = document.createElement("tr"); tdId = document.createElement("td"); tdCity = document.createElement("td"); tdCode = document.createElement("td"); tdStreet = document.createElement("td"); tdNumber = document.createElement("td"); tdId.className="id"; tdCity.className="city"; tdCode.className="code"; tdStreet.className="street"; tdNumber.className="number"; tr.append(tdId); tr.append(tdCity); tr.append(tdCode); tr.append(tdStreet); tr.append(tdNumber); tdId.innerHTML = oUser.id; tdCity.innerHTML = oUser.city; tdCode.innerHTML = oUser.code; tdStreet.innerHTML = oUser.street; tdNumber.innerHTML = oUser.number; tr = $('table').append(tr); }); } });
true
383ade779d0b4789dc57e74ba9807a475c2523ba
JavaScript
zolotyh/27042017
/examples/1.js
UTF-8
3,963
2.78125
3
[ "MIT" ]
permissive
const image = document.createElement('img'); document.body.appendChild(image); image.style.position = 'absolute'; image.style.zIndex = 1000; image.style.left = 0; image.style.top = 0; image.setAttribute('src', 'http://localhost:8001/assets/images/layout.png'); image.onmousedown = function (e) { const coords = getCoords(image); const shiftX = e.pageX - coords.left; const shiftY = e.pageY - coords.top; image.style.position = 'absolute'; moveAt(e); image.style.zIndex = 1000; // над другими элементами function moveAt(e) { image.style.left = e.pageX - shiftX + 'px'; image.style.top = e.pageY - shiftY + 'px'; window.pixelperfectconfig = getStyle(image); } document.onmousemove = function (e) { moveAt(e); }; image.onmouseup = function () { document.onmousemove = null; image.onmouseup = null; }; } image.ondragstart = function () { return false; }; function getCoords(elem) { var box = elem.getBoundingClientRect(); var body = document.body; var docEl = document.documentElement; var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop; var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft; var clientTop = docEl.clientTop || body.clientTop || 0; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var top = box.top + scrollTop - clientTop; var left = box.left + scrollLeft - clientLeft; return { top: Math.round(top), left: Math.round(left) }; } function KeyPress(e) { if(e.altKey && e.code === 'KeyX'){ // x key const isVisible = image.style.display !== 'none' if(isVisible){ image.style.display = 'none'; } else { image.style.display = 'block'; } return; } let step = 1; if(e.shiftKey){ step = 10; } if(e.code === 'KeyO'){ if(image.style.opacity > 0){ image.style.opacity -= step/100; return; } } if(e.code === 'KeyP'){ if(image.style.opacity < 1){ image.style.opacity = +image.style.opacity + step/100; return; } } if(e.code === 'KeyH' || e.code === 'ArrowLeft'){ image.style.left = +image.style.left.replace('px','') - step + 'px'; e.preventDefault(); } if(e.code === 'KeyL' || e.code === 'ArrowRight'){ image.style.left = +image.style.left.replace('px','') + step + 'px'; e.preventDefault(); } if(e.code === 'KeyK' || e.code === 'ArrowUp'){ image.style.top = +image.style.top.replace('px','') - step + 'px'; e.preventDefault(); } if(e.code === 'KeyJ' || e.code === 'ArrowDown'){ image.style.top = +image.style.top.replace('px','') + step + 'px'; e.preventDefault(); } if(e.altKey && e.code === 'KeyR'){ image.style.opacity = 1; image.style.display = 'block'; image.style.left = 0; image.style.top = 0; window.pixelperfectconfig = null; } window.pixelperfectconfig = getStyle(image); } document.onkeydown = KeyPress; document.addEventListener('DOMContentLoaded', function(){ if(window.pixelperfectconfig){ setStyle(image, window.pixelperfectconfig) } }); function setStyle(elem, config){ elem.style.opacity = config.opacity; elem.style.top = config.top; elem.style.left = config.left; elem.style.display = config.display } function getStyle(elem){ return { opacity: elem.style.opacity, top:elem.style.top, left: elem.style.left, display: elem.style.display } } Object.defineProperty(window, "pixelperfectconfig", { get: function () { return JSON.parse(localStorage.getItem('.position')); }, set: function(value){ return localStorage.setItem('.position', JSON.stringify(value)); } });
true
2e5471fb1bf8b69e69d5ed05d9993081a842f155
JavaScript
RostislavZalevsky/HTML-CSS-JS-Padding-Margin
/script.js
UTF-8
1,460
2.96875
3
[]
no_license
var Text = document.getElementById("Text"); Text.onkeydown = ClearText; var margintop = document.getElementById("margin-top"); var marginbottom = document.getElementById("margin-bottom"); var marginleft = document.getElementById("margin-left"); var marginright = document.getElementById("margin-right"); var bordertop = document.getElementById("border-top"); var borderbottom = document.getElementById("border-bottom"); var borderleft = document.getElementById("border-left"); var borderight = document.getElementById("border-right"); var paddingtop = document.getElementById("padding-top"); var paddingbottom = document.getElementById("padding-bottom"); var paddingleft = document.getElementById("padding-left"); var paddingright = document.getElementById("padding-right"); function ChangeProperty() { Text.style.margin = margintop.value + "px " + marginright.value + "px " + marginbottom.value + "px " + marginleft.value + "px"; Text.style.borderTopWidth = bordertop.value + "px"; Text.style.borderRightWidth = borderight.value + "px"; Text.style.borderBottomWidth = borderbottom.value + "px"; Text.style.borderLeftWidth = borderleft.value + "px"; Text.style.padding = paddingtop.value + "px " + paddingright.value + "px " + paddingbottom.value + "px " + paddingleft.value + "px"; } function ClearText() { Text.innerHTML = ""; Text.onkeydown = null; }
true
19ed565342c471b2fd8c16dcaec70ce3dbafe16a
JavaScript
happysuslik/training
/angular/table/assets/javascripts/work2.js
UTF-8
858
2.71875
3
[]
no_license
/** * Created by Gix on 20.11.2015. */ var model = { user: "Root", recipes: [{ name: "Яишница", passed: true}, { name: "Индейка", passed: true}, { name: "Курица в духовке", passed: true}, { name: "Яблочный пирог", passed: false}] }; var recipeListApp = angular.module("recipeListApp", []); recipeListApp.controller("RecipeCtrl", function ($scope) { $scope.data = model; $scope.addNewRecipe = function() { $scope.data.recipes.push({ name: $scope.recipeName, passed: false }); $scope.recipeName = ""; }; $scope.showText = function (passed) { return passed ? "Да" : "Нет"; }; $scope.setStyle = function (passed) { return passed ? "color:green" : "color:red; font-weight: bold"; }; });
true
b3cfe4e60cd0abde74ba97cc974c26aa6f2fa705
JavaScript
svetoslavmishev/js-web
/ExpressJS/02.NodeJSIntroduction/IntroductionToNodeHomework/storageModule.js
UTF-8
2,196
3.078125
3
[]
no_license
let storage = (() => { let storage = new Map(); let fs = require('fs'); function put(key, value) { if (!checkIfString(key)) { throw new Error('The key must be a String!'); } if (isInStorage(key)) { throw new Error('The key is already in the Storage'); } storage.set(key, value); } function get(key) { if (!checkIfString(key)) { throw new Error('The key must be a String!'); } if (!isInStorage(key)) { throw new Error('The key is not in the Storage'); } return storage.get(key); } function getAll() { if (storage.size == 0) { return 'The Storage is empty!'; } return storage; } function update(key, newValue) { if (!checkIfString(key)) { throw new Error('The key must be a String!'); } if (!isInStorage(key)) { throw new Error('The key must be in the Storage!'); } storage.set(key, newValue); } function remove(key) { if (!checkIfString(key)) { throw new Error('The key must be a String!'); } if (!isInStorage(key)) { throw new Error('The key must be in the Storage!'); } storage.delete(key); } function clear() { storage.clear(); } function save() { fs.writeFile( './storage.json', JSON.stringify([...storage]), function(err) { if (err) { return; } }); } function load(cb) { fs.readFile( './storage.json', 'utf8', function (err,data) { if (err) { return; } storage = new Map(JSON.parse(data)); console.log(cb()); }); } function checkIfString(key) { return typeof key === 'string'; } function isInStorage(key) { return storage.has(key); } return { put, get, getAll, update, remove, clear, save, load }; })(); module.exports = { storage };
true
909bb35e1246adced855c0bf8e7f6e434e6ba27a
JavaScript
augustinevt/logistic-pizza-app
/js/ui.js
UTF-8
1,689
2.734375
3
[]
no_license
var pizzaInfo = {toppings: []}; function domify() { $('.order').remove(); currentCustomer.orders.forEach(function(order) { $('body').append('<div class="order" id="order'+ order.id + '"></div>'); $('#order' + order.id).append('<h3>'+order.id+'</h3>'); $('#order' + order.id).append('<h2 class="size">hello</h2>'); $('#order' + order.id).append('<button class="newPizza" type="button" id="order-'+order.id+'">New Pizza</button>'); order.pizzas.forEach(function(pizza) { var toppings = ''; pizza.toppings.forEach(function(topping, i){ toppings += "<h6>" + topping + "</h6>"; }); $('#order' + order.id).append('<div class="iconContainer"><h2 class=".size">' + pizza.size + '</h2><div class="pizzaIcon"></div>'+toppings+'</div>'); }); $('#order-' + order.id).click(function(){ $('#cloud').fadeIn(); $('pizzaForm').fadeIn(); $('#addTopping').click(function(){ pizzaInfo.toppings.push($('input[type="text"]').val()); $('input[type="text"]').val(''); }); $('#createPizza').click(function(){ pizzaInfo['size'] = $('input[type="radio"]:checked').val(); order.pizzas.push(new Pizza(pizzaInfo, order)); pizzaInfo = {toppings: []}; $('#cloud').fadeOut(); $('pizzaForm').fadeOut(); $(this).unbind(); domify(); }); $(this).unbind(); }); }); } $(function(){ var id = 0; // var name = prompt("hello! What's your name?"); currentCustomer = new Customer("fred"); $('#newOrder').click(function() { currentCustomer.orders.push(new Order(currentCustomer, id)); id++; domify(); }); });
true
410b168b40e8a7a847b5e34dbe5eda8877ec6fcd
JavaScript
Nadjakoroleva/dima-hero
/js/script.js
UTF-8
2,366
3.046875
3
[]
no_license
let hero; let healthpack; let enemy; let x = 2; let dx = 5; let y = 2; let dy = 5; let hx = 400; let hy = 100; let ex = -10; let ey = -10; let dex = 1; let dey = 1; let c = 0; let raz = 100; let lose = 0; let health = 0; let dhealth = 0; let dmg = 0; let boost = 0; function setup() { createCanvas(800, 800); } function preload() { // preload() runs once hero = loadImage("hero.png"); healthpack = loadImage("healthpack.png"); enemy = loadImage("enemy.png"); } function draw() { background("#FFFFFF"); hero.resize(0, raz); image(hero, x, y); healthpack.resize(0, 30); image(healthpack, hx, hy); if (x > hx - 50 && x < hx + 100) { if (y > hy - 100 && y < hy + 50) { hx = random(100, 700); hy = random(100, 700); c = c + 1; raz = raz + 10; dhealth = dhealth + 1; } } //Food textSize(20); text("ОЗ", 50, 695); if (health <= 25) { fill("#FF0303"); } rect(50, 700, health, 20); //healthbar health = 100 - millis() / 1000 - dmg + dhealth; // healthbar engine if (health > 100) { health = 100; } if (health <= 0) { health = 0; } if (health == 0) { x = 4000; y = 4000; lose = 1; health = 0; } //lose fill(0); textSize(30); text("Счет: ", 650, 50); text(c, 740, 50); if (c > 1) { image(enemy, ex, ey); } else { ex = -1000; ey = -1000; if (c > 9) { boost = 2; } } //enemy engine if (c >= 15) { c = 15; ex = 4000; ey = 4000; health = 100; textSize(100); text("WIN!", 300, 400); } if (ex < 0 || ex > width) { ex = -ex; } if (ey < 0 || ey > height - 10) { ey = -ey; } if (ex < x) { ex = ex + dex + boost; } if (ey < y) { ey = ey + dey + boost; } if (ex > x) { ex = ex - dex - boost; } if (ey > y) { ey = ey - dey - boost; } if (ey - 30 <= y + 10 && ey + 30 >= y - 10) { if (ex + 30 >= x - 10 && ex - 30 <= x + 10) { dmg = dmg + 1; } } else { dmg = 0; } //x = 4000; y = 4000; lose = 1;}} lose #2 if (lose == 1) { textSize(30); text("Игра окончена", 250, 55); } } function keyPressed() { if (keyCode == RIGHT_ARROW) { x = x + dx; } if (keyCode == LEFT_ARROW) { x = x - dx; } if (keyCode == UP_ARROW) { y = y - dy; } if (keyCode == DOWN_ARROW) { y = y + dy; } }
true
ae1dda7ed28e1160d69a17a860a6cd9e15804440
JavaScript
EirikBirkeland/search-replace-chrome-extension
/index.js
UTF-8
435
3.03125
3
[]
no_license
document.addEventListener("DOMContentLoaded", function (event) { function textNodesUnder (el) { let n; const a = []; const walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false); while (n = walk.nextNode()) { a.push(n); } return a; } textNodesUnder(document).map(x => { if(!x.childNodes.length && x.textContent.match(/Erna/)){ x.textContent = "Fjerna" } }); });
true
7d8d2d47ad057f05cf044f47363475855e2c97ac
JavaScript
Reaper622/DataStructure-Algorithm-TS
/Algorithm/Search/FindClosestElements.js
UTF-8
2,109
3.59375
4
[]
no_license
"use strict"; exports.__esModule = true; /** * 给定一个排序好的数组,两个整数 k 和 x, * 从数组中找到最靠近 x(两数之差最小)的 k 个数。 * 返回的结果必须要是按升序排好的。 * 如果有两个数与 x 的差值一样,优先选择数值较小的那个数。 * * @param {number[]} arr * @param {number} k * @param {number} x */ function FindClosestElements(arr, k, x) { var left = 0; var right = arr.length - 1; var mid; while (left < right) { mid = Math.floor(left + (right - left) / 2); // 若找到数组中确有此值 跳出循环 if (arr[mid] === x) { k--; break; } else if (arr[mid] < x && arr[mid + 1] > x) { x - arr[mid] > arr[mid + 1] - x ? mid = mid + 1 : mid = mid; k--; break; } else if (arr[mid] < x) { left = mid + 1; } else { right = mid; } } // 目标在数组内 if (left !== right) { var pointerL = mid; var pointerR = mid; while (k > 0) { if (x - arr[pointerL - 1] <= arr[pointerR + 1] - x) { if (pointerL > 0) { pointerL--; k--; } else if (k > 0 && pointerR < arr.length - 1) { pointerR++; k--; } } else { if (k > 0 && pointerR < arr.length - 1) { pointerR++; k--; } else if (pointerL > 0) { pointerL--; k--; } } } return arr.slice(pointerL, pointerR + 1); } else { // 如果目标在左边界以外 if (left === 0) { return arr.slice(0, k); } // 如果目标在右边界以外 else { return arr.slice(arr.length - k); } } } exports.FindClosestElements = FindClosestElements;
true
7372933e9068bce9a5ff36d00a7df3f2d5fcb57d
JavaScript
Emmett09/Pizza_Shop_App
/src/App.js
UTF-8
20,400
3.0625
3
[]
no_license
import React, { Component } from "react"; import Basket from "./Basket"; class App extends Component { constructor(props) { super(props); // each array starting with apiData is an // array to hold our JSON data // isFetched indicates if the API call has finished // errorMsg is either null (none) or there is some error this.state = { custCheeseError: "", custCheeseLimit: 1, custToppingError: "", custToppingLimit: 1, apiDataToppings: [], apiDataCheeses: [], apiDataBases: [], apiDataSizes: [], custSizeChoice: 1.0, custBaseChoice: [], custToppingChoices: [], custCheeseChoices: [], custPizzaSizeChoices: [], isFetched: false, errorMsg: null }; this.handleBaseListChange = this.handleBaseListChange.bind(this); this.handleResetAll = this.handleResetAll.bind(this); this.handleToppingChoiceRemovalAdvanced = this.handleToppingChoiceRemovalAdvanced.bind( this ); this.handleToppingChoice = this.handleToppingChoice.bind(this); this.handleCheeseChoiceRemovalAdvanced = this.handleCheeseChoiceRemovalAdvanced.bind( this ); this.handleCheeseChoice = this.handleCheeseChoice.bind(this); this.handlePizzaSizeListChange = this.handlePizzaSizeListChange.bind(this); } // componentDidMount() is invoked immediately after a // component is mounted (inserted into the tree) async componentDidMount() { try { const API_URL = "https://raw.githubusercontent.com/petermooney/cs385/main/pizzaAPI/pizza.json"; const response = await fetch(API_URL); // wait for the response. When it arrives, store the JSON version // of the response in this variable. const jsonResult = await response.json(); this.setState({ custCheeseLimit: jsonResult.CHEESE_LIMIT }); this.setState({ custToppingLimit: jsonResult.TOPPING_LIMIT }); // update the state variables correctly. this.setState({ apiDataSizes: jsonResult.sizes }); this.setState({ apiDataToppings: jsonResult.toppings }); this.setState({ apiDataCheeses: jsonResult.cheeses }); this.setState({ apiDataBases: jsonResult.bases }); //console.log(this.state.apiData.length); this.setState({ isFetched: true }); } catch (error) { // In the case of an error ... this.setState({ isFetched: false }); // This will be used to display error message. this.setState({ errorMsg: error }); } // end of try catch } // end of componentDidMount() // sort method so that bases is in sorted order. sortBases(baseA, baseB) { let comparison = 0; // remember strings can be compared using > and < in Javascript if (baseA.baseName > baseB.baseName) comparison = 1; else if (baseA.baseName < baseB.baseName) comparison = -1; else comparison = 0; return comparison; } // sort method so that toppings table is in sorted order. sortToppings(toppingsA, toppingsB) { let comparison = 0; // remember strings can be compared using > and < in Javascript if (toppingsA.topName > toppingsB.topName) comparison = 1; else if (toppingsA.topName < toppingsB.topName) comparison = -1; else comparison = 0; return comparison; } // sort method so that cheeses table is in sorted order. sortCheese(cheeseA, cheeseB) { let comparison = 0; // remember strings can be compared using > and < in Javascript if (cheeseA.chName > cheeseB.chName) comparison = 1; else if (cheeseA.chName < cheeseB.chName) comparison = -1; else comparison = 0; return comparison; } // Event handler for the drop-down-list handleBaseListChange(event) { // We assign the value of the event // The event is what is 'selected' from the list. This action // is an event. The baseID is passed here. // we need to find this object from the apiDataBases array // We force Javascript to convert the event.target.value to a // numeric value so that we can use it for filtering. let choosenBaseObject = this.state.apiDataBases.filter( this.findBaseByBaseID(Number(event.target.value)) ); // REMEMBER - filter always returns an array - even if it is // just one object.We don't use concat as we are assigning a brand // new array to custBaseChoice. this.setState({ custBaseChoice: choosenBaseObject }); } // This filter function will find the object in the // apiDataBases array which matches the baseID of the option chosen by the // user. findBaseByBaseID(baseID) { return function (pizzaBaseObject) { return pizzaBaseObject.baseID === baseID; }; } handleToppingChoice(topName) { // we have to limit the number of toppings any user can order // if they have already choosen this.state.custToppingLimit toppings // cannot choose any more. give an error message if (this.state.custToppingChoices.length < this.state.custToppingLimit) { this.setState({ custToppingError: "" }); // no error with this condition // use filter to find the topping object with name = topName let choosenToppingObject = this.state.apiDataToppings.filter( this.findToppingByTopName(topName) ); // REMEMBER - filter always returns an array - even if it is // just one object. // here we must use concat as custToppingChoices is an array this.setState({ custToppingChoices: this.state.custToppingChoices.concat( choosenToppingObject ) }); } else { // don't add any more toppings. There is a limit on toppings. // give an error message instead. this.setState({ custToppingError: "Limit of " + this.state.custToppingLimit + " toppings. Please review your choices" }); } } // This filter function will find the object in the // apiDataToppings array which matches the baseID of the option chosen by the // user. findToppingByTopName(topName) { return function (toppingObject) { return toppingObject.topName === topName; }; } // This is a boolean to indicate if this toppinng has already // been chosen by the user. alreadyChosenThisTopping(topName) { let foundThisTopping = this.state.custToppingChoices.filter( this.findToppingByTopName(topName) ); return foundThisTopping.length > 0; } // how many times is this topping chosen! This is the same as the function // above except for a different return statement. numberTimesChosenThisTopping(topName) { let foundThisTopping = this.state.custToppingChoices.filter( this.findToppingByTopName(topName) ); return foundThisTopping.length; } // we want to remove ONE object with the topping name = topName. handleToppingChoiceRemovalAdvanced(topName) { // we start by reusing our filter call back function to find toppings // based on their topping name. // The findIndex method simply returns the index of the first position // in the array where an object with this topping name is found. // If there are many objects with this topping name, the first index is returned. // we make a local copy of the state array custToppingChoices // this is the recommended approach. let currentCustToppingChoices = this.state.custToppingChoices; let firstObjectIndex = currentCustToppingChoices.findIndex( this.findToppingByTopName(topName) ); // here we use splice. This means that we want to SPLICE one // object from the array at the position firstObjectIndex // The object at this index is removed and the array is // reformed. currentCustToppingChoices.splice(firstObjectIndex, 1); // We now setState with the newly spliced array minus // one object this.setState({ custToppingChoices: currentCustToppingChoices }); } handleCheeseChoice(cheeseName) { // we have to limit the number of cheese any user can order // if they have already choosen this.state.custCheeseLimit cheeses // cannot choose any more. give an error message if (this.state.custCheeseChoices.length < this.state.custCheeseLimit) { this.setState({ custCheeseError: "" }); // no error with this condition // use filter to find the cheeese object with name = chName let choosenCheeseObject = this.state.apiDataCheeses.filter( this.findCheeseByCheeseName(cheeseName) ); // REMEMBER - filter always returns an array - even if it is // just one object. // here we must use concat as custToppingChoices is an array this.setState({ custCheeseChoices: this.state.custCheeseChoices.concat( choosenCheeseObject ) }); } else { // don't add any more cheese. There is a limit on cheese. // give an error message instead. this.setState({ custCheeseError: "Limit of " + this.state.custCheeseLimit + " cheeses. Please review your choices" }); } } // This filter function will find the object in the // apiDataCheeses array which matches the chName of the option chosen by the // user. findCheeseByCheeseName(cheeseName) { return function (cheeseObject) { return cheeseObject.chName === cheeseName; }; } // This is a boolean to indicate if this cheese has already // been chosen by the user. alreadyChosenThisCheese(cheeseName) { let foundThisCheese = this.state.custCheeseChoices.filter( this.findCheeseByCheeseName(cheeseName) ); return foundThisCheese.length > 0; } // how many times is this cheese chosen! This is the same as the function // above except for a different return statement. numberTimesChosenThisCheese(cheeseName) { let foundThisCheese = this.state.custCheeseChoices.filter( this.findCheeseByCheeseName(cheeseName) ); return foundThisCheese.length; } // we want to remove ONE object with the topping name = topName. handleCheeseChoiceRemovalAdvanced(cheeseName) { // we start by reusing our filter call back function to find cheeses // based on their cheese name. // The findIndex method simply returns the index of the first position // in the array where an object with this cheese name is found. // If there are many objects with this cheese name, the first index is returned. // we make a local copy of the state array custCheeseChoices // this is the recommended approach. let currentCustCheeseChoices = this.state.custCheeseChoices; let firstObjectIndex = currentCustCheeseChoices.findIndex( this.findCheeseByCheeseName(cheeseName) ); // here we use splice. This means that we want to SPLICE one // object from the array at the position firstObjectIndex // The object at this index is removed and the array is // reformed. currentCustCheeseChoices.splice(firstObjectIndex, 1); // We now setState with the newly spliced array minus // one object this.setState({ custCheeseChoices: currentCustCheeseChoices }); } handleResetAll() { this.setState({ custToppingError: "" }); this.setState({ custToppingChoices: [] }); this.setState({ custBaseChoice: [] }); this.setState({ custCheeseChoices: [] }); this.setState({ custPizzaSizeChoices: [] }); this.setState({ custSizeChoice: 1.0 }); } // in this method the user's choice of size // will determine the pricing of all parts of the pizza. handlePizzaSizeListChange(event) { // We assign the value of the event // The event is what is 'selected' from the list. This action // is an event. The sName is passed here. // we need to find this object from the apiDataSizes array let choosenSizeObject = this.state.apiDataSizes.filter( this.findSizeBySizeName(event.target.value) ); // REMEMBER - filter always returns an array - even if it is // just one object.We don't use concat as we are assigning a brand // new array to custPizzaSizeChoices. this.setState({ custPizzaSizeChoices: choosenSizeObject }); // the choosenSizeObject is a single element array // we need to get the pricing or cost factor value from this. let costFactor = choosenSizeObject[0].costFactor; // set this.state.custSizeChoice to this value // now we can multiply by this cost factor. this.setState({ custSizeChoice: Number(costFactor) }); } findSizeBySizeName(sizeName) { return function (pizzaSizeObject) { return pizzaSizeObject.sName === sizeName; }; } // Remember our three state variables. // PAY ATTENTION to the JSON returned. We need to be able to // access specific properties from the JSON returned. // Notice that this time we have three possible returns for our // render. This is conditional rendering based on some conditions render() { if (this.state.errorMsg) { return ( <div className="error"> <h1>An error has occured in the API call</h1> <p>You can do the following to fix this.... </p> <p>{this.state.errorMsg.toString()}</p> </div> ); // end of return. } else if (this.state.isFetched === false) { return ( <div className="fetching"> <h1>We are loading your API request........</h1> </div> ); // end of return } else { // we have no errors and we have data return ( <div className="App"> <div className="container"> <h1>CS385 Pizza Ltd.</h1> <Basket custToppingsArray={this.state.custToppingChoices} custBaseArray={this.state.custBaseChoice} custCheesesArray={this.state.custCheeseChoices} custPizzaSizesArray={this.state.custPizzaSizeChoices} custSizeChoice={this.state.custSizeChoice} /> <div className="alert alert-info" role="alert"> <h1>Pizza Size</h1> <form> <div className="form-group"> Which size? (pick one please): <br /> <select className="form-control" onChange={this.handlePizzaSizeListChange} > {this.state.apiDataSizes.map((sz, index) => ( <option key={index} value={sz.sName}> {sz.sName} </option> ))} </select> </div> </form> </div> <div className="alert alert-info" role="alert"> <h1>Pizza Bases</h1> <form> <div className="form-group"> Pick your base (one please): <br /> <select className="form-control" onChange={this.handleBaseListChange} > {this.state.apiDataBases .sort(this.sortBases) .map((b, index) => ( <option key={index} value={b.baseID}> {b.baseName}, € {(this.state.custSizeChoice * b.price).toFixed(2)} </option> ))} </select> </div> </form> {this.state.custBaseChoice.length > 0 && ( <p className="lead"> BASE CHOICE: {this.state.custBaseChoice[0].baseName} </p> )} </div> <div className="alert alert-info" role="alert"> <h1>Pizza Toppings</h1> {this.state.custToppingError} <table className="table table-sm table-bordered"> <thead> <tr> <th>Name (topping)</th> <th>Cost (portion)</th> <th>Action</th> </tr> </thead> <tbody> {this.state.apiDataToppings .sort(this.sortToppings) .map((s, index) => ( <tr key={index}> <td> {s.topName} {this.alreadyChosenThisTopping(s.topName) && ( <mark className="lead"> x{this.numberTimesChosenThisTopping(s.topName)} </mark> )} </td> <td> €{(this.state.custSizeChoice * s.price).toFixed(2)} </td> <td> <button onClick={() => this.handleToppingChoice(s.topName)} type="button" className="btn btn-dark" > + </button> &nbsp; {this.alreadyChosenThisTopping(s.topName) && ( <button className="btn btn-dark" onClick={() => this.handleToppingChoiceRemovalAdvanced( s.topName ) } > {" "} - </button> )} </td> </tr> ))} </tbody> </table> </div> <div className="alert alert-info" role="alert"> <h1>Pizza Cheeses</h1> {this.state.custCheeseError} <table className="table table-sm table-bordered"> <thead> <tr> <th>Name (topping)</th> <th>Cost (portion)</th> <th>Action</th> </tr> </thead> <tbody> {this.state.apiDataCheeses .sort(this.sortCheese) .map((c, index) => ( <tr key={index}> <td> {" "} {c.chName} {this.alreadyChosenThisCheese(c.chName) && ( <mark className="lead"> x{this.numberTimesChosenThisCheese(c.chName)} </mark> )} </td> <td> €{(this.state.custSizeChoice * c.price).toFixed(2)} </td> <td> <button onClick={() => this.handleCheeseChoice(c.chName)} type="button" className="btn btn-dark" > + </button> &nbsp; {this.alreadyChosenThisCheese(c.chName) && ( <button className="btn btn-dark" onClick={() => this.handleCheeseChoiceRemovalAdvanced(c.chName) } > - </button> )} </td> </tr> ))} </tbody> </table> </div> <button onClick={this.handleResetAll} type="button" className="btn btn-primary btn-lg btn-block" > Reset All{" "} </button> </div> </div> ); // end of return } // end of the else statement. } // end of render() } // end of App class export default App;
true
f7e28d623132db2fbdf7920d24f06c14024fe864
JavaScript
rapm94/todo-client
/src/helpers/api.js
UTF-8
1,183
2.65625
3
[]
no_license
import axios from "axios"; const URL = 'http://127.0.0.1:6080/api'; export const getTodos = async () => { try { const todos = await axios.get(URL + "/todos") return todos } catch (error) { console.log(error) } } export const addTodo = async (formData) => { try { const todo = ({ name: formData.name, description: formData.description, done: false, assigned: formData.assigned, priority: formData.priority, }) const saveTodo = await axios.post(URL + "/add-todo", todo ) return saveTodo } catch (error) { console.log(error) } } export const updateTodo = async(todo) => { try { const todoUpdate = { done: !todo.done } const updatedTodo = await axios.put(`${URL}/edit-todo/${todo._id}`, todoUpdate) return updatedTodo } catch (error) { console.log(error) } } export const deleteTodo = async(_id) => { try { const deletedTodo = await axios.delete(`${URL}/delete-todo/${_id}`) return deletedTodo } catch (error) { console.log(error) } }
true
81422e9f1c6332939025c3f8102d2c27a7ce44b0
JavaScript
Ottervanger/lumo
/src/renderer/tile/WebGLTileRenderer.js
UTF-8
7,157
2.953125
3
[ "MIT" ]
permissive
'use strict'; const defaultTo = require('lodash/defaultTo'); const EventType = require('../../event/EventType'); const Shader = require('../../webgl/shader/Shader'); const TextureArray = require('../../webgl/texture/TextureArray'); const VertexAtlas = require('../../webgl/vertex/VertexAtlas'); const TileRenderer = require('./TileRenderer'); // Constants /** * Tile add handler symbol. * * @private * @constant {symbol} */ const TILE_ADD = Symbol(); /** * Tile remove handler symbol. * * @private * @constant {symbol} */ const TILE_REMOVE = Symbol(); // Private Methods const addTileToTextureArray = function(array, tile) { array.set(tile.coord.hash, tile.data); }; const removeTileFromTextureArray = function(array, tile) { array.delete(tile.coord.hash); }; const addTileToVertexAtlas = function(atlas, tile) { atlas.set( tile.coord.hash, tile.data, tile.data.length / atlas.stride); }; const removeTileFromVertexAtlas = function(atlas, tile) { atlas.delete(tile.coord.hash); }; /** * Class representing a webgl tile renderer. */ class WebGLTileRenderer extends TileRenderer { /** * Instantiates a new WebGLTileRenderer object. */ constructor() { super(); this.gl = null; this[TILE_ADD] = new Map(); this[TILE_REMOVE] = new Map(); } /** * Executed when the layer is attached to a plot. * * @param {Layer} layer - The layer to attach the renderer to. * * @returns {WebGLTileRenderer} The renderer object, for chaining. */ onAdd(layer) { super.onAdd(layer); this.gl = this.layer.plot.getRenderingContext(); return this; } /** * Executed when the layer is removed from a plot. * * @param {Layer} layer - The layer to remove the renderer from. * * @returns {WebGLRenderer} The renderer object, for chaining. */ onRemove(layer) { this.gl = null; super.onRemove(layer); return this; } /** * Returns the orthographic projection matrix for the viewport. * * @returns {Float32Array} The orthographic projection matrix. */ getOrthoMatrix() { return this.layer.plot.getOrthoMatrix(); } /** * Instantiate and return a new Shader object using the renderers internal * WebGLRenderingContext. * * @param {object} source - The shader param object. * @param {string} source.common - Common glsl to be shared by both vertex and fragment shaders. * @param {string} source.vert - The vertex shader glsl. * @param {string} source.frag - The fragment shader glsl. * * @returns {Shader} The shader object. */ createShader(source) { return new Shader(this.gl, source); } /** * Creates a texture array of appropriate size for the layer pyramid using * the provided texture size. Creates and attaches the necessary event * handlers to add and remove data from the array accordingly. * * @param {object} options - The options for the texture array. * @param {number} options.chunkSize - The resolution of the tile texture. * @param {string} options.format - The texture pixel format. * @param {string} options.type - The texture pixel component type. * @param {string} options.filter - The min / mag filter used during scaling. * @param {string} options.wrap - The wrapping type over both S and T dimension. * @param {bool} options.invertY - Whether or not invert-y is enabled. * @param {bool} options.premultiplyAlpha - Whether or not alpha premultiplying is enabled. * @param {Function} options.onAdd - The function executed when a tile is added. * @param {Function} options.onRemove - The function executed when a tile is removed. * * @returns {TextureArray} The texture array object. */ createTextureArray(options = {}) { // create texture array const array = new TextureArray( this.gl, { // set texture params format: options.format, type: options.type, filter: options.filter, invertY: options.invertY, premultiplyAlpha: options.premultiplyAlpha }, { // set num chunks to be able to fit the capacity of the pyramid numChunks: this.layer.pyramid.getCapacity(), chunkSize: options.chunkSize }); // create handlers const onAdd = defaultTo(options.onAdd, addTileToTextureArray); const onRemove = defaultTo(options.onRemove, removeTileFromTextureArray); const add = event => { onAdd(array, event.tile); }; const remove = event => { onRemove(array, event.tile); }; // attach handlers this.layer.on(EventType.TILE_ADD, add); this.layer.on(EventType.TILE_REMOVE, remove); // store the handlers under the array this[TILE_ADD].set(array, add); this[TILE_REMOVE].set(array, remove); return array; } /** * Destroys a texture array object and removes all event handlers used to * add and remove data from the array. * * @param {TextureArray} array - The texture array to destroy. */ destroyTextureArray(array) { // detach handlers this.layer.removeListener(EventType.TILE_ADD, this[TILE_ADD].get(array)); this.layer.removeListener(EventType.TILE_REMOVE, this[TILE_REMOVE].get(array)); // remove handlers this[TILE_ADD].delete(array); this[TILE_REMOVE].delete(array); } /** * Creates a vertex atlas of appropriate size for the layer pyramid using * the provided attribute pointers. Creates and attaches the necessary * event handlers to add and remove data from the atlas accordingly. * * @param {object} options - The options for the vertex atlas. * @param {object} options.attributePointers - The vertex attribute pointers. * @param {number} options.chunkSize - The size of a single chunk, in vertices. * @param {Function} options.onAdd - The function executed when a tile is added. * @param {Function} options.onRemove - The function executed when a tile is removed. * * @returns {VertexAtlas} The vertex atlas object. */ createVertexAtlas(options = {}) { // create vertex atlas const atlas = new VertexAtlas( this.gl, options.attributePointers, { // set num chunks to be able to fit the capacity of the pyramid numChunks: this.layer.pyramid.getCapacity(), chunkSize: options.chunkSize }); // create handlers const onAdd = defaultTo(options.onAdd, addTileToVertexAtlas); const onRemove = defaultTo(options.onRemove, removeTileFromVertexAtlas); const add = event => { onAdd(atlas, event.tile); }; const remove = event => { onRemove(atlas, event.tile); }; // attach handlers this.layer.on(EventType.TILE_ADD, add); this.layer.on(EventType.TILE_REMOVE, remove); // store the handlers under the atlas this[TILE_ADD].set(atlas, add); this[TILE_REMOVE].set(atlas, remove); return atlas; } /** * Destroys a vertex atlas object and removes all event handlers used to add * and remove data from the atlas. * * @param {VertexAtlas} atlas - The vertex atlas to destroy. */ destroyVertexAtlas(atlas) { // detach handlers this.layer.removeListener(EventType.TILE_ADD, this[TILE_ADD].get(atlas)); this.layer.removeListener(EventType.TILE_REMOVE, this[TILE_REMOVE].get(atlas)); // remove handlers this[TILE_ADD].delete(atlas); this[TILE_REMOVE].delete(atlas); } } module.exports = WebGLTileRenderer;
true
500c6802fd7434dca89f0340671f93757d670581
JavaScript
qwop/userscript
/monolith/88/110898.user.js
UTF-8
867
2.609375
3
[]
no_license
// ==UserScript== // @name WebCT Automatic Login // @namespace http://userscripts.org/users/dstjacques // @description Automatic login for the WebCT portal // @include * // ==/UserScript== var username = ""; var password = ""; var userField = document.getElementById("webctid"); userField.value = username; var passField = document.getElementById("password"); passField.value = password; if (window.addEventListener) { window.addEventListener('load', function() { login(); }, false); } else if (window.attachEvent) { window.attachEvent('onload', login); } function login() { if(userField !== "" && passField.value !== "") { document.forms[0].submit(); } else { alert("Your login information is missing or WebCT has changed and the script needs to be updated."); } }
true
6a9ed7577f1182e5f14e33fdd57db26c10441a02
JavaScript
hangem422/vanilla-mvvm-architecture
/sample/src/moudles/component.js
UTF-8
3,685
2.890625
3
[]
no_license
const _pendding = new WeakMap(); const _penddingPreProp = new WeakMap(); class Component { #init = false; state = {}; prop = {}; constructor() { Promise.resolve().then(() => { if (this.#init) return; this.preRender(); }); } /** * @description Change the state value. * @param {{ [key: string]: any }} state State values to change */ setState(state) { const debounce = _pendding.has(this); // Check whether the previous `setState' function waiting to be reflected is executed. const nextState = debounce ? _pendding.get(this) : { ...this.state }; let needRender = false; // Reflects the changes. Object.entries(state).forEach(([key, value]) => { if (nextState[key] !== undefined && nextState[key] !== value) { nextState[key] = value; if (!needRender) needRender = true; } }); if (needRender && !debounce) { _pendding.set(this, nextState); Promise.resolve().then(() => { // Reflects the final state pending. const preState = new Map(); const preProp = _penddingPreProp.get(this); const nextState = _pendding.get(this); // Save the previous state. Object.keys(nextState).forEach((key) => { preState.set(key, this.state[key]); }); // Release the pendding and render the component. if (preProp) _penddingPreProp.delete(this); _pendding.delete(this); this.state = nextState; this.preRender(preState, preProp || new Map()); }); } } /** * @description Reflects the properties. * @param {{{ [key: string]: any }}} prop Properties to reflect */ setProp(prop) { const nextProp = {}; const preProp = new Map(); Object.entries(prop).forEach(([key, value]) => { if (this.prop[key] !== value) preProp.set(key, this.prop[key]); nextProp[key] = value; }); if (preProp.size) { // If there is any change in the property, render the component. // If there is state render waiting, suspend prop render. this.prop = nextProp; if (_pendding.has(this)) _penddingPreProp.set(this, preProp); else this.preRender(new Map(), preProp); } } /** * @description Proceed before component rendering. * @param {Map<string, any>} preState Previous State Value * @param {Map<string, any>} preProp Previous Property */ preRender(preState, preProp) { let afterRenderFunc = () => this.componentDidUpdate(preState, preProp); // If initialization is not in progress, run componentDidMount after render. if (this.#init === false) { afterRenderFunc = () => this.componentDidMount(); this.#init = true; } Promise.resolve().then(afterRenderFunc); this.render(); } /** * @description Render component. */ render() { const proto = Object.getPrototypeOf(this); const name = proto?.constructor.name ?? "Unknown"; console.warn(`${name} component did not override the render function.`); } /** * @description Called after component is first rendered. */ componentDidMount() {} /** * @description Called after component update. * @param {Map<string, any>} preState Previous State Value * @param {Map<string, any>} preProp Previous Property */ componentDidUpdate(preState, preProp) {} } /** * @description Validate that the Map has one of parma's properties. * @param {Map<string, any>} map validate target * @param {...string} props porpertie names * @returns {boolean} */ export const hasSomeProp = (map, ...props) => { return props.some((prop) => map.has(prop)); }; export default Component;
true
e643d591b9f80bdfe31f730311b49b83423a353c
JavaScript
bogdanorzea/leetcode
/src/insertIntoBST.js
UTF-8
2,679
3.875
4
[]
no_license
// https://leetcode.com/problems/rotate-list/ const assert = require('assert').strict; /** * 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) * } */ class TreeNode { constructor(val, left, right) { this.val = (val === undefined ? 0 : val); this.left = (left === undefined ? null : left); this.right = (right === undefined ? null : right); } } /** * @param {TreeNode} root * @param {number} val * @return {TreeNode} */ var insertIntoBST = function (root, val) { if (!root) { return new TreeNode(val); } if (root.val > val) { root.left = insertIntoBST(root.left, val); } else { root.right = insertIntoBST(root.right, val); } return root; }; /** * * @param {[number]} arr */ const arrayToBST = (arr) => { let root = arr[0] != null ? new TreeNode(arr[0]) : null; let parents = [root]; for (let i = 1; i < arr.length; i += 2) { let current = parents.shift(); let leftNode = arr[i] != null ? new TreeNode(arr[i]) : null; if (leftNode) { current.left = leftNode; parents.push(leftNode); } if ( i < arr.length - 1) { let rightNode = arr[i + 1] != null ? new TreeNode(arr[i + 1]) : null; if (rightNode) { current.right = rightNode; parents.push(rightNode); } } } return root; }; /** * * @param {TreeNode} root */ const BSTToArray = (root) => { let arr = []; let currentNodes = [root]; while (currentNodes.length > 0) { let currentNode = currentNodes.shift(); if (currentNode != null) { arr.push(currentNode.val); currentNodes.push(currentNode.left); currentNodes.push(currentNode.right); } else { arr.push(null); } } while (arr.length > 0 && arr[arr.length-1] == null) { arr.pop(); } return arr; }; assert.deepStrictEqual(BSTToArray(insertIntoBST(arrayToBST([]), 5)), [5]); assert.deepStrictEqual(BSTToArray(insertIntoBST(arrayToBST([7]), 5)), [7, 5]); assert.deepStrictEqual(BSTToArray(insertIntoBST(arrayToBST([4,2,7]), 5)), [4, 2, 7, null, null, 5]); assert.deepStrictEqual(BSTToArray(insertIntoBST(arrayToBST([4,1, 5, null, 3]), 2)), [4,1,5,null,3,null,null,2]); assert.deepStrictEqual(BSTToArray(insertIntoBST(arrayToBST([40,20,60,10,30,50,70]), 25)), [40,20,60,10,30,50,70,null,null,25]); console.log('DONE');
true
aa5dedcc2e5055637ed44f9ef229996e66c6df49
JavaScript
akashgujjar273/DS-Algo-In-JavaScript
/data structures/6 hash tables/2 interviewq.js
UTF-8
678
3.765625
4
[]
no_license
//on2 not effiecient function itemInCommon(arr1, arr2) { for(let i = 0; i < arr1.length; i++) { for(let j = 0; j < arr2.length; j++) { if (arr1[i] === arr2[j]) return true } } return false } let array1 = [1, 3, 5] let array2 = [2, 4, 5] itemInCommon(array1, array2) //effiecient o2n drop constant so it will be on function itemInCommon(arr1, arr2) { let obj = {} for (let i = 0; i < arr1.length; i++) { obj[arr1[i]] = true } for (let j = 0; j < arr2.length; j++) { if (obj[arr2[j]]) return true } return false } let array1 = [1, 3, 5] let array2 = [2, 5, 4] itemInCommon(array1, array2)
true
984dc85bb6f9b69160bd919bbeea3acfef0cf9aa
JavaScript
HelloMissGu/hxqymanage
/src/utils/validators.js
UTF-8
992
2.953125
3
[]
no_license
const validateNumber = ({ min = -Infinity, max = Infinity, integer = false } = {}) => (value) => { const number = Number(value); if (Number.isNaN(number)) return '请输入数字'; if (integer && number % 1 !== 0) return '请输入整数'; if (number < min) return `数字不能小于${min}`; if (number > max) return `数字不能大于${max}`; return undefined; }; const validateMobile = (value) => { if (value === '') return '请输入手机号'; if (!/^1\d{10}$/.test(value)) return '请输入中国大陆手机号'; return undefined; }; const validatePassword = (value) => { if (value === '') return '请输入密码'; if (value.length < 4) return '请输入至少4位密码'; return undefined; }; const validateLiveTitle = (value) => { if (value === '') return '请输入直播标题'; if (value.length > 12) return '直播标题不能超过12字'; return undefined; }; export { validateNumber, validateMobile, validatePassword, validateLiveTitle, };
true
2a4411fa380650401d4efb8a7bfe27317f416c1d
JavaScript
hitore/leetcode-practise
/middle/328-OddEvenLinkedList.js
UTF-8
867
3.65625
4
[]
no_license
/* 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。 2020-03-03 71 / 71 个通过测试用例 执行用时 : 136 ms, 在JavaScript提交中击败了59.00% 的用户 内存消耗 : 36.6 MB, 在JavaScript提交中击败了69.00% 的用户 */ var oddEvenList = function(head) { if (head === null) return head; let p1 = head; let list = head.next; let p2 = list; while(p1.next !== null && p2.next !== null) { p1.next = p2.next; p1 = p1.next; p2.next = p1.next; p2 = p2.next } p1.next = list; return head; };
true
af6e5ab29eef3e516ecf97a58d98d36efd77cd09
JavaScript
roark/burly-bouncer
/src/bouncer.js
UTF-8
1,778
2.765625
3
[ "MIT" ]
permissive
const Decision = require('./decision') class Bouncer { constructor () { this._rules = {} this._timeout = 5000 this._errorCallback = null } setRule (ruleName, ruleFunc) { // validate args if (typeof ruleName !== 'string') { throw new Error('rule name must be a String') } if (typeof ruleFunc !== 'function') { throw new Error('rule must be a Function') } const rule = this._rules[ruleName] // verify rule doesn't exist if (typeof rule === 'function') { throw new Error('rule already defined: ' + ruleName) } // otherwise set rule this._rules[ruleName] = ruleFunc } canUser (ruleName, args) { const rule = this._rules[ruleName] const decision = new Decision(this._timeout) if (rule === undefined || rule === null) { // rule undefined decision.deny('no rule set: ' + ruleName) } else { // rule defined try { rule(decision, args) } catch (error) { decision.deny('error interpreting rule: ' + ruleName) this._reportError(error) } } return decision.promise() } handleError (newErrorCallback) { if (typeof this._errorCallback === 'function') { throw new Error('error handling already setup') } if (typeof newErrorCallback === 'function') { this._errorCallback = newErrorCallback } else { throw new Error('error callback must be a function') } } setTimeout (timeout) { if (typeof timeout !== 'number') { throw new Error('timeout must be a number') } else { this._timeout = timeout } } _reportError (error) { if (typeof this._errorCallback === 'function') { this._errorCallback(error) } } } module.exports = Bouncer
true
ee84b00ec6f7ce13ae8b43ce7349d2cd8641a572
JavaScript
MatthewRonaldJohnson/Tech-Blog
/public/js/updatePost.js
UTF-8
1,003
3
3
[]
no_license
const postForm = document.getElementById('PostForm'); const postTitle = document.getElementById('title'); const postBody = document.getElementById('body'); postForm.addEventListener('submit', async function (e) { e.preventDefault(); if(!postTitle.value || !postBody.value){ alert("Your post must have a title and body!"); return; } //build new post in DB w/ these values and user id, then link user to Post page for that post await updatePost(buildNewPost(postTitle.value, postBody.value)) location = `/post/${postId}`; }) function buildNewPost(title, body) { const newPost = { title, body, id: postId, //postId variable defined in script tag in html }; return newPost; } async function updatePost(post) { const response = await fetch('/api/post', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(post) }) return response.json() }
true
d118880e4839b240aa48e2c177efc0396b0fc31b
JavaScript
mkgamer14/Xzero-bot-map-nieuw
/commands/review.js
UTF-8
1,679
3.328125
3
[]
no_license
const discord = require("discord.js"); module.exports.run = async (bot, message, args) => { // Aantal sterren opvragen. const aantalSterren = args[0]; // Nakijken als men een getal meegeeft, of als men een getal tussen 1 en 5 opgeeft. if (!aantalSterren || aantalSterren < 1 || aantalSterren > 5) return message.channel.send("Geef een aantal sterren op! Kies tussen 1 en 5."); // Nakijken als je een bericht hebt meegegeven. const bericht = args.splice(1, args.length).join(' ') || '**Geen bericht meegegeven**'; // Kanaal waar reviews inkomen opzoeken. var reviewChannel = message.guild.channels.find('name', 'review'); // als kanaal niet is gevonden geef een bericht. if (!reviewChannel) return message.channel.send("Kanaal niet gevonden"); var sterren = ""; // Voor ieder aantal sterren gaan we deze tekst aanmaken. for (var i = 0; i < aantalSterren; i++) { sterren += ":star: "; } // Verwijder het bestaande bericht. message.delete(); // Maak de review aan met het aantal sterren en het berichtje. const review = new discord.RichEmbed() .setTitle(`${message.author.username} heeft een review geschreven! :tada:`) .setColor("#00ff00") .addField("Sterren:", `${sterren}`) .addField("Review:", `${bericht}`); // Zend bericht naar de gebruiker dat hij een review heeft aangemaakt. message.channel.send(":white_check_mark: Je hebt succesvol een review geschreven!"); // Zend het bericht in het review kanaal. return reviewChannel.send(review); } module.exports.help = { name: "review", description: "review command." }
true
9d90cbf68d9b6abcd3d2bac67812dd1dec01d44e
JavaScript
CodeHiti/user-list-and-task-tracker
/exercise-1/js/app.js
UTF-8
1,267
2.734375
3
[]
no_license
var userDataApiUrl = 'https://5dc588200bbd050014fb8ae1.mockapi.io/assessment'; fetch(userDataApiUrl).then((response) => { return response.json(); }).then((userData) => { getUsers(userData); }); var source = $("#template").html(); var template = Handlebars.compile(source); function getUsers(users) { for (var i = 0; i < users.length; i++) { var user = users[i]; var userDetails = { id: user["id"], createdAt: String(user["createdAt"]).split('.')[0].split('T')[0] + ' ' + String(user["createdAt"]).split('.')[0].split('T')[1], name: user["name"], avatar: user["avatar"] } var userTemplate = template(userDetails) $('.user-page').append(userTemplate); } } revealDetails = (userId) => { var userSpotted = document.getElementById(`item-id-${userId}`); var detailsButton = document.getElementById(`button-${userId}`); var nameFocussed = document.getElementById(`name-${userId}`); userSpotted.style.display = userSpotted.style.display === 'none' ? '' : 'none'; detailsButton.style.display = detailsButton.style.display === '' ? 'none' : ''; nameFocussed.style.textDecoration = nameFocussed.style.display === 'underline' ? '' : 'underline'; }
true
42e075a4699fa45ce2bdf4cff0efe80ffd85306f
JavaScript
Creatorpravin/JavaScriptGrammar
/Chapter2/console_dir.js
UTF-8
71
2.515625
3
[]
no_license
let x = { property: 1, prop1: 2, method: function(){}}; console.dir(x);
true
b793ecd718823fd87c2f5f6c4b0f2813b5dc18c3
JavaScript
bjorger/webwiz
/src/donutChart.js
UTF-8
5,982
2.90625
3
[]
no_license
import * as d3 from 'd3'; import { generation_colors } from './types'; /** * @typedef {Object} Pokemon * @property {String} name * @property {Number} type_1 * @property {Number} type_2 * @property {Number} total * @property {Number} generation * @property {Number} legendary */ var old_data = []; /** * @param {Pokemon[]} data */ export const drawDonutChart = (data, setGen, gen, primaryType) => { const update = (data) => { d3.select('#pieChart').selectAll('svg').remove(); const gen1 = data.filter((pokemon) => pokemon.generation === 0); const gen2 = data.filter((pokemon) => pokemon.generation === 1); const gen3 = data.filter((pokemon) => pokemon.generation === 2); const gen4 = data.filter((pokemon) => pokemon.generation === 3); const gen5 = data.filter((pokemon) => pokemon.generation === 4); const gen6 = data.filter((pokemon) => pokemon.generation === 5); let generations = { 'Gen 1': gen1.length, 'Gen 2': gen2.length, 'Gen 3': gen3.length, 'Gen 4': gen4.length, 'Gen 5': gen5.length, 'Gen 6': gen6.length, }; Object.keys(generations).forEach((key) => { if (generations[key] === 0) { delete generations[key]; } }); var width = 400; var height = 300; var margin = 40; // The radius of the pieplot is half the width or half the height (smallest one). I subtract a bit of margin. var radius = 400 / 2 - margin; var svg = d3 .select('#pieChart') .append('svg') .attr('width', width) .attr('height', height) .append('g') .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')'); // set the color scale var color = d3.scaleOrdinal().domain(generations).range(generation_colors); // Compute the position of each group on the pie: var pie = d3 .pie() .value(function (d) { return d.value; }) .sort(null); var data_ready = pie(d3.entries(generations)); // Now I know that group A goes from 0 degrees to x degrees and so on. // shape helper to build arcs: var arc = d3 .arc() .innerRadius(radius * 0.4) .outerRadius(radius * 0.8); var outerArc = d3 .arc() .innerRadius(radius * 0.9) .outerRadius(radius * 0.9); var arcOver = d3 .arc() .innerRadius(radius * 0.4) .outerRadius(radius * 0.85); // Add the polylines between chart and labels: svg.selectAll('allPolylines') .data(data_ready) .enter() .append('polyline') .attr('stroke', (d, index) => generation_colors[index]) .style('opacity', 1) .style('fill', 'none') .attr('stroke-width', 1) .attr('points', function (d) { var posA = arc.centroid(d); // line insertion in the slice var posB = outerArc.centroid(d); // line break: we use the other arc generator that has been built only for that var posC = outerArc.centroid(d); // Label position = almost the same as posB var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2; // we need the angle to see if the X position will be at the extreme right or extreme left posC[0] = radius * 0.95 * (midangle < Math.PI ? 1 : -1); // multiply by 1 or -1 to put it on the right or on the left return [posA, posB, posC]; }); // Build the pie chart: Basically, each part of the pie is a path that we build using the arc function. svg.selectAll('mySlices') .data(data_ready) .enter() .append('path') .attr('class', 'donutArc') .attr('fill', function (d) { return color(d.data.key); }) .on('click', (d) => { let currentGen = +d.data.key.replace(/^\D+/g, '') - 1; // -1 because we take the string values -> Gen 1 is 0 etc.. if (gen === currentGen) { setGen(undefined); } else { setGen(currentGen); } }) .transition() .delay(function (d, i) { return i; }) .duration(800) .attrTween('d', function (d, index) { var i = d3.interpolate(d.startAngle + 0.1, d.endAngle); return function (t) { d.endAngle = i(t); if (gen !== undefined) { if (gen === index) { return arcOver(d); } } return arc(d); }; }) .style('opacity', 1) .on('end', function (d, i) { d3.select(this).on('mouseover', function (d) { d3.select(this).transition().duration(800).attr('d', arcOver); }); d3.select(this).on('mouseleave', function (d) { if (gen !== d.index) { d3.select(this).transition().duration(800).attr('d', arc); } }); }); // Now add the annotation. Use the centroid method to get the best coordinates svg.selectAll('mySlices') .data(data_ready) .enter() .append('text') .text(function (d) { return d.data.value; }) .attr('transform', function (d) { return 'translate(' + arc.centroid(d) + ')'; }) .on('click', (d) => { let currentGen = +d.data.key.replace(/^\D+/g, '') - 1; // -1 because we take the string values -> Gen 1 is 0 etc.. if (gen === currentGen) { setGen(undefined); } else { setGen(currentGen); } return; }) .style('text-anchor', 'middle') .style('font-size', 17) .style('font-weight', 'bold') .attr('fill', 'white'); svg.selectAll('allLabels') .data(data_ready) .enter() .append('text') .text((d) => d.data.key) .attr('transform', function (d) { var pos = outerArc.centroid(d); var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2; pos[0] = radius * 0.99 * (midangle < Math.PI ? 1 : -1); return 'translate(' + pos + ')'; }) .style('text-anchor', function (d) { var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2; return midangle < Math.PI ? 'start' : 'end'; }) .attr('font-weight', 'bold') .attr('fill', 'white'); }; if (primaryType !== undefined) { var new_data = data.filter((Pokemon) => Pokemon.type_1 === primaryType); if (new_data.length !== data.length) { update(new_data); } } else { if (data.length !== old_data.length || primaryType === undefined) { update(data); } old_data = data; } };
true
745814f174044ec0cffba2c7c658810745624b85
JavaScript
ourarash/isometric_cubes
/sketch.js
UTF-8
3,535
2.875
3
[]
no_license
// By Arash Saifhashemi /// <reference path="../node_modules/@types/p5/global.d.ts" /> let leftTopX = 0; let leftTopY = 0; let w = 1; let precision = 10; let maxPrecision = 20; let minPrecision = 3; let step = 1; let time = 0; let smallAxisSize = 80; let bigAxisSize = 250; function setup() { leftTopX = 0; leftTopY = 0; createCanvas(windowWidth, windowHeight); angleMode(DEGREES); } function draw() { clear(); stroke(255, 255, 0); background(51); strokeWeight(w); // Default push(); translate(windowWidth / 2, windowHeight / 2); // rotate(time); drawFour(bigAxisSize, smallAxisSize); pop(); push(); translate(windowWidth / 2, windowHeight / 2); // rotate(45); rotate(time); drawFour(bigAxisSize, smallAxisSize); pop(); time++; if (time % 10 == 0) { precision += step; if (precision > maxPrecision || precision < minPrecision) { step = -step; } } } function drawFour(bigAxisSize, smallAxisSize) { drawXY(0, bigAxisSize, smallAxisSize); scale(-1, 1); drawXY(0, bigAxisSize, smallAxisSize); scale(1, -1); drawXY(0, bigAxisSize, smallAxisSize); scale(-1, 1); drawXY(0, bigAxisSize, smallAxisSize); } function drawXY(angle, bigAxisSize, smallAxisSize) { // The diagonal lines line( 0, -bigAxisSize, bigAxisSize * Math.sin(Math.PI / 4), -bigAxisSize * Math.cos(Math.PI / 4) ); line( bigAxisSize * Math.sin(Math.PI / 4), -bigAxisSize * Math.cos(Math.PI / 4), bigAxisSize, 0 ); line(leftTopX, leftTopY, leftTopX, leftTopY - bigAxisSize); line(leftTopX, leftTopY, leftTopX + bigAxisSize, leftTopY); let startX = leftTopX; let startY = leftTopY - bigAxisSize; let endX = leftTopX + bigAxisSize / precision; let endY = leftTopY; for (let i = 0; i < precision; i++) { line(startX, startY, endX, endY); startY += bigAxisSize / precision; endX += bigAxisSize / precision; } // On the top ({ startX, startY, endX, endY } = DrawTopAndTopMirror( bigAxisSize, smallAxisSize, startX, startY, endX, endY )); push(); rotate(90); // to the right ({ startX, startY, endX, endY } = DrawTopAndTopMirror( bigAxisSize, smallAxisSize, startX, startY, endX, endY )); pop(); } function DrawTopAndTopMirror( bigAxisSize, smallAxisSize, startX, startY, endX, endY ) { push(); stroke(255, 0, 0); line( leftTopX, leftTopY - bigAxisSize - smallAxisSize, leftTopX, leftTopY - bigAxisSize - 2 * smallAxisSize ); line( leftTopX, leftTopY - bigAxisSize - smallAxisSize, leftTopX + smallAxisSize, leftTopY - bigAxisSize - smallAxisSize ); startX = leftTopX; startY = leftTopY - bigAxisSize - 2 * smallAxisSize; endX = leftTopX + smallAxisSize / precision; endY = leftTopY - bigAxisSize - smallAxisSize; for (let i = 0; i < precision; i++) { line(startX, startY, endX, endY); startY += smallAxisSize / precision; endX += smallAxisSize / precision; } // top mirror line( leftTopX, leftTopY - bigAxisSize - smallAxisSize, leftTopX, leftTopY - bigAxisSize ); startX = leftTopX + smallAxisSize; startY = leftTopY - bigAxisSize - smallAxisSize; endX = leftTopX; endY = leftTopY - bigAxisSize - smallAxisSize + smallAxisSize / precision; for (let i = 0; i < precision; i++) { line(startX, startY, endX, endY); endY += smallAxisSize / precision; startX -= smallAxisSize / precision; } pop(); return { startX, startY, endX, endY }; }
true
b93678136674dbbe43d3d700d31a4c1565b5d987
JavaScript
lvletan/lab2_files
/files/js/functions.js
UTF-8
2,105
3.171875
3
[]
no_license
let value="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." let main_selector="main" let small_selector="right" function createCard(){ var start = document.createElement("DIV"); var img_wrapper= document.createElement("DIV"); img_wrapper.className="card-image" var img = document.createElement("IMG"); //random select image var imageID = Math.floor(Math.random() * 4+1); img.src="images/image"+imageID+".png" img_wrapper.appendChild(img) var text_wrapper = document.createElement("DIV") text_wrapper.className="card-text" //random genereate text length var text_repeat= Math.floor(Math.random() * 4) var text=document.createTextNode(value.repeat(text_repeat)) text_wrapper.appendChild(text) start.appendChild(img_wrapper) start.appendChild(text_wrapper) return start; } function removeCard(cards){ if(cards.length>0){ var index= Math.floor(Math.random() * cards.length) cards[index].parentNode.removeChild(cards[index]) } } function addRandom1(){ var card = createCard() card.className="card" document.getElementById(main_selector).appendChild(card) } function removeRandom1(){ var select = document.getElementById(main_selector) var cards = select.querySelectorAll('.card') //randomly select item to remove removeCard(cards) } function addRandom2(){ var card = createCard() card.className="small-card" document.getElementById(small_selector).appendChild(card) } function removeRandom2(){ var select = document.getElementById(small_selector) var cards = select.querySelectorAll('.small-card') //randomly select item to remove removeCard(cards) }
true
95cbaae3d6fcfd3a9a048f7933ad61c10308fffd
JavaScript
jzepedaa/friendFinder
/app/routing/apiRoutes.js
UTF-8
1,113
2.828125
3
[]
no_license
var friends = require('../data/friends.js'); module.exports = function (app) { app.get('/api/friends', function (req, res) { res.json(friends); }); app.post('/api/friends', function (req, res) { var match = { name: "", photo: "", friendDifference: 1000 }; var data = req.body; var scores = data.scores; var name = data.name; var photo = data.photo; var differenceAmount = 0; for (var i = 0; i < friends.length - 1; i++) { console.log(friends[i].name); differenceAmount = 0; for (var j = 0; j < 10; j++) { differenceAmount += Math.abs(parseInt(scores[j]) - parseInt(friends[i].scores[j])); if (differenceAmount <= match.friendDifference) { match.name = friends[i].name; match.photo = friends[i].photo; match.friendDifference = differenceAmount; } } } friends.push(data); res.json(match); }); };
true
09b8c5b4a35e99bb4c139cb92d42ba1932dc61bf
JavaScript
swimhiking/GeoExtApp
/packages/remote/GeoExt/src/mixin/SymbolCheck.js
UTF-8
8,134
2.96875
3
[]
no_license
/* Copyright (c) 2015-2016 The Open Source Geospatial Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * A utility class providing methods to check for symbols of OpenLayers we * depend upon. * * This class can be mixed into classes to check if the dependencies to external * symbols are fulfilled. An example: * * Ext.define('MyNewClass.DependingOnOpenLayersClasses', { * mixins: ['GeoExt.mixin.SymbolCheck'], * // the contents of the `symbols` property will be checked * symbols: [ * 'ol.Map', // checking a class * 'ol.View.prototype.constrainResolution', // an instance method * 'ol.control.ScaleLine#getUnits', // other way for instance method * 'ol.color.asArray', // one way to reference a static method * 'ol.color::asString' // other way to reference a static method * ] * // … your configuration and methods … * }); * * Since this sort of checking usually only makes sense in debug mode, you can * additionally wrap the `symbols`-configuration in these &lt;debug&gt;-line * comments: * * Ext.define('MyNewClass.DependingOnOpenLayersClasses', { * mixins: ['GeoExt.mixin.SymbolCheck'], * // <debug> * symbols: [] * // </debug> * }); * * This means that the array of symbols is not defined in production builds * as the wrapped lines are simply removed from the final JavaScript. * * If one of the symbols cannot be found, a warning will be printed to the * developer console (via `Ext.log.warn`, which will only print in a debug * build): * * [W] The class "MyNewClass.DependingOnOpenLayersClasses" depends on the * external symbol "ol.color.notExisting", which does not seem to exist. * * @class GeoExt.mixin.SymbolCheck */ Ext.define('GeoExt.mixin.SymbolCheck', { extend: 'Ext.Mixin', statics: { /** * An object that we will use to store already looked up references in. * * The key will be a symbol (after it has been normalized by the * method #normalizeSymbol), and the value will be a boolean indicating * if the symbol was found to be defined when it was checked. * * @private */ _checked: { // will be filled while we are checking stuff for existance }, /** * Checks whether the required symbols of the given class are defined * in the global context. Will log to the console if a symbol cannot be * found. * * @param {Ext.Base} cls An ext class defining a property `symbols` that * that this method will check. */ check: function(cls) { // <debug> var staticMe = this; var proto = cls.prototype; var olSymbols = proto && proto.symbols; var clsName = proto && proto['$className']; if (!olSymbols) { return; } Ext.each(olSymbols, function(olSymbol) { olSymbol = staticMe.normalizeSymbol(olSymbol); staticMe.checkSymbol(olSymbol, clsName); }); // </debug> }, /** * Normalizes a short form of a symbol to a canonical one we use to * store the results of the #isDefinedSymbol method. The following two * normalizations take place: * * * A `#` in the symbol is being replaced with `.prototype.` so that * e.g. the symbol `'ol.Class#methodName'` turns into the symbol * `'ol.Class.prototype.methodName'` * * A `::` in the symbol is being replaced with `.` so that * e.g. the symbol `'ol.Class::staticMethodName'` turns into the * symbol `'ol.Class.staticMethodName'` * * @param {String} symbolStr A string to normalize. * @return {String} The normalized string. * @private */ normalizeSymbol: (function() { // <debug> var hashRegEx = /#/; var colonRegEx = /::/; // </debug> var normalizeFunction = function(symbolStr){ // <debug> if (hashRegEx.test(symbolStr)) { symbolStr = symbolStr.replace(hashRegEx, '.prototype.'); } else if (colonRegEx.test(symbolStr)) { symbolStr = symbolStr.replace(colonRegEx, '.'); } return symbolStr; // </debug> }; return normalizeFunction; }()), /** * Checks the passed symbolStr and raises a warning if it cannot be * found. * * @param {String} symbolStr A string to check. Usually this string has * been {@link #normalizeSymbol normalized} already. * @param {String} [clsName] The optional name of the class that * requires the passed openlayers symbol. * @private */ checkSymbol: function(symbolStr, clsName){ // <debug> var isDefined = this.isDefinedSymbol(symbolStr); if (!isDefined) { Ext.log.warn( 'The class "' + (clsName || 'unknown') + '" ' + 'depends on the external symbol "' + symbolStr + '", ' + 'which does not seem to exist.' ); } // </debug> }, /** * Checks if the passed symbolStr is defined. * * @param {String} symbolStr A string to check. Usually this string has * been {@link #normalizeSymbol normalized} already. * @return {Boolean} Whether the symbol is defined or not. * @private */ isDefinedSymbol: function(symbolStr){ // <debug> var checkedCache = this._checked; if (Ext.isDefined(checkedCache[symbolStr])) { return checkedCache[symbolStr]; } var parts = symbolStr.split('.'); var lastIdx = parts.length - 1; var curSymbol = Ext.getWin().dom; var isDefined = false; var intermediateSymb = ''; Ext.each(parts, function(part, idx){ if (intermediateSymb !== '') { intermediateSymb += '.'; } intermediateSymb += part; if(curSymbol[part]) { checkedCache[intermediateSymb] = true; curSymbol = curSymbol[part]; if (lastIdx === idx) { isDefined = true; } } else { checkedCache[intermediateSymb] = false; return false; // break early } }); checkedCache[symbolStr] = isDefined; return isDefined; // </debug> } }, /** * @property {String[]} symbols The symbols to check. */ /** * Whenever a class mixes in GeoExt.mixin.SymbolCheck, this method will be * called and it actually runs the checks for all the defined #symbols. * * @param {Ext.Class} cls The class that this mixin is mixed into. * @private */ onClassMixedIn: function(cls) { // <debug> GeoExt.mixin.SymbolCheck.check(cls); // </debug> } });
true
bd02aa69eaaf83f96a1ffeb1a5640eed206af75f
JavaScript
CamdenKo/functionalJSSorting
/test.js
UTF-8
902
2.96875
3
[]
no_license
const sortingMethods = require('./sorting') const generateTest = (method) => { describe(method.name, () => { it('works for empty set', () => { expect(method([])).toEqual([]) }) it('works for a single element', () => { const toTest = [1] expect(method(toTest)).toEqual(toTest) }) it('works for a simple 2 element arr', () => { const toTest = [2, 1] expect(method(toTest)).toEqual([1, 2]) }) it('works for a complex arr', () => { const toTest = [5, 6, 9, 1, 0, 1, 0, 5, 6] expect(method(toTest)).toEqual([0, 0, 1, 1, 5, 5, 6, 6, 9]) }) it('works for strings', () => { const toTest = ['a', 'z', 'e', 's'] expect(method(toTest)).toEqual(['a', 'e', 's', 'z']) }) }) } const generateTests = () => Object.values(sortingMethods) .forEach((method) => { generateTest(method) }) generateTests()
true
a5735a5f498e410a9f8f77804b788a9bcd172de0
JavaScript
laxmikantm/LaxmiProtractorExcercise
/crud_spec.js
UTF-8
2,792
2.703125
3
[]
no_license
describe('CRUD Operations-Laxmi', function() { var homepageUrl= 'http://computer-database.herokuapp.com/computers'; var addNewCompBtn = element(by.id('add')); var d = new Date(); var testRecordName = '1234Laxmi'; var newRecordName= testRecordName+d.getMinutes()+d.getSeconds(); var computerName = element(by.id('name')); var introducedDate = element(by.id('introduced')); var disContinuedDate = element(by.id('discontinued')); var company = element(by.cssContainingText('option', 'RCA')); var companyAmendment = element(by.cssContainingText('option', 'MOS Technology')); var saveBtn = $('.btn.primary'); var doneText = $('.alert-message.warning'); var homepageLink = $('a[href="/"]'); var searchBox = element(by.id('searchbox')); var filterByName = element(by.id('searchsubmit')); var resultTableCell1= element(by.xpath('//table[contains(@class,"computers zebra-striped")]/tbody/tr/td[1]/a')); var resultTableCell4= element(by.xpath('//table[contains(@class,"computers zebra-striped")]/tbody/tr/td[4]')); var deleteBtn = $('.btn.danger[type=submit]'); beforeAll(function() { browser.ignoreSynchronization = true; browser.get(homepageUrl); }); afterAll(function() { browser.ignoreSynchronization = false; }); it('should have correct homepage title', function() { 'use strict;' expect(browser.getTitle()).toContain('Computers database'); }); //Create & verify it('should be able to add new record', function() { browser.get(homepageUrl); addNewCompBtn.click(); computerName.sendKeys(newRecordName); introducedDate.sendKeys('2017-01-01'); disContinuedDate.sendKeys('2017-12-30'); company.click(); saveBtn.click(); expect(doneText.getText()).toContain(testRecordName); }); //Search it('should be able to search the newly added record', function() { homepageLink.click(); // or We can use browser.get(homepageUrl); searchBox.sendKeys(newRecordName); filterByName.click(); expect(resultTableCell1.getText()).toContain(newRecordName); }); //Update it('should be able to amend the record', function() { homepageLink.click(); // or We can use browser.get(homepageUrl); searchBox.sendKeys(newRecordName); filterByName.click(); resultTableCell1.click(); companyAmendment.click(); saveBtn.click(); searchBox.sendKeys(newRecordName); filterByName.click(); expect(resultTableCell4.getText()).toContain('MOS Technology'); }); //Delete it('should be able to delete the record', function() { homepageLink.click(); // or We can use browser.get(homepageUrl); searchBox.sendKeys(newRecordName); filterByName.click(); resultTableCell1.click(); deleteBtn.click(); expect(doneText.getText()).toContain('Computer has been deleted'); }); });
true
037a260b69ad0b7bf267cd1b2b1c47b8670825fd
JavaScript
sschand/basic_mean_demo
/server/config/routes.js
UTF-8
934
2.96875
3
[]
no_license
// This is our routes.js file located in server/config/routes.js // This is where we will define all of our routing rules! // We will have to require this in the server.js file (and pass it app!) // First, at the top of your routes.js file you'll have to require the controllers var friends = require('./../controllers/friends.js'); module.exports = function(app) { // verb: get, plural of targe as the URI is the RESTful index method (it returns all friends) app.get('/friends', function(req, res) { // res.json([{name: "Andrew", age: 24}, {name: "Michael", age: 34}]) // delegate to the controller and pass along the req and res // CALL BACKEND CONTROLLER METHOD friends.index(req, res); }); app.post('/friends', function(req, res) { friends.addFriend(req, res); }); app.delete('/delete/:id', function(req, res) { friends.deleteFriend(req, res); }); };
true
824a9a7b44aba53827c44d08b3137a28a4c7d36e
JavaScript
flokiowl/test-tiny
/src/js/main.js
UTF-8
7,111
2.75
3
[]
no_license
'use strict'; // language and currency lists var item1 = [ document.querySelector('.header-top__item.en'), document.querySelector('.header-top__link.en') ]; var item2 = [ document.querySelector('.header-top__item.fr'), document.querySelector('.header-top__link.fr') ]; var item3 = [ document.querySelector('.header-top__item.gm'), document.querySelector('.header-top__link.gm') ]; var item4 = [ document.querySelector('.header-top__item.dollar'), document.querySelector('.header-top__link.dollar') ]; var item5 = [ document.querySelector('.header-top__item.euro'), document.querySelector('.header-top__link.euro') ]; var item6 = [ document.querySelector('.header-top__item.pound'), document.querySelector('.header-top__link.pound') ]; item1[1].addEventListener('click', function() { item1[0].classList.add('active'); if (item1[0].classList.contains('active')) { item2[0].classList.remove('active'); item3[0].classList.remove('active'); } }) item2[1].addEventListener('click', function() { item2[0].classList.add('active'); if (item2[0].classList.contains('active')) { item1[0].classList.remove('active'); item3[0].classList.remove('active'); } }) item3[1].addEventListener('click', function() { item3[0].classList.add('active'); if (item3[0].classList.contains('active')) { item1[0].classList.remove('active'); item2[0].classList.remove('active'); } }) item4[1].addEventListener('click', function() { item4[0].classList.add('active'); if (item4[0].classList.contains('active')) { item5[0].classList.remove('active'); item6[0].classList.remove('active'); } }) item5[1].addEventListener('click', function() { item5[0].classList.add('active'); if (item5[0].classList.contains('active')) { item4[0].classList.remove('active'); item6[0].classList.remove('active'); } }) item6[1].addEventListener('click', function() { item6[0].classList.add('active'); if (item6[0].classList.contains('active')) { item4[0].classList.remove('active'); item5[0].classList.remove('active'); } }) //burger (mobile main-nav) var burgerBtn = document.querySelector('.main-nav__burger'); var menuList = document.querySelector('.main-nav__list'); burgerBtn.addEventListener('click', function() { menuList.classList.toggle('main-nav__list--open'); }) //slider //slider dots var sliderWrap = document.querySelector('.slider__wrapper'); var prev = document.querySelector('.slider__control_left'); var next = document.querySelector('.slider__control_right'); var button1 = document.querySelector('.slider__dot--first'); var button2 = document.querySelector('.slider__dot--second'); var button3 = document.querySelector('.slider__dot--third'); button1.addEventListener('click', function() { sliderWrap.style.transform = 'translateX(0%)'; button1.classList.add('dot-active'); button2.classList.remove('dot-active'); button3.classList.remove('dot-active'); }) button2.addEventListener('click', function() { sliderWrap.style.transform = 'translateX(-100%)'; button2.classList.add('dot-active'); button1.classList.remove('dot-active'); button3.classList.remove('dot-active'); }) button3.addEventListener('click', function() { sliderWrap.style.transform = 'translateX(-200%)'; button3.classList.add('dot-active'); button1.classList.remove('dot-active'); button2.classList.remove('dot-active'); }) //slider prev/next var multiItemSlider = (function () { return function (selector, config) { var _mainElement = document.querySelector(selector), // основный элемент блока _sliderWrapper = _mainElement.querySelector('.slider__wrapper'), // обертка для .slider-item _sliderItems = _mainElement.querySelectorAll('.slider__item'), // элементы (.slider-item) _sliderControls = _mainElement.querySelectorAll('.slider__control'), // элементы управления _sliderControlLeft = _mainElement.querySelector('.slider__control_left'), // кнопка "LEFT" _sliderControlRight = _mainElement.querySelector('.slider__control_right'), // кнопка "RIGHT" _wrapperWidth = parseFloat(getComputedStyle(_sliderWrapper).width), // ширина обёртки _itemWidth = parseFloat(getComputedStyle(_sliderItems[0]).width), // ширина одного элемента _positionLeftItem = 0, // позиция левого активного элемента _transform = 0, // значение транфсофрмации .slider_wrapper _step = _itemWidth / _wrapperWidth * 100, // величина шага (для трансформации) _items = []; // массив элементов // наполнение массива _items _sliderItems.forEach(function (item, index) { _items.push({ item: item, position: index, transform: 0 }); }); var position = { getMin: 0, getMax: _items.length - 1, } var _transformItem = function (direction) { if (direction === 'right') { if ((_positionLeftItem + _wrapperWidth / _itemWidth - 1) >= position.getMax) { return; } if (!_sliderControlLeft.classList.contains('slider__control_show')) { _sliderControlLeft.classList.add('slider__control_show'); } if (_sliderControlRight.classList.contains('slider__control_show') && (_positionLeftItem + _wrapperWidth / _itemWidth) >= position.getMax) { _sliderControlRight.classList.remove('slider__control_show'); } _positionLeftItem++; _transform -= _step; } if (direction === 'left') { if (_positionLeftItem <= position.getMin) { return; } if (!_sliderControlRight.classList.contains('slider__control_show')) { _sliderControlRight.classList.add('slider__control_show'); } if (_sliderControlLeft.classList.contains('slider__control_show') && _positionLeftItem - 1 <= position.getMin) { _sliderControlLeft.classList.remove('slider__control_show'); } _positionLeftItem--; _transform += _step; } _sliderWrapper.style.transform = 'translateX(' + _transform + '%)'; } // обработчик события click для кнопок "назад" и "вперед" var _controlClick = function (e) { var direction = this.classList.contains('slider__control_right') ? 'right' : 'left'; e.preventDefault(); _transformItem(direction); }; var _setUpListeners = function () { // добавление к кнопкам "назад" и "вперед" обрботчика _controlClick для событя click _sliderControls.forEach(function (item) { item.addEventListener('click', _controlClick); }); } // инициализация _setUpListeners(); return { right: function () { // метод right _transformItem('right'); }, left: function () { // метод left _transformItem('left'); } } } }()); var slider = multiItemSlider('.slider')
true
ea46cfa8521eb5677c0e9c48d24759a841a08f28
JavaScript
Nanogami/Hockey
/js/script.js
UTF-8
2,017
3.515625
4
[]
no_license
let ball let p1 let p2 function setup() { createCanvas(windowWidth, windowHeight); p1 = new Paddle(1,color('gray')) p2 = new Paddle(2,color('gray')) ball = new Ball() } function draw(){ background('white') drawLine() ball.draw() ball.move() p1.draw() p2.draw() let checkScore = ball.checkScore() if(ball.collision(p1) || ball.collision(p2)){ ball.move() } if (checkScore === 2){ p2.updateScore() } else if(checkScore === 1){ p1.updateScore() } if (keyIsPressed) { if(keyIsDown(87)){ p1.move(-1) } if(keyIsDown(83)){ p1.move(1) } if(keyIsDown(68)){ p1.move2(1) } if(keyIsDown(65)){ p1.move2(-1) } if(keyIsDown(UP_ARROW)){ p2.move(-1) } if(keyIsDown(DOWN_ARROW)){ p2.move(1) } if(keyIsDown(LEFT_ARROW)){ p2.move3(-1) } if(keyIsDown(RIGHT_ARROW)){ p2.move3(1) } } showScore() } const drawLine = function(){ strokeWeight(4) stroke('blue') line(width / 4 + 100, 0,width / 4 + 100,height) stroke('red') line(width / 2, 0, width / 2,height) stroke('blue') line((width / 2 + (width / 4)) - 100, 0,(width / 2 + (width / 4) - 100),height) //porteria izquierda fill('#87CEEB') stroke('red') ellipse(0, height / 2, 400, 400) line(0,((height / 2)-70),20,((height / 2)-70)) line(0,((height / 2)+70),20,((height / 2)+70)) //porteria derecha fill('#87CEEB') stroke('red') ellipse(width, height / 2, 400, 400) line((width-20),((height / 2)-70),width,((height / 2)-70)) line((width-20),((height / 2)+70),width,((height / 2)+70)) //circulo de el medio fill('#214588') stroke('#87CEEB') ellipse(width / 2, height / 2, 80, 80) //puntos rojos fill('red') noStroke() ellipse(width / 2 - 200, height / 2 - 200, 20, 20) ellipse(width / 2 + 200, height / 2 - 200, 20, 20) ellipse(width / 2 - 200, height / 2 + 200, 20, 20) ellipse(width / 2 + 200, height / 2 + 200, 20, 20) } const showScore = function(){ fill('black') textSize(50) text(p1.getScore(), width/2 -300, 70) text(p2.getScore(), width/2 +275, 70) }
true
7a7c21869cf5d523fd82e059a5c49cb53bdd9639
JavaScript
anqing-xian/bird
/script/Sky.js
UTF-8
435
2.78125
3
[ "MIT" ]
permissive
const skyDom = document.getElementsByClassName('sky')[0]; const skyStyles = getComputedStyle(skyDom);//获取到天空的样式 const skyWidth = parseFloat(skyStyles.width); const skyHeight = parseFloat(skyStyles.height) class Sky extends Rectangle { constructor () { super(skyWidth, skyHeight, 0, 0, -50, 0, skyDom); } onMove() { if(this.left <= -skyWidth /2) { this.left = 0; } } }
true
2f5375deb2da601d60455ba52d2e8e078494b0b2
JavaScript
romacardozx/DogsWorld
/api/src/controllers/Dogs.js
UTF-8
4,625
2.625
3
[]
no_license
const {Breed, Temperament} = require ("../db") const axios = require('axios'); const { Op } = require("sequelize"); const { API_KEY } = process.env; require('dotenv').config(); //const {v4: uuidv4 } = require('uuid') /*async function llamadoApiRazas(){ try { let response = await axios.get(`https://api.thedogapi.com/v1/breeds?api_key=${API_KEY}`) let apibreeds = response.data.map(breed => { return { //id = breed.id, name: breed.name , weight: breed.weight.metric, height: breed.height.metric, life_span: breed.life_span, image: breed.image.url, Temperament:breed.temperament && breed.temperament.split(', ') }}); return apibreeds }catch{err => console.error(err)}; } async function getAllDogs (req, res, next) { let {name} = req.query; try { let apibreeds = await llamadoApiRazas() //?ncludi Trying to get breed by name (if provided by query) ing temperament if (name) { const filteredbd = await Breed.findAll({ include: {model:Temperament, through:{attributes:[]}}, where: { name: { [Op.iLike]: `%${name}%` } }, }) let filteredapi = apibreeds.filter((e) => e.name.tolowercase().includes(name.tolowercase())) res.json([...filteredbd, ...filteredapi]) } //? If name is not provided send all breeds else { let bdbreeds = await Breed.findAll({ include: {model: Temperament, through: {attributes: []}}}) res.json([...bdbreeds, ...apibreeds]) } } catch (err) { next(err) } }*/ async function llamadoApiRazas(){ //? Importo razas de la api y los guardo en la BD //? IMPORTING BREEDS FROM API AND SAVING TO DB try { await axios.get('https://api.thedogapi.com/v1/breeds') .then(response => response.data) .then(json => { json.forEach(async breed => { var [bree, _created] = await Breed.findOrCreate({ where: {name: breed.name || 'Could not import name',}, defaults: { weight: breed.weight.metric || 'Could not import weight', height: breed.height.metric || 'Could not import height', life_span: breed.life_span || 'Could not import life span', image: breed.image.url || 'Could not import image', }}) let breedTemp = breed.temperament && breed.temperament.split(', '); breedTemp?.forEach(breetem => { Temperament.findOne({ where: {name: breetem} }) .then(tem => {bree.addTemperament(tem?.dataValues.id)}) }) } ) }) .then(console.log('Breeds (re)imported to DB')) .catch(err => console.error(err)); } catch{err => console.error(err)}; } async function getAllDogs (req, res, next) { const { name } = req.query try { await llamadoApiRazas() //?ncludi Trying to get breed by name (if provided by query) ing temperament if (name) { Breed.findAll({ include: {model:Temperament, through:{attributes:[]}}, where: { name: { [Op.iLike]: `%${name}%` } }, }).then((resp) => { resp.length ? res.send(resp) : res.send({ message: 'Breed not found' }) }) } //? If name is not provided send all breeds else { Breed.findAll({ include: [Temperament] }).then((resp) => { resp.length ? res.send(resp) : res.send({ message: 'Could not get breeds' }) }) } } catch (err) { next(err) } } async function addDog (req, res, next) { const { name, height, weight, life_span, temperament } = req.body //? Creating Breed in post with body details try { Breed.create({ name, height, weight, life_span, image:'https://i.imgur.com/2O2A3WP.jpeg', }) .then((breed) => breed.addTemperaments(temperament)) .then(res.send({ message: 'Created.!' })) } catch (err) { next(err.message) } } async function getDogById (req, res, next) { var { id } = req.params //? Getting Breed if provided in params try { Breed.findByPk(id, { include: Temperament }).then((resp) => { resp ? res.send(resp) : res.send({ message: `Could not get breed with id: ${id}` }) }) } catch (err) { next(err) } } module.exports = { getDogById, getAllDogs, addDog}
true
c67b7f137c49b812088dec5eb21aa9d98d392798
JavaScript
MelissaGarrett/javascript-arrays-bootcamp-prep-000
/arrays.js
UTF-8
959
3.703125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
var chocolateBars = ["snickers", "hundred grand", "kitkat", "skittles"]; function addElementToBeginningOfArray (arr, element) { var newArr = arr; newArr.unshift(element); return newArr; } function destructivelyAddElementToBeginningOfArray (arr, element) { arr.unshift(element); return arr; } function addElementToEndOfArray (arr, element) { var newArr = arr; newArr.push(element); return newArr; } function destructivelyAddElementToEndOfArray(arr, element) { arr.push(element); return arr; } function accessElementInArray (arr, idx) { return arr[idx]; } function destructivelyRemoveElementFromBeginningOfArray (arr) { arr.shift(); return arr; } function removeElementFromBeginningOfArray (arr) { var newArr = arr.shift(); return arr; } function destructivelyRemoveElementFromEndOfArray (arr) { arr.pop(); return arr; } function removeElementFromEndOfArray (arr) { var newArr = arr.pop(); return arr; }
true
d5f99bbeea35b87fef198c88c36b04accb1a933f
JavaScript
kt390256/Spotiqualize
/routes/home.js
UTF-8
2,470
2.515625
3
[]
no_license
var express = require('express'); var router = express.Router(); const HomeController = require('../controller/HomeController'); const ArtistController = require('../controller/ArtistController'); const AlbumController = require('../controller/AlbumController'); const FeatureArtistController = require('../controller/FAController'); const SongController = require('../controller/SongController'); /* / means the root of the current drive ./ means the current directory ../ means the parent of the current directory */ /* GET home page. */ router.get('/', HomeController.getEverything); /* Display Add Artist page. */ router.get('/addArtist', ArtistController.showAddArtist); /* Add Artist page. */ router.post('/addArtist', ArtistController.addArtist); /*Display add Album page*/ router.get('/addAlbum', AlbumController.showAddAlbum); /* Add Album page. */ router.post('/addAlbum', AlbumController.addAlbum); /*Add Featured artist page*/ router.get('/addFeatureArtist', FeatureArtistController.showAddFA); /*Add Feature artist*/ router.post('/addFeatureArtist', FeatureArtistController.addFA); /*Display Add song page*/ router.get('/addSong', SongController.showAddSong); /*Add song*/ router.post('/addSong', SongController.addSong); // // <!-- <script> // $(document).ready( function() { // // var arr = []; // let isFound; // // for(let i = 0; i < <%=song.length%>; i++) // { // console.log("asd"); // isFound = false;//start with can't find it // if(i === 0){//add first element during the first loop // arr[i] = <%=song[i]%>; // continue; // } // for(let j = 0; j < arr.length; j++){//loop through arr // if(song[i]===arr[j]){ //if the word is about to be added is already exists // isFound = true;//swtich to true // continue; // } // }//end of for // if(isFound === false){//only add if isFound is false // arr[i]= song[i]; // } // }//end of first for // }) // </script> --> // <!-- // <div class="ui dividing header">Featured Artist Database</div> // // <div class ="ui four column equal width center padded grid"> // <% fa.forEach(function(fa){ %> // <div class="column"> // <h3 class="ui center aligned olive segment"><%=fa.faname%></h3> // </div> // <% }) %> // </div> --> module.exports = router;
true
62680fa438d7383e24b8d96cfa1308ec77e658a0
JavaScript
drawwithcode/2019-08--naflav
/sketch.js
UTF-8
825
2.8125
3
[]
no_license
function preload() { // put preload code here } function setup() { // put setup code here createCanvas(windowWidth, windowHeight); background('#9F7CE4'); //question definition var myText = "Did I forget my drawing tablet back in Brazil?"; textFont("Fondamento"); textSize(60); fill('#333'); textAlign(CENTER); text(myText, width / 2, height / 2); //answer definition var myText = "click anywhere to remember"; textFont("Source Code Pro"); textSize(16); fill('#333'); textAlign(CENTER); text(myText, width / 2, height / 2 + 60); } function draw() { // put drawing code here } function mouseClicked() { window.open('index2.html', '_self'); } //this is to redirect to another page //function mouseClicked () { // window.open('https://www.wikihow.com/Make-a-Chair', '_self') //}
true
160d5913149730d598bb79c2aea5efd24525b106
JavaScript
michael-horn/Build-a-Tree
/levels.js
UTF-8
10,913
2.546875
3
[]
no_license
/* * Build-a-Tree * Life on Earth Project (http://sdr.seas.harvard.edu/content/life-earth) * * Michael S. Horn * Northwestern University * [email protected] * Copyright 2011, Michael S. Horn * * This project was funded by the National Science Foundation (grant 1010889). * Any opinions, findings and conclusions or recommendations expressed in this * material are those of the author(s) and do not necessarily reflect the views * of the National Science Foundation (NSF). */ // id, parent-id, name, depth, image, const LEVELS = [ { name : "Level 1", subtitle : "Plants and Animals", taxa : [ { id : 0, parent_id : null, name : "Eukaryotes", tag : "eukaryotes", trait : "cells with nuclei" }, { id : 1, parent_id : 0, name : "Animals", tag : "animals", trait : "digestive cavity" }, { id : 2, parent_id : 0, name : "Plants", tag : "plant", tip : true }, { id : 3, parent_id : 1, name : "Birds", tag : "bird", tip : true }, { id : 4, parent_id : 1, name : "Lizards", tag : "lizard", tip : true } ], dyk : ("<p>Plants and animals are both eukaryotes (<i>you-KARR-ee-ohts</i>). " + "That means that they are complex multicellular organism. " + "Plants and animals diverged (evolved into two different forms of life) " + "around 1,400 million years ago. Birds and lizards diverged much more " + "recently&#151;around 277 million years ago.</p>"), fhelp : { src : "tip1", align : "left" } }, { name : "Level 2", subtitle : "Bats, Birds, and People", taxa : [ { id : 0, parent_id : null, name : "Vertebrates", tag : "vertebrates", trait : "internal skeleton" }, { id : 1, parent_id : 0, name : "Mammals", tag : "mammals", trait : "mammary glands" }, { id : 2, parent_id : 1, name : "Humans", tip : true, tag : "human" }, { id : 3, parent_id : 0, name : "Birds", tip : true, tag : "bird" }, { id : 4, parent_id : 1, name : "Bats", tip : true, tag : "bat" } ], dyk : ("<p>Bats, like humans, are placental mammals. Bats have hair, give " + "birth to live babies, and nurse their young. Even though bats " + "and birds look similar in many ways, bats are more closely related " + "to humans because they share a more recent ancestor in common.</p>"), fhelp : { src : "tip2", align : "center" } }, /* { name : "Level 3", subtitle : "People, Fungi, and Plants", taxa : [ { id : 0, parent_id : null, name : "Eukaryotes", tag : "eukaryotes", trait : "cells with nuclei" }, { id : 1, parent_id : 0, name : "Animals and Fungi", tag : "a+f", trait : "cells with chitin" }, { id : 2, parent_id : 0, name : "Plants", tip : true, tag : "plant" }, { id : 3, parent_id : 1, name : "Fungi", tip : true, tag : "fungus" }, { id : 4, parent_id : 1, name : "Humans", tip : true, tag : "human" } ], dyk : ("<p>Scientists think that fungi (including mushrooms) are more closely " + "related to animals than they are to plants. This means that fungi and " + "animals have a more recent ancestor in common than fungi and plants. " + "One suprising piece of evidence to support this hypothesis is that both " + "fungi and animals are capable of generating proteins that can sense light.</p>"), fhelp : { src : "tip3", align : "center" } }, */ { name : "Level 3", subtitle : "Arthropods", taxa : [ { id : 0, parent_id : null, name : "Arthropods", tag : "arthropods", trait : "exoskeleton" }, { id : 1, parent_id : 0, name : "Arachnids", tag : "arachnids", trait : "eight legs" }, { id : 2, parent_id : 1, name : "Scorpions", tip : true, tag : "scorpion" }, { id : 3, parent_id : 1, name : "Spiders", tip : true, tag : "spider" }, { id : 4, parent_id : 0, name : "Insects", tip : true, tag : "butterfly" } ], dyk : ("<p>Spiders, scorpions, and insects are all different kinds of <i>" + "arthropods</i>. However, unlike insects, spiders and scorpions have " + "eight legs instead of six. Spiders and scorpions also lack the wings " + "and antennae of insects.</p>") }, { name : "Level 4", subtitle : "Amniotes", taxa : [ { id : 0, parent_id : null, name : "Amniotes", tag : "amniotes", trait : "amniotic egg" }, { id : 1, parent_id : 0, name : "Diapsids", tag : "diapsids", trait : "lizard-like face" }, { id : 2, parent_id : 1, name : "Theropods", tag : "dinobirds", trait : "wishbone" }, { id : 3, parent_id : 2, name : "Birds", tip : true, tag : "bird" }, { id : 4, parent_id : 2, name : "T. Rex", tip : true, tag : "trex" }, { id : 5, parent_id : 1, name : "Lizards", tip : true, tag : "lizard" }, { id : 6, parent_id : 0, name : "Bats", tip : true, tag : "bat" } ], dyk : ("<p>Modern birds and Tyrannosaurus rex share a more recent ancestor " + "than tyrannosaurs and lizards.</p>") }, { name : "Level 5", subtitle : "What about amphibians?", taxa : [ { id : 0, parent_id : null, name : "Tetrapods", tag : "tetrapods", trait : "four-limbed vertebrates" }, { id : 1, parent_id : 0, name : "Amniotes", tag : "amniotes", trait : "amniotic egg" }, { id : 2, parent_id : 1, name : "Diapsids", tag : "diapsids", trait : "lizard-like face" }, { id : 3, parent_id : 2, name : "Theropods", tag : "dinobirds", trait : "wishbone" }, { id : 4, parent_id : 3, name : "Birds", tip : true, tag : "bird" }, { id : 5, parent_id : 3, name : "T. Rex", tip : true, tag : "trex" }, { id : 6, parent_id : 2, name : "Lizards", tip : true, tag : "lizard" }, { id : 7, parent_id : 1, name : "Humans", tip : true, tag : "human" }, { id : 8, parent_id : 0, name : "Frogs", tip : true, tag : "frog" } ], dyk : ("<p>Frogs are a type of amphibian. Unlike amniotes (such as mammals, reptiles, birds), " + "amphibians must return to the water to lay eggs and reproduce.</p>") }, { name : "Level 6", subtitle : "Vertebrates and Invertebrates", taxa : [ { id : 0, parent_id : null, name : "Animals", tag : "animals", trait : null }, { id : 1, parent_id : 0, name : "Vertebrates", tag : "vertebrates", trait : "internal skeleton" }, { id : 2, parent_id : 0, name : "Arthropods", tag : "arthropods", trait : "exoskeleton" }, { id : 3, parent_id : 1, name : "Mammals", tag : "mammals", trait : "mammary glands" }, { id : 4, parent_id : 1, name : "Theropods", tag : "dinobirds", trait : "wishbone" }, { id : 5, parent_id : 4, name : "Birds", tip : true, tag : "bird" }, { id : 6, parent_id : 4, name : "T. Rex", tip : true, tag : "trex" }, { id : 7, parent_id : 3, name : "Giraffes", tip : true, tag : "giraffe" }, { id : 8, parent_id : 3, name : "Bats", tip : true, tag : "bat" }, { id : 9, parent_id : 2, name : "Spiders", tip : true, tag : "spider" }, { id : 10, parent_id : 2, name : "Insects", tip : true, tag : "butterfly" } ], fhelp : { src : "tip7", align : "center" } }, { name : "Level 7", subtitle : "Getting harder...", taxa : [ { id : 0, parent_id : null, name : "Animals", tag : "animals", trait : null }, { id : 1, parent_id : 0, name : "Vertebrates", tag : "vertebrates", trait : "internal skeleton" }, { id : 2, parent_id : 0, name : "Arthropods", tag : "arthropods", trait : "exoskeleton" }, { id : 3, parent_id : 1, name : "Amniotes", tag : "amniotes", trait : "amniotic egg" }, { id : 4, parent_id : 3, name : "Diapsids", tag : "diapsids", trait : "lizard-like face" }, { id : 5, parent_id : 2, name : "Arachnids", tag : "arachnids", trait : "eight legs" }, { id : 6, parent_id : 1, name : "Frogs", tip : true, tag : "frog", hint : "Frogs are a type of <i>amphibian</i>. Amphibians belong to a group of animals called vertebrates." }, { id : 7, parent_id : 3, name : "Bats", tip : true, tag : "bat", hint: "Bats are a type of mammal. Mammals belong to a group of animals called <i>diapsids</i> that also includes birds and lizards." }, { id : 8, parent_id : 4, name : "Birds", tip : true, tag : "bird", hint : "Birds and lizards belong to a group of animals called <i>diapsids</i>. Crocodiles and dinosaurs are also diapsids." }, { id : 9, parent_id : 4, name : "Lizards", tip : true, tag : "lizard", hint : "Lizards and Birds belong to a group of animals called <i>diapsids</i>. Crocodiles and dinosaurs are also diapsids." }, { id : 10, parent_id : 2, name : "Crabs", tip : true, tag : "crab", hint : "Crabs and spiders both belong to a group of animals called <i>arthropods</i>. Arthropods are invertibrate animals with exoskeletons." }, { id : 11, parent_id : 5, name : "Spiders", tip : true, tag : "spider", hint : "Spiders and crabs both belong to a group of animals called <i>arthropods</i>. Arthropods are invertibrate animals with exoskeletons." }, { id : 12, parent_id : 5, name : "Scorpions", tip : true, tag : "scorpion", hint : "Spiders and crabs both belong to a group of animals called <i>arthropods</i>. Arthropods are invertibrate animals with exoskeletons." } ], fhelp : { src : "tip8", align : "center" } } /* { name : "Bonus Level 8", subtitle : "Insanely Hard!", taxa : [ { id : 0, parent_id : null, name : "Animals", tag : "animals", trait : null }, { id : 1, parent_id : 0, name : "Vertebrates", tag : "vertebrates", trait : "internal skeleton" }, { id : 2, parent_id : 0, name : "Arthropods", tag : "arthropods", trait : "exoskeleton" }, { id : 3, parent_id : 2, name : "Arachnids", tag : "arachnids", trait : "eight legs" }, { id : 4, parent_id : 1, name : "Amniotes", tag : "amniotes", trait : "amniotic egg" }, { id : 5, parent_id : 4, name : "Mammals", tag : "mammals", trait : "mammary glands" }, { id : 6, parent_id : 4, name : "Diapsids", tag : "diapsids", trait : "lizard-like face" }, { id : 7, parent_id : 6, name : "Theropods", tag : "dinobirds", trait : "wishbone" }, { id : 8, parent_id : 1, name : "Frogs", tip : true, tag : "frog" }, { id : 9, parent_id : 6, name : "Lizards", tip : true, tag : "lizard" }, { id : 10, parent_id : 7, name : "Birds", tip : true, tag : "bird" }, { id : 11, parent_id : 7, name : "T. Rex", tip : true, tag : "trex" }, { id : 12, parent_id : 5, name : "Giraffes", tip : true, tag : "giraffe" }, { id : 13, parent_id : 5, name : "Bats", tip : true, tag : "bat" }, { id : 14, parent_id : 2, name : "Crabs", tip : true, tag : "crab" }, { id : 15, parent_id : 3, name : "Spiders", tip : true, tag : "spider" }, { id : 16, parent_id : 3, name : "Scorpions", tip : true, tag : "scorpion" }, ], dky : null } */ ];
true
5d29e184b7f6b5ecbda374fc853adc1f00d07879
JavaScript
jfarenq/summit-health-patient-records
/site/public/src/informationController.js
UTF-8
2,297
2.890625
3
[ "Apache-2.0" ]
permissive
function retrievePatientInformation(){ if (!sessionStorage.getItem("patientid")) { console.log("Redirecting to login"); window.location = '/login.html'; return; } var url = "./info"; var params = "id="+sessionStorage.getItem("patientid"); var http = new XMLHttpRequest(); http.open("GET", url+"?"+params, true); http.onreadystatechange = function() { if(http.readyState == 4 && http.status == 200) { var patientdata = JSON.parse(http.responseText); var patientname = document.getElementById('name'); patientname.innerHTML = patientdata.personal.name; var patientdetails = document.getElementById('details'); patientdetails.innerHTML = patientdata.personal.age + " years old, " + patientdata.personal.gender; var patientstreet = document.getElementById('street'); patientstreet.innerHTML = patientdata.personal.street; var patientcity = document.getElementById('city'); patientcity.innerHTML = patientdata.personal.city; var patientzipcode = document.getElementById('zipcode'); patientzipcode.innerHTML = patientdata.personal.zipcode; var appointments = document.getElementById('appointments'); patientdata.appointments.forEach( function(appointment){ var box = document.createElement('div'); box.className = 'boxitem'; box.innerHTML = '<img class="stethascope" src="/images/stethascope.svg"><div class="boxitemlabel">' + appointment + '</div>' appointments.appendChild(box); }) var medications = document.getElementById('medications'); patientdata.medications.forEach( function(medication){ var box = document.createElement('div'); box.className = 'boxitem'; box.innerHTML = '<img class="beaker" src="/images/beaker.svg"><div class="boxitemlabel">' + medication + '</div>' medications.appendChild(box); }) var patientlogout = document.getElementById('logout'); patientlogout.innerHTML = sessionStorage.getItem("patientusername") + "/logout"; } } http.send(null); }
true
64e4e1988cb99cde00035fb524782472b59f3558
JavaScript
itzsarim/coding-practice
/frontend-practise/bigfrontend-dev/DS&A/sum-chain.js
UTF-8
264
3.796875
4
[]
no_license
// sum(1)(2)(3)() = 6 const sum = x => y => y ? sum(x+y) : x; console.log(sum(1)(2)(3)(4)()); let sum2 = function (a) { let closureFunc = b => b ? sum(a + b) : a; closureFunc.toString = () => a; return closureFunc; } alert(sum2(10)(2)(3)(4));
true
f245da8b0f0da41aa7a344ec4ec0a681385e557d
JavaScript
craigdallimore/booking
/static/js/View/View.js
UTF-8
570
2.625
3
[]
no_license
(function(App) { function View(config) { for(var attr in config) { this[attr] = config[attr]; } } View.prototype.render = function() { if (!this.el) { this.el = document.createElement(this.tagName || 'div'); this.el.className = this.className || ''; } if (this.template) { var JSON = this.model.toJSON(); this.el.innerHTML = ''; this.el.appendChild(this.template(JSON)); } return this; }; App.View = View; }(App));
true
5dbdcf6f3eeda21ec56e23b2b13b42e6edf5cb94
JavaScript
FuriticuS/Lessonreact
/src/redux/reducer/auth-reducer.js
UTF-8
8,434
2.75
3
[]
no_license
// ------ action type сделаем переменные для всех type в наших функциях import {authUser, loginUser, logoutUser, securityAPI} from "../../api/api"; import {stopSubmit} from "redux-form"; const SET_USER_DATA = 'auth/SET_USER_DATA'; const GET_CAPTCHA_URL_SUCCESS = 'auth/GET_CAPTCHA_URL_SUCCESS'; //для нашего запроса посмотрим API документацию и зададим для переменных их нулевые значения let initialState = { // данные из документашки с back API - userId, email, login userId: null, email: null, login: null, //если залогинен то true isAuth: false, captchaUrl: null }; //------------------------------------------------------------------- action's //создаем редьюсор для login и добавляем его в коллекцию redux-store const authReducer = (state = initialState, action) => { // для нашей функции state = this._State.profilePage // вместо if используем switch switch (action.type) { case SET_USER_DATA: case GET_CAPTCHA_URL_SUCCESS: return { // получим state и перезапишем его ...state, // все данные лежат в action (state тоже) // - payload - в ней лежит userId, email, login, isAuth ...action.payload }; default : return state; } } //------------------------------------------------- action-creators // --- задача этой функции вернуть объект action // --- упаковываем action в объект который будет задиспачен в reducer export const setAuthUserData = (userId, email, login, isAuth) => { return { type: SET_USER_DATA, payload: { userId, email, login, isAuth } } } // --- для capthca export const getCaptchaUrlSuccess = (captchaUrl) => { return{ type: GET_CAPTCHA_URL_SUCCESS, payload: {captchaUrl} } } //-------------------------------------------------thunk for header авторизация // добавляем новое = await и async export const getAuthUserData = () => async (dispatch) => { // get запрос на адрес https://social-network.samuraijs.com/api/1.0/ хотим получить users let response = await authUser(); //делаем проверку зарегистрирован пользователь или нет // response - приходит с запросом с сервера, в нем лежит data, в дате лежит resultCode - eckjdbt в документашке API if (response.data.resultCode === 0) { // response.data - метод axios, а data->userId , data->email, data->login - это в документашке api описание в разделе Properties let {id, login, email} = response.data.data; // если все ок до dispatch dispatch(setAuthUserData(id, email, login, true)); } } //------------------------------------------------- thunk функция для аторизации прямо с сайта // 1 - создаем thunk для логанизации // 2 - в api.js создаем Post запрос для авторизации на сервере (73 строка) // 3 - в api.js создаем logout с помощью запроса delete // 4 - обращаемся в нашей thunk к созданным функциям login и logout // 5 - если все хорошо тогда вызываем thunk getAuthUserData чтобы отобразить login в хедере // 6 - создаем thunk для logout // 7 - передаем значение true для isAuth в getAuthUserData в dispatch(setAuthUserData(true)) // 8 - создаем hoc компоненту для копоненты Login и ей в connect передаем (login и logout) // 9 - создаем собыетие для пропсов LoginReduxForm onSubmit={onSubmit} // 10 - создаем mapStateToProps который возьмет reducer isAuth в redux-store // 11 - если все успешно и isAuth = true то redirect на страницу profile export const login = (email, password, rememberMe, captcha) => async (dispatch) => { let response = await loginUser(email, password, rememberMe, captcha, true); if (response.data.resultCode === 0) { dispatch(getAuthUserData()); } // если в поле к примеру ПАРОЛЬ введено неправильное значение // где login - название нашей формы, а email - где проблема // чтобы сервер сам нам описал ошибку заведем переменную в которую будет записываться массив ошибок // где response.data.messages.length название и длина сообщения с сервера // https://social-network.samuraijs.com/docs#auth_login_post здесь все ответы // где _error реакция на все ошибки в форме else { // если ответ с сервера(resultCode) = 10 (это условие backenda) if(response.data.resultCode === 10) { dispatch(getCaptchaUrl()); } let errorMessages = response.data.messages.length > 0 ? response.data.messages[0] : "Some error"; dispatch(stopSubmit("login", {_error: errorMessages})); } }; // 1 - создаем thunk для logout // 2 - в setAuthUserData добавляем переменную isAuth // 3 - в isAuth передать false // 4 - занулить все наши значения в dispatch // 5 - в Header компоненте создаем кнопку logout // 6 - создаем событие onClick={props.logout} где ждем пропсы от контейнейрной компоненты // 7 - в HeaderContainer в методе connect конектим наш logout из auth-reducer export const logout = () => async (dispatch) => { let response = await logoutUser() if (response.data.resultCode === 0) { dispatch(setAuthUserData(null, null, null, false)); } } //------------------------------------------------- thunk функция для Captcha // 1 - в api сделали запрос // 2 - в reducer сделали thunk // 3 - смотрим все в документашке для зарпосов на серве // 4 - у нас есть security/get-captcha-url которая возращает data обьект со свойством url // 5 - добавляем captchaUrl в initialState с нулевым первым значением // 6 - делаем action-creator с GET_CAPTCHA_URL_SUCESS под именем getCaptchaUrlSuccess // 7 - добавляем в наш action case с GET_CAPTCHA_URL_SUCESS // 8 - добавляем в thunk наш action = getCaptchaUrlSuccess() для выполнения результата // 9 - нашу thunk для captcha можно добавить в другую санку - в нашем случае login // 10 - если captchaUrl изменится то мы пользователю покажем картинку (в initial state) // 11 - в Login.js зафиксить изменения captchaUrl и если она не NULL то показать картинку пользователю // 12 - прокинуть с помощью props в логин форму // 13 - сделать проверку captchaUrl null или нет export const getCaptchaUrl = () => async (dispatch) => { let response = await securityAPI.getCaptchaUrl(); // проверку делать не надо т.к. капча прийдет в обязательном порядке let captchaUrl = response.data.url; dispatch(getCaptchaUrlSuccess(captchaUrl)); } export default authReducer; // после создания REDUCER - мы должны его зписать в reducer-store, чтобы могли его вызвать
true
d2742d5cc6420b769467393be8f3c3ad96575887
JavaScript
ajaytalemuger/node-assignment-user-api
/src/routers/user.js
UTF-8
3,263
2.65625
3
[]
no_license
const express = require("express"); const router = new express.Router(); const User = require('../models/user'); const auth = require('../middlewares/auth'); const { checkIfUserExist, validateUserId, checkIfEmailAlreadyExists, checkPostbody } = require("../middlewares/validate"); // Array of fields allowed in search query. Used in find by search query endpoint const allowedSearchFields = ['name', 'email', '_id']; // handler to retrieve details of all the users router.get("/", async (req, res) => { const users = await User.find(); res.send(users); }); // Handler to retrieve details of a single user for the userid given in url parameter router.get("/:userId", validateUserId, checkIfUserExist, async (req, res) => { try { res.send(req.requestedUser); } catch (e) { res.status(500).send({ error: "Error while retrieving user details" }); } }); // Handler to retrieve details of a single user for the search query given in post body router.post("/search/", async (req, res) => { try { const searchQuery = req.body; if (validateSearchQuery(searchQuery)) { sendUserDetailsForSearchQuery(searchQuery, res) } else { res.status(400).send({ error: "Invalid search query" }); } } catch (e) { console.log(e) res.status(500).send({ error: "Error while retrieving user details" }); } }); async function sendUserDetailsForSearchQuery(searchQuery, res) { const user = await User.findOne(searchQuery); if (user) { res.send(user); } else { res.send({ error: "No user found for the given search query" }); } } function validateSearchQuery(searchQuery) { inputSearchFields = Object.keys(searchQuery); return inputSearchFields.every(searchField => allowedSearchFields.includes(searchField)); } async function getUser(userId) { return User.findById(userId); } // Handler to update user details router.patch("/:userId", auth, validateUserId, checkIfUserExist, async (req, res) => { try { const inputUserDetails = req.body; const user = req.requestedUser; Object.keys(inputUserDetails).forEach(updateField => user[updateField] = inputUserDetails[updateField]); await user.save(); res.send({ message: "User details successfully updated", user }); } catch (e) { res.status(500).send({ error: "Error occured while updating user details" }); } }); // Handler to create new user router.post("/", auth, checkPostbody, checkIfEmailAlreadyExists, async (req, res) => { try { const userDetails = req.body; const user = await new User(userDetails); user.save(); res.send({ message: "User successfully created", user }); } catch (e) { res.status(500).send({ error: "Error occured while creating user" }); } }); // Handler to delete a user router.delete("/:userId", auth, validateUserId, checkIfUserExist, async (req, res) => { try { const user = req.requestedUser; await user.remove(); res.send({ message: "User successfully deleted", user }); } catch (e) { res.status(500).send({ error: "Error occured while deleting user" }); } }); module.exports = router;
true
2edc83fa87a920982d24ecdba23d0d9b03ca7f0f
JavaScript
julshotal/igme230
/Portfolio/JS/JSprojects1/p5CodeFolderSetup/Demo3-3AvatarStack/Demo3-3AvatarStack/MainAvStack.js
UTF-8
956
3.359375
3
[]
no_license
/** * Demo3-3 Avatar Stack - by Al Biles * Main driver to test Avatar and AvAtack classes. * This will be the jumping off point for your first * major "project". For now, the Avatars are all white * dots on a black background that move around using * Perlin noise. * * ICE 3-3 is to pop the top element of the AvStack when * the user types a '-'. */ let a1; // A single Avatar to play with let avS; // An Avatar Stack to play with function setup() { // Window big enough for Aviatars to wander freely createCanvas(600, 400); colorMode(HSB); // Create the actual Avatar object a1 = new Avatar(); //Create the actual AvStack object avS = new AvStack(); } function draw() { background(0); // Clear canvas to black // Test the single Avatar a1.move(); a1.display(); // Test the Avatar stack avS.moveAll(); avS.displayAll(); } function keyTyped() { if (key == 'a') avS.myPush(new Avatar()); if (key == 'c') avS.myClear(); }
true
00ba3985f55503f8798e472c316d1b4eb2c85096
JavaScript
coolpo/webpackconfig
/src/index.js
UTF-8
463
2.515625
3
[]
no_license
import './assets/css/index.styl' import Img1 from './assets/img/1.jpg' import Img2 from './assets/img/2.jpg' import mod1 from './assets/js/mod1' function start() { const app = document.querySelector('#app') const img1 = new Image() const img2 = new Image() img1.src = Img1 img2.src = Img2 const p = document.createElement('p') p.innerHTML = 'hello, webpack!' app.appendChild(img1) app.appendChild(img2) app.appendChild(p) } start() mod1('模块1')
true
34a3603bf95bc8f228b87d8e31b251204856f6b9
JavaScript
pburkett/gregslist-vue
/src/services/CarsService.js
UTF-8
649
2.609375
3
[]
no_license
import { AppState } from '../AppState' import { api } from './AxiosService' class CarsService { async getCars() { // fetch data const res = await api.get('cars') // add to AppState AppState.cars = res.data } async getOne(id) { const res = await api.get(`cars/${id}`) AppState.activeCar = res.data } async create(car) { console.log(car) const res = await api.post('cars', car) AppState.cars.push(res.data) return res.data.id } async delete(id) { await api.delete(`cars/${id}`) AppState.cars = AppState.cars.filter(c => c.id !== id) } } export const carsService = new CarsService()
true
5164562faa0939155f5321574fc88d769b17da40
JavaScript
jonasfrey/jsanimation
/animation.js
UTF-8
1,455
3.609375
4
[]
no_license
/** This is a very simple, yet powerful animation object Usage: //initialization animation.fps = 60; //set fps optional animation.renderFunction = myRepeatingFunction; // set the function which is called every fps //controls animation.start(); //start the animation animation.stop(); //stop the animation */ window.animation = {}; animation.id = null; animation.framespersecond = 30; animation.framecount = 0; animation.millisecondsperframe = 1000 / animation.framespersecond; animation.timestampms = Date.now(); animation.timestampms2 = Date.now(); animation.msdifference = 0; animation.renderFunction = null; animation.fps = function(fps = null){ if(fps == null){ return this.framespersecond; } this.framespersecond = fps; this.millisecondsperframe = 1000 / this.framespersecond; } var repeatOften = function() { animation.timestampms2 = Date.now(); animation.msdifference = animation.timestampms2 - animation.timestampms; if(animation.msdifference > animation.millisecondsperframe){ animation.framecount++; animation.frame(); animation.timestampms = animation.timestampms2 - (animation.msdifference % animation.millisecondsperframe); } animation.id = requestAnimationFrame(repeatOften); } animation.frame = function(){ animation.renderFunction(); } animation.stop = function() { cancelAnimationFrame(animation.id); } animation.start = function(){ animation.id = requestAnimationFrame(repeatOften); }
true
3b4fe4a4f91324acc0f07697e317254ad19ddd59
JavaScript
CedricTheofanous/sports
/team-landing-page/src/containers/EventsContainer.js
UTF-8
2,659
2.6875
3
[ "MIT" ]
permissive
import React, {useState, useEffect} from 'react' import styled from 'styled-components' import FutureEvent from '../components/FutureEvent' import PastEvent from '../components/PastEvent' import LoadingSpinner from '../components/LoadingSpinner' const StyledDiv = styled('div')` display: grid; grid-template-columns: 1fr 1fr; grid-column-gap: 5vw; ` // errors running multiple fetch requests in the same effect, decided to test what I have working instead of debug const EventsContainer = props => { const {idTeam, teamName} = props const [isEventsLoading, setIsEventsLoading] = useState(true) const [pastEvents, setPastEvents] = useState([]) const [futureEvents, setFutureEvents] = useState([]) useEffect(() => { let cancel = false const runEffect = async () => { // past const pastFetch = await fetch( `https://www.thesportsdb.com/api/v1/json/1/eventsnext.php?id=${idTeam}`, ) if (cancel) { return } const pastResults = await pastFetch.json() if (cancel) { return } setPastEvents(pastResults.results) // future const futureFetch = await fetch( `https://www.thesportsdb.com/api/v1/json/1/eventslast.php?id=${idTeam}`, ) if (cancel) { return } const futureResults = await futureFetch.json() if (cancel) { return } console.log(futureResults) setFutureEvents(futureResults.events) setIsEventsLoading(false) } runEffect() return () => { cancel = true } }, [idTeam, teamName]) if (isEventsLoading) { return ( <StyledDiv> <LoadingSpinner /> </StyledDiv> ) } return ( <StyledDiv> <section> <h2>Schedule</h2> {futureEvents.map(event => { return ( <FutureEvent key={event.idEvent} strHomeTeam={event.strHomeTeam} strAwayTeam={event.strAwayTeam} dateEventLocal={event.dateEventLocal} ></FutureEvent> ) })} </section> <section> {console.log(pastEvents)} <h2>Scores</h2>{' '} {pastEvents.map(event => { return ( <PastEvent key={event.idEvent} strHomeTeam={event.strHomeTeam} strAwayTeam={event.strAwayTeam} dateEventLocal={event.dateEventLocal} intHomeScore={event.intHomeScore} intAwayScore={event.intAwayScore} ></PastEvent> ) })} </section> </StyledDiv> ) } export default EventsContainer
true
815b5980bfe9100550ab98db08b01516956a41ef
JavaScript
MainShayne233/js_monkey_patches
/test/array_patches_test.js
UTF-8
3,621
3.109375
3
[]
no_license
require('../lib/array_patches.js') var assert = require('assert') // monkey patching for the monkey patching tests assert.arraysEqual = function(array1, array2) { return assert.equal(true, array1.equals(array2)) } describe('Array', function() { describe('#equals(otherArray)', function() { it('should return true if arrays or equal, false otherwise', function() { assert.equal(true, [1,2,3,4].equals([1,2,3,4])) assert.equal(false, [1,2,3,4].equals([1,2,3])) }) }) describe('#mapAndFilter(mapFunc, filterFunc)', function() { it('should return a mapped and filtered array', function() { var onlyIntegers = function(x) { return x === Math.round(x) } var input = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,17,19,20] assert.arraysEqual([1,2,3,4], input.mapAndFilter(Math.sqrt, onlyIntegers)) }) }) describe('#min()', function() { it('should return the smallest value of the array', function() { assert.equal(101, [432,6789,765,101,263,46567].min()) }) }) describe('#minBy(mapFunction)', function() { it('should return the smallest return value of the function', function() { var flipNumber = function(x) { return parseFloat(String(x).reverse()) } assert.equal(12342.32, [2.343,12342.32,123,23.4321,345].minBy(flipNumber)) }) }) describe('#max()', function() { it('should return the largest value of the array', function() { assert.equal(46567, [432,6789,765,101,263,46567].max()) }) }) describe('#maxBy(mapFunction)', function() { it('should return the largest return value of the function', function() { var flipNumber = function(x) { return parseFloat(String(x).reverse()) } assert.equal(23.4321, [2.343,12342.32,123,23.4321,345].maxBy(flipNumber)) }) }) describe('#pluck(attr)', function () { it('should return just the specified attr of each element', function () { var names = [ {firstName: 'joe', lastName: 'garry'}, {firstName: 'john', lastName: 'go'}, {firstName: 'josh', lastName: 'wade'} ] assert.arraysEqual(['joe','john','josh'], names.pluck('firstName')) }) }) describe('#shifted', function () { it('should return the array without the first element', function () { var names = ['joe','john','josh', 'george'] assert.arraysEqual(['john','josh', 'george'], names.shifted()) assert.arraysEqual(['joe','john','josh', 'george'], names) }) }) describe('#popped', function () { it('should return the array without the last element', function () { var names = ['joe','john','josh', 'george'] assert.arraysEqual(['joe', 'john','josh'], names.popped()) assert.arraysEqual(['joe','john','josh', 'george'], names) }) }) describe('#flatten', function () { it('should return the flattened array', function() { var scores = [[3,34,34,[34,[[[[3]]],4,5,[2]]],4,33,[43]]] assert.arraysEqual([3, 34, 34, 34, 3, 4, 5, 2, 4, 33, 43], scores.flatten()) }) }) describe('#compact', function () { it('should return an array of only definded values', function() { var marks = [89, null, 95, 82, 0, NaN, 75, undefined] assert.arraysEqual([89,95,82,0,75], marks.compact()) }) }) describe('#include', function () { it('should return true if the array contains the element, false otherwise', function() { var marks = [54,64,70.0,54,23,76,43] console.log(marks.include(70)) assert.equal(true, marks.include(76)) assert.equal(false, marks.include(71)) }) }) })
true
881430a186a539a9ba9dc877b639f7c69366c994
JavaScript
Pilewski/react-scrabble
/lib/app.js
UTF-8
1,252
2.75
3
[]
no_license
import React, { Component } from 'react'; import tribonacci from './vanilla'; import letterScores from './letterScores' import Helper from './helper'; class App extends Component { constructor() { super(); this.state = { userInput: '', signature: [], arrayLength: 1, tribList: [] } } clearState() { this.setState({userInput: '', signature: [], }); } createArray() { let tribArray = this.state.signature; let numberToPush = parseInt(this.state.userInput) tribArray.push(numberToPush); if (this.state.signature.length === 3){ this.setState({tribList: tribonacci(this.state.signature, this.state.arrayLength)}); } this.setState({tribList: tribArray}); } render(){ return( <div> <input placeholder='Submit Three Numbers' onChange={(e)=> this.setState({userInput: e.target.value})} /> <input placeholder='Submit Array Length' onChange={(e)=> this.setState({arrayLength: e.target.value})} /> <Helper name='RESET' handleClick={this.clearState.bind(this)}/> <Helper name='SUBMIT' handleClick={this.createArray.bind(this)}/> {this.state.tribList} </div> ) } } export default App;
true
2848d12f869b4be313062222f88cdeb574fd145d
JavaScript
brandonin/algorithms
/reverse.js
UTF-8
454
3.6875
4
[]
no_license
function reverse(input){ var input = input.split(''); for(var i = 0; i < input.length/2; i++){ var temp = input[i]; input[i] = input[input.length-i-1]; input[input.length-i-1] = temp; } console.log(input.join('')); } reverse('hello'); function reverse1(input){ var input = input.split(''); for(var i = input.length-1; i >=0; i--){ input.push(input[i]); } input.splice(0, input.length); console.log(input.join('')); } reverse1("hello");
true
de343bb8957eb2281a5153d7c625049a5c656383
JavaScript
nocenter/hypercloud
/lib/templates/js/register.js
UTF-8
276
2.65625
3
[ "MIT" ]
permissive
/* global $ */ // register page js $(function () { var usernameInput = $('#input-username') var usernameOutput = $('#output-username') output() usernameInput.on('keyup', output) function output () { usernameOutput.text(usernameInput.val() || 'username') } })
true
7d6b37c56520befa97e977be463789f606b8f86c
JavaScript
yatharthkatyayan/drawAndTalk
/src/component/container/container.jsx
UTF-8
1,549
2.625
3
[]
no_license
import React, { useEffect, useState } from "react"; import Board from "../board/board"; import "./style.css"; const Container = () => { const [size, setsize] = useState(8); const [color, setcolor] = useState("rgb(101, 226, 101)"); useEffect(() => { let color_container = document.getElementById("color-container"); color_container.style.backgroundColor = color; }, [color]); const handleSize = () => { let doc = document.getElementById("myRange").value; setsize(doc); }; const handleColor = () => { let new_color = document.getElementById("color-picker").value; let color_container = document.getElementById("color-container"); color_container.style.backgroundColor = new_color; setcolor(new_color); }; return ( <div className="container"> <div className="menu"> <div className="container-color-picker" id="color-container"> <input className="color-picker" type="color" id="color-picker" defaultValue={color} onChange={handleColor} /> </div> <div className="slidecontainer"> <input type="range" min="1" max="150" className="slider" id="myRange" value={size} onChange={handleSize} /> </div> </div> <div className="board-container"> {<Board BrushColor={color} BrushSize={`${size}`}></Board>} </div> </div> ); }; export default Container;
true
6090d83f1a5cc4f5b0901c64d9ca8b235dbf0ba8
JavaScript
taksenov/taksenov.github.io
/VanillaJS/11_DZ-8-master/hm2/script.js
UTF-8
6,373
2.859375
3
[]
no_license
// ДЗ 2: Создать приложение для ВКонтакте, которое загружает список ваших // друзей и выводит их на страницу в следующем формате: // Фото, ФИО, Возраст, Дата рождения. // Друзья должны быть отсортированы по дате рождения в порядке убывания. // То есть на самом верху списка расположен друг с ближайший датой рождения. // Использование шаблонизатора приветствуется. // ============================================================================= // ============================================================================= // VK AppID = 5757533 // ============================================================================= // ============================================================================= // Установка HTTP-сервера: // 1) npm install http-server -g // Запуск HTTP-сервера: // 2) http-server hm2 -p 7777 -a 127.0.0.1 // 3) http://localhost:7777/ // ============================================================================= let vkAppId = 5757533; let headerUserFriendsVK = document.getElementById('headerUserFriendsVK'); let listOfDownloadedFriends = document.getElementById('listOfDownloadedFriends'); let allRenderedFriends = document.getElementById('allRenderedFriends'); let VK_ACCESS_FRIENDS = 2; // вспомогательные функции====================================================== // функция сравнения возраста function compareAge(personA, personB) { let friendA = new Date(personA.bdate.replace(/(\d+)\.(\d+)\.(\d+)/, '$2/$1/$3')); let friendB = new Date(personB.bdate.replace(/(\d+)\.(\d+)\.(\d+)/, '$2/$1/$3')); friendA = Date.parse(friendA); friendB = Date.parse(friendB); return friendB - friendA; // здесь можно поменять порядок сортировки, поменяв слагаемые } // compareAge // вспомогательные функции====================================================== new Promise(function(resolve) { if (document.readyState === 'complete') { resolve(); } else { window.onload = resolve; } }) // запрос авторизации в ВК .then(function() { return new Promise(function(resolve, reject) { VK.init({ apiId: vkAppId }); VK.Auth.login(function(response) { if (response.session) { resolve(response); } else { reject(new Error('Не удалось авторизоваться')); } }, VK_ACCESS_FRIENDS); }); }) // получение полного имени пользователя .then(function() { return new Promise(function(resolve, reject) { VK.api('users.get', {'name_case': 'gen'}, function(response) { if (response.error) { reject(new Error(response.error.error_msg)); } else { headerUserFriendsVK.textContent = `Друзья ${response.response[0].first_name} ${response.response[0].last_name}`; resolve(); } }); }) }) // получение id всех друзей пользователя .then(function() { return new Promise(function(resolve, reject) { VK.api('friends.get', {v: '5.8'}, function(serverAnswer) { if (serverAnswer.error) { reject(new Error(serverAnswer.error.error_msg)); } else { resolve(serverAnswer); } }); }); }) // получение данных всех ранее полученных друзей, обработка дат рождения, вывод в DOM .then( function(serverAnswer) { return new Promise( function(resolve, reject) { VK.api( 'users.get', { v: '5.8', user_ids: serverAnswer.response.items, fields: 'bdate,photo_50,friend_status' }, function(serverAnswer) { if (serverAnswer.error) { reject(new Error(serverAnswer.error.error_msg)); } else { console.log('serverAnswer.response = ', serverAnswer.response); // в промежуточный массив брать только тех кто указал дату рождения полностью let tempArrOfFriendsObj = []; for (let i = 0; i < serverAnswer.response.length; i++) { if ( serverAnswer.response[i].bdate && typeof serverAnswer.response[i].bdate !== 'undefined' ) { if (serverAnswer.response[i].bdate.match(/\.\d{4}/i)) { let tempLength = tempArrOfFriendsObj.length; tempArrOfFriendsObj[tempLength] = serverAnswer.response[i]; } } } // вызов функции сортировки по возрасту tempArrOfFriendsObj.sort(compareAge); // вывод данных о друзьях в DOM let source = allRenderedFriends.innerHTML; let templateFn = Handlebars.compile(source); let template = templateFn({ friendslist: tempArrOfFriendsObj }); listOfDownloadedFriends.innerHTML = template; resolve(); } }); } ); }) .catch(function(e) { alert(`Ошибка: ${e.message}`); });
true
386b14198c17d18c01c1ef3a7da2a17798350fab
JavaScript
Radhika1220/ProgrammingConstructsJS
/Repetition_WhileLoop/FlipCoin.js
UTF-8
463
3.765625
4
[]
no_license
var headCount=0; var tailCount=0; while(headCount<=10 || tailCount<=10) { let coinVal=Math.floor(Math.random()*10)%2; console.log(coinVal); if(coinVal==0) { console.log("Head") headCount++; } else { console.log("Tail") tailCount++; } } if(headCount==11) { console.log("******Head is the Winner******"+headCount); } else { console.log("***********Tail is the Winner*********"+ tailCount); }
true
13eacecfa77d717385615ba3f99d94682bcfc9e7
JavaScript
jonmetz/pianogoggles
/js/checkBackground.js
UTF-8
2,396
2.765625
3
[]
no_license
var checkBackground = ( function () { var THRESHOLD = 150750; // var INTERVAL = 100; var STABILITY_THRESHOLD = 50; var ready = false; var thresholdingFrames = []; var backgroundThreshold = []; var counter = 0; var getBackgroundThreshold = function() { return backgroundThreshold; } var computeBackgroundThreshold = function() { for (var index = 0; index < thresholdingFrames[0].data.length; index++) { backgroundThreshold.push(0); for (var frame = 0; frame < thresholdingFrames.length; frame++) { backgroundThreshold[index] += thresholdingFrames[frame].data[index]; } backgroundThreshold[index] = backgroundThreshold[index] / thresholdingFrames.length; } thresholdingFrames = []; messageUser.write('Start playing!'); } var isReady = function() { return ready; } var processFrame = function(frame) { if (thresholdingFrames.length === 0) { // Is this the first frame thresholdingFrames.push(frame); counter++; return; // quit without doing other shit } // else var lastFrame = thresholdingFrames[thresholdingFrames.length - 1]; var diff = getDiffFrames(frame, lastFrame); if (diff > THRESHOLD) { // background isn't stable, restart process thresholdingFrames = []; counter = 0; } else { // background is stable for now, keep checking counter++; thresholdingFrames.push(frame); } if (counter > STABILITY_THRESHOLD) { // Are we done yet? console.log("DONE"); computeBackgroundThreshold(); ready = true; } } var getDiffFrames = function(frame1, frame2) { var diff = 0; var i_frame1, i_frame2; var data1 = frame1.data; var data2 = frame2.data; for (var i = 0; i < data1.length; i++) { i_frame1 = data1[i]; i_frame2 = data2[i]; if (i_frame1 > i_frame2) { diff += i_frame1 - i_frame2; } else { diff += i_frame2 - i_frame1; // console.log(i_frame2 - i_frame1); } } return diff; }; return { isReady: isReady, getBackgroundThreshold: getBackgroundThreshold, processFrame: processFrame, THRESHOLD: THRESHOLD } })();
true
f2d7551a66dfa257854233b1d59db60da04b1a9c
JavaScript
heber013/computersapp
/steps/when.js
UTF-8
1,041
2.625
3
[]
no_license
import ComputerPage from '../pageObjects/computer.page'; import ComputerListPage from '../pageObjects/computerlist.page'; const { When } = require('cucumber'); When('I enter the computer data:', (computertable) => { computertable.hashes().forEach(function (computer) { if (computer['name']) { ComputerPage.enterName(computer['name']); } if (computer['introduced date']){ ComputerPage.enterIntroducedDate(computer['introduced date']); } if (computer['discontinued date']){ ComputerPage.enterDiscontinuedDate(computer['discontinued date']); } if (computer['company']){ ComputerPage.selectCompany(computer['company']); } }); }); When('I select to save the computer', () => { ComputerPage.selectCreateComputer(); }); When('I select to delete the computer', () => { ComputerPage.selectDeleteComputer(); }); When('I search the computer {string}', (name) => { ComputerListPage.searchComputer(name); }); When('I open the computer {string}', (name) => { ComputerListPage.openComputer(name); });
true
3e6e16f20ce046413dcbc4ebbe6bf73178a27254
JavaScript
ybhsos/react200
/src/R015_Map.js
UTF-8
816
2.734375
3
[]
no_license
import React,{Component} from "react"; class R015_Map extends Component{ componentDidMount() { var Map_Arr = [3,2,8,8]; let Map_newArr = Map_Arr.map(x => x); console.log("1 . :" + Map_newArr); let Map_Mul = Map_Arr.map(x=>x*2); console.log("2 . :"+ Map_Mul); var ObjArray = [{key:'react',value:'208'}, {key:'리액트',value: "TwoHundred"} ] let Map_objArr = ObjArray.map((obj,index)=>{ console.log((index+3)+" "+JSON.stringify(obj)) var Obj = {}; obj[obj.key] = obj.value; return obj; }) console.log("5 :"+JSON.stringify((Map_objArr))) } render() { return( <h2>[THIS IS MAP]</h2> ) } } export default R015_Map;
true
8f952b9cb24d178414a513a7725f6fa489d92c57
JavaScript
zesii/PigFarming
/pig/static/js/app/jsonParse.js
UTF-8
465
2.734375
3
[]
no_license
/** * Created by Administrator on 2016/11/5. */ var jsonParse = (function(){ var arrToJsons = function(arr){ var objArr = []; for(var i=0;i<arr.length;i++){ var str = arr[i][0]; str = "{"+str+"}"; console.log(str); var obj = JSON.parse(str); objArr[i] = obj; } console.log(objArr); return objArr; } return { arrToJsons: arrToJsons } })();
true
4570c80ad7ff86de7caf257add2ea10e18edf13f
JavaScript
mcschatz/breakout
/lib/brick.js
UTF-8
443
3.171875
3
[ "MIT" ]
permissive
var Brick = function(game, position) { this.game = game; this.position = position; this.size = {x: 87, y: 18}; this.status = 1; }; Brick.prototype = { draw: function(canvas, color) { if(this.status === 1) { canvas.beginPath(); canvas.rect(this.position.x, this.position.y, this.size.x, this.size.y); canvas.fillStyle = color; canvas.fill(); canvas.closePath(); } } }; module.exports = Brick;
true
173cf2f809df3b93280bd9e3e794fa12d95bd301
JavaScript
Saliba-san/startpage
/Bento/js/greeting.js
UTF-8
710
3.578125
4
[]
no_license
// Get the hour const today = new Date(); const hour = today.getHours(); // Here you can change your name const name = ' Saliba-san'; // Here you can change your greetings const gree1 = 'Hora de capotar,'; const gree2 = 'Bom dia! '; const gree3 = 'Boa tarde, '; const gree4 = 'Boa noite, '; // Define the hours of the greetings if (hour >= 23 && hour < 5) { document.getElementById('greetings').innerText = gree1 + name; } else if (hour >= 6 && hour < 12) { document.getElementById('greetings').innerText = gree2 + name; } else if (hour >= 12 && hour < 17) { document.getElementById('greetings').innerText = gree3 + name; } else { document.getElementById('greetings').innerText = gree4 + name; }
true
7b65a0837352803366cd5b9cc0bf3ed1a7337a4e
JavaScript
holterdipolter/teleframe
/lib/functions/if-ping-true-false.js
UTF-8
818
2.765625
3
[]
no_license
// name: if ping true/false // outputs: 4 if (msg.payload){ flow.set('pingCounter', 12); flow.set('onlineFlag', true); if (!(flow.get('onlineFlag'))){ msg.payload = "firstOnline"; return [null, msg, null, msg]; } else { msg.payload = "online"; return [null, null, null, msg]; } } else { flow.set('pingCounter', flow.get('pingCounter') -1); if (flow.get('pingCounter') <= 0){ flow.set('onlineFlag', false); msg.payload = "offline, pingCounter = " + (flow.get('pingCounter') + " -> stop"); return [msg, null, null, null]; } else { msg.payload = "offline, pingCounter = " + (flow.get('pingCounter')); return [null, null, msg, null]; } }
true
eaf501d2f0b6699c0e4860f7d4a24ae56470decc
JavaScript
eclectic-matt/Node.JS
/GameTester/gametester/shithead/functions/setup.js
UTF-8
2,371
3.78125
4
[]
no_license
//CREATE A DRAW PILE - called 'drawPile', hidden, and owned by no-one let drawPile = new Deck('drawPile', true, null); //GENERATE THE CARDS BASED ON THE SHITHEAD RULES let cardArray = new DeckType('SHITHEAD_CARDS'); //ADD CARDS IN BULK drawPile.addCards(cardArray,false); //SHUFFLE THE CARDS drawPile.shuffle(); //ADD THE DRAW PILE TO THE DECK this.addDeck(drawPile); //CREATE A DISCARD PILE - called 'discardPile', visible, owned by no-one let discardPile = new Deck('discardPile', false, null); //NO CARDS YET - JUST ADD IT this.addDeck(discardPile); //CREATE A BURN PILE? - called 'burnPile', visible, owned by no-one //let burnPile = new Deck('burnPile', false, null); //CREATE PLAYERS for(var i = 1; i <= this.playerCount; i++){ //GENERATE A PLAYER NAME let playerName = 'Player' + i; //CREATE A PLAYER CALLED 'P' + i (1,2,3,4) let player = new Player(playerName); //CREATE THE PLAYER'S HAND let playerHand = new Deck(playerName + 'Hand', false, player); //DRAW 3 CARDS FROM THE DECK let handCards = this.decks[0].draw(3, true); //ADD THEM TO THE HAND DECK playerHand.addCards(handCards); //ADD THIS DECK TO THE PLAYER player.addDeck(playerHand); //ADD A FACE DOWN 'DECK' let playerFaceDownOne = new Deck(playerName+'FaceDownOne',true, player); let faceDownCardOne = this.decks[0].draw(1, true); playerFaceDownOne.addCard(faceDownCardOne); player.addDeck(playerFaceDownOne); //ADD THE OTHER FACE DOWN 'DECK' let playerFaceDownTwo = new Deck(playerName+'FaceDownTwo',true, player); let faceDownCardTwo = this.decks[0].draw(1, true); playerFaceDownTwo.addCard(faceDownCardTwo); player.addDeck(playerFaceDownTwo); //ADD A FACE UP 'DECK' let playerFaceUpOne = new Deck(playerName+'FaceUpOne',false, player); let faceUpCardOne = this.decks[0].draw(1, true); playerFaceUpOne.addCard(faceUpCardOne); player.addDeck(playerFaceUpOne); //ADD THE OTHER FACE DOWN 'DECK' let playerFaceUpTwo = new Deck(playerName+'FaceUpTwo',false, player); let faceUpCardTwo = this.decks[0].draw(1, true); playerFaceUpTwo.addCard(faceUpCardTwo); player.addDeck(playerFaceUpTwo); //ADD THIS PLAYER TO THE GAME this.addPlayer(player); } //SHUFFLE THE PLAYERS this.shufflePlayers(); //ALERT THE FIRST PLAYER //alert('The first player will be ' + this.players[0].name + '!'); console.log('The first player will be ' + this.players[0].name + '!');
true
198f9553ea70872df4368e42212203c54d261711
JavaScript
joorjoor/AtomicExamples
/WebView3D/JavaScript/Resources/Components/Scene.js
UTF-8
533
2.765625
3
[ "MIT" ]
permissive
"atomic component"; //Define a Scene component exports.component = function(self) { //we are attaching that component to the Scene, so we are sure that ours node is a scene var scene = self.node; var time = 12; self.start = function() { // create the procedural sky var pnode = scene.createChild(); self.procSky = pnode.createComponent("ProcSky"); self.procSky.setDayTime(time); }; self.update = function(timeStep) { time += timeStep * .08; self.procSky.setDayTime(time); }; };
true
12d6c80a2a4c7c69020e2c527426e3f7cdf5bb49
JavaScript
ritvij14/noterr.io
/app.js
UTF-8
3,772
3.5625
4
[]
no_license
var homeButton = document.getElementById("home-button"); var aboutUsButton = document.getElementById("about-us-button"); var addNoteButton = document.getElementById("add-note-button"); var savedNotesList = document.getElementById("saved-notes"); var deleteButton = document.getElementsByClassName("delete-btn"); var editButton = document.getElementsByClassName("edit-btn"); var editStatus = false; var noteNumber = 0; //for home button in nav bar homeButton.addEventListener('click', () => { if (!(homeButton.classList.contains("active"))) { var current = document.getElementsByClassName("active"); //console.log(current); current[0].classList.remove("active"); homeButton.classList.add("active"); } }) //for about us button in nav bar aboutUsButton.addEventListener('click', () => { if(!(aboutUsButton.classList.contains("active"))) { var current = document.getElementsByClassName("active"); //console.log(current); current[0].classList.remove("active"); aboutUsButton.classList.add("active"); } }) //for adding a new note addNoteButton.addEventListener('click', () => { //console.log("Creating new note"); //take note typed by user var newNoteTitle = document.getElementById('note-title').value; var newNoteContent = document.getElementById('note-content').value; if (newNoteTitle === "" || newNoteContent === "null") { alert("Please fill all entries"); } else { console.log(newNoteContent); var title = document.createElement('h2'); var noteContent = document.createElement('p'); title.appendChild(document.createTextNode(newNoteTitle)) noteContent.appendChild(document.createTextNode(newNoteContent)); //create edit and delete buttons var buttons = document.createElement('div'); var editBtn = document.createElement('a'); var edit = document.createElement('i'); var deleteBtn = document.createElement('a'); var del = document.createElement('i'); edit.className = 'far fa-edit'; del.className = 'far fa-trash-alt'; editBtn.className = 'edit-btn'; editBtn.href = '#'; deleteBtn.className = 'delete-btn'; deleteBtn.href = '#'; editBtn.appendChild(edit); deleteBtn.appendChild(del); buttons.className = 'ml-auto'; buttons.appendChild(editBtn); buttons.appendChild(deleteBtn); //create card var card = document.createElement('div'); card.className = 'card container-fluid'; card.style = 'justify-content: center;'; card.id = 'note-card'; card.appendChild(title); card.appendChild(noteContent); card.appendChild(buttons); //console.log(card); //create list item var notesLi = document.createElement('li'); notesLi.className = 'col-xl-4 note'; notesLi.appendChild(card); console.log(notesLi); //save note savedNotesList.appendChild(notesLi); //event listener for delete button deleteBtn.addEventListener('click', () => { if(confirm("Are you sure you wanna delete this note?")) savedNotesList.removeChild(notesLi); }) //event listener for edit button editBtn.addEventListener('click', () => { document.getElementById('note-title').value = newNoteTitle; document.getElementById('note-content').value = newNoteContent; savedNotesList.removeChild(notesLi); }) //clear the input areas once note is added document.getElementById('note-title').value = ""; document.getElementById('note-content').value = ""; } })
true
4f1fbc8f79271f93c5b3349cf5429f89d923d294
JavaScript
shaneavila/the-odin-project
/web-development-101/rock-paper-scissors/main.js
UTF-8
2,363
3.953125
4
[]
no_license
const numOfRounds = 5; let computer = 0; let player = 0; function computerPlay() { const choices = ['rock', 'paper', 'scissors']; const rand = choices[Math.floor(Math.random() * choices.length)]; return rand; } function finalScore() { const winner = player > computer ? `You won! Score: Player - ${player}, Computer - ${computer}` : `You lost! Score: Player - ${player}, Computer - ${computer}`; document.getElementById('score').innerHTML = winner; } function playRound(playerSelection, computerSelection) { const win = `${playerSelection.charAt(0).toUpperCase() + playerSelection.slice(1)} beats ${computerSelection}.`; const lose = `${computerSelection.charAt(0).toUpperCase() + computerSelection.slice(1)} beats ${playerSelection}.`; const tie = "It's a tie! Try again."; if (playerSelection === 'rock') { if (computerSelection === 'scissors') { player += 1; return `${win}`; } if (computerSelection === 'paper') { computer += 1; return `${lose}`; } } else if (playerSelection === 'paper') { if (computerSelection === 'rock') { player += 1; return `${win}`; } if (computerSelection === 'scissors') { computer += 1; return `${lose}`; } } else if (playerSelection === 'scissors') { if (computerSelection === 'paper') { player += 1; return `${win}`; } if (computerSelection === 'rock') { computer += 1; return `${lose}`; } } return tie; } let playerSelection; const buttons = document.querySelectorAll('button'); buttons.forEach(button => { button.addEventListener('click', () => { if (button.id === 'rock') { playerSelection = 'rock'; } else if (button.id === 'paper') { playerSelection = 'paper'; } else if (button.id === 'scissors') { playerSelection = 'scissors'; } document.getElementById('results').innerHTML = playRound(playerSelection, computerPlay()); if (computer === numOfRounds || player === numOfRounds) { document.getElementById('rock').disabled = true; document.getElementById('paper').disabled = true; document.getElementById('scissors').disabled = true; finalScore(); } else { document.getElementById('score').innerHTML = `Score: Player - ${player}, Computer - ${computer}`; } }); });
true
197ce5c29d869acb89effa194210dd1333775cd0
JavaScript
TerryHintz/tutoring
/src/Events.js
UTF-8
405
2.578125
3
[]
no_license
import React, { Component } from 'react'; import './App.css'; class Events extends Component { state = { word: 'default' } handleKeyPress = (event) => { console.log(event.key); } render() { return ( <div> <input type={'text'} onKeyPress={(event) => this.handleKeyPress(event)}/> <div>{this.state.word}</div> </div> ); } } export default Events;
true
aac8f14e4d77489a7c017a99a217b82496d12e31
JavaScript
parnasos/Ejercicios-Adalab
/Mod 2/2.5/2.5_9/main.js
UTF-8
741
2.84375
3
[]
no_license
'use strict'; const teacherTuerto = document.querySelector(".teacher--tuerto"); const teacherIsra = document.querySelector(".teacher--isra"); const teacherNasi = document.querySelector(".teacher--nasi"); teacherNasi.addEventListener ("click", addclass); teacherIsra.addEventListener ("click", addclass); teacherTuerto.addEventListener ("click", addclass); function addclass(event) { event.currentTarget.classList.toggle("teacher--selected"); if (event.currentTarget.querySelector(".favorite").innerHtml==="Añadir") { event.currentTarget.querySelector(".favorite").innerHtml.replace("Añadir", "Quitar"); } else { event.currentTarget.querySelector(".favorite").innerHtml= "Añadir"; } }
true
f6c73b6ef13688dd13e8e826345299a94924653f
JavaScript
Nicole0724/appCache
/assets/js/wsw_funs.js
UTF-8
4,163
2.53125
3
[]
no_license
// 全局函数定义-通用方法 Wsw.funs = function (name) { } // 取得当前Userinfo状态及信息 参数:cookieNameAll 表示像userinfo这样的大key值 /*使用方法 * var userInfo = Wsw.funs.getCookieAll('userinfo'); console.log(decodeURIComponent(userInfo.think.nickname)); //Jquery字符UrlEncode 编码、解码 Jquery解码:decodeURIComponent(url); Jquery编码:encodeURIComponent(url); * */ Wsw.funs.getCookieAll = function (cookieNameAll) { var strCookieAll = document.cookie; // console.log(strCookieAll); var arrCookieAll = strCookieAll.split("; "); for (var i = 0; i < arrCookieAll.length; i++) { var arrAll = arrCookieAll[i].split("="); if (cookieNameAll == arrAll[0]) { var strCookie = '{' + decodeURIComponent(arrAll[1]) + '}'; // return $.parseJSON(strCookie); /**/ return eval("(" + strCookie + ")"); } } return ""; } // 执行ajax, 参数: // apiUrl 接口地址(相对路径) // opt 参数 // sync 是否同步(bool/true异步、false同步), // lock 锁定(bool, sync 同一时间仅允许一次操作), // loadBar 加载提示(bool/true加载、false不加载), // funcs 回调函数对象 // 失败方法 Wsw.funs.excuteQuery = function (apiUrl, opt, sync, lock, loadBar, funcs) { //禁止重复提交 if ($('input[name="disableSubmit"]').val() == '0' || !lock) { //标记禁止提交 $('input[name="disableSubmit"]').val('1'); $.ajax({ type: 'post', url: Wsw.config.getApi(apiUrl), dataType: 'json', async: sync, data: opt, beforeSend: function (XMLHttpRequest) { if (loadBar) $('.wsw_loading').slideDown('fast'); }, success: function (data) { if (loadBar) $('.wsw_loading').slideUp('fast'); //状态200 if (parseInt(data.status) == 200) { funcs.func200(data); } //状态303 脏词拒绝提交 else if (parseInt(data.status) == 303) { Wsw.tips.open(Wsw.msg.dataFaile, 'notice'); } //状态400 else if (parseInt(data.status) == 400 && funcs.func400 != null && typeof(funcs.func400) != 'undefined') { funcs.func400(data); } //状态401 else if (parseInt(data.status) == 401 && funcs.func401 != null && typeof(funcs.func401) != 'undefined') { funcs.func401(data); } //状态403 else if (parseInt(data.status) == 403 && funcs.func403 != null && typeof(funcs.func403) != 'undefined') { funcs.func403(data); } //状态404 else if (parseInt(data.status) == 404 && funcs.func404 != null && typeof(funcs.func404) != 'undefined') { funcs.func404(data); } //状态405 else if (parseInt(data.status) == 405 && funcs.func405 != null && typeof(funcs.func405) != 'undefined') { funcs.func405(data); } //状态409 else if (parseInt(data.status) == 409 && funcs.func409 != null && typeof(funcs.func409) != 'undefined') { funcs.func409(data); } //状态409 else if (parseInt(data.status) == 500 && funcs.func500 != null && typeof(funcs.func500) != 'undefined') { funcs.func500(data); } //模式(失败) else { if (typeof(funcs.funcFail) != 'undefined' && funcs.funcFail != null) { funcs.funcFail(data); } else { // Wsw.tips.open(Wsw.msg.systemFail, 'notice'); } } //标记为允许提交 $('input[name="disableSubmit"]').val('0'); } }); } }
true
926760ba96b81c5c918ea92fd81359545f5a6dea
JavaScript
KirilSZyapkov/Syntax-Functions-and-Statements
/Syntax, Functions and Statements/aggregateElements.js
UTF-8
300
3.453125
3
[]
no_license
function aggregateElements(input) { let sum = input.reduce((a, b) => a + b, 0); let inverseSum = input.reduce((a, b) => a + (1 / b), 0); let concInput = input.join(''); console.log(sum); console.log(inverseSum); console.log(concInput); } aggregateElements([1, 2, 3])
true
9d5c6538403b0398fcc2b407b4f0f65e02779e8d
JavaScript
scared1995/avito
/src/card.js
UTF-8
5,366
2.96875
3
[]
no_license
getPagination('#myTable'); function getPagination(table) { var lastPage = 1; $('#maxRows').on('change', function (evt) {//функция для переключения кол-во отображаемых строк lastPage = 1; $('.pagination') .find('li')//находим все элементы списка на странице .slice(1, -1)//метод уменьшения или увеличения элементов .remove();//удаляем лишние цифры var trnum = 0; // обнуляем счетчик tr var maxRows = parseInt($(this).val()); // получаем максимальное кол-во строк из опции select var totalRows = $(table + ' tbody tr').length; // кол-во строк таблицы if (maxRows >= totalRows) { //если макс. кол-во строк будет больше или равно кол-во строк в таблице,то скрыаем пагинацию $('.pagination').hide(); } else { $('.pagination').show(); } $(table + ' tr:gt(0)').each(function () { trnum++; // запускаем счетчик if (trnum > maxRows) { // если номер tr больше maxRows $(this).hide(); // то скрываем их } if (trnum <= maxRows) { //если меньше $(this).show();// то показать } }); if (totalRows > maxRows) { // if tr total rows gt max rows option если кол-во строк tr больше кол-во стро select var pagenum = Math.ceil(totalRows / maxRows); // округляем вверх результат деления // номера страниц for (var i = 1; i <= pagenum;) { // для каждой страницы пагинации добавлять элеменn li $('.pagination #prev') .before( '<li data-page="' + i + '">\ <span>' + i++ + '<span class="sr-only btn btn-secondary">(current)</span></span>\ </li>' ) .show(); } } $('.pagination [data-page="1"]').addClass('active'); // добавляем класс active для первого li $('.pagination li').on('click', function (evt) { //по клику на каждую страницу evt.stopImmediatePropagation();//прекращаем текущее событие evt.preventDefault();// отменяем действие события по умолчанию var pageNum = $(this).attr('data-page'); // получаем номер страницы var maxRows = parseInt($('#maxRows').val()); // получаем максимальное кол-во строк из опции select if (pageNum == 'prev') { if (lastPage == 1) { return; } pageNum = --lastPage; } if (pageNum == 'next') { if (lastPage == $('.pagination li').length - 2) { return; } pageNum = ++lastPage; } lastPage = pageNum; var trIndex = 0; $('.pagination li').removeClass('active'); // добавляем класс active для всех li $('.pagination [data-page="' + lastPage + '"]').addClass('active'); // добавляем класс эктив по клику limitPagging(); $(table + ' tr:gt(0)').each(function () {//для каждого tr в таблице trIndex++; // if ( trIndex > maxRows * pageNum || trIndex <= maxRows * pageNum - maxRows ) { $(this).hide(); } else { $(this).show(); } //else fade in }); }); limitPagging(); }) .val(5) .change(); } //функция лимита страниц function limitPagging() { if ($('.pagination li').length > 7) { if ($('.pagination li.active').attr('data-page') <= 3) { $('.pagination li:gt(5)').hide(); $('.pagination li:lt(5)').show(); $('.pagination [data-page="next"]').show(); } if ($('.pagination li.active').attr('data-page') > 3) { $('.pagination li:gt(0)').hide(); $('.pagination [data-page="next"]').show(); for (let i = (parseInt($('.pagination li.active').attr('data-page')) - 2); i <= (parseInt($('.pagination li.active').attr('data-page')) + 2); i++) { $('.pagination [data-page="' + i + '"]').show(); } } } } $(function () {//функция добавления id для каждой строки $('table tr:eq(0)').prepend('<th> ID </th>'); var id = 0; $('table tr:gt(0)').each(function () { id++; $(this).prepend('<td>' + id + '</td>'); }); });
true
56e14d6fb5a9b65fcf0846bf114d592162e4ff60
JavaScript
EmirVelazquez/gifTastic
/assets/javascript/app.js
UTF-8
7,064
3.515625
4
[]
no_license
/*Master function that will execute only after the DOM has loaded */ $(document).ready(function () { //Global Variables //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //This array holds the original buttons displayed when DOM loads var buttonArray = ["puppy", "kitty", "parrot", "eagle", "lion", "wolf", "elephant", "badger", "racoon", "shark"]; //Functions //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //This function goes through the buttonArray, creates new buttons inside buttonholder nav, adds text to the button function populateButtons() { //This will empty the buttonHolder container in the html to prevent repeat buttons $("#buttonHolder").empty(); //This line declares a for loop and runs through the array, if true then code block executes for (var i = 0; i < buttonArray.length; i++) { //This line creates a new button and puts it inside newButton variable var newButton = $("<button>"); //This line adds a bootstrap class to the button just for style newButton.addClass("btn btn-outline-warning"); //This line will ad an ID to the button newButton.attr("id", "buttonId"); //This line will add a data-attribute to the button, will be used to pull the name from button to request API data newButton.attr("button-name", buttonArray[i]); //This line places the word inside the button newButton.text(buttonArray[i]); //This line appends a new button inside the buttonHolder nav $("#buttonHolder").append(newButton); } } //This event handler takes the users input on the text bar and puts it into the buttonArray, calls the populateButtons function $("#submitText").on("click", function (event) { //This line prevents the user from trying to submit the form, user can hit enter on keyboard or click button event.preventDefault(); //This line takes the value from textbox, makaes it lower case, trims any spaces, and places in variable 'input' var input = $("#textBar").val().toLowerCase().trim(); //This line will push the input into the existing buttonArray global variable buttonArray.push(input); //This line will empty the textbox so the user doesn't need to delete contents after every submission $("#textBar").val(""); //This line will call the populateButtons function to display the new button added populateButtons(); }); /*This function will capture the button name from the data-attribute(button-name) added to the buttons then pull Data from GHIPY API and display it on the DOM*/ function displayButtonGifs() { //This line is making a local var userRequest and placing the button name inside of said variable var userRequest = $(this).attr("button-name"); //This is my API key from GHIPY Developers var myApi = "3u7HQLGRJoAsC5pVcaCb93cYkBN01PM8"; //This is the queryURL we are using, in this case it is GHIPY API, I set a limit of 10 requested Gifs var queryURL = "https://api.giphy.com/v1/gifs/search?api_key=" + myApi + "&q=" + userRequest + "&limit=10"; //This line will clear the gifDisplay container each time user clicks new button to request gifs $("#gifDisplay").empty(); //This is the ajax call to the queryURL, will get data from GIPHY API $.ajax({ url: queryURL, method: "GET" }).then(function (response) { //This for loop will execute for the length of the data requested from GHIPY API which was limited to 10 for (var i = 0; i < response.data.length; i++) { //This line makes variable to place div inside (this will hold gif and rating) gifCard = $("<div>"); //This line give the div a class= "card" gifCard.addClass("card"); //This line places card inside container holding gifs $("#gifDisplay").append(gifCard); //This line places the gif inside a local variable (still Gif) gifStill = response.data[i].images.fixed_height_still.url; //This line places the gif inside a local variable (animated Gif) gifAnimated = response.data[i].images.fixed_height.url; //This line will make a local variable to hold the new image element that holds the displayed gifStill, data-state, data-still, data-animate gifContainer = $("<img>").attr("src", gifStill).addClass("gif").attr("data-state", "still").attr("data-still", gifStill).attr("data-animate", gifAnimated); //This line will append the gif inside the card gifCard.append(gifContainer); //This line will make a new local variable to hold the new figcaption element that holds the rating ratingContainer = $("<figcaption>Rating: " + response.data[i].rating.toUpperCase() + "</figcaption>"); //This line will display the rating after the gif gifCard.append(ratingContainer); //Test console.log(gifContainer); }; //This on click event handler replaces data-still displayed gif to data-animate when user clicks on gif(similar to pause and play) $(".gif").on("click", function () { //This line makes a variable called state that holds the current data-state the gif has when it is clicked var state = $(this).attr("data-state"); //This if statement says that if data-state inside of state variable is equal to "still" then run this code block if (state === "still") { //Gets the source url gif and swaps it to the data-animate gif $(this).attr("src", $(this).attr("data-animate")); //This sets the data-state to animate, code block ends $(this).attr("data-state", "animate"); //If state !== "still" then this code block runs } else { //Gets the source url gif and swaps it to the data-still gif $(this).attr("src", $(this).attr("data-still")); //This sets the data-state to still, code block ends $(this).attr("data-state", "still"); } }); }); } //Main Process //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //This will call the populateButtons function populateButtons(); //This click event listener is for all elements with the ID 'buttonId', will work for dynamically generated elements $(document).on("click", "#buttonId", displayButtonGifs); });
true
ac038cc43dcef949fcf1667a86062f2204e94fa8
JavaScript
fiskr/scripps
/HSP/1157/mobile-optimize.js
UTF-8
2,440
3.078125
3
[]
no_license
/* * put the following in the doc.ready * for the hello world init.js file */ //put this at the bottom of the "mobile banner" for the uber article (function(){ if(document.URL.match(/http.*?\.com.*\.html\?layout=mobile/) ){ //only execute if on a mobile page (checking the current URL) $('#sh-head').css('display','none'); //hide the heading // $('#coming-soon div.hub-tabs').css('display','none'); // only necessary if desktop has these tabs var i = 0; // iterations of the timeout var isOver = 0; // number designating how many pieces I have removed from mobile var NUM_TO_REMOVE = 4; //how many modules needing to be removed var elemCheck = setTimeout(function(){ clearInterval(elemCheck); // stop the timeout from running again i++; //iterate to tell how many times we've ran the timeout function //hide social toolbar on mobile if($('#social-toolbar')){ //if the social-toolbar exists $('#social-toolbar').ready(function(){ //and once ready $('#social-toolbar').css('display','none'); //hide the toolbar console.log('There is a social toolbar. It took: ' + i); isOver++; //iterate how many pieces have been removed }); } if($('section#social-module')){ // if social module exists, $('section#social-module').ready(function(){ // and once ready, $('section#social-module').css('display', 'none') // hide the social module $('article.builder-uber + hr').css('display', 'none'); //get rid of following hr console.log('There is a social module section. It took: ' + i); isOver++; //iterate how many pieces have been removed }); } //you get the idea now... if($('div#we-recommend')){ $('div#we-recommend').ready(function(){ $('div#we-recommend').css('display', 'none') $('div#we-recommend + hr').css('display', 'none'); // getting rid of following hr console.log('There is a we-recommend. It took: ' + i); isOver++; //iterate how many pieces have been removed }); } if($('a.see-more')){ $('a.see-more').ready(function(){ $('a.see-more').css('display','none'); console.log('There is a see-more button. It took: ' + i); isOver++; //iterate how many pieces have been removed }); } if(isOver < NUM_TO_REMOVE){ //if you still need to remove modules console.log('not over: ' + isOver); setInterval(elemCheck, 10); //start the interval again } },10); } })();
true
1e1b89475c8b7f42bb8663c0a6209e04afdac953
JavaScript
enso-ui/strings
/src/strings.js
UTF-8
1,181
3
3
[ "MIT", "ISC" ]
permissive
const diff = (first, second) => (first ?? '').split('') .filter((char, index) => char !== (second ?? '').charAt(index)) .join(''); const regEx = new RegExp(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g); const valid = string => string !== null && typeof string !== 'undefined' && string !== ''; const snake = string => (valid(string) ? string.match(regEx)?.map(word => word.toLowerCase()).join('_') : ''); const slug = (string, slug = '-') => (valid(string) && string.match(regEx) ? string.toLowerCase().match(regEx)?.join(slug) : ''); const pascal = string => (valid(string) ? string.match(regEx)?.map(word => word.toUpperCase()).join('') : ''); const lcfirst = string => (valid(string) ? string.charAt(0).toLowerCase() + string.slice(1) : ''); const lcwords = string => (valid(string) ? string.match(regEx)?.map(word => word.toLowerCase()).join(' ') : ''); const ucfirst = string => (valid(string) ? string.charAt(0).toUpperCase() + string.slice(1) : ''); const camel = string => lcfirst(pascal(string)); export { diff, snake, slug, pascal, camel, lcfirst, lcwords, ucfirst, };
true
40d6907f7201d24d36a8ee25e7825b85f986e29a
JavaScript
hendriksandy/javascript_01
/index.js
UTF-8
165
2.640625
3
[]
no_license
console.log("Hello Winc Academy") console.log("Hello Winc Academy") let name = 'andy' console.log(name) let age = "48" console.log(age) console.log(typeof age)
true
a93c25e7336b9e52ae45b0d911073b5483d52410
JavaScript
Nikhil9hac/js-tutorial
/creating.js
UTF-8
1,252
3.328125
3
[]
no_license
newli=document.createElement('li') <li>​</li>​ tnode=documenr VM2892:1 Uncaught ReferenceError: documenr is not defined at <anonymous>:1:1 (anonymous) @ VM2892:1 tnode=document.createTextNode('Nikhil') "Nikhil" nweli.classname='created1'; VM3141:1 Uncaught ReferenceError: nweli is not defined at <anonymous>:1:1 (anonymous) @ VM3141:1 newli.className='created1'; "created1" newli.id='created2'; "created2" newli.setAttribute('title','javascript_title'); undefined newli <li class=​"created1" id=​"created2" title=​"javascript_title">​</li>​ newli.appendChild(tnode) "Nikhil" newli <li class=​"created1" id=​"created2" title=​"javascript_title">​Nikhil​</li>​ newli.innerHTML='<b>`${tnode}`/b>' "<b>`${tnode}`/b>" newli <li class=​"created1" id=​"created2" title=​"javascript_title">​…​</li>​<b>​`${tnode}`/b>​</b>​</li>​ let ul=document.querySelector('ul.navi'); undefined ul <ul class=​"navi">​…​</ul>​ ul.appendChild(newli) <li class=​"created1" id=​"created2" title=​"javascript_title">​…​</li>​ newli.style.color='white'; "white" newli.style.marginTop='25px' "25px" newli.style.marginTop='5px' "5px" newli.style.marginTop='2px' "2px" newli.style.marginTop='1px' "1px"
true
d074030c54c835f51f639338b237b32cf5305019
JavaScript
unuseless/xo
/src/exo/controls/base/ExoDropdownExtension.js
UTF-8
4,040
2.546875
3
[]
no_license
import DOM from "../../../pwa/DOM"; import Core from "../../../pwa/Core"; class ExoDropdownExtension { constructor(control) { this.control = control; this.events = new Core.Events(this); } async init(){ const ctl = this.control; const btnClone = ctl.htmlElement.cloneNode(true); ctl.htmlElement = DOM.parseHTML(`<div class="exf-dropdown-cnt drop-dir-${ctl.direction || "down"}"></div>`); ctl.htmlElement.appendChild(btnClone); btnClone.addEventListener("click", e => { e.preventDefault(); }) const state = await Core.acquireState(ctl.dropdown, { process: (data, options)=>{ if(typeof(data) === "object" && Array.isArray(data.items)){ ctl.direction = data.direction || ctl.direction; ctl.dropEvent = data.event || ctl.dropEvent return data.items; } return data; } }) ctl.htmlElement.appendChild(await this.renderDropdown(state)); ctl.container.textContent = ""; ctl.container.appendChild(ctl.htmlElement); } get dropdownEvent(){ return this.control.dropEvent === "mouse" ? "mouseenter" : "click" } async renderDropdown(items) { const listElement = DOM.parseHTML(`<ul class="exf-btn-dropdown ${this.control.direction || "left"}" />`); for (const item of items) { listElement.appendChild(await this.getListItem(item)); } this.control.htmlElement.addEventListener(this.dropdownEvent, e => { const ev = new CustomEvent("beforeDropdown", { bubbles: true, cancelable: true, detail: { dropdownItems: e.target.querySelectorAll(".exf-btn-dropdown li"), buttonControl: this } }); this.control.htmlElement.dispatchEvent(ev); }); return listElement; } async getListItem(item) { let template = document.createElement("li"); let icon = `<span class="${item.icon}"></span>`; if (typeof (item.click) === "function") { item.type = "click"; } item.type = item.action ? "action" : item.type || "action"; let caption = item.caption || item.name || ""; let cls = item.class || ""; switch (item.type) { case "click": template = DOM.parseHTML( `<li class="${cls}" title="${item.tooltip || ""}"><a>${icon} ${caption}</a></li>`, ); template.addEventListener("click", item.click) break; case "action": template = DOM.parseHTML( `<li class="${cls}" data-action="${item.action}" title="${item.tooltip || ""}"><a>${icon} ${caption}</a></li>`, ); template.addEventListener("click", this.handleClick.bind(this)) break; case "event": template = DOM.parseHTML( `<li class="${cls}" data-action="${item.title}" title="${item.tooltip || ""}"><a>${icon} ${caption}</a></li>`, ); break; case "field": template = DOM.parseHTML( `<li class="${cls}" title="${item.tooltip}}"><a>${icon} ${caption}</a></li>`, ); template.querySelector("a").appendChild(await xo.form.run(item.field)); break; default: template = DOM.parseHTML( `<li class="${cls}" title="${item.tooltip}"><a href="${item.url}">${icon} ${caption}</a></li>`, ); break; } return template; } handleClick(e){ this.events.trigger("click") } } export default ExoDropdownExtension;
true
e6be6eada57b4ca00edab32543a209a3d2435421
JavaScript
tjwudi/xmirror
/js/xmirror.js
UTF-8
660
2.59375
3
[]
no_license
(function(window) { var constraints = { 'video': { mandatory: { maxWidth: 300, maxHeight: 300, minWidth: 300, minHeight: 300 } } }; function success(stream) { var videos = document.querySelectorAll('video'), attachedStream = stream; if (window.URL) { attachedStream = window.URL.createObjectURL(attachedStream); } videos = [].slice.call(videos); videos.forEach(function(video) { video.src = attachedStream; }); } function fail() { console.err('Failed to capture video stream'); } navigator.getUserMedia(constraints, success, fail); })(window);
true
401e1cd0c2bd2c71f3bb18024060ae8e3b28510f
JavaScript
aventex94/api-users
/actions/actionUser.js
UTF-8
2,238
2.59375
3
[]
no_license
const Joi = require('joi'); var empty = require('is-empty'); module.exports = { v1: { validateBodyPost: validateBodyPost, validateBodyPut: validateBodyPut, validateId: validateId, } } function validateBodyPost(req, res, next) { const schema = Joi.object().keys({ name: Joi.string().required().min(4), password: Joi.string().required().min(6), lastname: Joi.string().required(), email: Joi.string().required().email(), ProfileId: Joi.number().positive().integer().required() }); const data = req.body; Joi.validate(data, schema, (err, value) => { if (err) { res.status(422).json({ status: "error", message: "Formato de parametros invalido", data: data }); } else { next(); } }); } /** * @param {Object} req * @param {Object} res * @param {*} next * preguntar por modificaciones desde el cliente //FIXME */ function validateBodyPut(req, res, next) { const schema = Joi.object.keys({ name: Joi.string().required().min(4), password: Joi.string().required().min(6), lastname: Joi.string().required().min(4), email: Joi.string().required().email(), ProfileId: Joi.number().positive().integer().required() }); const data = req.body; Joi.validate(data, schema, (err, value) => { if (err) { res.status(422).json({ status: "error", message: "Formato de parametros invalido", data: data }); } else { next(); } }); } /** * Validates the id received from the params * @param {Object} req * @param {Object} res * @param {*} next */ function validateId(req, res, next) { const schema = Joi.object().keys({ userId: Joi.number().positive().integer().required() }); const data = req.body; Joi.validate(data, schema, (err) => { if (err) { res.status(422).json({ status: 'error', message: 'Invalid ID', data: data }) } else { next(); } }) }
true
90059d415e97b6b1bb9411c60cf28486358359a5
JavaScript
fablee1/m4-d4
/src/App.js
UTF-8
1,465
2.515625
3
[]
no_license
import WarningSign from './components/WarningSign'; import {Row, Col, Button} from 'react-bootstrap' import Fantasy from './data/fantasy.json' import History from './data/history.json' import Horror from './data/horror.json' import Romance from './data/romance.json' import Scifi from './data/scifi.json' import BookList from './components/BookList' import React, { useState } from 'react' import './App.css'; const App = () => { const [categoryName, setCategoryName] = useState(null) const [category, setCategory] = useState(null) const categories = {'Fantasy': Fantasy, 'History': History, 'Horror': Horror, 'Romance': Romance, 'Scifi': Scifi} return ( <div className="App"> <WarningSign text="HELLO" /> <Row className="mb-5 d-flex justify-content-center"> { Object.keys(categories).map((cat, i) => { return <Col key={i} xs={6} sm={4} md={2} className="d-flex justify-content-center px-4 mb-2"> <Button variant="success" className="w-100" onClick={() => {setCategoryName(cat); setCategory(categories[cat])}}>{cat}</Button> </Col> }) } </Row> <Row className="d-flex justify-content-center mb-4 text-center"> { categoryName ? <h2>{categoryName}</h2> : <h2>Select A Category To View Books!</h2> } </Row> { category && <BookList books={category} /> } </div> ); } export default App;
true
a6d8ea19a7a22a121b4ffeeeb04b7ff596930de5
JavaScript
roymcfarland/refactoru-handlebars-store
/main.js
UTF-8
2,144
2.953125
3
[]
no_license
////////////////////////////////// //////// PRODUCTS DATA.JS //////// ////////////////////////////////// var productsData = { productsList: [ { title: "Super Mario World", cost: 11.25, image: "http://ecx.images-amazon.com/images/I/31QRKPQ24FL._AA160_.jpg", details: { players: "1-2", levels: "74 different areas in 7 different castles" } }, { title: "Donkey Kong Country", cost: 12.45, image: "http://ecx.images-amazon.com/images/I/31ACJPWHBVL._AA160_.jpg", sale: 5.00, details: { characters: "Donkey Kong and Diddy Kong", enemies: "Kremlings" } }, { title: "Street Fighter II", cost: 4.94, image: "http://ecx.images-amazon.com/images/I/51aqQ0RJtxL._AA160_.jpg", details: { description: 'Get dirty with the nasty street fighters in the multi-player Street Fighter II.' } } ] }; $(document).on('ready', function() { // Get the HTML content of our template and store it // as a JavaScript variable var templateSource = $('#product-template').html(); // console.log(templateSource); // Have handlebars compile this sources into a // reusable template function var template = Handlebars.compile(templateSource); // console.log(template); // Use the template to generate new HTML content var outputHTML = template(productsData); // console.log(outputHTML); // Append outputHTML to the page $('#product-container').append(outputHTML); $(document).on('click', '.addToWishList', function(e){ e.preventDefault(); var newItemTitle = $(this).siblings('.title').text(); var newObject = { title: newItemTitle }; var element = wishListItems(newObject); $('#wishlist').append(element); }); var wishlistSource = $('#wishlist-template').html(); // console.log(wishlistSource); var wishListItems = Handlebars.compile(wishlistSource); // console.log(wishListItems); $(document).on('click', '.removeFromWishList', function(e){ e.preventDefault(); $(this).closest('.wishlist-list').remove(); }); });
true
9252ea677ce863d2c9583bab376b04ac8c70a63e
JavaScript
cmccarthy15/GraceShopper
/server/api/products.js
UTF-8
3,507
2.6875
3
[]
no_license
const router = require('express').Router() const { Product, Review } = require('../db/models') module.exports = router router.get('/', (req, res, next) => { Product.findAll({ include: [{ all: true }] }) .then(products => res.json(products)) .catch(next) }) router.post(`/`, (req, res, next) => { Product.create(req.body) .then(product => { product.setCategories(req.body.categories) res.json(product) }) .catch(next) }) router.get('/:productId', (req, res, next) => { Product.findById(req.params.productId) .then(product => res.json(product)) .catch(next) }) router.put(`/:productId`, (req, res, next) => { Product.findById(req.params.productId) .then(product => { product.update({ name: req.body.name || product.name, image: req.body.image || product.image, price: req.body.price || product.price, description: req.body.description || product.description, stock: req.body.stock || product.stock }) .then(updatedProduct => { updatedProduct.setCategories(req.body.categories) res.sendStatus(200) }) }) .catch(next) }) router.delete(`/:productId`, (req, res, next) => { Product.findById(req.params.productId) .then(product => { product.destroy() .then(res.sendStatus(200)) .catch(next) }) }) //all reviews related routes //momo started writing from here router.get("/:productId/reviews", (req, res, next) => { return Review.findAll({ where: { productId: req.params.productId } }) .then(reviews => res.json(reviews)) .catch(next); }); //get one product with reviews?? // router.get("/", (req, res, next) => { // return Product.findById(req.params.id, { // include: [{ model: Review, as: "review" }] // }) // .then(product => res.json(product)) // .catch(next); // }); //post a review to a product router.post("/:id/reviews", (req, res, next) => { console.log('plz') return Product.findById(req.params.id).then(product => { if (!product) { res.sendStatus(404); } else { let review = req.body; review.userId = req.user.id; review.productId = req.params.id; console.log(review, 'hi back') return Review.create(review).then(createdReview => res.json(createdReview)); } }); }); // should eventually put in a put and delete request for admins and users to edit or delete their reviews right??? //meh ill just put the beginnings in, since the component may not handle it. //edit a review of a product router.put("/:id/reviews",(req, res, next) => { return Product.findById(req.params.id).then(product => { if (!product) { res.sendStatus(404); } else { let review = req.body; return Review.update(review).then(updatedReview => res.json(updatedReview)); } }); }); router.delete( "/:productId/reviews/:reviewId", (req, res, next) => { return Review.findById(req.params.reviewId).then(product => { if (!product) { res.sendStatus(404); } else { return product.destroy().then(() => res.sendStatus(204)); } }); } ); router.get(`/search/:searchTerm`, (req, res, next) => { const searchTerm = req.params.searchTerm Product.findAll({ where: { $or: { name: { $like: '%' + searchTerm + '%' }, description: { $like: '%' + searchTerm + '%' } } } }) .then(results => res.json(results)) })
true
c94fb4a84f4139b134c1330b064295e769dd32b4
JavaScript
monmaheen/SampleTestCode
/Todo-List-Project/Colors.js
UTF-8
2,591
3.4375
3
[]
no_license
var numSquares = 6; var squares = document.querySelectorAll(".square"); var color = generateRandom(numSquares); var pickColor = randomColor(); var colorDisplay = document.getElementById("colorDisplay"); var answerSpan = document.querySelector("#answer") var helement = document.querySelector("h1"); var reset = document.getElementById("reset"); var easy = document.getElementById("easy"); var hard = document.getElementById("hard"); colorDisplay.textContent = pickColor; reset.addEventListener("click",function(){ color = generateRandom(numSquares); pickColor = randomColor(); colorDisplay.textContent = pickColor; for (var i = 0; i<squares.length;i++) { squares[i].style.background = color[i]; } helement.style.backgroundColor = "steelblue"; }) easy.addEventListener("click",function(){ this.classList.add("blue-class"); hard.classList.remove("blue-class"); numSquares = 3; color = generateRandom(numSquares); pickColor = randomColor(); colorDisplay.textContent = pickColor; for (var i = 0; i<(squares.length);i++) { if(color[i]){ squares[i].style.background = color[i]; } else{ squares[i].style.display = "none"; } } }) hard.addEventListener("click",function(){ this.classList.add("blue-class"); easy.classList.remove("blue-class"); numSquares = 6; color = generateRandom(numSquares); pickColor = randomColor(); colorDisplay.textContent = pickColor; for (var i = 0; i<(squares.length);i++) { squares[i].style.background = color[i]; squares[i].style.display = "inline"; } }) for (var i = 0; i<squares.length;i++) { squares[i].style.background = color[i]; squares[i].addEventListener("click",function(){ if (this.style.backgroundColor === pickColor) { answerSpan.textContent = "Correct!"; colorChange(pickColor) helement.style.backgroundColor = pickColor; } else { answerSpan.textContent = "Try Again!"; this.style.backgroundColor = "#232323"; } }); } function colorChange(color){ for (var i =0; i<squares.length;i++) { squares[i].style.background = color; } } function randomColor(){ var random = Math.floor(Math.random() * color.length) return color[random]; } function generateRandom(num){ var arr = []; for (var i =0; i < num ; i++){ arr.push(randomColorGenerator()); } return arr; } function randomColorGenerator(){ var r = Math.floor(Math.random() * 256); var g = Math.floor(Math.random() * 256); var b = Math.floor(Math.random() * 256); return "rgb(" + r +", " + g + ", " + b +")"; }
true
08ab9ef0cecf701972c5b69f972bc4471b651e1f
JavaScript
grmrh/Word-Guess
/index.js
UTF-8
3,476
3.453125
3
[]
no_license
var inquirer = require('inquirer'); var Word = require('./word'); var colors = require('colors'); // random words generator https://www.randomlists.com/random-words const randomWords = [ 'tranquil', 'middle', 'wretched', 'unwieldy', 'detail', 'fluffy', 'delicate', 'shallow', 'jittery', 'eminent', 'pencil', 'toothpaste', 'knowledgeable', 'selfish', 'pathetic', 'stone', 'hammer', 'overjoyed', 'scrape', 'comb', 'purple', 'toes', 'acidic', 'homeless', 'perpetual', 'evanescent', 'wealth', 'polite', 'dizzy', 'moaning', 'bashful', 'settle', 'experience', 'elite', 'crayon', 'apparel', 'torpid', 'piquant', 'sprout', 'health', 'stick', 'absent', 'coherent' ]; const NUMBER_OF_TRIAL = 15; const question = [ { type: 'input', name: 'ych', message: 'Guess a letter! ' } ]; const wantToPlayQuestion = [ { type: "confirm", name: "continueToPlay", message: "Continue to play?", default: true } ] // contructor function function Game() { this.Word = null; this.PlayingWord = null; this.remainingNumTrials = null; } Game.prototype.prework = function() { // between 0 and 42, integer 0, 1, 2, ...., 42 var randomlyChosenIndex = Math.floor(Math.random() * Math.floor(randomWords.length)); // from 0 to 42 var word = randomWords[randomlyChosenIndex]; var wLength = word.length; var playingWord = Array(wLength).fill('_').join(''); var numTrial = NUMBER_OF_TRIAL; console.log(randomlyChosenIndex, word, playingWord, numTrial); this.Word = (word && new Word(word)) || null; this.PlayingWord = (playingWord && new Word(playingWord)) || null; this.remainingNumTrials = numTrial || null; } // shared mothod Game.prototype.play = function() { var Word = this.Word && this.Word.Letters; var PlayingWord = this.PlayingWord && this.PlayingWord.Letters; var remainingNumTrials = this.remainingNumTrials; var matched = false; inquirer.prompt(question) .then(ans => { var matched = this.PlayingWord.setMatched(ans.ych, Word); this.remainingNumTrials --; if (this.remainingNumTrials <= 0) { console.log("Sorry, the allowed number of trials has been exhausted. Exit the game!".yellow); process.exit(0); } else if (PlayingWord.every(e => e.single !== '_')) { console.log(`You got it right! - ${this.PlayingWord.wordString()}`.inverse.green); // ask if the user want to continue to play inquirer.prompt(wantToPlayQuestion) .then(ans => { if (['Y', 'y', 'Yes', 'yes', 'YES', true].some(e => e == ans.continueToPlay)) { // OK. play again this.prework(); this.play(); } else { console.log("Good bye!"); process.exit(0); } }); } else if(PlayingWord.some(e => e.single === '_') && this.remainingNumTrials > 0) { console.log(this.PlayingWord.wordString()); console.log(matched ? 'Correct!!!'.cyan : 'Not correct!!!'.red, `${this.remainingNumTrials} trials left.`); this.play(); } }); }; // Let game start var Game = new Game(); Game.prework(); Game.play();
true
5906ba429560862518729b52d3dcdd6563072f72
JavaScript
dadaa1/reactall
/src/shijian/throttle.js
UTF-8
565
3.203125
3
[]
no_license
// 定时器实现,缺点:当停止后最后还会调用一次,不好 function throttle(method, wait) { let timeout = null; return function() { if (!timeout) { timeout = setTimeout(() => { method.apply(this, arguments); timeout = null; }, wait); } }; } // 时间戳实现 function throttle1(method, wait) { let prev = new Date().getTime(); return function() { const now = new Date().getTime(); if (now - prev >= wait) { method.apply(this, arguments); prev = new Date().getTime(); } }; }
true
6b300389cc05d22723db2b07a8dd7cd71c282371
JavaScript
burakyetistiren/to-do-list-js-es6
/src/ListItem.js
UTF-8
406
2.578125
3
[]
no_license
import {Engine} from './Engine.js'; export class ListItem{ constructor(description = "", id){ // changed this.description = description; // changed this.id = id; const en = new Engine(); // changed en.setSearchBar(); } setDescription(desc){ this.description = desc; } setId(id){ this.id = id; } getDescription(){ return this.description; } getId() { return this.id; } }
true
74e3295643a13f1fc162d020dd31c2f25d1961ba
JavaScript
llxxll12345/projects
/greedy.js
UTF-8
8,998
2.703125
3
[]
no_license
function $(str) { return document.getElementById(str); } //get from document function $tag(str,target) { target = target || document; return target.getElementsByTagName(str); } //get from tag //generate a 2D array function multiArray(m, n) { var arr = new Array(n); for (var i = 0; i < m; i++) arr[i] = new Array(m); return arr; } //print info //get info function getText(target) { if (document.all) return target.innerText; else return target.textContent; } var std_v = 20; var width = 20; var height = 20; var Exclaim = ["Good Job!","Excellent!","Amazing!","Extraodinary!","orz Lord!"]; var len = 5; var speed; var Grids = multiArray(width,height); var map; var snake; var btnStart; var topScore = len; var snakeTimer; var brakeTimers = []; var acceleratorTimers = []; var directkey; // btnPause.setAttribute("disabled", true); window.onload = function(){ btnStart = $("btnStart"); Create_Grid(); document.onkeydown = attachEvents; // attach to direction event btnStart.onclick = function (e) { btnStart.blur(); //blur focus start(); //start game btnStart.setAttribute("disabled", true); //btnPause.removeAttribute("disabled"); btnStart.style.color = "#aaa"; //change of the starting button //btnPause.style.color = "#fff"; } } //add objects function addObject(name){ var p = pointGenerator(); map[p[0]][p[1]] = name; Grids[p[0]][p[1]].className = name; } function add_ba(){ var num = numGenerator(1, 5); for (var i = 1; i <= num; i++){ brakeTimers.push(window.setTimeout(function(){addObject("brake"),1000})); acceleratorTimers.push(window.setTimeout(function (){addObject("accelerator"), 1000}));//? } } //clear off function clear(){ for (var y = 0; y < Grids.length; y++){ for (var x = 0; x < Grids[y].length; x++){ Grids[x][y].className = ""; } } } //generate a ramdom point function pointGenerator(startX, startY, endX, endY) { startX = startX || 0; startY = startY || 0; endX = endX || width; endY = endY || height; var temp = []; var x = Math.floor(Math.random() * (endX - startX)) + startX; var y = Math.floor(Math.random() * (endY - startY)) + startY; if (map[x][y]) return pointGenerator(startX, startY, endX, endY); temp[0] = x; temp[1] = y; return temp; } //generate random numbers function numGenerator(start, end) { return Math.floor(Math.random() * (end - start)) + start; } //start the game function start() { len = 3; speed = 10; directkey = 39; map = multiArray(width,height); snake = new Array(); clear(); Create_snake(); for (var i = 1; i <= 10;i ++) addObject("food"); addObject("trap"); walk(); add_ba(); } //Create Grids function Create_Grid(){ var body = $tag("body")[0]; var table = document.createElement("table"); var tbody = document.createElement("tbody") for(var j = 0; j < height; j++){ var col = document.createElement("tr"); for(var i = 0; i < width; i++){ var row = document.createElement("td"); Grids[i][j] = col.appendChild(row); } tbody.appendChild(col); } table.appendChild(tbody); $("snakeWrap").appendChild(table); } //Construct A Sanke function Create_snake(){ var pointer = pointGenerator(len-1, len-1, width/2); for(var i = 0; i < len; i++) { var x = pointer[0] - i, y = pointer[1]; snake.push([x,y]); map[x][y] = "cover"; } } //Add keyboard event function attachEvents(enter){ enter = enter || event; directkey = Math.abs(enter.keyCode - directkey) != 2 && enter.keyCode > 36 && enter.keyCode < 41 ? enter.keyCode : directkey; return false; } //Timer of walking function walk(){ if(snakeTimer) window.clearInterval(snakeTimer); snakeTimer = window.setInterval(move, Math.floor(3000 / speed)); } //moving the snake function move(){ //get the target point var headX = snake[0][0], headY = snake[0][1]; switch(directkey){ case 37: headX = (headX - 1 + width) % width; break; case 38: headY = (headY - 1 + height) % height; break; case 39: headX = (headX + 1 + width) % width; break case 40: headY = (headY + 1 + height) % height; break; } //meet itself or too short, end game if (map[headX][headY] == "cover" || len <= 2) { alert("GAME OVER >_<"); if (getText($("score")) * 1 < len) alert("Your Score is " + len * 10); $("score").innerHTML = Math.max(getText($("score")), len * 10); btnStart.removeAttribute("disabled"); btnStart.style.color = "#000"; //change Start button window.clearInterval(snakeTimer); // return; for (var i = 0; i < brakeTimers.length; i++) window.clearTimeout(brakeTimers[i]); for (var i = 0; i < acceleratorTimers.length; i++) window.clearTimeout(acceleratorTimers[i]); } //level up if(len % 7 == 0 && speed < 60 && map[headX][headY] == "food") { speed += 5; //document.onkeydown = alert("Speed up! Avoid traps!\ _ /"); walk(); //document.onkeydown = attachEvents; } //slower, get a break if(map[headX][headY] == "brake") { speed = 5; //document.onkeydown = alert("Slow down for a moment!~_~"); walk(); //document.onkeydown = attachEvents; //attachEvents(enter); //move(); } //Meet an accelerator if(map[headX][headY] == "accelerator") { speed += 20; //console.log("You meet an accelerator!\ _ /"); walk(); //document.onkeydown = attachEvents; //attachEvents(enter); } //add Trap if(len % 7 == 0 && len < 60 && map[headX][headY] == "food") { addObject("trap"); } //Excalim //if(len <= 50 && len % 10 == 0){ //var cheer = Exclaim[len/10-1]; // trace(cheer); //} //Eat and gain length if(map[headX][headY] != "food"){ var lastX = snake[snake.length-1][0]; var lastY = snake[snake.length-1][1]; map[lastX][lastY] = false; Grids[lastX][lastY].className = ""; snake.pop(); }else{ map[headX][headY] = false; //trace("Gain food!"); addObject("food"); } //meet traps and lose length if (map[headX][headY] == "trap"){ var lastX = snake[snake.length - 1][0]; var lastY = snake[snake.length - 1][1]; map[lastX][lastY] = false; Grids[lastX][lastY].className = ""; snake.pop(); //trace("Oh no!You meet a trap!"); } snake.unshift([headX, headY]); map[headX][headY] = "cover"; Grids[headX][headY].className = "cover"; len = snake.length; } /*function Pause(obj, mytime) { if (window.eventList == Null) window.eventList = new Array(); var index = -1; for (var i = 0; i < window.eventList.length; i++) { if (window.eventList[i] == null) { window.eventList[i] = obj; ind = i; break; } } if (ind == -1) { ind = window.eventList.length; window.eventList[ind] = obj; } setTimeout(resume, mytime); }*/
true
b38bfec721b72cc4789284af6f03e9011a9f7292
JavaScript
EduardoDuQuesne/exercise-sandwich-maker
/javascripts/cheese.js
UTF-8
266
2.765625
3
[]
no_license
/*jshint esversion: 6 */ let cheesePrices = { swiss: 1, american: 1, muenster: 1.25, gouda: 1.25, havarti: 1.25 }; const addCheese = function(cheeseSelection) { return cheesePrices[cheeseSelection]; }; module.exports = { addCheese };
true
c6d32d36450f76bf2b566038ec64513518d64112
JavaScript
Automedon/CodeWars-7-kyu-Soluitions
/Thinkful - Number Drills: Rømer temperature.js
UTF-8
754
3.984375
4
[ "MIT" ]
permissive
/* Description: You're writing an excruciatingly detailed alternate history novel set in a world where Daniel Gabriel Fahrenheit was never born. Since Fahrenheit never lived the world kept on using the Rømer scale, invented by fellow Dane Ole Rømer to this very day, skipping over the Fahrenheit and Celsius scales entirely. Your magnum opus contains several thousand references to temperature, but those temperatures are all currently in degrees Celsius. You don't want to convert everything by hand, so you've decided to write a function, celsius_to_romer() that takes a temperature in degrees Celsius and returns the equivalent temperature in degrees Rømer. For example: celsius_to_romer(24) should return 20.1. */ function celsiusToRomer(temp) { return temp*21/40+7.5 }
true
2a00dbd799fa2c012646636d0e13e927de4a0f3f
JavaScript
tolustar/user-story
/src/pages/viewStory/ViewStory.js
UTF-8
3,307
2.546875
3
[]
no_license
import React, { useState, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useHistory, useParams } from "react-router-dom"; import "./ViewStory.css"; import LogoutButton from "./../../components/LogoutButton"; import allActions from "./../../store/actions"; export const acceptOrRejectStory = (stories, value, id) => { let getIndex = stories.findIndex((item) => item.id === parseInt(id)); stories[getIndex].status = value; return stories; }; export default function ViewStory() { const history = useHistory(); let { id } = useParams(); const currentUser = useSelector((state) => state.currentUser); const allStories = useSelector((state) => state.stories); const dispatch = useDispatch(); const [story, setStory] = useState([]); const getStory = () => { if (currentUser.details.role !== "Admin") { history.push("/"); } let retrieveStory = allStories.filter( (item) => item.id === parseInt(id) )[0]; setStory(retrieveStory); }; const updateStory = (value) => { let result = acceptOrRejectStory(allStories, value, id); dispatch( allActions.storyActions.createStory( JSON.parse(JSON.stringify(result)) ) ); history.push("/stories"); }; useEffect(() => { getStory(); }, []); // eslint-disable-line react-hooks/exhaustive-deps return ( <div className="list-stories"> <LogoutButton /> <div className="container"> <div className="row"> <div className="col-md-2"></div> <div className="col-md-8"> <div className="list-stories-table-container d-flex flex-column align-items-center"> <h4 className="mt-2 mb-4">View Story - {story.summary} </h4> <div className="d-flex flex-column mb-3 mt-4"> <div className="mb-3"> <strong>Summary</strong> - {story.summary} </div> <div className="mb-3"> <strong>Description</strong> - {story.description} </div> <div className="mb-3"> <strong>Type</strong> - {story.type} </div> <div className="mb-3"> <strong>Complexity</strong> - {story.complexity} </div> <div className="mb-3"> <strong>Estimated Hours</strong> -{story.estimatedHrs} </div> <div className="mb-3"> <strong>Cost</strong> - {story.cost} </div> <div className="mb-3"> <strong>Status</strong> - {story.status === null ? "Waiting for review" : story.status } </div> </div> <div> <button className="btn btn-success mr-3" onClick={() => updateStory("accepted")}> Accept </button> <button className="btn btn-danger" onClick={() => updateStory("rejected")}> Reject </button> </div> </div> <div className="col-md-2"></div> </div> </div> </div> </div> ); }
true
eb63ed5fa2f206988a4d358b326e2f94ac54161f
JavaScript
2pavel/calc
/calc.js
UTF-8
2,337
3.625
4
[]
no_license
// Basic operation functions function add(a, b) { return Number(a) + Number(b); } function subtract(a, b) { return Number(a) - Number(b); } function multiply(a, b) { return Number(a) * Number(b); } function divide(a, b) { return Number(a) / Number(b); } function sqroot (a) { return Math.sqrt(Number(a)); } function operate(a, b, op) { switch(op) { case '+': return add(a, b); case '-': return subtract(a, b); case '÷': return divide(a, b); case 'squareRoot': return sqroot(a, b); case '*': return multiply(a, b); default: return '69XDDD420'; } } // Selectors here const numbtns = document.querySelectorAll('.numbtn'); const opbtns = document.querySelectorAll('.func'); const display = document.getElementById('screenbar'); const equals = document.getElementById('equals'); const Clear = document.getElementById('clear'); const sqr = document.getElementById('sqroot'); // Operation variables initialization let op = undefined; let a = ''; let b = ''; let displayValue = ''; numbtns.forEach((button) => { button.addEventListener('click', () => { (displayValue += button.innerText).toString(); display.innerText = displayValue; if (a === '') { a = button.innerText; } else if (op === undefined) { a = display.innerText; } else if (b === '') { b = button.innerText; } else { (b += button.innerText).toString(); } }); }); opbtns.forEach((button) => { button.addEventListener('click', () => { a = displayValue; (op = button.innerText).toString(); displayValue = ''; }); }); sqr.addEventListener('click', () => { display.innerText = sqroot(a); }); equals.addEventListener('click', () => { display.innerText = ''; displayValue = ''; display.innerText = operate(a, b, op); if (a === '' || b === '' || op === undefined) { console.log('That\'s not how you use calculator'); } console.log(a); console.log(b); console.log(op); a = ''; b = ''; }); function clear() { displayValue = ''; display.innerHTML = ''; op = undefined; a = ''; b = ''; } Clear.addEventListener('click', clear);
true
8b39221671415d3d701ed5ef0c5c1720c8db44cd
JavaScript
doctape/doctape-client-js
/src/wrapper-browser.js
UTF-8
2,422
2.53125
3
[ "MIT" ]
permissive
window.Doctape = function (config) { var self = new DoctapeSimple(config); self.prototype = DoctapeSimple; /* ** EVENT ARCHITECTURE */ (function () { var evcb = {}; this.emit = function (event, data) { setTimeout(function () { var i, l; if (evcb[event] !== undefined && (l = evcb[event].length) > 0) { for (i = 0; i < l; i++) { if (typeof evcb[event][i] === 'function') { evcb[event][i](data); } } } }, 0); }; this.subscribe = function (event, fn) { if (evcb[event] === undefined) { evcb[event] = [fn]; } else if (evcb[event].indexOf(fn) === -1) { evcb[event].push(fn); } }; this.unsubscribe = function (event, fn) { var idx; if (evcb[event] !== undefined && (idx = evcb[event].indexOf(fn)) !== -1) { evcb[event].splice(idx, 1); } }; }).call(self.core.env); /* ** REQUEST ARCHITECTURE */ self.core.env.req = function (options, cb) { var header, headers = options.headers || {}, method = options.method || 'GET', url = options.protocol + '://' + options.host + (options.port ? ':' + options.port : '') + options.path, xhr = new XMLHttpRequest(); xhr.open(method, url); for (header in headers) { xhr.setRequestHeader(header, headers[header]); } xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.responseText !== null) { cb(null, xhr.responseText); } else { cb(xhr.statusText); } } }; xhr.send(options.postData); }; var getHashObject = function () { var i, obj = {}, part, parts = window.location.hash.substr(1).split('&'); for (i = 0; i < parts.length; i++) { part = parts[i].split('='); obj[decodeURIComponent(part[0])] = decodeURIComponent(part[1]); } return obj; }; self.run = function (cb) { var hash = getHashObject(); if (typeof hash.access_token === 'undefined' && typeof hash.error === 'undefined') { window.location = self.authURL + '&state=' + encodeURIComponent(hash.state); } else { self.useToken({ token_type: 'Bearer', expires_in: 3600, access_token: hash.access_token }, cb); } }; self.init(); return self; };
true