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 |
---|---|---|---|---|---|---|---|---|---|---|---|
74248b14e1d97e399cf267e9011b5169e1303609
|
JavaScript
|
fabianopmartins/Modulo-Vendas-JSF-Primefaces
|
/Soften/target/Soften/resources/js/javascript.js
|
UTF-8
| 652 | 2.84375 | 3 |
[] |
no_license
|
function mascaraMutuario(o,f){
v_obj=o
v_fun=f
setTimeout('execmascara()',1)
}
function execmascara(){
v_obj.value=v_fun(v_obj.value)
}
function cpfCnpj(v){
v=v.replace(/\D/g,"")
if (v.length <= 14) { //CPF
v=v.replace(/(\d{3})(\d)/,"$1.$2")
v=v.replace(/(\d{3})(\d)/,"$1.$2")
v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2")
} else { //CNPJ
v=v.replace(/^(\d{2})(\d)/,"$1.$2")
v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3")
v=v.replace(/\.(\d{3})(\d)/,".$1/$2")
v=v.replace(/(\d{4})(\d)/,"$1-$2")
}
return v
}
| true |
7ab54420a60f143991cfea8b919db2b3c7ef694e
|
JavaScript
|
meteerogl/coronaTrackerReactRedux
|
/src/components/Covid/ListCountries/ListCountries.js
|
UTF-8
| 6,172 | 2.53125 | 3 |
[] |
no_license
|
import React, {Component} from 'react';
import {Link, Route, Switch} from 'react-router-dom';
import DetailedCountry from "../DetailedCountry/DetailedCountry";
import {Table, Column, HeaderCell, Cell} from 'rsuite-table';
import 'rsuite-table/dist/css/rsuite-table.css';
class ListCountries extends Component {
constructor(props) {
super(props);
const country_statistics = this.props.country_statistics[0]
let data = Object.keys(country_statistics).map(function (key) {
if (typeof country_statistics[key] === "string") {
return {}
}
return country_statistics[key];
});
this.state = {
addColumn: false,
data: data,
sortColumn: "total_cases",
sortType: "desc"
};
this.handleSortColumn = this.handleSortColumn.bind(this);
}
handleSortColumn(sortColumn, sortType) {
this.setState({
loading: true
});
setTimeout(() => {
this.setState({
sortColumn,
sortType,
loading: false
});
}, 800);
}
getData() {
console.log(this.state)
const {data, sortColumn, sortType} = this.state;
if (sortColumn && sortType) {
return data.sort((a, b) => {
let x = a[sortColumn];
let y = b[sortColumn];
if (typeof x === 'string') {
x = x.charCodeAt();
}
if (typeof y === 'string') {
y = y.charCodeAt();
}
if (sortType === 'asc') {
return x - y;
} else {
return y - x;
}
});
}
return data;
}
render() {
const CountryNameCell = ({ rowData, dataKey, ...props }) => {
function handleAction() {
alert(`id:${rowData["code"]}`);
}
console.log(rowData)
return (
<Cell {...props} className="link-group">
<Link
to={{ pathname: '/covid-19/'+rowData["code"]}}
key={rowData[dataKey]}>
{rowData[dataKey]}
</Link>
</Cell>
);
};
return (
<React.Fragment>
<Switch>
<Route exact path="/covid-19/" render={() => (
<div className='mt-3'>
<Table
height={543}
data={this.getData()}
sortColumn={this.state.sortColumn}
sortType={this.state.sortType}
onSortColumn={this.handleSortColumn}
loading={this.state.loading}
onRowClick={data => {
console.log(data);
}}>
<Column width={180} sortable>
<HeaderCell>Country Name</HeaderCell>
<CountryNameCell dataKey="title"/>
</Column>
<Column width={130} sortable>
<HeaderCell>Total Cases</HeaderCell>
<Cell dataKey="total_cases"/>
</Column>
<Column width={160} sortable>
<HeaderCell>New Cases Today</HeaderCell>
<Cell dataKey="total_new_cases_today"/>
</Column>
<Column width={170} sortable>
<HeaderCell>New Deaths Today</HeaderCell>
<Cell dataKey="total_new_deaths_today"/>
</Column>
<Column width={130} sortable>
<HeaderCell>Total Deaths</HeaderCell>
<Cell style={{backgroundColor:"#ff3333",color:"white"}} dataKey="total_deaths"/>
</Column>
<Column width={160} sortable>
<HeaderCell>Total Recovered</HeaderCell>
<Cell style={{backgroundColor:"green",color:"white"}} dataKey="total_recovered"/>
</Column>
<Column width={170} sortable>
<HeaderCell>Total Serious Cases</HeaderCell>
<Cell dataKey="total_serious_cases" />
</Column>
</Table>
</div>
/**
<table className="table">
<thead>
<tr>
<th>#</th>
<th>Country Name</th>
<th>Total Cases</th>
<th>Total Deaths</th>
<th>New Cases Today</th>
<th>New Deaths Today</th>
<th>Total Recovered</th>
<th>Total Serious Cases</th>
</tr>
</thead>
<tbody>
<ListItem country_statistics={this.props.country_statistics}></ListItem>
</tbody>
</table>
*/
)}/>
<Route path=":id" component={DetailedCountry}/>
</Switch>
<Route path="/covid-19/:id" component={DetailedCountry}/>
</React.Fragment>
)
}
}
export default ListCountries;
| true |
843f22870073015f956663d9354d30c38f254d4e
|
JavaScript
|
knazir/WebFiddle
|
/public/js/dashboard/project-tile.js
|
UTF-8
| 2,531 | 3.109375 | 3 |
[] |
no_license
|
class ProjectTile extends Component {
constructor(containerElement, project, selectProjectCallback, openDeleteModalCallback, deleteProjectCallback) {
super(containerElement);
this._project = project;
this._selectProjectCallback = selectProjectCallback;
this._openDeleteModalCallback = openDeleteModalCallback;
this._deleteProjectCallback = deleteProjectCallback;
this._deleteButton = new Component(containerElement.querySelector(".project-delete-button"));
this._deleteButton.getContainerElement().addEventListener("click", this._deleteProject.bind(this));
containerElement.addEventListener("mouseenter", () => this._deleteButton.show());
containerElement.addEventListener("mouseleave", () => this._deleteButton.hide());
this._fillTile();
}
getProject() {
return this._project;
}
_deleteProject(event) {
event.stopPropagation();
this._openDeleteModalCallback(this._project.name);
}
_fillTile() {
this._containerElement.querySelector("h3").textContent = this._project.name;
this._containerElement.addEventListener("click", () => this._selectProjectCallback(this._project));
}
/* Creates the following DOM element:
* <div class="project-tile">
* <div class="project-delete-button">
* <img src="images/delete.png" class="positioned-delete-button hidden">
* </div>
* <div class="project-tile-content">
* <img class="project-icon" src="images/project_folder.png">
* <h3></h3>
* </div>
* </div>
*/
static createDomNode() {
const element = document.createElement("div");
element.classList.add("project-tile");
const deleteButtonContainer = document.createElement("div");
deleteButtonContainer.classList.add("project-delete-button");
deleteButtonContainer.classList.add("hidden");
const deleteButton = document.createElement("img");
deleteButton.src = "images/delete.png";
deleteButton.classList.add("positioned-delete-button");
deleteButton.innerHTML = "×";
deleteButtonContainer.appendChild(deleteButton);
element.appendChild(deleteButtonContainer);
const content = document.createElement("div");
content.classList.add("project-tile-content");
const icon = document.createElement("img");
icon.classList.add("project-icon");
icon.src = "images/project_folder.png";
content.appendChild(icon);
const title = document.createElement("h3");
content.appendChild(title);
element.appendChild(content);
return element;
}
}
| true |
7f04cf2ceb3746f3ac3c79afcc82ab0a6186a28d
|
JavaScript
|
wangsterj/mini-apps-1
|
/challenge_4/client/src/components/app.jsx
|
UTF-8
| 5,087 | 3.125 | 3 |
[] |
no_license
|
import React from 'react';
import axios from 'axios';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
board: [],
// player true = player 1, false = 2
player: true,
win: false
}
}
onClick(event) {
if (this.state.win) {
return;
}
var id = event.target.id;
var col = id%10;
var player = '';
var marker = 0;
// checks which player's turn
if (this.state.player) {
player = 'playerUno';
marker = 1;
} else {
player = 'playerDos';
marker = -1;
}
// adds player's piece to the board
for (var role = 5; role >=0;role --) {
if (this.state.board[role][col] === 0) {
this.state.board[role][col] = marker;
document.getElementById(role.toString()+col.toString()).classList.add(player);
break;
}
}
// Check if winning move
if (this.checkWin(role,col)) {
document.getElementById('win').innerHTML=player+ " wins!";
this.state.win = true;
this.post();
}
this.state.player = !this.state.player;
}
post() {
axios.post('http://localhost:3000/post', this.state.board)
.then(function (response) {
console.log("Posted board!");
})
.catch(function (error) {
console.log(error);
});
}
get() {
axios.get('http://localhost:3000/get', {
params: {
ID: 123,
}
})
.then(function (response) {
var board = JSON.parse(response.data[0].board);
this.state.board = board;
console.log(JSON.parse(response.data[0].board));
})
.catch(function (error) {
console.log(error);
});
}
checkWin(Row,Col) {
var result = false;
// check for horizontal win
for (var col = 0; col < 4; col++) {
var sum = this.state.board[Row][col] + this.state.board[Row][col+1] + this.state.board[Row][col+2] + this.state.board[Row][col+3];
if (sum === 4 || sum === -4) {
result = true;
}
}
// Check for vertical win
for (var row = 0; row < 3; row++) {
var sum = this.state.board[row][Col] + this.state.board[row+1][Col] + this.state.board[row+2][Col] + this.state.board[row+3][Col];
if (sum === 4 || sum === -4) {
result = true;
}
}
// Check for major
var startRow = 0;
var startCol = Col - Row;
for (var iRow = startRow; iRow < 3; iRow++) {
var jCol = startCol + iRow;
if (jCol >=0 && jCol <= 6) {
var board = this.state.board;
var sum = board[iRow][jCol]+board[iRow+1][jCol+1]+board[iRow+2][jCol+2]+board[iRow+3][jCol+3];
if (sum === 4 || sum === -4) {
result = true;
}
}
}
// Check for minor
var startRow = 0;
var startCol = Col - Row;
for (var iRow = startRow; iRow < 3; iRow++) {
var jCol = startCol + iRow;
if (jCol >=0 && jCol <= 6) {
var board = this.state.board;
var sum = board[iRow][jCol]+board[iRow+1][jCol-1]+board[iRow+2][jCol-2]+board[iRow+3][jCol-3];
if (sum === 4 || sum === -4) {
result = true;
}
}
}
return result;
}
makeBoard() {
var DOMboard = [];
var cell = [];
for (var row = 0; row < 6; row++) {
this.state.board[row] = [];
var cell = [];
for (var col = 0; col < 7; col++) {
this.state.board[row][col] = 0;
var id = row.toString() + col.toString();
cell.push(<td key = {id} id = {id} onClick={(event) => this.onClick.bind(this)(event)}></td>)
}
DOMboard.push(<tr key ={id} id = {row}>{cell}</tr>);
}
return DOMboard;
}
componentDidMount() {
// this.get();
}
rerender() {
}
reset() {
var DOMboard = [];
var cell = [];
for (var row = 0; row < 6; row++) {
this.state.board[row] = [];
var cell = [];
for (var col = 0; col < 7; col++) {
this.state.board[row][col] = 0;
var id = row.toString() + col.toString();
cell.push(<td key = {id} id = {id} onClick={(event) => this.onClick.bind(this)(event)}></td>)
}
DOMboard.push(<tr key ={id} id = {row}>{cell}</tr>);
}
return DOMboard;
}
render() {
return (
<div>
<table id = 'table'>
{this.makeBoard.bind(this)()}
</table>
<button onClick = {this.post.bind(this)}>POST</button>
<button onClick = {this.get.bind(this)}>GET</button>
<button onClick = {this.reset.bind(this)}>RESET</button>
</div>
);
}
}
function Board(props) {
var board = props.board;
var DOMboard = [];
var cell = [];
for (var row = 0; row < 6; row++) {
var cell = [];
for (var col = 0; col < 7; col++) {
this.state.board[row][col] = 0;
var id = row.toString() + col.toString();
cell.push(<td key = {id} id = {id} onClick={(event) => this.onClick.bind(this)(event)}></td>)
}
DOMboard.push(<tr key ={id} id = {row}>{cell}</tr>);
}
return (
<div>
{DOMboard}
</div>
);
};
export default App;
| true |
71395a465c25904463e2d5d8297a54146819455a
|
JavaScript
|
hashmaparraylist/LeetCode
|
/Algorithms/JavaScript/01 Two Sum/solution.js
|
UTF-8
| 1,599 | 3.8125 | 4 |
[] |
no_license
|
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
var result = [];
var sorted = [];
for(var i = 0; i < nums.length; i++) {
sorted[i] = {
'index': i,
'number': nums[i]
};
}
sorted.sort(function(a, b) {
return a.number - b.number;
});
for(i = 0; i < sorted.length; i++) {
var sub = target - sorted[i].number;
var index = binarySearch(sorted, sub, i + 1, sorted.length - 1);
if (index > -1 && index != i) {
result[0] = (sorted[i].index < sorted[index].index) ? sorted[i].index + 1 : sorted[index].index + 1;
result[1] = (sorted[i].index > sorted[index].index) ? sorted[i].index + 1 : sorted[index].index + 1;
}
}
return result;
};
var bubbleSort = function(nums) {
for(var i = 0; i < nums.length - 1; i++) {
for(var j = 0; j < nums.length - 1 - i; j++) {
if(nums[j].number > nums[j + 1].number) {
var tmp = nums[j + 1];
nums[j + 1] = nums[j];
nums[j] = tmp;
}
}
}
return nums;
};
// binary sort;
var binarySearch = function(arr, target, begin, end) {
if (begin > end) return -1;
var binary = Math.floor((begin + end) / 2);
if (arr[binary].number == target) {
return binary;
}
if (arr[binary].number > target) {
return binarySearch(arr, target, begin, binary - 1);
} else {
return binarySearch(arr, target, binary + 1, end);
}
};
| true |
6dd0ed496c2c4cf202f3424b48593cac3064f3f3
|
JavaScript
|
Ryzl001/reactOdPodstaw
|
/react_app/helloworld/src/HobbyList.js
|
UTF-8
| 755 | 2.984375 | 3 |
[] |
no_license
|
import React, { Component } from 'react';
class HobbyList extends Component {
render() {
const liStyle = {fontSize: '1.5em'}; // camelCase przy nazwie stylu a wartość w cudzysłowie zawsze jako String, musi być zachowany standard JS obiektu
const hobbies = ['Sleeping', 'Eating', 'Cuddling'];
return (
<ul>
{hobbies.map((h, i) => { // każdy element powinien mieć unikalny key (np. id elementu z bazy danych), w tym przypadku używamy numer indeksu danego elementu w tablicy, nie jest to dobre rowziązanie bo w przypadku zmiany kolejności lub ilości elementów w tablicy indeks może ulec zmianie
return <li key={i} style={liStyle}>{h}</li>
})}
</ul>
)
}
}
export default HobbyList;
| true |
414439d540086ba5f82413b08faa359d3c0f39e4
|
JavaScript
|
SamFare/RecrutmentGame
|
/src/Engine/Colider/Colider.js
|
UTF-8
| 473 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
export default class Colider {
haveColided (entity1, entity2) {
if (this.boxXposIntersectsOnLeft(entity1, entity2) &&
entity1.hitBox.getYMax() > entity2.hitBox.getYMin() &&
!(entity2.hitBox.getYMax() < entity1.hitBox.getYMin())) {
return true
}
return false
}
boxXposIntersectsOnLeft (entity1, entity2) {
return entity1.hitBox.getXMax() > entity2.hitBox.getXMin() &&
!(entity1.hitBox.getXMin() > entity2.hitBox.getXMax())
}
}
| true |
cd3e715e6cf181a7b628e869688f69e2f6abe61c
|
JavaScript
|
PaulKatchmark/crafty-maze
|
/maze.js
|
UTF-8
| 8,955 | 2.640625 | 3 |
[] |
no_license
|
window.onload = function () {
"use strict";
var width = 800,
height = 600,
radius = 16,
xCount = Math.floor(width / radius),
yCount = Math.floor(height / radius),
x,
y,
id = 0,
grid = [],
cell,
previousRow = [],
currentRow = [],
previousCell = false,
i,
g,
startCell,
click,
lastTrail,
seconds = 0,
chosenTime = 0,
t,
points = 5,
totalPoints = document.getElementById('totalPoints'),
gameTimer = document.getElementById('gameTimer'),
timeChosen = document.getElementById('timeChosen'),
addTime = document.getElementById('addTime'),
minusTime = document.getElementById('minusTime');
// displaying 0 for your chosen time the first time the page loads or on refresh
timeChosen.textContent = "0";
// when the game begins you will start with 5 points;
totalPoints.textContent = "You start the game with " + points + " points";
// timer displays at top of page and this will add seconds to it.
function add() {
seconds++;
gameTimer.textContent = seconds;
timer();
}
// function to make sure timer increase at correct interval
function timer() {
t = setTimeout(add, 1000);
}
// stops the timer and resets t, so it increases at correct speed next time add() is run
//also doesn't reset "seconds" so will still display correctly when maze is complete
function stopTimer() {
clearTimeout(t);
}
// will stop timer and reset and will also reset display of timer on page
function clearTimer() {
gameTimer.textContent = "0";
stopTimer();
seconds = 0;
}
// adds 1 each time you click the plus button
addTime.onclick = function() {
chosenTime++;
timeChosen.textContent = chosenTime;
}
// subtracts 1 each time you click the minus button
minusTime.onclick = function() {
chosenTime--;
timeChosen.textContent = chosenTime;
}
// will look to see if you chose a time within 10 seconds of the maze completion, if you did you get a point and "cheering" sounds
// if you didn't get within 10 seconds you will lose a point and the crowd will "boo"
function calcPoints() {
var negRange = parseInt(seconds) - 10,
posRange = parseInt(seconds) + 10;
if (chosenTime <= posRange && chosenTime >= negRange){
Crafty.audio.play("earnedPoint", 1, 0.9);
points++;
return points;
}
Crafty.audio.play("lostPoint", 1, 0.9);
points--;
return points
}
// turning support for on
Crafty.support.audio = true;
// path to audio file
Crafty.audio.add({
start: ["assets/sounds/retro-gaming-loop.wav"],
win: ["assets/sounds/smb_world_clear.wav"],
lose: ["assets/sounds/smb_gameover.wav"],
earnedPoint: ["assets/sounds/cheers.wav"],
lostPoint: ["assets/sounds/boos.wav"]
});
Crafty.init(width, height);
Crafty.background('rgb(230,230,230)');
function dfsSearch(startCell, endCell) {
Crafty.trigger('DFSStarted', null);
endCell.drawEndNode();
startCell.drawStartNode();
var currentCell = startCell,
neighborCell,
stack = [],
neighbors = [],
stackPopped = false,
found = false;
currentCell.visited = true;
while (!found) {
// console.log("redTrail");
neighbors = currentCell.getAttachedNeighbors();
if (neighbors.length) {
// if there is a current neighbor that has not been visited, we are switching currentCell to one of them
stack.push(currentCell);
// get a random neighbor cell
neighborCell = neighbors[Math.floor(Math.random() * neighbors.length)];
neighborCell.visited = true;
Crafty.e("Trail").connectNodes(currentCell, neighborCell);
// update our current cell to be the newly selected cell
currentCell = neighborCell;
stackPopped = false;
} else {
stackPopped = true;
if (stack.length === 0) {
// this point can not be found. bail
break;
}
currentCell = stack.pop();
}
if (currentCell.x === endCell.x && currentCell.y === endCell.y) {
found = true;
}
}
if (stack.length) {
stack.push(endCell);
}
Crafty.trigger('DFSCompleted', null);
return stack;
};
click = function () {
Crafty.trigger("MusicStop")
clearTimer();
timer();
// on click, audio begins to play. (audio file, repeat, 90% volume)
Crafty.audio.play("start", -1, 0.9);
// on click, use dfs to search our maze
var stack = dfsSearch(startCell, this),
timeout = 0,
neighbor;
if (stack.length) {
startCell = stack.shift();
while (stack.length) {
neighbor = stack.shift();
timeout = Crafty.e("Trail")
.attr({slow: false, trailColor: 'rgb(0,0,255)'})
.bind("MusicStop", function () {
Crafty.audio.stop();
})
.connectNodes(startCell, neighbor);
startCell = neighbor;
}
//sets the music to stop once maze is complete and a little encouragment for finishing the maze
Crafty.e("Delay").delay(function() {
Crafty.trigger("MusicStop")
stopTimer();
calcPoints();
totalPoints.textContent = "You currently have " + points + " points";
if (points == 7) {
Crafty.trigger("MusicStop");
Crafty.audio.play("win", 1, 0.9);
Crafty.scene('Victory');
} else if (points == 3) {
Crafty.trigger("MusicStop");
Crafty.audio.play("lose", 1, 0.9);
Crafty.scene('Lose');
}
}, timeout, 0);
}
};
// build the grid for our DFS and rendering
for (y = 0; y < yCount; y++) {
// row information is used to assign neighbors
currentRow = [];
for (x = 0; x < xCount; x++) {
id = x * y + y;
cell = Crafty.e("2D, Mouse, Cell")
.attr({id: id, x: x * radius, y: y * radius})
.bind('MouseDown', click);
currentRow.push(cell);
grid.push(cell);
if (previousCell !== false) {
previousCell.addNeighbor(cell);
cell.addNeighbor(previousCell);
}
// set our initial start cell to the center of the maze
if (Math.floor(yCount / 2) === y && Math.floor(xCount / 2) === x) {
startCell = cell;
}
previousCell = cell;
}
if (previousRow.length !== 0) {
for (i = 0; i < previousRow.length; i++) {
previousRow[i].addNeighbor(currentRow[i]);
currentRow[i].addNeighbor(previousRow[i]);
}
}
previousRow = currentRow;
// clear previous cell to prevent wrapped neighbors
previousCell = false;
}
// use dfs to create our maze
function dfsCreate(startCell) {
var currentCell = startCell,
neighborCell,
stack = [],
neighbors = [],
visited = 1;
currentCell.visited = true;
while (visited < grid.length) {
neighbors = currentCell.getUnVisitedNeighbors();
if (neighbors.length) {
// if there is a current neighbor that has not been visited, we are switching currentCell to one of them
stack.push(currentCell);
// get a random neighbor cell
neighborCell = neighbors[Math.floor(Math.random() * neighbors.length)];
visited++;
neighborCell.visited = true;
// while building, on move, knock down the walls!
neighborCell.removeWall(currentCell);
currentCell.removeWall(neighborCell);
// update our current cell to be the newly selected cell
currentCell = neighborCell;
} else {
currentCell = stack.pop();
}
}
}
dfsCreate(grid[Math.floor(Math.random() * grid.length)]);
for (g = 0; g < grid.length; g++) {
grid[g].drawWalls();
}
};
| true |
9f207be187407340f7e624adee38d7cc3bd49e91
|
JavaScript
|
mirza-adnan/testing-demo
|
/functions/reverseString.js
|
UTF-8
| 250 | 3.3125 | 3 |
[] |
no_license
|
function reverseString(text) {
if (typeof text !== "string") return "";
let output = "";
const n = text.length;
for (let i = n - 1; i >= 0; i--) {
output += text[i];
}
return output;
}
module.exports = reverseString;
| true |
31c00026b9d9e090c796a6bbdfbec50d2e594c2f
|
JavaScript
|
amit1307/node-todo-api
|
/playground/mongodb-find.js
|
UTF-8
| 2,119 | 2.703125 | 3 |
[] |
no_license
|
/**
* Created by garga9 on 31/10/2017.
*/
const {MongoClient, ObjectID} = require('mongodb');
MongoClient.connect('mongodb://localhost:27017/ToDoApp', (err, db) => {
if(err) {
return console.log('Unable to connect to db', err);
}
//Find documents which are completed
db.collection('ToDo').find({completed:true}).toArray().then((doc) => {
console.log('ToDo');
console.log(JSON.stringify(doc, undefined, 2));
}, (err) => {
console.log('Unable to read data from DB', err);
});
//Find Users where name is Amit
db.collection('Users').find({name:'Amit'}).toArray().then((doc) => {
console.log('Users with name as Amit');
console.log(JSON.stringify(doc, undefined, 2))
}, (err) => {
console.log('Unable to find users', err);
});
//Count Users with age less than 40
db.collection('Users').find({age:{$lt: 40}}).toArray().then((docs) => {
console.log(`${docs.length} Users less than 40`);
console.log(docs)
}, (err) => {
console.log('Error in filtering users', err);
});
//Count the Users with age less than 40 AND name is Amit
db.collection('Users').find({age:{$lt:40}}, {name:'Amit'}).toArray().then((docs) => {
console.log(`${docs.length} Users less than 40 with name Amit`);
console.log(docs)
}, (err) => {
console.log('Error in filtering users', err)
});
//Count the Users with name as John OR location as London
db.collection('Users').find(
{ $or : [{name:'John'}, {location:'London'}]}
).toArray().then((docs) => {
console.log(`${docs.length} Users with name as John or location as London`);
console.log(docs)
}, (err) => {
console.log('Error in filtering users', err);
});
//Aggregate and match usage
db.collection('Users').aggregate([
{ $match: {name : 'Amit'}}
]).get().then((docs) => {
console.log('Users with name Amit');
console.log(docs);
}, (err) => {
console.log('Error in filtering users', err);
})
});
| true |
5c4dc951be8d97508d2522318ff659df32de86f8
|
JavaScript
|
muramena/Hermes
|
/server/routes/specialist.js
|
UTF-8
| 1,323 | 2.546875 | 3 |
[] |
no_license
|
const express = require('express')
const specialist_controller = require('../controllers/specialist_controller');
/**
* express module
*/
var app = express();
/**
* Gets all specialist from the DB.
* @module specialist
* @function
* @param {String} path
* @param {Function} callback
* @return {Object} - Status, specialist.
*/
app.get('/specialist', specialist_controller.specialist_all);
/**
* Creates specialist and saves it in the DB.
* @module specialist
* @function
* @param {String} path
* @param {Function} callback
* @return {Object} - Status, specialist.
*/
app.post('/specialist', specialist_controller.specialist_create);
/**
* Update a specialist from the DB by ID.
* @module specialist
* @function
* @param {String} path
* @param {Function} callback
* @return {Object} - Status, specialist.
*/
app.put('/specialist/update/:id', specialist_controller.specialist_update_by_id);
/**
* Update a specialist sector from the DB by ID
* @module specialists
* @function
* @param {Object} req - Express request object
* @param {Object} res - Express response object
* @param {Object} id - req.params.id specialist id
* @return {Object} - Status, specialists.
*/
app.put('/specialist/updatesector', specialist_controller.specialist_assign_to_sector_by_id);
module.exports = app;
| true |
050bf29d55e1ba03f64ced4e339217ef754be984
|
JavaScript
|
ashishmadanmca/springboot-react-app
|
/frontend/src/component/AddStudent.jsx
|
UTF-8
| 3,935 | 2.59375 | 3 |
[] |
no_license
|
import React, { Component } from 'react'
import { Formik, Form, Field, ErrorMessage } from 'formik';
import StudentDataService from '../service/StudentDataService';
class AddStudent extends Component {
constructor(props) {
super(props)
this.state = {
id: -1,
name: '',
city: '',
pincode: '',
}
this.onSubmit = this.onSubmit.bind(this)
this.validate = this.validate.bind(this)
}
componentDidMount() {
console.log(this.state.id)
if (this.state.id == -1) {
return
}
}
//Validates the inputs
validate(values) {
let errors = {}
if (!values.name) {
errors.name = '*Please enter name'
} else if (!values.city) {
errors.city = '*Please enter city'
} else if (!values.pincode) {
errors.pincode = '*Please enter pincode'
}
return errors
}
//Submit method for creating student
onSubmit(values) {
let student = {
id: this.state.id,
name: values.name,
city: values.city,
pincode: values.pincode
}
StudentDataService.createStudent(student)
.then((response) => {
console.log("Student created successfully..")
alert("Student added");
this.props.onCloseModel()
}, (error) => {
alert("Error Occured" + error);
});
console.log(values);
}
render() {
let { id, name , city, pincode } = this.state
return (
<div>
<div id="addStudentsContainer" className="container">
<h4 id="addStudentsTitle">Enter Student Details</h4>
<Formik
initialValues={{ id, name , city, pincode }}
onSubmit={this.onSubmit}
validateOnChange={true}
validateOnBlur={true}
validate={this.validate}
enableReinitialize={true}
>
{
(props) => (
<Form>
<fieldset className="form-group">
<label>Name</label>
<Field className="form-control" type="text" name="name" />
<ErrorMessage name="name" component="div"
className="alert alert-warning" />
</fieldset>
<fieldset className="form-group">
<label>City</label>
<Field className="form-control" type="text" name="city" />
<ErrorMessage name="city" component="div"
className="alert alert-warning" />
</fieldset>
<fieldset className="form-group">
<label>Pincode</label>
<Field className="form-control" type="text" name="pincode" />
<ErrorMessage name="pincode" component="div"
className="alert alert-warning" />
</fieldset>
<button id="btnSave" className="" type="submit">Save</button>
</Form>
)
}
</Formik>
</div>
</div>
)
}
}
export default AddStudent;
| true |
a77e77ece2bd36e51de02f4baa52647f684b6c86
|
JavaScript
|
miloshcavitch/3dCodePortfolio
|
/Javascript Examples/huewars/vectorRender.js
|
UTF-8
| 11,667 | 2.984375 | 3 |
[] |
no_license
|
var renderPseudoSprite = function(object, context){
context.translate(unit * object.xCenter, unit * object.yCenter);
context.rotate( object.rotation);
object.shapes.forEach(function(shape){
switch (shape.type){
case 'curvedline':
renderCurvedLine(object, context, shape);
//debugRender(object, context, shape);
break;
case 'polygon':
case 'polyline':
renderPolygon(object, context, shape);
break;
case 'circle':
renderCircle(object, context, shape);
break;
case 'curvedshape':
renderCurvedShape(object, context, shape);
//renderPolygon(object, context, shape);
//debugRender(object,context,shape);
break;
}
});
/*
context.beginPath();
context.moveTo(0,0);
context.lineTo(0,-2000);
context.strokeStyle = 'red';
context.stroke();
context.closePath();
*/
context.rotate(object.rotation * -1);
context.translate( unit * (object.xCenter * -1), unit * (object.yCenter * -1) );
}
var renderPolygon = function(object, context, shape){
context.beginPath();
context.moveTo( unit * (shape.positions[0].x * object.width), unit * (shape.positions[0].y * object.height));
shape.positions.forEach(function(p){
context.lineTo( unit * (p.x * object.width), unit * (p.y * object.height) );
});
context.globalAlpha = shape.globalAlpha;
switch (shape.type){
case 'polyline':
context.strokeStyle = object.colorArray[shape.color];
context.lineWidth = unit * shape.lineWidth * object.width;
context.stroke();
break;
case 'polygon':
context.fillStyle = object.colorArray[shape.color];
context.fill();
if (shape.globalAlpha >= 0.9){
context.lineWidth = unit * 1;
context.strokeStyle = object.colorArray[shape.color];
context.stroke();
}
break;
}
context.closePath();
if (shape.symmetryBool === true){
symmetryRenderPoly(object, context, shape);
}
}
var renderCircle = function(object, context, shape){
context.beginPath();
context.arc( unit * (shape.positions[0].x * object.width), unit * (object.height * shape.positions[0].y), unit *(shape.radius * object.width), 0, Math.PI * 2);
context.globalAlpha = shape.globalAlpha;
if (shape.line === true){
context.strokeStyle = object.colorArray[shape.color];
context.stroke();
} else {
context.fillStyle = object.colorArray[shape.color];
context.fill()
}
context.closePath();
if (shape.symmetryBool === true){
var flippedX = Math.abs(shape.positions[0].x - object.symmetryLine);
if (shape.positions[0].x > object.symmetryLine){
flippedX = flippedX * -1;
}
context.beginPath();
context.arc( unit * (flippedX * object.width), unit * (shape.positions[0].y * object.height), unit * (shape.radius * object.width), 0, Math.PI * 2)
if (shape.line === true){
context.stroke();
} else {
context.fill();
}
context.closePath();
}
}
var renderPolyline = function(object, context, shape){
context.beginPath();
context.moveTo( unit * (shape.positions[0].x * object.width), unit * (shape.positions[0].y * object.height));
shape.positions.forEach(function(p){
context.lineTo( unit * (p.x * object.width), unit * (p.y * object.height));
});
context.lineWidth = unit * shape.lineWidth * object.width;
context.globalAlpha = shape.globalAlpha;
context.strokeStyle = object.colorArray[shape.color];
context.stroke();
context.closePath();
if (shape.symmetryBool == true){
symmetryRenderPoly(object, context, shape);
}
}
var renderCurvedShape = function(object, context, shape){
context.beginPath();
context.moveTo( unit * (shape.positions[0].x * object.width) , unit * (shape.positions[0].y * object.height) );
for (var i = 1; i < shape.positions.length; i+=3){
var lastpoint = {x: undefined, y: undefined};
if (i+3 > shape.positions.length){
lastpoint.x = shape.positions[0].x;
lastpoint.y = shape.positions[0].y;
} else{
lastpoint.x = shape.positions[i+2].x;
lastpoint.y = shape.positions[i+2].y;
}
context.bezierCurveTo( unit * (shape.positions[i].x * object.width), unit * (shape.positions[i].y * object.height), unit * (shape.positions[i+1].x * object.width), unit * (shape.positions[i+1].y * object.height), unit * (lastpoint.x * object.width), unit * (lastpoint.y * object.height) );
}
context.fillStyle = object.colorArray[shape.color];
context.globalAlpha = shape.globalAlpha;
context.fill();
if (shape.globalAlpha >= 0.9){
context.lineWidth = unit * 1;
context.strokeStyle = object.colorArray[shape.color];
context.stroke();
}
context.closePath();
if (shape.symmetryBool === true){
symmetryRenderCurvedShape(object, context, shape);
}
}
var renderCurvedLine = function(object, context, shape){
context.beginPath();
context.moveTo( unit * (shape.positions[0].x * object.width), unit * (shape.positions[0].y * object.height) );
for ( var i = 1; i < shape.positions.length; i+=3){
context.bezierCurveTo( unit * (shape.positions[i].x * object.width), unit * (shape.positions[i].y * object.height), unit * (shape.positions[i+1].x * object.width), unit * (shape.positions[i+1].y * object.height), unit * (shape.positions[i+2].x * object.width), unit * (shape.positions[i+2].y * object.height))
}
context.strokeStyle = object.colorArray[shape.color];
context.globalAlpha = shape.globalAlpha;
context.lineWidth = unit * shape.lineWidth * object.width;
context.stroke();
context.closePath();
if (shape.symmetryBool === true){
symmetryRenderCurvedLine(object, context, shape);
}
}
var symmetryRenderCurvedLine = function(object, context, shape){
context.beginPath();
var initFlippedX = Math.abs(shape.positions[0].x - object.symmetryLine);
if (shape.positions[0].x > object.symmetryLine){
initFlippedX = initFlippedX * -1;
}
context.moveTo( unit * (initFlippedX * object.width), unit * (shape.positions[0].y * object.height) );
for ( var i = 1; i < shape.positions.length; i+=3){
var flippedXOne = Math.abs(shape.positions[i].x - object.symmetryLine);
if (shape.positions[i].x > object.symmetryLine){
flippedXOne *= -1;
}
var flippedXTwo = Math.abs(shape.positions[i+1].x - object.symmetryLine);
if (shape.positions[i+1].x > object.symmetryLine){
flippedXTwo *= -1;
}
var flippedXThree = Math.abs(shape.positions[i+2].x - object.symmetryLine);
if (shape.positions[i+2].x > object.symmetryLine){
flippedXThree *= -1;
}
context.bezierCurveTo( unit * (flippedXOne * object.width), unit * (shape.positions[i].y * object.height), unit * (flippedXTwo * object.width), unit * (shape.positions[i+1].y * object.height), unit * (flippedXThree * object.width), unit * (shape.positions[i+2].y * object.height))
}
context.stroke();
context.closePath();
}
var symmetryRenderPoly = function(object, context, shape){
context.beginPath();
var initFlippedX = Math.abs(shape.positions[0].x - object.symmetryLine);
if (shape.positions[0].x > object.symmetryLine){
initFlippedX = initFlippedX * -1;
}
context.moveTo( unit * (initFlippedX * object.width), unit * (shape.positions[0].y * object.height))
shape.positions.forEach(function(p){
var flippedX = Math.abs(p.x - object.symmetryLine);
if (p.x > object.symmetryLine){
flippedX = flippedX * -1;
}
context.lineTo( unit * (flippedX * object.width), unit * (p.y * object.height) );
});
switch (shape.type){
//no need to set alpha or linewidth etc. already set
case 'polyline':
context.stroke();
break;
case 'polygon':
context.fill();
if (shape.globalAlpha >= 0.9){
context.lineTo( unit * (initFlippedX * object.width), unit * (shape.positions[0].y * object.height));
context.stroke();
}
break;
}
context.closePath();
}
var symmetryRenderCurvedShape = function(object, context, shape){
context.beginPath();
var initFlippedX = Math.abs(shape.positions[0].x - object.symmetryLine);
if (shape.positions[0].x > object.symmetryLine){
initFlippedX = initFlippedX * -1;
}
context.moveTo( unit * (initFlippedX * object.width) , unit * (shape.positions[0].y * object.height) );
for (var i = 1; i < shape.positions.length; i+=3){
var lastpoint = {x: undefined, y: undefined};
if (i+3 > shape.positions.length){
lastpoint.x = Math.abs(shape.positions[0].x - object.symmetryLine);
if (shape.positions[0].x > object.symmetryLine){
lastpoint.x = lastpoint.x * -1;
}
lastpoint.y = shape.positions[0].y;
} else{
lastpoint.x = Math.abs(shape.positions[i+2].x - object.symmetryLine);
if (shape.positions[i+2].x > object.symmetryLine){
lastpoint.x = lastpoint.x * -1;
}
lastpoint.y = shape.positions[i+2].y;
}
var oneX = Math.abs(shape.positions[i].x - object.symmetryLine);
if (shape.positions[i].x > object.symmetryLine){
oneX = oneX * -1;
}
var twoX = Math.abs(shape.positions[i+1].x - object.symmetryLine);
if (shape.positions[i+1].x > object.symmetryLine){
twoX = twoX * -1;
}
context.bezierCurveTo( unit * (oneX * object.width), unit * (shape.positions[i].y * object.height), unit * (twoX * object.width), unit * (shape.positions[i+1].y * object.height), unit * (lastpoint.x * object.width), unit * (lastpoint.y * object.height) );
}
context.fill();
if (shape.globalAlpha >= 0.9){
context.stroke();
}
context.closePath();
}
var debugRender = function(object, context, shape){
shape.positions.forEach(function(p){
context.beginPath();
context.arc( unit * (p.x * object.width), unit * (p.y * object.height), 10, 0, Math.PI * 2);
context.globalAlpha = 0.5;
context.fillStyle = 'black';
context.fill();
context.closePath();
});
}
var debugPoint = function(x, y){
ctx.beginPath();
ctx.arc(x,y,10,0,Math.PI * 2);
ctx.globalAlpha = 0.5;
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
console.log(x + ", " + y);
}
| true |
5b546ec07dc7b87e92471a45085176ae29b9fde4
|
JavaScript
|
BetterBrandAgency/better-boilerplate-documentation
|
/src/scripts/main.js
|
UTF-8
| 5,159 | 2.640625 | 3 |
[] |
no_license
|
var didScroll;
var lastScrollTop = 0;
var delta = 5;
function openOverlay() {
$('.js-overlay').addClass('is-open'); // Find element with the class 'js-menu-container' and apply an additional class of 'is-open'
}
function closeOverlay() {
$('.js-overlay').removeClass('is-open'); // Find element with the class 'js-menu-container' and remove the class 'is-open'
}
function updateOverlayButton() {
$('.js-overlay-button').find('.menu-icon').toggleClass('is-active');
}
function updateMenuButton() {
$('.js-menu-button').find('.menu-icon').toggleClass('is-active');
}
function hasScrolled() {
var st = $('html, body').scrollTop();
if(Math.abs(lastScrollTop - st) <= delta){
return;
}
if (st > lastScrollTop){
$('.hero').addClass('has-scrolled');
}
else {
if (st <= 100) {
$('.hero').removeClass('has-scrolled');
}
}
lastScrollTop = st;
}
jQuery(document).ready(function($){
// Hero
setTimeout(function() {
$('.hero').addClass('has-delayed');
}, 3000);
hasScrolled();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
// Select Menus
$('select').niceSelect();
// Accordions
var accordion__title = '.js-accordion__title';
var accordion__content = '.js-accordion__content';
$(accordion__content).slideUp();
$('.is-active').parent().find(accordion__content).slideDown();
$(accordion__title).click( function () {
$(this).toggleClass('is-active');
$(this).next(accordion__content).slideToggle();
return false;
});
// Carousels
const carousels = $('.js-carousel');
// Generate Slider Objects
$(carousels).each(function() {
var currentSlide = 0;
// Init Sliders and set options
const carousel = new Siema({
selector: this,
duration: 200,
easing: 'ease-out',
perPage: 1,
startIndex: 0,
draggable: true,
threshold: 20,
loop: true,
onInit: activePagination,
onChange: activePagination
});
// Slider autoplay
setInterval(() => carousel.next(), 5000);
// Next and Previous Navigation
const carousel_prev = $(this).parent().find('.js-carousel__prev');
const carousel_next = $(this).parent().find('.js-carousel__next');
$(carousel_prev).click(function() {
carousel.prev();
});
$(carousel_next).click(function() {
carousel.next();
});
// Pagiation
Siema.prototype.addPagination = function() {
const pagination_container = $(this).parent().find('.js-carousel-pagination');
for (let i = 0; i < carousel.innerElements.length; i++) {
const button = document.createElement('button');
button.className = 'carousel__pagination-button carousel__pagination-button--' + i;
button.textContent = i + 1;
if(i === 0) {
button.className ='carousel__pagination-button carousel__pagination-button--' + i + ' is-active';
}
$(button).click(function() {
carousel.goTo(i);
currentSlide = i;
$(this).parent().find('.carousel__pagination-button').removeClass('is-active');
$(this).parent().find('.carousel__pagination-button--' + currentSlide).addClass('is-active');
});
this.selector.parentElement.lastElementChild.appendChild(button);
}
}
// Active States for Pagination
function activePagination() {
currentSlide = this.currentSlide;
$(this.selector).parent().find('.carousel__pagination-button').removeClass('is-active');
$(this.selector).parent().find('.carousel__pagination-button--' + currentSlide).addClass('is-active');
}
// Trigger pagination creator
carousel.addPagination();
});
// Multi Carousel
const multiCarousels = $('.js-multi-carousel');
// Generate Slider Objects
$(multiCarousels).each(function() {
var currentSlide = 0;
// Init Sliders and set options
const carousel = new Siema({
selector: this,
duration: 200,
easing: 'ease-out',
perPage: 1,
startIndex: 0,
draggable: true,
threshold: 20,
loop: true,
perPage: {
800: 1,
1200: 2,
1600: 3
}
});
// Next and Previous Navigation
const carousel_prev = $(this).parent().find('.js-carousel__prev');
const carousel_next = $(this).parent().find('.js-carousel__next');
$(carousel_prev).click(function() {
carousel.prev();
});
$(carousel_next).click(function() {
carousel.next();
});
});
// Menu Button
$('.js-menu-button').click(function(e){
e.preventDefault();
updateMenuButton();
});
// Overlay
$('.js-overlay-open').click(function(){
openOverlay();
updateOverlayButton();
});
$('.js-overlay-close').click(function(){
closeOverlay();
updateOverlayButton();
});
// Detect support of CSS Transforms in SVG
if (supportsCSSTransformsOnSVG) {
$('.hero__illustration').addClass('animation-supported');
}
});
| true |
9b0752722491be82174f20b67f3bda728b6bde95
|
JavaScript
|
FernandoGuardado/Web-API-HW-3
|
/server.js
|
UTF-8
| 8,968 | 2.53125 | 3 |
[] |
no_license
|
// Fernando Guardado
var express = require('express');
var bodyParser = require('body-parser');
var passport = require('passport');
var authJwtController = require('./auth_jwt');
var User = require('./Users');
var jwt = require('jsonwebtoken');
var Movie = require('./Movies');
var dotenv = require('dotenv').config();
var mongoose = require('mongoose');
var port = process.env.PORT || 8080;
// creates application
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
// initialize router
var router = express.Router();
mongoose.connect(process.env.DB , (err, database) => {
if (err) throw err;
console.log("Connected to the database.");
db = database;
console.log("Database connected on " + process.env.DB);
});
//===============================================================================================
// routes
//===============================================================================================
// /postjwt route
router.route('/postjwt')
.post(authJwtController.isAuthenticated, function (req, res) {
console.log(req.body);
res = res.status(200);
if (req.get('Content-Type')) {
console.log("Content-Type: " + req.get('Content-Type'));
res = res.type(req.get('Content-Type'));
}
res.send(req.body);
}
);
//===============================================================================================
// /users/:userID route
router.route('/users/:userId')
.get(authJwtController.isAuthenticated, function (req, res) {
var id = req.params.userId;
User.findById(id, function(err, user) {
if (err) res.send(err);
var userJson = JSON.stringify(user);
// return that user
res.json(user);
});
});
//===============================================================================================
// /users route
router.route('/users')
.get(authJwtController.isAuthenticated, function (req, res) {
User.find(function (err, users) {
if (err) res.send(err);
// return the users
res.json(users);
});
});
//===============================================================================================
// /signup route
router.post('/signup', function(req, res) {
if (!req.body.username || !req.body.password) {
res.json({success: false, msg: 'Please pass username and password.'});
}
else {
var user = new User();
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;
// save
user.save(function(err) {
if (err) {
// duplicate entry
if (err.code == 11000)
return res.json({ success: false, message: 'A user with that username already exists.'});
else
return res.send(err);
}
res.json({ message: 'User created! Welcome ' + req.body.name + '!' });
});
}
});
//===============================================================================================
// /signin route
router.post('/signin', function(req, res) {
var userNew = new User();
userNew.name = req.body.name;
userNew.username = req.body.username;
userNew.password = req.body.password;
User.findOne({ username: userNew.username }).select('name username password').exec(function(err, user) {
if (err) res.send(err);
user.comparePassword(userNew.password, function(isMatch){
if (isMatch) {
var userToken = {id: user._id, username: user.username};
var token = jwt.sign(userToken, process.env.SECRET_KEY);
res.json({success: true, token: 'JWT ' + token});
}
else {
res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
});
});
//===============================================================================================
// /movies route
router.route('/movies')
// get all movies
.get(authJwtController.isAuthenticated, function (req, res) {
Movie.find(function (err, movies) {
if (err) res.send(err);
// return movies
res.json(movies);
});
})
// create a new movie
.post(authJwtController.isAuthenticated, function (req, res) {
if (!req.body.title) {
res.json({ success: false, message: 'You have entered the movie information incorrectly. You where missing the title.' });
}
else if(!req.body.year){
res.json({ success: false, message: 'You have entered the movie information incorrectly. You where missing the year.' });
}else if(!req.body.genre){
res.json({ success: false, message: 'You have entered the movie information incorrectly. You where missing the genre.' });
}else if(!req.body.actors){
res.json({ success: false, message: 'You have entered the movie information incorrectly. You where missing at least one actor.' });
}
else if (req.body.actors.length <= 2) {
res.json({ success: false, message: 'Please add at atleast three actors to the movie.' })
}
else {
var movie = new Movie();
// set inputs to movie data
movie.title = req.body.title;
movie.year = req.body.year;
movie.genre = req.body.genre;
movie.actors = req.body.actors;
// save
movie.save(function(err) {
if (err) {
//d uplicate entry
if (err.code === 11000)
return res.json({ success: false, message: req.body.title + ' already exists in the database!' });
else
return res.send(err);
}
res.json({ message: req.body.title + ' has been created & added to the database.' });
});
}
})
// update a movie
.put(authJwtController.isAuthenticated, function (req, res) {
Movie.findById(req.body._id,function (err, movie) {
if (err) {
res.send(err);
}
else if (!req.body.title) {
res.json({ success: false, message: 'You have entered the movie information incorrectly. You where missing the title.' });
}
else if(!req.body.year){
res.json({ success: false, message: 'You have entered the movie information incorrectly. You where missing the year.' });
}else if(!req.body.genre){
res.json({ success: false, message: 'You have entered the movie information incorrectly. You where missing the genre.' });
}else if(!req.body.actors){
res.json({ success: false, message: 'You have entered the movie information incorrectly. You where missing at least one actor.' });
}
else if (req.body.actors.length <= 2)
{
res.json({ success: false, message: 'Please add at atleast three actors to the movie.' });
}
else {
movie.title = req.body.title;
movie.year = req.body.year;
movie.genre = req.body.genre;
movie.actors = req.body.actors;
movie.save(function(err) {
if (err) {
// duplicate entry
if (err.code === 11000)
return res.json({ success: false, message: req.body.title + ' already exists in the database!' });
else
return res.send(err);
}
res.json({ message: req.body.title + ' has been updated!' });
});
}
});
})
// delete a movie
.delete(authJwtController.isAuthenticated, function (req, res) {
Movie.findByIdAndRemove(req.body._id,function (err, movie) {
if (err) res.send(err);
res.json({ message: req.body.title + ' has been deleted from the database.'});
});
});
//===============================================================================================
app.use('/', router);
app.listen(port);
| true |
bce30f41432c95beb495625167ce4141b9db3020
|
JavaScript
|
rohit-rcrohit7/ClimateMonitorV2
|
/ClimateMonitorV2/public/javascripts/detailedstats.js
|
UTF-8
| 4,882 | 3.015625 | 3 |
[] |
no_license
|
// Everything required once loaded
$(document).ready(() => {
/**
* Multi_date_search, throws a call to the backend to search through multiple dates for sensor details given a sensor id.
* @param {Date} fromDate - Average PM10 Value
* @param {Date} toDate - Average PM2 Value
* @param {int} sensorID - Amount of people this is for
*/
function multi_date_search(fromDate, toDate, sensorID) {
console.log("Going into multi-date-search")
$body = $("body");
jsonData = { from: fromDate, to: toDate, id: sensorID }
$.ajax({
url: '/fromto',
data: JSON.stringify(jsonData),
contentType: 'application/json',
type: 'POST',
success: function (dataR) {
var ret = dataR
console.log("Success Hit")
updateGraphMultiDay(ret)
},
complete: function (data, res) {
console.log("Complete Hit")
console.log(res)
$body.removeClass("loading");
},
error: function (xhr, status, error) {
console.log(error.message);
},
// shows the loader
beforeSend: function () {
$body.addClass("loading");
},
})
}
multi_date_search(new Date("2020-04-01"), new Date("2020-04-29"), 24239)
function updateGraphMultiDay(data) {
var i;
label2 = "PM2.5 Values"
var pm2Data = []
var pm10Data = []
//var pm2Color = []
//var pm10Color = []
//scatterChartPM10.data.datasets = []
//scatterChartPM2.data.datasets = []
console.log(data)
if (data.length == 0) {
alert("Sorry, the data wasn't found!")
} else {
for (j = 1; j < data.length; j++) {
console.log(data[j])
new_data = data[j]
for (i = 1; i < new_data.length; i++) {
date = new Date(new_data[i]['timestamp'])
p2Time = parseFloat(new_data[i]['P2'])
p1Time = parseFloat(new_data[i]['P1'])
pm2 = [date, p2Time] // To input data as an array to work with dygraph
pm10 = [date, p1Time] // To input data as an array to work with dygraph
//pm2Color.push('green')
//pm10Color.push('red')
pm2Data.push(pm2)
pm10Data.push(pm10)
}
}
//scatterChartPM10.data.datasets.push({ label: "Pm10 Data", data: pm10Data, backgroundColor: 'red' })
//scatterChartPM2.data.datasets.push({ label: "Pm2 Data", data: pm2Data, backgroundColor: 'blue' })
//scatterChartPM10.update()
//scatterChartPM2.update()
}
console.log(pm2Data)
var highestPM2Data = Math.max(... pm2Data) //Allows high number in pm2Data to be value range for graph
var highestPM10Data = Math.max(... pm10Data) //Allows high number in pm10Data to be value range for graph
pm2Chart = new Dygraph(document.getElementById('graphdiv3'), pm2Data, {
drawPoints: true,
valueRange: [0.0, highestPM2Data],
labels: ['Date', 'PM2'],
ylabel: 'PM2',
showRoller: true,
rollPeriod: 1, //Changes average period of data on graph
strokeWidth: 1.0,
pointSize: 2
});
pm10Chart = new Dygraph(document.getElementById('graphdiv4'), pm10Data, {
drawPoints: true,
valueRange: [0.0, highestPM10Data],
labels: ['Date', 'PM10'],
ylabel: 'PM10',
showRoller: true,
rollPeriod: 1, //Changes average period of data on graph
strokeWidth: 1.0,
pointSize: 2
});
}
var pm2Chart = document.getElementById('detailedstats').getContext('2d');
var pm10Chart = document.getElementById('detailedstats2').getContext('2d');
/*
var scatterChartPM2 = new Chart(pm2Chart, {
type: 'scatter',
data: {
},
options: {
scales: {
xAxes: [{
type: 'time',
position: 'bottom',
time: {
unit: 'day'
}
}]
}
},
}) */
/*
var scatterChartPM10 = new Chart(pm10Chart, {
type: 'scatter',
data: {
},
options: {
scales: {
xAxes: [{
type: 'time',
position: 'bottom',
time: {
unit: 'day'
}
}]
}
},
}) */
});
| true |
d53b9db2a82ac6f3a041b52a1277af4d5510d601
|
JavaScript
|
bantamer/codewars
|
/src/string/1/highestAndLowest.js
|
UTF-8
| 291 | 3.296875 | 3 |
[] |
no_license
|
function highAndLow(numbers) {
const sorted = numbers.split(' ').sort((a, b) => b - a);
const max = sorted.shift();
const min = sorted.pop();
if (min === undefined) {
return String(max + ' ' + max);
}
return String(max + ' ' + min);
}
console.log(highAndLow('1 2 3 12 -5'));
| true |
5388b159e61fac65d9ddd3a6b319fc23054131de
|
JavaScript
|
tinchodiaz76/AXIOS_API_RICKANDMORTY
|
/src/Components/Personajes/Personajes.js
|
UTF-8
| 1,438 | 2.53125 | 3 |
[] |
no_license
|
import {Row} from "react-bootstrap";
//import PropTypes from "react-PropTypes"
import PropTypes from "prop-types";
import VerPersonaje from "../VerPersonaje/VerPersonaje";
const Personajes = ({personajes}) => {
/*Aca mano a VerPersonaje el objeto completo
return (
<Row className="justify-content-center">
{personajes?.length>0 && personajes.map((item) => ( //personajes?.length>0 Lo ponemos porque posiblemente llegue vacio, espera que tenga elementos y luyego hace el map.
<VerPersonaje personaje={item}/>
)
)}
</Row>
);
Aca mano a VerPersonaje el objeto completo*/
/*Aca mando a VerPersonaje el objeto desestructurado*/
return (
<Row className="justify-content-center">
{personajes?.length>0 && personajes.map((item) => <VerPersonaje {...item} />)}
</Row>
);
/*Aca mando a VerPersonaje el objeto desestructurado*/
};
Personajes.propTypes = {
personajes : PropTypes.arrayOf( //Es un array de objetos
PropTypes.shape({
created : PropTypes.string,
gender : PropTypes.string,
id : PropTypes.string,
name : PropTypes.string,
species : PropTypes.string,
status : PropTypes.string,
}).isRequired
),
};
export default Personajes;
| true |
ec561a9599458be00c7a2ee05c27ca7b8843f5a8
|
JavaScript
|
misterdebbie/dChong_Assignment3
|
/app_server/routes/restaurants.js
|
UTF-8
| 3,803 | 2.578125 | 3 |
[] |
no_license
|
var util = require('util');
var Db = require('mongodb').Db,
Server = require('mongodb').Server,
ObjectID = require('mongodb').ObjectID;
//dependency on mongoDB driver
//expose Db, Server, ObjectID
//connect to localhost
//port 27017 is mongoDB default
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('test', server);
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'restaurant' database");
db.collection('restaurants', {strict:true}, function(err, collection) {
if (err) {
console.log("The 'restaurants' collection doesn't exist.");
}
});
}
});
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving restaurant: ' + id);
db.collection('restaurants', function(err, collection) {
collection.findOne({'_id': new ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
//issue a query to the restaurants collectiom
//toArray method will consume the result set, produce an array and pass to the callback, items parameter!
exports.findAll = function(req, res) {
console.log('Retrieving all restaurants');
db.collection('restaurants', function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
exports.addRestaurant = function(req, res) {
var restaurant = req.body;
console.log('Adding restaurant: ' + JSON.stringify(restaurant));
db.collection('restaurants', function(err, collection) {
collection.insert(restaurant,{safe:true},function(err, result) {
if (err){
res.send({'error': 'Something is wrong!'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
};
exports.updateRestaurant = function(req, res) {
var id = req.params.id;
var restaurant = req.body;
console.log('Updating restaurant: ' + id);
console.log(JSON.stringify(restaurant));
db.collection('restaurants', function(err, collection) {
collection.update({'_id':new ObjectID(id)}, restaurant,{safe:true},(function(err, result) {
if (err){
console.log('Error updating restaurant: ' + err);
res.send({'error': 'Something is wrong!'});
} else {
console.log('Success: ' + result + ' updated');
res.send(restaurant);
}
}));
});
};
exports.deleteRestaurant = function(req, res) {
var id = req.params.id;
console.log('Deleting restaurant: ' + id);
db.collection('restaurants', function(err, collection) {
collection.remove({'_id':new ObjectID(id)}, {safe:true},(function(err, result) {
if (err){
res.send({'error': 'Something is wrong!'});
} else {
console.log('Success: ' + result + ' deleted');
res.send(req.body);
}
}));
});
};
/*
exports.update = function(req, res) {
/*console.log('Retrieving all restaurants');
db.collection('restaurants', function(err, collection) {
collection.find().toArray(function(err, items) {
//res.send(items);*/
//res.render('test',{title: 'good morning'})
//});
// });
//}
//exports.confirm = function(req, res) {
/*console.log('Retrieving all restaurants');
db.collection('restaurants', function(err, collection) {
collection.find().toArray(function(err, items) {
//res.send(items);
var updateName = req.body.name;
var updateBorough = req.body.borough;
res.send(updateName,updateBorough);
//});
// });
};*/
| true |
95919867a0b599d342841a980f2a363583c573e0
|
JavaScript
|
MarlonEFE/eco
|
/ProyectoDW/js/slider.js
|
UTF-8
| 440 | 2.703125 | 3 |
[] |
no_license
|
var c=1;
var j=document.getElementById('js');
function carrusel(){
j.style.opacity="0";
j.style.transition="all 1s";
setTimeout("cambio()",1000);
}
function cambio(){
c++;
if(c>3){
c=1;
}
j.setAttribute("src","../img/hogar/ban"+c+".jpg");
j.style.opacity="1";
j.style.transition="all 1s";
setTimeout("carrusel()",2000);
}
document.body.setAttribute("onload","carrusel()");
| true |
c28575ecd87f2296a2cd8fddf6d283085d913bb6
|
JavaScript
|
ArmitageRU/HTML5
|
/js/Route.js
|
UTF-8
| 582 | 2.9375 | 3 |
[] |
no_license
|
"use strict";
function Route(startPoint){
this.from = startPoint;
this.to = null;
this.actualLength = null;
this.elapsedTime=0;
};
Route.prototype = {
RenderPath:function(ctx, frameTime){
if(this.from!=null && this.to !=null){
var grad= ctx.createLinearGradient(this.from.x, this.from.y, this.to.x, this.to.y);
grad.addColorStop(0, "green");
grad.addColorStop(1, "red");
ctx.beginPath();
ctx.moveTo(this.from.x, this.from.y);
ctx.lineTo(this.to.x, this.to.y);
ctx.strokeStyle = grad;
ctx.lineWidth = 7;
ctx.stroke();
}
}
}
//28, 804 - 227, 967
| true |
9420585fa5f644001cb8121b4ce8c581aad661bd
|
JavaScript
|
marlonyDevelopers/Engine1.1
|
/src/engine/communications/gameType/bingo/BingoMessageDecoder.js
|
UTF-8
| 17,657 | 2.578125 | 3 |
[] |
no_license
|
(function(window){
function BingoMessageDecoder(){
var game;
var _this = this;
var lastWin = 0;
var nextExtraCost = 0;
var currentExtraPosition = 1;
var duringPlayLoader;
//public functions
this.setGameType = function(gameType){
game = gameType;
if(game.gameConfig.loadCardsStateDuringPlay){
duringPlayLoader = new DuringPlayStateLoader(game);
}
}
this.decodeServerMessage = function(message){ //(message:Array):BaseResponse{
var response;
if (message[0] == "&&") {
switch(message[1]){
case 'L':
response = decodeLoginMessage(message);
break;
case 'I':
response = decodeInitMessage(message);
break;
case 'CB':
response = decodeChangeBetMessage(message);
break;
case 'CN':
response = decodeChangeCardNumbersMessage(message);
break;
case 'CCC':
response = decodeChangeConfigCards(message);
break;
case 'W':
response = decodePlayResponse(message);
break;
case 'GEB':
case 'GEBE':
response = decodeExtraBallResponse(message);
break;
case 'CEB':
response = decodeCancelExtraBallResponse(message);
break;
case 'CC':
response = decodeChangeCoinResponse(message);
break;
case 'GC':
response = decodeGetCreditsResponse(message);
break;
case 'CS':
response = decodeChangeStage(message);
break;
case 'J':
response = decodeJackpotResponse(message);
break;
case 'NJS':
response = decodeJackpotShow(message);
break;
default:
response = decodeConnLostResponse(message);
break;
}
}else{
alert("Server message format error");
}
return response;
}
this.getLastWin = function(){
return lastWin;
}
this.getNextExtraCost = function(){
return nextExtraCost;
}
//private functions
function decodeLoginMessage(message){ //message:Array):LoginResponse{
console.log('--> login '+ message.toString());
var response = {};//:LoginResponse = new LoginResponse();
response.type = "LoginResponse";
response.status = message[2];
return response;
}
function decodeInitMessage(message){
console.log('--> init '+ message.toString());
var response = new InitResponse();
response.coin = game.coin = message[2];
response.credits = message[3] / game.coin;
response.credits_in_cash = (parseInt(message[3]))/100;
response.win = message[4];
response.win_in_cash = response.win * (game.coin/100);
response.jackpot = message[5]/100;
response.bet = game.bet = message[6];
response.freeBallsPosition = message[8];
var openCards = message[7].split("");
var index = 9;
for(var i = 0; i < openCards.length; i++){
var card = new BingoCardsData(); //var card:BingoCardsData
card.addNumbersFromString(message[index]);
card.enabled = (openCards[i] == 0) ? false : true;
response.cards.push(card);
index++;
}
response.totalBet = response.bet * countOpenCards(response.cards);
var drawBalls = message[index].split(";");
index++;
for(i = 0; i < drawBalls.length; i++){
response.drawnBalls.push(drawBalls[i]);
}
response.bonusData = message[14];
response.firstTime = message[15];
response.specialValue = message[16]/100;
game.setCards(response.cards);
return response;
}
function decodeChangeCardNumbersMessage(message){
console.log('--> ChangeCardNumbers '+ message.toString());
var response = new ChangeCardNumbersResponse();//{};
var cards = message.length;
for(var i = 2; i < cards; i++){
var card = new BingoCardsData();
card.addNumbersFromString(message[i]);
response.cards.push(card);
}
game.setCards(response.cards);
return response;
}
function decodeGetCreditsResponse(message){
var response = new GetCreditsResponse(); //{};
//response.type = "GetCreditsResponse";
response.credits = message[2] / game.coin;
response.credits_in_cash = (parseInt(message[2]))/100;
response.jackpot = message[3]/100;
response.specialValue = message[4]/100;
return response;
}
function decodePlayResponse(message){
if(game.gameConfig.loadCardsStateDuringPlay) duringPlayLoader.reset();
for(var i = 0; i < game.cards.length; i++){
game.cards[i].reset();
}
currentExtraPosition = 1;
var response = new PlayResponse();
response.credits = message[2] / game.coin;
response.credits_in_cash = (parseInt(message[2])) / 100;
lastWin = response.win = message[3];
response.win_in_cash = response.win * (game.coin/100);
response.jackpot = message[4]/100;
if(message[13] > 0){
response.toPayJackpot = true;
response.toPayJackpotValue = message[13];
}
response.bonusData = message[9];
response.bonusExtraData = message[10]; //nombre protocolo: Bonus Data Position
response.bonusData2 = message[14];
response.hasExtra = (message[6] == "0") ? false : true;
response.extraCost = message[7];
var freeExtra = message[8].split(";");
for(i = 0; i < freeExtra.length; i++){
response.freeExtraPos.push(freeExtra[i]);
}
response.specialValue = message[15]/100;
nextExtraCost = response.extraCost;
var drawnBalls = message[5].split(";");
for(i = 0; i < drawnBalls.length; i++){
response.drawnBalls.push(drawnBalls[i]);
tryToMarkNumber(drawnBalls[i], response);
}
var winPaid = JSON.parse(message[11]);// as Array;
response.winPaid = processWinPaidArray(winPaid);
var willPayList = JSON.parse(message[12]); //as Array;
response.willPay = processWillPayArray(willPayList);
response.cardsData = game.cards;
//to print duringPLayData -> printDuringPlayData = 1 in game bingoGameConfig.js
if(game.gameConfig.loadCardsStateDuringPlay && game.gameConfig.printDuringPlayData) duringPlayLoader.printDuringPLayData(response);
return response;
}
function decodeExtraBallResponse(message){ //(message:Array):GetExtraBallResponse{
for(var i = 0; i < game.cards.length; i++){
game.cards[i].changedfunc(false); //era changed(false) pero tenia 2 definiciones una funcion y otra variable incompatibles y saltaba
}
var response = new GetExtraBallResponse();
response.credits = message[2] / game.coin;
response.credits_in_cash = (parseInt(message[2]))/100;
lastWin = response.win = message[3];
response.win_in_cash = response.win * (game.coin/100);
response.jackpot = parseInt(message[4])/100;
response.bonusData = message[8];
response.bonusExtraData = message[11]; //nombre protocolo: Bonus Data Position
response.bonusData2 = message[12];
response.currentExtraPosition = currentExtraPosition;
//quita el win de ultima extra.
var index = game.gameConfig.numberOfExtraBalls;
if( currentExtraPosition == index){
response.credits -= response.win;
response.credits_in_cash -= response.win_in_cash;
}
response.ball = message[5];
tryToMarkNumber(response.ball);
response.hasMoreExtras = (message[6] == "0") ? false : true;
response.nextExtraCost = message[7];
nextExtraCost = response.nextExtraCost;
var winPaid = JSON.parse(message[9]);
response.winPaid = processWinPaidArray(winPaid);
var willPay = JSON.parse(message[10]);
response.willPay = processWillPayArray(willPay);
currentExtraPosition++;
response.cardsData = game.cards;
response.specialValue = message[12]/100;
return response;
}
function decodeCancelExtraBallResponse(message){ //(message:Array):CancelExtraBallResponse{
for(var i = 0; i < game.cards.length; i++){
game.cards[i].reset();
}
var response = new CancelExtraBallResponse();
response.credits = message[2] / game.coin;
response.creditsEnd = message[2] / game.coin;
response.credits_in_cash = (parseInt(message[2]))/100;
response.jackpot = parseInt(message[3])/100;
response.win = lastWin;
response.win_in_cash = response.win * (game.coin/100);
response.credits -= lastWin;
//A cambiar - ticket id: 15220
response.credits_in_cashEnd = response.credits_in_cash;
response.credits_in_cash -= response.win_in_cash;
var balls = message[4].split(";");
var params = ApplicationController.getApplicationController().parameters;
var willPay = (params.is_log && params.logData) ? calculateCancelPayFromLog(params.logData) : message[5].split(";");
if(balls.length != willPay.length){
alert("Error on cancel extra ball, the server sent different ball and ball pays numbers");
}
for(i = 0; i < balls.length; i++){
response.remainingBalls.push({ballNumber:balls[i], win:willPay[i] * game.bet});
}
return response;
}
function tryToMarkNumber(number, response){ //(number:int, response:PlayResponse = null):void{
for(var i = 0; i < game.cards.length; i++){
if(game.cards[i].enabled){
for(var j = 0; j < game.cards[i].numbers.length; j++){
if(game.cards[i].enabled && game.cards[i].numbers[j] == number){
game.cards[i].boxes[j].setMarked(true);
if(game.gameConfig.loadCardsStateDuringPlay && response.type == "PlayResponse"){
duringPlayLoader.loadCurrentBallData(number, i, j, response);
}
break;
}
}
}
}
}
function processWinPaidArray(winPaid){ //(winPaid:Array):Vector.<WinPrizes>{
/*
ver si JSON.parse() funciona en los otros navegadores.
LLega un array con 4 array adentro descodificando esto: [[],[],[],[6,11,13]]
1 vacio
2 vacio
3 vacio
4 lenht = 3 6,11,13
*/
var list = [];
for(var i = 0; i < winPaid.length; i++){
//objeto "WinPrizes".
var win = {};
win.cardNumber = i;
win.prizes = new Array();
win.prizesIndexes = new Array();
var hasWonSomething = false;
if(game.cards[i].hasChanged){
game.cards[i].setTotalWin(0);
}
for(var j = 0; j < winPaid[i].length; j++){
hasWonSomething = true;
var prizeIndex = winPaid[i][j];
//objeto "Prize".
var prize = {};
prize.index = prizeIndex;
prize.name = game.gameConfig.prizes[prizeIndex].name;
win.prizesIndexes.push(prizeIndex);
win.prizes.push(prize);
if(game.cards[i].enabled){
if(game.cards[i].hasChanged){
game.cards[i].addWin(game.gameConfig.prizes[prizeIndex].pay * game.bet);
}
}
}
if(hasWonSomething){ list.push(win); }
}
return list;
/*
var list = [];
for(var i = 0; i < winPaid.length; i++){
var win = new WinPrizes(i);
var hasWonSomething = false;
if(game.cards[i].hasChanged){
game.cards[i].setTotalWin(0);
}
for(var j = 0; j < winPaid[i].length; j++){
hasWonSomething = true;
var prizeIndex = winPaid[i][j];
var prize = new Prize();
prize.index = prizeIndex;
prize.name = game.gameConfig.prizes[prizeIndex].name;
win.prizesIndexes.push(prizeIndex);
win.prizes.push(prize);
if(game.cards[i].enabled){
if(game.cards[i].hasChanged){
game.cards[i].addWin(game.gameConfig.prizes[prizeIndex].pay * game.bet);
}
}
}
if(hasWonSomething){ list.push(win); }
}
return list;*/
}
function processWillPayArray(willPayList){ //(willPayList:Array):Vector.<WillPay>{
// [[1, 1, 1, [17]], [3, 0, 0, [3]], [3, 0, 3, [9]]]
var list = [];
for(var i = 0; i < willPayList.length; i++){
if(willPayList[i].length == 4){
//objeto "willPay".
var willPay = {}; //new WillPay(willPayList[i][0], willPayList[i][1], willPayList[i][2]);
willPay.card = willPayList[i][0];
willPay.line = willPayList[i][1];
willPay.column = willPayList[i][2];
willPay.boxIndex = willPay.column + (willPay.line * 5);
willPay.boxTotalWin = 0; //se setea mas abajo
willPay.prizeIndexList = new Array();
for(var j = 0; j < willPayList[i][3].length; j++){
willPay.prizeIndexList.push(willPayList[i][3][j]);
//new:
console.log("->>>" + typeof ApplicationController.getApplicationController().getGameConfig().prizes);
console.log("->>>" + ApplicationController.getApplicationController().getGameConfig().prizes.length);
console.log("->>>" + ApplicationController.getApplicationController().getGameConfig().prizes[willPayList[i][3][j]]);
console.log("->>>" + willPayList);
console.log("->>>" + willPayList[i].length);
console.log("->>>" + willPayList[i][3].length);
console.log("->>>" + willPayList[i][3][j]);
// ->>>object
// ->>>17
// ->>>undefined
// ->>>4
// ->>>1
// ->>>17
/*
El probelma es que busca por el indice, viene 17, pero
*/
willPay.boxTotalWin += ApplicationController.getApplicationController().getGameConfig().prizes[willPayList[i][3][j]].pay * game.bet;
}
if(willPay.prizeIndexList.length > 0){
list.push(willPay);
var box = game.cards[willPay.card].boxes[getIndexByColAndRow(willPay.column, willPay.line, game.gameConfig.cardsSize.x)];
var changed = false;
for(var x = 0; x < willPay.prizeIndexList.length; x++){
var index = willPay.prizeIndexList[x];
if(!box.hasAlmost(index)){
changed = true;
box.addAlmost(index, game.gameConfig.prizes[index].pay * game.bet);
}
}
if(!changed){
box.changed(false);
}
}
}
}
return list;
/*
var list = [];
for(var i = 0; i < willPayList.length; i++){
if(willPayList[i].length == 4){
var willPay = new WillPay(willPayList[i][0], willPayList[i][1], willPayList[i][2]);
for(var j = 0; j < willPayList[i][3].length; j++){
willPay.prizeIndexList.push(willPayList[i][3][j]);
//new:
willPay.boxTotalWin += ApplicationController.getApplicationController().gameConfig.prizes[willPayList[i][3][j]].pay * game.bet;
}
if(willPay.prizeIndexList.length > 0){
list.push(willPay);
var box = game.cards[willPay.card].boxes[getIndexByColAndRow(willPay.column, willPay.line, game.gameConfig.cardsSize.x)];
var changed = false;
for(var x = 0; x < willPay.prizeIndexList.length; x++){
var index = willPay.prizeIndexList[x];
if(!box.hasAlmost(index)){
changed = true;
box.addAlmost(index, game.gameConfig.prizes[index].pay * game.bet);
}
}
if(!changed){
box.changed(false);
}
}
}
}
return list;*/
}
function getIndexByColAndRow(column, row, totalColumns){ //(column:int, row:int, totalColumns:int):int{
var pos = column + (row * totalColumns);
return pos;
}
function countOpenCards(cards){
var openCards = 0;
for(var i = 0; i < cards.length; i++){
if(cards[i].enabled){
openCards++;
}
}
return openCards;
}
function calculateCancelPayFromLog(logData){ //(logData:LogData):Array{
alert("TODO: bingoMessageDecoder.js -> calculateCancelPayFromLog");
/*
var willPay:Array = new Array();
var ocurrences:Dictionary = new Dictionary();
var wins:Array;
var lastWin:String = "";
for(var i:int = 0; i <= logData.buyedExtraBalls; i++){
if(lastWin != logData.priceIndexes[i]){
lastWin = logData.priceIndexes[i];
wins = logData.priceIndexes[i].split(",");
for(var j:int = 0; j < wins.length; j++){
var count:int = lastWin.split(wins[j]).length;
if(wins[j] in ocurrences && ocurrences[wins[j]] < count){
ocurrences[wins[j]] = count;
}else{
ocurrences[wins[j]] = 1;
}
}
}
}
for(i; i <logData.priceIndexes.length; i++){
if(lastWin != logData.priceIndexes[i]){
lastWin = logData.priceIndexes[i];
wins = logData.priceIndexes[i].split(",");
var lineOcurrences:Dictionary = new Dictionary();
for(var l:int = 0; l < wins.length; l++){
if(wins[l] in lineOcurrences){
lineOcurrences[wins[l]] += 1;
}else{
lineOcurrences[wins[l]] = 1;
}
}
var prizePay:int = 0;
for(var key:String in lineOcurrences){
var prev:int = (ocurrences.hasOwnProperty(key)) ? ocurrences[key] : 0;
var newCount:int = lineOcurrences[key];
var dif:int = newCount - prev;
if(dif > 0){
ocurrences[key] = (ocurrences.hasOwnProperty(key)) ? ocurrences[key] + dif : dif;
prizePay += getPrizePay(key) * dif;
}
}
willPay.push(prizePay);
}else{
willPay.push(0);
}
}
function getPrizePay(prizeName:String):int{
var gameConfig:BingoGameConfig = ApplicationController.getApplicationController().gameType.gameConfig as BingoGameConfig;
for(var i:int = 0; i < gameConfig.prizes.length; i++){
if(gameConfig.prizes[i].name == prizeName){
return gameConfig.prizes[i].pay;
}
}
return null;
}
return willPay;*/
}
}
//to global scope access:
window.BingoMessageDecoder = BingoMessageDecoder;
}(window));
| true |
cc4e9882e4ba9aba8fd1373e7f79da593df99708
|
JavaScript
|
eunicode/algos
|
/cw/6-shell-game.js
|
UTF-8
| 4,698 | 4.1875 | 4 |
[] |
no_license
|
/* =================================================================
INSTRUCTIONS
================================================================= */
/*
The Shell Game
https://www.codewars.com/kata/546a3fea8a3502302a000cd2
"The Shell Game" involves three shells/cups/etc upturned on a playing surface, with a ball placed underneath one of them.
The shells are then rapidly swapped round, and the game involves trying to track the swaps and, once they are complete, identifying the shell containing the ball.
This is usually a con, but you can assume this particular game is fair...
Your task is as follows.
Given the shell that the ball starts under, and list of swaps, return the location of the ball at the end.
All shells are indexed by the position they are in at the time.
For example, given the starting position 0 and the swap sequence [(0, 1), (1, 2), (1, 0)]:
- The first swap moves the ball from 0 to 1
- The second swap moves the ball from 1 to 2
- The final swap doesn't affect the position of the ball.
So
swaps = [[0,1], [1,2], [1, 0]]
find_the_ball(0, swaps) == 2
*/
/* =================================================================
SOLUTIONS
================================================================= */
/*
*/
/* =================================================================
CODE
================================================================= */
/* eslint-disable */
const find_the_ball = function(start, swaps) {
// If there is no swapping, the ball is in the start position
if (swaps.length === 0) {
return start;
}
// Find the highest index of a cup
const numOfCups = swaps.reduce((acc, curr) => {
// `swaps` is a 2D array. Find the greatest number in the sub-array
const greater = curr[0] > curr[1] ? curr[0] : curr[1];
// Compare the greatest number in sub-array #1 and sub-array #2. Return the greater number.
return acc > greater ? acc : greater;
}, 0);
console.log({ numOfCups });
// Generate an array with elements 1 - numOfCups
// const record = ["A", "B", "C"];
const record = [];
for (let i = 0; i < numOfCups; i++) {
record.push(i);
}
console.log({ record });
// ES6 method
// const recordES6 = [...new Array(numOfCups).keys()];
// console.log({ recordES6 });
// const ball = record[start]; // `start` is 0, so ball is under cup "A"
const ball = start;
swaps.forEach(elm => {
// elm = [0,1]
const firstPos = elm[0]; // 0
const secondPos = elm[1]; // 1
// Save this value before it gets overwritten
const temp = record[firstPos]; // record[0] // "A"
record[firstPos] = record[secondPos]; // record[0] = record[1] // index 0 => "B"
record[secondPos] = temp; // record[1] // index 1 => "A"
});
// console.log({ record }); // ["C", "B", "A"]
// Ball was under cup "A", what position/"index" is "A" at now?
const locationOfBall = record.indexOf(ball);
console.log({ locationOfBall });
return locationOfBall; // "index" 2
};
/* =================================================================
TESTS
================================================================= */
// An empty swap does nothing
console.log(find_the_ball(5, []));
// 5
console.log(find_the_ball(0, [[0, 1], [2, 1], [0, 1]]));
// 2
/* =================================================================
NOTES
================================================================= */
/*
CHALLENGE OVERVIEW
The best way to think about this problem is to draw it out.
Imagine we have 3 cups, "A", "B" and "C"
record = [A, B, C]
The original position of A is index 0, the original position of B is index 1, etc
0 1 2
A B C
We put the ball under cup A.
Then we start swapping cups.
[0, 1], [2, 1], [0, 1]
Swap #1: B A C // [B, A, C]
Swap #2: B C A // [B, C, A]
Swap #3: C B A // [C, B, A]
In my code though, I labeled the cups 1, 2, 3.
Swap #0: [1, 2, 3]
Swap #1: [2, 1, 3]
Swap #2: [2, 3, 1]
Swap #3: [3, 2, 1]
The indices of the array are the three slots or positions. They don't change.
The values of the array are the cups. The cups' positions get switched.
--------------------------------------------------------------------
MAP
new Map()
new Map([ ["A", 1], ["B", 2] ])
{
"A" => 1,
"B" => 2
}
map.set(key, value)
map.set("A", 100)
{
"A" => 100,
"B" => 2
}
map.set("C", 3)
{
"A" => 100,
"B" => 2,
"C" => 3
}
With Maps, "keys" can be objects.
*/
/* =================================================================
TO DO
================================================================= */
/*
Solve more efficiently
*/
/*
--------------------------------------------------------------------
*/
| true |
e435ad7e4c9e45042755ae904480895fcb1ac6a7
|
JavaScript
|
begriffs/decaying-accumulator
|
/test/test.js
|
UTF-8
| 6,362 | 2.65625 | 3 |
[] |
no_license
|
var DecayingAccumulator = require('../DecayingAccumulator'),
chai = require('chai'),
assert = chai.assert,
expect = chai.expect,
sinon = require('sinon'),
_ = require('underscore'),
freezeTime = function(epoch) {
if(Date.prototype.getTime.restore) {
Date.prototype.getTime.restore();
}
sinon.stub(Date.prototype, 'getTime', function() { return epoch; });
};
describe('DecayingAccumulator', function() {
var dac, decayUnit = 1000;
beforeEach(function() {
dac = new DecayingAccumulator({decaySpeed: decayUnit});
freezeTime(0);
});
describe('#currentValue()', function() {
context('when called initially', function() {
it('should start at zero', function() {
assert.equal(dac.currentValue(), 0);
});
it('the first vote counts fully', function() {
dac.nudge(1);
assert.equal(dac.currentValue(), 1);
});
it('two votes count as one', function() {
dac.nudge(1);
dac.nudge(1);
assert.equal(dac.currentValue(), 1);
});
it('the first downvote counts fully', function() {
dac.nudge(-1);
assert.equal(dac.currentValue(), -1);
});
it('two downvotes count as one', function() {
dac.nudge(-1);
dac.nudge(-1);
assert.equal(dac.currentValue(), -1);
});
it('conflicting votes cancel', function() {
dac.nudge(1);
dac.nudge(-1);
assert.equal(dac.currentValue(), 0);
});
it('a large vote rescales the axis', function() {
dac.nudge(2);
dac.nudge(-1);
assert.equal(dac.currentValue(), 0.5);
});
it('a large internal vote does not rescale', function() {
dac.nudge(-1);
dac.nudge(2);
assert.equal(dac.currentValue(), 1);
});
});
context('when called over time', function() {
it('decays downward fully after one decay unit', function() {
dac.nudge(1);
freezeTime(decayUnit);
assert.equal(dac.currentValue(), 0);
});
it('does not jitter at zero', function() {
dac.nudge(1);
freezeTime(decayUnit * 0.9);
dac.currentValue();
freezeTime(decayUnit * 1.001);
assert.equal(dac.currentValue(), 0);
});
it('decays downward fully even with more nudges', function() {
dac.nudge(1);
dac.nudge(1);
freezeTime(decayUnit);
assert.equal(dac.currentValue(), 0);
});
it('decays upward fully after one decay unit', function() {
dac.nudge(-1);
freezeTime(decayUnit);
assert.equal(dac.currentValue(), 0);
});
it('if unmoved it remains at zero forever', function() {
assert.equal(dac.currentValue(), 0);
freezeTime(decayUnit * 1000000);
assert.equal(dac.currentValue(), 0);
});
it('does not decay below zero once nudged', function() {
dac.nudge(1);
freezeTime(decayUnit * 2);
assert.equal(dac.currentValue(), 0);
});
it('decays monotonically', function() {
dac.nudge(1);
var samples = _.map(
[0, 0.25, 0.5, 1],
function (t) {
freezeTime(t*decayUnit);
return dac.currentValue();
}
);
_.each([0,1,2], function (i) {
expect(samples[i]).to.be.above(samples[i+1]);
});
});
it('maxes out at one even after some decay', function() {
dac.nudge(1);
freezeTime(decayUnit / 2);
dac.nudge(1);
assert.equal(dac.currentValue(), 1);
});
it('builds tolerance after nudges', function() {
dac.nudge(1);
dac.nudge(1);
dac.nudge(1);
dac.nudge(1);
freezeTime(decayUnit);
dac.nudge(1);
assert.equal(dac.currentValue(), 0.25);
});
it('does not change its rate of decay when observed', function() {
var dac2 = new DecayingAccumulator(decayUnit);
dac.nudge(1);
dac2.nudge(1);
freezeTime(decayUnit / 4);
dac.currentValue();
freezeTime(decayUnit / 3);
dac.currentValue();
freezeTime(decayUnit / 2);
dac.currentValue();
assert.equal(dac.currentValue(), dac2.currentValue());
});
it('does not change its rate of decay by vote frequency', function() {
var dac2 = new DecayingAccumulator(decayUnit);
dac.nudge(1);
dac2.nudge(1);
dac2.nudge(1);
dac2.nudge(1);
freezeTime(decayUnit / 2);
assert.equal(dac.currentValue(), dac2.currentValue());
});
});
context('constructed with extended options', function() {
it('provides defaults if necessary', function() {
dac = new DecayingAccumulator();
dac.nudge(1);
assert.equal(dac.currentValue(), 1);
});
it('can override the initial scale', function() {
dac = new DecayingAccumulator({decaySpeed: decayUnit, currentScale: 4});
dac.nudge(1);
assert.equal(dac.currentValue(), 0.25);
});
});
});
describe('#nudge()', function() {
context('cooldown', function() {
beforeEach(function() {
dac = new DecayingAccumulator({
decaySpeed: decayUnit,
cooldownSpeed: decayUnit * 3
});
});
it('regains full strength after enough inactivity', function() {
dac.nudge(2);
freezeTime(decayUnit * 3);
dac.nudge(1);
assert.equal(dac.currentValue(), 1);
});
context('shorter than decay time', function() {
beforeEach(function() {
dac = new DecayingAccumulator({
decaySpeed: decayUnit,
cooldownSpeed: decayUnit / 2
});
});
it('does not cause values greater than one', function() {
dac.nudge(1);
freezeTime(decayUnit * 3 / 4);
dac.nudge(1);
assert.equal(dac.currentValue(), 1);
});
it('does not cause a reverse movement', function() {
dac.nudge(1);
freezeTime(decayUnit / 10);
dac.nudge(2);
freezeTime(decayUnit * 3 / 4);
var decayed = dac.currentValue();
dac.nudge(-1);
expect(dac.currentValue()).to.be.below(decayed);
});
});
});
});
});
| true |
e801f5381a5d54aed3934bc46b4ac72133d14101
|
JavaScript
|
pmoskovi/RxJS
|
/examples/messaging/sample/canvas-share/canvas-consumer.js
|
UTF-8
| 935 | 2.6875 | 3 |
[
"Apache-2.0"
] |
permissive
|
/**
* Created by pkhanal on 5/7/15.
*/
(function() {
var canvas = document.getElementById('demo');
var drawingContext = canvas.getContext("2d");
if (!drawingContext) {
// Error
return;
}
var worker = Rx.DOM.fromWebWorker('worker/messaging-worker.js');
worker.subscribe(function(messageEvent) {
var data = messageEvent.data;
switch (data.type) {
case "draw":
var drawingInfo = JSON.parse(data.param);
drawingContext.moveTo(drawingInfo.first.offsetX, drawingInfo.first.offsetY);
drawingContext.lineTo(drawingInfo.second.offsetX, drawingInfo.second.offsetY);
drawingContext.stroke();
break;
case "clear":
drawingContext.clearRect(0, 0, canvas.width, canvas.height);
drawingContext.beginPath();
break;
}
});
})();
| true |
05d07f2609fe3d2f93d6b249c05dc356752e2828
|
JavaScript
|
mjkaufer/WhatsGoingOn
|
/client/client.js
|
UTF-8
| 445 | 2.796875 | 3 |
[] |
no_license
|
Meteor.methods({
'callback':function(message,worked){
if(worked)//call went through without errors
alert("Your call to " + message + " has been completed!");
else
alert("Call didn't go through - some error");
}
});
window.onload = function(){
document.getElementById('button').onclick = function(){
var number = document.getElementById('number').value;
alert("Sending call to " + number)
Meteor.call('sendCall',number);
}
}
| true |
8a75995c0e690cfee80b7ef57f8efe041d70a328
|
JavaScript
|
pinterari/nk3096-alkfejl-bead
|
/budget/public/getMonth.js
|
UTF-8
| 875 | 3.078125 | 3 |
[] |
no_license
|
$(function () {
var date = document.getElementById('date').innerHTML;
var show = date.substring(0, 4);
var month = parseInt(date.substring(5, 7));
switch(month) {
case 1: show += '. január'; break;
case 2: show += '. február'; break;
case 3: show += '. március'; break;
case 4: show += '. április'; break;
case 5: show += '. május'; break;
case 6: show += '. június'; break;
case 7: show += '. július'; break;
case 8: show += '. augusztus'; break;
case 9: show += '. szeptember'; break;
case 10: show += '. október'; break;
case 11: show += '. november'; break;
case 12: show += '. december'; break;
default: break;
}
document.getElementById('date').innerHTML = show;
})
| true |
f26a12d9e134a5ab01c160dfe9da49428d5e7bf3
|
JavaScript
|
bobykostov/JS-Core
|
/JavaScript Fundamentals/4. Functions and Arrow Functions - LAB/06. Aggregate Elements.js
|
UTF-8
| 368 | 3.0625 | 3 |
[] |
no_license
|
function aggregate(arr) {
function aggregate(elems, initVal, func) {
let val = initVal;
for (let i = 0; i < elems.length; i++) {
val = func(val, elems[i]);
}
console.log(val);
}
aggregate(arr, 0, (a,b) => a + b);
aggregate(arr, 0, (a,b) => a + (1 / b));
aggregate(arr, '', (a,b) => a + b);
}
| true |
b3e2197c4f97a37a81530fd6f529302df630e52f
|
JavaScript
|
bashi/tokei
|
/docs/index.js
|
UTF-8
| 10,657 | 2.765625 | 3 |
[
"Apache-2.0"
] |
permissive
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
function formatTime(date) {
const hours = date.getHours().toString();
const minutes = ('00' + date.getMinutes().toString()).slice(-2);
return `${hours}:${minutes}`;
}
// --- Storage
const SUBCLOCKS_STORE_NAME = 'subclocks';
class SubClocksStore {
constructor(db) {
this.db = db;
}
getEntries() {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction(SUBCLOCKS_STORE_NAME, 'readonly');
const objectStore = transaction.objectStore(SUBCLOCKS_STORE_NAME);
const entries = new Array();
const cursor = objectStore.openCursor();
cursor.onsuccess = e => {
const target = e.target;
if (target.result) {
entries.push(target.result.value);
target.result.continue();
}
else {
resolve(entries);
}
};
cursor.onerror = e => reject(e);
});
}
addEntry(entry) {
const transaction = this.db.transaction(SUBCLOCKS_STORE_NAME, 'readwrite');
const objectStore = transaction.objectStore(SUBCLOCKS_STORE_NAME);
const request = objectStore.add(entry);
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve();
request.onerror = reject;
});
}
removeEntry(entry) {
const transaction = this.db.transaction(SUBCLOCKS_STORE_NAME, 'readwrite');
const objectStore = transaction.objectStore(SUBCLOCKS_STORE_NAME);
const request = objectStore.delete(entry.placeId);
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve();
request.onerror = reject;
});
}
storeEntries(entries) {
const transaction = this.db.transaction(SUBCLOCKS_STORE_NAME, 'readwrite');
const objectStore = transaction.objectStore(SUBCLOCKS_STORE_NAME);
return this.clearStore(objectStore).then(() => this.addEntries(entries, objectStore));
}
clearStore(store) {
const request = store.clear();
return new Promise((resolve, reject) => {
request.onsuccess = e => resolve(e);
request.onerror = e => reject(e);
});
}
addEntries(entries, store) {
return __awaiter(this, void 0, void 0, function* () {
const addEntry = (entry) => {
return new Promise((resolve, reject) => {
const request = store.add(entry);
request.onsuccess = e => resolve(e);
request.onerror = e => reject(e);
});
};
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
yield addEntry(entry);
}
});
}
}
function createSubClocksStore() {
const STORE_DB_NAME = 'clock';
const STORE_DB_VERSION = 1;
const request = indexedDB.open(STORE_DB_NAME, STORE_DB_VERSION);
return new Promise((resolve, reject) => {
request.onerror = e => reject(e);
request.onupgradeneeded = e => {
const db = request.result;
db.createObjectStore(SUBCLOCKS_STORE_NAME, { keyPath: 'placeId' });
};
request.onsuccess = () => resolve(new SubClocksStore(request.result));
});
}
function placeDetails(placeId) {
const div = document.createElement('div');
const service = new google.maps.places.PlacesService(div);
const request = { placeId: placeId };
return new Promise((resolve, reject) => {
service.getDetails(request, (place, status) => {
if (status !== 'OK') {
reject(status);
}
resolve(place);
});
});
}
function getCityEntry(description, placeId) {
return placeDetails(placeId).then(detail => {
return {
placeId: placeId,
name: detail.name,
formattedAddress: detail.formatted_address,
description: description,
utcOffsetInMinuts: detail.utc_offset,
sortOrder: Date.now()
};
});
}
// --- New SubClock
// TODO: Hide the pane when pressed esc key
class SubClockAddPane {
constructor(app) {
this.app = app;
this.el = document.querySelector('.add-subclock-pane');
this.el.hidden = true;
this.queryEl = this.el.querySelector('.city-autocomplete-field');
const options = {
types: ['(cities)']
};
this.autocomplete = new google.maps.places.Autocomplete(this.queryEl, options);
google.maps.event.addListener(this.autocomplete, 'place_changed', () => this.placeChanged());
}
show() {
this.el.hidden = false;
this.queryEl.focus();
}
hide() {
this.el.hidden = true;
}
placeChanged() {
const place = this.autocomplete.getPlace();
if (!place || !place.place_id) {
return;
}
const entry = {
placeId: place.place_id,
name: place.name,
formattedAddress: place.formatted_address,
utcOffsetInMinuts: place.utc_offset,
sortOrder: Date.now()
};
this.app.addSubClock(entry);
this.queryEl.value = '';
}
}
// --- App
class App {
constructor(subclocks, subClocksStore) {
this.subclocks = subclocks;
this.subclocks.sort((a, b) => a.sortOrder - b.sortOrder);
this.subClocksStore = subClocksStore;
this.addPane = new SubClockAddPane(this);
this.showSettings = false;
const settingsIcon = document.querySelector('.settings-icon');
settingsIcon.addEventListener('click', e => {
this.toggleSettings();
});
}
start() {
this.update();
}
addSubClock(entry) {
this.subclocks.push(entry);
this.subClocksStore.addEntry(entry).then(() => this.invalidate());
}
removeSubClock(target) {
const subclocks = [];
for (let entry of this.subclocks) {
if (entry.placeId !== target.placeId) {
subclocks.push(entry);
}
}
this.subclocks = subclocks;
this.subClocksStore.removeEntry(target).then(() => this.invalidate());
}
toggleSettings() {
const actionEls = document.querySelectorAll('.subclock-actions');
this.showSettings = !this.showSettings;
if (this.showSettings) {
this.addPane.show();
actionEls.forEach(el => el.classList.remove('actions-hidden'));
}
else {
this.addPane.hide();
actionEls.forEach(el => el.classList.add('actions-hidden'));
}
}
update() {
const date = new Date();
if (!this.previousDate || this.previousDate.getMinutes() !== date.getMinutes()) {
this.updateMainClock(date);
this.updateSubClocks(date);
}
this.previousDate = date;
setTimeout(() => this.update(), 1000);
}
updateMainClock(date) {
const mainClockTime = document.querySelector('.main-clock-time');
mainClockTime.textContent = formatTime(date);
const mainClockDate = document.querySelector('.main-clock-date');
mainClockDate.textContent = date.toDateString();
}
updateSubClocks(date) {
const subclockListEl = document.querySelector('.subclock-list');
subclockListEl.innerHTML = '';
for (let entry of this.subclocks) {
const subclockEl = this.createSubClock(date, entry);
subclockListEl.appendChild(subclockEl);
}
}
createSubClock(date, entry) {
const offset = date.getTimezoneOffset() + entry.utcOffsetInMinuts;
const cityDate = new Date(date.getTime() + offset * 60 * 1000);
let timeDifferenceContent = '';
if (date.getTimezoneOffset() != entry.utcOffsetInMinuts) {
if (date.getDate() < cityDate.getDate()) {
timeDifferenceContent = 'Tomorrow, ';
}
else if (date.getDate() > cityDate.getDate()) {
timeDifferenceContent = 'Yesterday, ';
}
}
if (offset > 0) {
timeDifferenceContent += '+';
}
timeDifferenceContent += (offset / 60).toFixed() + ' hrs';
const timeContent = formatTime(cityDate);
const additionaActionClasses = this.showSettings ? '' : 'actions-hidden';
const subclockContent = `
<div class="subclock-container">
<div class="subclock-item">
<div class="subclock-city-name">${entry.name}</div>
<div class="subclock-time-difference">${timeDifferenceContent}</div>
<div class="subclock-time">${timeContent}</div>
</div>
<div class="subclock-actions ${additionaActionClasses}">
<svg class="subclock-remove" fill="#ccc" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
<path d="M0 0h24v24H0z" fill="none"/>
</svg>
</div>
</div>
`;
const el = document.createElement('div');
el.innerHTML = subclockContent;
const removeEl = el.querySelector('.subclock-remove');
removeEl.addEventListener('click', () => {
this.removeSubClock(entry);
});
return el;
}
invalidate() {
this.previousDate = undefined;
this.start();
}
}
// --- Init
function init() {
let subClocksStore;
createSubClocksStore()
.then(store => {
subClocksStore = store;
return store.getEntries();
})
.then(entries => {
const app = new App(entries, subClocksStore);
app.start();
});
}
document.addEventListener('DOMContentLoaded', init);
| true |
84e50be161563fca9a5d20ab9142254fe0b21ab8
|
JavaScript
|
besiankrasniqi/Main
|
/Javascript/Menu Responsive more option/menu.js
|
UTF-8
| 4,008 | 2.8125 | 3 |
[] |
no_license
|
var navigationMenu_ = document.getElementById('navigation-menu');
var menuElems = {
navigationMenu : document.getElementById('navigation-menu'),
menuItems : navigationMenu_.getElementsByTagName('li'),
moreMenu : document.getElementById('more-menu'),
moreMenuList : document.getElementById('more-menu-list'),
menuWrapper : document.getElementById('wrapper-menu')
};
var menu = {
//menu object
resizeWidth : function(percentageWidth) {
var self = this;
var getItemCount = menuElems.menuItems.length,
newWidth = 100 / parseInt(getItemCount) - 0.5,
wPercent = newWidth + '%';
console.log('percentage is %s', wPercent);
for (var i=0; i<menuElems.menuItems.length; i++){
menuElems.menuItems[i].style.width = wPercent;
}
if(percentageWidth){
menuElems.navigationMenu.style.width = percentageWidth;
console.log('width percentage is %s', percentageWidth);
}
},
menuManage : function() {
var self = this;
var menuWidth;
menuWidth = menuElems.menuWrapper.offsetWidth;
if (menuWidth >= 814){
var firstItem = menuElems.moreMenuList.getElementsByTagName('li')[0];
if (firstItem) {
console.log('first item is %s', firstItem);
menuElems.navigationMenu.appendChild(firstItem);
menuElems.moreMenu.style.display = "none";
}
menuElems.moreMenu.style.display = 'none';
self.resizeWidth('100%');
}
else if (menuWidth < 814 && menuWidth >= 713) {
var lastItem = menuElems.menuItems[7];
if (lastItem){
menuElems.moreMenuList.appendChild(lastItem);
lastItem.style.width = '100%';
}
var secondItem = menuElems.moreMenuList.getElementsByTagName('li')[1];
if (secondItem) {
console.log('first item is %s', secondItem);
menuElems.navigationMenu.appendChild(secondItem);
menuElems.moreMenu.style.display = "none";
}
menuElems.moreMenu.style.display = "block";
menuElems.navigationMenu.style.width = '86%';
self.resizeWidth();
}
else if (menuWidth < 713 && menuWidth >= 613) {
var preLastItem = menuElems.menuItems[6];
if (preLastItem){
menuElems.moreMenuList.appendChild(preLastItem);
preLastItem.style.width = '100%';
}
var thirdItem = menuElems.moreMenuList.getElementsByTagName('li')[2];
if (thirdItem) {
console.log('first item is %s', thirdItem);
menuElems.navigationMenu.appendChild(thirdItem);
menuElems.moreMenu.style.display = "none";
}
menuElems.moreMenu.style.display = "block";
menuElems.navigationMenu.style.width = '86%';
self.resizeWidth();
}
else if ( menuWidth < 613 && menuWidth >= 513 ) {
var thirdLastItem = menuElems.menuItems[5];
if (thirdLastItem){
menuElems.moreMenuList.appendChild(thirdLastItem);
thirdLastItem.style.width = '100%';
}
menuElems.moreMenu.style.display = "block";
menuElems.navigationMenu.style.width = '86%';
self.resizeWidth();
}
}
};
//Event Listeners
window.addEventListener('resize', function(){
menu.menuManage();
});
menuElems.moreMenu.addEventListener('click', function(){
console.log('show elem');
var currentClass = menuElems.moreMenuList.getAttribute('class');
if (currentClass == 'menu-more-list' ){
menuElems.moreMenuList.setAttribute('class', 'menu-more-list-show');
} else if (currentClass == 'menu-more-list-show'){
menuElems.moreMenuList.setAttribute('class', 'menu-more-list');
}
});
| true |
cfd036a95003eeb507f44097453fde99df88e4f6
|
JavaScript
|
GPCubo/Crud-NodeJs
|
/public/Formulario/scripts.js
|
UTF-8
| 2,687 | 2.984375 | 3 |
[] |
no_license
|
const terms = document.getElementById("terms")
const form = document.getElementById("form");
const button = document.getElementById("button");
const inputs = document.querySelectorAll(".controls");
const campos = {
name: false,
lastname: false,
mail: false,
terms:false
};
const validateFormulario = (e) =>{
switch(e.target.name){
case "name":
validarCampo(expresiones.nombre,e.target,"name");
break;
case "surname":
validarCampo(expresiones.nombre,e.target,"lastname");
break;
case "email":
validarCampo(expresiones.correo,e.target,"mail");
break;
}
};
const validarCampo = (expresion,input,campo) =>{
if(expresion.test(input.value)){
document.getElementById(`error__${campo}`).classList.remove(`error__${campo}-active`);
campos[campo] = true
}else {
document.getElementById(`error__${campo}`).classList.add(`error__${campo}-active`);
campos[campo] = false
}
}
inputs.forEach((input) =>{
input.addEventListener("change",validateFormulario);
input.addEventListener("keyup",validateFormulario);
});
const expresiones = {
usuario: /^[a-zA-Z0-9\_\-]{4,16}$/, // Letras, numeros, guion y guion_bajo
nombre: /^[a-zA-ZÀ-ÿ\s]{1,40}$/, // Letras y espacios, pueden llevar acentos.
password: /^.{4,12}$/, // 4 a 12 digitos.
correo: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,
telefono: /^\d{7,14}$/ // 7 a 14 numeros.
}
terms.addEventListener('change', (e) => {
campos.terms = e.target.checked
e.target.checked ? button.removeAttribute('disabled') : button.setAttribute('disabled', true)
})
form.addEventListener("submit",(e)=>{
e.preventDefault();
const datos = new FormData(form);
const send = document.getElementById("sending")
const formValues = Object.values(campos)
const valid = formValues.findIndex(value => value == false)
if(valid == -1){
fetch("/add-public",{
method:"POST",
body: JSON.stringify({
name: datos.get("name"),
surname: datos.get("surname"),
email: datos.get("email")
}),
headers:{
"Content-type": "application/json"
}
}).then(res => res.json())
.then(data=>{
if(data.ok){
send.classList.add("sending"),
setTimeout(()=>{
location.reload()
},1000)}
else{
send.classList.add("sending")
send.textContent = "Ya este correo se ha registrado"
}
})
}
})
| true |
c9d0987d1a7efef6f9f954017e549aa2f305896e
|
JavaScript
|
simonf7070/tmac
|
/tmac/Scripts/IpAddressValidation.js
|
UTF-8
| 877 | 2.578125 | 3 |
[] |
no_license
|
$.validator.unobtrusive.adapters.addBool("ipaddress");
$.validator.addMethod("ipaddress", function (value) {
return tmac.isValidIpAddress(value);
});
var tmac = (function (window, undefined) {
function isValidIpAddress(value) {
if (value) {
var ipAddressParts = value.split('.');
if (ipAddressParts.length != 4) {
return false;
}
for (var i = 0; i < ipAddressParts.length; i++) {
var num = parseInt(ipAddressParts[i], 10);
if ($.isNumeric(num)) {
if (num < 0 || num > 255) {
return false;
}
} else {
return false;
}
}
}
return true;
}
return {
isValidIpAddress: isValidIpAddress
};
})(window);
| true |
3afe16739f3e80a3fc30be818febb03c962c1f42
|
JavaScript
|
kjkandrea/refactoring-2nd-edition
|
/chapter-11/src/04-preserve-whole-object/HeatingPlan-03.js
|
UTF-8
| 510 | 2.71875 | 3 |
[] |
no_license
|
const { textSpanIsEmpty } = require('typescript');
/**
* 예시: 새 함수를 다른 방식으로 만들기
*/
class HeatingPlan {
xxNEWwithinRange(tempRange) {
const low = tempRange.low;
const high = tempRange.high;
const isWithinRange = this.withinRange(low, high);
return isWithinRange;
}
}
const tempRange = aRoom.daysTempRange;
const isWithinRange = aPlan.xxNEWwithinRange(tempRange);
if (!isWithinRange) {
alerts.push('방 온도가 지정 범위를 벗어났습니다.');
}
| true |
72140544440ef2c2a45513a57b1edebe0f200fdb
|
JavaScript
|
mkathc/tesis-app
|
/src/services/timer.js
|
UTF-8
| 325 | 2.71875 | 3 |
[] |
no_license
|
function createTimer(time, callback, callback_over) {
let second = 1000
let count = 0
let interval = setInterval(() => {
count += second
callback(count / second)
if (count >= time * second) {
callback_over()
clearInterval(interval)
}
}, second);
return interval
}
export { createTimer }
| true |
4e2b546ffc4990366a303eaeccc147c6b3b7ac4f
|
JavaScript
|
river-hermsen/vue
|
/soundboard/js/main.js
|
UTF-8
| 1,126 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
var app = new Vue({
el: '#app',
created: function () {
window.addEventListener("keypress", this.play, false);
},
methods: {
play: function(e) {
console.log(e.charCode);
if (e.charCode == 65) {
//A
document.getElementById("key65").play();
} else if (e.charCode == 83) {
//S
document.getElementById("key83").play();
} else if (e.charCode == 68) {
//D
document.getElementById("key68").play();
} else if (e.charCode == 70) {
//F
document.getElementById("key70").play();
} else if (e.charCode == 71) {
//G
document.getElementById("key71").play();
} else if (e.charCode == 72) {
//H
document.getElementById("key72").play();
} else if (e.charCode == 74) {
//J
document.getElementById("key74").play();
} else if (e.charCode == 75) {
//K
document.getElementById("key75").play();
} else if (e.charCode == 76) {
//L
document.getElementById("key76").play();
}
}
}
})
| true |
563497bbfdeb1820dd2f07a1cbb0898a5890c1da
|
JavaScript
|
dmwin72015/redux-saga-simple-use
|
/src/getReducer.js
|
UTF-8
| 1,428 | 3.046875 | 3 |
[] |
no_license
|
import invariant from 'invariant';
const identify = () => {};
function handleAction(actionType, reducer = identify) {
return (state, action) => {
const { type } = action || {};
invariant(type, 'dispatch: action should be a plain Object with type');
if (actionType === type) {
return reducer(state, action);
}
return state;
};
}
function reduceReducers(...reducers) {
return (previous, current) => reducers.reduce((p, r) => r(p, current), previous);
}
function handleActions(handlers, defaultState) {
const reducers = Object.keys(handlers).map(type => handleAction(type, handlers[type]));
// currentAction当前调用的action
// fn 为当前执行action的函数,p为state 累积的state, 是为了保持state的完整性
// 例如 在定义的reducer中可以 return { a:'xx'}, 而不必 return { ...state , a: 'xx'};
// 普通的reducer中,如果直接返回 {a: 'xx'},对导致state的其他数据丢失。
const reducer = reduceReducers(...reducers);
return (state = defaultState, action) => {
return reducer(state, action);
};
}
export function getReducer(model) {
const { reducers = {}, state } = model;
return handleActions(reducers, state);
}
// export default function aggretReducers(args) {
// console.log(args);
// return (state, action) => {
// console.log('??? 调用');
// console.log(state, action);
// return {};
// };
// }
| true |
b8afcf25d189c49145ee60b079f60f2406c0be11
|
JavaScript
|
BryanNilsen/Welcome-To-Nashville-Solo
|
/src/scripts/navigation.js
|
UTF-8
| 710 | 3.109375 | 3 |
[] |
no_license
|
// get references to navigation buttons
const navTabs = document.querySelectorAll(".nav_tab")
// get references to category sections
const sections = document.querySelectorAll(".section")
const showSection = (evt) => {
const sectionId = evt.target.id.split("_")
navTabs.forEach(navTab => {
if (navTab.id === `tab_${sectionId[1]}`) {
navTab.classList.remove("inactive")
} else {
navTab.classList.add("inactive")
}
})
sections.forEach(section => {
if (section.id === sectionId[1]) {
section.classList.remove("hidden")
} else {
section.classList.add("hidden")
}
}
)
}
navTabs.forEach(navTab => {
navTab.addEventListener("click", showSection)
})
| true |
d051e31906d538b610320f01ac833c199cdd99ff
|
JavaScript
|
Aliing/WindManager
|
/webapps/resources/cwp/ppsk_index_zh-Hans.js
|
UTF-8
| 942 | 2.515625 | 3 |
[] |
no_license
|
function fillData(){
var txt =[["安全的互联网门户"],
["<strong>新用户应填写下面的表格,请求私人预共享密钥以访问安全的无线网络。</strong>"],
["名字*"],
["姓*"],
["电子邮件*"],
["联系电话"],
["访问*"],
["注释"],
["注册需要一段时间完成(*为必填项)。"],
["登录"],
["注册"],
];
document.getElementById("h1Title").innerHTML=txt[0];
document.getElementById("h2Title").innerHTML=txt[1];
fillPlaceHolder("field1",txt[2]);
fillPlaceHolder("field2",txt[3]);
fillPlaceHolder("field3",txt[4]);
fillPlaceHolder("opt_field1",txt[5]);
fillPlaceHolder("field4",txt[6]);
fillPlaceHolder("opt_field2",txt[7]);
document.getElementById("momentNote").innerHTML=txt[8];
document.title=txt[9];
document.getElementById("register_button_id").innerHTML=txt[10];
}
function fillPlaceHolder(fieldID,changeText){
$("#"+fieldID).attr('placeholder',changeText);
}
| true |
439a38235422816badb07f0c382580acd854c602
|
JavaScript
|
chrisprice/esfmt
|
/lib/walker.js
|
UTF-8
| 2,262 | 2.609375 | 3 |
[] |
no_license
|
function Walker(opts) {
opts = opts || {};
opts.recurse = opts.recurse || walk;
var obj = {};
function walk(node, key, parent) {
if (node === null) {
return;
}
switch (node.type) {
case 'BinaryExpression':
case 'LogicalExpression':
case 'AssignmentExpression':
opts.recurse(node.left, 'left', node);
opts.recurse(node.right, 'right', node);
break;
case 'IfStatement':
case 'ConditionalExpression':
opts.recurse(node.test, 'test', node);
opts.recurse(node.consequent, 'consequent', node);
opts.recurse(node.alternate, 'alternate', node);
break;
case 'ExpressionStatement':
opts.recurse(node.expression, 'expression', node);
break;
case 'Literal':
case 'Identifier':
break;
case 'CallExpression':
case 'NewExpression':
opts.recurse(node.callee, 'callee', node);
node.arguments.forEach(opts.recurse);
break;
case 'BlockStatement':
case 'Program':
node.body.forEach(opts.recurse);
break;
case 'UnaryExpression':
opts.recurse(node.argument, 'argument', node);
break;
case 'VariableDeclaration':
node.declarations.forEach(opts.recurse);
break;
case 'VariableDeclarator':
opts.recurse(node.id, 'id', node);
opts.recurse(node.init, 'init', node);
break;
case 'MemberExpression':
opts.recurse(node.object, 'object', node);
opts.recurse(node.property, 'property', node);
break;
case 'FunctionExpression':
case 'FunctionDeclaration':
// TODO: limited subset
node.params.forEach(opts.recurse);
opts.recurse(node.body, 'body', node);
break;
case 'ThisExpression':
break;
case 'ObjectExpression':
node.properties.forEach(opts.recurse);
break;
case 'ArrayExpression':
node.elements.forEach(opts.recurse);
break;
case 'Property':
opts.recurse(node.key, 'key', node);
opts.recurse(node.value, 'value', node);
break;
case 'ReturnStatement':
opts.recurse(node.argument, 'argument', node);
break;
case 'SequenceExpression':
node.expressions.forEach(opts.recurse);
break;
default:
console.log(node);
throw new Error('Unknown node type ' + node.type);
}
}
obj.walk = walk;
return obj;
}
module.exports = Walker;
| true |
433bd94b057e068f652f8b652bc9dd84535971e6
|
JavaScript
|
Morjhin/Javascript
|
/3. Project/app.js
|
UTF-8
| 12,494 | 3.078125 | 3 |
[] |
no_license
|
let DOMStrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn',
incomeContainer: '.income__list',
expensesContainer: '.expenses__list',
budgetLabel: '.budget__value',
incomeLabel: '.budget__income--value',
expensesLabel: '.budget__expenses--value',
percentageLabel: '.budget__expenses--percentage',
container: '.container',
expensesPercLabel: '.item__percentage'
};
// BUDGET CONTROLLER
let budgetController = (function () {
let Expense = function (id, description, value) {
this.id = id;
this.description = description;
this.value = value;
this.percentage = -1
};
Expense.prototype.calcPercentage = function(totalIncome) {
if (totalIncome > 0) {
this.percentage = ((this.value / totalIncome) * 100).toFixed(1);
} else {
this.percentage = -1;
}
};
Expense.prototype.getPercentage = function() {
return this.percentage;
};
let Income = function (id, description, value) {
this.id = id;
this.description = description;
this.value = value;
};
function calculateTotal(type) {
let sum = 0;
data.allItems[type].forEach(function (cur) {
sum += cur.value;
})
data.totals[type] = sum;
}
let data = {
allItems: {
exp: [],
inc: [],
},
totals: {
exp: 0,
inc: 0
},
budget: 0,
percentage: -1
};
let difference = function() {
data.budget = data.totals.inc - data.totals.exp;
};
let percentage = function() {
if (data.totals.inc > 0) {
data.percentage = ((data.totals.exp / data.totals.inc) * 100).toFixed(1);
} else {
data.percentage = -1;
}
};
let nodeListForEach = function(list, callback) {
for (let i = 0; i < list.length; i++) {
callback(list[i], i);
}
};
return {
addItem: function (type, des, val) {
let newItem, ID;
// Create new ID
if (data.allItems[type].length > 0){
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
// Create new Item
if (type === 'exp') {
newItem = new Expense(ID, des, val)
} else if (type === 'inc') {
newItem = new Income(ID, des, val)
}
// Push it into out data structure
data.allItems[type].push(newItem);
// Return the new element
return newItem;
},
deleteItem: function(type, id) {
let ids, index;
ids = data.allItems[type].map(function(current) {
return current.id;
});
index = ids.indexOf(id);
if (index !== -1) {
data.allItems[type].splice(index, 1);
}
},
calculateTotal,
difference,
percentage,
calculatePercentage: function() {
data.allItems.exp.forEach(function (current) {
current.calcPercentage(data.totals.inc);
});
},
getPercentage: function() {
let allPercentages;
allPercentages = data.allItems.exp.map(function (current) {
return current.getPercentage();
});
return allPercentages;
},
getBudget: function() {
return {
budget: data.budget,
totalInc: data.totals.inc,
totalExp: data.totals.exp,
percentage: data.percentage
}
},
displayPercentage: function (percentages) {
let fields = document.querySelectorAll(DOMStrings.expensesPercLabel);
nodeListForEach(fields, function (current, index) {
if (percentages[index] > 0) {
current.textContent = percentages[index] + '%';
} else {
current.textContent = '---';
} if (percentages[index] >= 100.1) {
current.textContent = '>%100'
}
});
},
changeType: function() {
let fields;
fields = document.querySelectorAll(
DOMStrings.inputType + ',' +
DOMStrings.inputDescription + ',' +
DOMStrings.inputValue
);
nodeListForEach(fields, function (current) {
current.classList.toggle('red-focus');
});
document.querySelector(DOMStrings.inputBtn).classList.toggle('red');
}
};
})();
// UI CONTROLLER
let UIController = (function () {
let formatNumber = function (number, type) {
let numberSplit, int, dec;
number = Math.abs(number);
number = number.toFixed(3);
numberSplit = number.split('.');
int = numberSplit[0];
if (int.length > 3 && int.length <= 6) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3);
}else if (int.length > 6) {
int = int.substr(0, int.length - 6) + ',' + int.substr(int.length - 6, 3) + ',' +
int.substr(int.length - 3, 3);
} // input 1234567, output 1,234567, output2 1,234,567
dec = numberSplit[1];
return (type === 'inc' ? '+' : '-') + ' ' + int + '.' + dec;
};
return {
getInput: function () {
return {
type: document.querySelector(DOMStrings.inputType).value,
description: document.querySelector(DOMStrings.inputDescription).value,
value: Number.parseFloat(document.querySelector(DOMStrings.inputValue).value),
};
},
addList: function (obj, type) {
let html, newHtml, element;
// Create HTML string with placeholder text
if (type === 'inc') {
element = DOMStrings.incomeContainer;
html = '<div class="item clearfix" id="inc-%id%"><div class="item__description">%description%</div>' +
'<div class="right clearfix"><div class="item__value">%value%</div><div class="item__delete">' +
'<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div>' +
'</div>';
} else if (type === 'exp') {
element = DOMStrings.expensesContainer;
html = '<div class="item clearfix" id="exp-%id%"><div class="item__description">%description%</div>' +
'<div class="right clearfix"><div class="item__value">%value%</div><div class="item__percentage">' +
'21%</div><div class="item__delete"><button class="item__delete--btn">' +
'<i class="ion-ios-close-outline"></i></button></div></div></div>';
}
// Replace the placeholder text with some actual data
newHtml = html.replace('%id%', obj.id);
newHtml = newHtml.replace('%description%', obj.description);
newHtml = newHtml.replace('%value%', formatNumber(obj.value, type));
// Insert the HTML into the DOM
document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);
},
deleteList: function(selectorID) {
let elem = document.getElementById(selectorID)
elem.parentNode.removeChild(elem);
},
clearFields: function() {
let fields, fieldsArr;
fields = document.querySelectorAll(DOMStrings.inputDescription + ',' + DOMStrings.inputValue);
fieldsArr = Array.prototype.slice.call(fields); // Array.... uses for converting array to something
fieldsArr.forEach(function (current) {
current.value = "";
});
fieldsArr[0].focus();
},
displayBudget: function (obj) {
let type;
obj.budget >= 0 ? type = 'inc' : type = 'exp';
document.querySelector(DOMStrings.budgetLabel).textContent = formatNumber(obj.budget, type);
document.querySelector(DOMStrings.incomeLabel).textContent = formatNumber(obj.totalInc, 'inc');
document.querySelector(DOMStrings.expensesLabel).textContent = formatNumber(obj.totalExp, 'exp');
document.querySelector(DOMStrings.percentageLabel).textContent = obj.percentage;
if (obj.percentage > 0) {
document.querySelector(DOMStrings.percentageLabel).textContent = obj.percentage + '%';
} else {
document.querySelector(DOMStrings.percentageLabel).textContent = '---';
}
if (obj.percentage >= 100.1) {
document.querySelector(DOMStrings.percentageLabel).textContent = '>%100';
}
}
};
})();
// GLOBAL APP CONTROLLER
let controller = (function (budgetCont, UICont, DOMStr) {
function eventListenerSetup() {
document.querySelector(DOMStr.inputBtn).addEventListener('click', ctrlAddItem);
document.addEventListener('keypress', function (event) {
if (event.keyCode === 13) {
ctrlAddItem();
}
});
document.querySelector(DOMStr.container).addEventListener('click', ctrlDeleteItem);
document.querySelector(DOMStr.inputType).addEventListener('change', budgetController.changeType);
}
return {
ctrlInit: function () {
eventListenerSetup();
UIController.displayBudget({
budget: 0,
totalInc: 0,
totalExp: 0,
percentage: -1
});
getTime();
}
};
})(budgetController, UIController, DOMStrings);
controller.ctrlInit();
function ctrlAddItem() {
let input, newItem;
// Get input data
input = UIController.getInput();
if (input.description !== "" && !isNaN(input.value) && input.value > 0 ) {
// Add the item to the budget controller
newItem = budgetController.addItem(input.type, input.description, input.value);
// Add the item to UI
UIController.addList(newItem, input.type);
// Clear fields
UIController.clearFields();
// Calculate and update budget
budgetUpdate();
// Calculate and update percentages
updatePercentages();
}
}
function budgetUpdate() {
// Calculate the budget
calculateBudget();
// Return to the budget
let budget = budgetController.getBudget();
// Display the budget on the UI
UIController.displayBudget(budget);
}
function calculateBudget() {
// Calculate total income and expenses
budgetController.calculateTotal('exp');
budgetController.calculateTotal('inc');
// Calculate income - expenses
budgetController.difference();
// Calculate the percentage of income that we spent
budgetController.percentage();
}
function ctrlDeleteItem(event) {
let itemID, splitID, type, ID;
itemID = event.target.parentNode.parentNode.parentNode.parentNode.id;
if (itemID) {
splitID = itemID.split('-');
type = splitID[0];
ID = parseInt(splitID[1]);
// Delete item from the data structure
budgetController.deleteItem(type, ID);
// Delete the item from the UI
UIController.deleteList(itemID);
// Update and show the budget
budgetUpdate();
// Calculate and update percentages
updatePercentages();
}
}
function updatePercentages() {
let percentages;
// Calculate percentages
budgetController.calculatePercentage();
// Read percentages from the budget
percentages = budgetController.getPercentage();
// Update the UI with the new percentages
budgetController.displayPercentage(percentages);
}
function getTime() {
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
"November", "December"];
const d = new Date();
document.querySelector('.budget__title--month').textContent = (months[d.getMonth()] + ' ' + d.getFullYear());
}
| true |
85ec2d89c439422c83c5462961ebd1038385ad09
|
JavaScript
|
ewauq/shruggy
|
/commands/help/help.js
|
UTF-8
| 2,033 | 2.671875 | 3 |
[] |
no_license
|
module.exports = {
/**
* Paramètres de la commande.
*/
name: "help",
description: "**${prefix}help ${prefix}aide** Retourne un message d'aide listant toutes les commandes disponibles.",
triggers: [
"aide",
"info",
"infos",
"help"
],
responses: [
"Pour l'instant je ne suis pas très évolué, un peu comme les humains, mais j'apprends vite.\n\nVoilà ce que je sais faire :\n\n${command_list}\nVoilà, et à part ça, mon but ultime est de dominer le monde, mais ça tout le monde sait déjà."
],
/**
* Exécution de la commande
*/
exec: function(message, _callback) {
this.output = null;
this.error = null;
// Exécution normale du code.
try {
var tools = require("../../lib/functions.js");
var config = require("../../config.json");
var fs = require('fs');
var command_list = "";
// Liste des commandes du bot.
var commands = fs.readdirSync("./commands");
// Pour chaque commande présente, on récupère sa description.
for(var i in commands) {
var cmd = require(`../${commands[i]}/${commands[i]}.js`);
if(cmd.description)
command_list = command_list + cmd.description.template({ prefix: config.command_prefix }) + "\n";
}
this.output = tools.randomize(this.responses).template({ command_list });
}
// Gestion des erreurs
catch(e) {
if(!this.responses) {
this.error = `Les phrases de réponses de la commande <${this.name}> n'ont pas été trouvées.`;
}
else {
this.error = `La commande <${this.name}> a provoqué une erreur : ${e.message}`;
}
}
// Quoiqu'il arrive, on fait appel au callback.
finally {
_callback(this.output, this.error);
}
}
};
| true |
033a57fac0fa42faa14c7acf9eb8cf151630dbfe
|
JavaScript
|
hellokj/itrip_project
|
/utils/nilChecker.js
|
UTF-8
| 411 | 2.78125 | 3 |
[] |
no_license
|
const NilChecker = (body, num, params) => {
a_list = Object.keys(body)
if(a_list.length + params.length < num){
return true;
}
i = 0
for(let j=0;j<a_list.length;j++) {
if(!params.includes(a_list[j])){
i++;
}
}
if(i == num - params.length) {
return false;
}
else {
return true;
}
}
module.exports = NilChecker
| true |
b7c0432521fec9493d6048c5f64c66e068f94200
|
JavaScript
|
jv640/JavaScript_30
|
/Drum_Kit/DrumKit.js
|
UTF-8
| 864 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
// There is a small bug that if we presses another ket before the trasition of previous completed.
// then it leaves its previous transaction incomplete
let count = 0;
function removeTransition (e) {
if (e.propertyName !== "transform") return;
// console.log(e)
this.classList.remove("playing");
// count = count - 1;
// console.log(count)
}
const keys = document.querySelectorAll('.key');
keys.forEach(key => key.addEventListener("transitionend", removeTransition));
window.addEventListener("keydown", function (e) {
const key = document.querySelector(`.key[data-key="${ e.key }"]`);
if (!key)
return;
key.classList.add("playing");
// count = count + 2;
// console.log(count)
let sound = key.getElementsByClassName("sound")[0].innerHTML;
// console.log(sound)
const audio = new Audio(`Audio/${ sound.toLowerCase() }.wav`);
audio.play();
});
| true |
9cc9714ebc0eb202681091ee141e952bcd8ea45a
|
JavaScript
|
brunoprp/Dashboard-MQTT-Python
|
/app_web_fask/static/chats_dash.js
|
UTF-8
| 1,038 | 2.609375 | 3 |
[] |
no_license
|
var pieData1 = [
{ value: 300, color:"#F7464A", highlight: "#FF5A5E", label: "Red"},
{ value: 50, color: "#46BFBD", highlight: "#5AD3D1", label: "Green"},
{ value: 100, color: "#FDB45C", highlight: "#FFC870", label: "Yellow"},
{ value: 40, color: "#949FB1", highlight: "#A8B3C5", label: "Grey"},
{ value: 120, color: "#4D5360", highlight: "#616774", label: "Dark Grey"}];
var doughnutData = [
{ value: 300, color:"#F7464A", highlight: "#FF5A5E", label: "Red"},
{ value: 50, color: "#46BFBD", highlight: "#5AD3D1", label: "Green"},
{ value: 100, color: "#FDB45C", highlight: "#FFC870", label: "Yellow"},
{ value: 40, color: "#949FB1", highlight: "#A8B3C5", label: "Grey"},
{ value: 120, color: "#4D5360", highlight: "#616774", label: "Dark Grey"} ];
var ctx = document.getElementById("chart-area").getContext("2d");
var myDoughnut = new Chart(ctx).Doughnut(doughnutData, {responsive : true});
var ctx1 = document.getElementById("pie").getContext("2d");
var myPie = new Chart(ctx1).Pie(pieData1);
| true |
9be288ada06754bece33c4876bc03181c5dfc6e6
|
JavaScript
|
christopherhurt/Pioned
|
/src/utils.js
|
UTF-8
| 3,701 | 2.84375 | 3 |
[] |
no_license
|
const _fontFamily = 'Roboto Slab, sans-serif';
const _normal = 18;
const _medium = 24;
const _medium2 = 32;
const _large = 50;
export const Styles = {
light: 'white',
special: 'rgb(23,139,251)',
special2: 'rgb(23,251,135)',
important: 'red',
lightBG: 'rgba(255,255,255,0.8)',
darkBG: 'rgba(0,0,0,0.8)',
fontFamily: _fontFamily,
fontSize: _normal,
mediumFontSize: _medium,
mediumFontSize2: _medium2,
largeFontSize: _large,
font: `${_normal}px ${_fontFamily}`,
mediumFont: `${_medium}px ${_fontFamily}`,
largeFont: `${_large}px ${_fontFamily}`,
};
export function drawTextWithBackground(text, ctx, x, y, fontSize=Styles.fontSize, color=Styles.light, background=Styles.darkBG, align='left') {
ctx.font = `${fontSize}px ${Styles.fontFamily}`;
const textWidth = ctx.measureText(text).width;
const bgWidth = textWidth + fontSize * 0.5;
const bgHeight = fontSize * 1.7;
// Alignment
const awords = align.split(/[ ,]+/);
if (awords.includes('center')) {
x -= bgWidth / 2;
} else if (awords.includes('right')) {
x -= bgWidth;
}
if (awords.includes('above')) {
y -= bgHeight;
}
ctx.fillStyle = background;
ctx.fillRect(
x,
y,
bgWidth,
bgHeight,
);
ctx.fillStyle = color;
ctx.fillText(text, x + fontSize * 0.25, y + fontSize * 1.2);
return [bgWidth, bgHeight];
}
function _intersects(x1, y1, w1, h1, x2, y2, w2, h2) {
return x1 <= x2 + w2 && x1 + w1 >= x2 && y1 <= y2 + h2 && y1 + h1 >= y2;
}
export function intersects(o1, o2) {
return _intersects(o1.x, o1.y, o1.width, o1.height, o2.x, o2.y, o2.width, o2.height);
}
export function copyArray(arr) {
const copy = [];
for(let i = 0; i < arr.length; i++) {
const row = [];
for(let j = 0; j < arr[0].length; j++) {
row.push(arr[i][j]);
}
copy.push(row);
}
return copy;
}
export function fillZeros(width, height) {
return Array(height).fill().map(() => Array(width).fill(0));
}
export function send(socket, type, data) {
socket.send(JSON.stringify({type, data}));
}
export function createCanvas(width, height) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
return canvas;
};
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fadeOut(elem) {
elem.style.opacity = 1;
while (elem.style.opacity > 0) {
elem.style.opacity -= 0.1
await sleep(40);
}
}
export async function postChat(message, type) {
const div = document.createElement('div');
div.className = 'chat-message';
switch(type) {
case 'info':
div.className += ' chat-info-message';
break;
case 'debug':
div.className += ' chat-debug-message';
break;
case 'error':
div.className += ' chat-error-message';
break;
case 'success':
div.className += ' chat-success-message';
break;
}
div.innerText = message;
const chat = document.getElementById('chat');
chat.appendChild(div);
// Scroll to bottom
const chatWrap = document.getElementById('chat-wrap');
chatWrap.scrollTop = chatWrap.scrollHeight;
await sleep(10000);
await fadeOut(div);
chat.removeChild(div);
}
export class ImageLoader {
constructor() {
this.images = {};
}
load(key, src) {
const img = new Image();
const p = new Promise((resolve, reject) => {
img.onload = () => {
this.images[key] = img;
resolve(img);
};
img.onerror = () => reject(`Could not load image: ${src}`);
});
img.src = src;
return p;
}
get(key) {
return this.images[key];
}
}
| true |
96ce8546c8267435f9ab8353e9ed44881c1b855a
|
JavaScript
|
SDen4/burger_project
|
/src/scripts/player.js
|
UTF-8
| 3,405 | 2.796875 | 3 |
[] |
no_license
|
(function() {
const vid = document.querySelector(".video");
const playerStart = document.querySelector(".player__start");
const playerPaused = document.querySelector(".player__pause");
const playerVolume = document.querySelector(".player__volume");
const playerMute = document.querySelector(".player__mute");
const scrollDur = document.querySelector(".player__scroll_duration");
const bigWwiteBtn = document.querySelector(".video__big-button");
playerStart.addEventListener('click', function() {
vid.play();
playerPaused.classList.add('player__pause_active');
playerStart.classList.add('player__start_unactive');
bigWwiteBtn.classList.add('player__start_unactive');
interval = setInterval(function() {
let durPercent = (vid.currentTime / vid.duration) * 100;
scrollDur.style.left = `${durPercent}%`;
}, 1000);
});
playerPaused.addEventListener('click', function() {
vid.pause();
playerStart.classList.remove('player__start_unactive');
playerPaused.classList.remove('player__pause_active');
bigWwiteBtn.classList.remove('player__start_unactive');
});
bigWwiteBtn.addEventListener('click', function() {
vid.play();
playerPaused.classList.add('player__pause_active');
playerStart.classList.add('player__start_unactive');
bigWwiteBtn.classList.add('player__start_unactive');
interval = setInterval(function() {
let durPercent = (vid.currentTime / vid.duration) * 100;
scrollDur.style.left = `${durPercent}%`;
}, 1000);
});
playerVolume.addEventListener('click', function() {
vid.muted = true;
playerMute.classList.add('player__mute_active');
});
playerMute.addEventListener('click', function() {
vid.muted = false;
playerMute.classList.remove('player__mute_active');
});
const lenghtlVal = document.querySelector(".player__volume-duration");
const scrollVal = document.querySelector(".player__scroll_volume");
let coords = {};
vid.volume = 1;
const measureElem = (elem, event) => {
const measures = elem.getBoundingClientRect();
return {
offsetTop: measures.top,
offsetLeft: measures.left,
width: measures.width,
clickedX: event.layerX
}
}
const setupMeasures = e => {
lenghtlVal.classList.add('allow');
coords.line = measureElem(lenghtlVal, e);
coords.btn = measureElem(scrollVal, e);
}
const checkEdges = (btn, line) => {
var x = btn.x;
if (x<0) x = 0;
if (x>line.width - btn.width) {
x = line.width - btn.width
};
scrollVal.style.left = `${x}px`;
let maxVolume = line.width - btn.width;
let curVolume = x;
vid.volume = curVolume/maxVolume;
};
const setupBlockPos = e => {
if(!lenghtlVal.classList.contains('allow')) return;
var {line, btn} = coords;
btn.x = e.pageX - line.offsetLeft - btn.clickedX;
checkEdges (btn, line);
};
scrollVal.addEventListener('mousedown', setupMeasures);
document.addEventListener('mousemove', setupBlockPos);
document.addEventListener('mouseup', e=> {
lenghtlVal.classList.remove('allow');
});
})()
| true |
e9b18eca01897b33e7d9f3da90b802ad149a28eb
|
JavaScript
|
Revtrov/webPortfolio
|
/portfolio/server.js
|
UTF-8
| 1,537 | 2.546875 | 3 |
[] |
no_license
|
const express = require('express')
const app = express()
const port = 3000
const path = require('path');
const router = express.Router();
const createRoute = (browserPath, filePath) => {
app.get(browserPath, (req, res) => {
res.sendFile(path.resolve(__dirname, filePath))
})
},
createPage = (pageName) => {
createRoute(`/${pageName}`, `${pageName}/index.html`);
createRoute(`/${pageName}/style.css`, `${pageName}/style.css`);
createRoute(`/${pageName}/script.js`, `${pageName}/script.js`);
},
createImageRoutes = (array) => {
for (i in array) {
createRoute(`/images/${array[i]}`, `images/${array[i]}`);
}
},
createProjectPage = (name) => {
createRoute(`/projects/${name}`, `projects/${name}/index.html`);
createRoute(`/projects/${name}/style.css`, `projects/${name}/style.css`);
createRoute(`/projects/${name}/script.js`, `projects/${name}/script.js`);
}
//home page
createPage("home");
//projects page routes
createPage("projects");
//about page Routes
createPage("about");
//contact page routes
createPage("contact");
//dice routes
createProjectPage("dice");
//snakes and ladders routes
createProjectPage("snakesAndLadders");
//typeracer
createProjectPage("typingPractice");
//images
createImageRoutes(["logo.png", "rollDice.png", "snakesAndLadders.png", "typingPractice.png"])
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
module.exports = router
| true |
b4d266c664b1aa80b05bab436505cac942b55e8e
|
JavaScript
|
Aulin93/ePortfolio
|
/src/Components/Thanquol.js
|
UTF-8
| 3,531 | 2.578125 | 3 |
[] |
no_license
|
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
TextField,
} from "@material-ui/core";
import { useState } from "react";
import { WeaponProfile } from "./WeaponProfile";
export function Thanquol() {
const [move, setMove] = useState(10);
const [wounds, setWounds] = useState(0);
const [changeValue, setChangeValue] = useState(0);
const [crushingBlowsAttacks, setCrushingBlowsAttacks] = useState(6);
const [staffOfTheHornedRatModifier, setStaffOfTheHornedRatModifier] =
useState(2);
const [numberOfWarpfireBraziers, setNumberOfWarpfireBraziers] = useState(0);
const [open, setOpen] = useState(false);
const [visible, setVisible] = useState(true);
const allocateWounds = () => {
const allocatedWounds = wounds + changeValue;
setWounds(allocatedWounds);
if (allocatedWounds < 4) {
setMove(10);
setCrushingBlowsAttacks(6);
setStaffOfTheHornedRatModifier(2);
} else if (allocatedWounds < 6) {
setMove(9);
setCrushingBlowsAttacks(5);
setStaffOfTheHornedRatModifier(2);
} else if (allocatedWounds < 9) {
setMove(8);
setCrushingBlowsAttacks(4);
setStaffOfTheHornedRatModifier(1);
} else if (allocatedWounds < 11) {
setMove(7);
setCrushingBlowsAttacks(3);
setStaffOfTheHornedRatModifier(1);
} else {
setMove(6);
setCrushingBlowsAttacks(2);
setStaffOfTheHornedRatModifier(0);
}
setOpen(false);
};
return (
<>
{visible ? (
<div className="StatBlock">
<h4>Thanquol</h4>
<p>Wounds: {wounds}/14</p>
<Dialog open={open} onClose={() => setOpen(false)}>
<DialogTitle>Allocate Wounds</DialogTitle>
<DialogContent>
<DialogContentText>
Assign a number of wounds to allocate
</DialogContentText>
<TextField
label="Change by"
type="number"
onChange={(event) => setChangeValue(event.target.valueAsNumber)}
/>
</DialogContent>
<DialogActions>
<Button onClick={allocateWounds}>Confirm</Button>
</DialogActions>
</Dialog>
<Button variant="contained" color="primary" onClick={() => setOpen(true)}>
Allocate Wounds
</Button>
<p>Move: {move}", Save: 4+, Bravery: 7</p>
<WeaponProfile
name="Staff of the Horned Rat - MELEE"
range='2"'
attacks="2"
toHit="4+"
toWound="3+"
rend="-1"
damage="D3"
/>
<WeaponProfile
name="Warpfire Braziers - MELEE"
range='2"'
attacks={numberOfWarpfireBraziers * 2}
toHit="3+"
toWound="3+"
rend="-2"
damage="3"
/>
<WeaponProfile
name="Crushing Blows - MELEE"
range='2"'
attacks={crushingBlowsAttacks}
toHit="4+"
toWound="3+"
rend="-1"
damage="2"
/>
<Button
variant="contained"
onClick={() => {
if (numberOfWarpfireBraziers < 4) {
const warpfireBraziers = numberOfWarpfireBraziers + 1;
setNumberOfWarpfireBraziers(warpfireBraziers);
}
}}
>
Add Warpfire Brazier
</Button>
<p>
Staff of the Horned Rat casting modifier: +{staffOfTheHornedRatModifier}
</p>
<Button variant="contained" color="secondary" onClick={() => setVisible(false)}>Stop Tracking This</Button>
</div>
) : null}
</>
);
}
| true |
9e6317f9a1c166916475c867557b3da8916b7cb3
|
JavaScript
|
yoghourtpuppy/lc_code
|
/stack/validParenthesis.js
|
UTF-8
| 1,297 | 4.59375 | 5 |
[] |
no_license
|
// Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
// An input string is valid if:
// Open brackets must be closed by the same type of brackets.
// Open brackets must be closed in the correct order.
// Note that an empty string is also considered valid.
// Example 1:
// Input: "()"
// Output: true
// Example 2:
// Input: "()[]{}"
// Output: true
// Example 3:
// Input: "(]"
// Output: false
// Example 4:
// Input: "([)]"
// Output: false
// Example 5:
// Input: "{[]}"
// Output: true
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
const map = {
')': '(',
'}': '{',
']': '[',
};
const stack = [];
for (let i = 0; i < s.length; i++) {
const char = s.charAt(i);
if (char === '(' || char === '{' || char === '[') {
stack.push(char); // push open parenthesis into stack
} else if (stack[stack.length -1] === map[char]) {// if the close parenthesis match the one on top of stack
stack.pop();
} else {
return false; // If no matching open one return false
}
}
return stack.length ? false : true; // If the stack is not empty, meaning there's extra open ones, return false
};
var a = isValid('()');
console.log('result: '+a);
| true |
92f6a8b9a7b3ef48dd8620690a633c15926b870d
|
JavaScript
|
ShahmeerHamza/Team-Report
|
/index.js
|
UTF-8
| 1,899 | 2.515625 | 3 |
[] |
no_license
|
const sign_in_btn = document.querySelector('#sign-in-form');
const sign_up_btn = document.querySelector('#sign-up-form');
const container = document.querySelector('.container');
sign_up_btn.addEventListener('click', () => {
container.classList.add('sign-up-mode');
});
sign_in_btn.addEventListener('click', () => {
container.classList.remove('sign-up-mode');
});
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyCFRUqTp42cJCAt_F8t65S8MrBDFHLSvAY",
authDomain: "teamreport-7ce2e.firebaseapp.com",
projectId: "teamreport-7ce2e",
storageBucket: "teamreport-7ce2e.appspot.com",
messagingSenderId: "904775004812",
appId: "1:904775004812:web:1d6dcda94a59ca3b1441a9",
measurementId: "G-YWGFDWQ9KW"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
// Let's code
// var datab = firebase.database().ref('data');
function signup() {
const email =document.getElementById("email").value
const password =document.getElementById("password").value
console.log(email, password)
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
const auth = getAuth();
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
}
const auth = firebase.auth();
function SignIn(){
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
const promise = auth.signInWithEmailAndPassword(email,password);
promise.catch( e => alert(e.msg));
window.open("https://www.google.com","_self");
}
| true |
b65b3e7bbbbda2c85cce47eda8beac60c231b57a
|
JavaScript
|
annasm07/AS-tennisApp
|
/AS-FinalProject/frontend/src/utils/counterLogic.js
|
UTF-8
| 1,237 | 2.765625 | 3 |
[] |
no_license
|
export function counterLogicPoints(
playerWhoWon,
{points, p1CounterPoints, p2CounterPoints},
) {
const pointsIncrement = {
1: 15,
2: 15,
3: 10,
};
let CounterWinner = 0,
playerWhoLost;
playerWhoWon === 'p1'
? (playerWhoLost = 'p2') &&
(p1CounterPoints += 1) &&
(CounterWinner = p1CounterPoints)
: (playerWhoLost = 'p1') &&
(p2CounterPoints += 1) &&
(CounterWinner = p2CounterPoints);
const previousPoint = points[points.length - 1];
let newPoint = JSON.parse(JSON.stringify(previousPoint));
newPoint = {
[playerWhoWon]: (newPoint[playerWhoWon] +=
pointsIncrement[CounterWinner] || 1),
[playerWhoLost]: newPoint[playerWhoLost],
};
points.push(newPoint);
return {
points,
p1CounterPoints,
p2CounterPoints,
};
}
export function counterLogicScoring(playerWhoWon, score) {
let playerWhoLost;
playerWhoWon === 'p1' ? (playerWhoLost = 'p2') : (playerWhoLost = 'p1');
const previousGame = score[score.length - 1];
let newGame = JSON.parse(JSON.stringify(previousGame));
newGame = {
[playerWhoWon]: (newGame[playerWhoWon] += 1),
[playerWhoLost]: newGame[playerWhoLost],
};
score.push(newGame);
return score;
}
| true |
b09f624940338c58100a031c4436ee3b4e620fce
|
JavaScript
|
johnjaller/canvas-project
|
/javascript/drawing-line.js
|
UTF-8
| 1,255 | 3.375 | 3 |
[] |
no_license
|
/**********************************************
* Drawing Line Functionality
* ==================================
* This class extends the PaintFunction class, which you can find in canvas-common
* Remember, order matters
***********************************************/
class DrawingLine extends PaintFunction {
// This class extends the PaintFunction class
// You are only passing one instance here
constructor(contextReal) {
super();
this.context = contextReal;
}
// On mouse down, ensure that the pen has these features
onMouseDown(coord, event) {
// Fill in the color
strokeStyleReal()
// Kind of line
this.context.lineJoin = "round";
// Width of line
lineWidthReal()
// Drawing the line here
this.context.beginPath();
this.context.moveTo(coord[0], coord[1]);
this.draw(coord[0], coord[1]);
}
// Clicking and removing your mouse
onDragging(coord, event) {
this.draw(coord[0], coord[1]);
}
onMouseMove() {}
onMouseUp() {
history()
}
onMouseLeave() {}
onMouseEnter() {}
draw(x, y) {
//
this.context.lineTo(x, y);
this.context.moveTo(x, y);
this.context.closePath();
// Draw the line onto the page
this.context.stroke();
}
}
| true |
cfc7601c45ef30376e9160cabccaf817bc4ea9c0
|
JavaScript
|
dr-k4rma/ProgrammingMemes
|
/ScrambleMiddleLetters/run.js
|
UTF-8
| 1,471 | 3.75 | 4 |
[] |
no_license
|
const str = "At the edge of a wide pond, Yoda sits on a log. In his mouth is a Gimer Stick, a short twig with three little branches at the far end. Luke is nowhere in sight, but now we begin to hear the sound of someone crashing through the foliage.";
function scramble(str){
let t = str.split("");
for(let i = t.length - 1; i > 0; i--){
let randomIndex = Math.floor(Math.random() * (i + 1));
let temp = t[i];
t[i] = t[randomIndex];
t[randomIndex] = temp;
}
return t.join("");
}
// Main
let separateWords = str.split(/\s+/);
for(let i = 0; i < separateWords.length; i++){
let word = separateWords[i];
if(word.length <= 3){
continue;
}
let punctuationIndex = word.search(/[^\w\s]/g);
let punctuation;
if (punctuationIndex != -1){
punctuation = word[punctuationIndex]
word = word.replace(punctuation, "");
console.log("Found " + punctuation + " @ " + punctuationIndex);
console.log(word);
}
let firstLetter = word.substring(0, 1);
let lastLetter = word.substring(word.length - 1, word.length);
let middleWord = word.substring(1, word.length - 1);
middleWord = scramble(middleWord);
word = firstLetter + middleWord + lastLetter;
let arr = word.split("");
arr.splice(punctuationIndex, 0, punctuation);
word = arr.join("");
separateWords[i] = word;
}
let output = separateWords.join(" ");
console.log(output);
| true |
cbb8b9385b41ec3abe1fbe48f6edef6283cd6e80
|
JavaScript
|
P-ppc/leetcode
|
/algorithms/FindModeInBinarySearchTree/solution.js
|
UTF-8
| 1,034 | 3.3125 | 3 |
[] |
no_license
|
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var findMode = function(root) {
let params = {
res: [],
maxCount: 0,
curCount: 0,
prev: null
}
if (root) {
inOrderTraveral(root, params)
}
return params.res
};
var inOrderTraveral = function (node, params) {
if (node.left) {
inOrderTraveral(node.left, params)
}
if (params.prev === node.val) {
params.curCount++
} else {
params.curCount = 1
}
if (params.curCount > params.maxCount) {
params.maxCount = params.curCount
params.res.splice(0, params.res.length)
params.res.push(node.val)
} else if (params.curCount === params.maxCount) {
params.res.push(node.val)
}
params.prev = node.val
if (node.right) {
inOrderTraveral(node.right, params)
}
}
| true |
2cf0080310d31b706132397df210e977d2cd7973
|
JavaScript
|
smallbomb/CheckIO_js
|
/Scientific Expedition/cipher-map.js
|
UTF-8
| 1,777 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
// https://js.checkio.org/mission/cipher-map/
const rotateccw = function (matrix) {
let s = "";
let newarr = [];
for (let j = 0; j < matrix.length; j++) {
for (let i = matrix.length - 1; i >= 0; i--) s += matrix[i].charAt(j);
newarr.push(s);
s = "";
}
return newarr;
}
function recallPassword(grille, password) {
let passwd = "";
for (let round = 0 ; round < 4; round++) {
grille.map((rows, i) => rows.split("").map((e, j) => {
if (e === 'X') passwd += password[i][j];
}));
grille = rotateccw(grille);
}
return passwd;
}
console.log(recallPassword(['X...',
'..X.',
'X..X',
'....'],
['itdf',
'gdce',
'aton',
'qrdi']));
console.log(recallPassword(['....',
'X..X',
'.X..',
'...X'],
['xhwc',
'rsqx',
'xqzz',
'fyzr']));
// var assert = require('assert');
// if (!global.is_checking) {
// assert.equal(recallPassword(['X...',
// '..X.',
// 'X..X',
// '....'],
// ['itdf',
// 'gdce',
// 'aton',
// 'qrdi']), 'icantforgetiddqd', "First Example");
// assert.equal(recallPassword(['....',
// 'X..X',
// '.X..',
// '...X'],
// ['xhwc',
// 'rsqx',
// 'xqzz',
// 'fyzr']), 'rxqrwsfzxqxzhczy', "Second Example");
// console.log("Coding complete? Click 'Check' to review your tests and earn cool rewards!");
// }
| true |
be207f3c45151813b2c662ac94bda3e01c11273a
|
JavaScript
|
brittjavs/shopify_movie_noms
|
/app.js
|
UTF-8
| 387 | 2.640625 | 3 |
[] |
no_license
|
const omdbKey = omdb.OMDB_KEY
let button = document.getElementById("search")
7
button.addEventListener("click", function(){
let inputTitle = document.getElementById("titleInput").value
fetch("http://www.omdbapi.com/?type=movie&s=" + inputTitle + "&apikey=" + omdbKey )
.then(resp => resp.json())
.then(movies => console.log(movies))
})
function displayMovies(){
}
| true |
3e9e5f3727e3c64358a27cc873cdf1538a9c702d
|
JavaScript
|
elvismelkic/vanado-task-backend
|
/tests/machine.test.js
|
UTF-8
| 4,440 | 2.59375 | 3 |
[] |
no_license
|
const request = require("supertest");
const app = require("../src/app");
const Machine = require("../src/models/machine");
const Failure = require("../src/models/failure");
const {
setupDatabase,
machineOne,
machineOneId,
machineTwo,
wrongId
} = require("./fixtures/db");
beforeEach(setupDatabase);
// POST TESTS
test("Should add new machine", async () => {
const response = await request(app)
.post("/api/machines")
.send({ name: "Test Machine Name" })
.expect(201);
const machine = await Machine.findById(response.body._id);
expect(response.body).toMatchObject({ name: "Test Machine Name" });
expect(machine.name).toBe("Test Machine Name");
});
test("Should return error if adding new machine with name that is taken", async () => {
await request(app)
.post("/api/machines")
.send({ name: machineOne.name })
.expect(400);
});
test("Should return error if adding new machine with empty name", async () => {
await request(app)
.post("/api/machines")
.send({ name: "" })
.expect(400);
});
// GET TESTS
test("Should get all machines", async () => {
const response = await request(app)
.get("/api/machines")
.send()
.expect(200);
expect(response.body.length).toBe(2);
});
test("Should get a machine by ID", async () => {
const response = await request(app)
.get(`/api/machines/${machineOneId}`)
.send()
.expect(200);
const machine = await Machine.findById(machineOneId);
const failures = await Failure.find({ machine: machine._id });
expect(machine.name).toBe(response.body.name);
expect(failures.length).toBe(response.body.failures.length);
});
test("Should return error if getting a machine by nonexisting ID", async () => {
const response = await request(app)
.get(`/api/machines/${wrongId}`)
.send()
.expect(404);
expect(response.body.error).toBe("Not found");
});
test("Should return error if getting a machine by random route (not ID type)", async () => {
await request(app)
.get("/api/machines/somerandomroute")
.send()
.expect(400);
});
// UPDATE TESTS
test("Should update machine if machine exists", async () => {
const response = await request(app)
.patch(`/api/machines/${machineOneId}`)
.send({ name: "Updated Machine Name" })
.expect(200);
const machine = await Machine.findById(machineOneId);
expect(machine.name).toBe(response.body.name);
expect(response.body.name).toBe("Updated Machine Name");
});
test("Should return error if updating machine that doesn't exists", async () => {
const response = await request(app)
.patch(`/api/machines/${wrongId}`)
.send({ name: "Updated Machine Name" })
.expect(404);
expect(response.body.error).toBe("Not found");
});
test("Should return error if updating machine on random route (not ID type)", async () => {
await request(app)
.patch("/api/machines/somerandomroute")
.send({ name: "Updated Machine Name" })
.expect(400);
});
test("Should return error if updating machine with name that is taken", async () => {
await request(app)
.patch(`/api/machines/${machineOneId}`)
.send({ name: machineTwo.name })
.expect(400);
});
test("Should return error if updating machine with invalid values", async () => {
const response = await request(app)
.patch(`/api/machines/${machineOneId}`)
.send({ name: "" })
.expect(400);
expect(response.body.errors.name.kind).toBe("required");
});
test("Should return error if updating machine with nonexisting fields", async () => {
const response = await request(app)
.patch(`/api/machines/${machineOneId}`)
.send({ manufacturer: "MAN" })
.expect(400);
expect(response.body.error).toBe("Invalid updates");
});
// DELETE TESTS
test("Should delete machine if machine exists", async () => {
await request(app)
.delete(`/api/machines/${machineOneId}`)
.send()
.expect(200);
const machine = await Machine.findById(machineOneId);
expect(machine).toBeNull();
});
test("Should return error if deleting machine that doesn't exists", async () => {
const response = await request(app)
.delete(`/api/machines/${wrongId}`)
.send()
.expect(404);
expect(response.body.error).toBe("Not found");
});
test("Should return error if deleting machine on random route (not ID type)", async () => {
await request(app)
.delete("/api/machines/somerandomroute")
.send()
.expect(400);
});
| true |
4da532379535bdce177d17953d1a471a9b78a260
|
JavaScript
|
akanksha-tanu/quiz
|
/quizApp/java/highscore.js
|
UTF-8
| 1,454 | 3.203125 | 3 |
[] |
no_license
|
var highScoresList=document.getElementById("highScoresList");
const highScores=JSON.parse(localStorage.getItem("highScores")) || [];
// var high=[];
// highScores.forEach(function(e){
// // console.log(e);
// high.push(e);
// })
// high.sort((a,b) => b.score-a.score) ;
// high.splice(5);
// highScoresList.innerHTML=high.map(function(score){
// return("<li><span class='name'>"+score.name+'</span> - <span class="score">'+score.score+"</span></li>");
// }).join("");
//retriving all the present high scores stored in li
var final=[];
var n="";
var sc=Number();
var li=Array.from(document.querySelectorAll("li"));
//console.log(li);
for(var i=0;i<li.length;i++){
var index=li[i].outerText.indexOf("-");
n=li[i].outerText.slice(0,index-1);
sc=li[i].outerText.slice(index+2,li[i].outerText.length);
//console.log(n+sc);
final.push({score:sc,name:n});
}
//console.log(final);
//retriving current scores in local storage
for(var j=0;j<highScores.length;j++)
{
final.push(highScores[j]);
}
for(var z=0;z<final.length;z++)
//console.log(Number(final[z].score));
final.sort((a,b) => b.score-a.score) ;
final.splice(5);
//console.log(final);
highScoresList.innerHTML=final.map(function(score){
return("<li style='visibility:visible;'><span class='name'>"+score.name+'</span> - <span class="score">'+score.score+"</span></li>");
}).join("");
| true |
99d94d8faa3bd3efecb1c4858d7ee3912d0331fa
|
JavaScript
|
davidmbedford/TriviaGame
|
/assets/javascript/app.js
|
UTF-8
| 5,608 | 2.96875 | 3 |
[] |
no_license
|
//// Trivia game
// A list of features I need to design
////shows one question until:
/////////the player answers it
/////////or their time runs out.
////when they hover over the answer, it is highlighted.
////when they click, it will:
////////show 'congrats' if they are correct
////////show 'oops' if they are wrong. and show the correct answer.
////////wait 3 seconds, move on to next question
////////from directions:"The scenario is similar for wrong answers and time-outs.'
////If they run out of time, tell the player:
////////"time's up" and display the correct answer.
////////Wait a few seconds, then show the next question.
////On the final screen, show the number of correct answers,
///////incorrect answers, and an option to restart the game
///////(without reloading the page).
/////// first and last slide will contain a start and a restart button
$(document).ready(function() {
//opening stats//
var correct = 0;
var wrong = 0;
var score = "";
var timerRunning = false; // we will need this to activate the slideshow after we hit start
var time = 0;
var slideCount = 0;
var intervalId;
var allQuestions = [
questionOne = {
aOne: "Labrador Retreiver",
aTwo: "Poodle",
aThree: "Portuguese Water Dog",
aFour: "Bernese Mountain Dog",
answer: "Bernese Mountain Dog",
image: "assets/images/BerneseMountainDog.jpg",
},
questionTwo = {
aOne: "Saluki",
aTwo: "French Bulldog",
aThree: "Irish Wolfhound",
aFour: "Corgi",
answer: "French Bulldog",
image: "assets/images/FrenchBulldog.jpg",
},
questionThree = {
aOne: "Dachshund",
aTwo: "Chihuahua",
aThree: "Bulldog",
aFour: "Pug",
answer: "Dachshund",
image: "assets/images/Dachshund.jpg",
},
questionFour = {
aOne: "English Mastiff",
aTwo: "Greyhound",
aThree: "Old English Sheep Dog",
aFour: "Portuguese Water Dog",
answer: "Portuguese Water Dog",
image: "assets/images/PortugueseWaterDog.jpg",
},
questionFive = {
aOne: "German Shepherd",
aTwo: "Golden Retriever",
aThree: "Boxer",
aFour: "Bulldog",
answer: "Boxer",
image: "assets/images/Boxer.jpg",
},
questionSix = {
aOne: "Pomeranian",
aTwo: "Poodle",
aThree: "Bichon Frise",
aFour: "Akita",
answer: "Bichon Frise",
image: "assets/images/BichonFrise.jpg",
},
questionSeven = {
aOne: "Siberian Husky",
aTwo: "Maltese",
aThree: "Pug",
aFour: "Beagle",
answer: "Beagle",
image: "assets/images/Beagle.jpg",
},
questionEight = {
aOne: "Airedale Terrier",
aTwo: "American Eskimo Dog",
aThree: "Basenji",
aFour: "Chow Chow",
answer: "Chow Chow",
image: "assets/images/ChowChow.jpg",
},
questionNine = {
aOne: "Irish Setter",
aTwo: "Basset Hound",
aThree: "Beagle",
aFour: "Dachshund",
answer: "Basset Hound",
image: "assets/images/BassetHound.jpg",
},
questionTen = {
aOne: "Akita",
aTwo: "Borzoi",
aThree: "Saluki",
aFour: "Papillon",
answer: "Akita",
image: "assets/images/Akita.jpg",
},
];
$("#correctStat").text(correct);
$("#wrongStat").text(wrong);
$("#scoreStat").text(score);
$("#timer").text("00:00");
if (!timerRunning) {
$(".main-card").append("<button id='startBtn'>" + "Start!" + "</button>");
}
//Most of the important variables are above.
//Below are the functions-etc that I need to have the questions/timers run
function setSlides() {
//one
$("#aOne").text(allQuestions[slideCount].aOne);
$("#aOne").attr("data-value", allQuestions[slideCount].aOne);
//two
$("#aTwo").text(allQuestions[slideCount].aTwo);
$("#aTwo").attr("data-value", allQuestions[slideCount].aTwo);
//three
$("#aThree").text(allQuestions[slideCount].aThree);
$("#aThree").attr("data-value", allQuestions[slideCount].aThree);
//four
$("#aFour").text(allQuestions[slideCount].aFour);
$("#aFour").attr("data-value", allQuestions[slideCount].aFour);
//answer
//$("#answer").text("Answer: " + allQuestions[slideCount].answer);
$("#answer").attr("data-value", allQuestions[slideCount].aOne);
//image
$("#dogPic").attr("src", allQuestions[slideCount].image);
console.log("time", time);
console.log("correct", correct);
slideCount++;
console.log("count", slideCount);
};
function begin() {
setSlides();
timerRunning = true;
var slideDuration = setInterval(setSlides, 5000);
intervalId = setInterval(count, 1000);
$(".clicker").on("click", function() {
var userGuess = $(this).attr("data-value");
console.log(userGuess);
var realAnswer = allQuestions[slideCount-1].answer;
console.log(realAnswer);
console.log(correct);
console.log(wrong);
if (userGuess === realAnswer) {
correct++;
$("#correctStat").text(correct);
}
else if (userGuess != realAnswer) {
wrong++;
$("#wrongStat").text(wrong);
}
});
};
function count() {
time++;
var converted = timeConverter(time);
//console.log(converted);
$("#timer").text(converted);
};
function timeConverter(t) {
var minutes = Math.floor(t / 60);
var seconds = t - (minutes * 60);
if (seconds < 10) {
seconds = "0" + seconds;
}
if (minutes === 0) {
minutes = "00";
}
else if (minutes < 10) {
minutes = "0" + minutes;
}
return minutes + ":" + seconds;
}
function stop() {
clearInterval(intervalId);
timerRunning = false;
};
$(document).on("click", "#startBtn", begin);
$("h5").hover(
function () {
$(this).css("border-style", "solid");
}, function() {
$( this ).css("border-style", "none");
});
});
| true |
6cd4ef1c0d859328a9c45bb89dcce4dc2605425e
|
JavaScript
|
tjorge30/noDBproject
|
/server/controllers/commentsCtrl.js
|
UTF-8
| 379 | 2.578125 | 3 |
[] |
no_license
|
const comments = require('../../comments.json')
module.exports = {
getComments: (req, res) =>{
res.status(200).send(comments)
},
postComment: (req, res) =>{
var newComment = {
id: comments.length + 1,
comment: req.body.comment
};
comments.push(newComment);
res.status(200).send(comments)
}
}
| true |
7a964756bdeba755199b149f894fb47ca2aae78f
|
JavaScript
|
OppositeVector/CanvasDrawing
|
/includes/js/BasicDrawing.js
|
UTF-8
| 12,403 | 3.671875 | 4 |
[] |
no_license
|
// This function draws a single pixel on HTML 5 canvas imageData
// It expects x and y to be integers
function DrawPixel(x, y, color, image) {
if((x < 0) || (x >= image.width) || (y < 0) || (y >= image.height)) {
return;
}
loc = (y * image.width * 4) + (x * 4);
image.data[loc] = color.r;
image.data[loc + 1] = color.g;
image.data[loc + 2] = color.b;
image.data[loc + 3] = color.a;
}
// Receives an array of pixels, a color and an HTML 5 canvas imageData
function DrawPixels(pArr, color, image) {
for(var i = 0; i < pArr.length; i += 2) {
loc = (pArr[i+1] * image.width * 4) + (pArr[i] * 4);
image.data[loc] = color.r;
image.data[loc + 1] = color.g;
image.data[loc + 2] = color.b;
image.data[loc + 3] = color.a;
// DrawPixel(pArr[i], pArr[i + 1], color, image);
}
}
function ClearImage(color, image) {
var li = image.data.length;
for(var i = 0; i < li; i += 4) {
image.data[i] = color.r;
image.data[i + 1] = color.g;
image.data[i + 2] = color.b;
image.data[i + 3] = color.a;
}
}
// Same as DrawPixels but this function expects image.data to be UInt32Array
function DrawPixel32(x, y, color, image) {
loc = (y * image.width) + x;
image[loc] = (color.a << 24) |
(color.b << 16) |
(color.g << 8) |
(color.b);
}
// Same as DrawPixels but this function expects image.data to be UInt32Array
function DrawPixels32(pArr, color, image) {
for(var i = 0; i < pArr.length; i += 2) {
DrawPixel32(pArr[i], pArr[i + 1], color, image);
}
}
function ClearImage32(color, image) {
for(var i = 0; i < image.data.length; ++i) {
image[i] = (color.a << 24) |
(color.b << 16) |
(color.g << 8) |
(color.b);
}
}
function ToColor(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
a: 255
} : null;
}
function ToHex(color) {
function ComponentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
return "#" + ComponentToHex(color.r) + ComponentToHex(color.g) + ComponentToHex(color.b)
}
// Takes two points and draws all the pixels between them on the image
function DrawLine(p1, p2, color, image) {
var xD = p2.x - p1.x;
var yD = p2.y - p1.y;
if((xD == 0) && (yD == 0)) {
DrawPixel(p1.x, p1.y, color, image);
return;
}
var absX = Math.abs(xD);
var absY = Math.abs(yD);
var g = (absX > absY) ? absX : absY;
var xStep = xD / g;
var yStep = yD / g;
var curX = p1.x;
var curY = p1.y;
for(var i = 0; i < g; i += 1) {
DrawPixel(Math.floor(curX), Math.floor(curY), color, image);
curX += xStep;
curY += yStep;
}
}
// Takes a center and a radius, Draws all the pixels that constitute the circle in the
// canvas data block (image)
function DrawCircle(cp, r, color, image) {
if(r == 0) {
DrawPixel(cp.x, cp.y, color, image);
return;
}
var acp = { x: Math.floor(cp.x), y: Math.floor(cp.y) };
var x = Math.floor(r);
var y = 0;
var decisionOver2 = 1 - x;
while(y <= x) {
DrawPixel( x + acp.x, y + acp.y, color, image);
DrawPixel( y + acp.x, x + acp.y, color, image);
DrawPixel(-x + acp.x, y + acp.y, color, image);
DrawPixel(-y + acp.x, x + acp.y, color, image);
DrawPixel(-x + acp.x, -y + acp.y, color, image);
DrawPixel(-y + acp.x, -x + acp.y, color, image);
DrawPixel( x + acp.x, -y + acp.y, color, image);
DrawPixel( y + acp.x, -x + acp.y, color, image);
++y;
if (decisionOver2<=0){
decisionOver2 += 2 * y + 1; // Change in decision criterion for y -> y+1
}else{
--x;
decisionOver2 += 2 * (y - x) + 1; // Change for y -> y+1, x -> x-1
}
}
}
// Recieves Center Point, Radius, Amount of Edges, And the angle of the first vertex from the y axis
function DrawRegularPolygon(cp, r, e, a, color, image) {
if(e < 3) {
throw Exception("Trying to caculate a regular polygon with less then 3 edges");
}
var acp = { x: Math.floor(cp.x), y: Math.floor(cp.y) };
if(r == 0) {
DrawPixel(acp.x, acp.y, color, image);
return;
}
var degreesPerLine = 360 / e;// The amount of degrees on a circle that each section will cover
var dplRads = Math.PI * (degreesPerLine / 180); // degreesPerLine in radians
// var sectionLength = Math.sqrt((2 - (2 * Math.cos(dplRads)))) * r;
var current = {
x: cp.x - (r * Math.cos(a)),
y: cp.y - (r * Math.sin(a)),
alpha: a
};
// retVal.push(acp.x, acp.y);
// console.log(acp.x + " " + acp.y);
for(var i = 0; i < e; ++i) {
var p1 = { x: current.x, y: current.y };
// var p2 = { x: cp.x + Math.cos(current.alpha), y: cp.y + Math.sin(current.alpha) };
current.alpha += dplRads;
current.x = cp.x - (r * Math.cos(current.alpha));
current.y = cp.y - (r * Math.sin(current.alpha));
// current.x += sectionLength * Math.cos(current.alpha);
// current.y += sectionLength * Math.sin(current.alpha);
DrawLine(p1, current, color, image);
// current.alpha += dplRads;
}
}
// Takes a points array, line count, a color and a canvas data block, creates a qudratic curve
// using pArr[0] as a start, pArr[2] as an end, and pArr[1] as a control point,
// pArr is shorter then 3, a simple line will be created
function DrawQuadraticCurve(pArr, lc, color, image) {
if(pArr.length == 0) {
return;
} else if(pArr.length == 1) {
DrawPixel(pArr[0].x, pArr[0].y, color, image);
return;
} else if(pArr.length == 2) {
DrawLine(pArr[0], pArr[1], color, image);
return;
}
var t = 0;
var tStep = 1 / lc;
var prev = { x: Math.floor(pArr[0].x), y: Math.floor(pArr[0].y) };
for(var i = 0; i <= lc; ++i) {
var tt = t * t;
var u = 1-t;
var uu = u * u;
var tu = 2 * u * t;
var x = (uu * pArr[0].x) + (tu * pArr[1].x) + (tt * pArr[2].x);
var y = (uu * pArr[0].y) + (tu * pArr[1].y) + (tt * pArr[2].y);
var p = { x: Math.floor(x), y: Math.floor(y) };
DrawLine(prev, p, color, image);
t += tStep;
prev = p;
}
}
// Recieves an a array of points, a line count, a color and a canvas data block
// Creates a bezier curve using pArr[0] as a start, pArr[3] as an end, and pArr[1] and pArr[2] as control points,
// if pArr is shorter then 4, a qudratic curve will be created
function DrawBezierCurve(pArr, lc, color, image) {
if(pArr.length < 4) {
return DrawQuadraticCurve(pArr, lc, color, image);
}
var t = 0;
var tStep = 1 / lc;
var prev = { x: Math.floor(pArr[0].x), y: Math.floor(pArr[0].y) };
for(var i = 0; i <= lc; ++i) {
var u = 1 - t;
var tt = t*t;
var uu = u*u;
var uuu = uu * u;
var ttt = tt * t;
var x = pArr[0].x * uuu;
x += 3 * uu * t * pArr[1].x;
x += 3 * u * tt * pArr[2].x;
x += ttt * pArr[3].x;
var y = pArr[0].y * uuu;
y += 3 * uu * t * pArr[1].y;
y += 3 * u * tt * pArr[2].y;
y += ttt * pArr[3].y;
var p = { x: Math.floor(x), y: Math.floor(y) };
DrawLine(prev, p, color, image);
t += tStep;
prev = p;
}
}
// Recieves Center Point, Radius, Amount of Edges, And the angle of the first vertex from the y axis
function CalculateRegularPolygon(cp, r, e, a) {
if(e < 3) {
throw Exception("Trying to caculate a regular polygon with less then 3 edges");
}
var retVal = [];
var acp = { x: Math.floor(cp.x), y: Math.floor(cp.y) };
if(r == 0) {
retVal.push(acp);
return retVal;
}
var degreesPerLine = 360 / e;// The amount of degrees on a circle that each section will cover
var dplRads = Math.PI * (degreesPerLine / 180); // degreesPerLine in radians
// var sectionLength = Math.sqrt((2 - (2 * Math.cos(dplRads)))) * r;
var current = {
x: cp.x - (r * Math.cos(a)),
y: cp.y - (r * Math.sin(a)),
alpha: a
};
// retVal.push(acp.x, acp.y);
// console.log(acp.x + " " + acp.y);
for(var i = 0; i < e; ++i) {
var p1 = { x: current.x, y: current.y };
retVal.push(p1);
// var p2 = { x: cp.x + Math.cos(current.alpha), y: cp.y + Math.sin(current.alpha) };
current.alpha += dplRads;
current.x = cp.x - (r * Math.cos(current.alpha));
current.y = cp.y - (r * Math.sin(current.alpha));
// current.x += sectionLength * Math.cos(current.alpha);
// current.y += sectionLength * Math.sin(current.alpha);
// DrawLine(p1, current, color, image);
// current.alpha += dplRads;
}
return retVal;
}
// -----------------------------------------------------------------------
// Alternative calculation functions
// Takes two points and returns an array of all the pixels in the way
function CalculateLine(p1, p2, arr) {
var retVal;
if(arr != null) {
retVal = arr;
} else {
retVal = [];
}
var xD = p2.x - p1.x;
var yD = p2.y - p1.y;
if((xD == 0) && (yD == 0)) {
retVal.push(p1.x, p1.y);
return retVal;
}
var absX = Math.abs(xD);
var absY = Math.abs(yD);
var g = (absX > absY) ? absX : absY;
var xStep = xD / g;
var yStep = yD / g;
var curX = p1.x;
var curY = p1.y;
for(var i = 0; i < g; i += 1) {
retVal.push(Math.floor(curX), Math.floor(curY));
curX += xStep;
curY += yStep;
}
return retVal;
}
// Takes a center and a radius, returns all the pixels that constitute the circle
function CalculateCircle(cp, r, arr) {
var retVal;
if(arr != null) {
retVal = arr;
} else {
retVal = [];
}
if(r == 0) {
retVal.push(cp.x, cp.y);
return retVal;
}
var acp = { x: Math.floor(cp.x), y: Math.floor(cp.y) };
var x = Math.floor(r);
var y = 0;
var decisionOver2 = 1 - x;
while(y <= x) {
retVal.push( x + acp.x, y + acp.y);
retVal.push( y + acp.x, x + acp.y);
retVal.push(-x + acp.x, y + acp.y);
retVal.push(-y + acp.x, x + acp.y);
retVal.push(-x + acp.x, -y + acp.y);
retVal.push(-y + acp.x, -x + acp.y);
retVal.push( x + acp.x, -y + acp.y);
retVal.push( y + acp.x, -x + acp.y);
++y;
if (decisionOver2<=0){
decisionOver2 += 2 * y + 1; // Change in decision criterion for y -> y+1
}else{
--x;
decisionOver2 += 2 * (y - x) + 1; // Change for y -> y+1, x -> x-1
}
}
return retVal;
}
function LinearInterpolation(p1, p2, t) {
return { x: p1.x + ((p2.x - p1.x) / t), y: p1.y - ((p2.y - p1.y) / t) };
}
// The value of the lerp will go into p1
function InternalLerp(p1, p2, t) {
p1.x = p1.x + ((p2.x - p1.x) / t);
p1.y = p1.y + ((p2.y - p1.y) / t);
}
// Takes a points array, line count and a pixels array, creates a qudratic curve
// using pArr[0] as a start, pArr[2] as an end, and pArr[1] as a control point,
// pArr is shorter then 3, a simple line will be created
function CalculateQuadraticCurve(pArr, lc, arr) {
var retVal;
if(arr == null) {
retVal = [];
} else {
retVal = arr;
}
if(pArr.length == 0) {
return retVal;
} else if(pArr.length == 1) {
retVal.push(pArr[0].x, pArr[0].y);
return retVal;
} else if(pArr.length == 2) {
return CalculateLine(pArr[0], pArr[1], retVal);
}
var t = 0;
var tStep = 1 / lc;
var prev = { x: Math.floor(pArr[0].x), y: Math.floor(pArr[0].y) };
for(var i = 0; i <= lc; ++i) {
var x = (Math.pow(1-t, 2) * pArr[0].x) + (2 * (1-t) * t * pArr[1].x) + (Math.pow(t, 2) * pArr[2].x);
var y = (Math.pow(1-t, 2) * pArr[0].y) + (2 * (1-t) * t * pArr[1].y) + (Math.pow(t, 2) * pArr[2].y);
var p = { x: Math.floor(x), y: Math.floor(y) };
retVal = CalculateLine(prev, p, retVal);
t += tStep;
prev = p;
}
return retVal;
}
// Recieves an a array of points, a line count and a pixel buffer into which the pixels should be written
// Creates a bezier curve using pArr[0] as a start, pArr[3] as an end, and pArr[1] and pArr[2] as control points,
// if pArr is shorter then 4, a qudratic curve will be created
function CalculateBezierCurve(pArr, lc, arr) {
var retVal;
if(arr == null) {
retVal = [];
} else {
retVal = arr;
}
if(pArr.length < 4) {
return CalculateQuadraticCurve(pArr, lc, retVal);
}
var t = 0;
var tStep = 1 / lc;
var prev = { x: Math.floor(pArr[0].x), y: Math.floor(pArr[0].y) };
for(var i = 0; i <= lc; ++i) {
var u = 1 - t;
var tt = t*t;
var uu = u*u;
var uuu = uu * u;
var ttt = tt * t;
var x = pArr[0].x * uuu;
x += 3 * uu * t * pArr[1].x;
x += 3 * u * tt * pArr[2].x;
x += ttt * pArr[3].x;
var y = pArr[0].y * uuu;
y += 3 * uu * t * pArr[1].y;
y += 3 * u * tt * pArr[2].y;
y += ttt * pArr[3].y;
var p = { x: Math.floor(x), y: Math.floor(y) };
retVal = CalculateLine(prev, p, retVal);
t += tStep;
prev = p;
}
return retVal;
}
| true |
13c7b607cf2eb669bf04203d1a2c10304f8eb0e1
|
JavaScript
|
ZHKO1/leetcode
|
/124.binary-tree-maximum-path-sum/124.js
|
UTF-8
| 943 | 3.09375 | 3 |
[] |
no_license
|
/*
* @lc app=leetcode id=124 lang=javascript
*
* [124] Binary Tree Maximum Path Sum
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxPathSum = function(root) {
var MAX = -Infinity;
dfsMaxPathSum(root);
return MAX;
function dfsMaxPathSum(node){
if(!node){
return 0;
}
if(!node.left && !node.right ){
MAX = Math.max(MAX, node.val)
return node.val;
}
var left = dfsMaxPathSum(node.left);
var right = dfsMaxPathSum(node.right);
var middle = node.val;
var max = Math.max(middle, middle + left, middle + right);
MAX = Math.max(MAX, max, middle + left + right)
return max;
}
};
// @lc code=end
| true |
eda0f1a15395826b0a91bbc7e5de02248605c3ec
|
JavaScript
|
Noel-A-Gonzalez/unitechkanban
|
/public/javascripts/app.js
|
UTF-8
| 2,288 | 2.53125 | 3 |
[] |
no_license
|
var app = function(){
/* Función que inicia todos los eventos que se cargan
al terminar de cargar la página
*/
var initEvent = function(){
$(document).ready(function() {
/*Renderizar pagina full*/
var fullHeight = $(window).height() - $(".header").outerHeight() - $(".title-board").outerHeight();
$(".container-full").height(fullHeight);
/*metodos*/
getUser();
column.getJSON();
moment.locale();
});
}
var getUser = function(){
$.get('rsesion/getSession', function(user){
$("#nameUser").text(user);
});
}
/*Cuando vuelve del callback, si acepta la peticion de acceso
- pone un alerta confirmando
- llama a positInWait del module posit(post-it.js)*/
var confirmCalendar = function(){
$.get('/confirmCalendar', function(data){
var fechaWait = new Date(data.fecha)
fecha = moment(data.fecha, 'YYYY.MM.DD').format('DD/MM/YYYY');
if(data){
if (data.link) {
Lobibox.alert("success",{
title: "Éxito",
msg: "Se ha registrado un nuevo evento en su calendario el " + fecha
});
}else{
$.post("ritem/deleteFecha", {item: data.id}, function(){
})
.done(function(red){
$('li[data-id="'+data.id+'"]').find(".drag-handler").show();
$('li[data-id="'+data.id+'"]').addClass("nowait").removeClass("positWait");
$('li[data-id="'+data.id+'"] .todo-actions .edit-todo').show();
$('li[data-id="'+data.id+'"] .lobilist-item-duedate').remove();
column.countItem();
Lobibox.alert("error",{
title: "ERROR",
msg: "Hubo un error al intentar conectar con Google Calendar. Verifique su conexión..."
});
})
}
}
});
}
/*
Suprimir el uso de la tecla ENTER en Textarea
*/
var form_sin_enter = function($char, $mozChar){
$('input').keypress(function(e){
if(e == 13){
return false;
}
});
$('textarea').keypress(function(e){
if(e.which == 13){
return false;
}
});
}
return{
initEvent:initEvent,
confirmCalendar:confirmCalendar,
form_sin_enter:form_sin_enter,
}
}();
app.initEvent();
| true |
0ae571ffe4caed1703fc279bc2190cb1800cd65e
|
JavaScript
|
Jomative/Workspace
|
/JavaScript/Practice/main.js
|
UTF-8
| 950 | 3.203125 | 3 |
[] |
no_license
|
/**@type {HTMLCanvasElement} */
const can = document.getElementById("can");
can.width = 300;
can.height = 100;
const ctx = can.getContext("2d");
const obj = {
x:0,
y:0,
w:10,
h:10
}
let keys = {};
let speed = 0.1;
function update(){
requestAnimationFrame(update);
ctx.clearRect(0,0,can.width,can.height);
if(keys.d) obj.x += speed;
if(keys.a) obj.x -= speed;
if(keys.w) obj.y -= speed;
if(keys.s) obj.y += speed;
if(obj.x < 0) obj.x = 0;
if(obj.x > can.width-10) obj.x = can.width-10;
if(obj.y < 0) obj.y = 0;
if(obj.y > can.height-10) obj.y = can.height-10;
ctx.fillStyle = "red";
ctx.fillRect(Math.floor(obj.x), Math.floor(obj.y), obj.w, obj.h);
}
update();
document.addEventListener("keydown",e=>{
let key = e.key.toLowerCase();
keys[key] = true;
});
document.addEventListener("keyup",e=>{
let key = e.key.toLowerCase();
keys[key] = false;
});
| true |
61075fc13324a8e0232745380fa2c1699b8f0138
|
JavaScript
|
JoaoVasconcelosV/curso-JSPro
|
/js/arrays.js
|
UTF-8
| 613 | 3.28125 | 3 |
[] |
no_license
|
let hitchedSpaceships = ['Supernova', 'Elemental', 'Helmet'];
console.log(hitchedSpaceships);
hitchedSpaceships.push("CalangoVoador");//add novo item a um array
console.log(hitchedSpaceships);
hitchedSpaceships.unshift("JumentoAir");//add novo item a primeira posição de um array
console.log(hitchedSpaceships);
hitchedSpaceships.pop();//rem o ultimo item de um array
console.log(hitchedSpaceships);
hitchedSpaceships.shift();//rem o primeiro item de um array
console.log(hitchedSpaceships.indexOf('Helmet'));//retorna a pos do item passado, se o item não existir retorna -1
console.log(hitchedSpaceships);
| true |
4a9cb526dc17d8a6bf4b0967bf747e4ecd7b399f
|
JavaScript
|
hypersport/LeetCode
|
/implement-magic-dictionary/implement_magic_dictionary.js
|
UTF-8
| 1,097 | 3.84375 | 4 |
[] |
no_license
|
/**
* Initialize your data structure here.
*/
var MagicDictionary = function() {
this.rdict = null;
};
/**
* Build a dictionary through a list of words
* @param {string[]} dict
* @return {void}
*/
MagicDictionary.prototype.buildDict = function(dict) {
this.rdict = dict;
};
/**
* Returns if there is any word in the trie that equals to the given word after modifying exactly one character
* @param {string} word
* @return {boolean}
*/
MagicDictionary.prototype.search = function(word) {
for (var index in this.rdict) {
var n = 0;
if (word.length == this.rdict[index].length) {
for (var i = 0; i < word.length; i ++) {
if (word.charAt(i) != this.rdict[index].charAt(i)) {
n ++;
}
}
if (n == 1) {
return true;
}
}
}
return false;
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* var obj = Object.create(MagicDictionary).createNew()
* obj.buildDict(dict)
* var param_2 = obj.search(word)
*/
| true |
47b719ca4a8f61e10ab3922bf3984ad638f7a5ec
|
JavaScript
|
SamuelTR20/React-basics
|
/src/components/listadoP.jsx
|
UTF-8
| 2,641 | 2.796875 | 3 |
[] |
no_license
|
import React, {useState} from 'react'
import uniqid from 'uniqid'
const ListadoP = () => {
const [nombre, setNombre] = useState('')
const [listaNombres, setListaNombres] = useState([])
const [modoEdicion, setModoEdicion] = useState(false)
const [id, setId] = useState('')
const addNombre = (e) => {
e.preventDefault()
if(nombre.trim() !== ''){
const nuevoNombre = {
id:uniqid(),
name: nombre
}
setListaNombres([...listaNombres, nuevoNombre])
setNombre('')
}
}
const deleteNombre = (id) => {
const nuevoArray = listaNombres.filter(item => item.id !== id)
setListaNombres(nuevoArray)
}
const editar = (item) =>{
modoEdicion ? setNombre('') : setNombre(item.name)
setId(item.id)
setModoEdicion(!modoEdicion)
}
const editarNombre = (e) => {
e.preventDefault()
const NuevoArray = listaNombres.map(item => item.id === id ? {id:id, name:nombre} : item)
setListaNombres(NuevoArray)
setModoEdicion(false)
setNombre('')
}
return (
<div>
<h2>Crud basico </h2>
<div className="row">
<div className="col">
<h2>Listado de nombres</h2>
<ul className='list-group'>
{
listaNombres.map( item =>
<li key={item.id} className="list-group-item">{item.name}
<button onClick={() => {deleteNombre(item.id)}} className="btn btn-danger float-right">Borrrar
</button>
<button onClick={() => {editar(item)}} className="btn btn-info float-right ">Editar
</button>
</li>
)
}
</ul>
</div>
<div className="col">
<h2>Formualrio para añadir</h2>
<form className='form-group' onSubmit={modoEdicion ? editarNombre : addNombre}>
<input onChange={(e) =>{setNombre(e.target.value)}} type="text" placeholder="Inserte el nombre" value={nombre} className="form-control mb-3"/>
<input type="submit" className="btn btn-info btn-block"
value={modoEdicion ? 'Editar Nombre' : 'Registrar nombre'}/>
</form>
</div>
</div>
</div>
)
}
export default ListadoP
| true |
466cdaf6667cc5f8372805ac31a41981c0812732
|
JavaScript
|
JinwooGong/GitHub
|
/HTML_AR/2day/ex03.js
|
UTF-8
| 140 | 2.796875 | 3 |
[] |
no_license
|
console.log("----- ex03 -----");
var a = "안녕";
var b = "하세요";
console.log(a+b);
console.log(a+1);
var c = "1" + 1;
console.log(c);
| true |
aacb2c3206e54ed658da0bfaafa16d9fed6013d4
|
JavaScript
|
adamorlowskipoland/js-slider
|
/script.js
|
UTF-8
| 3,444 | 2.890625 | 3 |
[] |
no_license
|
const model = {
"pics": [
{
"imgName" : "pic1",
"imgSrc" : "imgs/pic1.jpg",
"imgAlt" : "Img training 1"
},
{
"imgName" : "pic2",
"imgSrc" : "imgs/pic2.jpg",
"imgAlt" : "Img training 2"
},
{
"imgName" : "pic3",
"imgSrc" : "imgs/pic3.jpg",
"imgAlt" : "Img training 3"
},
{
"imgName" : "pic4",
"imgSrc" : "imgs/pic4.jpg",
"imgAlt" : "Img training 4"
}
]
}
const operator = {
"carouselTimeout" : "",
"currentImg" : 0,
"clearTimeout" : function() {
clearTimeout(operator.carouselTimeout);
},
"createImg" : function() {
const wrapper = document.getElementById('wrapper');
const pic = document.createElement('img');
pic.id = 'pic';
wrapper.appendChild(pic);
},
"getImg" : function() {
const pic = document.getElementById('pic');
return pic;
},
"carousel" : function(x) {
operator.carouselTimeout = setTimeout(function() {
viewer.changeImg(x+1);
}, 3000);
},
"eventListeners" : function() {
const previous = document.getElementById('previous');
const next = document.getElementById('next');
previous.addEventListener('click', function() {
operator.clearTimeout();
viewer.changeImg(operator.currentImg-1);
});
next.addEventListener('click', function() {
operator.clearTimeout();
viewer.changeImg(operator.currentImg+1);
});
const indicators = Array.from(document.getElementsByClassName('indicator'));
indicators.forEach(indicator => indicator.addEventListener('click', function() {
var index = indicators.indexOf(this);
operator.clearTimeout();
viewer.setImg(index);
}));
}
}
const viewer = {
"setImg" : function(x) {
const pic = operator.getImg();
pic.setAttribute('src', model.pics[x].imgSrc);
pic.setAttribute('alt', model.pics[x].imgAlt);
operator.carousel(x);
viewer.activeIndicator(x);
},
"changeImg" : function(x) {
if (x < 0) {
x = (model.pics.length - 1)
viewer.setImg(x);
} else if (x < model.pics.length) {
viewer.setImg(x);
} else {
x = 0;
viewer.setImg(x);
}
operator.currentImg = x;
},
"showIndicators" : function() {
for (var pic in model.pics) {
const indicatorsList = document.getElementById('indicators-list');
var indicator = document.createElement('li');
indicator.className = 'indicator';
indicatorsList.appendChild(indicator);
viewer.activeIndicator(0);
};
},
"activeIndicator" : function(x) {
const indicators = document.querySelectorAll('.indicator');
indicators.forEach(function(indicator) {
indicator.classList.remove('active');
});
var indicator = indicators[x];
indicator.classList.add('active');
},
"displayInit" : function() {
operator.createImg();
viewer.showIndicators();
viewer.setImg(operator.currentImg);
operator.eventListeners();
}
}
viewer.displayInit();
| true |
0a33736b37aaa1e40df1563daf521bea3d5be260
|
JavaScript
|
abelRoland/encapsulation-week-1
|
/src/handlers/toggle-completed.js
|
UTF-8
| 1,377 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
var handlers = {
addTodos: function (e) {
debugger;
e = e || window.event;
e.preventDefault();
var add = document.getElementById("text-to-add").value;
if (add === "") {
alert("Please write a Todo!");
return;
}
app.addTodo(add);
view.displayTodos();
logger.push({
action: "Add Todo",
state: app.state,
});
document.getElementById("add").value = "";
},
deleteTodo: function (position) {
debugger;
app.deleteTodo(position);
view.displayTodos();
logger.push({
action: "Delete Todo ",
state: app.state,
});
},
toggleCompleted: function () {
debugger;
var address = document.querySelector("ul");
var toggleCompletedPo = address.childNodes;
toggleCompletedPo.forEach(function (child) {
if (child.childNodes[0].checked === true) {
var input = child.id;
app.toggleCompleted(Number(input));
child.className = "checkbox";
}
if (child.childNodes[0].checked === false) {
child.className = "";
child.setAttribute("checked", false);
}
});
logger.push({
action: "toggle completed",
state: app.state,
});
},
toggleAll: function () {
app.toggleAll();
view.displayTodos();
logger.push({
action: "toggle All",
state: app.state,
});
},
};
| true |
1fc72bb4d519c843d24b29568ba5658583bb0901
|
JavaScript
|
Akire-saku/node-exercises.github.io
|
/ej4/hotel.js
|
UTF-8
| 2,720 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
var Hotel = function (nombre, ciudad, telefono, direccion, sitioWeb, gerente, habitaciones ) {
var sthis = this;
this.datosHotel = {
nombre: "",
ciudad: "",
telefono: "",
direccion: "",
sitioWeb: "",
gerente: "",
habitaciones: 0
};
sthis.datosHotel.nombre= nombre;
sthis.datosHotel.ciudad= ciudad;
sthis.datosHotel.telefono= telefono;
sthis.datosHotel.direccion= direccion;
sthis.datosHotel.sitioWeb= sitioWeb;
sthis.datosHotel.gerente= gerente;
sthis.datosHotel.habitaciones= habitaciones;
sthis.getNombre = function getNombre()
{
return sthis.datosHotel.nombre;
}
sthis.setNombre = function setNombre(nombre)
{
sthis.datosHotel.nombre = nombre;
}
sthis.getCiudad = function getCiudad ()
{
return sthis.datosHotel.ciudad;
}
sthis.setCiudad = function setCiudad(ciudad)
{
sthis.datosHotel.ciudad = ciudad;
}
sthis.getTelefono = function getTelefono() {
return sthis.datosHotel.telefono;
}
sthis.setTelefono = function setTelefono(telefono)
{
sthis.datosHotel.telefono = telefono;
}
sthis.getDireccion = function getDireccion()
{
return sthis.datosHotel.direccion;
}
sthis.setDireccion = function setDireccion(direccion)
{
sthis.datosHotel.direccion = direccion;
}
sthis.getSitioWeb = function getSitioWeb()
{
return sthis.datosHotel.sitioWeb;
}
sthis.setSitioWeb = function setSitioWeb(sitioWeb)
{
sthis.datosHotel.sitioWeb = sitioWeb;
}
sthis.getGerente = function getGerente()
{
return sthis.datosHotel.gerente;
}
sthis.setGerente = function setGerente(gerente)
{
sthis.datosHotel.gerente = gerente;
}
sthis.getHabitaciones = function getHabitaciones()
{
return sthis.datosHotel.habitaciones;
}
sthis.setHabitaciones = function setHabitaciones(habitaciones)
{
sthis.datosHotel.habitaciones = habitaciones;
}
var checkTel = function (){
var re = new RegExp("[+][0-9]{2}. [0-9]{8}");
return re.test(sthis.datosHotel.telefono);
}, checkSitio = function (){
var re = new RegExp("[http://www].[a-zA-Z].[a-zA-Z]{2,3}");
return re.test(sthis.datosHotel.sitioWeb);
}
this.check = function check (campo) {
var check;
switch(campo) {
case "telefono": {
check = checkTel();
break;
}
case "sitio": {
check = checkSitio();
break;
}
}
return check;
}
};
| true |
f90a39061fe3cfb53b20316c88220dd4b0684f1d
|
JavaScript
|
alexuribarri/goit-js-hw-07
|
/js/task-05.js
|
UTF-8
| 393 | 3.40625 | 3 |
[] |
no_license
|
const form = {
nameInput: document.querySelector("#name-input"),
nameOutput: document.querySelector("#name-output"),
};
//console.log(form.nameInput);
function onNameInput() {
form.nameOutput.innerHTML = `${form.nameInput.value}`;
if (form.nameInput.value === "") {
form.nameOutput.innerHTML = `незнакомец`;
}
}
form.nameInput.addEventListener("input", onNameInput);
| true |
fc12e8aa2843eff7ca4eba48883b5df949b5684c
|
JavaScript
|
amgorder/vending_machine
|
/app/Controllers/VendingController.js
|
UTF-8
| 1,123 | 2.6875 | 3 |
[] |
no_license
|
import { vendingService } from '../Services/VendingService.js'
import { ProxyState } from '../AppState.js';
import Vending from '../Models/Vending.js';
function _draw() {
let sodaElem = document.getElementById("soda")
let candyElem = document.getElementById("candy")
let waterElem = document.getElementById("water")
let fireCrackersElem = document.getElementById("fire")
sodaElem.innerText = ProxyState.vendingMachine.soda.toString()
candyElem.innerText = ProxyState.vendingMachine.candy.toString()
waterElem.innerText = ProxyState.vendingMachine.water.toString()
fireCrackersElem.innerText = ProxyState.vendingMachine.fireCrackers.toString()
console.log('draw page');
}
export default class VendingController{
constructor() {
console.log('hello from the vending controller');
}
soda() {
vendingService.soda()
_draw()
}
candy() {
vendingService.candy()
_draw()
}
water() {
vendingService.water()
_draw()
}
fireCrackers() {
vendingService.fireCrackers()
_draw()
}
}
| true |
fa5ae1fada42533ac1c2ea5021287611f9116072
|
JavaScript
|
onham/node-chat-app
|
/server/utils/validation.test.js
|
UTF-8
| 566 | 2.921875 | 3 |
[] |
no_license
|
const expect = require('expect');
const { isRealString } = require('./validation');
describe('isRealString', () => {
it('should reject non-string values', () => {
const str = 123;
const check = isRealString(str);
expect(check).not.toBeTruthy();
});
it('should reject string with only spaces', () => {
const str = ' ';
const check = isRealString(str);
expect(check).not.toBeTruthy();
})
it('should allow string with non-space characters', () => {
const str = 'henlo';
const check = isRealString(str);
expect(check).toBeTruthy();
});
});
| true |
3692ad507f95eba8c0b391411086372ccde09339
|
JavaScript
|
jking026/complete-javascript-course
|
/01-Fundamentals-Part-1/starter/assignments.js
|
UTF-8
| 4,234 | 4.1875 | 4 |
[] |
no_license
|
/*
// LECTURE: VALUES AND VARIABLES//
let greeting = "Hello, welcome to a new tommorrow ";
let firstNameUser = "James "
// alert(greeting + firstName + ".");
//LECTURE: DATA TYPES//
const country = "United States of America";
const continent = "North America";
let population = 328000000;
// LECTURE: LET, CONST, AND VAR//
const isIsland = true;
// isIsland = false;
// console.log(typeof isIsland);
language = "English";
// console.log(typeof country);
// console.log(typeof continent);
// console.log(typeof population);
// console.log(typeof language);
// console.log(typeof isIsland);
//LECTURE: BASIC OPERATORS//
let usaHalfPopulation = population / 2; //outputs 164000000
let finlandTotalPopulation = 6000000;
let averageCountryPopulation = 33000000;
// const description = "Portugal is in Europe, and its 11 million people speak portuguese";
let description = `Portugal is in Europe, and its 11 million people speak portuguese`
usaHalfPopulation++; //increases val by 1; 164000001
// console.log(usaHalfPopulation);
// console.log(usaHalfPopulation > finlandTotalPopulation); //outputs true
// console.log(usaHalfPopulation < averageCountryPopulation); //outputs false
// console.log(description); //outputs "Portugal is in Europe, and its 11 million people speak portuguese"//
//LESSON: STRINGS AND TEMPLATE LITERALS//
description = `Portugal is in Europe,
and its 11 million people speak portuguese.`
// console.log(description);
//LECTURE: Taking Decisions: if / else Statements//
// let census = population - averageCountryPopulation;
// if (population >= averageCountryPopulation) {
// census = `USA's population is above average.🙀`;
// } else {
// census = `USA'S population is ${averageCountryPopulation - population} below average`;
// }
//ANSWER//
// if (population > 33000000) {
// console.log(`${country}'s population is above average`);
// } else {
// console.log(
// `${country}'s population is ${33000000 - population} million below average`,
// );
// }
// console.log(census);
//LESSON: TYPE CONVERSION AND COERCION//
// console.log('9' - '5'); // prediction: 4
// console.log('19' - '13' + '17'); //prediction '617'
// console.log('19' - '13' + 17); //prediction 23
// console.log('123' < 57); //prediction false
// console.log(5 + 6 + '4' + 9 - 4 - 2) //prediction 117
// //5 + 6 = 11 + '4' => "114" + 9 => "1149" - 4 => 1145 -2 => 1143//
//LESSON: EQUALITY OPERATORS: == VS. ===
// const numNeighbors = Number(prompt("How many neighbor countries does your country have? "));
// if (numNeighbors === 1) {
// console.log("Only 1 border!");
// } else if (numNeighbors > 1) {
// console.log("More than 1 border")
// } else {
// console.log("No borders")
// }
// //Note: without the Number(promp) and === strict equality the 1 would log "No borders"
//LESSON: LOGICAL OPERATORS//
const country = "USA";
const language = 'english';
const population = 328000000;
const idealPopulation = 50000000;
const isIsland = false;
if (population < idealPopulation && language === 'english' && !isIsland) {
console.log(`You should live in ${country}`)
} else {
console.log(`${country} does not meet your criteria 😢`)
}
//LECTURE: THE SWITCH STATEMENT//
let census = population - averageCountryPopulation;
if (population >= averageCountryPopulation) {
census = `USA's population is above average.🙀`;
} else {
census = `USA'S population is ${averageCountryPopulation - population} below average`;
}
console.log(census)
//LESSON: THE SWITCH STATEMENT//
// const language = 'chinese';
// const language = 'spanish';
// const language = 'english';
// const language = 'hindi';
// const language = 'arabic';
let language = 'default';
switch (language) {
case 'chinese':
console.log('MOST number of native speakers! 🏆');
break;
case 'spanish':
console.log('2nd place in number of native speakers 🥈');
break;
case 'english':
console.log('3rd place 🥉');
break;
case 'hindi':
console.log('Number 4');
break;
case 'arabic':
console.log('5th most spoken language');
break;
default:
console.log('Great language too 🐱💻');
break;
}
*/
//LESSON; THE CONDITIONAL (TERNARY) OPERATOR//
| true |
fb07b5567abac0d46ead0c2c894b5358c37edc6b
|
JavaScript
|
edbertsherlo/react-app
|
/src/features/signup/slice.js
|
UTF-8
| 2,905 | 2.53125 | 3 |
[] |
no_license
|
import { createSlice } from '@reduxjs/toolkit';
import * as singupAPI from "./api";
import { submitSigninSuccess, submitSigninFailed } from "../signin/slice";
export const signupSlice = createSlice({
name: 'signup',
initialState: {
form: {
first_name: "",
last_name: "",
email: "",
password: "",
confirm_password: "",
},
errors: [],
loading: false,
},
reducers: {
fieldValueUpdated: (state, { payload }) => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
if(payload.field === 'email') {
state.form.username = payload.value;
}
state.form[payload.field] = payload.value;
},
submitSignup: (state) => {
state.loading = true;
},
submitSignupSuccess: (state) => {
state.loading = false;
},
submitSignupFailed: (state, { payload }) => {
state.loading = false;
state.errors = payload;
},
},
});
signupSlice.actions.submitButtonClicked = () => async (dispatch, getState) => {
dispatch(submitSignup())
const form = getState().signup.form;
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const errors = []
if (!(form.username && re.test(form.username))) {
errors.push("email_error")
}
if (!form.first_name) {
errors.push("first_name_error")
}
if (!form.last_name) {
errors.push("last_name_error")
}
if (!form.password) {
errors.push("password_error")
}
if (!form.confirm_password || form.password !== form.confirm_password) {
errors.push("confirm_password_error")
}
if (errors.length > 0) {
dispatch(submitSignupFailed(errors));
} else {
const response = await singupAPI.signupForm(form);
if (response && response.status) {
localStorage.setItem("idToken", response.idToken)
dispatch(submitSigninSuccess(response.idToken));
dispatch(submitSignupSuccess());
} else {
localStorage.removeItem("idToken")
const errors = (response && response.data && Object.keys(response.data)) || [];
dispatch(submitSigninFailed(errors));
dispatch(submitSignupFailed(errors));
}
}
};
export const { fieldValueUpdated, submitSignup, submitSignupSuccess, submitSignupFailed, submitButtonClicked } = signupSlice.actions;
export default signupSlice.reducer;
| true |
959420f6717cd6e15f95f5a30add483d51d67842
|
JavaScript
|
vardandanielyan/node-js
|
/src/utils/forecast.js
|
UTF-8
| 825 | 2.734375 | 3 |
[] |
no_license
|
const request = require('request')
const forecast = (latitude, longitude ,callback) => {
const url = 'http://api.weatherstack.com/current?access_key=ca5ab61f6ab7d86c927c6c5d657b8b5f&query='+longitude+','+latitude;
request({url, json: true},(error, { body } ) => {
if (error)
{
callback('Unable to connect to forecast services',undefined)
}else if(body.error){
callback('Unable to find forecast',undefined)
}else{
const temperature = body.current.temperature;
const rainChance = body.current.precip;
const humidity = body.current.humidity;
callback(undefined, {
temperature: temperature,
rainChance: rainChance,
humidity: humidity
})
}
})
}
module.exports = forecast;
| true |
60e85069d38a1b724ca34eda70153c324ccda544
|
JavaScript
|
HenriPablo/FlightLogLaravel
|
/resources/assets/js/utils/RolesUtils.js
|
UTF-8
| 628 | 3 | 3 |
[] |
no_license
|
export { filterPersons, assignPersonsToAss }
/** START LOAD PEOPLE */
let filterPersons = (type, persons) => {
var x =[];
for( let i = 0; i < persons.length; i++ ){
if( persons[i]["roles"].includes( type ))
{
x.push( persons[i]);
}
}
return x;
};
let assignPersonsToAss = (role, ass, persons, nk) => {
for (let i = 0; i < ass.length; i++) {
if (ass[i].assignmentKey === nk)
{
ass[i].assignedPersons = persons;
ass[i].assignedRole = role;
}
}
//console.log("ass in assignPersonsToAss: ", ass);
return ass;
};
| true |
5cad6f4ca8366577e25d933fcf2b858e0a5c2a78
|
JavaScript
|
Liza102021/JS1
|
/JS1/skript.js
|
UTF-8
| 757 | 3.546875 | 4 |
[] |
no_license
|
console.log("Задание 1");
var i;
for (i=0; i<=10; i++){
if (i%2==0)
console.log(i + " ");
}
var i, sum;
console.log("Задание 2")
i=1;
sum=0;
while(sum<10){
if(i%2==0){
console.log(i);
sum++;
}
i++;
}
var userPass = '';
var currentPass = '.';
console.log("Задание 3")
do {
userPass = prompt("Введите пароль");
}
while (userPass != currentPass);
console.log("Вы авторизованы");
console.log("Задание 4");
var a;
for (a=0; a<=10; a++){
if (a%2==0)
console.log(a + " ");
}
console.log("Задание 5")
var c =1
let q = prompt("Введите число:");
do {
console.log("*");
c++;
} while (c<=q);
| true |
83dfd4b9b520fba419c8fc9ba43195988f2c50df
|
JavaScript
|
JamesFThomas/Github-Finder
|
/src/context/alert/AlertState.js
|
UTF-8
| 1,095 | 2.6875 | 3 |
[] |
no_license
|
import React, { useReducer } from 'react';
import AlertContext from './alertContext';
import AlertReducer from './alertReducer';
import {
SET_ALERT,
REMOVE_ALERT
} from '../types'
const AlertState = (props) => {
// create object to represent initial state of application
const initialState = null
// initialize useReducer() hook with the state object and dispatch() function for conditional updating
const [state, dispatch] = useReducer(AlertReducer, initialState);
// Function setAlert => will alert users to enter text for search query
const setAlert = (msg, type) =>{
// will send msg && type to reducer function
dispatch({
type: SET_ALERT,
payload: { msg, type }
})
// will send message to reducer to remove alert after 5 seconds
setTimeout(()=> dispatch({ type: REMOVE_ALERT }), 5000)
}
// makes state available to entire application
return (
<AlertContext.Provider
value={{
alert: state,
setAlert
}}
>
{props.children}
</AlertContext.Provider>
);
};
export default AlertState;
| true |
fc46de20b479264954513f5765d852c5d2763e11
|
JavaScript
|
LightKingS/Grupo-dos-engra-adinho
|
/Calculadora.js
|
UTF-8
| 300 | 3.171875 | 3 |
[] |
no_license
|
var prompt = require('prompt-sync')()
let a = Number(prompt('Digite um número: '))
let b = Number(prompt('Digite outro número: '))
function sum(a, b){
return a + b;
}
function sub(a, b) {
return a - b;
}
function mult(x, y){
return x * y;
}
function div(a, b){
return a / b
}
| true |
f2ecd6d12ba98680ae642cbf4174fecdf4ea7da6
|
JavaScript
|
sachinrmore/javascript-samples
|
/unit-tests/matcher.spec.js
|
UTF-8
| 925 | 3.171875 | 3 |
[] |
no_license
|
describe('Test suite', function(){
it('toBe matcher works', function(){
let a = 10;
let b = 10;
expect(a).toBe(b);
expect(a).not.toBe(null);
expect(a).not.toBeNull();
})
it("should work for objects", function() {
var foo = {
a: 12,
b: 34
};
var bar = {
a: 12,
b: 34
};
expect(foo).toEqual(bar);
});
it("The 'toBeDefined' matcher compares against `undefined`", function() {
var a = {
foo: "foo"
};
expect(a.foo).toBeDefined();
expect(a.bar).not.toBeDefined();
expect(a.foo).not.toBeUndefined();
});
it("The matcher is for boolean casting testing", function() {
var a = false, foo = "foo";
expect(foo).toBeTruthy();
expect(a).toBeFalsy();
});
})
//Other matcher
// toContain(), toBeLessThan(), toBeGreaterThan(), toThrow(), toThrowError()
| true |
b4960b7b7f2e08fe9e21eb19e279b64e5fdf1826
|
JavaScript
|
Felanrod/COMP2112-Lab4
|
/js/main.js
|
UTF-8
| 2,414 | 3.0625 | 3 |
[] |
no_license
|
/* eslint line-break-style: 0, comma-dangle: 0 */
const paraNewLine = `\n\n`;
let emails;
let init = false;
// Named my local storage key lab4Emails3095 so it would be unique,
// 3095 is the last 4 digits of my studnet number
// Checks if there is a local copy of emails if not then creates one
if (!localStorage.getItem('lab4Emails3095')) {
console.log(`Emails don't exist in Local Storage`);
fetch('https://my.api.mockaroo.com/email.json?key=6e4ecfc0')
.then((response) => response.json())
.then((data) => {
localStorage.setItem('lab4Emails3095', JSON.stringify(data));
console.log(`Saved emails to Local Storage`);
renderEmails();
});
} else {
renderEmails();
}
function renderEmails(emails) {
const list = document.querySelector('#list');
// Initializes the emails by parsing the string saved in local storage
// Inside conditional so it doesn't overwrite after emails have been selected
if (!init) {
emails = JSON.parse(localStorage.getItem('lab4Emails3095'));
init = true;
}
const HtmlSnippet = emails.map((email, index) => `
<div data-index=${index} class="email-item pure-g ${email.selected ? 'email-item-selected' : ''}">
<div class="pure-u">
<img width="64" height="64" alt="${email.name}'s avatar" class="email-avatar" src="${email.pic}">
</div>
<div class="pure-u-3-4">
<h5 class="email-name">${email.name}</h5>
<h4 class="email-subject">${email.subject}</h4>
<p class="email-desc">
${email.body.slice(0, (email.body.indexOf(paraNewLine)))}
</p>
</div>
</div>`
).join('');
list.innerHTML = HtmlSnippet;
// Grab all the newly rendered emails into an array
const emailList = [...document.querySelectorAll('.email-item')];
emailList.map(email => {
email.addEventListener('click', function() {
// When an email is clicked make all emails not selected
emails.forEach(element => {
element.selected = false;
});
// Make the clicked email selected
emails[this.dataset.index].selected = true;
// Re-render the emails
renderEmails(emails);
})
})
}
| true |
3d9620510ca9e52f007dd76f0203e37ca7e10fed
|
JavaScript
|
cyborgspider/ryric
|
/build/js/scripts.js
|
UTF-8
| 905 | 3.359375 | 3 |
[] |
no_license
|
(function(){
var songList = [];
//This function returns a string (such as 3:30) into milliseconds
function minutesToMilli(time){
return (Number(time.split(':')[0])*60+Number(time.split(':')[1]))*1000;
}
function displayLyrics(arr, index){
console.log(arr[0].lyrics[index]);
console.log(arr[0].timestamp[index]);
}
function generateTimestamps(arr){
return arr[0].timestamp.map(function(timestamp){
return minutesToMilli(timestamp);
});
}
function createTimeouts(index, timestamp){
setTimeout(function(){console.log(index);}, timestamp);
}
function init(){
// var len = songList[0].lyrics.length,
// i = 0;
// while (i < len){
// createTimeouts(songList[0].lyrics[i], minutesToMilli(songList[0].timestamp[i]));
// i++;
// }
$.ajax({
url:'json/songs.js',
})
.done(function(data){
console.log(data);
})
.fail(function(){
console.log('failed');
});
}
init();
})();
| true |
aaaf6c4af07941b78f05492195b584e380da784b
|
JavaScript
|
Domi236/miniProjects
|
/menuBar.js
|
UTF-8
| 226 | 2.875 | 3 |
[] |
no_license
|
var list = document.querySelectorAll('.toggle-me');
list.forEach(function(el) {
el.onclick = function() {
list.forEach(function(el) {
el.classList.remove('active');
});
el.classList.add('active');
}
});
| true |
3119391ef49ea59e4eac8256d14741a958b76108
|
JavaScript
|
ashenbrownfox/practiceapp
|
/src/Form.js
|
UTF-8
| 1,198 | 2.765625 | 3 |
[] |
no_license
|
import React, { Component,useState, useEffect } from "react";
class Form extends Component {
constructor(){
super()
this.state = {
firstName: "",
lastName: "",
age: 0,
gender: "",
destination: "",
dietaryRestrictions: []
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event){
const {name, value} = event.target
this.setState({
[name]: value
})
}
render(){
return (
<form>
<input type="text" name="firstName" placeholder="First Name" onChange={this.handleChange} value={this.state.firstName} />
<br/>
<input type="text" name="lastName" placeholder="Last Name" onChange={this.handleChange} value={this.state.lastName} />
<br/>
<input type="text" name="age" placeholder="Age" placeholder="Last Name" onChange={this.handleChange} value={this.state.age}/>
<button>Submit</button>
<p>Your name {this.state.firstName} {this.state.lastName}</p>
<p>Your age: {this.state.age}</p>
</form>
)
}
}
export default Form;
| true |
c631995cb7ef51766e0f8a66e1a8cc394558cf4f
|
JavaScript
|
marcoavfcc01121979/js-oo
|
/Conta/ContaCorrente.js
|
UTF-8
| 458 | 2.890625 | 3 |
[] |
no_license
|
import Cliente from "./Cliente.js";
import Conta from "./Conta.js";
class ContaCorrente extends Conta{
static numerosDeConta = 0;
constructor(cliente, agencia) {
super(0, cliente, agencia)
ContaCorrente.numerosDeConta += 1;
}
sacar(valor){
let taxa = 1.1;
const valorSacado = taxa * valor
if(this._saldo >= valorSacado) {
this._saldo -= valorSacado;
return valorSacado;
}
}
}
export default ContaCorrente;
| true |
7c474626e1facfe897eac906e094bb94dda53e2c
|
JavaScript
|
javiarias/UAJ-Final
|
/js/individual.js
|
UTF-8
| 7,745 | 2.796875 | 3 |
[] |
no_license
|
import * as Common from "./common.mjs";
var currentPlayer = {};
var pageSize = 15;
var page = 0;
var maxPages = 0;
var currentHistory = [];
document.getElementById("getData").onclick = getPlayerData;
document.getElementById("left").onclick = left;
document.getElementById("right").onclick = right;
document.getElementById("left").disabled = true;
document.getElementById("right").disabled = true;
document.getElementById("currentPage").innerHTML = "0 / 0";
document.getElementById("searchID").addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.key === "Enter") {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("getData").click();
}
});
function is_numeric(str){
return /^\d+$/.test(str);
}
function getPlayerData(e)
{
var id = document.getElementById("searchID").value;
var url = "http://localhost:25565/accounts/by-nick/" + id;
$.get(url, function(data, status){
currentPlayer = data.currentPlayer;
if(currentPlayer.history !== undefined)
currentHistory = currentPlayer.history.concat(currentPlayer.pending);
else
currentHistory = currentPlayer.pending;
page = 0;
maxPages = Math.trunc(currentHistory.length / pageSize);
refreshTable();
refreshPlayerTable();
Common.refreshCharacterTable(document.getElementById("InfoPlayerCharacters"), currentPlayer.characterInfo, currentPlayer.totalGames);
getCharacterStatistics();
}).done(function() {
Common.informError(document.getElementById("PlayerError"), "");
document.getElementById("pageContent").hidden = false;
}).fail(function() {
Common.informError(document.getElementById("PlayerError"), "Player not found");
document.getElementById("pageContent").hidden = true;
document.getElementById("table").innerHTML = "";
document.getElementById("InfoPlayerTable").innerHTML = "";
document.getElementById("InfoPlayerCharacters").innerHTML = "";
});
}
function left(e)
{
page--;
refreshTable();
}
function right(e)
{
page++;
refreshTable();
}
function refreshPlayerTable(){
document.getElementById("InfoPlayerTable").innerHTML = "";
var time = (currentPlayer.totalTime / currentPlayer.totalGames) * 45.0;
var mins = ('00' + Math.trunc(time / 60.0)).slice(-2);
var secs = ('00' + Math.trunc(time % 60.0)).slice(-2);
var creation = new Date(currentPlayer.creation);
var lastGame = new Date(currentPlayer.lastGame);
var str = "<tr>"
str += "<td>" + currentPlayer.nick + "</td>";
str += "<td>" + currentPlayer.rating + "</td>";
str += "<td>" + creation.toLocaleDateString() + "</td>";
str += "<td>" + Common.timeSince(lastGame) + " ago </td>";
str += "<td>" + currentPlayer.totalGames + "</td>";
var aux = currentPlayer.wins + " / " + currentPlayer.draws + " / " + currentPlayer.losses + "<br/>";
aux += ((currentPlayer.wins / currentPlayer.totalGames) * 100).toFixed(2) + "% / " + ((currentPlayer.draws / currentPlayer.totalGames) * 100).toFixed(2) + "% / " + ((currentPlayer.losses / currentPlayer.totalGames) * 100).toFixed(2) + "%";
str += "<td>" + aux + "</td>";
str += "<td>" + mins + ":" + secs + "</td>";
str += "</tr>";
document.getElementById("InfoPlayerTable").innerHTML += str;
}
function refreshTable()
{
document.getElementById("right").disabled = page >= maxPages;
document.getElementById("left").disabled = page == 0;
document.getElementById("table").innerHTML = "";
for (let i = (currentHistory.length - 1) - (page * pageSize); i >= 0 && i > (currentHistory.length - 1) - ((page + 1) * pageSize); i--) {
const element = currentHistory[i];
var avg = 0;
var time = 0;
element.rounds.forEach(r => {
avg += r.result;
time += r.time;
});
avg = avg / element.rounds.length;
var result = "";
if(avg > 0.5) result = "Victory";
else if (avg < 0.5) result = "Loss";
else result = "Draw";
time = (time * 45.0);
var mins = ('00' + Math.trunc(time / 60.0)).slice(-2);
var secs = ('00' + Math.trunc(time % 60.0)).slice(-2);
var table = document.getElementById("table");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
var cell7 = row.insertCell(6);
switch(result){
case "Victory":
row.style.backgroundColor = Common.winColor;
break;
case "Loss":
row.style.backgroundColor = Common.lossColor;
break;
case "Draw":
row.style.backgroundColor = Common.drawColor;
break;
}
var imgUser = document.createElement('img');
var imgRival = document.createElement('img');
imgUser.src = '/images/' + element.playerChar + '.png';
imgRival.src = '/images/' + element.rivalChar + '.png';
imgUser.style="width:48px;height:48px;"
imgRival.style="width:48px;height:48px;"
cell1.appendChild(imgUser);
cell2.innerHTML = result + "<br/>";
element.rounds.forEach(round => {
var imgUser = document.createElement('img');
imgUser.style="width:14px;height:23px;"
if(round.result > 0.5) imgUser.src = '/images/resultWin.png';
else if (round.result < 0.5) imgUser.src = '/images/resultLoss.png';
else round.result = imgUser.src = '/images/resultDraw.png';
cell2.appendChild(imgUser);
cell2.innerHTML += " ";
});
cell3.innerHTML = mins + ":" + secs;
var dmgToShots = 0;
if(element.shotsFired > 0) dmgToShots = (element.dmgDealt / element.shotsFired);
cell4.innerHTML = element.accuracy.toFixed(2) + "%";
cell5.innerHTML = dmgToShots.toFixed(2) + " HP";
cell6.innerHTML = element.rivalNick;
cell7.appendChild(imgRival);
}
document.getElementById("currentPage").innerHTML = (page + 1) + " / " + (maxPages + 1);
}
function refreshWinrate(wr, char1, char2){
document.getElementById("right").disabled = page >= maxPages;
document.getElementById("left").disabled = page == 0;
document.getElementById("CharacterWinrate").innerHTML = "";
var table = document.getElementById("CharacterWinrate");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.appendChild(Common.checkImage(char1));
cell3.appendChild(Common.checkImage(char2));
if(wr != -1)
cell2.innerHTML = wr + "%";
else
cell2.innerHTML = "No data";
document.getElementById("currentPage").innerHTML = (page + 1) + " / " + (maxPages + 1);
}
function getCharacterStatistics(){
var char1 = document.getElementById("char1");
var char2 = document.getElementById("char2");
for (var x in Common.charactersNames) {
char1.options[char1.options.length] = new Option(x, x);
}
for (var x in Common.charactersNames) {
char2.options[char2.options.length] = new Option(x, x);
}
char2.value = Common.next(char1.value);
char1.onchange = function() {
refreshWinrate(getCharacterWinrate(char1.value, char2.value), char1.value, char2.value);
}
char2.onchange = function() {
refreshWinrate(getCharacterWinrate(char1.value, char2.value), char1.value, char2.value);
}
refreshWinrate(getCharacterWinrate(char1.value, char2.value), char1.value, char2.value);
}
function getCharacterWinrate(char1, char2){
var character = currentPlayer.characterInfo[char1];
var against = character[char2];
if(against === undefined)
return -1;
return Math.round(10000*against.wins / against.totalGames)/100;
}
| true |
431ddc5c66d37d84f649c44ed656d395a4d97bfe
|
JavaScript
|
T-G/ES6
|
/arrays/swapArrayWithSpread.js
|
UTF-8
| 1,946 | 3.9375 | 4 |
[] |
no_license
|
const breakfastMenuIdeas = ["Buckwheat Pancakes"];
const dinnerMenuIdeas = ["Glazed Salmon", "Meatloaf", "American Cheeseburger"];
// const allMenuIdeas = ["Harvest Salad", "Southern Fried Chicken"];
/* To add breakfastMenuIdeas in the begining of allMenuIdeas */
//allMenuIdeas.pop(breakfastMenuIdeas)
/* To add breakfastMenuIdeas at the end of allMenuIdeas */
//allMenuIdeas.push(breakfastMenuIdeas)
/* the problem with .pop and .push is that they mutate the original array, and you
shouldn't mutate an array*/
/* more intuitive way to add items in an array is by using the SPREAD operator
we need to put the array items in a new array like:
const otherMenuIdeas = [...allMenuIdeas]
it will create a shallow clone of allMenuIdeas array
const otherMenuIdeas = [...breakfastMenuIdeas, ...allMenuIdeas];
*/
const allMenuIdeas = [
...breakfastMenuIdeas,
"Harvest Salad",
"Southern Fried Chicken",
...dinnerMenuIdeas
];
console.log(`Allmenu Ideas: ${allMenuIdeas}`);
/* you cannot update an array using the spread operator,
To update an array item we can use slice() array method
slice() operates based on indexed of an array (startIndex, endingIndex)
findIndex() method can find the elements positional index integer and returns it
example below:
*/
// find the index position of "Harvest Salad" and replace it with "Garden Salad"
const saladIndex = allMenuIdeas.findIndex( idea => idea === "Harvest Salad");
const finalMenuIdeasAfterPerformingUpdate = [
...allMenuIdeas.slice(0, saladIndex),
"Garden Salad",
...allMenuIdeas.slice(saladIndex + 1)
];
console.log(finalMenuIdeasAfterPerformingUpdate);
/*
DELETING an array item
*/
const meatLoafIndex = allMenuIdeas.findIndex( idea => idea === "Meatloaf");
const finalMenuIdeasAfterPerformingDelete = [
...allMenuIdeas.slice(0, meatLoafIndex),
...allMenuIdeas.slice(meatLoafIndex + 1)
];
console.log(finalMenuIdeasAfterPerformingDelete);
| true |
eebbb025a6ef2b816d1016b8f9772d5a5b5dea0f
|
JavaScript
|
Solomon-m/mylearning
|
/Asynchronous programming-End of the loop/07-Using the map method with Observable.js
|
UTF-8
| 1,833 | 3.625 | 4 |
[] |
no_license
|
// When we map over an array we will get an array
// When we filter or concatAll on an array we will get array.
// In case of observable, if we map over an Observable we will be getting Observable.
var Observable = Rx.Observable;
var button = document.getElementById('button');
// In case of forEach in Observable it gives 3 callback function onNext,onError and onCompleted.
var clicks = Observable.fromEvent(button, 'click');
// points is an Observable.
// when we map over an observable we get observable. When we filter observable we get observable and soon on and so forth.
var points = clicks.map(function(e){
return {x:e.clientX,y:e.clientY};
})
/*
- When we do forEach over observable, under the hood it calls addEventListener.
- Observable are lazy. if we comment out the below code it will not call addEventListener
for button unless we call forEach on that observable.
- This following code ( Observable.fromEvent(button, 'click') ) promises that when you call forEach on
it, it will call addEventListener
- When we map over clicks it creates Observable (points). Again when we map over points observable it
maps over underlying observable (click) and then when data arrives it transforms in map's projection
function.
*/
var subscription =
points.forEach(
function onNext(e) {
// If there is any element in observable collection onNext will execute.
console.log("onNext function::", e);
// Here we are unsubsribing from an event.
// removing listener from click event.
subscription.dispose();
},
function onError(error) {
//If any asychronous error that will be piped here.
console.error("onError:", error);
},
function onCompleted() {
console.log("onCompleted: arguments:", arguments);
});
| true |
3fb848a5af2e839c67855e9fd242313d1f6a3624
|
JavaScript
|
zjj131415/Marketing
|
/html/t5/js/veImage.js
|
UTF-8
| 7,995 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
;(function (factory) {
/* CommonJS module. */
if (typeof module === "object" && typeof module.exports === "object") {
module.exports = factory(window);
/* AMD module. */
} else if (typeof define === "function" && define.amd) {
define(factory(window));
/* Browser globals. */
} else {
factory(window);
}
}(function(global, undefined) {
"use strict";
var veImagePrototype = veImage.prototype;
//默认参数
var defaults = {
canvas: null,//画布
image: null,//图片
relativeWidth: 750 //相对宽度,裁剪的时候可计算比率
};
//绑定的事件 目前只适用于webkit内核浏览器
var events = {start:'touchstart', move:'touchmove', end:'touchend'};
/**
* 简单的数组合并
*/
function extend(source, target) {
for(var key in source) {
if(source.hasOwnProperty(key))
target[key] = source[key];
}
return target;
}
function veImage(opts) {
if(!opts.canvas || !opts.image) {
throw new Error('请传入正确的画布或图片');
}
this.opts = extend(opts, defaults); //默认参数与传入参数合并
this.canvas = this.opts.canvas;//画布
this.size = this.canvas.getBoundingClientRect();//画布的尺寸参数
this.context = this.canvas.getContext('2d');//画布上下文
this.image = opts.image;//图片
//设置画布的宽高
this.canvas.width = this.size.width;
this.canvas.height = this.size.height;
//将图片用合适的尺寸放入到画布中
var rateWidth = this.canvas.width / this.image.width,//画布与图片的宽比
rateHeight = this.canvas.height / this.image.height,//画布与图片的高比
rate = rateWidth > rateHeight ? rateHeight : rateWidth;//取小的比率
//设置目标宽高 也就是缩放后的宽高
this.dWidth = this.image.width * rate;
this.dHeight = this.image.height * rate;
//将画布的中心点 作为起始坐标 缩放的时候会从中间开始放大,效果更佳,图片也能画在正中间
this.origin = {
x: Math.floor(this.canvas.width / 2),
y: Math.floor(this.canvas.height / 2)
};
this._draw();//画图
this._bind(); //绑定手指事件
}
/**
* 记录手指的坐标
* @param touches
* @private
*/
function _finger(touches) {
var coordinate = [],
len = touches.length;
for(var i=0; i<len; i++) {//TouchList类型 不能用forEach
coordinate.push({x:touches[i].clientX, y:touches[i].clientY})
}
return coordinate;
}
/**
* 绑定开始事件
*/
veImagePrototype.startEvt = function(e) {
this.start = _finger(e.touches);//记录开始的坐标
this._mode(e.touches);//模式初始化
};
/**
* 绑定手指移动事件
*/
veImagePrototype.moveEvt = function(e) {
e.preventDefault();//禁止滚动
var fingers = _finger(e.touches);//记录移动中的坐标
//不能仅仅通过手指数量来判断 因为当缩放后,移除手指的时候,会出现一个手指还停留在页面上,导致位移
if(this.mode == 1) {//位移
this._translate(fingers);
}else if(this.mode == 2) {//缩放
this._zoom(fingers);
}
//将start的坐标复为移动中的坐标 时时计算偏移值,不然会变得非常大,图片在移动中会飞出画面
this.start = fingers;
};
/**
* 模式判断
*/
veImagePrototype._mode = function(fingers) {
if(fingers.length == 1) {
this.mode = 1;//位移模式
}else if(fingers.length > 1) {
this.mode = 2;//缩放模式
}
};
/**
* 位移
*/
veImagePrototype._translate = function(fingers) {
//计算手指的位移
this._draw(
fingers[0].x - this.start[0].x,
fingers[0].y - this.start[0].y
);
};
/**
* 缩放
*/
veImagePrototype._zoom = function(fingers) {
//上一次手指两个X轴和Y轴之间的距离
var lastOffset = {
x : Math.abs(this.start[0].x - this.start[1].x),
y : Math.abs(this.start[0].y - this.start[1].y)
};
if(lastOffset.x == 0 || lastOffset.y == 0) {//防止分母是0
return;
}
//缩放不需要坐标轴偏移 但计算缩放值 需要偏移值
//缩放率分母是上一次手指,分子是当前手指两个X轴和Y轴之间的距离
this._draw(
0, 0,
Math.abs(fingers[0].x - fingers[1].x) / lastOffset.x,
Math.abs(fingers[0].y - fingers[1].y) / lastOffset.y
);
};
/**
* 绑定结束事件
*/
veImagePrototype.endEvt = function(e) {
};
/**
* 裁剪
* @param w 裁剪的宽度
* @param h 裁剪的高度
* @param x 开始裁剪的X轴坐标
* @param y 开始裁剪的Y轴坐标
* @returns {string}
*/
veImagePrototype.crop = function(w, h, x, y) {
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
rate = this.canvas.width / this.opts.relativeWidth;//当前画布的宽度与设置的相对宽度 计算比率
x *= rate;
y *= rate;
canvas.width = w*rate;
canvas.height = h*rate;
context.drawImage(
this.canvas,
x, y, canvas.width, canvas.height,
0, 0, canvas.width, canvas.height
);
return canvas.toDataURL("image/png", 1);
};
/**
* 画图
* @param dx X轴偏移量
* @param dy Y轴偏移量
* @param zoomWidth 宽度缩放比
* @param zoomHeight 高度缩放比
* @private
*/
veImagePrototype._draw = function(dx, dy, zoomWidth, zoomHeight) {
//清空画布 擦除之前绘制的所有内容 不清空的话会显示各个步骤的画布
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.save();//保存状态
//防止缩放到0值,导致图片消失
if(zoomHeight == 0 || zoomWidth == 0){
return ;
}
//计算偏移
this.origin.x += dx || 0;//计算X轴坐标
this.origin.y += dy || 0;//计算Y轴坐标
this.context.translate(this.origin.x, this.origin.y);//位移
//计算缩放
zoomWidth = zoomWidth || 1;
zoomHeight = zoomHeight || 1;
var zoom = zoomWidth > zoomHeight ? zoomWidth : zoomHeight;//统一按一个比例做缩放
this.dWidth *= zoom;//宽度缩放
this.dHeight *= zoom;//高度缩放
//画图
this.context.drawImage(
this.image,
0, 0, this.image.width, this.image.height,
-this.dWidth / 2, -this.dHeight / 2, this.dWidth, this.dHeight);//目标画布的中心点
//还原到上一个状态 也就是空画布的时候
this.context.restore();
};
/**
* 绑定事件
*/
veImagePrototype._bind = function() {
this.canvas.addEventListener(events.start, this);
this.canvas.addEventListener(events.move, this);
this.canvas.addEventListener(events.end, this);
};
/**
* 高级的绑定方法
*/
veImagePrototype.handleEvent = function(e) {
switch (e.type) {
case events.start:
this.startEvt(e);
break;
case events.move:
this.moveEvt(e);
break;
case events.end:
this.endEvt(e);
break;
}
};
global.veImage = veImage;
return veImage;
}));
| true |
e4dd352c81ff75098121d556da41c6e81acd7ec9
|
JavaScript
|
philmjc/GreenMath
|
/trialCode/trial.js
|
UTF-8
| 713 | 2.640625 | 3 |
[] |
no_license
|
user = {
curr:1,
courses : [
{id:1},
{id:2}
]
};
var updateUser = function(obj) {
user = Object.assign(user, obj);
};
function gp(id) {
if (!user.courses) return false;
if (!id && user.currIndex) return user.courses[user.currIndex].prog;
var ids = user.courses.map(function(el) {return el.id;});
var i = id ? id : user.curr;
var index = ids.indexOf(i);
if (index < 0) return false;
updateUser({currIndex:index});
if (!user.courses[index].prog) user.courses[index].prog = {};
return user.courses[index].prog;
}
function up(obj) {
var pro = gp();
console.log(pro);
Object.assign(pro, obj);
}
up({mark:1, scores:[true,true]});
console.log(user.courses[user.currIndex].prog);
| true |
e58e842159605f3abd999786179169bd36b2bc1b
|
JavaScript
|
agasca/arrays
|
/matriz.js
|
UTF-8
| 759 | 3.734375 | 4 |
[] |
no_license
|
function explosion(){
alert("Boom!");
document.write("<h1>Mala elección</h1>");
}
var x, y;
var textos = ["Cesped","Bomba"];
var campo = [ // 1 = bomba
[1,0,0],
[0,1,0],
[1,1,1] ]
alert("Cuidado!!!\n" + "Estas en un campo minado");
x = parseInt(prompt("Ingresa un valor entre 0 y 2 para la posición en el eje X"));
y = parseInt(prompt("Ingresa un valor entre 0 y 2 para la posición en el eje Y"));
//valida que el usuario no ingrese undefined
if( x < 0 || x > 2 || y < 0 || y > 2
|| (x >= 0 && typeof campo[x][y] == "undefined")
|| (isNaN(x) || isNaN(y))
){
alert("Fuera del campo");
explosion();
}else{
//permite encontrar el resultado sin ifs
var posicion = campo[x][y];
document.write (textos[posicion]);
}
| true |
f578b59c8f27f5307ced5458e7e641dbea7d3207
|
JavaScript
|
Sheryleen/knex-calendar-project
|
/controllers/appointments.js
|
UTF-8
| 1,103 | 2.59375 | 3 |
[] |
no_license
|
const knex = require("../db/knex");
exports.getAllAppointments = (req, res) => {
knex //instance of knex
.select() //select all
.table("appointments") //from appointments
.then(appointments => res.json(appointments)); //getting all appts back
};
exports.getOneAppointment = (req, res) => {
knex("appointments")
.select()
.then(appointments => res.json(appointments));
};
exports.addOneAppointment = (req, res) => {
knex("appointments")
.insert({
...req.body //all column data in row
})
.returning("*")
.then(appointments => res.json(appointments));
};
exports.updateOneAppointment = (req, res) => {
knex("appointments")
.update({
...req.body, //all column data in row
updated_at: new Date()
})
.where("id", req.params.id)
.returning("*")
.then(updatedAppointment => res.json(updatedAppointment));
};
exports.removeOneAppointment = (req, res) => {
knex("appointments")
.del()
.where("id", req.params.id)
.returning("*")
.then(newAppointment => res.json(newAppointment)); //returns removed appt
};
| true |
b5af129124eb61eca3edb039d40fe0ece7ada65e
|
JavaScript
|
taikiken/practice_react_redux
|
/dev/babels/src/ex1/ListTypes.js
|
UTF-8
| 1,778 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
/**
* Copyright (c) 2011-2017 inazumatv.com, inc.
* @author (at)taikiken / http://inazumatv.com
* @date 2017/04/27 - 14:31
*
* Distributed under the terms of the MIT license.
* http://www.opensource.org/licenses/mit-license.html
*
* This notice shall be included in all copies or substantial portions of the Software.
*
*/
/**
* redux reducer
* - type set
* - CLICK
* - createStore(ListTypes.update)
*/
export default class ListTypes {
/**
* button click
* @event CLICK
* @returns {string} ListTypesClick
*/
static get CLICK() {
return 'ListTypesClick';
}
/**
* Ul default state
* - id - `redux-ul`
* - mode - `ex1`
* - list - []
* @returns {{id: string, mode: string, list: Array}} Ul default state を返します
*/
static get defaultState() {
return {
id: 'redux-ul',
mode: 'ex1',
list: [],
};
}
/**
* redux.creatStore 対象 method
* - action.type: {@link ListTypes.CLICK} - list と action.list を結合します
* - action.type: ListTypes.CLICK 以外 - {@link ListTypes.defaultState} を返します
* @param {Object} state 状態
* @param {Object} action update 状態
* @returns {*} 更新後状態
*/
static update(state = {}, action) {
const clone = Object.assign({}, ListTypes.defaultState);
switch (action.type) {
// for button click
case ListTypes.CLICK: {
console.log(`ListTypes.update ${action.type}`, state, action, clone);
// const cloneButton = clone;
clone.list = action.list.concat(clone.list);
return clone;
}
// for @@redux/INIT
default: {
console.log(`ListTypes.update default ${action.type}`, state, action, clone);
return clone;
}
}
}
}
| true |
b80d68e74d51bbd39cd770f68701cfb17d125903
|
JavaScript
|
SACHIN5SOS/Weather-App
|
/weatherapp-asynjs/WeatherApp-node/app-promise.js
|
UTF-8
| 1,122 | 2.671875 | 3 |
[] |
no_license
|
const axios = require('axios');
const yargs = require('yargs');
const argv= yargs
.options({
a: {
demand : true,
alias: 'address',
describe: 'Adress to fetch wether to',
string: true
}
})
.help()
.alias('help','h')
.argv;
var encodedAddress= encodeURIComponent(argv.address);
var geocodeUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='+encodedAddress;
axios.get(geocodeUrl).then((response)=>{
if(response.data.status==='ZERO_RESULTS'){
throw new Error('Unable to track this location');
}
// console.log(response.data);
var lat=response.data.results[0].geometry.location.lat;
var long=response.data.results[0].geometry.location.lng;
var url = "https://api.darksky.net/forecast/ef9fea25361db109862704601da8d480/"+lat+","+long;
return axios.get(url);
}).then((response)=>{
var temperature= response.data.currently.temperature;
console.log(`Current Temp is: ${temperature}`);
}).catch((e)=>{
if(e.code==='ENOTFOUND'){
console.log('Unable to connect with servers');
}
else{
console.log('Unable to track this location');
}
});
| true |
5f19e12ae0ec63c69c88e82987050dcd9d606fdc
|
JavaScript
|
PetarSimonovic/noteApp
|
/notePad.js
|
UTF-8
| 2,099 | 3.578125 | 4 |
[] |
no_license
|
// Variables
let noteList = [];
let notePList = document.getElementById("noteListWrapper");
let addNoteButton = document.getElementById("addNoteButton");
let pageStorage = window.localStorage;
noteList = pageStorage.notes.split(',');
// event listeners
addNoteButton.addEventListener("click", addNote);
notePList.addEventListener("click", (e) => {
clickNote(e.target.id);
});
// Functions
function addNoteListToStorage() {
if(development === true){
pageStorage.setItem('notes', noteList);
}
}
function addNote() {
let text = document.getElementById("addNoteField").value;
noteList.push(text);
addNoteListToStorage();
let index = noteList.length - 1;
createListItem(text, index);
document.getElementById("addNoteField").value = "";
}
function emojifiText(message) {
let data = { text: message };
fetch("https://makers-emojify.herokuapp.com", {
method: "POST", // or 'PUT'
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
let emojifiedText = data.emojified_text;
openModal(emojifiedText);
})
.catch((error) => {
console.error("Error:", error);
});
// console.log(emojifiedText);
// return data.emojified_text;
}
function createListItem(text, index) {
let liNode = document.createElement("li");
let aNode = document.createElement("a");
let textNode = document.createTextNode(text);
aNode.appendChild(textNode);
liNode.appendChild(aNode);
notePList.appendChild(liNode);
addAttributes(aNode, index);
}
function addAttributes(aNode, index) {
aNode.href = `#${index}`;
aNode.id = `${index}`;
}
function openModal(note = "") {
let modal = document.getElementById("modalWrapper");
let para = document.getElementById("note-paragraph");
modal.style.display = "block";
para.innerHTML = note;
}
function closeModal() {
let modal = document.getElementById("modalWrapper");
modal.style.display = "none";
}
function clickNote(noteId) {
note = noteList[noteId];
note2 = emojifiText(note);
}
| true |
1ac5bab08c62759ae02b5879fd0469fb171e8ad3
|
JavaScript
|
psb/object-dance-party
|
/src/main.js
|
UTF-8
| 692 | 2.6875 | 3 |
[] |
no_license
|
$(document).ready(function(){
// This is a list of the different kinds of dancers. Right now,
// there's just one, but eventually, you'll want to add more.
var kindsOfDancers = {
BlinkyDancer: BlinkyDancer, // found in blinkyDancer.js
PoleDancer: PoleDancer, // found in otherDancers.js
ColoredDancer: ColoredDancer // found in otherDancers.js
};
// This is a list of all the dancers that have been created.
// * danceFloor.js will add to it when you click on stuff.
// * When you're writing mixins that affect existing dancers, you'll use it.
window.dancers = [];
var danceFloor = makeDanceFloor(kindsOfDancers, dancers);
setupControls(danceFloor);
});
| true |
f1a0881ee4e4b2c901a0c853c08a21de6c285b7d
|
JavaScript
|
guille615/Yasuo-Bot-Telegram
|
/index.js
|
UTF-8
| 1,440 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
const emojis = require("./emojis");
const telegramBot = require('node-telegram-bot-api');
const fs = require('fs');
const config = require('./config.json');
const token = config.telegramToken;
const api = new telegramBot(token, { polling: true });
const listaComandos = [];
const commandFiles = fs.readdirSync('./commands');
for (const file of commandFiles) {
const name = file.substring(0, file.length - 3);
listaComandos[name] = `./commands/${file}`;
}
api.listaComandos = listaComandos;
console.log('\033c');
console.log('Bot iniciado!!');
const reg = new RegExp(`^${config.prefix}`);
api.onText(reg, (msg) => {
const chatId = msg.chat.id;
const commandWithArgs = msg.text.split(' ');
const comandoWithPrefix = commandWithArgs[0];
const comandoIntroducido = comandoWithPrefix.substring(1, comandoWithPrefix.length);
const args = commandWithArgs.slice(1, commandWithArgs.length);
if (listaComandos[comandoIntroducido]) {
var comando = require(listaComandos[comandoIntroducido]);
var mensajeSplit = msg.text.split(' ');
try {
comando.execute(api, msg, args);
}
catch (error) {
api.sendMessage(chatId, `Se ha producido un error al ejecutar el comando. ${emojis.ups}`);
console.log(msg.text, error);
}
} else {
api.sendMessage(chatId, `El comando introducido no existe. ${emojis.jou}`);
}
});
| true |
1cb669f0da65ee543326d629db07a8e281ccc50f
|
JavaScript
|
jh3y/stationery-cabinet
|
/src/configurable-waves/script.js
|
UTF-8
| 2,522 | 2.828125 | 3 |
[] |
no_license
|
import { GUI } from 'https://cdn.skypack.dev/dat.gui'
const WAVES = document.querySelectorAll('.wave')
const CONFIG = [
{
speed: 30,
opacity: 0.3,
height: 12,
width: 800,
},
{
speed: 45,
opacity: 0.6,
height: 12,
width: 800,
},
{
speed: 15,
opacity: 1,
height: 6,
width: 400,
},
]
const UTILS = {
copy: () => {
const el = document.createElement('textarea')
el.value = grabCSS()
el.height = el.width = 0
document.body.appendChild(el)
el.select()
document.execCommand('copy')
document.body.removeChild(el)
alert('CSS Saved To Clipboard!')
},
}
const BG = {
value: '#543663',
}
const updateWave = index => () => {
for (const key of Object.keys(CONFIG[index])) {
WAVES[index].style.setProperty(`--${key}`, CONFIG[index][key])
}
}
WAVES.forEach((_, index) => updateWave(index)())
const grabCSS = () => `
.wave {
animation: wave calc(var(--speed, 0) * 1s) infinite linear;
background-image: url("https://assets.codepen.io/605876/wave--infinite.svg");
background-size: 50% 100%;
bottom: -5%;
height: calc(var(--height, 0) * 1vh);
left: 0;
opacity: var(--opacity);
position: absolute;
right: 0;
width: calc(var(--width, 0) * 1vw);
}
@keyframes wave {
to {
transform: translate(-50%, 0);
}
}
.wave:nth-of-type(1) {
--height: ${CONFIG[0].height};
--opacity: ${CONFIG[0].opacity};
--speed: ${CONFIG[0].speed};
--width: ${CONFIG[0].width};
}
.wave:nth-of-type(2) {
--height: ${CONFIG[1].height};
--opacity: ${CONFIG[1].opacity};
--speed: ${CONFIG[1].speed};
--width: ${CONFIG[1].width};
}
.wave:nth-of-type(3) {
--height: ${CONFIG[2].height};
--opacity: ${CONFIG[2].opacity};
--speed: ${CONFIG[2].speed};
--width: ${CONFIG[2].width};
}
`
const CONTROLLER = new GUI({
width: 300,
})
WAVES.forEach((_, index) => {
const WAVE = CONTROLLER.addFolder(`Wave ${index + 1}`)
WAVE.add(CONFIG[index], 'speed', 0.5, 100, 0.1)
.name('Speed')
.onChange(updateWave(index))
WAVE.add(CONFIG[index], 'opacity', 0.1, 1, 0.1)
.name('Opacity')
.onChange(updateWave(index))
WAVE.add(CONFIG[index], 'height', 5, 50, 1)
.name('Height')
.onChange(updateWave(index))
WAVE.add(CONFIG[index], 'width', 200, 1000, 100)
.name('Width')
.onChange(updateWave(index))
})
CONTROLLER.addColor(BG, 'value')
.name('Background Color')
.onChange(() => document.documentElement.style.setProperty('--bg', BG.value))
CONTROLLER.add(UTILS, 'copy').name('Copy CSS')
| true |