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
98bf3ce088180693d5b561522d31a64e1989872b
JavaScript
Tanner132/Edabit-Questions
/app.js
UTF-8
386
3.4375
3
[]
no_license
// question 1. function largestSwap(num) { let reverseN = num.toString().split("").reverse().join("") if (reverseN > num){ return false; } else if (reverseN <= num){ return true; } } //question 2 const isSpecialArray = a => a.every((v, i) => v%2 == i%2); //question 3 function formatNum(num) { return num.toLocaleString() }
true
6addd23dd733625eef239a89f928900889903c93
JavaScript
TenHiderovich/backend-project-lvl1
/src/games/prime.js
UTF-8
688
3.3125
3
[]
no_license
import gameEngine from '..'; import getRandomValue from '../getRandomValue'; const isPrime = (num) => { if (num < 2) { return false; } if (num === 2) { return true; } let i = 2; const limit = Math.sqrt(num); while (i <= limit) { if (num % i === 0) { return false; } i += 1; } return true; }; const introductoryQuestion = 'Answer "yes" if given number is prime. Otherwise answer "no".'; const getGameData = () => { const question = getRandomValue(2, 100); const correctAnswer = isPrime(question) ? 'yes' : 'no'; return { question, correctAnswer, }; }; export default () => gameEngine(introductoryQuestion, getGameData);
true
d450ae0d8b81c0f473a1fe4d370a29a687a9a403
JavaScript
Gloryofthe80s/Backbone_task.js
/app/scripts/main.js
UTF-8
814
2.84375
3
[]
no_license
$(document).ready(function() { //initialize Parse Parse.initialize("wyONZpwmaFf4u7zRyXDHgeY0A332GZC3DMuSZvjk", "vmQqYkifJtvCWkMuhZ4gS720S1ytSmb1G7jtCRD2"); //create the task collection window.tasksCollection = new TasksCollection(); // event binder for adding tasks $('#create-new-task-input').on('keypress', function(e) { //on enter keypress, so long as the input isn't empty if(e.which == 13 && $(this).val() != '') { var newTask = { name: $('#create-new-task-input').val(), }; // construct the task object and add it to the collection var aNewTask = new Task( newTask ); tasksCollection.add( newTask ); aNewTask.save(); //clear the text input $(this).val(''); }}); }) // end $(document).ready
true
97606347b9dc6630a130541fd11eeaa480872672
JavaScript
NickzzDev/discord-avatar-command
/v12.js
UTF-8
690
2.53125
3
[]
no_license
const Discord = require('discord.js'); exports.run = async(client, message, args) => { const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.member; const embed = new Discord.MessageEmbed() .setFooter(`PFP requested by ${message.author.tag}`) .setColor(`0x00f8ff`) .setTimestamp() .setTitle(`${member.user.tag} Profile Picture`) .setDescription(`[View Avatar Here](${member.user.displayAvatarURL({ dynamic: true, size: 4096 })}) \n\nMade by [Nickzz](https://github.com/NickzzDev/)`) .setImage(member.user.displayAvatarURL({ dynamic: true })) message.channel.send(embed) }
true
132c63dcaa2f7ebea11ba6bf3890cd9e831429d4
JavaScript
rbodell/chevalier_rebecca_sdi
/GoToTrainingWeek2/Chevalier_Rebecca_Expressions_Assignment/js/script.js
UTF-8
3,973
3.71875
4
[]
no_license
/* Rebecca Chevalier SDI Section #1 Expressions Assignment 09/10/2015 */ // Letting the user know what to do alert("Hi there! I am trying to figure out how much money you have left from your paycheck after you pay your cable bill! "); //Asking the user what cable company they use var cablecompany = prompt("What cable company do you use? "); //Fun comment to let the user know I retained the information alert("Oh, I use "+cablecompany+" too!"); //console.log console.log("Name of user's cable company is "+cablecompany+"."); //Ask the user how much their cable bill is var cablebill = prompt ("And how much is your bill with "+cablecompany+" each month? \n(TIP: Do NOT use the dollar sign!)"); //Funny comment to let the user know I retained more information alert("Wow... $"+cablebill+" is a lot of money just to watch Game of Thrones!"); //console.log the value for the cable bill console.log("Amount of user's cable bill is $"+cablebill+"."); //Ask the user how much money they make a month var takehomepay = prompt ("I'm going to calculate how much money you'll have left over after your "+cablecompany+" bill now. How much is your monthly take home pay?"); //console.log the value of the take home pay console.log("Amount of user's take home pay is $"+takehomepay+"."); //Funny comment to let the user know I retained the information alert("Yikes. Only $"+takehomepay+"? Hope you graduate Full Sail...") //Confirming begining of calculation alert("Ok! Let's calculate!"); // Figure out how much you have left over after cable bill charge var amountleftover = (takehomepay - cablebill); //console.log to track the amount left over console.log("Amount left over after cable bill is removed from salary is $"+amountleftover+"."); //Letting the user know the result alert("So after your "+cablecompany+" bill of $"+cablebill+", you will have $"+amountleftover+" to spend on other things!"); //Adding in user's electric bill alert("While we're at it, let's add in your electric bill and water bill!"); var electricbill = prompt ("How much is your electric bill?"); alert("Great. So, your electric bills is $"+electricbill+". Lets continue."); //console.log tracking the electric bill value console.log("The amount of the user's electric bill is $"+electricbill+"."); //Adding in user's water bill var waterbill = prompt ("What is the amount of your water bill?"); alert("Okay. So you spend $"+waterbill+" on water a month."); //console.log tracking the water bill value console.log("The amount of the user's water bill is $"+waterbill+"."); //Calculating total monthly utility bill //In the form of an array var bills = [cablebill, waterbill, electricbill]; var totalmonthlybills = parseInt(bills[0]) + parseInt(bills[1]) + parseInt(bills[2]); alert("Your total monthly bills amount to $"+totalmonthlybills+"."); console.log("User's monthly bills amount to $"+totalmonthlybills+"."); //Letting user know we will calculate the total annual cost of bills alert("Since you are here, let's see how much your annual cost of utilities will be.") //Function for calculating yearly total charge of monthly bill var yearlybillcharge = (totalmonthlybills *= 12); //Calculating utility bills for the year alert("Your annual utility bills will cost you $"+yearlybillcharge+", for a total of 12 months."); //Adding the amount of annual salary to the console console.log("The user's annual utility cost will be $"+yearlybillcharge+" for a total of 12 months."); var annualsalary = (takehomepay *= 12); console.log("The user's annual salary will be $"+annualsalary+"."); //Letting the user know their annual salary alert("By the way... your annual salary is $"+annualsalary+". \n(PRO TIP: Stay in school)"); //Funny alert hoping the user's annual salary can coveer the cost of the annual utilities alert("I hope your annual salary of $"+annualsalary+" is enough to cover your yearly utility cost of $"+yearlybillcharge+"!");
true
e27b182b5df7978c69395725f763b200737c632a
JavaScript
Anntex/workshop_interactive_media
/dns_lookup/dns_lookup.js
UTF-8
785
3.15625
3
[]
no_license
/** * This file describes the functionality to lookup an web url using the * dns module of the node.js API. * * @author dennis grewe [[email protected]] * @see http://nodejs.org/api/dns.html */ var dns = require('dns'); /* the lookup method resolves a domain into the IPv4 or IPv6 record.*/ dns.lookup('www.hdm-stuttgart.de', function(err, address) { if (err) throw err; /* log the founded address to console*/ console.log('One of the ip addresses of www.hdm-stuttgart.de: ' + address.toString()); /* to test the address, do reverse operations and resolve the domain of the address*/ dns.reverse(address, function(err, domains) { if (err) throw err; console.log('Reverse test for ' + address.toString() + ': ' + JSON.stringify(domains)); }); });
true
ff51a6ed88a0b518437b7108ab1611fb30714018
JavaScript
BryantCabrera/leetCode
/325_maximumSizeSubarraySumEqualsK.js
UTF-8
776
4
4
[]
no_license
// Maximum Size Subarray Sum Equals K // https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/ // 325. Maximum Size Subarray Sum Equals k // Medium // 1152 // 37 // Add to List // Share // Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead. // Note: // The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range. // Example 1: // Input: nums = [1, -1, 5, -2, 3], k = 3 // Output: 4 // Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest. // Example 2: // Input: nums = [-2, -1, 2, 1], k = 1 // Output: 2 // Explanation: The subarray [-1, 2] sums to 1 and is the longest. // Follow Up: // Can you do it in O(n) time?
true
ab72522b862ecc6f9b5b8b27794d1012e6d155d1
JavaScript
D-Y-A-G/DA_CODE_QUIZ_TIME_WEEK4
/script.js
UTF-8
4,791
4.28125
4
[]
no_license
// CREATING QUIZ start by setting variables and start with click button and timer function // User is presented with a Start button and a title of Quiz - work on style of button // When user clicks start quiz the timer starts and user is presented with a multiple choice question var countDown = document.querySelector(".timer"); let timeLeft = 60; //const questions = document.createElement("div"); let questions = document.getElementById("questions"); let answers = document.getElementById("answers"); var quizStart = document.getElementById("startquizbtn"); quizStart.addEventListener("click", quizTimer); function quizTimer() { var timer = setInterval(function () { timeLeft--; countDown.textContent = timeLeft; if (timeLeft === 0) { clearInterval(timer); } }, 1000); quizStart.style.visibility = "hidden"; } //need to hide button element after being clicked and add points to correct questions // Questions variables changed to const because value needs to be the same const quizQuestion1 = "In what year was JavaScript Developed?"; const quizQuestion2 = "Which built-in method calls a function for each element in the array?"; const quizQuestion3 = "Which of the following function of Array object removes the last element from an array and returns that element?"; // creating sections to store questions const question1Section = document.createElement("div"); const firstQuestion = document.createElement("ul"); firstQuestion.textContent = quizQuestion1; question1Section.append(firstQuestion); questions.append(question1Section); const question2Section = document.createElement("div"); const secondQuestion = document.createElement("ul"); secondQuestion.textContent = quizQuestion2; question2Section.append(secondQuestion); questions.append(question2Section); const question3Section = document.createElement("div"); const thirdQuestion = document.createElement("ul"); thirdQuestion.textContent = quizQuestion3; question3Section.append(thirdQuestion); questions.append(question3Section); //////////////////Multiple choice answers//////////////////// const answer1a = "A: 1987"; const answer1b = "B: 2002"; const answer1c = "C: 1995"; // correct answer c const answerOneA = document.createElement("li"); answerOneA.textContent = answer1a; question1Section.append(answerOneA); const answerOneB = document.createElement("li"); answerOneB.textContent = answer1b; question1Section.append(answerOneB); const answerOneC = document.createElement("li"); answerOneC.textContent = answer1c; question1Section.append(answerOneC); /////////////////////////////////////////////////////////// const answer2a = " A: for each ()"; // correct answer a const answer2b = " B: loop ()"; const answer2c = " C: while ()"; const answertwoA = document.createElement("li"); answertwoA.textContent = answer2a; question2Section.append(answertwoA); const answertwoB = document.createElement("li"); answertwoB.textContent = answer2b; question2Section.append(answertwoB); const answertwoC = document.createElement("li"); answertwoC.textContent = answer2c; question2Section.append(answertwoC); ////////////////////////////////////////////////////////// const answer3a = " A: push"; const answer3b = " B: pop"; //correct answer b const answer3c = " C: join"; const answerThreeA = document.createElement("li"); answerThreeA.textContent = answer3a; question3Section.append(answerThreeA); const answerThreeB = document.createElement("li"); answerThreeB.textContent = answer3b; question3Section.append(answerThreeB); const answerThreeC = document.createElement("li"); answerThreeC.textContent = answer3c; question3Section.append(answerThreeC); /////////////////////////////////////////////////////////// // when user clicks start he is presented with first question and when an answer is clicked user is presented next quesion- building function// function getQuestion(currentQuestion) { if (currentQuestion == undefined) { createQuestionSection(quizQuestion1, answer1a, answer1b, answer1c); } else if (currentQuestion === quizQuestion1) { createQuestionSection(quizQuestion2, answer2a, answer2b, answer2c); } else if (currentQuestion === quizQuestion2) { createQuestionSection(quizQuestion3, answer3a, answer3b, answer3c); } else; } //When user selects and answer if answer is incorrect time is deducted from timer //When user selects clicks for an answer he is presented with the next question //if timer runs out before questions are answered the quiz is over // when all questions are done user is presented with results score and to input their name for highscore // provide highscore tracking with name input //reference link of questions source on readme https://www.tutorialspoint.com/javascript/javascript_online_quiz.htm
true
46c510aee19799af75f3dc44354c1eb8a0689e78
JavaScript
share/sharedb-mongo
/test/test_op_link_validator.js
UTF-8
4,363
2.515625
3
[ "MIT" ]
permissive
var OpLinkValidator = require('../op-link-validator'); var expect = require('chai').expect; describe('OpLinkValidator', function() { it('starts with no unique op', function() { var validator = new OpLinkValidator(); var opWithUniqueVersion = validator.opWithUniqueVersion(); expect(opWithUniqueVersion).to.equal(null); }); it('starts not at the end of the list', function() { var validator = new OpLinkValidator(); expect(validator.isAtEndOfList()).to.equal(false); }); it('has no unique op with just one op', function() { var op = {v: 1}; var validator = new OpLinkValidator(); validator.push(op); var opWithUniqueVersion = validator.opWithUniqueVersion(); expect(opWithUniqueVersion).to.equal(null); }); it('has a unique op with just two different ops', function() { var op1 = {v: 1}; var op2 = {v: 2}; var validator = new OpLinkValidator(); validator.push(op1); validator.push(op2); var opWithUniqueVersion = validator.opWithUniqueVersion(); expect(opWithUniqueVersion).to.equal(op1); }); it('does not have a uniquye op with just two identical ops', function() { var op1 = {v: 1}; var op2 = {v: 1}; var validator = new OpLinkValidator(); validator.push(op1); validator.push(op2); var opWithUniqueVersion = validator.opWithUniqueVersion(); expect(opWithUniqueVersion).to.equal(null); }); it('has a unique op with three ops with different versions', function() { var op1 = {v: 1}; var op2 = {v: 2}; var op3 = {v: 3}; var validator = new OpLinkValidator(); validator.push(op1); validator.push(op2); validator.push(op3); var opWithUniqueVersion = validator.opWithUniqueVersion(); expect(opWithUniqueVersion).to.equal(op2); }); it('is not at the end of the list with three ops', function() { var op1 = {v: 1}; var op2 = {v: 2}; var op3 = {v: 3}; var validator = new OpLinkValidator(); validator.push(op1); validator.push(op2); validator.push(op3); expect(validator.isAtEndOfList()).to.equal(false); }); it('does not have a unique op with three ops with the same version', function() { var op = {v: 1}; var validator = new OpLinkValidator(); validator.push(op); validator.push(op); validator.push(op); var opWithUniqueVersion = validator.opWithUniqueVersion(); expect(opWithUniqueVersion).to.equal(null); }); it('does not have a unique op if the first two ops are the same', function() { var op1 = {v: 1}; var op2 = {v: 1}; var op3 = {v: 2}; var validator = new OpLinkValidator(); validator.push(op1); validator.push(op2); validator.push(op3); var opWithUniqueVersion = validator.opWithUniqueVersion(); expect(opWithUniqueVersion).to.equal(null); }); it('does not have a unique op if the last two ops are the same', function() { var op1 = {v: 1}; var op2 = {v: 2}; var op3 = {v: 2}; var validator = new OpLinkValidator(); validator.push(op1); validator.push(op2); validator.push(op3); var opWithUniqueVersion = validator.opWithUniqueVersion(); expect(opWithUniqueVersion).to.equal(null); }); it('has a unique op in a long chain', function() { var op1 = {v: 1}; var op2 = {v: 1}; var op3 = {v: 1}; var op4 = {v: 2}; var op5 = {v: 2}; var op6 = {v: 3}; var op7 = {v: 4}; var validator = new OpLinkValidator(); validator.push(op1); validator.push(op2); validator.push(op3); validator.push(op4); validator.push(op5); validator.push(op6); validator.push(op7); var opWithUniqueVersion = validator.opWithUniqueVersion(); expect(opWithUniqueVersion).to.equal(op6); }); it('has a unique op with two ops and a current op of null', function() { var op1 = {v: 1}; var op2 = {v: 2}; var op3 = null; var validator = new OpLinkValidator(); validator.push(op1); validator.push(op2); validator.push(op3); var opWithUniqueVersion = validator.opWithUniqueVersion(); expect(opWithUniqueVersion).to.equal(op2); }); it('is at the end of the list with a current op of null', function() { var op = null; var validator = new OpLinkValidator(); validator.push(op); expect(validator.isAtEndOfList()).to.equal(true); }); });
true
438fc567253ca2705ed10e0785bc90ce8b7f2157
JavaScript
Samanta-ctrl/JavaScript
/JS Arrays/arrays.js
UTF-8
1,199
4.5
4
[]
no_license
//Initialize new array var names = ['Soumen','Arindam','Mark','James']; var years = new Array(1990,1963,1995,1998); //calling array function using new keyword console.log(names[0]); console.log(names[1]); console.log(names[2]); console.log(names); console.log(names.length); //array length //Mutate array data names[1] = 'Ben'; //changing array elements using index value names[3] = 'Poltu'; console.log(names); //***************************************************************** //different data types and methods of arrays:- var john = ['John', 'Smith', 1995, 'designer',false]; john.push('blue') //add the elements in the last position of the array console.log(john); john.unshift('Mr.'); //add one or more elements in the begining of the array console.log(john); john.pop(); //removes the elements from the end console.log(john); john.shift(); // remove first element console.log(john); console.log(john.indexOf(1995)); //returns the position //if the given element is not present in the index then it it return -1. var isDesigner = john.indexOf('designer') == -1 ? 'John is NOT a designer' : 'John is a Designer'; console.log(isDesigner);
true
60233b5740f4c00912d57ea2379c000853d5566f
JavaScript
smk1628/webpack
/src/js/module3.js
UTF-8
319
2.640625
3
[]
no_license
//使用默认暴露计算乘除的2个函数 export default { //函数简写方式 mul(a,b){ return a*b }, div(a,b){ return a/b } //未简写 // mul:function(a,b){ // return a*b // }, // div:function(a,b){ // return a/b // } }
true
2548c1c5b6fecc167d1ff71052351055972920e8
JavaScript
chipzco/ang
/js/services/curry.js
UTF-8
2,169
3.03125
3
[]
no_license
myApp.factory('curryService', function ($log) { var curryfns = {}; // this is doing binding and partial function application, // so I thought bind was a more appropriate name // The goal is that when you execute the returned wrapped version of fn, its this will be scope curryfns.bind=function(fn, scope) { // arguments is an implicit variable in every function that contains a full list // of what was passed in. It is important to note that javascript doesn't enforce arity. // since arguments is not a true array, we need to make it one. // a handy trick for this is to use the slice function from array, // since it will take arguments, and return a real array. // we are storing it in a variable, because we will need to use it again. var slice = Array.prototype.slice, // use slice to get an array of all additional arguments after the first two //that have been passed to this function. args = slice.call(arguments, 2); $log.debug("in outer curry"); $log.debug(args); var myinitnumber=args[0] +100; $log.debug("initnumber = " + myinitnumber); // we are returning a function mostly as a way to delay the execution. // as an aside, that this is possible in a mainstream language is a minor miracle // and a big part of why i love javascript. return function() { // since functions are objects in javascript, they can actually have methods. // this is one of the built in ones, that lets you execute a function in a different // context, meaning that the this variable inside the // function will actually refer to the first argument we pass in. // the second argument we are jamming together the arguments from the first function // with the arguments passed in to this wrapper function, and passing it on to fn. // this lets us partially apply some arguments to fn when we call bind. var newint=myinitnumber +50; $log.debug("in inner curry with new int" + newint); $log.debug(arguments); return fn.apply(scope, args.concat(slice.call(arguments))); }; }; return curryfns; });
true
86e919bdf515c69d55e0eb56e32621d476266a4f
JavaScript
estelora/nodeTutorial
/src/hello.js
UTF-8
1,440
3.8125
4
[ "MIT" ]
permissive
// node.js Hello World // syntax to require modules var http = require('http'); // createServer has 2 parameters // callback with 'request' & 'response' http.createServer(function (request, response) { //request event here // Status code in the header for response response.writeHead(200); // Response body response.write("Hello, I\'m waiting for dog."); //setTimeout to simulate a longer running process //Timeout event is big in node.js setTimeout(function(){ response.write("My dog arrived, waiting is done."); // end the response, close the connection response.end(); }, 5000); // end the response, close the connection //response.end(); // listen for connections on this port // (port 8080) }).listen(8080); console.log('listening on port 8080'); //to run, in terminal, enter: // node hello.js //to see the written response, enter: // curl http://localhost:8080 //can also go to localhost:8080 in the browser to get the same result //non-blocking function var fs = require('fs'); var contents = fs.readFile('index.html', function(err, contents){ console.log(contents); }); //writes something and reads index.html at the same time var http = require('http'); var fs = require('fs'); http.createServer(function(request, response) { response.writeHead(200); fs.readFile('index.html', function(error, data) { response.write(data); response.end(); }); }).listen(8080);
true
21657028cb5476c6261e3fc908a9cc9d1c8be06c
JavaScript
caffeine-dependency/ProductTechnicalSpecs
/server/controllers.js
UTF-8
2,072
2.625
3
[]
no_license
const { getTechSpecById, addTechSpec, deleteTechSpec, addImg, addQuestion } = require('../database/dbhelpers') // Tech Spec Controllers const getTechSpec = (req, res) => { let {id} = req.params; getTechSpecById(id) .then((data) => { res.status(200).send(data.rows); }) .catch((error) => { res.status(404).send(error); }); } const createTechSpec = (req, res) => { let {id,technicalFeatures,designAndFit,zippersAndFly,pocketConfig,construction,collarConfig,hemConfig,fabricTreatment,materials,care} = req.body; addTechSpec(id,technicalFeatures,designAndFit,zippersAndFly,pocketConfig,construction,collarConfig,hemConfig,fabricTreatment,materials,care) .then(() => { res.status(201).send('data added!'); }) .catch((error) => { res.status(404).send(error); }) } const removeTechSpec = (req,res) => { let {id} = req.params; deleteTechSpec(id) .then(() => { res.status(200).send('document deleted') }) .catch((error) => { res.status(404).send(error); }) } // Image Carousel Controllers const insertImg = (req, res) => { let {productid, imageurl, username, imgcaption} = req.body; addImg(productid, imageurl, username, imgcaption) .then(() => { res.status(201).send('image added') }) .catch((error) => { res.status(404).send('failed to add image') }) } // Question and Answer Controllers const insertQuestion = (req,res) => { let {id, productid, questionheader, questioncontent, username, userlocation, userage, useractivity} = req.body addQuestion(id, productid, questionheader, questioncontent, username, userlocation, userage, useractivity) .then(() => { res.status(201).send('successfully added question!') }) .catch((error) => { res.status(404).send('failed to add question') }) } module.exports = { getTechSpec, createTechSpec, removeTechSpec, insertImg, insertQuestion }
true
5cb09a8f6c5389395155b9428beaa3dcca310999
JavaScript
takuya-motoshima/codeigniter-extension
/sample/client/src/theme/js/custom/apps/projects/users/users.js
UTF-8
1,505
2.6875
3
[ "MIT" ]
permissive
"use strict"; // Class definition var KTProjectUsers = function () { var initTable = function () { // Set date data order const table = document.getElementById('kt_project_users_table'); if (!table) { return; } const tableRows = table.querySelectorAll('tbody tr'); tableRows.forEach(row => { const dateRow = row.querySelectorAll('td'); const realDate = moment(dateRow[1].innerHTML, "MMM D, YYYY").format(); dateRow[1].setAttribute('data-order', realDate); }); // Init datatable --- more info on datatables: https://datatables.net/manual/ const datatable = $(table).DataTable({ "info": false, 'order': [], "columnDefs": [{ "targets": 4, "orderable": false }] }); // Search --- official docs reference: https://datatables.net/reference/api/search() var filterSearch = document.getElementById('kt_filter_search'); if (filterSearch) { filterSearch.addEventListener('keyup', function (e) { datatable.search(e.target.value).draw(); }); } } // Public methods return { init: function () { initTable(); } } }(); // On document ready KTUtil.onDOMContentLoaded(function() { KTProjectUsers.init(); });
true
8e4a8fb2bfffb4c77af246d3c6a0dd4f79bebdcb
JavaScript
mohammadid52/react-calendar
/src/lib/datetime/hijri_calendar.js
UTF-8
852
2.703125
3
[]
no_license
/* eslint-disable */ const HijriCalendar = (function () { const MIN_CALENDAR_YEAR = 1000 const MAX_CALENDAR_YEAR = 3000 // return array of weeks for this month and year // return array of days from beginning of week until start of this month and year // return array of days from end of this month and year until end of the week // private function dayHash(hijriDate, gregorianDate, isFiller) { return { hijri: { year: hijriDate.getYear(), month: hijriDate.getMonth(), date: hijriDate.getDate(), }, gregorian: { year: gregorianDate.getFullYear(), month: gregorianDate.getMonth(), date: gregorianDate.getDate(), }, ajd: hijriDate.toAJD(), filler: isFiller ? true : undefined, } } return hijriCalendar })() export default HijriCalendar
true
2d1eca0f0cee62141b300e5bdc6ee57ad2d2f2bb
JavaScript
Zooeeee/TWS1-1
/practices/superposition_operation/own_elements_operation/subscript_is_even/single_element.js
UTF-8
908
2.859375
3
[]
no_license
'use strict'; var single_element = function(collection){ var element = new Array; var count = new Array; var i ; var a = new Array; for(i=0;i<collection.length;i++){ if (i%2!=0) a.push(collection[i]);} collection = a ; var n = collection[0]; element[0] = n; for(i=0;i<collection.length;i++){ if (collection[i] == n) {;} else { element.push(collection[i]); n = collection[i];} } collection = collection.sort(); for(var a=0;a<element.length;a++){ count[a] = 0; for (var b = 0 ; b <collection.length;b++) if (collection[b] == element[a]){ count[a]++; } } var result = new Array; for(var i = 0 ; i < element.length;i++){ if (count[i] == 1) result.push(element[i]); } return result; }; module.exports = single_element;
true
306aaf9ec505a4af7f26e56c26dd5b4185600e01
JavaScript
googledaniel/art-zine
/src/pages/Submission.js
UTF-8
1,698
2.703125
3
[]
no_license
import React, { useState, useEffect, useRef } from 'react'; import { Link } from 'react-router-dom'; export default function Submission(props) { const [articles, setArticles] = useState([]); const titleInput = useRef(null); const bodyInput = useRef(null); const summaryInput = useRef(null); useEffect(() => { //Immediately Invoked Function Expression - IFFE! (async () => { try { const response = await fetch('/api/articles'); const data = await response.json(); setArticles(data); } catch (error) { console.error(error); } })(); }, []); const handleSubmit = async e => { e.preventDefault(); const titleValue = titleInput.current.value; const bodyValue = bodyInput.current.value; const summaryValue = summaryInput.current.value; try { const response = await fetch('/api/articles', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: titleValue, body: bodyValue, summary: summaryValue }) }); const data = await response.json(); setArticles([...articles, data]); window.location.assign('/'); } catch (error) { console.error(error); } }; return ( <div className="SubmissionPage"> <form style={{ display: 'flex', flexDirection: 'column' }} onSubmit={handleSubmit} > Title: <input type="text" ref={titleInput} /> <br /> Summary: <input type="text" ref={summaryInput} /> <br /> Body:{' '} <textarea rows="2" cols="20" wrap="hard" id="submission" ref={bodyInput} ></textarea> <br /> <input type="submit" id="SubmitButton" value="Submit Article" /> </form> </div> ); }
true
8a9fd6d49ffa489df97d39fb241dded0fc0c8877
JavaScript
helloyongwei/storageManage-Nzy-Yw
/back-end/sql/storehouse.js
UTF-8
2,874
2.875
3
[]
no_license
/** * @module 仓库处理sql */ const sequelize = require('./sequelize') const errMsg = require('../static/errMsg') const consoleUtil = require('../util/console') const selectSql = 'SELECT * FROM storehouse LIMIT :offset, :limit' const defaultOffset = 0 const defaultLength = 5 const selectByIdSql = 'SELECT * FROM storehouse WHERE storeHouse_id=:id' const insertSql = 'INSERT INTO storehouse (name, location, size) VALUES (:name, :location, :size)' module.exports = { selectStorehouses, selectStorehouseById, insertStorehouse } /** * 获取仓库信息 * @param {number|string} offset 起点 * @param {number|string} limit 长度 * @return {Promise} * @example * [ { storeHouse_id: 3, name: '香樟园', location: '南', size: '850平方米' }, * {....}] */ function selectStorehouses (offset, limit) { offset = offset || defaultOffset limit = limit || defaultLength offset -= 0 limit -= 0 return new Promise((resolve, reject) => { sequelize.query(selectSql, { replacements: {offset, limit}, type: sequelize.QueryTypes.SELECT }).then(storehouses => { resolve(storehouses) }).catch(err => { consoleUtil.consoleError(err) reject(JSON.stringify(errMsg.errSqlSystemError)) }) }) } /** * 查询指定id仓库 * @param {number|string} id storehouse的id * @returns {Promise} * @example[ { storeHouse_id: 3, name: '香樟园', location: '南', size: '850平方米' }] */ function selectStorehouseById (id) { return new Promise((resolve, reject) => { if (!id) { reject(new Error(JSON.stringify(errMsg.errSqlInsertParamLack))) return } sequelize.query(selectByIdSql, { replacements: {id}, type: sequelize.QueryTypes.SELECT }).then(storehouse => { resolve(storehouse) }).catch(err => { consoleUtil.consoleError(err) reject(JSON.stringify(errMsg.errSqlSystemError)) }) }) } /** * 插入一个仓库信息 * @param {Object} storehouse - 仓库 * @param {string} storehouse.name - 名称 * @param {string} storehouse.location - 地址 * @param {string} storehouse.size - 大小 * @returns {Promise} 返回[a,b] a--id b--count */ function insertStorehouse (storehouse) { return new Promise((resolve, reject) => { if (!storehouse || !storehouse.name || !storehouse.location || !storehouse.size) { reject(new Error(JSON.stringify(errMsg.errSqlInsertParamLack))) return } sequelize.query(insertSql, { replacements: {name: storehouse.name, location: storehouse.location, size: storehouse.size}, type: sequelize.QueryTypes.INSERT }) .then(result => { storehouse.storeHouse_id = result[0] resolve(storehouse) }) .catch(err => { consoleUtil.consoleError(err) reject(new Error(JSON.stringify(errMsg.errSqlSystemError))) }) }) }
true
ff1864d1df1e965aab1097dd08851e0afb28df5b
JavaScript
AnuPoudyal/cs301_workspace
/computeOperand.js
UTF-8
316
3.796875
4
[]
no_license
//Write a function compute, that takes three parameters. First parameter is a call back function //that does the actual operation, second and third are the operands function display(result){ console.log("result"); } function compute(mycallback,a,b){ let sum=a+b; mycallback(sum); } compute(display,5,5);
true
3b085c9aef58f055a2542bf057a3c5603633be6c
JavaScript
kausgang/world_at_a_glance
/public/javascripts/render_map.js
UTF-8
3,897
2.609375
3
[]
no_license
function render_map(){ var width = 860, height = 500, rotate = 0, // so that [-60, 0] becomes initial center of projection maxlat = 83; // clip northern and southern poles (infinite in mercator) var projection = d3.geo.mercator() .rotate([rotate,0]) .scale(1) // we'll scale up to match viewport shortly. .translate([width/2, height/2]); // find the top left and bottom right of current projection function mercatorBounds(projection, maxlat) { var yaw = projection.rotate()[0], xymax = projection([-yaw+180-1e-6,-maxlat]), xymin = projection([-yaw-180+1e-6, maxlat]); return [xymin,xymax]; } // set up the scale extent and initial scale for the projection var b = mercatorBounds(projection, maxlat), s = width/(b[1][0]-b[0][0]), scaleExtent = [s, 10*s]; projection .scale(scaleExtent[0]); var zoom = d3.behavior.zoom() .scaleExtent(scaleExtent) .scale(projection.scale()) .translate([0,0]) // not linked directly to projection .on("zoom", redraw); var path = d3.geo.path() .projection(projection); // var svg = d3.selectAll('body') // .append('svg') // .attr('width',width) // .attr('height',height) // .call(zoom); var svg = d3.select('#globe') .attr("width", width) .attr("height", height) .call(zoom); d3.json("https://raw.githubusercontent.com/kausgang/interactive_world_map/master/ne_110m_admin_0_countries.json", function(error, world){ // svg.selectAll('path') // .data(topojson.feature(world, world.objects.countries).features) // .enter().append('path') var countries = topojson.feature(world,world.objects.ne_110m_admin_0_countries).features; svg // .selectAll(".countries") .selectAll("g") .data(countries) .enter() .append("path") .attr("class",function(d){ //add the country name in class attribute so that later it can be retrieved // return d.properties.BRK_NAME; //THIS WORKS TOO return d.properties.NAME; }) .attr("d",path) .on("click",function(d){ // console.log(this); var x = this.getAttribute("class"); //return the country name //console.log(x) alert('Select year to know if history is available for '+x); }) redraw(); // update path data }); // track last translation and scale event we processed var tlast = [0,0], slast = null; function redraw() { if (d3.event) { var scale = d3.event.scale, t = d3.event.translate; // if scaling changes, ignore translation (otherwise touch zooms are weird) if (scale != slast) { projection.scale(scale); } else { var dx = t[0]-tlast[0], dy = t[1]-tlast[1], yaw = projection.rotate()[0], tp = projection.translate(); // use x translation to rotate based on current scale projection.rotate([yaw+360.*dx/width*scaleExtent[0]/scale, 0, 0]); // use y translation to translate projection, clamped by min/max var b = mercatorBounds(projection, maxlat); if (b[0][1] + dy > 0) dy = -b[0][1]; else if (b[1][1] + dy < height) dy = height-b[1][1]; projection.translate([tp[0],tp[1]+dy]); } // save last values. resetting zoom.translate() and scale() would // seem equivalent but doesn't seem to work reliably? slast = scale; tlast = t; } svg.selectAll('path') // re-project path data .attr('d', path); } }
true
7f5b09f522609b21ab921dd695f1fe654d081052
JavaScript
nickscaglione/web-js-oo-task-list-web-0916
/js/controllers/lists.controller.js
UTF-8
717
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
'use strict'; // Lists Controller function ListsController() { this.$addListForm = $('#add_list'), this.$listTitleInput = $('#list_title'), this.$selectListMenu = $('#select_list'), this.$addTaskForm = $('#add_task') this.$wrapper = $('#wrapper') } ListsController.prototype.init = function() { this.$addTaskForm.hide() // add (build) new list, shows adds task form this.$addListForm.submit((event)=>{ event.preventDefault() let newList = new List(this.$listTitleInput[0].value) newList.build() this.$listTitleInput.val('') let lists = $('#lists .list') lists.last().find('h2 button').click(() => { lists.last().remove() }) this.$addTaskForm.show() }) }
true
87e709fb3348dc1b25e7e46ff09924509b4615b7
JavaScript
davidabutler92/07_one-to-many
/__tests__/app.test.js
UTF-8
5,186
2.84375
3
[]
no_license
const fs = require('fs'); const request = require('supertest'); const app = require('../lib/app'); const pool = require('../lib/utils/pool'); const Book = require('../lib/models/Book'); const Page = require('../lib/models/Page'); describe('app endpoints', () => { beforeEach(() => { return pool.query(fs.readFileSync(`${__dirname}/../sql/setup.sql`, 'utf-8')); }); afterAll(() => { return pool.end(); }); it('should create a new book using POST', async() => { const res = await request(app) .post('/api/v1/books') .send({ title: 'Harry Potter', author: 'J.K. Rowling', genre: 'Fantasy' }); expect(res.body).toEqual({ id: '1', title: 'Harry Potter', author: 'J.K. Rowling', genre: 'Fantasy' }); }); it('should get all books', async() => { }); it('should get a book by id using GET', async() => { const book = await Book.insert({ title: 'Eragon', author: 'Christopher Paolini', genre: 'Fantasy' }); const pages = await Promise.all([ { text: 'hello WORLD', bookId: book.id }, { text: 'something else', bookId: book.id }, { text: 'brand NEW text', bookId: book.id } ].map(page => Page.insert(page))); const res = await request(app) .get(`/api/v1/books/${book.id}`); expect(res.body).toEqual({ ...book, pages: expect.arrayContaining(pages) }); }); it('should get all books using GET', async() => { const books = await Promise.all([ { title: 'book one', author: 'shmit shmitster', genre: 'sci-fi' }, { title: 'book two', author: 'shmit shmitster', genre: 'horror' }, { title: 'book three', author: 'shmit shmitster', genre: 'fantasy' } ].map(book => Book.insert(book))); const res = await request(app) .get('/api/v1/books'); expect(res.body).toEqual(expect.arrayContaining(books)); expect(res.body).toHaveLength(books.length); }); it('should update a book by id using PUT', async() => { const book = await Book.insert({ title: 'A new book', author: 'David Butler', genre: 'Horror' }); const res = await request(app) .put(`/api/v1/books/${book.id}`) .send({ title: 'A new book', author: 'David Butler', genre: 'Horror' }); expect(res.body).toEqual({ id: book.id, title: 'A new book', author: 'David Butler', genre: 'Horror' }); }); it('should delete a book using DELETE', async() => { const book = await Book.insert({ title: 'Harry Potter', author: 'J.K. Rowling', genre: 'Fantasy' }); const res = await request(app) .delete(`/api/v1/books/${book.id}`); expect(res.body).toEqual(book); }); //testing routes for Page model it('should create a new page using POST', async() => { const book = await Book.insert({ title: 'Harry Potter', author: 'J.K. Rowling', genre: 'Fantasy' }); const res = await request(app) .post('/api/v1/pages') .send({ text: 'youre a wizard, harry!', bookId: `${book.id}` }); expect(res.body).toEqual({ id: '1', text: 'youre a wizard, harry!', bookId: book.id }); }); it('should get a page by id using GET', async() => { const book = await Book.insert({ title: 'Harry Potter', author: 'J.K. Rowling', genre: 'Fantasy' }); const page = await Page.insert({ text: 'youre a wizard, harry!', bookId: book.id }); const res = await request(app) .get(`/api/v1/pages/${page.id}`); expect(res.body).toEqual(page); }); it('should get all pages using GET', async() => { const book = await Book.insert({ title: 'Harry Potter', author: 'J.K. Rowling', genre: 'Fantasy' }); const pages = await Promise.all([ { text: 'HARRY POTTER!!!!', bookId: book.id }, { text: 'something else', bookId: book.id }, { text: 'dat new new text', bookId: book.id } ].map(page => Page.insert(page))); const res = await request(app) .get('/api/v1/pages'); expect(res.body).toEqual(expect.arrayContaining(pages)); expect(res.body).toHaveLength(pages.length); }); it('should update a page using PUT', async() => { const book = await Book.insert({ title: 'Harry Potter', author: 'J.K. Rowling', genre: 'Fantasy' }); const page = await Page.insert({ text: 'youre a wizard, harry!', bookId: book.id }); const res = await request(app) .put(`/api/v1/pages/${page.id}`) .send({ text: 'something else' }); expect(res.body).toEqual({ id: page.id, text: 'something else', bookId: book.id }); }); it('should delete a page using DELETE', async() => { const book = await Book.insert({ title: 'Harry Potter', author: 'J.K. Rowling', genre: 'Fantasy' }); const page = await Page.insert({ text: 'youre a wizard, harry!', bookId: book.id }); const res = await request(app) .delete(`/api/v1/pages/${page.id}`); expect(page).toEqual(res.body); }); });
true
dce7155475b2ca1804067a5f3bdbf1da65d9d865
JavaScript
willvitorino/GCharts
/js/modal.js
UTF-8
666
3.03125
3
[]
no_license
// Get the modal let modal = document.getElementById('myModal'); // Get the <span> element that closes the modal let span = document.getElementsByClassName("clsModal"); // When the user clicks on the button, open the modal for (btn of document.getElementsByClassName("openModal")) { btn.onclick = function () { // modal.style.display = "block"; $('.modal').modal('show'); } } function closeModal(event) { // modal.style.display = "none"; $('.modal').modal("hide"); } // When the user clicks anywhere outside of the modal, close it window.onclick = function (event) { if (event.target == modal) { closeModal(); } }
true
cec16fac44922be923523299be86fc786a8c0330
JavaScript
petarcmarinov97/SoftUni-JavaScript
/JS-Fundamentals/Objects/traveltime.js
UTF-8
1,430
3.546875
4
[]
no_license
function travelTime(arr) { let result = {}; for (let line of arr) { let [state, town, price] = line.split(" > ").map(x=>x.trim()); town = town.charAt(0).toUpperCase() + town.slice(1); if (!result.hasOwnProperty(state)) { result[state] = {}; } if (!result[state].hasOwnProperty(town)) { result[state][town] = Number.POSITIVE_INFINITY; } if (result[state].hasOwnProperty(town)) { if ( result[state][town] > Number(price)) { result[state][town] = Number(price); } } } let sortedStates = Object.keys(result).sort((a, b)=>{ "use strict"; return a.toLowerCase().localeCompare(b.toLowerCase()); }); for (let state of sortedStates) { let innerResult = ""; innerResult += (state + " -> "); let sortedTownsByPrice = Object.keys(result[state]).sort((t1,t2)=>{ "use strict"; return result[state][t1] - result[state][t2]; }); for (let obj of sortedTownsByPrice) { innerResult += (obj + " -> "); innerResult += (result[state][obj]+ " "); } console.log(innerResult.trim()); } } travelTime([ "Bulgaria > Sofia > 500", "Bulgaria > Sopot > 800", "France > Paris > 2000", "Albania > Tirana > 1000", "Bulgaria > Sofia > 200" ] )
true
7a716054b30d02474e32359f0b2c27f2b2d61f73
JavaScript
nipunwijetunge/Ceylon-Travel-Guide-Website
/ProductPage/MainJS.js
UTF-8
8,651
2.96875
3
[ "MIT" ]
permissive
/* PRODUCTS DATA */ // Load products var products = { 1: { name: "PULP ELEPHANT", desc: "Hand made pulp elephant statue.", img: "pulp-elephant.jpg", price: 842 }, 2: { name: "WOODEN ELEPHANT", desc: "An elephant made with \"KALUWARA\".", img: "wooden-elephant.jpg", price: 1200 }, 3: { name: "LAQUARED BOX", desc: "Hand made Laquared Box.", img: "laquared-cakebox.jpg", price: 675 }, 4: { name: "CERAMIC PEN HOLDER", desc: "Elephant feet shaped pen holder.", img: "ceramic-pen-holder.jpg", price: 55 }, 5: { name: "LEATHER TRAVELLING BAG", desc: "Original hand made leather bag.", img: "leather-travelling-bag.jpg", price: 200 }, 6: { name: "HAND LOOM BOX PURSE", desc: "Light weight fashionable purse.", img: "hand-loom-box-purse.jpg", price: 25 }, 7: { name: "SILVER NECKLACE", desc: "Hard patterned silver necklace.", img: "silver-necklace-2.jpg", price: 2000 }, 8: { name: "CUSHION COVER", desc: "Ultra soft Cushion Covers.", img: "cusion-cover.jpg", price: 15 }, 9: { name: "HAND LOOM PURSE", desc: "Cute Hand loom purse for kids.", img: "hand-loom-purse.jpg", price: 32 }, 10: { name: "CINNAMON PACK", desc: "Best quality Ceylon Cinnamon.", img: "cinnamon-pack.jpg", price: 25 }, 11: { name: "SPICES PACK", desc: "A pack of best quality spices.", img: "spices-pack.jpg", price: 10 }, 12: { name: "LEATHER SIDE BAG", desc: "Original leather side bag.", img: "leather-side-bag.jpg", price: 40 }, 13: { name: "LEATHER HUMPTY OVAL", desc: "Hand made leather humpty oval.", img: "leather-humpty-oval.jpg", price: 80 }, 14: { name: "CEYLON TEA PACK", desc: "Quality hand picked ceylon tea.", img: "ceylon-tea.jpg", price: 10 }, 15: { name: "SILVER NECKLACE", desc: "Hard patterned silver necklace.", img: "silver-necklace-3.jpg", price: 1700 } }; /*PRODUCTS HTML GRID GENERATOR */ window.addEventListener("load", function () { var container = document.getElementById("cart-products"), item = null, part = null; for (let i in products) { item = document.createElement("div"); item.classList.add("p-item"); // Product Image part = document.createElement("img"); part.src = products[i]['img']; part.classList.add("p-img"); part.alt = products[i]['name']; item.appendChild(part); // Product Name part = document.createElement("div"); part.innerHTML = products[i]['name']; part.classList.add("p-name"); item.appendChild(part); // Product Price part = document.createElement("div"); part.innerHTML = "$" + products[i]['price']; part.classList.add("p-price"); item.appendChild(part); // Product Description part = document.createElement("div"); part.innerHTML = products[i]['desc']; part.classList.add("p-desc"); part.classList.add("text"); item.appendChild(part); // Add to cart part = document.createElement("input"); part.type = "button"; part.value = "Add to Cart"; part.classList.add("p-add"); part.onclick = cart.add; part.dataset.id = i; item.appendChild(part); container.appendChild(item); } }); /* SHOPPING CART */ var total; var cart = { data: null, // current shopping cart /* LOCALSTORAGE */ load: function () { // load() : load previous shopping cart cart.data = localStorage.getItem("cart"); if (cart.data == null) { cart.data = {}; } else { cart.data = JSON.parse(cart.data); } }, save: function () { // save() : save current cart localStorage.setItem("cart", JSON.stringify(cart.data)); }, /* CART ACTIONS */ add: function () { // add() : add selected item to cart // Update current cart if (cart.data[this.dataset.id] === undefined) { var product = products[this.dataset.id]; cart.data[this.dataset.id] = { name: product['name'], desc: product['desc'], img: product['img'], price: product['price'], qty: 1 }; } else { cart.data[this.dataset.id]['qty']++; } // Save local storage + HTML update cart.save(); cart.list(); }, list: function () { // list() : update HTML var container = document.getElementById("cart-monitor"), item = null, part = null, product = null; container.innerHTML = ""; // Empty cart // Credits : https://coderwall.com/p/_g3x9q/how-to-check-if-javascript-object-is-empty var isempty = function (obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { return false; } } return true; }; if (isempty(cart.data)) { item = document.createElement("div"); item.innerHTML = "Cart is empty"; item.style.fontSize = "30px"; item.style.fontWeight = "bold"; item.style.color = "white"; item.style.position = "relative"; item.style.top = "100px"; item.style.left = "85%"; container.appendChild(item); } // Not empty else { // List items var subtotal = 0; total = 0; for (var i in cart.data) { item = document.createElement("div"); item.classList.add("c-item"); product = cart.data[i]; // Quantity part = document.createElement("input"); part.type = "number"; part.value = product['qty']; part.dataset.id = i; part.classList.add("c-qty"); part.addEventListener("change", cart.change); item.appendChild(part); // Name part = document.createElement("span"); part.innerHTML = product['name']; part.classList.add("c-name"); item.appendChild(part); // Subtotal subtotal = product['qty'] * product['price']; total += subtotal; container.appendChild(item); } // EMPTY BUTTONS item = document.createElement("input"); item.type = "button"; item.value = "Empty"; item.addEventListener("click", cart.reset); item.classList.add("c-empty"); container.appendChild(item); // CHECKOUT BUTTONS item = document.createElement("input"); item.type = "button"; item.value = "Checkout - " + "$" + total; item.addEventListener("click", cart.checkout); item.classList.add("c-checkout"); container.appendChild(item); } }, change: function () { // change() : change quantity if (this.value === 0) { delete cart.data[this.dataset.id]; } else { cart.data[this.dataset.id]['qty'] = this.value; } cart.save(); cart.list(); }, reset: function () { // reset() : empty cart if (confirm("Empty cart?")) { cart.data = {}; cart.save(); cart.list(); } }, checkout: function () { // checkout() : checkout the cart document.getElementById('id01').style.display = 'block'; } }; // Load previous cart and update HTML on load window.addEventListener("load", function () { cart.load(); cart.list(); }); /*form validation*/ function confirmation() { var name = document.getElementById("myForm").elements[0].value; var address = document.getElementById("myForm").elements[1].value; var email = document.getElementById("myForm").elements[2].value; var tel = document.getElementById("myForm").elements[3].value; if (name === "" || address === "" || email === "" || tel === "") { alert("Please fill required fields") } else { var c = confirm(name + " you have successfully purchased $" + total + " for our products. \n" + "Your Address: " + address + "\nYour Email: " + email + "\nYour Tel: " + tel); if (c === true) { document.getElementById("id01").style.display = "none"; cart.data = {}; cart.save(); cart.list(); } } }
true
a4d712bd8d8d927826a81130a4040351f31ca4ab
JavaScript
shakuu/Exams
/JSFundamentals/03-task3.js
UTF-8
3,831
3.109375
3
[ "MIT" ]
permissive
function solve(args) { let selectors = []; let property = { 'weight': 0, 'value': '' }; // Weight: // new selectors // new property // Regex let matchWeight = /@(\d+)/, matchSelector = /(([a-z|0-9])+) ?\{ ?(@\d+)?/im, matchProperty = /(([a-z|0-9|-])+): ?([^:; \{\}@]*);/im, matchClosingBracket = /^(\s*)?}(\s*)?$/im; let currentSelector = '', currentWeight = 0, scopeStack = [], selectorHistory = [], weightStack = []; const empty = 'initial'; currentSelector = empty; // scopeStack.push(empty); // REMOVE SPACES for (let lineNr = 0; lineNr < args.length; lineNr += 1) { let line = (args[lineNr] + '').replace(/\s\s+/gim, ' ').trim(); let weightIsChanged = false, weightSingleLine = false; // Apply new weight at the end of the line if (matchWeight.test(line)) { // Get current weight // Remove it from the line if (matchSelector.test(line)) { weightStack.push(currentWeight); } if (matchProperty.test(line)) { weightSingleLine = true; weightStack.push(currentWeight); } let match = line.match(matchWeight); currentWeight = +match[1]; // weightIsChanged = true; line = line.replace(matchWeight, '').trim(); } if (matchSelector.test(line)) { // Get the Selector // Add to selectors // Set current selector let match = line.match(matchSelector); if (!selectors[match[1]]) { selectors[match[1]] = []; selectorHistory.push(match[1]); } scopeStack.push(currentSelector); weightStack.push(currentWeight); currentSelector = match[1]; } else if (matchProperty.test(line)) { // Search for property // Eval weight // Add value/ change value let match = line.match(matchProperty); // If it's a new property. if (!selectors[currentSelector][match[1]]) { selectors[currentSelector][match[1]] = { "value": match[3], "wieght": +currentWeight }; } else { let prevWeight = +selectors[currentSelector][match[1]].wieght; if (currentWeight > prevWeight) { selectors[currentSelector][match[1]].value = match[3]; } } if (weightSingleLine) { currentWeight = weightStack.pop(); weightSingleLine = false; } } else if (line.trim() === '}') { currentSelector = scopeStack.pop(); currentWeight = weightStack.pop(); } } selectorHistory.sort(); // div { font-size: 20px; } let output = [], curSelectorOutput = []; for (let sel of selectorHistory) { // console.log(sel); curSelectorOutput = []; // console.log(selectors[sel][0]); for (let prop in selectors[sel]) { curSelectorOutput.push(`${prop}: ${selectors[sel][prop].value}; }`); } curSelectorOutput.sort(); for (let item of curSelectorOutput) { output.push(`${sel} { ${item}`); } } console.log(output.join('\r\n')); } const test1 = [ 'li {', ' font-size: 2px;', ' font-weight: bold;', '}', 'div {', ' font-size: 20px; @5', '}', 'div { @4', ' font-size: 17px;', '}', '@19', 'li {', ' font-size: 42px;', ' color: red; @9', '}' ]; solve(test1);
true
0d5330d30da6f5be7a26b248e7e1ef5af759438a
JavaScript
MaxHutchings/actual
/shopping.js
UTF-8
1,635
2.53125
3
[]
no_license
'use strict'; const sqlite = require('sqlite'); async function init() { const db = await sqlite.open('./database.sqlite', { verbose: true }); await db.migrate({ migrationsPath: './migrations-sqlite' }); return db; } const dbPromise = init(); fuckYou(); async function fuckYou() { const db = await dbPromise; await db.run('DELETE FROM ShoppingList WHERE id = ?', ['1388bad7-a3dd-4983-9a18-6cc37ab71584']); } async function getList() { const db = await dbPromise; const list = await db.all('SELECT * FROM ShoppingList'); return list; } async function addItem(item) { let id = item.id; let itemName = item.name; let barcode = item.upc; let toBuy = item.toBuy; const db = await dbPromise; await db.run('INSERT INTO ShoppingList VALUES (?, ?, ?, ?)', [id, barcode, itemName, toBuy]); } async function removeItem(payload) { const db = await dbPromise; let id = payload.id; await db.run('DELETE FROM ShoppingList WHERE id = ?', [id]); } async function updateItem(item) { const db = await dbPromise; let id = item.id; let toBuy = item.toBuy; await db.run('UPDATE ShoppingList SET toBuy = ? WHERE id = ?', [toBuy, id]); } async function isInList(id) { const db = await dbPromise; let list = await db.all('SELECT * FROM ShoppingList WHERE id = ?', [id]); if (await list.length === 0) { return false; } else { return true; } } async function getItem(id) { const db = await dbPromise; let item = await db.all('SELECT * FROM ShoppingList WHERE id = ?', [id]); return item; } module.exports = { getList, addItem, removeItem, updateItem, isInList, getItem, };
true
c37010cabe76a9eb74469cc48dd4ddeeb441a113
JavaScript
PI-KA-CHU/homework_refactor_1
/test/statementTest.js
UTF-8
2,591
2.71875
3
[]
no_license
const test = require('ava'); const {statement} = require('../src/statement'); // test('Sample test', t => { // t.true(true); // t.is(1, 1); // t.deepEqual({a: 1}, {a: 1}); // }); test('test 1', t => { const invoice = { 'customer': 'BigCo', 'performances': [ { 'playID': 'hamlet', 'audience': 55, }, { 'playID': 'as-like', 'audience': 35, }, { 'playID': 'othello', 'audience': 40, }, ], }; const result = statement(invoice, plays); t.is(result, "Statement for BigCo\n" + " Hamlet: $650.00 (55 seats)\n" + " As You Like It: $580.00 (35 seats)\n" + " Othello: $500.00 (40 seats)\n" + "Amount owed is $1,730.00\n" + "You earned 47 credits \n"); }); test('test 2', t => { const invoice = { 'customer': 'BigCo', 'performances': [ { 'playID': 'hamlet', 'audience': 30, } ], }; const result = statement(invoice, plays); t.is(result, "Statement for BigCo\n" + " Hamlet: $400.00 (30 seats)\n" + "Amount owed is $400.00\n" + "You earned 0 credits \n"); }); test('should_return_Statement for BigCo\n Hamlet: $410.00 (31 seats)\nAmount owed is $410.00\nYou earned 1 credits \n_given_playID_hamlet_audience_31', t => { const invoice = { 'customer': 'BigCo', 'performances': [ { 'playID': 'hamlet', 'audience': 31, } ], }; const result = statement(invoice, plays); t.is(result, "Statement for BigCo\n" + " Hamlet: $410.00 (31 seats)\n" + "Amount owed is $410.00\n" + "You earned 1 credits \n"); }); test('test 4', t => { const invoice = { 'customer': 'BigCo', 'performances': [ { 'playID': 'as-like', 'audience': 20, } ], }; const result = statement(invoice, plays); t.is(result, "Statement for BigCo\n" + " As You Like It: $360.00 (20 seats)\n" + "Amount owed is $360.00\n" + "You earned 4 credits \n"); }); test('test 5', t => { const invoice = { 'customer': 'BigCo', 'performances': [ { 'playID': 'as-like', 'audience': 21, } ], }; const result = statement(invoice, plays); t.is(result, "Statement for BigCo\n" + " As You Like It: $468.00 (21 seats)\n" + "Amount owed is $468.00\n" + "You earned 4 credits \n"); }); const plays = { 'hamlet': { 'name': 'Hamlet', 'type': 'tragedy', }, 'as-like': { 'name': 'As You Like It', 'type': 'comedy', }, 'othello': { 'name': 'Othello', 'type': 'tragedy', }, };
true
94f6a3d071c46d226054c96b3fa801febefa8906
JavaScript
wang-yuhao/multimedia
/Node.js/buffer_class.js
UTF-8
605
3.671875
4
[]
no_license
//create a Buffer with a length of 10 and padding with 0. const buf1 = Buffer.alloc(10); //create a buffer with a length of 10 and padding with 0x1. const buf2 = Buffer.alloc(10,1); //create a buffer with a length of 10 and uninitialized //this methode is more quickly than Buffer.alloc() //but the returned Buffer instance may contain old data. //so need overwrite with fill() or write() const buf3 = Buffer.allocUnsafe(10); //create a Buffer contain [0x1, 0x2, 0x3] const buf4 = Buffer.from([1,2,3]); //create a Buffer contain UTF-8 byte[0x74,0xc3,0xa9,0x73,0x74] const buf5 = Buffer.from('test');
true
ae31e40bd0e280e8a8fde28ae55959c5f9f9e91d
JavaScript
wangyi96/MyHobby
/pc端轮播图(js原生代码)/js/page-index.js
UTF-8
3,286
3.09375
3
[]
no_license
/** * Created by Supreme on 2017/8/16. */ window.onload = function(){ /*获取imgList*/ var imfList = document.getElementById("imgList"); /*获取img*/ var imgArr = document.getElementsByTagName("img"); /*设置imgList的整体宽度*/ imgList.style.width = 520*imgArr.length + "px"; /*获取导航navDiv*/ var navDiv = document.getElementById("navDiv"); /*获取navDiv的父元素outer*/ var outer = document.getElementById("outer"); /*计算出导航按钮在outer中的居中位置*/ navDiv.style.left = ( outer.offsetWidth - navDiv.offsetWidth) / 2 + "px"; /*设置图片默认的索引*/ var index = 0; /*获取所有的 a */ var allA = document.getElementsByTagName("a"); /*给第一个 a 设置默认的样式效果*/ allA[index].style.backgroundColor = "black"; /*为所有的 a 绑定点击响应函数*/ for(var i = 0; i < allA.length; i++){ /*为每一个超链接添加一个 num 属性*/ allA[i].num = i; allA[i].onclick = function(){ //关闭自动切换的定时器 clearInterval(timer); index = this.num; //获取点击超链接的索引.将其复制给 index //切换图片 //imgList.style.left = -520 * index + "px"; //修改正在选中的 a /*allA[index].style.backgroundColor = "black";*/ setA(); //调一个 serA //使用 move 函数来切换图片 move(imgList , "left" , -520 * index , 20 , function(){ //动画执行完毕,开启自动切换 autoChange(); }); }; } //自动切换图片(开启自动切换图片) autoChange(); /*创建一个方法,来设置选中的 a */ function setA(){ //判断当前的索引是否是最后一张 if(index >= imgArr.length - 1){ //犯了重点错误 index = 0; //此时显示的最后一张图片,而最后一张图片和第一张是一摸一样 //通过CSS将最后一张切换成第一张 imgList.style.left = 0; } for(var i = 0; i < allA.length; i++){ /*重点错误*/ allA[i].style.backgroundColor = ""; //对所有的 a 进行遍历,设置成红色 /* 相当于设置成了 内敛样式 ,优先级高于 (hover), navDiv a{background-color:red;} * 应将 “black” 改为 空 */ } //将选中的 a 设置为黑色 allA[index].style.backgroundColor = "black"; }; // //定义一个自动切换的定时器的标识 var timer; //创建一个函数,用来开启自动切换图片 function autoChange(){ //开启一个定时器,用来定时切换图片 timer = setInterval(function(){ //切换图片,是使图片的索引自增 index ++; //判断 index 的值 index %= imgArr.length; //执行动画,切换图片 move(imgList , "left" , -520 * index , 20 , function(){ //修改导航按钮 setA(); }); },3000); } };
true
6c062c19cbad1b663b13979dc95cb99f3b612332
JavaScript
juncn/acc
/sample_code/createIterator.js
UTF-8
458
3.46875
3
[]
no_license
const createIterator = () => { let x = 0; return { next: () => { if (x > 3) { return {value: undefined, done: false} } else { const currentValue = x; x += 1; return {value: currentValue, done: true} } } } }; const iterator = createIterator(); console.log(iterator.next()); console.log(iterator.next()); console.log(iterator.next()); console.log(iterator.next()); console.log(iterator.next());
true
771b57dfe68d3a8635beccfb73839ecbd5abc33e
JavaScript
souh03/javascript-module-1
/week-1/Homework/K-functions-parameters/exercise3.js
UTF-8
240
3.640625
4
[]
no_license
// Write your function here function greeting(Daniel,createGreeting){ var create =Daniel + createGreeting ; return create; } var createGreeting = var greeting = console.log(greeting("Hello,"," my name is Daniel "));
true
379353fcdd492758f8c4f2a802f5b91adb3b0a37
JavaScript
shpp-syakovenko/it-social
/src/redux/usersReducer.js
UTF-8
4,677
2.546875
3
[]
no_license
import {usersAPI} from "../api/api"; import {updateObjectInArray} from "../utils/objectHelper"; const FOLLOW = 'FOLLOW'; const UNFOLLOW = 'UNFOLLOW'; const SET_USERS = 'SET_USERS'; const SET_CURRENT_PAGE = 'SET_CURRENT_PAGE'; const TOTAL_USERS_COUNT = 'TOTAL_USERS_COUNT'; const TOGGLE_LOADER = 'TOGGLE_LOADER'; const FOLLOWING_PROGRESS = 'FOLLOWING_PROGRESS'; let startState = { users: [ /* {id: 0, urlPhoto: 'https://pbs.twimg.com/profile_images/552426642107166720/iaEkxjZG.jpeg', fullName: 'Sergey Yakovenko', followed: true, status: 'I\'m happy today', location: {country: 'Ukraine', city: 'Kropuvnuckiy'}}, {id: 1, urlPhoto: 'https://pbs.twimg.com/profile_images/552426642107166720/iaEkxjZG.jpeg', fullName: 'Dmitriy Polishuck', followed: false, status: 'I\'m fine today', location: {country: 'Italy', city: 'Roma'}}, {id: 2, urlPhoto: 'https://pbs.twimg.com/profile_images/552426642107166720/iaEkxjZG.jpeg', fullName: 'Roma Zagorskiy', followed: true, status: 'I want eat today', location: {country: 'Greece', city: 'Athens'}}, {id: 3, urlPhoto: 'https://pbs.twimg.com/profile_images/552426642107166720/iaEkxjZG.jpeg', fullName: 'Igor Bagnuk', followed: false, status: 'I want sleep today', location: {country: 'Latvia', city: 'Riga'}}*/ ], pageSize: 20, totalUsersCount: 1, currentPage: 1, isFetching: false, followingProgress: [] }; const usersReducer = (state = startState, action) => { switch (action.type) { case FOLLOW: return { ...state, users: updateObjectInArray(state.users, action.userId, 'id', {followed: true}) }; case UNFOLLOW: return { ...state, users: updateObjectInArray(state.users, action.userId, 'id', {followed: false}) }; case SET_USERS: return {...state, users: [...action.users]}; case SET_CURRENT_PAGE: return {...state, currentPage: action.currentPage}; case TOTAL_USERS_COUNT: return {...state, totalUsersCount: action.totalCount }; case TOGGLE_LOADER: return {...state, isFetching: action.isFetching }; case FOLLOWING_PROGRESS: return { ...state, followingProgress: action.isFetching ? [...state.followingProgress, action.userId] // Добавляем новый id (Подписываемся) : state.followingProgress.filter(id => id !== action.userId) // //Удаляем Id (отписываемся): функция filter копирует все id кроме того что нам пришел }; default: return state; } }; export const followSuccess = (userId) => ({ type: FOLLOW, userId: userId }); export const unfollowSuccess = (userId) => ({type: UNFOLLOW, userId: userId }); export const setUsers = (users) => ({type: SET_USERS, users: users }); export const setCurrentPage = (currentPage) => ({type: SET_CURRENT_PAGE, currentPage: currentPage}); export const setTotalUserCount = (totalCount) =>({type: TOTAL_USERS_COUNT, totalCount}); export const toggleLoader = (isFetching) =>({type: TOGGLE_LOADER, isFetching}); export const toggleFollowingProgress = (isFetching, userId) =>({type: FOLLOWING_PROGRESS, isFetching, userId}); // Выбрать всех юзеров с текущей страницы export const getUsersCurrentPage = (currentPage, pageSize) => { return async (dispatch) => { dispatch(toggleLoader(true)); const data = await usersAPI.getUsers(currentPage, pageSize); dispatch(setCurrentPage(currentPage)); dispatch(setTotalUserCount(data.totalCount)); dispatch(setUsers(data.items)); dispatch(toggleLoader(false)); } }; // Выносим что бы не дублировать код в отдельный метод const followUnfollow = async (userId, dispatch, actionCreator, apiMethod) => { dispatch(toggleFollowingProgress(true, userId)); const response = await apiMethod(userId); if(response.data.resultCode === 0){ dispatch(actionCreator(userId)); } dispatch(toggleFollowingProgress(false, userId)); }; export const unfollow = (userId) => { // кнопка отписаться return async (dispatch) => { followUnfollow(userId, dispatch, unfollowSuccess,usersAPI.unfollow ); } }; export const follow = (userId) => { // кнопка подписаться return async (dispatch) => { followUnfollow(userId, dispatch, followSuccess, usersAPI.follow); } }; export default usersReducer;
true
d7fde6496dfdef82dfb0a3e6bbe13899da29218c
JavaScript
PrestonPhelan/RabbitsVsWolves
/predator.js
UTF-8
2,305
2.90625
3
[]
no_license
const Animal = require("./animal"); const Util = require('./util'); class Predator extends Animal { constructor(options = {}) { super(options); this.speed = 5; this.radius = 10; this.color = "#ff0000"; this.prevMove = [0, 0]; this.destination = null; } eating() { } getMove(prey, predators) { let closestDistance; let closestAnimal; prey.forEach( food => { if (!food.alive) { return; } let distance = Util.calcDistance(food.pos, this.pos); if (!closestDistance || distance < closestDistance) { closestDistance = distance; closestAnimal = food; } }); if (closestDistance <= this.radius) { console.log("Eat"); this.eating(); closestAnimal.eaten(); this.movement = [0, 0]; return; } if (this.food > 1 && !this.onReproductionCooldown) { //TODO adjust food as appropriate predators.forEach( mate => { if (mate === this || !mate.alive || mate.onReproductionCooldown) { return; } let distance = Util.calcDistance(mate.pos, this.pos); if (!closestDistance || distance < closestDistance) { closestDistance = distance; closestAnimal = mate; } }); } //Get target's current position & movement if (closestDistance <= this.radius && !closestAnimal.onReproductionCooldown) { console.log("Mating"); this.mate(); } this.movement = Util.pursuitAngle(this.pos, closestAnimal.pos, closestAnimal.movement); } mate() { this.onReproductionCooldown = true; this.game.predators.push(new Predator({game: this.game})); } update(prey, predators) { if (this.removed) { return; } if (!this.alive) { this.deathCounter(); } if (this.starved()) { this.death(); return; } if (this.onReproductionCooldown) { this.ReproductionCooldownCounter += 1; if (this.ReproductionCooldownCounter === 250) { this.onReproductionCooldown = false; this.ReproductionCooldownCounter = 0; } } this.getMove(prey, predators); this.move(); } //AI on Deciding Move //Sniff? //Starving? //Check if previous move is same direction as current } module.exports = Predator;
true
8af7238fa798245380f0c9f9bcbc54a6c3474182
JavaScript
Kolyannik/JsonClassSerializer
/src/serializer.js
UTF-8
10,656
3.171875
3
[]
no_license
var uuid = 0; // уникальный идентификтор объекта /** * проверить, что переменная является объектом * @param {any} value переменная * @returns {boolean} результат проверки */ function isObject(value) { return value !== null && typeof value === 'object'; } /** * проверить, что переменная является строкой * @param {any} value переменная * @returns {boolean} результат проверки */ function isString(value) { return typeof value === 'string' || value instanceof String; } /** * проверить, что переменная является целым числом * @param {any} value переменная * @returns {boolean} результат проверки */ function isInteger(value) { return !isString(value) && parseInt(value) === value; } /** * контекст сериализации */ class SerializationContext { /** * конструктор * @param {Serializer} ser сериализатор */ constructor(ser) { this.__proto__.__proto__ = ser; this.cache = []; // кэш сериализованных объектов this.index = 0; // идентификатор объекта для ссылки } /** * сериализовать объект * @param {any} val объект * @returns {string} строка */ serialize(val) { if (Array.isArray(val)) { // массив return this.serializeArray(val); } else if (isObject(val)) { // объект if (this._ignore.some(e => val instanceof e)) { // игнорируемый тип return undefined; } else { return this.serializeObject(val); } } else { // прочие значения return val; } } /** * сериализовать массив * @param {Array} val массив * @returns {Array} результат */ serializeArray(val) { let res = []; for (let item of val) { let e = this.serialize(item); if (typeof e !== 'undefined') res.push(e); } return res; } /** * сериализовать объект * @param {Object} val объект * @returns {Object} результат */ serializeObject(val) { let name = this._ctorToName[val.constructor]; if (name) { // зарегистрированный для сериализации тип if (!val.__uuid) val.__uuid = ++uuid; let cached = this.cache[val.__uuid]; if (cached) { // объект есть в кэше if (!cached.index) { // индекс еще не назначен cached.index = ++this.index; let key = Object.keys(cached.ref)[0]; let old = cached.ref[key]; cached.ref[`@${name}|${cached.index}`] = old; delete cached.ref[key]; } // возвращаем ссылку на объект return { [`@${name}`]: cached.index }; } else { let res; let cached = { ref: { [`@${name}`]: {} } }; this.cache[val.__uuid] = cached; if (typeof val.serialize === 'function') { // класс реализует интерфейс сериализации res = val.serialize(); } else { // обычная сериализация res = this.serializeObjectInner(val); } cached.ref[Object.keys(cached.ref)[0]] = res; return cached.ref; } } else { // простой объект return this.serializeObjectInner(val); } } /** * сериализовать объект * @param {Object} val объект * @returns {Object} результат */ serializeObjectInner(val) { let res = {}; for (let key of Object.getOwnPropertyNames(val)) { if (!(isString(key) && key.startsWith('__'))) { // игнорируем поля, начинающиеся на два символа подчеркивания res[key] = this.serialize(val[key]); } } return res; } } /** * контекст десериализации */ class DeserializationContext { /** * конструктор * @param {Serializer} ser сериализатор */ constructor(ser) { this.__proto__.__proto__ = ser; this.cache = []; // кэш сериализованных объектов } /** * десериализовать объект json * @param {any} val объект json * @returns {any} объект */ deserialize(val) { if (Array.isArray(val)) { // массив return this.deserializeArray(val); } else if (isObject(val)) { // объект return this.deserializeObject(val); } else { // прочие значения return val; } } /** * десериализовать объект * @param {Object} val объект * @returns {Object} результат */ deserializeArray(val) { return val.map(item => this.deserialize(item)); } /** * десериализовать массив * @param {Array} val массив * @returns {Array} результат */ deserializeObject(val) { let res = {}; for (let key of Object.getOwnPropertyNames(val)) { let data = val[key]; if (isString(key) && key.startsWith('@')) { // указание типа if (isInteger(data)) { // ссылка res = this.cache[data]; if (res) { return res; } else { console.error(`Не найден объект с идентификатором ${data}`); return data; } } else { // описание объекта let [name, id] = key.substr(1).split('|'); let ctor = this._nameToCtor[name]; if (ctor) { // конструктор есть в описании res = new ctor(); // сохраняем в кэше, если указан айдишник if (id) this.cache[id] = res; if (typeof res.deserialize === 'function') { // класс реализует интерфейс сериализации res.deserialize(data); } else { // десериализуем свойства объекта for (let key of Object.getOwnPropertyNames(data)) { res[key] = this.deserialize(data[key]); } } return res; } else { // конструктор не найден console.error(`Конструктор типа "${name}" не найден.`); return val[key]; } } } else { // простое поле res[key] = this.deserialize(val[key]); } } return res; } } /** * сериализатор */ export default class Serializer { /** * конструктор */ constructor() { this._nameToCtor = []; // словарь сопоставлений типов this._ctorToName = []; // словарь сопоставлений типов this._ignore = [Element]; // список игнорируемых типов } /** * зарегистрировать сопоставление * @param {string} alias псевдоним * @param {Function} ctor конструктор */ register(alias, ctor) { if (typeof ctor === 'undefined' && typeof alias === 'function') { // передан один аргумент - конструктор ctor = alias; alias = ctor.name; } this._nameToCtor[alias] = ctor; this._ctorToName[ctor] = alias; } /** * зарегистрировать тип для игнорирования * @param {Function} ctor конструктор */ ignore(ctor) { if (this._ignore.indexOf(ctor) < 0) { this._ignore.push(ctor); } } /** * сериализовать объект * @param {any} val объект * @param {Function} [replacer] функция преобразования или массив свойств сериализации * @param {string} [space] для отступов * @returns {string} строка */ serialize(val, replacer, space) { return JSON.stringify(new SerializationContext(this).serialize(val), replacer, space); } /** * десериализовать строку или объект json * @param {any} val строка или объект json * @returns {any} объект */ deserialize(val) { // преобразуем строку в объект if (isString(val)) val = JSON.parse(val); return new DeserializationContext(this).deserialize(val); } }
true
b0b98d4ef5dde11cda1231008e572e902fac83bd
JavaScript
Abhishekdabas/Nagarro_WebTraining_2018_April
/Day4/NodeJSBasics/sample_package/server_middlewares.js
UTF-8
914
2.9375
3
[]
no_license
const express = require('express') const app = express() app.use(function (req, res, next) { console.log("I always run") next() }) app.use('/b', (req, res, next) => { console.log("I run whenever you ask for /b") next() }) app.use('/a', (req, res, next) => { console.log("I run whenever you ask for /a") next() }) app.get('/a', (req, res) => { console.log("You requested a") res.send("a") }) app.get('/a/b', (req, res) => { console.log("You requested a/b") res.send("a/b") }) app.get('/b/a', (req, res) => { console.log("You requested b/a") res.send("b/a") }) app.get('/b/c', (req, res) => { let a = [1, 2] res.send( ` <ul> <li>${a[0]}</li> <li>${Math.pow(a[1], 3)}</li> </ul> ` ) }) app.use(function (req, res) { res.status(404).send("<h1>No such page found</h1>") }) app.listen(8181)
true
80e2144ad860dd56f8e166dd6b02455a887f3893
JavaScript
VA-HCA2/Week1
/Week1/Mod2/MyWork/SimpleMathScripts/netWorth.js
UTF-8
124
2.703125
3
[]
no_license
"use strict"; var assets=6000; var debts=3000; var netWorth=assets-debts; console.log("Your net worth is " +netWorth);
true
c6db7500f9d4fad82a57b1ac9756bf327831a3de
JavaScript
rhyolight/chess-moves
/war/js/chess.js
UTF-8
2,633
2.609375
3
[]
no_license
var CHESS = { dropMove: function($piece, $from, $to, msg) { $('td.cell').removeClass('highlight'); if (msg.indexOf('SUCCESS') > -1) { $from.empty(); $to.empty(); $to.append($piece); $piece.attr('style', 'position: relative') .addClass('ui-draggable') .mouseover(this.chessImageOver) .mouseout(this.dehighlightAll) .draggable(); } else { alert(msg); } }, chessImageOver: function() { $.ajax({ type: "POST", url: "/possibleMoves.groovy", data: "cellDescriptor=" + $(this).parent().attr('id'), success: function(msg){ var moves = msg.split(','); for (var i in moves) { $('#' + moves[i]).addClass('highlight'); } } }); }, dehighlightAll: function() { $cells.removeClass('highlight'); } }; $(function() { $chessImages = $('.cell img'); $cells = $('td.cell'); $chessImages.mouseover(CHESS.chessImageOver); $chessImages.mouseout(CHESS.dehighlightAll); $chessImages.draggable(); $cells.droppable({ activate: function(evt, ui) { $chessImages.droppable('disable'); }, drop: function(evt, ui) { $pieceImg = $(ui.draggable); $cell = $(this); $previousCell = $pieceImg.parent(); if ($cell.attr('id') != $previousCell.attr('id')) { $.ajax({ type: "POST", url: "/makeMove.groovy", data: "from=" + $previousCell.attr('id') + "&to=" + $cell.attr('id'), success: function(msg) { CHESS.dropMove($pieceImg, $previousCell, $cell, msg) }, faiure: function(msg) { alert('there was an unexpected error: ' + msg); } }); } $chessImages.droppable('enable'); } }); $('span.allMoves').mouseover(function() { var side = $(this).text(); $.ajax({ type: "POST", url: "/possibleMoves.groovy", data: "allMoves=" + side, success: function(msg){ var moves = msg.split(','); for (var i in moves) { $('#' + moves[i]).addClass('highlight'); } } }); }).mouseout(CHESS.dehighlightAll); });
true
ec3ec026427769653debe89c24347b27d85f2ddc
JavaScript
dstroot/react-storybook-lib
/src/components/CookieMessageRTL/index.test.js
UTF-8
4,738
2.8125
3
[]
no_license
import React from 'react'; /** * The react-testing-library is a very lightweight solution for testing React components. * It provides light utility functions on top of react-dom and react-dom/test-utils, * in a way that encourages better testing practices. */ // React test library import { render, fireEvent, cleanup } from '@testing-library/react'; // component to test import CookieMessageRTL from '../CookieMessageRTL'; // automatically unmount and cleanup DOM after each test is finished. afterEach(cleanup); // tests describe('CookieMessageRTL', () => { it('it should render', () => { /** * By default, react-testing-library will create a div and * append that div to the document.body and this is where * your react component will be rendered. */ const { container } = render(<CookieMessageRTL />); expect(container.firstChild).toMatchSnapshot(); }); it('it should be at the bottom of the page', () => { const { getByTestId } = render(<CookieMessageRTL />); expect(getByTestId('cookie-message')).toHaveClass('fixed-bottom bg-dark'); }); it('it should contain the expected text', () => { const { getByText } = render(<CookieMessageRTL />); const element = getByText( `We use cookies to understand the performance of our web site, enable social media features, and serve more relevant content to you. We may also use cookies on our and our partners’ behalf to help us manage advertising and assess the performance of our campaigns. For further information please see our`, { exact: false } ); expect(element).toBeInTheDocument(); }); it('it should have a link to /cookiepolicy', () => { const { getByTitle } = render(<CookieMessageRTL />); expect(getByTitle('Cookie Policy.')).toBeInTheDocument(); }); it('it should have a button that says "I agree"', () => { const { getByText } = render(<CookieMessageRTL />); const button = getByText('I Agree'); expect(button).toBeInTheDocument(); expect(button).toHaveClass('btn'); }); it('it should disappear when the button is clicked', () => { // setup const { getByText, container } = render(<CookieMessageRTL />); // assert - componment exists expect(container.firstChild).toBeInTheDocument(); // action - click button const button = getByText('I Agree'); fireEvent.click(button); // assert - component no longer exists in DOM expect(container.firstChild).toBeNull(); expect(container.firstChild).toMatchSnapshot(); }); }); /** * Custom matchers: * - toBeDisabled * - toBeEnabled * - toBeEmpty * - toBeInTheDocument * - toBeInvalid * - toBeRequired * - toBeValid * - toBeVisible * - toContainElement * - toContainHTML * - toHaveAttribute * - toHaveClass * - toHaveFocus * - toHaveFormValues * - toHaveStyle * - toHaveTextContent */ /** * Based on the Guiding Principles, your test should resemble how users * interact with your code (component, page, etc.) as much as possible. * With this in mind, we recommend this order of priority: * Queries Accessible to Everyone queries that reflect the experience * of visual/mouse users as well as those that use assistive technology * * **getByLabelText**: Only really good for form fields, but this is the * number one method a user finds those elements, so it should be your top preference. * * **getByPlaceholderText**: A placeholder is not a substitute for a label. But if * that's all you have, then it's better than alternatives. * * getByText: Not useful for forms, but this is the number 1 method a user * finds other elements (like buttons to click), so it should be your top * preference for non-form elements. * * getByDisplayValue: The current value of a form element can be useful when * navigating a page with filled-in values. * * Semantic Queries HTML5 and ARIA compliant selectors. Note that the user * experience of interacting with these attributes varies greatly across * browsers and assistive technology. * * **getByAltText**: If your element is one which supports alt text (img, area, * and input), then you can use this to find that element. ` *` * **getByTitle**: The title attribute is not consistently read by screenreaders, * and is not visible by default for sighted users. * * **getByRole**: This can be used to select dialog boxes and other * difficult-to-capture elements in a more semantic way * * Test IDs * * **getByTestId**: The user cannot see (or hear) these, so this is only * recommended for cases where you can't match by text or it doesn't make * sense (the text is dynamic). */
true
6fee2e134b485b8a593f2276ab5efdf12041290d
JavaScript
qwerty6016/asteroids-harvesters
/public/game-loop.js
UTF-8
3,480
3
3
[ "MIT" ]
permissive
const statCanvas = document.getElementById('staticCanvas'); const statCtx = statCanvas.getContext("2d"); const statWidth = statCanvas.width; const statHeight = statCanvas.height; const dynCanvas = document.getElementById('dynamicCanvas'); const dynCtx = dynCanvas.getContext("2d"); const dynWidth = dynCanvas.width; const dynHeight = dynCanvas.height; let data = null; let ships = null; // display alert if size of staticCanvas not equal to size of dynamicCanvas if (statWidth != dynWidth || statHeight != dynHeight) alert("Different width/height of canvases! statWidth = " + statWidth + ", dynWidth = " + dynWidth + "; statHeight = " + statHeight + ", dynHeight = " + dynHeight); // draw staticCanvas background statCtx.fillStyle = "#000d23"; statCtx.fillRect(0, 0, statWidth, statHeight); function animFrame(){ requestAnimationFrame(animFrame, dynCanvas); gameLoop(); }; function gameLoop() { dynCtx.clearRect(0, 0, dynWidth, dynHeight); drawStarsAndAsteroids(data.starsYellow, "yellow", data.starsSize); drawStarsAndAsteroids(data.starsWhite, "white", data.starsSize); drawStarsAndAsteroids(data.asteroids1, data.asteroids1[0].color, data.asteroidsSize); drawStarsAndAsteroids(data.asteroids2, data.asteroids2[0].color, data.asteroidsSize); drawStarsAndAsteroids(data.asteroids3, data.asteroids3[0].color, data.asteroidsSize); drawProjectiles(); for (let k in ships) { if (!ships[k].disconnected) { drawPlayerShip(ships[k]); } else { delete ships[k]; } }; }; function drawStarsAndAsteroids(starsOrAsteroids, color, size) { dynCtx.fillStyle = color; for(let i = 0; i < starsOrAsteroids.length; i++) { dynCtx.beginPath(); dynCtx.arc(starsOrAsteroids[i].x, starsOrAsteroids[i].y, size, 0, Math.PI*2, true); dynCtx.fill(); }; }; function drawPlayerShip(playerShip) { dynCtx.fillStyle = "#a8a8a8"; dynCtx.fillRect(playerShip.currentPosition.x, playerShip.currentPosition.y, playerShip.weaponSize.x, playerShip.weaponSize.y); dynCtx.fillRect(playerShip.currentPosition.x + playerShip.size.x - playerShip.weaponSize.x, playerShip.currentPosition.y, playerShip.weaponSize.x, playerShip.weaponSize.y); dynCtx.fillStyle = data.colors[playerShip.platformColorNum]; dynCtx.fillRect(playerShip.currentPosition.x + playerShip.weaponSize.x, playerShip.currentPosition.y + playerShip.platformSize.y, playerShip.platformSize.x, playerShip.platformSize.y); dynCtx.font = "15px Comic Sans MS"; dynCtx.textAlign = "center"; dynCtx.fillStyle = "black"; dynCtx.fillText(playerShip.playerNumber, playerShip.currentPosition.x + playerShip.weaponXCenter, playerShip.currentPosition.y + playerShip.weaponYCenter); dynCtx.fillStyle = "white"; dynCtx.fillText(playerShip.score, playerShip.currentPosition.x + playerShip.shipXCenter, playerShip.currentPosition.y + playerShip.size.y - 10); dynCtx.fillStyle = data.colors[playerShip.platformColorNum]; for(let i = 0; i < playerShip.platformCargoFilledSpace; i++) { dynCtx.fillRect(playerShip.currentPosition.x + playerShip.weaponSize.x + playerShip.platformCargoUnitSize.x * i, playerShip.currentPosition.y, playerShip.platformCargoUnitSize.x, playerShip.platformCargoUnitSize.y); }; }; function drawProjectiles() { dynCtx.fillStyle = data.projectileColor; for(let i = 0; i < data.projectiles.length; i++) { dynCtx.fillRect(data.projectiles[i].x, data.projectiles[i].y, data.projectileSize.x, data.projectileSize.y); }; };
true
a135d2b7b1df81c13af53ed33b10d447ada613bf
JavaScript
gabrielflorit/enter-view
/enter-view.js
UTF-8
3,290
2.71875
3
[ "MIT" ]
permissive
/* * enter-view.js is library */ (function(factory) { if (typeof define === 'function' && define.amd) { define(factory); } else if (typeof module !== 'undefined' && module.exports) { module.exports = factory(); } else { window.enterView = factory.call(this); } })(function() { const lib = function(opts) { let raf; let ticking; let distanceFromTop; let elements; const init = function() { hasValidOptions( err => { if (err) { console.error(err); } else { setupRaf(); setupElements(); setupEvents(); updateScroll(); } }); }; const hasValidOptions = function(cb) { const required = ['selector', 'trigger']; for (let r in required) { if (!opts[required[r]]) { cb('missing parameter: ' + required[r]); return; } } cb(null); }; const setupRaf = function() { raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { return setTimeout(callback, 1000 / 60); }; }; const setupElements = function() { // store all matching elements const nodeList = document.querySelectorAll(opts.selector); elements = []; for (let i = 0; i < nodeList.length; i++) { elements.push(nodeList[i]); } }; const setupEvents = function() { window.addEventListener('resize', onResize, true); window.addEventListener('scroll', onScroll, true); // call once on init onResize(); }; const onResize = function() { // calculate offset from top to trigger at distanceFromTop = getOffset(); updateScroll(); }; const onScroll = function() { if (!ticking) { ticking = true; requestAnimationFrame(updateScroll); } }; const updateScroll = function() { ticking = false; elements = elements.filter( el => { const rect = el.getBoundingClientRect(); const top = rect.top; const bottom = rect.bottom; if (top < distanceFromTop) { opts.trigger(el); return false; } return true; }); if (!elements.length) { window.removeEventListener('scroll', onScroll, true); } }; const getOffset = function() { const h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); if (opts.offset) { const num = parseInt(opts.offset.replace('%', '')) / 100; const fraction = Math.max(0, Math.min(100, num)); return h - fraction * h; } return h; }; init(); }; return lib; });
true
cb0553c3b5b05ac8cf2234ca56a333ce3953ea75
JavaScript
gmeluski/quartet
/src/js/answerStore.js
UTF-8
663
3.078125
3
[]
no_license
class answerStore { constructor() { this.answerData = Array(9).fill(0) this.hello = this.hello } /* * getter for answers * * @return {Array} */ get answers() { return this.answerData } /** * getter for the total * * @return {Number} */ get total() { return this.answerData.reduce((previousValue, currentValue) => { return parseInt(previousValue, 10) + parseInt(currentValue, 10) }, 0) } /** * setter for the answers * * @param {String} position * @param {String} value */ setAnswer(position, value) { this.answerData[position] = value } } export default answerStore
true
790a565d7a1febdacdbbe93da169f58edd2dc13b
JavaScript
yuda-lyu/w-restapi
/src/routesToAPI.mjs
UTF-8
4,844
2.671875
3
[ "MIT" ]
permissive
import each from 'lodash/each' import genPm from 'wsemi/src/genPm.mjs' import isstr from 'wsemi/src/isstr.mjs' /** * 由Routes陣列資料轉hapi的API資料陣列 * * @param {Array} [routes=[]] 輸入需自動產製的routes資料陣列,每個元素需有'apiName'欄位,其值給予表名字串,'props'欄位,其值給予欄位物件,預設[] * @param {String} [apiParent='api'] 輸入api上層路徑字串,預設'api' * @param {Function} [proc=() => {}] 輸入各api處理函數,prop會傳入method(API method),apiName(表名),propName(指定欄位名稱),propValue(指定欄位值),payload(post時數據),req(hapi的req),res(hapi的res),pm(回傳用Promise),處理完畢後成功時呼叫pm.resolve回傳,失敗時呼叫pm.reject回傳,預設()=>{} * @returns {Array} 回傳hapi的API資料陣列 */ function routesToAPI(routes = [], apiParent = '', proc = () => {}) { //apis let apis = [] //basePath let basePath = `/` if (isstr(apiParent)) { basePath = `/${apiParent}/` } //each routes each(routes, (v) => { let r //GET all r = { path: basePath + v.apiName, method: 'GET', handler: function (req, res) { let pm = genPm() proc({ method: 'GET', apiName: v.apiName, propName: null, propValue: null, payload: null, req, res, pm, }) return pm }, } apis.push(r) //GET props each(v.props, (vv, col) => { r = { path: basePath + v.apiName + `/${col}/{${col}}`, method: 'GET', handler: function (req, res) { let pm = genPm() let p = req.params proc({ method: 'GET', apiName: v.apiName, propName: col, propValue: p[col], payload: null, req, res, pm, }) return pm }, } apis.push(r) }) //POST, PUT each(['POST', 'PUT'], (method) => { //POST, PUT all r = { path: basePath + v.apiName, method, handler: function (req, res) { let pm = genPm() let data = req.payload proc({ method, apiName: v.apiName, propName: null, propValue: null, payload: data, req, res, pm, }) return pm }, } apis.push(r) //POST, PUT props each(v.props, (vv, col) => { r = { path: basePath + v.apiName + `/${col}/{${col}}`, method, handler: function (req, res) { let pm = genPm() let p = req.params let data = req.payload proc({ method, apiName: v.apiName, propName: col, propValue: p[col], payload: data, req, res, pm, }) return pm }, } apis.push(r) }) }) //因安全因素不使用DELETE all //DELETE props each(v.props, (vv, col) => { r = { path: basePath + v.apiName + `/${col}/{${col}}`, method: 'DELETE', handler: function (req, res) { let pm = genPm() let p = req.params proc({ method: 'DELETE', apiName: v.apiName, propName: col, propValue: p[col], payload: null, req, res, pm, }) return pm }, } apis.push(r) }) }) return apis } export default routesToAPI
true
040e20be45ac29b39a77ed018b094c47b16f400b
JavaScript
Shanker-Suryakumar/ReactNativeLearning
/js-demos/jsdemos/demo10-functions.js
UTF-8
537
4.15625
4
[]
no_license
function plus(x,y){ //plus is available in global context return x+y; } let sum=plus; //sum is another name added global context console.log('plus(10,20)',plus(10,20)); console.log('sum(10,20)',sum(10,20)); //if minus is not accessible, do I need this word? // we can create anonymous functions //ANONYMOUS FUNCTION let substract =function (x,y){ return x-y; } //here substract is available in the context console.log('substract(20,14)',substract(20,14)); console.log('substract.name',substract.name);
true
0a0d3a4d18d4b1a68630f35e058fbe9bca098638
JavaScript
wguilherme/uri-javascript-exercicios-resolvidos
/INICIANTE/1011.js
UTF-8
656
4.125
4
[ "MIT" ]
permissive
/* Faça um programa que calcule e mostre o volume de uma esfera sendo fornecido o valor de seu raio (R). A fórmula para calcular o volume é: (4/3) * pi * R3. Considere (atribua) para pi o valor 3.14159. Dica: Ao utilizar a fórmula, procure usar (4/3.0) ou (4.0/3), pois algumas linguagens (dentre elas o C++), assumem que o resultado da divisão entre dois inteiros é outro inteiro.*/ var input = require('fs').readFileSync('/dev/stdin', 'utf8'); var lines = input.split('\n'); var raio = parseFloat(lines.shift()).toFixed(2); var pi = 3.14159; var volume = (4/3) * pi * Math.pow(raio, 3); console.log("VOLUME = " + parseFloat(volume).toFixed(3));
true
9f5817ef0d1580390a777aebbb7f155569c2c54c
JavaScript
ReaganBruce/JStoTSConversions
/console-resume-ts/app.js
UTF-8
1,667
3.421875
3
[]
no_license
"use strict"; var myName = "Reagan"; var myCareer = "Software Dev"; var myDescription = "I like to code and problem solve!"; console.log("Name: " + myName.toUpperCase()); console.log("Career: " + myCareer); console.log("Description: " + myDescription); console.log(''); console.log("My name is " + myName.toUpperCase() + " and I'm a " + myCareer + " and I'm a " + myDescription); console.log(''); var interestArray = ['Drumming', 'Reading', 'Touring', 'Eating']; console.log('My Interests: '); for (var i = 0; i < interestArray.length; i++) { console.log("* " + interestArray[i]); } console.log(''); var myPrevExperienceArray = [ { jobTitle: "Crew Member", companyTitle: "Trader Joes", jobDescription: "Annoyed Customers" }, { jobTitle: "Worker", companyTitle: "Work Inc", jobDescription: "Worked at a job" }, { jobTitle: "Just a Guy", companyTitle: "Cool Guy Stuff", jobDescription: "Did cool stuff" } ]; console.log('My Previous Experience: '); for (var _i = 0, myPrevExperienceArray_1 = myPrevExperienceArray; _i < myPrevExperienceArray_1.length; _i++) { var index = myPrevExperienceArray_1[_i]; console.log("* " + index.jobTitle + " at " + index.companyTitle + " - " + index.jobDescription); } console.log(''); console.log('My Skills: '); var mySkillsArr = ['Drumming', 'Driving', 'Reading', 'Cooking']; for (var i = 0; i < mySkillsArr.length; i++) { displaySkill(mySkillsArr[i], true); } function displaySkill(skillName, isCool) { if (isCool) { console.log("* Bam: " + skillName); } else { console.log(skillName); } }
true
f58e03b767a882a467e169776ae9418831167ded
JavaScript
Lokesh-tkri/fullstackopen
/part2/App.js
UTF-8
1,006
2.890625
3
[ "MIT" ]
permissive
const Header = ({name}) => { return ( <h2>{name}</h2> ) } const Total = ({ parts }) => { let exer = parts.map((part)=>part.exercises) const sum = exer.reduce((s,p) => s+p) return( <h2><p>Number of exercises {sum}</p></h2> ) } const Part = ({part}) => { return ( <p> {part.name} {part.exercises} </p> ) } const Content = ({parts}) => { return ( <div> {parts.map((part) => (<Part key={part.id} part={part} />))} </div> ) } const Course = ({course}) => { return ( <> <Header name={course.name} /> <Content parts={course.parts} /> <Total parts={course.parts} /> </> ) } const App = ({courses}) => { return ( <div> <h1> Web development curricullum</h1> <br /> {courses.map((course) => { return <Course key={course.id} course={course} />})} </div> ) }; export default App;
true
6780f522feb23e442322c30a80d6993dcf5830b5
JavaScript
Anjola85/simple-martplace-backend-api
/src/utils/helper.js
UTF-8
2,230
2.796875
3
[]
no_license
import config from 'config'; import NodeGeocoder from 'node-geocoder'; import slugify from 'slugify'; import {User} from "../rest/v1/user/user.model"; /** * @param {Number} size Hour count * @return {Date} The date * */ export const addHourToDate = (size) => { const date = new Date(); let hours = date.getHours() + 1; date.setHours(hours); return date; }; /** * @param {Number} size code length * @param {Boolean} alpha Check if it's alpha numeral * @return {String} The code **/ export const generateOTCode = (size = 4, alpha = false) => { let characters = alpha ? '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' : '0123456789'; characters = characters.split(''); let selections = ''; for (let i = 0; i < size; i++) { let index = Math.floor(Math.random() * characters.length); selections += characters[index]; characters.splice(index, 1); } return selections; }; /** * This will setup auth seeded data * @param {Number} count **/ export const seedAccount = async (count = 5) => { try { await User.deleteMany({}).exec(); for (let i = 0; i < count; i++) { const auth = await new User({ email: `user${i + 1}@gmail.com`, password: 'password', account_verified: true }); this.auth = await auth.save(); } } catch (e) { console.log('seeding exception:::::', e); } }; /** * @param {Object} address The String for the address * @param {Object} options * @return {Object} * */ export const addressToLatLng = async (address, options = {}) => { const geocoder = NodeGeocoder({ provider: config.get('google.credentials.provider'), apiKey: config.get('google.credentials.apiKey'), ...options }); return geocoder.geocode(address); }; /** * Convert callback to promise * @param {String} text * @param {String} params date * @return {String} * */ export const slugifyText = (text) => { if (text === null || typeof text === 'undefined') { return text; } if (text.indexOf(' ') > 0) { return slugify(text.toLowerCase()); } return text.toLowerCase(); };
true
3ead5fd5ddfb48bc4cd34c8b11b2e0e6ad6e0211
JavaScript
CourtneyBrothers/group-project-company-site-lucky-tundra-mimes
/main.js
UTF-8
1,420
3.03125
3
[]
no_license
kayakList = [ { name:"Mamba", price:"$879", description:"Our lightest playboat", url:"kayak1.jpg" }, { name :"Zen", price:"$579", description:"Great for beginners", url:"kayak2.jpg" }, { name : "Angler", price : "$779", description: "For the seasoned sportsman", url: "kayak3.jpg" }, { name : "Outback", price : "$1179", description: "The workhorse", url: "kayak4.jpg" }, { name : "Barracuda", price : "$579", description: "Versatile sit-on-top", url: "kayak5.jpg" }, { name : "Kraken", price : "$479", description: "Speedy and nimble", url: "kayak6.jpg" }, { name : "Nomad", price : "$979", description: "Rugged playboat", url: "kayak7.jpg" }, { name : "Big Rig", price : "$1279", description: "Extra stable and roomy", url: "kayak8.jpg" } ]; function cardAssign() { let empty = ""; for (var i=0; i < kayakList.length; i++) { let productName = `<div class="card"><p>Name: ${kayakList[i].name}</p><p>Price: ${kayakList[i].price}</p><p>Description: ${kayakList[i].description}</p><img src=${kayakList[i].url} alt="kayak product"></div>`; empty += productName; console.log('this is each card',empty); }; console.log('this is your complete HTML',empty); document.querySelector(".container").innerHTML = empty; }; cardAssign();
true
2ca83e788b2352e1e7209e777bf94821c6982831
JavaScript
Maxim-Pekov/modal-Window
/script.js
UTF-8
891
2.703125
3
[]
no_license
let btnModal = document.querySelector('.modalBtn'), overlay = document.querySelector('.modal') close = document.querySelector('.modal-close'); btnModal.addEventListener('click', function(){ //overlay.style.display ='block'; overlay.classList.remove('hidden'); overlay.classList.add('open'); document.body.style.overflow ='hidden';// при вызове модального окна задний фон не подвижный }) close.addEventListener('click', function(){ overlay.classList.add('hidden'); overlay.classList.remove('open'); document.body.style.overflow =''; // делает задний фон подвижным }) overlay.addEventListener('click', function(event){ if(!event.target.closest('.modal-content')){ this.classList.add('hidden'); this.classList.remove('open'); document.body.style.overflow =''; } })
true
43072c4af56ed642bcc4d6f1496e2f80d51a5c49
JavaScript
echandler/ExamplesByMesh
/HTML5/EaselJS/PixelFlow/scripts/main.js
UTF-8
25,314
2.703125
3
[ "MIT" ]
permissive
/* The MIT License Copyright (c) 2011 Mike Chambers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //listen for when the window finishes loaded. x$(window).load(init); var stage, canvas, canvasWrapper; var canvasOffset = {top:0, left:0}; //hash to store multitple drones //when on a multitouch device var drones = {length:0}; //the last drone that was created var lastDrone; //image selected by the user to pull images from var image; //XUI object for the overlay canvas var canvasOverlayWrapper; var overlayStage; //canvas offset. we cache for performance reasons //so we dont have to recalculate it all of the time var canvasOverlayOffset = {top:0, left:0}; //items for the overlay graphics var targetShape, lineShape, targetColor, lineGraphics; var isFirefox = false; var hasTouchSupport = false; //event names for transform and transition end //since webkit and mozilla based browsers have different names for each var transformName, transitionEndName; //Global instance so it cna be accessed from anywhere. //this stores var PD = new PixelData(); //viewport dimensions for container / browser var viewport = {height:0, width:0}; /************** initialization methods **************/ //called once the page has loaded function init() { //whether we should abort initialization //because we find the browser doesnt support something //that we need var abort = false; //check for canvas if(!Modernizr.canvas) { x$("#canvasSupport").setStyle("color", "#FF0000"); abort = true; } //check for CSS transitions if(!Modernizr.csstransitions) { abort = true; x$("#transitionSupport").setStyle("color", "#FF0000"); } //check for CSS transforms if(!Modernizr.csstransforms) { abort = true; x$("#transformSupport").setStyle("color", "#FF0000"); } if(abort) { //if something isnt supported that we need, //display the noSupport dialog x$("#noSupport").setStyle("display", "block"); //and stop initializing return; } //XUI element for main canvas canvasWrapper = x$("#mainCanvas"); //check if we are running in firefox isFirefox = (navigator.userAgent.indexOf("Firefox") != -1); //Firefox 4 beta has support for touch events on Windows 7 //but, i havent been able to develop on one, and since it uses //a different touch api than webkit, im not going to try and support //it right now. //so, basically, if its Firefox, we say not touch hasTouchSupport = Modernizr.touch && !isFirefox; if(!hasTouchSupport) { //listen for mousedown on the image select screen x$(".imageButton").on("mousedown", onImageSelectDown); } else { //on iOS mousedown has significant lag in firing, so we //listen for touchstart on touch devices x$(".imageButton").on("touchstart", onImageSelectDown); //listen for all touchmove events made in the documet //so we can cancel them (and prevent the user from moving //the page around) x$(document).on("touchmove", onDocumentTouchMove); } //set css style names depending on firefox / webkit if(isFirefox) { transformName = "-moz-transform"; transitionEndName = "transitionend"; } else { transformName = "webkitTransform"; transitionEndName = "webkitTransitionEnd"; } //check if the browser supports the canvas.toDataURL API //Andorid doesn't if(!supportsToDataURL()) { //if it doesnt, disable the save image button x$("#saveButtonSpan").setStyle("display", "none"); } } //initializes the drawing canvas function initCanvas() { //get a reference to the actual canvas element //todo: make sure this is the canvas element canvas = canvasWrapper[0]; //initialize the Stage instance with the Canvas. Note, //canvasWrapper is a JQuery object, but stage expects //the actual Canvas element. stage = new Stage(canvas); //set autoClear to false, so the stage is not //cleared between renders (when stage.tick()) is called stage.autoClear = false; //string to use for how to save an image var instructionString; if(hasTouchSupport) { //we are on a touch device //listen for touch events for drawing canvasWrapper.on("touchstart", onTouchStart); canvasWrapper.on("touchend", onTouchEnd); instructionString = "Touch and Hold Image to Save"; } else { instructionString = "Right Click Image to Save"; //if it doesnt have touch support, then we assume //it is a mouse based computer //and we display the overlay graphic //We dont show the overlay on touch devices, and currently most touch //devices (smart phones and tablets) are not fast enough to manager both canvases //ideally we could profile based on performance, but for now, we are just doing //it based on input //overlay canvas used to draw target and line //note we dynamically add it, instead of removing it so we can save //some processing / initialization on touch devices canvasWrapper.after('<canvas id="overlayCanvas"></canvas>'); canvasOverlayWrapper = x$("#overlayCanvas"); //listen for a click event on the overlay canvasOverlayWrapper.on("click", onCanvasClick); //color used to draw target and line targetColor = Graphics.getRGB(0,0,0,.1); //stage to manage the overlay canvas. Need to get the actual //element from the JQuery object. overlayStage = new Stage(canvasOverlayWrapper[0]); //EaselJS Shape that is drawn at the mouse point targetShape = new Target(targetColor); //Shape and graphic used to draw a line from the //Drone to the touch point lineShape = new Shape(); //note: we redraw the graphic a lot, but just resuse the //same Graphics instance (by calling clear). This saves a LOT //of object creation lineGraphics = new Graphics(); lineShape.graphics = lineGraphics; } //set the save image instructions x$("#saveInstructionsSpan").inner(instructionString); //listen for when the window looses focus (so we can pause everything) x$(window).on("blur", onWindowBlur); //set the tick interval to 24 frames per second. Ticker.setInterval(1000/24); //listen for the tick event (time event) //note, the secound argument allows this listener //to be paused Ticker.addListener(window, true); //pause the Tick instance, so it doesnt broadcast //the tick event. (We will unpause when the user clicks //the canvas) Ticker.setPaused(true); } /************* Timer event handler ************/ //called at each time interval. This is essentially the listener //for Ticker.addListener. This is where everything is redrawn and moved. function tick() { //redraw the main stage / canvas stage.update(); //check if we have an overlay graphic if(canvasOverlayWrapper) { //update the overlay line updateLine(); //redraw the overlay stage / canvas overlayStage.update(); } } /************* mouse event handlers *************/ //called when the drawing canvas is clicked (with a mouse) function onCanvasClick(e) { //toggle pause state var paused = !Ticker.getPaused(); Ticker.setPaused(paused); if(paused) { //we are paused //stop listening for mouse move events (and thus stop) //drawing canvasOverlayWrapper.un("mousemove", onMouseMove); //remove the overlay graphics from the stage overlayStage.removeChild(targetShape); overlayStage.removeChild(lineShape); } else { //we are no longer paused //check and see if there is already a drone instance if(lastDrone) { //if so, remove it stage.removeChild(lastDrone); } //create a target for the new drone, based on the current canvas relative //position of the mouse cursor var t = { x:e.pageX - canvasOffset.left, y:e.pageY - canvasOffset.top }; //create a new drone lastDrone = createNewDroneOnPoint(t); //add the drone to the stage stage.addChild(lastDrone); //add the overlay graphics to the stage overlayStage.addChild(targetShape); overlayStage.addChild(lineShape); //position the overlay mouse tracking shape targetShape.x = t.x; targetShape.y = t.y; //start listening for mouse move events canvasOverlayWrapper.on("mousemove", onMouseMove); } //draw the overlay stage overlayStage.update(); } //called when the mouse is moved over the canvas (on mouse based devices) function onMouseMove(e) { //update the the overlay shape position, and the drone's target //with the current canvas relative coordinates targetShape.x = lastDrone.target.x = e.pageX + canvasOffset.left; targetShape.y = lastDrone.target.y = e.pageY + canvasOffset.top; } /************ UI event Handlers / transition events *****************/ //event handler for when an image is selected on the main screen function onImageSelectDown(e) { //unsubscribe from the event x$(".imageButton").un(e.type, onImageSelectDown); //get the image which was clicked image = e.target; //set the thumbnail image to load the selected image. we just pass the url //as the image should be cached x$("#thumbImage").attr("src", image.src); //get a reference to the imageSelectDiv var divXUI = x$("#imageSelectDiv"); //initialize the canvas initCanvas(); //update the screen and canvas dimensions updateCanvasDimensions(); //object to set css properties var css = {}; //note the 100 constant below is the top-padding style for the div, set in the stylesheet. //i should pull this from the CSS and parse it into an int (100px) //do a css transform and move the div off of the screen (up) css[transformName] = "translate(0px,"+ -(viewport.height + 100) + "px)"; //listen for when the transition ends divXUI.on(transitionEndName, onImageSelectTransitionEnd); //set the update style divXUI.css(css); var creditsDiv = x$("#credits"); //move the credits off the bottom of the screen with a css transform creditsDiv.setStyle(transformName, "translate(0px, 200px)"); creditsDiv.on(transitionEndName, onCreditsTransitionEnd); } //called when the credits transition ends function onCreditsTransitionEnd(e) { unsubscribeFromEvent(e).remove(); } //called when the transition from the main screen ends function onImageSelectTransitionEnd(e) { //unsubscribe the event and remove the element from the dom unsubscribeFromEvent(e).remove(); //we have to do this here. If we do it earlier, then it glitches the //gpu on ipad //scale the selected image and copy the pixel data scaleImageData(); var bottomXUI = x$("#bottomBar"); var margin = bottomXUI.getStyle("right"); bottomXUI.css({bottom:margin}); var topXUI = x$("#topBar"); topXUI.css({top:margin}); //listen for when the transition ends bottomXUI.on(transitionEndName, onBottomBarTransitionEnd); } //called when the transition to bring the bottom bar to //the screen ends. function onBottomBarTransitionEnd(e) { //at this point we have completed the transition and are now in the //drawing view //unsubscribe from the event unsubscribeFromEvent(e); //listen for when the window resizes x$(window).on("resize", onWindowResize); //listen for when any of the buttons on the bottom bar are clicked x$(".bottomButton").on("click", onBottomButtonClick); } //called when any of the bottom tab buttons are pressed function onBottomButtonClick(e) { //get the data- attribute associated with the clicked link var action = e.target.getAttribute("data-button"); //figure out which was clicked switch(action) { case "SAVE": { //save button was clicked saveImage(); break; } case "CLEAR": { //clear button was clicked stage.clear(); break; } } } /************** save image methods ****************/ //called when the user has requested to generate an image from the canvas function saveImage() { //get the image data url string from the stage. Create a PNG //with a white background var dataURL = stage.toDataURL("#FFFFFF", "image/png"); var saveImage = x$("#saveImage"); //dont start transition until image has loaded. This is mostly //for smart phones, tablets, which might take a second to process the data //we dont want the image to tween in before it has loaded. saveImage.on("load", onSaveImageLoad); //load the data url in the save image element saveImage.attr("src", dataURL); //open the modal div openModalDiv(); } //called when the image data has loaded into the save image panel function onSaveImageLoad(e) { unsubscribeFromEvent(e); //listen for when the close button is pressed x$("#savePanelCloseLink").on("click", onCloseSavePanelClick); //generate the CSS transform to move the save panel onto the screen var css = {}; css[transformName] = "translate("+ -((viewport.width / 2) + 150) +"px,0px)"; //update the panel styles x$("#savePanel").css(css); } //called when the save panel close button is pressed function onCloseSavePanelClick(e) { unsubscribeFromEvent(e); //close the modal dialog closeModalDiv(); //create the CSS to return the panel to its original position var css = {}; css[transformName] = "translate(0px,0px)"; var savePanel = x$("#savePanel"); //update the css savePanel.css(css); //listen for when the transition ends savePanel.on(transitionEndName, onSaveCloseTransitionEnd); } //called when the save panel transition offscreen / close completes function onSaveCloseTransitionEnd(e) { unsubscribeFromEvent(e); var saveImage = x$("#saveImage"); //stop listening for the load event saveImage.un("load", onSaveImageLoad); //clear the image saveImage.attr("src", ""); } /************** touch events for iOS / Android **************/ //called when a user touches the screen. //on iOS, there is full multitouch support, and this will be called //for each touch point. //on Android, there is only support for single touch. function onTouchStart(e) { //prevent default so iOS doesnt try to scale / move page e.preventDefault(); var startIndex = 0; var touch; var id; //see if this is the first touch point if(drones.length == 0) { //it is //get first touch point touch = e.changedTouches[0]; //get its id id = touch.identifier; //listen for the touchmove event on the main canvas canvasWrapper.on("touchmove", onTouchMove); //create a new target for the drone, based on the canvas //relative touch coordinates var t = { x:touch.pageX - canvasOffset.left, y:touch.pageY - canvasOffset.top }; //create a new drone, and store it in the lastDrone var lastDrone = createNewDroneOnPoint(t); //add the drone, with the touch id addDrone(lastDrone, id); //increment the start index (for the look below) startIndex++; } //get the number of change touch points for this event //in this case, how many new touch points were added at the //same time var len = e.changedTouches.length; //loop through the points for(var i = startIndex; i < len; i++) { //get the touch instance touch = e.changedTouches[i]; //touch id id = touch.identifier; //clone the last drone (so the new one will appear to grow //from it) var d = lastDrone._clone(); //add the new, cloned drone with the specified id addDrone(d, id); //set the last drone to the new drone lastDrone = d; } //start the Ticker so we start getting tick events Ticker.setPaused(false); } //called when a touch ends on iOS and Android devices. (i.e. user lifts a finger //from screen) function onTouchEnd(e) { //prevent default so iOS doesnt try to scale / move page e.preventDefault(); //get a list of all the touch points that changed var changedTouches = e.changedTouches; //get the number of changed touch points var len = changedTouches.length; //loop through the changed touch points for(var i = 0; i < len; i++) { ///remove the drone associated with the touch id //that ended removeDrone(changedTouches[i].identifier); } //check if there are any drones left if(drones.length == 0) { //if not stop listening for the touch move event canvasWrapper.un("touchmove", onTouchMove); //pause the Ticker Ticker.setPaused(true); } } //called on when a touch points moves (used on iOS / Android) //devices. //Note, Android only supports single touch. If there are multiple touch //points, touchmove events will not be broadcast. function onTouchMove(e) { //prevent default so iOS doesnt try to scale / move page e.preventDefault(); //get all of the touch points that changed / moved var changedTouches = e.changedTouches; //get the number of changed touch points var len = changedTouches.length; var target; var drone; var touch; //loop through all of the changed touch points for(var i = 0; i < len; i++) { //get the touch touch = changedTouches[i]; //get the drone associated with the touch drone = drones[touch.identifier]; //if there is nothing, then dont do anything if(!drone) { continue; } //update the target for the drone, based on the canvas relative //touch coordinates drone.target.x = touch.pageX - canvasOffset.left; drone.target.y = touch.pageY - canvasOffset.top; } } /*************** Drone utility methods ***********/ //adds a new drone and associates it with the specified touch id //the drones are stored in an object, instead of an Array so we //can look it up by its ID (and not have to loop through the Array //each time) function addDrone(drone, id) { //get the drone length var length = drones.length; //see if the drone already exists for the specified id if(drones[id]) { //if it does, do nothing return; } //increment the length property drones.length++; //store the drone drones[id] = drone; //add the drone to the stage stage.addChild(drone); } //removes the drone associated with the specified touch id function removeDrone(id) { //if there is no drone for the specified id if(!drones[id]) { //dont do anything return; } //get the drone var drone = drones[id]; //remove it from the stage stage.removeChild(drone); //delete the drone id from the object delete drones[id]; //decrement the length property drones.length--; } //create a new drone, using the specific target function createNewDroneOnPoint(t) { var d = new Drone(t); d.x = t.x; d.y = t.y; return d; } /************** general app functions *************/ //checks whether the browser supports the Canvas.toDataURL API //Android currently doesnt function supportsToDataURL() { //create a canvas var c = document.createElement("canvas"); //get a data url from it var data = c.toDataURL("image/png"); //see if it is valid return (data.indexOf("data:image/png") == 0); } //redraws the overlay line based on Mouse and Drone position function updateLine() { //clear previous line lineGraphics.clear(); //stroke style lineGraphics.setStrokeStyle(1); //stroke color lineGraphics.beginStroke(targetColor); //draw the line between the mouse target and the drone lineGraphics.moveTo(targetShape.x, targetShape.y); lineGraphics.lineTo(lastDrone.x, lastDrone.y); } //function that updates the size of the canvas based on the window size function updateCanvasDimensions() { //only run if height / width has changed if(viewport.height == window.innerHeight && viewport.width == window.innerWidth) { return } viewport.height = window.innerHeight; viewport.width = window.innerWidth; //set the new canvas dimensions //note that changing the canvas dimensions clears the canvas. canvasWrapper.attr("height", viewport.height); canvasWrapper.attr("width", viewport.width); //save the canvas offset canvasOffset.left = canvasWrapper.attr("offsetLeft"); canvasOffset.top = canvasWrapper.attr("offsetTop"); //check if we have an overlay canvas if(canvasOverlayWrapper) { //update the size canvasOverlayWrapper.attr("height", viewport.height); canvasOverlayWrapper.attr("width", viewport.width); //save the offset (we could probably just use the canvas ones above, //since their position and size should be synced up. canvasOverlayOffset.left = canvasOverlayWrapper.attr("offsetLeft"); canvasOverlayOffset.top = canvasOverlayWrapper.attr("offsetTop"); } } //scales the selected image to the current dimensions of the main drawing canvas. //the scaled image is used to provide a pixel / color map for drawing on the main canvas function scaleImageData() { //get the window dimensions //note, we should technically get the canvas dimensions here var w = viewport.width; var h = viewport.height; //create a temporary canvas. We will use this to scale the image, and generate //the pixel information var srcCanvas = x$('<canvas>'); srcCanvas.attr("height", h); srcCanvas.attr("width", w); //note: dont try and access image while it is cached by //the GPU (i.e. as part of a CSS transition). This can lead //to some weird visual glitches var context = srcCanvas[0].getContext("2d"); //draw the image into the temp canvas, setting the h / w //this will scale / skew it so it fills the entire canvas context.drawImage(image, 0, 0, w, h); //get the ImadeData from the canvas (this contains all of the pixel // rgba info) var imageData = context.getImageData(0, 0, w, h); //see if we have created an instance of the PixelData instance (which //provides access to the data) if(!PD) { //no, create a new instance PD = new PixelData(); } //update the image data PD.imageData = imageData; } //unsubscribes the event.target from the specified event //returns an XUI wrapper of the element that was the target of //the event function unsubscribeFromEvent(e) { return x$(e.target).un(e.type); } /************** Window / Document Events ************/ //called on touchmove events in the document (unless something else captures it) function onDocumentTouchMove(e) { //this is to prevent page scroll on touch devices e.preventDefault(); } //called when the window looses focus function onWindowBlur(e) { //pause the Tick / time manager //this is so it doesnt keep drawing / using CPU //when the user switches away Ticker.setPaused(true); } //called when the browser window is resized function onWindowResize(e) { //todo: a lot if not most of this code could be moved to //updateCanvasDimensions() //right now, the stage instance, doesnt expose the canvas //context, so we have to get a reference to it ourselves var context = canvasWrapper[0].getContext("2d"); //copy the image data from the current canvas var data = context.getImageData(0, 0, canvas.width, canvas.height); //update the canvas dimensions since the window //has resized. Note that changing canvas dimensions, //will cause it to be cleared updateCanvasDimensions(); scaleImageData(); //copy the data back onto the resized canvas. It is possible //that if the previous canvas was larger than the newly sized one //that we will loose some pixels (as they will be cut off) context.putImageData(data, 0,0); //note, we only have to do this because we have stage.autoClear set //to false, otherwise, the stage instance could redraw the entire canvas //only rerender the stage if the Tick manager is not paused if(!Ticker.getPaused()) { //render stage stage.update(); } } /****************** modal window methods ********************/ //utility function that opens a modal dialog with a css transition function openModalDiv() { //set the display to block so the div is added to the page flow x$("#modalDiv").setStyle("display","block"); //we have to set this small timeout, because if we change the opacity right after //changing the display, the css transition wont kick in setTimeout("openModalDivDelay()", 10); } //called from setTimeout while opening modal window function openModalDivDelay() { //set the opacity style to kick in the css transition //fade it in x$("#modalDiv").setStyle("opacity",1.0); } //utility function to close the modal dialog function closeModalDiv() { var div = x$("#modalDiv"); //fade it out. div.setStyle("opacity",0.0); //listen for when the transition ends div.on(transitionEndName, onModalTransitionEnd); } //called when the transition to remove the modal div ends function onModalTransitionEnd(e) { //unsubscribe from the event unsubscribeFromEvent(e); //have to set display to none, or else it will capture mouse click x$("#modalDiv").setStyle("display","none"); }
true
a638352717ae2644357b48feeec021a28cb1a711
JavaScript
maghoff/tagged-console-target
/index.js
UTF-8
1,925
2.5625
3
[]
no_license
var util = require('util'); var winston = require('winston'); var moment = require('moment'); require('colors'); function TaggedConsoleTarget(options) { options = options || {}; winston.Transport.call(this, { name: 'taggedConsoleLogger', level: options.level, handleExceptions: options.handleExceptions, exceptionsLevel: options.exceptionsLevel, humanReadableUnhandledException: options.humanReadableUnhandledException }); this.target = options.target || process.stdout; this.target.on('error', function (err) { this.emit('error', err); }.bind(this)); this.prevTimestamp = new Date(); this.target.write(moment(this.prevTimestamp).format('HH:mm:ss.SSS YYYY-MM-DD dddd').grey + '\n'); }; util.inherits(TaggedConsoleTarget, winston.Transport); TaggedConsoleTarget.prototype.log = function (level, msg, meta, callback) { var colorForLevel = { 'warn': "yellow", 'warning': "yellow", 'error': "red" }; var color = colorForLevel[level]; meta = meta || {}; var tags = meta.tags || []; var timestamp = meta.timestamp || new Date(); if (moment(timestamp).format('YYYY-MM-DD') !== moment(this.prevTimestamp).format('YYYY-MM-DD')) { this.prevTimestamp = timestamp; this.target.write(moment(timestamp).format('HH:mm:ss.SSS YYYY-MM-DD dddd').grey + '\n'); } var header = moment(timestamp).format('HH:mm:ss.SSS').grey + (' [' + tags.join(', ') + ']').green; var target = this.target; var fullyFlushed = true; msg.split('\n').forEach(function (line, index) { var coloredLine; if (color) coloredLine = line[color]; else coloredLine = line; var separator = [' ', '>'][index === 0 ? 0 : 1].grey; fullyFlushed &= target.write(header + separator + coloredLine + '\n'); }); if (fullyFlushed) { this.emit('logged'); } else { this.target.once('drain', function () { this.emit('logged'); }.bind(this)); } callback(null, true); }; module.exports = TaggedConsoleTarget;
true
4fbd61a0abe570983bd137c92eae35e3f02e6455
JavaScript
WerlingM/ndbc_latest
/js/randUtils.js
UTF-8
791
3.5
4
[]
no_license
let randUtils = { getRandomInt: function(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; }, //Floating point number, two decimal places getRandomFloat: function(min, max) { var number = Math.random() * (max - min) + min; var factor = Math.pow(10, 2); var tempNumber = number * factor; var roundedTempNumber = Math.round(tempNumber); return roundedTempNumber / factor; }, //helper function to get a random element from an array getRandomElement: function(arr) { //randomInt does not include the max val, so don't subtract 1 from length return arr[this.getRandomInt(0, arr.length)]; } } module.exports = randUtils;
true
b404ce70408b567af36ab284a0cb0b7f4eb309cc
JavaScript
kialam/tower-analytics-frontend
/src/SmartComponents/SamplePage/BarChart.js
UTF-8
8,040
2.5625
3
[ "Apache-2.0" ]
permissive
/* eslint-disable */ import React, { Component } from 'react'; import * as d3 from 'd3'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; class BarChart extends Component { constructor(props) { super(props); this.server = process.env.REACT_APP_SERVER_ADDRESS ? process.env.REACT_APP_SERVER_ADDRESS : window.location.host; this.protocol = process.env.REACT_APP_SERVER_PROTOCOL ? process.env.REACT_APP_SERVER_PROTOCOL : 'https'; } getApiUrl(name) { return this.protocol + '://' + this.server + '/tower_analytics/' + name + '/'; } shouldComponentUpdate() { console.log('shouldComponentUpdate'); return false; } async componentDidMount() { console.log('componentDidMount start'); console.log(ReactDOM.findDOMNode(this)); console.log(document.getElementById("#bar-chart-root")); await this.drawChart(); console.log('componentDidMount end'); } async drawChart() { const url = this.getApiUrl('data'); const response = await fetch(url); const data = [[12, 12, "01/01"], [50, 5, "01/02"], [6, 6, "01/03"], [6, 6, "01/04"], [9, 9, "01/05"], [10, 10, "01/06"]]; const totals = data.map(x => x[0] + x[1]); console.log(data); console.log(totals); const y = d3.scaleLinear() .domain([ 0, Math.max(...totals) ]) .range([ 0, 210 ]); const chartBottom = this.props.height - 70; const chartLeft = 70; const parseTime = d3.timeParse('%m/%d'); const x2 = d3.scaleTime().range([ chartLeft + 40, (data.length - 1) * 70 + chartLeft + 40 ]); const y2 = d3.scaleLinear().range([ 210, 0 ]); x2.domain(d3.extent(data, function(d) { return parseTime(d[2]); })); y2.domain([ 0, Math.max(...totals) ]); y2.nice(5); console.log("#" + this.props.id); console.log(document.getElementById("#" + this.props.id)); console.log(d3.select("#" + this.props.id)); const svg = d3.select("#" + this.props.id) .append('svg') .attr('width', this.props.width) .attr('height', this.props.height) .style('margin-left', 100) .style('background-color', 'white'); //.style('border-style', 'solid') //.style('border-color', 'blue') //.style('border-width', '5px'); // Add the y Axis const svgYAxis = svg.append('g'); svgYAxis.attr('transform', 'translate(' + chartLeft + ',' + (chartBottom - 210) + ')') .call(d3.axisRight(y2) .ticks(5) .tickSize(this.props.width - chartLeft - 50)) .selectAll('.domain').attr('stroke', '#d7d7d7'); svgYAxis.selectAll('.tick text').attr('x', -5).attr('dy', 4).attr('fill', '#393f44').attr('text-anchor', 'end'); svgYAxis.selectAll('.tick line').attr('stroke', '#d7d7d7'); const svgChart = svg.append('g'); const columns = svgChart.selectAll('rect') .data(data) .enter() .append('g') .attr('data-failures', (d) => d[1]) .attr('data-passes', (d) => d[0]) .attr('data-total', (d) => d[0] + d[1]) .on('mouseover', handleMouseOver) .on('mousemove', handleMouseOver) .on('mouseout', handleMouseOut); columns.append('rect') .attr('x', (d, i) => i * 70 + chartLeft + 25) .attr('y', (d) => chartBottom - y(d[0])) .attr('width', 30) .attr('height', (d) => y(d[0])) .attr('fill', '#d9534f'); columns.append('rect') .attr('x', (d, i) => i * 70 + chartLeft + 25) .attr('y', (d) => chartBottom - y(d[1]) - y(d[0])) .attr('width', 30) .attr('height', (d) => y(d[1]) - 1) .attr('fill', '#5cb85c'); // Add the x Axis const svgXAxis = svg.append('g'); svgXAxis.attr('transform', 'translate(0,' + chartBottom + ')') .call(d3.axisBottom(x2) .ticks(data.length) .tickFormat(d3.timeFormat('%m/%d'))); svgXAxis.selectAll('.domain').attr('stroke', '#d7d7d7'); svgXAxis.selectAll('text').attr('fill', '#393f44'); svgXAxis.selectAll('line').attr('stroke', '#d7d7d7'); // text label for the y axis svg.append('text') .attr('transform', 'translate(30, ' + this.props.height / 2 + ') rotate(-90)') .style('text-anchor', 'middle') .text('Jobs Across All Clusters') .attr('fill', '#393f44'); // text label for the x axis svg.append('text') .attr('transform', 'translate(' + this.props.width / 2 + ', ' + (this.props.height - 30) + ')') .style('text-anchor', 'middle') .text('Time: Day') .attr('fill', '#393f44'); // tooltip const tooltip = svg.append('g'); tooltip.attr('id', 'svg-chart-tooltip'); tooltip.style('opacity', 0); tooltip.style('pointer-events', 'none'); tooltip.attr('transform', 'translate(100, 100)'); tooltip.append('rect') .attr('transform', 'translate(10, -10) rotate(45)') .attr('x', 0) .attr('y', 0) .attr('height', 20) .attr('width', 20) .attr('fill', '#393f44'); tooltip.append('rect') .attr('x', 10) .attr('y', -41) .attr('rx', 2) .attr('height', 82) .attr('width', 135) .attr('fill', '#393f44'); tooltip.append('circle') .attr('cx', 26) .attr('cy', 0) .attr('r', 7) .attr('stroke', 'white') .attr('fill', 'green'); tooltip.append('circle') .attr('cx', 26) .attr('cy', 26) .attr('r', 7) .attr('stroke', 'white') .attr('fill', 'red'); tooltip.append('text') .attr('x', 43) .attr('y', 4) .attr('font-size', 12) .attr('fill', 'white') .text('Successful'); tooltip.append('text') .attr('x', 43) .attr('y', 28) .attr('font-size', 12) .attr('fill', 'white') .text('Failed'); tooltip.append('text') .attr('fill', 'white') .attr('stroke', 'white') .attr('x', 24) .attr('y', 30) .attr('font-size', 12) .text('!'); const jobs = tooltip.append('text') .attr('fill', 'white') .attr('x', 137) .attr('y', -21) .attr('font-size', 12) .attr('text-anchor', 'end') .text('No Jobs'); const failed = tooltip.append('text') .attr('fill', 'white') .attr('font-size', 12) .attr('x', 122) .attr('y', 4) .text('0'); const successful = tooltip.append('text') .attr('fill', 'white') .attr('font-size', 12) .attr('x', 122) .attr('y', 28) .text('0'); const date = tooltip.append('text') .attr('fill', 'white') .attr('stroke', 'white') .attr('x', 20) .attr('y', -21) .attr('font-size', 12) .text('Never'); function handleMouseOver(d) { const coordinates = d3.mouse(this); const x = coordinates[0] + 5; const y = coordinates[1] - 5; date.text(d[2]); jobs.text('' + this.dataset.total + ' Jobs'); failed.text('' + this.dataset.failures); successful.text('' + this.dataset.passes); tooltip.attr('transform', 'translate(' + x + ',' + y + ')'); tooltip.style('opacity', 1); tooltip.interrupt(); } function handleMouseOut() { tooltip.transition() .delay(15) .style('opacity', 0) .style('pointer-events', 'none'); } console.log('done'); } render () { return <div id={ this.props.id }></div>; } } BarChart.propTypes = { height: PropTypes.number, width: PropTypes.number, id: PropTypes.string }; export default BarChart;
true
a72bfa349b3f5cdd0185470b23674f2cfb85860b
JavaScript
SnehaNeupane/Swagger-ui
/lib/command_execute.js
UTF-8
807
2.96875
3
[]
no_license
'use strict'; var childproc = require('child_process'); exports.exec = function(cmds, aftercommand=null){ var next; next = function(){ var cmd; if (cmds.length > 0) { cmd = cmds.shift(); console.log("Running command: " + cmd); return childproc.exec(cmd, function(err, stdout, stderr){ if (err != null) { console.log(err); } if (stdout != null) { console.log(stdout); } if (stderr != null) { console.log(stderr); } return next(); }); } else { if(typeof aftercommand == 'function'){ aftercommand(); } return console.log("Done executing commands."); } }; // console.log("Running the follows commands:"); // console.log(cmds); return next(); };
true
1bab88b8a175d89c53e7471509934fdc350202d1
JavaScript
reydelo/api-practice
/main2.js
UTF-8
781
2.859375
3
[]
no_license
// var myFunction = function() { // console.log('hello'); // } // // var myVar = console.log('goodbye'); var products = { // properties of var product: source, template, request source: function() { return $("#api-template").html() }, template: function() { return Handlebars.compile(products.source()); }, request: function() { /* optional way to call the url: $.getJSON("http://localhost:3000/api/products.json");*/ var getProducts = $.ajax({ url: "http://localhost:3000/api/products" }); getProducts.done(this.buildTemplate); }, buildTemplate: function(data) { var html = products.template()(data); $('body').append(html); }, init: function() { this.request(); } } $(function() { products.init(); });
true
484706fc9f78c1cc2f35bef29aa2b22e1a03b4f1
JavaScript
naylapaixao/traineeprominas-ncsp-view-sandbox-JS
/script-get-student.js
UTF-8
1,981
3.03125
3
[ "MIT" ]
permissive
const app = document.getElementById('root'); const container = document.createElement('table'); container.setAttribute('class', 'table'); const table = document.createElement('table'); container.setAttribute('class', 'table'); //app.appendChild(logo); app.appendChild(container); app.appendChild(table); var request = new XMLHttpRequest(); request.open('GET', 'https://traineeprominas-lrm-sandbox.herokuapp.com/api/v1/student', true); request.onload = function () { // Begin accessing JSON data here var data = JSON.parse(this.response); if (request.status >= 200 && request.status < 400) { app.appendChild(container); app.appendChild(table); data.forEach(student => { const card = document.createElement('thead'); const id = document.createElement('th'); id.textContent = student.id; id.setAttribute('scope', 'col'); const name = document.createElement('th'); name.textContent = student.name; name.setAttribute('scope', 'col'); const age = document.createElement('th'); age.textContent = student.age; age.setAttribute('scope', 'col'); const lastName = document.createElement('th'); lastName.textContent = student.lastName; lastName.setAttribute('scope', 'col'); const course = document.createElement('th'); course.textContent = student.course.name; course.setAttribute('scope', 'col'); container.appendChild(card); card.appendChild(id); card.appendChild(name); card.appendChild(lastName); card.appendChild(age); card.appendChild(course); }); } else { const errorMessage = document.createElement('marquee'); errorMessage.textContent = 'Não foi possivel realizar a ação'; app.appendChild(errorMessage); } } request.send();
true
7b6d8384397faf50b909569ca80391fb16710843
JavaScript
juliswer/Cursos
/Frontend/Javascript/Codigo_facilito/clase4.js
UTF-8
1,245
3.921875
4
[]
no_license
if(true){ console.log("La condición fue verdadera"); } else if(false){ console.log("La condición fue falsa"); } var numero_uno = 23; var numero_dos = 30; if(numero_uno > numero_dos){ console.log("Entre al bloque"); } else{ console.log("No podés entrar"); } if(numero_uno == numero_dos){ //la diferencia de == y === es que el primero convierte el dato a uno que pueda dar igualdad, mientras que el triple igual lo toma tal como se lo damos console.log("taweno"); //se recomienda siempre usar el triple igual (===) } /* Con los if se usan los operadores lógicos, los cuales son: > Mayor que < Menor que OR selecciona entre una opción y otra AND, && Hace que puedas poner dos opciones válidas en una misma sentencia == Significa igualdad, pero de ser necesario convierte uno de los valores (ej, "30" a 30.) === Significa igualdad pero toma los valores tales como los ingresamos. != Significa que es diferente, pero al igual que el == transforma uno de los valores de ser necesario. !== Significa que es diferente, se lee, la igual que el anterior como "Diferente de..." y la diferencia es que no transforma ningún valor. */
true
e52490f5d2b1516991cb79642defe80e936dbe39
JavaScript
dmshanin/javascript-online-3
/lesson-7/3.js
UTF-8
1,994
4.40625
4
[]
no_license
/** * Задача 3. * * Напишите функцию `createArray`, которая будет создавать массив с заданными значениями. * Первым параметром функция принимает значение, которым заполнять массив. * А вторым — количество элементов, которое должно быть в массиве. * * Генерировать ошибки, если: * - При вызове функции не было передано два аргумента; * - В качестве первого аргумента были переданы не число, не строка, не объект и не массив; * - В качестве второго аргумента был передан не число. */ // Решение function createArray(fill, quantity) { // При вызове функции не было передано два аргумента if (typeof fill === 'undefined' || typeof quantity === 'undefined') { throw new Error('missing one or some parameters'); } // В качестве первого аргумента были переданы не число, не строка, не объект и не массив: if (typeof arguments[0] !== 'number' && typeof arguments[0] !== 'string' && typeof arguments[0] !== 'object') { throw new Error('first parameter is not a number, string, object type and is not an array'); } // В качестве второго аргумента был передан не число: if (typeof arguments[1] !== 'number') { throw new Error('second parameter is not a number type'); } let array; array = []; for (let i = 0; i < quantity; i++) { array.push(fill); } return array; } const result = createArray('x', 5); console.log(result); // [ x, x, x, x, x ] exports.createArray = createArray;
true
23fde62def24fd16ba76688363efce2af3b13113
JavaScript
Cedrichuzhiguo/StockBarn
/Skill Code/lambda/index.js
UTF-8
21,077
2.625
3
[]
no_license
/* eslint-disable func-names */ /* eslint-disable no-console */ /* eslint-disable no-restricted-syntax */ // IMPORTANT: Please note that this template uses Dispay Directives, // Display Interface for your skill should be enabled through the Amazon developer console // See this screenshot - https://alexa.design/enabledisplay const Alexa = require('ask-sdk-core'); const persistenceAdapter = require('ask-sdk-s3-persistence-adapter'); const https = require('https'); const LoadStockDataInterceptor = { async process(handlerInput) { const attributesManager = handlerInput.attributesManager; const persistedAttributes = await attributesManager.getPersistentAttributes() || {}; const stocks = persistedAttributes.stocks || []; console.log(`Current stocks: ${stocks}`); setAttribute(handlerInput, 'stocks', stocks); } }; const LaunchRequestHandler = { canHandle(handlerInput) { return handlerInput.requestEnvelope.request.type === `LaunchRequest` ; }, async handle(handlerInput) { const stocks = await getPersistedStockList(handlerInput); let profile = await retrieveAccountProfile(handlerInput) || {}; let nickname = profile.nickname || ''; if(stocks.length===0){ const welcomeMessage = `Hello ${nickname}! Welcome to Stock Ninja! I can help with your investment portfolio. For example, I can help you check the price of a stock. You can say, check the price of Amazon.` const helpMessage = 'You can say, what is the price of Facebook'; return handlerInput.responseBuilder .addDelegateDirective({ name: 'CheckPriceIntent', confirmationStatus: 'NONE', slots: {} }) .speak(welcomeMessage) .reprompt(helpMessage) .getResponse(); } let stockOutput = await speakPortfolioWithSSML(stocks, handlerInput); // //Simple SSML let speakOutput = `<amazon:emotion name="excited" intensity="medium"> Hello ${nickname}, welcome back! Stock Ninja is now checking your portfolio:<break time="1s"/> ${stockOutput} </amazon:emotion> ` ; return handlerInput.responseBuilder.speak(speakOutput).reprompt(suggestAccountLink).getResponse(); }, }; const AddStockToListIntentHandler = { canHandle(handlerInput){ console.log("envelope:", handlerInput.requestEnvelope); return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest' && Alexa.getIntentName(handlerInput.requestEnvelope) === 'AddStockToListIntent'; }, async handle(handlerInput){ console.log("Inside AddStockToListIntentHandler"); const stockSymbol = getSlotValue(handlerInput, 'stockSymbol'); let stocks = await getPersistedStockList(handlerInput); if(stocks.includes(stockSymbol)){ return handlerInput.responseBuilder .speak(`Actually, you already had ${stockSymbol} in your list.`) .getResponse(); } console.log(`Now, add ${stockSymbol} to the list`); stocks = await saveToPersistStockList(handlerInput, stockSymbol); // const speakOutput = `Got it, ${stockSymbol}!`; const speakOutput = `${stockSymbol} is added. Now, you have ${stocks.length} in your list in total. ` return handlerInput.responseBuilder .speak(speakOutput) .getResponse(); } } const CheckStockPriceHandler = { canHandle(handlerInput) { const request = handlerInput.requestEnvelope.request; console.log("Inside CheckStockPriceHandler"); console.log(JSON.stringify(request)); const stockSymbol = getSlotValue(handlerInput, 'stockSymbol'); return request.type === "IntentRequest" && (request.intent.name === "CheckPriceIntent" && stockSymbol); }, async handle(handlerInput) { console.log("Inside CheckStockPriceHandler - handle"); const response = handlerInput.responseBuilder; const stockSymbol = getSlotValue(handlerInput, 'stockSymbol'); const priceInfo = await getStockPrice(stockSymbol); let price = priceInfo.c || 1.0; let speakOutput = `Current stock price for ${stockSymbol} is: ${price} USD. \n`; if (supportsDisplay(handlerInput)) { console.log('Do nothing for now. Might want to expand here'); } let counter = await saveStockQueryCounter(handlerInput, stockSymbol); console.log('Counter:', counter); if(counter.shouldStore){ setAttribute(handlerInput, attr_name.REDIRECT_INTENT, 'AddStockToListIntent'); setAttribute(handlerInput, attr_name.STOCK_SYMBOL, stockSymbol); speakOutput += `You have checked ${stockSymbol} ${counter.count} times. Do you like to add it to your list?`; response.speak(speakOutput); // response.addDelegateDirective({ // name: 'AddStockToListIntent', // confirmationStatus: 'NONE', // slots: { // stockSymbol:{ // name: 'stockSymbol', // value: stockSymbol // } // } // }) }else{ response.speak(speakOutput).reprompt('You can also add your stock to the list, so that I can remember it for you.'); } return response.getResponse(); }, }; const CheckPortfolioIntentHandler = { canHandle(handlerInput) { const request = handlerInput.requestEnvelope.request; console.log("Inside CheckPortfolioIntentHandler"); console.log(JSON.stringify(request)); return request.type === "IntentRequest" && (request.intent.name === "CheckPortfolioIntent"); }, async handle(handlerInput) { console.log("Inside CheckPortfolioIntentHandler - handle"); const response = handlerInput.responseBuilder; const stocks = await getPersistedStockList(handlerInput); const stockNum = stocks.length ; if(stockNum === 0){ setAttribute(handlerInput, attr_name.REDIRECT_INTENT, 'AddStockToListIntent'); return handlerInput.responseBuilder .addDelegateDirective({ name: 'AddStockToListIntent', confirmationStatus: 'NONE', slots: {} }) .speak(promptForAddingStock) .getResponse(); } let speakOutput = await speakPortfolioWithSSML(stocks, handlerInput); return response.speak(speakOutput) .reprompt(suggestAccountLink) .getResponse(); }, }; async function speakPortfolioWithSSML(stocks, handlerInput){ let speakOutput = `You currently have ${stocks.length} stocks in your list. Here is the current prices: <break time="2s"/>`; let stock; for (stock of stocks){ const priceInfo = await getStockPrice(stock); let price = priceInfo.c || 0.0; speakOutput += `${stock}: ${price} USD; `; } if (supportsDisplay(handlerInput)) { console.log('Do nothing for now. Might want to expand here'); } return speakOutput; } /* Account linking using cognito: https://medium.com/@ankit81008/alexa-accountlinking-cognito-74a29243b1ca */ const LinkAccountIntentHandler = { canHandle(handlerInput){ console.log("BuyIntentHandler: envelope:", handlerInput.requestEnvelope); return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest' && Alexa.getIntentName(handlerInput.requestEnvelope) === 'LinkAccountIntent'; }, handle(handlerInput){ let accessToken = handlerInput.requestEnvelope.context.System.user.accessToken; if (accessToken == undefined){ // The request did not include a token, so tell the user to link var speechText = "I am sending an Account Linking card to your Alexa mobile app. " + "Please check the Alexa app on your mobile app. Your Stock Ninja login credentials is required."; return handlerInput.responseBuilder .speak(speechText) .reprompt('You can link account whenever you want.') .withLinkAccountCard() .getResponse(); } else { return handlerInput.responseBuilder .speak('You have already linked your account.') .reprompt('If you choose to, the account can also be unlinked on Alexa mobile app.') .withLinkAccountCard() .getResponse(); } } }; const BuyIntentHandler = { canHandle(handlerInput){ console.log("BuyIntentHandler: envelope:", handlerInput.requestEnvelope); return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest' && Alexa.getIntentName(handlerInput.requestEnvelope) === 'BuyIntent'; }, handle(handlerInput){ let accessToken = handlerInput.requestEnvelope.context.System.user.accessToken; if (accessToken == undefined){ // The request did not include a token, so tell the user to link // accounts and return a LinkAccount card var speechText = "You must have a Stock Ninja account for a stock transaction. " + "Please use the Alexa app to link your Amazon account with your Stock Ninja Account."; return handlerInput.responseBuilder .speak(speechText) .withLinkAccountCard() .getResponse(); } else { return handlerInput.responseBuilder .speak('Now, transaction dialog should start from here') .withLinkAccountCard() .getResponse(); } } }; const ConfirmationIntentHandler = { canHandle(handlerInput) { console.log("Inside YesIntentHandler"); //const redirectIntent = getAttribute(handlerInput, attr_name.REDIRECT_INTENT); const request = handlerInput.requestEnvelope.request; return request.type === 'IntentRequest' && (request.intent.name === 'AMAZON.YesIntent'||request.intent.name === 'AMAZON.NoIntent'); }, handle(handlerInput) { console.log("Inside YesIntentHandler - handle"); const request = handlerInput.requestEnvelope.request; const redirectIntent = getAttribute(handlerInput, attr_name.REDIRECT_INTENT); let response = handlerInput.responseBuilder; if(request.intent.name === 'AMAZON.NoIntent'){ console.log('User said: NO to redirect:', redirectIntent); if (redirectIntent){ setAttribute(handlerInput, attr_name.REDIRECT_INTENT, null); // reset redirectIntent to empty. setAttribute(handlerInput, attr_name.STOCK_SYMBOL, null); return response.speak('OK. Anything else?').reprompt(exitSkillMessage).getResponse(); }else{ return response.speak(exitSkillMessage).getResponse(); } } const stockSymbol = getAttribute(handlerInput, attr_name.STOCK_SYMBOL); if(redirectIntent==='AddStockToListIntent' && stockSymbol){ saveToPersistStockList(handlerInput, stockSymbol); return handlerInput.responseBuilder .speak('Done!') .reprompt('Anything else?') .getResponse(); } setAttribute(handlerInput, attr_name.REDIRECT_INTENT, null); // reset redirectIntent to empty. //setAttribute(handlerInput, attr_name.STOCK_SYMBOL, null); return response.addDelegateDirective({ name: redirectIntent, confirmationStatus: 'NONE', slots: { stockSymbol: { name: 'stockSymbol', value: stockSymbol } } }) .speak('Great.') .getResponse(); }, }; const HelpHandler = { canHandle(handlerInput) { console.log("Inside HelpHandler"); const request = handlerInput.requestEnvelope.request; return request.type === 'IntentRequest' && request.intent.name === 'AMAZON.HelpHandler'; }, handle(handlerInput) { console.log("Inside HelpHandler - handle"); return handlerInput.responseBuilder .speak(helpMessage) .reprompt(helpMessage) .getResponse(); }, }; const ExitHandler = { canHandle(handlerInput) { console.log("Inside ExitHandler"); const attributes = handlerInput.attributesManager.getSessionAttributes(); const request = handlerInput.requestEnvelope.request; return request.type === `IntentRequest` && ( request.intent.name === 'AMAZON.StopIntent' || request.intent.name === 'AMAZON.PauseIntent' || request.intent.name === 'AMAZON.CancelIntent' ); }, handle(handlerInput) { return handlerInput.responseBuilder .speak(exitSkillMessage) .getResponse(); }, }; const SessionEndedRequestHandler = { canHandle(handlerInput) { console.log("Inside SessionEndedRequestHandler"); return handlerInput.requestEnvelope.request.type === 'SessionEndedRequest'; }, handle(handlerInput) { console.log(`Session ended with reason: ${JSON.stringify(handlerInput.requestEnvelope)}`); return handlerInput.responseBuilder.getResponse(); }, }; const ErrorHandler = { canHandle() { console.log("Inside ErrorHandler"); return true; }, handle(handlerInput, error) { console.log("Inside ErrorHandler - handle"); console.log(`Error handled: ${JSON.stringify(error)}`); console.log(`Handler Input: ${JSON.stringify(handlerInput)}`); return handlerInput.responseBuilder .speak(helpMessage) .reprompt(helpMessage) .getResponse(); }, }; /* CONSTANTS */ const skillBuilder = Alexa.SkillBuilders.custom(); const attr_name = { REDIRECT_INTENT: 'REDIRECT_INTENT', STOCK_SYMBOL: 'STOCK_SYMBOL' }; const suggestAccountLink = 'Do you think I\'m helpful enough? I can help you even more, if you link with a Stock Ninja account.'; const exitSkillMessage = `Thank you for using stock ninja! You'll make a lot money soon!`; const promptForAddingStock = `To add a stock, you can say Amazon, or A-M-Z-N`; const helpMessage = `I am stock ninja, help you manage your portfolio. For example, you can ask, check price of amazon.`; /* HELPER FUNCTIONS */ function getAttribute(handlerInput, name){ const attributes = handlerInput.attributesManager.getSessionAttributes() || {}; console.log('Current attribute:', attributes); let value = attributes[name] || null; console.log(`Found attribute ${name}:${value}`); return value; }; function setAttribute(handlerInput, name, value){ const attributes = handlerInput.attributesManager.getSessionAttributes() || {}; attributes[name] = value ; if (!value){ delete attributes[name]; } handlerInput.attributesManager.setSessionAttributes(attributes); }; function getSlotValue(handlerInput, slotName){ let slots = handlerInput.requestEnvelope.request.intent.slots || {}; let slotOfName = slots[slotName] || {} ; return slotOfName.value || null; }; async function getPersistedStockList(handlerInput){ const attributesManager = handlerInput.attributesManager; const persistedAttributes = await attributesManager.getPersistentAttributes() || {}; const stocks = persistedAttributes.stocks || []; console.log(`Read stocks: ${stocks}`); return stocks; } async function saveToPersistStockList(handlerInput, stockSymbol){ const attributesManager = handlerInput.attributesManager; let persistedAttributes = await attributesManager.getPersistentAttributes() || {}; let stocks = persistedAttributes.stocks || []; stocks.push(stockSymbol); persistedAttributes.stocks = stocks ; attributesManager.setPersistentAttributes(persistedAttributes); await attributesManager.savePersistentAttributes(); console.log(`Saved stocks: ${stocks}`); return stocks; } async function saveStockQueryCounter(handlerInput, stockSymbol){ const attributesManager = handlerInput.attributesManager; let persistedAttributes = await attributesManager.getPersistentAttributes() || {}; console.log('Current persisted Attributes:', persistedAttributes); let stocks = persistedAttributes.stocks || []; let counters = persistedAttributes.queryCounters || {}; let count = counters[stockSymbol] || 0 ; count = count + 1; counters[stockSymbol] = count ; persistedAttributes.queryCounters = counters ; attributesManager.setPersistentAttributes(persistedAttributes); await attributesManager.savePersistentAttributes(); let result = {count: count}; if(stocks.includes(stockSymbol)){ result.shouldStore = false; return result; } result.shouldStore = (count>2); return result; } /* Read from persisted storage, or from profile service call The success profile looks like: { "sub": "cb648136-7010-4335-bf5d-446234d9613f", "address": "10 Langbourne Place, Toronto, Canada", "email_verified": "true", "nickname": "Cedric", "phone_number_verified": "true", "phone_number": "+16043532272", "email": "[email protected]", "username": "cedric" } */ async function retrieveAccountProfile(handlerInput){ const attributesManager = handlerInput.attributesManager; let persistedAttributes = await attributesManager.getPersistentAttributes() || {}; console.log('Current persisted Attributes:', persistedAttributes); let profile = persistedAttributes.profile || null; let accessToken = handlerInput.requestEnvelope.context.System.user.accessToken; if(accessToken){ if (!profile){ profile = await getAccountProfileWithToken(accessToken); } }else if(profile){ //account unlinked. Time to clear userProfile info profile = null; } persistedAttributes.profile = profile ; attributesManager.setPersistentAttributes(persistedAttributes); await attributesManager.savePersistentAttributes(); console.log(`Return profile: ${profile}`); return profile; } // returns true if the skill is running on a device with a display (show|spot) function supportsDisplay(handlerInput) { var hasDisplay = handlerInput.requestEnvelope.context && handlerInput.requestEnvelope.context.System && handlerInput.requestEnvelope.context.System.device && handlerInput.requestEnvelope.context.System.device.supportedInterfaces && handlerInput.requestEnvelope.context.System.device.supportedInterfaces.Display return hasDisplay; } //Check whether session attribute 'attributeName' has a value 'value'. function isAttributeEqualsToValue(handlerInput, attributeName, value){ const attributes = handlerInput.attributesManager.getSessionAttributes(); const currentValue = attributes[attributeName] || null ; return value == currentValue ; } const stock_to_tickers = { facebook: 'FB', amazon: 'AMZN', apple: 'AAPL', netflix:'NFLX', Netflix: 'NFLX', google: 'GOOG', tesla: 'TSLA', Tesla: 'TSLA', microsoft: 'MSFT', Microsoft: 'MSFT' } function getStockTickerSymbol(stockName){ return stock_to_tickers[stockName]; } //https://finnhub.io/api/v1/quote?symbol=AAPL&token=bqn2eh7rh5re7283jbh0 async function getStockPrice(stockName) { let symbol = getStockTickerSymbol (stockName); if (!symbol){ console.log(`Can not find the symbol for ${stockName}`); return null; } let path = `/api/v1/quote?symbol=${symbol}&token=bqn2eh7rh5re7283jbh0`; console.log(`Request stock price with ${path}`); var options = { host: 'finnhub.io', path: path, method: 'GET', }; let price = await httpsRequest(options); return price; } async function getAccountProfileWithToken(token){ console.log(`Get account with token: ${token}.`); if (!token){ return null; } var options = { host: 'stockassistant.auth.us-west-2.amazoncognito.com', path: '/oauth2/userInfo', method: 'GET', headers: { 'authorization': 'Bearer ' + token } }; let profile = await httpsRequest(options); return profile; } function httpsRequest(options){ return new Promise(((resolve, reject) => { var req = https.request(options, res => { res.setEncoding('utf8'); let responseString = ""; //accept incoming data asynchronously res.on('data', chunk => { responseString = responseString + chunk; }); //return the data when streaming is complete res.on('end', () => { console.log(responseString); resolve(JSON.parse(responseString)); }); res.on('error', (error) => { reject(error); }); }); req.end(); })); } function compareSlots(slots, value) { for (const slot in slots) { if (Object.prototype.hasOwnProperty.call(slots, slot) && slots[slot].value !== undefined) { if (slots[slot].value.toString().toLowerCase() === value.toString().toLowerCase()) { return true; } } } return false; } /* LAMBDA SETUP */ exports.handler = skillBuilder.withPersistenceAdapter( new persistenceAdapter.S3PersistenceAdapter({bucketName:process.env.S3_PERSISTENCE_BUCKET}) ) .addRequestHandlers( // HasStockDataLaunchRequestHandler, LaunchRequestHandler, AddStockToListIntentHandler, CheckStockPriceHandler, CheckPortfolioIntentHandler, BuyIntentHandler, LinkAccountIntentHandler, ConfirmationIntentHandler, HelpHandler, ExitHandler, SessionEndedRequestHandler ).addRequestInterceptors( LoadStockDataInterceptor ).addErrorHandlers(ErrorHandler) .lambda();
true
2bee746e93f851405a9887ea9adb10cbc61f354f
JavaScript
siastar/TVP
/_stuff/backup/backup1/routes/VinylsRoute.js
UTF-8
2,774
2.6875
3
[]
no_license
console.log('...opening /routes/VinylsRoute') const express = require('express'); const vinylRouter = express.Router(); const VinylSchema = require('../model/VinylSchema.js'); // C R U D: Create - Read - Update - Delete //mongoose methods are implicitally used without importing mongoose itself because it //comes already incapsulated in vinylSchema.js, whose instance requires mongoose in the beginning //(Alice in Objectland) //Read vinylRouter.get( '/' , (req , res) => { VinylSchema.find({} , (err , response) => {//.find -> mongoose method if (err) res.status(500).json({message:{ msgBody : "cannot reach vinyls", msgError : true }}) else res.status(200).json(response); }); }); //Create vinylRouter.post( '/' , (req , res) => { const vinyl = new VinylSchema(req.body); //new instance of the model vinylSchema vinyl.save((err, document) => { //.save -> mongoose method if (err) res.status(500).json({message:{ msgBody : "cannot add vinyl", msgError : true }}) else res.status(200).json({message:{ msgBody : "vinyl succesfully added", msgError : false }}); }); }); //Delete vinylRouter.delete('/:id' , (req , res) => { VinylSchema.findByIdAndDelete(req.params.id , err => { //.findByIdAndDelete -> mongoose // params is in res properties if (err) res.status(500).json({message:{ msgBody : "cannot remove vinyl", msgError : true }}) else res.status(200).json({message:{ msgBody : "vinyl succesfully", msgError : false }}); }); }); //Update vinylRouter.put('/:id' , (req , res) => { VinylSchema.findOneAndUpdate(req.params.id , // params.id is the element to update req.body , // updated content, findOneandupdate is a mongoose method {runValidators : true}, (err , response) => { if (err) res.status(500).json({message:{ msgBody : "cannot modify vinyl", msgError : true }}) else res.status(200).json({message:{ msgBody : "vinyl successfully modified", msgError : false }}); }); }); module.exports = vinylRouter
true
c55f56a1fcbbb34977c0531df8662fcfc78d3367
JavaScript
luomuxie/ts-screeps
/src_sec.js/main.js
UTF-8
3,769
3.609375
4
[]
no_license
/* 1、创建一个creeps Your spawn creates new units called "creeps" by its method spawnCreep. Usage of this method is described in the documentation. Each creep has a name and certain body parts that give it various skills. You can address your spawn by its name the following way: Game.spawns['Spawn1']. Create a worker creep with the body array [WORK,CARRY,MOVE] and name Harvester1 (the name is important for the tutorial!). You can type the code in the console yourself or copy & paste the hint below. */ Game.spawns['Spawn1'].spawnCreep( [WORK, CARRY, MOVE], 'Harvester1' ); /* 2、控制screep 去工作,如收集能量 To send a creep to harvest energy, you need to use the methods described in the documentation section below. Commands will be passed each game tick. The harvest method requires that the energy source is adjacent to the creep. You give orders to a creep by its name this way: Game.creeps['Harvester1']. Use the FIND_SOURCES constant as an argument to the Room.find method. */ module.exports.loop = function () { var creep = Game.creeps['Harvester1']; var sources = creep.room.find(FIND_SOURCES); if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) { creep.moveTo(sources[0]); } } /* 3、添加判断,以致能来回工作 To make the creep transfer energy back to the spawn, you need to use the method Creep.transfer. However, remember that it should be done when the creep is next to the spawn, so the creep needs to walk back. If you modify the code by adding the check .store.getFreeCapacity() > 0 to the creep, it will be able to go back and forth on its own, giving energy to the spawn and returning to the source. Extend the creep program so that it can transfer harvested energy to the spawn and return back to work. */ module.exports.loop = function () { var creep = Game.creeps['Harvester1']; if(creep.store.getFreeCapacity() > 0) { var sources = creep.room.find(FIND_SOURCES); if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) { creep.moveTo(sources[0]); } } else { if( creep.transfer(Game.spawns['Spawn1'], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE ) { creep.moveTo(Game.spawns['Spawn1']); } } } /* 4、每个creep的生命周期是1500秒,现在花费200能量创建第二个creep铺助工作 Great! This creep will now work as a harvester until it dies. Remember that almost any creep has a life cycle of 1500 game ticks, then it "ages" and dies (this behavior is disabled in the Tutorial). Let's create another worker creep to help the first one. It will cost another 200 energy units, so you may need to wait until your harvester collects enough energy. The spawnCreep method will return an error code ERR_NOT_ENOUGH_ENERGY (-6) until then. */ Game.spawns['Spawn1'].spawnCreep( [WORK, CARRY, MOVE], 'Harvester2' ); /* 5、通过for把第二个creep加入工作工 The second creep is ready, but it won't move until we include it into the program. To set the behavior of both creeps we could just duplicate the entire script for the second one, but it's much better to use the for loop against all the screeps in Game.creeps. */ module.exports.loop = function () { for(var name in Game.creeps) { var creep = Game.creeps[name]; if(creep.store.getFreeCapacity() > 0) { var sources = creep.room.find(FIND_SOURCES); if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) { creep.moveTo(sources[0]); } } else { if(creep.transfer(Game.spawns['Spawn1'], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) { creep.moveTo(Game.spawns['Spawn1']); } } } }
true
48065ec218b691fe94a063ad0f3b51d5b0ff5e4c
JavaScript
node-pinus/pinus
/tools/pinus-robot/dist/lib/console/js/ui/graph.js
UTF-8
4,778
2.546875
3
[ "MIT" ]
permissive
var graphs = {}; function updateGraph(chart,targetName) { var main = document.getElementById(targetName); if (!main) { var tname = targetName+'div'; var _dom = $("#avg_template").clone().attr('id',tname).find('.screen-label').html(targetName+' Response Time Graph').end().find('.cgraphdiv').attr('id',targetName).end(); $("#graph_div").append(_dom); main = document.getElementById(targetName); var p = $('#'+tname); p.find('.screen-buttons').click(function(){ //var t = p.find('.console').toggle(); //p.find('.console').hide(); //p.css('height','26px'); }); }; if (graphs[chart.uid]) { graphs[chart.uid].updateOptions({ "file" : chart.rows, labels : chart.columns }); } else { var newchart = document.createElement("div"); newchart.setAttribute("class", "post"); newchart.innerHTML = [] .concat( '<div style="width:100%;float:left">', '<div id="chart', chart.uid, '" style="float:left;width:92%;height:200px;"></div>', '<div id="chartlegend', chart.uid, '" style="float:left;width:80px;height:200px;"></div>', '</div>').join(''); main.appendChild(newchart); graphs[chart.uid] = new Dygraph(document.getElementById("chart" + chart.uid), chart.rows, { labelsDiv : document.getElementById("chartlegend" + chart.uid), labelsSeparateLines : true, labels : chart.columns }); } } var sumshow = 'none'; function updateDetailAgent(_totalAgentSum,title){ for (var agent in _totalAgentSum) { var target = $("#sum_"+agent); if (!!target.html()) {target.remove();}; var _summary = _totalAgentSum[agent]; var _dom = $("#table_template").clone() .find(".summary").html(jsonToTable(_summary)).end().attr("id", "sum_" + agent); _dom.find(".screen-label").html(agent + title); $("#summary_div").append(_dom); }; $(".close").click(function() { var self = $(this).parent().parent().parent().parent().css('display','none'); }); }; function showDetailAgent(){ sumshow = ''; $("#summary_div").css('display',sumshow); $("#table_img").css('display',sumshow); $("#table_img").click(function(){ sumshow = 'none'; $(this).css('display',sumshow); $("#summary_div").css('display',sumshow); }); }; function updateAvgAgent(everyAgentavgDatas,title){ for (var index in everyAgentavgDatas) { var chart = everyAgentavgDatas[index]; var uid = chart.uid; var target = $("#avg_"+uid); if (!!target.html()) { } else { var _dom = $("#avg_template").clone().attr("id", "avg_" + uid); _dom.find(".screen-label").html(uid.substring(3,uid.length)+title); _dom.find(".avgrestime").attr("id", "davg_" + uid); _dom.css('display','block'); $("#avg_div").append(_dom); }; updateGraph(chart,"davg_"+uid); }; }; var avgshow = 'none'; function showDetailAgentAvg(){ avgshow = ''; $("#avg_div").css('display',avgshow); $("#avg_img").css('display',avgshow); $("#avg_img").click(function(){ avgshow = 'none'; $(this).css('display',avgshow); $("#avg_div").css('display',avgshow); }); }; var qsshow = 'none'; function showDetailAgentQs(){ qsshow = ''; $("#qs_div").css('display',qsshow); $("#qs_img").css('display',qsshow); $("#qs_img").click(function(){ qsshow = 'none'; $(this).css('display',qsshow); $("#qs_div").css('display',qsshow); }); }; function updateEveryAgent(everyAgentavgDatas,divname,title){ for (var index in everyAgentavgDatas) { var chart = everyAgentavgDatas[index]; var uid = chart.uid; var target = $("#qs_"+uid); if (!!target.html()) { } else { var _dom = $("#avg_template").clone().attr("id", "qs_" + uid); _dom.find(".screen-label").html(uid.substring(2,uid.length)+title); _dom.find(".avgrestime").attr("id", "dqs_" + uid); $("#qs_div").append(_dom); }; updateGraph(chart,"dqs_"+uid); }; $(".close").click(function() { var self = $(this).parent().parent().parent().parent().css('display','none'); }); }; function updateEveryAgent1(everyAgentqsDatas,divname,title){ for (var index in everyAgentqsDatas) { var chart = everyAgentqsDatas[index]; var uid = chart.uid; var target = $("#"+uid); if (!!target.html()) { } else { var _dom = $("#avg_template").clone(); _dom.find(".screen-label").html(uid +' ' + title); _dom.find(".avgrestime").attr("id", uid); _dom.css('display','block'); $("#" + divname).append(_dom); }; //target = $(); updateGraph(chart,uid); }; $(".close").click(function() { var self = $(this).parent().parent().parent().parent().css('display','none'); }); }; //update([{"name":"","uid":0,"summary": //{"Load Data uniques uniqs":2000},"charts":{"latency":{"name":"","uid":22,"columns":["time","min","max","avg","median","95%","99%"],"rows":[[0.03,0,0,0,0,0,0],[0.03,5,92,27.5,26,45,75],[0.04,6,62,26,25,45,57]]}}}]);
true
b15378ae87b3f480cf746bdeb2d67222f6b96aa6
JavaScript
saisaira/webDesignusingReactJs-05-10-2020-
/js/practice.js
UTF-8
2,293
4
4
[]
no_license
// creating object var details={ name:"Apssdc", year:2015, courses:["webdesign using react","python","ml","PWA"] } // for loop syntax and functionality of working // for(var i=0;i<details.courses.length;i++){ // document.write(details.courses[i]+"<br>"); // } // for-in(object,Array) // for(var i in details.courses){ // document.write(details.courses[i]+"<br>") // } // for-of(strings,array not object) // var name="APSSDC react"; // for(var i of details.courses){ // document.write(i,"<br>"); // } // var age=18; // if(age==18){ // document.write("you are major"); // }else if(age>18){ // document.write("you are above 18") // }else{ // document.write("you are minor") // } // ternary operator(?) // syntax: condition ? if true : else // var age=20; // var status = (age>=18) ? 'adult' : 'minor'; // document.write(status); // predefined or builtin functions // Examples: Date(),String(),Number() etc.. // user-defined functions // function addition(a,b){ // window.alert(a+b); // } // addition(89,11); // var addition=(a,b)=>{ // window.alert(a+b); // } // addition(89,11); // var r1=10; // var r1=400; // document.write(r1,"<br>"); // { // var r1=40; // document.write(r1,"<br>"); // } // document.write(r1); // let r1=10; // document.write(r1+"let","<br>"); // { // let r1=40; // document.write(r1+"let","<br>"); // } // document.write(r1+"let"); // const a=40; // { // const a=400; // document.write(a,"<br>"); // } // document.write(a); // class Square{ // constructor(height,width){ // this.h=height; // this.w=width; // } // } // var a=new Square("40cm","40cmwidth") // document.write(a.w); // var n=[4,9,16,25,36]; // // var s=n.map(Math.sqrt); // // document.write(s,typeof(s)); // var addition=(num)=>{ // return num*num; // } // var s=n.map(addition); // document.write(s); // function addition(p1,p2,...s){ // document.write(p1+p2,"<br>"); // document.write(s[2]); // } // addition(1,2,3,4,5,6,7,8,9,90); // const array=[1,2,3]; // const array1=[...array]; // array1.push(4,5,6,7); // document.write(array1); // var n=["swami","sairam","Gauthami","kalyan"]; // var[name1,name2,name3,name4]=n // document.write(name3) // let n=2020; // let message=`THis year is ${n}`; // document.write(message);
true
cc37cbe387219b94050c0b1504be612fc108370f
JavaScript
gitgeorgec/keepalive
/src/components/KeepAlive/index.js
UTF-8
1,154
2.65625
3
[]
no_license
import React, { createRef, useEffect, useRef, useState } from 'react'; const AliveContext = React.createContext({}); export const AliveScope = props => { const [state, setState] = useState({}); const nodes = createRef({}); nodes.current = {} function keep(id, children) { setState({ ...state, [id]: { id, children } }) } return ( <AliveContext.Provider value={{ keep, nodes }}> {props.children} {Object.values(state).map(({ id, children }) => { return ( <div key={id} ref={ref => nodes.current[id] = ref}> {children} </div> ) })} </AliveContext.Provider> ); } const withScope = WrappedCompoennt => props => ( <AliveContext.Consumer> {({keep, nodes}) => <WrappedCompoennt {...props} keep={keep} nodes={nodes}/>} </AliveContext.Consumer> ) function KeepAlive({ id, children, keep, nodes }) { const NodeRef = useRef(null); useEffect(() => { keep(id, children); }, []) useEffect(() => { if (nodes.current && nodes.current[id]) { NodeRef.current.appendChild(nodes.current[id]) } }, [nodes, id]) return ( <div ref={NodeRef}> </div> ) } export default withScope(KeepAlive)
true
8e80142092c172f77a28ac3bf9313e25b9003fe5
JavaScript
Gleb-1/ItGid-courses__JS2.0
/UNIT 3. OPERATOR IF, ELSE, SWITCH CASE - SELECTION IN JAVASCRIPT/js/unit_03.js
UTF-8
11,495
4.0625
4
[]
no_license
// Task 1 // При нажатии кнопки b-1 срабатывает функция f1. Функция должна прочитать содержимое i-1 и сравнить его с числом 4 (сравнение ==). Результат сравнения - true или false выведите в out-1. document.querySelector('.i-1'); let a2 = document.querySelector('.out-1'); document.querySelector('.b-1').onclick = function f1 () { let num =+ document.querySelector('.i-1').value; if ( num == 4 ) { a2.innerHTML = ('true'); } else { a2.innerHTML = ('false'); } } // Task 2 // Даны две переменные a21 и a22. При нажатии кнопки b-2, запускается функция f2. Функция должна сравнить переменные с помощью if else и вывести в out-2 число, которое больше. Вариант равенства переменных не рассматриваем. let a21 = 45; let a22 = 32; document.querySelector('.out-2'); document.querySelector('.b-2').onclick = function f2 () { if ( a21 > a22 ) { document.querySelector('.out-2').innerHTML = (a21); } else { document.querySelector('.out-2').innerHTML = ('false'); } } // Task 3 // Даны 2 input - i-31 и i-32, оба - input[type=number]. При нажатии кнопки b-3 срабатывает функция f3. Функция должна вычитать содержимое i-31 и i-32 в переменные и сравнить их, вывести в out-3 большее число. // Проведите самостоятельный тест работы, введите пары чисел 4 и 9, 9 и 22, 5 и 111. document.querySelector('.i-31'); document.querySelector('.i-32'); document.querySelector('.b-3').onclick = function f3 () { let num1 = parseInt (document.querySelector('.i-31').value); let num2 = parseInt (document.querySelector('.i-32').value); if ( num1 > num2 ) { document.querySelector('.out-3').innerHTML = (num1); } else{ document.querySelector('.out-3').innerHTML = (num2); } } // Task 4. Создайте на странице input[type=number] с классом i-4, куда пользователь может ввести год своего рождения. Есть кнопка b-4 которая запускает функцию f4. Функция должна вывести в .out-4 число 1 если пользователю больше или равно 18 лет, и 0 если меньше. let years = document.querySelector('.i-4'); years = 18; document.querySelector('.b-4').onclick = function f4(){ let num_3 = document.querySelector('.i-4').value; if ( num_3 >= years) { document.querySelector('.out-4').innerHTML = (1); } else { document.querySelector('.out-4').innerHTML = (0); } } // Task 5. Создайте на странице input[type=number] с классом i-5, куда пользователь может ввести число. Есть кнопка b-5 которая запускает функцию f5. Функция должна вывести в .out-5 символ m если число меньше нуля, 0 если число равно нулю и 1 если больше. let introduce = document.querySelector('.i-5'); introduce = 0; document.querySelector('.b-5').onclick = function f5(){ let num_4 = document.querySelector('.i-5').value; if ( num_4 < introduce ) { document.querySelector('.out-5').innerHTML = ('m'); } else if ( num_4 > introduce ) { document.querySelector('.out-5').innerHTML = (1); } else { document.querySelector('.out-5').innerHTML = (0); } } // Task 6. Создайте на странице input[type=number] с классом i-6, куда пользователь может ввести число. Есть кнопка b-6 которая запускает функцию f6. Функция должна вывести в .out-6 слово even если число четное и odd если нечетное. Для проверки четности используется целочисленный остаток от деления на 2 (оператор %). Если остаток равен нулю - четное, нет - нечетное. let even_odd = document.querySelector('.i-6'); even_odd = 0; document.querySelector('.b-6').onclick = function f6 () { let num_5 = document.querySelector('.i-6').value; if (num_5 % 2 == even_odd) { document.querySelector('.out-6').innerHTML = ('even'); } else { document.querySelector('.out-6').innerHTML = ('odd'); } } // Task 7. // Даны 2 input - i-71 и i-72, оба - input[type=number]. При нажатии кнопки b-7 срабатывает функция f7. Функция должна число из i-71 возвести в степень i-72, вывести результат в out-7. Для возведения в степень можно использовать **, или Math.pow. document.querySelector('.i-71'); document.querySelector('.i-72'); document.querySelector('.b-7').onclick = function f7 () { let num_6 = document.querySelector('.i-71').value; let num_7 = document.querySelector('.i-72').value; document.querySelector('.out-7').innerHTML = (num_6**num_7 ); } // Task 8. // Дан select s-8, который содержит 3 значения: 1, 2, 3. Дана кнопка b-8. При ее нажатии срабатывает функция f8. Функция должна получить выбранное в select число, потом с помощью switch case сравнить его поочередно с ‘1’, ‘2’, ‘3’. И если число выбрано - 1, то вывести в out-8 строку one, если 2 - two, если 3 - three. document.querySelector('.s-8'); document.querySelector('.b-8').onclick = function f8 () { let number = parseInt (document.querySelector('.s-8').value); switch (number) { case 1: document.querySelector('.out-8').innerHTML = ('one'); break; case 2: document.querySelector('.out-8').innerHTML = ('two'); break; case 3: document.querySelector('.out-8').innerHTML = ('three'); break; // default: // document.querySelector('.out-8').innerHTML = ('okkk'); } } // Task 9 // Создайте на странице input[type=number] с классом i-9, куда пользователь может ввести номер квартиры. Есть кнопка b-9 которая запускает функцию f9. Функция должна вывести в .out-9 номер подъезда, в котором находится квартира. // если от 1 до 32 - то вывести цифру 1 // если от 33 до 43 - то вывести 2 // если от 44 до 64 - то 3. // В противном случае, вывести 0. document.querySelector('.i-9'); document.querySelector('.b-9').onclick = function f9 () { let num_8 = document.querySelector('.i-9').value; if ( num_8 >= 1 && num_8 <= 32 ) { document.querySelector('.out-9').innerHTML = ('1'); } else if ( num_8 >= 33 && num_8 <= 43 ){ document.querySelector('.out-9').innerHTML = ('2'); } else if ( num_8 >= 44 && num_8 <= 64 ){ document.querySelector('.out-9').innerHTML = ('3'); } else { document.querySelector('.out-9').innerHTML = ('0'); } } // Task 10 // Дан input i-101 и input-102, type=number. Дан select s-103, который содержит две операции - +, -, *, / . Дана кнопка b-10, при нажатии на которую срабатывает функция f10. Функция выводит в out-10 результат операций выбранной в 3-м select к числам введенным в первом и втором input. Например выбрано 1 13 +, нужно вывести 1+13. document.querySelector('.i-101'); document.querySelector('.i-102'); document.querySelector('.s-103'); document.querySelector('.b-10').onclick = f10; function f10 () { let input_101 =+ document.querySelector('.i-101').value; let input_102 =+ document.querySelector('.i-102').value; let number_2 = document.querySelector('.s-103').value; switch (number_2) { case '+': document.querySelector('.out-10').innerHTML = (input_101+input_102); break; case '-': document.querySelector('.out-10').innerHTML = (input_101-input_102); break; case '*': document.querySelector('.out-10').innerHTML = (input_101*input_102); break; case '/': document.querySelector('.out-10').innerHTML = (input_101/input_102); break; } } // Task 11 // Дан select s-111 и s-112, каждый из которых содержит 1 и 0. Дан select s-113, который содержит две операции - && и || . Дана кнопка b-11, при нажатии на которую срабатывает функция f11. Функция выводит в out-11 результат логических операций выбранных в 3 select к числам выбранным в первом и втором select. Например выбрано 1 1 &&, нужно вывести результат операции над выбранными числами и знаком. Т.е. если выбрали 1&&0 - то вывести 0, если 1||1 то 1. document.querySelector('.b-11').onclick = f11; function f11(){ let num_9 =+ document.querySelector('.s-111').value; let num_10 =+ document.querySelector('.s-112').value; let num_11 = document.querySelector('.s-113').value; switch ( num_11) { case num_11 == '&&': document.querySelector ('.out-11').innerHTML = num_9 && num_10; break; case num_11 == '||': document.querySelector ('.out-11').innerHTML = num_9 || num_10; break; } } // document.querySelector('.b-11').onclick = f11; // function f11(){ // let num_9 = +document.querySelector('.s-111').value; // let num_10 = +document.querySelector('.s-112').value; // let num_11 = document.querySelector('.s-113').value; // let oyn_1 = document.querySelector ('.out-11'); // if ( num_11 == '&&' ) { // oyn_1.innerHTML = num_9 && num_10; // } // else if ( num_11 == '||' ){ // oyn_1.innerHTML = num_9 || num_10; // } // } // 1&&1 = 1 // 1&&0 = 0 // 0&&1 = 0 // 0&&0 = 0 // 1||1 = 1 // 1||0 = 1 // 0||1 = 1 // 0||0 = 0 // console.log('Андрей' && 'Андрей' == true); //false // console.log(1 && 0 == true); // false // console.log('2' && '2' == true ); // false // console.log('4' && '1'); // true // console.log(true && 'Gleb' ); // Gleb // console.log(true && false ); // false // console.log('Gleb' && true ); // true // console.log(1 && '1'); let a = '200.1'; if ( true && false) { console.log('Ok'); } else { console.log('no'); }
true
fad47b348f791a2035df1833cca0578ef86cbc9f
JavaScript
kozuchowski/React-zadania
/2_Snippety/7_fetch/js/1_SimpleFetch/App.js
UTF-8
530
2.9375
3
[]
no_license
import ReactDOM from "react-dom"; import React, { useState, useEffect } from "react"; const FetchExample = () => { const [data, setData] = useState(false); useEffect(() => { fetch("https://api.ipify.org") .then(response => response.text()) .then(ip => { setData(ip); }); }); if (data === false) { return <h1>Ustalam adres IP...</h1>; } else { return <h1>Twoje IP: {data}</h1>; } }; const App = () => <FetchExample />; ReactDOM.render(<App />, document.getElementById("app"));
true
2c75f41e1f48ad2f0f26f87c868a2be968a1f099
JavaScript
mariavar/urban
/js/router.js
UTF-8
2,682
2.625
3
[]
no_license
const app = { init: function() { app.pages = document.querySelectorAll('.page'); document.querySelectorAll('.menubtn').forEach((link)=>{ link.addEventListener('click', app.nav); }); document.querySelectorAll('.dashboardbtn').forEach((link)=>{ link.addEventListener('click', app.dashnav); }); history.replaceState({}, 'Dashboard', '#dashboard'); window.addEventListener('popstate', app.poppin); }, nav: function(ev){ ev.preventDefault(); let currentPage = ev.target.getAttribute('data-target'); document.querySelector('.active').classList.remove('active'); document.getElementById(currentPage).classList.add('active'); console.log(currentPage) history.pushState({}, currentPage, `#${currentPage}`); // document.getElementById(currentPage).dispatchEvent(app.show); }, dashnav: function(ev){ ev.preventDefault(); let dashboardPage = ev.target.getAttribute('data-target'); let x = document.querySelectorAll('.showing'); let y = document.querySelectorAll("."+dashboardPage); for (i=0; i < x.length; i++) { x[i].classList.remove('showing'); }; for (j=0; j <= y.length; j++) { y[j].classList.add('showing'); }; }, poppin: function(ev){ console.log(location.hash, 'popstate event'); let hash = location.hash.replace('#' ,''); document.querySelector('.active').classList.remove('active'); document.getElementById(hash).classList.add('active'); console.log(hash) //history.pushState({}, currentPage, `#${currentPage}`); //document.getElementById(hash).dispatchEvent(app.show); } } document.addEventListener('DOMContentLoaded', app.init); function changeColorPlantBtn() { let grafBtn = document.getElementById("grafer-btn"); let planterBtn = document.getElementById("planter-btn"); if (grafBtn.classList.contains("btn-primary")) { grafBtn.classList.remove("btn-primary"); grafBtn.classList.add("btn-secondary"); planterBtn.classList.remove("btn-secondary"); planterBtn.classList.add("btn-primary"); } } function changeColorGraphBtn() { let grafBtn = document.getElementById("grafer-btn"); let planterBtn = document.getElementById("planter-btn"); if (planterBtn.classList.contains("btn-primary")) { planterBtn.classList.remove("btn-primary"); planterBtn.classList.add("btn-secondary"); grafBtn.classList.remove("btn-secondary"); grafBtn.classList.add("btn-primary"); } }
true
441a64fbe8e10cf2757bbd68a1532a7dfb031e31
JavaScript
Stobles/Uniform
/js/modal.js
UTF-8
1,383
2.8125
3
[]
no_license
let modal = document.querySelector('.modal') let news = document.querySelectorAll('.news__body') let modalTitle = document.querySelector('.modal__title') let modalDate = document.querySelector('.modal__date--body') let modalTime = document.querySelector('.modal__date--time') let modalText = document.querySelector('.modal__text') news.forEach(body => body.addEventListener('click', ()=>{ let title = body.querySelector('.news__body--title > p').innerHTML let date = body.querySelector('.news__body--date--text').innerHTML let time = body.querySelector('.news__body--date--time').innerHTML let texts = body.querySelectorAll('.news__body--text > p') let text = [] texts.forEach(textItem => text += textItem.innerHTML.replace(/<\/?[^>]+(>|$)/g, "") + '. ' ) modal.classList.add('active') modalTitle.textContent = title modalDate.textContent = date modalTime.textContent = time modalText.textContent = text if(modal.classList.contains('active')){ document.addEventListener('click', (e)=>{ if(e.target.classList.contains('close') || e.target.closest('.close') || e.target.classList.contains('modal')){ modal.classList.remove('active') } }) } }) )
true
2f5394c374500fa854aa9551578c46eafb901b43
JavaScript
richardhodgson/lian
/lib/mock/monk.js
UTF-8
4,134
2.609375
3
[]
no_license
var Promise = require('monk/lib/promise'); function copy (ob) { var dataSet = {}; for (key in ob) { dataSet[key] = ob[key]; } return dataSet; } function Db () { this._collections = {}; } Db.prototype.get = function (collectionName) { if (! this._collections[collectionName]) { this._collections[collectionName] = new Collection(collectionName); } return this._collections[collectionName]; } Db.prototype.close = function (callback) { callback && callback(); return this; } function Collection (name) { this._name = name; this._lastId = 0; this._data = {}; this._indexes = { 'unique': [] }; } Collection.prototype.index = function (property, type, callback) { if (! 'unique' in type) { throw new Error("Mock monk only supports unique indexes"); } var promise = new Promise(this, 'index'); promise.complete(callback); this._indexes['unique'].push(property); promise.fulfill.call(promise, false, undefined); return promise; } Collection.prototype.insert = function (ob, callback) { var promise = new Promise(this, 'insert'); promise.complete(callback); this._lastId++; var id = this._lastId; var dataSet = copy(ob); dataSet._id = id; if (this._data[id]) { throw new Error("cannot insert object, _id already exists"); } var canInsert = true; if (this._indexes['unique'].length > 0) { var index = this._indexes['unique'], unique = {}; for (var i = 0; i < index.length; i++) { var property = index[i]; unique[property] = dataSet[property]; } this.count(unique, function (err, results) { if (results > 0) { promise.emit('error', 'duplicate key error index: one of ' + index.join(',')); canInsert = false; } }); } if (canInsert) { this._data[id] = dataSet; promise.fulfill.call(promise, false, copy(dataSet)); } return promise; } Collection.prototype.find = function (ob, callback) { var promise = new Promise(this, 'find'); promise.complete(callback); var results = [], lookup = {}; var keys = []; for (var key in ob) { if (ob[key] === null) { continue; } keys.push(key); } var targetKey = keys.pop(); for (var id in this._data) { var candidate = this._data[id]; if (candidate[targetKey] && candidate[targetKey] == ob[targetKey]) { // test rest of values for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; if (!key in candidate || candidate[key] != ob[key]) { candidate = null; break; } } if (candidate) { results.push(copy(candidate)); } } } promise.fulfill.call(promise, false, results); return promise; } Collection.prototype.findOne = function (ob, callback) { var promise = new Promise(this, 'findOne'); promise.complete(callback); this.find(ob, function (err, results) { promise.fulfill.call(promise, false, (results.length) ? results[0] : null); }); return promise; } Collection.prototype.update = function (target, ob, callback) { var promise = new Promise(this, 'update'); promise.complete(callback); var id = target._id; if (! this._data[id]) { throw new Error("cannot find object _id to update, try inserting instead"); } this._data[id] = copy(ob); // resolves the callback with number of updates (which without {multi:true} option is always: 1) promise.fulfill.call(promise, false, 1); return promise; } Collection.prototype.count = function (ob, callback) { var promise = new Promise(this, 'count'); promise.complete(callback); this.find(ob, function (err, results) { promise.fulfill.call(promise, false, results.length); }); return promise; } module.exports = Db;
true
0b8b7a8b874f2f63b7d73ba6a28ca46560b531d9
JavaScript
vmx/xml2dom
/modjewel-require.js
UTF-8
9,443
2.921875
3
[ "MIT" ]
permissive
//---------------------------------------------------------------------------- // The MIT License // // Copyright (c) 2009, 2010 Patrick Mueller // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // an implementation of the require() function as specified for use with // CommonJS Modules - see http://commonjs.org/specs/modules/1.0.html //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // inspired from David Flanagan's require() function documented here: // http://www.davidflanagan.com/2009/11/a-module-loader.html //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // function wrapper //---------------------------------------------------------------------------- (function(){ //---------------------------------------------------------------------------- // some constants //---------------------------------------------------------------------------- var PROGRAM = "modjewel" var VERSION = "0.2.0" //---------------------------------------------------------------------------- // if require() is already defined, leave //---------------------------------------------------------------------------- if (window.require) { log("require() function already defined") return } //---------------------------------------------------------------------------- // a function to log a message; writes it to the console //---------------------------------------------------------------------------- function log(message) { if (!message) message = "" console.log(PROGRAM + " " + VERSION + ": " + message) } //---------------------------------------------------------------------------- // retrieve a URL's content via HTTP GET //---------------------------------------------------------------------------- function httpGet(url) { var xhr = new XMLHttpRequest() xhr.open("GET", url, false) xhr.send(null) // note, Chrome on Mac returns status=0 for file: URLs even if // they don't exist, breaking some tests in commonjs if ((xhr.status == 0) || (xhr.status == 200)) { if (typeof xhr.responseText != "string") return undefined return xhr.responseText } } //---------------------------------------------------------------------------- // strip leading chars //---------------------------------------------------------------------------- function stripLeading(string, c) { var regex = new RegExp("^" + c + "+") return string.replace(regex, "") } //---------------------------------------------------------------------------- // strip trailing chars //---------------------------------------------------------------------------- function stripTrailing(string, c) { var regex = new RegExp(c + "+$") return string.replace(regex, "") } //---------------------------------------------------------------------------- // join two parts of a URL //---------------------------------------------------------------------------- function urlJoin(urlBase, urlPart) { return stripTrailing(urlBase, "/") + "/" + stripLeading(urlPart, "/") } //---------------------------------------------------------------------------- // retrieve a module's content //---------------------------------------------------------------------------- function getModuleSource(uri) { for (var i=0; i<require.paths.length; i++) { var url = urlJoin(require.paths[i], uri) var contents = httpGet(url) if (contents != null) return {url: url, contents: contents} } } //---------------------------------------------------------------------------- // normalize a 'file name' with . and .. with a 'directory name' //---------------------------------------------------------------------------- function normalize(dir, file) { var dirParts = stripTrailing(dir, "/").split("/") var fileParts = file.split("/") for (var i=0; i<fileParts.length; i++) { var filePart = fileParts[i] if (filePart == ".") { } else if (filePart == "..") { if (dirParts.length > 0) { dirParts.pop() } else { throw new Error("Error normalizing '" + dir + "' and '" + file + "'") } } else { dirParts.push(filePart) } } return dirParts.join("/") } //---------------------------------------------------------------------------- // the require function //---------------------------------------------------------------------------- function require(moduleId) { var origModuleId = moduleId if (moduleId.match(/^\.{1,2}\//)) { moduleId = normalize(require.__currentModulePath, moduleId) } var moduleUri = moduleId + ".js" if (require.__modules.hasOwnProperty(moduleUri)) { return require.__modules[moduleUri].exports } var originalModulePath = require.__currentModulePath require.__currentModulePath = moduleId.substring(0, moduleId.lastIndexOf('/')+1) var originalModule = require.__currentModule try { var moduleFunction var moduleSourceUri if (require.__preload.hasOwnProperty(moduleUri)) { moduleFunction = require.__preload[moduleUri] moduleSourceUri = "" } else { var moduleSource = getModuleSource(moduleUri) if (moduleSource == null) { throw new Error("unable to load module " + origModuleId) } source = moduleSource.contents source += "\n//@ sourceURL=" + moduleUri moduleFunction = new Function("require", "exports", "module", source) moduleSourceUri = moduleSource.uri } function get_setExports(module) { return function getExports(object) { if (module != require.__currentModule) { throw new Error("invalid call to require.setExports") } module.exports = object } } var context = {} var exports = {} var module = { id: moduleId, uri: moduleSourceUri, exports: exports } module.setExports = get_setExports(module) require.__modules[moduleUri] = module require.__currentModule = module moduleFunction.call(context, require, exports, module) return module.exports } finally { require.__currentModulePath = originalModulePath require.__currentModule = originalModule } } //---------------------------------------------------------------------------- // make the require function a global //---------------------------------------------------------------------------- window.require = require //---------------------------------------------------------------------------- // set some version information //---------------------------------------------------------------------------- require.implementation = PROGRAM require.version = VERSION //---------------------------------------------------------------------------- // initialize require.paths //---------------------------------------------------------------------------- require.paths = [""] //---------------------------------------------------------------------------- // used by pre-built modules that can be included via <script src=> //---------------------------------------------------------------------------- require.preload = function require_preload(moduleName, moduleDefFunction) { require.__preload[moduleName + ".js"] = moduleDefFunction } //---------------------------------------------------------------------------- // initialize internal stuff //---------------------------------------------------------------------------- require.__currentModulePath = "" require.__currentModule = undefined require.__modules = {} require.__preload = {} //---------------------------------------------------------------------------- })()
true
e8c6593516a96f76959c2c324e49c1f7ac723e98
JavaScript
BuildFire/focusGamePlugin
/widget/js/gameUI.js
UTF-8
4,794
2.734375
3
[ "MIT" ]
permissive
//by danielhindi on 1/10/18. var gameUI= { init:function(user,scoreboard){ this.user=user; this.scoreboard=scoreboard; this.focusSection = document.getElementById("focusSection"); this.shapesSection = document.getElementById("shapesSection"); this.actionBar = document.getElementById("actionBar"); this.btnYes = document.getElementById("btnYes"); this.btnNo = document.getElementById("btnNo"); this.score=document.getElementById("score"); this.arc=document.getElementById("arc"); this.gameTmr=null; var shapeBaseURL= "./css/shapes/"; game.showFocusSymbol = function (symbol, cb) { gameUI.focusSection.innerHTML = "<div>Is there a " + symbol.color + " " + symbol.shape + "</div>" + '<img style="background-color:' + symbol.color + '" class="shape" src="' + shapeBaseURL + symbol.shape + '.png" />'; gameUI.shapesSection.innerHTML='Get Ready...'; gameUI.actionBar.classList.add("hidden"); gameUI.btnYes.onclick=null; gameUI.btnNo.onclick=null; ///pause for 3 sec for the user to focus setTimeout(function(){ cb.call(game); },3000); }; game.showSymbols = function(symbols,seconds,userAnsweredFn){ var html=''; var ts = new Date(); symbols.forEach(function(s){ html += '<img style="background-color:' + s.color + '" class="shape" src="' + shapeBaseURL + s.shape + '.png" />'; }); gameUI.shapesSection.innerHTML=html; var scale = 1.0 - (symbols.length-8)/10; gameUI.shapesSection.style.transform='scale(' + scale + ')'; gameUI.actionBar.classList.remove("hidden"); gameUI.arc.style.animationDuration = seconds+ 's'; setTimeout(function() { gameUI.arc.classList.add('timeBomb'); },10); if(gameUI.gameTmr)clearTimeout(gameUI.gameTmr); gameUI.gameTmr = setTimeout(function() {/// time limit userAnsweredFn.call(game,null); },seconds * 1000); function getBonus(){ var ms = new Date() - ts; var bonus = 5000 - ms; if(bonus<0)bonus=0; return Math.round(bonus/100) ; } function fnYes() { gameUI.arc.classList.remove('timeBomb'); if(gameUI.gameTmr)clearTimeout(gameUI.gameTmr); userAnsweredFn.call(game,true,getBonus()); }; function fnNo() { gameUI.arc.classList.remove('timeBomb'); if(gameUI.gameTmr)clearTimeout(gameUI.gameTmr); userAnsweredFn.call(game,false,getBonus()); }; if( location.protocol.indexOf('http')==0) { gameUI.btnYes.onclick = fnYes; gameUI.btnNo.onclick = fnNo; } else{ gameUI.btnYes.ontouchstart = fnYes; gameUI.btnNo.ontouchstart = fnNo; } }; game.showNewScore = function(newScore,level,cb){ score.innerHTML="Level: " + (Math.floor(level / 10)+1) + " Score: " + newScore; cb.call(game); }; game.showGameOver = function (score) { gameUI.gameMusic.pause(); gameUI.scoreboard.logScore(gameUI.user, score,function(err,result){ if(result && result.rankedAt >= 0){ new Audio('audio/win.mp3').play(); /// means you made top 10 list gameUI.shapesSection.innerHTML=''; var span = document.createElement('span'); span.innerHTML="Congratulations! You ranked #" + (result.rankedAt +1) ; gameUI.shapesSection.appendChild(span); var btn = document.createElement('button'); btn.innerHTML="See High Score!"; btn.onclick=function(){location = "index.html";}; gameUI.shapesSection.appendChild(btn); } else { new Audio('audio/lose.mp3').play(); gameUI.shapesSection.innerHTML = "Game Over! <button onclick='location.reload()'>Start Over</button>"; } }); gameUI.actionBar.style.display="none"; }; this.gameMusic = new Audio('audio/gamePlay.mp3'); this.gameMusic.play(); this.gameMusic.addEventListener('ended', function() { this.currentTime = 0; this.play(); }, false); } };
true
3ce39e43c17203998985f15c50c3c8b24157888c
JavaScript
agu3rra/mynotes
/Programming/JavaScript/PS-PracticalDesignPatterns/creational/factory/task.js
UTF-8
391
3.125
3
[]
no_license
// as of ES6 you can use class var Repo = require('./taskRepo.js') class Task { constructor(name) { this.name = name this.completed = false } complete() { console.log(`completing task: ${this.name}`) this.completed = true } save() { console.log(`saving task: ${this.name}`) Repo.save(this) } } module.exports = Task;
true
2997b75e60c9848c875eac9dfcdcd51c9723ee3a
JavaScript
mikelane/colorfade
/colorfade.js
UTF-8
2,456
3.1875
3
[]
no_license
var c = function() { return({ log: function(msg) { consoleDiv = document.getElementById('console'); para = document.createElement('p'); text = document.createTextNode(msg); para.appendChild(text); consoleDiv.appendChild(para); } }); }(); function toRGB(H, S, V) { S /= 100; V /= 100; var C = V * S; H /= 60; var X = C * (1 - Math.abs((H % 2) - 1)); var R = 0; var G = 0; var B = 0; if(0 <= H && H < 1) { R = C; G = X; B = 0; } else if(1 <= H && H < 2) { R = X; G = C; B = 0; } else if(2 <= H && H < 3) { R = 0; G = C; B = X; } else if(3 <= H && H < 4) { R = 0; G = X; B = C; } else if(4 <= H && H < 5) { R = X; G = 0; B = C; } else if(5 <= H && H < 6) { R = C; G = 0; B = X; } else { R = 0; G = 0; B = 0; } var m = V - C; R = Math.round(255 * (R + m)).toString(16); R.length < 2 ? R = "0" + R : R = "" + R; G = Math.round(255 * (G + m)).toString(16); G.length < 2 ? G = "0" + G : G = "" + G; B = Math.round(255 * (B + m)).toString(16); B.length < 2 ? B = "0" + B : B = "" + B; var RGB = "#" + R + G + B; return RGB; } function pulseColor() { //var H = Math.floor(Math.random() * 360); var H = 0; var i = setInterval(function() { if(H >= 360) { return; } fadeIn(H); c.log(H); H += 10 }, 3100); } function fadeIn(H) { var colorbox = document.querySelector("#colorbox"); var V = 0; var interval = setInterval(function() { if(V > 100) { clearInterval(interval); c.log(toRGB(H, 100, 100)); setTimeout(function() { interval = setInterval(function() { if(V < 0) { clearInterval(interval); return; } colorbox.style.backgroundColor = toRGB(H, 100, V); colorbox.style.borderColor = toRGB(((H + 180) % 360), 100, V--); }, 10) }, 1000); return; } colorbox.style.backgroundColor = toRGB(H, 100, V); colorbox.style.borderColor = toRGB(((H + 180) % 360), 100, V++); }, 10); } function fadeOut(H) { var colorbox = document.querySelector("#colorbox"); var V = 100; var interval = setInterval(function() { if(V < 0) { clearInterval(interval); return; } colorbox.style.backgroundColor = toRGB(H, 100, V); colorbox.style.borderColor = toRGB(((H + 180) % 361), 100, V--); }, 10); }
true
1d736656a26518c6b8a4220cfe5e7e41e2ed6e98
JavaScript
leozheng08/QuickFood
/WEB-INF/classes/map.js
UTF-8
1,377
2.828125
3
[]
no_license
var map; var directionsService; var directionsRenderer; var start; function initMap(){ directionsService = new google.maps.DirectionsService(); directionsRenderer = new google.maps.DirectionsRenderer(); var chicago = new google.maps.LatLng(41.850033, -87.6500523); var mapOptions = { zoom:7, center: chicago } map = new google.maps.Map(document.getElementById('map'), mapOptions); directionsRenderer.setMap(map); start = new google.maps.LatLng(37.7699298, -122.4469157); geocode(); } function geocode(){ var location = '3021 S Michigan Ave'; axios.get('https://maps.googleapis.com/maps/api/geocode/json',{ params:{ address:location, key:'AIzaSyBicN5EAdRH-1kG9-xqnZK0w8KO9g5drfk' } }).then(function(response){ console.log(response); var lat = response.data.results[0].geometry.location.lat; var lng = response.data.results[0].geometry.location.lng; var end = new google.maps.LatLng(lat, lng); var request = { origin: start, destination: end, travelMode: 'DRIVING' }; directionsService.route(request, function(result, status) { if (status == 'OK') { directionsRenderer.setDirections(result); } }); }).catch(function(error){ console.log(error); }); }
true
baff94cd8d99eb9d8f10a8f2831e2c0e103ebe05
JavaScript
dewil-official/node-quiz-server
/client/scripts/quiz.js
UTF-8
5,200
2.65625
3
[ "MIT" ]
permissive
// Imports var socket = io(); var quiz = {}; var user = {}; var users = []; socket.on("connect", function() { if (!sessionStorage.sessionToken) window.location = "/"; if (sessionStorage.sessionToken) socket.emit("validateToken", sessionStorage.sessionToken); }); socket.on("validationSuccess", function(isMaster) { if (isMaster == true) { window.location = "/master"; } socket.emit("requestUpdate", sessionStorage.sessionToken); }); socket.on("validationFailed", function() { sessionStorage.sessionToken = null; window.location = "/"; }); socket.on("resetInput", function() { $("#user-answer").val(""); }); socket.on("notifyUpdate", function() { socket.emit("requestUpdate", sessionStorage.sessionToken); }); socket.on("broadcast", function(msg) { M.toast({ html: msg }); }); function refreshPage() { location.reload(); } /* || || || Quiz-Logic || \/ \/ */ socket.on("pageUpdate", function(data) { // Set the template if needed. if (quiz != {}) { quiz = data.quiz; user = data.user; setTemplate(); } else { if ( data.quiz.number != quiz.number && data.status != "waiting" && data.status != "score" && data.status != "finished" ) { quiz = data.quiz; user = data.user; setTemplate(); } else if ( (data.quiz.status == "answer" && quiz.status == "question") || (data.quiz.status == "question" && quiz.status == "answer") ) { // On answer-reveal, don't apply template. quiz = data.quiz; user = data.user; } else { quiz = data.quiz; user = data.user; setTemplate(); } } if (data.users) users = data.users; $("#question").html(quiz.question); if (quiz.type == "choice") { $("#answer1").html(quiz.answer1); $("#answer2").html(quiz.answer2); $("#answer3").html(quiz.answer3); $("#answer4").html(quiz.answer4); } if (quiz.type == "guess") { var range = quiz.other.split("-"); $("#guess-answer").attr("min", range[0]); $("#guess-answer").attr("max", range[1]); $("#guess-answer-reflection").html($("#guess-answer").val()); } if (quiz.type == "image") { $("#image").attr("src", quiz.other); $(".materialboxed").materialbox(); } if (quiz.type == "yt") { $("#video").attr("src", quiz.other); } if (quiz.status != "score") $("#score").html(user.score); if (quiz.status == "score" || quiz.status == "finished") { let html = ""; users.sort(function(a, b) { return b.score - a.score; }); users.forEach(u => { let userHtml = $("#scoreUser-template").html(); userHtml = userHtml.replace("USER", u.name + ": " + u.score); html += userHtml; }); $("#page-content .collection").html(html); } if (quiz.status == "question") { $("#trueAnswer") .parent() .attr("hidden", "hidden"); } if (quiz.status == "answer") { $("#trueAnswer") .parent() .removeAttr("hidden"); if (quiz.type == "choice") { $("#trueAnswer").html($("#answer" + quiz.trueAnswer).html()); } else { $("#trueAnswer").html(quiz.trueAnswer); } } }); function countStringInArray(arrayData, countString) { var count = 0; arrayData.forEach(d => { if (d == countString) { count++; } }); return count; } function setTemplate() { if (quiz.status == "waiting") $("#page-content").html($("#waiting-template").html()); if (quiz.status == "score") $("#page-content").html($("#score-template").html()); if (quiz.status == "finished") $("#page-content").html($("#finished-template").html()); if (quiz.status == "question" || quiz.status == "answer") { $("#page-content").html($("#quiz-template").html()); if (quiz.type == "image") $("#image-type").removeAttr("hidden"); if (quiz.type == "yt") $("#yt-type").removeAttr("hidden"); if (quiz.type == "choice") $("#choice-type").removeAttr("hidden"); if (quiz.type == "guess") $("#guess-type").removeAttr("hidden"); if (quiz.type != "choice" && quiz.type != "guess") $("#user-answer") .parent() .removeAttr("hidden"); } } function choiceSelect(nr) { if (!$("#answer" + nr).hasClass("active")) { $(".collection-item").removeClass("active"); $("#answer" + nr).addClass("active"); } // Update Logic for this type goes here: socket.emit("userInput", { input: nr, token: sessionStorage.sessionToken }); } function submitUpdate() { if (quiz.type == "guess") { socket.emit("userInput", { input: $("#guess-answer").val(), token: sessionStorage.sessionToken }); } else { socket.emit("userInput", { input: $("#user-answer").val(), token: sessionStorage.sessionToken }); } } function submitReady() { if ($("#ready").is(":checked")) { socket.emit("userReady", { token: sessionStorage.sessionToken, ready: true }); } else if ($("#ready")) { socket.emit("userReady", { token: sessionStorage.sessionToken, ready: false }); } } function updateReflection() { $("#guess-answer-reflection").html($("#guess-answer").val()); }
true
c393e1c9ae6c0ea2591a8b19ae761c4fb2de9b00
JavaScript
watchcity/karma-angular
/scraps.js
UTF-8
713
3.109375
3
[]
no_license
// var d1 = [], d2 = [], d3 = []; // //for (var i = 0; i<data.length;i++) { // var today = new Date(); // today.setHours(0,0,0,0); // //Get time of last 5 years // var last5Years = new Date(today.setFullYear(today.getFullYear() + 5)).getTime(); // //Get time of last 10 years // var last10Years = new Date(today.setFullYear(today.getFullYear() + 5)).getTime(); // // var s = data[i].Date.split('T')[0]; // var t = [new Date(s).getTime()]; // d1.push(t); //push all dates to d1 // if (t < last5Years) { // d2.push(t); //push last 5years dates to d2 // } // else if (t < last10Years) { // d3.push(t); //push last 10 years dates to d3 // } // //}
true
7b421ae7ea8c5165f6566d5074f5b7bb341eeee4
JavaScript
meatbags/galleria
/js/glsl/fragments/waves_shader.js
UTF-8
517
2.921875
3
[ "MIT" ]
permissive
/** Waves shader */ const WavesShader = ` vec3 p = position; float f = time * 0.2; float noise = perlinNoise(vec2(f + p.y, f + p.x)); float t = 0.0; float tMin = 2.5; float tMax = 6.5; if (p.y < tMax && p.y > tMin) { t = sin((tMax - p.y) / (tMax - tMin) * 3.14159) * 0.12; } float x = t * noise; float z = -t * ((noise + 1.0) / 2.0); vec3 noiseVec = vec3(x, 0.0, z); vec3 transformed = p + noiseVec; vNormal.y = sin(x) * 2.0; vNormal.z = cos(x) * 6.0; `; export default WavesShader;
true
f8277461ec8eb6b01490e5eb315c45a117603d38
JavaScript
J3eff/curso-web-javascript
/fundamentos/unarios.js
UTF-8
299
3.546875
4
[]
no_license
let num1 = 1 let num2 = 2 num1++ //pósfixada | Acrecenta uma unidade ao valor da variavel console.log(num1) --num1 //pre fixada -> tem precedencia maior do que a pósfixada | Subtrai uma uniadade ao valor da variavel console.log(num1) console.log(++num1 === num2--) console.log(num1 === num2)
true
ab01e633a57c12a10b347041e8eb0397405d990a
JavaScript
bbdouglas/hnindex
/html/main.js
UTF-8
2,753
2.609375
3
[]
no_license
(function() { function searchError(jqXHR, textStatus, errorThrown) { $("#results").text("Error: " + textStatus + ", " + errorThrown); } function search() { function searchSuccess(data, textStatus, jqXHR) { var results = $("#results"); results.empty(); var prev = $("<a>").addClass("nav-link").text("<"); if (data.response.start > 0) { prev.attr("href",""); prev.click(function(e) { e.preventDefault(); start -= rows; qParams.start = start; $.ajax(url,settings); }); } var headerContents = $("<span>").text("Total: " + data.response.numFound + ", Start: " + data.response.start); var next = $("<a>").addClass("nav-link").text(">"); if (data.response.start + data.response.docs.length < data.response.numFound) { next.attr("href",""); next.click(function(e) { e.preventDefault(); start += rows; qParams.start = start; $.ajax(url,settings); }); } var header = $("<p>").append(prev).append(headerContents).append(next); results.append(header); for (var i = 0; i < data.response.docs.length; ++i) { var profileData = data.response.docs[i]; var profile = $("<p>"); var userURL = "https://news.ycombinator.com/user?id=" + profileData.id; var profileHeader = $('<span><a href="' + userURL + '" target="_blank">' + profileData.id + "</a> (" + profileData.karma + ")</span><br>"); profile.append(profileHeader); var profileBio = $("<div>").addClass("bio"); profileBio.html(profileData.about); profile.append(profileHeader); profile.append(profileBio); results.append(profile); } } $("#results").text("Searching..."); var query = $("#query").val(); var start = 0; var rows = 10; var url = "/solr/hnindex/select" var qParams = { q:"{!edismax df=about}" + query, wt:"json", fl:"id,karma,about", start:start, rows:rows, sort:"karma desc", }; var settings = { data:qParams, dataType:"json", error:searchError, success:searchSuccess, }; if (query.length == 0) { $("#results").text("Please input a query string."); } else if (query.length > 80) { $("#results").text("Exceeded maximum query length (80 characters)."); } else { $.ajax(url,settings); } } $( document ).ready(function() { var queryBox = $("#query"); queryBox.val(""); queryBox.keypress(function(e) { var key = e.which; if (key == 13) { search(); } }); $("#search").click(search); }); })();
true
a90faa1c10d3e7f3a7fa6f8d6a1fbca8c38fadf1
JavaScript
gitgrimbo/cache-flow-problems
/src/shared/dumb-assign.js
UTF-8
349
2.96875
3
[ "MIT" ]
permissive
/** * Use when you don't want Object.assign semantics. * * I.e. you don't want to "copy the values of all enumerable own properties". */ function assign(dest, src1, src2, etc) { for (var i = 1; i < arguments.length; i++) { for (var k in arguments[i]) { dest[k] = arguments[i][k]; } } return dest; } module.exports = assign;
true
efedc0011cc4858d47c56638d62a43b5ee8f1e0a
JavaScript
ectky/JSProjects
/01. Increment-Counter/incrementCounter.js
UTF-8
600
2.75
3
[]
no_license
function increment(selector) { $(selector) .append($('<textarea class="counter" value="0" disabled>0</textarea>')) .append($('<button class="btn" id="incrementBtn">Increment</button>')) .append($('<button class="btn" id="addBtn">Add</button>')) .append($('<ul class="results"></ul>')) $('#incrementBtn') .click(function () { $('textarea').val(Number($('textarea').val()) + 1); }); $('#addBtn') .click(function () { $('ul').append($(`<li>${$('textarea').val()}</li>`)); }); }
true
89ba9f0c42e813a6e42f0cd74a986315dfbba18d
JavaScript
MEECAH/watercolors-generative
/watercolor.js
UTF-8
5,268
3.046875
3
[]
no_license
//some global variables var seed, sides, r, recurrences = 0, mpVariance, angleVariance, magVariance, numDesiredPaintLayers, numPaintLayersDrawn, numDeformationLayers, vertices = [], ogPolygon = [], baseDeformedPolygon = [], tmp = [], m = 1, sd = 1, imageScale = 1, frameCount = 1, //set to 0 for gif creation, else set to 1 img; //seed = Math.round(Math.random() * Number.MAX_SAFE_INTEGER); //random seed seed = 3693199348549950; //use this line for a specific seed //edit this to increase the number of recursions //on the deformation function //numDeformationLayers = 3; //choose a basic drawing mode, 0 for lines 1 for color fill let drawingMode = 1; function setup() { //frameRate(1) //createLoop({duration:10, gif:true}) let myCanvas = createCanvas(imageScale * 1100, imageScale * 930); background(230,230,230); angleMode(DEGREES); myCanvas.parent("container"); randomSeed(seed); sides = 360 / 10; r = imageScale * 160; // this generates a set of (x,y) // coordinates that define a 10 sided ellipse like polygon for (let a = 0; a <= 360; a += sides) { let x = r * sin(a + 18) + width / 2; let y = r * cos(a + 18) + height / 2; vert = [x, y]; vertices.push(vert); ogPolygon.push(vert); //xCoords.push(x) //yCoords.push(y) //console.log(vert) } for (let i = 0; i < vertices.length; i++) { //ellipsePolygon.push(createVector(xCoords[i],yCoords[i])) } } function draw() { if (drawingMode == 0) { stroke(255); noFill(); } else { fill(255, 40, 45, 2); noStroke(); } for (let i = 1; i <= 3; i++) { numDeformationLayers = i; baseDeformedPolygon = deform(vertices); tmp = [...baseDeformedPolygon]; for (let i = 0; i < 17; i++) { numDeformationLayers = 3; //let details = deform(baseDeformedPolygon); splotch(baseDeformedPolygon); vertices = [...tmp]; } } // if (frameCount == 5) { // clear(); // background(35); // frameCount = 0; // numDeformationLayers = 1; // vertices = []; // vertices = [...ogPolygon]; // } //code block above only used for animated gif rendering noLoop(); //loop(); } function splotch(arg) { //this if/else is for making gifs of the deformation process if (frameCount == 0) { //base polygon before any deformations beginShape(); arg.forEach((vert) => vertex(vert[0], vert[1])); endShape(); //console.log(vertices); frameCount++; } else { center = createVector(width / 2, height / 2); let deformed = deform(arg); //recursively deformed polygon beginShape(); deformed.forEach((vert) => vertex(vert[0], vert[1])); endShape(); //draw red stuff //stroke(255, 0, 0); //strokeWeight(5); //these are exclusively used for making animated gif versions for documentation purposes // frameCount++; // numDeformationLayers++; } } //custom function to deform by add 'jutting' between polygon edges function deform(arg, layers) { push(); //stroke(255, 0, 0); //strokeWeight(3); //deep copy arg array arr = []; for (let i = 0; i < arg.length; i++) { arr.push(arg[i]); } for (let i = 0; i < arr.length - 1; i += 2) { //for fine tuning the randomness on polygon deformation mpVariance = 0; //randomGaussian(1, 10) angleVariance = 0; //randomGaussian(1, 10); magVariance = 1; //posRandomGaussian(20, 50); midpoint = calcMidpoint(arr[i], arr[i + 1]); midpoint.add(mpVariance); //this adds imperfection to the midpoint location //point(midpoint); //angleMode(RADIANS); base = createVector(0, 0); //drawArrow(base,midpoint,'red') vect = createVector(arr[i + 1][0] - arr[i][0], arr[i + 1][1] - arr[i][1]); vect.mult(random()); // / (numDeformationLayers - 1)); //vect.setMag( vect.mag()*magVariance / (1 * numDeformationLayers)); //add imperfection to the mag of jut vect.rotate(90 + angleVariance); //add imperfection to the rotation of the jut vect.add(midpoint); //console.log(vect); //point(vect); jut = [vect.x, vect.y]; //console.log(jut); arr.splice(i + 1, 0, jut); //i++; //drawArrow(base,vect,'blue') } pop(); recurrences++; if (recurrences == numDeformationLayers) { recurrences = 0; return arr; } else { return deform(arr); } } //calculate the midpoint between two vertices in a 2d pixel plane function calcMidpoint(v1, v2) { let midpoint = createVector(0, 0); midpoint.add(v1); midpoint.add(v2); return midpoint.div(vert.length); } //truncate random gaussian, making mean value more likely(?) function posRandomGaussian(m, sd) { let s = randomGaussian(m, sd); if (s < 0) { s = 0; } return s; } // draw an arrow for a vector at a given base position function drawArrow(base, vec, myColor) { push(); stroke(myColor); strokeWeight(3); fill(myColor); translate(base.x, base.y); line(0, 0, vec.x, vec.y); rotate(vec.heading()); let arrowSize = 7; translate(vec.mag() - arrowSize, 0); triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); pop(); } let seedtext = document.getElementById("seed"); seedtext.innerHTML = ` <p> seed value: ` + seed + ` </p> `;
true
5c1e0d705a46f260df60e07bd8d3cc409ccc14a5
JavaScript
parkerproject/github-search-repo
/src/utils.js
UTF-8
874
2.703125
3
[]
no_license
export function encodeQuery(obj) { const ret = []; for (let d in obj) { if (obj.hasOwnProperty(d) && obj[d]) { ret.push(encodeURIComponent(d) + ":" + encodeURIComponent(obj[d])); } } return ret.join(" "); } export function parseQueryStr(str) { const queries = decodeURIComponent(str); const hash = {}; queries.split(" ").forEach((val, key) => { let q; if (key === 0) { if (!val) { return; } q = val.replace("?", ""); q = q.split("="); } else { q = val.split(":"); } hash[q[0]] = q[1]; }); return hash; } export function buildQuery({ q, stars, license, fork }) { let url = encodeQuery({ stars, license, fork }); url = `q=${q} ${url}`; return url; } export function isEmpty(obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) return false; } return true; }
true
7b61c53677133d8164918af85f38f0a46365bf32
JavaScript
DeckHunter/UI_Mobalytics
/Backgrounds.js
UTF-8
704
2.859375
3
[]
no_license
var imgFundo = window.document.body var h1 = document.getElementById('js-h1') function background(id){ console.log('funcao Chamda '+id) if(id === 0) { imgFundo.style.backgroundImage= "url('img/Background.png')" h1.innerHTML = 'start your legend' } if(id === 1){ imgFundo.style.backgroundImage = "url('img/csGo_bg.png')" h1.innerHTML = 'Strike Now!' } if(id === 2) { imgFundo.style.backgroundImage = "url('img/tft_bg.png')" h1.innerHTML = 'get better at teamfight tactics' } if(id === 3){ imgFundo.style.backgroundImage = "url('img/magic_bg.png')" h1.innerHTML = 'All the strategy, All the action' } }
true
4fe17eb03fb4bf922606f5d740b25720b8e6563d
JavaScript
jairuzu/solarStrike
/src/game/collisionService.js
UTF-8
2,632
2.578125
3
[]
no_license
angular.module('Solar Strike').service('collisionService', function(utilityService) { this.checkCollision = function(objA, objB) { if (objA.collisionObjNamesToDetect.indexOf(objB.name) !== -1 || objB.collisionObjNamesToDetect.indexOf(objA.name) !== -1) { var xDiff = objA.centerX - objB.centerX; var yDiff = objB.centerY - objA.centerY; var centerAngle = utilityService.correctAngle2PI(Math.atan2(yDiff, xDiff)); if (objA.collisionShape === 'circle' && objB.collisionShape === 'circle') { var diff = Math.sqrt(Math.pow(Math.abs(xDiff),2)+Math.pow(Math.abs(yDiff),2)); var dist = diff - objA.boundWidth/2 - objB.boundWidth/2; if (dist <= 0) { return true; } else { return false; } } else if (objA.collisionShape === "rectangle" && objB.collisionShape === "rectangle") { if (objA.centerX + objA.boundWidth/2 > objB.centerX - objB.boundWidth/2 && objA.centerX - objA.boundWidth/2 < objB.centerX + objB.boundWidth/2 && objA.centerY + objA.boundHeight/2 > objB.centerY - objB.boundHeight/2 && objA.centerY - objA.boundHeight/2 < objB.centerY + objB.boundHeight/2) { return true; } else { return false; } } else if (objA.collisionShape === "point" || objB.collisionShape === "point") { if (objA.collisionShape === "point" && objB.collisionShape === "point") { //Do nothing. } else if (objA.collisionShape === "point") { var diff = Math.sqrt(Math.pow(Math.abs(xDiff),2)+Math.pow(Math.abs(yDiff),2)); var dist = diff - objB.boundWidth/2; if (dist <= 0) { return true; } else { return false; } } else { var diff = Math.sqrt(Math.pow(Math.abs(xDiff),2)+Math.pow(Math.abs(yDiff),2)); var dist = diff - objA.boundWidth/2; if (dist <= 0) { return true; } else { return false; } } } else { console.log('TBD'); } } else { return false; } } });
true
fb6f2877e22068db821b8ae3be3464af78e75211
JavaScript
ywoo-park/computer-graphics-final
/computer-graphics-final-client/script.js
UTF-8
14,371
2.84375
3
[]
no_license
var PointerLockControls = function (camera, cannonBody) { var velocityFactor = 0.2; var jumpVelocity = 20; var scope = this; var pitchObject = new THREE.Object3D(); pitchObject.add(camera); var yawObject = new THREE.Object3D(); yawObject.position.y = 2; yawObject.add(pitchObject); var quat = new THREE.Quaternion(); var enter = false; var moveForward = false; var moveBackward = false; var moveLeft = false; var moveRight = false; var canJump = false; var contactNormal = new CANNON.Vec3(); // Normal in the contact, pointing *out* of whatever the player touched var upAxis = new CANNON.Vec3(0, 1, 0); cannonBody.addEventListener("collide", function (e) { var contact = e.contact; // contact.bi and contact.bj are the colliding bodies, and contact.ni is the collision normal. // We do not yet know which one is which! Let's check. if (contact.bi.id == cannonBody.id) // bi is the player body, flip the contact normal contact.ni.negate(contactNormal); else contactNormal.copy(contact.ni); // bi is something else. Keep the normal as it is // If contactNormal.dot(upAxis) is between 0 and 1, we know that the contact normal is somewhat in the up direction. if (contactNormal.dot(upAxis) > 0.5) // Use a "good" threshold value between 0 and 1 here! canJump = true; }); var velocity = cannonBody.velocity; var PI_2 = Math.PI / 2; var onMouseMove = function (event) { if (scope.enabled === false) return; var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0; var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0; yawObject.rotation.y -= movementX * 0.002; pitchObject.rotation.x -= movementY * 0.002; pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x)); }; var onKeyDown = function (event) { switch (event.keyCode) { case 13: // enter enter = true; case 38: // up case 87: // w moveForward = true; break; case 37: // left case 65: // a moveLeft = true; break; case 40: // down case 83: // s moveBackward = true; break; case 39: // right case 68: // d moveRight = true; break; } }; var onKeyUp = function (event) { switch (event.keyCode) { case 13: // enter enter = false; case 38: // up case 87: // w moveForward = false; break; case 37: // left case 65: // a moveLeft = false; break; case 40: // down case 83: // a moveBackward = false; break; case 39: // right case 68: // d moveRight = false; break; } }; document.addEventListener('mousemove', onMouseMove, false); document.addEventListener('keydown', onKeyDown, false); document.addEventListener('keyup', onKeyUp, false); this.enabled = false; this.getObject = function () { return yawObject; }; var focused = false; // Moves the camera to the Cannon.js object position and adds velocity to the object if the run key is down var inputVelocity = new THREE.Vector3(); var euler = new THREE.Euler(); this.update = function (delta) { if (scope.enabled === false) return; delta *= 0.1; inputVelocity.set(0, 0, 0); // start conversation("enter") // enter for starting input if(focused === false && enter){ document.getElementById('question-input').focus(); enter = false; focused = true; } if(focused === true && enter && question && question.length > 0){ enter = false; focused = false; fetchBotResponse(question); document.getElementById("question").innerText = question; document.getElementById("question-input").value = ""; document.activeElement.blur(); question = ""; } if(focused === false){ if (moveForward) { inputVelocity.z = -velocityFactor * delta; } if (moveBackward) { inputVelocity.z = velocityFactor * delta; } if (moveLeft) { inputVelocity.x = -velocityFactor * delta; } if (moveRight) { inputVelocity.x = velocityFactor * delta; } } // Convert velocity to world coordinates euler.x = pitchObject.rotation.x; euler.y = yawObject.rotation.y; euler.order = "XYZ"; quat.setFromEuler(euler); inputVelocity.applyQuaternion(quat); //quat.multiplyVector3(inputVelocity); // Add to the object velocity.x += inputVelocity.x; velocity.z += inputVelocity.z; yawObject.position.copy(cannonBody.position); }; }; // code start var sphereShape, sphereBody, world, physicsMaterial, walls = [], balls = [], ballMeshes = [], boxes = [], boxMeshes = []; var camera, scene, renderer; var geometry, material, mesh; var controls, time = Date.now(); var blocker = document.getElementById('blocker'); var instructions = document.getElementById('instructions'); var havePointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; var action, mixer, clock, animations; var answer = "Ready to answer"; var question = ""; var actionList = ["Dance", "Death", "Idle", "Jump", "No", "Punch", "Running", "Sitting", "Standing", "ThumbsUp", "Walking", "WalkJump", "Wave", "Yes"]; var emotionIndex = 0; if (havePointerLock) { var element = document.body; var pointerlockchange = function (event) { if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) { controls.enabled = true; blocker.style.display = 'none'; } else { controls.enabled = false; } } var pointerlockerror = function (event) { instructions.style.display = ''; } // Hook pointer lock state change events document.addEventListener('pointerlockchange', pointerlockchange, false); document.addEventListener('mozpointerlockchange', pointerlockchange, false); document.addEventListener('webkitpointerlockchange', pointerlockchange, false); document.addEventListener('pointerlockerror', pointerlockerror, false); document.addEventListener('mozpointerlockerror', pointerlockerror, false); document.addEventListener('webkitpointerlockerror', pointerlockerror, false); instructions.addEventListener('click', function (event) { document.getElementById('ui').style = "border: #006400 3px solid; background: rgba(0,0,0,0.1); display: auto;" instructions.style.display = 'none'; // Ask the browser to lock the pointer element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; if (/Firefox/i.test(navigator.userAgent)) { var fullscreenchange = function (event) { if (document.fullscreenElement === element || document.mozFullscreenElement === element || document.mozFullScreenElement === element) { document.removeEventListener('fullscreenchange', fullscreenchange); document.removeEventListener('mozfullscreenchange', fullscreenchange); element.requestPointerLock(); } } document.addEventListener('fullscreenchange', fullscreenchange, false); document.addEventListener('mozfullscreenchange', fullscreenchange, false); element.requestFullscreen = element.requestFullscreen || element.mozRequestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen; element.requestFullscreen(); } else { element.requestPointerLock(); } }, false); } else { instructions.innerHTML = 'Your browser doesn\'t seem to support Pointer Lock API'; } renderRandomEmotion(); initCannon(); init(); animate(); function renderRandomEmotion() { const min = 0; const max = 5; emotionIndex = Math.floor(Math.random() * (max - min)) + min; document.getElementById("button-" + emotionIndex).style = "border : 3px solid black"; } function onchangeQuestionInput() { question = document.getElementById("question-input").value; } function fetchBotResponse(question) { document.getElementById('answer').innerText = "I'm thinking..."; axios.post('http://172.17.0.2:8080/cakechat_api/v1/actions/get_response', { "context" : [ question ], "emotion" : "joy" }) .then(function (response) { answer = response.data.response; document.getElementById('answer').innerHTML = answer; }) .catch(function (error) { console.log(error); }); } function initCannon() { // Setup our world world = new CANNON.World(); world.quatNormalizeSkip = 0; world.quatNormalizeFast = false; var solver = new CANNON.GSSolver(); world.defaultContactMaterial.contactEquationStiffness = 1e9; world.defaultContactMaterial.contactEquationRelaxation = 4; solver.iterations = 7; solver.tolerance = 0.1; var split = true; if (split) world.solver = new CANNON.SplitSolver(solver); else world.solver = solver; world.gravity.set(0, -20, 0); world.broadphase = new CANNON.NaiveBroadphase(); // Create a slippery material (friction coefficient = 0.0) physicsMaterial = new CANNON.Material("slipperyMaterial"); var physicsContactMaterial = new CANNON.ContactMaterial(physicsMaterial, physicsMaterial, 0.0, // friction coefficient 0.3 // restitution ); // We must add the contact materials to the world world.addContactMaterial(physicsContactMaterial); // Create a sphere var mass = 5, radius = 1.3; sphereShape = new CANNON.Sphere(radius); sphereBody = new CANNON.Body({mass: mass}); sphereBody.addShape(sphereShape); sphereBody.position.set(0, 5, 0); sphereBody.linearDamping = 0.9; world.add(sphereBody); // Create a plane var groundShape = new CANNON.Plane(); var groundBody = new CANNON.Body({mass: 0}); groundBody.addShape(groundShape); groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2); world.add(groundBody); } function init() { clock = new THREE.Clock(); camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 1000); scene = new THREE.Scene(); scene.fog = new THREE.Fog(0x000000, 0, 500); var ambient = new THREE.AmbientLight(0x111111); scene.add(ambient); // lights var light = new THREE.HemisphereLight(0xffffff, 0x444444); light.position.set(0, 20, 0); scene.add(light); light = new THREE.DirectionalLight(0xffffff); light.position.set(0, 20, 10); scene.add(light); controls = new PointerLockControls(camera, sphereBody); scene.add(controls.getObject()); // floor geometry = new THREE.PlaneGeometry(300, 300, 50, 50); geometry.applyMatrix(new THREE.Matrix4().makeRotationX(-Math.PI / 2)); material = new THREE.MeshLambertMaterial({color: 0xeeee00}); mesh = new THREE.Mesh(geometry, material); mesh.castShadow = true; mesh.receiveShadow = true; scene.add(mesh); renderer = new THREE.WebGLRenderer({antialias: true}); renderer.shadowMap.enabled = true; renderer.shadowMapSoft = true; renderer.setSize(window.innerWidth, window.innerHeight); renderer.setClearColor(scene.fog.color, 1); document.body.appendChild(renderer.domElement); window.addEventListener('resize', onWindowResize, false); // model var loader = new THREE.GLTFLoader(); var pos = [{x: 5, y: 0, z: -1}, {x: -3, y: 0, z: -2}, {x: 4, y: 0, z: -3}] for (let i = 0; i < 1; i++) { loader.load('./model/RobotExpressive.glb', function (gltf) { model = gltf.scene; model.position.set(pos[i].x, pos[i].y, pos[i].z) scene.add(model); animations = gltf.animations; mixer = new THREE.AnimationMixer( model ); let selectedAction = ""; switch (parseInt(emotionIndex)) { case 0: selectedAction = "Walking" break; case 1: selectedAction = "Punch" break; case 2: selectedAction = "Dance" break; case 3: selectedAction = "Idle" break; case 4: selectedAction = "Idle" break; } const actionIndex = actionList.findIndex(action => action === selectedAction); console.log(actionIndex); action = mixer.clipAction( animations[ actionIndex ] ); action.play(); animate(); }, undefined, function (e) { console.error(e); }); } } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } function animate() { // render loop var dt = clock.getDelta(); if ( mixer ) mixer.update( dt ); requestAnimationFrame(animate); if (controls.enabled) { world.step(dt); } controls.update(Date.now() - time); renderer.render(scene, camera); time = Date.now(); }
true
761e7271c36f2d46c7300241bd845bb483df0b1b
JavaScript
gktaj/practice_new
/practice jq/js_weird_parts-master/js_weird_parts/old/03/L25/app.js
UTF-8
113
3.390625
3
[ "MIT" ]
permissive
var a = 0; var b = false; if (a !== b) { console.log('They are not equal!'); } else { console.log("Equal."); }
true
8fbf03f637a920014bff5ed75ff3e8e79ee02ba2
JavaScript
NammCode/web-udemy-javascript
/5. oopJs/constructor.js
UTF-8
921
4.46875
4
[]
no_license
// Construction function Person(name, dob) { this.name = name; this.birthday = new Date(dob); this.calculateAge = function(){ const diff = Date.now() - this.birthday.getTime(); const ageDate = new Date(diff); return Math.abs(ageDate.getUTCFullYear() - 1970); } } const nam = new Person('Nam', '04-06-1997'); console.log(nam); console.log(nam.calculateAge()); // String const name1 = 'Jeff'; const name2 = new String('Jeff'); console.log(name2); // Number const num1 = 5; const num2 = new Number(5); // Function const getSum1 = function(x,y) { return x + y; } const getSum2 = new Function('x', 'y', 'return 1 + 1'); console.log(getSum2(1, 1)); // Object const john1 = {name: "John"}; const john2 = new Object({name: "John"}); // Array const arr1 = [1, 2, 3, 4]; const arr2 = new Array(1, 2, 3, 4); console.log(arr2); // Regular Expressions const res1 = /\w+/; const res2 = new RegExp('\\w+');
true
c9c72e4304977a3175e6da7c150d13f2705475f3
JavaScript
jleupp/NutriTracClient
/routes/users.js
UTF-8
5,918
2.796875
3
[]
no_license
var express = require('express'); var router = express.Router(); /* GET users listing. */ // router.get('/', function(req, res, next) { // res.send('respond with a resource'); // }); // -- USERS login redirect to JAVA API controller // var credentials = require('./credentials.js'); // var session = require('express-session'); // router.use(session({ // resave: false, // saveUninitialized: false, // secret: credentials.cookieSecret, // key: "user" // })); var cookieParser = require('cookie-parser'); // router.use(cookieParser(credentials.cookieSecret)); /****************************************************** User Login *******************************************************/ router.post('/login', function (request, response, next) { console.log(request.body); //request.session.user = "Session Test on server side"; // var email = request.body.email; // var password = response.body.password; // var xhr = new XMLHttpRequest(); // xhr.open('post', 'http://localhost:8080/NutriTrac/rest/ping'); // xhr.setRequestHeader('Content-Type', 'application/json'); // xhr.send(); // xhr.onreadystatechange = function() { // console.log('READY STATE : ' + xhr.readyState); // if (xhr.readyState ===4) { // console.log(xhr.responseText); // } // }; var xhr = new XMLHttpRequest(); console.log('ERROR AFTER var xhr'); xhr.open('post', 'http://localhost:8080/NutriTrac/rest/login'); console.log('ERROR AFTER xhr.open'); xhr.setRequestHeader('Content-Type', 'application/json'); console.log('ERROR AFTER setRequestHeader'); console.log(request.cookies); xhr.onreadystatechange = function () { console.log("ReadyStateChange : " + xhr.readyState); if (xhr.readyState === 4) { if (xhr.status === 200) { console.log("Response text print out" + xhr.responseText); request.session.user = xhr.responseText; //response.cookie('testCookie', {test : "test"}/*, {signed : true}*/); console.log("This is my response cookie: " + response.cookie('cookieUser', xhr.responseText)); console.log(request.session.user); response.send(xhr.responseText); } } }; console.log('SENDING'); xhr.send(JSON.stringify(request.body)); }); /****************************************************** User Logout *******************************************************/ router.post("/logout", function (request, response, next) { console.log("Inside my log out user function on server side"); console.log("Request body: " + request.body); console.log("Session user inside my log out user function on server side " + request.session.user); //var sessionUserName = request.session.user.firstname; // var sessionUserEmail = request.session.user.email; var sessionUserName = "Current User"; var sessionUserEmail = "User logged out"; console.log("Session info here: " + request.session.user); var returnObject = { firstname: sessionUserName, email: sessionUserEmail }; delete request.session.user; response.cookie('cookieUser', null) // console.log("This is my cookie in log out: " + request.signedCookies['testCookie']) console.log("This is my cookie in log out: " + request.signedCookies.testCookie) console.log(request.cookies.testCookie); console.log("Session user after delete" + request.session.user) console.log("My object to send back after log out" + returnObject.firstname + " " + returnObject.email) response.send(JSON.stringify(returnObject)); }); /****************************************************** User Check Login Status *******************************************************/ router.get("/checklogged", function (request, response, next) { if (request.session.user) { response.send(true); } else { response.send(false); } }); /****************************************************** RETURN LOGGED IN USER *******************************************************/ router.get("/returnuser", function (request, response, next) { console.log("IN RETURN USER"); console.log(request.session.user); if (request.session.user) { response.send(request.session.user); } else { response.send(false); } }); /****************************************************** User Create New User *******************************************************/ router.post('/createuser', function (request, response, next) { console.log(request.body); //request.session.user = "Session Test on server side"; var xhr = new XMLHttpRequest(); console.log('ERROR AFTER var xhr'); xhr.open('post', 'http://localhost:8080/NutriTrac/rest/createuser'); console.log('ERROR AFTER xhr.open'); xhr.setRequestHeader('Content-Type', 'application/json'); console.log('ERROR AFTER setRequestHeader'); console.log(request.cookies); xhr.onreadystatechange = function () { console.log("ReadyStateChange : " + xhr.readyState); if (xhr.readyState === 4) { if (xhr.status === 200) { console.log("Response text print out" + xhr.responseText); request.session.user = xhr.responseText; //response.cookie('testCookie', {test : "test"}/*, {signed : true}*/); console.log("This is my response cookie: " + response.cookie('cookieUser', xhr.responseText)) // console.log(credentials.cookieSecret); console.log(request.session.user); response.send(xhr.responseText); } } }; console.log('SENDING'); xhr.send(JSON.stringify(request.body)); }); module.exports = router;
true
83e17f102c4188a18f05bbf9b9f4fc7918d65d22
JavaScript
bshaley25/LetsMakeAGame
/MouseDodge/game.js
UTF-8
1,835
3.6875
4
[]
no_license
const canvas = document.createElement('canvas') document.body.appendChild(canvas) canvas.width = window.innerWidth - 500 canvas.height = window.innerHeight - 300 const ctx = canvas.getContext('2d') class Circle { constructor(x,y,r,dx,dy) { this.x = x this.y = y this.r = r this.dx = dx this.dy = dy } draw() { ctx.beginPath() ctx.arc(this.x, this.y, this.r, 0, 2*Math.PI) ctx.fillStyle = 'red' ctx.fill() ctx.stroke() } update() { this.x += this.dx this.y += this.dy console.log(this.x,this.y) if (this.y + this.r > canvas.height || this.y - this.r < 0) { this.dy *= -1 } if (this.x + this.r > canvas.width || this.x - this.r < 0 ) { this.dx *= -1 } if( Math.abs(this.x - mouse.x) < (this.r * .9) && Math.abs(this.y - mouse.y) < (this.r * .9)) { window.alert("You Lost!") } } } const mouse = { x: null, y: null } window.addEventListener('mousemove', event => { mouse.x = event.x mouse.y = event.y }) const numberOfCircles = 20 const circleArray = [] for ( let i = 0; i < numberOfCircles; i++ ) { const x = Math.random() * canvas.width const y = Math.random() * canvas.height const dx = ((Math.random() * 2) - 1) * 5 const dy = ((Math.random() * 2) - 1) * 5 circleArray.push(new Circle(x,y, 20, dx,dy)) } console.log(mouse) function animate() { ctx.clearRect(0,0, canvas.width, canvas.height) circleArray.forEach(circle => { circle.draw() circle.update() }) ctx.beginPath() ctx.arc(mouse.x, mouse.y, 15, 0, 2*Math.PI) ctx.fillStyle = 'black' ctx.fill() ctx.stroke() requestAnimationFrame(animate) } animate()
true
778c708849228ba3c5b08f7ff73807140fe381d2
JavaScript
mikoval/nodeProject
/Connect4Utility.js
UTF-8
14,077
2.953125
3
[]
no_license
module.exports = { complete: function(grid){ var width = grid.length; var height = grid[0].length; //check player 1 //vertical check for win for (var i=0;i<grid.length;i++) { var count = 0 for (var j=0;j<grid[0].length;j++) { if (grid[i][j]=="R") count++; else count=0; if (count>=4) return true; } } //horizontal check for win for (var i=0;i<grid[0].length;i++) { var count = 0 for (var j=0;j<grid.length;j++) { if (grid[j][i]=="R") count++; else count=0; if (count>=4) return true; } } // top-left to bottom-right : bottom left corner for( var rowStart = 0; rowStart < grid[0].length - 3; rowStart++){ var count = 0; var row; var col; for( row = rowStart, col = 0; row < grid[0].length && col < grid.length; row++, col++ ){ if(grid[col][row] == "R"){ count++; if(count >= 4) return true; } else { count = 0; } } } // top-left to bottom-right : top right corner for(var colStart = 1; colStart < grid.length - 3; colStart++){ count = 0; var row; var col; for( row = 0, col = colStart; row < grid[0].length && col < grid.length; row++, col++ ){ if(grid[col][row] == "R"){ count++; if(count >= 4) return true; } else { count = 0; } } } //bottom-left to top-right : bottom-right corner for( var colStart = 0; colStart < grid.length - 3; colStart++){ var count = 0; var row; var col; for( x = colStart, y = grid[0].length-1; x < grid.length && y >=0; x++, y-- ){ if(grid[x][y] == "R"){ count++; if(count >= 4) return true; } else { count = 0; } } } //bottom-left to top-right : top-left corner for( var rowStart = grid[0].length - 2; rowStart >= 0; rowStart--){ var count = 0; var row; var col; for( x = 0, y = rowStart; x < grid.length && y >= 0; x++, y-- ){ if(grid[x][y] == "R"){ count++; if(count >= 4) return true; } else { count = 0; } } } //////////////////////////////////////////////////// //check player 2 //vertical check for win for (var i=0;i<grid.length;i++) { var count = 0 for (var j=0;j<grid[0].length;j++) { if (grid[i][j]=="B") count++; else count=0; if (count>=4) return true; } } //horizontal check for win for (var i=0;i<grid[0].length;i++) { var count = 0 for (var j=0;j<grid.length;j++) { if (grid[j][i]=="B") count++; else count=0; if (count>=4) return true; } } // top-left to bottom-right : bottom left corner for( var rowStart = 0; rowStart < grid[0].length - 3; rowStart++){ var count = 0; var row; var col; for( row = rowStart, col = 0; row < grid[0].length && col < grid.length; row++, col++ ){ if(grid[col][row] == "B"){ count++; if(count >= 4) return true; } else { count = 0; } } } // top-left to bottom-right : top right corner for(var colStart = 1; colStart < grid.length - 3; colStart++){ count = 0; var row; var col; for( row = 0, col = colStart; row < grid[0].length && col < grid.length; row++, col++ ){ if(grid[col][row] == "B"){ count++; if(count >= 4) return true; } else { count = 0; } } } //bottom-left to top-right : bottom-right corner for( var colStart = 0; colStart < grid.length - 3; colStart++){ var count = 0; var row; var col; for( x = colStart, y = grid[0].length-1; x < grid.length && y >=0; x++, y-- ){ if(grid[x][y] == "B"){ count++; if(count >= 4) return true; } else { count = 0; } } } //bottom-left to top-right : top-left corner for( var rowStart = grid[0].length - 2; rowStart >= 0; rowStart--){ var count = 0; var row; var col; for( x = 0, y = rowStart; x < grid.length && y >=0; x++, y-- ){ if(grid[x][y] == "B"){ count++; if(count >= 4) return true; } else { count = 0; } } } //check if no moves left for(var i = 0; i < width; i++){ if(grid[i][0] == "_"){return false;} } return true; }, makeMove: function(game, move, currentTurn){ var color = getColor(currentTurn) for(var i = game[move].length-1; i >= 0; i-- ){ if(game[move][i] == "_") { game[move][i] = color; return true; } } return false; }, gameValue: function(grid){ //check player 1 //vertical check for win score = 0; for (var i=0;i<grid.length;i++) { var count = 0 for (var j=0;j<grid[0].length;j++) { if (grid[i][j]=="R") count++; else count=0; if(count==3 && (grid[i ][j + 1] || grid[i][j-3])== "_"){ score+=50; } if (count>=4) return 10000; } } //horizontal check for win for (var i=0;i<grid[0].length;i++) { var count = 0 for (var j=0;j<grid.length;j++) { if (grid[j][i]=="R") count++; else count=0; if(count==3 && (grid[j ][i + 1] || grid[j][i-3])){ score+=50;} if (count>=4) return 10000; } } // top-left to bottom-right : bottom left corner for( var rowStart = 0; rowStart < grid[0].length - 3; rowStart++){ var count = 0; var row; var col; for( row = rowStart, col = 0; row < grid[0].length && col < grid.length; row++, col++ ){ if(grid[col][row] == "R"){ count++; if(count==3){ score+=10;} if(count >= 4) return 10000; } else { count = 0; } } } // top-left to bottom-right : top right corner for(var colStart = 1; colStart < grid.length - 3; colStart++){ count = 0; var row; var col; for( row = 0, col = colStart; row < grid[0].length && col < grid.length; row++, col++ ){ if(grid[col][row] == "R"){ count++; if(count==3){ score+=10;} if(count >= 4) return 10000; } else { count = 0; } } } //bottom-left to top-right : bottom-right corner for( var colStart = 0; colStart < grid.length - 3; colStart++){ var count = 0; var row; var col; for( x = colStart, y = grid[0].length-1; x < grid.length && y >=0; x++, y-- ){ if(grid[x][y] == "R"){ count++; if(count==3){ score+=10;} if(count >= 4) return 10000; } else { count = 0; } } } //bottom-left to top-right : top-left corner for( var rowStart = grid[0].length - 2; rowStart >= 0; rowStart--){ var count = 0; var row; var col; for( x = 0, y = rowStart; x < grid.length && y >=0; x++, y-- ){ if(grid[x][y] == "R"){ count++; if(count==3){ score+=10;} if(count >= 4) return 10000; } else { count = 0; } } } //////////////////////////////////////////////////// //check player 2 //vertical check for win for (var i=0;i<grid.length;i++) { var count = 0 for (var j=0;j<grid[0].length;j++) { if (grid[i][j]=="B") count++; else count=0; if(count==3 && (grid[i ][j + 1] || grid[i][j-3])){ score-=50;} if (count>=4) return -10000; } } //horizontal check for win for (var i=0;i<grid[0].length;i++) { var count = 0 for (var j=0;j<grid.length;j++) { if (grid[j][i]=="B") count++; else count=0; if(count==3 && (grid[j ][i + 1] || grid[j][i-3])){ score-=50;} if (count>=4) return -10000; } } // top-left to bottom-right : bottom left corner for( var rowStart = 0; rowStart < grid[0].length - 3; rowStart++){ var count = 0; var row; var col; for( row = rowStart, col = 0; row < grid[0].length && col < grid.length; row++, col++ ){ if(grid[col][row] == "B"){ count++; if(count==3 ){ score-=10;} if(count >= 4) return -10000; } else { count = 0; } } } // top-left to bottom-right : top right corner for(var colStart = 1; colStart < grid.length - 3; colStart++){ count = 0; var row; var col; for( row = 0, col = colStart; row < grid[0].length && col < grid.length; row++, col++ ){ if(grid[col][row] == "B"){ count++; if(count==3){ score-=10;} if(count >= 4) return -10000; } else { count = 0; } } } //bottom-left to top-right : bottom-right corner for( var colStart = 0; colStart < grid.length - 3; colStart++){ var count = 0; var row; var col; for( x = colStart, y = grid[0].length-1; x < grid.length && y >=0; x++, y-- ){ if(grid[x][y] == "B"){ count++; if(count==3){ score-=10;} if(count >= 4) return -10000; } else { count = 0; } } } //bottom-left to top-right : top-left corner for( var rowStart = grid[0].length - 2; rowStart >= 0; rowStart--){ var count = 0; var row; var col; for( x = 0, y = rowStart; x < grid.length && y >=0; x++, y-- ){ if(grid[x][y] == "B"){ count++; if(count==3){ score-=10;} if(count >= 4) return -10000; } else { count = 0; } } } for (var i = 0; i < grid.length; i++){ for (var j = 0; j < grid[0].length; j++){ value = 4 - Math.abs((grid.length-1)/2.0 - i); value = value * 3 value = value + (4 - Math.abs((grid[0].length-1)/2.0 - j)); value = value / 5; if(grid[i][j] == "R"){score += value;} if(grid[i][j] == "B"){score -= value;} } } //check if no moves left for(var i = 0; i < width; i++){ if(grid[i][0] == "_"){return score;} } return 0; } }; function getColor(turn){ if(turn == "p1"){return "R";} else if (turn == "p2"){return "B"} else{return "_"} }
true
ab6993d98a1a642b7a4982d8911cc10eb29b569f
JavaScript
alanrahi/massageWebsite
/reserve.js
UTF-8
544
2.859375
3
[ "MIT" ]
permissive
$('button').click(function(){ $('.calendar').toggle(); }); /*$('button').click(function(){ alert("Calendar"); })*/ /*var inter; $(document).ready(function(){ inter = setInterval(function(){ $('.calendar').append('<img src="images/calendar"onclick="myFunction(this)">'); },1000); }); var counter = 0; function myFunction(img) { counter++; document.getElementById('countervalue').innerHTML = counter; img.onclick = null; img.remove(); if(counter === 20){ clearInterval(inter); } }*/
true
adaa53fa4127f828c03427d7b0ef03b9a397760d
JavaScript
LordDarkula/Kookipali
/scripts/Cookie2.js
UTF-8
1,781
3
3
[ "MIT" ]
permissive
function changefunc() { document.getElementById("5 star").selected = "true"; } function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function starwarslight() { var x=prompt("Good Job! You Joined the Light Side!Have you joined the light side on google","Type Yes or No"); x=x.toLowerCase(); if(x=="yes") { alert("You have completed Joining the Light Side good Job"); } else if(x=="no") { var sign=prompt("Do you want to sighn up now", "Type yes if you want to sign up now and anything else if you don't"); sign=sign.toLowerCase(); if(sign=="yes") { window.location="https://www.google.com/starwars/"; } else { } } else { alert("I see that you have not typed the write words, Looks like you need to meditate in the force"); } } function starwarsdark() { var x=prompt("You have made a grave Descion, and will be infamous for your power. Have you joined your side on google","Type Yes or No"); x=x.toLowerCase(); if(x=="yes") { alert("You have completed your journey to the Dark Side"); } else if(x=="no") { var sign=prompt("Do you want to sighn up now", "Type yes if you want to sign up now and anything else if you don't"); sign=sign.toLowerCase(); if(sign=="yes") { window.location="https://www.google.com/starwars/"; } } else { alert("I see that you have not typed the write words, Looks like you need more hate to stabilize"); } } function MahYes() { alert("You have followed the path of Cookipali. Remeber Don't swear"); } function MahNo() { alert("Good Job! You have done the right thing"); } window.onbeforeunload = function (e) { return 'You are about to Leave The Awesome Cookipali Hiring Website'; };
true
ded5cd03e7561327873c892573942c75c01a4ab8
JavaScript
LaurensGiesen/Make-a-Meal
/assets/js/infoMeals.js
UTF-8
2,038
2.6875
3
[]
no_license
"use strict"; function popUpDishes(e) { e.preventDefault(); if (e.target.tagName === "IMG") { let meals = JSON.parse(localStorage.getItem(`localMeals`)); if (e.target.tagName !== "A") { document.querySelector(`#popup`).classList.remove(`hidden`); } let selectedMealID = e.target.closest("article").getAttribute(`data-id`); if (e.target.tagName === "ARTICLE") { selectedMealID = e.target.getAttribute(`data-id`); } let meal = {}; for (let i = 0; i < meals.length; i++) { if (meals[i].id.toString() === selectedMealID) { meal = meals[i]; } } document.querySelector('#popup .contentwrapper').innerHTML = `<article data-id="${meal["id"]}"> <h3>${meal["title"]}</h3> <figure> <img src="images/${meal["img"]}" alt="${meal["title"]}" title="${meal["title"]}"> <figcaption> Meal by: <span>${meal["cook"]}</span> </figcaption> </figure> <div class="info"> <dl> <dt>calories:</dt> <dd>${meal["calories"]}</dd> <dt>servings:</dt> <dd>${meal["servings"]}</dd> <dt>days to book in advance:</dt> <dd>${meal["book"]}</dd> <dt>type:</dt> <dd>${meal["type"]}</dd> </dl> <p>€ <span>${meal["price"]}</span>/pp</p> <a href="#" class="order">Order</a> </div> </article>`; initPopUpOrderButton(); } } function closePopUpDishes(e) { e.preventDefault(); document.querySelector(`#popup`).classList.add(`hidden`); }
true
ec3c728c16db35188f364ce8990ff70f09fac072
JavaScript
54x1/USN
/backend/routes/auth.js
UTF-8
5,866
2.546875
3
[]
no_license
const router = require('express').Router() const User = require('../models/User') const bcrypt = require('bcrypt') const jwt = require('jsonwebtoken') const verify = require('./verify') router.post('/register', async (req, res) => { try { if ( !req.body.username || !req.body.email || !req.body.password || req.body.password.length < 6 ) { console.log({ errors: 'All fields are required or password length is less then 6', }) return res.status(422).json({ error: 'All fields are required or password length is less then 6', }) } else { // find email or username const user = await User.findOne({ $or: [ { email: req.body.email, }, { username: req.body.username, }, ], }) if (user) { // backend error stuff let errors = {} if (user.username === req.body.username) { errors.username = 'Username already exists' } if (user.email === req.body.email) { errors.email = 'Email already exists' } console.log({ errors: errors }) return res.status(500).json(errors) } else { // fetch user from body const newUser = new User({ username: req.body.username, email: req.body.email, password: req.body.password, }) // hash password bcrypt.genSalt(10, (err, salt) => { bcrypt.hash(newUser.password, salt, (err, hash) => { if (err) throw err newUser.password = hash // save newU user newUser .save() .then((user) => res.status(200).json(user)) .catch((err) => console.log(err)) }) }) } } } catch (err) { res.status(500).json(err) } }) let refreshTokens = [] router.post('/login', (req, res) => { try { // check if username or email if (req.body.username.indexOf('@') > -1) { console.log('@here') // email login stuff User.findOne({ email: req.body.username }).then((validUser) => { if (!validUser) { console.log('Invalid Credentials') res.status(500).json('Invalid Credentials') } else { try { bcrypt .compare(req.body.password, validUser.password) .then((validPassword) => { if (validPassword) { console.log('workingemail') const { password, ...user } = validUser._doc // token stuff const accessToken = jwt.sign( { id: validUser.id, isAdmin: validUser.isAdmin }, 'mySecretKey', { expiresIn: '1d' } ) const refreshToken = jwt.sign( { id: validUser.id, isAdmin: validUser.isAdmin }, 'myRefreshSecretKey' ) refreshTokens.push(refreshToken) res.status(200).json({ user, accessToken, refreshToken }) } else { console.log('Invalid Credentials') res.status(500).json('Invalid Credentials') } }) } catch (err) { res.status(500).json(err) } } }) } else { // username login stuff console.log('no@') User.findOne({ username: req.body.username }).then((validUser) => { if (!validUser) { console.log('Invalid Credentials') res.status(500).json('Invalid Credentials') } else { try { bcrypt .compare(req.body.password, validUser.password) .then((validPassword) => { if (validPassword) { console.log('workingusername') const { password, ...user } = validUser._doc // access token const accessToken = jwt.sign( { id: validUser.id, isAdmin: validUser.isAdmin }, 'mySecretKey', { expiresIn: '1d' } ) const refreshToken = jwt.sign( { id: validUser.id, isAdmin: validUser.isAdmin }, 'myRefreshSecretKey' ) refreshTokens.push(refreshToken) res.status(200).json({ user, accessToken, refreshToken }) } else { console.log('Invalid Credentials') res.status(500).json('Invalid Credentials') } }) } catch (err) { res.status(500).json(err) } } }) } } catch (err) { res.status(500).json(err) } }) router.post('/refresh', verify, (req, res) => { const refreshToken = req.body.token if (!refreshToken) { return res.status(401).json('Not authenticated!') } if (!refreshTokens.includes(refreshToken)) { return res.status(403).json('Not valid token!') } jwt.verify(refreshToken, 'myRefreshSecretKey', (err, user) => { console.log(err) refreshTokens = refreshTokens.filter((token) => token !== refreshToken) const newAccessToken = jwt.sign( { id: user.id, isAdmin: user.isAdmin }, 'mySecretKey', { expiresIn: '1d' } ) const newRefreshToken = jwt.sign( { id: user.id, isAdmin: user.isAdmin }, 'myRefreshSecretKey', { expiresIn: '1d' } ) refreshTokens.push(newRefreshToken) res.status(200).json({ accessToken: newAccessToken, refreshToken: newRefreshToken, }) }) }) router.post('/logout', verify, (req, res) => { res.status(200).json('Logged Out Success!') }) module.exports = router
true
6de52d64b6a13ee883696bf7162d4d8dcfddaeb5
JavaScript
IgorSh12/VR
/VR/form.js
UTF-8
1,084
2.84375
3
[]
no_license
let inputs = document.querySelectorAll('.input'); inputs[5].addEventListener('click', (e) =>{ e.preventDefault(); document.querySelector('.fail').style.color = 'red' console.log(inputs[4].value ) if(inputs[0].value == ''){ document.querySelector('.fail').innerHTML = 'Вы забыли ввести имя' } else{ if(inputs[1].value == '' || inputs[2].value == ''){ document.querySelector('.fail').innerHTML = 'Ваш пол неизвестен' }else{ if(inputs[3].value == ''){ document.querySelector('.fail').innerHTML = 'Вы не указали возраст' }else{ if(inputs[4].checked == false){ document.querySelector('.fail').innerHTML = 'Будьте добры согласиться' }else{ if(inputs[0].value == 'Рубль'){ document.querySelector('.fail').innerHTML = 'Вы упали' } } } } } })
true
2267b9f32e5a5bf666d9a5a61a3cafb805ae2a22
JavaScript
michalWSEI/wsei-javascript-zadania
/1_Zadania/obowiązkowe/8_DOM_Wyszukiwanie_elementow/js/app.js
UTF-8
1,474
3.21875
3
[]
no_license
document.addEventListener("DOMContentLoaded", function () { /* Poniżej napisz kod rozwiązujący zadania. Odpowiedzi oddzielaj komentarzami. exc 0 */ let titleElement = document.querySelector('.title'); let dataAnimation = getDataAnimation(titleElement); // exc 1 let homeElementQuerySelector = document.querySelector('#home'); let homeElementGetElementById = document.getElementById('home'); let liElement = document.querySelector('li[data-direction]'); let blockElement = document.querySelector('.block'); console.log(`exc1`, homeElementQuerySelector, homeElementGetElementById, liElement, blockElement); // exc 2 let navTagLiElement = document.querySelectorAll('nav > ul > li'); let divTagParagraphElement = document.querySelectorAll('div > p'); let artTagDivElement = document.querySelectorAll('article > div'); console.log(`exc2`, navTagLiElement, divTagParagraphElement, artTagDivElement); // exc 3 // podpunkt 2 wypisuje elementy h2, // h1 nie są obecne w strzukturze DOM dostepnego dokumentu html let artTagClassNameFirst = document.querySelector('article[class=first]'); let countH2 = 0; Array .from(artTagClassNameFirst.children[0].children) .forEach(divElement => Array .from(divElement.children) .forEach(child => (child.tagName === 'H2') && countH2++)); console.log(`exc3`, countH2); }); function getDataAnimation(element) { return element.attributes['data-animation'].value; }
true
f2ba13c02ce2a61e5f660b7bef254a6f56625469
JavaScript
laura-gomez-c/flutter_test_app
/assets/microapp4/scripts.js
UTF-8
163
2.65625
3
[]
no_license
function showContent() { var temp = document.getElementsByTagName("template")[0]; var clon = temp.content.cloneNode(true); document.body.appendChild(clon); }
true