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
0565b1eabf7071f3a9c0bbaacc79b14103e4fe43
JavaScript
dailc/leetcode
/algorithms/301-Remove-Invalid-Parentheses/Remove-Invalid-Parentheses.js
UTF-8
1,957
3.1875
3
[ "MIT" ]
permissive
/* 作者: dailc * 时间: 2017-07-31 * 描述: Remove-Invalid-Parentheses * * 来自: https://leetcode.com/problems/remove-invalid-parentheses */ (function(exports) { /** * @param {string} s * @return {string[]} */ var removeInvalidParentheses = function(s) { if (!s) { return [""]; } var res = [], visited = [], queue = [], len = s.length, found = false; queue.push(s); visited[s] = 1; while(queue.length) { var tmp = queue.pop(); if (isValid(tmp)) { res.push(tmp); found = true; } if (found) { // found确保只会去除一次最小的情况 continue; } len = tmp.length; for (var i = 0; i < len; i++) { var ch = tmp.charAt(i); if (ch != '(' && ch != ')') { continue; } var next = tmp.substr(0, i) + tmp.substr(i + 1); if (!visited[next]) { queue.unshift(next); visited[next] = 1; } } } return res; }; function isValid(str) { if (!str) { return true; } var count = 0, len = str.length; for (var i = 0; i < len; i++) { var tmp = str.charAt(i); if (tmp == '(') { count ++; } else if (tmp == ')' && count-- == 0) { return false; } } return count == 0; } exports.removeInvalidParentheses = removeInvalidParentheses; })(window.LeetCode = window.LeetCode || {});
true
e554d31504d7b07dc89c283a57f5c13567898acb
JavaScript
puhakkaJ/fullstackopen2021
/part5/bloglist-backend/utils/list_helper.js
UTF-8
2,041
3.015625
3
[]
no_license
const blog = require("../models/blog") const _ = require('lodash') const dummy = (blogs) => { return 1 } const totalLikes = (blogs) => { const reducer = (sum, item) => { return sum + item } return blogs.map(blog => blog.likes).reduce(reducer, 0) } const favoriteBlog = (blogs) => { if (blogs.length === 0) { return {} } var sorted = blogs.sort((a,b) => a.likes-b.likes) return sorted[sorted.length -1] } const mostBlogs = (blogs) => { if (blogs.length === 0) { return {} } var sorted = blogs.reduce((acc, value) => { // Group initialization if (!acc[value.author]) { acc[value.author] = []; } // Grouping acc[value.author].push(value); //console.log(acc) return acc; }, {}) var sorted2 = Object.fromEntries( Object.entries(sorted).sort(([,a],[,b]) => a.length-b.length)) //console.log(Object.keys(sorted2)[Object.keys(sorted2).length -1]) //console.log(Object.entries(sorted2)[Object.entries(sorted2).length -1][1].length) return { author: Object.keys(sorted2)[Object.keys(sorted2).length -1], blogs: Object.entries(sorted2)[Object.entries(sorted2).length -1][1].length } } const mostLikes = (blogs) => { if (blogs.length === 0) { return {} } var sorted = blogs.reduce((acc, value) => { // Group initialization if (!acc[value.author]) { acc[value.author] = []; } // Grouping acc[value.author].push(value); //console.log(acc) return acc; }, {}) var sorted2 = Object.fromEntries( Object.entries(sorted).sort(([,a],[,b]) => totalLikes(a)-totalLikes(b))) //console.log(Object.keys(sorted2)[Object.keys(sorted2).length -1]) //console.log(totalLikes(Object.entries(sorted2)[Object.entries(sorted2).length -1][1])) return { author: Object.keys(sorted2)[Object.keys(sorted2).length -1], likes: totalLikes(Object.entries(sorted2)[Object.entries(sorted2).length -1][1]) } } module.exports = { dummy, totalLikes, favoriteBlog, mostBlogs, mostLikes }
true
b67002fcf72525ed4858104d8427c03a23efa6f6
JavaScript
xthecoolboy/Amaterasu
/commands/Music/search.js
UTF-8
2,954
2.6875
3
[ "MIT" ]
permissive
const Command = require("../../util/Command.js"); const handleVideo = require("../../util/MusicHandling.js"); const { RichEmbed, Util } = require("discord.js"); const he = require("he"); const ytapi = require("simple-youtube-api"); const youtube = new ytapi(process.env.GOOGLE_API_KEY); const idx = ["0️⃣", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣"]; class Search extends Command { constructor (client) { super(client, { name: "search", description: "Searches for up to 10 videos from YouTube.", category: "Music", usage: "search <song>", guildOnly: true, aliases: ["none"] }); } async run (message, args, level) { try { if (message.settings.djonly && !message.member.roles.some(c => c.name.toLowerCase() === message.settings.djrole.toLowerCase())) return this.client.embed("notDJ", message); const voiceChannel = message.member.voiceChannel; if (!voiceChannel) return this.client.embed("noVoiceChannel", message); const permissions = voiceChannel.permissionsFor(message.client.user); if (!args[0]) return this.client.embed("noArgs", message); if (!permissions.has("CONNECT")) return this.client.embed("noPerms-CONNECT", message); if (!permissions.has("SPEAK")) return this.client.embed("noPerms-SPEAK", message); let video; try { const videos = await youtube.searchVideos(args.join(" "), 10); if (!videos.length) return this.client.embed("noSongsFound", message, args); let index = 0; const embed = new RichEmbed() .setAuthor("🔍 Song Selection") .setDescription(`${videos.map(video2 => `**${idx[index++]} -** ${he.decode(video2.title)}`).join("\n")}`) .setFooter("Please provide a value to select one of the search results ranging from 0️⃣-9️⃣.") .setColor(0x00FFFF); message.channel.send(embed); const response = await message.channel.awaitMessages(msg2 => (msg2.content > -1 && msg2.content < 10) && msg2.author.id === message.author.id, { max: 1, time: 10000, errors: ["time"]}); if (!response) return this.client.embed("invalidEntry", message); const videoIndex = parseInt(response.first().content); video = await youtube.getVideoByID(videos[videoIndex].id); } catch (err) { console.log(err); return this.client.embed("noSearchResults", message); } return handleVideo(video, message, voiceChannel); } catch(err) { this.client.logger.error(err.stack); return this.client.embed("", message); } } } module.exports = Search;
true
3beeb6d4c5c18c4c8a5bed17588dc425276a964f
JavaScript
dstuessy/louis-js
/src/louis.js
UTF-8
3,436
2.8125
3
[ "MIT" ]
permissive
/*jslint fudge, white: true */ (function () { 'use strict'; var requestAnimationFrame = window.requestAnimationFrame; if (requestAnimationFrame === undefined || requestAnimationFrame === null) { requestAnimationFrame = function(fn) { return setTimeout(fn, 0); }; } function partial(fn, args) { return function partiallyApplied() { var moreArgs = Array.prototype.slice.call(/*ignoreme*/arguments, /*ignoreme*/0); return fn.apply(null, args.concat(moreArgs)); }; } // dummy function to do 'no operation' function noop() { return undefined; } function now() { return Date.now(); } function timePerTick(fps) { return 1000 / fps; } function delta(currentTime, previousTickTime) { return currentTime - previousTickTime; } function Terminate(state) { return { state: state, terminated: true }; } function Continue(state) { return { state: state, terminated: false }; } function Accumulator(tickFn, fps, startTime) { var accumulatedTime = 0; var previousTime = startTime; return function accumulate(currentTime, tickResult) { accumulatedTime += delta(currentTime, previousTime); while (accumulatedTime > timePerTick(fps) && !tickResult.terminated) { tickResult = tickFn(tickResult.state); accumulatedTime -= timePerTick(fps); } accumulatedTime = 0; previousTime = now(); return tickResult; }; } function tick(previousResult, previousTickTime, fps, accumulator, draw, onEnd) { var tickResult = accumulator(now(), previousResult), deltaTime = delta(now(), previousTickTime), isItNextTick = deltaTime >= timePerTick(fps); if (isItNextTick || tickResult.terminated) { draw(tickResult.state); previousTickTime = now(); } if (tickResult.terminated) { onEnd(tickResult.state); } else { requestAnimationFrame(partial(tick, [tickResult, previousTickTime, fps, accumulator, draw, onEnd])); } } /** * The Accumulator receives 60 fps * as a hard-coded value * as this is the desired framerate * for logic updates. This should * always be independent to the * graphics updates, in order * to ensure no frames are dropped * as a result of coupled logic * and graphics updates. */ function animate(fps, onStart, onTick, draw, onEnd, startResult) { var previousTickTime = now(); onStart(startResult); tick(Continue(startResult), previousTickTime, fps, Accumulator(onTick, 60, now()), draw, onEnd); } window.Animation = function (options) { var animation = Object.create(null); animation.animate = partial(animate, [ options.fps, options.onStart || noop, options.onTick || noop, options.draw || noop, options.onEnd || noop ]); return Object.freeze(animation); }; window.Animation.Terminate = Terminate; window.Animation.Continue = Continue; window.Animation = Object.freeze(window.Animation); }());
true
071de96cc906e06cb4a67cf0fd34ad3b6dafd64a
JavaScript
amigo92/Resourcer
/public/app/controllers/customerCtrl.js
UTF-8
2,731
2.609375
3
[]
no_license
angular.module('customerCtrl', ['customerService']) .controller('customerController', function(Customer) { var vm = this; // set a processing variable to show loading things vm.processing = true; // grab all the customers at page load Customer.all() .success(function(data) { // when all the customers come back, remove the processing variable vm.processing = false; // bind the customers that come back to vm.customers vm.customers = data; }); // function to delete a customer vm.deleteCustomer = function(id) { vm.processing = true; Customer.delete(id) .success(function(data) { // get all customers to update the table // you can also set up your api // to return the list of customers with the delete call Customer.all() .success(function(data) { vm.processing = false; vm.customers = data; }); }); }; }) // controller applied to customer creation page .controller('customerCreateController', function(Customer) { var vm = this; // variable to hide/show elements of the view // differentiates between create or edit pages vm.type = 'create'; vm.dataRole = { multipleSelect: [], option1: 'Marketing', option2: 'Sales', option3: 'Admin', }; //console.log(main.customer); // vm.customerData.role=vm.dataRole.singleselect; // function to create a customer vm.saveCustomer = function() { vm.processing = true; vm.message = ''; console.log(vm.customerData); // use the create function in the customerService Customer.create(vm.customerData) .success(function(data) { vm.processing = false; vm.customerData = {}; vm.message = data.message; }); }; }) // controller applied to customer edit page .controller('customerEditController', function($routeParams, Customer) { var vm = this; // variable to hide/show elements of the view // differentiates between create or edit pages vm.type = 'edit'; // get the customer data for the customer you want to edit // $routeParams is the way we grab data from the URL Customer.get($routeParams.customer_id) .success(function(data) { vm.customerData = data; }); // function to save the customer vm.saveCustomer = function() { vm.processing = true; vm.message = ''; vm.dataRole = { multipleSelect: [], option1: 'Marketing', option2: 'Sales', option3: 'Admin', }; // call the customerService function to update Customer.update($routeParams.customer_id, vm.customerData) .success(function(data) { vm.processing = false; // clear the form vm.customerData = {}; // bind the message from our API to vm.message vm.message = data.message; }); }; });
true
d1d93517dd72594c099c6aabea1955a330094eea
JavaScript
jingjing721/ddc-wx
/utils/util.js
UTF-8
1,505
2.546875
3
[]
no_license
/* * Description: 对象转可拼接参数。 url: 跳转的URL;params: 对象形式的参数 * Types:url -> String; params -> Object * Author: yanlichen <[email protected]> * Date: 2019/1/8 */ export function navigateTo(url, params) { url += (url.indexOf("?") != -1) ? "" : "?"; for(var i in params) { url += ((url.indexOf("=") != -1) ? "&" : "") + i + "=" + params[i]; } wx.navigateTo({ url }) } /* * Description: showToast提醒。 title: 提醒的文字;timer: 可选设置时间 * Types:title -> String; timer -> number * Author: yanlichen <[email protected]> * Date: 2019/1/8 */ export function showToast(title, timer) { wx.showToast({ title: title || '请添加提示', icon: 'none', duration: timer || 2000 }) } /* * Description: 深度拷贝。data: 拷贝的对象 * Types:data -> Object * Author: yanlichen <[email protected]> * Date: 2019/1/8 */ export function deepCopy(data) { if (typeof data === 'object') { return JSON.parse(JSON.stringify(data)) } } /* * Description: 设置缓存 key: 设置key值; data: 设置value值 * Types: key -> String, data -> String || Object * Author: yanlichen <[email protected]> * Date: 2019/1/10 */ export function setCache(key, data) { wx.setStorageSync(key, data); } /* * Description: 读取缓存 key: 读取key值 * Types:key -> String * Author: yanlichen <[email protected]> * Date: 2019/1/10 */ export function getCache(key) { return wx.getStorageSync(key) } export default { navigateTo, showToast, deepCopy, setCache, getCache }
true
e95cc59d9b03973d0ac99c89f88f5900e1299a81
JavaScript
imparthgalani/AP_MART
/AP_MART/build/web/js/image.js
UTF-8
519
2.59375
3
[ "MIT" ]
permissive
function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#showimg').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); // convert to base64 string } } $("#addimg").change(function () { readURL(this); }); $("form").on("change", ".file-upload-field", function () { $(this).parent(".file-upload-wrapper").attr("data-text", $(this).val().replace(/.*(\/|\\)/, '')); })
true
6cf9750a44fe8184b6f303b97c7bcfe73cea63c9
JavaScript
awdsza/algorithm
/leetcode/easy/1678_Goal_Parser_Interpretation/awdsza.js
UTF-8
1,127
4.125
4
[]
no_license
/** * @param {string} command * @return {string} */ /*정규식을 이용해 푸는방법*/ /* Runtime: 72 ms, faster than 92.54% of JavaScript online submissions for Goal Parser Interpretation. Memory Usage: 39.1 MB, less than 5.48% of JavaScript online submissions for Goal Parser Interpretation. */ var interpret = function(command) { return command.replace(/\(\)/g,'o').replace(/\(al\)/g,'al'); }; /*배열을 하나하나 읽어서 변환하는 방법*/ /*Runtime: 76 ms, faster than 81.02% of JavaScript online submissions for Goal Parser Interpretation. Memory Usage: 38.9 MB, less than 9.73% of JavaScript online submissions for Goal Parser Interpretation.*/ // var interpret = function(command) { // let result=""; // for(let i=0;i<command.length;i++){ // let char = command[i]; // if(char==='G'){ // result += 'G' // }else if(char === '('){ // if(command[i+1] === ')'){ // result += 'o'; // }else if(command[i+1] === 'a'){ // result += 'al'; // } // } // }; // return result; // };
true
e5518b20256840bb6cd9dacc736d7eb12b92f8fa
JavaScript
sergio8999/DWEC
/Unidad 1/Ejercicio 5/1_1.js
UTF-8
288
3.15625
3
[]
no_license
// var name = prompt("Tell me your name: "); var nombre = prompt("Introduce nombre: "); var apellidos = prompt("Introduce apellidos: "); var edad = prompt("Introduce edad: "); document.write("<p>"+nombre+"</p>"); document.write("<p>"+apellidos+"</p>"); document.write("<p>"+edad+"</p>");
true
b01e493eb74e9ce0a35c9960e1fbbd23e5c7855e
JavaScript
programmistik/MyInstagramOnContainers
/MyIdentityService/wwwroot/js/site.js
UTF-8
5,637
2.640625
3
[]
no_license
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification // for details on configuring this project to bundle and minify static web assets. // Write your JavaScript code. $(document).ready(function () { $(window).scroll(function () { if ($(this).scrollTop() > 50) { $('#back-to-top').fadeIn(); } else { $('#back-to-top').fadeOut(); } }); // scroll body to 0px on click $('#back-to-top').click(function () { $('#back-to-top').tooltip('hide'); $('body,html').animate({ scrollTop: 0 }, 800); return false; }); //$('#back-to-top').tooltip('show'); }); function jsAddLike(id) { $.ajax({ url: '/Post/jsAddLike', type: 'POST', data: { id: id }, success: function (data) { //let btn = $('#like'); //if (btn.hasClass('btn-danger')) { // btn.removeClass('btn-danger').addClass('btn-success'); //} //else { // btn.removeClass('btn-success').addClass('btn-danger'); //} } }); } function jsDelPost(id) { if (confirm("Are you sure you want to delete this post?")) { $.ajax({ url: '/Post/jsDelPost', type: 'DELETE', data: { id: id }, success: function (data) { //location.reload(true); document.getElementById(id).remove(); //$.ajax({ // url: '/Profile/UserProfile', // data: { id: 2 }, // success: function (data) { // } //}); } }); } } function jsAddFriend(id) { $.ajax({ url: '/Profile/jsAddFriend', type: 'POST', data: { id: id }, success: function (data) { let btn = $('#friend'); if (btn.hasClass('btn-danger')) { btn.removeClass('btn-danger').addClass('btn-success'); btn.html("Add to friends"); } else { btn.removeClass('btn-success').addClass('btn-danger'); btn.html("Delete from friends"); } } }); } function readURL(input) { if (input.files && input.files[0]) { var image = input.files[0]; // FileList object if (window.File && window.FileReader && window.FileList && window.Blob) { var reader = new FileReader(); // Closure to capture the file information. reader.addEventListener("load", function (e) { const imageData = e.target.result; window.loadImage(imageData, function (img) { if (img.type === "error") { console.log("couldn't load image:", img); } else { window.EXIF.getData(img, function () { console.log("done!"); var orientation = window.EXIF.getTag(this, "Orientation"); var canvas = window.loadImage.scale(img, { orientation: orientation || 0, canvas: true }); document.getElementById("container2").appendChild(canvas); canvas.style.marginLeft = "10px"; if (orientation == 1) canvas.style.width = "500px"; else canvas.style.height = "500px"; }); } }); }); reader.readAsDataURL(image); } else { console.log('The File APIs are not fully supported in this browser.'); } } } $("#inputGroupFile01").change(function () { $('canvas:nth-of-type(1)').remove(); readURL(this); //getDataUrl(this); }); // we need to save the total rotation angle as a global variable var current_rotation = 0; // change CSS transform property on click document.querySelector("#rotate-button").addEventListener('click', function () { // update total rotation // if angle is positive, rotation happens clockwise. if negative, rotation happens anti-clockwise. current_rotation += 90; // rotate clockwise by 90 degrees document.querySelector("#container2").style.transform = 'rotate(' + current_rotation + 'deg)'; }); function jsShowNews(model) { console.log(model); } //---------------------- let tree = { label: 'root', nodes: [ { label: 'item1', nodes: [ { label: 'item1.1' }, { label: 'item1.2', nodes: [ { label: 'item1.2.1' } ] } ] }, { label: 'item2' } ] } Vue.component('tree-menu', { props: ['label', 'nodes', 'depth'], name: 'tree-menu', computed: { indent() { return { transform: `translate(${this.depth * 50}px)` } } }, template: ` <div class="tree-menu"> <div :style="indent">{{ label }}</div> <tree-menu v-for="node in nodes" :nodes="node.nodes" :label="node.label" :depth="depth + 1" > </tree-menu> </div> ` }); new Vue({ el: "#app", data: { tree } });
true
36e59143241ca05333ed5a9f279411dcffe2b475
JavaScript
Dung288-806/BuggerApp
/src/store/Reducer/ReducerBuilder.js
UTF-8
1,356
2.859375
3
[]
no_license
import * as ActionType from "../Actions/ActionType"; const INGREDIENT_PRICE = { meat: 0.5, bacon: 1, salad: 0.5, cheese: 1, }; const initialState = { ingredients: {}, totalPrice: 4, }; const reducer = (state = initialState, action) => { switch (action.type) { case ActionType.ADD: { const newIngredient = { ...state.ingredients }; const newCount = state.ingredients[action.typeIng] + 1; newIngredient[action.typeIng] = newCount; const priceOfType = INGREDIENT_PRICE[action.typeIng]; const newTotalPrice = state.totalPrice + priceOfType; return { ...state, ingredients: newIngredient, totalPrice: newTotalPrice, }; } case ActionType.REMOVE: { const updateIngredient = { ...state.ingredients }; const countNew = state.ingredients[action.typeIng] - 1; updateIngredient[action.typeIng] = countNew; const priceOfType = INGREDIENT_PRICE[action.typeIng]; const newTotalPrice = state.totalPrice - priceOfType; return { ...state, ingredients: updateIngredient, totalPrice: newTotalPrice, }; } case ActionType.INITIAL: { return { ...state, ingredients: action.ingredients, totalPrice: 4 }; } default: return state; } }; export default reducer;
true
c3774eca3f24f530b702b7104566030ed2080002
JavaScript
bbukaty/VG-relations
/explorer.js
UTF-8
5,025
3.109375
3
[ "MIT" ]
permissive
// Load data into window subjects = null; d3.json("data/subjects_all.json", function(error, json) { if (error != null) { console.log(error); document.getElementById('loadGif').remove(); document.getElementById('loadError').style.visibility = 'visible'; return; } subjects = json; document.getElementById('loadDiv').remove(); document.getElementById('subjInput').style.visibility = 'visible'; // example chart createSankey('kiwi'); }); /* Get input from the subject form and prevent default form behavior */ function captureForm() { createSankey(document.getElementById('subject').value); return false; } /* Accepts a dict of dicts of dicts, etc... of numbers. Returns the sum of all the 'leaf node' numbers in this data structure. */ function sumBranches(obj) { var total = 0; if (typeof obj == 'number') { return obj; } else { total = 0 for (var key in obj) { total += sumBranches(obj[key]); } return total; } } /* Given a subject name and an optional relation name, generates data for a Sankey visualization and displays it in the page. */ function createSankey(subjName, relName=null) { if (!(subjName in subjects)) { document.getElementById('loadError').style.visibility='visible'; return; } // reset the error message on successful submission document.getElementById('subjError').style.visibility='hidden'; if (relName == null) { sankeyData = genSubjData(subjName, subjects[subjName]); } else { sankeyData = genSubjRelData(subjName, relName, subjects[subjName]); } displaySankey(sankeyData); } /* Takes in a subject name and its corresponding dict of relations. Generates lists of nodes and links for a Sankey diagram. */ function genSubjData(subjName, subj) { var nodes = [{ name: subjName, type: 'subj' }]; var links = []; // keep track of indices of objects and relations so we can link things var relIndices = {}; var objIndices = {}; currIndex = 1; topRels = Object.keys(subj).sort(function(a,b){ return sumBranches(subj[b])-sumBranches(subj[a]); }).slice(0,30); topRels.forEach(function (relName) { relIndices[relName] = currIndex; currIndex++; nodes.push({ name: relName, type: 'rel' }); links.push({ source: 0, target: relIndices[relName], value: sumBranches(subj[relName]) }); topObjs = Object.keys(subj[relName]).sort(function(a,b){ return subj[relName][b] - subj[relName][a]; }).slice(0,4); topObjs.forEach(function (objName) { if (!(objName in objIndices)) { objIndices[objName] = currIndex; nodes.push({ name: objName, type: 'obj' }); currIndex++; } links.push({ source: relIndices[relName], target: objIndices[objName], value: subj[relName][objName] }); }); }) return { nodes: nodes, links: links }; } /* Takes in a subject name, a relation name, and its corresponding dict of relations. Generates lists of nodes and links for a Sankey diagram (focused on the relation). */ function genSubjRelData(subjName, relName, subj) { var nodes = [{ name: subjName, type: 'subj' }, { name: relName, type: 'rel' }]; var links = [{ source: 0, target: 1, value: sumBranches(subj[relName]) }]; topObjs = Object.keys(subj[relName]).sort(function(a,b){ return subj[relName][b] - subj[relName][a]; }).slice(0, 30); topObjs.forEach(function (objName) { nodes.push({ name: objName, type: 'obj' }); links.push({ source: 1, target: nodes.length-1, value: subj[relName][objName] }); }); return { nodes: nodes, links: links } } /* Draws the diagram and initializes click handlers and tooltips. */ function displaySankey(sankeyData) { d3.select("svg").remove(); // clear existing chart var chart = d3.select("#chart").append("svg").chart("Sankey.Path"); chart .colorLinks('#a0a0a0') .nodeWidth(20) .spread(true) .on('node:click', function(node) { if (node.type == 'rel') { createSankey(sankeyData.nodes[0].name, node.name); } else { createSankey(node.name); } }) .on('link:click', function(link) { if (link.source.type == 'subj') { createSankey(link.source.name, link.target.name); } else { createSankey(link.target.name); } }) .draw(sankeyData); // add tooltips to links d3.select("svg").selectAll(".link").append("title").text(function(link) { return link.source.name + " → " + link.target.name + "\n" + link.value + " occurrences" }); }
true
876c91dc38740a6d2dd1a15c5c1993df4149dd49
JavaScript
yejing2514/ewj-
/emj/js/jquery.cookie.js
UTF-8
924
3.328125
3
[]
no_license
var cookieMy = new Object(); //遍历数组方法 cookieMy.arrsearch = function(value, arr) { for(var i = 0; i < arr.length; i++) { if(value == arr[i]) { return true; } } return false; } //添加cookie cookieMy.addCookie = function(key, value, day) { var date = new Date(); date.setDate(date.getDate() + day); document.cookie = key + '=' + encodeURI(value) + ';expires=' + date; } //获取cookie cookieMy.getCookie = function(key) { var str = decodeURI(document.cookie); var arr = str.split('; '); for(var i = 0; i < arr.length; i++) { var arr1 = arr[i].split('='); if(key == arr1[0]) { return arr1[1]; } } } //删除cookie cookieMy.delCookie = function(key, value) { addCookie(key, value, -1) } //遍历数组1 cookieMy.arrsearchXia = function(value, arr) { for(var i = 0; i < arr.length; i++) { if(value == arr[i]) { return i; //位置后一位 } } return false; }
true
3c270be49f00c2296374e2a5a4dfaad22fe7566e
JavaScript
prudhvi2244/26-05-2021
/myscript2.js
UTF-8
691
2.984375
3
[]
no_license
var employee={ eid:1, ename:"Prudhvi", isSenior:true, mobiles:[9090901234,7878781234,899912345], address:{ streetno:'44/44', city:'Bangalore', state:'Karnataka' } } console.log(typeof(employee)) console.log('Diaplaying Employee Data') console.log(employee) console.log('Employee ID:'+employee.eid) console.log('Employee Name:'+employee.ename) console.log('Senior Employee?:'+employee.isSenior) console.log('Employee Mobiles:'+employee.mobiles[1]) console.log('Employee Address : StreetNo:'+employee.address.streetno) console.log('Employee Address : City:'+employee.address.city) console.log('Employee Address : State:'+employee.address.state)
true
3bac44cbf88e749956b2d2d59fcc5fde563cae53
JavaScript
stas-yushkov/learn-js
/js/hw-01/practice/ternary.js
UTF-8
1,723
3.234375
3
[ "MIT" ]
permissive
{// ДЗ на тернарные const loginRight = '1111'; //это логин. лень долго вводить ручками при тесте const passwordRight = '2222'; //это пароль. лень долго вводить ручками при тесте let loginEntered = null; let passwordEntered = null; const messageNeedLogin = 'введи логин'; const messageNeedPasswd = 'введи пароль'; const messageGreeting = 'здоров. надо же, и логин и пароль верны'; const messageCancelled = 'отменено. чего было пытаться'; const messageEnteredWrongPasswd = 'вспомнишь пароль, заходи'; const messageEnteredWrongLogin = 'я вас не знаю. Даже логин не помнишь, о чем тут говорить'; (loginEntered = prompt(messageNeedLogin)) === loginRight ? ((passwordEntered = prompt(messageNeedPasswd)) === passwordRight ? console.log(messageGreeting) : ((passwordEntered === null) ? console.log('null',passwordEntered,messageCancelled) : (passwordEntered === '') ? console.log('nothing',passwordEntered,messageCancelled) : console.log('somethingWrongPasswd',passwordEntered,messageEnteredWrongPasswd))) : ((loginEntered === null) ? console.log('null',loginEntered,messageCancelled) : ((loginEntered === '') ? console.log('nothing',loginEntered,messageCancelled) : console.log('somethingWrongLogin',loginEntered,messageEnteredWrongLogin))); }//ДЗ на тернарные
true
db882fbb575bcad0da18fd2475ea33ff7c1f3933
JavaScript
bkpetitt/Arrays
/matcharray02.js
UTF-8
3,919
3.09375
3
[]
no_license
// Programmer: BKP // Date: 09/05/2017 // Subject: Create two-dimensionmal array using Randomizers // arRow is current row of array // arCol is current column of array // maxRow and maxCol are maxium size of arrays rows and columns // // var matches= [ // ['day:','month:','date:','opponent:','locale:','time:','lafScore','oppScore','OT'], ['Friday','August',26,'St Francis Brooklyn','Home','6pm',0,1,true], ['Tuesday','August',30,'Albany','Away','7pm',0,1,false], ['Friday','September',2,'Fairfield','Home','7pm',0,2,false], ['Sunday','September',4,'Quinnipiac','Away','1pm',0,2,false], ['Friday','September',9,'Fordham','Away','7pm',3,1,false], ['Saturday','September',17,'Yale','Away','1pm',2,0,false], ['Tuesday','September',20,'LaSalle','Home','7pm',2,1,false], ['Saturday','September',24,'Loyola*','Home','1pm',0,2,false], ['Tuesday','September',27,'FDU','Away','7pm',1,0,false], ['Saturday','October',1,'Army*','Away','4pm',2,0,false], ['Wednesday','October',5,'Bucknell*','Away','7pm',1,0,false], ['Saturday','October',8,'American* Alumni Day','Home','1pm',0,3,false], ['Wednesday','October',12,'NJIT','Home','7pm',0,0,true], ['Saturday','October',15,'Boston U*','Away','1pm',0,1,false], ['Saturday','October',22,'Holy Cross*','Home','7pm',1,1,true], ['Wednesday','October',26,'Lehigh* ','Home','7pm',1,0,false], ['Saturday','October',29,'Navy*','Away','7pm',2,3,true], ['Saturday','November',5,'Colgate*','Home','4pm',0,1,false], ]; // // var arRow = 0; var arCol = 0; var maxRow = 0; var maxCol = 0; // var totalLaf = 0; var totalOpp = 0; var totalOt = 0; var totalWin = 0; var totalLoss = 0; var totalDraw = 0; var totalHWin = 0; var totalHLoss = 0; var totalHDraw = 0; var totalAWin = 0; var totalALoss = 0; var totalADraw = 0; // var cntHome = 0; var cntAway = 0; var recHome = 0; var recAway = 0; // // // determine number of rows var maxRow = matches.length; // determine length of columns var maxCol = matches[0].length; // console.log('^^------------------------^^') // console.log('Array Height (total matches): ', maxRow); console.log('Number Matches: ', maxRow); console.log('Number of Match Elements: ', maxCol); console.log('^^------------------------^^') // // for (arRow=0; arRow<maxRow; arRow++) { // console.log('Row: ',arRow,' Stored Value: ',matches[arRow]); var totalLaf = totalLaf + matches[arRow][6]; var totalOpp = totalOpp + matches[arRow][7]; // // calculating complete record if (matches[arRow][6]===matches[arRow][7]) { var totalDraw = totalDraw + 1;} else if (matches[arRow][6]>matches[arRow][7]) { var totalWin = totalWin + 1;} else { var totalLoss = totalLoss + 1;} // // calculating home record if (matches[arRow][4]==='Home') { var cntHome = cntHome + 1;} else if (matches[arRow][6]===matches[arRow][7]) { var totalHDraw = totalHDraw + 1;} else if (matches[arRow][6]>matches[arRow][7]) { var totalHWin = totalHWin + 1;} else { var totalHLoss = totalHLoss + 1;} // // calculating away record if (matches[arRow][4]==='Away') { var cntAway = cntAway + 1;} else if (matches[arRow][6]===matches[arRow][7]) { var totalADraw = totalADraw + 1;} else if (matches[arRow][6]>matches[arRow][7]) { var totalAWin = totalAWin + 1;} else { var totalALoss = totalALoss + 1;} } // // console.log('^^------------------------^^') console.log('LAF Record: ',totalWin,totalLoss,totalDraw); console.log('LAF Home Record: ',totalHWin,totalHLoss,totalHDraw); console.log('LAF Away Record: ',totalAWin,totalALoss,totalADraw); console.log('^^------------------------^^') console.log('Total LAF goals: ', totalLaf); console.log('Total Opp goals: ', totalOpp); console.log('Total OT goals: ', totalOt); console.log('Total Home Matches: ', cntHome); console.log('Total Away Matches: ', cntAway); console.log('Home Record: ', recHome); console.log('Away Record: ', recAway); // //
true
8cbd88ab495fafc5c22ca6528e6878116dc37d12
JavaScript
s-davies/aA_Classwork
/W9D4/skeleton/frontend/users_search.js
UTF-8
1,133
2.8125
3
[]
no_license
const APIUtil = require("./api_util.js"); const FollowToggle = require("./follow_toggle.js"); class UsersSearch { constructor($el) { this.$el = $el; this.$input = $el.find('input'); this.$ul = $el.find('.users'); this.searchString = []; this.handleInput(); } handleInput() { this.$input.on("keyup", (event) => { if (event.key != "Backspace"){ this.searchString.push(event.key); } else { this.searchString.pop(); } const check = APIUtil.searchUsers(this.searchString.join("")) .then((data) => { this.renderResults(data); }); }) } renderResults(data) { this.$ul.empty(); for (let i = 0; i < data.length; i++) { let $li = $(`<li><a href='/users/${data[i].id}'>${data[i].username}</a></li>`); this.$ul.append($li); let $button = $(`<button class="follow-toggle" data-user-id="${data[i].id}" data-initial-follow-state="${data[i].followed === true ? "followed" : "unfollowed"}"></button>`); const toggle = new FollowToggle($button); $li.append($button); } } } module.exports = UsersSearch;
true
e2cc97bd3d5a78d67f6e50652785c7863ec5b363
JavaScript
Jinnapat/thinkfood-backend
/server/login.js
UTF-8
3,196
2.53125
3
[]
no_license
/*{ ... data : { user : customer or shop id : int } --->can i use '/profile/:user/:id' to get req.parms data required when user press profile button to enter to profile page }*/ // var bodyParser = require('body-parser'); // app.use(bodyParser.json()); // support json encoded bodies // app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies // app.post('/api/users', function(req, res) { // var user_id = req.body.id; // var token = req.body.token; // var geo = req.body.geo; // res.send(user_id + ' ' + token + ' ' + geo); // }); var mysql = require("mysql"); var pool = mysql.createPool({ canRetry: false, connectionLimit : 100, host : 'db4free.net', port : 3306, user : 'da_think', password : '12345678', database : 'thickinc_gang', }); //app.get("/profile/:user/:id", (req, res) => { app.get("/getprofile/", (req, res) => { user_data = ['init']; //var sqlcommand = 'select * from ${req.parms.user} where id = ${req.params.id};'; var sqlcommand = 'select * from ${data.user} where id = ${data.id};'; pool.getConnection((err, connection) => { if(err) throw err; console.log('connected as id ' + connection.threadId); connection.query(sqlcommand, (err, rows) => { if(err) throw err; console.log('The data from users table are: \n', rows); res.send({ user_data: rows}); }); }); }); /*{ ... data : { customer_username customer_email customer_password customer_birthday } data required when customer press save button to update their profile }*/ app.get("/updatecustomerprofile/:id", (req, res) => { user_data = ['init']; var sqlcommand = `update customer set customer_username=${customer_username}, customer_email=${customer_email}, customer_password=${customer_password}, customer_birthday=${customer_birthday} where customer_id = ${req.params.id};`; pool.getConnection((err, connection) => { if(err) throw err; console.log('connected as id ' + connection.threadId); connection.query(sqlcommand, (err, rows) => { if(err) throw err; console.log(rows); res.send('Profile updated...'); }); }); }); /*{ ... data : { shop_name shop_username shop_password } data required when customer press save button to update their profile }*/ app.get("/updateshopprofile/:id", (req, res) => { user_data = ['init']; var sqlcommand = `update shop set shop_name=${shop_name}, shop_username=${shop_username}, shop_password=${shop_password} where shop_id = ${req.params.id};`; pool.getConnection((err, connection) => { if(err) throw err; console.log('connected as id ' + connection.threadId); connection.query(sqlcommand, (err, rows) => { if(err) throw err; console.log(rows); res.send('Profile updated...'); }); }); }); // app.post('/')
true
a53e24a63aa8f82c9c30bebc8863e26071cf7641
JavaScript
csmr/random-dev-notes
/nodejs-express-couch-fun.js
UTF-8
2,232
2.6875
3
[ "MIT" ]
permissive
/** Notes on express.js & cradle **/ // Routes // parametrizing a route app.get( '/showPlace/:place?', function( req, res ) { res.send( req.param('place', 'Helsinki')); // if no param place, uses default Helsinki }); // request-object // source https://github.com/visionmedia/express/blob/master/lib/request.js // request parameters req.query.parFoo // http://www.ufo.fi?parFoo=1 // req.get - any header value gotten req.get('user-agent') req.get('') req.accepted // content types req.accepts('html', 'json') // which types are accepted req.acceptLanguage // response-object // res -object // res.attachment | .cookies | .clearCookies | .download | .links | .sendfile // json response app.get( "/rawjsobj", function( req, res ) { res.json( { fooBar: 0, content: "message" } ) res.cookie( "aCookye", "Some Content", { expires: new Date(Date.now() + 900000), domain: 'what.com' } ) }) // Optional content type app.get( "/select", function( req, res ) { res.format({ html: function() { res.send("<h1>Hi</h1>") }, json: function() { res.json({ message: "body" }) }, text: function() { res.send("sum text") } }) }) // redirect app.get( "/newDirection", function( req, res ) { res.status( 302 ).redirect( "/home" ) // statuscode, new url } /*** CouchDB ***/ // get Cradle npm install -S cradle cradle = require('cradle') // 0. config conn cradle.setup( configObj ) // 1. open server conn var conn = new( cradle.Connection ) var serverReport = { info: conn.info(), stats: conn.stats(), databases: conn.databases(), lastConfig: conn.config() } // 2. create db var db = conn.database('sumBase') db.exists( function( err, exists ) { if ( !err && !exists ) db.create() } // 3. use db db.info() db.all() // dumps the contents of databas // operations // - in couch- get/put/post/delete // - in cradle- get/save/view/delete db.get( 'documentNameFoo', handlerFunc ) db.view( 'sum/pathTo/aDoc', iteratorFunc ) db.save( 'another/pathTo/oneDoc', docObjRef ) db.delete( 'docN', docRevision, respHandlerFunc ) db.merge( 'theDocument', { someField: "newValue" }, handlFunc ) // update single field value // erase database db.destroy()
true
a538b485a66c58ce536add36bcfd4d9a6699cd34
JavaScript
Isaqb/SuperHeroApi-desafio
/src/component/AddGrupo.js
UTF-8
2,256
2.78125
3
[]
no_license
import React, { useState } from "react"; import "./AddGrupo.css" const AddGroup = (props) => { const { heros } = props.location.state; const [search, setSearch] = useState(''); const filtered = search.length === 0 ? [] : heros.filter( h => h.name.toLowerCase().includes(search.toLowerCase()) ) const handleSearch = (e) => { e.preventDefault(); setSearch(e.target.value); } const addGroup = (hero) => { localStorage.setItem(hero.id, JSON.stringify(hero)); window.location.reload(); } const showHero = () => { var values = [], keys = Object.keys(localStorage), i = keys.length; while (i--) { values.push(JSON.parse(localStorage.getItem(keys[i]))); } return values; } return ( <> <div className="grupos"> <h1 className="titulo"> Meu Grupo</h1> <div className="grupos"> {showHero().map(f => { return ( <div key={f?.id} className="card-group"> <p><b>Nome:</b> {f?.name}</p> <img className="heroImg" alt={f?.name} src={f?.image.url}></img> </div> ); })} </div> </div> <br /> <div className="grupos"> <h1 className="titulo">Grupos</h1> <input className="input" type="text" onChange={(e) => handleSearch(e)} placeholder='Selecione seus hérois' /> <div className="grupos"> {filtered.map(f => { return ( <div key={f?.id} className="cardbox"> <p><b>Nome:</b> {f?.name}</p> <img className="heroImg" alt={f?.name} src={f?.image.url}></img> <button onClick={() => addGroup(f)}>Adicionar ao grupo</button> </div> ); })} </div> </div> </> ); } export default AddGroup;
true
a1980cd9ee9d54af86c5b1c19c7cce6efa2edcd7
JavaScript
andrewp24/is448
/chapter5_js/eg2-load/load.js
UTF-8
871
3.671875
4
[]
no_license
window.onload = pageLoad; function pageLoad() { load_greeting(); var quote_button = document.getElementById("quote_button"); quote_button.onclick = display_quote; var mood = document.getElementById("change"); mood.onclick = changeImage; } //the onload event handler function load_greeting() { alert("You are visiting my home page. WELCOME!"); var greeting_message = "You are visiting my home page. WELCOME!"; document.getElementById("greeting_box").value = greeting_message; } //the onclick event handler function display_quote() { var quote_of_the_day = "A penny saved is a penny earned"; alert(quote_of_the_day); } function changeImage() { alert("here"); var mood = document.getElementById("mood").src; if (mood.includes("happy")) { document.getElementById("mood").src = "sad.png"; } else { document.getElementById("mood").src = "happy.jpg"; } }
true
3411f8527067a02f3b22f770cece19310ef7b531
JavaScript
sdague/serverless-home-automation
/ibm_cloud_functions/conversation.js
UTF-8
1,407
2.890625
3
[ "Apache-2.0" ]
permissive
/** * * main() will be invoked when you Run This Action. * * @param OpenWhisk actions accept a single parameter, * which must be a JSON object. * * In this case, the params variable will look like: * { "message": "xxxx" } * * @return which must be a JSON object. * It will be the output of this action. * */ var request = require('request'); function main(params) { var username = params.username var password = params.password var workspace_id = params.workspace_id var input_text = params.data var url = "https://gateway.watsonplatform.net/conversation/api/v1/workspaces/" + workspace_id + "/message?version=2017-04-21" var body = {"input": {"text": input_text}} return new Promise(function(resolve, reject) { request( { url: url, method: 'POST', auth: { 'user': username, 'pass': password }, headers: { "content-type": "application/json", }, body: JSON.stringify({"input": { "text": input_text }}) }, function(error, response, body) { if (error) { reject(error); } else { var output = JSON.parse(body) resolve({msg: output}); } }); } ); }
true
b73f042d0bca1a797c8d53a3290e58ec293406f4
JavaScript
mamilla11/ana-shishoit
/source/kekstagram/js/preview.js
UTF-8
1,398
3.046875
3
[]
no_license
'use strict'; (function () { /** * @class Preview * @description All future preview behaviour should be added to this class. * @prop {Object} picture - picture information. * @prop {Element} view - root element of picture preview DOM element. * @prop {Object} elements - child elements of picture preview DOM element. * @param {Object} picture - picture information. */ var Preview = function (picture) { this.picture = picture; this.view = null; this.elements = {}; this.initView(); }; /** * Initializes preview DOM element. */ Preview.prototype.initView = function () { this.view = document.querySelector(window.templates.Preview.name) .content .querySelector(window.templates.Preview.Selector.CONTAINER) .cloneNode(true); this.elements.image = this.view.querySelector( window.templates.Preview.Selector.IMAGE ); this.elements.likes = this.view.querySelector( window.templates.Preview.Selector.LIKES ); this.elements.comments = this.view.querySelector( window.templates.Preview.Selector.COMMENTS ); this.elements.image.src = this.picture.url; this.elements.likes.textContent = this.picture.likes; this.elements.comments.textContent = this.picture.comments.length; }; window.Preview = Preview; })();
true
09624b6a216c58073aac2fb84536e03c291dfbf8
JavaScript
CLLKazan/Webbication
/js/get_categories.js
UTF-8
611
2.875
3
[]
no_license
/* Ajax запрос получения списка категорий и их аттрибутов */ function get_categories() { var request = new XMLHttpRequest(); //ajax переменная request.open("GET", "php/get_categories.php", false); //соединяемся с сервером. Т.к. параметров нет, отправляем запрос методом GET request.onreadystatechange = parse_categories; //функция, вызываемая при изменении состояния запроса request.send(null); //отправляем параметры (null) }
true
5da7136a23e0b650c1e6ab60db86191c1f68e461
JavaScript
hoangbdUET/file-browser-backend
/src/_file-sys/path-stat.js
UTF-8
3,075
2.65625
3
[]
no_license
const fs = require('fs'); const {s3} = require('../_aws'); const withFs = dir => { return new Promise((resolve, reject) => { fs.lstat(dir, (err, stat) => { if (err) return reject(err); // return resolve(stat) return resolve({ isDirectory: () => stat.isDirectory(), isFile: () => stat.isFile(), size: stat.size, LastModified: stat.mtime, metaData: "" }) }) }) }; const withS3 = (bucket, dir) => { return new Promise(async (resolve, reject) => { //special case if (dir === '' || dir === '/') return resolve({ isDirectory: () => true, isFile: () => false }); //default of s3 dont use / at start //but in fs system use / if (dir[0] === '/' || dir[0] === '//') dir = dir.substr(1); try { const params = {Bucket: bucket, Prefix: dir}; // console.log(params); const data = await s3.listObjectsV2(params).promise(); // console.log("data list object === ", data.Contents); // console.log(dir); const foundContent = data.Contents.find( content => { // console.log("compares ", content.Key, "||", dir, "||"); // let rs = content.Key === dir || content.Key === dir + '/'; // loi khi thu muc khong co file con // let rs = content.Key.includes(dir) || content.Key.includes(dir + '/'); let rs = content.Key === (dir) || content.Key === (dir + '/'); return rs } ); // foundContent.Key = dir + '/'; // console.log("=======", !foundContent, foundContent); // console.log(foundContent); // if (!foundContent) return reject(new Error('Directory is not founded')); if (!foundContent) return resolve(null); // console.log("found content ===", foundContent); // to sync with version that using fs // folder end with / // file doesnt end with / let metaData = (await s3.headObject({Bucket: bucket, Key: foundContent.Key}).promise()).Metadata; if (metaData.encodingtype === "base64") { for (let key in metaData) { // console.log(key) if (key !== "encodingtype") { metaData[key] = (new Buffer(metaData[key], 'base64')).toString("utf8"); } } } let secondSlash = dir.indexOf("/", dir.indexOf("/") + 1); // console.log(secondSlash); // console.log(dir); metaData.location = dir.substring(secondSlash); const stat = { isFile: () => { return foundContent.Key[foundContent.Key.length - 1] !== '/' }, isDirectory: () => { return foundContent.Key[foundContent.Key.length - 1] === '/' }, metaData: metaData, size: foundContent.Size, modifiedDate: foundContent.LastModified }; // calculate size // because s3 treat folder as an empty object // therefore folder will have 0kb size return resolve(stat); } catch (error) { reject(error) } }) }; // withS3('test-quang', 'folder').then(data => console.log(data)) module.exports = (dir, options) => { if (options && options.s3) { if (!options.bucket) return Promise.reject(new Error('Bucket is required')); return withS3(options.bucket, dir) } return withFs(dir) };
true
36aeacf06180c8b44b44cac8376d155608603345
JavaScript
Anisha7/spiced-rotten-potatoes
/models/user.js
UTF-8
2,643
2.921875
3
[]
no_license
const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); const session = require('express-session'); const UserSchema = new mongoose.Schema({ username: { type: String, unique: true, required: true, trim: true }, password: { type: String, required: true, } //userId: { type: Schema.Types.ObjectId, ref: 'user' } }) //hashing a password before saving it to the database UserSchema.pre('save', function (next) { var user = this; bcrypt.hash(user.password, 10, function (err, hash){ if (err) { return next(err); } user.password = hash; next(); }) }); //authenticate input against database // not working REWRITE // UserSchema.statics.authenticate = function (username, password, callback) { // //console.log("authenticating"); // //console.log(User.find({username:username})); // User.find({ username: username }) // .exec(function (err, user) { // if (err) { // return callback(err) // } else if (!user) { // var err = new Error('User not found.'); // err.status = 401; // return callback(err); // } // bcrypt.compare(password, user.password, function (err, result) { // if (result === true) { // return callback(null, user); // } else { // return callback(); // } // }) // }); // } // Authentication - Login UserSchema.statics.authenticate = function(username, password, callback) { User.findOne({ username: username }) .exec(function(error, user) { if (error) { return callback(error); } else if (!user) { var err = new Error('User not found!'); err.status = 401; return callback(err); } // Compare using bcrypt bcrypt.compare(password, user.password, function(error, result){ if (result === true) { return callback(null, user); } else { return callback(); } }); }); }; // the function that tries to check username/password entered to the database UserSchema.statics.auth = function(username, password) { let user = User.find({username: username}); console.log(user); if (user === null) { return false; } console.log("auth user password: ") console.log(user.password); console.log(user.username); // ***** set this equal to password values let userPassword = ""; if (bcrypt.compare(password, user.password)) { return true; } return "wrong password"; } const User = mongoose.model('User', UserSchema); module.exports = User;
true
083217140cda846b34e632e2752ff50f31e27f9b
JavaScript
xAlessandroC/TrickyRace
/js/environment/environment.js
UTF-8
1,542
2.921875
3
[ "Apache-2.0" ]
permissive
var environment_texture function setUpEnvironmentMapping(){ var faceInfos = [ { target: gl.TEXTURE_CUBE_MAP_POSITIVE_X, url: 'resources/images/environment/x+.jpg', }, { target: gl.TEXTURE_CUBE_MAP_NEGATIVE_X, url: 'resources/images/environment/x-.jpg', }, { target: gl.TEXTURE_CUBE_MAP_POSITIVE_Y, url: 'resources/images/environment/y+.jpg', }, { target: gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, url: 'resources/images/environment/y-.jpg', }, { target: gl.TEXTURE_CUBE_MAP_POSITIVE_Z, url: 'resources/images/environment/z+.jpg', }, { target: gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, url: 'resources/images/environment/z-.jpg', } ]; environment_texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_CUBE_MAP, environment_texture); faceInfos.forEach((faceInfo) => { const {target, url} = faceInfo; gl.texImage2D(target, 0, gl.RGBA, 256, 256, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); const image = new Image(); image.src = url; image.addEventListener('load', function() { console.log("loaded " + image.src) // Now that the image has loaded upload it to the texture. gl.bindTexture(gl.TEXTURE_CUBE_MAP, environment_texture); gl.texImage2D(target, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); gl.generateMipmap(gl.TEXTURE_CUBE_MAP); }); }); gl.generateMipmap(gl.TEXTURE_CUBE_MAP); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); }
true
8105f17607d64f927cc9a97c4a62f7b921a03e34
JavaScript
adimelamed/ds_frontend
/home.js
UTF-8
383
2.6875
3
[]
no_license
$(document).ready(function() { searchBars(); }); function searchBars(){ $("#content div").each(function(i, curr) { var name = $(curr).attr('id'); var sn = document.getElementById('search').value.toLowerCase(); if (sn == "") { $('#content > div').show(); } else if(sn == name){ $("#content > div").hide(); $('#content > div[id*="'+name+'"]').show(); } }); }
true
18852fce17c121f75d69ddd1badb26c7f2694f2d
JavaScript
subhodip7/repo
/src/main/webapp/js/administrator.js
UTF-8
4,117
2.625
3
[ "MIT" ]
permissive
/* * This Javascript file is included in all administrator pages. Functions here * should be common to the administrator pages. */ // AJAX var xmlhttp = new getXMLObject(); // OPERATIONS var OPERATION_ADMINISTRATOR_ADDINSTRUCTORINATOR = "administrator_addinstructor"; var OPERATION_ADMINISTRATOR_LOGOUT = "administrator_logout"; // PARAMETERS var INSTRUCTOR_EMAIL = "instructoremail"; var INSTRUCTOR_GOOGLEID = "instructorid"; var INSTRUCTOR_NAME = "instructorname"; var INSTRUCTOR_INSTITUTION = "instructorinstitution"; function addInstructor(googleID, name, email, institution) { if (xmlhttp) { xmlhttp.open("POST", "teammates", false); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;"); xmlhttp.send("operation=" + OPERATION_ADMINISTRATOR_ADDINSTRUCTORINATOR + "&" + INSTRUCTORINATOR_GOOGLEID + "=" + googleID + "&" + INSTRUCTORINATOR_NAME + "=" + name + "&" + INSTRUCTORINATOR_EMAIL + "=" + email + "&" + INSTRUCTORINATOR_INSTITUTION + "=" + institution); } } function verifyInstructorData() { var googleID = $('[name="' + INSTRUCTOR_GOOGLEID + '"]').val(); googleID = sanitizeGoogleId(googleID); var name = $('[name="' + INSTRUCTOR_NAME + '"]').val().trim(); var email = $('[name="' + INSTRUCTOR_EMAIL + '"]').val().trim(); var institution = $('[name="' + INSTRUCTOR_INSTITUTION + '"]').val().trim(); $('[name="' + INSTRUCTOR_GOOGLEID + '"]').val(googleID); $('[name="' + INSTRUCTOR_NAME + '"]').val(name); $('[name="' + INSTRUCTOR_EMAIL + '"]').val(email); $('[name="' + INSTRUCTOR_INSTITUTION + '"]').val(institution); if (googleID == "" || name == "" || email == "") { setStatusMessage(DISPLAY_FIELDS_EMPTY, true); return false; } else if (!isValidGoogleId(googleID)) { setStatusMessage(DISPLAY_GOOGLEID_INVALID, true); return false; } else if (!isEmailValid(email)) { setStatusMessage(DISPLAY_EMAIL_INVALID, true); return false; } else if (!isNameValid(name)) { setStatusMessage(DISPLAY_NAME_INVALID, true); return false; } else if (!isInstitutionValid(institution)) { setStatusMessage(DISPLAY_INSTITUTION_INVALID, true); return false; } return true; } function getXMLObject() { var xmlHttp = false; try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { xmlHttp = false; } } if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } return xmlHttp; } function handleLogout() { if (xmlhttp.status == 200) { var url = xmlhttp.responseXML.getElementsByTagName("url")[0]; window.location = url.firstChild.nodeValue; } } function isGoogleIDValid(googleID) { if (googleID.indexOf("\\") >= 0 || googleID.indexOf("'") >= 0 || googleID.indexOf("\"") >= 0) { return false; } else if (googleID.match(/^[a-zA-Z0-9@ .-]*$/) == null) { return false; } else if (googleID.length > 29) { return false; } return true; } function logout() { if (xmlhttp) { xmlhttp.open("POST", "teammates", false); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;"); xmlhttp.send("operation=" + OPERATION_ADMINISTRATOR_LOGOUT); } handleLogout(); } function showHideErrorMessage(s) { $("#" + s).toggle(); } function toggleDeleteAccountConfirmation(googleId) { var rawList = document.getElementById('courses_' + googleId).innerHTML; var list = rawList.replace(/<br>/g, "\n").trim() + "\n\n"; return confirm("Are you sure you want to delete the account " + googleId + "?\n\n" + list + "This operation will delete ALL information about this account " + "from the system."); } $(function () { $("[data-toggle='tooltip']").tooltip(); });
true
fdc38484390467e2710c61c722fd9ecf1adb848f
JavaScript
realglobe-Inc/hec-jissho1
/lib/common_func.js
UTF-8
1,932
3.15625
3
[ "MIT" ]
permissive
/** * Server 側と UI 側の共通関数 */ const camelcase = require('camelcase') const snakecase = require('snake-case') const CAMEL = 1 const SNAKE = 2 const DELIMITER = '#' const commonFunc = { /** * 通報情報 report をフォーマットする */ formatRawToDb ({report, actorKey, event}) { let [lat, lng] = report.location let {id: reportId, heartRate, date} = report let reportFullId = commonFunc.reportFullId({actorKey, reportId}) let data = _translateCase(SNAKE)({ reportFullId, reportId, actorKey, heartRate, lat, lng, date, event }) return data }, formatDbToUI (report) { let formatted = _translateCase(CAMEL)(report) for (let key of Object.keys(formatted)) { if (_isDate(key)) { formatted[key] = new Date(formatted[key]) } } return formatted }, formatRawToUI ({report, actorKey, event}) { return commonFunc.formatDbToUI(commonFunc.formatRawToDb({report, actorKey, event})) }, /** * データベース関係。 actorKey, reportId, reportFullId の三者変換 */ reportFullId ({actorKey, reportId}) { return `${actorKey}${DELIMITER}${reportId}` }, toActorKey (reportFullId) { return reportFullId.split(DELIMITER)[0] }, toReportId (reportFullId) { return parseInt(reportFullId.split(DELIMITER)[1], 10) } } /** * オブジェクトのキーを camelcase(or snakecase) に変換する */ function _translateCase (type) { return (obj) => { let translate = { [SNAKE]: snakecase, [CAMEL]: camelcase }[type] let res = {} let keys = Object.keys(obj) for (let key of keys) { res[translate(key)] = obj[key] } return res } } function _isDate (key) { // RFC 形式 // example: 2016-09-27T05:43:07.000Z return key === 'date' || key === 'createdAt' || key === 'updatedAt' } module.exports = commonFunc
true
398b9bbae90ff8ada439b39d510a311f292cc52b
JavaScript
fatexik/js--touchsoft
/task-04/TatyanaTimoshek/myFilter.js
UTF-8
785
3.125
3
[]
no_license
/* eslint no-extend-native: ["error", { "exceptions": ["Array"] }] */ /** * Написать реализацию метода .myFilter, который работает * аналогично оригинальному * https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/filter */ Array.prototype.myFilter = function myFilter(callback, context) { var array = this.slice(); var resultArray = []; var index; if (typeof callback !== 'function') { throw new Error('Callback is not a function.'); } for (index = 0; index < array.length; index++) { if ( array[index] !== undefined && callback.apply(context, [array[index], index, array]) ) { resultArray.push(array[index]); } } return resultArray; };
true
fb47a2406a3e014bd6f52a9f7c949d0a64730eef
JavaScript
starfishda/Graphics
/[Term Project] Eating Villan/Script/Abstract/DrawingObject.js
UTF-8
1,202
2.859375
3
[]
no_license
// This is a variable for managing static class-specific resources var Resource = {}; class DrawingObject { static geometry = null; static material = null; mesh; radius = 1; Initialize(resource) { } Enable() { // Initialize when the class is first used (only one executed) if (Resource[this.className] == null) { Resource[this.className] = {"className": this.className}; this.Initialize(Resource[this.className]) } this.mesh = this.CreateThreeMesh(Resource[this.className]) // Store that class in a THREE object this.mesh.logic = this; // Add to Scene ObjectManager.Scene.add(this.mesh); this.Start(); return this.mesh; } // Abstract function Start() { } // Abstract function Update() { } IsCollision(object) { if (object == null) return false; var difference = new THREE.Vector3(); difference.copy(this.mesh.position).sub(object.mesh.position); return difference.length() <= this.radius + object.radius; } Dispose() { ObjectManager.disposelist.push(this); } }
true
7b55642f24212a34516b8e884095c8544f20c976
JavaScript
KennyNathalia/Horeca-app
/horeca.js
UTF-8
3,382
3.703125
4
[]
no_license
const frisPrice= 2.00; const bierPrice= 2.50; const wijnPrice= 3.00; const bit8Price= 4.00; const bit16Price= 5.00; var frisAmount= 0; var bierAmount= 0; var wijnAmount= 0; var bit8Amount= 0; var bit16Amount= 0; var loop= false; while(loop==false){ var drinken = prompt("Hallo en welkom bij Cafe-bar Davinci! \nWelke bestelling wilt u toevoegen? \n(fris, bier, wijn of snack.) \nFris= $2.00 Bier= $2.50 Wijn= 3.00 Bitterballen 8= $2.70 Bitterballen 16= $5.40").toLowerCase(); if(drinken=="fris"){ var frisAmount = Number(prompt("Hoeveel flesjes fris wilt u toevoegen aan uw bestelling?")) document.getElementById("frisBon").style.display="block"; document.getElementById("fris2").style.display="block"; } else if(drinken=="bier"){ var bierAmount = Number(prompt("Hoeveel glazen bier wilt u toevoegen aan uw bestelling?")) document.getElementById("bierBon").style.display="block"; document.getElementById("bier2").style.display="block"; } else if(drinken=="wijn"){ var wijnAmount = Number(prompt("Hoeveel glazen wijn wilt u toevoegen aan uw bestelling?")) document.getElementById("wijnBon").style.display="block"; document.getElementById("wijn2").style.display="block"; } else if(drinken=="snack"){ var snack = Number(prompt("Hoeveel bitterballen wilt u toevoegen aan uw bestelling? \n(8 of 16)")) if (snack=="8") { var bit8Amount= Number(prompt("Hoeveel bitterbalschalen van 8 wilt u hebben?")) var afrond = snack.toFixed(2); document.getElementById("bit8bon").style.display="block"; document.getElementById("bit2").style.display="block"; } else if (snack=="16"){ var bit16Amount= Number(prompt("Hoeveel bitterbalschalen van 16 wilt u hebben")) var afrond = snack.toFixed(2); document.getElementById("bit16bon").style.display="block"; document.getElementById("bit3").style.display="block"; } else { alert("U kunt alleen kiezen tussen 8 of 16.") } } else if(drinken=="stop"){ loop=true var totalFris= frisPrice * frisAmount var totalBier= bierPrice * bierAmount var totalWijn= wijnPrice * wijnAmount var totalBit8= bit8Price * bit8Amount var totalBit16= bit16Price * bit16Amount var totalPrice= totalFris + totalBier + totalWijn + totalBit8 + totalBit16 document.getElementById("frisBon").innerHTML = "Het aantal fris wat u heeft is " + frisAmount document.getElementById("fris2").innerHTML = "Dat kost dan $" + totalFris document.getElementById("bierBon").innerHTML = "Het aantal bier wat u heeft is " + bierAmount document.getElementById("bier2").innerHTML = "Dat kost dan $" + totalBier document.getElementById("wijnBon").innerHTML = "Het aantal wijn wat u heeft is " + wijnAmount document.getElementById("wijn2").innerHTML = "Dat kost dan $" + totalWijn document.getElementById("bit8bon").innerHTML = "Het aantal bitterballen van 8 wat u heeft is " + bit8Amount document.getElementById("bit2").innerHTML = "Dat kost dan $" + totalBit8 document.getElementById("bit16bon").innerHTML = "Het aantal bitterballen van 16 wat u heeft is " + bit16Amount document.getElementById("bit3").innerHTML = "Dat kost dan $" + totalBit16 document.getElementById("bon").innerHTML = "Het totale wat u heeft is $" + totalPrice; } else { alert("Dit staat niet op het menu.") } }
true
cacd6530dd33407a063f27698da58cafa4565c36
JavaScript
qingyangmoke/js-asynctask
/index.js
UTF-8
453
2.984375
3
[ "MIT" ]
permissive
/** * 执行异步任务 * @param {Array<Function>} middleWares - 数组 * @param {any} ...args - 可变参数 */ async function runAsyncTask(middleWares, ...args) { if (middleWares.length === 0) return; const len = middleWares.length; let index = 0; async function next() { if (index < len) { const func = middleWares[index++]; func.apply(null, [...args, next]); } }; await next(); } module.exports = runAsyncTask;
true
ccfdfd54f5c2e769dee6e35c097664915041c45c
JavaScript
SamuelDorado/breakout-ES6
/js/bricks.js
UTF-8
1,488
3.234375
3
[]
no_license
export class Brick { constructor(width, height, padding, offsetTop, offsetLeft, color) { this.width = width this.height = height this.padding = padding this.offsetTop = offsetTop this.offsetLeft = offsetLeft this.color = color } } export class BrickWall { constructor(rowCount, columnCount) { this.rowCount = rowCount this.columnCount = columnCount this.bricks = [] for (let i = 0; i < columnCount; i++) { this.bricks[i] = []; for (let j = 0; j < rowCount; j++) { this.bricks[i][j] = { x: 0, y: 0, status: 1 }; } } } drawBricks(brick, canvasCtx) { for (var c = 0; c < this.columnCount; c++) { for (var r = 0; r < this.rowCount; r++) { if (this.bricks[c][r].status === 1) { var brickX = (c * (brick.width + brick.padding)) + brick.offsetLeft, brickY = (r * (brick.height + brick.padding)) + brick.offsetTop; this.bricks[c][r].x = brickX; this.bricks[c][r].y = brickY; canvasCtx.beginPath(); canvasCtx.rect(brickX, brickY, brick.width, brick.height); canvasCtx.fillStyle = brick.color; canvasCtx.fill(); canvasCtx.closePath(); } } } } }
true
fea4fa9011e09286355de02dc100c7d44fd191bc
JavaScript
snehalkadam393/review-job
/jobs/UTIL_H2INMEM_QUERY/buildScripts/helperJavaScript.js
UTF-8
9,792
2.625
3
[]
no_license
/* TEST_PROCESS_IMAGELIST: HelperJavaScript.js Introduces DOM manipulation with jQuery to enhance the creation of the ANNOTATION_PLAN ANNOTATION_PLAN no longer shares the same dropdown as PROPERTIES but gets a dedicated cloned copy @Since JAN-09-2019 @Author: Ioannis K. Moutsatsos */ /* wait for the document to be fully loaded before working with it */ jQuery(document).ready(function() { }); /* Function creates map when both key and value are provided from CV selection */ function addPlannedAction(node, plan, action, prop, oper, value) { var planAction = document.getElementById(action).value; var dsProp = document.getElementById(prop).value; console.log('#' + prop) var dsOper = document.getElementById(oper).value; if (value == 'annoSelector') { var propValue = Q(jQuery('#' + value)).find('select').val(); } else { var propValue = document.getElementById(value).value; } var planVal = ''; planVal = planVal.concat('[', "action:", '"', planAction, '",', "operator:", '"', dsOper, '",', "property:", '"', dsProp, '",', "value:", '"', propValue, '"', ']'); console.log('queryPlanValue:' + planVal) document.getElementById(plan).value = document.getElementById(plan).value.concat(planVal); parentId = document.getElementById(plan).parentNode.id jQuery('#' + parentId).trigger('change') /* add checkbox option to document node */ addAnnotationCheckBox(node, planAction, dsProp, dsOper, propValue, planVal) } /* a generic function to add an annotation action checkbox ---------------------------------------*/ function addAnnotationCheckBox(planNode, mNode, mKey, mOper, mValue, planValue) { var dNode = document.getElementById(planNode); var x = document.createElement("INPUT"); x.setAttribute("type", "checkbox"); x.setAttribute("name", planNode + "Action"); x.setAttribute("value", planValue); dNode.appendChild(x); var y = document.createElement("label"); y.setAttribute("class", "attach-previous"); var labelFor = mNode + '.' + mKey + '.' + mValue; x.title = labelFor; y.setAttribute("for", labelFor); y.innerHTML = mNode + '.' + mKey + mOper.replace('equal', '=') + mValue + '<br/>'; dNode.appendChild(y); } /* the action is deleted from checklist as well as from hidden xtPlan text input */ function deletePlannedAction(plan, planNode) { jQuery(document).ready(function() { var selected = []; console.log("input[name='" + planNode + "Action']:checked"); jQuery.each(jQuery("input[name='" + planNode + "Action']:checked"), function() { selected.push(jQuery(this).val()); delEntry = jQuery(this).val(); console.log("Deleting:" + delEntry); document.getElementById(plan).value = document.getElementById(plan).value.replace(delEntry, ''); parentId = document.getElementById(plan).parentNode.id; jQuery('#' + parentId).trigger('change'); label2remove = jQuery(this).attr('title'); console.log("Removing:" + label2remove); jQuery('label[for="' + label2remove + '"]').remove(); jQuery(this).remove(); }); //alert("Deleted: " +selected.join(", ")); }); } function resetPlannedAction(plan, planNode) { document.getElementById(plan).value = ''; jQuery(document).ready(function() { console.log("input[name='" + planNode + "Action']:checked"); jQuery.each(jQuery("input[name='" + planNode + "Action']"), function() { label2remove = jQuery(this).attr('title'); jQuery('label[for="' + label2remove + '"]').remove(); jQuery(this).remove(); }); parentId = document.getElementById(plan).parentNode.id; jQuery('#' + parentId).trigger('change'); }); } /* note that a similar function exists in SCRIPT_HELPER function setQueryFlag() { console.log('calling2On') document.getElementById("queryFlag").value = 'ON' parentId = document.getElementById("queryFlag").parentNode.id jQuery('#' + parentId).trigger('change') } */ function setProcessFlag() { console.log('setting_processFlag_2On') document.getElementById("processFlag").value = 'ON' parentId = document.getElementById("processFlag").parentNode.id jQuery('#' + parentId).trigger('change') } /* assembles a json string of other parameters and from it sets the value of the transfer parameter jsonParams is used by the: imageMagickProcessor_jsonInput.groovy */ function setJsonTransferParam(transferParamId) { //TEST_IMAGES,OVERLAY,GLOBAL_IMPATH,GLOBAL_SESSIONS_WORKSPACE console.log('setting_json_parameters') jsonParams = { TEST_IMAGES: joinObj(jQuery('#' + jQuery('input[value=TEST_IMAGES]')[0].nextSibling.id).find('option:selected'), 'value'), OVERLAY: jQuery('#imgPerComposite').val(), GLOBAL_IMPATH: document.getElementById('imagickPath').value, GLOBAL_SESSIONS_WORKSPACE: document.getElementById('sessionsWorkspace').value, cantaloupeLocalBaseUrl: document.getElementById('cantaloupeLocalBaseUrl').value, cantaloupeLocalConfig: document.getElementById('cantaloupeLocalConfig').value, vOutputFolder: document.getElementById('jobSessionPath').value, } document.getElementById(transferParamId).value = JSON.stringify(jsonParams) transferParentId = document.getElementById(transferParamId).parentNode.id jQuery('#' + transferParentId).trigger('change') } /* assembles a json string of other parameters and from it sets the value of the transfer parameter images2View: options are i2v (TEST_IMAGES) i2conv (PROCESSED_IMAGES) jsonParams is used by the: JSON_GALLERIES_imageGalleryFromTemplate.groovy */ function setJsonGalleryParam(transferParamId, images2View) { //vOutputFolder,vIMAGELIST_URL,vIMAGE_OBJECTS,vIMAGE_GALLERY,vPRIMARY_IMAGE_LIST,vJOB_PATH,vIMAGE_ADJUSTMENTS,vTEST_IMAGES,vBUILD_LABEL console.log('setting_json_parameters') gallerySource=images2View galleryPath=(gallerySource=='i2conv')?jQuery('#galleryPath').val():'imageList' galleryImages=(gallerySource=='i2conv')?document.getElementById('i2convArchive').value:document.getElementById(images2View).value gallerySuffix=(gallerySource=='i2conv')?'_LevelIntensities':'' objNames = jQuery('#' + jQuery('input[value=IMAGE_OBJECTS]')[0].nextSibling.id).find('input:checked').map(function() { return Q(this).val() }) objOpacity = jQuery('#' + jQuery('input[value=IMAGE_OBJECTS]')[0].nextSibling.id).find('input:checked').map(function() { return 'opacity_' + Q(this).val() }).map(function() { return Q('#' + this).val() }) objColor = jQuery('#' + jQuery('input[value=IMAGE_OBJECTS]')[0].nextSibling.id).find('input:checked').map(function() { return 'colpick_' + Q(this).val() }).map(function() { return Q('#' + this).val() }) var d = new Date(); var timestamp=d.getFullYear()+("0"+(d.getMonth()+1)).slice(-2)+("0"+d.getDate()).slice(-2)+ ("0" + d.getHours()).slice(-2)+ ("0" + d.getMinutes()).slice(-2)+("0" + d.getSeconds()).slice(-2); jsonParams = { vOutputFolder: document.getElementById('jobSessionPath').value, vIMAGELIST_URL: jQuery('#' + jQuery('input[value=IMAGELIST_URL]')[0].nextSibling.id).find('input')[0].value, vTEST_IMAGES: galleryImages, vIMAGE_LABELS: document.getElementById('i2vlabels').value, vPRIMARY_IMAGE_LIST: jQuery(jQuery('input[value=PRIMARY_IMAGE_LIST]')[0].nextSibling).find('option:selected').val(), vLAYOUT: document.getElementById('gridRows').value.concat(',', jQuery('input[name=fillBy]').filter(':checked').val()), vIMAGE_OBJECTS: { NAMES: Object.values(objNames).slice(0, objNames.length).join(','), COLOR: Object.values(objColor).slice(0, objColor.length).join(','), OPACITY: Object.values(objOpacity).slice(0, objOpacity.length).join(','), }, vBRIGHTNESS: jQuery('#set_brightness').val(), vCONTRAST: jQuery('#set_contrast').val(), LAYOUT: { vFILLSIZE: jQuery('#gridRows').val(), vFILLBY: jQuery('[name^=fillBy]:checked').val() }, OVERLAY: { OVERLAYFLAG: jQuery('#getOverlay').val(), OVERLAYSIZE: jQuery('#imgPerComposite').val() }, vNOTES: jQuery('input[value=GALLERY_NOTES]')[0].nextSibling.value, TSTAMP: timestamp, GALLERY_SOURCE: gallerySource, GALLERY_PATH: galleryPath, vBUILD_LABEL: jQuery('#' + jQuery('input[value=GALLERY_LABEL]')[0].nextSibling.id).find('input')[0].value+gallerySuffix } document.getElementById(transferParamId).value = JSON.stringify(jsonParams) transferParentId = document.getElementById(transferParamId).parentNode.id jQuery('#' + transferParentId).trigger('change') } /*assembles a json object for the current result set */ function setJsonResultParam(transferParamId){ //resultSetId: resultSetId, jsonParams = { queryId: document.getElementById("lastResult").value, artifactPath: document.getElementById("artifactPath").value, artifactLabel:jQuery('#' + jQuery('input[value=RESULT_LABEL]')[0].nextSibling.id).find('input')[0].value, resultSetURL: document.getElementById("dataCsv").value, resultSetColumns: document.getElementById("dataCols").value, TSTAMP: getTimeStamp(), } document.getElementById(transferParamId).value = JSON.stringify(jsonParams) transferParentId = document.getElementById(transferParamId).parentNode.id jQuery('#' + transferParentId).trigger('change') } /* returns selected values of an AC parameter as a list of comma separated values similar to how AC cascade values */ function joinObj(a, attr) { var out = []; for (var i = 0; i < a.length; i++) { out.push(a[i][attr]); } return out.join(", "); } /* returns a time stamp to be used in JSON objects */ function getTimeStamp(){ d = new Date(); return d.getFullYear()+("0"+(d.getMonth()+1)).slice(-2)+("0"+d.getDate()).slice(-2)+ ("0" + d.getHours()).slice(-2)+ ("0" + d.getMinutes()).slice(-2)+("0" + d.getSeconds()).slice(-2); }
true
78e24ec65577735a0b681991b5f5c6c1c7d55b2a
JavaScript
uverpro/JavaTUT
/App-Academy/W1/W1D1/W1D1-Problems/Variable-Exercise.js
UTF-8
842
5.0625
5
[]
no_license
// Variables Exercise // 1. Declare a variable called `firstName` and assign it your first name as a string: let firstName = "Cory"; // 2. Declare a variable called `lastName` and assign it your last name as a string: let lastName = "Pedigo"; // 3. Declare a variable called `age`: let age; // 4. Print out the `firstName`, `lastName`, and `age` variables. What do you // expect them to be when they get printed? console.log(firstName, lastName, age); // Cory Pedigo undefined // 5. Assign the `age` variable to a number: age = 35; // 6. Print out the `firstName`, `lastName`, and `age` variables. What do you // expect them to be when they get printed? console.log(firstName, lastName, age); // Cory Pedigo 35 console.log(`My name is ${firstName} ${lastName} and I am ${age} years old.`); // My name is Cory Pedigo and I am 35 years old.
true
b08d8cd6822f263570c95f567df8e825d07e0237
JavaScript
bgran/full-stack
/osa2/kurssitiedot/App.js
UTF-8
1,207
2.671875
3
[]
no_license
import React from 'react' import ReactDOM from 'react-dom' import Course from './Course' const Header = (props) => { return ( <h1>{props.course_name}</h1> ) } const Courses = (props) => { let o = props.courses return ( <div> <Header course_name={"Web development curriculum"} /> {o.map((item, index) => ( <Course course={item} ind={index} /> )) } </div> ) } const App = () => { const courses = [ { "name": "Half Stack application development", id:1, "parts":[ {"name": "Fundamentals of Reach", "exercises":10, id:1}, {"name": "Using props to pass data", "exercises":7, id:2}, {"name": "State of component", "exercises":14, id:3}, {"name": "Redux", "exercises":11, id:4} ] }, { "name": "Node.js", "id" : 2, "parts": [ {"name": "Routing", "exercises":3, id:1}, {"name": "Middlewaret", "exercises":7, id:2} ] } ] return ( <div> <Courses courses={courses} /> </div> ) } ReactDOM.render(<App />, document.getElementById('root')) export default App;
true
efc19ad4d93bd3dbf60c81a3a7b7954ab46ab691
JavaScript
volkaankarakus/JavaScript
/SıfırdanJS/1-Temeller/11-AsenkronProgramlamaPart1/12-AjaxveDELETE/app.js
UTF-8
3,429
3.390625
3
[]
no_license
class Request{ constructor(){ this.xhr = new XMLHttpRequest(); } get(url,callback){ this.xhr.open("GET",url); this.xhr.onload = () => { if(this.xhr.status==200) { callback(null,this.xhr.responseText); } else{ callback("GET Requestte hata olustu.",null); } }; this.xhr.send(); } post(url,data,callback){ this.xhr.open("POST",url); this.xhr.setRequestHeader("Content-Type","application/json"); this.xhr.onload = () => { if(this.xhr.status === 201){ // Basarili callback(null,this.xhr.responseText); } else{ // Hatali callback("POST Requestte hata olustu.",null) } } this.xhr.send(JSON.stringify(data)); } put(url,data,callback){ this.xhr.open("PUT",url); this.xhr.setRequestHeader("Content-Type","application/json"); // PUT'un onload'unda 200 kodu gelir. this.xhr.onload = () => { if(this.xhr.status === 200){ // Basarili callback(null,this.xhr.responseText); } else{ // Hatali callback("PUT Requestte hata olustu.",null) } } this.xhr.send(JSON.stringify(data)); } // jsonplaceholder'da bir 10. albumun delete'i icin /albums/10 vermemiz yeterli. // response olarak da bos bir obje doner. delete(url,callback){ this.xhr.open("DELETE",url); this.xhr.onload = () => { if(this.xhr.status==200) { callback(null,"Veri Silme Basarili."); // this.xhr.responseText donmesine gerek yok. bu {} donuyor. onun yerine bir yazi yazdiralim. } else{ callback("DELETE Requestte hata olustu.",null); } }; this.xhr.send(); } } const request = new Request(); // get requesti gonderme request.get("https://jsonplaceholder.typicode.com/albums",function(err,response){ if(err === null){ // Basarili console.log(response); } else{ // Hatali console.log(err); } }); // post requesti gonderme request.post("https://jsonplaceholder.typicode.com/albums",{userId:2, title:"Volkan"},function(err,album){ // Basarili if(err === null){ console.log(album); } else{ // Hata console.log(err); } }); // put request gonderme // id'si 10 olan albumu degistirelim request.put("https://jsonplaceholder.typicode.com/albums/10",{userId:500, title:"Ali"},function(err,album){ // Basarili if(err === null){ console.log(album); } else{ // Hata console.log(err); } }); // delete requesti gonderme // id'si 20 olan albumu silelim request.delete("https://jsonplaceholder.typicode.com/albums/20",function(err,response){ if(err === null){ // Basarili console.log(response); } else{ // Hatali console.log(err); } }); /* {} bize bos bir obje donmus oldu. */
true
b8b24b51c29bce59de63886caefd8ec97110565b
JavaScript
wing00/drnktank
/apps/front/static/front/js/pong_components/topbar.jsx
UTF-8
4,136
2.515625
3
[]
no_license
import React from 'react'; import { Link } from 'react-router'; function PlayerIcon(props) { const onFire = props.stats[2]; return ( <div className="player"> {props.value} <br /> {props.current == props.value ? ( <i className="fa fa-2x fa-user-circle" /> ) : ( <i className="fa fa-2x fa-user" /> ) } <br /> {props.stats[1].map(function(object, num){ if (onFire) { return ( <i className="fa fa-fire" key={num} /> ); } else { return ( <i className="fa fa-circle" key={num} /> ); } })} <br /> {props.stats[0]} <br /> </div> ); } function calculateStats(stats, player) { let cupCount = stats[player].reduce(function(x, y) {return (y > -1) ? x + 1 : x;}, 0); let lastThree = stats[player].slice(-3).reverse(); let fireArray = []; for (let i = 0; i < lastThree.length ; i++) { if (lastThree[i] == -1) { break; } fireArray.push(1); } let onFire = fireArray.length == 3; return [cupCount, fireArray, onFire] } export default class TopBar extends React.Component { constructor(props) { super(props); } render() { return ( <div className="topBar"> <div className="myTeamIcons col-lg-4 col-md-4 col-sm-4 col-xs-12 text-center"> <h2>Blue Team</h2> <PlayerIcon value={this.props.names[0]} current={this.props.currentPlayer} stats={calculateStats(this.props.stats, 0)} onClick={() => this.props.onClick(this.props.names[0])} /> <PlayerIcon value={this.props.names[1]} current={this.props.currentPlayer} stats={calculateStats(this.props.stats, 1)} onClick={() => this.props.onClick(this.props.names[1])} /> </div> <div className="col-lg-4 col-md-4 col-sm-4 col-xs-12 text-center"> {this.props.winner ? ( <div className="statusboard text-center"> <h2>{this.props.winner} Wins!</h2> <button type="button" className="btn btn-primary text-center" onClick={(i) => this.props.rematch()}>Rematch</button> <br/><br /> <Link to="/setup"><button type="button" className="btn btn-primary text-center">New Game</button></Link> </div> ) : ( <div className="statusboard text-center"> <h4>Current Shooter<br/>{this.props.currentPlayer}</h4> </div> )} </div> <div className="theirTeamIcons col-lg-4 col-md-4 col-sm-4 col-xs-12 text-center"> <h2>Red Team</h2> <PlayerIcon value={this.props.names[2]} current={this.props.currentPlayer} stats={calculateStats(this.props.stats, 2)} onClick={() => this.props.onClick(this.props.names[2])} /> <PlayerIcon value={this.props.names[3]} current={this.props.currentPlayer} stats={calculateStats(this.props.stats, 3)} onClick={() => this.props.onClick(this.props.names[3])} /> </div> </div> ) } }
true
9062eb78b9206c36455c2b7f66dfbf112fc5b573
JavaScript
MichaelMerc/village88
/Algorithm I/algo1-3.js
UTF-8
78
3.125
3
[]
no_license
for(var i=0; i<5; i++) { i = i + 3; console.log(i); } //Answer is 3, 7
true
1b4f8fec9922c91c941de266b3b5c88917277247
JavaScript
chrismarcosgomes/caloriesMeal
/js/app.js
UTF-8
10,300
3.5
4
[]
no_license
// storage //item controller // ify func that runs right away const itemCtrl=( ()=>{ // item constructor const Item = function(id, name, calories){ this.id = id; this.name = name; this.calories = calories; } // data structure/state const data={ items:[ // { // id:0, // name:"Tacos", // calories:1200 // },{ // id:1, // name:"Sopes", // calories:800 // },{ // id:2, // name:"Torta", // calories:1400 // } ], // current item is meant for updating in the form currentItem:null, totalCaloies:0 // func that lets me access my data structure logData().. public method }; return { getItems:()=>{ return data.items }, addItem:(name,calories)=>{ console.log(name,calories) let ID; // create ID if(data.items.length>0){ // a sense of auto increment ID= data.items[data.items.length-1].id+1; }else{ ID=0; } // calories to number instead of string calories= parseInt(calories) // create new item newItem=new Item(ID,name,calories); // add new item to array data.items.push(newItem); return newItem; }, getItemById:(id)=>{ let found = null; data.items.forEach((current)=>{ if(current.id===id){ found=current; } }) return found; }, updateItem:(name, calories)=>{ // calories to number calories=parseInt(calories) let found= null; data.items.forEach((item)=>{ if(item.id===data.currentItem.id){ item.name=name; item.calories=calories; found=item; } }) return found; }, deleteItem:(id)=>{ const ids=data.items.map((item)=>{ return item.id }) // get the index const index=ids.indexOf(id); data.items.splice(index,1) }, clearAllItem:()=>{ data.items=[] } ,getCurrentItem:()=>{ return data.currentItem; }, setCurrentItem:(current)=>{ data.currentItem=current; }, getTotalCalories:()=>{ let total=0; // loop thew items and add cals data.items.forEach((item)=>{ total+=item.calories; }) // set total cal in data structure data.totalCalories=total; // return total return data.totalCalories }, logData:()=>{ return data; } } } )(); //ui control // ify func that runs right away const uiCtrl=( ()=>{ // we make a ui selector so we us JS instead of html. for ID's and classes const uiSelector={ itemList:"#item-list", listItems:"#item-list li", addBtn:".add-btn", itemNameInput:"#item-name", itemCaloriesInput:"#item-calories", totalCalories:".total-calories", updateBtn:".update-btn", deleteBtn:".delete-btn", backBtn:".back-btn", clearBtn:".clear-btn", } return{ populateItemList:(items)=>{ let html=""; // lopps threw Items items.forEach((Item)=>{ // we are appending here and creating the list to show html+=`<li class="collection-item" id="item-${Item.id}"> <strong>${Item.name}: </strong><em>${Item.calories} Calories</em> <a href="#" class="secondary-content"> <i class="edit-item fa fa-pencil-alt"></i> </a> </li>` }); //insert li tag to ui document.querySelector(uiSelector.itemList).innerHTML=html; }, // we are getting the value of them from the id's item-name,item-calories(querySelector) getItemInput:()=>{ return{ name:document.querySelector(uiSelector.itemNameInput).value, calories:document.querySelector(uiSelector.itemCaloriesInput).value } } ,addListItem:(item)=>{ // show list item document.querySelector(uiSelector.itemList).style.display="block" // create li element const li= document.createElement("li"); // add class li.className="collection-item"; // add the unique id li.id=`item-${item.id}` // add to html li.innerHTML=`<strong>${item.name}: </strong><em>${item.calories} Calories</em> <a href="#" class="secondary-content"> <i class="edit-item fa fa-pencil-alt"></i> </a>`; // insert item document.querySelector(uiSelector.itemList).insertAdjacentElement("beforeend",li) } ,updateListItem:(item)=>{ let listItems=document.querySelectorAll(uiSelector.listItems) // turn node list into array listItems=Array.from(listItems) listItems.forEach((listItem)=>{ const itemId=listItem.getAttribute("id"); if(itemId===`item-${item.id}`){ document.querySelector(`#${itemId}`).innerHTML=`<strong>${item.name}: </strong><em>${item.calories} Calories</em> <a href="#" class="secondary-content"> <i class="edit-item fa fa-pencil-alt"></i> </a>`; } }) }, deleteListItem:(id)=>{ const itemID=`#item-${id}` const item=document.querySelector(itemID); item.remove() } , hideList:()=>{ document.querySelector(uiSelector.itemList).style.display="none" }, addItemToForm:()=>{ document.querySelector(uiSelector.itemNameInput).value=itemCtrl.getCurrentItem().name; document.querySelector(uiSelector.itemCaloriesInput).value=itemCtrl.getCurrentItem().calories; uiCtrl.showEditState(); } ,clearInput:()=>{ document.querySelector(uiSelector.itemNameInput).value=""; document.querySelector(uiSelector.itemCaloriesInput).value=""; }, showTotalCalories:(calories)=>{ document.querySelector(uiSelector.totalCalories).textContent=calories; }, clearEditState:()=>{ uiCtrl.clearInput(); document.querySelector(uiSelector.updateBtn).style.display="none"; document.querySelector(uiSelector.deleteBtn).style.display="none" document.querySelector(uiSelector.backBtn).style.display="none" document.querySelector(uiSelector.addBtn).style.display="inline" } ,clearback:(e)=>{ e.preventDefault() uiCtrl.clearInput(); document.querySelector(uiSelector.updateBtn).style.display="none"; document.querySelector(uiSelector.deleteBtn).style.display="none" document.querySelector(uiSelector.backBtn).style.display="none" document.querySelector(uiSelector.addBtn).style.display="inline" } , showEditState:()=>{ document.querySelector(uiSelector.updateBtn).style.display="inline"; document.querySelector(uiSelector.deleteBtn).style.display="inline" document.querySelector(uiSelector.backBtn).style.display="inline" document.querySelector(uiSelector.addBtn).style.display="none" }, removeItems:()=>{ let listItems=document.querySelectorAll(uiSelector.listItems); // turn node list into array listItems=Array.from(listItems) listItems.forEach((currrent)=>{ currrent.remove() }) } // get a public method so we can get the querySelector vars ,getSelectors:()=>{ return uiSelector; }} } )(); // app control // ify func that runs right away const App=( (itemCtrl,uiCtrl)=>{ // load event listeners const loadEventListeners=()=>{ // this lets us use our selectors const UISelector=uiCtrl.getSelectors(); // add item event document.querySelector(UISelector.addBtn).addEventListener( "click",itemAddSubmit) // disbale submit on enter document.addEventListener("keypress",(e)=>{ if(e.keyCode===13|| e.witch===13){ e.preventDefault() return false; } }) // edit icon click event document.querySelector(UISelector.itemList).addEventListener("click", itemEditClick) // back click event document.querySelector(UISelector.backBtn).addEventListener("click", uiCtrl.clearback) // UPDATE document.querySelector(UISelector.updateBtn).addEventListener("click", itemUpdateSubmit) // edit delete click event document.querySelector(UISelector.deleteBtn).addEventListener("click", itemDeleteSubmit) //clear items event document.querySelector(UISelector.clearBtn).addEventListener("click", clearAllItemsClick) } // add item submit const itemAddSubmit=(e)=>{ // get form input from UI Cntrl const input=uiCtrl.getItemInput() //console.log(input) // check for name and calories if(input.name !=="" && input.calories !==""){ // add item const newItem=itemCtrl.addItem(input.name,input.calories) // add item to ui list uiCtrl.addListItem(newItem) //get the total calories const totalCalories=itemCtrl.getTotalCalories() // add total calories to UI uiCtrl.showTotalCalories(totalCalories) // clear fileds for meal and calories uiCtrl.clearInput(); } e.preventDefault(); }; // click edit item const itemEditClick=(e)=>{ //console.log("update item") if(e.target.classList.contains("edit-item")){ //console.log("edit working") const listID=e.target.parentNode.parentNode.id; // console.log(listID) const listidArray= listID.split("-") const id= parseInt(listidArray[1]) const itemtoEdit=itemCtrl.getItemById(id); // set to current item itemCtrl.setCurrentItem(itemtoEdit) // add item to form uiCtrl.addItemToForm(); } e.preventDefault(); } // update item submit const itemUpdateSubmit=(e)=>{ // get item input const input=uiCtrl.getItemInput(); // update item const updatedItem=itemCtrl.updateItem(input.name, input.calories) // update UI uiCtrl.updateListItem(updatedItem); const totalCaloies=itemCtrl.getTotalCalories(); uiCtrl.showTotalCalories(totalCaloies) uiCtrl.clearEditState() e.preventDefault(); } // CLEAR ITEM EVENT const clearAllItemsClick=()=>{ // DELTE ALL ITEM FROM DATA itemCtrl.clearAllItem(); const totalCalories = itemCtrl.getTotalCalories(); // Add total calories to UI uiCtrl.showTotalCalories(totalCalories); uiCtrl.removeItems() uiCtrl.hideList() } // delete button const itemDeleteSubmit=(e)=>{ // get current item const currentItem=itemCtrl.getCurrentItem(); //delete from data structure itemCtrl.deleteItem(currentItem.id) // delete from ui uiCtrl.deleteListItem(currentItem.id); // Get total calories const totalCalories = itemCtrl.getTotalCalories(); // Add total calories to UI uiCtrl.showTotalCalories(totalCalories); uiCtrl.clearEditState(); e.preventDefault() } // return func init, initializer for the app... public methods return{ init:()=>{ // clear edit state uiCtrl.clearEditState(); // console.log("I WORK") // put data stucture into a var const items=itemCtrl.getItems(); //console.log(items) // check if any items if(items.length===0){ uiCtrl.hideList() }else{ // populate list with items uiCtrl.populateItemList(items); } //get the total calories const totalCalories=itemCtrl.getTotalCalories() // add total calories to UI uiCtrl.showTotalCalories(totalCalories) // load event listeners loadEventListeners() } } } )(itemCtrl,uiCtrl); // init app App.init()
true
ee47488d9d1dde49a556917f2ed7b2cfa9659dd1
JavaScript
kernsinator/frostykernel
/scripts/puzzle-scripts/chickasaw.js
UTF-8
1,532
3.25
3
[]
no_license
let answers = [ 'Hattakat ihooã hollo.', "Kowi'at shoha.", "Holloli.", "The woman loves me.", "The dog dances.", "I chase the cat." ]; let accuracy = [false, false, false, false, false, false]; let q1 = document.getElementById('q1'); let q2 = document.getElementById('q2'); let q3 = document.getElementById('q3'); let q4 = document.getElementById('q4'); let q5 = document.getElementById('q5'); let q6 = document.getElementById('q6'); let correct = 0; let progressBar = document.getElementById('correct'); let progressOutput = document.getElementById('num-correct'); function checkAnswers() { if (q1.value === answers[0]) { accuracy[0] = true; } else { accuracy[0] = false; } if (q2.value === answers[1]) { accuracy[1] = true; } else { accuracy[1] = false; } if (q3.value === answers[2]) { accuracy[2] = true; } else { accuracy[2] = false; } if (q4.value === answers[3]) { accuracy[3] = true; } else { accuracy[3] = false; } if (q5.value === answers[4]) { accuracy[4] = true; } else { accuracy[4] = false; } if (q6.value === answers[5]) { accuracy[5] = true; } else { accuracy[5] = false; } tallyCorrect(); progressOutput.innerHTML = correct; progressBar.value = correct; } function tallyCorrect() { correct = 0; for(i = 0 ; i < 8 ; i++) { if (accuracy[i]) { correct++ } } }
true
e5d9492b01f769f9988487ddfa43ba4dc854366e
JavaScript
lullabyjune/leetcode
/prevPermOpt1.js
UTF-8
1,678
3.3125
3
[]
no_license
/** * @param {number[]} A * @return {number[]} */ var prevPermOpt1 = function(A) { let isIncrement = true, length = A.length, max = '0' function findSuitable (index) { let aimNum = A[index], max = Number.MAX_SAFE_INTEGER, maxIndex = -1 for (let i = index - 1; i >= 0; i--) { if (A[i] > aimNum) { max = A[i] maxIndex = i break; } } console.log(aimNum, max, index) return maxIndex === -1 ? -1 : { num: max, numIndex: maxIndex } } for (let i = 0; i < length - 1; i++) { if (A[i] > A[i + 1]) { isIncrement = false break } } if (!isIncrement) { for (let i = length - 1; i >= 0; i--) { let canUse = findSuitable(i) console.log(canUse) if (canUse !== -1) { let arr = A.slice() let tmp = arr[i] arr[i] = canUse.num arr[canUse.numIndex] = tmp max = arr.join('') > max ? arr.join : max } } } return A }; let arr = [1,9,4, 8, 6,7] // arr = [3, 2, 1] // arr = [1, 1, 5] // arr = [3, 1, 1, 3] // arr = [1,9,6,7,9,6,4,4,2,2,7,7,7,6,3,5,7,7,3,8,8,4,4,1,5,4,7,4,7,3,7,5,4,1,7,4,9,6,5,9,8,9,9,4,6,6,5,5,7,7,8,1,4,6,4,5,4,4,8,9,5,7,2,4] arr = [6,1,5,9,1,1,9,7,7,9,7,6,2,7,3,4,5,1,7,6,3,5,3,1,4,7,1,1,8,8,9,1,9,5,1,6,5,4,7,3,2,7,4,9,7,6,2,5,7,4,3,7,5,5,4,4,2,1,3,1,6,4,8,7,5,9,3,1,4,4,7,5,3,7,2,4,4,8,5,4,8,1,1,3,4,3,5,4,8,1,5,4,9,8,4,5,3,1,1,3] console.log(prevPermOpt1(arr))
true
8a65ead9adced02f8ab4ef829d80f95ab7c32548
JavaScript
pierman1/Browser-Technologies
/1.2.funda-fork/funda/js/modules/constants.js
UTF-8
2,558
2.59375
3
[]
no_license
var constants = (function () { var loader = document.querySelector('#loader'); var noMatchError = document.querySelector('#matches .error'); var inputElements = (function () { var locationElements = (function () { var input = document.querySelector('#location .input'); var submit = document.querySelector('#location .submit'); return { input, submit }; })(); var kindElements = (function () { var inputs = document.querySelectorAll('#kind input[type="radio"]'); var submit = document.querySelector('#kind .submit'); return { submit, inputs }; })(); var priceElements = (function () { var buy = document.querySelector('.price-buy'); var rent = document.querySelector('.price-rent'); var submit = document.querySelector('#price .submit'); var elements = document.querySelectorAll('#price form > div'); var inputMinBuy = document.querySelector('#price #min-price-buy'); var inputMaxBuy = document.querySelector('#price #max-price-buy'); var inputMinRent= document.querySelector('#price #min-price-rent'); var inputMaxRent = document.querySelector('#price #max-price-rent'); return { buy, rent, submit, elements, inputMinBuy, inputMaxBuy, inputMinRent, inputMaxRent }; })(); var buyOrRentElements = (function () { var inputs = document.querySelectorAll('#buy-rent input[type="radio"]'); var submit = document.querySelector('#buy-rent .submit'); return { submit, inputs }; })(); var likeElements = (function () { var like = document.querySelector('.objects__items .like'); var dislike = document.querySelector('.objects__items .dislike'); console.log(like); return { like, dislike } })(); return { locationElements, kindElements, priceElements, buyOrRentElements, likeElements } })(); return { loader, inputElements, noMatchError } })();
true
92ad24d49c77faaaa1820731d44211b29b468c7e
JavaScript
MireGitHub/EVA
/code/node/webserver/test_json.js
UTF-8
87
2.703125
3
[]
no_license
var string = "{'key':'value'}"; var obj = JSON.parse(string); console.log(obj.key);
true
85b837122b378783c416a86a4426203816ee12bf
JavaScript
10wpressure/JavaScript
/Tutorial/learn-javascript-main/1. Build a Passenger Counter App/9. Using functions to write less code/index.js
UTF-8
272
3.15625
3
[]
no_license
// Setting up the the race 🏎 🏎 🏎 function countdown() { for (let i = 5; i > 0; i--) { console.log(i) } } // GO! 🏁 // Players are running the race 🏎 💨 // Race is finished! 🍾 // Get ready for a new race 🏎 🏎 🏎 countdown()
true
87d7f2fc4c63334c8dee6baf8197b925b625b657
JavaScript
QQzs/HTML_Day
/Demo/瀑布流/jQuery实现瀑布流/js/index.js
UTF-8
2,340
2.640625
3
[]
no_license
// 页面加载完毕 $(window).on('load',function () { // 实现瀑布流布局 waterFall(); $(window).on('scroll',function () { // 是否加载 if(checkWillLoad()){ var data = {'dataImage': [{'image': '10.jpg'}, {'image': '11.jpg'}, {'image': '14.jpg'}, {'image': '15.jpg'}, {'image': '13.jpg'}, {'image': '17.jpg'}]}; // 遍历创建 $.each(data.dataImage, function (index , value) { var newBox = $('<div>').addClass('box').appendTo($('#main')); var newPic = $('<div>').addClass('pic').appendTo($(newBox)); $('<img>').attr('src','images/' + $(value).attr('image')).appendTo($(newPic)); }); } waterFall(); }); }); function checkWillLoad() { // v/ar allBox = $('#main .box'); // var lastBox = allBox[allBox.length - 1]; var lastBox = $('#main>div').last(); var lastBoxDis = $(lastBox).outerHeight() * 0.5 + $(lastBox).offset().top; var screenHeight = $(window).height(); var scrollTopHeight = $(window).scrollTop(); // console.log(lastBoxDis , screenHeight , scrollTopHeight); return lastBoxDis <= screenHeight + scrollTopHeight; } function waterFall() { // 拿到所有盒子 var allBox = $('#main>.box'); // var boxWidht = allBox[0].offsetWidth; var boxWidth = $(allBox).eq(0).outerWidth(); // 屏幕的宽度 var screenWidth = $(window).width(); console.log(screenWidth , boxWidth); // 求出列数 var col = Math.floor(screenWidth/boxWidth); // 父标签居中 $('#main').css({ 'width' : col * boxWidth + 'px', 'margin' : '0 auto' }); var heightArr = []; $.each(allBox , function (index , value) { var boxHeight = $(value).outerHeight(); if (index < col){ // heightArr.push(boxHeight); heightArr[index] = boxHeight; }else{ var minHeight = Math.min.apply(this,heightArr); // 最小高度的坐标 var minIndex = $.inArray(minHeight,heightArr); $(value).css({ 'position' : 'absolute', 'top' : minHeight + 'px', 'left' : boxWidth * minIndex + 'px' }); heightArr[minIndex] += boxHeight; } }); }
true
b909e0cfbc0a3e4d4ee16381c160a1321fdcc65f
JavaScript
runandrew/codeWars-practice
/practice-problems/7kyu-find-next-perfect-square.js
UTF-8
398
4.21875
4
[]
no_license
// Find the next perfect square const findNextSquare = (sq) => { // Return the next square if sq if a perfect square, -1 otherwise // Take the square value and evaluate if it's a perfect square // If not, return -1 // If so, increment the value and return the square of it const root = Math.pow(sq, 0.5); if (Number.isInteger(root)) return Math.pow(root + 1, 2); else return -1; }
true
58728520fb9326f8341d1d9941e66fbf23b1f1db
JavaScript
nolonwabo/my_screen
/where_to_eat.js
UTF-8
431
2.921875
3
[]
no_license
var mealTemplate = document.querySelector('.mealTemplate').innerHTML; var mealTemp = Handlebars.compile(mealTemplate); var slide = 0; burgers(); function burgers() { var i; var x = document.getElementsByClassName('mySlides'); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } slide++; if (slide > x.length) { slide = 1 } x[slide - 1].style.display = "block"; setTimeout(burgers, 2000); }
true
01e3b5de0f216e05a4bbfb3f495c4ea7e5f2a0d1
JavaScript
Toast-Glitch/phase-1-arithmetic-lab
/index.js
UTF-8
202
3.015625
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
let num1 = 1; let num2 = 62; let num3 = 16; let num4 = 6; let multiply = (num1 * num2) let random = Math.floor(Math.random() * 10) + 1; let mod = (num3 % num4); let max = Math.max = (2,16,8,14,20);
true
c6949fe9d065e54b15965b64521d5fcc194f0cc3
JavaScript
jsagardoy/react-promise-tracker
/src/trackPromise.test.js
UTF-8
1,900
2.578125
3
[ "MIT" ]
permissive
import {trackPromise, emitter} from './trackPromise'; import {Emitter} from './tinyEmmiter'; describe('trackPromise', () => { test('On Initial case, promise fired, promise emitter.emit is called', () => { // Arrange emitter.emit = jest.fn((a,b) => { return; }); const myPromise = Promise.resolve().then(() => { return "ok"; }); // Act trackPromise(myPromise); // Assert expect(emitter.emit).toHaveBeenCalledTimes(1); return myPromise; }); test('Promise tracked, we got resolve, check that emit is called 2 times', () => { // Arrange emitter.emit = jest.fn((a,b) => { return; }); const myPromise = Promise.resolve(); // Act trackPromise(myPromise); // Assert return myPromise.then(() => { expect(emitter.emit).toHaveBeenCalledTimes(2); }); }); test('Promise tracked, we got fail, check that emit is called 2 times', () => { // Arrange expect.assertions(1); emitter.emit = jest.fn((a,b) => { return; }); const myPromise = new Promise((resolve, reject) => { reject(); }) //const myPromise = Promise.reject(); // Act trackPromise(myPromise); // Assert return myPromise.catch(()=> { expect(emitter.emit).toHaveBeenCalledTimes(2) }); }); // Pending promise failed test('Two Promises tracked, we got resolve on both, check that emit is called 4 times', () => { // Arrange expect.assertions(1); emitter.emit = jest.fn((a,b) => { return; }); const myPromiseA = Promise.resolve(); const myPromiseB = Promise.resolve(); const promises = [myPromiseA, myPromiseB]; // Act trackPromise(myPromiseA); trackPromise(myPromiseB); // Assert return Promise.all(promises).then(() => { expect(emitter.emit).toHaveBeenCalledTimes(4); }); }); });
true
63899300a6739c6b2adf5725c824bc76fd5ff57c
JavaScript
nvlled/ddcsum
/tools/genformat.js
UTF-8
1,053
2.71875
3
[]
no_license
Promise = require("bluebird"); const fs = Promise.promisifyAll(require("fs")); const process = require("process"); async function writeJson(summary) { let json = JSON.stringify(summary, null, 4); await fs.writeFileAsync("data.json", json); } function writeSqlite(summary) { // TODO: } async function main() { let filename = process.argv.slice(2)[0] || "data.txt"; let lines = []; try { let contents = await fs.readFileAsync(filename, "utf-8"); lines = contents.split(/\n+/); } catch (e) { console.error("unable to read file: " + filename); return; } let summary = {}; for (let line of lines) { let [_, classNum, heading] = line.match(/^(\d+) (.*)$/) ||[]; if (!classNum || !heading) continue; let heading_ = summary[classNum]; if (heading_) { console.warn(`duplicate entry for ${classNum}, overwrite ${heading_} -> ${heading}`); } summary[classNum] = heading; } writeJson(summary); } main();
true
5c291f4849b3f9d3480c39701bd97930aa533e56
JavaScript
sunesimonsen/chance-generators
/src/createGeneratorFacade.js
UTF-8
595
2.59375
3
[ "MIT" ]
permissive
const createGeneratorFacade = Generator => { const generatorFacade = (...args) => new Generator(...args); const defaultGenerator = new Generator(); generatorFacade.isGenerator = true; generatorFacade.generatorName = defaultGenerator.generatorName; [ "expand", "first", "generate", "map", "shrink", "take", "toString", "values" ].forEach(method => { if (defaultGenerator[method]) { generatorFacade[method] = defaultGenerator[method].bind(defaultGenerator); } }); return generatorFacade; }; module.exports = createGeneratorFacade;
true
7dff4ecf8e064a36b97cd96a1eea87701a581591
JavaScript
themtrx/SoftwareUniversity
/JS Advanced/Exam prep/Exam - 07 July 2019/01. SoftDo_Ресурси/scripts/index.js
UTF-8
5,014
3.078125
3
[]
no_license
// NOTE: The comment sections inside the index.html file is an example of how suppose to be structured the current elements. // - You can use them as an example when you create those elements, to check how they will be displayed, just uncomment them. // - Also keep in mind that, the actual skeleton in judge does not have this comment sections. So do not be dependent on them! // - Тhey are present in the skeleton just to help you! // This function will be invoked when the html is loaded. Check the console in the browser or index.html file. function mySolution(){ let msgArea = document.querySelector('#inputSection textarea'); let inputName = document.querySelector('#inputSection div input[type="username"]'); let sendBtn = document.querySelector('#inputSection div button'); let pendingParent = document.querySelector('#outputSection #pendingQuestions'); let openParent = document.querySelector('#outputSection #openQuestions') sendBtn.addEventListener('click', askQuestion); function askQuestion () { let pendingWrap = document.createElement('div'); pendingWrap.setAttribute('class', 'pendingQuestion'); pendingParent.appendChild(pendingWrap); let userImg = document.createElement('img'); userImg.setAttribute('src', './images/user.png'); userImg.setAttribute('width', 32); userImg.setAttribute('height', 32); pendingWrap.appendChild(userImg); let userName = document.createElement('span'); let actualName = inputName.value?inputName.value:'Anonymous'; userName.textContent = actualName; pendingWrap.appendChild(userName); let pendingMsg = document.createElement('p'); pendingMsg.textContent = msgArea.value; pendingWrap.appendChild(pendingMsg); let buttonParent = document.createElement('div'); buttonParent.setAttribute('class', 'actions'); pendingWrap.appendChild(buttonParent); let btnArchive = document.createElement('button'); btnArchive.setAttribute('class', 'archive'); btnArchive.textContent = 'Archive'; buttonParent.appendChild(btnArchive); btnArchive.addEventListener('click', archiveQuestion); let btnOpen = document.createElement('button'); btnOpen.setAttribute('class', 'open'); btnOpen.textContent = 'Open'; buttonParent.appendChild(btnOpen); btnOpen.addEventListener('click', openQuestion); msgArea.value = ''; inputName.value = ''; } function archiveQuestion () { this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); } function openQuestion() { let wholeQuestion = this.parentNode.parentNode; wholeQuestion.setAttribute('class', 'openQuestion'); let actionDiv = this.parentNode; let actionButtons = Array.from(wholeQuestion.querySelectorAll('button')); for (const btn of actionButtons) { actionDiv.removeChild(btn) } let replyBtn = document.createElement('button'); replyBtn.setAttribute('class', 'reply'); replyBtn.textContent = 'Reply'; actionDiv.appendChild(replyBtn); let replySection = document.createElement('div'); replySection.setAttribute('class', 'replySection'); replySection.setAttribute('style', 'display: none;'); wholeQuestion.appendChild(replySection); let replyInput = document.createElement('input'); replyInput.setAttribute('class', 'replyInput'); replyInput.setAttribute('type', 'text'); replyInput.setAttribute('placeholder', 'Reply to this question here...'); replySection.appendChild(replyInput); let sendBtn = document.createElement('button'); sendBtn.setAttribute('class', 'replyButton'); sendBtn.textContent = 'Send'; replySection.appendChild(sendBtn); sendBtn.addEventListener('click', replyQuestion); let replyList = document.createElement('ol'); replyList.setAttribute('class', 'reply'); replyList.setAttribute('type', '1'); replySection.appendChild(replyList); replyBtn.addEventListener('click', () => { if(replySection.style.display === 'block'){ replySection.style.display = 'none'; replyBtn.textContent = 'Reply' }else { replySection.style.display = 'block'; replyBtn.textContent = 'Back' } }); openParent.appendChild(wholeQuestion); } function replyQuestion(){ let answerList = this.parentNode.querySelector('ol'); let answerInput = this.parentNode.querySelector('input[type="text"]'); let answerElement = document.createElement('li'); answerElement.textContent = answerInput.value; answerList.appendChild(answerElement); answerInput.value = ''; } }
true
18eb4c38913ce3d574c862c0705f329cb2746bb3
JavaScript
hongqizhang/hongqizhang.github.io
/js/newscenter.js
UTF-8
5,034
2.96875
3
[]
no_license
$(function(){ //获取浏览器可视窗口的宽和高 // (function(){ // //有坑,不能用document.body.clientWidth document.body.clientHeight // var innerHeight1 = document.documentElement.clientHeight; // var innerWidth1 = document.documentElement.clientWidth; // //让轮播图大小适应不同的浏览器第一屏 // $(".header").css({"height":innerHeight1,"width":innerWidth1}); // })(); // //顶部的banner的高度 // $(".headimg").css("height",document.documentElement.clientHeight-80); //导航栏下划线移动 //鼠标放上去下划线跑动 $(".nav-ul li").on("mouseover",function(){ $(".underline").stop().animate({ "margin-left":$(this).index()*132 },300); }); //如果不点击,鼠标离开下划线回到第初始位置 $(".nav-ul li").on("mouseout",function(){ $(".underline").stop().animate({ "margin-left":132 },600); }); //newsout没有高度 子元素浮动后,他就高度跨了 内部元素撑不开,设置newsout的高度 $(".newsout").height($(".news-right").outerHeight()-0 + 40); $(".newscontent").height($(".news-right").outerHeight()); //设置news-right-list的高度,由于浮动 失去了高度,手动改变的高度 //由于高度是由图片和文字撑开,所以先必须判断谁的高度大,就取谁的高度 (function(){ var listHeight = 0; listHeight = $(".news-right-listimg").outerHeight(true) > $(".news-right-listtitle").outerHeight(true)- 0 +$(".news-right-listword").outerHeight(true) ? $(".news-right-listimg").outerHeight(true):$(".news-right-listtitle").outerHeight(true)- 0 +$(".news-right-listword").outerHeight(true); $(".news-right-list").height(listHeight); })(); //请求数据 // $.ajax({ // type:"get", // url:"../data/companynews.json", // async:true, // success:function(res){ // seteData(res.data); // console.log(res.data); // }, // error:function(){ // alert("请求数据失败!!"); // } // }); //测试选择器的下标 // console.log($(".news-right-list").find("p").eq(0).html()); //处理数据的函数 // function seteData(arr){ // var newslistHeight; // for (var i = 0; i < arr.length; i++) { // var newslist = $("<div><img/ ><p><a></a></p><p></p></div>").addClass("news-right-list"); // newslist.find("img").attr("src",arr[i].pic).addClass("news-right-listimg"); // newslist.find("p").eq(0).addClass("news-right-listtitle").text(arr[i].title); // newslist.find("p").eq(1).addClass("news-right-listword").text(arr[i].word); // $(".news-right").append(newslist); // //判断谁高 // var listHeight = 0; // listHeight = $(".news-right-listimg").outerHeight(true) > $(".news-right-listtitle").outerHeight(true)- 0 +$(".news-right-listword").outerHeight(true) ? $(".news-right-listimg").outerHeight(true):$(".news-right-listtitle").outerHeight(true)- 0 +$(".news-right-listword").outerHeight(true); // //把最高的值付给list // $(".news-right-list").height(listHeight); // //ul的高度累加 // newslistHeight +=listHeight; // } // //把最终的高度赋给ul // $(".news-right").height(newslistHeight); // // //newsout没有高度 子元素浮动后,他就高度跨了 内部元素撑不开,设置newsout的高度 // $(".newsout").height($(".news-right").outerHeight()-0 + 40); // // $(".newscontent").height($(".news-right").outerHeight()); // } //地图API封装函数 function showMap(long,lat){ var map = new BMap.Map("myMap"); var point = new BMap.Point(long, lat); map.centerAndZoom(point, 17); map.enableScrollWheelZoom(); map.addControl(new BMap.NavigationControl()); map.addControl(new BMap.ScaleControl()); map.addControl(new BMap.OverviewMapControl()); map.addControl(new BMap.MapTypeControl()); map.setCurrentCity("北京"); var marker = new BMap.Marker(point); // 创建标注 map.addOverlay(marker); marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画 // // var opts = { // width : 250, // 信息窗口宽度 // height: 100, // 信息窗口高度 // title : "贵州泛联科技有限公司" // 信息窗口标题 // // } // var infoWindow = new BMap.InfoWindow("World", opts);// 创建信息窗口对象 // map.openInfoWindow(infoWindow, map.getCenter()); // // 打开信息窗口 } //点击按钮,地图显示 $(".clickmap1").click(function(){ $(".coverWrap").show(); showMap(106.651187,26.624632) $("body").css("overflow","hidden"); }); $(".clickmap2").click(function(){ $(".coverWrap").show(); $("body").css("overflow","hidden"); showMap(116.317672,40.0432) }); //点击关闭,地图隐藏 $(".closeCover").click(function(){ $(".coverWrap").hide(); $("body").css("overflow","auto"); }); });
true
c05d27f6306f3d7bf84dd7952b306bdf2ee6b6eb
JavaScript
mayankmandloi/sugamsurajangular
/newToDo/main.js
UTF-8
349
2.734375
3
[]
no_license
var task1={ id:0, title:"Some Task", description:"detailed description of our task", creationdate:new Date(), enddate: new Date("2018-01-20"), status:false }; function createTask(id,title,description,enddate) { this.id=id; this.title=title; this.description=description; this.creationdate= new Date(); this.enddate=enddate; this.status=false; }
true
c1612d6bcdbc15bc36dbdcf6a6b155444c3ce227
JavaScript
sonhero981/Homework
/ss3/homework2.js
UTF-8
618
3.296875
3
[]
no_license
//Bài5 Đăng nhập // let username = ''; // let password = ''; // while (username !== 'mindx'|| password !=='codethechange'){ // username = prompt('Nhap username: '); // password = prompt('Nhap password: '); // if (username !== 'mindx'){ // alert('username sai '); // } else if (password!== 'codethechange'){ // alert('Password sai'); // } else{ // alert('Dang nhap thanh cong'); // break;//de dung vong lap // } // } //Phạm vi của biến: giá trị của biến chỉ có tác dụng trong 1 {}. let n = 10; if( n > 2 ){ let n = 20; console.log(n); }
true
f1cf23227189d3065b4bd8c553a1474bfa600d51
JavaScript
putrairawan992/ecommerce-prototype
/src/hoc/withApiMethod.jsx
UTF-8
2,452
2.640625
3
[]
no_license
import React, { Component } from "react"; import { fetchDataService } from "../api/services"; // getMethod, getMethodWithoutParam, fetchData, // import { compose } from "redux"; // import { connect } from "react-redux"; const withApiMethod = WrappedComponent => { class WithApiMethod extends Component { constructor(props) { super(props); this.state = { loading: false, error: [], responseGet: [], responsePost: [], responseUpdate: [], responseDelete: [] }; this.method = { GET: "GET", POST: "POST", PATCH: "PATCH", DELETE: "DELETE" }; } // componentWillUnmount(){ // this.doGet() // } doGet = (url, payload) => { this.fetchData(url, this.method.GET, payload); }; doPost = (url, payload) => { this.fetchData(url, this.method.POST, payload); }; doUpdate = (url, payload) => { this.fetchData(url, this.method.PATCH, payload); }; doDelete = (url, payload) => { this.fetchData(url, this.method.DELETE, payload); }; responseMethod = (method, response) => { switch(method){ case this.method.GET : return {responseGet : response.data, loading: false} case this.method.POST : return {responsePost : response.data, loading: false} case this.method.PATCH : return {responseUpdate : response.data, loading: false} case this.method.DELETE : return {responseDelete : response.data, loading: false} default : } } fetchData = async (url, method, payload) => { const request = { method: method, url: url, data: payload }; this.setState({loading: true}); try { const response = await fetchDataService(request); this.setState(this.responseMethod(method, response)); } catch (error) { this.setState({ error: error, loading: false }); } }; render() { const { data, responsePost, error } = this.state; return ( <WrappedComponent data={data} error={error} responsePost={responsePost} doPost={this.doPost} doGet={this.doGet} {...this.props} /> ); } } return WithApiMethod; }; export default withApiMethod;
true
e28a55863520053c626aaf05875ee844c13fa804
JavaScript
benzed3/FriendFinder
/app/data/friends.js
UTF-8
279
2.609375
3
[]
no_license
var friendsArray = [ { friendName: "Edward", photo: "", scores: [3, 4, 1, 5, 4, 4, 4, 4, 5, 3] } ]; console.log(friendsArray); // Note how we export the array. This makes it accessible to other files using require. module.exports = friendsArray;
true
2e1fce9a946b0f54f5a74814603721433a38c72d
JavaScript
jonsullivan/aws-ec2
/index.js
UTF-8
5,242
2.546875
3
[ "MIT" ]
permissive
var aws = require('aws-lib'); function processInstanceDescription(err, response, callback) { var instance; try { instance = response.reservationSet.item.instancesSet.item; } catch (e) { err = 'Could not find instance: ' + err; instance = response; } callback(err, instance); } module.exports = function (awsKey, awsSecretKey) { var ec2 = aws.createEC2Client(awsKey, awsSecretKey); //the api version that this library defaults to is ancient and doesn't support things like tagging //so let's specify a more recent version ec2.version = '2011-12-15'; function launchOnDemandInstances(params, callback) { var options = { 'ImageId':params.ami, 'MinCount':1, 'MaxCount':params.numToLaunch, 'Placement.AvailabilityZone':params.awsZone, 'InstanceType':params.instanceType }; //specify the security groups to launch in for (var i = 0; i < params.securityGroups.length; i++) { options['SecurityGroup.' + (i + 1)] = params.securityGroups[i]; } ec2.call('RunInstances', options, function (err, response) { //make sure we have an instance set in the response and return that if (!response.instancesSet) { err = 'Failure launching instance(s): ' + err; } else { response = response.instancesSet; } callback(err, response); }); } function launchSpotInstances(params, callback) { var options = { 'SpotPrice':params.spotPrice, 'InstanceCount':params.numToLaunch, 'LaunchSpecification.ImageId':params.ami, 'LaunchSpecification.InstanceType':params.instanceType, 'LaunchSpecification.Placement.AvailabilityZone':params.awsZone }; //specify the security groups to launch in for (var i = 0; i < params.securityGroups.length; i++) { options['LaunchSpecification.SecurityGroup.' + (i + 1)] = params.securityGroups[i]; } ec2.call('RequestSpotInstances', options, function (err, response) { //make sure we have a valid state and return the response if (!response.spotInstanceRequestSet) { err = 'Failed to issue spot instance request \n ' + err; } else { response = response.spotInstanceRequestSet.item; if (response.state == 'cancelled' || response.state == 'failed') { err = ' error issue spot instance request fault code is: ' + response.fault; } } callback(err, response); }); } function getInstances(filters, callback) { ec2.call('DescribeInstances', filters, function (err, response) { var instances = [], reservationSet; try { reservationSet = response.reservationSet.item; for (var i = 0; i < reservationSet.length; i++) { if (reservationSet[i].instancesSet.item instanceof Array) { for (var j = 0; j < reservationSet[i].instancesSet.item.length; j++) { instances.push(reservationSet[i].instancesSet.item[j]); } } else { instances.push(reservationSet[i].instancesSet.item); } } } catch (e) { err = 'No instances found: ' + e + ' - ' + err; instances = response; } callback(err, instances); }); } function getInstanceDescriptionFromPrivateIp(privateIp, callback) { ec2.call('DescribeInstances', {'Filter.1.Name':'private-ip-address', 'Filter.1.Value':privateIp}, function (err, response) { processInstanceDescription(err, response, callback); }); } function getInstanceDescriptionFromId(instanceId, callback) { ec2.call('DescribeInstances', {'Filter.1.Name':'instance-id', 'Filter.1.Value':instanceId}, function (err, response) { processInstanceDescription(err, response, callback); }); } function describeSpotInstanceRequest(requestId, callback) { ec2.call('DescribeSpotInstanceRequests', {'Filter.1.Name':'spot-instance-request-id', 'Filter.1.Value':requestId}, function (err, response) { if (!response.spotInstanceRequestSet) { err = ' Failed to find spot instance request: ' + requestId + ' ' + err; } else { response = response.spotInstanceRequestSet.item; } callback(err, response); }); } function terminateEc2Instance(instanceId, callback) { ec2.call('TerminateInstances', {'InstanceId.1':instanceId}, function (err, response) { var result; try { result = response.instancesSet.item.currentState.name; } catch (e) { err = 'Failure terminating instance: ' + instanceId + ' ' + err; } if (!err && result != 'shutting-down') { err = 'Instance is not termimating '; } callback(err, response); }); } function cancelSpotRequest(requestId, callback) { ec2.call('CancelSpotInstanceRequests', {'SpotInstanceRequestId.1':requestId}, function (err, response) { if (!response.spotInstanceRequestSet) { err = 'Failed to cancel spot request: ' + requestId + ' ' + err; } else { response = response.spotInstanceRequestSet.item; } callback(err, response); }); } return { launchOnDemandInstances:launchOnDemandInstances, launchSpotInstances:launchSpotInstances, getInstanceDescriptionFromPrivateIp:getInstanceDescriptionFromPrivateIp, getInstanceDescriptionFromId:getInstanceDescriptionFromId, getInstances:getInstances, describeSpotInstanceRequest:describeSpotInstanceRequest, terminateEc2Instance:terminateEc2Instance, cancelSpotRequest:cancelSpotRequest } }
true
ea05989ce14e84b6ea11e2599621003a8496079b
JavaScript
kvlinden-courses/cs336-code
/unit06-http/server.js
UTF-8
2,124
2.734375
3
[]
no_license
/** * This implements some HTTP method/code, form and cookie examples. */ const express = require('express'); const app = express(); const http_status = require('http-status-codes'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const HOST = "localhost"; const PORT = 3000; app.use(express.static('public')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); // -------------------------------- // HTTP route and return code examples. // These routes respond to non-GET requests. app.put('/', function(req, res) { res.send("Hello, PUT!"); }); app.post('/', function(req, res) { res.send("Hello, POST!"); }); app.delete('/', function(req, res) { res.send("Hello, DELETE!"); }); // This rejects access to this "lost" resource. app.get('/lost', function(req, res) { res.sendStatus(http_status.NOT_FOUND); }); // This creates a redirect. app.get('/redirect', function(req, res) { res.redirect('/redirect.html'); }); // This creates a server error. app.get('/broken', function(req, res) { res.send(1/0); }); // -------------------------------- // HTTP form example // Responds to form posts from the forms/index.html example. app.post('/forms', function(req, res) { res.send('Hello, form POST!<br>Posted message: <code>' + req.body.user_message + '</code>'); }); // -------------------------------- // HTTP cookies examples // This implements routes to list/create/delete cookies. app.get("/cookies", function(req, res) { let cookieMessage = 'cookieName not set...'; if (req.cookies.cookieName) { cookieMessage = "cookieName: " + req.cookies.cookieName; } res.send("Hello, cookies!<br> " + cookieMessage); }); app.get("/cookies/set", function(req, res) { res.cookie("cookieName", "cookieValue"); res.send("Cookie is set."); }); app.get("/cookies/clear", function(req, res) { res.clearCookie("cookieName"); res.send("Cookie is deleted."); }); app.listen(PORT, HOST, () => { console.log("listening on " + HOST + ":" + PORT + "..."); });
true
7631ad508b9e6b692fd44809c944229d4f6741f8
JavaScript
virtorodrigues/listing-github-repositories
/src/pages/main/index.js
UTF-8
2,064
2.53125
3
[]
no_license
import React, { useState, useEffect } from 'react' import './styles.css' import logo from '../../assets/logo.svg' import { apiRepos } from '../../service/api' import loadingImg from '../../assets/spinner.gif' import ListRepository from '../../components/listRepository' export default function Main({ match, history }) { const [ repos, setRepos ] = useState([]) const [ reposOrigin, setReposOrigin ] = useState([]) const [ search, setSearch ] = useState('') const [ loading, setLoading ] = useState(true) useEffect(() => { async function loadData(){ const response = await apiRepos.get(match.params.id) setReposOrigin(response.data.items) setRepos(response.data.items) setLoading(false) } loadData() }, [match.params.id]) useEffect(() => { async function loadRepo(){ const result = reposOrigin.length>0 && reposOrigin.filter((repo) => repo.name.toUpperCase().includes(search.toUpperCase()) ) setRepos(result) } loadRepo() }, [search, reposOrigin]) function goToSearch(e) { e.preventDefault() history.push(`/`) } return ( <div className='main-container'> { loading && <img src={loadingImg} alt='loading' /> || <> <img src={logo} alt='logo' /> <div className='detail-user'> <h1>Voce pesquisou por: { match.params.id } </h1> <div> <button onClick={goToSearch} type="submit">Nova busca</button> <input onChange={e => setSearch(e.target.value)} placeholder="Filtrar repositório"/> </div> </div> <ListRepository repository={repos} /> </> } </div> ) }
true
07932a8f7c8208274f0a53388a0d26c87f8399d2
JavaScript
KirillLitvinenko/slot
/script.js
UTF-8
6,548
2.75
3
[]
no_license
const ROWS = 3; const COLS = 3; const SPIN_DURATION = 2000; //duration in ms const STOP_DELAY = 500; // stop delay in ms let testMatrix = []; let testModeBlockShow = false; function createTestModeView() { let testModeElement = $('#test-reels'); let template = $('#reel').html(); let generatedHtml = ''; for (let i = 0; i < COLS; i++) { let clone = $(template); clone.find('#reel-position').attr('id', 'reel-position-' + i); clone.find('#reel-value').attr('id', 'reel-value-' + i); generatedHtml = generatedHtml + clone.get(0).outerHTML; } testModeElement.append(generatedHtml); $('.select-position').change(function() { $(this).parent().find('.select-value').attr('disabled', parseInt($(this).val()) < 0) }); } function generateTestMatrix() { testMatrix = []; let rowNumber, cellValue; for (let i = 0; i < COLS; i++) { rowNumber = parseInt($('#reel-position-' + i).val()); cellValue = parseInt($('#reel-value-' + i).val()); testMatrix.push({row: rowNumber, cellValue: cellValue}); } } function generateSpinResult() { let resultMatrix = []; for (let i = 0; i < ROWS; i++) { resultMatrix[i] = []; for (let j = 0; j < COLS; j++) { resultMatrix[i][j] = Math.floor(Math.random() * 5); } } return resultMatrix; } function createView() { let generatedHtml = ''; let generatedColumnsHtml = ''; for (let i = 0; i < COLS; i++) { let itemsInColumn = 0; let firstLastClass = ''; while (itemsInColumn < ROWS) { if (i === 0) { firstLastClass = 'firstInARow'; } else if (i === ROWS - 1) { firstLastClass = 'lastInARow'; } generatedHtml += ('<div class="cell ' + firstLastClass + '" id="cell-' + itemsInColumn + i + '"></div>'); itemsInColumn++; } generatedColumnsHtml += ('<div class="column" id="column-' + i + '">' + generatedHtml + '</div>'); generatedHtml = ''; } $('#rotate').append(generatedColumnsHtml); } function spin(type) { let resultToView = generateSpinResult(); // change random results with test values if any if (testModeBlockShow && testMatrix.length && type === 'result') { for (let i = 0; i < testMatrix.length; i++) { if (testMatrix[i].row >= 0) { resultToView[testMatrix[i].row][i] = testMatrix[i].cellValue; } } } for (let i = 0; i < resultToView.length; i++) { for (let j = 0; j < resultToView[i].length; j++) { let currentCell = $('#cell-' + i + j); currentCell.removeClass('win-row'); // where 141 -- image width, 20 -- double sprite margin, 10 -- first margin in sprite currentCell.css('background-position-x', -((141 * resultToView[i][j]) + (20 * resultToView[i][j]) + 10)) } } if (type === 'result') { setDisabledStateOnInputs(true); $('.column').addClass('column-animated'); addSubtractMoneyAmount(-1); $('#win-sum-text').text('').removeClass('blinking-text'); let timeout = setTimeout(function() { endSpin(resultToView, timeout) }, SPIN_DURATION); } } // check if win combination is three same items and return item value if so ro -1 if not function threeInARowCheck(row) { return row.every(function(element) { return element === row[0]; }) ? row[0] : -1; } function styleRowOnWin(winRow) { for (let i = 0; i < COLS; i ++) { $('#cell-' + winRow + i).addClass('win-row'); } } // manual changing amount of money function changeMoneyAmount() { let moneyInputElement = $('#money-input'); let money = 0; moneyInputElement.change(function() { money = parseInt(moneyInputElement.val()); $('#start-spin').attr('disabled', money < 0); }); } function addSubtractMoneyAmount(sum) { let moneyInputElement = $('#money-input'); let moneyAmount = parseInt(moneyInputElement.val()); moneyInputElement.val((moneyAmount + sum).toString()); } function calculateWin(resultMatrix) { let stakeRow = $('#stake-row').val(); let winSum = 0; let threeInARow = threeInARowCheck(resultMatrix[stakeRow]); if (threeInARow !== -1) { switch (threeInARow) { case 0: winSum = 20; break; case 1: winSum = 50; break; case 2: if (stakeRow === '0') { winSum = 2000; } else if (stakeRow === '1') { winSum = 1000; } else { winSum = 4000; } break; case 3: winSum = 10; break; case 4: winSum = 150; break; default: winSum = 0; break; } } else { let cherryAndSeven = resultMatrix[stakeRow].every(function(element) { return ![0, 1, 3].includes(element); // only cherry and 7 in row }); let bars = resultMatrix[stakeRow].every(function(element) { return ![2,4].includes(element); // only bars in row }); if (cherryAndSeven) { winSum = 75; } else if (bars) { winSum = 5; } else { winSum = 0; } } return winSum; } function endSpin(resultMatrix, timeout) { let stakeRow = $('#stake-row').val(); let winSum = calculateWin(resultMatrix); $('.column').each(function(index) { (function(that, i) { setTimeout(function() { $(that).removeClass('column-animated'); }, STOP_DELAY * i); })(this, index); }); setTimeout(function() { if (winSum > 0) { styleRowOnWin(stakeRow); addSubtractMoneyAmount(winSum); $('#win-sum-text').text(winSum).addClass('blinking-text'); } setDisabledStateOnInputs(false); clearTimeout(timeout); }, STOP_DELAY * COLS - 1); } function setDisabledStateOnInputs(state) { $('#start-spin').attr('disabled', state); $('#money-input').attr('disabled', state); $('#stake-row').attr('disabled', state); $('#test-mode').attr('disabled', state); } $(document).ready(function() { createTestModeView(); $('#generate-test').click(function() { generateTestMatrix(); $('#test-mode-sign').removeClass('hide'); }); $('#test-mode').change(function(event) { let hiddenFieldElement = $('#hidden-field'); let testModeSign = $('#test-mode-sign'); if ($(event.target).is(':checked')) { hiddenFieldElement.removeClass('hide'); testModeBlockShow = true; testMatrix.length && testModeSign.removeClass('hide'); } else { hiddenFieldElement.addClass('hide'); testModeBlockShow = false; testModeSign.addClass('hide'); } }); $('#start-spin').click(function() {spin('result')}); changeMoneyAmount(); createView(); spin(); });
true
58ff340dfb808aa2a4a8b586f9bd9366479012ea
JavaScript
bluebrid/base-knowledge
/javascript/advance/Nodejs/9.AsyncHooks全链路信息/demo.3/AsyncLocalStorage.js
UTF-8
1,885
2.8125
3
[]
no_license
// AsyncLocalStorage.js const asyncHooks = require('async_hooks'); const { executionAsyncId } = asyncHooks; class AsyncLocalStorage { constructor() { this.storeMap = new Map(); // {1} this.createHook(); // {2} } createHook() { const ctx = this; const hooks = asyncHooks.createHook({ /** * * @param {*} asyncId 异步资源唯一ID * @param {*} type 异步资源的类型 * @param {*} triggerAsyncId 当前异步资源是由那个异步资源创建的异步资源ID * @param {*} resource 初始化的异步资源 */ init(asyncId, type, triggerAsyncId, resource) { // https://www.imooc.com/article/314713 详细说明 if (ctx.storeMap.has(triggerAsyncId)) { ctx.storeMap.set(asyncId, ctx.storeMap.get(triggerAsyncId)); } }, /** * 当启动异步操作或完成异步操作是,系统将会调用回调来通知用户,也就是我们的业务回调函数,在这之前会先触发before回调 * @param {*} asyncId */ before(asyncId) { console.log(asyncId) }, /*** * 当asyncId 对应的异步资源被销毁时调用destory 回调,用来垃圾回收 */ destroy(asyncId) { ctx.storeMap.delete(asyncId); } }); // 因为Promise默认是没有开启的,通过显示调用可以开启Promise的异步调用 hooks.enable(); } run(store, callback) { // {3} this.storeMap.set(executionAsyncId(), store); callback(); } getStore() { // {4} return this.storeMap.get(executionAsyncId()); } } module.exports = AsyncLocalStorage;
true
dcc273434681f08d423b41ddd86a8442ebfacd61
JavaScript
linkesch/psd.js
/lib/psd/nodes/search.js
UTF-8
925
2.59375
3
[ "MIT" ]
permissive
// Generated by CoffeeScript 1.7.1 (function() { var clone, flatten; clone = require('lodash/clone'); flatten = require('lodash/flatten'); module.exports = { childrenAtPath: function(path, opts) { var matches, query; if (opts == null) { opts = {}; } if (!Array.isArray(path)) { path = path.split('/').filter(function(p) { return p.length > 0; }); } path = clone(path); query = path.shift(); matches = this.children().filter(function(c) { if (opts.caseSensitive) { return c.name === query; } else { return c.name.toLowerCase() === query.toLowerCase(); } }); if (path.length === 0) { return matches; } else { return flatten(matches.map(function(m) { return m.childrenAtPath(clone(path), opts); })); } } }; }).call(this);
true
832ba72b2a80fe9b40f0839d9e97e5100ce29d83
JavaScript
batar/tutorial-udemy
/js/03 - Weitere Grundlagen/Aufgabe-Strings.js
UTF-8
1,939
3.296875
3
[]
no_license
"use strict" let shopping = " Apfel, Pfirsich, +++Avocado, Mango " // Bei einer Einkaufsliste haben sich ein paar Fehler // eingeschlichen. Unsere Texterkennung des Scans hat ein // paar Leerzeichen zu viel erkannt, sowie ein paar // Plus-Zeichen eingelesen, die im Original gar nicht // existieren. Das möchten wir korrigieren! // Aufgabe 1: Entferne die Leerzeichen links und rechts, und // schreibe das Ergebnis zurück in die Variable "shopping" // Aufgabe 2: Finde die Position der drei Plus-Zeichen, und // speichere diese in einer Variablen // Aufgabe 3: Schneide die 3 Plus-Zeichen aus und gebe das // Ergebnis mit einem console.log aus. // Verwende dazu einmal die .substr()-Funktion, und einmal // die .slice()-Funktion // // Es soll ausgegeben werden: "Apfel, Pfirsich, Avocado, Mango" // Tipp: Du wirst hierzu 2 Aufrufe der jeweiligen Funktionen // benötigen - einmal bis hin zu den +++-Zeichen, und einmal // für das Stück danach! // Aufgabe 4: Schneide die 3 Plus-Zeichen aus. Verwende dazu // die .replace()-Funktion! // Aufgabe 5: Jetzt soll die Shopping-Liste ausgegeben werden. // Wandle die Liste in folgendes Schreibweise um. Platziere // auch die 2 Striche über / unter der Auflistung, und verwende // dazu die .repeat()-Funktion! // // -------------------- // Einkaufsliste: // - Apfel // - Birne // - Avocado // - Mango // -------------------- // // Tipp: Du kannst z.B. mit Hilfe der .replace()-Funktion immer nur ein // Komma in einen Zeilenumbruch inklusive Bindestrich umwandeln. // // Jetzt hier ist es vollkommen okay, wenn du daher .replace() mehrfach // hintereinander aufrufst, bis alle Kommas in umgewandelt wurden: // >> shopping.replace(...).replace(...).replace(...) // // Später lernst du hierfür auch noch eine "elegantere" Methode kennen. // // Du darfst wahlweise alles in einem console.log()-Aufruf ausgeben, // oder auch mehrere console.log()-Aufrufe verwenden.
true
1f10d0faf4aa7d873b0a1d944be4f4472eae3a53
JavaScript
6pm/conway-game-of-life
/src/js/modules/gameOfLife/index.js
UTF-8
13,931
3.296875
3
[]
no_license
// export default class GameOfLife class GameOfLife { constructor(selector, options = {}) { this.itemWidth = options.itemWidth || 15 this.gameSize = options.gameSize || 200 this.state = options.state || this.getInitialState(this.gameSize) this.selector = selector this.loop = false this.ifPlaying = false this.generation = 0 this.interval = 2000 this.history = [] this.ctx = this.initCanvas(selector) this.renderNavigation() this.renderGenerationTitle() this.renderItems() this.renderHistory() } /** * Створити початковий стан гри, де всі клітинки будуть пустими * @param {Number} gameSize - число клітинок в довжину і ширину * @return {Array} - двохмірний массив, заповнений нулями */ getInitialState(gameSize) { return Array(gameSize).fill(0).map(() => Array(gameSize).fill(0)) } /** * Створити заповнену(живу) клітинку по координатам * @param {Number} row - координата рядка, в якому знаходиться необхідна клітинка * @param {Number} cell - координата стовбця клітинки */ drawFilledCell(row, cell) { this.ctx.fillStyle = '#28b929' this.ctx.fillRect(cell * this.itemWidth + 2, row * this.itemWidth + 2, this.itemWidth - 2, this.itemWidth - 2) } /** * Створити пусту(мертву) клітинку по координатам * @param {Number} row - координата рядка, в якому знаходиться необхідна клітинка * @param {Number} cell - координата стовбця клітинки */ drawEmptyCell(row, cell) { this.ctx.fillStyle = 'black' this.ctx.fillRect(cell * this.itemWidth, row * this.itemWidth, this.itemWidth, this.itemWidth) this.ctx.clearRect(cell * this.itemWidth + 1, row * this.itemWidth + 1, this.itemWidth - 1, this.itemWidth - 1) } /** * Почати гру і зберегти setInterval в середині обєкта, щоб в майбутньому можна було його зупинити. * @param {Number} interval - інтервал в ms, через яке буде гереруватись нове покоління */ startGameLoop(interval) { this.ifPlaying = true this.selector.classList.add('gol-playing') this.loop = setInterval(() => { this.makeGeneration() this.generation += 1 this.updateGenerationCounter() }, interval) } /** * Зупинити гру, очистити setInterval. */ stopGame() { this.ifPlaying = false this.selector.classList.remove('gol-playing') clearInterval(this.loop) } /** * Створити нове покоління на основі попереднього. Перерендерються тільки ті клітинки, * які поміняли стан. */ makeGeneration() { this.state.forEach((row, rowIndex) => { row.forEach((item, cellIndex) => { const parents = this.findParendCount(rowIndex, cellIndex) const ifStayLive = item && parents === 2 || parents === 3 const ifAlive = !item && parents === 3 // якщо клітинка була жива - оживити if (ifStayLive || ifAlive) { this.drawFilledCell(rowIndex, cellIndex) this.state[rowIndex][cellIndex] = 1 } else { // перенаселення this.drawEmptyCell(rowIndex, cellIndex) this.state[rowIndex][cellIndex] = 0 } }) }) } /** * Знайти скільки сусідів має клітинка. * @param {Number} row - координата рядка, на якій знаходиться клітинка * @param {Number} cell - координата стовбця * @return {Number} - кількість сусідів клітинки */ findParendCount(row, cell) { const parentChords = [ {row: row - 1, cell: cell - 1}, {row: row - 1, cell}, {row: row - 1, cell: cell + 1}, {row: row, cell: cell - 1}, // eslint-disable-line no-multi-spaces {row: row, cell: cell + 1}, // eslint-disable-line no-multi-spaces {row: row + 1, cell: cell - 1}, {row: row + 1, cell}, {row: row + 1, cell: cell + 1} ] return parentChords.map((coordinate) => { try { return this.state[coordinate.row][coordinate.cell] || 0 } catch(err) { return 0 } }).reduce((a, b) => a + b) } // ЕВЕНТ ЛІСТЕНЕРИ /** * Лістенер кліка по canvas. Якщо гра не йде, тоді поміняти стан клітинки. * @param {Object} e - івент кліка */ onGameClick(e) { if (this.ifPlaying) return false const row = Math.ceil(e.offsetY / this.itemWidth) - 1 const cell = Math.ceil(e.offsetX / this.itemWidth) - 1 if (this.state[row][cell]) { this.state[row][cell] = 0 this.drawEmptyCell(row, cell) } else { this.state[row][cell] = 1 this.drawFilledCell(row, cell) } } /** * Лістенер кнопки 'start' - запустити гру. */ onStartGame() { if (this.ifPlaying) return false this.ifPlaying = true this.selector.classList.add('gol-playing') this.startGameLoop(this.interval) } /** * Лістенер кнопки 'pause' - поставити гру на паузу, але лічильник для покоління не обнуляти. */ onPauseGame() { this.stopGame() } /** * Лістенер кнопки 'stop' - зупинити гру і обнулити покоління. */ onStopGame() { this.stopGame() this.generation = 0 this.updateGenerationCounter() } /** * Зміна швидкості гри. Зупинити гру, видалити setInterval і почати нову гру з новим інтервалом. */ onTimeIntervalChange(e) { this.interval = e.target.value if (this.ifPlaying) { this.stopGame() this.startGameLoop(this.interval) } } /** * Зміна 'Zoom'. Зупинити гру, заново перерендерити всі елементи з новими розмірами і запустити знову гру. */ onZoomChange(e) { const ifPlaying = this.ifPlaying this.stopGame() this.itemWidth = e.target.value this.renderItems() if (ifPlaying) { this.startGameLoop(this.interval) } } /** * Додати елемент до історії. Зберігається стан гри і покоління. */ saveToHistory() { this.history.push({ // клонування this.state.concat() і this.state.slice(0) не працює, // тому довелось конвертувати в json і потім назад в массив state: JSON.parse(JSON.stringify(this.state)), generation: this.generation }) const item = document.createElement('span') item.classList.add('gol-snapshot') item.setAttribute('data-history-position', this.history.length - 1) item.innerHTML = `Snapshot gen${this.generation}` item.addEventListener('click', this.onSnapshotClick.bind(this)) this.historySelector.appendChild(item) } /** * Відновити стан клітинок і покоління з історії. * @param {Object} e - івент кліка */ onSnapshotClick(e) { this.stopGame() const index = e.target.getAttribute('data-history-position') this.state = this.history[index].state this.generation = this.history[index].generation this.updateGenerationCounter() this.renderItems() } // ***************** // МЕТОДИ РЕНДЕРУ // ***************** /** * Створити тег canvas, добавити його в селектор і повернути контекст. * @param {DOM element} selector - DOM селектор, на якаму був ініціалізований клас * @return {Array} - контекст з canvas */ initCanvas(selector) { const canvasWrapper = document.createElement('div') canvasWrapper.classList.add('gol-canvas-wrap') const canvas = document.createElement('canvas') canvas.width = this.itemWidth * this.gameSize canvas.height = this.itemWidth * this.gameSize canvas.addEventListener('click', this.onGameClick.bind(this)) canvasWrapper.appendChild(canvas) selector.appendChild(canvasWrapper) return canvas.getContext('2d') } /** * Створити клітинки і добавити в canvas. Використовується для повного перезапису всіх клітинок. */ renderItems() { const size = this.itemWidth * this.gameSize const canvas = this.selector.getElementsByTagName('canvas')[0] canvas.width = size canvas.height = size this.ctx.clearRect(0, 0, size, size) this.state.forEach((row, rowIndex) => { row.forEach((item, cellIndex) => { // створити квадрати if (item) { this.drawFilledCell(rowIndex, cellIndex) } else { this.drawEmptyCell(rowIndex, cellIndex) } }) }) } /** * Створити кнопки навігації: 'play', 'pause', 'start', 'stop', 'zoom', 'interval', * і добавити в DOM. */ renderNavigation() { const wrapper = document.createElement('div') wrapper.classList.add('gol-navigation') const startBtn = document.createElement('span') startBtn.setAttribute('title', 'Start game') startBtn.addEventListener('click', this.onStartGame.bind(this)) startBtn.classList.add('gol-start-btn') const pauseBtn = document.createElement('span') pauseBtn.setAttribute('title', 'Pause game') pauseBtn.addEventListener('click', this.onPauseGame.bind(this)) pauseBtn.classList.add('gol-pause-btn') const stopBtn = document.createElement('span') stopBtn.setAttribute('title', 'Stop game') stopBtn.addEventListener('click', this.onStopGame.bind(this)) stopBtn.classList.add('gol-stop-btn') const saveHistoryBtn = document.createElement('button') saveHistoryBtn.innerHTML = 'Save snapshot' saveHistoryBtn.classList.add('gol-save-history') saveHistoryBtn.addEventListener('click', this.saveToHistory.bind(this)) const timeInput = this.renderRangeInput('Speed:', this.onTimeIntervalChange.bind(this), this.interval, 2000, 20000, 2000) const zoomInput = this.renderRangeInput('Zoom:', this.onZoomChange.bind(this), this.itemWidth) wrapper.appendChild(startBtn) wrapper.appendChild(pauseBtn) wrapper.appendChild(stopBtn) wrapper.appendChild(timeInput) wrapper.appendChild(zoomInput) wrapper.appendChild(saveHistoryBtn) this.selector.insertBefore(wrapper, this.selector.firstChild) } /** Cтворити DOM елемент з input type="range" * @param {Text} text -назва поля * @param {Function} action - функція, яка буде запускатись на зміну input * @param {Number} value -початкове значення input * @param {Number} min - мінімальне значення * @param {Number} max - максимальне значення * @param {Number} step - крок, за яким буде збільшуватись value * @return {DOM element} - input з заголовком і стилізованими класами */ renderRangeInput(text, action, value = 1, min = 5, max = 25, step = 1) { const timeWrap = document.createElement('div') timeWrap.classList.add('gol-range') const title = document.createElement('span') const titleText = document.createTextNode(text) title.appendChild(titleText) timeWrap.appendChild(title) const timeInput = document.createElement('input') timeInput.addEventListener('change', action) timeInput.setAttribute('type', 'range') timeInput.setAttribute('value', value) timeInput.setAttribute('step', step) timeInput.setAttribute('min', min) timeInput.setAttribute('max', max) timeWrap.appendChild(timeInput) return timeWrap } /** * Обновити число з поколіннями на сторінці. */ updateGenerationCounter() { const generationTitle = document.getElementsByClassName('gol-legend-generation')[0] generationTitle.innerHTML = `Generation: ${this.generation}` } /** * Створити елемент, який буде показувати кількість поколінь гри і добавити його в DOM */ renderGenerationTitle() { const legendWrap = document.createElement('div') legendWrap.classList.add('gol-legend') const generationCounter = document.createElement('span') generationCounter.classList.add('gol-legend-generation') generationCounter.appendChild(document.createTextNode(`Generation: ${this.generation}`)) legendWrap.appendChild(generationCounter) this.selector.insertBefore(legendWrap, this.selector.firstChild) } /** * Створити елемент, який буде відображати збережені покоління і добавити його в DOM */ renderHistory() { const historyWrap = document.createElement('div') historyWrap.classList.add('gol-history') const title = document.createElement('span') title.classList.add('gol-history-title') title.appendChild(document.createTextNode('Saved history:')) const historyItems = document.createElement('div') historyItems.classList.add('gol-history-items') historyWrap.appendChild(title) historyWrap.appendChild(historyItems) this.selector.appendChild(historyWrap) this.historySelector = historyItems } }
true
0f69f5f126970b54d93f259a0400d52601e4dad6
JavaScript
tamerMarzouk/glitch-fccPersonalLibraryAPI
/tests/2_functional-tests.js
UTF-8
6,934
2.890625
3
[]
no_license
/* * * * FILL IN EACH FUNCTIONAL TEST BELOW COMPLETELY * -----[Keep the tests in the same order!]----- * */ var chaiHttp = require('chai-http'); var chai = require('chai'); var assert = chai.assert; var server = require('../server'); var insertedIds=[]; chai.use(chaiHttp); suite('Functional Tests', function() { test(' add a book title POST /api/books', (done)=>{ this.timeout(2000); let title='Book title'; chai.request(server) .post('/api/books') .send({title:title}) .end((err,res)=>{ assert.equal(res.status,200,'HTTP Status should be 200!'); assert.equal(res.body.title,title,'incorrect book title'); assert.isArray(res.body.comments) insertedIds.push(res.body._id); done(); }) }) test(' XSS add a book title POST /api/books', (done)=>{ this.timeout(2000); let title='<script>alert(1)</script>'; chai.request(server) .post('/api/books') .send({title:title}) .end((err,res)=>{ assert.equal(res.status,200,'HTTP Status should be 200!'); assert.equal(res.body.title,'&lt;script&gt;alert(1)&lt;/script&gt;','Possible XSS'); assert.isArray(res.body.comments) insertedIds.push(res.body._id); done(); }) }); /* * ----[EXAMPLE TEST]---- * Each test should completely test the response of the API end-point including response status code! */ test('#example Test GET /api/books', function(done){ chai.request(server) .get('/api/books') .end(function(err, res){ assert.equal(res.status, 200); assert.isArray(res.body, 'response should be an array'); assert.property(res.body[0], 'commentcount', 'Books in array should contain commentcount'); assert.property(res.body[0], 'title', 'Books in array should contain title'); assert.property(res.body[0], '_id', 'Books in array should contain _id'); done(); }); }); test('GET /api/books/:_id', (done)=>{ this.timeout(3000) let id=insertedIds[0]; chai.request(server) .get('/api/books/'+id) .end((err,res)=>{ assert.equal(res.status,200); assert.equal(res.body._id,id,'incorrect data received'); done(); }) }); test('missing book GET /api/books/anything',(done)=>{ this.timeout(3000); chai.request(server) .get('/api/books/anything') .end((err,res)=>{ assert.equal(res.status,404); assert.equal(res.text,'no book exists'); done(); }) }) test('Post comment to book POST /api/books/:id',(done)=>{ this.timeout(3000); let _id=insertedIds[0]; chai.request(server) .post('/api/books/'+_id) .send({comment:'this comment'}) .end((err,res)=>{ assert.equal(res.status,200); assert.isArray(res.body); done(); }) }) test('Post comment to book and confirm data POST /api/books/:id',(done)=>{ this.timeout(3000); let _id=insertedIds[0]; let comment='testing comment 93,' chai.request(server) .post('/api/books/'+_id) .send({comment:comment}) .end((err,res)=>{ assert.equal(res.status,200); assert.isArray(res.body); //now read the comment and make sure it's the same chai.request(server) .get('/api/books/'+_id) .end((err,res)=>{ assert.equal(res.status,200) assert.include(res.body.comments,comment); done(); }) }) }) suite('Routing tests', function() { suite('POST /api/books with title => create book object/expect book object', function() { test('Test POST /api/books with title', function(done) { chai.request(server) .post('/api/books') .send({title:'Routing Test'}) .end((err,res)=>{ assert.equal(res.status,200); done(); }); }); test('Test POST /api/books with no title given', function(done) { chai.request(server) .post('/api/books') .send({}) .end((err,res)=>{ assert.equal(res.status,400); done(); }); }); }); suite('GET /api/books => array of books', function(){ test('Test GET /api/books', function(done){ chai.request(server) .get('/api/books') .end((err,res)=>{ assert.equal(res.status,200); assert.isArray(res.body) done(); }); }); }); suite('GET /api/books/[id] => book object with [id]', function(){ test('Test GET /api/books/[id] with id not in db', function(done){ chai.request(server) .get('/api/books/5d172843a84fc012280eb8c6') .end((err,res)=>{ assert.equal(res.status,404); assert.equal(res.text,'no book exists'); done(); }); }); test('Test GET /api/books/[id] with valid id in db', function(done){ let _id=insertedIds[0]; chai.request(server) .get('/api/books/'+_id) .end((err,res)=>{ assert.equal(res.status,200); assert.isArray(res.body.comments); done(); }); }); }); suite('POST /api/books/[id] => add comment/expect book object with id', function(){ test('Test POST /api/books/[id] with comment', function(done){ let _id=insertedIds[0]; let comment='Testing comment Xyz,' chai.request(server) .post('/api/books/'+_id) .send({comment:comment}) .end((err,res)=>{ assert.equal(res.status,200); assert.isArray(res.body); //now read the comment and make sure it's the same chai.request(server) .get('/api/books/'+_id) .end((err,res)=>{ assert.equal(res.status,200) assert.include(res.body.comments,comment); done(); }) }) }); }); }); suite('Delete API /api/books' , ()=>{ test('Delete book given valid id',done=>{ this.timeout(3000); let _id=insertedIds[0]; chai.request(server) .delete('/api/books/'+_id) .end((err,res)=>{ assert.equal(res.status,200) assert.equal(res.text,'delete successful'); done(); }) }); test('Delete book given non valid id',done=>{ this.timeout(3000); let _id=insertedIds[0]; chai.request(server) .delete('/api/books/'+_id) .end((err,res)=>{ assert.equal(res.status,404) assert.equal(res.text,'not found!'); done(); }) }) //delete all books test('Delete all books',done=>{ this.timeout(3000); chai.request(server) .delete('/api/books') .end((err,res)=>{ assert.equal(res.status,200) assert.equal(res.text,'complete delete successful'); done(); }) }) }) });
true
5f150f9690f92766fca24ce68811ee36a1b1928a
JavaScript
littlehour/littlehour.github.io
/learn-webpack/src/app1.js
UTF-8
274
2.9375
3
[]
no_license
import {cube} from './math.js'; function component(){ var ele=document.createElement('pre'); ele.innerHTML=[ 'hello webpack!', '5 cubed is equal to '+cube(5)+' '+square(5) ].join('\n\n'); return ele; }; document.body.appendChild(component());
true
a28df4c5df8e794c670634e7db0aca3953a3226b
JavaScript
Oslandia/workshop-jitenshea
/jitenshop/webapp/static/city.js
UTF-8
3,533
2.53125
3
[ "MIT" ]
permissive
// Jitenshea functions for the 'city' page // Map with all stations with Leaflet $(document).ready(function() { var tile = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }); var city = document.getElementById("stationMap").dataset.city; var map = L.map("stationMap"); var currentLayer = L.geoJSON(null, { style: function(data) { return { color: d3.interpolateRdYlGn( data.properties.nb_bikes / data.properties.nb_stands ) } }, pointToLayer: function(data, coords) { return L.circleMarker(coords, {radius: 4}) .bindPopup("<ul><li><b>ID</b>: " + data.properties.id + "</li><li><b>Name</b>: " + data.properties.name + "</li><li><b>Stands</b>: " + data.properties.nb_stands + "</li><li><b>Bikes</b>: " + data.properties.nb_bikes + "</li><li><b>At</b> " + data.properties.timestamp + "</li></ul>") .on('mouseover', function(e) { this.openPopup(); }) .on('mouseout', function(e) { this.closePopup(); }) .on('click', function(e) { window.location.assign(city + "/" + data.properties.id); }); } }).addTo(map); var clusterLayer = L.geoJSON(null, { style: function(data){ return {color: d3.schemeSet1[data.properties.cluster_id]}; }, pointToLayer: function(data, coords) { return L.circleMarker(coords, {radius: 4}) .bindPopup("<ul><li><b>ID</b>: " + data.properties.id + "</li><li><b>Name</b>: " + data.properties.name + "</li>" + "<li><b>Cluster id</b>: " + data.properties.cluster_id + "</li></ul>") .on('mouseover', function(e) { this.openPopup(); }) .on('mouseout', function(e) { this.closePopup(); }) .on('click', function(e) { window.location.assign(city + "/" + data.properties.id); }); } }); var baseMaps = { "current": currentLayer, "cluster": clusterLayer }; tile.addTo(map); L.control.layers(baseMaps).addTo(map); $.getJSON(API_URL + "/" + city + "/availability?geojson=true", function(data) { currentLayer.addData(data); map.fitBounds(currentLayer.getBounds()) }); $.getJSON(API_URL + "/" + city + "/clusters?geojson=true", function(data) { clusterLayer.addData(data); }); }); // K-mean centroid plotting $(document).ready(function() { var url = API_URL + "/lyon/centroids"; $.get(url, function(content) { function mapCentroidValues(id){ return content.data[id].hour.map(function(t, i){ return [t, content.data[id].values[i]]; }); }; var clusters = {}; for (cluster = 0; cluster <= 3; cluster++) clusters[content.data[cluster].cluster_id] = mapCentroidValues(cluster) Highcharts.chart('clusterCentroids', { title: { text: 'Cluster centroid definitions' }, yAxis: { title: { text: 'Available bike percentage' } }, xAxis: { type: "Hour of the day" }, colors: d3.schemeSet1, series: [{ name: "cluster 0", data: clusters[0], tooltip: { valueDecimals: 2 } },{ name: "cluster 1", data: clusters[1], tooltip: { valueDecimals: 2 } },{ name: "cluster 2", data: clusters[2], tooltip: { valueDecimals: 2 } },{ name: "cluster 3", data: clusters[3], tooltip: { valueDecimals: 2 } }] } ); } ); } );
true
e749874edc440887e1ab767cab91b741603d0510
JavaScript
alexconway808/makeadeck
/public/js/deck.js
UTF-8
1,563
4.1875
4
[]
no_license
//Creating the class var Deck = function() { //Creating the constructors this.cards = []; //Calling the generate function this.generate(); } //Adding the generate function to the Deck class Deck.prototype.generate = function(){ var suitNames = ["Diamonds", "Spades", "Clubs", "Hearts"]; var tempCard = 1; for (var cardsPerSuit = 1; cardsPerSuit <= 13; cardsPerSuit++, tempCard++){ // this.cards.push(i + ""); //push the numbers into an array as a string using the + "" if (cardsPerSuit === 1){ cardsPerSuit = "Ace"; } if (cardsPerSuit === 11){ cardsPerSuit = "Jack"; } if (cardsPerSuit === 12){ cardsPerSuit = "Queen"; } if (cardsPerSuit === 13){ cardsPerSuit = "King"; } for (var suits = 0; suits < suitNames.length; suits++){ var card = new Card(suitNames[suits], cardsPerSuit); this.cards.push(card); } cardsPerSuit = tempCard; } } Deck.prototype.deal = function(){ return this.cards.splice(0, 5); //Splice out and return the first 5 elements of the this.cards array } Deck.prototype.shuffle = function(){ var counter = this.cards.length; var random_index = 0; var temp = null; while (counter > 0) { random_index = Math.floor(Math.random() * counter); counter--; temp = this.cards[counter]; this.cards[counter] = this.cards[random_index]; this.cards[random_index] = temp; } } //assign each card to a random number //sort the numbers asc to desc //change the number back to cards //display random deck
true
94b092cae88677c9927769c057435813d354420d
JavaScript
aberkow/nexus-tone-test
/js/index.js
UTF-8
2,928
2.75
3
[]
no_license
var $ = require("jquery"); //var nx = require('nexusUI'); var tone = require('tone'); var delay = new tone.FeedbackDelay('16n', 0.5).toMaster(); var sampler = new tone.Sampler({ 0: '../studderSchool.wav' }, { player: { loop: true, } }).connect(delay); //the .onload method is deprecated. this is correct. tone.Buffer.on('load', function(){ waveform1.setBuffer(sampler._buffers[0]._buffer); waveform1.select(0, 500); //sampler.triggerAttack('0'); }); // tone.Buffer.onload = function(){ // waveform1.setBuffer(sampler._buffers[0]._buffer); // waveform1.select(0, 500); // sampler.triggerAttack(0); // } //why can't I require nexusUI here? nx.onload = function(){ //start and stop the sampler. toggle1.on('*', function(data){ debugger; if (data.value === 1){ sampler.triggerAttack('0'); } else { sampler.triggerRelease(); } }); //change the delay time dial1.on('*', function(data){ delay.delayTime.value = data.value; }); tilt1.on('*', function(data){ if (data.x >== 0){ sampler.reverse = false; sampler.player._playbackRate = data.x; } else { sampler.reverse = true; sampler.player._playbackRate = data.x * -1; } }); nx.colorize('accent', '#1ac'); waveform1.on('*', function(data){ sampler.player.setLoopPoints(data.starttime/1000, data.stoptime/1000); }); //set button1.mode = 'impulse' so that it only works on //click (as opp to button down and up) // button1.mode = 'impulse'; // button1.on('*', function(data){ // console.log('button1 pressed'); // //sampler.retrigger = true lets the sample play back // //many times w/o waiting until it's finished. // sampler.retrigger = true; // sampler.start(); // }); // //let the sampler loop. // toggle1.on('*', function(data){ // if (data.value === 1) { // sampler.loop = true; // } else { // //sampler.loop needs to be set explicitly to false. // //otherwise it loops forever. // sampler.loop = false; // } // }); // waveform1.on('*', function(data){ // sampler.player.setLoopPoints(data.starttime/1000, data.stoptime/1000); // }); // //change the delay feedback // dial2.on('*', function(data){ // delay.feedback.value = data.value; // }); // //change the playback rate for sampler. // dial3.on('*', function(data){ // sampler.playbackRate = data.value; // }); } //wav needed as audio format. possibly mp3 too? // var sampler = new tone.Player('../studderSchool.wav', function(){ // console.log('sample loaded'); // }); // var buffer = new tone.Buffer(); // // buffer.onload = function(){ // waveform1.setBuffer = (sampler._buffers[0]._buffer); // waveform1.select(0, 500); // sampler.triggerAttack('0'); // //debugger; // } //var delay = new tone.FeedbackDelay('16n', 0.5).toMaster(); // sampler.connect(delay); //sampler.toMaster();
true
623330cb1ec232319bca0b0a945c2aaab2483af7
JavaScript
thedanielmark/xstack-status
/js/support.js
UTF-8
2,872
2.859375
3
[]
no_license
// listen for "submit" click var supportForm = document.querySelector("#supportForm"); supportForm.addEventListener("submit", e => { e.preventDefault(); document.getElementById("supportFormLoader").classList.remove("d-none"); document.getElementById("supportFormButton").setAttribute("disabled", "disabled"); var type = supportForm["type"].value; var category = supportForm["category"].value; var subject = supportForm["subject"].value; var description = supportForm["description"].value; // get email from localStorage // get email from localStorage var email = localStorage.enteredEmail; var auth_token = localStorage.auth_token; $.ajax({ type: "POST", url: "https://weareeverywhere.in/create-support-ticket.php", datatype: "html", data: { username: email, auth_token: auth_token, type: type, category: category, subject: subject, description: description }, success: function (response) { var parsedResponse = JSON.parse(response); console.log(response); if (parsedResponse === "invalid-auth-or-user") { // handle error document.getElementById("supportFormError").innerHTML = "Invalid user. Redirecting you to the login page."; document.getElementById("supportFormError").style.display = "block"; document.getElementById("supportFormLoader").style.display = "none"; document.getElementById("supportFormButton").removeAttribute("disabled", "disabled"); setTimeout(() => { localStorage.clear(); window.location.reload(); }, 5000); } else if (parsedResponse === "mail-fail") { // handle error window.location.replace("support.php?popup=error"); } else if (parsedResponse === "mail-success") { window.location.replace("support.php?popup=success"); } }, error: function (error) { } }); }); // to check if the url has parameters var url = window.location.href; if (url.indexOf("?") > -1) { console.log("Url has params"); const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); const popup = urlParams.get('popup'); if (popup === "success") { // toast here setTimeout(() => { showToastPosition('Done!', 'You have successfully created a ticket!', 'bottom-left', 'success'); }, 500); } if (popup === "error") { // toast here setTimeout(() => { showToastPosition('Oops!', 'That did\'t work. Please try again.', 'bottom-left', 'error'); }, 500); } }
true
8fb0860bf5205eeb93d8626930e166e05dc55254
JavaScript
mshoard/omg-js
/packages/omg-js-childchain/src/watcherApi.js
UTF-8
612
2.671875
3
[]
no_license
const fetch = require('node-fetch') const JSONBigNumber = require('json-bigint') class WatcherError extends Error { constructor ({ code, description }) { super(description) this.code = code } } async function get (url) { const resp = await fetch(url) const body = await resp.text() let json try { // Need to use a JSON parser capable of handling uint256 json = JSONBigNumber.parse(body) } catch (err) { throw new WatcherError('Unknown server error') } if (json.result === 'error') { throw new WatcherError(json.data) } return json.data } module.exports = { get }
true
e2ee86c46f6fb2d8f3da3161ac92307e68e0e9b8
JavaScript
haarabi/test-site
/scripts/main.js
UTF-8
1,311
3.890625
4
[]
no_license
// var myHeading = document.querySelector('h3'); // myHeading.textContent = "Hello world!"; // function multiply(num1, num2){ // return num1*num2; // } // // attaching evenets to an element // // line of code displays an alert on user clicking anywhere on the page // document.querySelector('html').Onclick = function(){ // alert('Ouch stop poking me!'); // } var myImage = document.querySelector('img'); myImage.onclick = function(){ var mySrc = myImage.getAttribute('src'); if (mySrc === 'images/landscape1.jpg'){ myImage.setAttribute('src', 'images/landscape2.jpg'); } else { myImage.setAttribute('src', 'images/landscape1.jpg'); } } var myButton = document.querySelector('button'); var myHeading = document.querySelector('h3'); function setUserName(){ var myName = prompt('Enter your name'); localStorage.setItem('name', myName); myHeading.textContent = 'Hello, ' + myName; } // when the page loads, check if there is saved name, if it is use it; otherwise ask for a name if(!localStorage.getItem('name')){ setUserName(); } else { var storedName = localStorage.getItem('name'); myHeading.textContent = 'Hello, ' + storedName; } // this provides an option for users to change the name myButton.onclick = function(){ setUserName(); }
true
73d15b7c2d6a6ea61db861060401f54ee7be0ad6
JavaScript
Brockwest2351/West_Brock_SDI
/loops_worksheet/js/loops_worksheet.js
UTF-8
1,313
3.46875
3
[]
no_license
/* Brock West Section 00 20JUL15 Loops Worksheet */ //alert("testing to see if this work!"); // calculate how many days until your next game var nextGame= prompt ("when in your next game? "); while(isNaN(nextGame)||nextGame===""){ nextGame=prompt ("Please enter a number and do not leave this blank.\nWhen is your next game.") } for (var i=0;i<nextGame;i++){ } console.log ("your next game is in "+nextGame+ " days."); var playNext= prompt ("will you play next game?"); while(playNext.toLowerCase()!="yes"&& playNext.toLowerCase()!="no"){ playNext=prompt ("Please only enter yes or no.\nWill you play next game?") } if(playNext === "no"){ console.log(" Have a great day.") } else { console.log("enjoy your game."); // if your points scored is greater or equal to 10 you can start next game var pointsScored = prompt("How many points did you score in your last game?"); while (isNaN(pointsScored) || pointsScored === "") { pointsScored = prompt("Please only enter a number and do not leave this blank. How many points did you score in your last game."); } var allowedPoints=10; var counter=1; do { console.log("you scored " + pointsScored) } while (pointsScored < allowedPoints); { console.log("You wont start next game."); pointsScored++; } }
true
ebc2e921a39a5f44b9deae747af75f8db32ea88d
JavaScript
halented/halgos
/35-count-valid-teams/solution.js
UTF-8
606
3.625
4
[]
no_license
function validTeams(ratings) { let numTeams = 0 let i = 0 for (i; i < ratings.length - 2; i++) { for (let j = i + 1; j < ratings.length - 1; j++) { for (let k = j + 1; k < ratings.length; k++) { if (ratings[i] < ratings[j] < ratings[k] || ratings[i] > ratings[j] > ratings[k]) { numTeams++ } } } } // returns an integer -- the number of possible valid teams return numTeams } console.log(validTeams([2, 5, 3, 4, 1])) // => 3 // validTeams([2,1,3]) // => 0 // validTeams([1,2,3,4]) // => 4
true
462e3ae67eedd6984e7c23def61962eff444a202
JavaScript
ps0305/Javascript-Algorithms-And-Data-Structures
/leetcode/split-array-with-same-average/index.js
UTF-8
1,079
3.40625
3
[]
no_license
/** * @param {number[]} A * @return {boolean} */ var splitArraySameAverage = function(A) { const sum = A.reduce((acc, cur) => acc + cur, 0); const n = A.length; if (!isSplittable(sum, n)) { return false; } const dp = createCombinationSum(A, n, Math.ceil(n / 2)); for (let k = 1; k <= n / 2; k++) { if ((sum * k) % n === 0 && dp[k].has((sum * k) / n)) { return true; } } return false; }; function isSplittable(sum, n) { for (let k = 1; k <= n / 2; k++) { if ((sum * k) % n === 0) { return true; } } return false; } function createCombinationSum(arr, n, k) { let dp = [...new Array(k + 1)].map(() => new Set()); dp[0].add(0); for (let i = 1; i <= n; i++) { const next = [...new Array(k + 1)].map(() => new Set()); next[0].add(0); for (let j = 1; j <= k; j++) { concat(next[j], dp[j], [...dp[j - 1]].map((val) => val + arr[i - 1])); } dp = next; } return dp; } function concat(target, ...args) { for (const set of args) { for (const el of set) { target.add(el); } } }
true
8b9acec8ee9404d90f0178c4273c633ba54e20ce
JavaScript
moshfiqrony/nextjs-tailwindcss-imdb
/utils/index.js
UTF-8
267
2.75
3
[ "MIT" ]
permissive
export const storeLocalStorage = (key, data) => { if(typeof window !== 'undefined'){ localStorage.setItem(key, data) } } export const getLocalStorage = (key) => { if(typeof window !== 'undefined'){ return localStorage.getItem(key) } }
true
8fa793e6ea59f366fbe9eaf057bdfa2730e860a1
JavaScript
Shantanu28/ruready
/WebRoot/include/jquery/.svn/text-base/jquery.menugroup.js.svn-base
UTF-8
8,023
2.921875
3
[]
no_license
//================================================================== // -jQuery MenuGroup Plugin- // // @author Oren E. Livne <[email protected]> // @date November 6, 2007 // // This plugin groups several drop-down menus. It plugins AJAX // action URLs for menu pre-population and on-change event response. // // Arguments: (default values appear in square brackets) // * actions - an associative array of actions (event listener structs) // that are triggered upon a menu's onchange. Action structs can be // set for each menu name (serving as a key). // Each action struct may contain the following elements: // o populate_url - URL to a server action that populates the child // menu of this menu upon an on-change event [null]. // o onchange - a function reference that accepts a single argument // (the new selected value) and can be used to trigger other events on // the page [null]. // Options: (default values appear in square brackets) // * onload_key - key of pre-population action in the actions array ['onload']. // * name_prefix - prefix of "name" elements of generated <select> tags. // If a div tag's id is x, the select's name will be name_prefix + x ['menugroup']. //================================================================== // Example of usage: /* // Your server actions might be organized in one object, e.g. // a Struts dispatch action class. var base_action = "/jquery/populateMenu.do?"; // Pre-population action URL on the server var onload_populate_url = base_action + "action=initial&menu=course"; // Menu on-change event actions courseOnChange = function(value) { alert('New course celection: value = ' + value); }; var actions = new Array(); actions['onload'] = { populate_url: onload_populate_url }; actions['${subjectMenu}'] = { populate_url: base_action + "?menu=${subjectMenu}" }; actions['${courseMenu}'] = { populate_url: base_action + "?menu=${courseMenu}" , onchange: courseOnChange}; actions['${topicMenu}'] = { populate_url: base_action + "?menu=${topicMenu}" }; actions['${subTopicMenu}'] = { }; // Activate the menu group options = { name_prefix: '${prefix}' }; $(this).menugroup(actions, options); */ jQuery.fn.menugroup = function(actions, options) { //================================================================== // menu_group_handler() // A handler that populates a drop-down menu from XML data. // // @param xml - XML output of the action // @param actions - list of actions for select on-change events // @param options - options struct //================================================================== function menu_group_handler(xml, actions, options) { // alert('menu_group_handler() BEGIN'); // Loop over select groups in the XML document and prepare a // menu (HTML select element) within the corresponding <div> tag $(xml).find('select').each(function() { // Convenient variables and aliases var div_id = $(this).attr('id'); var div = '#' + div_id; var select_id = div_id + '_select'; var select = '#'+select_id; // alert('populating <div> ' + div); // Clear this division's default text $(div).html(''); // Create and format a new select element var div_class = $(div).attr('class'); $('<select></select>') .attr('id',select_id) .attr('name',options.name_prefix + div_id) // .addClass(div_class + "_" + div_id) .appendTo(div); // alert('Created <select> element'); //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // Add all attributes found in the XML section corresponding to // this div to the select element. E.g., a disabled attribute. // I don't know how to loop over attributes of an XML element, // so we use nested <attribute> elements instead, with <name> // and <value> elements within each. // // In the future this can be replaced by looping over DOM attributes: // @see http://www.howtocreate.co.uk/tutorials/javascript/dombasics //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ $(xml).find('#' + div_id + ' > attribute').each(function() { var name_text = $(this).find('name').text(); var value_text = $(this).find('value').text(); $(select).attr(name_text, value_text); }); // each( //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // Find options in the XML text and append them to the select menu. // Find out which one is selected and save it in the selected_value // variable. //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ var selected_value; $(xml).find('#' + div_id + ' > option').each(function() { var label_text = $(this).find('label').text(); var value_text = $(this).find('value').text(); var selected_text = $(this).find('selected').text(); var isSelected = $(this).is(":contains(selected)"); if (isSelected) { selected_value = value_text; } // alert(label_text + " " + value_text + " " + selected_text); $('<option></option>') .attr('value', value_text) .html(label_text) .appendTo(select); }); // each( // Set the menu selection $(select).val(selected_value); // Trigger child menu population and other event listeners (in the // listener function hook) upon changing the selection in the parent // menu. var populate_url = actions[div_id].populate_url; var onchange_listener = actions[div_id].onchange; if ((populate_url != null) || (onchange_listener != null)) { // alert('added menu selection event: ' + select + ' populate_url='+populate_url); $(select).change(function () { var value = $(select + " option:selected").eq(0).attr('value'); if (populate_url != null) { populate_menu_group(div_id, actions, options, value); } if (onchange_listener != null) { onchange_listener(value); } }); } }); // each of find('select') //alert('menu_group_handler() END'); }; // menu_group_handler() //================================================================== // populate_menu_group() // Hook an AJAX action to pre-populate drop-down menu. Its handler // will set on-change event actions on created menus. // // @param key - key into the actions array whose populate_url // action is invoked here using AJAX. // @param actions - list of actions for select on-change events // @param options - options struct // @param value - newly selected value of the last drop-down menu // that was changed (if null, does not apply) //================================================================== function populate_menu_group(key, actions, options, value) { var populate_url = actions[key].populate_url; var value_query = ((value == null) || (value.indexOf('_') >= 0)) ? '' : ('&value=' + value + '&change=true'); if (options.debug) { alert('Invoking populate URL ' + populate_url + value_query); } $.ajax({ type: "POST", url: populate_url + value_query, dataType: "xml", success: function(xml) { menu_group_handler(xml, actions, options); } // success: function }); // $.ajax( }; // populate_menu_group() //================================================================== // Main code //================================================================== // alert('menugroup()'); // instead of selecting a static container with $("#rating"), we now // use the jQuery context var me = this; // Use this code to set default options and override them with the arguments // passed to this function var settings = jQuery.extend({ onload_key: 'onload', name_prefix: 'menugroup', debug: false }, options); populate_menu_group(settings.onload_key, actions, settings, null); // if possible, return "this" to not break the chain return this; };
true
67ac1721e68071c110621cec744abbecd7312762
JavaScript
edu22snt/importaCSV
/web/src/main/webapp/resources/scripts/componentes.js
UTF-8
1,740
3.4375
3
[]
no_license
/** * JS com a função que verifica se o valor horas por dia está utrapassando o valor máximo. */ function verificaValorHoraDia() { var vhd = $(".cadastro_proprietario_txtVazaoHoraDia").val(); if(vhd > 24) { vhd = 24; } $(".cadastro_proprietario_txtVazaoHoraDia").autoNumeric('set', vhd); } /** * JS com a função que verifica se o valor dias por mês está utrapassando o valor máximo. */ function verificaValorDiaMes() { var vdm = $(".cadastro_proprietario_txtVazaoDiaMes").val(); if(vdm > 30) { vdm = 30; } $(".cadastro_proprietario_txtVazaoDiaMes").autoNumeric('set', vdm); } /** * JS com a função que verifica se o número do telefone tem 9 digitos. */ function mascaraTelefone() { var v = document.getElementById(".cadastro_proprietario_telefone").value; v = v.replace(/\D/g,""); v = v.replace(/^(\d{2})(\d)/g,"($1) $2"); v = v.replace(/(\d)(\d{4})$/,"$1-$2"); document.getElementById("cadastro:telefone").value = v } /** * JS com a função que verifica se o número do telefone fax tem 9 digitos. */ function mascaraFax(){ var v = document.getElementById("cadastro_proprietario_fax").value; v = v.replace(/\D/g,""); v = v.replace(/^(\d{2})(\d)/g,"($1) $2"); v = v.replace(/(\d)(\d{4})$/,"$1-$2"); document.getElementById("cadastro:fax").value = v } /** * JS com a função que verifica se o número do celular tem 9 digitos. */ function mascaraCelular(){ var v = document.getElementById("cadastro_proprietario_celular").value; v = v.replace(/\D/g,""); v = v.replace(/^(\d{2})(\d)/g,"($1) $2"); v = v.replace(/(\d)(\d{4})$/,"$1-$2"); document.getElementById("cadastro:celular").value = v }
true
2c3e959f901d58da0da31062830669b7564e03ea
JavaScript
milestone-sys/web-design-system
/components/button-cards/card.js
UTF-8
2,070
2.640625
3
[ "MIT" ]
permissive
function ensureSameHeight(nodes) { let maxHeight = 0 for (let i = 0; i < nodes.length; i++) { nodes[i].style.height = 'auto' maxHeight = Math.max(nodes[i].offsetHeight, maxHeight) applyMaxHeight(nodes, maxHeight) } } function applyMaxHeight(nodes, maxHeight) { for (let i = 0; i < nodes.length; i++) { if (nodes[i].offsetHeight < maxHeight) { nodes[i].style.height = maxHeight + 'px' } } } NodeList.prototype.ensureCardContentsSameHeightWithinParent = function(args) { if (this.length <= 0) { return } const self = this function run() { let latestParent = null for (let i = 0; i < self.length; i++) { if (latestParent != self[i]) { latestParent = self[i] ;(function(parent) { const rowMaxHeight = [] let currentRowIndex = 0 let currentOffsetPosition let elementsCollection = [] function resize() { for (let j = 0; j < args.subSelectors.length; j++) { const currentElements = parent.querySelectorAll(args.subSelectors[j]) for (let k = 0; k < currentElements.length; k++) { const currentElement = currentElements[k] const rowOffsetPosition = currentElement.getBoundingClientRect().top if (currentOffsetPosition !== rowOffsetPosition) { elementsCollection = [] currentOffsetPosition = rowOffsetPosition currentRowIndex++ rowMaxHeight[currentRowIndex] = 0 } if (currentOffsetPosition == rowOffsetPosition) { elementsCollection.push(currentElement) ensureSameHeight(elementsCollection) } } } } resize() })(latestParent) } } } run() let timeout = true addEventListener( 'resize', function() { clearTimeout(timeout) timeout = setTimeout(run, 500) }, false ) timeout = setTimeout(run, 500) }
true
dc08552bea82f2c4c49b94ff4efd5ec7ea61e136
JavaScript
14raryana/employeeTracker
/Services/employeeService.js
UTF-8
1,856
2.890625
3
[]
no_license
const connection = require("../connection"); module.exports = function() { return { add: function(employee){ const query = "INSERT INTO employees(first_name, last_name, role_id, manager_id) VALUES(?, ?, ?, ?)"; return new Promise(function(resolve, reject){ connection.query(query, [employee.firstName, employee.lastName, employee.roleId, employee.managerId], function(err, results){ if (err) { reject(err); } else { console.log("Successfully added " + employee.firstName + " " + employee.lastName + " as an employee"); resolve(results); } }) }); }, getAll: function() { const query = "SELECT * FROM employees"; return new Promise(function(resolve, reject){ connection.query(query, function(err, results){ if (err) { reject(err); } else { resolve(results); } }) }) }, update: function(employee){ const query = "UPDATE employees SET role_id = ? WHERE id = ?;"; return new Promise(function(resolve, reject) { connection.query(query,[employee.role_id, employee.id], function(err, results) { if(err) { reject(err); } else { console.log("Successfully updated " + employee.first_name + " " + employee.last_name); resolve(results); } }); }); } } }
true
d77680f31c9cef480b14b14e3c9b6be10e359365
JavaScript
nicong622/account-book
/src/js/utils/utils.js
UTF-8
1,841
2.75
3
[ "MIT" ]
permissive
import moment from 'moment' export var Store = (function() { // Store.js var store = {}, win = (typeof window != 'undefined' ? window : global), storage = win['localStorage']; store.serialize = function (value) { return JSON.stringify(value) }; store.deserialize = function(value) { if(typeof value != 'string') { return undefined } try { return JSON.parse(value) } catch(e) { return value || undefined } }; store.set = function(key, val) { if(val === undefined) { return store.remove(key) } storage.setItem(key, store.serialize(val)); return val }; store.get = function(key, defaultVal) { var val = store.deserialize(storage.getItem(key)); return (val === undefined ? defaultVal : val) }; store.remove = function(key) { storage.removeItem(key) }; store.clear = function() { storage.clear() }; store.getAll = function() { var ret = {}; store.forEach(function(key, val) { ret[key] = val }); return ret }; store.forEach = function(callback) { for(var i = 0; i < storage.length; i++) { var key = storage.key(i); callback(key, store.get(key)) } }; return store }()); export var Utils = { getTimeStamp(date){ return moment(date).format('YYYY-M-D'); }, getDaysInMonth(month){ if(!month){ month = moment().format('YYYY-M'); } let howMany = moment(month, 'YYYY-M').daysInMonth(), days = [], date = 1; while (date <= howMany){ days.push(String(date++)); } return days; } };
true
b39dcebfce858059a23cca089231a8db2fe39882
JavaScript
uivan1/uaqride
/public/img/login.js
UTF-8
1,863
3
3
[]
no_license
document.getElementById("reg").addEventListener("click",send_form); function val_correo(){ var email=document.getElementById("email").value; var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; return regex.test(email) ? true : false; } function send_form(){ var nombre=document.getElementById("nombre"); var facultad=document.getElementById("facultad"); var nombreU=document.getElementById("nombreU"); var email=document.getElementById("email"); var fecha=document.getElementById("fechaNac"); var contra=document.getElementById("contra"); var contra2=document.getElementById("contra2"); var mensaje=document.getElementById("mensaje"); if(nombre.value=="" || facultad.value=="" || nombreU.value=="" || email.value=="" || contra.value=="" || contra2.value=="" || fechaNac.value==""){ mensaje.innerHTML="Debes llenar todos los campos"; mensaje.style.visibility = "visible"; return false; }else{ if(!val_correo()){ mensaje.innerHTML="El correo ingresado no es válido"; mensaje.style.visibility = "visible"; return false; }else if(contra.value.length<8){ mensaje.innerHTML="La contraseña debe de contener al menos 8 caracteres"; mensaje.style.visibility = "visible"; return false; }else if(contra.value!=contra2.value){ mensaje.innerHTML="Las contraseñas no coinciden"; mensaje.style.visibility = "visible"; return false; }else{ // document.getElementById("myForm").submit(); return true; } } } function send_form2(){ var u=document.getElementById("u"); var p=document.getElementById("p"); var mensaje2=document.getElementById("mensaje2"); if(u.value=="" || facultad.p=="" ){ mensaje2.innerHTML="Debes de llenar ambos campos"; mensaje2.style.visibility = "visible"; return false; }else{ return true; } }
true
5058b6d89668a2aaaba1fc6885d2861f75102a42
JavaScript
TheClarity/Brooks_5_Journals
/NewFrontier/NewFrontier.js
UTF-8
1,036
2.9375
3
[]
no_license
$(document).ready(function() { var day = true; $("#switch").click(function() { current = document.getElementById("main").class; if(current == "off"){ document.getElementById("main").class="on"; var background = document.getElementById("main"); background.style.backgroundColor = '#FFF'; background.style.color = '#000'; document.getElementById("title").innerHTML = "day"; } else { document.getElementById("main").class="off"; var background = document.getElementById("main"); background.style.backgroundColor = '#000'; background.style.color = '#FFF'; document.getElementById("title").innerHTML = "night"; } }); $("#hover").mouseover(function() { document.getElementById("hover").style.backgroundColor = "#FFFF00"; }); $("#hover").mouseout(function() { document.getElementById("hover").style.backgroundColor = "#FF4500"; }); });
true
9f820b8bd19154275724f79e36a5984774dbb31b
JavaScript
Doesntmeananything/coding-problems
/Algorithms/Duplicate Encoder.js
UTF-8
306
3.21875
3
[]
no_license
function duplicateEncode(word) { const workArray = word.toLowerCase().split(''); const result = workArray.map((char) => { if (workArray.indexOf(char) !== workArray.lastIndexOf(char)) { return ')'; } return '('; }); return result.join(''); } console.log(duplicateEncode('(( @'));
true
744379a1364b5caa0d72773d4f87991bf3ba6023
JavaScript
lvachon/SkiSim
/js/tasks.js
UTF-8
2,273
3.015625
3
[]
no_license
function Tasks(terrain, workers){ this.terrain = terrain; this.workers = workers; this.tasks = []; this.addTask = (x,y,task)=>{ x=Math.floor(x)+0.5; y=Math.floor(y)+0.5; if(x<0||x>=this.terrain.gridWidth||y<0||y>this.terrain.gridDepth){return false;} if(this.tasks.filter(t=>t.x==x&&t.y==y&&t.task==task).length){return false;} if(this.workers.filter(w=>w.currentTask&&w.currentTask.x==x&&w.currentTask.y==y&&w.currentTask.task==task&&w.currentState!='IDLE').length){return false;} this.tasks.push({x,y,task}); this.terrain.addWorkingPoint(x, y); return true; } this.processQueue = ()=>{ const idleWorkers = this.workers.filter(worker=>worker.currentState==='IDLE'); for(let i=0;i<idleWorkers.length && this.tasks.length;i++){ idleWorkers[i].assignTask(this.tasks.shift()); } } this.getWorkerTable = ()=>{ return `<table> <thead> <tr> <td>Worker</td> <td>Status</td> <td>Task</td> <td>Position</td> </tr> </thead> <tbody> ${this.workers.map(worker=>{ return `<tr> <td>${worker.name}</td> <td>${worker.currentState}</td> <td>${worker.currentTask?worker.currentTask.task:'None'}</td> <td> <a href='#' onmouseup="godcam.setTarget(${worker.gridX},${worker.gridY});"> ${Math.floor(worker.gridX*10)/10},${Math.floor(worker.gridY*10)/10} </a> </td> </tr>`; }).join("") } </tbody> </table>`; } this.save = (slot)=>{ localStorage.setItem(`${slot}_tasks_tasks`,JSON.stringify(this.tasks)); localStorage.setItem(`${slot}_tasks_workers`,JSON.stringify(this.workers.map(worker=>{return { name: worker.name, gridX:worker.gridX, gridY:worker.gridY, currentTask:worker.currentTask, currentState:worker.currentState, }}))); } this.load = (slot)=>{ this.tasks = JSON.parse(localStorage.getItem(`${slot}_tasks_tasks`)); this.workers = JSON.parse(localStorage.getItem(`${slot}_tasks_workers`)).map(worker=>{ const agent = new Agent(worker.gridX, worker.gridY, this.terrain); agent.name = worker.name; agent.currentTask = worker.currentTask; agent.currentState = worker.currentState; scene.add(agent.mesh); return agent; }); } }
true
7befa2a22d2c75e06a417594332011b203aa653d
JavaScript
lopis/StockPortfolioUbuntu
/src/qml/data.js
UTF-8
7,559
3.140625
3
[]
no_license
// Keeps a pointer to the listModel to allow // assync return of values. var portfolio = {listModel: {}}; var defaultNames = "MSFT,Microsoft,1"; //";AMZN,Amazon,1;AAPL,Apple,1"; // max and min value calculated for the chart var max = 0.0; var min = 999999; var dates = []; var isReady = false; // is true if the plot data is up to date var isBusy = false; // is true if the plot is being updated // This queue will contain the tick names to be fetched. // Use push(tickName) and pop(tickName) to add and get/remove values. var schedule = []; var afterReadyCall; // The normalized Values currently being drawn // This is an array of floats // Each array represents a series in the plot var normValues = []; // Pointer to the status text var status; var plotHeight = 280; // Hack :/ //function normalizeValues(valuesObj) { // dates[0] = valuesObj.get(0).date; // dates[1] = valuesObj.get(valuesObj.count-1).date; // for (var i = 0; i < valuesObj.count; i++) { // if (valuesObj.get(i).close > max) { // max = valuesObj.get(i).close; // } // if (valuesObj.get(i).close < min) { // min = valuesObj.get(i).close; // } // } // var values= []; // if (max > 0) { // for (i = 0; i < valuesObj.count; i++) { // // Converts the values to a scale of [0, plotHeight] // values.push(plotHeight * (valuesObj.get(i).close-min) / (max-min)); // } // } // normValues.push(values); //} // Receives long date 2013-12-30 // Returns short date Dez 30 var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; function longDate2Short (dateStr){ var d = new Date(dateStr); return months[d.getMonth()] + " " + d.getDate(); } function normalizeValuesMany(listModel) { normValues = []; var listCount = listModel.get(0).valuesObj.count; dates[0] = longDate2Short(listModel.get(0).valuesObj.get(0).date); dates[1] = longDate2Short(listModel.get(0).valuesObj.get(listCount * 0.25).date); dates[2] = longDate2Short(listModel.get(0).valuesObj.get(listCount * 0.50).date); dates[3] = longDate2Short(listModel.get(0).valuesObj.get(listCount * 0.75).date); dates[4] = longDate2Short(listModel.get(0).valuesObj.get(listCount - 2).date); for(var item = 0; item < listModel.count; item++){ for (var i = 0; i < listModel.get(item).valuesObj.count; i++) { if (listModel.get(item).valuesObj.get(i).close > max) { max = listModel.get(item).valuesObj.get(i).close; } if (listModel.get(item).valuesObj.get(i).close < min) { min = listModel.get(item).valuesObj.get(i).close; } } } for(item = 0; item < listModel.count; item++){ var values= []; for (var i = 0; i < listModel.get(item).valuesObj.count; i++) { values.push(plotHeight * (listModel.get(item).valuesObj.get(i).close-min) / (max-min)); } normValues.push(values); } } /* * Will populate the listModel with */ function getData(listModel, afterReady, numOfMonths) { schedule = []; portfolio.listModel = listModel; console.log("Model count: " + listModel.count); console.log("portfolio count: " + portfolio.listModel.count); afterReadyCall = afterReady; // Load the data from the file or server. var date = new Date(); var earlierDate = new Date; earlierDate.setDate(date.getDate() - 30*numOfMonths); var monthBegin = earlierDate.getMonth(); var dayBegin = earlierDate.getDate(); var yearBegin = earlierDate.getFullYear(); var monthEnd = date.getMonth(); var dayEnd = date.getDate(); var yearEnd = date.getFullYear(); for (var tickID = 0; tickID < portfolio.listModel.count; tickID++){ portfolio.listModel.get(tickID).valuesObj.clear(); var tickName = portfolio.listModel.get(tickID).tickName; //FIXME: is tickName defined? var url = ["http://ichart.finance.yahoo.com/table.txt?", "a=", monthBegin, "&b=", dayBegin, "&c=", yearBegin, "&d=", monthEnd, "&e=", dayEnd, "&f=", yearEnd, "&g=d&s=", tickName].join(""); loadData(tickID, url); } } // Test if tickname is valid function testData(tickName, afterReady) { // Load the data from the file or server. var date = new Date(); var earlierDate = new Date; earlierDate.setDate(date.getDate() - 5); var monthBegin = earlierDate.getMonth(); var dayBegin = earlierDate.getDate(); var yearBegin = earlierDate.getFullYear(); var monthEnd = date.getMonth(); var dayEnd = date.getDate(); var yearEnd = date.getFullYear(); var url = ["http://ichart.finance.yahoo.com/table.txt?", "a=", monthBegin, "&b=", dayBegin, "&c=", yearBegin, "&d=", monthEnd, "&e=", dayEnd, "&f=", yearEnd, "&g=d&s=", tickName].join(""); var doc = new XMLHttpRequest(); doc.onreadystatechange = function() { afterReady(doc); } console.log("test url: " + url); doc.open("get", url); doc.setRequestHeader("Content-Encoding", "UTF-8"); doc.send(); } function loadData(tickID, url) { if (!isBusy) { isBusy = true; //console.log("url: " + url); getValues(tickID, url); } else { schedule.push([tickID, url]); } } function getValues(tickID, url) { var doc = new XMLHttpRequest(); // Used for XML, but works for plain text or CSV doc.onreadystatechange = function() { if (doc.readyState === XMLHttpRequest.DONE) { if (doc.responseText === "") { console.log("Connection failed, trying again in 1s.") statusText.text = "Connection failed"; return false; } parseCSV(tickID, doc.responseText); if (tickID == 3) { console.log(url); } isBusy = false; if (schedule.length > 0){ //console.log("Still busy"); var next = schedule.pop(); loadData(next[0], next[1], next[2]); } else { //console.log("Ready."); isReady = true; afterReadyCall(); } } } doc.open("get", url); doc.setRequestHeader("Content-Encoding", "UTF-8"); doc.send(); } function parseCSV(tickID, csvString) { var linesArray = csvString.split("\n"); // statusText.text = "Parsing: " + portfolio.listModel.get(tickID).tickName + "(" + portfolio.listModel.get(tickID).valuesObj.count + ")"; // Starts in line=1 to ignore CSV header for (var line = 1; line < linesArray.length-1; line++) { var lineArray = linesArray[line].split(","); var quote = {}; quote["date"] = lineArray[0]; quote["open"] = parseFloat(lineArray[1]); quote["high"] = parseFloat(lineArray[2]); quote["low"] = parseFloat(lineArray[3]); quote["close"] = parseFloat(lineArray[4]); quote["volume"] = parseInt(lineArray[5]); portfolio.listModel.get(tickID).valuesObj.append(quote); } var curVal = portfolio.listModel.get(tickID).valuesObj.get(0).close; var oldVal = portfolio.listModel.get(tickID).valuesObj.get(1).close; portfolio.listModel.get(tickID).raisedPercent = (100*(curVal-oldVal)/oldVal).toFixed(2); //console.log("Parsed " + portfolio.listModel.get(tickID).tickName); }
true
400dc875a7eee1b243f5221e5a6614eacdb69a56
JavaScript
hieunm286/MyShopFianl
/src/components/HoaDon.js
UTF-8
4,846
2.59375
3
[]
no_license
import React, { useState } from 'react' import Data from '../components/data.json' export default function HoaDon(props) { const data = Data const [id, setId] = useState('') const [name, setName] = useState('Tên sản phẩm') const [origin, setOrigin] = useState('Xuất sứ') const [price, setPrice] = useState(0) const [check, setCheck] = useState(false) const getProductInfo = (event) => { setId(event.target.value) data.forEach((item) => { if (item.id === event.target.value) { setName(item.name) setOrigin(item.origin) setPrice(item.price) setCheck(true) } if (item.id === id) { setName('item.name') setOrigin('item.origin') setPrice('item.price') setCheck(false) } }) } const addProduct = () => { if (check) { let item = {} item.id = id; item.name = name; item.origin = origin; item.price = price; item.quantity = 1; item.productCost = price props.addProduct(item) } else { alert('Sản phẩm không tồn tại! Vui lòng kiểm tra lại!') } } return ( <div className="mt-4"> <div className=""> <h5>Hóa đơn bán hàng</h5> <div className="d-flex justify-content-between"> <h6>Ngày xuất: {props.date}</h6> <button type="button" className="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Thêm sản phẩm </button> </div> </div> <hr></hr> {/* Modal */} <div className="modal fade" id="exampleModal" tabIndex={-1} role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="exampleModalLabel">Thêm sản phẩm</h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div className="modal-body"> <form> <div className="form-group"> <label htmlFor="formGroupExampleInput">Mã sản phẩm</label> <input type="text" className="form-control" id="formGroupExampleInput" placeholder="Mã sản phẩm" onChange={(event) => getProductInfo(event)} /> </div> <div className="form-group"> <label htmlFor="formGroupExampleInput2">Tên sản phẩm</label> <input type="text" className="form-control" id="formGroupExampleInput2" value={name} disabled /> </div> <div className="form-group"> <label htmlFor="formGroupExampleInput2">Xuất sứ</label> <input type="text" className="form-control" id="formGroupExampleInput3" value={origin} disabled /> </div> <div className="form-group"> <label htmlFor="formGroupExampleInput2">Giá bán</label> <input type="text" className="form-control" id="formGroupExampleInput4" value={price} disabled /> </div> </form> </div> <div className="modal-footer"> <button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" className="btn btn-primary" data-dismiss="modal" onClick={() => addProduct()}>Save changes</button> </div> </div> </div> </div> {/*Table*/} {/* <hr></hr> <Pay cost={cost} point={point} /> <Customer /> */} </div> ); };
true
0dd21d37859fd1520b5856e9580f2d06a186e9c2
JavaScript
ssthurai/lowagner.github.io
/js/records.js
UTF-8
5,361
2.890625
3
[]
no_license
// GLOBAL parameters YOU CAN SET var recordsMAXpp = 4; // max number of records to display per page var recordsSHOWbackTOtopAFTER = 3; // after X records, show the back to top link. this should NOT be greater than or equal to recordsMAXpp. // SET INTERNALLY IN THE CODE var recordsDISPLAYED = 0; // number of records displayed var recordsMIN = 0; // index of which record (of the records filtered) to start displaying var recordsMAX = 0; // index of which record is last to display. var recordsBEFORE = false; // if there were any records before recordsMIN var recordsAFTER = false; // if there were any records after recordsMAX function writerecord( record, recordnumber ) { // place holder for other more intense record writing document.write('<li>'+record["title"]+"</li>"); }; function writeornotrecord( record, recordnumber ) { //document.write("<p> record number = "+recordnumber + "</p>"); if ( recordnumber < recordsMIN ) recordsBEFORE = true; else if ( recordnumber > recordsMAX ) recordsAFTER = true; else { writerecord( record, recordnumber ); recordsDISPLAYED += 1; } }; function writebyfilter( basehtml, data, func ) { // // just double checking some stuff here // if ( recordsSHOWbackTOtopAFTER >= recordsMAXpp ) // recordsSHOWbackTOtopAFTER = recordsMAXpp-1; // first check if we need to write only a certain page... var s = 0; if ('s' in QueryString) { if ( QueryString['s'] == "all" ) { s = "all"; } else { s = parseInt( QueryString['s'] ); } } if ( s == "all" ) { data( func ).each( writerecord ); writenavtable( s, null, 1, null ); } else { recordsMIN = s*recordsMAXpp; recordsMAX = (s+1)*recordsMAXpp-1; data( func ).each( writeornotrecord ); if ( recordsDISPLAYED == 0 ) { document.write("Sorry, no results found with those filters."); } else if ( recordsDISPLAYED >= recordsSHOWbackTOtopAFTER || recordsBEFORE || recordsAFTER ) { var left = ""; if (recordsBEFORE) left = basehtml+everythingButS; var center = 0; if ( recordsDISPLAYED >= recordsSHOWbackTOtopAFTER ) center = 1; var right = ""; if (recordsAFTER) right = basehtml+everythingButS; writenavtable(s, left, center, right); } } }; function showfilters( basehtml, filters ) { document.write("<ul>"); for ( var i=0; i<filters.length; i++ ) { if ( (filters[i].length == 2) && filters[i][1] == "all" ) { if ( QueryString['s'] == "all" ) { // if the page is already showing all, perhaps it is showing all records of some other filter // so take out all other filters document.write("<li><a href=\""+basehtml+"?s=all\">all</a></li>"); } else { // otherwise, perhaps we were looking at a given page, and we want to see // all of the records for the given filter document.write("<li><a href=\""+basehtml+everythingButS+"s=all\">all</a></li>"); } } else { var writeout = "<li><a href=\""+basehtml+"?"; var label = ""; for ( var j=0; j<filters[i].length; j+=2 ) { var filter = filters[i][j]; var value= filters[i][j+1]; writeout += filter+"="+value; label += value; if ( j < filters[i].length - 2 ) { writeout += "&"; label += ", "; } } writeout += "\">"+label+"</a></li>"; document.write( writeout ); } } document.write("</ul>"); } function showtags( basehtml, tags ) { document.write("<ul>"); for ( var i=0; i<tags.length; i++ ) { var tag = tags[i]; document.write( "<li><a href=\""+basehtml+"?g="+tag+"\">"+tag+"</a></li>"); } document.write("</ul>"); } function addtofilter( filter, option, value, numberlength ) { if ( value !== undefined ) { if ( filter[option] === undefined ) filter[option] = {}; if ( numberlength === undefined ) { if ( typeof value === "object" ) { for ( var key in value ) { filter[option]['likenocase'] = key; // PROBLEM HERE. } } else { filter[option]['likenocase'] = value; } } else { } // if ( typeof value === "number" ) { // if ( modifier == "+" ) // filter[option]['gte'] = value; // else if ( modifier == "-" ) // filter[option]['lte'] = value; // else //( modifier === undefined ) // filter[option]['is'] = value; // } // else if ( typeof value === "string" ) { // filter[option]['likenocase'] = value; // } // else if ( typeof value === "object" ) { // if ( typeof modifier === "object" ) { // // } else { // // } // } } }
true
186753e808c14d00184558815c378d88b55d6ef4
JavaScript
Hisham-401-advanced-javascript/data-structures-and-algorithms
/Data-Structures/graph/__test__/graph.test.js
UTF-8
1,348
3.609375
4
[ "MIT" ]
permissive
'use strict' const {Node, Graph} = require('../graph.js'); let testNode1 = new Node('Alpha'); let testNode2 = new Node('Beta'); let testNode3 = new Node('Gamma'); // Node can be successfully added to the graph it ('Should allow a node to be added to a graph', () => { const graph = new Graph(); expect(graph).toBeTruthy(); expect(graph.size()).toBe(0); graph.addNode(testNode1); expect(graph.size()).toBe(1); }) // // An edge can be successfully added to the graph // it ('Should allow an edge to be successfully added to a graph', () => { // const graph = new Graph(); // graph.addNode(testNode1); // graph.addNode(testNode2); // expect(graph.size()).toBe(2); // graph.addEdge(testNode1,testNode2,'some distance'); // let setOfReturns = graph.getNeighbors(testNode1); // expect(setOfReturns).toEqual(['Beta', 'some distance']); // }) // A collection of all nodes can be properly retrieved from the graph it ('Should return all nodes from a graph', () => { const graph = new Graph(); graph.addNode(testNode1); graph.addNode(testNode2); graph.addNode(testNode3); expect(graph.size()).toBe(3); let setOfReturns = graph.getNodes(); let testArray = []; setOfReturns.forEach(node => testArray.push(node.value)); console.log(testArray); expect(testArray).toStrictEqual(['Alpha', 'Beta', 'Gamma']); })
true
fed33650f09457f9123f8c39561357240798abe6
JavaScript
Vvijin/display_test
/src/components/album/function.js
UTF-8
408
2.625
3
[]
no_license
import axios from 'axios'; export async function fetchAlbum(id) { const res = await axios.get(`https://jsonplaceholder.typicode.com/albums/${id}`) return res.data; //console.log(res.data); } export async function fetchPhoto(id) { const res = await axios.get(`https://jsonplaceholder.typicode.com/photos?albumId=${id}`) return res.data; //console.log(res.data); }
true
0a099320bb7fb14b6d965291ff7e7bc362e4e5ea
JavaScript
littleflute/Live-Stream-Web-Plugins
/News/Bitcoin/js/app.js
UTF-8
329
2.6875
3
[]
no_license
var app = (function () { var start = function() { getPrice(); setInterval(getPrice, 60000); } var getPrice = function () { $.getJSON("https://api.coindesk.com/v1/bpi/currentprice.json", function( data ) { $("h1").text("Bitcoin $" + data.bpi.USD.rate); }); } return { start: start } })(); app.start();
true
0190f63a66b756384ad4d856abdbf34d03ab1157
JavaScript
aerol457/FilesManage
/static/projects/7.Stopwatch App/stopwatch.js
UTF-8
2,391
2.890625
3
[]
no_license
$(function(){ var appMode = false; var timeCounter = 0; var lapCounter = 0; var action; var numOfLaps = 0 ; var timemMinutes,timeSecond,timeCentiseconds,lapmMinutes,lapSecond,lapCentiseconds; HideAndShow("#startButton","#lapButton"); $("#startButton").click(function(){ HideAndShow("#stopButton","#lapButton"); appMode = true; startAction(); }); $("#lapButton").click(function(){ if(appMode){ clearInterval(action); lapCounter = 0; addLap(); startAction(); } }); $("#stopButton").click(function(){ HideAndShow("#resumeButton","#resetButton"); clearInterval(action); }); $("#resumeButton").click(function(){ HideAndShow("#stopButton","#lapButton"); startAction(); }); $("#resetButton").click(function(){ location.reload(); }); function HideAndShow(x,y){ $(".control").hide(); $(x).show(); $(y).show(); } function startAction(){ action = setInterval(function(){ timeCounter++; lapCounter++; updateTime(); }, 10) } function updateTime(){ timemMinutes = Math.floor(timeCounter/6000); timeSecond = Math.floor(((timeCounter%6000)/100)); timeCentiseconds = (timeCounter%6000)%100; $("#timeminute").text(format(timemMinutes)); $("#timesecond").text(format(timeSecond)); $("#timecentisecond").text(format(timeCentiseconds)); lapmMinutes = Math.floor(lapCounter/6000); lapSecond = Math.floor((lapCounter%6000)/100); lapCentiseconds = (lapCounter%6000)%100; $("#lapminute").text(format(lapmMinutes)); $("#lapsecond").text(format(lapSecond)); $("#lapcentisecond").text(format(lapCentiseconds)); } function format(number){ if(number < 10){ return '0' + number; }else{ return number; } } function addLap(){ numOfLaps++; var myLapDetails = '<div id = loop>'+ '<div class="laptimetitle">'+ 'Lap'+ numOfLaps + '</div>'+ '<div class="laptime">'+ '<span>'+ format(lapmMinutes) +'</span>'+ ':<span>'+ format(lapSecond) +'</span>'+ ':<span>'+ format(lapCentiseconds) +'</span>'+ '</div>'+ '</div>'; $(myLapDetails).prependTo(".loop"); } });
true
d15d0d4546b2754e24ccebbb01781476c6a812d8
JavaScript
willsparrowc/the-game-of-24dots
/Code/pages/main/game_manager.js
UTF-8
5,658
2.65625
3
[]
no_license
var app = getApp() var util = require('../../utils/util.js') var Card = require('../../utils/card.js') var Box = require('../../utils/box.js') var Banner = require('../../utils/banner.js') var Timer = require('../../utils/timer.js') var Expression = require('../../utils/expression.js') function GameManager() { this.size = 4 this.periodIndex = 0 this.period = util.periods[this.periodIndex] // 初试状态为简易E this.failExpressions = [] // 失败的表达式记录 this.overTime = 0 this.winTime = 0 } GameManager.prototype = { setup: function() { this.failTimes = 0 // 当前超时次数 this.solveTimes = 0 // 当前解决次数 this.quickSolveTimes = 0 // 当前快速解决次数 this.banner = new Banner(this.period) this.timer = new Timer(this.period) this.box = new Box(this.period) this.expression = new Expression(this.period) this.expression.getNewExpression() this.timer.startTimer() this.addCards(this.expression.nums) }, /** * 重新启动函数 */ restartSuccess: function (remainTime) { this.timer.endTimer() var solveTimes = this.solveTimes + 1 // 暗藏模式 if(++(this.winTime) == util.winTime && this.overTime == 0){ this.final() } // 快速完成 var quickSolveTimes = this.quickSolveTimes if(this.timer.isQuick(remainTime)) ++quickSolveTimes if(solveTimes == util.upgradeTime.normal || quickSolveTimes == util.upgradeTime.quick){ // 达到一般升级的次数 wx.showToast({ title: 'PASS!', image: '../../images/upgrade.png', duration: 5000 }) console.log("升级") this.upgrade() this.setup() } else { // 没有达到升级的次数 wx.showToast({ title: 'RIGHT!', icon: 'success', duration: 5000 }) console.log('======成功重启=====') this.solveTimes = solveTimes this.quickSolveTimes = quickSolveTimes this.restart() } }, // 超时重启,返回值用来判断是否游戏结束 restartFail: function () { this.timer.endTimer() this.failExpressions.push(this.expression) var failTimes = this.failTimes + 1 this.overTime += 1 // 最高优先级 overTime if (this.overTime == util.overTime){ this.final() return true } // 简易状态的重启和结束游戏 if(this.period == util.periods[0]){ if(failTimes == util.downgradeTime.normal){ this.final() return true } else { this.failA(failTimes) } } else if (this.period == util.periods[1]) { // 中等状态的重启和降级 if(failTimes == util.downgradeTime.normal){ this.failB() } else { this.failA(failTimes) } } else { // 三种困难状态的重启和降级 if (failTimes == util.downgradeTime.difficult) { this.failB() } else { this.failA(failTimes) } } return false }, // 重启的一些小函数 restart: function () { /* 更新卡片和计时器 */ this.emptyBox() this.expression = new Expression(this.period) this.timer.setRemainTime(this.timer.getStartTime()) this.expression.getNewExpression() this.addCards(this.expression.nums) this.timer.startTimer() }, final: function () { app.globalData.expressions = this.getFailExpressions() wx.redirectTo({ url: '../index/index', }) }, failA: function (failTimes) { wx.showToast({ title: 'TIME OUT!', image: '../../images/fail.png', duration: 5000 }) console.log('========失败重启========') this.failTimes = failTimes this.restart() }, failB: function () { wx.showToast({ title: 'FAIL!', image: '../../images/downgrade.png', duration: 5000 }) console.log('====降级====') this.downgrade() this.setup() }, /** * 卡片操作 */ lockCard: function (position) { this.box.cards[position].lock() }, unlockCard: function (position) { this.box.cards[position].unlock() }, getCardColor: function (position) { return this.box.cards[position].getColor() }, addCards: function (nums) { for (var i = 0; i < this.size; ++i) { var card = new Card(i, nums[i]) this.box.insertCard(card) } }, emptyBox: function (){ this.box.cards = this.box.create() }, calculate: function (selectedCards, operator) { // 当合并卡片结果为24,且为最后一张卡片 if (this.box.join(selectedCards, operator) == 24) if (this.box.getHiddenCardsNum() == this.size-1) return true return false }, /** * 状态的改变 */ upgrade: function() { var index = this.periodIndex if(index + 1 < util.periods.length) ++index this.period = util.periods[index] this.periodIndex = index }, downgrade: function() { var index = this.periodIndex if(index - 1 >= 0) --index this.period = util.periods[index] this.periodIndex = index }, /** * 其他函数 */ goback: function (position1, position2) { this.box.split(position1, position2) }, getCards: function () { return this.box.cards }, getBanner: function () { return this.banner.getBanner() }, getFailExpressions: function () { var expressionsToString = '' for (var i = 0; i < this.failExpressions.length; ++i){ expressionsToString += this.failExpressions[i].toString() expressionsToString += '\n' } return expressionsToString } } module.exports = GameManager
true
1b786ed21d61cf490b2fadcb4345c3d8309d32d1
JavaScript
Diplomatiq/resily
/scripts/check-release-tag.mjs
UTF-8
1,154
2.75
3
[ "MIT" ]
permissive
/** * This script reads the version field from package.json * and checks if the current git HEAD has a matching tag. * * E.g. if the current version is '1.0.0', the matching tag is 'v1.0.0'. * * Runs automatically on `npm publish`. */ import { spawnSync } from 'child_process'; import { readFileSync } from 'fs'; import { dirname, join } from 'path'; import { fileURLToPath } from 'url'; const { stdout } = spawnSync('git', ['describe', '--tags', '--exact-match'], { encoding: 'utf-8' }); const tag = stdout.trim(); const currentDir = dirname(fileURLToPath(import.meta.url)); const packageJsonPath = join(currentDir, '..', 'package.json'); const packageJsonContents = readFileSync(packageJsonPath, { encoding: 'utf-8' }); const packageJson = JSON.parse(packageJsonContents); const packageVersion = packageJson.version; if (tag !== `v${packageVersion}`) { if (tag) { console.log( `Current tag (${tag}) does not match package version (${packageVersion}). Publishing from wrong branch?`, ); } else { console.log(`Current commit has no tag. Publishing from wrong branch?`); } process.exit(1); }
true
3973acdb0dc81695edb2948ddb2800b1795fcec1
JavaScript
dnhart/giphy-api
/assets/javascript/giphyapi.js
UTF-8
3,985
2.9375
3
[ "MIT" ]
permissive
var topics=["angry","bored", "confused", "happy dance", "unimpressed", "good job", "bye", "mind blown", "eye roll", "inspired", "no", "yes", "whatever", "thank you", "shocked"]; var searchTerm; function setup(){ $("#buttonBox").html(""); $.each(topics, function(i, value) { var newButton =$("<button type='button' class='btn btn-info buttonSearch' value='"+value+"'>"+value+'</button>'); var buttonBox =$("#buttonBox"); buttonBox.append(newButton); }); //assign onClick functionality to display gifs from Giphy when topic buton is clicked. $(".buttonSearch").on("click", buttonSearch); }; //setup initial buttons from the topics array setup(); //assigns onClick function to search button $(".userInput").on("click", userNormalSearch); $(".userAnimeInput").on("click", userAnimeSearch); //sets searchTerm when topic button is clicked function buttonSearch(){ searchTerm = this.attributes[2].value; searchTerm = searchTerm.replace(/\s+/g, '+').toLowerCase(); displayGifs (); }; //sets searchTerm when the user enters a term in the search box function userNormalSearch(e){ e.preventDefault(); searchTerm = $('#search').val().trim(); userSearch(); }; function userAnimeSearch(e){ e.preventDefault(); if($('#search').val().trim()){ searchTerm ="Anime "+ $('#search').val().trim(); userSearch();} else { alert("Please enter a new topic."); } }; function userSearch(e){ if (searchTerm && topics.indexOf(searchTerm) === -1) { topics.push(searchTerm); setup(); searchTerm = searchTerm.replace(/\s+/g, '+').toLowerCase(); displayGifs (); } else { alert("Please enter a new topic."); }; $('#search').val(''); $('#search').attr("placeholder", "Search"); }; //takes the searchTerm, queries Giphy, and displays results. function displayGifs (){ //giphy query var queryURL = "https://api.giphy.com/v1/gifs/search?q="+searchTerm+"&api_key=dc6zaTOxFJmzC&rating=pg-13&limit=10"; //pulls the inforation (still image, animated image, rating, and slug) from the gighy JSON object $.ajax({ url: queryURL, method: 'GET' }).done(function(response) { var giphyArray = response; var importArray =giphyArray.data; //clears the existing images, if any $("#photoContainer").html(""); // Wrap everything in an IIFE (function($, viewport){ // Executes only in XS breakpoint if( viewport.is('xs') ) { //pulls the variables and displays the images from the JSON object $.each(importArray, function(key, value){ var whatisthekey = key; var stillImage = value.images.fixed_height_small_still.url; var animatedImage = value.images.fixed_height_small.url; var rating = value.rating; var slug = value.slug; $("#photoContainer").append("<div class='portfolio-item'><img class='img-responsive still' src="+stillImage+" alt='"+slug+"'><img class='img-responsive animated' src="+animatedImage+" alt='"+slug+"'><figcaption>Rating: "+rating+"</div>"); }); } // Executes in SM, MD and LG breakpoints if( viewport.is('>=sm') ) { $.each(importArray, function(key, value){ var whatisthekey = key; var stillImage = value.images.fixed_height_still.url; var animatedImage = value.images.fixed_height.url; var rating = value.ratng; var slug = value.slug; $("#photoContainer").append("<div class='portfolio-item'><img class='img-responsive still' src="+stillImage+" alt='"+slug+"'><img class='img-responsive animated' src="+animatedImage+" alt='"+slug+"'><figcaption>Rating: "+rating+" </div>"); }); };//end if viewport >sm //assigns onClick functionality to images $(".portfolio-item").on("click", toggleGifs); })(jQuery, ResponsiveBootstrapToolkit); }); //end ajax loop };//end displayGifs //toggles visibiity on still and animated images function toggleGifs (event){ $(event.currentTarget.firstChild).toggle(); $(event.currentTarget.childNodes[1]).toggle(); };
true
35345273c3ced905f939b824c68eb0e8218613af
JavaScript
schoenflies/cracking_the_coding_interview
/src/chapter_1/1.6 String_Compression.js
UTF-8
429
3.265625
3
[]
no_license
//Time complexity is O(n) export function strComp(str) { if (!str || str.length === 0) { return str; } let store = {}; for (let i = 0; i < str.length; i++) { let char = str.charAt(i); if (store[char]) { store[char]++; } else { store[char] = 1; } } let comp = []; for (let key in store) { comp.push(store[key], key); } return comp.length < str.length ? comp.join('') : str; }
true