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
2a2524eac9661ea2364e50c9a55d7bebc1f9c81e
JavaScript
npdr/keeper-app
/keeper-app/src/components/Note/Note.jsx
UTF-8
2,010
2.640625
3
[]
no_license
import React, { useState } from 'react'; import DeleteIcon from '@material-ui/icons/Delete'; import EditIcon from '@material-ui/icons/Edit'; import CheckCircleIcon from '@material-ui/icons/CheckCircle'; import './styles.css'; function Note(props) { const [editable, setEditable] = useState(false); const [note, setNote] = useState({ title: props.title, content: props.content }); function handleEdit() { setEditable(!editable); } function handleChange(event) { const { name, value } = event.target; setNote(prevState => { return { ...prevState, [name]: value }; }); } function handleDelete() { props.deleteFunction(props.id); } function handleUpdate() { const noteToUpdate = { id: props.id, title: note.title, content: note.content }; props.updateFunction(noteToUpdate); setEditable(!editable); } return ( <div id={props.id} className="note"> {editable ? <div className="note-edit"> <input name='title' onChange={handleChange} value={note.title} /> <textarea name='content' onChange={handleChange} value={note.content} rows='3' /> <button onClick={handleUpdate}><CheckCircleIcon /></button> </div> : <div> <button onClick={handleEdit}><EditIcon /></button> <h1>{note.title}</h1> <p>{note.content}</p> <button onClick={handleDelete}><DeleteIcon /></button> </div> } </div> ); } export default Note;
true
146a0b5f5cc6f21d0a0b59fdaede3f03ee89fe48
JavaScript
ASE-thingy-blue/thingy-api-blue
/test/test.js
UTF-8
12,759
2.65625
3
[]
no_license
//-----SETUP----- // install ava as global package // execute: // npm install --global ava //all test in the "test" folder will get executed //you can execute the files via npm test in the route folder //!!!!!!!!!!!!DONT FORGET TO START THE DATABASE!!!!!!! //test values get injected! import test from 'ava'; import server from '../index'; import schemas from '../routing/helper/responseSchemas'; const Mongoose = require('mongoose'); const Joi = require('joi'); let User = Mongoose.model('User'); let token; let terrariumId; let thingyId; //inject test data to the database //and makes the token available as class variable test.before(t => { //require('child_process').execSync("node testvalues/insertTestValues.js"); //Get token const requestToken = Object.assign({}, { method: 'POST', url: '/authenticate', payload: { name: "Joe Slowinski", password: "testpw" } }); return server.inject(requestToken) .then(response => { token = response.result.token; }); }); test.before(t => { //Get terrarium id const requestTerr = Object.assign({}, { method: 'GET', url: '/terrarium', payload: {}, headers: { authorization: token } }); return server.inject(requestTerr) .then(response => { terrariumId = JSON.parse(response.payload)[0]._id; }); //Get thingy id }); test.before(t => { const requestThin = Object.assign({}, { method: 'GET', url: '/terrarium/'+terrariumId+'/thingies', payload: {}, headers: { authorization: token } }); return server.inject(requestThin) .then(response => { thingyId = JSON.parse(response.payload).thingies[0]._id; }); }); //apis that dont need authentication test('Test if the home is working', t => { const request = Object.assign({}, { method: 'GET', url: '/', payload: {} }); return server.inject(request) .then(response => { t.is(response.statusCode, 200, 'status code is 200 so the home is available'); }); }); //api with authentication test('Test /authentication', t => { const request = Object.assign({}, { method: 'POST', url: '/authenticate', payload: { name: "Joe Slowinski", password: "testpw" } }); return server.inject(request) .then(response => { token = response.result.token; t.is(response.statusCode, 200) && t.true(response.result.success); }); }); /** * ALL TERRARIUMS */ test('Test /terrarium', t => { const request = Object.assign({}, { method: 'GET', url: '/terrarium', payload: {}, headers: { authorization: token } }); let schema = Joi.array().items({ "_id": Joi.string(), "name": Joi.string(), "thingies" : Joi.array().items(schemas.thingyWithAll), "isDefault": Joi.boolean() }); return server.inject(request) .then(response => { let resp = JSON.parse(response.payload); let test = Joi.validate(resp, schema); if(test.error === null){ t.is(response.statusCode, 200); } else { console.error(test); t.false(true, "Schema is not fitting the response:\n"); } }); }); test('Test /terrarium/temperature', t => { const request = Object.assign({}, { method: 'GET', url: '/terrarium/temperature', payload: {}, headers: { authorization: token } }); let schema = Joi.array().items({ "_id": Joi.string(), "name": Joi.string(), "thingies": Joi.array().items(schemas.thingyWithTemperatures), "isDefault": Joi.boolean() }); return server.inject(request) .then(response => { let resp = JSON.parse(response.payload); let test = Joi.validate(resp, schema); if(test.error === null){ t.is(response.statusCode, 200); } else { console.error(test); t.false(true, "Schema is not fitting the response:\n"); } }); }); test('Test /terrarium/humidity', t => { const request = Object.assign({}, { method: 'GET', url: '/terrarium/humidity', payload: {}, headers: { authorization: token } }); let schema = Joi.array().items({ "_id": Joi.string(), "name": Joi.string(), "thingies": Joi.array().items(schemas.thingyWithHumidities), "isDefault": Joi.boolean() }); return server.inject(request) .then(response => { let resp = JSON.parse(response.payload); let test = Joi.validate(resp, schema); if(test.error === null){ t.is(response.statusCode, 200); } else { console.error(test); t.false(true, "Schema is not fitting the response:\n"); } }); }); test('Test /terrarium/airquality', t => { const request = Object.assign({}, { method: 'GET', url: '/terrarium/airquality', payload: {}, headers: { authorization: token } }); let schema = Joi.array().items({ "_id": Joi.string(), "name": Joi.string(), "thingies": Joi.array().items(schemas.thingyWithAirQualities), "isDefault": Joi.boolean() }); return server.inject(request) .then(response => { let resp = JSON.parse(response.payload); let test = Joi.validate(resp, schema); if(test.error === null){ t.is(response.statusCode, 200); } else { console.error(test); t.false(true, "Schema is not fitting the response:\n"); } }); }); /** * SPECIFIC TERRARIUMS */ test('Test /terrarium/{terrarium_id}/thingies', t => { const request = Object.assign({}, { method: 'GET', url: '/terrarium/'+terrariumId+'/thingies', payload: {}, headers: { authorization: token } }); let schema = Joi.object({ "_id": Joi.string(), "name": Joi.string(), "thingies": Joi.array().items(schemas.thingy), "isDefault": Joi.boolean() }); return server.inject(request) .then(response => { let resp = JSON.parse(response.payload); let test = Joi.validate(resp, schema); if(test.error === null){ t.is(response.statusCode, 200); } else { console.error(test); t.false(true, "Schema is not fitting the response:\n"); } }); }); test('Test /terrarium/{terrarium_id}/temperatures', t => { const request = Object.assign({}, { method: 'GET', url: '/terrarium/'+terrariumId+'/temperatures', payload: {}, headers: { authorization: token } }); let schema = Joi.object({ "_id": Joi.string(), "name": Joi.string(), "thingies": Joi.array().items(schemas.thingyWithTemperatures), "isDefault": Joi.boolean() }); return server.inject(request) .then(response => { let resp = JSON.parse(response.payload); let test = Joi.validate(resp, schema); if(test.error === null){ t.is(response.statusCode, 200); } else { console.error(test); t.false(true, "Schema is not fitting the response:\n"); } }); }); test('Test /terrarium/{terrarium_id}/humidities', t => { const request = Object.assign({}, { method: 'GET', url: '/terrarium/'+terrariumId+'/humidities', payload: {}, headers: { authorization: token } }); let schema = Joi.object({ "_id": Joi.string(), "name": Joi.string(), "thingies": Joi.array().items(schemas.thingyWithHumidities), "isDefault": Joi.boolean() }); return server.inject(request) .then(response => { let resp = JSON.parse(response.payload); let test = Joi.validate(resp, schema); if(test.error === null){ t.is(response.statusCode, 200); } else { console.error(test); t.false(true, "Schema is not fitting the response:\n"); } }); }); test('Test /terrarium/{terrarium_id}/airqualities', t => { const request = Object.assign({}, { method: 'GET', url: '/terrarium/'+terrariumId+'/airqualities', payload: {}, headers: { authorization: token } }); let schema = Joi.object({ "_id": Joi.string(), "name": Joi.string(), "thingies": Joi.array().items(schemas.thingyWithAirQualities), "isDefault": Joi.boolean() }); return server.inject(request) .then(response => { let resp = JSON.parse(response.payload); let test = Joi.validate(resp, schema); if(test.error === null){ t.is(response.statusCode, 200); } else { console.error(test); t.false(true, "Schema is not fitting the response:\n"); } }); }); /** * SPECIFIC THING IN A SPECIFIC TERRARIUM */ test('Test /terrarium/{terrarium_id}/thingies/{thingy_id}', t => { const request = Object.assign({}, { method: 'GET', url: '/terrarium/'+terrariumId+'/thingies/'+thingyId, payload: {}, headers: { authorization: token } }); let schema = schemas.thingyWithAll; return server.inject(request) .then(response => { let resp = JSON.parse(response.payload); let test = Joi.validate(resp, schema); if(test.error === null){ t.is(response.statusCode, 200); } else { console.error(test); t.false(true, "Schema is not fitting the response:\n"); } }); }); test('Test /terrarium/{terrarium_id}/thingies/{thingy_id}/temperature', t => { const request = Object.assign({}, { method: 'GET', url: '/terrarium/'+terrariumId+'/thingies/'+thingyId+'/temperature', payload: {}, headers: { authorization: token } }); let schema = schemas.thingyWithTemperatures; return server.inject(request) .then(response => { let resp = JSON.parse(response.payload); let test = Joi.validate(resp, schema); if(test.error === null){ t.is(response.statusCode, 200); } else { console.error(test); t.false(true, "Schema is not fitting the response:\n"); } }); }); test('Test /terrarium/{terrarium_id}/thingies/{thingy_id}/humidity', t => { const request = Object.assign({}, { method: 'GET', url: '/terrarium/'+terrariumId+'/thingies/'+thingyId+'/humidity', payload: {}, headers: { authorization: token } }); let schema = schemas.thingyWithHumidities; return server.inject(request) .then(response => { let resp = JSON.parse(response.payload); let test = Joi.validate(resp, schema); if(test.error === null){ t.is(response.statusCode, 200); } else { console.error(test); t.false(true, "Schema is not fitting the response:\n"); } }); }); test('Test /terrarium/{terrarium_id}/thingies/{thingy_id}/airquality', t => { const request = Object.assign({}, { method: 'GET', url: '/terrarium/'+terrariumId+'/thingies/'+thingyId+'/airquality', payload: {}, headers: { authorization: token } }); let schema = schemas.thingyWithAirQualities; return server.inject(request) .then(response => { let resp = JSON.parse(response.payload); let test = Joi.validate(resp, schema); if(test.error === null){ t.is(response.statusCode, 200); } else { console.error(test); t.false(true, "Schema is not fitting the response:\n"); } }); });
true
704a5a1cbcf4696038252a2c5910755759d3309a
JavaScript
patdaburu/jingling
/proxy/ProxyMiddleware.js
UTF-8
12,235
2.578125
3
[ "MIT" ]
permissive
/** * ProxyMiddleware * @module proxy/ProxyMiddleware * {@link http://expressjs.com/en/guide/routing.html|Express Routing} */ "use strict"; var _ = require('underscore'); var Logger = require('../log/Logger'); var EventEmitter = require('events').EventEmitter; var express = require('express'); var inherits = require('util').inherits; var Forwarder = require('./Forwarder'); var url = require('url'); var util = require('util'); /** * These are the defined web service types. * @readonly * @enum {string} */ var ServiceTypes = { /** * MapServer * {@link http://resources.arcgis.com/en/help/main/10.2/index.html#//0154000002m7000000|What is a map service?} */ MAP_SERVER: 'MapServer', /** * FeatureServer * {@link http://resources.arcgis.com/en/help/main/10.2/index.html#//0154000002w8000000|What is a feature service?} */ FEATURE_SERVER: 'FeatureServer', /** * Info - ArcGIS Server Information */ REST_INFO: 'Info' } /** * @class * @classdesc This is a base class for classes that know how to perform proxy functions. * @param {Object} options - These are the options that define the routing behavior. * @param {string} options.serviceUrl - This is the URL of the service to which requests are forwarded. * @param {ServiceTypes} options.serviceType - This is the type of the service to which requests are forwarded. * @param {number} [options.timeout=10*1000] - How long should the proxy wait before timing out a connection? * @param {function({}, function(error, response, body))} [options.request=require('request')] - This is the function used to make HTTP(S) requests. * @param {Forwarder} [options.forwarder=new Forwarder()] - This is the forwarder that handles the actual forwarding of requests. * @param {Logger} [options.logger=new Logger()] - This is the logger used by the proxy router. * @constructor * @see GeocodingProxyRouter * @see MapServerProxyMiddleware * @see RestInfoProxyMiddleware * @see request */ function ProxyRouter(options) { // Mix the args with defaults, then with this object. _.extend(this, _.extend({ serviceUrl: null, serviceType: null, timeout: 10 * 1000, forwarder: new Forwarder(), logger: new Logger(), methods: ['all'] }, options)); /** * This is the Express/Connect router on which this proxy router's behavior is based. * @type {express.Router} * @private */ this._router = express.Router(); /** * These are the routes that have been defined for this router. * @type {Array} * @private * @see {Route} */ this._routes = []; /** * This is a dictionary of regular expression strings and RegExp objects used by the proxy router. * @type {Object} * @see RegExp */ this.re = {}; /** * This is a regular expression that captures everything in a request's original URL after the service type, not * including the query string. * @type {RegExp} */ this.re.subPath = new RegExp('\\/' + this.serviceType + '\\/?(.*)\\??', 'i'); // TODO: Document this regular expression IN DETAIL!!! /** * This is a regular expression pattern (character literal) that can be used to split a sub-path into its parts. * @type {RegExp} */ this.re.pathParts = /\//; // We now need to construct the regular expression that matches and captures everything before the host, // the host itself, and everything after from a URL. var serviceUrlHost = url.parse(this.serviceUrl).hostname; var serviceUrlHostEscapeDots = serviceUrlHost.replace('.', '\\.'); // (https?\:\/\/|^)(services\.arcgisonline\.com)([\/$\?].*) this.re.captureHost = new RegExp('(https?\\:\\/\\/|^)(' + serviceUrlHostEscapeDots + ')([\\/$\\?].*)', 'i'); // TODO: Document this regular expression IN DETAIL!!! /** * This is the proxy router's default route path. * @type {Route} * @private */ this._defaultRoutePath = "/" + this.serviceType + "/?*"; this._defaultRoute = this.addRoute(this._defaultRoutePath); // Let's make sure we have a service type. if (!this.serviceType) { // Log the fact if we don't. this.logger.error(util.format('%s does not specify a service type!', this.constructor.name)); } // Let's make sure we have a service URL. if (!this.serviceUrl) { // Log the fact if we don't. this.logger.error(util.format('%s does not specify URL!', this.constructor.name)); } // If the caller didn't specify any HTTP methods to handle... if (!this.methods) { // Log this! this.logger.warn(util.format('%s specifies no HTTP methods to handle!', this.constructor.name)); } else { // Otherwise, let's set up the handlers! // Iterate over all the known HTTP methods. _.each(['get', 'post', 'put', 'delete', 'all'], function (method) { // If the methods property contains this HTTP method... if (_.intersection(this.methods, [method]).length > 0) { // ...figure out what the name for the handler method is based on the method name. var handler = 'on' + method.charAt(0).toUpperCase() + method.substr(1); // Now, add the default handler for this HTTP method to the default route. this._defaultRoute[method](_.bind(this[handler], this)); } }, this); } } inherits(ProxyRouter, EventEmitter); /** * Get this proxy router's Express/Connect router. "A Router instance is a complete middleware and routing system; * for this reason, it is often referred to as a 'mini-app'." * @returns {Router} * {@link http://expressjs.com/en/guide/routing.html|Express Routing} */ ProxyRouter.prototype.getRouter = function () { return this._router; } /** * Add a new route to this router. * @param {string} path - This is the path the route handles. * @returns {Route} - The method returns the route the newly-created route. */ ProxyRouter.prototype.addRoute = function (path) { // Create the Express/Connect route. var route = this._router.route(path); // The base class injects a handler for all the methods handled by this route. route.all(_.bind(this.onInject, this)); // Add this route to the collection of routes for this router. this._routes.push(route); // Return the route to the caller. return route; } /** * Get the part of a request URL's path that is below this router's service path. * @param {Request} req - This is the original request. * @returns {string} - The method returns the relative path. */ ProxyRouter.prototype.getRelativePathInfo = function (req) { // We're going to populate an object with information about the relative path. var relPathInfo = {}; // Match the request's originalUrl property against the regex that captures the subpath. var match = this.re.subPath.exec(req.originalUrl); // If we found a match... if (match) { // ...it's the path. relPathInfo.path = match[1]; // Also, chop the path up into its constituent pieces. relPathInfo.parts = match[1].split(this.re.pathParts); } else { throw { message: "The original URL did not match the sub-path pattern." }; } // Return the object containing all that relative path information. return relPathInfo; } /** * This is a standard handler function applied to every route created for this proxy. * @param {Request} req - This is the incoming request. * @param {Response} res - This is the outgoing reponse. * @param {function()} next - Call this function to pass control to the next handler. * @see addRoute */ ProxyRouter.prototype.onInject = function (req, res, next) { // Get the relative path from request (a service of this class) and add it to the request object so that other // handlers can use it if they need to. req.relativePathInfo = this.getRelativePathInfo(req); res.setHeader('Access-Control-Allow-Origin', 'http://www.arcgis.com'); // TODO: We have to deal with this. It's necessary for the ESRI tools. res.setHeader('Access-Control-Allow-Credentials', true); res.setHeader('Vary', 'Origin'); // If we've been given the next handler, let's call it. next && next(); } /** * This is the standard handler function provided by this class. * @param {Request} req - This is the incoming request. * @param {Response} res - This is the outgoing reponse. * @param {function()} next - Call this function to pass control to the next handler. * @see addRoute */ ProxyRouter.prototype.onRequest = function (req, res, next) { // To where are we forwarding this request? var to = url.resolve(this.serviceUrl, req.relativePathInfo.path); // Now that we know where's it's going, let the forwarder take it from here. this.forwarder.autoForward(req, to, function (err, res, body) { // When the forwarder is finished, we need to move on to the next handler (assuming a subclass hasn't // opted to deal with that part itself). next && next(); }); } /** * If the proxy router handles all HTTP methods with a common handler, this is the default handler method. Override * this method to modify the proxy's behavior. The default behavior is to pass the call to onRequest(). * @param {Request} req - This is the incoming request. * @param {Response} res - This is the outgoing response. * @param {function()} next - Call this function to pass control to the next handler. * @see onRequest */ ProxyRouter.prototype.onAll = function (req, res, next) { this.onRequest(req, res, next); } /** * This is the standard handler for HTTP 'GET' requests. Override this method to modify the proxy's behavior when * 'GET' requests are handled. The default behavior is to pass the call to onRequest(). * @param {Request} req - This is the incoming request. * @param {Response} res - This is the outgoing response. * @param {function()} next - Call this function to pass control to the next handler. * @see onRequest */ ProxyRouter.prototype.onGet = function (req, res, next) { this.onRequest(req, res, next); } /** * This is the standard handler for HTTP 'GET' requests. Override this method to modify the proxy's behavior when * 'GET' requests are handled. The default behavior is to pass the call to onRequest(). * @param {Request} req - This is the incoming request. * @param {Response} res - This is the outgoing response. * @param {function()} next - Call this function to pass control to the next handler. * @see onRequest */ ProxyRouter.prototype.onPost = function (req, res, next) { this.onRequest(req, res, next); } /** * This is the standard handler for HTTP 'GET' requests. Override this method to modify the proxy's behavior when * 'GET' requests are handled. The default behavior is to pass the call to onRequest(). * @param {Request} req - This is the incoming request. * @param {Response} res - This is the outgoing response. * @param {function()} next - Call this function to pass control to the next handler. * @see onRequest */ ProxyRouter.prototype.onPut = function (req, res, next) { this.onRequest(req, res, next); } /** * This is the standard handler for HTTP 'GET' requests. Override this method to modify the proxy's behavior when * 'GET' requests are handled. The default behavior is to pass the call to onRequest(). * @param {Request} req - This is the incoming request. * @param {Response} res - This is the outgoing reponse. * @param {function()} next - Call this function to pass control to the next handler. * @see onRequest */ ProxyRouter.prototype.onDelete = function (req, res, next) { this.onRequest(req, res, next); } /** * Destroy the object. */ ProxyRouter.prototype.destroy = function () { // Let everybody know this is happening. this.emit('destroy'); // Remove all the listeners. this.removeAllListeners(); } module.exports = ProxyRouter; /** * These are the defined web service types. * @readonly * @enum {string} */ module.exports.ServiceTypes = ServiceTypes;
true
4a948db7e0ddcdbc750403d8c2b9d60493a290bb
JavaScript
Californ1a/AoC
/2020/2/part1.js
UTF-8
787
3.6875
4
[]
no_license
const fs = require("fs"); async function readInput(filename) { const input = await fs.promises.readFile(filename, "utf-8"); return input.replace(/\r\n/g, "\n").trim().split("\n"); } function puzzle(input) { let sum = 0; input.forEach((line) => { const reg = /^(\d+)-(\d+) (\w): (.+)$/gi; const matches = reg.exec(line); const minimum = matches[1]; const maximum = matches[2]; const letter = matches[3]; const password = matches[4]; const regex = new RegExp(letter, "gi"); const letters = password.match(regex); if (letters) { const passTest = letters.length >= minimum && letters.length <= maximum; if (passTest) { sum += 1; } } }); return sum; } readInput("input.txt").then((input) => { const answer = puzzle(input); console.log(answer); });
true
e57daa35fdc8afe44943ddc073647bb61ec4c66e
JavaScript
PatriciaPoveda/Buscador-de-series-Codeflix
/src/js/9listener.js
UTF-8
549
2.546875
3
[ "MIT" ]
permissive
const listenRemoveFavList = function () { const icons = document.querySelectorAll(".js-fa-times-circle"); for (let i = 0; i < icons.length; i++) { icons[i].addEventListener("click", removeFavList); } }; const listenFavList = function () { const seriesPaint = document.querySelectorAll(".js-serie"); for (const serie of seriesPaint) { serie.addEventListener("click", paintFavList); } }; favoritesBtn.addEventListener("click", clickButtonReset); btnSearch.addEventListener("click", getSerie); getLocalStorage();
true
b12d9e0352b347c311ea7b3654b94367ec83996f
JavaScript
OmarBara/warmUp
/warmUp18.js
UTF-8
786
4.34375
4
[]
no_license
// You are given an input string. // For each symbol in the string if it's the first character occurence, replace it with a '1', else replace it with the amount of times you've already seen it... // But will your code be performant enough? // Examples: // input = "Hello, World!" // result = "1112111121311" // input = "aaaaaaaaaaaa" // result = "123456789101112" function countChar(string) { // body... var arr = string.split('') //make initial zero array with same lenght var zeros = Array.from(arr) for (var i = 0; i < zeros.length; i++) { zeros[i] = 0 } //compare the value if existed increment zero array for (var i = 0; i < arr.length; i++) { for (var j = i; j < arr.length; j++) { if(arr[i] === arr[j]){ zeros[j]++ } } } return zeros.join('') }
true
8a223c3d5e5f2d27d8742cfbde5a337e560096d2
JavaScript
1kyte/Linkedin-Analysis
/linkedintest/collectionBox/Linkedin Analysis_files/companyChart.js
UTF-8
2,564
2.921875
3
[ "MIT", "Apache-2.0" ]
permissive
( function () { $.get("/data/read?type=company_inAU",function (data, status) { if(status=="success") { dataList = data.data; console.log({'company':data}); createButton(dataList); // createPiaChart(data) }else{ alert("Download data fail!") } }); }() ); function createButton(list) { companyList = document.getElementById('companyListButton'); list.forEach(({location, name}) => { // console.log(location) const company = document.createElement('button'); company.innerText = name company.type = 'button'; company.id = name; onCompanyClick = enhancedOnCompanyClicked(company,name,location); company.onclick = onCompanyClick; companyList.appendChild(company) }) } function enhancedOnCompanyClicked(company,name,list){ return function () { createPiaChart(name,list) } } function createPiaChart(company,data) { var list = []; var name = []; for (var i=0,l=data.length; i<l; i++){ list.push({'value':data[i].number,'name':data[i].title}) name[i] = data[i].title; } // console.log(name) var piaChart = echarts.init(document.getElementById('companyLocation')); option = { title : { text: 'Location of '+company, x:'center', textStyle:{ fontSize: 25, fontWeight:'bolder', }, }, tooltip : { trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)" }, legend: { orient: 'vertical', left: 'left', data: name }, textStyle:{ fontSize: 15, fontWeight:'bolder', }, // roseType: 'radius', series : [ { name: 'Types of jobs', type: 'pie', radius : '55%', center: ['50%', '60%'], data:list, itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] }; piaChart.setOption(option); }
true
7f08bc5553abaa9c5bf75d445e3ad3e24ecfe1fc
JavaScript
avi-walia/ang-cur
/src/app/core/services/page.state.resolver.js
UTF-8
3,567
2.515625
3
[]
no_license
(function () { 'use strict'; angular .module('evolution') .service('pageStateResolver', pageStateResolver); pageStateResolver.$inject = [ 'i18nService', 'ROUTES' ]; /* @ngInject */ function pageStateResolver( i18nService, ROUTES ) { var service = this; service.activePageName = ''; service.pageLoading = false; service.getPageConfigFromState = getPageConfigurationObjectFromStateName; service.setActivePageName = setActivePageName; service.resolve = pageToStateMapper; service.check = stateToPageMapper; /** * Given a state will give you the entire page configuration. * * @param sState string, a state name * @param callback function, to act on */ function getPageConfigurationObjectFromStateName(sState, callback) { var oPageConfiguration = _.find(ROUTES, {stateName: sState}); if (_.isObject(oPageConfiguration)) { // localize it oPageConfiguration = i18nService.filterLocalizedKeys(oPageConfiguration); // closure if (!oPageConfiguration.isAbstract) { callback(oPageConfiguration); } } } /** * Given a page name will return you the entire page configuration. * * @param sPage string, a page name * @param callback function, to act on */ function getPageConfigurationObjectFromPageName(sPage) { var oPageConfiguration = _.find(ROUTES, {pageName: sPage}); if (_.isUndefined(oPageConfiguration)) { return false; } // localize it oPageConfiguration = i18nService.filterLocalizedKeys(oPageConfiguration); return !oPageConfiguration.isAbstract ? oPageConfiguration : false; } /** * Given a state returns a page name. * * @param sState string, a state name * @returns string, holding the requested page name OR empty string (false) */ function stateToPageMapper(sState) { var pageName; service.getPageConfigFromState(sState, function (oPageConfiguration) { pageName = 'pageName' in oPageConfiguration ? oPageConfiguration.pageName : ''; }); return pageName; } /** * Given a page returns a state name. * * @param sPage string, a page name * @returns string, holding the requested state name OR false */ function pageToStateMapper(sPage, callback) { var oPageConfiguration = getPageConfigurationObjectFromPageName(sPage); if ('stateName' in oPageConfiguration) { callback(oPageConfiguration.stateName); } } /** * Sets * "activePageName", the active page name. * * @param sState string, a state name */ function setActivePageName(sState) { var oPageConfiguration = _.find(ROUTES, {stateName: sState}); if (angular.isDefined(oPageConfiguration)){ if ('pageName' in oPageConfiguration) { if (!oPageConfiguration.isAbstract) { service.activePageName = oPageConfiguration.pageName; } } } } } })();
true
c2ddfe7afa9cb4800bafda97dece8cc23db63296
JavaScript
St0rage/DanComp
/script/products.js
UTF-8
1,008
2.71875
3
[]
no_license
// ANIMASI HOVER BOX let hoverProducts = document.querySelector('#hover-box'); let hoverMarketPlace = document.querySelector('#hover-box2'); function hoverBox() { hoverMarketPlace.classList.remove('hover-market-place'); hoverProducts.classList.toggle('hover-products'); } function hoverBox2() { hoverProducts.classList.remove('hover-products'); hoverMarketPlace.classList.toggle('hover-market-place'); } let hoverLi = Array.from(document.querySelector('.list').firstElementChild.children); let listImg = document.querySelector('.list-img').firstElementChild; hoverLi.forEach(e => { e.addEventListener('mouseover', () => { let text = e.firstElementChild.textContent.toLocaleLowerCase(); listImg.setAttribute('src', `../../img/items/hover/${text}.png`); }); }); // BANNER BACKGROUND let banner = document.querySelector('.banner'); let bannerName = banner.getAttribute('name'); banner.style.backgroundImage = `url('../../img/banner/banner-products/${bannerName}.jpg')`;
true
aec2630a10e887c6cce42660782eab366002d98f
JavaScript
rizkyzonna/demokbb
/assets/js/script copy.js
UTF-8
6,112
2.71875
3
[ "MIT" ]
permissive
// date var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; var yyyy = today.getFullYear(); if(dd<10) { dd='0'+dd } if(mm<10) { mm='0'+mm } today = dd+'/'+mm+'/'+yyyy; $("#date").html(today); //time function updateClock ( ) { var currentTime = new Date ( ); var currentHours = currentTime.getHours ( ); var currentMinutes = currentTime.getMinutes ( ); var currentSeconds = currentTime.getSeconds ( ); // Pad the minutes and seconds with leading zeros, if required currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes; currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds; var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds; $("#time").html(currentTimeString); } $(document).ready(function() { setInterval('updateClock()', 1000); }); // Local storage function setLocalStorage() { // Check browser support if (typeof(Storage) !== "undefined") { //Get Value var nk = $('#nk').val(); var nr = $('#nr').val(); var smax = $('#smax').val(); var pth = $('#pth').val(); var ptb = $('#ptb').val(); var kt = $('#kt').val(); var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; var yyyy = today.getFullYear(); if(dd<10) { dd='0'+dd } if(mm<10) { mm='0'+mm } today = dd+'/'+mm+'/'+yyyy; var currentTime = new Date ( ); var currentHours = currentTime.getHours ( ); var currentMinutes = currentTime.getMinutes ( ); var currentSeconds = currentTime.getSeconds ( ); // Pad the minutes and seconds with leading zeros, if required currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes; currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds; var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds; //cek local storage var localLength = localStorage.length; var n = localLength+1; // var kartu = []; kartu[0] = nk; kartu[1] = nr; kartu[2] = smax; kartu[3] = pth; kartu[4] = ptb; kartu[5] = kt; kartu[6] = today + ' ' + currentTimeString; // Store localStorage.setItem("kartu"+n, JSON.stringify(kartu)); // Retrieve console.log(JSON.parse(localStorage.getItem("kartu1"))); window.location.href = 'tk-cek.html'; } else { alert('Sorry, your browser does not support Web Storage...'); } } function viewStorage() { if (localStorage.getItem('current')) { var kartu = JSON.parse(localStorage.getItem('current')); $('#cek-nk').html(kartu[0]); $('#cek-nr').html(kartu[1]); $('#cek-smax').html(kartu[2]); $('#cek-pth').html(kartu[3]); $('#cek-ptb').html(kartu[4]); $('#cek-kt').html(kartu[5]); } else { var localLength = localStorage.length; var getKartu = 'kartu'+localLength; var kartu = JSON.parse(localStorage.getItem(getKartu)); console.log(kartu); $('#cek-nk').html(kartu[0]); $('#cek-nr').html(kartu[1]); $('#cek-smax').html(kartu[2]); $('#cek-pth').html(kartu[3]); $('#cek-ptb').html(kartu[4]); $('#cek-kt').html(kartu[5]); $('#backToInput').attr('onclick', 'backToInput('+localLength+')'); var currentKartu = localStorage.getItem(getKartu); localStorage.setItem('current', currentKartu); } } function backToInput(current) { localStorage.removeItem('kartu'+current); window.location.href = 'tk-index.html'; } function cekCurrent() { if (localStorage.getItem('current')) { var kartu = JSON.parse(localStorage.getItem('current')); $('#nk').val(kartu[0]); $('#nr').val(kartu[1]); $('#smax').val(kartu[2]); $('#pth').val(kartu[3]); $('#ptb').val(kartu[4]); $('#kt').val(kartu[5]); } localStorage.removeItem('current'); } function sendData() { $('#success').html('Input data berhasil'); $('#sendData').remove(); $('#backToInput').remove(); localStorage.removeItem('current'); } function listData(){ var length = localStorage.length; for (var i = 0; i < length; i++) { console.log(JSON.parse(localStorage.getItem('kartu'+(i+1)))); var kartu = []; kartu[i] = JSON.parse(localStorage.getItem('kartu'+(i+1))); $('.table').append('<tr class="dataKartu"><td><input type="checkbox" name=""></td><td id="date'+i+'">'+kartu[i][6]+'</td><td id="nk'+i+'"><a href="#" onclick="editKartu('+(i+1)+')">'+kartu[i][0]+'</a></td><td>Tambah Kartu</td><td id="nr'+i+'">'+kartu[i][1]+'</td><td></td><td>0/1</td></tr>') } } function editKartu() { window.location.href = 'uk-edit.html'; } $("ul > li > ul").hide(); $("ul > li").click(function(e) { e.stopPropagation(); $(this).children().toggle(function(e) { if (!$(this).is(":visible")) { $(this).find("ul").hide(); $(this).find("sub").show(); }; }); $(this).siblings().each(function(i) { if ($(this).children("ul").length > 0) { if ($(this).children("ul").css("display").toLowerCase() == "block") { $(this).children().toggle(function(e) { if (!$(this).is(":visible")) { $(this).find("ul").hide(); $(this).find("sub").show(); }; }); } } }); }); // var names = []; // names[0] = prompt("New member name?"); // localStorage.setItem("names", JSON.stringify(names)); // //... // var storedNames = JSON.parse(localStorage.getItem("names"));
true
8197246f080dae3e64b4d90309f0cf0f43208479
JavaScript
francogramas/blog
/public/js/dropdown.js
UTF-8
1,053
2.796875
3
[ "MIT" ]
permissive
$(document).ready(function(){ $("#paises").change(function(event){ $.get("/departamentos/"+event.target.value+"", function(response,state){ $("#departamentos").empty(); for (i = 0; i < response.length; i++) { $("#departamentos").append("<option value='" + response[i].id+ "'>" + response[i].name + "</option>") } }); }); $("#departamentos").change(function(event){ $.get("/ciudades/"+event.target.value+"", function(response,state){ $("#ciudad").empty(); for (i = 0; i < response.length; i++) { $("#ciudad").append("<option value='" + response[i].id+ "'>" + response[i].name + "</option>") } }); }); $(function() { $("#buscarP").autocomplete({ source: "/buscar/producto", minLength: 1, select: function(event, ui) { $('#buscarP').val(ui.item.value); $('#producto_id').val(ui.item.id); } }); $("#buscarP").click(function(){ $("#buscarP").val(""); $("#producto_id").val("0"); }); }); });
true
110ba5cac5f240cfd54654e55579ec3df98e0fb0
JavaScript
bchaperon/crystal
/src/server/createCard.js
UTF-8
3,326
2.734375
3
[]
no_license
function pickCardValues (values) { var card; var allySubTypeName; // pick out the white listed keys card = _.pick(values, 'cardSet', 'rankInCardSet', 'imageUrl', 'name', 'type', 'subType', 'faction', 'classes', 'castingCost', 'attack', 'defense', 'durability', 'unique', 'restricted', 'rarity', 'description', 'opposingDescription', 'tags'); if (card.classes.length === 0) { card.classes[0] = EnumClasses.neutral; } card.description = card.description || ''; card.tags = card.tags || []; // trim, check var types... // hero if (card.type === EnumCardTypes.hero) { card.subType = null; card.castingCost = null; // only one class, and no neutral hero if (card.classes.length !== 1) { throw new Meteor.Error(403, 'A hero must have exactly one class'); } if (card.classes[0] === EnumClasses.neutral) { throw new Meteor.Error(403, 'The class of a hero cannot be neutral'); } // set health according to the class switch (card.classes[0]) { case EnumClasses.warrior: card.defense = 30; break; case EnumClasses.hunter: case EnumClasses.wulven: case EnumClasses.elemental: card.defense = 28; break; case EnumClasses.rogue: card.defense = 27; break; case EnumClasses.mage: case EnumClasses.priest: card.defense = 26; break; } } // ally : add the subtype in the tags (yari, undead, templar...) if (card.type === EnumCardTypes.ally && card.subType !== EnumAllyTypes.none) { allySubTypeName = EnumAllyTypes.nameForId(card.subType); if (card.tags.indexOf(allySubTypeName) === -1) { card.tags.push(allySubTypeName); } } return card; } Meteor.methods({ // create a new card, server side createCard: function (values) { var card, existingCard; var cardSet; check(values, Object); if ( ! Crystal.isAdmin()) { throw new Meteor.Error(403, 'Only an admin user can do that'); } // pick out the white listed keys card = pickCardValues(values); // check duplicates references existingCard = Cards.findOne({ cardSet: card.cardSet, rankInCardSet: card.rankInCardSet }); if (existingCard) { throw new Meteor.Error(403, 'A card with the same set and rank already exists (_id: ' + existingCard._id + ')'); } // find the card set cardSet = CardSets.findOne(card.cardSet); if (! cardSet) { throw new Meteor.Error(403, "This card set doesn't exist : " + card.cardSet); } // set the _id : we use the card reference (se001, ex042...) card._id = Crystal.cardRef(card.cardSet, card.rankInCardSet); // set the rank (useful to sort the cards) card.rank = (cardSet.rank * 1000) + card.rankInCardSet; // insert the card, and return the _id of this new card return Cards.insert(card); }, updateCard: function (cardId, values) { var card; check(cardId, String); check(values, Object); if ( ! Crystal.isAdmin()) { throw new Meteor.Error(403, 'Only an admin user can do that'); } // pick out the white listed keys card = pickCardValues(values); delete card.cardSet; delete card.rankInCardSet; // update the card return Cards.update({ _id: cardId }, { $set: card }); } });
true
6ddd47b3a208baf074551bd63d92840fa1521498
JavaScript
coltonw/AcidPlatformer
/src/js/physics/runPhysics.js
UTF-8
5,608
2.78125
3
[]
no_license
(function(acidgame, $, undefined) { /** * Physics engine will handle distances in blocks and times in seconds (rather than pixels and frames) This will allow easy adjustment later. */ var pixelsPerBlock = 40 var framesPerSecond = 40; acidgame.physics = acidgame.physics || {}; var character; var physicsObjects = []; var groundHeight; var canvasWidth; var canvasHeight; acidgame.physics.init = function(characterSprite, ground, width, height, pxlsPerBlck, fps) { groundHeight = ground; canvasWidth = width; canvasHeight = height; pixelsPerBlock = pxlsPerBlck; framesPerSecond = fps; character = acidgame.physics.addRectangleObject(characterSprite, 'character', 1, 0); acidgame.physics.setVelocity(character, 0, 0); acidgame.physics.setAcceleration(character, 0, 0); character.directionMultiplier = 1; }; acidgame.physics.setCanvasDimensions = function(width, height) { canvasWidth = width; canvasHeight = height; }; acidgame.physics.addRectangleObject = function(sprite, hitboxName, x, y) { x = x || 0; y = y || 0; var width = ((hitboxName) ? acidgame.hitbox.getWidth(hitboxName) : sprite.width) / pixelsPerBlock; var height = ((hitboxName) ? acidgame.hitbox.getHeight(hitboxName) : sprite.height) / pixelsPerBlock; var physicsObject = { sprite: sprite, hitbox: hitboxName, rectangle: new createjs.Rectangle(x, y, width, height) }; if (hitboxName) { physicsObject.node = acidgame.xSortQueue.add(physicsObject); } acidgame.physics.setSprite(physicsObject); return physicsObject; }; acidgame.physics.run = function() { var current = acidgame.xSortQueue.getHead() var iter var rightX var reSortQueue = [] var i; while (current !== null) { // Check ground collision if (current.val.isAirborne && current.val.rectangle.y < 0) { current.val.isAirborne = false; current.val.rectangle.y = 0; current.val.acceleration[1] = 0; current.val.velocity[1] = 0; if (current.val.onGroundCollision) { // perhaps make some sort of event handler if more of these are added. current.val.onGroundCollision(); } } // Check other collisions iter = current.next; rightX = current.val.rectangle.x + current.val.rectangle.width; while (iter !== null && iter.val.rectangle.x < rightX) { // TODO: Add in velocity vectors to prevent fast moving objects going through each other if (current.val.rectangle.y < iter.val.rectangle.y + iter.val.rectangle.height && current.val.rectangle.y + current.val.rectangle.height > iter.val.rectangle.y) { // TODO: account for multiple objects colliding with the same object collide(current.val, iter.val); } iter = iter.next; } doPhysics(current.val, reSortQueue); current = current.next; } // Add back in all the nodes that moved for (i = 0; i < reSortQueue.length; i++) { acidgame.xSortQueue.reAdd(reSortQueue[i], reSortQueue[i].prev); } }; acidgame.physics.getCharacter = function() { return character; }; function collide(obj1, obj2) { // TODO } function doPhysics(physicsObject, reSortQueue) { if (physicsObject.velocity) { if (physicsObject.acceleration) { vec2.add(physicsObject.velocity, physicsObject.velocity, physicsObject.acceleration); } physicsObject.rectangle.x = physicsObject.rectangle.x + physicsObject.velocity[0]; physicsObject.rectangle.y = physicsObject.rectangle.y + physicsObject.velocity[1]; if (physicsObject.velocity[0] !== 0) { // TODO: prevent repeating physics on this node (queue reSorts for afterwards?) acidgame.xSortQueue.remove(physicsObject.node); reSortQueue = reSortQueue || []; reSortQueue.push(physicsObject.node); } } acidgame.physics.setSprite(physicsObject); } acidgame.physics.setVelocity = function(physicsObject, x, y) { physicsObject.velocity = vec2.fromValues(x / framesPerSecond, y / framesPerSecond); }; acidgame.physics.setXVelocity = function(physicsObject, x) { physicsObject.velocity[0] = x / framesPerSecond; }; acidgame.physics.setYVelocity = function(physicsObject, y) { physicsObject.velocity[1] = y / framesPerSecond; }; acidgame.physics.setAcceleration = function(physicsObject, x, y) { physicsObject.acceleration = vec2.fromValues(x / framesPerSecond / framesPerSecond, y / framesPerSecond / framesPerSecond); }; acidgame.physics.setXAcceleration = function(physicsObject, x) { physicsObject.acceleration[0] = x / framesPerSecond / framesPerSecond; }; acidgame.physics.setYAcceleration = function(physicsObject, y) { physicsObject.acceleration[1] = y / framesPerSecond / framesPerSecond; }; acidgame.physics.setAirborne = function(physicsObject, air) { physicsObject.isAirborne = air; }; acidgame.physics.setSprite = function(physicsObject) { physicsObject.sprite.x = physicsObject.rectangle.x * pixelsPerBlock + ((physicsObject.directionMultiplier && physicsObject.directionMultiplier < 0) ? physicsObject.sprite.getBounds().width : 0); physicsObject.sprite.y = canvasHeight - groundHeight - physicsObject.rectangle.y * pixelsPerBlock - physicsObject.rectangle.height * pixelsPerBlock; if (physicsObject.hitbox) { acidgame.hitbox.adjust(physicsObject.hitbox, physicsObject.sprite); } }; }(window.acidgame = window.acidgame || {}, jQuery));
true
4543cd7362d98a0b9e939a189884a13c066bcfb7
JavaScript
it-teaching-abo-akademi/csdewas-project-2-ottolindfors
/my-react-app/src/AddStockModal.js
UTF-8
5,271
2.859375
3
[]
no_license
import React from "react"; import {urlBuilderDate} from "./api"; export class AddStockModal extends React.Component { constructor(props) { super(props); this.state = { stockSymbol: "", purchaseDate: "", shares: "", hasErrors: false, errorMessage: "", loading: false, }; this.handleOnsubmit = this.handleOnsubmit.bind(this); this.handleOnChange = this.handleOnChange.bind(this); this.handleCancel = this.handleCancel.bind(this); } handleOnsubmit(event) { event.preventDefault(); const stockSymbol = this.state.stockSymbol; const purchaseDate = this.state.purchaseDate; const shares = this.state.shares; let purchasePrice = null; this.setState( { loading: true }, () => { // Fetch purchase price from API let puchasePriceFetcher = this.puchasePriceFetcher(stockSymbol, purchaseDate); // Returns a promise puchasePriceFetcher.then(fetchedPrice => { if (!this.state.hasErrors) { purchasePrice = fetchedPrice; this.props.onAdd(stockSymbol, purchaseDate, purchasePrice, shares); } this.setState({ hasErrors: false, loading: false, }); }) // Errors are already caught in purchasePriceFetcher so no need to do it here } ); } handleOnChange(event) { if (event.target.name === "stockSymbol") { this.setState({ stockSymbol: event.target.value.toUpperCase() }); } if (event.target.name === "purchaseDate") { this.setState({ purchaseDate: event.target.value }) } if (event.target.name === "shares") { this.setState({ shares: event.target.value }) } } handleCancel() { // Reset state this.setState({ stockSymbol: "", purchaseDate: "", stockError: "", dateError: "", }); // Action this.props.onCancel(); } render() { if (!this.props.show) { return null; } if (this.state.loading) { // Loading while fetching data return ( <p>Loading ...</p> ) } return ( <div> <h3>Add stock</h3> <form onSubmit={this.handleOnsubmit}> <label> Stock symbol <input type="text" name="stockSymbol" value={this.state.stockSymbol} onChange={this.handleOnChange} required/> </label> <label> Date of purchase <input type="date" name="purchaseDate" value={this.state.purchaseDate} onChange={this.handleOnChange} required/> </label> <label> Number of shares <input type="number" min="1" name="shares" value={this.state.shares} onChange={this.handleOnChange} required/> </label> <input type="submit" value="Add"/> </form> <p>{this.state.errorMessage}</p> <button onClick={this.handleCancel}>Cancel</button> </div> ) } puchasePriceFetcher(stockSymbol, isoDate) { // isoDate should be of format YYYY-MM-DD as returned by the <input type="date /> const yyyymmdd = isoDate.replace(/-/g, ""); const apiUrl = urlBuilderDate(stockSymbol, yyyymmdd); return fetch(apiUrl) .then(response => { // "Parse" json if (response.ok) { // API returns an empty json if the stock symbol is valid but there is no available data. return response.json() // returns 'undefined' if json from api is empty } if (response.status === 404) { // API throws 404 if stock symbol is unknown throw new Error("Unknown stock symbol"); } else { // All other errors throw new Error("Error while fetching from api ..."); } }) .then(jsonData => { // The API returns an empty json if the stock symbol is valid but there is no available data. if (jsonData.length > 0) { return jsonData[0].close; } else { throw new Error("No available stock data for that date. Either the exchange was closed that day (e.g. weekend) or the date is too far in the past."); } }) .catch(error => { // Handle errors console.log("==>", error.message); this.setState({ hasErrors: true, errorMessage : error.message }); }) } }
true
b4505568c9a2b8a9308b904b282c3c0592bbc34a
JavaScript
dominic-taylor/frontend-nanodegree-resume
/js/resumeBuilder.js
UTF-8
5,453
2.546875
3
[]
no_license
var name = 'Dominic Taylor'; var role = 'Web Dev'; var bio = { 'name': 'Dominic', 'role': 'Web Dev', 'contact': { 'email': '[email protected]', 'mobile': '123654', 'location': 'Wellington, NZ' }, 'bioPic': 'images/fry.jpg', 'welcomeMessage': 'SUP!', 'skills': ['eating', 'jumping', 'skipping', 'speaking quietly'] } var formattedName= HTMLheaderName.replace("%data%",name); var formattedRole= HTMLheaderRole.replace("%data%", role); var formattedPic= HTMLbioPic.replace('%data%',bio.bioPic) var formattedEmail = HTMLemail.replace('%data%', bio.contact.email); var formattedMobile = HTMLmobile.replace('%data%', bio.contact.mobile); var formattedLocation = HTMLlocation.replace('%data%', bio.contact.location); var formattedMessage = HTMLwelcomeMsg.replace('%data%', bio.welcomeMessage); $("#header").prepend(formattedName, formattedRole); $('#header').append(formattedPic, formattedMessage); $("#topContacts").append(formattedMobile, formattedEmail, formattedLocation); $("#header").append(HTMLskillsStart); for (skill in bio.skills) { var formattedSkills = HTMLskills.replace("%data%", bio.skills[skill]); $("#skills").append(formattedSkills); }; var work = { 'jobs': [ { 'employer': 'Isentia', "title": "Broadcast Monitor", "location": "Wellington, New Zealand", "years": "July 2015 - Present", "description":"Monitor and write summeries of radio broadcasts and play\ table tennis when the cricket is on." }, { "employer": "Mario Bros Circus", "title": "Lion Tamer", "location": "Mushroom Kingdom, Under the Sea", "years": "Aug 2010 - Jan 2015", "description":"The title says it all." } ] }; var education ={ "schools": [ { "name": "Victoria University", "degree": "BA in Philosophy", "years": "2007-11", "location": "Wellington, NZ" }, { "name": "Wairoa College", "degree": "University Enterance", "years": "2002-2007", "location": "Wairoa, NZ" } ], "onlineCourse":[ {"title":"HTML and CSS", "school": "Udacity", "dates": "December 2015", "url": "https://www.udacity.com/" } ] }; var projects = { 'list': [ { 'title': 'Rocket Fryer', "dates": 'August 1993 -1999', 'description': 'Fried rockets semi regularly \ but could never beat the record. ', 'projectImage': 'images/fry.jpg' } ] }; function displayProjects() { for (project in projects.list) { $("#projects").append(HTMLprojectStart); var formattedProjectTitle = HTMLprojectTitle.replace("%data%", projects.list[project].title); var formattedProjectDates = HTMLprojectDates.replace("%data%", projects.list[project].dates); var formattedProjectDescription = HTMLprojectDescription.replace("%data%", projects.list[project].description); var formattedProjectImage = HTMLprojectImage.replace("%data%", projects.list[project].projectImage); $('.project-entry:last').append(formattedProjectTitle, formattedProjectDates, formattedProjectDescription, formattedProjectImage); } } displayProjects(); function displayWork () { for (job in work.jobs) { $("#workExperience").append(HTMLworkStart); var formattedEmployer = HTMLworkEmployer.replace('%data%', work.jobs[job].employer); var formattedTitle = HTMLworkTitle.replace('%data%', work.jobs[job].title); var formattedEmployerTitle = formattedEmployer + formattedTitle; var formattedworklocation = HTMLworkLocation.replace('%data%', work.jobs[job].location); $(".work-entry:last").append(formattedEmployerTitle); $(".work-entry:last").append(formattedworklocation); var formattedDates = HTMLworkDates.replace('%data%', work.jobs[job].years); $(".work-entry:last").append(formattedDates); var formattedDescription = HTMLworkDescription.replace('%data%',work.jobs[job].description) $(".work-entry:last").append(formattedDescription); } } displayWork(); function displayEducation () { for (school in education.schools) { $('#education').append(HTMLschoolStart); formattedSchoolName = HTMLschoolName.replace('%data%', education.schools[school].name); formattedSchoolLocation = HTMLschoolLocation.replace("%data%", education.schools[school].location); $(".education-entry:last").append(formattedSchoolLocation); formattedSchoolDates = HTMLschoolDates.replace('%data%', education.schools[school].years); formattedSchoolDegree = HTMLschoolDegree.replace('%data%', education.schools[school].degree); $('.education-entry:last').append(formattedSchoolName, formattedSchoolDates, formattedSchoolDegree); } } displayEducation(); $('.education-entry:last').append(HTMLonlineClasses); for (online in education.onlineCourse) { var formattedonlineTitle = HTMLonlineTitle.replace('%data%', education.onlineCourse[online].title); $('.education-entry:last').append(); var formattedonlineSchool = HTMLonlineSchool.replace('%data%', education.onlineCourse[online].school); $('.education-entry:last').append(); var formattedonlineDates = HTMLonlineDates.replace('%data%', education.onlineCourse[online].dates); $('.education-entry:last').append(); var formattedonlineURL = HTMLonlineURL.replace('%data%', education.onlineCourse[online].url); $('.education-entry:last').append(formattedonlineTitle,formattedonlineSchool, formattedonlineDates,formattedonlineURL); };
true
9fc739a297ab21f1c02c90925bc40c0914c4a58f
JavaScript
MalinduPabasara/Car_Rental_Project
/Car_Rent_FrontEnd/assets/js/payment.js
UTF-8
2,662
3.046875
3
[]
no_license
let cusCardNumRegEx = /^4[0-9]{12}(?:[0-9]{3})?$/; $('#cardnum').on('keyup', function (event) { if (event.key == 'Enter') { $('#expiry').focus(); } let inputID = $('#cardnum').val(); if (cusCardNumRegEx.test(inputID)) { $('#cardnum').css('border', '2px solid green'); $('#lblCardNumber').text(''); $('#lblCardNumber').css({ 'color': 'green', 'font-size': '12px' }); } else { $('#cardnum').css('border', '2px solid red'); $('#lblCardNumber').text('Please input correct Card Number.'); $('#lblCardNumber').css({ 'color': 'red', 'font-size': '12px' }); } }); let cusCardCVSRegEx = /^[0-9]{1,3}$/; $('#cvs').on('keyup', function (event) { if (event.key == 'Enter') { $('#name').focus(); } let inputID = $('#cvs').val(); if (cusCardCVSRegEx.test(inputID)) { $('#cvs').css('border', '2px solid green'); $('#lblcvs').text(''); $('#lblcvs').css({ 'color': 'green', 'font-size': '12px' }); } else { $('#cvs').css('border', '2px solid red'); $('#lblcvs').text('Please input correct CVS (only 3 digit).'); $('#lblcvs').css({ 'color': 'red', 'font-size': '12px' }); } }); let cusNameRegEx = /^[a-zA-Z ]+$/; $('#name').on('keyup', function (event) { if (event.key == 'Enter') { // $('#txtaddress').focus(); } let inputID = $('#name').val(); if (cusNameRegEx.test(inputID)) { $('#name').css('border', '2px solid green'); $('#lblname').text(''); $('#lblname').css({ 'color': 'green', 'font-size': '12px' }); } else { $('#name').css('border', '2px solid red'); $('#lblname').text('Type only letters'); $('#lblname').css({ 'color': 'red', 'font-size': '12px' }); } }); let cusDOBRegEx = /^[0-9]{4}$/; $('#txtdob').on('keyup', function (event) { if (event.key == 'Enter') { $('#txtcontactNo').focus(); } let inputID = $('#txtdob').val(); if (cusDOBRegEx.test(inputID)) { $('#txtdob').css('border', '2px solid green'); $('#lbldob').text(''); $('#lbldob').css({ 'color': 'green', 'font-size': '12px' }); } else { $('#txtdob').css('border', '2px solid red'); $('#lbldob').text('Wrong input. Enter valid birthday (10/10/1990)'); $('#lbldob').css({ 'color': 'red', 'font-size': '12px' }); } });
true
4b1a3f68abc61e8cb7a40b6fc5620660b975dd07
JavaScript
Peilin-D/web-server
/static/src/register.js
UTF-8
925
2.8125
3
[]
no_license
$("#register").click(e => { var registerInfo ={ "name":document.getElementById("full-name").value, "username":document.getElementById("user-name").value, "password":document.getElementById("pass-word").value, "department":document.getElementById("department").value } if(registerInfo.username.length < 2) { alert("username must have at least 2 characters"); return; } if(registerInfo.password.length < 6) { alert("password must have at least 6 characters"); return; } $.ajax({ url: "/register", method: 'POST', data: registerInfo }).done(() => { window.localStorage.username=registerInfo.username window.location.href = "/login" }).fail(err => { if (err.status === 409) { alert(err.responseText) window.location.reload() } }) }) $("#cancel").click(e => { console.log('clicked', window.location.href) window.location.href = "/login" })
true
e3a9a0278d948a426c8bdde7e2c71917f100a050
JavaScript
pristas-peter/react-app
/packages/react-intl-extract-webpack-plugin/babel/print-icu-message.js
UTF-8
2,091
2.65625
3
[ "MIT" ]
permissive
/* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ const {parse} = require('intl-messageformat-parser'); const ESCAPED_CHARS = { '\\' : '\\\\', '\\#': '\\#', '{' : '\\{', '}' : '\\}', }; const ESAPE_CHARS_REGEXP = /\\#|[{}\\]/g; module.exports = function (message) { let ast = parse(message); return printICUMessage(ast); } function printICUMessage(ast) { let printedNodes = ast.elements.map((node) => { if (node.type === 'messageTextElement') { return printMessageTextASTNode(node); } if (!node.format) { return `{${node.id}}`; } switch (getArgumentType(node.format)) { case 'number': case 'date': case 'time': return printSimpleFormatASTNode(node); case 'plural': case 'selectordinal': case 'select': return printOptionalFormatASTNode(node); } }); return printedNodes.join(''); } function getArgumentType(format) { const {type, ordinal} = format; // Special-case ordinal plurals to use `selectordinal` instead of `plural`. if (type === 'pluralFormat' && ordinal) { return 'selectordinal'; } return type.replace(/Format$/, '').toLowerCase(); } function printMessageTextASTNode({value}) { return value.replace(ESAPE_CHARS_REGEXP, (char) => ESCAPED_CHARS[char]); } function printSimpleFormatASTNode({id, format}) { let argumentType = getArgumentType(format); let style = format.style ? `, ${format.style}` : ''; return `{${id}, ${argumentType}${style}}`; } function printOptionalFormatASTNode({id, format}) { let argumentType = getArgumentType(format); let offset = format.offset ? `, offset:${format.offset}` : ''; let options = format.options.map((option) => { let optionValue = printICUMessage(option.value); return ` ${option.selector} {${optionValue}}`; }); return `{${id}, ${argumentType}${offset},${options.join('')}}`; }
true
299ec5e98522b211fd34c255863931a2b83e5f1f
JavaScript
gnehzr/tnoodle
/jracer/src_tnoodle_resources/tnoodleServerHandler/jracer/nowjs/now.js
UTF-8
2,326
2.75
3
[]
no_license
var now = {}; (function() { now.core = {}; now.core.clientId = 4242; now.core.user = null; var loaded = false; window.addEventListener('load', function() { loaded = true; for(var i = 0; i < readyCallbacks.length; i++) { readyCallbacks[i](); } }, false); var readyCallbacks = []; now.ready = function(readyCallback_) { readyCallbacks.push(readyCallback_); if(loaded) { readyCallback_(); } }; now.ping = function(callback) { callback(); }; now.joinChannel = function(desiredNick, desiredChannelName, callback) { var error = null; var clientId_user = {}; now.core.user = { nick: desiredNick, clientId: now.core.clientId, joinTime: new Date().getTime(), channel: { channelName: desiredChannelName }, admin: true }; clientId_user[now.core.user.clientId] = now.core.user; now.handleChannelMembers(clientId_user); callback(error, desiredNick, desiredChannelName); }; // The following is copied straight from noderacer.js function authenticate_authorize(func, authorize) { return function() { // The last argument to each function must be a callback var args = []; for(var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } var callback = args[args.length-1]; /* var user = users.getUserByClientId(this.user.clientId); if(!user) { callback("User for clientId " + this.user.clientId + " not found"); return; } if(authorize && !user.admin) { callback("User " + user.nick + " not admin"); return; } */ var user = now.core.user; args.unshift(user); func.apply(this, args); }; } function auth(func) { return authenticate_authorize(func, false); } function auth_admin(func) { return authenticate_authorize(func, true); } now.sendGameInfo = auth_admin(function(user, gameInfo, callback) { now.handleGameInfo(gameInfo); }); now.sendRandomState = auth_admin(function(user, randomState, callback) { now.handleRandomState(randomState); }); now.sendMoveState = auth(function(user, moveState, callback) { now.handleMoveState(user, moveState); }); now.sendMessage = auth(function(user, msg) { // We don't simulate the node server here, because this gives the user // a visual indicator that they're not connected to the server. }); })();
true
267cb4582c7d4af0ba280291d907e0508e228431
JavaScript
nikhilvibhav/learnyounode-solutions
/modular-filter.js
UTF-8
378
2.75
3
[]
no_license
var fs = require('fs'); var path = require('path'); function filterFilesByExt(dir, filterString, callback) { fs.readdir(dir, function(err, listOfFiles) { if (err) return callback(err); listOfFiles = listOfFiles.filter(function (file) { return path.extname(file) === "." + filterString; }); callback(null, listOfFiles); }); } module.exports = filterFilesByExt;
true
a3c4b42173e979668e3bf596f1571520bb194b1e
JavaScript
baked-dev/cluster-electron
/index.js
UTF-8
6,851
2.671875
3
[]
no_license
const cluster = require('cluster'); const numCPUs = require('os').cpus().length; class Logger { log (string, processID = process.pid) { console.log(`${new Date().toISOString()} | ${processID} | ${string}`) } } const logger = new Logger; //custom emitter to wrap the emit stuff into functions if (cluster.isMaster) { const Emitter = require('events'); class CustomInterface extends Emitter { constructor () { super(); this.last_start_all = 0; } add_task (data) { logger.log('adding task', 'MASTER') //find worker that has the least amout of tasks let lowest_key = get_best_worker(); //send task start message to worker console.log(data); worker_message(lowest_key, {action:'new_task', payload: data}); workersmap[lowest_key].tasks_amount++; workersmap[lowest_key].tasks.push(data); //return this easy method chaning return this; } edit_task (data) { //find out which worker handles the task const workerID = find_task(data.id); if (workerID !== false) { worker_message(workerID, {action:'edit_task', payload: edit_task(workerID, data)}); } return this; } start_task (taskID) { const workerID = find_task(taskID); if (workerID !== false) { worker_message(workerID, {action:'start_task', payload: taskID}); } return this; } start_all (force = false) { if (new Date().getTime() - this.last_start_all < 2000 || force) { logger.log('cooldown on start all', 'MASTER'); } else { //holy shit i made this and it worked first try // note to my past self: this is ugly Object.keys(workersmap).map(e => workersmap[e].tasks.map(f => (!f.running?f.id:false))).map(e => e.map(f => f!==false?this.start_task(f):false)); this.last_start_all = new Date().getTime(); } return this; } new_worker () { new_worker(); return this; } init_workers () { init_workers() return this; } } const worker_message = send_message_to_worker = (worker, message) => { workersmap[worker].worker.send(message); } const get_best_worker = find_worker_with_lowest_tasks_amount = () => { let lowest_val = false; let lowest_key = false; for (let key of Object.keys(workersmap)) { if (lowest_val === false || workersmap[key].tasks_amount < lowest_val) { lowest_val = workersmap[key].tasks_amount; lowest_key = key; } } return lowest_key; } const find_task = get_worker_id_that_handles_task = (taskID) => { for (let key of Object.keys(workersmap)) { if (workersmap[key].tasks.map(e => e.id).includes(taskID)) return key; } return null; } const new_worker = register_new_worker_and_event_listeners = () => { const id = workersID++; workersmap[id] = { worker: cluster.fork(), tasks_amount: 0, tasks: [], pid: null, }; workersmap[id].worker.on('message', ({ action, payload }) => { if (action === 'update_task') { Interface.emit('update_task', {worker:id, data: payload}); //imtercept message to set that task to running const { status } = payload; //cant destructure id because that would interfere with the workersID in this context if (status === 'started' || status === 'stopped') { edit_task(id, {id:payload.id, running: (status === 'started'?true:false)}); } } else if (action === 'ready') { workersmap[id].pid = payload; } }); return id; } const init_workers = initialise_one_worker_per_cpu_code = () => { for (let core = 0; core < numCPUs; core++) { new_worker(); } } const restart_worker = restart_worker_after_death_by_pid = (worker) => { //find workersID for (const key of Object.keys(workersmap)) { if (workersmap[key].pid === worker.pid) { const { tasks } = workersmap[key]; //start new worker new_worker(); //re-distribute dead tasks for (const task of tasks) { Interface.add_task(task); } break; } } } const edit_task = edit_task_in_workersmap = (workerID, data) => { //find task index in array for (let i in workersmap[workerID].tasks) { if (workersmap[workerID].tasks[i].id === data.id) { //merge objects instead of completely overwriting, allows editing by just sending {id:taskID, running:true} for example workersmap[workerID].tasks[i] = Object.assign(workersmap[workerID].tasks[i], data); return workersmap[workerID].tasks[i] } } } const randInt = random_integer = (min, max) => { return Math.floor(Math.random()*(max - min)) + min; } //global reference to the Interface that will be exported let workersmap = {}, workersID = 0, Interface = new CustomInterface(); logger.log('Master running', 'MASTER'); cluster.on('death', restart_worker); module.exports = { Interface, isMaster: cluster.isMaster }; } else { // trying to make the task to run dynamic. const TaskTypes = {}; logger.log('Worker running and waiting for tasks'); const new_task = register_new_task = (data) => { // dont want to pass the entire task class down to itself console.log(data.payload) const task = TaskTypes[data.payload.type]; taskmap[data.payload.id] = new task(data.payload); } let taskmap = {}; process.send({action:'ready', payload: process.pid}); process.on('message', (data) => { if (data.action === 'new_task') { logger.log('new task: ' + JSON.stringify(data.payload)); new_task(data); } else if (data.action === 'start_task') { taskmap[data.payload].start(); } else if (data.action === 'edit_task') { logger.log('edit task: ' + JSON.stringify(data.payload)); } }) module.exports = { Interface: false, isMaster: cluster.isMaster, TaskTypes }; } //lmao
true
3047aa3b45218e82606cba2bbfda6274cb25fa4a
JavaScript
sanket0896/DSA-Practice
/Scaler/046_Stacks-2/A4-Maximum_Rectangle.js
UTF-8
1,790
4.15625
4
[]
no_license
/** * Maximum Rectangle Given a 2D binary matrix of integers A containing 0's and 1's of size N x M. Find the largest rectangle containing only 1's and return its area. Note: Rows are numbered from top to bottom and columns are numbered from left to right. Input Format The only argument given is the integer matrix A. Output Format Return the area of the largest rectangle containing only 1's. Constraints 1 <= N, M <= 1000 0 <= A[i] <= 1 For Example Input 1: A = [ [0, 0, 1] [0, 1, 1] [1, 1, 1] ] Output 1: 4 Input 2: A = [ [0, 1, 0, 1] [1, 0, 1, 0] ] Output 2: 1 */ function solve(A) { let n = A.length; let m = A[0].length; let ans = -Infinity; let hist = new Array(m).fill(0); for(let i = 0; i < n; ++i){ for(let j = 0; j < m; ++j){ hist[j] = A[i][j] ? hist[j] + 1 : 0; } ans = Math.max(ans, maxHistArea(hist)); } return ans; function maxHistArea(hist){ let stack = []; let max = -Infinity; for(let i = 0; i < hist.length; ++i){ while (stack.length && hist[i] <= hist[stack[stack.length - 1]]) { let el = stack.pop(); let r = i; let l = !stack.length ? -1 : stack[stack.length - 1]; max = Math.max(max, ((r-el) + (el - l - 1)) * hist[el]); } stack.push(i); } while (stack.length) { let el = stack.pop(); let r = hist.length; let l = !stack.length ? -1 : stack[stack.length - 1]; max = Math.max(max, ((r-el) + (el - l - 1)) * hist[el]); } return max; } } A = [ [0, 1, 0, 1], [1, 0, 1, 0] , ] console.log(solve(A));
true
c6a23965172aeaa3859d2a8ecf53572174f5c4c1
JavaScript
shhuang123/polling-app
/src/components/Display.js
UTF-8
1,582
3
3
[]
no_license
import React from 'react'; import Button from './Button' class Form extends React.Component { constructor(props){ super(props) this.state = { choices: ['Sushi', 'Burger'], addition: '', count: 0 } this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({ addition: event.target.value }) } handleSubmit(event) { event.preventDefault(); this.setState(prevState => ({ choices: [...prevState.choices, this.state.addition], addition: '' })) } // constructor(props) { // super(props); // this.state = { // count: 0, // } // // this.increment = this.increment.bind(this) // } // // increment() { // this.setState({ // count: this.state.count + 1 // }); // }; render () { const { choices } = this.state console.log(choices); let button = choices.map((i) => <Button key={i} name={i} />) return ( <div> <div className="question">What is your favorite food?</div> <br /> {button} <form onSubmit={this.handleSubmit} className="left"> <p> Add more choices </p> <p> <input className="field" type='text' placeholder='i.e. Pad Thai!' value={this.state.addition} onChange={this.handleChange} /> </p> <input type="submit" value="submit" className="field-button" /> </form> </div> ) } } export default Form;
true
2cd6c649c2831a6c12daa16fc3630737201c11b0
JavaScript
musichopin/InfiniteSkills_Learning-JavaScript-Programming
/Chapter 13 Form Handling/api-forms/scripts/custom.js
UTF-8
2,963
3.640625
4
[]
no_license
// custom controls // DOM nodes var form = { register: document.getElementById("register"), email: document.getElementById("email"), pass1: document.getElementById("pass1"), pass2: document.getElementById("pass2"), strength: document.getElementById("strength") // we added a reference to span node }; // form submit form.register.addEventListener( "submit", CheckForm ); // check email field form.email.addEventListener( "change", function(e) { if (e.target.value == "") alert("You forgot the email!"); } ); // stop space character form.pass1.addEventListener( "keypress", NoSpaces ); form.pass2.addEventListener( "keypress", NoSpaces ); // password strength form.pass1.addEventListener( "keyup", PasswordStrength ); // keyup event is fired after a keypress has been received // and the characters actually appeared on the field // stop spaces being entered function NoSpaces(e) { if (e.charCode == 32) e.preventDefault(); } // custom control is one which isnt provided by html // check password strength var strtext = ["weak", "average", "strong"]; var strcolor = ["#c00", "#f80", "#080"]; // we define text and color for our password strength indicator function PasswordStrength(e) { var pass = form.pass1.value; // we could have written a for loop which went through every // character and detected what they are, but this method // with regex is slightly faster // count uppercase: match no of uppercase chars // this command returns an array containing all the uppercase letters var uc = pass.match(/[A-Z]/g); // g:global match uc = (uc && uc.length || 0); // if we have an array we get its length or we return zero if there is empty array // count numbers var nm = pass.match(/\d/g); nm = (nm && nm.length || 0); // count symbols var nw = pass.match(/\W/g); // W: not a number, digit or underscore nw = (nw && nw.length || 0); // determine strength based on its length awarding bonus points // such as upper case letters, numbers and symbols var s = pass.length + uc + (nm * 2) + (nw * 3); s = Math.min(Math.floor(s / 10), 2); // anything under 10 is weak, 10-20 average and 20+ strong // we convert the result into 0-2 range by dividing 10 // since we might have more than 2, we take minimum // we then use the result as an index for our strength node, with text and color arrays form.strength.textContent = strtext[s]; // writes text for span node form.strength.style.color = strcolor[s]; } // form submit validation var reEmail = /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/; function CheckForm(e) { var msg = ""; // check email if (!reEmail.test(form.email.value)) { msg += "\nyour email address"; } // check passwords if (form.pass1.value == "" || form.pass1.value != form.pass2.value) { msg += "\nyour passwords"; } // complete message if (msg != "") { msg = "Please check:"+msg; } else { msg = "Form is valid!\nSubmitting..."; } alert(msg); e.preventDefault(); }
true
d67a4e6a783b3217e97d649571d0ee78a59fe471
JavaScript
jjwjack/baidu_ife
/task-16/main.js
UTF-8
3,091
3.21875
3
[]
no_license
/** * aqiData,存储用户输入的空气指数数据 * 示例格式: * aqiData = { * "北京": 90, * "上海": 40 * }; */ var aqiData = {}; var btn_add = document.getElementById("btn_add"); /** * 从用户输入中获取数据,向aqiData中增加一条数据 * 然后渲染aqi-list列表,增加新增的数据 */ function addAqiData() { var input_city = document.getElementById("aqi-city-input").value; var input_value = document.getElementById("aqi-value-input").value; //trim方法 input_city = input_city.replace(/(^\s*)|(\s*$)/g,""); input_value = input_value.replace(/(^\s*)|(\s*$)/g,""); if (!input_city.match(/(^[a-zA-Z\u4e00-\u9fa5]+$)/)) { alert("城市名必须为中英文字符"); return; } if (!input_value.match(/^[0-9]+$/)) { alert("空气质量指数必须为整数"); return; } aqiData[input_city] = input_value; console.log(aqiData); return aqiData; } /** * 渲染aqi-table表格 */ function renderAqiList() { var aqi_table = document.getElementById("aqi-table"); var aqi_th = document.createElement("tr"); //点击添加前判断是否有tr,如果有就清空table if (aqi_table.getElementsByTagName("tr")) { aqi_table.innerHTML = null; } // <td>城市</td><td>空气质量</td><td>操作</td> aqi_th.innerHTML = "<th>城市</th><th>空气质量</th><th>操作</th>"; aqi_table.appendChild(aqi_th); //用for in遍历json对象 for (var key in aqiData){ // console.log(key); // console.log(aqiData[key]); var aqi_tr = document.createElement("tr"); // <td>北京</td><td>90</td><td><button>删除</button></td> aqi_tr.innerHTML = "<td>"+key+"</td><td>"+aqiData[key]+"</td><td><button>删除</button></td>"; aqi_table.appendChild(aqi_tr); } } function check_input(){ var input_city = document.getElementById("aqi-city-input").value; var input_value = document.getElementById("aqi-value-input").value; } /** * 点击add-btn时的处理逻辑 * 获取用户输入,更新数据,并进行页面呈现的更新 */ function addBtnHandle() { addAqiData(); renderAqiList(); } /** * 点击各个删除按钮的时候的处理逻辑 * 获取哪个城市数据被删,删除数据,更新表格显示 */ function delBtnHandle() { // do sth. } function init() { // 在这下面给add-btn绑定一个点击事件,点击时触发addBtnHandle函数 btn_add.onclick = function(){ addAqiData(); renderAqiList(); var aqi_table = document.getElementById("aqi-table"); var btns = aqi_table.getElementsByTagName("button"); for (var i = 0; i < btns.length; i++) { btns[i].onclick = function(){ var del_city = this.parentNode.parentNode.firstChild.innerHTML; //删除json中的城市数据 delete aqiData[del_city]; //先隐藏这个删除的行,等点击添加时,会清除删掉的城市 this.parentNode.parentNode.style.display = "none"; }; } }; // 想办法给aqi-table中的所有删除按钮绑定事件,触发delBtnHandle函数 } init();
true
2498e021ad5e149d20d70241d2990be9eae7385f
JavaScript
mohammadalmoqdad/bussmall
/js/results.js
UTF-8
484
2.515625
3
[]
no_license
// function renderSummary() { // imagesSection.removeEventListener('click', handleClickonProducts); // console.log('you selected 25 times already!!'); // var ulE1 = document.getElementById('finalResults'); // for (var i = 0; i < Products.all.length; i++) { // var liE = document.createElement('li'); // ulE1.appendChild(liE); // // liE.textContent = `${Goat.all[i].goatName} has ${Goat.all[i].clicks} clicks and ${Goat.all[i].views} views`; // }}
true
2d53ed50b33d9329f89efd443eeb1109bd41bd17
JavaScript
AkankshaShrimal/Nodejs-Practice
/Day3/app.js
UTF-8
3,200
3.125
3
[ "MIT" ]
permissive
const Joi = require('joi') // returns a class, joi package for validation const express = require('express'); //Importing dependencies const port = process.env.PORT || 3000; var app = express(); app.use(express.json()); var courses = [ // putting courses manually {id :1 ,name :'math'}, {id :2 ,name :'science'}] app.get('/courses',function(req,res){ // to handle a get request for url '/courses' res.send(courses); }); app.get('/courses/:id',(req,res)=>{ // get request with parameters let searchResult = courses.find(c => c.id == parseInt(req.params.id)); if(!searchResult) return res.status(404).send("no such course"); res.send(searchResult); }) app.post("/courses",(req,res)=>{ //simple post request (you can use chrome postman to execute them) const result = validateCourse(req.body); //validation using joi /* An alternate code to validate instead of joi if(!req.body.name || req.body.name.lemgth <3) {//400 error for bad request res.status(400).send("name is required for course"); return; } */ if(result.error) {//400 error for bad request return res.status(400).send(result.error.details[0].message); } const course = { id : courses.length + 1, name : req.body.name } courses.push(course); res.send(course); }) app.put("/courses/:id",(req,res)=>{ //put request for updating a given course // look up the course if not return 404 let searchResult = courses.find(c => c.id == parseInt(req.params.id)); if(!searchResult) return res.status(404).send("no such course"); //validate , if not proper return 400 bad request error const result = validateCourse(req.body); if(result.error) {//400 error for bad request return res.status(400).send(result.error.details[0].message); } //update searchResult.name = req.body.name; res.send(searchResult); }) app.delete("/courses/:id",(req,res)=>{ //look for the given course let searchResult = courses.find(c => c.id == parseInt(req.params.id)); if(!searchResult) return res.status(404).send("no such course"); //delete the course var index = courses.indexOf(searchResult); courses.splice(index,1); //return course res.send("deleted " + searchResult.name); }) function validateCourse(course) { const schema = { name : Joi.string().min(3).required() } return Joi.validate(course,schema); } app.listen(port,function(){ //starting a server at port console.log("server started at port " + port + "..."); });
true
8521a8e2d507bf657e814032825ed1bc1a30a780
JavaScript
tiarss/games-movie-app
/src/components/ViewGame.js
UTF-8
1,810
2.578125
3
[]
no_license
import { Box, Flex, Image, Heading, Text } from "@chakra-ui/react"; import axios from "axios"; import React, { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import Navbar from "./Navbar"; function ViewGame() { let { id } = useParams(); const [dataById, setDataById] = useState([]); useEffect(() => { const fetchData = async () => { const result = await axios.get( `https://backendexample.sanbersy.com/api/data-game/${id}` ); let data = result.data; //console.log(data) setDataById({ id: data.id, title: data.name, img: data.image_url, year: data.release, genre: data.genre, platform: data.platform, single: data.singlePlayer, multi: data.multiplayer, }); //console.log(result.data) }; fetchData(); }); const Mode = (single, multi) => { if (single === 1 && multi === 1) { return "Single Player & Multiplayer"; } else if (single === 1) { return "Single Player"; } else if (multi === 1) { return "Multiplayer"; } else { return "-"; } }; return ( <div> <Navbar /> <Flex mt="50px" p="50px" direction="column"> <Box> <Heading size="lg" mb="20px"> {dataById.title} </Heading> </Box> <Flex> <Image src={dataById.img} alt="movie" w="250px" /> <Flex direction="column" p="0 20px"> <Text>Genre : {dataById.genre}</Text> <Text>Platform : {dataById.platform}</Text> <Text>Release Year : {dataById.year}</Text> <Text>Mode : {Mode(dataById.single,dataById.multi)}</Text> </Flex> </Flex> </Flex> </div> ); } export default ViewGame;
true
60a6addad2a8cde81ab08029841aa2c811e04d24
JavaScript
PavelZankin/Intensive
/scripts/search/sj.search.controller.js
UTF-8
1,547
2.703125
3
[]
no_license
/* SuperJob */ sj.getLocalParams = function() { return { keyword: $('#specialty')[0].value, town: getArea() || 'Россия', currency: 'rub', payment_from: +($('.min')[0].innerHTML + '000') || 1000, count: $('#per_page')[0].value /2 || 50 }; } function sjParseDate(date) { var d = new Date(date*1000); return { year: d.getFullYear(), month: d.getMonth() + 1, day: d.getDate(), hour: d.getHours(), minute: d.getMinutes(), second: d.getSeconds() } } function sjSearch() { if (!sj.getLocalParams().keyword) return; sj('vacancies', null, function(response) { if (!response.objects.length) { if (!$('#list-of-results')[0].innerHTML.match(/По данному запросу ничего/)) { $('#list-of-results')[0].innerHTML += ` <h1> <br/> По данному запросу ничего не найдено. <br/> </h1> `; return; }; } var vacs = response.objects; vacs.forEach(function(vac){ if (!vac.payment_from || !vac.payment_to) { vac.payment_from = vac.payment_from || 'Не указано'; vac.payment_to = vac.payment_to || 'Не указано'; } var d = sjParseDate(vac.date_published); vac.date_published = d.day+'.'+d.month+'.'+d.year+' '+d.hour+':'+d.minute; vac.unixTimeFormat = +(new Date(d.year, d.month-1, d.day, d.hour, d.minute, d.second)); }); displayVacancies(vacs, 'sj'); }); }
true
d8d12b33f8991793f586717168d08164465e40d0
JavaScript
Katsiaryna31/My-projects
/JS/keksobooking/js/map.js
UTF-8
1,780
2.671875
3
[]
no_license
'use strict'; (function () { var MAIN_PIN_LOCATION_X = 570; var MAIN_PIN_LOCATION_Y = 375; var MAIN_PIN_WIDTH = 64; var MAIN_PIN_HEIGHT = 80; var MAP_TOP_SIDE = 130; var MAP_BOTTOM_SIDE = 630; var MAP_LEFT_LIMIT = 0; var mainPinCenterX = MAIN_PIN_LOCATION_X + MAIN_PIN_WIDTH / 2; var mainPinCenterY = MAIN_PIN_LOCATION_Y + MAIN_PIN_HEIGHT; var mainPinPositionFirst = mainPinCenterX + ',' + mainPinCenterY; var mainPin = document.querySelector('.map__pin--main'); var mapSizes = window.card.pinList.getBoundingClientRect(); var mapRightLimit = mapSizes.width - MAIN_PIN_WIDTH; var mapTopLimit = MAP_TOP_SIDE - MAIN_PIN_HEIGHT; var mapBottomLimit = MAP_BOTTOM_SIDE - MAIN_PIN_HEIGHT; var map = document.querySelector('.map'); var renderPins = function (pins) { var fragment = document.createDocumentFragment(); for (var j = 0; j < pins.length; j++) { var advertPin = window.pin.take(pins, j); fragment.appendChild(advertPin); } window.card.pinList.appendChild(fragment); }; var removePins = function () { var pinElemenetsList = document.querySelectorAll('.map__pin'); pinElemenetsList.forEach(function (pinElement) { if (!pinElement.classList.contains('map__pin--main')) { pinElement.parentNode.removeChild(pinElement); } }); }; window.map = { item: map, mainPin: mainPin, mainPinLocationY: MAIN_PIN_LOCATION_Y, mainPinLocationX: MAIN_PIN_LOCATION_X, mainPinPositionFirst: mainPinPositionFirst, topLimit: mapTopLimit, rightLimit: mapRightLimit, bottomLimit: mapBottomLimit, leftLimit: MAP_LEFT_LIMIT, mainPinWidth: MAIN_PIN_WIDTH, mainPinHeight: MAIN_PIN_HEIGHT, renderPins: renderPins, removePins: removePins }; })();
true
3f696ff65c1b826dd682d74049b6eeb18d597801
JavaScript
orinocoz/Traffic
/js/traffic.js
UTF-8
12,208
2.828125
3
[ "MIT" ]
permissive
/** * Created by mm on 15/08/15. */ function newSerie(s, par) { // Return a new serie from s, normalize vs first element var r = [], e = []; var f = s[0][par]; for (var i = 0; i < s.length; i++) { e = [s[i]['Time'], (s[i][par] - f)]; r.push(e); } return r; } function sumSeries(s1, s2) { // s1 + s2, assuming equal size, time at index zero and assumed equal between s1 and s2 var r = [], e = []; for (var i = 0; i < s1.length; i++) { e = [s1[i][0], s1[i][1] + s2[i][1]]; r.push(e); } return r; } function newSerieNoAcc(s) { // Return a new serie with that is not accumulating from s var r = [], e; e = [s[0][0], s[0][1]]; r.push(e); for (var i = 1; i < s.length; i++) { e = [s[i][0], s[i][1] - s[i - 1][1]]; r.push(e); } return r; } function getVolElem(v) { if (v > 1020 * 1024) return ["GB", v / (1024 * 1024)]; if (v > 1024) return ["MB", v / 1024]; return ["kB", v]; } function scale(str, s) { // Scale series by str var i; if (str == "GB") { for (i = 1; i < s.length; i++) { s[i][1] = s[i][1] / (1024 * 1024); } return s; } else if (str == "MB") { for (i = 1; i < s.length; i++) { s[i][1] = s[i][1] / 1024; } return s; } else return s; } function getMax(s) { // Return max value from s, last element return s[s.length - 1][1]; } function scaleVal(str, v) { if (str == "GB") { return v; } else if (str == "MB") return v * 1024; else // kB return v * 1024 * 1024; } function labelFormatter(label, series) { return "<div style='font-size:12pt; text-align:center; padding:2px; color:black;'>" + label + "<br/>" + Math.round(series.percent) + "%</div>"; } function plotTraffic(series) { var up, down, tot, sum; var upNoAcc, downNoAcc; var max_up, max_down; var upVolStr, downVolStr, totVolStr; var th; // threshold var fromDate, toDate, noOfDays, aveSum; var dayStr; up = newSerie(series, 'UplinkVolume'); down = newSerie(series, 'DownlinkVolume'); tot = sumSeries(up, down); max_up = getMax(up); upVolStr = getVolElem(max_up); max_down = getMax(down); downVolStr = getVolElem(max_down); totVolStr = getVolElem(max_up + max_down); up = scale(totVolStr[0], up); down = scale(totVolStr[0], down); tot = scale(totVolStr[0], tot); th = scaleVal(totVolStr[0], 40); // threshold is 40 GB, convert to current scale $.plot($("#graph1"), [ {data: up, yaxis: 1, lines: {show: true, fill: false, steps: true}, label: "Uplink volume (" + upVolStr[1].toFixed(0) + " "+ upVolStr[0] + ")"}, {data: down, yaxis: 1, lines: {show: true, fill: false, steps: true}, label: "Downlink volume (" + downVolStr[1].toFixed(0) + " " + downVolStr[0] + ")"}, {data: tot, yaxis: 1, lines: {show: true, fill: false, steps: true}, label: "Total volume (" + totVolStr[1].toFixed(0) + " " + totVolStr[0] + ")"} ], { legend: {position: "nw"}, xaxis: {mode: "time", timezone: "browser"}, yaxes: [ {min: 0} ] }); upNoAcc = newSerieNoAcc(up); downNoAcc = newSerieNoAcc(down); $.plot($("#graph2"), [ {data: upNoAcc, yaxis: 1, lines: {show: true, fill: true, steps: true}, label: "Uplink volume (" + upVolStr[0] + ")" }, {data: downNoAcc, yaxis: 1, lines: {show: true, fill: true, steps: true}, label: "Downlink volume (" + downVolStr[0] + ")"} ], {legend: {position: "nw"}, xaxis: {mode: "time", timezone: "browser"}, yaxes: [{min: 0}]} ); $.plot($("#pie1"), [ {data: max_up, label: "Uplink" }, {data: max_down, label: "Downlink"} ], {series: {pie: {show: true, radius: 1, label: {show: true, radius: 2 / 3, formatter: labelFormatter}}}, legend: {show: false}} ); sum = getVolElem(max_up + max_down); $.plot($("#pie2"), [ {data: sum[1], label: "Consumed" }, {data: th - sum[1], label: "Left"} ], {series: {pie: {show: true, radius: 1, label: {show: true, radius: 2 / 3, formatter: labelFormatter}}}, legend: {show: false}} ); fromDate = new Date($("#dateFrom").val()).setHours(0); toDate = new Date($("#dateTo").val()).setHours(24); dayStr = " days "; noOfDays = (toDate - fromDate) / (1000 * 60 * 60 * 24); if (noOfDays <= 1) { noOfDays = 1; // toDate == fromDate dayStr = " day "; } aveSum = getMax(tot) / noOfDays; $("#trafficData").text(" (" + noOfDays.toFixed(0) + dayStr + aveSum.toFixed(1) + " " + totVolStr[0] + "/day)"); } function Router() { // router object var firstUplinkVal = 0, firstDownlinkVal = 0; var upSum = 0, downSum = 0; var up = [], down = []; var upRate = [], downRate = []; var period = (10 * 60)/ 2; // 10 minutes in sec, sample rate every 2nd sec this.volume = function(time, upVal, downVal) { if (firstUplinkVal == 0) { firstUplinkVal = upVal; } upVal -= firstUplinkVal; if (firstDownlinkVal == 0) { firstDownlinkVal = downVal; } downVal -= firstDownlinkVal; up.push([time, upVal]); down.push([time, downVal]); upSum += upVal; downSum += downVal; if (up.length > period) { firstUplinkVal = 0; firstDownlinkVal = 0; upSum -= up[0]; downSum -= down[0]; up.shift(); down.shift(); } }; this.rate = function(time, upVal, downVal) { upRate.push([time, upVal]); downRate.push([time, downVal]); if (upRate.length > period) { upRate.shift(); downRate.shift(); } }; this.getUpVolume = function() { return up; }; this.getDownVolume = function() { return down; }; this.getUpRate = function() { return upRate; }; this.getDownRate = function() { return downRate; }; this.getUpSum = function() { return upSum; }; this.getDownSum = function() { return downSum; }; this.getSumStr = function(str) { var val; if (str == 'up') { val = upSum; } else { val = downSum; } if (val > (1024 * 1024)) { val /= (1024 * 1024); return val.toFixed(1) + " GB"; } else if (val > 1024) { val /= 1024; return val.toFixed(1) + " MB"; } else { return val.toFixed(1) + " kB"; } }; this.scaleRate2Str = function(val) { if (val > (1000 * 1000)) { val /= (1000 * 1000); return val.toFixed(1) + " GB/s"; } else if (val > 1000) { val /= 1000; return val.toFixed(1) + " MB/s"; } else { return val.toFixed(1) + " kb/s"; } }; } function plotRealTime(d, r) { var g_up = $('#gauge-up'); var g_down = $('#gauge-down'); var gaugeOptions = { chart: { type: 'solidgauge' }, title: null, pane: { center: ['50%', '85%'], size: '140%', startAngle: -90, endAngle: 90, background: { backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE', innerRadius: '60%', outerRadius: '100%', shape: 'arc' } }, tooltip: { enabled: false }, // the value axis yAxis: { stops: [ [0.1, '#55BF3B'], // green [0.5, '#DDDF0D'], // yellow [0.9, '#DF5353'] // red ], lineWidth: 0, minorTickInterval: null, tickPixelInterval: 400, tickWidth: 0, title: { y: -70 }, labels: { y: 16 } }, plotOptions: { solidgauge: { dataLabels: { y: 5, borderWidth: 0, useHTML: true } } } }; r.volume(d.time, d['uplink'], d['downlink']); r.rate(d.time, d['uplink rate'], d['downlink rate']); $.plot($("#graph1"), [ {data: r.getUpVolume(), lines: {show: true, fill: true}, label: "Uplink volume (" + r.getSumStr('up') + ")"}, {data: r.getDownVolume(), lines: {show: true, fill: true}, label: "Downlink volume (" + r.getSumStr('down') + ")"}, {data: r.getUpRate(), yaxis: 2, label: "Uplink rate (" + r.scaleRate2Str(d['uplink rate']) + ")"}, {data: r.getDownRate(), yaxis: 2, label: "Downlink rate (" + r.scaleRate2Str(d['downlink rate']) + ")"} ], {legend: {position: "nw"}, xaxis: {mode: "time", timezone: "browser"}, yaxes: [{min: 0 }, {position: "right", min: 0}]}); $.plot($("#pie1"), [{data: r.getUpSum(), label: "Volume up"}, {data: r.getDownSum(), label: "Volume down"} ], {series: {pie: {show: true, radius: 1, label: {show: true, radius: 2 / 3, formatter: labelFormatter}}}, legend: {show: false}} ); $.plot($("#pie2"), [{data: d['uplink rate'], label: "Rate up"}, {data: d['downlink rate'], label: "Rate down"} ], {series: {pie: {show: true, radius: 1, label: {show: true, radius: 2 / 3, formatter: labelFormatter}}}, legend: {show: false}} ); // The uplink speed gauge g_up.highcharts(Highcharts.merge(gaugeOptions, { yAxis: { min: 0, max: 2000, title: { text: 'Uplink' } }, credits: { enabled: false }, series: [{ name: 'Speed up', data: [80], dataLabels: { format: '<div style="text-align:center"><span style="font-size:25px;color:' + ((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y}</span><br/>' + '<span style="font-size:12px;color:silver">kb/s</span></div>' }, tooltip: { valueSuffix: ' kb/s' } }] })); // The downlink speed gauge g_down.highcharts(Highcharts.merge(gaugeOptions, { yAxis: { min: 0, max: 2000, title: { text: 'Downlink' } }, credits: { enabled: false }, series: [{ name: 'Speed down', data: [80], dataLabels: { format: '<div style="text-align:center"><span style="font-size:25px;color:' + ((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y}</span><br/>' + '<span style="font-size:12px;color:silver">kb/s</span></div>' }, tooltip: { valueSuffix: ' kb/s' } }] })); g_up.highcharts().series[0].points[0].update(d['uplink rate']); g_down.highcharts().series[0].points[0].update(d['downlink rate']); }
true
118f61c01d97354fdc17bf540ba976639e90291b
JavaScript
AroundTheCorne7/UniversitiyProjects
/sketch.js
UTF-8
1,751
3.25
3
[]
no_license
/** * Created by AroundTheCorner on 7/1/2017. */ var bird; var target; var maxObstacles = 15; var obstacles = []; var updateFromBeg = true; function setup() { createCanvas(800, 600); resetSketch(); while (obstacles.length < maxObstacles) { var x = random(700) + 50; var y = random(500) + 50; var size = random(50) + 15; var doesOverlap = false; var currObstacle = new Obstacle(x, y, size); if (currObstacle.doOverlap(bird.pos.x, bird.pos.y, bird.size).result) { continue; } for (var i = 0; i < obstacles.length; i++) { if (obstacles[i].doOverlap(currObstacle.x, currObstacle.y, currObstacle.size).result) { doesOverlap = true; break; } } if (!doesOverlap) { obstacles.push(currObstacle); } } } function resetSketch() { bird = new Bird(10, height - 30, 35); target = new Target(770, 30, 30); } function draw() { background(0); var d = dist(bird.pos.x, bird.pos.y, target.x, target.y) if (d <= target.speed) { target.gotCaught(); target.changeColor(); bird.speed = 0; } stroke(200); fill(200, 200, 200, 80); obstacles.forEach(function (currentValue) { currentValue.draw(); }); bird.traditionalSeek(createVector(target.x, target.y), 1); obstacles.forEach(function (obsticle) { var d = dist(bird.pos.x, bird.pos.y, obsticle.x, obsticle.y); var f = 1 / (d * d); var strength = 1.5; f = map(f, 0, 1 / (obsticle.size * obsticle.size), 0, strength); f = constrain(f, 0, strength); // if (d > 70) { // return; // } bird.traditionalSeek(createVector(obsticle.x, obsticle.y), -f); }); bird.update(); bird.show(); target.update(updateFromBeg); target.show(); }
true
deb771d0bfce1e9c4b161f645d8f9d111301bf67
JavaScript
Vankum100/Javascript
/es6-learning/src/Person.js
UTF-8
373
3.234375
3
[]
no_license
// Babel Helps us `output` this `src` es2015 code in vanilla js // transformations are only possible with help of // babel-preset-es2015 package // set up the presets in `.babelrc` file class Person { constructor(name){ this.name = name; } greet() { return this.name + ' says hello.'; } } console.log(new Person('jeffrey').greet());
true
808db210ee92c322a760913dced67277eea207d9
JavaScript
tautvydascoding/2018-07
/dirbame_cia/diena_5/Gvidas/js_pradmenys/js/main.js
UTF-8
3,407
3.625
4
[]
no_license
// console.log("labas"); // // var namas = "daugiabutis"; // var spalva = "geltona A233"; // var aukstuSkaicius = 5; // var butuSkaiciusAukste = 4; // var laiptiniuSk = 3; // // // uzduotis suskaiciuoti butu skaiciu daugiabutyje // var laiptinejeButu = aukstuSkaicius * butuSkaiciusAukste; // // console.log("butu skaicius laiptineje: ", laiptinejeButu); // console.log("butu skaicius laiptineje: " + laiptinejeButu); // // var skaiciaviami = (560+10) / 10; // var skaiciaviami2 = 560 + 10 / 10; // // console.log(skaiciaviami); // console.log(skaiciaviami2); // uzduotis-1 var vardas = "petras"; var pavarde = "pievas"; var amzius = 35; var atlyginamas = 950; console.log( typeof(vardas) ); console.log( typeof(pavarde) ); console.log( typeof(amzius) ); console.log( typeof(atlyginimas) ); // uzduotis-2 function printVardasPavardeAmzius () { console.log("vardas yra:", vardas); console.log("pavarde yra:", pavarde); console.log("amzius yra:", amzius); console.log("atlyginimas yra:", atlyginamas); } printVardasPavardeAmzius (); // uzduotis-3 function printMetinisPajamuDydis () { var ats = atlyginamas * 12; console.log("metinis atlyginimas:", ats); } printMetinisPajamuDydis(); // naujesnis budas function printMetinisPajamuDydis2 (x) { var ats1 = x * 12; console.log("jeigu uzdirbu", x, "atlyginimas yra:", ats1); } printMetinisPajamuDydis2(650); // uzduotis-4 var salis = "lietuva"; var miestas = "kaunas"; var adresas = "kursiu g. 7"; var pastoKodas = 55555; function printAddressData () { console.log("salis yra:", salis); console.log("mietas yra:", miestas); console.log("adresas yra:", adresas); console.log("pasto kodas yra:", pastoKodas); } printAddressData(); // uzduotis-5 function printTekstas(x) { console.log(x); } printTekstas( "Jokubo istorijos"); // uzduotis-6 bus teste function daugyba(x, y) { var atsakymas = x * y; console.log("atsakymas yra:", atsakymas); } daugyba(10, 6); // uzdutois-7 function pitagoroTeorema(x, y) { var ats = (x * x) + (y * y); console.log("trikampio ilgoji krastine:", ats); } pitagoroTeorema(2, 4); // 1 UZDUOTIS // sukurti kintamuosius (ir jiems priskirti reiksmes): // vardas, pavarde, amzius, atlyginimas // teo: // typeof( k ); f-ja kuri isveda kintamojo tipa // console.log( typeof(vardas) ); // console.log( typeof(amzius) ); // 2 UZDUOTIS // sukurti funkcija "printVardasPavardeAmzius()" , kuri atspausdina i konsole pirmos uzduoties kintamuosius // 3 UZDUOTIS // sukurti funkcija "printMetinisPajamuDydis()" , // kuri atspausdina i konsole suma 12 atlyginimu (vienas atlyginimas yra lygus "uzduotis 1" kintamajam - "atlyginimas") // 4 UZDUOTIS // A) sukurti kintamuosius: salis, miestas, adresas, pastoKodas // B) sukurti f-ja "printAddressData()", kuri atspausdina i konsole visus siuos kintamuosius // ---- advance----- // 5 UZDUOTIS // sukurti funkcija "printTekstas(x)" , // kuri atspausdina i konsole "x" reiksmes // iskviesti f-ja ir vietoj x irasyti koki nors teksta pvz: printTekstas( "Jokubo istorijos"); // 6 UZDUOTIS // sukurti f-ja, kuri sudaugina du paduotus skaicius "daugyba(x, y)" // 7 UZDUOTIS // F-ja kuri paskaiciuoja trikampio ilgaja krastine (Pitagoro teorema) // pitagoroTeorema(x, y) x*x + y*y //==========================KOMANDINE (3-4h) Bootstrap && GIT================= // ant lentos
true
59f146c0a3736c967e986670efaec59854309789
JavaScript
wangdoudou86/32-senior-slide
/main.js
UTF-8
2,250
3.109375
3
[]
no_license
let $buttons = $('#buttonWrapper>button') let $slides = $('#slides') let current = 0 let $images = $slides.children('img') makefakeSlides() $slides.css({transform:'translateX(-400px)'})//真的第一张位置在-400px处 bindEvents() $('#previous').on('click',function(){ gotoSlide(current-1) }) $(next).on('click',function(){ gotoSlide(current+1) }) let timer = setInterval(function(){ gotoSlide(current+1) },2000) $('.window').on('mouseenter',function(){ window.clearInterval(timer) }) $('.window').on('mouseleave',function(){ timer = setInterval(function(){ gotoSlide(current+1) },2000) }) function makefakeSlides(){ let $firstCopy = $images.eq(0).clone(true)//true就克隆它全家,false就克隆它自己 let $lastCopy = $images.eq($images.length-1).clone(true) $slides.append($firstCopy) $slides.prepend($lastCopy) } function bindEvents(){ $('#buttonWrapper').on('click','button',function(e){ //事件委托,点击$('#buttonWrapper')里的button时执行function(e) let $button = $(e.currentTarget) //点击的按钮 let index = $button.index() //点击的按钮在数组中的序号 gotoSlide(index) }) } //把去到每一张图片的功能分离出来很重要 function gotoSlide(index){ if(index>$buttons.length-1){ index = 0 }else if(index < 0){ index = $buttons.length-1 } if(current === $buttons.length-1 && index === 0){ //从最后一张去第一张 $slides.css({transform:`translateX(${-($buttons.length+1)*400}px)`}).one('transitionend',function(){ $slides.hide() $slides.offset() $slides.css({transform:'translateX(-400px)'}).show() }) }else if(current === 0 && index === $buttons.length-1){ //从第一张去最后一张 $slides.css({transform:'translateX(0)'}).one('transitionend',function(){ $slides.hide() $slides.offset() $slides.css({transform:`translateX(${-$buttons.length*400}px)`}).show() }) }else{ $slides.css({transform:`translateX(${-(index+1)*400}px)`})//不要把px括进去哦 } current = index //!!!不要忘了赋值 }
true
2c7b0a050977bcc9c8bfdabc8566f3c78f789322
JavaScript
hub-i/hub-i.github.io
/교재/chap 8/p212_1.js
UTF-8
924
4.15625
4
[ "MIT" ]
permissive
let a; var arr = [ { id: 5, name: "Judith" }, { id: 7, name: "Francis" } ]; a=arr.findIndex(o => o.id === 7); // returns 0 arr.findIndex(o => o.name === "Francis"); // returns 1 arr.findIndex(o => o === 3); // returns -1 arr.findIndex(o => o.id === 17); // returns -1 console.log(a); var arr = [ { id: 5, name: "Judith" }, { id: 7, name: "Francis" }]; arr.find(o => o.id === 5); // returns object { id: 5, name: "Judith" } arr.find(o => o.id === 2); // returns null console.log("-----------------------------------"); var arr = [1, 17, 16, 5, 4, 16, 10, 3, 49]; //배열 0,1,2 방의 값은 무시하고 //배열 3 이상의 방의 값중에서 스퀘어 루트 함수를 통해 //구한 결과가 정수인 경우 해당 배열 요소의 값을 리턴한다. var ret = arr.find( (x, i) => { console.log('i = ',i); return i > 2 && Number.isInteger(Math.sqrt(x)); } ); // returns 4 console.log(ret);
true
d9be6b27c03abf5c829f8eeeffb3009057cf7081
JavaScript
RivaD2/data-structures-and-algorithms
/data-structures/fizzBuzzTree/fizz-buzz-tree.js
UTF-8
3,400
4
4
[ "MIT" ]
permissive
'use strict'; class Node { constructor(value, k) { this.value = value; // I need to know what k it is so when I copy tree I can use the same num this.k = k; //a new array of k length this.children = new Array(k); } } class Tree extends Node { constructor() { super() this.root = null; } add(newValue, k) { let newNode = new Node(newValue, k); if(this.root === null) { this.root = newNode; return this; } else { //process involves looping just like in linkedlist //starting in head and updating current as I go let current = this.root; let queue = []; while(current) { let childCount = current.children.length; for(let i = 0; i < childCount; i++) { const child = current.children[i]; if(child === undefined) { current.children[i] = newNode; i = current.children.length; current = undefined; //break from loop } else { queue.unshift(child); } } if(current !== undefined) { current = queue.pop(); } } } } } const fizzBuzzTree = unfizzyTree => { //Is value of each node divisible by 3, 5 or both. let fizzyTree = new Tree(); let current = unfizzyTree.root; //creating a root separately for fizzy tree before traversal of unfizzy tree let fizzBuzzRoot = new Node(getFizzBuzz(current.value), current.k); fizzyTree.add(fizzBuzzRoot); let queue = []; while(current) { const childCount = current.children.length; //looping through unfizzy tree and find all nodes to add to new tree for(let i = 0; i < childCount; i++) { const child = current.children[i]; if(child === undefined) { //we are at the end of the tree, nothing left to do current = undefined; i = childCount; } else { //found a child node, so I need to add corresponding child node queue.unshift(child); fizzyTree.add(getFizzBuzz(child.value), child.k); } } if(current !== undefined) { current = queue.pop(); } } return fizzyTree; } const getFizzBuzz = value => { //this function will return value that I want to add to new tree // so fizz, buzz, fizzbuzz, or original value let number = parseInt(value); if(number % 3 && number % 5) { //If the number is divisible by 3 and 5, replace the number with “Fizzbuzz” return value; } else if(number % 3 && !(number % 5)) { return 'Buzz'; } else if(number % 5 && !(number % 3)) { return 'Fizz'; } else { return 'Fizzbuzz'; } } const k = 3; const nodeCount = 19; //creating a k-ary tree const unfizzedTree = new Tree(); for(let i = 1; i <= nodeCount; i++) { unfizzedTree.add(i.toString(), k); } console.log(JSON.stringify(unfizzedTree)); const fizzedTree = fizzBuzzTree(unfizzedTree); console.log(JSON.stringify(fizzedTree)); module.exports = fizzBuzzTree;
true
fda9e1cd050a721dd8119fb6538fbd5f0da7a5bf
JavaScript
Lucas-Brum/Programacao-para-Web-II
/Unidade 2/Livro 1/EX03/Script.js
UTF-8
446
2.890625
3
[]
no_license
function flores(){ var array = ['Anturio.jpg','Bromelia.jpg','Dente de leão.jpg', 'Flor da meia noite.jpg','Girassol.jpg','Lirio.jpg', 'Rosa.jpg','Tulipa.jpg','Flor de lis.jpg','Crisantemo.jpg'] for (let i = 0; i <= 9; i++){ let flor = document.createElement('img') flor.src = array[i] let lista = document.querySelector('#Lista') lista.appendChild(flor) } }
true
6037619cd29305f745db4c4c054aaed8228064fc
JavaScript
liubiantaotest/web-security-docker
/back-end/XSS/persistent/client/js.js
UTF-8
897
2.703125
3
[]
no_license
const template = data => { return ` <div class="message-item"> <i>IP: ${data.ip} 说道: </i> <sapn class="content">${data.content}</sapn> </div>`; }; // 获取内容 const getContent = () => { $.ajax({ url: 'http://127.0.0.1:8084/getContent.php', method: 'GET', async: true }) .done(data => { data = JSON.parse(data); // 清空内容 $('.message-item').remove(); // 插入数据 for (let i = 0; i < data.length; i++) { $('.message-board').append(template(data[i])); } }) }; // 点击提交 $('#submit').click(() => { const content = $('textarea').val(); if (content === '') { return; } $.ajax({ url: 'http://127.0.0.1:8084/postContent.php', method: 'POST', async: true, data: { content } }) .done(() => { getContent(); }) }); $(document).ready(() => { getContent(); });
true
8b304ac13f7325f4f22e4b3a2d7de72859d14103
JavaScript
massimilianobraglia/jymfony
/src/Component/Cache/src/Adapter/AbstractAdapter.js
UTF-8
6,068
2.625
3
[ "MIT" ]
permissive
import * as fs from 'fs'; const ArrayAdapter = Jymfony.Component.Cache.Adapter.ArrayAdapter; const FilesystemAdapter = Jymfony.Component.Cache.Adapter.FilesystemAdapter; const RedisAdapter = Jymfony.Component.Cache.Adapter.RedisAdapter; const CacheItem = Jymfony.Component.Cache.CacheItem; const CacheItemPoolInterface = Jymfony.Component.Cache.CacheItemPoolInterface; const InvalidArgumentException = Jymfony.Component.Cache.Exception.InvalidArgumentException; const AbstractTrait = Jymfony.Component.Cache.Traits.AbstractTrait; const DateTime = Jymfony.Component.DateTime.DateTime; const LoggerAwareInterface = Jymfony.Component.Logger.LoggerAwareInterface; const NullLogger = Jymfony.Component.Logger.NullLogger; /** * @memberOf Jymfony.Component.Cache.Adapter * @abstract */ export default class AbstractAdapter extends implementationOf(CacheItemPoolInterface, LoggerAwareInterface, AbstractTrait) { /** * Constructor. * * @param {string} [namespace = ''] * @param {int} [defaultLifetime = 0] */ __construct(namespace = '', defaultLifetime = 0) { /** * @type {string} * * @private */ this._namespace = '' === namespace ? '' : (CacheItem.validateKey(namespace) + ':'); if (undefined !== this.constructor.MAX_ID_LENGTH && namespace.length > this.constructor.MAX_ID_LENGTH - 24) { throw new InvalidArgumentException(__jymfony.sprintf('Namespace must be %d chars max, %d given ("%s")', this.constructor.MAX_ID_LENGTH - 24, namespace.length, namespace)); } /** * Create a cache item for the current adapter. * * @param {string} key * @param {*} value * @param {boolean} isHit * * @returns {Jymfony.Component.Cache.CacheItem} * * @private */ this._createCacheItem = (key, value, isHit) => { const item = new CacheItem(); item._key = key; item._value = value; item._isHit = isHit; item._defaultLifetime = defaultLifetime; return item; }; /** * @type {Jymfony.Component.Logger.LoggerInterface} * * @private */ this._logger = new NullLogger(); } /** * Creates a system cache pool. * * @param {string} namespace * @param {int} defaultLifetime * @param {string} directory * @param {Jymfony.Component.Logger.LoggerInterface} [logger] */ static createSystemCache(namespace, defaultLifetime, directory, logger = undefined) { const cache = (() => { try { const fsAdapter = new FilesystemAdapter(namespace, defaultLifetime, directory); fs.accessSync(directory, fs.constants.W_OK); return fsAdapter; } catch (e) { if ('EROFS' !== e.code) { throw e; } } return new ArrayAdapter(defaultLifetime); })(); cache.setLogger(logger || new NullLogger()); return cache; } /** * Creates a connection for cache adapter. * * @param {string} dsn * @param {Object.<string, *>} options */ static createConnection(dsn, options = undefined) { options = options || {}; if (! isString(dsn)) { throw new InvalidArgumentException(__jymfony.sprintf('The createConnection() method expect argument #1 to be string, %s given.', typeof dsn)); } if (0 === dsn.indexOf('redis:')) { return RedisAdapter.createConnection(dsn, options); } throw new InvalidArgumentException(__jymfony.sprintf('Unsupported DSN: %s.', dsn)); } /** * @inheritdoc */ async getItem(key) { const id = await this._getId(key); let isHit = false; let value = undefined; try { for (const val of Object.values(await this._doFetch([ id ]))) { value = val; isHit = true; } } catch (e) { this._logger.warning('Failed to fetch key "{key}"', { key, exception: e }); } return this._createCacheItem(key, value, isHit); } /** * @inheritdoc */ async getItems(keys = []) { let ids = await Promise.all(keys.map(key => this._getId(key))); let items; try { items = await this._doFetch(ids); } catch (e) { this._logger.warning('Failed to fetch requested items', { keys, exception: e }); items = []; } ids = Object.entries(ids) .reduce((res, val) => (res[val[1]] = keys[val[0]], res), {}); return new Map(this._generateItems(items, ids)); } /** * @inheritdoc */ save(item) { if (! (item instanceof CacheItem)) { return false; } let lifetime = item._expiry - DateTime.unixTime; if (undefined === item._expiry) { lifetime = item._defaultLifetime; } if (undefined !== lifetime && 0 > lifetime) { return this._doDelete([ item.key ]); } return this._doSave({ [item.key]: item.get() }, lifetime); } * _generateItems(items, keys) { try { for (const [ id, value ] of __jymfony.getEntries(items)) { if (undefined === keys[id]) { continue; } const key = keys[id]; delete keys[id]; yield [ key, this._createCacheItem(key, value, true) ]; } } catch (e) { this._logger.warning('Failed to fetch requested items', { keys: Object.values(keys), exception: e }); } for (const key of Object.values(keys)) { yield [ key, this._createCacheItem(key, undefined, false) ]; } } /** * @inheritdoc */ async close() { // Nothing to do. } }
true
c992e79492e67713d594bb5872a83ac8feb5570b
JavaScript
denny999222/Rype
/src/components/common/components/Header.js
UTF-8
3,641
2.78125
3
[]
no_license
// Takes in props of {name, imageURL, containerStyle, contentStyle, leftButton, rightButton, onPressLeft, onPressRight} // "name" : which is the text it will show // "imageURL" : (could be logo, etc) which has a fixed size to fit into header // "containerStyle" : pertains to the view surrounding the content (whether text or image) // and can override existing styling // "contentStyle" : pertains to the content inside the view (text or image) // and can also override existing styling // "leftButton" : button on the left which is a component prop // "rightButton" : button on the right whih is a component prop // "onPressLeft": action of what left button does // "onPressRight": action of what right button does import React,{Component} from 'react'; import {StyleSheet, View, Text, Image, TouchableOpacity, SafeAreaView} from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome5'; class Header extends Component{ renderHeader = () => { const {imageURL, name, contentStyle, leftButton, rightButton, onPressLeft, onPressRight, containerStyle} = this.props; if (typeof imageURL !== 'undefined'){ return ( <View style={styles.rowStyle} > <TouchableOpacity style={styles.buttonStyle} onPress={onPressLeft} > {leftButton || <Icon name='ad' color={containerStyle.backgroundColor || styles.container.backgroundColor} size={rightButton.props.size} />} </TouchableOpacity> <Image style={[styles.imageStyle, contentStyle]} source={{uri: imageURL}} /> <TouchableOpacity style={styles.buttonStyle} onPress={onPressRight} > {rightButton || <Icon name='ad' color={containerStyle.backgroundColor || styles.container.backgroundColor} size={leftButton.props.size} />} </TouchableOpacity> </View> ) } else if (name !== 'undefined'){ return ( <View style={styles.rowStyle} > <TouchableOpacity style={styles.buttonStyle} onPress={onPressLeft} > {leftButton || <Icon name='ad' color={containerStyle.backgroundColor || styles.container.backgroundColor} size={rightButton.props.size} />} </TouchableOpacity> <Text style={[styles.textStyle, contentStyle]}> {name} </Text> <TouchableOpacity style={styles.buttonStyle} onPress={onPressRight}> {rightButton || <Icon name='ad' color={containerStyle.backgroundColor || styles.container.backgroundColor} size={leftButton.props.size} />} </TouchableOpacity> </View> ) } } render(){ const {containerStyle} = this.props; return( <SafeAreaView style={[styles.container, containerStyle]} > {this.renderHeader()} </SafeAreaView> ); } }; const styles = StyleSheet.create({ container:{ height:'7%', justifyContent:'center', backgroundColor:'#f6f6f6', }, imageStyle :{ width:'30%', aspectRatio:4.3, }, textStyle:{ fontSize: 32, }, buttonStyle:{ justifyContent:'flex-end', }, rowStyle:{ flexDirection:'row', justifyContent:'space-between', alignItems:'center', marginRight:'2%', marginLeft:'2%', paddingBottom:'2%' }, iconStyle:{ padding:'2%', } }); export {Header};
true
f83ed8576190824694504abf491e100f24ce4ad1
JavaScript
Novoidarskyi/goit-js-hw-08-gallery
/js/make-gallery.js
UTF-8
1,873
2.53125
3
[]
no_license
import galleryItems from "./gallery-items.js"; const refs = { galleryPictures: document.querySelector(".js-gallery"), modal: document.querySelector(".js-lightbox"), modalImage: document.querySelector(".lightbox__image"), buttonClose: document.querySelector('[data-action="close-lightbox"]'), }; let activeIndex; const picturesGridMarkup = galleryItems.map( ({ preview, original, description }) => { return `<li class="gallery__item"> <a class="gallery__link" href="${original}" > <img class="gallery__image" src="${preview}" data-source="${original}" alt="${description}" /> </a> </li>`; } ); refs.galleryPictures.insertAdjacentHTML( "afterbegin", picturesGridMarkup.join("") ); refs.galleryPictures.addEventListener("click", (e) => { e.preventDefault(); if (e.target.localName !== "img") { return; } refs.modal.classList.add("is-open"); refs.modalImage.src = e.target.dataset.source; for (let i = 0; i < picturesGridMarkup.length; i += 1) { if (picturesGridMarkup[i].includes(e.target.src)) { activeIndex = i; } } console.log(activeIndex); }); refs.buttonClose.addEventListener("click", removeModal); refs.modal.addEventListener("click", (e) => { if (e.target.localName !== "img") { removeModal(); } }); window.addEventListener("keyup", (e) => { if (e.key !== "Escape") { return; } removeModal(); }); window.addEventListener("keyup", (e) => { if (e.key === "ArrowRight" && activeIndex < galleryItems.length - 1) { activeIndex += 1; refs.modalImage.src = galleryItems[activeIndex].original; } if (e.key === "ArrowLeft" && activeIndex > 0) { activeIndex -= 1; refs.modalImage.src = galleryItems[activeIndex].original; } }); function removeModal() { (refs.modalImage.src = ""), refs.modal.classList.remove("is-open"); }
true
5c359a1f332fd51377fc1e94020194364d079434
JavaScript
HongseockKim/javascript
/javascript_1/array.js
UTF-8
4,260
4.09375
4
[]
no_license
//array 배열 자료 구조 중 하나 //다른 언어 같은 경우 같은 종류의 type 의 object 만 담을 수 있다. // 자바스크립트는 다른 type 의 자료를 보관할수 있지만 // 되도록이면 같은 종류의 type의 object 를 보관 하도록 한다. 'use strict'; // 1. Array🐶 //배열의 선언 방법 Decleartion const arr1 = new Array(); const arr2 = [1,2]; //2. Index position 인덱스를 통한 접근 const fruits = ['🍎','🍌']; console.log(fruits); console.log(fruits.length); console.log(fruits[0]); console.log(fruits[1]); //배열의 제일 마지막 index console.log(fruits.length - 1); //배열 출력 for(const value of fruits){ console.log(value); } fruits.forEach(function(furit,idx,array){ //2번 출력 된다 왜냐면 안에 인자가 2개가 있어서 사과 바나나 console.clear(); console.log('he'); console.log(furit) console.log(idx); console.log(array); }); //이름 없는 함수의 경우 arrow 를 쓸수 있다 fruits.forEach((value,idx,array) => { console.log(value,idx,array); }); //딱 한줄로 사용 할수도 있음 fruits.forEach((value,idx,array) => console.log(value,idx,array)); //4.Addtion, deletion , copy 배열을 추가 하거나 지우거나 복사하는법 //push fruits.push('🍒','🍑'); console.log(fruits); //pop 배열 하나 뺴기 데이터가 그냥 빠지는 게 아니고 빠지면서 그 빠진 데이터 가 리턴 된다; // 그냥 빼도 되지만 fruits.pop(); //popValue 는 변수에 담으면 그 빠진 값이 들어가게 된다;!!!!!!!!!!!!!!!!!! const popValue = fruits.pop(); console.log(fruits); console.log(popValue + 'www'); //unshift 앞에서 배열 추가하기 //수박 레몬 순 fruits.unshift('🍉','🍋'); console.log(fruits); //shift 앞에서 부터 배열이 빠진다; // 수박부터 빠짐 fruits.shift(); console.log(fruits); // 중요 알고 가야할것 // shift 와 unshitf 는 pop 과 push 보다 매우 매우 느리다. // 배열의 뒤로 가는건 빈공간으로 가는거지만 //앞으로 데이터 를 추가하는건 기존에 있는 값들을 한칸씩 뒤로 간다음 넣는거라 느리다 빅데이터 알고리즘 에 대해 공부하면 깊게 알수 있음 //splice fruits.push('🥦','🥝','🍓'); console.log(fruits); //fruits.splice(어디서부터 자르고 싶은 idx , 어디까지 자를껀지의 idx 이고 설명에 ? 가 붙어 있는건 선언을 해도 되고 안해도 된다); //fruits.splice(1); //console.log(fruits); //지정 안하면 내가 지정한 idx 이후부터 다 지워 버린다 fruits.splice(1,1); console.log(fruits); //이렇게 하면 데이터를 지우면서 지운 자리에 데이터를 추가도 할수 있다; fruits.splice(1,2, '🥑','🍇'); console.log(fruits); //combine two array 두가지 배열도 묶어서 할수 있다. //concat const fruist2 = ['🥯','🫕']; //기존에 있던 배열에 concat 이라는 함수를 이용하여 새로만든 fruit2 배열을 합칠수있다; const newfruis = fruits.concat(fruist2); console.log(newfruis); //5.Searching 검사 // 배열안에 어떤값이 몇번째 idx 에 있는지 확인할때 유용하다 // indexOf //console.clear(); console.log(fruits); //배열 안에 사과 없으면 -1 로 출력이됨 console.log(fruits.indexOf('🍎')); //포도가 배열에 들어있고 idx 값이 2라는 것을 호출 console.log(fruits.indexOf('🍇')); //includes //포도가 배열안에 있고 있으면 불리언 값인 true 를 반환 해준다 console.log(fruits.includes('🍇')); //수박이 배열에 없고 없으면 불리언 값인 flase 를 반환 한다 console.log(fruits.includes('🍉')); // lastIndexOf //console.clear(); console.log(fruits); fruits.push('🍋'); console.log(fruits); console.log(fruits.indexOf('🍋')); // 만약 같은 값의 가진 값을 마지막에 추가하여 indexOf 를 사용하면 // 같은 값을 가진 값이 idx 값이 0 이라서 마지막에 추가한 같은 값의 idx 가 안나오고 첫번째로 있는 idx 0 번이 출력 된다; //lastIndexOf 는 같은 값을 가진 마지막 값의 idx 를 출력한다 console.log(fruits.lastIndexOf('🍋')); console.log(fruits);
true
bc7c71d53a00c3a943d23deda194ecc72ff6d547
JavaScript
MichaelMurry49/aA_Classwork
/W10D3/minesweeper_react/frontend/tile.jsx
UTF-8
1,421
2.75
3
[]
no_license
import React from "react"; class Tile extends React.Component { constructor(props){ super(props) this.state = { icon: "T" } this.text = "T"; // debugger; //this.setIcon(); } setIcon(){ // debugger let tile = this.props.tile; if(tile.flagged){ // debugger; this.text = "\u2691"; this.setState({ icon: "\u2691"}) } else if(tile.explored){ if(!tile.bombed){ // debugger; this.text = tile.adjacentBombCount(); this.setState({ icon: tile.adjacentBombCount()}) } else { this.text = "B"; this.setState({ icon: "B" }) } } else if(tile.bombed){ // debugger; this.text = "B"; this.setState({ icon: "B"}) } } handleClick(e){ if(e.altKey){ this.prop.tile.toggleFlag(); this.props.updateGame(); } else { } this.props.tile.explore(); this.props.updateGame(); this.setIcon(); } render(){ // debugger; return( <div className={`${this.state.icon} tile`} onClick={this.handleClick.bind(this)}>{this.state.icon}</div> ) } } export default Tile;
true
9a24affeed18ff5f9515420dc394bce02606da84
JavaScript
lenalast/nolhagaBigard
/js/script.js
UTF-8
1,889
2.984375
3
[ "MIT" ]
permissive
var emailRegexp = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*"); var nanRegexp = new RegExp("^([^0-9]*)$"); function submitForm(event) { event.preventDefault(); var firstname = document.getElementById("firstname").value; var lastname = document.getElementById("lastname").value; var email = document.getElementById("email").value; var message = $("#message").val(); var validationPassed = validateFields(firstname, lastname, email); //Boolsk sats - Om x är sant kör koden, annars inte. validationPassed && handleModal(firstname); } function validateFields(firstname, lastname, email) { var isValid = true; $('.error-message').remove(); if (firstname.length < 2 || !nanRegexp.test(firstname)) { isValid = false; $('#firstname').before('<div class="error-message">Förnamn måste innehålla minst 2 karaktärer och får inte vara siffror</div>'); } if (lastname.length < 2 || !nanRegexp.test(lastname)) { isValid = false; $('#lastname').before('<div class="error-message">Efternamn måste innehålla minst 2 karaktärer och får inte vara siffror</div>'); } if (email.length < 1 || !emailRegexp.test(email)) { isValid = false; $('#email').before('<div class="error-message">Email måste följa formatet: [email protected]</div>'); } return isValid; } function handleModal(firstname) { //Remove focus from form $('*:focus').blur(); //Clear form $('#contact-form').trigger('reset'); //Show modal $('main').append('<div class="_modal"><div class="_modal-content"><h1>Tack ' + firstname + ' för ditt meddelande!</h1></div></div>'); //Remove modal $('._modal').click(function () { $('._modal').addClass('_hide'); setTimeout(function () { $('._modal').remove(); }, 300) }) }
true
e90bd39e586ec08c68b82e56634daf95aa7a0fc6
JavaScript
moroclash/NodeExpress
/index.js
UTF-8
1,812
2.84375
3
[]
no_license
const Joi = require('joi') const express = require('express') const app = express() // get this file or import them internaly inside express app.set('view engine', 'pug') app.set('views', './views') //enable to pars to jsone by adding json as midel ware so it will add it in pipline // of reciving reques so when we deal with request in the end, it will be alredy parsed app.use(express.json()) const loging = (req, res, next) => { console.log('Loging ..... :)') next() } // so we add here a midel-ware funtion that make something and pass the controler // to the next() function app.use(loging) var users = [ { id: 1, name: "user1"}, { id: 2, name: "user2"}, { id: 3, name: "user3"}, ] app.get('/', (req, res) => { res.render('index', { title:"hello", message:"WOW...."}) }); app.get('/user', (req, res) => { res.json(" hello, I'm server.") }); // the url will be e.g http://localhost:5000/user/512 app.get('/user/:id', (req, res) => { let user = users.find( u => u.id == req.params.id) if(!user) return res.status(400).send('user not found') res.send(user) }); // the url will be e.g http://localhost:5000/user/qp/5?parameter1=hello&p2=test // called Query string paramaters app.get('/user/qp/:id', (req, res) => { res.json(req.query) }); app.get('/users/:id', (req, res) => { const schema = Joi.object({ name: Joi.string().min(3).required(), }) let result = schema.validate(req.query) if(result.error) return res.status(400).send(result.error.details[0].message) let newUser = { id: user.length +1, name: req.query.name } users.push(newUser) res.json(newUser) }); const port = process.env.PORT || 5000 app.listen(port, () => { console.log(`the server listen on port ${port}`)})
true
27f0190280193999b5c5cf384920c17afdc6f825
JavaScript
dfala/edq
/app/utils/firebase/classHelpers.js
UTF-8
2,197
2.546875
3
[ "MIT" ]
permissive
var ref = require('../../constants/fbref'); var helpers = require('./helpers'); function addClassToUser(userId, newClassName, role, classId){ var classObj = { isTeacher: false, isMentor: false, isStudent: false, name: newClassName }; role === 'teacher' && (classObj.isTeacher = true); role === 'mentor' && (classObj.isMentor = true); role === 'student' && (classObj.isStudent = true); ref.child(`users/${userId}/classes/${classId}`).set(classObj); }; function removeClassFromUser(userId, classId){ ref.child(`users/${userId}/classes/${classId}`).remove(); }; var classHelpers = { addNewClassToFB(userId, newClassName){ var newClassRef = ref.child('classes').push({name: newClassName}); addClassToUser(userId, newClassName, 'teacher', newClassRef.key()); }, removeClass(userId, classId, cb){ ref.child(`classes/${classId}/students`).once('value', (snapshot) => { var students = snapshot.val(); for(var studentId in students){ ref.child(`users/${studentId}/classes/${classId}`).remove(); } ref.child(`classes/${classId}`).remove(); removeClassFromUser(userId, classId); cb(); }); }, addStudent(user, className, classId){ var classData = { name: className, isTeacher: user.userType === 'teacher' ? true : false, isMentor: user.userType === 'mentor' ? true : false, isStudent: user.userType === 'student' ? true : false, }; helpers.getUserIdWithEmail(user.email, (userId) => { if(userId === -1){ var newUserRef = ref.child('users').push({ firstName: user.firstName, lastName: user.lastName, email: user.email }); userId = newUserRef.key(); newUserRef.child(`classes/${classId}`).set(classData); } else { ref.child(`users/${userId}/classes/${classId}`).set(classData); } ref.child(`classes/${classId}/${user.userType}s/${userId}`).set(user); }); }, removeUser(userId, classId, userType){ ref.child(`classes/${classId}/${userType}s/${userId}`).remove(); ref.child(`users/${userId}/classes/${classId}`).remove(); } }; module.exports = classHelpers;
true
635a27e616a163cd12608f5e65f8fae11f98a15b
JavaScript
kinan92/WepAppMVC1
/WepAppMVC1/Scripts/sokoban.js
UTF-8
4,499
3.203125
3
[ "MIT" ]
permissive
var player = new PlayerPos(-1, -1); document.getElementById("restart").onclick = restart; document.getElementById("randomMap").onclick =randomMap; var goalList=[];// a list function DrawMap() { var map = document.getElementById("mapHeere"); goalList=[]; for (var y = 0; y < 16; y++) { for (var x = 0; x < 19; x++) { var box =document.createElement("div"); if(tileMap.mapGrid[y][x] == "P") //the player { box.classList.add("Space"); box.classList.add("player"); player.y = y; player.x = x; } else if(tileMap.mapGrid[y][x] == "W") //the Wall { box.classList.add("Wall"); } else if(tileMap.mapGrid[y][x] == "B") //the Block { box.classList.add("Block"); box.classList.add("Space"); } else if(tileMap.mapGrid[y][x] == "G") //the Goal { box.classList.add("Goal"); goalList.push(box); } else if(tileMap.mapGrid[y][x] == "R") //the forest { box.classList.add("Goal"); box.classList.add("redBlock"); box.classList.add("Block"); } else // is Space { box.classList.add("Space"); } box.setAttribute("Id", (y + ',' + x)); map.appendChild(box); } } } function PlayerPos(x, y) { this.x = x; this.y = y; } function TheKey(event) { //event.keyCode; console.log(event.keyCode); if(event.keyCode == 37) { event.preventDefault(); console.log("left"); var newPosX = player.x -1; var newPosY = player.y; var newNewPosX= player.x -2; var newNewPosY= player.y; move(newPosX, newPosY, newNewPosX, newNewPosY); } else if(event.keyCode == 39) { event.preventDefault(); console.log("right"); var newPosX = player.x +1; var newPosY = player.y; var newNewPosX= player.x +2; var newNewPosY= player.y; move(newPosX, newPosY, newNewPosX, newNewPosY); } else if(event.keyCode == 38) { event.preventDefault(); console.log("upp"); var newPosX = player.x ; var newPosY = player.y -1; var newNewPosX= player.x ; var newNewPosY= player.y -2; move(newPosX, newPosY, newNewPosX, newNewPosY); } else if(event.keyCode == 40) { event.preventDefault(); console.log("down"); var newPosX = player.x ; var newPosY = player.y +1; var newNewPosX= player.x ; var newNewPosY= player.y +2; move(newPosX, newPosY, newNewPosX, newNewPosY); } } function move(newPosX, newPosY ,newNewPosX ,newNewPosY) { var playerElem = document.getElementById(player.y +"," +player.x); var nextElem = document.getElementById(newPosY + "," + newPosX); var nextNextElem = document.getElementById(newNewPosY + "," + newNewPosX); console.log("nextNextElem"); if(nextElem.classList.contains("Wall")) { console.log("wall"); } else if(nextElem.classList.contains("Block")) { if(nextNextElem.classList.contains("Wall")) { console.log("wall"); } else if(nextNextElem.classList.contains("Block")) { console.log("Block"); } else if(nextElem.classList.contains("forest")) { console.log("forest"); } else if(nextElem.classList.contains("Goal")) { playerElem.classList.remove("player"); nextElem.classList.add("player"); player.x=newPosX; player.y=newPosY; nextElem.classList.remove("Block"); nextNextElem.classList.add("Block"); } else if(nextNextElem.classList.contains("forest")) { console.log("forest"); } else { playerElem.classList.remove("player"); nextElem.classList.add("player"); player.x=newPosX; player.y=newPosY; nextElem.classList.remove("Block"); nextNextElem.classList.add("Block"); } } else { playerElem.classList.remove("player"); nextElem.classList.add("player"); player.x=newPosX; player.y=newPosY; } list(); } function list() { var finichline = true; for (var i=0 ;i< goalList.length ; i++) { if(!goalList[i].classList.contains("Block")) { finichline = false; break; } } if(finichline) { jQuery('#hid').show(); } } function restart() { var clear =document.getElementById("mapHeere"); clear.innerHTML = ""; jQuery('#hid').hide(); DrawMap(); } function randomMap() { var clear =document.getElementById("mapHeere"); clear.innerHTML = ""; tileMap = mapsArray[Math.floor(Math.random() * mapsArray.length)]; DrawMap(); jQuery('#hid').hide(); }
true
1707bfda5e3a0eed0ca1bb4516def678f80e0cfa
JavaScript
Katchau/omoshiroitest
/store/index.js
UTF-8
4,810
2.859375
3
[]
no_license
/* Currency structure id - name - picture - value (chaos worth) */ export const state = () => ({ currency: null, ratio: { id: 1, value: 1, picture: '', name: '' }, items: null, selection: null, searchResults: null, loadingScreen: false, itemInfo: [], statInfo: [] }) export const mutations = { SET_CURRENCY (state, currency) { state.currency = currency }, SET_RATIO (state, ratio) { state.ratio = ratio }, SET_SELECTION (state, page) { state.selection = page }, SET_ITEM (state, items) { state.items = items }, SET_RESULTS (state, results) { state.searchResults = results }, SET_FLIP (state, index) { state.searchResults[index].flipped = !state.searchResults[index].flipped }, SET_LOADING (state, loading) { state.loadingScreen = loading }, SET_ITEM_INFO (state, itemInfo) { state.itemInfo = itemInfo }, SET_STAT_INFO (state, statInfo) { state.statInfo = statInfo } } export const actions = { nuxtServerInit (vuexContext, context) { return context.$axios.get('/getCurrency') .then(({ data }) => { vuexContext.dispatch('setCurrency', data) }) .catch((e) => { vuexContext.commit('SET_SELECTION', 'err') vuexContext.dispatch('setCurrency', []) }) }, setCurrency (vueContext, currency) { const lines = currency.lines || [] if (lines.length === 0) { return } const details = currency.currencyDetails const ret = [] ret.push({ name: 'Chaos Orb', id: 1, value: 1, picture: details[0].icon }) lines.forEach((obj) => { if (obj !== null && obj.receive !== null) { const tmp = {} tmp.name = obj.currencyTypeName tmp.id = obj.receive.get_currency_id // tmp.value = obj.chaosEquivalent tmp.value = obj.receive.value tmp.picture = details[tmp.id - 1].icon ret.push(tmp) } }) vueContext.commit('SET_CURRENCY', ret) vueContext.dispatch('setRatio', ret[0]) }, setRatio ({ commit }, obj) { // obj.value = 1 / obj.value commit('SET_RATIO', obj) }, setSelection ({ commit }, selection) { commit('SET_SELECTION', selection) }, setItems ({ commit }, items) { const lines = items.lines if (lines === undefined) { commit('SET_ITEM', []) return } const ret = [] lines.forEach((obj) => { const tmp = {} tmp.name = obj.name // todo fix this cancer down with the displayName tmp.displayName = (obj.links !== undefined && obj.links !== 0) ? obj.name + ' with ' + obj.links + ' links' : obj.name if (tmp.displayName === tmp.name) { tmp.displayName = (obj.mapTier !== undefined && obj.mapTier !== 0) ? obj.name + ' tier: ' + obj.mapTier : obj.name } tmp.id = obj.id tmp.value = obj.chaosValue tmp.picture = obj.icon tmp.baseType = obj.baseType // having itemType would be nice to identify if it was a item or not but no need for now tmp.usefulInfo = { isRelic: obj.detailsId.includes('-relic'), mapTier: obj.mapTier, gemLvl: obj.gemLevel, gemQlt: obj.gemQuality, variant: obj.variant, links: obj.links, isEssence: obj.name.toLowerCase().includes('essence') } ret.push(tmp) }) commit('SET_ITEM', ret) }, setSearchResults ({ commit }, results) { const ret = [] if (results.result === undefined || results.result.length === 0) { return commit('SET_RESULTS', []) } results.result.forEach((obj) => { const tmp = {} tmp.time = obj.listing.indexed tmp.whisperMsg = obj.listing.whisper tmp.price = obj.listing.price tmp.picture = obj.item.icon tmp.itemDetails = obj.item tmp.flipped = false ret.push(tmp) }) commit('SET_RESULTS', ret) }, changeFlipState ({ commit }, index) { commit('SET_FLIP', index) }, setLoadingScreen ({ commit }, state) { commit('SET_LOADING', state) }, async setItemInfo ({ commit }, $axios) { const { data } = await $axios.get('/fetchItemInfo') commit('SET_ITEM_INFO', data) }, async setStatInfo ({ commit }, $axios) { const { data } = await $axios.get('/fetchStatInfo') commit('SET_STAT_INFO', data) } } export const getters = { searchResults (state) { return state.searchResults }, ratio (state) { return state.ratio }, currency (state) { return state.currency }, items (state) { return state.items }, selection (state) { return state.selection }, loadingScreen (state) { return state.loadingScreen }, itemInfo (state) { return state.itemInfo }, statInfo (state) { return state.statInfo } }
true
dae7835e27e918598bf3b27f511e6502d2bb1a4a
JavaScript
huip/Algorithm
/Code/LeetCode/46.permute.js
UTF-8
604
3.234375
3
[ "MIT" ]
permissive
/** * @param {number[]} nums * @return {number[][]} */ var permute = function (nums) { let res = [] function helper(arr, len, currLen, visited, path) { if (currLen == len) { res.push([...path]) } for (let i = 0; i < len; i++) { if (!visited[i]) { path.push(nums[i]) visited[i] = true helper(arr, len, currLen+1, visited, path) path.pop() visited[i] = false } } } helper(nums, nums.length, 0, {}, []) return res }; permute([1, 2, 3])
true
661f7bf5ced980a12833af1f6edb234d1c7aa069
JavaScript
rinkuagarwal/angulay-typescript
/array.js
UTF-8
536
4.15625
4
[]
no_license
var numbers = [4, 6, -1, 1]; //number //numbers.push('1');/type safety // const sum=numbers.reduce(function(previous,current){ // return previous+current; // }) var sum = numbers.reduce(function (previous, current) { return previous + current; }); console.log(sum); // numbers.sort(function(number1:number, number2:number){ // return number1-number2; // }) // console.log(numbers); //map incresaese the number by 10 var updatedNumbers = numbers.map(function (element) { return element + 10; }); console.log(updatedNumbers);
true
dd09854c83a325025723195a9ca235855bae9d09
JavaScript
ibramaida/e_commerce_clothing
/public/js/search.js
UTF-8
251
2.53125
3
[]
no_license
const searchKey = decodeURI(location.pathname.split("/").pop()) const searchSpanElement = document.querySelector("#search-key") searchSpanElement.innerHTML = searchKey getProducts(searchKey).then(data => createProductCards(data, ".card-container"))
true
2bd1492692a58eb19c1545e9fdfd9a9577868e18
JavaScript
n1re/JavaScriptPractise
/w3resource/Functions/5.everyWordFirstLetterToUpperCase.js
UTF-8
423
3.71875
4
[]
no_license
function everyWordFirstLetterToUpperCase(string) { const words = string.split(' ') for (let i = 0; i < words.length; i++) { let word = words[i] const firstLetter = word[0] const upperCased = firstLetter.toUpperCase() words[i] = word.replace(firstLetter, upperCased) } return words.join(' ') } assert( everyWordFirstLetterToUpperCase('test string') === 'Test String' )
true
61332367e7e679ada143cd9444f74237dc523bb2
JavaScript
Fahrul23/digital-invitation
/src/config/redux/reducer/profileReducer.js
UTF-8
272
2.625
3
[]
no_license
const initialState = { name: 'fahrul' } const profileReducer = (state=initialState,action) =>{ if(action.type === 'UPDATE_NAME'){ return{ ...state, name : 'Fahrul Ihsan' } } return state; } export default profileReducer;
true
5e2ca3f23f523bb274a80db8fd0932bfd87abd9c
JavaScript
Silvana123/SoftUni
/Level 1/03. JavaScript Basics (November 2014)/ExamProblems/ExamProblems/Exam29Jul14/01. PricesTrends.js
UTF-8
822
3.109375
3
[]
no_license
function solve(arr) { console.log('<table>'); console.log('<tr><th>Price</th><th>Trend</th></tr>'); var prev = undefined; for (var i = 0; i < arr.length; i++) { var trend; var rounded = Number(arr[i]).toFixed(2); rounded = Number(rounded); if (i === 0 || rounded === prev) { trend = 'fixed'; } else if (rounded > prev) { trend = 'up'; } else { trend = 'down'; } prev = rounded; console.log('<tr><td>%s</td><td><img src="%s.png"/></td></td>', rounded.toFixed(2), trend); } console.log('</table>'); } //var input = [ // ['50', '60'], // ['36.333', '36.5', '37.019', '35.4', '35', '35.001', '36.225'] //]; //for (var arr in input) { // solve(input[arr]) //}
true
b3fbe6925f5cd7b87d9bae8259cbfe5ea70a100d
JavaScript
mangione77/film-finder
/src/components/App.js
UTF-8
5,359
2.53125
3
[]
no_license
import React, { Component } from 'react' import Main from './Main' import {sendData, generateUrl, getPersonId} from './api' import { Sidebar } from './Sidebar' import './css/App.css' import { Grid, Row, Col } from 'react-bootstrap' class App extends Component { constructor () { super() const newDate = new Date() this.currentYear = newDate.getFullYear() this.state = { filters: { people: [], genres: [], age: '', date: [1895, this.currentYear], sort: 'popularity.desc', page: 1 }, movies: [] } this.updateFilterState = this.updateFilterState.bind(this) this.updateFilterPeople = this.updateFilterPeople.bind(this) this.updateFilterAge = this.updateFilterAge.bind(this) this.updateFilterGenre = this.updateFilterGenre.bind(this) this.updateFilterDate = this.updateFilterDate.bind(this) this.getReset = this.getReset.bind(this) this.deleteFilterPeople = this.deleteFilterPeople.bind(this) this.updateFilterSort = this.updateFilterSort.bind(this) this.deleteFilterGenre = this.deleteFilterGenre.bind(this) this.clearFilterGenre = this.clearFilterGenre.bind(this) this.getNextPage = this.getNextPage.bind(this) } updateFilterState (filter, value) { let filters = Object.assign({}, this.state.filters) filters.page = 1 filters[filter] = value this.setState({filters}, this.getFilteredMovies) } /* GET FILTER VALUES */ updateFilterPeople (value) { if (value.trim().length) { // get id from api getPersonId(value).then(data => { let person if (data.data.results.length) { person = { id: data.data.results[0].id, name: data.data.results[0].name } } else { person = { id: undefined, name: value } } // update state // console.log(this.state.filters.people) this.updateFilterState('people', [...this.state.filters.people, person]) }) } } updateFilterAge (value) { this.updateFilterState('age', value) } updateFilterGenre (value) { this.updateFilterState('genres', [...this.state.filters.genres, value]) } updateFilterDate (value) { this.updateFilterState('date', value) } deleteFilterPeople (value) { var newArray = this.state.filters.people newArray.splice(value, 1) this.updateFilterState('people', newArray) } deleteFilterGenre (value) { let newArray = this.state.filters.genres const pos = newArray.indexOf(value) newArray.splice(pos, 1) this.updateFilterState('genres', newArray) } clearFilterGenre () { this.updateFilterState('genres', []) } updateFilterSort (value) { this.updateFilterState('sort', value) } getReset () { this.setState({ filters: { people: [], genres: [], age: '', date: [1895, this.currentYear], sort: 'popularity.desc', page: 1 } }, this.getFilteredMovies) // console.log('class', document.getElementsByClassName('rc-slider-handle-1')) // document.getElementsByClassName('rc-slider-handle-1')[0].style.left = '0%' // document.getElementsByClassName('rc-slider-handle-2')[0].style.left = '100%' // document.getElementsByClassName('rc-slider-track-1')[0].style.left = '0%' // document.getElementsByClassName('rc-slider-track-1')[0].style.width = '100%' } /* GET FILTERED MOVIES */ getFilteredMovies () { var moviesUrl = generateUrl(this.state.filters) sendData(moviesUrl).then(data => { let valueToSet if (this.state.filters.page > 1) { valueToSet = [...this.state.movies, ...data.data.results] } else { valueToSet = data.data.results let element = document.getElementById('image-container') element.scrollTop = 0 } this.setState({ movies: valueToSet }) }) } /* PAGINATION */ getNextPage () { this.updateFilterState('page', ++this.state.filters.page) } /* COMPONENT METHODS */ componentDidMount () { this.getFilteredMovies() } componentDidUpdate () { // console.log('update', this.state) } render () { return ( <Grid className='fluid background'> <Row className='grid'> <Col className='sideBar' xs={12} md={4}> <Sidebar people={this.state.filters.people} onSubmit={this.updateFilterPeople} onDelete={this.deleteFilterPeople} ageValue={this.state.filters.age} onAgeClick={this.updateFilterAge} date={this.state.filters.date} currentValue={this.updateFilterDate} defaultValue={[1895, this.currentYear]} genreValue={this.state.filters.genres} genreAdd={this.updateFilterGenre} genreDelete={this.deleteFilterGenre} genreClear={this.clearFilterGenre} resetData={this.getReset} /> </Col> <Col className="main" xs={12} md={8}> <Main sortItems={this.updateFilterSort} allMovies={this.state.movies} loadMore={this.getNextPage} /> </Col> </Row> </Grid> ) } } export default App
true
49fc079a86f91e49a7b16af1114b08f4efe05c25
JavaScript
AHeroOfTime/bjs
/playground/modules/scripts.js
UTF-8
457
2.609375
3
[]
no_license
import first, { returnHi as sayHi, last, middle } from './utils.js'; // import wes from './wes.js'; import * as everything from './wes.js'; import { handleButtonClick } from './handlers.js'; // console.log(wes); // console.log(everything); // console.log(first); // const name = 'aaron'; // console.log(sayHi(name)); // console.log(last, middle); const button = document.querySelector('button'); button.addEventListener('click', handleButtonClick);
true
d27f1ea6fa9a25bb60de168bed6d6c945618a3e8
JavaScript
salvatore-trimarchi/js-lista-cognomi
/js/main.js
UTF-8
4,839
2.9375
3
[]
no_license
//###################################################### // // latinitas switch var latinitas = true; // global variables var usrSurnameValue, formErase = false, listErase = false, surnameList = [ 'Bianchi', 'Rossi', 'Duzioni', 'Balsano', 'Verdi', 'Giallini', 'Santamaria', 'Favino', 'Mastandrea', 'Accorsi' ]; // starting list in console console.log('-- original surname list -----------------------'); for (var i = 0; i < surnameList.length; i++) { console.log('#'+(i+1)+' '+surnameList[i]); } // form sources var usrSurnameForm = document.getElementById('usr_surname'); // info display hooks var msgHtml = document.getElementById('msg'); var checkMsgHtml = document.getElementById('check_msg'); var displayResultHtml = document.getElementById('display_result'); var resultListHtml = document.getElementById('result_list'); // button hooks var checkBtn = document.getElementById('check_btn'); var eraseBtn = document.getElementById('erase_btn'); var resumeBtn = document.getElementById('resume_btn'); var insertionBtn = document.getElementById('insertion_btn'); // ** SURNAME CHECK ** checkBtn.addEventListener('click', function() { // form data retrieving usrSurnameValue = usrSurnameForm.value; console.log('usrSurnameValue = ' + usrSurnameValue); // consistency check if (usrSurnameValue == '') { msgHtml.className = 'show'; checkMsgHtml.innerHTML = 'Compila il campo cognome'; } else { // surname check var index = null; for (var i=0; i<surnameList.length; i++) { if (usrSurnameValue.toLowerCase() == surnameList[i].toLowerCase()) index = i; } if (index != null) { // surname already in list: show notice checkMsgHtml.innerHTML = usrSurnameValue+' è già presente in lista'; console.log(usrSurnameValue+' già presente'); formErase = true; } else { // surname not in list: show notice and insertion button checkMsgHtml.innerHTML = usrSurnameValue+' non è presente in lista'; console.log(usrSurnameValue+' non presente'); insertionBtn.className = 'show'; formErase = false; } msgHtml.className = 'show'; } } ); // ** CHECK REDO ** eraseBtn.addEventListener('click', function() { usrSurnameForm.value = ''; } ); // ** CHECK RESUME ** resumeBtn.addEventListener('click', function() { msgHtml.className = 'hide'; checkMsgHtml.innerHTML = ''; insertionBtn.className = 'hide'; if (formErase) usrSurnameForm.value = ''; if (listErase) { displayResultHtml.className = 'hide'; resultListHtml.innerHTML = ''; } } ); // ** SURNAME INSERTION ** insertionBtn.addEventListener('click', function() { // adding surname to list surnameList.push(usrSurnameValue); console.log(usrSurnameValue+' aggiunto') // capitalize list for (var i = 0; i < surnameList.length; i++) { surnameList[i] = surnameList[i][0].toUpperCase() + surnameList[i].substring(1).toLowerCase(); } // sorting capitalized list surnameList.sort(); // surname position & final list content filling console.log('-- new surname list -------------------'); usrSurnameValue = usrSurnameValue[0].toUpperCase() + usrSurnameValue.substring(1) var index = null; for (var i = 0; i < surnameList.length; i++) { console.log('#'+(i+1)+' '+surnameList[i]); var prefix; if (usrSurnameValue == surnameList[i]) { prefix = '<tr class="strong">'; index = i; } else { prefix = '<tr>'; } var pos = (latinitas == true) ? a2l(i+1) : (i+1); resultListHtml.innerHTML += prefix+'<td>'+pos+'</td><td>'+surnameList[i]+'</td><tr>'; } // insertion message insertionBtn.className = 'hide'; var pos = (latinitas == true) ? a2l(index+1) : (index+1); checkMsgHtml.innerHTML = usrSurnameValue+' è stato aggiunto in posizione <span class="strong">'+pos+'</span>'; formErase = true; listErase = true; // show list displayResultHtml.className = 'show'; } ); //###################################################### // LATINITAS function a2l(n) { var r = ''; if (n>3999) r='impossibilis'; else { var m=[1,5,10,50,100,500,1000], d=[0,0,0,2,2,4,4], v=['I','V','X','L','C','D','M']; for(var i=6; i>=0; i--){ while (n>=m[i]) { r=r+v[i]; n=n-m[i]; } if (i>0){ var di=d[i]; if (n>=m[i]-m[di]) { r=r+v[di]+v[i]; n=n-(m[i]-m[di]); } } } } return r; }; //###################################################### //
true
0b0070361ced9374da2b184ae2a85e02b9a2e879
JavaScript
manolomaroto/coursera
/assignment1/app.js
UTF-8
740
2.9375
3
[]
no_license
(function(){ 'use strict'; angular.module('LunchCheck',[]) .controller('LunchCheckController',['$scope',LunchCheckController]); function LunchCheckController($scope){ $scope.lunch = ""; $scope.result =""; $scope.checkIfTooMuch = function(){ var lunchFood = $scope.lunch.split(','); if(lunchFood==""){ $scope.result='Please enter data first'; document.body.style.color = "#f00"; }else if(lunchFood.length<=3){ $scope.result='Enjoy!' document.body.style.color = "#0f0"; }else{ $scope.result='Too much'; } } } })();
true
619fa3b358fefb520d8f8ab447c1673d39bcb3f6
JavaScript
derekdg/Stock-Data-jQM-1.1
/js/myQuote.js
UTF-8
3,480
2.546875
3
[]
no_license
var myQuote = { yqlURL: "http://query.yahooapis.com/v1/public/yql?q=", dataFormat: "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys", symbol: "", stockStats: "", init: function() { //Sumbit click handler: $("#submit").click(function() { //Get the ticker from the form: myQuote.symbol = $("#ticker").val(); //Get the stock data from YQL, return a jQuery Deferred: var $d = myQuote.getStockData(); //After retrieving the JSON data, populate the list view: $d.success( function (json, textStatus, jqXHR) { //Build the <li> items for the listview: var ulist = myQuote.buildStats(json); //Reload the listview: myQuote.populateListview(ulist); } ); }); }, getStockData: function() { //Build the URL to pass to YQL: var realtimeQ = myQuote.yqlURL+"select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + myQuote.symbol + "%22)%0A%09%09&"+ myQuote.dataFormat; //Using a jQuery Deferred object, get the json data: var $defer = $.ajax({ url : realtimeQ, data : '{}', dataType: 'json' }).success(function (json, textStatus, jqXHR) { }).error(function () { alert('ERROR!'); }); //Return the jQuery deferred obj: return $defer; }, buildStats: function(json) { var o = json.query.results.quote; var list = $('<ul/>').attr({ 'data-role': 'listview', 'data-inset': 'true', 'id': 'myKeyStatsList', 'data-divider-theme': 'f', 'data-theme': 'f' }); list.append("<li data-role='list-divider'>Stock Data</li>"); list.append("<li>" + o.Name + " (" + o.StockExchange + ":" + o.Symbol + ")</li>"); list.append("<li>Ask Price <span class='ui-li-count'>$" + valueOrDefault(o.AskRealtime,0) + "</span></li>"); list.append("<li data-role='list-divider'>Dividend Data</li>"); list.append("<li>Dividend Yield <span class='ui-li-count'>" + valueOrDefault(o.DividendYield, 0) + "%</span></li>"); list.append("<li>Dividend per Share <span class='ui-li-count'>$" + valueOrDefault(o.DividendShare) + "</span></li>"); list.append("<li>Ex-Dividend Date <span class='ui-li-count'>" + valueOrDefault(o.ExDividendDate) + "</span></li>"); list.append("<li>Dividend Pay Date <span class='ui-li-count'>" + valueOrDefault(o.DividendPayDate) + "</span></li>"); list.append("<li data-role='list-divider'>Ratios</li> "); list.append("<li>EPS <span class='ui-li-count'>" + valueOrDefault(o.EarningsShare) + "</span></li>"); list.append("<li>EBITDA <span class='ui-li-count'>" + valueOrDefault(o.EBITDA) + "</span></li>"); list.append("<li>Price/Sales <span class='ui-li-count'>" + valueOrDefault(o.PriceSales) + "</span></li>"); list.append("<li>Price/Book <span class='ui-li-count'>" + valueOrDefault(o.PriceBook) + "</span></li>"); list.append("<li>Price/Earnings <span class='ui-li-count'>" + valueOrDefault(o.PERatio) + "</span></li>"); list.append("<li>PEG <span class='ui-li-count'>" + valueOrDefault(o.PEGRatio) + "</span></li>"); list.append("<li>Short <span class='ui-li-count'>" + valueOrDefault(o.ShortRatio) + "</span></li>"); return list; }, populateListview: function(list) { //Reload the listview: $("#divStatsList").empty(); list.appendTo($("#divStatsList")).listview(); } } //END: myQuote //Function to return a blank if a value is null. function valueOrDefault(val, def) { if (def == undefined) def = "N/A"; return val == undefined ? def : val; }
true
d8bcc05ca7550ad081e33eaa502f4f2d8da7e599
JavaScript
xu-126/qt_lesson
/leetcode/lru/index.js
UTF-8
2,168
3.046875
3
[]
no_license
<<<<<<< HEAD /** * 最近最少使用原则 * @param capacity:number 容量 */ var LRUCache = function(capacity){ this.capacity = capacity;//空间的上限 this.arr = [];//数据结构 this.obj = {};// 3,3 // 使用的空间 arr.length // set push // get }; LRUCache.prototype.get = function(key){ //调整优先级 if(arr.length<this.capacity){ arr.shift(key); arr.push(key); return obj(key); }else{ return -1; } } LRUCache.prototype.set = function(key,value){ if(arr.length<this.capacity){ arr.push(key,value); }else{ arr.shift(); arr.push(key,value); } } new LRUCache(2); // [] length push // [1] push // [1,2] 在哪端是最常用的?push // get(1) 读操作 // 1所在的位置,从原来的数组里移除push到队尾 // 不会带来空间使用量的增加 // [2,1] // put [3]带来空间的分配,回收空间? // 判断数组的 length>=容量 要 回收最前面 shift push ======= /** * 最近最少使用原则 * @param capacity:number 容量 */ var LRUCache = function(capacity){ this.capacity = capacity;//空间的上限 this.arr = [];//数据结构 this.obj = {};// 3,3 // 使用的空间 arr.length // set push // get }; LRUCache.prototype.get = function(key){ //调整优先级 if(arr.length<this.capacity){ arr.shift(key); arr.push(key); return obj(key); }else{ return -1; } } LRUCache.prototype.set = function(key,value){ if(arr.length<this.capacity){ arr.push(key,value); }else{ arr.shift(); arr.push(key,value); } } new LRUCache(2); // [] length push // [1] push // [1,2] 在哪端是最常用的?push // get(1) 读操作 // 1所在的位置,从原来的数组里移除push到队尾 // 不会带来空间使用量的增加 // [2,1] // put [3]带来空间的分配,回收空间? // 判断数组的 length>=容量 要 回收最前面 shift push >>>>>>> 5145978b61313a82b79a4143eb066a8ebb09ac17 // length<容量 不要 push push(3)
true
2e413f37c242f56bfa9c1e18526422c1c30a78f6
JavaScript
emiliawanat/playlist
/app.js
UTF-8
826
2.84375
3
[]
no_license
var playlist = new Playlist(); var chandelier = new Song("Chandelier", "Sia", "3:36"); var chicago = new Song("Chicago", "Sufjan Stevens", "6:05"); var boyhood = new Movie("Boyhood", 2014, "2:45:00"); playlist.add(chandelier); playlist.add(chicago); playlist.add(boyhood); var playlistElement = document.getElementById("playlist"); playlist.renderInElement(playlistElement); var playButton = document.getElementById("play"); playButton.onclick = function () { playlist.play(); playlist.renderInElement(playlistElement); } var nextButton = document.getElementById("next"); nextButton.onclick = function () { playlist.next(); playlist.renderInElement(playlistElement); } var stopButton = document.getElementById("stop"); stopButton.onclick = function () { playlist.stop(); playlist.renderInElement(playlistElement); }
true
471f2fae9f9a3f3035278d10a3284e61a7582f60
JavaScript
vivcis/Maniera-fe-pjt-51
/javascript/sign-in.js
UTF-8
1,372
2.53125
3
[]
no_license
const form = document.getElementById('form'); const email = document.getElementById('email'); const password = document.getElementById('password'); const BASE_URL = 'https://maniera-dev.herokuapp.com/api/'; //----signin loader--- const loading = document.getElementById('loading'); loading.style.display = 'none'; form.addEventListener('submit', async e => { e.preventDefault(); loading.style.display = 'block'; let response = await axios.post(`${BASE_URL}auth/signin`, { email: email.value, password: password.value }) localStorage.setItem('token', response.data.token); loading.style.display = 'none'; }) // google signin function onSignIn(googleUser) { var profile = googleUser.getBasicProfile(); console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead. console.log('Name: ' + profile.getName()); console.log('Image URL: ' + profile.getImageUrl()); console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present. } // facebook login function facebookLogin() { FB.login((response) => { console.log(response) }) } window.fbAsyncInit = function() { FB.init({ appId : '143288521228126', autoLogAppEvents : true, xfbml : true, version : 'v11.0' }); };
true
1d664aad1c7c7fd849efefbbc0b927b393b51535
JavaScript
ilonabudapesti/yi-summer-2015
/03 functional-js/underscore-rewrite/src/myUnderbar.js
UTF-8
4,293
2.96875
3
[]
no_license
(function() { 'use strict'; window._ = {}; _.identity = function(val) { return val; }; /** * COLLECTIONS * =========== */ _.first = function(array, n) { return n === undefined ? array[0] : array.slice(0, n); }; _.last = function(array, n) { if (n === undefined) { return array[array.length-1]; } else { return array.slice(Math.max(0, array.length-n)); } }; _.each = function(collection, fun) { if ( Array.isArray(collection) ) { for (var i = 0; i < collection.length; i++) { fun(collection[i], i, collection); } } else { for (var i in collection) { fun(collection[i], i, collection); } } }; _.indexOf = function(array, target){ var result = -1; _.each(array, function(item, index) { if (item === target && result === -1) { result = index; } }); return result; }; _.filter = function(collection, test) { }; _.reject = function(collection, test) { // show }; // _.uniq = function(list) { // var result = []; // checkEachElement: for (var i = 0; i < list.length; i++) { // for (var k = 0; k < result.length; k++) { // if ( list[i] === result[k] ) continue checkEachElement; // } // result.push( list[i] ); // } // return result; // }; // _.uniq = function (arr) { // var existingValues = {}; // var result = []; // var containsUndefined = false; // _.each(arr, function (item) { // var type = typeof item; // // Initialize to {} // if ( existingValues[item] === undefined ) { // existingValues[item] = {}; // } // // Handle all cases but undefined, checking type // if ( item !== undefined && // ( existingValues[item][type] === undefined ) || // existingValues[item][type] !== item ) { // existingValues[item][type] = item; // result.push(item); // } // // Handle undefined // if ( item === undefined && containsUndefined === false ) { // result.push(item); // containsUndefined = true; // } // }); // return result; // } _.uniq = function(array) { var hash = {}; _.each(array, function(val) { hash[val] = val; }); return _.map(hash, function(value) { return value; }); } _.map = function(collection, iterator) { var result = []; _.each(collection, function(item, index, collection){ result.push(iterator(item, index, collection)); }); return result; }; _.pluck = function(collection, key) { return _.map(collection, function(item){ return item[key]; }); }; _.reduce = function(collection, iterator, accumulator) { }; _.contains = function(collection, target) { return _.reduce(collection, function(wasFound, item) { if (wasFound) { return true; } return item === target; }, false); }; _.every = function(collection, iterator) { }; _.some = function(collection, iterator) { }; // stop here /** * OBJECTS * ======= */ _.extend = function(obj) { }; _.defaults = function(obj) { }; /** * FUNCTIONS * ========= */ _.once = function(func) { var alreadyCalled = false; var result; return function() { if (!alreadyCalled) { result = func.apply(this, arguments); alreadyCalled = true; } return result; }; }; _.memoize = function(func) { }; _.delay = function(func, wait) { }; /** * ADVANCED COLLECTION OPERATIONS * ============================== */ _.shuffle = function(array) { }; /** * EXTRA CREDIT * ================= */ _.invoke = function(collection, functionOrKey, args) { }; _.sortBy = function(collection, iterator) { }; _.zip = function() { }; _.flatten = function(nestedArray, result) { }; _.intersection = function() { }; _.difference = function(array) { }; _.throttle = function(func, wait) { }; }());
true
05141a3c4256bae57c85aa6a7f2b75ace220e59c
JavaScript
MohamedSaidMuse/BudgetApp-usingReact.js
/src/Components/Chart/Chart.js
UTF-8
605
2.8125
3
[]
no_license
import ChartBar from './ChartBar'; import './Chart.css' const Chart = (props) => { const dataPointValues =props. dataPoints.map(dataPoint => dataPoint.value); // the above code will return an array of values // the spread opetator below here is to pull out the ... array elemnets and add them as stand lone arguments const totalMaximum =Math.max(...dataPointValues); return (<div className ="chart"> {props.dataPoints.map((dataPoint) => (<ChartBar key ={dataPoint.label} value ={dataPoint.value} maxValue ={totalMaximum} label ={dataPoint.label}/>))} </div> ); }; export default Chart;
true
d51ed3c273450ce6f24771cc4f03ae19eff8c35d
JavaScript
RaviPatel1713/data-structures-javascript
/exercises/mini-projects-challenges/telephone_number_validator.js
UTF-8
3,010
3.796875
4
[]
no_license
function telephoneCheck(str) { str = str.trim(); let invalidCharRegex = /[^0-9\s-()]/g; let invalidLength = (arg) => arg.length < 10 || arg.length > 16; let invalidNumberCount = (arg) => { let numberCount = (arg.match(/\d/g) || []).length; return numberCount !== 10 && numberCount !== 11; }; let invalidParenthesisUse = (arg) => { arg = arg.trim(); let openingParentCount = (arg.match(/\(/g) || []).length; let closingParentCount = (arg.match(/\)/g) || []).length; if (openingParentCount === 0 && closingParentCount === 0) { return false; // valid parenthesis usage } else if (openingParentCount === 1 && closingParentCount === 1) { // returns invalidity if the number count inside the parenthesis is not 3 (for area code) return arg.indexOf(')') - arg.indexOf('(') - 1 !== 3; } return true; }; if (invalidCharRegex.test(str.trim())) { console.log("invalid char regex"); return false; } if (invalidLength(str)) { console.log("invalid length"); return false; } if (invalidNumberCount(str)) { console.log("invalid number count"); return false; } let numberCount = (str.match(/\d/g) || []).length; if (numberCount === 11) { if (parseInt(str[0]) !== 1) { console.log("not 1") return false; } str = str.slice(1); } if (invalidParenthesisUse(str)) return false; return true; } //____________ALTERNATE SOLUTION_______________ /* function telephoneCheck(str) { str = str.trim(); let invalidCharRegex = /[^0-9\s-()]/g; let invalidLength = (arg) => arg.length < 10 || arg.length > 16; let invalidParenthesisUse = (arg) => { arg = arg.trim(); let openingParentCount = (arg.match(/\(/g) || []).length; let closingParentCount = (arg.match(/\)/g) || []).length; if (openingParentCount === 0 && closingParentCount === 0) { return false; // valid parenthesis usage } else if (openingParentCount === 1 && closingParentCount === 1) { // returns invalid if the number count b/w the parenthesis is not 3 (for area code) return arg.indexOf(')') - arg.indexOf('(') - 1 !== 3; } return true; }; if (invalidCharRegex.test(str.trim()) || invalidLength(str)) { return false; } // the block validates that the country code is 1 with 11 telephone digits // and removes the country code from telephone id if ((str.match(/\d/g) || []).length === 11) { let countryCode = parseInt(str.split().splice(0, 1).join()); console.log(countryCode); if (countryCode !== 1) { return false; } } // executed at the very end b/c checks the 10 digits telephone id without countrycode if (invalidParenthesisUse(str)) return false; return true; } */
true
9ce26304521a8ee7bcb22bf3f212ccb2fd5f85ab
JavaScript
ByjusAbi/carritos
/player.js
UTF-8
753
2.6875
3
[]
no_license
class Player { constructor(){ this.index=null; this.distancia=0; this.nombre=null; } getCount(){ var playerCountRef = database.ref('playerCount'); playerCountRef.on("value",function(data){ playerCount = data.val(); }) } updateCount(count){ database.ref('/').update({ playerCount: count }); } update(name){ var playerIndex = "players/player" + this.index; database.ref(playerIndex).set({ name:this.nombre , distancia:this.distancia }); } static infoJugadores(){ var jugadoresInfo=database.ref('players'); jugadoresInfo.on("value",(data)=>{datosJugadores=data.val();}) } }
true
b5a4e09f93476fa65dd09ac79eed5bf6b53fd81d
JavaScript
SandorDavid/codecoolchat
/src/main/resources/static/script/login.js
UTF-8
2,284
2.625
3
[]
no_license
$(function () { function postRegistrationData(event) { let validInput = true; $.each($('#registrationForm').serializeArray(), function (index, inputField) { if(inputField.value == "" && validInput == true){ $("#loginError").html("&nbsp;"); $("#registrationError").html(inputField.name + " is empty"); $("#registrationForm :Password").val(""); validInput = false; } }); event.preventDefault(event); if(validInput == true) { $.ajax({ type: "POST", url: "/user/registration", data: $('#registrationForm').serialize(), success: response => { window.location.replace(response.redirect); }, error: response => { $("#loginError").html("&nbsp;"); $("#registrationError :Password").val(""); $("#registrationError").text(response.responseJSON.response); } }); } } $('#registrationButton').click(postRegistrationData); function postLoginData(event) { let validInput = true; $.each($('#loginForm').serializeArray(), function (index, inputField) { if(inputField.value == "" && validInput == true){ $("#registrationError").html("&nbsp;"); $("#loginError").html(inputField.name + " is empty"); $('#loginForm :Password').val(""); validInput = false; } }); event.preventDefault(event); if(validInput == true) { $.ajax({ type: "POST", url: "/user/login", data: $('#loginForm').serialize(), success: response => { window.location.replace(response.redirect); }, error: response => { $("#registrationError").html("&nbsp;"); $("#loginError").text(response.responseJSON.response); $('#loginForm :Password').val(""); } }); } } $('#loginButton').click(postLoginData); });
true
527e7270e6453636b63c9e282f41db6f111971f3
JavaScript
kykyxDD/biblioGlobus-fligths
/src/js/nav.js
UTF-8
6,912
2.75
3
[]
no_license
!function() { var nextFrame = window. requestAnimationFrame || window. oRequestAnimationFrame || window. msRequestAnimationFrame || window. mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(cb) { return setTimeout(cb, 17, +new Date +17) } function loop(time) { if(navigation.glide) { navigation.timer = nextFrame(loop) navigation.glideMove() } else delete navigation.timer } function V (x, y) { return new Vector(x, y) } function Vector(x, y) { this.x = x; this.y = y } Vector.prototype = { constructor: Vector, get length() { return Math.sqrt(this.x * this.x + this.y * this.y) }, vsub:function(v){return new Vector(this.x - v.x,this.y - v.y)}, vadd:function(v){return new Vector(this.x + v.x,this.y + v.y)}, vdiv:function(v){return new Vector(this.x / v.x,this.y / v.y)}, vmul:function(v){return new Vector(this.x * v.x,this.y * v.y)}, ssub:function(v){return new Vector(this.x - v ,this.y - v )}, sadd:function(v){return new Vector(this.x + v ,this.y + v )}, sdiv:function(v){return new Vector(this.x / v ,this.y / v )}, smul:function(v){return new Vector(this.x * v ,this.y * v )}, vrot:function(v){return new Vector( this.x * v.x + this.y * v.y, -this.x * v.y + this.y * v.x) }, srot:function(v){return new Vector( this.x * Math.cos(v) - this.y * Math.sin(v), this.x * Math.sin(v) + this.y * Math.cos(v)) }, sub:function(v){return v instanceof Vector?this.vsub(v):this.ssub(v)}, add:function(v){return v instanceof Vector?this.vadd(v):this.sadd(v)}, div:function(v){return v instanceof Vector?this.vdiv(v):this.sdiv(v)}, mul:function(v){return v instanceof Vector?this.vmul(v):this.smul(v)}, rot:function(v){return v instanceof Vector?this.vrot(v):this.srot(v)}, sum:function(){return this.x + this.y}, toString:function(){return '('+ this.x +','+ this.y +')'} } window.navigation = { position : V(0.4, 0.6), min : V(0, 0), max : V(1, 1), axis : V(1, 0), accel : 0.92, reset : 300, weight : 50, frames : [], addFrame: function(size) { var frame = new FrameOfReference() frame.dimension = V(size[0], size[1]) this.frames.push(frame) return frame }, _resize: function(size) { this.size = size this.offset = size.div(2).length this.position = this._bound(this.position) this.frames.some(function(frame) { frame._resize(this.size) frame._set(this.position) }, this) }, glideStart: function(drag) { var duration = Date.now() - drag.start, vector = this.position.sub(drag.position), momentum = vector.div(duration).mul(this.weight) if(duration && duration < this.reset) this._glide(momentum) }, glideMove: function() { var mspf = 1000 / 60, passed = Date.now() - this.glide.start, frame = passed / mspf, accel = this.table[frame |0] + Math.pow(this.accel, frame), delta = this.glide.momentum.mul(accel) if(frame >= this.table.length || delta.length < 1e-4) { delete this.glide } else { this.move(this.glide.position.add(delta)) } }, _glide: function(momentum) { this.glide = { start : Date.now(), position : this.position, momentum : momentum } if(!this.timer) this.timer = nextFrame(loop) }, setAcceleration: function(precision) { this.table = [] for(var i = 0, sum = 0; i < precision; i++) { this.table[i] = sum += Math.pow(this.accel, i) } this.accelPrecisionLimit = this.table[this.table.length - 1] }, _bound: function(position) { var point = position.rot(this.axis), offset = V(0, 1).mul(this.offset), invert = V(this.axis.x, -this.axis.y), max = this.max.sub(offset), min = this.min.add(offset), x = Math.min(max.x, Math.max(min.x, point.x)), y = Math.min(max.y, Math.max(min.y, point.y)) if(y < min.y || y > max.y) { y = (min.y + max.y) / 2 } return V(x, y).rot(invert) }, move: function(position, timed) { var bounded = this._bound(position), delta = bounded.sub(this.position) if(timed) { this._glide(delta.div(this.accelPrecisionLimit)) } else { this.position = bounded this.frames.some(function(frame) { frame._set(bounded) }) } } } navigation.setAcceleration(150) function FrameOfReference() { } FrameOfReference.prototype = { scaleMax: 2, scaleMin: 1, scale : 1, move: function(x, y, timed) { delete navigation.glide navigation.move(V(x, y).mul(this.scale).div(this.dimension), timed) }, grip: function(x, y) { delete navigation.glide this.drag = { start : Date.now(), position : navigation.position, point : V(x, y) } }, pull: function(x, y, opposite) { if(this.drag) { var vector = V(x, y).sub(this.drag.point), normal = vector.div(this.dimension), position = opposite ? this.drag.position.sub(normal) : this.drag.position.add(normal) navigation.move(position) if(Date.now() - this.drag.start > navigation.reset) this.grip(x, y) // mousemove will go postal with // } else this.grip(x, y) } }, free: function(x, y, glide) { if(this.drag) { glide && navigation.glideStart(this.drag) delete this.drag } }, capture: function(x1, y1, x2, y2) { delete this.drag var point1 = V(x1, y1), point2 = V(x2, y2) this.lastScale = this.scale this.length = point2.sub(point1).length }, stretch: function(x1, y1, x2, y2) { var point1 = V(x1, y1), point2 = V(x2, y2), length = point2.sub(point1).length this.zoom(this.lastScale * length / this.length) }, release: function(x1, y1, x2, y2) { this.grip(x1, y1) }, zoom: function(scale) { scale = Math.max(this.scaleMin, Math.min(this.scaleMax, scale)) this.dimension = this.dimension.div(this.scale).mul(scale) this.scale = scale navigation._resize(this.size.div(this.dimension)) this._set(navigation.position) }, resize: function(width, height) { navigation._resize(V(width, height).div(this.dimension), this) }, bounds: function(point1, point2, thickness) { var control1 = V(point1[0], point1[1]).div(this.dimension), control2 = V(point2[0], point2[1]).div(this.dimension), segment = control2.sub(control1), axis = segment.div(segment.length), height = V(0, 0.5).mul(thickness).div(this.dimension), limit1 = control1.rot(axis).sub(height), limit2 = control2.rot(axis).add(height) navigation.axis = axis navigation.min = V(Math.min(limit1.x, limit2.x), Math.min(limit1.y, limit2.y)) navigation.max = V(Math.max(limit1.x, limit2.x), Math.max(limit1.y, limit2.y)) }, updatePosition: function(x, y) {}, updateSize : function(w, h) {}, _resize: function(size) { this.size = size.mul(this.dimension) this.updateSize(this.size.x, this.size.y) }, _set: function(position) { this.position = position.mul(this.dimension) this.center = this.position.sub(this.size.div(2)) this.updatePosition(this.center.x, this.center.y, this.scale) } } }()
true
3e52459efccaede400ed0e6fe4a730f8087031b2
JavaScript
kikardo/contador_de_cliques
/src/estados.js
UTF-8
511
2.71875
3
[]
no_license
import React, {Component} from 'react'; class Botao extends Component { state={vezesPressionado:0} handleButtonPress = () => { const vezesPressionado = this.state.vezesPressionado + 1; this.setState({vezesPressionado})} render() { return( <div> <span> Fui pressionado: {this.state.vezesPressionado} vezes <br/></span> <button className="App-button" variant="info" onClick={this.handleButtonPress}> Clique Aqui!</button> </div> ) } } export default Botao;
true
c3a9199595e367103b5e90db4877f6a5f60f820e
JavaScript
eugenekhristo/react-fundamentals-github-battle
/app/components/Battle.jsx
UTF-8
3,811
2.515625
3
[]
no_license
import React, { Component, Fragment } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; class BattleInput extends Component { state = { username: '' }; handleChange = e => this.setState({ username: e.target.value.trim().toLowerCase() }); handleSubmit = e => { e.preventDefault(); const { onSubmit, id } = this.props; const { username } = this.state; onSubmit(id, username); }; render() { const { username } = this.state; const { label, id } = this.props; return ( <form className="column battle-input" onSubmit={this.handleSubmit}> <label className="battle-input__label" htmlFor={id}> {label} </label> <input type="text" id={id} placeholder="github username" autoComplete="off" className="battle-input__input" value={username} onChange={this.handleChange} /> <button type="submit" className="button"> Submit </button> </form> ); } } BattleInput.propTypes = { label: PropTypes.string.isRequired, id: PropTypes.string.isRequired, onSubmit: PropTypes.func.isRequired }; const PlayerPreview = ({ imageUrl, username, id, onReset }) => { return ( <div className="player-preview column"> <img src={imageUrl} alt="Avatar" className="player-preview__img" /> <h2 className="player-preview__username">@{username}</h2> <button className="player-preview__reset" onClick={() => onReset(id)}> Reset </button> </div> ); }; PlayerPreview.propTypes = { imageUrl: PropTypes.string.isRequired, username: PropTypes.string.isRequired, id: PropTypes.string.isRequired, onReset: PropTypes.func.isRequired }; class Battle extends Component { state = { playerOneName: '', playerTwoName: '', playerOneImage: null, playerTwoImage: null }; handleSubmit = (id, username) => { const newState = {}; newState[`${id}Name`] = username; newState[`${id}Image`] = `https://github.com/${username}.png?size=200`; this.setState(newState); }; handleReset = id => { const newState = {}; newState[`${id}Name`] = ''; newState[`${id}Image`] = null; this.setState(newState); }; render() { const { playerOneImage, playerOneName, playerTwoImage, playerTwoName } = this.state; return ( <Fragment> <div className="row"> {!playerOneName && ( <BattleInput label="Player One" id="playerOne" onSubmit={this.handleSubmit} /> )} {playerOneImage !== null && ( <PlayerPreview id="playerOne" username={playerOneName} imageUrl={playerOneImage} onReset={this.handleReset} /> )} {!playerTwoName && ( <BattleInput label="Player Two" id="playerTwo" onSubmit={this.handleSubmit} /> )} {playerTwoImage !== null && ( <PlayerPreview id="playerTwo" username={playerTwoName} imageUrl={playerTwoImage} onReset={this.handleReset} /> )} </div> {playerOneName && playerTwoName && ( <Link className="button" style={{ cursor: 'pointer' }} to={{ pathname: `${this.props.match.url}/results`, search: `playerOneName=${playerOneName}$playerTwoName=${playerTwoName}` }} > Battle </Link> )} </Fragment> ); } } export default Battle;
true
dba45834572272be73881c51584afef9246b5d4e
JavaScript
Raj-Sanjay-Shah/ai-games-research
/koboldai/koboldai-scenarios/src/javaman-scenarios/javaman-scenarios.js
UTF-8
1,441
2.5625
3
[]
no_license
const rl = require('readline-sync'); const menu = require('../app/menu.js'); const katariah = require('./katariah/katariah.js'); // const tamrielGen = require('./tamriel-gen.js'); // const advCall = require('./adventure-call.js'); let message; let menuOptions = [ { text: `Back`, execute: () => { menu.showMenu("Back from javaman's scenarios selection."); } }, { text: `Adventure Call with Falconhoof (not implemented yet)`, execute: () => { } }, { text: `Tamriel: the Reign of Katariah`, execute: () => { katariah.execute(); } }, { text: `Tamriel: Character Generators (not implemented yet)`, execute: () => { } }, ] const printMenu = () => { console.clear(); console.log(message ? `Message: ${message}` : ''); console.log(`========================= SELECT A SCENARIO =========================`); menuOptions.forEach((menuOption, i) => console.log(`${i}. ${menuOption.text}`)); console.log(`=====================================================================`); return rl.question(`Choose an option: `); } const execute = () => { let option; while (!option) { option = printMenu(); if (!option) { message = "Please choose an option."; execute(); } else if (option != "0") { menuOptions[option].execute(); } } menu.showMenu("Back from javaman's scenarios selection."); } module.exports.execute = execute;
true
8b081e6cce87c555868a5af32d079bd5bb151f3e
JavaScript
tomasfrancizco/pomodoro
/script.js
UTF-8
2,347
3.09375
3
[]
no_license
const timer = document.getElementById("timer"); const startButton = document.getElementById("start-button"); const pauseButton = document.getElementById("pause-button"); const clearButton = document.getElementById("clear-button"); const newTimeInput = document.getElementById("set-time-input"); const newTimeForm = document.getElementById("set-time-form") const newTimeButton = document.getElementById("set-time-button") const audio = new Audio("./purge.mp3"); const bar = document.getElementById("progress-bar"); newTimeForm.addEventListener("submit", newTimeSubmit) let newTime = 1500; let isPaused = false; let interval; let current = 0; let count = newTime - current; function newTimeSubmit(event){ event.preventDefault() if(newTimeInput.value > 99 || newTimeInput.value < 1){ return } else { newTime = (newTimeInput.value * 60) count = newTime - current } newTimeInput.value = "" return timer.innerHTML = printClock(newTime); } function start() { isPaused = false; startButton.disabled = true; pauseButton.disabled = false; newTimeButton.disabled = true; interval = setInterval(() => { if (!isPaused && count > 0) { count--; progress() timer.innerHTML = printClock(count); } if (count == 0) { audio.play(); } }, 1000); } const printClock = num => { return `${ Math.floor(num / 60) < 10 ? "0" + Math.floor(num / 60) : Math.floor(num / 60) }:${ Math.floor(num % 60) < 10 ? "0" + Math.floor(num % 60) : Math.floor(num % 60) }` } function pause() { isPaused = true; clearInterval(interval); current = count; startButton.disabled = false; pauseButton.disabled = true; } function progress() { if(current == 0){ current = 1; let width = 1; const id = setInterval(frame, newTime * 10); function frame() { if (width >= 100 || isPaused == true) { clearInterval(id); current = 0; } else { width++; bar.style.width = width + "%"; } } } } function clearAll() { clearInterval(interval); count = 1500; current = 0; newTime = 1500; isPaused = true; timer.innerHTML = "25:00"; audio.pause(); audio.currentTime = 0; bar.style.width = 0; startButton.disabled = false; pauseButton.disabled = true; newTimeButton.disabled = false; }
true
a44e18fe6842f7d93989f85a2eeaba50a68b7ef1
JavaScript
azukaar/blossom-js
/modules/serialise.js
UTF-8
3,386
2.96875
3
[]
no_license
import { contextTrap } from './ctx'; import { BlossomProxyElement } from './convertElement'; function subSerialise(element) { if (element === null) { return null; } else if (typeof element === 'boolean') { return element; } else if (typeof element === 'function') { return element.toString(); } else if (typeof element === 'object' && element instanceof Array) { return element.map(entry => subSerialise(entry)); } else if (typeof element === 'object') { const result = {}; Object.entries(element).map((entry) => { result[entry[0]] = subSerialise(entry[1]); return entry; }); return result; } else if (typeof element === 'number') return element; return element; } function serialise(element) { const result = subSerialise(element); if (typeof result !== 'string') { return JSON.stringify(result); } return result.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;'); } function deserialise(unescapedElement, bindTo) { let element = unescapedElement; if (element === null) { return null; } if (typeof element === 'string') { element = element.replace(/&amp;/g, '&') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&quot;/g, '"'); } if (element === 'true') return true; else if (element === 'false') return false; else if (typeof element === 'boolean') return element; else if (element.match && element.match(/^{/) && element.match(/}$/)) { let result; try { result = JSON.parse(element); } catch (e) { return element; } Object.entries(result).map((entry) => { result[entry[0]] = deserialise(entry[1], bindTo); return entry; }); return result; } else if (element.match && element.match(/^\[/) && element.match(/\]$/)) { let result; try { result = JSON.parse(element); } catch (e) { return element; } result = result.map(entry => deserialise(entry, bindTo)); return result; } else if (element.match && (element.match(/^\s*function\s*\(/) || (element.match(/^\(/) && element.match(/=>/)))) { let tostring = element.slice(); if (!tostring.match(/^\s*function/)) { tostring = `(function${tostring}`; if (tostring.match(/=>\s+{/)) { tostring = tostring.replace(/=>\s+{/, '{'); tostring += ')'; } else { tostring = tostring.replace('=>', '{return '); tostring += '})'; } } else { tostring = `(${tostring})`; } if (bindTo) { const input = eval(tostring); const func = (...args) => contextTrap(bindTo, input.bind(BlossomProxyElement(bindTo)), args); func.toString = () => input.toString(); return func; } return eval(tostring); } else if (typeof element === 'object' && element instanceof Array) { return element.map(entry => deserialise(entry, bindTo)); } else if (typeof element === 'object') { const result = {}; Object.entries(element).map((entry) => { result[entry[0]] = deserialise(entry[1], bindTo); return entry; }); return result; } else if (element === '') { return ''; // eslint-disable-next-line no-restricted-globals } else if (!isNaN(element)) { return Number(element); } return element; } export { serialise, deserialise };
true
a49e102fd3f4b22be0b3ed9cb8d04b7fe39e83cc
JavaScript
huutu289/Javascript-selfStudy
/JAVASCRIPT/Phần 8 - ECMAScript 6+/3.arrow-function.js
UTF-8
1,805
5.0625
5
[]
no_license
/* --viết ngắn gọn hơn */ const arrowFunction = (log) => { console.log(log); } arrowFunction('arrow function: '); //-nếu return trên 1 dòng,có thể viết như sau const sum = (a, b) => { return a + b; } console.log('viết bình thường: ', sum(2, 3)); //viết gọn, k cần từ khóa return const sum1 = (a, b) => a + b; console.log('viết gọn ko cần từ khóa return: ', sum1(3, 3)); //return 1 object, để trong dấu ngoặc tròn const returnObject = (a, b) => ({ a: a, b: b }) console.log('return 1 object: ', returnObject(1, 3)); //nếu có 1 đối số const return1Argument = (log) => { console.log(log) } //có thể viết lại như sau const return1Argument2 = log => console.log(log); //--đặc tính của Arrow function: //-ko có context //- ko thể sử dụng để làm object constructor //---------------ko có context------------ //ví dụ 1: sử dụng khai báo thông thường, dùng từ khóa this ok. const course = { name: 'JavaScript', getName: function(){ return this.name } } console.log(course.getName()); //ví dụ 2: sử dụng arrow function, ko dùng từ khóa this được const course2 = { name: 'php', getName: ()=>{ return this;//return undefined return this.name;//lỗi vì không có context } } console.log(course2.getName()); //--------------ko thể sử dụng làm object constructor------------ //ok: nếu sử dụng hàm thông thường const Course = function(name, price){ this.name = name; this.price = price; } //lỗi: khi sử dụng arrow function const Course1 = (name, price)=>{ this.name = name; this.price = price; } var objectJs = new Course('JavaScript', 1000);//ok var objectPHP = new Course1('PHP',2000);//lỗi
true
a73a5f1ef3f0e7f410dc3362e9eb1536c0e102e7
JavaScript
lizlux/mercury-cli
/es6/CuratedContentEditModel.js
UTF-8
1,924
2.578125
3
[]
no_license
/// <reference path="../app.ts" /> 'use strict'; App.CuratedContentEditModel = Em.Object.extend({ featured: null, regular: null, optional: null }); App.CuratedContentEditModel.reopenClass({ find: function () { return new Em.RSVP.Promise(function (resolve, reject) { Em.$.ajax({ url: M.buildUrl({ path: '/wikia.php' }), data: { controller: 'CuratedContent', method: 'getData', format: 'json' }, success: function (data) { if (Em.isArray(data.data)) { resolve(App.CuratedContentEditModel.sanitize(data.data)); } else { reject('Invalid data was returned from Curated Content API'); } }, error: function (data) { reject(data); } }); }); }, /** * @desc Accepts a raw object that comes from CuratedContent API and creates a model that we can use * * @param rawData * @returns {any} */ sanitize: function (rawData) { var featured = {}, regular = { items: [] }, optional = {}; if (rawData.length) { rawData.forEach(function (section) { if (section.featured === 'true') { featured = section; } else if (section.title === '') { optional = section; } else { regular.items.push(section); } }); } return App.CuratedContentEditModel.create({ featured: featured, regular: regular, optional: optional }); } });
true
1df73892be7109e9d9cd26806302af5217d687f5
JavaScript
crolson/Kanakatana2014
/Assets/Resources/Scripts/Player.js
UTF-8
4,798
3.03125
3
[]
no_license
/* * this script controls the player movement and health */ #pragma strict //The players normal max health var maxHealth : float; //The players max health after all modifiers var modifiedMaxHealth : float; //The players current health. var currentHealth : float; //Whether the player is invulnerable. If true, the player's health cannot decreace var invincible : boolean; //Whether the player has been recently hit. var recentHitInvincibility : boolean; //The last time the player was hit var recentHitTime : float; //The durration of the player's invincibility upon being hit? var recentHitDuration : float; //whether the player is rooted in place. if true, ignore nockback var rooted : boolean; //the unmodified speed the player moves at var baseSpeed : float; //The speed modifier for being a bunny var bunnyModifier : float; //Whether the player can move or not. var moveEnabled : boolean; /* * Refrences to other objects */ //the health bar of the player var healthBar : GameObject; //the player health bar prefab var healthBarBg : GameObject; /* * Refrences to Prefabs */ //the player health bar prefab var healthBarPrefab : GameObject; //the grey health bar prefab. var healthBarBgPrefab : GameObject; function Awake() { CreateHealthBar(); } function Update () { //check to see if the player is still invincible UpdateInvincibility(); //scale the health bar to match the player's current house. UpdateHealthBar(); } function FixedUpdate () { } //This function gets called when the player gets hit. // damage : ammount of damage to take // knockback : the vector of force to be applied to the player function GetHit(damage : float, knockback : Vector2) { ApplyDamage(damage); ApplyKnockback(knockback); } //applies damage to the player function ApplyDamage(damage : float) { //if the player is invincible, do not apply damage if(this.invincible) { return; } } //Applies knockback to the player when they are hit function ApplyKnockback(knockback : Vector2) { //if we are not rooted if(!this.rooted) { rigidbody2D.AddForce(knockback); } } //set the player to become invincible when they get hit. function BecomeInvincible(durration : float) { this.invincible = true; } //updates the state of the players invincibility every update. function UpdateInvincibility() { //if the player has not recently been hit if(this.recentHitTime + recentHitDuration < Time.time) { this.recentHitInvincibility = false; } } //reloads the current level function Die() { Application.LoadLevel(Application.loadedLevelName); } function CreateHealthBar() { //the background bar game object var bg : GameObject; //instantiate the health bar at the players location this.healthBar = Instantiate(this.healthBarPrefab, transform.position, Quaternion.identity); //parent the healthBar to the player this.healthBar.transform.parent = transform; //move the healthbar to the proper location on the hud this.healthBar.transform.localPosition = new Vector2(0, -11); //instantiate the grey healthbar background this.healthBarBg = Instantiate(this.healthBarBgPrefab, transform.position, Quaternion.identity); //set the bg bar to be in the same location as the health bar this.healthBarBg.transform.position = this.healthBar.transform.position; } //transform the scale of the healthbar function UpdateHealthBar() { this.healthBar.transform.localScale = new Vector3(this.currentHealth / this.maxHealth, 1 ,1); //set the bg bar to be in the same location as the health bar this.healthBarBg.transform.position = this.healthBar.transform.position; } //Checks to see if the player is still alive function CheckAlive() { if(this.currentHealth <= 0) { Die(); } } //moves the player, Handles colisions, and animates the player. function movePlayer() { //the location of the mouse click var click : Vector3; //if the player has clicked somewhere if(Input.GetMouseButton(0)) { //save the location click = Input.mousePosition; //offset the location to be relative to the center of the screen. var clickX = click.x - Screen.width/2; var clickY = click.y - Screen.height/2; //the location of the click var clickVector : Vector3 = new Vector3(clickX, clickY, 0); //the vector from the player to the mouse var moveVector : Vector3 = clickVector; //if the click is above the HUD and the player can move if(isAboveKanaBar(click.y) && this.moveEnabled){ //move the player toards the clicked location rigidbody2D.velocity = new Vector3(clickX, clickY, 0).normalized * (baseSpeed * bunnyModifier); } } else { rigidbody2D.velocity = new Vector2(0, 0); } } //determines if a click happened above the ability bar function isAboveKanaBar(clickY : float) : boolean{ if(clickY > 60) { return true; } else { return false; } }
true
f2e15fc23317f397b7f025392fc4eb902bf5a5ce
JavaScript
KaraioYu/algorithm
/main.js
UTF-8
607
3.859375
4
[]
no_license
/** * 求两个数的最大公约是 */ function GCD(n1, n2) { return n1 * n2; } function LCM(n1, n2) { return 1; } function test() { var dom = document.createElement('div'); dom.innerHTML = 'GCD 400 and 800 equals: ' + GCD(400, 800); document.getElementById('main').appendChild(dom); dom = document.createElement('div'); dom.innerHTML = 'GCD 25 and 35 equals: ' + GCD(25, 35); document.getElementById('main').appendChild(dom); dom = document.createElement('div'); dom.innerHTML = 'LCM 25 and 35 equals: ' + LCM(25, 35); document.getElementById('main').appendChild(dom); } test();
true
ec3a6daa2d841aa15afbdaf2e6b16179238b2f19
JavaScript
kfcteh/aws-search-back
/tests/integration.test.js
UTF-8
709
2.5625
3
[]
no_license
const request = require('supertest'); const app = require('../index') describe('POST /products', () => { it('respond with json containing product to add', () => { return request(app) .post('/products') .send({ asin: 'B002QYW8LW' }) .expect(201) .then(response => { expect(response.body.id).toEqual('B002QYW8LW') }) }) }) describe('GET /products', () => { it('respond with json containing a list of products', () => { return request(app) .get('/products') .expect(200) .then(response => { const products = response.body expect(products.some((product) => product.id == 'B002QYW8LW')).toEqual(true) }) }) })
true
232acf85bd58faeeba30acd07f957e62f6234dfa
JavaScript
wangtao0101/leetcode-problem-types
/template/409.js
UTF-8
257
2.828125
3
[ "MIT" ]
permissive
/* * @lc app=leetcode.cn id=409 lang=javascript * * [409] 最长回文串 */ // @lc code=start /** * @param {string} s * @return {number} */ var longestPalindrome = function(s) { }; // @lc code=end //* Testcase Example: '"abccccdd"'
true
47b1605f22934be431da016078d6b6ef6cd89b6f
JavaScript
QGtiger/vueProject
/iview-Blog/src/libs/proxy.js
UTF-8
844
2.578125
3
[ "MIT" ]
permissive
const http = require('http'); const request = require('request'); const host = '127.0.0.1'; const port = 8010; //创建一个api代理服务 const apiServer = http.createServer((req, res)=>{ const url = 'http://blog.qnpic.top'+req.url; const options = { url: url }; function callback(error, response, body){ if(!error && response.statusCode === 200){ // 设置编码类型,否则中文显示乱码 res.setHeader('Content-Type', 'text/plain;charset=UTF-8'); //设置所有域都可以访问 res.setHeader('Access-Control-Allow-Origin', '*'); //返回代理后的内容 res.end(body); } } request.get(options, callback); }) apiServer.listen(port, host, ()=>{ console.log(`接口代理在http://${host}:${port}/`); })
true
65956fe7260b3a53849d95a3744b0e588147933e
JavaScript
lfmichel/Programming
/webProg/jquery/script_jquery copy.js
UTF-8
564
2.671875
3
[]
no_license
/* Sintaxe */ /* $(seletor).acao(); */ /* $(document).ready(function(){ $('button').click(function(){ $('h1').hide(); }); }); */ /* Simplificando o jquery */ /* Forma reduzida do .ready */ /* $(function(){ $('button').click(function(){ $('h1').hide(); }); }); */ /* /* Alterando a cor do css $(function(){ $('button').click(function(){ $('h1').css("color", "red"); }); }); */ /* Alterando a cor do css com id */ $(function(){ $('button').click(function(){ $('#unico').css("color", "red"); }); });
true
429e16afe7cac090cbbb839d74e8c9f3e31facef
JavaScript
llllllllr/breastfeed
/部分样式修改/me_queResult/me_queResult.js
UTF-8
3,523
2.671875
3
[]
no_license
// page/jieguo/jieguo.js Page({ /** * 页面的初始数据 */ data: { n:1, type1:"自我效能量表", type2:"情绪调查量表", con_height: "1250rpx", count_zw: 3, //统计自我效能量表显示个数 count_qx: 3, //统计情绪调查量显示个数 用于决定container的height是100%还是固定rpx count_all:6, //统计所有显示个数 jieguo: [ { "id": "1", "type": "自我效能量表", "score": "20", "advice": "你很棒噢!", "time": "2020/03/01" }, { "id": "2", "type": "自我效能量表", "score": "22", "advice": "你很棒棒噢!", "time": "2020/03/04" }, { "id": "3", "type": "自我效能量表", "score": "20", "advice": "你真棒!", "time": "2020/03/06" }, { "id": "4", "type": "情绪调查量表", "score": "16", "advice": "欧力给!", "time": "2020/02/08" }, { "id": "5", "type": "情绪调查量表", "score": "18", "advice": "噶油!", "time": "2020/01/16" }, { "id": "6", "type": "情绪调查量表", "score": "20", "advice": "你真棒!", "time": "2020/02/25" }, ] }, onLoad: function (options) { this.setData({ bg_color1: "#000000", n1_color: "#FFFFFF", bg_color2: "#FFFFFF", n2_color: "#000000", bg_color3: "#FFFFFF", n3_color: "#000000" }) if (this.data.count_all >= 7 || this.data.id == 3) this.setData({ con_height: "100%" }) }, question:function(e){ var id=0; var idx=e.currentTarget.dataset.id-1;//下标 // wxml中表的顺序也是根据data中表内容的顺序来显示的,所以js中的可以与wxml的数据对应 // 从而获得此刻框中的问卷表名称 var string = this.data.jieguo[idx].type; console.log(string); // 判断string中是否有此字符串 if (string.indexOf("自我") >= 0) { id=1; } if (string.indexOf("情绪") >= 0) { id = 2; } console.log("id_____"+id); wx.navigateTo({ url: '../me_questionaire/me_questionaire?questionId=' + id+'&ansID='+idx, //ansID为问卷的ID,到时根据idx来找问卷的答案 }) }, tap_n1: function () { if (this.data.count_all >= 7) this.setData({ con_height: "100%" }) else this.setData({ con_height: "1350rpx" }) this.setData({ n: 1, bg_color1: "#000000", n1_color: "#FFFFFF", bg_color2: "#FFFFFF", n2_color: "#000000", bg_color3: "#FFFFFF", n3_color: "#000000" }) }, tap_n2: function () { if (this.data.count_zw >= 7) this.setData({ con_height: "100%" }) else this.setData({ con_height: "1350rpx" }) this.setData({ n: 2, bg_color2: "#000000", n2_color: "#FFFFFF", bg_color1: "#FFFFFF", n1_color: "#000000", bg_color3: "#FFFFFF", n3_color: "#000000" }) }, tap_n3: function () { if (this.data.count_qx >= 7) this.setData({ con_height: "100%" }) else this.setData({ con_height: "1350rpx" }) this.setData({ n: 3, bg_color3: "#000000", n3_color: "#FFFFFF", bg_color1: "#FFFFFF", n1_color: "#000000", bg_color2: "#FFFFFF", n2_color: "#000000" }) }, })
true
aa251a5245e782df739e5f13f5b7f733f053d188
JavaScript
bluecrayon52/node-course-3-chat-app
/server/utils/message.test.js
UTF-8
1,036
2.890625
3
[]
no_license
var expect = require('expect'); var {generateMessage, generateLocationMessage} = require('./message'); /* ----TEMPLATE-------- describe('', () => { it('', (done) => { }); }); */ // synchronous, no need to call done describe('generateMessage', () => { it('should generate correct message object', () => { var from = 'Bob'; var text = 'I love Burgers!'; var message = generateMessage(from, text); expect (message).toMatchObject({from, text}); expect(typeof message.createdAt).toBe('number'); }); }); describe('generateLocationMessage', () => { it('should generate correct location object', () => { var from = 'Bob'; var latitude = 10; var longitude = 15; var url = `https://www.google.com/maps?q=${latitude},${longitude}`; var message = generateLocationMessage(from, latitude, longitude); expect (message).toMatchObject({from, url}); expect(typeof message.createdAt).toBe('number'); }); });
true
e46693d7c4aa59730d29531469a81b3b851a830f
JavaScript
MisterTrent/petcam
/static/scripts.js
UTF-8
1,263
2.6875
3
[]
no_license
var myLib = (function(){ 'use strict'; var lib = {}; lib.loadMore = function(){ var xhr = new XMLHttpRequest(); var method = 'GET'; var url = '/ajax/load_snapshots'; xhr.addEventListener('load',lib.displayLoadedImages); xhr.addEventListener('error',lib.displayXhrError); xhr.open(method, url, true); xhr.send(); } lib.displayLoadedImages = function(e){ lib.removeLoadButton(); lib.appendImages(e.target.responseText); } lib.displayXhrError = function(){ } lib.removeLoadButton = function(){ document.getElementById('snapshots-loader-wrapper').remove(); } lib.appendImages = function(html){ document.getElementById('snapshots-container').innerHTML += html; lib.setLoadListener(); } lib.setLoadListener = function(){ var loadButton = document.getElementById('load-more-button'); if(loadButton !== null){ loadButton.addEventListener('click', lib.loadMore); } } //TODO flask sessions instead of messing w/ javascript return lib }()); document.addEventListener('DOMContentLoaded', function(e){ myLib.setLoadListener(); });
true
b9bda79e8fd7e86e77fc02532883127f0d8a879c
JavaScript
spyrocash/todo-app
/src/App.js
UTF-8
2,464
2.734375
3
[]
no_license
import React, { Component } from 'react'; import _ from 'lodash'; import logo from './logo.svg'; import './App.css'; import cuid from 'cuid'; import TodoHeader from './components/TodoHeader'; import TodoMain from './components/TodoMain'; import TodoFooter from './components/TodoFooter'; class App extends Component { state = { todos: { '1': {id: '1', text: 'aaa', completed: true}, '2': {id: '2', text: 'bbb', completed: true}, '3': {id: '3', text: 'ccc', completed: false}, }, todoIds: ['1', '2'], filter: 'all', // all, active, completed } handleCreateTodo = (text) => { const newId = cuid(); this.setState({ todos: { ...this.state.todos, [newId]: { id: newId, text: text, completed: false, }, }, todoIds: [...this.state.todoIds, newId], }) } handleToggleComplete = (id, completed) => { // Object Way const todos = this.state.todos; todos[id].completed = completed; this.setState({ todos: todos, }); } handleDeleteTodo = (id) => { console.log(id); const todos = this.state.todos; delete todos[id]; const newTodoIds = _.filter(this.state.todoIds, (todoId) => { return id !== todoId; }); this.setState({ todos: todos, todoIds: newTodoIds, }) } handleFilter = (filter) => { this.setState({ filter: filter, }) } render() { const filter = this.state.filter; const todos = this.state.todos; const todoIds = this.state.todoIds; const todoItems = todoIds.map(function(todoId) { return todos[todoId]; }); let visibleTodoItems; switch (filter) { case 'active': visibleTodoItems = _.filter(todoItems, todo => !todo.completed); break; case 'completed': visibleTodoItems = _.filter(todoItems, todo => todo.completed); break; case 'all': default: visibleTodoItems = todoItems; break; } const activeCount = _.size(_.filter(todoItems, todo => !todo.completed)); return ( <div className="todoapp"> <TodoHeader onCreateTodo={this.handleCreateTodo} /> <TodoMain items={visibleTodoItems} onToggleComplete={this.handleToggleComplete} onDeleteTodo={this.handleDeleteTodo} /> <TodoFooter onFilter={this.handleFilter} filter={this.state.filter} activeCount={activeCount} /> </div> ); } } export default App;
true
76bd3f34b4d79ed17e4ce87eefc53c9a9c9bd2bb
JavaScript
jjsants/Dicee-Game
/index.js
UTF-8
766
3.84375
4
[]
no_license
document.querySelector(".btn").addEventListener("click", trowDices); function trowDices(){ //dice 1; var diceOne = Math.floor(Math.random() * 6) + 1; var randomDiceOne = "images/dice"+diceOne+".png"; document.querySelectorAll("img")[0].setAttribute("src", randomDiceOne); //dice 2; var diceTwo = Math.floor(Math.random() * 6) + 1; var randomDiceTwo = "images/dice"+diceTwo+".png"; document.querySelectorAll("img")[1].setAttribute("src", randomDiceTwo); //displaying the result; if(diceOne > diceTwo){ document.querySelector("h1").innerHTML="Dice 1 Wins 🏁" }else if(diceTwo > diceOne){ document.querySelector("h1").innerHTML="Dice 2 Wins 🏁" }else{ document.querySelector("h1").innerHTML="Draw! Try it again." } }
true
97b3c4267429a131a22b2835378fa4556d6c551f
JavaScript
pdxwebdev/yadacoin
/static/app/plugins/cordova-plugin-googlemaps/www/geomodel.js
UTF-8
3,870
2.671875
3
[ "MIT" ]
permissive
cordova.define("cordova-plugin-googlemaps.geomodel", function(require, exports, module) { /** # # Copyright 2010 Alexandre Gellibert # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. */ var LatLng = require('./LatLng'), LatLngBounds = require('./LatLngBounds'), GEOCELL_GRID_SIZE = 4, GEOCELL_ALPHABET = '0123456789abcdef'; function computeBox(geocell) { var subcell_lng_span, subcell_lat_span; var xy, x, y; var bbox = _createBoundingBox(90.0, 180.0, -90.0, -180.0); while(geocell.length > 0) { //geoChar = geocell.charAt(i); //pos = GEOCELL_ALPHABET.indexOf(geoChar); subcell_lng_span = (bbox.getEast() - bbox.getWest()) / GEOCELL_GRID_SIZE; subcell_lat_span = (bbox.getNorth() - bbox.getSouth()) / GEOCELL_GRID_SIZE; xy = _subdiv_xy(geocell.charAt(0)); x = xy[0]; y = xy[1]; bbox = _createBoundingBox(bbox.getSouth() + subcell_lat_span * (y + 1), bbox.getWest() + subcell_lng_span * (x + 1), bbox.getSouth() + subcell_lat_span * y, bbox.getWest() + subcell_lng_span * x); geocell = geocell.substring(1); } var sw = new LatLng(bbox.getSouth(), bbox.getWest()); var ne = new LatLng(bbox.getNorth(), bbox.getEast()); var bounds = new LatLngBounds(sw, ne); return bounds; } function _createBoundingBox(north, east, south, west) { var north_,south_; if(south > north) { south_ = north; north_ = south; } else { south_ = south; north_ = north; } return { northEast: {lat: north_, lng: east}, southWest: {lat: south_, lng: west}, getNorth: function() { return this.northEast.lat; }, getSouth: function() { return this.southWest.lat; }, getWest: function() { return this.southWest.lng; }, getEast: function() { return this.northEast.lng; } }; } /** * https://code.google.com/p/geomodel/source/browse/trunk/geo/geocell.py#370 * @param latLng * @param resolution * @return */ function getGeocell(lat, lng, resolution) { var cell = ''; var north = 90.0; var south = -90.0; var east = 180.0; var west = -180.0; var subcell_lng_span, subcell_lat_span; var x, y; while(cell.length < resolution + 1) { subcell_lng_span = (east - west) / GEOCELL_GRID_SIZE; subcell_lat_span = (north - south) / GEOCELL_GRID_SIZE; x = Math.min(Math.floor(GEOCELL_GRID_SIZE * (lng - west) / (east - west)), GEOCELL_GRID_SIZE - 1); y = Math.min(Math.floor(GEOCELL_GRID_SIZE * (lat - south) / (north - south)),GEOCELL_GRID_SIZE - 1); cell += _subdiv_char(x, y); south += subcell_lat_span * y; north = south + subcell_lat_span; west += subcell_lng_span * x; east = west + subcell_lng_span; } return cell; } /* * Returns the (x, y) of the geocell character in the 4x4 alphabet grid. */ function _subdiv_xy(char) { // NOTE: This only works for grid size 4. var charI = GEOCELL_ALPHABET.indexOf(char); return [(charI & 4) >> 1 | (charI & 1) >> 0, (charI & 8) >> 2 | (charI & 2) >> 1]; } /** * Returns the geocell character in the 4x4 alphabet grid at pos. (x, y). * @return */ function _subdiv_char(posX, posY) { // NOTE: This only works for grid size 4. return GEOCELL_ALPHABET.charAt( (posY & 2) << 2 | (posX & 2) << 1 | (posY & 1) << 1 | (posX & 1) << 0); } module.exports = { computeBox: computeBox, getGeocell: getGeocell }; });
true
81cae85f8e704d86c614f6a5abc87023e45ac687
JavaScript
FiorelaBasilioManrique/LIM011-card-validation
/src/index.js
UTF-8
1,574
3.125
3
[]
no_license
import isValid from './validator.js'; const number = document.getElementById('numero'); const validar = document.getElementById('validar'); const cardTarje = document.getElementById('cardTarje'); const message = document.getElementById('mensaje'); // MODAL const modal = document.getElementById('modal'); const flex = document.getElementById('flex'); const close = document.getElementById('close'); const openModal = () => { // cardTarje.classList.add('hide'); modal.classList.remove('hide'); } close.addEventListener('click', (e) => { e.preventDefault(); modal.classList.add('hide'); cardTarje.classList.remove('hide'); }); window.addEventListener('click', (e) => { if (e.target == flex) { modal.classList.add('hide'); cardTarje.classList.remove('hide'); } }); const validaTarjeta = `<p id="parrafo" class="parrafo">El N° de tarjeta es válida.</p> <img class="check" src="img/check.gif" alt="">` const noValida = `<p class="parrafo">El N° de tarjeta no es válida</p> <img class="signoAd" src="img/admiracion.png" alt="">`; validar.addEventListener('click', (e) => { e.preventDefault(); // FUNCION if (number.value !== '') { const response = isValid(number.value); const modal = document.querySelector('.modal-body'); openModal(); if (response === true) { modal.innerHTML = validaTarjeta; } else { modal.innerHTML = noValida; } } else { message.innerHTML = 'Ingrese un número de tarjeta'; } number.value = ''; });
true
22954c43044d3faf1be3a342f2c7ac74fe097955
JavaScript
wurishi/note
/xstate/03.js
UTF-8
3,416
2.609375
3
[]
no_license
import { Machine, interpret, assign, } from "./node_modules/xstate/dist/xstate.web.js"; const machine = Machine({ initial: "red", states: { red: {}, }, context: { count: 0, user: null, }, }); console.log(machine.initialState.context); const service = interpret( machine.withContext({ count: 10, test: 1, user: { name: "Jerry", }, }) ); service.start(); console.log(service.state.context); const lightMachine = Machine( { initial: "red", states: { red: { entry: (context, event) => console.log("entry red"), exit: (context, event) => console.log("exit red"), on: { CLICK: { target: "green", actions: (context, event) => console.log("hello green", context, event), }, }, }, green: { entry: ["entryGreen", "temp"], exit: "exitGreen", on: { CLICK: { target: "red", actions: "greenClick", }, }, }, }, }, { actions: { greenClick: (context, event) => console.log("hello red"), entryGreen: (context, event) => console.log("entry green"), exitGreen: (context, event) => console.log("exit green"), temp: () => console.log("temp"), }, } ); const state0 = lightMachine.initialState; const state1 = lightMachine.transition(state0, "CLICK"); const state2 = lightMachine.transition(state1, "CLICK"); console.log(state1); const div = document.createElement("div"); document.body.appendChild(div); const counterMachine = Machine( { id: "counter", initial: "ENABLED", context: { count: 0, }, states: { ENABLED: { on: { INC: { actions: ["increment", "updateView"] }, DYNAMIC_INC: { actions: ["dynamic_increment", "updateView"] }, RESET: { actions: ["reset", "updateView"] }, DISABLE: "DISABLED", }, }, DISABLED: { on: { ENABLE: "ENABLED", }, }, }, }, { actions: { increment: assign({ count: (context) => context.count + 1, }), dynamic_increment: assign({ count: (context, event) => { console.log(context, event); return context.count + (event.value || 0); }, }), reset: assign({ count: 0, }), updateView: (context) => { div.textContent = context.count; }, }, } ); const counterService = interpret(counterMachine); counterService.start(); console.log("----------------"); console.log(counterService.state); const btn = document.createElement("button"); btn.textContent = "increment"; document.body.appendChild(btn); btn.addEventListener("click", () => { counterService.send("INC"); // console.log(counterService.state); }); const btn2 = document.createElement("button"); btn2.textContent = "increment 10"; document.body.appendChild(btn2); btn2.addEventListener("click", () => { counterService.send({ type: "DYNAMIC_INC", value: 10 }); }); const btn3 = document.createElement("button"); btn3.textContent = "enable"; document.body.appendChild(btn3); btn3.onclick = () => counterService.send("ENABLE"); const btn4 = document.createElement("button"); btn4.textContent = "disable"; document.body.appendChild(btn4); btn4.onclick = () => counterService.send("DISABLE");
true
b8d0590520e92481d4f22faaebfa41041d5cfe9f
JavaScript
SorielV/club
/server/web/middleware/auth.js
UTF-8
3,564
2.515625
3
[]
no_license
import { verify, COOKIE_KEY } from './../../utils/jwt' // Auth Information export const authInformation = async (req) => { return await (process.env.AUTH_BASE === 'st' ? getSessionHeader(req) : getSessionCookie(req) ) } // Normal Auth export const HandleAuth = async (req, res, next) => { try { const { data: user, token } = await authInformation(req) req.user = user req.token = token return next() } catch (error) { console.log(error) req.error = error.message return next() } } // Normal Authorization export const isAuth = async (req, res, next) => { if (req.user) { return next() } else { if (req.error) { return res .status(403) .json({ message: req.error }) .end() } else { return res .status(404) .json({ message: 'No has ingresado' }) .end() } } } export const isNotAuth = async (req, res, next) => { if (req.user) { return res.redirect('/') } else { return next() } } // Privileged Authorization export const isAdmin = async (req, res, next) => { if (req.user && req.user.type === ADMIN) { return next() } else { if (req.error) { return res .status(403) .json({ message: req.error }) .end() } else { return res .status(403) .json({ message: 'No tienes los privilegios de administrador' }) .end() } } } // TODO: Guardar [idClub, rol] acorde a los clubes de usuario // FIX: query { idClub } export const isMember = async (req, res, next) => { const { idClub } = req.query if (req.user && req.user.clubs.includes(idClub)) { return next() } else { if (req.error) { return res .status(403) .json({ message: req.error }) .end() } else { return res .status(403) .json({ message: 'No eres miembro C:' }) .end() } } } /** * Set request user if the request is signed based in cookies * @param {express: request} req * @param {express: response} res * @param {express: next} next */ export const sessionCookie = async (req, res, next) => { if (req.cookies[COOKIE_KEY]) { req.user = await verify(req.cookies[COOKIE_KEY]) req.token = req.cookies[COOKIE_KEY] } return next() } /** * Set request user if the request is signed based in headers * @param {express: request} req * @param {express: response} res * @param {express: next} next */ export const sessionHeader = async (req, res, next) => { if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { const token = req.headers.authorization.split(' ')[1] req.user = await verify(token) req.token = token } return next() } export const getSessionHeader = async (req) => { if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { const token = req.headers.authorization.split(' ')[1] return { data: await await verify(token), token } } else { return {} } } export const getSessionCookie = async (req) => { if (req.cookies[COOKIE_KEY]) { const token = req.cookies[COOKIE_KEY] return { data: await verify(token), token } } else { return {} } } export const logoutSessionStorageBase = (req, res, next) => { // TODO: LS logout (Client-side implementation) return res.redirect('/') } export const logoutCookieBase = (req, res, next) => { res.clearCookie(COOKIE_KEY) return res.redirect('/') }
true
58431fbeda70ee0772943d3d9a730051d5359cea
JavaScript
vardan099/anyfin
/server/controllers/CountriesController.js
UTF-8
1,439
2.515625
3
[]
no_license
const CountriesService = require('../services/CountriesService'); const Fixer = require('fixer-node'); const fixer = new Fixer('65a46a3c3c9c4a87ab07b6a72500b80d'); class CountriesController { async getCountriesByName(req, res, next) { try { const { name } = req.params; let newCountries = []; const countries = await CountriesService.findByName(name); if( countries.length > 0 ){ const latest = await fixer.latest(); const rates = JSON.parse(JSON.stringify(latest.rates)); countries.forEach(country => { let exchange = []; country.currencies.forEach(currency=>{ const {code} = currency; const rateExchange = (rates[code] / rates["SEK"]).toFixed(2); if(!isNaN(rateExchange)){ exchange.push({code:code,exchange:rateExchange}) } }); country.exchange = exchange; newCountries.push(country) }); } res.status(200).json(newCountries); } catch (error) { console.log('Get Countries Error: ', error); res.status(error.status ? error.status : 500).send({message: error.message}); } }; } module.exports = new CountriesController();
true
106f9e21365fede64605cf859e2802913e0af1e5
JavaScript
beaulabs/ColoradoScooters
/UpdateLocation.js
UTF-8
1,076
2.8125
3
[]
no_license
// nohup bash UpdateLocation.sh &>/dev/null & // Create 5K upserts and bulk write var _id_min = 1; var _id_max = 999999 var lat_min = 37.020691; var lat_max = 40.988098; var lon_min = -109.015325; var lon_max = -102.101746; function getRnd(bottom, top) { return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom; } function getRndBool() { return Math.random() >= 0.5 } for (var times= 0; times<86400; times ++) { var bulk = db.scooters.initializeUnorderedBulkOp(); for (var i = 0; i < 5000; i++) { var _id = getRnd(_id_min, _id_max)|0; var point = { "type" : "Point", "coordinates" : [getRnd(lon_min, lon_max), getRnd(lat_min,lat_max)] } bulk.find( { "_id": _id } ).upsert().update( { $set: { "location": point }, $set: { "is_reserved": getRndBool() }, $set: { "is_disabled": getRndBool() } } ); } bulk.execute(); print(times + " iteration of 5K bulk updates DONE"); } print("DONE!");
true
9815dc5b3081328a619c7ce61c324c3b0dd57b26
JavaScript
mankoty567/dodo-la-saumure
/.gitignore/commands/weather.js
UTF-8
1,831
2.96875
3
[]
no_license
const Discord = require("discord.js"); //Ajouter toutes les autres const que la commande need ici module.exports.run = async (bot, message, args) => { message.delete() if(args[1].toLowerCase() === "sun" || args[1].toLowerCase() === "soleil") { message.channel.send("```Markdown\nLe temps est maintenant ensoleillé! ☀️```") message.channel.edit({"topic" : message.channel.topic.replace(/Météo.*\n/, "Météo : Ensoleillé ☀️\n")}) } else if(args[1].toLowerCase() === "cloud" || args[1].toLowerCase() === "nuage" || args[1].toLowerCase() === "nuageux") { message.channel.send("```Markdown\nLe temps est maintenant nuageux! ☁️```") message.channel.edit({"topic" : message.channel.topic.replace(/Météo.*\n/, "Météo : Nuageux ☁️\n")}) } else if(args[1].toLowerCase() === "rain" || args[1].toLowerCase() === "pluie") { message.channel.send("```Markdown\nLe temps est maintenant pluvieux! 🌧️```") message.channel.edit({"topic" : message.channel.topic.replace(/Météo.*\n/, "Météo : Pluvieux 🌧️\n")}) } else if(args[1].toLowerCase() === "storm" || args[1].toLowerCase() === "orage") { message.channel.send("```Markdown\nLe temps est maintenant orageux! ⚡```") message.channel.edit({"topic" : message.channel.topic.replace(/Météo.*\n/, "Météo : Orageux ⛈️\n")}) } else { message.author.send("Je suis désolé, mais le temps que tu as spécifié ne fonctionne pas! Tu peux utilisez :\n:black_small_square: .weather sun/soleil : Temps ensoleillé ☀️\n:black_small_square: .weather cloud/nuageux : Temps nuageux ☁️\n:black_small_square: .weather rain/pluie : Temps pluvieux 🌧️\n:black_small_square: .weather storm/orage : Temps orageux ⛈️") } } module.exports.help = { name: "weather" }
true
9c1c2d3439a13626d7a6920a034ff6fa98ce4b92
JavaScript
sosaysthecaptain/vehicleRouting
/testing/manualMap.js
UTF-8
3,398
2.921875
3
[]
no_license
// Testing things live here var upperLeft; var upperLeftInner; var lowerLeft; var lowerLeftInner; var upperRight; var upperRightInner; var lowerRight; var lowerRightInner; var testRoutePair; var bestRoutePair; var correctRoutePair; var needsExchange; var needsFlip; // individually grabbable stops on test map function setTestVariables() { upperLeft = points[0]; upperLeftInner = points[1]; lowerLeft = points[2]; lowerLeftInner = points[3]; upperRight = points[4]; upperRightInner = points[5]; lowerRight = points[6]; lowerRightInner = points[7]; // random route pair randomRoutePair = new routePair(); //drawRoutePairLight(randomRoutePair); //logRoutePairs(randomRoutePair); // best route pair var bestA = [lowerLeftInner, lowerLeft, lowerRight, lowerRightInner]; var bestB = [upperRightInner, upperRight, upperLeft, upperLeftInner]; bestRoutePair = new routePair(); bestRoutePair.routeAWithoutDepot = bestA; bestRoutePair.routeBWithoutDepot = bestB; bestRoutePair.addDepot(); // must call this manually if manually messing with arrays bestRoutePair.calcTotalDistance(); //drawRoutePairLight(bestRoutePair); //logRoutePairs(bestRoutePair); // correct route pair var correctA = [upperLeftInner, upperLeft, lowerLeft, lowerLeftInner]; var correctB = [upperRightInner, upperRight, lowerRight, lowerRightInner]; correctRoutePair = new routePair(); correctRoutePair.routeAWithoutDepot = correctA; correctRoutePair.routeBWithoutDepot = correctB; correctRoutePair.addDepot(); // must call this manually if manually messing with arrays correctRoutePair.calcTotalDistance(); drawRoutePairLight(correctRoutePair); logRoutePairs(correctRoutePair); // needs exchange route pair var needsExchangeA = [upperLeftInner, upperRight, lowerLeft, lowerLeftInner]; var needsExchangeB = [upperRightInner, upperLeft, lowerRight, lowerRightInner]; needsExchange = new routePair(); needsExchange.routeAWithoutDepot = needsExchangeA; needsExchange.routeBWithoutDepot = needsExchangeB; needsExchange.addDepot(); // must call this manually if manually messing with arrays needsExchange.calcTotalDistance(); //drawRoutePairLight(needsExchange); //logRoutePairs(needsExchange); // needs flip route pair var needsFlipA = [upperLeft, upperLeftInner, lowerLeft, lowerLeftInner]; var needsFlipB = [upperRightInner, upperRight, lowerRight, lowerRightInner]; needsFlip = new routePair(); needsFlip.routeAWithoutDepot = needsFlipA; needsFlip.routeBWithoutDepot = needsFlipB; needsFlip.addDepot(); // must call this manually if manually messing with arrays needsFlip.calcTotalDistance(); //drawRoutePairLight(needsFlip); //logRoutePairs(needsFlip); } function runTest() { /* Put things in this to save typing */ correctRoutePair = mutateExchange(correctRoutePair); drawRoutePairLight(correctRoutePair); logRoutePairs(correctRoutePair); } function drawBest() { /* Assesses the current population & draws the best route pair to date. */ assessFitness(); console.log('BEST OF PHENOTYPE: '+ floor(bestRoutePairToDate.totalDistance) + ', theoretical best 2730'); drawRoutePairLight(bestRoutePairToDate); }
true
41be8552db660558440b07c0d6f40d96113214db
JavaScript
erielrj/landing-agil-fotografia
/scripts/sidemenu.js
UTF-8
444
3.015625
3
[]
no_license
function openNav() { document.getElementById("mySidenav").style.width = "250px"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; } /* Colocando o evento click nos links da sidenav para disparar as função closeNav */ (function () { const navLinks = document.querySelectorAll('nav > a'); for (link of navLinks) { link.addEventListener('click', function () { closeNav(); }) } })();
true
54174fc4ad8c6786989317f765cd4a54dbfa12ae
JavaScript
omardkh/Discord_Sticky-Message-Bot
/src/commands/edit.js
UTF-8
3,148
2.5625
3
[ "MIT" ]
permissive
// Edit command const BotFunctions = require("../bot_functions.js"); const Errors = require("../messages/errors.js"); const Colors = require("../messages/colors.js"); function Run(client, msg) { const msgParams = msg.content.toLowerCase().split(" "); const server_id = msg.guild.id; const channel_id = BotFunctions.GetMessageChannelID(msgParams[2]); const sticky_id = msgParams[3]; client.channels.fetch(channel_id).then(_ => { if (!global.stickies.ValidSticky(server_id, channel_id, sticky_id)) return BotFunctions.SimpleMessage(msg.channel, Errors["no_sticky_id"], "Error editing sticky", Colors["error"]); BotFunctions.SimpleMessage(msg.channel, `What are you wanting to change for #${sticky_id} sticky? (message | title | color)`, "Which property?", Colors["question"], (sentMessage) => { BotFunctions.WaitForUserResponse(msg.channel, msg.member, 20000, response => { const response_content = response.content.toLowerCase(); const key = response_content == "color" ? "hex_color" : response_content; BotFunctions.DeleteMessage(sentMessage); if (key !== "message" && key !== "title" && key !== "hex_color" && key !== "is_embed") return BotFunctions.SimpleMessage(msg.channel, "The value you provided is not a valid sticky property.", "Error", Colors["error"]); BotFunctions.SimpleMessage(msg.channel, `What do you want to set #${sticky_id} sticky's ${key} to?`, "What value?", Colors["question"], (sentMessage) => { BotFunctions.WaitForUserResponse(msg.channel, msg.member, key == "message" ? 600000 : 40000, response => { BotFunctions.DeleteMessage(sentMessage); BotFunctions.SimpleMessage(msg.channel, `Please wait while I change that sticky's ${key}...`, "Processing", Colors["sticky"], (sentMessage) => { global.stickies.EditSticky(server_id, channel_id, sticky_id, key, response.content, (val) => { if (typeof(val) == "string") return BotFunctions.SimpleMessage(msg.channel, val, "Error changing sticky", Colors["error"], () => BotFunctions.DeleteMessage(sentMessage)); if (val) BotFunctions.SimpleMessage(msg.channel, `Successfully changed Sticky #${sticky_id}'s ${key}.`, "Modified sticky", Colors["success"], () => BotFunctions.DeleteMessage(sentMessage)); else BotFunctions.SimpleMessage(msg.channel, Errors["no_sticky_id"], "Error editing sticky", Colors["error"], () => BotFunctions.DeleteMessage(sentMessage)); }); }); }); }); }); }); }).catch(_ => { BotFunctions.SimpleMessage(msg.channel, Errors["invalid_channel"], "Error getting channel ID", Colors["error"]); }); } module.exports = {Run};
true
70b38383ec6f5858fbb5c1ce93ac382aa39efe1c
JavaScript
VisualSJ/harbors-engine
/harbors/lib/debug/console.js
UTF-8
3,068
2.609375
3
[]
no_license
(function(block, node, font, loop){ var console, line1, line2, line3, infoElem,task, time, info, draw; var init = function(harbors){ if(!h.options.debug){ return false; } console = (new block).set({ width: 200, height: 195, background: "#222", opacity: 0.3, zIndex: Number.MAX_VALUE }); line1 = (new font).set({ color: "#fff", left: 10, top: 5 }).text("harbors 0.0.1"); line2 = (new font).set({ color: "#fff", left: 10, top: 25 }).text(h.options.system.os + " " + h.options.system.browser + " " + (h.options.system.version).substr(0, 8) + "..."); line3 = (new font).set({ color: "#fff", left: 10, top: 45 }).text("time: draw: task:"); infoElem = []; for(var i=0; i<6; i++){ infoElem.push((new font).set({ color: "#fff", left: 10, top: 65 + i * 20 })); console.append(infoElem[i]); } time = (new font).set({ color: "#fff", left: 42, top: 45 }).text("0"); draw = (new font).set({ color: "#fff", left: 100, top: 45 }).text("0"); task = (new font).set({ color: "#fff", left: 162, top: 45 }).text("0"); console.append(line1); console.append(line2); console.append(line3); console.append(time); console.append(draw); console.append(task); h("canvas").append(console); info = []; h.log = function(str){ for(var i=1; i<arguments.length; i++){ switch(typeof arguments[i]){ case "string": str = str.replace("%s", arguments[i]); break; case "number": str = str.replace("%d", arguments[i]); break; default: str = str.replace("%s", arguments[i].toString()); } } info.push(str); while(info.length > 6){ info.shift(); } for(i=0; i<info.length; i++){ infoElem[i].text(info[i]); } }; var cacheTime = 0; loop.getDrawTime = function(num){ if(cacheTime++ < 30) return; cacheTime = 0; time && time.text(num); }; var cacheInfo = 0; h._getDebugInfo = function(taskLength, drawLength){ if(cacheInfo++ < 30) return; cacheInfo = 0; task && task.text(taskLength); draw && draw.text(drawLength); }; }; h.addInitTask(init); })(HSBlockElement, HSNodeElement, HSFontElement, HSLoop);
true
ff8c54d16e00a08f4be2614d3095f8eacd22d1d4
JavaScript
handleman/jsconcepts
/algorithms/fast_sorting.js
UTF-8
470
2.90625
3
[ "MIT" ]
permissive
const fast_sort = (item) => { if(item && Array.isArray(item)){ if(item.length <= 2 ){ return item; } else{ var pivot = item[Math.floor((item.length)/2)-1]; item.splice(item.indexOf(pivot),1); var leftPart = item.filter(function(val){ return val <= pivot}); var rightPart = item.filter(function(val){ return val > pivot}); return fast_sort(leftPart).concat([pivot], fast_sort(rightPart)) } }else{ return null; } }; export default fast_sort;
true
7b141091d51a32d3f86046c018399592c32b4297
JavaScript
neknek25251989/helloworld
/JavaScript/assignment/assignment_example.js
UTF-8
399
3
3
[ "MIT" ]
permissive
var a = 10; document.getElementById("demoa").innerHTML = a; var b = 10; b += 5; document.getElementById("demob").innerHTML = b; var c = 10; c -= 5; document.getElementById("democ").innerHTML = c; var d = 10; d *= 5; document.getElementById("demod").innerHTML = d; var e = 10; e /= 5; document.getElementById("demoe").innerHTML = e; var x = 10; x %= 5; document.getElementById("demox").innerHTML = x;
true