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
b27a0a8d8ae66bceffdc2f76a78306f2504b6140
JavaScript
mdmubeenkhan/rms
/src/main/webapp/js/review.js
UTF-8
6,711
2.78125
3
[]
no_license
function view(){ var rowId = event.target.parentNode.id; var data = document.getElementById(rowId).querySelectorAll("td"); var rowID = data[1].innerHTML; var rowVER = 0; localStorage.setItem("rowID", rowID); localStorage.setItem("rowVER", rowVER); window.location.replace("http://localhost:9080/RMS/view.html"); } function loadreview(){ document.getElementById("userName").innerHTML = localStorage.getItem("dbusername"); document.getElementById("role").innerHTML = localStorage.getItem("dbusertype"); disablelinks(); const url1 = 'http://localhost:9080/RMS/api/rms/review-data-from-db'; const data = { "username":localStorage.getItem("dbusername"), } var xhr = new XMLHttpRequest(); xhr.open("POST", url1, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(data)); xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var apiResponse = this.responseText; var tablebody = document.getElementById("tableBody"); if(apiResponse === "[]"){ //tablebody.innerHTML = "No records found"; document.getElementById("dataentry").innerHTML = "No records found"; }else{ var res = apiResponse.replace("[", "").replace("]", ""); let obj = res.split('},'); for(var i=0;i<obj.length;i++ ){ var rowRecord = obj[i].replace("{","").replace("}",""); var rowArray = rowRecord.split(","); var row = tablebody.insertRow(i); row.setAttribute("id","row"+i); row.setAttribute('ondblclick',"view()"); var checkbox = document.createElement("input"); checkbox.setAttribute("type","checkbox"); checkbox.setAttribute("id","check"+i); checkbox.setAttribute("selected","false"); checkbox.setAttribute('onclick',"check()"); row.insertCell(0).appendChild(checkbox); for(var j=0;j<rowArray.length;j++){ cellArray = rowArray[j].split(":"); cellRecord = cellArray[1].replace("\"", "").replace("\"", ""); var cell = row.insertCell(j+1); cell.innerHTML = cellRecord; } } } } }; } function check(){ var checkId = event.target.id; var selected = document.getElementById(checkId).getAttribute("selected"); if(selected === "false"){ document.getElementById(checkId).setAttribute("checked","true"); document.getElementById(checkId).setAttribute("selected","true"); }else if(selected === "true"){ document.getElementById(checkId).setAttribute("checked","false"); document.getElementById(checkId).setAttribute("selected","false"); } var rowId = event.target.parentNode.parentNode.id; var data = document.getElementById(rowId).querySelectorAll("td"); var rowID = data[1].innerHTML; localStorage.setItem("rowID", rowID); } function approvedata(){ var checkboxes = document.querySelectorAll("input[type=checkbox]"); var count = 0; for(var i=0;i<checkboxes.length;i++){ if(checkboxes[i].getAttribute("selected") === "true"){ count = count+1; } } if(count == "0"){ alert("Select atleast one record to approve"); }else if(count > "1"){ alert("Select only one record to approve"); }else if(count == "1"){ var rowID = localStorage.getItem("rowID") } const url2 = 'http://localhost:9080/RMS/api/rms/approve-review-data'; const data = { "ID":rowID, } var xhr = new XMLHttpRequest(); xhr.open("POST", url2, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(data)); xhr.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200 ) { var apiResponse = this.responseText; if(apiResponse === "[]"){ document.getElementById("dataentry").innerHTML = "No records found" ; }else{ document.getElementById("dataentry").innerHTML = "Requirement is approved" ; } }else if(this.readyState === 4 && this.status !== 200){ document.getElementById("dataentry").innerHTML = "Requirement is not approved" ; } }; } function rejectdata(){ var checkboxes = document.querySelectorAll("input[type=checkbox]"); var count = 0; for(var i=0;i<checkboxes.length;i++){ if(checkboxes[i].getAttribute("selected") === "true"){ count = count+1; } } if(count == "0"){ alert("Select atleast one record to reject"); }else if(count > "1"){ alert("Select only one record to reject"); }else if(count == "1"){ var rowID = localStorage.getItem("rowID") } const url3 = 'http://localhost:9080/RMS/api/rms/reject-review-data'; const data = { "ID":rowID, } var xhr = new XMLHttpRequest(); xhr.open("POST", url3, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(data)); xhr.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200 ) { var apiResponse = this.responseText; if(apiResponse === "[]"){ //document.getElementById("dataentry").innerHTML = "No records found" ; }else{ document.getElementById("dataentry").innerHTML = "Requirement is rejected" ; } }else if(this.readyState === 4 && this.status !== 200){ document.getElementById("dataentry").innerHTML = "Requirement is not rejected" ; } }; } function modifydata(){ var checkboxes = document.querySelectorAll("input[type=checkbox]"); var count = 0; for(var i=0;i<checkboxes.length;i++){ if(checkboxes[i].getAttribute("selected") === "true"){ count = count+1; } } if(count == "0"){ alert("Select atleast one record to modify"); }else if(count > "1"){ alert("Select only one record to modify"); }else if(count == "1"){ var rowID = localStorage.getItem("rowID") } const url4 = 'http://localhost:9080/RMS/api/rms/modify-review-data'; const data = { "ID":rowID, } var xhr = new XMLHttpRequest(); xhr.open("POST", url4, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(data)); xhr.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200 ) { var apiResponse = this.responseText; if(apiResponse === "[]"){ document.getElementById("dataentry").innerHTML = "No records found" ; }else{ document.getElementById("dataentry").innerHTML = "Requirement needs modification" ; } }else if(this.readyState === 4 && this.status !== 200){ document.getElementById("dataentry").innerHTML = "Requirement does not need modification" ; } }; }
true
59f91982d140b174fdd233f2603b8dad827c238e
JavaScript
sasha370/sasha370-TestGuru
/app/javascript/utilities/check_password_confirmation.js
UTF-8
1,150
2.953125
3
[]
no_license
document.addEventListener('turbolinks:load', function () { // Get form block whit password form = document.querySelector('.need-validation') if (form) { var passwordField = this.querySelector('.password_field') var confirmationField = this.querySelector('.confirmation_field') // listen to an event in any field if (passwordField && confirmationField) { passwordField.addEventListener('input', validateFields) confirmationField.addEventListener('input', validateFields) } function validateFields() { var password = passwordField.value var confirmation = confirmationField.value if (confirmation === '') { // cleaUp field`s status if delete all chars confirmationField.classList.remove('is-invalid') confirmationField.classList.remove('is-valid') return } if (password !== confirmation) { confirmationField.classList.remove('is-valid') confirmationField.classList.add('is-invalid') } else { confirmationField.classList.remove('is-invalid') confirmationField.classList.add('is-valid') } } } })
true
e160afb0466a49cfbf700512dd772105fb3eaf48
JavaScript
asafeliasim/COVID19-react-chartjs
/src/App.js
UTF-8
916
2.609375
3
[]
no_license
import React,{useEffect,useState} from 'react'; import {Cards,Chart,CountryPicker} from './components'; import styles from './App.module.css' import {fetchData} from "./api"; import covid19 from './images/covid19.png'; const App =()=> { const [data,setData] = useState({}); const [country,setCountry] = useState(""); useEffect(async()=>{ setData(await fetchData()); },[setData,setCountry]) const handleCountryChange = async (country) => { const fetchedData = await fetchData(country); setCountry(country) setData(fetchedData); console.log(fetchedData); } return ( <div className={styles.container}> <img className={styles.image} src={covid19} alt="Covid19"/> <Cards data={data}/> <CountryPicker handleCountryChange={handleCountryChange}/> <Chart data={data} country={country}/> </div> ); } export default App;
true
c587110636471ba4fe43a5a470ebe26592d9ea6f
JavaScript
Kradox27/rukaPro2.0
/middleware/handlebars.js
UTF-8
1,039
2.546875
3
[]
no_license
const Handlebars = require('handlebars'); const moment = require('moment'); Handlebars.registerHelper({ eq: (v1, v2) => v1 === v2, eqRol: (v1) => global.permisos.some(e => e.codigoPermiso == v1), eqBool: (v1) => v1 === true, ne: (v1, v2) => v1 !== v2, lt: (v1, v2) => v1 < v2, gt: (v1, v2) => v1 > v2, lte: (v1, v2) => v1 <= v2, gte: (v1, v2) => v1 >= v2, and() { return Array.prototype.slice.call(arguments, 0, arguments.length - 1).every(Boolean); }, or() { return Array.prototype.slice.call(arguments, 0, arguments.length - 1).some(Boolean); }, toJSON: (obj) => { return JSON.stringify(obj, null, 3) }, formatDate: (date) => { return date != "" ? moment.tz(date, "America/Santiago").format("DD/MM/YYYY") : ""; }, formatMoney: (money) => { return utils.formatMoney(money); }, toUpper: (string) => { return string.toUpperCase(); }, toLower: (string) => { return string.toLowerCase(); }, });
true
24945ee4fd0f359ae74861d63e2d42fa515ee149
JavaScript
dannewoo/creativecode
/p5js/Week10_keys_events_images/key_events_07_key_press_release/sketch.js
UTF-8
380
3.171875
3
[]
no_license
var drawT = false; function setup() { createCanvas(600, 400); background(0); noStroke(); textSize(200); textAlign(CENTER); fill(255); } function draw() { background(0); if (drawT == true) { text("T", width/2, height/2 + 75); } } function keyPressed() { if (key == 'T' || key == 't') { drawT = true; } } function keyReleased() { drawT = false; }
true
9da1a25aa189cf18b658016c08ee0f87a0fd0026
JavaScript
FlamingLotusGirls/Serenity
/sound/SoundAdmin/SoundAdmin.js
UTF-8
15,451
2.609375
3
[ "MIT" ]
permissive
const fs = require('fs'); const express = require('express'); const cors = require('cors'); const http = require('http'); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: true })); // I think this means we support that too app.use(cors()); const port = 9000; // https://codeburst.io/node-js-best-practices-smarter-ways-to-manage-config-files-and-variables-893eef56cbef const config = require('./data/config.json') var g_scape = null; var g_sinks = null; // PUT to listening SerenityAudio controllers. They might be down so timeouts, and async! function controllers_update(path, scape) { console.log('notifying Sound players of changes'); const postData = JSON.stringify(scape); // todo: for each host in configured list, try to get just the first one going first :-) config.controllers.forEach(function(host){ console.log('posting to %s',host); const options = { hostname: host, port: 8000, path: path, method: 'PUT', headers: { 'Content-Type': 'application/json', 'Content-Length': postData.length } }; const req = http.request(options, (res) => { console.log(`HTTP REQUEST STATUS: ${res.statusCode}`); res.setEncoding('utf8'); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); res.on('end', () => { console.log('No more data in response.'); }); }); req.on('error', (e) => { console.error(`problem with request: ${e.message}`); }); // Write data to request body // console.log('writing the data: len %d\n',postData.length); req.setTimeout(500); // don't want to get too far behind, better to give up req.write(postData); req.end(); }); } // SCAPE FILES // Read from the default file function scape_init() { // first try to load the last thing that was set //console.log('scape init'); var rawdata = null; if (fs.existsSync(config.currentScape)) { rawdata = fs.readFileSync(config.currentScape); } else { rawdata = fs.readFileSync(config.soundscapeDir + 'default.json'); } var s = JSON.parse(rawdata); s = scape_correctify(s) //console.log(s); return(s); } // There are cases where there might be sub-entities which are "named" // but have never been set or never configured. They should all have // 0's for volume and-or intentisty. While the code is supposed to no longer // remove elements, some might, so write this helper function that // will make sure all the items are where they are supposed to be. // returns the newly fixed object function scape_correctify(s) { // ZONES if (s.hasOwnProperty('zones') == false) { s.zones = {}; } if (s.zones.hasOwnProperty('names') == false) { s.zones.names = config.zones.names; } var zones = s.zones.names; for (let zone of zones) { if (zones.hasOwnProperty(zone) == false) { zones[zone] = {} } if (zones[zone].hasOwnProperty("volume")==false) { zones[zone].volume = 0 } } // EFFECTS if (s.hasOwnProperty('effects') == false) { s.effects = {}; } if (s.effects.hasOwnProperty('names') == false) { s.effects.names = config.effects.names; } var names = s.effects.names; for (let name of names) { if (names.hasOwnProperty(name) == false) { names[name] = {} } if (names[name].hasOwnProperty("volume")==false) { names[name].volume = 0 } if (names[name].hasOwnProperty("intensity")==false) { names[name].intensity = 0 } } // MASTER if (s.hasOwnProperty('master') == false) { s.master = {} } if (s.master.hasOwnProperty('volume') == false) { s.master.volume = 0; } // BACKGROUND if (s.hasOwnProperty('background') == false) { s.background = {} } if (s.background.hasOwnProperty('name') == false) { s.background.name = ''; } if (s.background.hasOwnProperty('volume') == false) { s.background.volume = 0; } return(s); } // write the newly changed scape to the last file function scape_flush(s) { fs.writeFileSync(config.currentScape, JSON.stringify(s)); //console.log(' flushed current scape '); console.log("updating controllers with new soundscape"); controllers_update("/soundscape", s); } // Init function, load the scape g_scape = scape_init(); // SINK FILE // Read from the default file function sink_init() { // first try to load the last thing that was set //console.log('scape init'); var rawdata = null; if (fs.existsSync(config.currentSink)) { rawdata = fs.readFileSync(config.currentSink); } else { rawdata = fs.readFileSync(config.defaultSink); } var s = JSON.parse(rawdata); //console.log(s); return(s); } // write the newly changed scape to the last file function sink_flush(s) { fs.writeFileSync(config.currentSink, JSON.stringify(g_sink)); //console.log(' flushed current sink '); console.log(" pushing sink changes to remotes "); // and send it to any players who might be listening.... asynchrnously!!! controllers_update("/sinks", s); } // Init function, load the scape g_sink = sink_init(); // // Endpoints // // Get the list of all possible backgrounds app.get('/audio/backgrounds', (req, res) => { console.log("got audio backgrounds"); res.json(config.backgrounds) }) // the current playing app.get('/audio/background', (req,res) => { console.log("got audio background"); res.json(g_scape.background); }) // res is there to throw errors function background_put(bg, res) { if (bg.hasOwnProperty('volume') == false) { res.status(400); res.send('background must have a volume'); return(false); } if ((bg.volume < 0) || (bg.volume > 100)) { res.status(400); res.send('volume '+bg.volume+' out of range'); return(false); } // If volume is zero, ignore name if (bg.volume == 0) { bg.name = '' } else { if (bg.hasOwnProperty('name') == false) { res.status(400); res.send('background must have a name'); return(false); } if (config.backgrounds.names.includes(bg.name) == false) { res.status(400); res.send(bg.name + ' is not a supported name'); return(false); } } g_scape.background.name = bg.name; g_scape.background.volume = bg.volume; return(true); } app.put('/audio/background', (req, res) => { console.log('got a PUT audio background request'); console.log(req.body); // side effect: sends error responses if failure if (false == background_put(req.body, res)) return; // TODO: notify all players of new background scape_flush(g_scape); res.send(g_scape.background); }) // Returns the current list of sounscapes as an array app.get('/audio/soundscapes', (req, res) => { console.log(" audio soundscape get "); var files = fs.readdirSync(config.soundscapeDir); // This isn't preciese because I only want the trailing .json var ret = {} ret.names = files.map(str => str.replace('.json','')) res.send(ret); }) // create a new soundscale with id 'id' using the current senttings //if no object is passed in, or with the passed in object app.post('/audio/soundscapes/:id', (req, res) => { console.log(" post soundscape id %s",id ); var id = req.params.id; // if exists fail var fn = config.soundscapeDir+id+'.json'; if (fs.existsSync(fn)) { res.status(400); res.send(id + ' already exists') return; } g_scape = scape_correctify(g_scape); // if empty body use default if (Object.keys(req.body).length==0) { fs.writeFileSync(fn, JSON.stringify(g_scape)); res.send(g_scape) } else { // TODO: should validate this fs.writeFileSync(fn, JSON.stringify(req.body)); res.send(req.body) } }) // Get any named one... and make it current or not? app.get('/audio/soundscapes/:id', (req, res) => { console.log(" audio soundscapes get id %s",id); const fileName = config.soundscapeDir + req.params.id + '.json'; return fs.readFile(fileName, function(err, data) { if (err) { if (err.code === 'ENOENT') { res.status(404); } else { res.status(500); } return res.send(`Error reading soundscape file ${fileName}: ${err.message}`); } return res.send(data); }); }) // Delete the soundscape /audio/soundscapes/NAME app.delete('/audio/soundscapes/:id', (req, res) => { console.log("audio soundscapes DELETE id %d",id); var id = req.params.id; if (id == 'default') { res.status(400) res.send(' cant remove the default'); return } var fn = config.soundscapeDir+id+'.json'; if (fs.existsSync(fn) == false) { res.status(400); res.send(id + ' does not exist') return; } fs.unlinkSync(fn) res.send('OK') }) // Returns the current sounscape as a JSON object app.get('/audio/soundscape', (req, res) => { console.log(" audio soundscape get "); // Maybe we want all the names in here. I don't think so though. //var ret = Object.assign({},g_scape) //ret.zones.names = config.zones.names //ret.background.names = config.backgrounds.names //ret.effects.names = config.effects.names //res.send(ret) res.json(g_scape); }) // Update the current soundscape app.put('/audio/soundscape', (req, res) => { console.log(" audio soundscape put "); if (req.body.background) { if (!background_put(req.body.background, res)) return; } if (req.body.effects) { if (!effects_put(req.body.effects, res)) return; } if (req.body.zones) { if (!zones_put(req.body.zones, res)) return; } if (req.body.master) { var master = req.body.master; if ((master.volume > 100) || (master.volume < 0)) { res.status(400); res.send(key + ' volume out of range'); return; } g_scape.master = master; } // make sure the result has all the things g_scape = scape_correctify(g_scape) scape_flush(g_scape); res.json(g_scape) }) app.get('/audio/effects', (req,res) => { console.log(" getting effects "); var effects = {}; effects.names = config.effects.names; for (const [key, value] of Object.entries(g_scape.effects)) { effects[key] = value; } //console.log(effects); res.send(effects) }) function effects_put(eff, res) { console.log("effects puts"); // Validate input for (const [key, value] of Object.entries(eff)) { //console.log(' validating %s object %s ',key,JSON.stringify(value)); // is the name valid if (config.effects.names.includes(key) == false) { res.status(400); res.send(key + ' is not a supported name') return(false); } if (value.hasOwnProperty('intensity') == true) { if ((value.intensity > 3) || (value.intensity < 0)) { res.status(400); res.send(key + ' intensity out of range'); return(false); } } if (value.hasOwnProperty('volume') == true) { if ((value.volume > 100) || (value.volume < 0)) { res.status(400); res.send(key + ' volume out of range'); return(false); } } } // valid, replace for (const [key, value] of Object.entries(eff)) { if (g_scape.effects.hasOwnProperty(key)==false) { g_scape.effects[key] = {} g_scape.effects[key].intensity = 0; g_scape.effects[key].volume = 0; } if (value.hasOwnProperty('intensity')==true) { g_scape.effects[key].intensity = value.intensity; } if (value.hasOwnProperty('volume')==true) { g_scape.effects[key].volume = value.volume; } } return(true); } app.put('/audio/effects', (req,res) => { console.log('got a PUT effects request'); console.log(req.body); if (effects_put(req.body, res) == false) return; scape = scape_correctify(g_scape); scape_flush(g_scape); // Todo: update sound players res.json(g_scape.effects) }) app.get('/audio/zones', (req, res) => { console.log(' endpoint audio zones called '); var ret = {} ret.names = config.zones.names; for (const [key, value] of Object.entries(g_scape.zones)) { if (value.volume > 0) { ret[key] = value; } } res.json(ret); }) function zones_put(z, res) { console.log("zones put"); // Validate input for (const [key, value] of Object.entries(z)) { //console.log(' validating %s object %s ',key,JSON.stringify(value)); // is the name valid if (config.zones.names.includes(key) == false) { res.status(400); res.send(key + ' is not a supported name') return(false); } if (value.hasOwnProperty('volume') == false) { res.status(400); res.send(key + ' must have volume') return(false); } if ((value.volume > 100) || (value.volume < 0)) { res.status(400); res.send(key + ' volume out of range'); return(false); } } // valid, replace for (const [key, value] of Object.entries(z)) { g_scape.zones[key] = value; } return(true); } app.get('/audio/master', (req,res) => { console.log(" get master object"); res.send( g_scape.master ) }) app.put('/audio/master', (req, res) => { console.log(' setting the master object ') console.log(req.body) var master = req.body if ((master.volume > 100) || (master.volume < 0)) { res.status(400); res.send(key + ' volume out of range'); return(false); } g_scape.master = master; scape_flush(g_scape); res.send('OK') }) // set zones only through the put scape stuff app.get('/audio/sinks', (req, res) => { console.log(" audio sinks GET "); var ret = {} ret.names = config.sinks.names; for (const [key, value] of Object.entries(g_sink)) { if (value.volume > 0) { ret[key] = value; } } res.send(ret); }) app.put('/audio/sinks', (req, res) => { console.log('got a PUT sinks request'); console.log(req.body); // Validate input for (const [key, value] of Object.entries(req.body)) { //console.log(' Sinks: validating %s object %s ',key,JSON.stringify(value)); // is the name valid if (config.sinks.names.includes(key) == false) { res.status(400); res.send(key + ' is not a supported name') return; } if (value.hasOwnProperty('volume') == false) { res.status(400); res.send(key + ' must have volume') return; } if ((value.volume > 100) || (value.volume < 0)) { res.status(400); res.send(key + ' volume out of range'); return; } } // valid, replace for (const [key, value] of Object.entries(req.body)) { g_sink[key] = value; } sink_flush(g_sink); // Todo: update sound players res.send(g_sink) }) // This is maybe a little weird. // There are 6 pairs of buttons on the sculpture // 1/1 and 1/2 ( which is a pair ) // through // 6/1 and 6/2 // When one gets hit, call this endpoint // // You don't have to put any data, putting to this means that button was hit // app.put('/audio/buttons/:bgroup/:button', (req, res) => { console.log(" audio buttons put "); var bgroup = req.params.bgroup; var button = req.params.button; // look up in Config if (config.buttons.hasOwnProperty(bgroup) == false) { res.status(400); res.send('button group '+bgroup+' not defined in config'); return(false); } if ((button != "0") && (button != "1")) { res.status(400); res.send('button '+button+' not defined, only 0 and 1 allowed'); return(false); } var effect = config.buttons[bgroup].effect; // off button if (button == "0") { g_scape.effects[effect].intensity = 0 } else if ( button == "1") { g_scape.effects[effect].intensity++ ; if (g_scape.effects[effect].intensity > 3) g_scape.effects[effect].intensity = 3; if (g_scape.effects[effect].volume == 0) { g_scape.effects[effect].volume = config.buttons[bgroup].volume; } } //console.log(g_scape.effects[effect]) scape_flush(g_scape); res.send('OK') }) app.get('/', (req, res) => res.send('Hello World from SoundAdmin!')) app.listen(port, () => { console.log(`SoundAdmin listening on port ${port}`) })
true
a2af26d6fda36f99a0cde68ba6ba785cdc79ce1c
JavaScript
AlameerAshraf/Online-Store
/js/ProjectJs/OrdersLoader.js
UTF-8
2,482
2.65625
3
[ "MIT" ]
permissive
var Data = document.getElementsByClassName("in-check") ; var ItemsNumbers = document.getElementsByClassName("cart-items") ; var db = openDatabase("AsssS", '1.0', "My WebSQL Database", 8 * 1024 * 1024); var select = function () { db.transaction(function (tx) { tx.executeSql("SELECT * FROM ST23 WHERE Pieces != 0 ", [], function (tx, results) { if (results.rows.length > 0) { ItemsNumbers[0].innerHTML += " <h3>My Shopping Bag ("+ results.rows.length +")</h3> " + "<div style='text-align: center ;'> <a onclick='myFunction()' class = 'add-cart item_add' > Order Now ! </a> </div> "; for( var i = 0 ; i< results.rows.length ; i++){ Data[0].innerHTML += "<ul class='cart-header'>"+" <div class='close1'></div> "+" <li class='ring-in'>" + "<a onmouseover='' style='cursor: pointer;'' onclick='Redirect(\""+ results.rows.item(i).Product_Name +"\")' >" +" <img src='" + results.rows.item(i).image+ "' class='img-responsive' alt=''> " + " </a>" + " </li>" + " <li><span class='name'>" + results.rows.item(i).Product_Name + "</span></li> " + " <li><span class='cost'>$ " + results.rows.item(i).price + "</span></li> " + " <li><span>"+ results.rows.item(i).Pieces +"</span> " + " <p> Total price for that product " + (results.rows.item(i).price * results.rows.item(i).Pieces).toFixed(2) + "</p></li> " + " <div class='clearfix'></div> " + " </ul> " ; } } else { Data[0].innerHTML += "<div class='bar'' > <P> You aren't Order Any Thing yet , We Hope you're Happy shopping with us </P> </div> " ; } }); }); } function myFunction() { document.getElementsByClassName("ckeckout")[0].style.display = "none" ; console.log(document.getElementsByClassName("lastview")[0]) ; document.getElementsByClassName("lastview")[0].style.display = "block" ; } function LoadItems () { select() ; } function Redirect (name) { window.location="single.html?ProductName="+""+ name +""; } function Empty () { document.getElementsByClassName("ckeckout")[0].style.display = "none" ; console.log(document.getElementsByClassName("lastview")[0]) ; document.getElementsByClassName("lastview")[0].style.display = "block" ; }
true
bcb3d3a28fda8671a2f92054b4316291aaab1c33
JavaScript
SaraMoya/todo-web
/src/App.js
UTF-8
1,404
2.796875
3
[]
no_license
import React, { useEffect } from 'react'; import TodosList from './todosList'; import Bar from './bar.js'; import './App.css'; class App extends React.Component { state = {todos: [], task: '' } handleChange = event => { let { task } = {...this.state} task = event.target.value this.setState({ task }) } addTodo = () => { if (this.state.task.length > 0) { let { todos } = { ...this.state }; todos.push({task: this.state.task, completed: false}) this.setState({ todos }); let { task } = {...this.state} task = '' this.setState({ task }) } } removeTodo = (indx) => { let { todos } = { ...this.state }; todos.splice(indx, 1) this.setState({ todos }); } completedTodo = (indx) => { let { todos } = {...this.state} todos[indx].completed = !todos[indx].completed this.setState({todos}) } editTodo = (indx, text) => { let { todos } = {...this.state} todos[indx].task = text console.log(todos) this.setState({todos}) } render(){ return ( <div className="App"> <Bar todos={this.state.todos} addTodo={this.addTodo} handleChange={this.handleChange} task={this.state.task}/> <TodosList todos={this.state.todos} removeTodo={this.removeTodo} completedTodo={this.completedTodo} editTodo={this.editTodo}/> </div> ); } } export default App;
true
8421c2d22d24a8cbee66ca3c43526551650f202d
JavaScript
shfeat/tampermonkey-extension
/scripts/dytt-remove-ads.js
UTF-8
4,994
2.875
3
[]
no_license
// ==UserScript== // @name 电影天堂,阳光电影去掉广告与高亮高分电影 // @namespace https://github.com/yujinpan/tampermonkey-extension // @version 1.3 // @license MIT // @description 主要是在电影天堂,阳光电影网站去掉页面上的广告(隐藏广告比较烦)。还有就是标记高分和获奖的电影,方便找到精华电影。 // @author yujinpan // @include http*://www.dytt8.net/* // @include http*://www.ygdy8.com/* // @include http*://www.dy2018.com/* // @include http*://www.xiaopian.com/* // @include http*://www.dygod.net/* // ==/UserScript== /** * 已有功能列表: * - 功能1:删除第一次加载出现的广告 * - 功能2:标记高分电影 * - 功能3:去掉搜索框的广告跳转 * - 功能4:去掉中间页面上的flash广告 * - 功能5:删除右下角的flash广告 * - 功能6:去掉按任意键弹出广告 * - 功能7:去掉首次点击任何地方弹出广告 */ // 功能1:删除第一次加载出现的广告 // 功能5:删除右下角的flash广告 (function() { // 生成广告列表实例 var ads = new Ads(['link', 'flash']); // 循环搜索广告 var adSearchCounter = 0; (function removeAd() { adSearchCounter++; console.log('第' + adSearchCounter + '次查找广告。'); var elems = document.body.children; // 查找全屏链接广告 var link = elems[0]; if (ads.get('link') && link && link.nodeName === 'A' && link.href) { link.remove(); ads.remove('link'); console.log(`找到全屏链接广告!成功删除!`); } // 查找右下角flash窗口 var flash = elems[elems.length - 1]; if (ads.get('flash') && flash && flash.style.position === 'fixed') { flash.remove(); ads.remove('flash'); console.log('找到右下角flash窗口!成功删除!'); } // 判断是否删除完毕 if (!ads.get()) return; // 超过20次就不再查找了 if (adSearchCounter > 20) { return console.log('未找到,寻找结束!'); } setTimeout(removeAd, 300); })(); /** * 广告列表类 * @param {Array} ads 广告集合 ['link', 'flash'] * @method remove(adName) 移除广告 * @method get(adName) 获取广告是否移除,默认无参数返回广告的总数量 */ function Ads(ads) { var _ads = {}; var _adsLen = 0; ads.forEach(function(ad) { _ads[ad] = true; _adsLen++; }); return { remove, get }; // 移除广告 function remove(key) { if (_ads[key]) { _ads[key] = false; _adsLen--; } } // 获取广告移除状态 function get(key) { return key ? _ads[key] : _adsLen; } } })(); // 功能2:标记高分电影 (function() { var markWords = ['高分', '获奖']; var allText = document.querySelectorAll('a, p'); var textMark = function(text, markWords) { markWords.forEach(function(word) { text = text.replace( new RegExp(word), '<strong style="color: red;font-size: 18px;">' + word + '</strong>' ); }); return text; }; allText.forEach(function(aElem) { aElem.innerHTML = textMark(aElem.innerHTML, markWords); }); })(); // 功能3:去掉搜索框的广告跳转 // ** 该功能目前与功能6有重合部分,先去掉 ** // (function() { // document // .querySelector('input[name="keyword"]') // .addEventListener('keydown', function(e) { // e.stopPropagation(); // }); // })(); // 功能4:去掉中间页面上的flash广告 // (还可以提高网站性能,不影响页面布局) (function() { var containWidth = document.querySelector('.contain').clientWidth; // 递归移除父级,除与广告的尺寸不一致就停止 // 误差范围宽度30px,高度10px var removeParentUntilDiffSize = function(elem) { var elemW = elem.clientWidth; var elemH = elem.clientHeight; var parent = elem.parentNode; var parentW = parent.clientWidth; var parentH = parent.clientHeight; if (checkSize(parentW, elemW, 30) && checkSize(parentH, elemH, 10)) { removeParentUntilDiffSize(parent); } else { elem.remove(); } }; // 校验大小是否在误差之内 var checkSize = function(current, target, range) { return current > target - 30 && current < target + 30; }; document.querySelectorAll('iframe').forEach(function(elem) { if (elem.clientWidth === containWidth) { removeParentUntilDiffSize(elem); } else { elem.src = ''; } }); })(); // 功能6:去掉按任意键弹出广告 (function() { document.addEventListener( 'keydown', function(e) { e.stopPropagation(); }, true ); })(); // 功能7:去掉首次点击任何地方弹出广告 (function() { document.addEventListener( 'click', function(e) { e.stopPropagation(); }, true ); })();
true
49b46a5fc82165696820ec5b17d1ecc70b5ebf79
JavaScript
FedeSeg/grupo_7_andesnut
/src/controllers/userController.js
UTF-8
1,502
2.578125
3
[]
no_license
const fs = require('fs'); //const bcrypt = require('bcryptjs') const userController = { register: (req,res) => { //let password = req.body.password //let resultado = bcrypt.hashSync(password, 10); // TENGO QUE ARMAR TODO EL REGISTRO res.render('users/register') }, /* ss processLogin: function(req, res){ let archivoUsuario = fs.readFileSync('usuarios.json', {encoding: 'utf-8'}); let usuarios; if (archivoUsuario == ""){ usuarios = []; } else{ usuarios = JSON.parse(archivoUsuario); } for (let i = 0; i < usuarios.lengh; i++){ if (usuarios[i].userEmail == req.body.userEmail && bcrypt.compareSync(req.body.password, usuarios[i].password ) ) } }, */ login: (req,res) => { //TENGO QUE VER QUE HAGO CON ESTE //RECORDATORIO FIJARME PROYECTO PLANETS SI TENGO TODO BIEN Y QUE ES LO QUE ME FALTA res.render('users/login') }, store: (req, res) => { const { userName, userLastName, userPhone, userAddress, userAddressNum, userEmail } = req.body const user = { userName: userName, userLastName: userLastName, userPhone: userPhone, userAddress: userAddress, userAddressNum: userAddressNum, userEmail: userEmail } console.log(user) const userCreated = userModel.create(user) } } module.exports = userController
true
860ed14e5c38fc08864595134127ae1c3f4d80c9
JavaScript
danielbarbosa-developer/ProductsAPI
/src/routes/routes.js
UTF-8
1,627
2.625
3
[]
no_license
const md5 = require("md5"); const TimeControl = require ("../controller/time-control.js"); const ProductsRepository = require("../Repository/products-repository.js"); const timeControl = new TimeControl(); const productsRepository = new ProductsRepository(); // //Definição das rotas da API e métodos HTTP const router = (app)=>{ app.get('/products/', (req, res)=>{ const products = productsRepository.getProducts(); res.status(200).send({products}); }); app.delete('/products/', (req, res)=>{ const products = productsRepository.getProducts(); var hashArray = md5(JSON.stringify(req.body).toLowerCase()); try{ productsRepository.saveProduct(products.filter(products=> products.hash !== hashArray)); res.status(200).send("OK"); } catch(err){ console.log(err); res.status(400).send("BAD_REQUEST"); } }); app.post('/products/',(req, res)=>{ var hashArray = md5(JSON.stringify(req.body).toLowerCase()); const products = productsRepository.getProducts(); const sameProducts = products.filter(requisicao=> requisicao.hash === hashArray); if(timeControl.timmer(sameProducts, 10) === false){ var requisicao = {"hash": hashArray, "time": Date.now(), "products": req.body} products.push(requisicao); productsRepository.saveProduct(products); res.status(201).send("CREATED"); } else{ res.status(403).send("FORBIDDEN"); } }) } module.exports = router;
true
3d3bbc0c1f08ebadd6f3b8580f36dbbbc41ce72a
JavaScript
lasallejs/class-activities
/19.1-activities/01_Hello_World_Again/unsolved/js/index.js
UTF-8
370
4.1875
4
[]
no_license
// Create a variable below var helloWorld = 'Hello this is Me, Welcome to the Next Level'; // Console.log() your variable here. console.log(helloWorld); var x = 20; var y = 2; var z = 'There are ' + (x + y) + ' kids at my house'; function addkids() { console.log(z); console.log(x); console.log(y); console.log('I am here'); } addkids();
true
3d3ede9f1217e76750691207215f8fca6e935af1
JavaScript
dzmitrybek/frontcamp-mentoring
/pure-part/src/app/AppPresenter.js
UTF-8
3,691
2.5625
3
[]
no_license
export default class AppPresenter { constructor(...args) { [this.view, this.model] = args; } init() { this.loadMainPage(); this.view.onSearchNews((query) => this.loadMainPage(query)); this.view.onRefreshNews(() => this.loadMainPage()); this.view.onAddNews(() => this.loadEditPage({}, true)); this.view.onUserPageBtn(() => this.loadUserPage()); this.view.onMainPage(() => this.loadMainPage()); this.view.onSignInPageBtn(() => this.loadLoginPage()); this.view.onSignOutBtn(() => { this.logout(); }); } async loadMainPage(query) { this.view.manageLoader(true); try { const data = await this.model.getNews(query) || []; this.view.toggleSearchBar(true); this.view.toggleAddBtn(false); this.view.renderNewsHeader(); if (data.length) { this.view.renderNews(data); } else { this.view.renderEmptyResult(); } } catch (error) { this.view.renderErrorMessage(); throw new Error(error); } finally { this.view.manageLoader(false) } } loadLoginPage() { this.clearPage(); this.view.renderLoginForm(); this.view.onSignInBtn((loginData) => { this.auth(this.model.login, loginData); }); this.view.onRegistrationBtn((loginData) => { this.auth(this.model.registration, loginData); }); } async auth(authMethod, authData){ try { const userName = await authMethod(authData); this.view.toggleUserBtn(true, userName); this.loadUserPage(); this.view.switchSignBtns(false); this.view.toggle(false); } catch(err) { this.view.renderAuthError(err.message); } } async logout() { await this.model.logout(); this.view.switchSignBtns(true); this.view.toggleUserBtn(false); this.loadMainPage(); } async loadUserPage() { this.view.manageLoader(true); try { const data = await this.model.getMyNews() || []; this.view.toggleSearchBar(false); this.view.toggleAddBtn(true); this.view.renderHeader('My News:'); if (data.length) { this.view.renderNews(data, true); this.view.onEditNewsItem((id) => { const elem = this.model.getMyNewsById(id) this.loadEditPage(elem); }); this.view.onDeleteItem(async (id) => { await this.model.deleteNewsItem(id); this.loadUserPage(); }); } else { this.view.renderEmptyResult(); } } catch (error) { this.view.renderErrorMessage(); throw new Error(error); } finally { this.view.manageLoader(false) } } loadEditPage(item, isAdding) { this.view.toggleAddBtn(false); this.view.renderHeader(isAdding ? 'Add News:' : 'Edit News'); this.view.renderEditForm(item); this.view.onSubmitEditForm(async (formData) => { if(isAdding) { await this.model.sendNewNewsItem(formData); } else { await this.model.updateNewsItem(formData); } this.loadUserPage(); }); } clearPage() { this.view.toggleSearchBar(false); this.view.toggleAddBtn(false); this.view.renderHeader(''); } }
true
49a6f56c72128c49f629620a32f8b1ec74436c1a
JavaScript
benhamilton15/FullStack-App-Bucket-List-Lab
/client/src/views/list_item_view.js
UTF-8
2,049
3.09375
3
[]
no_license
const PubSub = require('../helpers/pub_sub.js'); const ListItemView = function (containerElement) { this.containerElement = containerElement; }; ListItemView.prototype.render = function (listItem) { const listItemContainer = document.createElement('div'); listItemContainer.id = "list-item-container"; const task = this.createDetail('Task', listItem.task); listItemContainer.appendChild(task); const difficulty = this.createDetail('Difficulty', listItem.difficulty); listItemContainer.appendChild(difficulty); const date = this.createDetail('Date', listItem.date); listItemContainer.appendChild(date); const completed = this.createDetail('Completed?', listItem.completed); listItemContainer.appendChild(completed); const deleteButton = this.createDeleteButton(listItem._id); listItemContainer.appendChild(deleteButton) const completedButton = this.createCompletedButton(listItem._id); listItemContainer.appendChild(completedButton) this.containerElement.appendChild(listItemContainer); } ListItemView.prototype.createDeleteButton = function (listItemID) { const button = document.createElement('button'); button.classList.add('delete-button'); button.textContent = 'Delete' button.value = listItemID button.addEventListener('click', (event) => { PubSub.publish('ListItemView:list-item-delete-clicked', event.target.value) }) return button; } ListItemView.prototype.createCompletedButton = function (listItemID) { const completedButton = document.createElement('button'); completedButton.classList.add('complete-button'); completedButton.textContent = 'Completed' completedButton.value = listItemID completedButton.addEventListener('click', (event) => { PubSub.publish('ListItemView:list-item-completed-clicked', event.target.value) }) return completedButton; }; ListItemView.prototype.createDetail = function (label, text) { const detail = document.createElement('h3'); detail.textContent = `${label}: ${text}`; return detail; } module.exports = ListItemView;
true
d3247a4af81ba2ec90bb92224b90fac7c5f25a39
JavaScript
Strategy11/formidable-forms
/js/packages/floating-links/s11-floating-links.js
UTF-8
8,198
3.21875
3
[]
no_license
/** * Class representing a floating action button for showing links. * * @class S11FloatingLinks */ class S11FloatingLinks { /** * Create a new S11FloatingLinks instance. * * @constructor */ constructor() { wp.hooks.addAction( 'set_floating_links_config', 'S11FloatingLinks', ({ links, options }) => { this.validateInputs( links, options ); this.links = links; this.options = options; this.initComponent(); }); } /** * Validate the input parameters. * * @param {Array<Object>} links - The links array. * @param {Object} options - The options object. * * @throws {Error} If the links array is empty or not provided. * @throws {Error} If the options.logoIcon is not provided or is an empty string. */ validateInputs( links, options ) { if ( ! Array.isArray( links ) || links.length === 0 ) { throw new Error( 'The "links" array is required and must not be empty.' ); } if ( ! options || typeof options.logoIcon !== 'string' || options.logoIcon.trim() === '' ) { throw new Error( 'The "options.logoIcon" is required and must be a non-empty string.' ); } } /** * Initialize the floating links component by creating the required elements, and applying styles. * * @memberof S11FloatingLinks */ initComponent() { // Create and append elements this.createWrapper(); this.createNavMenu(); this.createIconButton(); // Add event listener to close the navigation menu when clicking outside of floating links wrapper this.addOutsideClickListener(); // Add scroll event listener to hide/show floating links on scroll this.addScrollEventListener(); // Apply styles this.setCSSVariables(); } /** * Create the wrapper element and add it to the DOM. * * @memberof S11FloatingLinks */ createWrapper() { // Create the wrapper element this.wrapperElement = document.createElement( 'div' ); this.wrapperElement.classList.add( 's11-floating-links', 's11-fadein' ); // Add the wrapper to the DOM document.body.appendChild( this.wrapperElement ); } /** * Create the navigation menu element with the specified links and append it to the wrapper element. * * @memberof S11FloatingLinks */ createNavMenu() { // Create the navigation menu element this.navMenuElement = document.createElement( 'div' ); this.navMenuElement.classList.add( 's11-floating-links-nav-menu', 's11-fadeout' ); // Create and append link elements this.links.forEach( ( link ) => { if ( ! this.linkHasRequiredProperties( link ) ) { return; } const linkElement = document.createElement( 'a' ); linkElement.classList.add( 's11-floating-links-nav-item' ); linkElement.href = link.url; linkElement.title = link.title; if ( link.openInNewTab === true ) { linkElement.target = '_blank'; linkElement.rel = 'noopener noreferrer'; } linkElement.innerHTML = ` <span class="s11-floating-links-nav-text">${link.title}</span> <span class="s11-floating-links-nav-icon">${link.icon}</span> `; this.navMenuElement.appendChild( linkElement ); }); // Append the navigation menu to the wrapper element this.wrapperElement.appendChild( this.navMenuElement ); } linkHasRequiredProperties( link ) { const requiredProperties = [ 'title', 'icon', 'url' ]; return requiredProperties.every( prop => link.hasOwnProperty( prop ) ); } /** * Create the icon button element, add a click event listener, and append it to the wrapper element. * * @memberof S11FloatingLinks */ createIconButton() { // Create the icon button element this.iconButtonElement = document.createElement( 'div' ); this.iconButtonElement.classList.add( 's11-floating-links-logo-icon' ); this.iconButtonElement.innerHTML = this.options.logoIcon.trim(); // Define close icon const closeIcon = ` <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="none" viewBox="0 0 32 32"> <path fill="#1D2939" d="M23.625 21.957c.47.467.47 1.225 0 1.693a1.205 1.205 0 0 1-1.699 0l-5.915-5.937-5.958 5.935c-.47.467-1.23.467-1.7 0a1.194 1.194 0 0 1 0-1.693l5.96-5.933-5.961-5.979a1.194 1.194 0 0 1 0-1.693 1.205 1.205 0 0 1 1.699 0l5.96 5.982 5.957-5.935a1.205 1.205 0 0 1 1.7 0 1.194 1.194 0 0 1 0 1.693l-5.96 5.932 5.917 5.935Z"/> </svg> `; // Add a click event listener this.iconButtonElement.addEventListener( 'click', () => { // Toggle the navigation menu element this.toggleFade( this.navMenuElement ); // Switch the icon of the icon button element this.switchIconButton( closeIcon ); }); // Append the icon button to the wrapper element this.wrapperElement.appendChild( this.iconButtonElement ); } /** * Switch the icon of the icon button element between the logo icon and the close icon. * This method is called when the icon button is clicked. * * @memberof S11FloatingLinks * * @param {string} closeIcon - The SVG close icon that will replace the logo icon when the navigation menu is opened. */ switchIconButton( closeIcon ) { this.iconButtonElement.classList.toggle( 's11-show-close-icon' ); if ( this.iconButtonElement.classList.contains( 's11-show-close-icon' ) ) { this.iconButtonElement.innerHTML = closeIcon.trim(); return; } this.iconButtonElement.innerHTML = this.options.logoIcon.trim(); } /** * Toggle the fade-in and fade-out animation for the specified element. * This method is used to show or hide the navigation menu when the icon button is clicked. * * @memberof S11FloatingLinks * * @param {HTMLElement} element - The element to apply the fade animation on. */ toggleFade( element ) { if ( ! element ) { return; } element.classList.add( 's11-fading' ); element.classList.toggle( 's11-fadein' ); element.classList.toggle( 's11-fadeout' ); element.addEventListener( 'animationend', () => { element.classList.remove( 's11-fading' ); }, { once: true }); } /** * Add a click event listener to the body to close the navigation when clicked outside of the floating links wrapper. * Prevents the click event from bubbling up to the body when clicking on the floating links wrapper. * * @memberof S11FloatingLinks */ addOutsideClickListener() { document.body.addEventListener( 'click', ( e ) => { if ( ! this.wrapperElement.contains( e.target ) && this.navMenuElement.classList.contains( 's11-fadein' ) ) { // Toggle the navigation menu element this.toggleFade( this.navMenuElement ); // Switch the icon of the icon button element this.switchIconButton( this.options.logoIcon.trim() ); } }); // Prevent click event from bubbling up to the body when clicking on the wrapper element this.wrapperElement.addEventListener( 'click', ( e ) => { e.stopPropagation(); }); } /** * Add a scroll event listener to the window to toggle visibility of the Floating Links. * Show the Floating Links when scrolling up, and hide when scrolling down. * * @memberof S11FloatingLinks */ addScrollEventListener() { window.addEventListener( 'scroll', () => { const currentScrollPosition = window.scrollY || document.documentElement.scrollTop; if ( currentScrollPosition < this.lastScrollPosition ) { // When scrolling up show the Floating Links if ( ! this.wrapperElement.classList.contains( 's11-fadein' ) ) { this.toggleFade( this.wrapperElement ); } } else { // When scrolling down hide the Floating Links if ( ! this.wrapperElement.classList.contains( 's11-fadeout' ) ) { this.toggleFade( this.wrapperElement ); } } this.lastScrollPosition = currentScrollPosition; }); } /** * Set dynamic CSS properties. * * @memberof S11FloatingLinks */ setCSSVariables() { const hoverColor = this.options?.hoverColor ? this.options.hoverColor : '#4199FD'; const bgHoverColor = this.options?.bgHoverColor ? this.options.bgHoverColor : '#F5FAFF'; // Set the CSS variables on the wrapper element this.wrapperElement.style.setProperty( '--floating-links-hover-color', hoverColor ); this.wrapperElement.style.setProperty( '--floating-links-bg-hover-color', bgHoverColor ); } } // Initialize Floating Links new S11FloatingLinks();
true
dcc20737ec6c31ba00c962958240fd0cacfd7e7f
JavaScript
osama-allam/Examination-System
/Scripts/prompts.js
UTF-8
2,020
2.78125
3
[]
no_license
var alertsCounter = 0; var alerts = document.querySelector(".alert"); function addNewAlert(message) { var newAlert = document.createElement('div'); alertsCounter++; newAlert.setAttribute('class','alert__content'); newAlert.setAttribute('id','alert'+alertsCounter); newAlert.innerHTML = "<div class='alert__info'>"+message+"</div>"+ "<div class='alert__close' ><i class='far fa-window-close'></i> </div>"; alerts.appendChild(newAlert); newAlert.addEventListener("click",function() { removeNewAlert(newAlert.id); }); var a = document.getElementsByClassName("alert__content"); if(a.length >= 0) { autoRemoveAllAlert(); } } function removeNewAlert(elementId) { var element = document.getElementById(elementId); alerts.removeChild(element); alertsCounter--; } function removeAllAlert() { var a = document.getElementsByClassName("alert__content"); while(a.length > 0 ) { alerts.removeChild(a[0]); alertsCounter--; } } function autoRemoveAllAlert() { var alertAutoTimer= setInterval(function(){ var a = document.getElementsByClassName("alert__content"); if(a.length != 0) { alerts.removeChild(a[0]); } alertsCounter--; if (alertsCounter < 0) { clearInterval(alertAutoTimer); } },3000); } //*********************Modal****************** var btnCloseModal = document.querySelector(".modal__close-btn"); var modal = document.querySelector(".modal"); var modalHeading = document.querySelector(".modal__heading"); var modalContent = document.querySelector(".modal__content"); var modalSaveBtn = document.querySelector(".modal__save-btn"); var modalCloseBtn = document.querySelector(".modal__close-btn"); modal.addEventListener("click", function (e) { if (e.target === btnCloseModal) { modal.style.display = 'none'; } if (e.target === modalSaveBtn) { showResult(); } });
true
7e09f0a1cd43dfabdbe5b44b43153f0380539e51
JavaScript
jleveau/M2-Workshops
/js/mongoWorkshop.js
UTF-8
2,314
2.625
3
[]
no_license
const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://mongo:27017'; const dbName = 'workshopDatabase'; const COLLECTION_NAME = "workshops" let db; function init() { return new Promise((resolve, reject) => { MongoClient.connect(url, function(err, client) { if (err) { return reject(err) } console.log("Connected successfully to server"); db = client.db(dbName); resolve(); }); }) } function getWorkshopList() { return new Promise((resolve, reject) => { const collection = db.collection(COLLECTION_NAME); collection.find({}).toArray(function(err, workshops) { if (err) { return reject(err); } return resolve(workshops) }) }) } function getWorkshopByName(name) { return new Promise((resolve, reject) => { if (!name) { reject(new Error("name parameter is required")) } const collection = db.collection(COLLECTION_NAME); collection.find({ name }).toArray(function(err, workshops) { if (err) { return reject(err); } if (workshops.length > 0) { return resolve(workshops[0]) } else { return resolve(null) } }) }) } function addWorkshop(name, description) { if (!name) { return Promise.reject(new Error("Workshop name required")); } if (!description) { return Promise.reject(new Error("Workshop description required")); } const collection = db.collection(COLLECTION_NAME); return collection.insert({ name, description }).then(() => {return}) } function removeWorkshopByName(name) { const collection = db.collection(COLLECTION_NAME); return collection.deleteMany({ name }).then(() => {return}) } function updateWorkshop(name, description) { const collection = db.collection(COLLECTION_NAME); return collection.updateMany({ name }, { description }).then(() => {return}) } module.exports = { init, getWorkshopList, getWorkshopByName, addWorkshop, removeWorkshopByName, updateWorkshop }
true
b962554b09b8c0ad7b696eacf511d26e6738792f
JavaScript
ironclass/ironclass
/src/MixMyClass.js
UTF-8
6,840
3.375
3
[]
no_license
// model data for testing the logic, just left the needed fields let users = [ { _workedWith: [], _id: "3", username: "Andre".toLowerCase(), role: "Student" }, { _workedWith: [], _id: "4", username: "Malte".toLowerCase(), role: "Student" }, { _workedWith: [], _id: "5", username: "Stefanie".toLowerCase(), role: "Student" }, { _workedWith: [], _id: "6", username: "Min".toLowerCase(), role: "Student" }, { _workedWith: [], _id: "7", username: "Franzi".toLowerCase(), role: "Student" }, { _workedWith: [], _id: "8", username: "Amelia".toLowerCase(), role: "Student" }, { _workedWith: [], _id: "9", username: "Marvin".toLowerCase(), role: "Student" }, { _workedWith: [], _id: "10", username: "Ksenia".toLowerCase(), role: "Student" }, { _workedWith: [], _id: "11", username: "Felix".toLowerCase(), role: "Student" }, { _workedWith: [], _id: "12", username: "Julia".toLowerCase(), role: "Student" }, { _workedWith: [], _id: "13", username: ("Maxence" + "Teacher").toLowerCase(), role: "Teacher" }, { _workedWith: [], _id: "14", username: ("Thor" + "TA").toLowerCase(), role: "TA" } ]; class MixMyClass { constructor(users, classObj) { this.users = users; // might not be necessary this.students = this.users.filter(user => user.role === "Student"); this.classObj = classObj; this.currentGroups = classObj._currentGroups; } // standard fisher-yates shuffle, if option = repeat shuffle(students) { for (let i = students.length - 1; i > 0; i--) { // generate random index j const j = Math.floor(Math.random() * (i + 1)); // swap last element with element at random index j [students[i], students[j]] = [students[j], students[i]]; } } // shuffle, that takes the _workedWith property into account shuffleWithSequence(students) { function oneIteration() { times++; for (let i = students.length - 1; i > 0; i -= 2) { if (i - 1 < 0) { return students; } let j = Math.floor(Math.random() * (i + 1)); // if second last student already worked together with student at random index j, regenerate random index let workedWithArray = students[i - 1]._workedWith.map(obj => obj.toString()); while (workedWithArray.includes(students[j]._id.toString())) { console.log( `${students[i - 1].username} already worked with ${students[j].username}, dice again...` ); j = Math.floor(Math.random() * (i + 1)); } // swap last student with student at random index j -> this will create group of two, therfore decrease i by 2 // hence it can happen, that the two remaining students already worked togther [students[i], students[j]] = [students[j], students[i]]; } // to solve this issue, repeat the whole process again, try for max 99 times let workedWithArray = students[0]._workedWith.map(obj => obj.toString()); if (workedWithArray.includes(students[1]._id.toString()) && times < 100) { console.log( `${times}: ${students[0].username} already worked with ${students[1].username}, restart` ); that.shuffle(students); oneIteration(); } } let times = 0; let that = this; oneIteration(); } // main method to create groups of different sizes, taking the present students into account with opt for not repeating group partners in groups of two createGroups(size = 2, notPresent = [], option = "noRepeat") { let presentStudents = this.students.filter( student => !notPresent.includes(student._id.toString()) ); let groups = []; // checking, that option is set to repeat, if group size is not equal to 2 if (size != 2) { option = "repeat"; } switch (option) { case "repeat": // shuffle all present students and divide in groups of "size" this.shuffle(presentStudents); while (presentStudents.length > 0) { groups.push(presentStudents.splice(0, size)); } // return groups; break; case "noRepeat": // shuffle all present students respecting _workedWith property this.shuffleWithSequence(presentStudents); // console.log(`This is round ${round}`); // TESTING // round++; // TESTING while (presentStudents.length > 0) { groups.push(presentStudents.splice(0, size)); } // pushing usernames of buddies in students _workedWith array groups.forEach(group => { group.forEach(student => { let currentStudent = student; let buddies = group.filter(student => student !== currentStudent); buddies.forEach(buddy => student._workedWith.push(buddy._id)); }); }); // return groups; break; } this.currentGroups = groups; return groups; } } module.exports = MixMyClass; // // TESTING // let round = 0; // TESTING // let newClass = new MixMyClass(users); // newClass.createGroups(2, ["9", "10", "11", "12"]); // newClass.createGroups(2, ["9", "10", "11", "12"]); // newClass.createGroups(2, ["9", "10", "11", "12"]); // newClass.createGroups(2, ["9", "10", "11", "12"]); // newClass.createGroups(2, ["9", "10", "11", "12"]); // newClass.createGroups(2, ["9", "10", "11", "12"]); // console.log( // 'TCL: newClass.createGroups(2, ["9", "10", "11", "12"]);', // newClass.createGroups(2, ["9", "10", "11", "12"]) // ); // console.log( // 'TCL: newClass.createGroups(2, ["9", "10", "11", "12"]);', // newClass.createGroups(2, ["9", "10", "11", "12"])[0][0] // ); // console.log(newClass.students[0]._id, newClass.students[0]._workedWith); // console.log(newClass.students[1]._id, newClass.students[1]._workedWith); // console.log(newClass.students[2]._id, newClass.students[2]._workedWith); // console.log(newClass.students[3]._id, newClass.students[3]._workedWith); // console.log(newClass.students[4]._id, newClass.students[4]._workedWith); // console.log(newClass.students[5]._id, newClass.students[5]._workedWith); // console.log(newClass.students[6]._id, newClass.students[6]._workedWith); // console.log(newClass.students[7]._id, newClass.students[7]._workedWith); // console.log(newClass.students[8]._id, newClass.students[8]._workedWith); // console.log(newClass.students[9]._id, newClass.students[9]._workedWith); // // TESTING GROUPS WITH DIFFERENT SIZES // let groupsOfThree = newClass.createGroups(3, ["ksenia"]); // console.log(groupsOfThree); // let groupsOfFive = newClass.createGroups(5, ["ksenia"]); // console.log(groupsOfFive);
true
9cd472c149a1f911ad86011179f63f43fc562189
JavaScript
NatanshP/twitterApp
/src/reducers/explore.js
UTF-8
690
2.59375
3
[]
no_license
const initialState = { tweets: {}, people: {}, trends: {} } export const explore = (state = initialState, { type, payload }) => { const getNewData = (key) => { const { list, page, ...rest } = payload return { ...state, [key]: page === 1 ? payload : { list: [...(state[key].list || []), ...list], page, ...rest } } } const reducers = { ADD_TWEETS_DATA () { return getNewData('tweets') }, ADD_TRENDS_DATA () { return getNewData('trends') }, ADD_PEOPLE_DATA () { return getNewData('people') } } if (reducers[type]) { return reducers[type]() } else { return state } }
true
c43349374187c9169a3aed5300551668c10ce7d5
JavaScript
aosante/advanced-node-concepts
/thread.js
UTF-8
969
2.625
3
[]
no_license
require('dotenv').config() process.env.UV_THREADPOOL_SIZE const http = require('http') const bcrypt = require('bcrypt') // Default = 3600 req/sec (more below) // UV_THREADPOOL_SIZE=1 | 1030 req/sec // UV_THREADPOOL_SIZE=2 | 2000 req/sec // UV_THREADPOOL_SIZE=3 | 2900 req/sec // UV_THREADPOOL_SIZE=3 | 3500 req/sec /* Increasing the threadpool size increasaes performance because intel processors come with hyperthreading which in essence makes 1 pysical core = 2 logical cores */ http.createServer((_, res) => { // 2 is the salt to be used bcrypt.hash('data to be encrypted', 2).then(hash => { res.writeHead(200, {'Content-Type': 'text-plain'}) res.write(hash) res.end() }) }).listen(1337) // run ab -n 100 -c 10 "http://localhost:1337/" for benchmarking // when running 100 requests, we get around 2250 requests per second // if number of requests is bumped up to 1000, then we around 3420 requests per second (50% increase)
true
bf2a13dcca649c9d925674261f5c9d23675e18e3
JavaScript
hao-wang/Montage
/js-test-suite/testsuite/5ec9ee864cc131873370d5ab7bd181f4.js
UTF-8
3,556
3.046875
3
[ "MIT" ]
permissive
function shouldBe(actual, expected) { if (actual !== expected) throw new Error('bad value: ' + actual); } function iterator(array) { var nextCount = 0; var returnCount = 0; var original = array.values(); return { [Symbol.iterator]() { return this; }, next() { ++nextCount; return original.next(); }, return() { ++returnCount; return { done: true }; }, reportNext() { return nextCount; }, reportReturn() { return returnCount; } }; }; (function () { var iter = iterator([1, 2, 3]); var [] = iter; shouldBe(iter.reportNext(), 0); shouldBe(iter.reportReturn(), 1); }()); (function () { var iter = iterator([1, 2, 3]); var [,] = iter; shouldBe(iter.reportNext(), 1); shouldBe(iter.reportReturn(), 1); }()); (function () { var iter = iterator([1, 2, 3]); var [,,] = iter; shouldBe(iter.reportNext(), 2); shouldBe(iter.reportReturn(), 1); }()); (function () { var iter = iterator([1, 2, 3]); var [,,,] = iter; shouldBe(iter.reportNext(), 3); shouldBe(iter.reportReturn(), 1); }()); (function () { var iter = iterator([1, 2, 3]); var [,,,,] = iter; shouldBe(iter.reportNext(), 4); shouldBe(iter.reportReturn(), 0); }()); (function () { var iter = iterator([1, 2, 3]); var [,,,,,] = iter; shouldBe(iter.reportNext(), 4); shouldBe(iter.reportReturn(), 0); }()); (function () { var iter = iterator([1, 2, 3]); var [,a,] = iter; shouldBe(iter.reportNext(), 2); shouldBe(iter.reportReturn(), 1); shouldBe(a, 2); }()); (function () { var iter = iterator([1, 2, 3]); var [a,] = iter; shouldBe(iter.reportNext(), 1); shouldBe(iter.reportReturn(), 1); shouldBe(a, 1); }()); (function () { var iter = iterator([1, 2, 3]); var [a,,] = iter; shouldBe(iter.reportNext(), 2); shouldBe(iter.reportReturn(), 1); shouldBe(a, 1); }()); (function () { var iter = iterator([1, 2, 3]); var [a,b = 42,] = iter; shouldBe(iter.reportNext(), 2); shouldBe(iter.reportReturn(), 1); shouldBe(a, 1); shouldBe(b, 2); }()); (function () { var {} = { Cocoa: 15, Cappuccino: 13 }; }()); (function () { var {Cocoa,} = { Cocoa: 15, Cappuccino: 13 }; shouldBe(Cocoa, 15); }()); (function () { var {Cocoa = 'Cocoa',} = { Cocoa: 15, Cappuccino: 13 }; shouldBe(Cocoa, 15); }()); (function () { var {Cocoa, Kilimanjaro = 'Coffee'} = { Cocoa: 15, Cappuccino: 13 }; shouldBe(Cocoa, 15); shouldBe(Kilimanjaro, 'Coffee'); }()); (function () { var {Cocoa, Kilimanjaro = 'Coffee'} = {}; shouldBe(Cocoa, undefined); shouldBe(Kilimanjaro, 'Coffee'); }()); (function () { var {Cocoa, Kilimanjaro = 'Coffee',} = { Cocoa: 15, Cappuccino: 13 }; shouldBe(Cocoa, 15); shouldBe(Kilimanjaro, 'Coffee'); }()); function testSyntaxError(script, message) { var error = null; try { eval(script); } catch (e) { error = e; } if (!error) throw new Error("Expected syntax error not thrown"); if (String(error) !== message) throw new Error("Bad error: " + String(error)); } testSyntaxError(String.raw`var {,} = {Cocoa: 15}`, String.raw`SyntaxError: Unexpected token ','. Expected a property name.`); testSyntaxError(String.raw`var {,} = {}`, String.raw`SyntaxError: Unexpected token ','. Expected a property name.`);
true
5b4977b6a726a23c1260ba2d499f2a35ff769f1d
JavaScript
Darko203/Back_End_Node.js
/lecture-7/peoples-registry/routes/index.js
UTF-8
1,211
2.6875
3
[]
no_license
var express = require('express'); const { get } = require('../app'); var router = express.Router(); let people = require('../real-estate-data') /* GET home page. */ router .get('/people', function(req, res) { res.send({ message:"All people registered on the platform", items: people }) }) .get('/people/:id', (req, res)=>{ let message =`Here is the person with id #${req.params.id}` const person = people.find(person=>{ return person.id == req.params.id }) if(!person){ `there is no person with id #${req.params.id}` } res.send({ message:message, item: person }) }) .post('/people', (req, res)=>{ // const person ={ // id: people.length+1, // name:req.body.name, // address:req.body.address, // dateOfBirth:req.body.dateOfBirth // }; people.push({ id: people.length+1, ...req.body }); res.send({ message:"New person added to the database", items: people }) }) .delete('/people/:id', (req, res)=>{ people = people.filter(person=>{ return person.id != req.params.id }) res.send({ message:`Person with id #${req.params.id} is now removed`, items: people }) }) module.exports = router;
true
ad5f79f7d44f10ad50a7e5c96d8dee975294c369
JavaScript
ashiqdev/COMPLETE-REACT
/es6_refresher/var_let_con.js
UTF-8
84
3.09375
3
[]
no_license
const name = 'Ashik'; let age = 24; age = 25; console.log(name); console.log(age);
true
46d9355bae691ea997ef1f5f63c5c0bfb9cdd773
JavaScript
golfyos/tea-bot
/tea-admin/src/reducers/auth.js
UTF-8
420
2.5625
3
[ "MIT" ]
permissive
import { USER_LOGIN } from "../constant"; const initState = { isLogin: false, username: "", password: "" }; const auth = (state = initState, action) => { switch (action.type) { case USER_LOGIN: return { ...state, username: action.payload.username, password: action.payload.password, isLogin: true }; default: return state; } }; export default auth
true
c64b6e4737456c5475ad20c9c52d63389e891c3c
JavaScript
zyqzyq1314/letao
/public/back2/js/login.js
UTF-8
1,320
2.578125
3
[]
no_license
/** * Created by Jepson on 2018/5/9. */ // 入口函数, 可以防止全局变量污染 $(function() { /* * 1. 表单校验功能, 在表单提交时,会进行校验, 所以一定要给表单设置 name 属性 * 校验要求: * (1) 用户名不能为空 * (2) 密码不能为空, 长度为6-12位 * */ $('#form').bootstrapValidator({ // 指定校验时的图标显示 feedbackIcons: { // 校验成功的 valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, // 配置字段 fields: { // 配置对应字段名 username: { // 配置校验规则 validators: { // 非空校验 notEmpty: { // 提示信息 message: "用户名不能为空" }, stringLength: { min: 2, max: 6, message: "用户名必须是2-6位" } } }, password: { validators: { notEmpty: { message: "密码不能为空" }, // 长度校验 stringLength: { min: 6, max: 12, message: "密码长度必须在6-12位" } } } } }); })
true
fe6146bd63ae444cdddab098cb743100e7f87ee7
JavaScript
ITDevSolution/JRONCEROS_examFinal_ISIL2019
/1/app.js
UTF-8
379
4.34375
4
[]
no_license
/** * Diseñar una función que permita retornar la suma de los “N” primeros números naturales. Debe ingresar como parámetro el valor “N” **/ function sumaN(n){ return (n*(n+1))/2; } var numero = parseInt(prompt("Ingrese numero: ")); document.getElementById("r").innerHTML = "La suma de los primeros numeros naturales de"+numero+" es: "+sumaN(numero);
true
0e62f11ab177d7562ea19897009801afb688e86c
JavaScript
tylertrudgeon/JS-Snake-Game
/CanvasSetup.js
UTF-8
828
3.515625
4
[]
no_license
//Targeting canvas by it's ID. const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); //Setting canvas to have squares. const scale = 20; const rows = canvas.height / scale; const columns = canvas.width / scale; let snake; //Creating IIFE to set up the snake. (function setup() { snake = new Snake(); apple = new Apple(); apple.appleLocation(); window.setInterval(() => { context.clearRect(0,0, canvas.height, canvas.width); snake.update(); apple.draw(); snake.draw(); if(snake.eat(Apple)) { apple.appleLocation(); } }, 150); }()); //Listening for keystrokes to determine snake direction. window.addEventListener('keydown', ((e) => { const direction = e.key; snake.changeDirection(direction); }));
true
666c989d7ab19b5231154af5c1b5bd2293677b08
JavaScript
Noushad-web/TPC
/src/component/allTags/ResmebleTag.jsx
UTF-8
978
2.546875
3
[]
no_license
import React, { useState } from 'react'; import { resembleTag } from "../../action"; import { useDispatch } from 'react-redux'; const ResmebleTag = () => { const dispatch = useDispatch(); const resembleTagHandler = (e) => { const innerHTML = e.target.innerHTML.toLowerCase(); dispatch(resembleTag(innerHTML)) } return ( <div> <h4>Resembles</h4> <ul className="tagsWrapper--yearTag"> <li><button className="tagsWrapper--yearTag__buttons btn-normal" onClick={resembleTagHandler}>Architecture</button></li> <li><button className="tagsWrapper--yearTag__buttons btn-normal" onClick={resembleTagHandler}>Nature</button></li> <li><button className="tagsWrapper--yearTag__buttons btn-normal" onClick={resembleTagHandler}>Fashion</button></li> <li><button className="tagsWrapper--yearTag__buttons btn-normal" onClick={resembleTagHandler}>Health</button></li> </ul> </div> ) } export default ResmebleTag
true
93b2e33d18f52c9ce3d91916453601e50db1396e
JavaScript
2kuba/N220Summer2021
/labs/lab8/bounceOffRect/js/bounce.js
UTF-8
1,350
3.578125
4
[]
no_license
//variables for circle location, velocity and rect location circleX = 100; circleY = 100; xVel = 5; yVel = 5; rectX = 0; rectY = 400; rectW = 800; rectH = 200; //create the canvas function setup() { createCanvas(800,600); } //move the circle about the canvas function move() { //change location of circle circleX = circleX + xVel; circleY = circleY + yVel; //change circle movement direction based on collision with rectangle or sides/top if (collideRect(circleX,circleY,rectX,rectY,rectW,rectH) == true) { yVel = yVel * -1; } else if (circleX > 800) { xVel = xVel * -1; } else if (circleX < 0) { xVel = xVel * -1; } else if (circleY < 00) { yVel = yVel * -1; } } //check for circle collision with rectangle function collideRect(circleX,circleY,rectX,rectY,rectW,rectH) { var colliding = false; if(circleX > rectX && circleX < rectX + rectW) { if(circleY > rectY && circleY < rectY + rectH) { return true; } } return false; } //draw the circle and rectangle function draw() { background(120); //move the circle about the canvas move(); //draw the rectangle fill("#edac51"); rect(rectX,rectY,rectW,rectH); //draw the circle fill("#51edc9"); circle(circleX,circleY,20); }
true
1ad61dcbd611a693404255b3407683844b4947b3
JavaScript
asarudick/exercises
/js/tests/minimumInteger.js
UTF-8
1,241
3.3125
3
[]
no_license
import assert from 'assert'; import minimumInteger from '../minimumInteger'; import range from 'lodash/range'; describe('minimumInteger', () => { it('should return 1 on empty arrays', () => { const arr = []; const result = minimumInteger(arr); assert.equal(result, 1); }); it('should return 2 element on [ 1 ]', () => { const arr = [ 1 ]; const result = minimumInteger(arr); assert.equal(result, 2); }); it('should return 3 on [ 1, 2 ]', () => { const arr = [ 1, 2 ]; const result = minimumInteger(arr); assert.equal(result, 3); }); it('should return 4 on [ 1, 2, 3, 5 ]', () => { const arr = [ 1, 2, 3, 5 ]; const result = minimumInteger(arr); assert.equal(result, 4); }); it('should return 4 on [ 1, 2, 3, 3, 2, 1 ]', () => { const arr = [ 1, 2, 3, 3, 2, 1 ]; const result = minimumInteger(arr); assert.equal(result, 4); }); it('should return 101 on [0 - 100, 102 - 200]', () => { const arr = range(0, 101).concat(range(102, 201)); const result = minimumInteger(arr); assert.equal(result, 101); }); it('should return 1 on [-100 - 0]', () => { const arr = range(-100, 1); const result = minimumInteger(arr); assert.equal(result, 1); }); });
true
1193a5d4f150488d00627aa40e18d9407a728c57
JavaScript
lilmissrayna/Curriculum-Resources
/Week3/Day2/PokemonPage/pokeDemo.js
UTF-8
4,748
3.96875
4
[]
no_license
console.log("Hello"); //JS is going to be responsible for 2 things. //For manipulating the page function Pokemon(name,type,image,backImage){ this.name = name; this.image = image; this.type = type; this.backImage = backImage; } //be careful, there are no generics so nothing stopping from sending anything to this function. //pokemon could be a number, string, even another function. //anything other than a specific pokemon object will break this function. function DOMManipulation(pokemon){ document.getElementById("pokemonName").innerText = pokemon.name; let pokeImg = document.getElementById("pokemonImg"); pokeImg.setAttribute("src",pokemon.image); document.getElementById("pokemonType").innerText = pokemon.type; let backImg = document.getElementById("backImg"); backImg.setAttribute("src",pokemon.backImage); } document.getElementById("pokemonSubmit").addEventListener('click',getPokemon); //For communicating with an API, in this case PokeAPI /** * AJAX - a technique for access web servers from a web page asynchronously. * * synchronous and asynchronous? * Allows us to still have a functioning webpage while it waits for a response from the server. * Otherwise, the whole page will block you from doing anything in the mean time. * * Javascript is a single threaded scripting language. * If operations were done synchronously (i.e. one "action" at a time), it will cause the whole page * to stop and refresh. * * AJAX consists of: * - Browser build in XMLHttpRequest object (requests data from the wbe server) * - Javascript to dynamically change the page. * - DOM ( to display our data) */ function getPokemon(){ /** * How does AJAX work? * 1) An event occurs in the web page (button is clicked or page is loaded) * 2) an XMLHttpRequest object is created by JS * 3) XMLHttpRequest object sends a request to a web server * 4) Server process the request * 5) Server sends a response back to the web page! */ console.log("I'm getting the pokemon"); const BASE_POKEMON_URL = "https://pokeapi.co/api/v2/pokemon/"; let pokemonId = document.getElementById("pokemonId").value; let pokeURL = BASE_POKEMON_URL + pokemonId let xhttp = new XMLHttpRequest(); //this is a built in object in the browser. //Whenever the state of the xmlhttprequest object changes, it will invoke this funciton! xhttp.onreadystatechange = function(){ // console.log("Hello there!"); //onreadystatechange function gets invoked whenever the readystate changes. //What a readystate? it holds the status of the XMLHttpRequest /** * 0 - request is not initialized * 1 - server connection established * 2 - request recieved * 3 - processing request * 4 - request is finished and response is ready */ // switch(this.readyState){ // case 0: // console.log(`I'm in state ${this.readyState}`) // break; // case 1: // console.log(`I'm in state ${this.readyState}`) // break; // case 2: // console.log(`I'm in state ${this.readyState}`) // break; // case 3: // console.log(`I'm in state ${this.readyState}`) // break; // case 4: // console.log(`I'm in state ${this.readyState}`) // break; // } //We will only interact with the response, once it's complete and it's a success! if(this.readyState == 4 && this.status == 200){ // console.log(this.responseText); //This is simply text, in the format off JSON //fortunatley for us, we have libaries that will convert it for us! let responseObject = JSON.parse(this.responseText); console.log(responseObject); console.log(responseObject.name); console.log(responseObject.types[0].type.name); console.log(responseObject.sprites.front_shiny); //We want to turn this into something our DOMManipulation function expects. //A pokemon with, name, image, and type. let pokeObject = new Pokemon(responseObject.name, responseObject.types[0].type.name, responseObject.sprites.front_shiny, responseObject.sprites.back_default); DOMManipulation(pokeObject); } } xhttp.open("GET", pokeURL); xhttp.send(); // DOMManipulation(pokeObject); }
true
e3aac100f452373feeaff3e0a7781574c6df5e8a
JavaScript
KeithTt/puppeteer-demo
/dist/rize_.js
UTF-8
587
2.71875
3
[]
no_license
"use strict"; // https://rize.js.org/api/classes/_index_.rize.html const Rize = require('rize'); const rize = new Rize(); // 在 puppeteer 中,在启动浏览器之后,您必须新建一个页面。然而在 Rize 中,您不需要这么做 rize .goto('https://github.com/') .type('input.header-search-input', 'node') .press('Enter') .waitForNavigation() .assertSee('Node.js') // .saveScreenshot('target/searching-node.png') .saveScreenshot('target/searching-node.png', { fullPage: true }) .end(); // 别忘了调用 `end` 方法来退出浏览器!
true
e5cfa754a1b3bf8f9ce49d832c8ffb7d72a12da4
JavaScript
unicodeveloper/lindaikeji-cli
/factory/post.js
UTF-8
1,527
2.828125
3
[ "MIT" ]
permissive
'use strict'; var request = require('request'), Q = require('q'), _ = require('lodash'); var BLOGGER_HOST = 'https://www.blogger.com/feeds/9174986572743472561/posts/default?alt=json&max-results='; // Fetches data from linda Ikeji's blog function fetchTopStories(count, cb) { request(BLOGGER_HOST + count, function (err, res) { if (!err && res.statusCode == 200) { var data = JSON.parse(res.body); cb(data); } }); } // Pre processing all the data from the platform function processContent(data) { var entries = data.feed.entry, stories = []; for (var i = 0; i < entries.length; i++) { var item = entries[i], postTitle = item.title.$t, summary = item.summary.$t, // Do not assume the link will always remain item 4 in the array url = _.filter(item.link, function (link) { return link.rel === 'alternate' && link.type === 'text/html'; })[0].href, timePublished = item.published.$t, timeUpdated = item.updated.$t; var story = { url: url, headline: postTitle, summary: summary, timePublished: timePublished, timeUpdated: timeUpdated }; stories.push(story); } return stories; } function getTrending(count) { var deferred = Q.defer(); fetchTopStories(count, function (res) { if (!res) { return deferred.reject(); } deferred.resolve(processContent(res)); }); return deferred.promise; } module.exports = { getTrending: getTrending };
true
3e4882d086bd9c423c9a011d00ee12dbb6c76f93
JavaScript
agonzadu/primer_repositorio
/js/scripts.js
UTF-8
2,675
4.125
4
[]
no_license
// Prueba de funcionamiento de JS //document.write("Hola"); // Generar alerta en a usuario // alert("Ventana de alerta para usaurio"); // Solicitar información a nuestro usuario /* var nombre = prompt("Por favor introduzca su nombre"); document.write("<h1>Bienvenid@: " + nombre + "</h1><br />"); var edad = prompt("Por favor introduzaca su Edad"); document.write("Su edad es: " + edad + " años"); */ // Operaciones matemáticas /*var numUno = 5; var numDos = 2; var numTres = 2; var suma = numUno + numDos; var resultado = suma / numTres; console.log(suma); console.log(resultado);*/ // Operaciones matemáticas personalizadas /*var numUno = parseInt(prompt("Introduzca Primer valor")); var numDos = parseInt(prompt("Introduzca Segundo valor")); var numTres = parseInt(prompt("Introduzca Tercer valor")); var suma = numUno + numDos; var resultado = suma / numTres; console.log("La operación es la siguiente: " + "(" + numUno + " + " + numDos + ")" + "/" + numTres); console.log(suma); console.log(resultado);*/ //Variables Booleanas /*var numUno = parseInt(prompt("Introduzca un Número")); //var numDos = parseInt(prompt("Introduzca un Número")); var resultado = numUno >= 18; console.log(resultado); */ //Variables Arrays - Cadenas /*var meses = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"]; var semana = [1,2,3,4,5,6,7,8,9]; console.log(meses); console.log(meses[3]); console.log(semana[5]); */ // ******************* Practica individual matemáticas ************************************* /*var numUno = parseInt(prompt("Introduzca valor 1:")); var numDos = parseInt(prompt("Introduzca valor 2:")); var numTres = parseInt(prompt("Introduzca valor 3:")); var resultadoSuma = numUno + numDos + numTres; var resultadoResta = numUno - numDos - numTres; var producto = numUno * numDos * numTres; var promedio = resultadoSuma / 3; document.write("<h3>Resultado de la Suma: " + resultadoSuma + "</h3>"); document.write("<h3>Resultado de la Resta: " + resultadoResta + "</h3>"); document.write("<h3>Resultado del producto: " + producto + "</h3>"); document.write("<h3>Promedio: " + promedio + "</h3>"); var resultados = alert("Suma: " + resultadoSuma + "\n" + "Resta: " + resultadoResta + "\n" + "Producto: " + producto + "\n" + "Promedio: " + promedio); */ var acceso = parseInt(prompt("Introduzca su edad:")); if (acceso >= 18){ alert("Bienvenido a la página") document.write("<h1>Bienvenido, por favor, siga</h1>") } else if(acceso >= 80){ alert("Abueloooo!!!!!") } else{ alert("Por favor, abandone la página") document.write("<h1>FUERA DE AQUI!!!!</h1>") }
true
dba3af1c53470da2f6d957a0f9f0db9bca531919
JavaScript
dkim0827/codecore_homework
/turtle_graphics/turtle-graphics.js
UTF-8
3,495
4.34375
4
[]
no_license
// Since example is chaining the function // exmaple > flash.forward(5).right().forward(5) // each function will give return value of this // except allPoints() & print(); class Turtle { // create Turtle class constructor(x, y) { this.x = x || 0; // if const flash = new Turtle() has to be (0,0) this.y = y || 0; // default setting for x,y = (0,0) this.direction = "East"; this.angle = 0; // will only accept right angles this.steps = [ [this.x, this.y] // will include the start point of turtle ]; } forward(step) { // create forward method for (let i = 0; i < step; i++) { if (this.angle === 0) { this.x++; } else if (this.angle === 90) { this.y--; } else if (this.angle === 180) { this.x--; } else if (this.angle === 270) { this.y++; } else { return this; } this.steps.push([this.x, this.y]); // will push each step in to array this.steps } return this; } right() { // create right method this.angle += 90; if (this.angle === 90) { this.direction = "South"; } else if (this.angle === 180) { this.direction = "West"; } else if (this.angle === 270) { this.direction = "North"; } else { this.direction = "East"; // turtle will start from East direction this.angle = 0; } return this; } left() { // create left method this.angle -= 90; if (this.angle === 90) { this.direction = "South"; } else if (this.angle === 180) { this.direction = "West"; } else if (this.angle === -90 || this.angle === 270) { // -90 => 270 this will make act together with right() this.angle = 270; this.direction = "North"; } else { this.direction = "East"; this.angle = 0; } return this; } allPoints() { // Create an allPoints method which returns an array containing all coordinates the turtle has walked over. return this.steps; } print() { // create a print method // since initial maxX & maxY is -Infinity // initial minX & minY is Infinity // it will only compare the numbers in the array // so print() method can only draw the range we need(have) let xArr = []; let yArr = []; for (let step of this.steps) { xArr.push(step[0]); yArr.push(step[1]); }; let maxX = Math.max(...xArr); let maxY = Math.max(...yArr); let minX = Math.min(...xArr); let minY = Math.min(...yArr); // if (step[0], step[1] === (x, y)) will return true // else it will return flase const getTurtleWalkedOver = (x, y) => { for (let step of this.steps) { if (step[0] === x && step[1] === y) return true; } return false; }; // Since print() is console logging from top to bottom // left to right. y need to start from the max value // x value need to start from the min value console.log("-- BEGIN LOG"); for (let y = maxY + 1; y >= minY; y--) { let row = ""; for (let x = minX; x <= maxX + 1; x++) { if (getTurtleWalkedOver(x, y)) { row += "■"; } else { row += "□"; } } console.log(row); } console.log("-- END LOG"); } } const flash = new Turtle(0, 4); flash .forward(3) .left() .forward(3) .right() .forward(5) .right() .forward(8) .right() .forward(5) .right() .forward(3) .left() .forward(3) .print();
true
fe33de49315d9a83fde20a55af4abdba3f8fb0fd
JavaScript
vickycodes/Blackjack
/js/application.js
UTF-8
4,089
3.15625
3
[]
no_license
$(document).ready(function(){ var player = new BlackJackGame(); var dealer = new BlackJackGame(); //ON CLICK OF THE "HIT" BUTTON $("#Hit").click(function(){ if (!player.isMoreThanTwentyOne()){ player.hit(); $(".cardDeck").append(`<img src="css/${player.getPictureCard()}">`); $("#gamestatusTotal").html(player.total); } if(dealer.isLess17()){ dealer._getDealerCard(); } console.log("Next Dealer Card:" + dealer.dealerCard); if (player.is21() && dealer.dealerTotal < 21){ $("#gamestatus").html("BLACK JACK - YOU WON!"); $("#dealerTotal").html(dealer.dealerTotal); $('#Hit').prop('disabled', true); $('#Stand').prop('disabled', true); } else if(player.isMoreThanTwentyOne()){ $("#gamestatus").html("BUSTED!!"); $("#dealerTotal").html(dealer.dealerTotal); } else if(player.isMoreThanTwentyOne() && dealer.isMoreThanTwentyOne()){ $("#gamestatus").html("It's a tie"); $("#dealerTotal").html(dealer.dealerTotal); } else if (player.is21()){ $("#gamestatus").html("BLACK JACK - YOU WON!"); } else if (dealer.dealerTotal === 21){ $("#gamestatus").html("You lost!!!"); $("#Blackjack").html("Blackjack"); } else if (dealer.isMoreThanTwentyOne() && !player.isMoreThanTwentyOne()){ $("#gamestatus").html("YOU WON!"); $("#dealerTotal").html(dealer.dealerTotal); } }); //ON CLICK OF THE "New Game" BUTTON $("#NewGame").click(function(){ player.reset(); dealer.reset (); $("#gamestatusTotal").html("0"); $("#dealerTotal").html("0"); $("#Blackjack").html(""); $(".cardDeck").empty(); $("#gamestatus").empty(); $('#Hit').prop('disabled', false); $('#Stand').prop('disabled', false); dealer._getDealerCard(); $("#dealerTotal").html(dealer.dealerTotal); console.log("Dealer Card1:" + dealer.dealerCard); dealer._getDealerCard(); console.log("Dealer Card2:" + dealer.dealerCard); console.log("Dealer total of 2 cards " + dealer.dealerTotal); player.hit(); $(".cardDeck").append(`<img src="css/${player.getPictureCard()}">`); player.hit(); $(".cardDeck").append(`<img src="css/${player.getPictureCard()}">`); $("#gamestatusTotal").html(player.total); if (player.is21()){ dealer._getDealerCard(); $("#dealerTotal").html(dealer.dealerTotal); $("#gamestatus").html("BLACK JACK - YOU WON!"); $('#Hit').prop('disabled', true); $('#Stand').prop('disabled', true); } }); $('#Stand').prop('disabled',false); //ON CLICK OF THE "Stand" BUTTON $("#Stand").click(function(){ $('#Hit').prop('disabled', true); // dealer._getDealerCard(); $("#dealerTotal").html(dealer.dealerTotal); if (player.is21()){ $("#gamestatus").html("!!! BLACK JACK - YOU WON !!!"); // console.log("You wiiiiin"); } else if (player.total === dealer.dealerTotal){ $("#gamestatus").html(" It's a tie!! "); $("#dealerTotal").html(dealer.dealerTotal); // console.log("It's a tie"); } else if (dealer.dealerTotal === 21){ $("#Blackjack").html("BLACK JACK!"); $("#gamestatus").html(" You lost!"); // console.log("You wiiiiin"); } else if (player.total < dealer.dealerTotal && dealer.dealerTotal < 21){ $("#gamestatus").html(" You lost!"); $("#dealerTotal").html(dealer.dealerTotal); } else if (player.total < dealer.dealerTotal && dealer.dealerTotal > 21){ $("#gamestatus").html(" !!! YOU WON !!! "); $("#dealerTotal").html(dealer.dealerTotal); } else if (dealer.isMoreThanTwentyOne()){ $("#gamestatus").html("!!! YOU WON !!! "); $("#dealerTotal").html(dealer.dealerTotal); } else if (player.total > dealer.dealerTotal && !player.isMoreThanTwentyOne()){ $("#gamestatus").html("!!! YOU WON !!! "); $("#dealerTotal").html(dealer.dealerTotal); // } else if () // $("#dealerTotal").html(dealer.dealerTotal); // $("#gamestatus").html("You lost!!!"); } }); });
true
5360dd87f2db128c045699a12a2e29c58fb45ea4
JavaScript
Ishwar77/addroitt-nodejs
/models/country.js
UTF-8
1,842
2.6875
3
[]
no_license
"use strict"; var dbConn = require("./../config/db.config"); //Employee object create var Country = function (country) { this.idcountry = country.idcountry; this.country = country.country; this.country_code = country.country_code; this.create_timestamp = new Date(); this.update_timestamp = new Date(); }; Country.create = function (newCountry, result) { dbConn.query("INSERT INTO country set ?", newCountry, function ( err, res ) { if (err) { console.log("error: ", err); result(err, null); } else { result(null, res.insertId); } }); }; Country.findById = function (idcountry, result) { dbConn.query( "Select * from country where idcountry = ? ", idcountry, function (err, res) { if (err) { console.log("error: ", err); result(err, null); } else { result(null, res); } } ); }; Country.findAll = function (result) { dbConn.query("Select * from country", function (err, res) { if (err) { console.log("error: ", err); result(null, err); } else { console.log("country : ", res); result(null, res); } }); }; Country.update = function (idcountry, country, result) { dbConn.query( "UPDATE country SET country=?, country_code=?", [country.country, country.country_code, idcountry], function (err, res) { if (err) { console.log("error: ", err); result(null, err); } else { result(null, res); } } ); }; Country.delete = function (idcountry, result) { dbConn.query( "DELETE FROM country WHERE idcountry = ?", [idcountry], function (err, res) { if (err) { console.log("error: ", err); result(null, err); } else { result(null, res); } } ); }; module.exports = Country;
true
d723a7f0045298718126d824b01ded7a80f5e87a
JavaScript
Cartman0/HatenaBookmarkFakeExtension
/background/background-script.js
UTF-8
609
2.640625
3
[]
no_license
// when clicked icon chrome.browserAction.onClicked.addListener(addHatenaBookmark); function addHatenaBookmark(tab){ // permissions でtabsを有効にするとurl titleが取れる //console.log('url', tab.url); if (tab){ chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, {'tab': tab}); }); } } // when receved URL chrome.runtime.onMessage.addListener(newTab); function newTab(request) { if (!request.url){ return; } chrome.tabs.create({'url': request.url}/*, function(tab){ console.log('created tab'); }*/); }
true
89bb5b60afb737ae245a391c0a7dd52a8bc15ed8
JavaScript
kozulova/js
/game/script.js
UTF-8
240
2.546875
3
[]
no_license
import Game from './classes/game.js'; const load = () => { let emos = ["🐶", "🐱", "🐭", "🐹", "🐰", "🐻"]; let game = new Game(emos); game.play(); } document.addEventListener("DOMContentLoaded", load);
true
dfc6896e0f769b1afd49f1c9bab4736500be2ca7
JavaScript
aroonm/Magnifier
/scripts/magnifier.js
UTF-8
3,991
2.84375
3
[ "MIT" ]
permissive
var _browserZoomVal; var _graphicalZoomVal; var zoomDelta; var offsetOnZoom; var xOffset; var yOffset; var mouseDetectionoffset; var keyPlus; var keyMinus; var windowWidth; var windowHeight; var bodyWidthBeforeGZ; var bodyWidthAfterGZ; var selectedText; var refactoredContentContainer; function initializeZoom() { _browserZoomVal = 1.0; _graphicalZoomVal = 1.0; zoomDelta = 0.1; offsetOnZoom = 10; mouseDetectionoffset = 100; windowWidth = $(window).width(); windowHeight = $(window).height(); xOffset = windowWidth/2; yOffset = windowHeight/2; bodyWidthBeforeGZ = $("body").width(); bodyWidthAfterGZ = bodyWidthBeforeGZ; keyPlus = 187; keyMinus = 189; selectedText = ""; $("body").before("<div id='mydiv'></div>"); console.log("created"); refactoredContentContainer = $("<div id='mydiv'></div>"); } $(document).ready(function() { initializeZoom(); $("#mydiv").hide(100); $(document).on('mousemove', function(e) { xOffset = getXCoord(e); yOffset = getYCoord(e); correctContentStartingPosition(); }); $(document).on('mouseout', function(e) { clearCoor(); }); $(document).on('keydown', function(e) { e.preventDefault(); // Detect keydown: shift+plus and shift+minus if ((e.key == '+' || e.keyCode == keyPlus) && (e.shiftKey)) { _browserZoomVal += zoomDelta; } else if ((e.key == '-' || e.keyCode == keyMinus) && (e.shiftKey)) { _browserZoomVal -= zoomDelta; } else if ((e.metaKey || e.ctrlKey) && (e.key == '+' || e.keyCode == keyPlus)) { _graphicalZoomVal += zoomDelta; } else if ((e.metaKey || e.ctrlKey) && (e.key == '-' || e.keyCode == keyMinus)) { _graphicalZoomVal -= zoomDelta; } else if ((e.key == ' ' || e.keyCode == 32)) { $("#mydiv").show(100); $("*:not(body)").hover( function (ev) { selectedText = $(this).text(); refactorContent(selectedText); }, function (ev) { // Do nothing } ); } else if(e.key == "Escape") { $("#mydiv").hide(100); } bodyWidthAfterGZ *= _graphicalZoomVal; adjustWidthDuringGZ(); browserZoom(); graphicalZoom(); }); }); function browserZoom() { document.body.style.zoom = _browserZoomVal; } function graphicalZoom() { $("body").css("transform", "scale("+_graphicalZoomVal+")"); compensateGraphicalScaling(); } function compensateGraphicalScaling() { var scaleToW = $("body").width() * _graphicalZoomVal; var scaleToH = $("body").height() * _graphicalZoomVal; var topOriginal = $('body').offset().top; var topNew = topOriginal * _graphicalZoomVal; $("body").css("position", "relative"); $("body").css("left", (scaleToW-($("body").width()))/2); $("body").css("top", (scaleToH-($("body").height()))/2); if($(document).width() >= $(window).width()) { var mouseX = xOffset; var mouseY = yOffset; if (xOffset <= mouseDetectionoffset) { console.log("aaa" + offsetOnZoom); $("body").scrollLeft( 300 ); offsetOnZoom++; } } } function getXCoord(event) { return event.clientX; } function getYCoord(event) { return event.clientY; } function clearCoor() { } function correctContentStartingPosition() { // if (yOffset <= mouseDetectionoffset) { // offsetOnZoom++; // $("body").css('margin-top', offsetOnZoom+'px'); // } // else { // if (xOffset <= mouseDetectionoffset) { // offsetOnZoom++; // $("body").css('margin-left', offsetOnZoom+'px'); // } // else if (xOffset >= $(window).width()-mouseDetectionoffset) { // offsetOnZoom--; // $("body").css('margin-left', offsetOnZoom+'px'); // } // } } function adjustWidthDuringGZ() { var shiftDelta = (bodyWidthAfterGZ - bodyWidthBeforeGZ) / 2; $("body").css("left", shiftDelta+"px"); } function resetZoomToDefault() { } function refactorContent(contentToRefactor) { console.log("hi: "+contentToRefactor); $('#mydiv').empty().append(contentToRefactor); }
true
f0ab6d2fc1294f4864539a563f50752045cc46d7
JavaScript
tnemec/react-dgscore
/src/components/NewCourse.js
UTF-8
8,589
2.59375
3
[]
no_license
import React, { Component } from 'react'; import { connect } from 'react-redux' import { Button, Grid, Col, Row, ListGroup, ListGroupItem, Modal, Form, ControlLabel, FormGroup, FormControl, Glyphicon, Checkbox, Alert } from 'react-bootstrap'; import localCourses from '../utilities/localCourses.js'; import constants from '../utilities/constants.js'; import uuid from 'uuid/v1'; class NewCourse extends Component { constructor(props) { super(props); this.state = { newCourse: { "name": "", "uuid": uuid(), "state": "", "city": "", "holes": 18, "defaultPar": 3, "notes": "", "holeData": [] }, useHoleData: false, showError: false }; this.handleFormChange = this.handleFormChange.bind(this); } totalPar = () => { let total = 0; if (this.state.newCourse.holeData.length) { total = this.state.newCourse.holeData.reduce((acc, item) => { acc + (item.p || this.state.newCourse.defaultPar); }); } else { total = this.state.newCourse.holes * this.state.newCourse.defaultPar } return 'Total Par: ' + total; } handleBack = () => { this.props.history.push('/course'); }; handleSave = (evt) => { let save = localCourses.saveCourse(this.state.newCourse); if(! save.status) { this.setState({showError: true}) } else { this.props.select(this.state.newCourse); this.props.history.push('/new'); } }; handleFormChange = (evt) => { if(evt.target.name === 'useHoleData') { this.setState({useHoleData: evt.target.checked}, () => { this.populateHoleData() }); } else { evt.preventDefault(); let newCourse = {}; if(evt.target.name.substr(0,2) === 'hn' || evt.target.name.substr(0,2) === 'hp'|| evt.target.name.substr(0,2) === 'hd') { let holeData = this.state.newCourse.holeData.slice(0); let thisHole = holeData[parseInt(evt.target.name.substr(2))] || {}; let val = (evt.target.name.substr(0,2) === 'hp') ? parseInt(evt.target.value) : evt.target.value; // par is always int val = (evt.target.name.substr(0,2) === 'hd') ? parseFloat(val) : val; // dist is float thisHole[evt.target.name.substr(1,1)] = val ; holeData[parseInt(evt.target.name.substr(2))] = thisHole; newCourse = Object.assign({}, this.state.newCourse, { 'holeData' : holeData }); } else { let val = (evt.target.name === 'holes' || evt.target.name === 'defaultPar') ? parseInt(evt.target.value) : evt.target.value; newCourse = Object.assign({}, this.state.newCourse, { [evt.target.name] : val}); } let newState = Object.assign({}, this.state, {newCourse: newCourse}); this.setState(newState, () => { //this.populateHoleData() }); } }; handleFormBlur = () => { this.populateHoleData() ; }; stateOptionsList = () => { let output = []; Object.keys(constants.stateList).forEach((key) => output.push(<option value={key} key={key}>{constants.stateList[key]}</option>) ) return output } populateHoleData = () => { // fills hole data with default values // also truncates holes to the amount specified let holeData = []; if(this.state.useHoleData) { holeData = this.state.newCourse.holeData.slice(0,this.state.newCourse.holes); console.log(holeData) for(let i = 0; i < this.state.newCourse.holes; i++) { if(!holeData[i]) { // add hole if is is undefined holeData[i] = {n:i+1,p:this.state.newCourse.defaultPar,d:''} } } } let newCourse = Object.assign({}, this.state.newCourse, { 'holeData' : holeData }); let newState = Object.assign({}, this.state, {newCourse: newCourse}); this.setState(newState); } holeDataList = (state) => { return state.newCourse.holeData.map((item, index) => <tr key={index}><td><FormControl name={'hn' + index} type="text" value={item.n || index+1} onChange={this.handleFormChange} /></td><td><FormControl name={'hp' + index} type="number" min="1" max="8" value={item.p || state.newCourse.defaultPar} onChange={this.handleFormChange} /></td><td><FormControl name={'hd' + index} type="number" value={item.d || ''} onChange={this.handleFormChange} /></td></tr> ) } render() { return ( <div className="new-course"> <Form onSubmit={this.handleSave}> <Grid> <Row> <Col md={12}><h3>New Course</h3></Col> </Row> <FormGroup controlId="name"> <ControlLabel>Course Name</ControlLabel> <FormControl name="name" type="text" value={this.state.newCourse.name} onChange={this.handleFormChange} /> </FormGroup> <Row> <Col md={7}> <FormGroup controlId="city"> <ControlLabel>City</ControlLabel> <FormControl name="city" type="text" value={this.state.newCourse.city} onChange={this.handleFormChange} /> </FormGroup> </Col> <Col md={5}> <FormGroup controlId="state"> <ControlLabel>State</ControlLabel> <FormControl name="state" componentClass="select" value={this.state.newCourse.state} onChange={this.handleFormChange}> {this.stateOptionsList()} </FormControl> </FormGroup> </Col> </Row> <Row> <Col md={4}> <FormGroup controlId="holes"> <ControlLabel>Holes</ControlLabel> <FormControl name="holes" type="number" value={this.state.newCourse.holes} onChange={this.handleFormChange} onBlur={this.handleFormBlur} /> </FormGroup> </Col> <Col md={4}> <FormGroup controlId="defaultPar"> <ControlLabel>Default Par</ControlLabel> <FormControl name="defaultPar" type="number" value={this.state.newCourse.defaultPar} onChange={this.handleFormChange} onBlur={this.handleFormBlur} /> </FormGroup> </Col> <Col md={4}> <div className="total-par"> {this.totalPar()} </div> </Col> </Row> <hr className="divider"></hr> <div className="hole-data-inst"> <p>Every hole will use the Default Par, or, you can enter individual values for each hole below.</p> <p>You can also enter hole data as you play a round.</p> </div> <Checkbox name="useHoleData" checked={this.state.useHoleData} onChange={this.handleFormChange}>Use individual values</Checkbox> {this.state.useHoleData && this.holeDataList && <div className="hole-data-values"> <table> <tbody> <tr> <th>Hole</th> <th>Par</th> <th>Distance (ft.)</th> </tr> {this.holeDataList(this.state)} </tbody> </table> </div> } </Grid> </Form> {this.state.showError && <Alert bsStyle="danger"> <h4>Error Saving Course</h4> <p>The course could not be saved to your local storage</p> </Alert> } <Grid className="fixed"> <Row> <Col md={6}> <div className="left-align"><Button size="lg" bsStyle="link" onClick={this.handleBack}>Cancel</Button></div> </Col> <Col md={6}> <div className="right-align"><Button size="lg" bsStyle="primary" onClick={this.handleSave}>Done</Button></div> </Col> </Row> </Grid> </div> ); } } const mapStateToProps = (state, ownProps) => { return { } }; const mapDispatchToProps = dispatch => { return { select: (course) => { dispatch({type:'SELECT_COURSE', payload: course}); } } } export default connect(mapStateToProps, mapDispatchToProps)(NewCourse);
true
6829aed33a42412eafc6a55beae7ac82c9abb496
JavaScript
Matheusfariasc/Serratec
/Fase 2/bolo.js
UTF-8
537
3.140625
3
[]
no_license
// Ingredientes var ovo; var leite; var farinha; var manteiga; var fermento; var acucar; // Atribuir // armazenar; Guardar : Conceder ovos = 3; leite = " 1 copo"; farinha = " 2 xícaras e meia"; manteiga = " 2 colheres"; acucar = 0.75; // Ana maria Brogui ovo = 2; manteiga = " 2 colheres de sopa"; console.log( " Ingredientes"); console.log( " Ovo:",ovo); console.log(" Leite:",leite); console.log("Farinha:",farinha); console.log( "Açucar:",acucar,); console.log("Manteiga:",manteiga,"\n" );
true
19bc0cdbf946c2b5b2e96d42a7ca95e9ce39c1a0
JavaScript
tanveerg1/NodeJS-Practice
/vowel.js
UTF-8
438
4.25
4
[]
no_license
//person object var person = { name : "John", age : 30, sex : "Male", education : "Bachelor Degree", eyeColor : "Blue" } //array of vowels var vowels = ['a', 'e','i','o','u']; //create an array of the keys in the person object var keys = Object.keys(person); //match the keys with the vowels and print the keys starting with vowels keys.forEach((e1)=>vowels.forEach(e2 => { if(e1.charAt(0) === e2){ console.log(e1); } }));
true
d5b5c3929e67057bf8519adc9ce47a196d1cf678
JavaScript
DeAndreHarvey/PokeFind-Back-end
/server/controllers/poke.js
UTF-8
2,340
2.546875
3
[]
no_license
var api = require('pokemon-go-api'); var _ = require('underscore') const username = ''; const password = ''; const provider = 'google'; var location = 'dublin blvd and donlon way' var latitude ; var longitude; var results = [] // note the immediate function and the object that is returned module.exports = (function() { return { // notice how index in the factory(client side) is calling the index method(server side) login: function(req, res) { api.login(username, password, provider) .then(function() { return api.location.set('address', location) .then(api.getPlayerEndpoint); }) .then(_.partial(api.mapData.getByCoordinates, 37.700246, -121.938618)) .then(function(data) { console.log('success',data); for ( var y in data){ if (data[y].wild_pokemon.length > 0){ for(var x in data[y].wild_pokemon){ results.push({ "poke_id": data[y].wild_pokemon[x].pokemon_data.pokemon_id, "lat" : data[y].wild_pokemon[x].latitude, "long" : data[y].wild_pokemon[x].longitude, "time_left" : data[y].wild_pokemon[x].time_till_hidden_ms }) } } } console.log(data); res.json(data) }) .catch(function(error) { console.log('error', error.stack); }) }, search_area: function(req, res) { console.log('this is current results ->',results); console.log(req.body); var latitude = req.body.lat var longitude = req.body.lng console.log(latitude, longitude); api.login(username, password, provider) .then(function() { return api.location.set('address', req.body.location) .then(api.getPlayerEndpoint); }) .then(_.partial(api.mapData.getByCoordinates, latitude, longitude)) .then(function(data) { console.log('success',data); for ( var y in data){ console.log(data[y].wild_pokemon); if (data[y].wild_pokemon.length > 0){ for(var x in data[y].wild_pokemon){ results.push({ "poke_id": data[y].wild_pokemon[x].pokemon_data.pokemon_id, "lat" : data[y].wild_pokemon[x].latitude, "long" : data[y].wild_pokemon[x].longitude, "time_left" : data[y].wild_pokemon[x].time_till_hidden_ms }) } } } console.log(results); res.json(results) results = [] }) .catch(function(error) { console.log('error', error.stack); }) } } })();
true
d339937df84e55c07a8d09632b44aea4d61be465
JavaScript
123Lez/Translator
/frontend/js/validation.js
UTF-8
1,396
3.03125
3
[]
no_license
function validation() { var name=document.myform.name_signUp.value; var lastname=document.myform.lastname_signup.value; var email=document.myform.email_signup.value; var password=document.myform.password_signup.value; var repassword=document.myform.repassword_signup.value; var atpos=email.indexOf("@"); var dotpos=email.lastIndexOf("."); //Sign up page validation if(name=="" || lastname=="" || email=="" || password=="" || repassword=="") { document.getElementById("pass").innerHTML = "<div class='alert alert-danger'>Cannot leave the text box empty</div>"; return false; } else if(password!=repassword) { document.getElementById("pass").innerHTML = "<div class='alert alert-danger'>Passwords do not match</div>"; document.myform.password_signup.focus(); return false; } else if(atpos<1||(dotpos-atpos<2)) { document.getElementById("pass").innerHTML = "<div class='alert alert-danger'>Please enter the correct email</div>"; return false; } else { return true; } //Logging in page validation } function validate_sign_in() { //sign in var sign_email=document.myform2.email_signIn.value; var sign_password=document.myform2.password_signIn.value; if(sign_email=="" || sign_password=="") { document.getElementById("msg").innerHTML="<div class='alert alert-danger'>Cannot leave the text box empty</div>"; return false; } else { return true; } }
true
cba8404111feab76c9cba846bdf2b7f6b51e2728
JavaScript
Anakinliu/IJCE_Projects
/TomcatTest/out/artifacts/TomcatTest_war_exploded/js/m.js
UTF-8
1,764
3.4375
3
[]
no_license
var usernameObj; var passwordObj; window.onload = function() { // 页面加载之后, 获取页面中的对象 usernameObj = document.getElementById("un"); passwordObj = document.getElementById("pw"); errorMsg = document.getElementById("msg"); }; function checkUsername() { // 验证用户名 var regex = /^[0-9a-zA-Z_]{0,9}$/; // 字母数字下划线1到10位, 不能是数字开头 var value = usernameObj.value;// value获取usernameObj中的文本 var msg = ""; // 最后的提示消息, 默认为空 if (!value) // 如果用户名没填, 填了就是一个字符串可以当作true, 没填的话不论null或者""都是false msg = "用户名必须填写"; // 改变提示消息 else if (!regex.test(value)) // 如果用户名不能匹配正则表达式规则 msg = "用户名不合法"; // 改变提示消息 // 将提示消息放入SPAN errorMsg.innerHTML = msg; usernameObj.focus(); //usernameObj.parentNode.parentNode.style.color = msg == "" ? "black" : "red"; // 根据消息结果改变tr的颜色 return msg ; // 如果提示消息为空则代表没出错, 返回true } function checkPassword() { // 验证密码 var regex = /^.{6,16}$/; // 任意字符, 6到16位 var value = passwordObj.value; var msg = ""; if (!value) msg = "密码必须填写"; else if (!regex.test(value)) msg = "密码不合法"; errorMsg.innerHTML = msg; passwordObj.focus(); //passwordObj.parentNode.parentNode.style.color = msg == "" ? "black" : "red"; return msg ; } //======= function submitUP() { if (!checkUsername() && !checkPassword()) { return true; } else { return false; } } //====== function clearUP() { // 清空un框和pw框 passwordObj.value = ""; usernameObj.value = ""; }
true
31f284afe08192bad14e6dead9ec3a5543c7be6b
JavaScript
Akashh1996/Skylab-Bootcmamp-2020
/daniel-martinez/Challenges/functions-javascript/codewars-exercices/disemvowel-trolls.js
UTF-8
349
3.171875
3
[]
no_license
function disemvowel(str) { var l = str.split(''); for (var i = 0; i < l.length; i++) { if ( l[i].toUpperCase() === 'A' || l[i].toUpperCase() === 'E' || l[i].toUpperCase() === 'I' || l[i].toUpperCase() === 'O' || l[i].toUpperCase() === 'U' ) { l[i] = ''; } } str = l.join(''); return str; } module.exports = disemvowel;
true
f8ad029e0db71d17322e9183bbed65a5434ad503
JavaScript
feross/bitmidi.com
/src/views/title.js
UTF-8
573
2.703125
3
[]
no_license
import { Component } from 'preact' export default class Title extends Component { componentDidMount () { const { title } = this.props this.setTitle(title) } componentWillReceiveProps (nextProps) { // eslint-disable-line react/no-deprecated const { title } = this.props if (title !== nextProps.title) this.setTitle(nextProps.title) } render () { return null } setTitle (title) { if (typeof title !== 'string' && title !== null) { throw new Error('Prop `title` must be a string or null') } document.title = title } }
true
107a633357066604c93410f03ca813b369f4f82f
JavaScript
n2sy/tp-express
/controllers/students.js
UTF-8
2,843
2.71875
3
[]
no_license
let { students_list, student_schema, student_schema_update } = require("../models/students"); _ = require("lodash"); exports.getAllStudents = (req, res) => { //res.send("All Students are there") // res.status(200).json({ // students : "All Students are there", // id : "A10" // }); res.status(200).json({ listStudents : students_list }) //res.send(student_list); } // function findStudent(id) { // return student_list.find((p) => p.id == id) // } exports.getStudent = (req, res) => { //let id = req.params['id']; let id = req.params.id; let selectedStudent = _.find(students_list, p => p.id === Number(id)); //let selectedStudent = _.find(students_list, p => p.id === parseInt(id)) //let selectedStudent = student_list.find((p) => p.id == id); if(!selectedStudent) return res.status(404).json({ message : "Student with the given Id is not found" }); res.send(selectedStudent) } exports.createStudent = (req, res) => { // let newStudent = { // //id : students_list.length + 1, // name : req.body.name, // age : req.body.age, // class : req.body.class // }; let validationResult = student_schema.validate(req.body); if(validationResult.error) { console.log(validationResult.error); return res.status(400).send(validationResult.error.details[0].message) } let newStudent = _.pick(req.body, ['name', 'age', 'class']); newStudent.id = students_list.length + 1; students_list.push(newStudent); res.status(201).json({ message : "New student successfully created", student : newStudent }); } exports.updateStudent = (req, res) => { let selectedStudent = _.find(students_list, p => p.id === Number(req.params.id)); if(!selectedStudent) return res.status(404).json({ message : "Student with the given ID is not found" }); let validationResult = student_schema_update.validate(req.body); if(validationResult.error) { return res.status(400).send(validationResult.error.details[0].message) } selectedStudent = _.merge(selectedStudent, req.body) res.status(200).json({ message : "Student successfully updated", student : selectedStudent }) } exports.deleteStudent = (req, res) => { let studentToDelete = _.find(students_list, s => s.id == Number(req.params.id)); if(!studentToDelete) { return res.status(404).json({ message : "Student with the given ID is not found" }); } students_list = students_list.filter(s => s.id != Number(req.params.id)) res.status(200).json({ message : "Student succesfully Deleted", nameStudent : studentToDelete.name }) }
true
a7931583a3d7a0355a55c1b98d9db497e5084031
JavaScript
AbbyShaw36/AbbyShaw36.github.io
/efficacy/react-calendar-note/src/util/createWeekDays.js
UTF-8
280
3.109375
3
[]
no_license
import { pullAt } from "lodash"; export default function createWeekDays(weekOffset=0) { const weekArr = ["日","一","二","三","四","五","六"]; let newWeekArr = []; while(weekArr.length) { newWeekArr.push(pullAt(weekArr,weekOffset)); } return newWeekArr; }
true
6f1432b3ee1bfd6208b2ea541aca18196200badf
JavaScript
whyzcandy/dancehack2017
/src/three/features/pois.js
UTF-8
528
2.578125
3
[ "MIT" ]
permissive
import Draw from './../util/draw' class Pois { constructor(geometries, drawType, color, parent, origin) { this.draw = new Draw(); this.color = color; switch (drawType) { case 'shapes': this.drawPoisAsShapes(geometries, parent, origin, 4000); break; } } drawPoisAsShapes(geometries, parent, origin, scale) { var pois = null; for (var geoType in geometries) { console.log(geoType); switch (geoType) { case 'Points': //Used for label placement break; } } } } export default Pois;
true
8cb452dcb45cdd0eca8100631ea1055a12036d88
JavaScript
nuxt-contrib/xs-url
/index.js
UTF-8
1,579
3.015625
3
[ "MIT" ]
permissive
exports.parse = function (url) { const output = {} let protocolIndex = url.indexOf('://') if (protocolIndex !== -1) { output.protocol = url.substring(0, protocolIndex) url = url.substring(protocolIndex + 3) } else if (url.indexOf('//') === 0) { url = url.substring(2) } let parts = url.split('/') output.host = parts.shift() let host = output.host.split(':') if (host.length === 2) { output.host = host[0] output.port = parseInt(host[1]) } // Remove empty elements parts = parts.filter(Boolean) output.path = parts.join('/') const hash = output.path.split('#') if (hash.length === 2) { output.path = hash[0] output.hash = hash[1] } const search = output.path.split('?') if (search.length === 2) { output.path = search[0] output.search = search[1] } return output } exports.format = function (obj, query) { let url = obj.protocol ? obj.protocol + ':' : '' url += '//' + obj.host url += obj.port ? ':' + obj.port : '' url += '/' + obj.path url += obj.search ? '?' + obj.search : '' if (query) { const search = formatQuery(query) if (search) { url += (obj.search ? '&' : '?') + search } } url += obj.hash ? '#' + obj.hash : '' return url } function formatQuery (query) { return Object.keys(query).sort().map(key => { var val = query[key] if (val == null) { return '' } if (Array.isArray(val)) { return val.slice().map(val2 => [key, '=', val2].join('')).join('&') } return key + '=' + val }).filter(Boolean).join('&') }
true
fb2becd1cf633fe054ab710fd6237592c3733eb2
JavaScript
PIKAIA-project/PIKAIA-frontend
/src/Binaural/componants/RenderTime.js
UTF-8
445
2.546875
3
[]
no_license
import React from "react"; import "../styles/countdown.css"; export const RenderTime = ({ remainingTime }) => { if (remainingTime === 0) { return <div className="timer">Redo?</div>; } return ( <div className="timer"> <div className="value"> {Math.floor(remainingTime / 60)}m{" "} {remainingTime - Math.floor(remainingTime / 60) * 60}s </div> <div className="text">Left</div> </div> ); };
true
39a77f4a846940f1cc6e5852d12f7b62bf1ea659
JavaScript
taoning2014/crack-lintcode
/achieve/second-round/125.js
UTF-8
878
3.6875
4
[]
no_license
'use strict'; // ======================================================================== // Time: 5min // Submit: 1 // ======================================================================== function isAlphanum(char) { return (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9'); } /** * @param {string} s * @return {boolean} */ var isPalindrome = function(s) { if (!s || typeof s !== 'string') { return true; } s = s.toLowerCase(); let l = 0; let r = s.length - 1; while (l < r) { while (!isAlphanum(s[l])) { l++; if (l === s.length) { break; } } while (!isAlphanum(s[r])) { r--; if (r === 0) { break; } } if (l >= r) { break; } if (s[l] !== s[r]) { return false; } l++; r--; } return true; }; console.log(isPalindrome("A"));
true
d1460c3cdeeef099babad3f2582411a35569a8d0
JavaScript
balihoo-aharl/regionalsite-standard
/src/js/plugins.js
UTF-8
4,938
2.71875
3
[ "MIT" ]
permissive
// Avoid `console` errors in browsers that lack a console. (function() { var method; var noop = function () {}; var methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn' ]; var length = methods.length; var console = (window.console = window.console || {}); while (length--) { method = methods[length]; // Only stub undefined methods. if (!console[method]) { console[method] = noop; } } }()); // All the google map functions (function() { var queryLimit = 10, queryCount = 0, map, markers = [], infowindows = [], locationData, geocoder = new google.maps.Geocoder(), mapBounds = new google.maps.LatLngBounds(); // Function to construct the map initializeMap = function(data) { locationData = data; var mapOptions = { mapTypeId: google.maps.MapTypeId.TERRAIN, scrollwheel: false }; // Make the map map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // Iterate over the location array for (var i = 0; i < queryLimit; i++) { addMarker(locationData[i]); } // Set Map Bounds after map finishes building google.maps.event.addListenerOnce(map, 'idle', function() { map.fitBounds(mapBounds); }); }; setTimeout(function() { // Doing this because even on a paid account the queries are throttled after 10 mQueue = setInterval(markerQueue, 1000); }, 1500); var markerQueue = function() { addMarker(locationData[queryCount]); }; // Add a marker to the map and push to the array. var addMarker = function(location) { var windowContent, infowindow, marker, pos, address = location.Address + ', ' + location.Address02 + ', ' + location.City01 + ', ' + location.State01 + ' ' + location.Zip01; geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { pos = results[0].geometry.location; // InfoWindow Content windowContent = '<p><strong>'+location.displayName+'</strong><br>'+ location.phone+'</p>'; // Create Info Window infowindow = new google.maps.InfoWindow({ content: windowContent, maxWidth: 250 }); // Create Marker marker = new google.maps.Marker({ position: pos, map: map, title: location.displayName }); // Make sure map centers on markers mapBounds.extend(pos); map.fitBounds(mapBounds); // Add listener to show InfoWinow google.maps.event.addListener(marker, 'click', function() { closeAllInfoWindows(); infowindow.open(map, marker); }); // store markers and infowindows in array for later use if wanted infowindows.push(infowindow); markers.push(marker); queryCount++; if (typeof mQueue !== 'undefined') { if (queryCount === locationData.length) { window.clearInterval(mQueue); map.panToBounds(mapBounds); console.log('Finished Loading Markers'); } } } else { if (status === 'ZERO_RESULTS') { queryCount++; } console.log("Geocode was not successful for the following reason: " + status); } }); }; // For closing info windows var closeAllInfoWindows = function() { for (var i=0;i<infowindows.length;i++) { infowindows[i].close(); } }; }()); // Equal Height Divs (function() { equalHeightDivs = function(selector) { var currentTallest = 0, currentRowStart = 0, rowDivs = [], $el, topPosition = 0; $(selector).each(function() { $el = $(this); topPosition = $el.position().top; if (currentRowStart != topPosition) { // we just came to a new row. Set all the heights on the completed row for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) { rowDivs[currentDiv].height(currentTallest); } // set the variables for the new row rowDivs.length = 0; // empty the array currentRowStart = topPosition; currentTallest = $el.height(); rowDivs.push($el); } else { // another div on the current row. Add it to the list and check if it's taller rowDivs.push($el); currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest); } // do the last row for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) { rowDivs[currentDiv].height(currentTallest); } }); }; }()); // Place any jQuery/helper plugins in here.
true
b7d964b77bb571556747c4d9276ad6db8306f441
JavaScript
miaozhirui/credan_app_recycling
/src/common/js/validate.js
UTF-8
3,936
3.109375
3
[]
no_license
//验证类 export default { isPhone(str) { return /^1[2|3|4|5|6|7|8|9][0-9]\d{8}$/.test(this.deleteSpace(str)); }, isNumber(str) { return /^\d+$/.test(this.deleteSpace(str)); }, //此判断语义有问题,由于历史遗留问题,被多处使用,暂不修改,可以用下面的isNotEmpty代替 isEmpty(str) { return /^.+$/.test(this.deleteSpace(str)); }, isNotEmpty(str) { return /^.+$/.test(this.deleteSpace(str)); }, isBankCard(str) { str = this.deleteSpace(str); let num = /^\d*$/; let strBin = "10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99"; if (str.length < 16 || str.length > 19) { return false; //位数 } else if (!num.exec(str)) { return false; //数字 } else if (strBin.indexOf(str.substring(0, 2)) == -1) { return false; //前6位校验 } else { let lastNum = str.substr(str.length - 1, 1); //取出最后一位(与luhm进行比较) let first15Num = str.substr(0, str.length - 1); //前15或18位 let newArr = new Array(); for (let i = first15Num.length - 1; i > -1; i--) { //前15或18位倒序存进数组 newArr.push(first15Num.substr(i, 1)); } let arrJiShu = new Array(); //奇数位*2的积 <9 let arrJiShu2 = new Array(); //奇数位*2的积 >9 let arrOuShu = new Array(); //偶数位数组 for (let j = 0; j < newArr.length; j++) { if ((j + 1) % 2 == 1) { //奇数位 if (parseInt(newArr[j]) * 2 < 9) arrJiShu.push(parseInt(newArr[j]) * 2); else arrJiShu2.push(parseInt(newArr[j]) * 2); } else //偶数位 arrOuShu.push(newArr[j]); } let jishu_child1 = new Array(); //奇数位*2 >9 的分割之后的数组个位数 let jishu_child2 = new Array(); //奇数位*2 >9 的分割之后的数组十位数 for (let h = 0; h < arrJiShu2.length; h++) { jishu_child1.push(parseInt(arrJiShu2[h]) % 10); jishu_child2.push(parseInt(arrJiShu2[h]) / 10); } let sumJiShu = 0; //奇数位*2 < 9 的数组之和 let sumOuShu = 0; //偶数位数组之和 let sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和 let sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和 let sumTotal = 0; for (let m = 0; m < arrJiShu.length; m++) { sumJiShu = sumJiShu + parseInt(arrJiShu[m]); } for (let n = 0; n < arrOuShu.length; n++) { sumOuShu = sumOuShu + parseInt(arrOuShu[n]); } for (let p = 0; p < jishu_child1.length; p++) { sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]); sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]); } //计算总和 sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2); //计算Luhm值 let k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10; let luhm = 10 - k; if (lastNum == luhm) { return true; } } return false; }, deleteSpace(str) { return str.replace(/\s/g, ''); }, isIdentityNum(str) { let rule = /^(^[1-9][0-9]{7}((0[0-9])|(1[0-2]))(([0|1|2][0-9])|3[0-1])[0-9]{3}$)|(^[1-9][0-9]{5}[1-9][0-9]{3}((0[0-9])|(1[0-2]))(([0|1|2][0-9])|3[0-1])(([0-9]{4})|[0-9]{3}[Xx])$)$/ return rule.test(this.deleteSpace(str)); } }
true
beee6532d4f99f0d7fce2766908e78d862a39148
JavaScript
instrumentsofchange/Aspire
/Aspire/ClientApp/src/areas/schedules/reducers/search-schedules-reducer.js
UTF-8
1,994
2.53125
3
[]
no_license
import { FETCH_PROGRAM_OPTIONS_REQUEST, FETCH_PROGRAM_OPTIONS_SUCCESS, FETCH_PROGRAM_OPTIONS_FAILURE, SEARCH_SCHEDULES_REQUEST, SEARCH_SCHEDULES_SUCCESS, SEARCH_SCHEDULES_FAILURE, DELETE_SCHEDULE_REQUEST, DELETE_SCHEDULE_SUCCESS, DELETE_SCHEDULE_FAILURE } from '../actions/search-schedule-data-actions'; const defaultState = { programOptionsLoading: true }; export default (state = defaultState, { type, payload, error }) => { let reducedState = state; const reduceAction = changes => ({ ...state, ...changes }); switch(type) { case FETCH_PROGRAM_OPTIONS_REQUEST: reducedState = reduceAction({ programOptionsLoading: true }); break; case FETCH_PROGRAM_OPTIONS_SUCCESS: reducedState = reduceAction({ programOptionsLoading: false, programOptions: payload }); break; case FETCH_PROGRAM_OPTIONS_FAILURE: reducedState = reduceAction({ programOptionsLoading: false, fetchProgramOptionsError: error }); break; case SEARCH_SCHEDULES_REQUEST: reducedState = reduceAction({ searchResultsLoading: true, scheduleDeleted: false }); break; case SEARCH_SCHEDULES_SUCCESS: reducedState = reduceAction({ searchResultsLoading: false, searchResults: payload }); break; case SEARCH_SCHEDULES_FAILURE: reducedState = reduceAction({ searchResultsLoading: false, searchSchedulesError: error }); break; case DELETE_SCHEDULE_REQUEST: reducedState = reduceAction({ deletingSchedule: true }); break; case DELETE_SCHEDULE_SUCCESS: reducedState = reduceAction({ deletingSchedule: false, scheduleDeleted: true }); break; case DELETE_SCHEDULE_FAILURE: reducedState = reduceAction({ deletingSchedule: false, deletingScheduleError: error }); break; } return reducedState; }
true
99e00c0c1326ddc7bd6d0507ff12e3726d544a8d
JavaScript
omerbguclu/enigma-react
/react-app/src/store/reducers/input.js
UTF-8
553
2.828125
3
[ "MIT" ]
permissive
import { KEY_BACKSPACE, KEY_VALID } from "../types/inputTypes"; export const keys = { VALID_KEY: 0, UNVALID_KEY: 1, BACKSPACE: 2, } const initial_state = keys.UNVALID_KEY; const reducer = (state = initial_state, action) => { switch (action.type) { case KEY_BACKSPACE: console.log(action.payload); state = keys.BACKSPACE; return state; case KEY_VALID: state = keys.VALID_KEY; return state; default: return state; } } export default reducer;
true
8be9c35eff1e2e024dd6e856a4a6e87446139a18
JavaScript
Bognar/Chartist-js
/assets/app.js
UTF-8
1,364
2.828125
3
[]
no_license
var obj = [ { "_id": "5c649fd39e10e7a8fda259f1", "picture": "http://placehold.it/32x32", "age": 130, "gender": "male" }, { "_id": "5c649fd344c4a506670b9e92", "picture": "http://placehold.it/32x32", "age": 26, "gender": "female" }, { "_id": "5c649fd31138668b7e8a3ce6", "picture": "http://placehold.it/32x32", "age": 37, "gender": "female" }, { "_id": "5c649fd3ee20d926ccd3d42f", "picture": "http://placehold.it/32x32", "age": 22, "gender": "female" }, { "_id": "5c649fd3d1b31e82b40a625f", "picture": "http://placehold.it/32x32", "age": 78, "gender": "male" }, { "_id": "5c649fd34105163c9dc77765", "picture": "http://placehold.it/32x32", "age": 31, "gender": "male" }, { "_id": "5c649fd39f69524a5b37fb8f", "picture": "http://placehold.it/32x32", "age": 11, "gender": "male" } ] // Loading data of ages from json obj into d1 also we can add var d2=[]; var d1 = []; for(var i=0; i < obj.length; i++){ d1.push(obj[i].age); // if we want to use label d2 'd2.push(obj[i]._id);' } new Chartist.Pie('.ct-chart', { //using d1 as an data surce to plot chart series: d1 // we acn here add label 'label: d2' }, { donut: true, donutWidth: 30, donutSolid: true, startAngle: 270, showLabel: true });
true
498e2a12be9c595e9f1a303d3bb7794dc583b08d
JavaScript
judelin/ProjectReact
/mon-app/src/appJeux/appTictato.js
UTF-8
6,046
2.796875
3
[]
no_license
import React, {useState, useEffect} from 'react'; import { Button } from 'react-bootstrap'; import {calculateWinner, findBestMove, differentZero, numbRandom} from './calculateWinner'; //import {CarreVal} from './component/Carre'; import { CarreVal} from './component/tictactoComponent'; import './component/affBra.css'; import './AppTict.css'; function TabBoard(props){ let sqrt = Math.round(Math.sqrt(props.tab.length)); let tab = props.tab; let onClick = props.onClick; let carre = "carre" let ligne = []; let id = 0; for(var i = 0; i < sqrt; i++){ let colonne = []; for(var j = 0; j < sqrt; j++){ const affiche = CarreVal(id, tab, onClick, carre) colonne.push(<div className="column" key={id}>{affiche}</div>); id = id + 1; }// ligne.push(<div key={i} className="row">{colonne}</div>) }// return ligne; }// function AppTictacto(){ const arrayT =Array(9).fill(""); const [history, setHistory] = useState(arrayT) const [xIsNext, setIsNest] = useState(false); const [status, setStatus] = useState("Next player"); const [countX, setCountX] = useState(0); const [countO, setCountO] = useState(0); /*squares: Array(9).fill(null), xIsNext: true });*/ function handleClick(i){ //const winner = calculateWinner(history); const squares = history.slice(); if (calculateWinner(squares) || squares[i]) { return; } squares[i] = xIsNext ? 'X' : 'O'; setHistory(squares); setIsNest(!xIsNext); setStatus("Next player O") // setCountO(countO + 1); } function handleRestart(){ const arrayT =Array(9).fill(""); const arrayTT =Array(16).fill(""); if(history.length === 9){ setHistory(arrayT); } if(history.length === 16){ setHistory(arrayTT); } let fal = xIsNext; // if(xIsNext){ setIsNest(fal); // } // window.location.reload(); } function handleTrois(){ const arrayT = Array(9).fill(""); let fal = xIsNext; setHistory(arrayT); setIsNest(fal); setCountO(0); } function handleQuatre(){ const arrayT = Array(16).fill(""); let fal = xIsNext; setHistory(arrayT); setIsNest(fal); setCountX(0); } function handleHumain(){ const arrayT =Array(9).fill(""); const arrayTT =Array(16).fill(""); if(history.length === 9){ setHistory(arrayT); } if(history.length === 16){ setHistory(arrayTT); } // if(xIsNext === false){ setIsNest(true); // } } function handleOrdinateur(){ const arrayT =Array(9).fill(""); const arrayTT =Array(16).fill(""); if(history.length === 9){ setHistory(arrayT); } if(history.length === 16){ setHistory(arrayTT); } let fal = xIsNext; // if(xIsNext){ setIsNest(false); // } } const winner = calculateWinner(history); let status1; useEffect(()=>{ const squares = history.slice(); if(!xIsNext && winner === null){ let ii = numbRandom(squares)[0]; if(differentZero(squares, 5) === 5 && squares.length !== 9){ ii = findBestMove(squares); } if(squares.length === 9){ if(differentZero(squares, 1) === 1){ ii = findBestMove(squares); } } //let ie = findBestMove(squares); // console.log(squares); // console.log(minimax(squares, 0, false)); if (calculateWinner(squares) || squares[ii]) { return; } //console.log(ii); squares[ii] = xIsNext ? 'X' : 'O'; // setHistory(squares); setIsNest(!xIsNext); setTimeout(setHistory, 1000, squares); setTimeout(setStatus, 1500, "Next player X"); // console.log(xIsNext) if(calculateWinner(squares) === "O"){ setCountO(countO + 1); setTimeout(setStatus, 1500, "Winner O"); } else if(calculateWinner(squares) === "X"){ setCountX(countX + 1); }else if(differentZero(squares, squares.length) === squares.length){ setTimeout(setStatus, 1500, "Match null"); // let fal = !xIsNext; // setIsNest(fal); } } },[xIsNext, setIsNest, setHistory, countO]); /* useEffect(() => { let squares = history.slice(); const winner = calculateWinner(squares); // console.log(calculateWinner(squares) === "X") if(winner === "X"){ setCountX(countX + 1); } else if(winner === "O" && xIsNext === true){ // alert("Winner"); setCountO(countO + 1); setIsNest(false); // setHistory(arrayT); }else{} },[xIsNext, countX, countO]);*/ /*if (winner) { status1 = 'Winner: ' + winner; } else { status1 = 'Next player: ' + (xIsNext ? 'O' : 'X'); }*/ //const status1 = winner ? 'Next player O' : ''; //const win = winner === "X"?countX:countO; return( <div className="row11"> <div className="colum2"> <TabBoard tab={history} onClick={(i) => handleClick(i)}/> <div><h4>{status}</h4></div> </div> <div className="colum2"> <h4>Score X:{countX} O: {countO}</h4> <div> <Button variant="light" onClick={handleTrois}>3X3</Button> <Button variant="light" onClick={handleQuatre}>4X4</Button> </div> <div> <Button variant="light" onClick={handleHumain}>Humain</Button> <Button variant="light" onClick={handleOrdinateur}>Ordinateur</Button> </div> <br/> <Button variant="secondary" onClick={handleRestart}>Redemarer</Button> </div> </div> );// } export default AppTictacto;
true
88c2faf8b9e1b142e139066c675bbeb5890a56a6
JavaScript
sigvef/analytics-unsplash
/analytics-unsplash.js
UTF-8
697
2.515625
3
[]
no_license
(function(){ var x = new XMLHttpRequest(); x.onload = function(){ var parser = new DOMParser(); var descriptions = parser.parseFromString(x.responseText, 'application/xml') .querySelectorAll('description'); var description = descriptions[1 + (descriptions.length - 1) * Math.random() | 0]; var src = /http.*jpg/.exec(description.innerHTML)[0]; [].forEach.call(document.querySelectorAll('.ga-heros img'), function(img) { img.src = src.replace('_500.jpg', '_1280.jpg'); img.parentElement.style.height = '575px'; img.style.position = 'absolute'; img.style.bottom = '-50%'; img.style.opacity = 1; }); }; x.open('GET', 'https://unsplash.com/rss'); x.send(); })();
true
6b33c736ede72bc4cf6e06c7929ca2959b8920b2
JavaScript
fmartinez2345/galery-movie
/src/components/MoviesContainer/MovieList/MovieList.component.js
UTF-8
422
2.5625
3
[]
no_license
import React from 'react'; import MovieData from './MovieData/MovieData.component'; const strToComponent = data => ( data.map( movie => <MovieData img = {movie} key={movie} />) ); const MovieList = ({data}) => { if(data !== undefined) { return ( <div className='img-conteiner'> {strToComponent(data)} </div> ); } else { return (<div></div>) } }; export default MovieList;
true
22045298c7322386559cf68bbfa79f5fa2e6deed
JavaScript
ramziash/Weather-App-React
/src/components/Page/GraphPage.js
UTF-8
2,032
2.671875
3
[]
no_license
// details from these websites. //https://recharts.org/en-US/examples/AreaResponsiveContainer //https://reacttraining.com/blog/react-router-v5-1/ import React, { useState, useEffect } from "react"; import { useParams, useHistory } from "react-router-dom"; import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, } from 'recharts'; const CityGraph = () => { const history=useHistory(); const backButtonFucntion = ()=> history.goBack(); const {cityId} =useParams() const [graph, setGraph] = useState({}); const [isLoading, setLoading]= useState(false); const [hasError, setError] = useState(false); const getGraph = () => { setLoading(true); fetch(`https://api.openweathermap.org/data/2.5/forecast?id=${cityId}&appid=${process.env.REACT_APP_OPENWEATHERMAP_API_KEY}&units=metric`) .then(res => res.json()) .then(data => { console.log(data) setLoading(false); setGraph(data); }) .catch(err => { setLoading(false); setError(true); }) }; useEffect(getGraph, []) if (isLoading) return <p>Loading ...</p>; if (hasError) return <p>Something went Wrong</p>; return ( <div className="cityWeatherDetails"> <ResponsiveContainer width="75%" height={250}> <AreaChart data={graph.list} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="dt_txt" /> <YAxis /> <Tooltip /> <Area type="monotone" dataKey="main.temp" name='temperature' stroke="#8884d8" fill="#8884d8" /> </AreaChart> </ResponsiveContainer> <button className = '' onClick={backButtonFucntion}> Back </button> </div> ) } export default CityGraph;
true
fe941059587c6961f90e9fe5cf7391668299c7c3
JavaScript
geekbing/geekbing.github.io
/vote/js/vote.js
UTF-8
3,407
2.9375
3
[]
no_license
var total_vote= 0; var xing_vote = 0; var chu_vote = 0; var bing_vote = 0; var ling_vote = 0; function the_max_vote() { var temp1=(xing_vote>chu_vote)?xing_vote:chu_vote; var temp2=(bing_vote>ling_vote)?bing_vote:ling_vote; var max_vote=(temp1>temp2)?temp1:temp2; return max_vote; } //根据最大票数设置显示结果的整体宽度 function setWidth() { var max=the_max_vote(); var setResult=document.getElementById("showResult"); switch(parseInt(max)) { case 1: setResult.style.width="130px";break; case 2: setResult.style.width="180px";break; case 3: setResult.style.width="230px";break; case 4: setResult.style.width="280px";break; } } //根据票数设置结果 function setResult() { var xing_width=((xing_vote*50)>200)?200:(xing_vote*50); var chu_width =((chu_vote *50)>200)?200:(chu_vote*50); var bing_width=((bing_vote*50)>200)?200:(bing_vote*50); var ling_width=((ling_vote*50)>200)?200:(ling_vote*50); var voteresult1=document.getElementById("voteresult1"); var vote_num1=document.getElementById("span1"); voteresult1.style.width=xing_width+"px"; vote_num1.innerHTML=xing_vote+"票"; var voteresult2=document.getElementById("voteresult2"); var vote_num2=document.getElementById("span2"); voteresult2.style.width=chu_width+"px"; vote_num2.innerHTML=chu_vote+"票"; var voteresult3=document.getElementById("voteresult3"); var vote_num3=document.getElementById("span3"); voteresult3.style.width=bing_width+"px"; vote_num3.innerHTML=bing_vote+"票"; var voteresult4=document.getElementById("voteresult4"); var vote_num4=document.getElementById("span4"); voteresult4.style.width=ling_width+"px"; vote_num4.innerHTML=ling_vote+"票"; //显示table var table=document.getElementById("showResult"); table.style.display="block"; setWidth(); } //根据字符串获取Cookie值 function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start=c_start + c_name.length+1 ; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start,c_end)); } } return "" } function setCookie(c_name,value,expiredays) { var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : "; expires="+exdate.toGMTString()); } //首先检查是否存在Cookie //若存在,则按钮设置为不能点击 //否则,添加Cookie信息 function checkCookie() { flag=getCookie('flag'); if(flag!=null&&flag!="") { var submit_button=document.getElementById("submit_button"); submit_button.style.disabled=true; } else { setCookie('flag',"123",365); } } function vote() { //首先检查用户是否已经投票过 checkCookie(); setWidth(); var selectItem = 0; var items = document.getElementsByName("item"); for(i = 0; i < items.length; i++) { if(items[i].checked) { selectItem++; total_vote++; switch(parseInt(items[i].value)) { case 1: xing_vote++;break; case 2: chu_vote++;break; case 3: bing_vote++;break; case 4: ling_vote++;break; } } } if(selectItem <= 0) { alert("请先选择你心目中的宿舍长"); return; } //设置投票结果 setResult(); for(i = 0; i < items.length; i++) { items[i].checked = false; } }
true
200d37dda4ba6fbfedad302041b39a7bdfbb3c9e
JavaScript
sjx1995/Learning-Code
/Leetcode/src/sourceCode/LinkedList/面试题02.07/main.js
UTF-8
1,036
3.046875
3
[ "MIT" ]
permissive
/* * @Author: Sunly * @Date: 2020-11-18 11:12:28 * @LastEditTime: 2020-11-18 11:12:30 * @LastEditors: Sunly * @Description: * @FilePath: \Leetcode\src\sourceCode\LinkedList\面试题02.07\main.js */ export const getIntersectionNode = (headA, headB) => { const map = new Map(); while (headA) { map.set(headA); headA = headA.next; } while (headB) { if (map.has(headB)) return headB; headB = headB.next; } return null; }; export const getIntersectionNode = (headA, headB) => { let nodeA = headA, nodeB = headB; let lengthA = 0, lengthB = 0; while (nodeA) { lengthA++; nodeA = nodeA.next; } while (nodeB) { lengthB++; nodeB = nodeB.next; } if (!lengthA || !lengthB) return null; let diff = Math.abs(lengthA - lengthB); let slow, fast; if (lengthA > lengthB) { fast = headA; slow = headB; } else { fast = headB; slow = headA; } while (diff--) { fast = fast.next; } while (fast && slow) { if (fast === slow) return fast; fast = fast.next; slow = slow.next; } return null; };
true
339aaa42ad657b961256cff589879d102b0d8fa1
JavaScript
samplek/js-functional-library-project-web-112017
/index.js
UTF-8
2,935
2.9375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
fi = (function() { return { libraryMethod: function() { return 'Start by reading https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0' }, each: function(input, action) { if (input.constructor === Array) { for (i = 0; i < input.length; i++) { action(input[i]); } } else { for (var key in input) { action(input[key]); } } }, map: function(input, func) { const final = []; if (input.constructor === Array) { for (i = 0; i < input.length; i++) { final.push(func(input[i])); } } else { for (var key in input) { final.push(func(input[key])); } } return final; }, // const reduceHelper = function(acc, arr){ // for (let i = 0; i < arr.length, i++) { // acc += arr[i]; // } // return acc // }, reduce: function(input, func, acc) { if (input.constructor === Array) { return func(acc, input) } else { val_array = Object.values(input) return func(acc, val_array) } }, find: function(input, matcher) { for (let i = 0; i < input.length; i++) { if (matcher(input[i])){ return input[i]; }; } }, filter: function (input, matcher) { const final = []; for (let i = 0; i < input.length; i++) { if (matcher(input[i])){ final.push(input[i]); }; } return final; }, size: function (input) { let final = 0; if (input.constructor === Array) { for (let i = 0; i < input.length; i++) { final ++; }; } else { for (key in input) { if (input.hasOwnProperty(key)) final ++; } } return final; }, first: function (arr, n=1) { return arr.slice(0,n) }, last: function (arr, n=1) { return arr.slice(-1*n) }, compact: function (input) { const final = []; for (let i = 0; i < input.length; i++) { if (input[i]){ final.push(input[i]); }; } return final; }, sortBy: function (arr, func) { let final = [...arr]; return final.sort(func); }, uniq: function (arr) { let final = [arr[0]]; for (let i = 0; i < arr.length; i++) { if (!final.includes(arr[i])) { final.push(arr[i]); } } return final; }, keys: function (obj) { let final = []; for (key in obj) { final.push(key); } return final; }, values: function (obj) { let final = []; for (key in obj) { final.push(obj[key]); } return final; }, functions: function() { }, } })() fi.libraryMethod()
true
81143baba65a1ad95f29a79a6139553a152d3cad
JavaScript
salesforce/lwc
/packages/@lwc/integration-karma/test/polyfills/proxy-concat/index.spec.js
UTF-8
2,360
3.40625
3
[ "MIT" ]
permissive
it('should correctly concatenate 2 standard arrays', () => { const first = [1, 2]; const second = [3, 4]; const result = first.concat(second); expect(result.length).toBe(4); expect(result).toEqual([1, 2, 3, 4]); }); it('should correctly concatenate all parameters', () => { const result = [1].concat([2], [3, 4], [5]); expect(result.length).toBe(5); expect(result).toEqual([1, 2, 3, 4, 5]); }); it('should correctly concatenate values and arrays', () => { const result = [1].concat([true], null, { x: 'x' }, [5]); expect(result.length).toBe(5); expect(result).toEqual([1, true, null, { x: 'x' }, 5]); }); it('should correctly concatenate when the target is a Proxy', () => { const first = new Proxy([1, 2], {}); const second = [3, 4]; const result = first.concat(second); expect(result.length).toBe(4); expect(result).toEqual([1, 2, 3, 4]); }); it('should correctly concatenate when the parameter is a proxy', () => { const first = [1, 2]; const second = new Proxy([3, 4], {}); const result = first.concat(second); expect(result.length).toBe(4); expect(result).toEqual([1, 2, 3, 4]); }); it('should correctly concatenate 2 proxified arrays', () => { const first = new Proxy([1, 2], {}); const second = new Proxy([3, 4], {}); const result = first.concat(second); expect(result.length).toBe(4); expect(result).toEqual([1, 2, 3, 4]); }); it('should invoke get traps for length, 0 and 1', () => { const getCalls = []; const hasCalls = []; const proxyHandler = { get(target, key) { getCalls.push([target, key]); return target[key]; }, has(target, key) { hasCalls.push([target, key]); return key in target; }, }; const first = [1, 2]; const second = [3, 4]; const secondProxified = new Proxy(second, proxyHandler); const result = first.concat(secondProxified); expect(result).toEqual([1, 2, 3, 4]); const getKeys = getCalls.map((item) => item[1]); // Instead of comparing all the items using .toEqual(), we look if specific elements are present in the accessed // keys. expect(getKeys.includes('length')).toBe(true); expect(getKeys.includes('0')).toBe(true); expect(getKeys.includes('1')).toBe(true); });
true
3477c19995837d59606d4c921ec8f90d33f2ca64
JavaScript
FirePontiac/FullStackApp
/middleware/passport.js
UTF-8
1,625
2.59375
3
[]
no_license
// Тут будем описывать параметры для работы с json web token const JwtStrategy = require('passport-jwt').Strategy const ExtractJwt = require('passport-jwt').ExtractJwt const keys = require('../config/keys') const mongoose = require('mongoose') const User = mongoose.model('users') const options = { jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), // Паспорт JS сообщаем что будем забирать токен // хранящийся в Хедерах secretOrKey: keys.jwt // Тут передаёем значение секретного ключа для токена } module.exports = passport => { passport.use( // Необходимо выполнить сверку со значениями в базе данных, для этого создаём новую стратегию // Для этого сверху подключили mongoose и вытащили пользователя из модели new JwtStrategy(options, async (payload, done) => { // В payload хранится ID пользователя // Далее у пользователя интересуемся только его email и Id методом select try { const user = await User.findById(payload.userId).select('email id') if (user) { done(null, user) } else { done(null, false) } } catch (e) { console.log(e, 'Бага 1') } }) ) }
true
907101a1fe5c104eb2bcec5ac0cba8fa5139f8d1
JavaScript
dlochrie/FileThingy
/lib/queue.js
UTF-8
2,247
3.0625
3
[ "MIT" ]
permissive
/** * @param {number=} opt_operationLimit Optional operation limit passed in as an * argument. * @constructor */ function Queue(opt_operationLimit) { this.limit = opt_operationLimit || this.DEFAULT_FILE_LIMIT; } /** * @const * @type {number} Default MAX limit of simultaneously opened operations. */ Queue.prototype.DEFAULT_FILE_LIMIT = 100; /** * @type {Array.<function>} Queue of operations to process. */ Queue.prototype.queue = []; /** * @type {number} Current number of processed operations. */ Queue.prototype.openFiles = 0; /** * @type {number} Total number of processed operations. */ Queue.prototype.totalFiles = 0; /** * Adds a file operation to the queue. * @param {function} fn Function to add to queue. * @param {function} cb Function to call when this operation completes. * @return {function} Callback function. */ Queue.prototype.addFile = function(fn, cb) { this.queue.push(fn); return cb; }; /** * Executes the queue of operations. * See the MIXU Node JS guide, section 7.2.3 for Flow Control. * @param {function(<string>)} done Callback function to fire when done. */ Queue.prototype.execute = function(done) { var self = this; function async(fn, callback) { fn(function() { /** * This timeout is set to half a second to help overcome the EMFILE * maximum open files errors that occur at the OS level. * If needs be, a flag can be created in the future so that a user can * specify how much time to wait between "batches." The actual timeout * has been set arbitrarily, and exists to "compliment" the FILE LIMIT. */ setTimeout(function() { callback(); }, 500); }); } function end() { done('Done renaming/moving files.'); } function start() { while (self.openFiles < self.limit && self.queue.length > 0) { var fn = self.queue.shift(); async(fn, function() { self.openFiles--; if (self.queue.length > 0) { start(); } else if (self.openFiles === 0) { end(); } }); self.openFiles++; } } /** * Start the queue. */ start(); }; /** * @expose * Expose Queue Class. */ module.exports = Queue;
true
001039e467e41bc62f3c27a9ad55b50b5a4ddaa7
JavaScript
liazcortez/Node-introduccion
/03-Fundamentos/promesas.js
UTF-8
1,095
3.546875
4
[]
no_license
let empleados = [{ id: 1, nombre: 'fer' }, { id: 2, nombre: 'pancho' }, { id: 3, nombre: 'juan' }]; let salarios = [{ id: 1, salario: 1000 }, { id: 2, salario: 2000 }]; let getempleado = (id) => { return new Promise((resolve, reject) => { let empleadoDB = empleados.find(empleado => { return empleado.id === id; }) console.log(empleadoDB); if (!empleadoDB) { reject(`no existe el empleado con el id ${id}`); } else { resolve(empleadoDB); } }); } let getsalario = (empleado) => { return new Promise((resolve, reject) => { let salarioDB = salarios.find(salario => { return salario.id === empleado.id }); console.log(salarioDB); if (!salarioDB) { reject('sin salario'); } else { resolve({ 'nombre': empleado.nombre, 'id': empleado.id, 'salario': salarioDB.salario }); } }); } getempleado(3).then(empleado => { return getsalario(empleado); }).then(resp => { console.log(resp); }).catch(err => { console.log(err); });
true
724f8c58f50535d9554b6d4220bad9f179cfc6c9
JavaScript
Anna-Myzukina/nodeschool.io-tower-of-babel
/tower-of-babel/Main.js
UTF-8
184
2.546875
3
[]
no_license
//Exercise 5 var arg1 = process.argv[2]; var arg2 = process.argv[3]; import Main from './Math'; console.log(Main.PI); console.log(Main.sqrt(+arg1)); console.log(Main.square(+arg2));
true
9e6213bb47942343de278b5c98416367b978a2c2
JavaScript
bruthlee/npmpack
/Demo/nzh.js
UTF-8
551
2.796875
3
[]
no_license
var Nzh = require("nzh"); var nzhcn = require("nzh/cn"); //直接使用简体中文 var nzhhk = require("nzh/hk"); //繁体中文 // 转中文小写 >> 十万零一百一十一 console.log(nzhcn.encodeS(100111)) // 转中文大写 >> 壹拾万零壹佰壹拾壹 console.log(nzhcn.encodeB(100111)) // 科学记数法字符串 >> 十二万三千四百五十六万万七千八百九十万亿 console.log(nzhcn.encodeS("1.23456789e+21")) // 转中文金额 >> 人民币壹拾万零壹佰壹拾壹元壹角壹分 console.log(nzhcn.toMoney("100111.11"))
true
114cd8caaec0402f9d4f51fe81123b3112901d8c
JavaScript
HIONJOINONKJNJ/h5
/js/rem.js
UTF-8
150
2.65625
3
[]
no_license
let width = window.innerWidth; if(width>640){ width=640; } let fontSize = width/750*100; document.querySelector("html").style.fontSize=fontSize+"px";
true
527ced75a5cb9223ce586c77b91517c0fed8e6d6
JavaScript
SrSandeepKumar/TheWeatherApp
/app/actions/users.js
UTF-8
2,591
2.625
3
[ "MIT" ]
permissive
import { polyfill } from 'es6-promise'; import request from 'axios'; import { push } from 'react-router-redux'; import * as types from '../types'; polyfill(); const getMessage = res => res.response && res.response.data && res.response.data.message; function makeUserRequest(method, data, api = '/login') { return request[method](api, data); } // Log In Action Creators export function beginLogin() { return { type: types.MANUAL_LOGIN_USER }; } export function loginSuccess(message) { return { type: types.LOGIN_SUCCESS_USER, message }; } export function loginError(message) { return { type: types.LOGIN_ERROR_USER, message }; } // Sign Up Action Creators export function signUpError(message) { return { type: types.SIGNUP_ERROR_USER, message }; } export function beginSignUp() { return { type: types.SIGNUP_USER }; } export function signUpSuccess(message) { return { type: types.SIGNUP_SUCCESS_USER, message }; } // Log Out Action Creators export function beginLogout() { return { type: types.LOGOUT_USER}; } export function logoutSuccess() { return { type: types.LOGOUT_SUCCESS_USER }; } export function logoutError() { return { type: types.LOGOUT_ERROR_USER }; } export function toggleLoginMode() { return { type: types.TOGGLE_LOGIN_MODE }; } export function manualLogin(data) { return dispatch => { dispatch(beginLogin()); return makeUserRequest('post', data, '/login') .then(response => { if (response.status === 200) { dispatch(loginSuccess(response.data.message)); dispatch(push('/')); } else { dispatch(loginError('Oops! Something went wrong!')); } }) .catch(err => { dispatch(loginError(getMessage(err))); }); }; } export function signUp(data) { return dispatch => { dispatch(beginSignUp()); return makeUserRequest('post', data, '/signup') .then(response => { if (response.status === 200) { dispatch(signUpSuccess(response.data.message)); dispatch(push('/')); } else { dispatch(signUpError('Oops! Something went wrong')); } }) .catch(err => { dispatch(signUpError(getMessage(err))); }); }; } export function logOut() { return dispatch => { dispatch(beginLogout()); return makeUserRequest('post', null, '/logout') .then(response => { if (response.status === 200) { dispatch(logoutSuccess()); } else { dispatch(logoutError()); } }); }; }
true
24f1309b01f1399ffb9a65365e6890906fd07806
JavaScript
d-sergio/ecotrans
/src/libs/react-components/sliders/slider-highlight/animation/create-animation.js
UTF-8
2,371
3.140625
3
[]
no_license
//Используется в animate-move.js import Animation from "../../../../animate/animate"; import changeStyleProperty from '../../../../animate/draw-functions/change-style-property'; import sliderTimeFunction from '../../../../animate/time-functions/slider-time-functions'; /**Создать и вернуть объект анимации * * Функция "ловит" текущий currentMarginLeft ленты слайдов и создаёт объект * анимации для прокрутки до currentPosition(новой позиции). Для этого * вычисляется targetMarginLeft. * * Props: * @param {object} - объект со следующими полями: * @param {number} currentPosition - текущая позиция, до которой происходит прокрутка * @param {node} carousel - лента слайдов * @param {function} callback - необязательный коллбэк выполнится после анимации * @param {number} animDuration - длительность анимации */ export default function createAnimationObject({animDuration, carousel, callback, currentPosition, adjacentCorrect}) { try{ if (!carousel) return; const slideWidth = carousel.children[0].offsetWidth; const currentMarginLeft = parseFloat(window.getComputedStyle(carousel).marginLeft); const targetMarginLeft = -currentPosition * slideWidth + adjacentCorrect; const timing = (targetMarginLeft < currentMarginLeft) ? sliderTimeFunction.inverted //если листаем к следующему слайду : sliderTimeFunction.straight; //если листаем к предыдущему слайду const animationProps = { timing: timing, duration: animDuration, draw: changeStyleProperty, element: carousel, property: 'marginLeft', startValue: currentMarginLeft, finalValue: targetMarginLeft, units: 'px', callback: callback } return new Animation(animationProps); } catch(e) { console.log('Slider Ошибка createAnimationObject(): ' + e.name + ":" + e.message + "\n" + e.stack); } }
true
27059ac5fbd8143e11c4c12525a316909366e045
JavaScript
Riiiad/riaddesign
/src/assets/js/main.js
UTF-8
2,156
3.140625
3
[]
no_license
var fooFunc = require('./export'); fooFunc.foo(); (function () { var i = 0, cl = 0; var words = ['with JavaScript', 'or jQuery', '& hope you like it x).']; var output = document.querySelector('#typing h1'); type(); function type() { output.innerHTML = words[i].substring(0, cl++); //console.log(words[i].substring(0, cl++)); if (cl < words[i].length + 1) { setTimeout(type, 120); //console.log("Typing"); } else { //console.log('wait...') setTimeout(erase, 5000); } } function erase() { output.innerHTML = words[i].substring(0, cl--); if (cl >= 0) { setTimeout(erase, 100); //console.log('Deleting'); } else { next(); } } function next() { if (i < words.length) { i++; type(); //console.log("Next"); } else if (i = words.length) { output.innerHTML = 'Loop'; } } }()); var sliderImages = [ { "name": "First image", "bodytext": "Some text for the first image", "source": "./assets/img/Slider/1.jpg" }, { "name": "Second image", "bodytext": "Some text for the second image", "source": "./assets/img/Slider/2.jpg" }, { "name": "Third image", "bodytext": "Some text for the second image", "source": "./assets/img/Slider/3.jpg" } ]; var currentImage = 0; var bigImage = document.querySelector('#big-img img'); var big = document.querySelector('#big-img'); function getImage() { var image = sliderImages[currentImage]; bigImage.src = image.source; big.querySelector('h2').innerHTML = image.name; big.querySelector('p').innerHTML = image.bodytext; return; } function removeclass() { bigImage.classList.remove('slide-in'); } function sliderBtns(direction) { bigImage.classList.add('slide-in'); setTimeout(removeclass, 500); console.log(currentImage); direction == 'next' ? currentImage++ : currentImage--; getImage(); } getImage();
true
c5887be6f892181bc24ec57bca16d78ce578e2bb
JavaScript
rfrancalangia/scraper
/starters/examples/pinterest.js
UTF-8
947
2.53125
3
[]
no_license
/* *************************************************************** * * File Name : pinterest.js * Created By : rfrancalangia * * Creation Date : 10-03-2017 * Last Modified : Tue Oct 3 08:29:30 2017 * Description : * * *************************************************************** */ var express = require('express'); var path = require('path'); var request = require('request'); var cheerio = require('cheerio'); var fs = require('fs'); var app = express(); var port = 8080; var url = "https://www.pinterest.com/pin/16395986122172500/"; var pin = {}; request(url, function(err, resp, body){ var $ = cheerio.load(body); var $img = $("meta[property='og:image']").attr('content'); var $desc = $("meta[property='og:description']").attr('content'); var pin = { img: $img, desc: $desc, url: url, } console.log("Scraped ",pin); }); app.listen(port); console.log("Server is listening on " + port);
true
9ed791faa3955ec06bf39ec9045d912236f42338
JavaScript
nandopacheco/micthing
/src/utils/MessageBus.js
UTF-8
586
3
3
[ "MIT" ]
permissive
class MessageBus { constructor(initialValue) { this.lastValue = initialValue; this.listeners = []; } addListener(listener) { this.listeners.push(listener); listener(this.lastValue); } removeListener(listener) { const index = this.listeners.indexOf(listener); if (index < 0) { throw new Error('listener not found'); } this.listeners.splice(index, 1); } update(value) { this.lastValue = value; for (let i = this.listeners.length - 1; i >= 0; i--) { this.listeners[i](value); } } } export default MessageBus;
true
b2bb06de8382ab320b6a52eff97ca864f0bebba5
JavaScript
Sayantika23/process-miner
/core/repository.js
UTF-8
1,823
2.5625
3
[ "Apache-2.0" ]
permissive
const fetch = require('axios'); const fs = require('fs'); class Repository { constructor(url) { this.url = url; this.data = null; this.extracted_data = null; this.attribute_results = null; } json() { return { url: this.url, data: this.data, extracted_data: this.extracted_data }; } cacheIfRequired() { if (this.shouldCache) { this.saveToCache(); } } loadFromCache() { const repoCacheFileName = repository.data.full_name.replace('/', '-'), fullPath = __dirname + '/../cache/' + repoCacheFileName + '.json'; return require(fullPath); } saveToCache(overwriteData) { const repoCacheFileName = this.data.full_name.replace('/', '-'), fullPath = __dirname + '/../cache/' + repoCacheFileName + '.json'; fs.writeFileSync(fullPath, JSON.stringify(overwriteData || this.json())); console.log('Successfully cached', this.url, 'at', fullPath); } fetch(category, loader) { if (!this.data) { // console.log('No Data Found. Loading Repo Data First for', this.url); return loader.fetch(this).then((data) => { this.data = data; if (this.shouldCache) { this.cacheIfRequired(); } return this.fetch(category, loader); }); } return loader.fetch(this, category).then(categoryData => { this.extracted_data = this.extracted_data || {}; this.extracted_data[category] = categoryData; if (this.shouldCache) { this.cacheIfRequired(); } return this; }); } } module.exports = Repository;
true
006b0eb97c81269c414a3410da78643426d91e3a
JavaScript
ZarifS/rented-backend
/server.js
UTF-8
6,279
2.65625
3
[]
no_license
const express = require("express"); const bodyParser = require("body-parser"); const admin = require("firebase-admin"); const serviceAccount = require("./secret-keys/rented-project-key.json"); const app = express(); const port = process.env.PORT || 8000; const cors = require("cors"); app.use(cors()); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); const USERS = "users"; //Init Firebase ADMIN SDK admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://rented-project.firebaseio.com" }); const db = admin.firestore(); const settings = { /* your settings... */ timestampsInSnapshots: true }; db.settings(settings); const auth = admin.auth(); // Create User gets a email and password from the client and creates a firebase // auth user. It then maps this user to the firestore users collection app.post("/api/createUser", (req, res) => { auth .createUser(req.body) .then(userRecord => { const { uid } = userRecord; addUserToDB(req.body, uid, res); }) .catch(e => { res.status(400).send({ error: e.message }); }); }); //Get user by uid app.get("/api/getUser/:uid", (req, res) => { let uid = req.params.uid; console.log(uid); let ref = db.collection("users").doc(uid); ref .get() .then(doc => { if (!doc.exists) { res.status(404).send({ error: "No such user." }); } else { res.send(doc.data()); } }) .catch(err => { res.status(404).send({ error: err.message }); }); }); //Update a user by id app.patch("/api/updateUser/:uid", (req, res) => { let uid = req.params.uid; console.log(uid); let ref = db.collection("users").doc(uid); let userData = req.body; console.log(userData); ref .update(userData) .then(() => { res.send({ message: "Updated User!" }); }) .catch(e => { res.status(400).send({ error: e.message }); }); }); //Add a new listing, body should include owner id app.post("/api/addListing", (req, res) => { console.log("add listing"); console.log("req.body: "); db.collection("listings") .add(req.body) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); res.send(docRef.id); }) .catch(function(error) { console.error("Error adding document: ", error); }); }); // Get all listings -> probably need to add a filter for location or something // later app.get("/api/getListings", (req, res) => { let listingsRef = db.collection("listings"); let allListings = []; listingsRef.get().then(snapshot => { snapshot.forEach(doc => { let listing_id = doc.id; let data = { ...doc.data() }; data["listing_id"] = listing_id; allListings.push(data); }); res.send(allListings); }); }); //Get listings belonging to a user (owner) app.get("/api/getListings/:uid", (req, res) => { const uid = req.params.uid; let allListings = []; let ref = db.collection("listings"); ref .where("owner_uid", "==", uid) .get() .then(snapshot => { snapshot.forEach(doc => { let listing_id = doc.id; let data = { ...doc.data() }; data["listing_id"] = listing_id; allListings.push(data); }); res.send(allListings); }) .catch(err => { res.status(404).send({ error: err.message }); }); }); //Get listing by listing id app.get("/api/getListing/:listing_id", (req, res) => { const id = req.params.listing_id; let ref = db.collection("listings").doc(id); ref .get() .then(doc => { if (!doc.exists) { res.status(404).send({ error: "No such listing." }); } else { let id = doc.id; res.send(doc.data()); } }) .catch(err => { res.status(404).send({ error: err.message }); }); }); // Adds user to the firestore DB, seperate from the auth users firebase has. // These users will have all our info needed. function addUserToDB(user, uid, res) { //don't store their password delete user.password; db.collection("users") .doc(uid) .set(user) .then(() => { res.send({ uid: uid }); }) .catch(e => { //Handle Error console.log(e.message); }); } // if the owner_id is equal to the current user_id then show update listing // button should be done on the front end. app.patch("/api/updateListing/:listing_id", (req, res) => { let listingID = req.params.listing_id; console.log(listingID); let ref = db.collection("listings").doc(listingID); let updateData = req.body; console.log(updateData); ref .update(updateData) .then(() => { res.send({ message: "Updated Listing!" }); }) .catch(e => { res.status(400).send({ error: e.message }); }); }); // get visiting list for a given user_id passed in the parameter app.get("/api/getVisitingList/:uid", (req, res) => { const uid = req.params.uid; console.log(uid); let allvisits = []; let ref = db.collection("visits"); ref .where("user_id", "==", uid) .get() .then(snapshot => { snapshot.forEach(doc => { let id = doc.id; console.log(id); let data = doc.data(); console.log(doc.data()); allvisits.push(data); }); res.send(allvisits); }) .catch(err => { res.status(404).send({ error: err.message }); }); }); app.post("/api/addToVisitingList", (req, res) => { db.collection("visits") .add(req.body) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); res.send(docRef.id); }) .catch(function(error) { console.error("Error adding document: ", error); }); }); app.delete("/api/deleteListing/:listing_id", (req, res) => { const deleteListing = req.params.listing_id; db.collection("listings") .doc(deleteListing) .delete() .then(function(docRef) { console.log( "Property with id " + deleteListing + " successfully deleted" ); res.send("Property with id " + deleteListing + " successfully deleted"); }) .catch(function(error) { console.error("Error deleting listing: ", error); }); }); app.listen(port, () => console.log(`Listening on port ${port}`));
true
474518da15b59b4a408dd697cf6438610ed36c6a
JavaScript
Fengxx545/RNStudyTest
/js/page/AyncStoreDemoPage.js
UTF-8
3,396
2.71875
3
[]
no_license
import React, { Component } from 'react'; import { Platform, StyleSheet, Text, View, TextInput, AsyncStorage } from 'react-native'; const KEY = "save_key"; export default class AyncStoreDemoPage extends Component { constructor(props) { super(props) this.state = { showText: '' } } doSave() { //用法一 AsyncStorage.setItem(KEY, this.value, error => { error && console.log(error.toString()); }); // //用法二 // AsyncStorage.setItem(KEY, this.value) // .catch(error => { // error && console.log(error.toString()); // }); // // //用法三 // try { // await AsyncStorage.setItem(KEY, this.value); // } catch (error) { // error && console.log(error.toString()); // } } doRemove() { //用法一 AsyncStorage.removeItem(KEY, error => { error && console.log(error.toString()); }); // //用法二 // AsyncStorage.removeItem(KEY) // .catch(error => { // error && console.log(error.toString()); // }); // // //用法三 // try { // await AsyncStorage.removeItem(KEY); // } catch (error) { // error && console.log(error.toString()); // } } getData() { //用法一 AsyncStorage.getItem(KEY, (error, value) => { this.setState({ showText: value }); console.log(value); error && console.log(error.toString()); }); // //用法二 // AsyncStorage.getItem(KEY) // .then(value => { // this.setState({ // showText: value // }); // console.log(value); // // }) // .catch(error => { // error && console.log(error.toString()); // }); // //用法三 // try { // const value = await AsyncStorage.getItem(KEY); // this.setState({ // showText: value // }); // console.log(value); // } catch (error) { // error && console.log(error.toString()); // } } render() { return ( <View style={styles.container}> <View style={styles.input_container}> <TextInput style={styles.input} onChangeText={text => { this.value = text; }} /> </View> <View style={styles.input_container}> <Text style={styles.welcome} onPress={() => { this.doSave(); }} >save</Text> <Text style={styles.welcome} onPress={() => { this.doRemove(); }} >del</Text> <Text style={styles.welcome} onPress={() => { this.getData(); }} >get</Text> </View> <Text style={styles.instructions}>{this.state.showText}</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, // justifyContent: 'center', // alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, input: { height: 40, flex: 1, borderColor: 'blue', borderWidth: 1, }, input_container: { flexDirection: "row" } });
true
ee2c21cb07f496e77ba7d9959948137e7e321fed
JavaScript
surajhiremath23/Project3rdSem
/web PROJECT/game.js
UTF-8
4,958
2.765625
3
[]
no_license
var docPs0=document.getElementById('pScore-0'); var docPs1=document.getElementById('pScore-1'); var PScore=0,CScore=0,TCScore; var activePlayer=1; var gamePlaying=false; document.getElementById('red1').style.display='block'; document.getElementById('red0').style.display='none'; document.getElementById('comturn').style.display='none'; document.getElementById('yourturn').style.display='none'; document.querySelector('.btn1').addEventListener('click', function () { if(gamePlaying){ buttonWork(1); } }); document.querySelector('.btn2').addEventListener('click', function () { if(gamePlaying){ buttonWork(2); } }); document.querySelector('.btn3').addEventListener('click', function () { if(gamePlaying){ buttonWork(3); } }); document.querySelector('.btn4').addEventListener('click', function () { if(gamePlaying){ buttonWork(4); } }); document.querySelector('.btn5').addEventListener('click', function () { if(gamePlaying){ buttonWork(5); } }); document.querySelector('.btn6').addEventListener('click', function () { if(gamePlaying){ buttonWork(6); } }); function ComScore(){ TCScore=Math.floor(Math.random()*6)+1; document.getElementById('pScore-0').textContent=TCScore; } function checkResult(TScore){ if(TCScore===TScore){ if(CScore<PScore){ document.getElementById('name1').textContent='Winner'; gamePlaying=false; document.getElementById('red0').style.display='none'; CScore-=TScore; } else if((CScore-TScore)===PScore){ console.log('Draw'); gamePlaying=false; document.getElementById('red0').style.display='none'; CScore-=TScore; } } if(gamePlaying){ if(CScore>PScore){ document.getElementById('name0').textContent='Winner'; gamePlaying=false; document.getElementById('score-0').textContent=CScore; document.getElementById('red0').style.display='none'; } } } function Active(){ if(activePlayer===0){ document.getElementById('comturn').style.display='block'; document.getElementById('yourturn').style.display='none'; document.getElementById('red0').style.display='block'; document.getElementById('red1').style.display='none'; } else{ document.getElementById('red1').style.display='block'; document.getElementById('red0').style.display='none'; } } function buttonWork(btn){ docPs1.textContent=btn; ComScore(); if(activePlayer===1){ if(TCScore!==btn){ PScore+=btn; document.getElementById('score-1').textContent=PScore; } else{ activePlayer=0; } } else{ CScore+=TCScore; checkResult(btn); document.getElementById('score-0').textContent=CScore; } Active(); } function toggleSidebar(){ document.getElementById('sidebar').classList.toggle('active'); } document.getElementById('newgame').addEventListener('click',function(){ if(document.getElementById('name').value){ document.getElementById('pname').textContent=document.getElementById('name').value; document.getElementById('name').style.display='none'; document.getElementById('newgame').style.display='none'; document.getElementById('reset').style.display='block'; document.getElementById('alertmsg').style.display='none'; gamePlaying=true; document.getElementById('yourturn').style.display='block'; } else document.getElementById('alertmsg').style.display='block'; }); document.getElementById('reset').addEventListener('click',function(){ PScore=0; CScore=0; activePlayer=1; gamePlaying=false; document.getElementById('reset').style.display='none'; document.getElementById('name').style.display='block'; document.getElementById('newgame').style.display='block'; document.getElementById('pScore-1').textContent='0'; document.getElementById('pScore-0').textContent='0'; document.getElementById('score-1').textContent='0'; document.getElementById('score-0').textContent='0'; document.getElementById('pname').textContent='Player'; document.getElementById('name0').textContent='Computer'; document.getElementById('name').value=''; document.getElementById('comturn').style.display='none'; document.getElementById('yourturn').style.display='none'; document.getElementById('red1').style.display='block'; document.getElementById('red0').style.display='none'; });
true
d6ba38411e2d81b1977a5be83df8532714c319dd
JavaScript
HYBOBOBO/The.letao_myself
/public/front/js/category.js
UTF-8
1,236
2.78125
3
[]
no_license
// 左边分类 $(function(){ // a标签上的ID var id ; $.ajax({ type:"get", url:"/category/queryTopCategory", dataType:"json", success:function(res){ console.log(res); var htmlStr = template("leftTpl",res) $(".ul_left").html(htmlStr) // 根据返回的数据渲染二级分类 renderId( res.rows[0].id ) } }) // 点击切换分类 $(".ul_left").on("click","a",function(){ // 排他 $(".ul_left").find("a").removeClass("current"); // 添加类名 $(this).addClass("current") // 获取当前a标签的data-id id = $(this).data("id") console.log(id); renderId(id) }) // 右边分类,封装成函数 function renderId(id){ $.ajax({ type:"get", url:"/category/querySecondCategory", data:{ id:id }, dataType:"json", success:function(res){ // console.log(res); var htmlStr = template("rightTpl",res) $(".ul_right").html(htmlStr) } }) } })
true
6d7fa7d2a301f191b25258cfb53b2526c55a6282
JavaScript
dann-y/portfolio-gatsby
/src/components/CustomCursor/CustomCursor.js
UTF-8
996
2.5625
3
[ "MIT" ]
permissive
import React, { useState, useEffect, useContext } from 'react'; import { MouseContext } from '../../context/mouse-context'; function useMousePosition() { const [mousePosition, setMousePosition] = useState({ x: null, y: null }); useEffect(() => { const mouseMoveHandler = (event) => { const { clientX, clientY } = event; setMousePosition({ x: clientX, y: clientY }); }; document.addEventListener('mousemove', mouseMoveHandler); return () => { document.removeEventListener('mousemove', mouseMoveHandler); }; }, []); return mousePosition; } const CustomCursor = () => { const { cursorType, cursorChangeHandler } = useContext(MouseContext); const { x, y } = useMousePosition(); return ( <> {/* 2. */} <div style={{ left: `${x}px`, top: `${y}px` }} className={'ring ' + cursorType}></div> <div className={'dot ' + cursorType} style={{ left: `${x}px`, top: `${y}px` }}></div> </> ); }; export default CustomCursor;
true
cf7a1dc57a455c6e4578f74e89256de01ed6ac0a
JavaScript
coguy450/WagonTwo
/public/js/reports.js
UTF-8
1,090
2.515625
3
[ "MIT" ]
permissive
var app = new Vue({ el: '#app', methods: { goHome: () => { location.href= "/"; } } }) var reportsDiv = new Vue({ el: '#reportsDiv', methods: { }, data: { reports: {} }, beforeCreate: function() { this.$http.get('/pastActions').then(response => { this.reports = response.data; console.log(response.data); }, (err) => { console.log(err); }) this.$http.get('/getRatings').then(response => { console.log(response.data); }, (err) => { console.log(err); }) }, filters: { date: function(val) { const f = new Date(val); const fYear = f.getFullYear(); const fMonth = f.getMonth() + 1; const fDay = f.getDay(); const fHour = f.getHours() > 12 ? f.getHours() - 12 : f.getHours(); const fMinutes = f.getMinutes().length > 1 ? f.getMinutes() : '0' + f.getMinutes(); const AMPM = f.getHours() > 12 ? 'PM' : 'AM'; const formattedDate = fMonth + '/' + fDay + '/' + fYear + ' at ' + fHour + ':' + fMinutes + AMPM; return formattedDate; } } })
true
0a8c04eac76e1fd6a4f4bc883a8e89f771f0d89f
JavaScript
SurpreetM/fewpjs-iterators-filter-lab-v-000
/index.js
UTF-8
464
3.375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Code your solution here function findMatching (driver, string) { return driver.filter( function(d) { return d.toLowerCase() === string.toLowerCase() }) } function fuzzyMatch(driver, string) { let nameLength = string.length return driver.filter( function(d) { return d.slice(0, nameLength) === string }) } function matchName(driver, string) { return driver.filter (function(d) { return d.name === string }) }
true
773863604d5188abb5d2df404798b57345fb7fc3
JavaScript
Ivan-Makarov/hj-homeworks-3
/event-object/skateboard-gallery/js/gallery.js
UTF-8
738
2.796875
3
[]
no_license
'use strict'; let thumbnailsSelector = document.getElementById('nav'); let thumbnails = thumbnailsSelector.getElementsByTagName('a'); let images = ['images/full/01.jpg', 'images/full/02.jpg', 'images/full/03.jpg', 'images/full/04.jpg', 'images/full/05.jpg', 'images/full/06.jpg', 'images/full/07.jpg'] let bigImage = document.getElementById('view'); let thumbnailsArray = Array.from(thumbnails); thumbnailsArray.forEach((thumbnail, i) => { thumbnail.addEventListener('click', function(event) { event.preventDefault(); thumbnailsArray.forEach((item) => { item.classList.remove('gallery-current') }); this.classList.add('gallery-current'); bigImage.src = images[i]; }); });
true
a99acb51dde72bfc19f8b74009f54b866dde6cb9
JavaScript
charlottedrb/lpdim_javascript
/tp3_socket/chat/main.js
UTF-8
1,470
2.78125
3
[]
no_license
document.addEventListener("DOMContentLoaded", () => { //io appelle l'api const socket = io("51.83.36.122:8080") const pseudo = document.querySelector("#pseudo") const text = document.querySelector("#text") const button = document.querySelector("#chat button") //nous met direct dans le input #text text.focus() text.addEventListener("keyup", (e) => { if(e.key == "Enter"){ send() } }) button.addEventListener('click', send) function send() { socket.emit("message", { pseudo: pseudo.value, text: text.value }) text.value = "" } const messages = document.querySelector("#messages") socket.on("message", (data) => { let message = _('div', messages, null, "message") let pseudo = _('span', message, data.pseudo, "pseudoMsg") let textMsg = _('p', message, data.text, "textMsg") //scrollTop : nb de pixel à partir du haut messages.scrollTop = messages.scrollHeight }) //Fonction de factorisation de la création d'élément DOM function _(tag, parent, text = null, id = null, classs = null) { let element = document.createElement(tag) if (text) element.appendChild(document.createTextNode(text)) parent.appendChild(element) if (id) element.id = id if (classs) element.classList.add(classs) return element } })
true
2e9af4a71ede791e368a5e73eda11f63292fe097
JavaScript
developert1990/SimpleMovie_React.js
/client/src/components/Main.jsx
UTF-8
4,066
3.0625
3
[]
no_license
import React, { useState, useEffect } from 'react'; import Zoom from 'react-reveal/Zoom'; const Main = () => { const USER_LS = "currentUser"; const [name, setName] = useState(localStorage.getItem(USER_LS)); const [timeString, setTimeString] = useState(''); const [randomNum, setRandomNum] = useState(parseInt(Math.random() * 3 + 1)); const [hasLocalStorage, setHasLocalStorage] = useState(false); const [isLoading, setIsLoading] = useState(false); const [errorMessage, setErrorMessage] = useState(); const [weather, setWeather] = useState(''); const API_WEATHER_KEY = '015408c7b2ff4cc5a6b9d6332e145cf6'; useEffect(() => { const storageValue = localStorage.getItem(USER_LS); console.log('get data from local Storage'); console.log(storageValue); if (storageValue) { setHasLocalStorage(true); // setName(storageValue); } }, []) useEffect(() => {//내부에서 didmount, update 가 동작, return 함수에는 unmount 가 동작!!!!!!!! const interval = setInterval(() => { const now = new Date(); const date = now.toLocaleDateString(); //const date = now.toLocaleDateString('ko-KR'); 이렇게 하면 한국어로됨 const time = now.toLocaleTimeString(); //const time = now.toLocaleTimeString('ko-KR'); setTimeString(`${date} ${time}`); }, 1000); // loadName(); return () => { console.log('unmounted') clearInterval(interval);//다른 페이지 갔다가 돌아오면, 타이머가 또 실행되서 중복될 수 있어서여!리턴할 때 클리어해주면, 컴포넌트가 언마운트 될 때 인터벌 없애줘영 } }, []); useEffect(() => { setRandomNum(parseInt(Math.random() * 3 + 1)) // set loading flag on render setIsLoading(true); // load location info navigator.geolocation.getCurrentPosition(async position => { const { latitude, longitude } = position.coords; const { place, weatherTemp, clouds } = await loadData(latitude, longitude); setWeather(`${place} ${weatherTemp} ${clouds}`); setIsLoading(false); }, err => { setErrorMessage(err.message); setIsLoading(false); }); }, []); const loadData = async (latitude, longitude) => { try { const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_WEATHER_KEY}&units=metric`); const data = await response.json(); const weatherTemp = data.main.temp; const place = data.name; const clouds = data.weather[0].description; return { weatherTemp, place, clouds }; } catch (err) { console.error(err); return err; } } const handleClick = (e) => { e.preventDefault(); if (name.length > 0) { console.log(name); localStorage.setItem(USER_LS, name); // const storageValue = localStorage.getItem(USER_LS); setHasLocalStorage(true); } } const renderWeather = () => isLoading ? <div className="spinner" /> : <span className="js-weather">{weather}</span>; return ( <Zoom left> <div className="main-screen" style={{ backgroundImage: `url(${require(`../images/${randomNum}.jpg`)})` }}> {errorMessage ? <span>{errorMessage}</span> : renderWeather()} <h1 className="current-time"> {timeString} </h1> {!hasLocalStorage && <form onSubmit={handleClick} className='welcome-form'> <input type="text" placeholder="Write Your Name" className="input-name" onChange={e => setName(e.target.value)} /> </form>} {hasLocalStorage && <h2 className="welcome-msg">Hello {name} ! </h2>} </div> </Zoom> ) } export default Main;
true
5d59da051eeba5e46bab2ff79e48d256829702a3
JavaScript
K750i/JS30
/02 - JS and CSS Clock/script.js
UTF-8
1,141
3.640625
4
[]
no_license
var secondHand = document.querySelector('.second-hand'); var minuteHand = document.querySelector('.min-hand'); var hourHand = document.querySelector('.hour-hand'); function setTime() { // executed at the interval set by setInterval var now = new Date(); var seconds = now.getSeconds(); var mins = now.getMinutes(); var hours = now.getHours(); var secondsDegree = (360 / 60 * seconds) + 90; // add 90deg to offset the initial css rotate transform var minsDegree = (360 / 60 * mins) + 90; var hoursDegree = (360 / 12 * hours) + 90; if (seconds) { secondHand.style.transitionDuration = '0.3s'; minuteHand.style.transitionDuration = '0.3s'; hourHand.style.transitionDuration = '0.3s'; } else { secondHand.style.transitionDuration = '0s'; minuteHand.style.transitionDuration = '0s'; hourHand.style.transitionDuration = '0s'; } secondHand.style.transform = `rotate(${secondsDegree}deg)`; minuteHand.style.transform = `rotate(${minsDegree}deg)`; hourHand.style.transform = `rotate(${hoursDegree}deg)`; console.log(seconds); console.log(secondsDegree); } setInterval(setTime, 1000);
true
40bd57163aaacae759b24ed6ec1d43ec4a628d23
JavaScript
zsnr1/nodejschat
/lekcja1.js
UTF-8
237
3.21875
3
[]
no_license
/* let i = 10; while(i > 0){ console.log(i); i--; }*/ let tablica = ['Tottenham', 'Man United']; /* for (let i of tablica){ console.log(i); }*/ for (let i = 0; i < tablica.length; i++){ console.log(tablica[i]); }
true
8e36bd05e3b030dffb9c3562268341f15d870dd7
JavaScript
sergixnet/javascript-async-examples
/promise-then-catch-finally.js
UTF-8
535
3.546875
4
[]
no_license
const error = true // this is to simulate an error, dont do it in production function sleep(ms) { console.log('Sleeping...') return new Promise((resolve, reject) => { if (error) { return reject({ msg: 'there was an error' }) } else { setTimeout(() => { resolve(ms) }, ms) } }) } console.log('Step 1') sleep(1500) .then(ms => console.log(`I was sleeping for ${ms} ms.`)) .catch(err => console.log(err.msg)) .finally(() => console.log('This executes finally')) console.log('Step 2')
true
77c9be178e57c795811d518d2b6c30c096d416b2
JavaScript
Ebecode/lm-ents
/js/elements.js
UTF-8
7,712
3.109375
3
[]
no_license
// selectors // // paning selectors const showcase = document.querySelector('.showcase-screen'); const menuIcon = document.querySelector('.show-list'); const editIcon = document.querySelector('.show-edit'); const closeIcon = document.querySelector('.hide-list'); const backIcon = document.querySelector('.hide-edit'); // edit form selectors const editTitle = document.querySelector('.edit-container .form-title'); const editFields = document.querySelectorAll('.edit-container form input[type="text"]'); const editName = document.querySelector('#elementname') const editNum = document.querySelector('#elementnumber') const editSym = document.querySelector('#elementsymbol') const editWgt = document.querySelector('#elementweight') const editDelete = document.querySelector('.form-submit.delete'); const btnSave = document.querySelector('.save-element'); const addElem = document.querySelector('.add-element'); // element list selectors const elementsUl = document.querySelector('.element-list') // showcase selectors const showcaseHead = document.querySelector('.input-heading') const swipeIcons = document.querySelectorAll('.swipe-icon') // element block selectors const displayName = document.querySelector(".elem-name") const displaySym = document.querySelector(".elem-symbol") const displayNum = document.querySelector(".elem-number") const displayWeight = document.querySelector(".elem-weight") // other global variables i want // let elementForm //chooses which form to display --! This is an important global variable let updateFunction //allows choosing what update function to use let displayElement //object element for display block values // paning functions // // reset edit form function clearEdit () { editFields.forEach(elem => (elem.value = "")) } function editReset () { editTitle.textContent = "Editar" if (elementsList.length > 0) { editDelete.classList.remove('btn-collapsed') } clearEdit() } // show list pane function showList(event) { showcase.classList.add('tolist') showcase.classList.remove('toedit') closeIcon.classList.remove('icon-hide') backIcon.classList.add('icon-hide'); editIcon.classList.add('icon-hide'); menuIcon.classList.add('icon-hide'); if (elementsList.length > 0) { editDelete.classList.add('btn-collapsed') } //editReset() event.stopImmediatePropagation() } // show showcase, hide list and edit panes function showShowcase(event) { //populate element display block populateBlock(displayElement) populateShowHead(displayElement) showcase.classList.remove('tolist') showcase.classList.remove('toedit') closeIcon.classList.add('icon-hide') backIcon.classList.add('icon-hide') menuIcon.classList.remove('icon-hide') editIcon.classList.remove('icon-hide') if (elementsList.length > 0){ elementForm = showEdit } editReset() event.preventDefault()//used temprarily for adding, modifying an dsaving button's sake event.stopImmediatePropagation() } // show edit pane function showEdit (event) { editReset()//maybe I should remove this updateFunction = "edit" showcase.classList.remove('tolist') showcase.classList.add('toedit') backIcon.classList.remove('icon-hide') closeIcon.classList.add('icon-hide') menuIcon.classList.add('icon-hide') editIcon.classList.add('icon-hide') event.stopImmediatePropagation() } // show add element editform function showAddElement (event) { event.preventDefault() updateFunction = "add" //modifies edit pane editTitle.textContent = "Nuevo elemento" clearEdit() showcase.classList.remove('tolist') showcase.classList.add('toedit') backIcon.classList.remove('icon-hide') closeIcon.classList.add('icon-hide') menuIcon.classList.add('icon-hide') editIcon.classList.add('icon-hide') event.stopImmediatePropagation(); } // Element creation functions // Empty li function addEmptyLi () { const newLi = document.createElement("li") const newInput = document.createElement("input") const newLabel = document.createElement("label") const newContent = document.createTextNode("Sin elementos") newLi.className = "element" newInput.type = "radio" newLabel.appendChild(newContent) newLi.appendChild(newInput) newLi.appendChild(newLabel) elementsUl.appendChild(newLi) } // Element li function addElementLi (obj) {//adds list items to ul list const elemName = obj.name const newLi = document.createElement("li") const newInput = document.createElement("input") const newLabel = document.createElement("label") const newContent = document.createTextNode(elemName) newLi.className = "element" newInput.type = "radio" newLabel.appendChild(newContent) newLi.appendChild(newInput) newLi.appendChild(newLabel) elementsUl.appendChild(newLi) } //populate element block function populateBlock (obj) { displayName.textContent = obj.name displaySym.textContent = obj.sym displayWeight.textContent = obj.weight displayNum.textContent = obj.num } //populate showcase heading function populateShowHead (obj) { showcaseHead.value = obj.name } // show / hide swipe buttons function hideSwipe () { swipeIcons.forEach(x => x.classList.add('btn-collapsed')) } function showSwipe () { swipeIcons.forEach(x => x.classList.remove('btn.collapsed')) } //update elements ul function updateElems (arr) { // clear the ul list if (elementsUl.hasChildNodes) { while (elementsUl.firstChild){ elementsUl.removeChild(elementsUl.firstChild) } } arr.forEach(x => { addElementLi(x) }); } // Object creation functions class Element { constructor(name, sym, num, weight) { this.name = name; this.sym = sym; this.num = num; this.weight = weight; } } //create dummy element const dummy = new Element("Elemento", "?", "0", "0.00") const elementsList = [] if (elementsList.length < 1){ displayElement = dummy populateBlock(displayElement) populateShowHead(displayElement) hideSwipe() addEmptyLi() editDelete.classList.add('btn-collapsed')//to smooth things out for elementForm load elementForm = showAddElement } // Event listeners // paning event listeners menuIcon.addEventListener('click', showList) // editIcon.addEventListener('click', showEdit) //gonna try conditional if elem list empty editIcon.addEventListener('click', elementForm) closeIcon.addEventListener('click', showShowcase) backIcon.addEventListener('click', showShowcase) addElem.addEventListener('click', showAddElement) // form submit listeners btnSave.addEventListener('click', function(event) { // if fields not empty --work on this later // if in add element mode if (updateFunction === "add") { const elName = editName.value const elNumber = editNum.value const elWeight = editWgt.value const elSymbol = editSym.value // create new element object const newElem = new Element(elName, elSymbol, elNumber, elWeight) // add to end of array elementsList.push(newElem) // update display displayElement = elementsList[elementsList.indexOf(newElem)] populateBlock(displayElement) populateShowHead(displayElement) } // if in edit mode // update the elements ul updateElems(elementsList) // call showshowcase showShowcase(event) elementForm = showEdit event.preventDefault() event.stopImmediatePropagation() })
true
31a16d0a4bd0c1af82fc66bd84de42cb137c9f20
JavaScript
sunny-sky/iqa_ssm
/src/main/webapp/js/view/permissionPage.js
UTF-8
4,476
2.53125
3
[]
no_license
var base = $('#base').val(); /* 增加权限 */ function addPermission() { //获取模态框数据 var logicName = $('#addLogicName').val(); var physicalName = $('#addPhysicalName').val(); $.ajax({ type: "POST", url: "addPermission", data: { "logicName":logicName, "physicalName":physicalName }, dataType: "json", success: function(data) { if(data.value=="0"){ self.location='login.html'; }else if(data.value=="1"){ setTimeout("location.reload()",1000) document.getElementById('myModal').style.display='none'; $(".modal-backdrop").remove(); document.getElementById('chongfu').style.display='block'; setTimeout("codefans2()",3000); }else if(data.value=="2"){ setTimeout("location.reload()",1000) document.getElementById('myModal').style.display='none'; $(".modal-backdrop").remove(); document.getElementById('chongfu2').style.display='block'; setTimeout("codefans2()",3000); }else { setTimeout("location.reload()",1000) document.getElementById('myModal').style.display='none'; $(".modal-backdrop").remove(); document.getElementById('success').style.display='block'; setTimeout("codefans()",3000); } } }) } /* 获取要编辑的权限信息 */ function editPermission(id) { //获取权限ID var permissionId = document.getElementById(id).id; //获取权限逻辑名 var editLogicName = document.getElementById("editLogicName"+permissionId).innerText; //获取权限物理名 var editPhysicalName = document.getElementById("editPhysicalName"+permissionId).innerText; $("#editPermissionId").val(permissionId); $("#editLogicName").val(editLogicName); $("#editPhysicalName").val(editPhysicalName); } //提交成功 function codefans(){ var box=document.getElementById("success"); box.style.display="none"; } //物理名重复提交 function codefans2(){ var box=document.getElementById("chongfu"); box.style.display="none"; } //逻辑名重复提交 function codefans3(){ var box=document.getElementById("chongfu2"); box.style.display="none"; } //请勿重复提交 function codefans3(){ var box=document.getElementById("chongfu3"); box.style.display="none"; } /* 提交更改 */ function update() { //获取模态框数据 var permissionId = $('#editPermissionId').val(); var logicName = $('#editLogicName').val(); var physicalName = $('#editPhysicalName').val(); if(permissionId!=null){ $.ajax({ type: "POST", url: "updatePermission", data: { "permissionId":permissionId, "logicName":logicName, "physicalName":physicalName }, dataType: "json", success: function(data) { if(data.value=="0"){ self.location='login.html'; }else if(data.value=="1"){ setTimeout("location.reload()",1000) document.getElementById('myModalEdit').style.display='none'; $(".modal-backdrop").remove(); document.getElementById('chongfu').style.display='block'; setTimeout("codefans()",3000); }else if(data.value=="2"){ setTimeout("location.reload()",1000) document.getElementById('myModalEdit').style.display='none'; $(".modal-backdrop").remove(); document.getElementById('chongfu2').style.display='block'; setTimeout("codefans3()",3000); }else{ setTimeout("location.reload()",1000) document.getElementById('myModalEdit').style.display='none'; $(".modal-backdrop").remove(); document.getElementById('success').style.display='block'; setTimeout("codefans()",3000); } } }) } } /* 删除权限 */ function deletePermission(id){ //获取模态框数据 var permissionId = document.getElementById(id).id; if(permissionId!=null){ if (confirm("确认将该权限删除?未经上级同意,禁止删除!")) { $.ajax({ type: "POST", url: "deletePermission", data: { "permissionId":permissionId }, dataType: "json", success: function(data) { if(data.value=="0"){ self.location='login.html'; }else if(data.value=="1"){ setTimeout("location.reload()",1000) document.getElementById('success').style.display='block'; setTimeout("codefans()",3000); } } }) ; } else { return; } } }
true
b706bdebef5e4b5a0c84af235aa099f398878c9d
JavaScript
chuyingqifei/2017-05-18-01-58-06-1495072686
/main/main.js
UTF-8
220
3.140625
3
[]
no_license
module.exports = function main(str) { // Write your cade here var len = str.length; var sum = 0; for(var i = 0;i<len;i++){ var x = parseInt(str.charAt(i)); sum += x; } return sum; }
true
c68946a550d347fabbb05fc879d4beb15d864354
JavaScript
toneyhiggins2/liri-node-app
/liri.js
UTF-8
6,893
3.078125
3
[]
no_license
require("dotenv").config(); var keys = require("./keys.js"); var axios = require("axios"); var fs = require("fs"); var moment = require("moment"); var Spotify = require('node-spotify-api'); var spotify = new Spotify(keys.spotify); var selectAction = process.argv[2]; var userSearch = process.argv.slice(3).join(" "); var concert = function(artist){ var URL = "https://rest.bandsintown.com/artists/" + artist + "/events?app_id=codingbootcamp"; axios.get(URL).then(function(response) { // Place the response.data into a variable, jsonData. var jsonData = response.data; // showData ends up being the string containing the show data we will print to the console var showData = [ "Venue: " + jsonData.venue.name, "Location: " + jsonData.venue.city, "Date: " + moment(jsonData.datetime, "MM/DD/YYY") ].join("\n\n"); // Append showData and the divider to log.txt, print showData to the console fs.appendFile("log.txt", showData + divider, function(err) { if (err) throw err; console.log(showData); }); console.log(showData); }); } var spotifyThis = function(song) { spotify .search({ type: 'track', query: userSearch }) .then(function(response) { //console.log(response); var jsonData = response.tracks.items; console.log("Below is the jsonData"); console.log(jsonData); // showData ends up being the string containing the show data we will print to the console var songData = [ "Artist: " + jsonData.artists, "Song Name: " + jsonData.name, "Song URL: " + jsonData.preview_url, "Album: " + jsonData.album.name ].join("\n\n"); // Append showData and the divider to log.txt, print showData to the console fs.appendFile("log.txt", songData, function(err) { if (err) throw err; console.log(songData); }); }) .catch(function(err) { console.log(err); }); } var movieThis = function(movie){ var URL = "http://www.omdbapi.com/?t=" + movie + "&y=&plot=short&apikey=trilogy" axios.get(URL).then(function(response) { // Place the response.data into a variable, jsonData. var jsonData = response.data; console.log(jsonData); // showData ends up being the string containing the show data we will print to the console var movieData = [ "Title: " + jsonData.Title, "Year: " + jsonData.Year, "IMDB Rating: " + jsonData.Ratings[0].Value, "Rotten Tomatoes Rating: " + jsonData.Ratings[1].Value, "Country: " + jsonData.Country, "Language: " + jsonData.Language, "Plot: " + jsonData.Plot, "Actors: " + jsonData.Actors ].join("\n\n"); // Append showData and the divider to log.txt, print showData to the console fs.appendFile("log.txt", movieData, function(err) { if (err) throw err; console.log(movieData); }); //console.log(movieData); }); } if (selectAction === "concert-this") { concert(userSearch); } else if (selectAction === "spotify-this-song") { spotifyThis(userSearch); } else if (selectAction === "movie-this") { movieThis(userSearch); } else if (selectAction === "do-what-it-says") { } // var Search = function() { // // divider will be used as a spacer between the tv data we print in log.txt // var divider = "\n------------------------------------------------------------\n\n"; // // findShow takes in the name of a tv show and searches the tvmaze API // this.concertThis = function(artist) { // var URL = "https://rest.bandsintown.com/artists/" + artist + "/events?app_id=codingbootcamp"; // axios.get(URL).then(function(response) { // // Place the response.data into a variable, jsonData. // var jsonData = response.data; // // showData ends up being the string containing the show data we will print to the console // var showData = [ // "Venue: " + jsonData.venue.name, // "Location: " + jsonData.venue.city, // "Date: " + moment(jsonData.datetime, "MM/DD/YYY") // ].join("\n\n"); // // Append showData and the divider to log.txt, print showData to the console // fs.appendFile("log.txt", showData + divider, function(err) { // if (err) throw err; // console.log(showData); // }); // console.log(showData); // }); // }; // this.spotifySong = function(song) { // //var URL = "http://api.tvmaze.com/search/people?q=" + song; // // Add code to search the TVMaze API for the given actor // // The API will return an array containing multiple actors, just grab the first result // // Append the actor's name, birthday, gender, country, and URL to the `log.txt` file // // Print this information to the console // spotify // .search({ type: 'track', query: 'spotify-this-song' }) // .then(function(response) { // console.log(response); // var jsonData = response.data; // // showData ends up being the string containing the show data we will print to the console // var songData = [ // "Artist: " + jsonData.person.name, // "Song Name: " + jsonData.person.birthday, // "Song URL: " + jsonData.person.gender, // "Album: " + jsonData.person.country.name // ].join("\n\n"); // // Append showData and the divider to log.txt, print showData to the console // fs.appendFile("log.txt", songData + divider, function(err) { // if (err) throw err; // console.log(songData); // }); // }) // .catch(function(err) { // console.log(err); // }); // }; // this.movieThis = function(movie) { // var URL = "http://www.omdbapi.com/?t=" + movie + "&y=&plot=short&apikey=trilogy" // axios.get(URL).then(function(response) { // // Place the response.data into a variable, jsonData. // var jsonData = response.data; // // showData ends up being the string containing the show data we will print to the console // var movieData = [ // "Title: " + jsonData.Title, // "Year: " + jsonData.Year, // "IMDB Rating: " + jsonData.Rating[0].Source, // "Rotten Tomatoes Rating: " + jsonData.Rating[1].Source, // "Country: " + jsonData.Country, // "Language: " + jsonData.Language, // "Plot: " + jsonData.Plot, // "Actors: " + jsonData.Actors // ].join("\n\n"); // // Append showData and the divider to log.txt, print showData to the console // fs.appendFile("log.txt", movieData + divider, function(err) { // if (err) throw err; // console.log(showData); // }); // console.log(showData); // }); // }; // };
true
95b4181777b6390633f8ba73232d4ba26e639c9f
JavaScript
NSIPIRAN/NodeJSCoursera
/models/biclicleta.js
UTF-8
906
3.09375
3
[]
no_license
var bicicleta=function(id,color,modelo,ubicacion){ this.id =id; this.color=color; this.modelo =modelo; this.ubicacion=ubicacion; } bicicleta.prototype.toString=function(){ return 'id: '+this.id + "| color: "+ this.color; } bicicleta.allBicis = []; bicicleta.add=function(aBici){ bicicleta.allBicis.push(aBici); } bicicleta.findById=function(aBiciId){ aBici=bicicleta.allBicis.find(x=>x.id==aBiciId); if(aBici){ return aBici;} else throw new Error(`No existe una bicicleta con el id ${aBici}`); } bicicleta.removeById = function(aBiciId){ for(var i=0;i<bicicleta.allBicis.length;i++){ bicicleta.allBicis.splice(i,1); break; } } var a= new bicicleta( 1,'rojo','urbana', [-8.109864,-79.024834]) var b= new bicicleta( 2,'blanco','urbana', [-8.13,-79.02485]) bicicleta.add(a); bicicleta.add(b); module.exports=bicicleta;
true
da4b721278a94407156d65d25a6ec31ed3317fe9
JavaScript
jameskreye/Web-Development
/2. Maths Game (JS)/javascript.js
UTF-8
5,831
3.21875
3
[ "MIT" ]
permissive
var playing = false; var action; var timeremaining; var score; var correctAnswer; //game lan komanse a zero , epi varyab playing komanse ak valeur faux. kote kem rele function an, kom kondisyon if lan pa executer , li ynyorel li ale nan else la, epi else la chanje valeur palying li bal true. sa vle di map jwe, konnya lem klike sou bouton , kondisyon an ale nan true a. li reload page lan epi , li reset page lan. //if we click on the start button document.getElementById("startreset").onclick = function(){ //if we are playing if(playing == true){ location.reload(); //reload the page }else{ //if we are not playing playing = true; //set score to 0 score = 0 document.getElementById("scorevalue").innerHTML = score; //show countdown box timeremaining = 60; document.getElementById("timeremainingvalue").innerHTML = timeremaining; //hide game over box hide("gameOver"); //i show time remaining box that was hidden. the display was none in the css file show("timeremaining"); //change button to reset document.getElementById("startreset").innerHTML = "Reset Game"; startCountdown(); //generate a new Q&A generateQA(); } } //seccion donde se hace click sobre el numero , correcto o incorrecto for(i = 1; i < 5 ; i++ ){ document.getElementById("box"+i).onclick = function(){ //check if we are playing if(playing == true){ //check now if answer is correct //i use this here , because i am referring to that same box that is being clicked. if(this.innerHTML == correctAnswer){ //correct answer score++; //actualizamos el nuevo valor de score document.getElementById("scorevalue").innerHTML = score; //hide wrong box and show correct box hide("wrong"); show("correct"); setTimeout(function(){ hide("correct"); }, 1000); generateQA(); showPrize(score,"medal"); }else{ hide("correct"); show("wrong"); setTimeout(function(){ hide("wrong"); }, 1000); } } } } //function sections //countdown function function startCountdown(){ action = setInterval(function(){ timeremaining -= 1; document.getElementById("timeremainingvalue").innerHTML = timeremaining; if(timeremaining == 0){ //game over stopCountdown(); show("gameOver"); document.getElementById("gameOver").innerHTML = "<p>Game over!</p><p>Your score is " + score + ".</p>"; //making the time remaining box desapear hide("timeremaining"); hide("correct"); hide("wrong"); playing = false; document.getElementById("startreset").innerHTML = "Start Game"; } }, 1000); } function showPrize(score,id){ if(score == 10){ show(id); } } //function to stop the counter so it dont go below zero function stopCountdown(){ clearInterval(action); } //function to hide function hide(id){ document.getElementById(id).style.display = "none"; } //function to show function show(id){ document.getElementById(id).style.display = "block"; } //generate question and answer function generateQA(){ var x = 1 + Math.round(9*Math.random()); var y = 1 + Math.round(9*Math.random()); correctAnswer = x * y; document.getElementById("question").innerHTML = x + "x" + y; //generate a random number from 1 to 4 , so the correct answer can fall randomly on a any box var correctPosition = 1 + Math.round(3*Math.random()); document.getElementById("box"+correctPosition).innerHTML = correctAnswer; //fill other boxes with wrong answers //this array start with one value, and later more values //are added with the method push var answers = [correctAnswer] for(i=1; i < 5; i++){ if(i !== correctPosition){ var wrongAnswer; do { wrongAnswer = (1 + Math.round(9*Math.random())) * (1 + Math.round(9*Math.random())); }while(answers.indexOf(wrongAnswer) > -1) document.getElementById("box"+i).innerHTML = wrongAnswer; answers.push(wrongAnswer); } } //click on answer box document.getElementById("box1").onclick = function(){ //check if we are playing if(playing == true){ //check now if answer is correct //i use this here , because i am referring to that same box that is being clicked. if(this.innerHTML == correctAnswer){ //correct answer score++; //actualizamos el nuevo valor de score document.getElementById("scorevalue").innerHTML = score; //hide wrong box and show correct box hide("wrong"); show("correct"); setTimeout(function(){ hide("correct"); }, 1000); generateQA(); }else{ hide("correct"); show("wrong"); setTimeout(function(){ hide("wrong"); }, 1000); } } } }
true
a18242fb06c04cd7dd00afd4761239068f0c7ee9
JavaScript
bhanu-pappala/Random
/JavaScript/howSum.js
UTF-8
653
2.953125
3
[]
no_license
#!/usr/bin/node const howSum = (target, arr, memo={}) => { if (target in memo) return memo[target]; if (target == 0) { return []; } if (target < 0) return null; for (let num of arr) { const remainder = target - num; const result = howSum(remainder, arr); if (result !== null) { memo[target] = [...result, num]; return memo[target]; } } memo[target] = null; return null; }; console.log(howSum(7, [2, 3])); console.log(howSum(7, [5, 4, 3, 7])); console.log(howSum(8, [2, 3, 4, 5, 6, 7, 8, 8, 9, 0])); console.log(howSum(5, [6]))
true
02bebf1bba5cd641541a31a8534c39759bc69cb7
JavaScript
thanhnavi17/DotaStore
/src/main/webapp/js/hethong.js
UTF-8
5,019
2.703125
3
[ "MIT" ]
permissive
var FormModalIsValid = true; function ValidateRequireControl(el, errorMes) { $(el).removeClass('is-invalid') $(el).nextAll(".spanError").remove() if ($(el).val() == null || $(el).val() == undefined) { $(el).addClass('is-invalid') $(el).after(`<span class = "text-danger spanError"> ${errorMes}</span>`) FormModalIsValid = false } else { let valuectl = $(el).val().trim() if (valuectl == null || valuectl == '') { $(el).addClass('is-invalid') $(el).after(`<span class = "text-danger spanError"> ${errorMes}</span>`) FormModalIsValid = false } } } function CreateValidate(el, errorMes) { $(el).removeClass('is-invalid') $(el).nextAll(".spanError").remove() $(el).addClass('is-invalid') $(el).after(`<span class = "text-danger spanError"> ${errorMes}</span>`) FormModalIsValid = false } function ClearError(el) { $(el).removeClass('is-invalid') $(el).nextAll(".spanError").remove() } function ValidateRequireControlMaxLength(el, errorMes, length) { if (FormModalIsValid) { let valuectl = $(el).val().trim() if (valuectl != null && valuectl != '') { $(el).removeClass('is-invalid') $(el).nextAll(".spanError").remove() if (valuectl.length > length) { $(el).addClass('is-invalid') $(el).after(`<span class = "text-danger spanError"> ${errorMes}</span>`) FormModalIsValid = false } } } } function ValidateRequireControlMinLength(el, errorMes, length) { if (FormModalIsValid) { let valuectl = $(el).val().trim() if (valuectl != null && valuectl != '') { $(el).removeClass('is-invalid') $(el).nextAll(".spanError").remove() if (valuectl.length < length) { $(el).addClass('is-invalid') $(el).after(`<span class = "text-danger spanError"> ${errorMes}</span>`) FormModalIsValid = false } } } } function ValidateRequireControlPass(el1, el2, errorMes) { let valuectl1 = $(el1).val().trim() let valuectl2 = $(el2).val().trim() if (valuectl1 != null && valuectl1 != '' && valuectl2 != null && valuectl2 != '') { $(el2).removeClass('is-invalid') $(el2).nextAll(".spanError").remove() if (valuectl1 != valuectl2) { $(el2).addClass('is-invalid') $(el2).after(`<span class = "text-danger spanError"> ${errorMes}</span>`) FormModalIsValid = false } } } function ValidateRequireControlEmail(el, errorMes) { let valuectl = $(el).val().trim() $(el).removeClass('is-invalid') $(el).nextAll(".spanError").remove() if (FormModalIsValid) { if (ValidateEmail(valuectl) == false) { $(el).addClass('is-invalid') $(el).after(`<span class = "text-danger spanError"> ${errorMes}</span>`) FormModalIsValid = false } } } function ValidateNumber(el, errorMes) { let valuectl = $(el).val().trim() $(el).removeClass('is-invalid') $(el).nextAll(".spanError").remove() if (FormModalIsValid) { if (CheckIsNumber(valuectl) == false) { $(el).addClass('is-invalid') $(el).after(`<span class = "text-danger spanError"> ${errorMes}</span>`) FormModalIsValid = false } } } function ValidatePassword(el, errorMes) { let valuectl = $(el).val().trim() $(el).removeClass('is-invalid') $(el).nextAll(".spanError").remove() if (FormModalIsValid) { if (CheckPassword(valuectl) == false) { $(el).addClass('is-invalid') $(el).after(`<span class = "text-danger spanError"> ${errorMes}</span>`) FormModalIsValid = false } } } function ValidateEmail(mail) { if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail)) { return (true) } return (false) } // mật khẩu phải có 1 chữ hoa, 1 chữ thường , 1 số, 1 chữ cái đặc biệt, 8-15 kí tự function CheckPassword(inputtxt) { let decimal = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/; if (inputtxt.match(decimal)) { return true } return false } function CheckIsNumber(num) { if (Number.isInteger(Number(num))) { return true } return false } function LoadAjaxContent(url, container) { $(container).html("<div><div class=\"loader\"></div></div>"); $.ajax({ url: encodeURI(url), cache: false, type: "GET", success: function (data) { $(container).html(data); } }); } function PostAction(url, container) { $(container).html("<div><div class=\"loader\"></div></div>"); $.ajax({ url: encodeURI(url), cache: false, type: "GET", success: function (data) { $(container).html(data); } }); }
true