hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
40068943022d366d3825ae4f877eb1c5aca3d17b | 1,730 | js | JavaScript | RockroboAlexaZones/script.js | MeisterTR/ioB-scripts | 6127ba7671399b621d06987392eada47f283b431 | [
"MIT"
] | 7 | 2018-07-22T08:52:58.000Z | 2019-10-10T19:12:28.000Z | RockroboAlexaZones/script.js | MeisterTR/ioB-scripts | 6127ba7671399b621d06987392eada47f283b431 | [
"MIT"
] | 8 | 2019-01-02T12:45:05.000Z | 2020-05-09T18:24:50.000Z | RockroboAlexaZones/script.js | MeisterTR/ioB-scripts | 6127ba7671399b621d06987392eada47f283b431 | [
"MIT"
] | null | null | null | let msg = "";
let id = "";
subscribe({
id: "alexa2.0.History.summary",
change: "ne"
}, function(obj) {
id = getState('alexa2.0.History.serialNumber'/*serialNumber*/).val
log('Starte id '+ id)
msg = obj.newState.val;
findrooms();
});
function findrooms (){
log(msg);
let stext = '';
// find keywords
let wrongkey = msg.match(/sprich mir nach|asd/);
let key = msg.match(/sauge|sage|reinige|wische|staubsauger/);
if(!wrongkey && key){
let command = {"command":"zoned_cleanup","zone_ids": []};
let kitchen = msg.match(/küche|Küche/);
let vorrat = msg.match(/vorratsraum|speisekammer/);
let wohnzimmer = msg.match(/wohnzimmer|esszimmer/);
let flur = msg.match(/flur|diele/);
let bad = msg.match(/bad|badezimmer|gästebad|gästebadezimmer/);
if(kitchen){
stext += 'Küche';
command.zone_ids.push("Kueche");
}
if(vorrat){
stext += ', Vorratsraum ';
command.zone_ids.push("Vorrat");
}
if(wohnzimmer){
stext += ', Wohnzimmer ';
command.zone_ids.push("Wohnzimmer");
}
if(flur){
stext += ', Flur ';
command.zone_ids.push("Diele");
}
if(bad){
stext += ', Gästebadezimmer ';
command.zone_ids.push("Gaestebad");
}
//add und to the end
var n = stext.lastIndexOf(',');
let lenght
stext = stext.slice(0, n) + stext.slice(n).replace(',', 'und');
log(JSON.stringify(command))
setStateDelayed('alexa2.0.Echo-Devices.'+ id +'.Commands.speak', 'Aber ich lasse den Staubsauger '+ stext +' saugen!',1500);
setStateDelayed('mqtt.0.valetudo.rockrobo.custom_command'/*valetudo/rockrobo/custom command*/, JSON.stringify(command),1500);
}
} | 26.212121 | 129 | 0.605202 |
4006a1dc40a87fa1eba20fb8909b31074090056c | 5,917 | js | JavaScript | assets/js/custom.js | bobi1539/yagami | b3127d7f99672af20ad2405ebc1b807cd1107750 | [
"MIT"
] | null | null | null | assets/js/custom.js | bobi1539/yagami | b3127d7f99672af20ad2405ebc1b807cd1107750 | [
"MIT"
] | null | null | null | assets/js/custom.js | bobi1539/yagami | b3127d7f99672af20ad2405ebc1b807cd1107750 | [
"MIT"
] | null | null | null | (function ($) {
"use strict";
$(document).ready(function () {
/*---------------------------------------------------
product carousel
----------------------------------------------------*/
$('.product-carousel').owlCarousel({
loop: true,
navText: ['<i class="icofont-simple-left"></i>', '<i class="icofont-simple-right"></i>'],
nav: true,
autoplay: true,
autoplayTimeout: 5000,
smartSpeed: 450,
margin: 20,
responsive: {
0: {
items: 1
},
768: {
items: 2
},
991: {
items: 3
},
1200: {
items: 3
},
1920: {
items: 3
}
}
});
/*---------------------------------------------------
slider carousel
----------------------------------------------------*/
$('.slider').owlCarousel({
loop: true,
navText: ['<i class="icofont-simple-left"></i>', '<i class="icofont-simple-right"></i>'],
nav: true,
autoplay: true,
autoplayTimeout: 5000,
smartSpeed: 450,
responsive: {
0: {
items: 1
},
768: {
items: 1
},
991: {
items: 1
},
1200: {
items: 1
},
1920: {
items: 1
}
}
});
/*---------------------------------------------------
testimonial carousel
----------------------------------------------------*/
$('.testi-carousel').owlCarousel({
loop: true,
nav: false,
autoplay: true,
autoplayTimeout: 5000,
animateOut: 'fadeOut',
animateIn: 'fadeIn',
smartSpeed: 450,
margin: 30,
responsive: {
0: {
items: 1
},
768: {
items: 2
},
991: {
items: 3
},
1200: {
items: 3
},
1920: {
items: 3
}
}
});
/*---------------------------------------------------
testimonial carousel two
----------------------------------------------------*/
$('.testi-carousel-two').owlCarousel({
loop: true,
nav: false,
autoplay: true,
autoplayTimeout: 5000,
animateOut: 'fadeOut',
animateIn: 'fadeIn',
smartSpeed: 450,
margin: 30,
responsive: {
0: {
items: 1
},
768: {
items: 2
},
991: {
items: 2
},
1200: {
items: 2
},
1920: {
items: 2
}
}
});
/*---------------------------------------------------
testimonial carousel three
----------------------------------------------------*/
$('.testi-carousel-three').owlCarousel({
loop: true,
nav: false,
autoplay: true,
autoplayTimeout: 5000,
animateOut: 'fadeOut',
animateIn: 'fadeIn',
smartSpeed: 450,
margin: 30,
responsive: {
0: {
items: 1
},
768: {
items: 2
},
991: {
items: 2
},
1200: {
items: 2
},
1920: {
items: 2
}
}
});
/*---------------------------------------------------
magnific popUp
----------------------------------------------------*/
$('.popup-video').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: false,
fixedContentPos: false,
disableOn: 300
});
/*---------------------------------------------------
scrollIt plugin activation
----------------------------------------------------*/
$.scrollIt();
});
/*---------------------------------------------------
sticky header
----------------------------------------------------*/
$(window).on('scroll', function () {
var scroll = $(window).scrollTop();
if (scroll < 100) {
$(".mainmenu").removeClass("sticky");
} else {
$(".mainmenu").addClass("sticky");
}
});
/*---------------------------------------------------
accordian
----------------------------------------------------*/
$('.collapse').on('shown.bs.collapse', function () {
$(this).prev().addClass('active');
});
$('.collapse').on('hidden.bs.collapse', function () {
$(this).prev().removeClass('active');
});
/*---------------------------------------------------
preloader
----------------------------------------------------*/
$(window).on('load', function () {
$('.preloader').fadeOut(500);
});
}(jQuery)); | 28.17619 | 101 | 0.258915 |
4006b656365b59c5e7254aba1200803c81e74e8b | 847 | js | JavaScript | routes/AccountRoutes.js | decoste/Project2 | aa3221400c216a4817e08aaa53ea029c7b888882 | [
"MIT"
] | null | null | null | routes/AccountRoutes.js | decoste/Project2 | aa3221400c216a4817e08aaa53ea029c7b888882 | [
"MIT"
] | 1 | 2021-01-20T23:11:20.000Z | 2021-01-20T23:11:20.000Z | routes/AccountRoutes.js | decoste/project2 | aa3221400c216a4817e08aaa53ea029c7b888882 | [
"MIT"
] | null | null | null | // Requiring our models and passport as we've configured it
const db = require("../models");
const passport = require("../config/passport");
module.exports = function(app) {
app.post("/api/user_data/balance", function(req, res) {
console.log("BALANCE!!!!!", req.body);
db.Accounts.update(req.body,
{
where: {
UserId: req.user.id
}
})
.then(function(dbPost) {
res.json(dbPost);
});
});
app.post("/api/user_data/balance/withdraw", function(req, res) {
console.log("BALANCE!!!!!", req.body);
db.Accounts.update(req.body,
{
where: {
UserId: req.user.id
}
})
.then(function(dbPost) {
res.json(dbPost);
});
});
};
| 26.46875 | 70 | 0.482881 |
4006df44142fb9b4d66187e2554b24dfd9dd691f | 7,932 | js | JavaScript | PlanetVoodoo/scroll-path/scroll-path.js | gftruj/webzamples | b500ecb2171e288ae6a14a917816d300a6d374c3 | [
"MIT"
] | 19 | 2020-06-24T14:32:28.000Z | 2022-03-21T19:02:40.000Z | PlanetVoodoo/scroll-path/scroll-path.js | gftruj/webzamples | b500ecb2171e288ae6a14a917816d300a6d374c3 | [
"MIT"
] | 1 | 2021-02-11T20:04:49.000Z | 2021-02-16T20:50:50.000Z | PlanetVoodoo/scroll-path/scroll-path.js | gftruj/webzamples | b500ecb2171e288ae6a14a917816d300a6d374c3 | [
"MIT"
] | 13 | 2020-12-29T02:03:53.000Z | 2022-02-04T14:09:27.000Z | // originally by Jan Azzati
// https://github.com/protyze/aframe-curve-component
if (typeof AFRAME === 'undefined') {
throw new Error('Component attempted to register before AFRAME was available.');
}
/**
* Alongpath component for A-Frame.
* Move Entities along a predefined Curve
*/
AFRAME.registerComponent('scroll-path', {
//dependencies: ['curve'],
schema: {
curve: { default: '' },
triggers: { default: 'a-curve-point' },
triggerRadius: { type: 'number', default: 0.01 },
dur: { default: 1000 },
loop: { default: false },
rotate: { default: false },
smoothRotation: {default: false},
resetonplay: { default: true },
speed: { default: 10 },
damping: {default: 0.9},
debugTriggers: {default: false}
},
init: function () {
this.impulse = 0;
this.rotationDummy = new THREE.Object3D();
this.updateCurve = this.updateCurve.bind(this);
this.debugMeshData = {
geometry: new THREE.SphereGeometry(0.1),
material: new THREE.MeshNormalMaterial({transparent: true, opacity: 0.5})
}
this.wheelEvent = this.wheelEvent.bind(this);
window.addEventListener("wheel", this.wheelEvent)
if(AFRAME.utils.device.isMobile ()){
this.touchEvent = this.touchEvent.bind(this)
window.addEventListener('touchstart', this.touchEvent);
window.addEventListener('touchmove', this.touchEvent);
window.addEventListener('touchend', this.touchEvent);
}
},
update: function (oldData) {
var diff = AFRAME.utils.diff (oldData, this.data)
if (diff.curve || diff.triggers) {
this.curve = document.querySelector(this.data.curve);
this.triggers = this.curve.querySelectorAll(this.data.triggers);
if (!this.curve) {
console.warn("Curve not found. Can't follow anything...");
} else {
this.initialPosition = this.el.object3D.position;
}
this.reset();
}
// debug triggers
diff.debugTriggers ? this.createDebugTriggers() : this.removeDebugTriggers()
if (diff.triggerRadius)
this.debugMeshData.geometry.radius = diff.triggerRadius;
},
reset: function () {
// Reset to initial state
this.interval = 0;
},
touchEvent: function(evt) {
var deltaY;
if (evt.type === "touchstart") {
this.clientY = evt.touches[0].clientY;
} else {
// touchmove, as well as touchend
deltaY = evt.changedTouches[0].clientY - this.clientY;
this.updateCurve(deltaY)
}
},
wheelEvent: function(evt) {
this.updateCurve(evt.deltaY)
},
updateCurve: function(dy) {
this.impulse = this.data.speed * (dy > 0 ? 1 : -1);
},
nextImpulse: function (impulse) {
if (Math.abs(impulse) > 1) {
return impulse *= this.data.damping;
} else {
return impulse = 0;
}
},
checkBounds: function (current, max) {
if (current < 0)
return 0
else if (current > max)
return max
return current;
},
tick: function (time, timeDelta) {
var curve = this.curve.components['curve'] ? this.curve.components['curve'].curve : null;
if (!curve) {
console.error("The entity associated with the curve property has no curve component.");
}
this.interval += this.impulse;
this.impulse = this.nextImpulse(this.impulse)
this.interval = this.checkBounds(this.interval, this.data.dur)
var position = this.interval / this.data.dur
if ((this.data.loop === false) && position >= 1) {
// Set the end-position
this.el.setAttribute('position', curve.points[curve.points.length - 1]);
} else {
// …updating position
var p = curve.getPoint(position);
this.el.object3D.position.copy(p)
// Update Rotation of Entity
if (this.data.rotate === true) {
var nextInterval = this.checkBounds(this.interval + timeDelta, this.data.dur)
var nextposition = nextInterval / this.data.dur
if (this.data.smoothRotation) {
this.rotationDummy.position.copy(this.el.object3D.position)
this.rotationDummy.lookAt(curve.getPoint(nextposition))
this.el.object3D.quaternion.slerp(this.rotationDummy.quaternion, 0.1)
} else {
this.el.object3D.lookAt(curve.getPoint(nextposition))
}
}
}
// Check for Active-Triggers
if (this.data.triggerRadius > 0 && this.triggers && (this.triggers.length > 0)) {
this.updateActiveTrigger();
}
},
play: function () {
if (this.data.resetonplay) {
this.reset();
}
},
remove: function () {
this.el.object3D.position.copy(this.initialPosition);
this.removeDebugTriggers();
this.debugMeshData.geometry.dispose();
this.debugMeshData.material.dispose();
window.removeEventListener("wheel", this.wheelEvent)
if(AFRAME.utils.device.isMobile ()){
this.touchEvent = this.touchEvent.bind(this)
window.removeEventListener('touchstart', this.touchEvent);
window.removeEventListener('touchmove', this.touchEvent);
window.removeEventListener('touchend', this.touchEvent);
}
},
createDebugTriggers() {
this.debugTriggers = new THREE.Object3D();
this.el.sceneEl.object3D.add(this.debugTriggers);
for (var i = 0; i < this.triggers.length; i++) {
if (this.triggers[i].object3D) {
const root = this.triggers[i].object3D
const mesh = new THREE.Mesh(this.debugMeshData.geometry, this.debugMeshData.material);
if (!root.userdata) root.userdata = {}
root.userdata.mesh = mesh;
root.add(mesh);
}
}
},
removeDebugTriggers() {
for (var i = 0; i < this.triggers.length; i++) {
if (this.triggers[i].object3D && this.triggers[i].object3D.userdata) {
const mesh = this.triggers[i].object3D.userdata.mesh;
if (mesh) mesh.parent.remove(mesh);
}
}
},
updateActiveTrigger: function () {
for (var i = 0; i < this.triggers.length; i++) {
if (this.triggers[i].object3D) {
if (this.triggers[i].object3D.position.distanceTo(this.el.object3D.position) <= this.data.triggerRadius) {
// If this element is not the active trigger, activate it - and if necessary deactivate other triggers.
if (this.activeTrigger && (this.activeTrigger != this.triggers[i])) {
this.activeTrigger.emit("alongpath-trigger-deactivated");
this.activeTrigger = this.triggers[i];
this.activeTrigger.emit("alongpath-trigger-activated");
} else if (!this.activeTrigger) {
this.activeTrigger = this.triggers[i];
this.activeTrigger.emit("alongpath-trigger-activated");
}
break;
} else {
// If this Element was the active trigger, deactivate it
if (this.activeTrigger && (this.activeTrigger == this.triggers[i])) {
this.activeTrigger.emit("alongpath-trigger-deactivated");
this.activeTrigger = null;
}
}
}
}
}
}); | 37.065421 | 123 | 0.557741 |
40074cb13d5c1395be366d3be2a468aa46b94276 | 488 | js | JavaScript | test/run-wunit.js | zanachka/webdext | 4c3bda9a272063587fba1a5ce24bcfc715460aae | [
"MIT"
] | 80 | 2017-06-12T04:39:25.000Z | 2022-02-12T22:22:15.000Z | test/run-wunit.js | zanachka/webdext | 4c3bda9a272063587fba1a5ce24bcfc715460aae | [
"MIT"
] | null | null | null | test/run-wunit.js | zanachka/webdext | 4c3bda9a272063587fba1a5ce24bcfc715460aae | [
"MIT"
] | 18 | 2017-06-13T06:20:47.000Z | 2021-04-30T21:52:05.000Z | "use strict";
var system = require('system');
if (system.args.length !== 2) {
console.log('Usage: run-wunit.js URL');
phantom.exit(1);
}
var page = require('webpage').create();
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.open(system.args[1], function(status){
if (status !== "success") {
console.log("Unable to access network");
phantom.exit(1);
} else {
console.log("Page opened");
phantom.exit(0);
}
});
| 20.333333 | 48 | 0.590164 |
4008a017ee48338e5e6cad638650527a1a7b708f | 56 | js | JavaScript | web-app/src/pages/dappHEX/index.js | MIPPLTeam/MyERC20_1 | 0ea241323433d853d384665cd28ed0c94c50cd13 | [
"MIT"
] | null | null | null | web-app/src/pages/dappHEX/index.js | MIPPLTeam/MyERC20_1 | 0ea241323433d853d384665cd28ed0c94c50cd13 | [
"MIT"
] | null | null | null | web-app/src/pages/dappHEX/index.js | MIPPLTeam/MyERC20_1 | 0ea241323433d853d384665cd28ed0c94c50cd13 | [
"MIT"
] | null | null | null | import { DAppHEX } from './DAppHEX'
export { DAppHEX }
| 14 | 35 | 0.660714 |
400939bbde2243d537bfae6d200a09a5731e712b | 1,129 | js | JavaScript | exercicios/challenge-30/challenge-30.js | bernardorz/golbyJs | ec38b398f5f935fabead205ed21afb3a276a1a2e | [
"MIT"
] | null | null | null | exercicios/challenge-30/challenge-30.js | bernardorz/golbyJs | ec38b398f5f935fabead205ed21afb3a276a1a2e | [
"MIT"
] | 15 | 2021-05-09T01:46:07.000Z | 2021-09-02T13:40:45.000Z | curso-javascript-ninja-master/Couse-content/challenge-30/challenge-30.js | wellingtonn96/CoursesAndTuturials | 3f4a2027ff1ca0f90a694e2a6f09c96461174b81 | [
"MIT"
] | null | null | null | /*
A loja de carros será nosso desafio final. Na aula anterior, você fez a parte
do cadastro dos carros. Agora nós vamos começar a deixar ele com cara de
projeto mesmo.
Crie um novo repositório na sua conta do GitHub, com o nome do seu projeto.
Na hora de criar, o GitHub te dá a opção de criar o repositório com um
README. Use essa opção.
Após criar o repositório, clone ele na sua máquina.
Crie uma nova branch chamada `challenge-30`, e copie tudo o que foi feito no
desafio da aula anterior para esse novo repositório, nessa branch
`challenge-30`.
Adicione um arquivo na raiz desse novo repositório chamado `.gitignore`.
O conteúdeo desse arquivo deve ser somente as duas linhas abaixo:
node_modules
npm-debug.log
Faça as melhorias que você achar que são necessárias no seu código, removendo
duplicações, deixando-o o mais legível possível, e então suba essa alteração
para o repositório do seu projeto.
Envie um pull request da branch `challenge-30` para a `master` e cole aqui
nesse arquivo, dentro do `console.log`, o link para o pull request no seu
projeto.
*/
console.log('Link do pull request do seu projeto');
| 34.212121 | 77 | 0.777679 |
400957c93f496da93c222ebfe5a6b2ad0edc20c2 | 170 | js | JavaScript | problem_one/algorithm.js | atrachier/euler_projects | 831a99bf6a3ab0c96cb6d792588862d17c07708d | [
"Apache-2.0"
] | null | null | null | problem_one/algorithm.js | atrachier/euler_projects | 831a99bf6a3ab0c96cb6d792588862d17c07708d | [
"Apache-2.0"
] | null | null | null | problem_one/algorithm.js | atrachier/euler_projects | 831a99bf6a3ab0c96cb6d792588862d17c07708d | [
"Apache-2.0"
] | null | null | null |
exports.countBy = function (x, y, n) {
const num = []
for (let i = 0; i < n; i++) {
if (i % x === 0 || i % y === 0) {
num.push(i)
}
}
return num
}
| 15.454545 | 38 | 0.405882 |
400a98427b1c44a9cb78ec50a4d69216d58e51a5 | 287 | js | JavaScript | app/store/configureStore.js | LibreTask/desktop | 7894816abc42f50038388f3b6aa7df92f53bcf83 | [
"MIT"
] | null | null | null | app/store/configureStore.js | LibreTask/desktop | 7894816abc42f50038388f3b6aa7df92f53bcf83 | [
"MIT"
] | 1 | 2018-11-03T22:36:19.000Z | 2018-11-03T22:36:19.000Z | app/store/configureStore.js | LibreTask/desktop | 7894816abc42f50038388f3b6aa7df92f53bcf83 | [
"MIT"
] | null | null | null | /*
* @link https://libretask.org/
* @license https://github.com/LibreTask/desktop/blob/master/LICENSE.md
*/
if (process.env.NODE_ENV === "production") {
module.exports = require("./configureStore.production");
} else {
module.exports = require("./configureStore.development");
}
| 26.090909 | 71 | 0.696864 |
400af8f5676819db8ff659295e165b9a0ded621f | 108 | js | JavaScript | package/ga.js | HomeofNever/Blog | afb6859ec3f23d18f744085170ede9e55d1e2a0e | [
"CC-BY-4.0",
"MIT"
] | null | null | null | package/ga.js | HomeofNever/Blog | afb6859ec3f23d18f744085170ede9e55d1e2a0e | [
"CC-BY-4.0",
"MIT"
] | 9 | 2020-05-17T03:43:35.000Z | 2022-03-26T10:09:28.000Z | package/ga.js | HomeofNever/Blog | afb6859ec3f23d18f744085170ede9e55d1e2a0e | [
"CC-BY-4.0",
"MIT"
] | null | null | null | const window = require("global/window")
window.ga_api = 'https://async-task.never.workers.dev/optical/blog' | 36 | 67 | 0.759259 |
400b45db3476cc190b64830411a487acc7fb2e4d | 5,564 | js | JavaScript | src/pages/Schedules/index.js | douglasbrandao21/semac-app | 656040be11b0dc9e091fb751038d9221e20228d8 | [
"MIT"
] | null | null | null | src/pages/Schedules/index.js | douglasbrandao21/semac-app | 656040be11b0dc9e091fb751038d9221e20228d8 | [
"MIT"
] | 1 | 2021-09-02T16:44:45.000Z | 2021-09-02T16:44:45.000Z | src/pages/Schedules/index.js | douglasbrandao21/semac-app | 656040be11b0dc9e091fb751038d9221e20228d8 | [
"MIT"
] | null | null | null | import React, { Fragment, useState, useEffect } from "react";
import { StyleSheet } from "react-native";
import * as Animatable from "react-native-animatable";
import Navbar from "~/components/Navbar";
import {
Container,
HeaderContainer,
HeaderSeparator,
Title,
ButtonsContainer,
Button,
ButtonActiveText,
ButtonText
} from "./styles";
import LinearGradient from "react-native-linear-gradient";
import Monday from "~/components/Schedule/Monday";
import Tuesday from "~/components/Schedule/Tuesday";
import Wednesday from "~/components/Schedule/Wednesday";
import Thursday from "~/components/Schedule/Thursday";
import Friday from "~/components/Schedule/Friday";
export default function Schedules() {
const [active, setActive] = useState("monday");
const styles = StyleSheet.create({
gradient: {
flex: 1,
width: 52,
display: "flex",
justifyContent: "center",
alignItems: "center",
borderRadius: 20
},
animatedView: {
display: "flex",
justifyContent: "center",
alignItems: "center",
width: "100%",
flex: 1
}
});
function handleMonday() {
setActive("monday");
}
function handleTuesday() {
setActive("tuesday");
}
function handleWednesday() {
setActive("wednesday");
}
function handleThursday() {
setActive("thursday");
}
function handleFriday() {
setActive("friday");
}
return (
<Container contentContainerStyle={{ alignItems: "center" }}>
<Navbar />
<Title>Programação do dia</Title>
<HeaderContainer>
<ButtonsContainer>
{active == "monday" ? (
<Button>
<LinearGradient
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
colors={["#2AF598", "#08AEEA"]}
style={styles.gradient}
>
<ButtonActiveText>seg</ButtonActiveText>
</LinearGradient>
</Button>
) : (
<Button onPress={handleMonday}>
<ButtonText>seg</ButtonText>
</Button>
)}
{active == "tuesday" ? (
<Button>
<LinearGradient
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
colors={["#FF6700", "#BD0E5D"]}
style={styles.gradient}
>
<ButtonActiveText>ter</ButtonActiveText>
</LinearGradient>
</Button>
) : (
<Button onPress={handleTuesday}>
<ButtonText>ter</ButtonText>
</Button>
)}
{active == "wednesday" ? (
<Button>
<LinearGradient
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
colors={["#08AEEA", "#017EC1"]}
style={styles.gradient}
>
<ButtonActiveText>qua</ButtonActiveText>
</LinearGradient>
</Button>
) : (
<Button onPress={handleWednesday}>
<ButtonText>qua</ButtonText>
</Button>
)}
{active == "thursday" ? (
<Button>
<LinearGradient
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
colors={["#FEE140", "#FF6700"]}
style={styles.gradient}
>
<ButtonActiveText>qui</ButtonActiveText>
</LinearGradient>
</Button>
) : (
<Button onPress={handleThursday}>
<ButtonText>qui</ButtonText>
</Button>
)}
{active == "friday" ? (
<Button>
<LinearGradient
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
colors={["#AC18E1", "#4330FC"]}
style={styles.gradient}
>
<ButtonActiveText>sex</ButtonActiveText>
</LinearGradient>
</Button>
) : (
<Button onPress={handleFriday}>
<ButtonText>sex</ButtonText>
</Button>
)}
</ButtonsContainer>
<HeaderSeparator />
</HeaderContainer>
{active == "monday" ? (
<Animatable.View
animation="fadeInUp"
duration={500}
style={styles.animatedView}
>
<Monday />
</Animatable.View>
) : (
<Fragment />
)}
{active == "tuesday" ? (
<Animatable.View
animation="fadeInUp"
duration={500}
style={styles.animatedView}
>
<Tuesday />
</Animatable.View>
) : (
<Fragment />
)}
{active == "wednesday" ? (
<Animatable.View
animation="fadeInUp"
duration={500}
style={styles.animatedView}
>
<Wednesday />
</Animatable.View>
) : (
<Fragment />
)}
{active == "thursday" ? (
<Animatable.View
animation="fadeInUp"
duration={500}
style={styles.animatedView}
>
<Thursday />
</Animatable.View>
) : (
<Fragment />
)}
{active == "friday" ? (
<Animatable.View
animation="fadeInUp"
duration={500}
style={styles.animatedView}
>
<Friday />
</Animatable.View>
) : (
<Fragment />
)}
</Container>
);
}
| 24.619469 | 64 | 0.474479 |
400bcd178200264cbf828307636ba6432a5e8b76 | 1,948 | js | JavaScript | src/assets/js/scroll.js | therewasaguy/p5.js-website | f98ab325b88cfdbc726aa0aeb116d99c81f08b9d | [
"MIT"
] | 1 | 2020-08-04T21:51:11.000Z | 2020-08-04T21:51:11.000Z | src/assets/js/scroll.js | therewasaguy/p5.js-website | f98ab325b88cfdbc726aa0aeb116d99c81f08b9d | [
"MIT"
] | null | null | null | src/assets/js/scroll.js | therewasaguy/p5.js-website | f98ab325b88cfdbc726aa0aeb116d99c81f08b9d | [
"MIT"
] | null | null | null | /*
Hastily written scroll to fixed position:
TO DO:
- needs to not fail on resize of resize after scrolling,
- and needs to use animate() to add jquery easing
*/
// if (window.matchMedia("min-width:720px").matches) {
// var elementPosition = $('#menu').offset();
//
// $(window).scroll(function(){
// if($(window).scrollTop() > elementPosition.top){
// var top = Math.round($(window).scrollTop()-elementPosition.top);
// $('#menu').css({'margin-top': top});
// } else {
// $('#menu').css({'margin-top': 0});
// }
// });
// }
$(function() {
var $window = $(window),
$sidebar = $("#menu"),
sidebarOffset = $sidebar.offset(),
$rotationElements = $([
'#download-page #asterisk-design-element',
'#reference-page #asterisk-design-element'
].join()),
rotationDegrees = 0;
var isWidescreen = function() {
return window.matchMedia("(min-width: 720px)").matches;
};
// Change sidebar position:
var setSidebarPosition = function() {
if ($window.scrollTop() > sidebarOffset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - sidebarOffset.top
});
} else {
$sidebar.stop().animate({
marginTop: 0
});
}
};
if (isWidescreen() && $window.scrollTop() > sidebarOffset.top) {
$sidebar.css('margin-top', $window.scrollTop() - sidebarOffset.top);
}
// Rotate specific elements:
var rotateElements = function() {
rotationDegrees = ($window.scrollTop() / 40) - 21;
$rotationElements.css({
'-ms-transform': 'rotate(' + rotationDegrees + 'deg)',
'-webkit-transform': 'rotate(' + rotationDegrees + 'deg)',
'transform': 'rotate(' + rotationDegrees + 'deg)'
});
};
$window.scroll(function() {
if (isWidescreen()) {
//setSidebarPosition(); // temp to stop buggy scrolling
rotateElements();
}
});
});
| 26.684932 | 73 | 0.575975 |
400d16c5799a187674cceb0853b6b89f4eead493 | 170 | js | JavaScript | src/utils/getAsyncData.js | chenx18/vue3.x_test | 3e0c2af822feceb0c4aa70a3978dd9aa45c25f16 | [
"MIT"
] | 58 | 2020-06-23T02:25:28.000Z | 2022-03-20T07:33:09.000Z | src/utils/getAsyncData.js | chenx18/vue3.x_test | 3e0c2af822feceb0c4aa70a3978dd9aa45c25f16 | [
"MIT"
] | 1 | 2020-10-11T02:49:05.000Z | 2022-02-10T08:32:06.000Z | src/utils/getAsyncData.js | chenx18/vue3.x_test | 3e0c2af822feceb0c4aa70a3978dd9aa45c25f16 | [
"MIT"
] | 26 | 2020-06-24T01:04:11.000Z | 2022-03-15T06:53:17.000Z | import { time } from './config'
//模拟ajax异步请求
const getAsyncData = data => {
return new Promise(res => setTimeout(() => res(data), time))
}
export default getAsyncData | 28.333333 | 64 | 0.682353 |
400d2d7c3767019592b202f6ee1dc6aa9c892f34 | 7,469 | js | JavaScript | src/views/measures/index.js | pasindumarasinghe/flame-coach-web | 149b7afd34c79c1addf66731c0586660cab7ab04 | [
"MIT"
] | null | null | null | src/views/measures/index.js | pasindumarasinghe/flame-coach-web | 149b7afd34c79c1addf66731c0586660cab7ab04 | [
"MIT"
] | 7 | 2021-10-10T01:38:37.000Z | 2021-12-05T18:46:02.000Z | src/views/measures/index.js | pasindumarasinghe/flame-coach-web | 149b7afd34c79c1addf66731c0586660cab7ab04 | [
"MIT"
] | 7 | 2021-10-15T15:30:19.000Z | 2022-03-19T19:25:04.000Z | import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core";
import React, { useState } from "react";
import Page from "../../components/Page";
import WeightChart from "../../components/Charts/WeightChart";
import Events from "../../components/Charts/Events";
import { filterWeightsPerTimeRange } from "../../components/Charts/utils/chartUtil";
import moment from "moment";
import Filters from "../../components/Charts/Filters";
import { useQueryClient } from "react-query";
import { logError } from "../../logging";
import PropTypes from "prop-types";
import Notification from "../../components/Core/Notification";
import update from "immutability-helper";
import ErrorMessage from "../../components/Core/Notification/ErrorMessage/ErrorMessage";
import InfoMessage from "../../components/Core/Notification/InfoMessage/InfoMessage";
import { useFetchWeightClient } from "../../api/measures/useFetchWeightClient";
import { useAddWeightClient } from "../../api/measures/useAddWeightClient";
import { useDeleteWeightClient } from "../../api/measures/useDeleteWeightClient";
import { useFetchClientPersonalInformation } from "../../api/client/useFetchClientPersonalInformation";
import { extractWeightType } from "../../api/client/clientPersonalInformationUtil";
import { useIsMobile } from "../../utils/mediaUtil";
const useStyles = makeStyles((theme) => ({
root: {
paddingTop: theme.spacing(3),
paddingBottom: theme.spacing(3),
height: "100%"
},
weightGraphicCardContent: {
height: "400px"
},
weightGraphicMobileCardContent: {
height: "400px",
marginBottom: "35px"
},
eventsCardContent: {
height: "400px"
},
filtersCardContent: {
height: "400px"
},
container: {
height: "100%"
}
}));
const MeasuresView = ({
customerIdentifier
}) => {
const classes = useStyles();
const queryClient = useQueryClient();
const isMobile = useIsMobile();
const [timeFrameWeight, setTimeFrameWeight] = useState("1_MONTH");
const [dateWeightAdding, setDateWeightAdding] = useState(moment()
.utc());
const [weightAdding, setWeightAdding] = useState(NaN);
const [notification, setNotification] = useState({
enable: false,
message: "",
level: "INFO"
});
const updateNotificationHandler = (enable, message, level) => {
setNotification({
enable,
message,
level
});
};
const notificationHandler = () => {
setNotification(update(notification,
{
enable: { $set: false }
}));
};
const personalData = useFetchClientPersonalInformation(customerIdentifier);
const {
isFetching,
isError,
data
} = useFetchWeightClient(customerIdentifier);
const { mutate: mutateAddWeight } = useAddWeightClient();
const { mutate: mutateDeleteWeight } = useDeleteWeightClient();
const filteredData = filterWeightsPerTimeRange(data, moment()
.utc(), timeFrameWeight);
const addWeightHandler = (weight, date) => {
if (Number.isNaN(weight)) {
const errorMessage = ErrorMessage.CODE_0006;
updateNotificationHandler(true, errorMessage.msg, errorMessage.level);
} else if (date === null) {
const errorMessage = ErrorMessage.CODE_0007;
updateNotificationHandler(true, errorMessage.msg, errorMessage.level);
} else {
mutateAddWeight({
clientIdentifier: customerIdentifier,
weight,
utcDate: date
}, {
onError: (error) => {
logError("Measures",
"useMutation addNewWeight",
"Error:", error.response);
logError("Measures", "useMutation addNewWeight", "Error Details:", error.response.data.detail);
const errorCode = ErrorMessage.fromCode(error.response.data.code);
updateNotificationHandler(true, errorCode.msg, errorCode.level);
},
onSuccess: () => {
queryClient.invalidateQueries(["getWeightClient", customerIdentifier]);
const successMessage = InfoMessage.CODE_0002;
updateNotificationHandler(true, successMessage.msg, successMessage.level);
}
});
}
};
const deleteWeightHandler = (event) => {
mutateDeleteWeight({
clientIdentifier: customerIdentifier,
identifier: event.identifier
}, {
onError: (error) => {
logError("Measures",
"useMutation deleteHandler",
"Error:", error.response);
logError("Measures", "useMutation deleteHandler", "Error Details:", error.response.data.detail);
const errorCode = ErrorMessage.fromCode(error.response.data.code);
updateNotificationHandler(true, errorCode.msg, errorCode.level);
},
onSuccess: () => {
queryClient.invalidateQueries(["getWeightClient", customerIdentifier]);
}
});
};
return (
<Page
title="Measures"
isError={isError || personalData.isError}
isLoading={isFetching || personalData.isFetching}
>
<Grid
container
spacing={1}
direction="row"
>
<Grid
item
xs={12}
md={9}
>
<Grid
container
spacing={1}
direction="column"
>
<Grid
item
xs={12}
>
<Grid container spacing={1}>
<Grid item md={9} xs={12}>
<WeightChart
className={isMobile ? classes.weightGraphicMobileCardContent
: classes.weightGraphicCardContent}
isMobile={isMobile}
timeFrame={timeFrameWeight}
dataChart={filteredData}
measureUnit={extractWeightType(personalData.data?.measureType.value)}
/>
</Grid>
<Grid item md={3} xs={12}>
<Events
className={classes.eventsCardContent}
dataEvents={filteredData}
onDeleteHandle={deleteWeightHandler}
measureUnit={extractWeightType(personalData.data?.measureType.value)}
/>
</Grid>
</Grid>
</Grid>
</Grid>
</Grid>
<Grid
item
md={3}
xs={12}
>
<Filters
className={isMobile ? null : classes.filtersCardContent}
enableAddingWeight
timeFrame={timeFrameWeight}
onChangeTimeFrameHandler={(newTimeFrame) => setTimeFrameWeight(newTimeFrame)}
date={dateWeightAdding}
onChangeDateHandler={(newDate) => setDateWeightAdding(newDate)}
weight={weightAdding}
onChangeWeightHandler={(newWeight) => setWeightAdding(newWeight)}
onAddWeightHandler={addWeightHandler}
/>
</Grid>
{notification.enable
? (
<Grid
item
xs={12}
md={9}
>
<Notification
collapse
open={notification.enable}
openHandler={notificationHandler}
level={notification.level}
message={notification.message}
/>
</Grid>
)
: null}
</Grid>
</Page>
);
};
MeasuresView.propTypes = {
customerIdentifier: PropTypes.string.isRequired
};
export default MeasuresView;
| 30.991701 | 105 | 0.601419 |
400dd37e4d8025808d2dc62e54cea859347f7b60 | 1,477 | js | JavaScript | src/server.js | ntbm/SimpleTracker | 9ba06e873a94611a47945e7c328c27ff517ba71a | [
"MIT"
] | null | null | null | src/server.js | ntbm/SimpleTracker | 9ba06e873a94611a47945e7c328c27ff517ba71a | [
"MIT"
] | null | null | null | src/server.js | ntbm/SimpleTracker | 9ba06e873a94611a47945e7c328c27ff517ba71a | [
"MIT"
] | null | null | null | const bodyParser = require('body-parser')
const multer = require('multer')
main().then(app => {
const server = app.listen(process.env.PORT || 3000, () => {
console.log(`Server started at PORT ${process.env.PORT || 3000}`)
})
})
async function main () {
const app = require('express')()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
const databaseClient = await require('./database')
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', req.get('Origin') || '')
res.setHeader('Access-Control-Allow-Methods',
'GET, POST, OPTIONS, PUT, PATCH, DELETE')
res.setHeader('Access-Control-Allow-Headers',
'content-type, auth-token, user, X-XSRF-TOKEN')
res.setHeader('Access-Control-Allow-Credentials', true)
// Check if preflight request
if (req.method === 'OPTIONS') {
res.status(200)
res.end()
} else {
next()
}
})
app.use((req, res, next) => {
req.models = req.models || databaseClient.models
next()
})
app.get('/', (req, res) => res.sendStatus(200))
app.post('/', multer().array(), (req, res) => {
const date = new Date()
const host = req.get('Origin')
const path = req.get('Referer').slice(host.length)
console.log(`[${date}] ${host}${path}`)
const Access = req.models.Access
new Access({date, host, path})
.save()
res.sendStatus(200)
})
app.use('/', require('./routes'))
return app
} | 28.403846 | 73 | 0.61002 |
400f2d58288af943a9184855ca3c2073d52673eb | 860 | js | JavaScript | resources/assets/js/components/common/forms/file-upload.js | alooze/oioi.tmp | 52c44db4fb014ab46ce615d43b54c744b27465b3 | [
"MIT"
] | null | null | null | resources/assets/js/components/common/forms/file-upload.js | alooze/oioi.tmp | 52c44db4fb014ab46ce615d43b54c744b27465b3 | [
"MIT"
] | null | null | null | resources/assets/js/components/common/forms/file-upload.js | alooze/oioi.tmp | 52c44db4fb014ab46ce615d43b54c744b27465b3 | [
"MIT"
] | null | null | null | const form = document.querySelector('.dashboard__info-form')
if (form) {
form.addEventListener('change', e => {
if (e.target.matches('input[type=file]') && e.target.files && e.target.files[0]) {
const container = e.target.closest('.dashboard__info-file')
container.classList.add('active')
container.querySelector('.form__file-previews').innerHTML = `
<i class="fa fa-close" aria-hidden="true"></i>
<span>${e.target.files[0].name}</span>
`
}
})
form.addEventListener('click', e => {
if (e.target.matches('.form__file-previews .fa-close')) {
const container = e.target.closest('.dashboard__info-file')
container.classList.remove('active')
container.querySelector('input[type=file]').value = null
container.querySelector('.form__file-previews').innerHTML = ''
}
})
}
| 33.076923 | 86 | 0.640698 |
400f5635e352c4ef1f262b5134588fc1443b6159 | 223 | js | JavaScript | src/system/init/initServerStatus.js | jason831127/streamyBackEnd | 71341fc3bd3bd51dcd19df521f15351aa0e11fd0 | [
"MIT"
] | null | null | null | src/system/init/initServerStatus.js | jason831127/streamyBackEnd | 71341fc3bd3bd51dcd19df521f15351aa0e11fd0 | [
"MIT"
] | null | null | null | src/system/init/initServerStatus.js | jason831127/streamyBackEnd | 71341fc3bd3bd51dcd19df521f15351aa0e11fd0 | [
"MIT"
] | null | null | null | module.exports = function (options) {
return new Promise(function (resolve, reject) {
if (!options) return reject(new Error('options required'));
/*
todo... 實作 server 狀態
*/
return resolve();
});
}; | 20.272727 | 63 | 0.609865 |
400f63d12e0447d3e8a500bea37a53fb1ea5fccb | 869 | js | JavaScript | nodeJS/ex/calculadora.js | Christiaan304/javascript | a44edc270bd33fed6e773812c1294897f29b890f | [
"MIT"
] | null | null | null | nodeJS/ex/calculadora.js | Christiaan304/javascript | a44edc270bd33fed6e773812c1294897f29b890f | [
"MIT"
] | null | null | null | nodeJS/ex/calculadora.js | Christiaan304/javascript | a44edc270bd33fed6e773812c1294897f29b890f | [
"MIT"
] | null | null | null | /*const prompt = require("prompt-sync")({sigint: true})*/
let n1 = prompt(`Digite o primeiro número: `)
let n2 = prompt(`Digite o segundo número: `)
let operacao = prompt(`Digite uma operação: `)
let sum = (n1, n2) => Number(n1) + Number(n2)
let sub = (n1, n2) => Number(n1) - Number(n2)
let mul = (n1, n2) => Number(n1) * Number(n2)
let div = (n1, n2) => (Number(n1) / Number(n2)).toFixed(2)
if ( operacao == `adicao` )
{
alert(`${n1} + ${n2} é igual a ${sum(n1, n2)}`)
}
else if ( operacao == `subtracao` )
{
alert(`${n1} - ${n2} é igual a ${sub(n1, n2)}`)
}
else if ( operacao == `multiplicacao` )
{
alert(`${n1} * ${n2} é igual a ${mul(n1, n2)}`)
}
else if ( operacao == `divisao` )
{
if ( Number(n2) == 0 )
{
alert(`Não é possível dividir por zero`)
}
else
{
alert(`${n1} / ${n2} é igual ${div(n1, n2)}`)
}
}
| 24.828571 | 58 | 0.542002 |
400fbc6fe6e0f7c215cdd334feffe8cccd018526 | 568 | js | JavaScript | node_modules/@iconify-icons/vs/w-square.js | kimsoonil/react-material-redux | da7322577720e7f9d58018fca5f50a3efe42d7f7 | [
"MIT"
] | 1 | 2021-02-04T06:47:14.000Z | 2021-02-04T06:47:14.000Z | node_modules/@iconify-icons/vs/w-square.js | kimsoonil/react-material-redux | da7322577720e7f9d58018fca5f50a3efe42d7f7 | [
"MIT"
] | null | null | null | node_modules/@iconify-icons/vs/w-square.js | kimsoonil/react-material-redux | da7322577720e7f9d58018fca5f50a3efe42d7f7 | [
"MIT"
] | 1 | 2021-02-04T06:47:14.000Z | 2021-02-04T06:47:14.000Z | var data = {
"body": "<path d=\"M336 0h1120q139 0 237.5 98.5T1792 336v1120q0 139-98.5 237.5T1456 1792H336q-139 0-237.5-98.5T0 1456V336Q0 197 98.5 98.5T336 0zm918 1493q12 0 21-12.5t13-25t11-37.5l269-1044q7-27-9-51t-36-24h-179q-12 0-21 12.5t-13 25t-11 37.5l-134 521l-134-521q-6-24-11-37.5t-14-25.5t-20-12H806q-16 0-25.5 19.5T761 374L627 895L493 374q-7-25-11-37.5t-13-25t-21-12.5H269q-20 0-36 24t-9 51l269 1044q7 25 11 37.5t13 25t21 12.5h178q27 0 45-75l135-523l135 523q18 75 45 75h178z\" fill=\"currentColor\"/>",
"width": 1792,
"height": 1792
};
export default data;
| 81.142857 | 498 | 0.725352 |
40104f22f3859bd6932cf8f0a1d9e379b6fef8ee | 253 | js | JavaScript | src/exceptions/FileHandlingError.js | bombies/DynamicJS | 8c1a0eb64766e04e5e6e518dac123d54c8eeaf1b | [
"Apache-2.0"
] | 1 | 2021-10-14T05:53:06.000Z | 2021-10-14T05:53:06.000Z | src/exceptions/FileHandlingError.js | bombies/DynamicJS | 8c1a0eb64766e04e5e6e518dac123d54c8eeaf1b | [
"Apache-2.0"
] | 32 | 2021-11-23T04:27:24.000Z | 2022-03-28T04:27:15.000Z | src/exceptions/FileHandlingError.js | bombies/DynamicJS | 8c1a0eb64766e04e5e6e518dac123d54c8eeaf1b | [
"Apache-2.0"
] | null | null | null | class FileHandlingError extends Error {
constructor(message = '') {
super();
this.name = 'FileHandlingError';
this.message = message;
}
}
module.exports = FileHandlingError;
FileHandlingError.prototype = Error.prototype; | 25.3 | 46 | 0.671937 |
401105123a7e748e3cb55f4b2fcb963597609ffe | 1,510 | js | JavaScript | packages/gnoll/commands/lib.js | sunflowerdeath/murloc | 05657349473f46faf42813be3b27afec855a64d7 | [
"Unlicense"
] | 3 | 2017-09-22T13:33:03.000Z | 2018-11-26T16:04:37.000Z | packages/gnoll/commands/lib.js | sunflowerdeath/murloc | 05657349473f46faf42813be3b27afec855a64d7 | [
"Unlicense"
] | 18 | 2017-09-28T17:53:59.000Z | 2022-03-08T22:21:42.000Z | packages/gnoll/commands/lib.js | sunflowerdeath/murloc | 05657349473f46faf42813be3b27afec855a64d7 | [
"Unlicense"
] | null | null | null | const path = require('path')
const emoji = require('node-emoji')
const chalk = require('chalk')
const rimrafSync = require('rimraf').sync
const getBabelConfig = require('../utils/getBabelConfig')
const paths = require('../utils/paths')
const BabelCompiler = require('../utils/babelCompiler')
module.exports = cmd => {
process.env.GNOLL_LIBRARY = 1
const babelConfig = getBabelConfig()
console.log(`Cleaning directory ${paths.lib}`)
rimrafSync(`${paths.lib}/*`)
const src = path.resolve(paths.root, cmd.entry)
const compiler = new BabelCompiler(src, paths.lib, {
babel: babelConfig,
watch: cmd.watch,
sourceMaps: cmd.sourceMaps
})
let ready = false
let errors = false
if (cmd.watch) {
console.log(emoji.get('eyes'), ' Starting watch...\n')
} else {
console.log(emoji.get('package'), ' Compiling files...\n')
}
compiler.on('copy', filepath => {
if (ready) console.log(`File '${filepath}' copied to build dir`)
})
compiler.on('success', filepath => {
if (ready) console.log(`File '${filepath}' compiled successfully`)
})
compiler.on('error', (filepath, error) => {
if (!ready) errors = true
console.log()
console.log(error.toString())
if (error.codeFrame) console.log(`\n${error.codeFrame}\n`)
})
compiler.on('ready', () => {
ready = true
if (errors) {
console.log(chalk.red('Compiled with errors.\n'))
} else {
console.log(chalk.green('Compiled successfully.\n'))
}
if (!cmd.watch) {
compiler.close()
process.exit(errors ? 1 : 0)
}
})
}
| 25.166667 | 68 | 0.662252 |
4013423b66aa5db35899f17dbeffaf408350ba9c | 348 | js | JavaScript | src/global/xx-bind-html.directive.js | calary/tms | 5470756b33c05d77616c0fc062640938f654000a | [
"MIT"
] | null | null | null | src/global/xx-bind-html.directive.js | calary/tms | 5470756b33c05d77616c0fc062640938f654000a | [
"MIT"
] | null | null | null | src/global/xx-bind-html.directive.js | calary/tms | 5470756b33c05d77616c0fc062640938f654000a | [
"MIT"
] | null | null | null | directive.$inject = ['$compile'];
function directive($compile){
return {
retrict: 'A',
link: function($scope, $ele, $attr){
$scope.$watch(function(){
return $scope.$eval($attr.xxBindHtml);
}, function(value){
$ele.html(value);
$compile($ele.contents())($scope);
});
}
};
}
module.exports = directive; | 21.75 | 46 | 0.577586 |
40139e434ff41890719ad427a955c24b2877c80a | 1,611 | js | JavaScript | .eleventy.js | PastelAzalea/PastelAzalea.github.io | 94482e330ce4461bb1ccf749b71922b4226682d7 | [
"MIT"
] | null | null | null | .eleventy.js | PastelAzalea/PastelAzalea.github.io | 94482e330ce4461bb1ccf749b71922b4226682d7 | [
"MIT"
] | null | null | null | .eleventy.js | PastelAzalea/PastelAzalea.github.io | 94482e330ce4461bb1ccf749b71922b4226682d7 | [
"MIT"
] | null | null | null | const debug = require("debug")("eleventy-homepage");
const postcssImporter = require("postcss-import");
const autoprefixer = require("autoprefixer");
const tailwindcss = require("tailwindcss");
const postcss = require("postcss");
const fs = require("fs");
const uglifyJS = require("uglify-js");
const CleanCSS = require("clean-css");
module.exports = function (config) {
config.setTemplateFormats(["html", "md", "hbs"]);
config.addPassthroughCopy("./src/assets/");
config.setDataDeepMerge(true);
config.addFilter("sort", function (value) {
return value.sort();
});
config.addFilter("toLocalDateString", function (value) {
return value.toLocaleDateString("en-UK", {
day: "numeric",
month: "long",
year: "numeric",
});
});
const css = fs.readFileSync("./src/css/stylesheet.css").toString();
postcss([postcssImporter, tailwindcss, autoprefixer])
.process(css, {
from: "./src/css/stylesheet.css",
to: "./src/_includes/partials/stylesheet.hbs",
})
.then((result) => {
fs.writeFileSync(
"./src/_includes/partials/stylesheet.hbs",
new CleanCSS({}).minify(result.css).styles
);
})
.catch((error) => {
debug("PostCSS Error: %o", error);
});
// create global script file
const jsContent = fs.readFileSync("./src/script/script.js").toString();
const minified = uglifyJS.minify(jsContent);
if (!minified.error) {
fs.writeFileSync("./src/_includes/partials/script.hbs", minified.code);
} else {
debug("Uglify-js Error: %o", minified.error);
}
debug("finished .eleventy.js");
};
| 29.833333 | 75 | 0.649286 |
40145cf1255458ca74614f2a4a9952d792676a31 | 836 | js | JavaScript | index.js | anilkumar-adhikari/JWT_authentication | 1dc59d91cbbd5e9c1049a249dba6cbfdb94ff8a4 | [
"MIT"
] | null | null | null | index.js | anilkumar-adhikari/JWT_authentication | 1dc59d91cbbd5e9c1049a249dba6cbfdb94ff8a4 | [
"MIT"
] | null | null | null | index.js | anilkumar-adhikari/JWT_authentication | 1dc59d91cbbd5e9c1049a249dba6cbfdb94ff8a4 | [
"MIT"
] | null | null | null | const request = require('request');
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const port = process.env.PORT || 9600;
require('dotenv/config');
const cors = require('cors');
// Import Routes
const authRoute = require('./routes/authRoute');
const privateRoute = require('./routes/privateRoute');
// Middleware
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(cors());
// Route Middleware
app.use('/api/user/', authRoute);
app.use('/api/posts/', privateRoute);
mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true, useUnifiedTopology: true }, (err)=>{
if(err) throw err;
console.log('Database is connected!!!!!')
});
app.listen(port, function(err){
if(err) throw err;
console.log(`Server is running on port ${port}`);
}) | 27.866667 | 106 | 0.696172 |
401709b29f17c1924a7e31cd9aacd8e80740a3e2 | 1,897 | js | JavaScript | modules/fileupload/fileuploadcontroller.js | contactjittu/expressapp | 9c5fb1348cebe943366716c47e9895a027d71bcc | [
"MIT"
] | 1 | 2018-09-28T20:56:30.000Z | 2018-09-28T20:56:30.000Z | modules/fileupload/fileuploadcontroller.js | contactjittu/expressapp | 9c5fb1348cebe943366716c47e9895a027d71bcc | [
"MIT"
] | 1 | 2021-05-10T23:49:20.000Z | 2021-05-10T23:49:20.000Z | modules/fileupload/fileuploadcontroller.js | contactjittu/expressapp | 9c5fb1348cebe943366716c47e9895a027d71bcc | [
"MIT"
] | 3 | 2017-09-29T10:59:32.000Z | 2018-07-16T10:46:07.000Z | 'use strict';
const express = require('express');
const router = express.Router();
const multer = require('multer');
const logger = require('../../utils/logger');
const fs = require('fs');
const dir = '././uploads';
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
const storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, dir);
},
filename: function (req, file, callback) {
const fileExtension = file.originalname.split('.').pop();
callback(null, 'file_' + Date.now() + '.' + fileExtension);
}
})
const fileFilter = (req, file, callback) => {
if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
return callback(new Error('Only image file are allowed!'), false);
}
callback(null, true);
}
const upload = multer({ storage: storage, fileFilter: fileFilter }).array('profilePic');
router.post('/uploadImage', upload, function (req, res) {
const fileArray = [];
try {
var files = req.files;
files.forEach(function (file) {
fileArray.push({ 'fileId': file.filename })
});
}
catch (e) {
logger.error(e.stack);
return res.status(500).send({ success: false, msg: 'Internal Server Error' });
}
return res.status(200).send({ success: true, msg: 'File is uploaded', data: fileArray });
});
router.get('/getImage/:fileId', function (req, res) {
const file = req.params.fileId;
if (!file) {
return res.status(400).send('<p>Bad Request</p>');
}
fs.readFile(dir + '/' + file, function (err, content) {
if (err) {
logger.error(err.stack);
if (err.code === 'ENOENT') {
return res.status(404).send('<p>Not Found</P>')
}
return res.status(500).send('<p>Internal Server Error</P>');
}
else {
res.writeHead(200, { 'Content-Type': 'image/jpg' });
res.end(content, 'binary');
return;
}
});
});
module.exports = router; | 26.71831 | 91 | 0.611492 |
40174fc215e24661d7dbfd15fd79f975137868ac | 2,644 | js | JavaScript | dist/out-tsc/src/app/layout/chamados/chamados.component.js | IgorHenrique/chamados | 3d2ad2203ab6ba9525c0770021e062da3dcd5ba0 | [
"Apache-2.0"
] | null | null | null | dist/out-tsc/src/app/layout/chamados/chamados.component.js | IgorHenrique/chamados | 3d2ad2203ab6ba9525c0770021e062da3dcd5ba0 | [
"Apache-2.0"
] | null | null | null | dist/out-tsc/src/app/layout/chamados/chamados.component.js | IgorHenrique/chamados | 3d2ad2203ab6ba9525c0770021e062da3dcd5ba0 | [
"Apache-2.0"
] | null | null | null | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from '@angular/core';
import { ChamadosService } from 'src/app/shared/services/chamados.service';
import { ServicosService } from 'src/app/shared/services/servicos.service';
import { FormBuilder, Validators } from '@angular/forms';
var ChamadosComponent = /** @class */ (function () {
function ChamadosComponent(servicoService, chamadoService, formBuilder) {
this.servicoService = servicoService;
this.chamadoService = chamadoService;
this.formBuilder = formBuilder;
this.formGroup = formBuilder.group({
titulo: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(120)]],
servico: ['', [Validators.required]],
mensagem: ['teste'],
observacao: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(120)]],
usuario: ['1', [Validators.required, Validators.email]],
});
}
ChamadosComponent.prototype.ngOnInit = function () {
this.findAll();
};
ChamadosComponent.prototype.findAll = function () {
var _this = this;
this.servicoService.findAll().subscribe(function (response) {
_this.servicos = response;
});
};
ChamadosComponent.prototype.abrirChamado = function () {
this.chamadoService.insert(this.formGroup.value).subscribe(function (response) {
alert("Ok");
});
};
ChamadosComponent = __decorate([
Component({
selector: 'app-chamados',
templateUrl: './chamados.component.html',
styleUrls: ['./chamados.component.scss']
}),
__metadata("design:paramtypes", [ServicosService,
ChamadosService,
FormBuilder])
], ChamadosComponent);
return ChamadosComponent;
}());
export { ChamadosComponent };
//# sourceMappingURL=chamados.component.js.map | 48.962963 | 150 | 0.631241 |
401759800f66c8a35fab736431a768ec6dacb85a | 267 | js | JavaScript | client/src/game-context.js | ssauperl/dapp-connect6 | cc08c076280a0bcff602dad874cfea0bc1b87498 | [
"MIT"
] | null | null | null | client/src/game-context.js | ssauperl/dapp-connect6 | cc08c076280a0bcff602dad874cfea0bc1b87498 | [
"MIT"
] | null | null | null | client/src/game-context.js | ssauperl/dapp-connect6 | cc08c076280a0bcff602dad874cfea0bc1b87498 | [
"MIT"
] | null | null | null | import React from "react";
export const dotsColor = {
BLACK: 2,
WHITE: 1
}
export const GameContext = React.createContext({
gameboard: new Array(), turn: 0, playerColor: dotsColor.WHITE, web3: null, accounts: [], selectedAccount: null, contract: null
}); | 29.666667 | 130 | 0.696629 |
4017720cf2fd9d25884df50b96605549948241b0 | 494 | js | JavaScript | src/utils/report.js | eemila/warsawlo | 79f460ebf1e880607d61945c0daaaa0222a1f49a | [
"MIT"
] | null | null | null | src/utils/report.js | eemila/warsawlo | 79f460ebf1e880607d61945c0daaaa0222a1f49a | [
"MIT"
] | null | null | null | src/utils/report.js | eemila/warsawlo | 79f460ebf1e880607d61945c0daaaa0222a1f49a | [
"MIT"
] | null | null | null | const macroURL = 'https://script.google.com/macros/s/AKfycbycBZl68tLHTSJkHPqn_PGUNCsHZq6hA1fzC6vs9kT-r_HQxKU/exec'
const serialize = (data) => Object.entries(data).map(entry => `${ encodeURIComponent(entry[0])} = ${encodeURIComponent(entry[1])}`).join('&')
const report = ({title, description}) => {
let data {
title,
description,
time: new Date()
}
fetch(`${macroURL}?${serialize(data)}`)
.then(res => res.text())
.then(res => console.log(res))
}
export default report
| 30.875 | 141 | 0.674089 |
4017b31a4d05104fe9a7ba0f0196e9115338465d | 821 | js | JavaScript | assets/javascripts/kitten/components/molecules/boxes/doc-link-box/stories.js | KissKissBankBank/kitten | 9ddcc5fb8955e2d564bddf2b70a09bcb8b02fa3b | [
"MIT"
] | 44 | 2016-12-14T15:04:17.000Z | 2022-01-15T01:06:13.000Z | assets/javascripts/kitten/components/molecules/boxes/doc-link-box/stories.js | KissKissBankBank/kitten | 9ddcc5fb8955e2d564bddf2b70a09bcb8b02fa3b | [
"MIT"
] | 1,450 | 2016-12-08T13:38:38.000Z | 2022-03-31T16:53:56.000Z | assets/javascripts/kitten/components/molecules/boxes/doc-link-box/stories.js | KissKissBankBank/kitten | 9ddcc5fb8955e2d564bddf2b70a09bcb8b02fa3b | [
"MIT"
] | 3 | 2017-08-11T12:08:20.000Z | 2018-09-18T08:46:25.000Z | import React from 'react'
import { DocLinkBox } from './index'
import { DocsPage } from 'storybook/docs-page'
export default {
title: 'Molecules/Boxes/DocLinkBox',
component: DocLinkBox,
parameters: {
docs: {
page: () => <DocsPage filepath={__filename} importString="DocLinkBox" />,
},
},
decorators: [story => <div className="story-Container">{story()}</div>],
}
export const Default = args => <DocLinkBox {...args} />
Default.args = {
isExternal: true,
href: 'https://www.kisskissbankbank.com',
title: 'Termes et Conditions de la collecte',
text: 'Cliquer pour ouvrir le fichier dans un nouvel onglet.',
}
Default.argTypes = {
isExternal: {
control: 'boolean',
},
href: {
control: 'text',
},
title: {
control: 'text',
},
text: {
control: 'text',
},
}
| 21.051282 | 79 | 0.628502 |
401a0139f5487bd182b0a80bda1c0bf3684c36b5 | 447 | js | JavaScript | frontend/src/ui/form/Keyboard/keyboards/KeyButton/KeyIcon/TenPower.js | HildoBijl/stepwise | 6b305aaebfc95028886384a840de1b8f8adbcf60 | [
"MIT"
] | null | null | null | frontend/src/ui/form/Keyboard/keyboards/KeyButton/KeyIcon/TenPower.js | HildoBijl/stepwise | 6b305aaebfc95028886384a840de1b8f8adbcf60 | [
"MIT"
] | 27 | 2020-06-11T12:33:20.000Z | 2022-03-23T17:01:40.000Z | frontend/src/ui/form/Keyboard/keyboards/KeyButton/KeyIcon/TenPower.js | HildoBijl/stepwise | 6b305aaebfc95028886384a840de1b8f8adbcf60 | [
"MIT"
] | null | null | null | import React from 'react'
import SvgIcon from '@material-ui/core/SvgIcon'
export default function Character({ char = '' }) {
return (
<SvgIcon>
<text textAnchor="middle" x="12" y="17" fontSize="14" fontFamily="KaTeX_Main, Times New Roman, serif">10</text>
<text textAnchor="middle" x="22" y="10" fontSize="9" fontFamily="KaTeX_Main, Times New Roman, serif" fontStyle="italic">x</text>
<circle cx="1" cy="13" r="1" />
</SvgIcon>
)
} | 37.25 | 131 | 0.671141 |
401aa14f0faf1268a0c994f464ba31a2dcc84b5f | 1,866 | js | JavaScript | js/startup_tables.js | Mrena/PlaceInfo | b9695cb55f1963cc54e5f79c505fe7084f80a89d | [
"MIT"
] | null | null | null | js/startup_tables.js | Mrena/PlaceInfo | b9695cb55f1963cc54e5f79c505fe7084f80a89d | [
"MIT"
] | null | null | null | js/startup_tables.js | Mrena/PlaceInfo | b9695cb55f1963cc54e5f79c505fe7084f80a89d | [
"MIT"
] | null | null | null | var startup_da_tables = require("./data_access/startup_da_tables");
var startup_tables = function(client,mysql_con,fs){
client.on("create_location_table",function(){
try{
startup_da_tables.createLocationTable(client,mysql_con,fs);
}catch(error){
console.log(error);
}
}).on("delete_location_table",function(){
try{
startup_da_tables.deleteLocationTable(client,mysql_con,fs);
}catch(error){
console.log(error);
}
}).on("empty_location_table",function(){
try{
startup_da_tables.emptyLocationTable(client,mysql_con,fs);
}catch(error){
console.log(error);
}
});
client.on("create_tables", function() {
try {
startup_da_tables.createTables(client, mysql_con, fs);
} catch(error) {
console.log(error);
}
}).on("delete_tables", function() {
try {
startup_da_tables.deleteTables(client, mysql_con, fs);
} catch(error) {
console.log(error);
}
}).on("empty_tables", function() {
try {
startup_da_tables.emptyTables(client, mysql_con, fs);
} catch(error) {
console.log(error);
}
});
client.on("create_tables_table", function () {
try {
startup_da_tables.createTablesTable(client, mysql_con, fs);
} catch (error) {
console.log(error);
}
}).on("delete_tables_table", function () {
try {
startup_da_tables.deleteTablesTable(client, mysql_con, fs);
} catch (error) {
console.log(error);
}
}).on("get_tables_status", function () {
try {
startup_da_tables.getTablesStatus(client, mysql_con, fs);
} catch (error) {
console.log(error);
}
});
};
exports.startup_tables = startup_tables; | 17.277778 | 68 | 0.585745 |
401b0c50c18735ade81fbcf275192fce31cdadd7 | 805 | js | JavaScript | src/hooks/populate-archivos-compartidos.js | ajomuch92/X-Code-Editor-Backend | 906155d0cc8b3a5371b46a283f036b61fdbb129d | [
"MIT"
] | null | null | null | src/hooks/populate-archivos-compartidos.js | ajomuch92/X-Code-Editor-Backend | 906155d0cc8b3a5371b46a283f036b61fdbb129d | [
"MIT"
] | null | null | null | src/hooks/populate-archivos-compartidos.js | ajomuch92/X-Code-Editor-Backend | 906155d0cc8b3a5371b46a283f036b61fdbb129d | [
"MIT"
] | null | null | null | // Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/api/hooks.html
// eslint-disable-next-line no-unused-vars
module.exports = function (options = {}) {
return async context => {
let result = context.result;
let app = context.app;
let idFiles = [];
let dates = [];
for(let i = 0; i < result.data.length; i++){
let element = result.data[i];
idFiles.push(element.id_archivo);
dates.push(element.compartido);
}
let files = [];
for(let j = 0; j < idFiles.length; j++){
let element = idFiles[j];
let file = await app.service('archivos').get(element);
file['compartido'] = dates[j];
files.push(file);
}
context.result = files;
return context;
};
};
| 29.814815 | 79 | 0.614907 |
401be5aa71dad01bc47eb9ab68abfe574de4126f | 1,724 | js | JavaScript | client/src/components/auth/authactions.js | RyleeAndrews/Total-Screen-Design-Manager-Front-End | 94659174d39ac741fca411eb06c10a6e147bb4ca | [
"MIT"
] | null | null | null | client/src/components/auth/authactions.js | RyleeAndrews/Total-Screen-Design-Manager-Front-End | 94659174d39ac741fca411eb06c10a6e147bb4ca | [
"MIT"
] | null | null | null | client/src/components/auth/authactions.js | RyleeAndrews/Total-Screen-Design-Manager-Front-End | 94659174d39ac741fca411eb06c10a6e147bb4ca | [
"MIT"
] | null | null | null |
'use strict';
import superagent from 'superagent';
import cookie from 'react-cookies';
export const authLogin = (user={}) => dispatch => {
let token = cookie.load("auth");
let authMethod = () => authenticateUsingBasic(user); // {}
if ( token ) { authMethod = () => authenticateUsingToken(token);}
return authMethod()
.then(res => {
dispatch(setUser(res.body));
return res;
})
.catch( e => console.error('Authenticaton Error:', e.message) );
};
let authenticateUsingToken = token => {
return superagent.get(`${__AUTH_URL__}/validate`)
.set('Authorization', 'Bearer ' + token);
};
let authenticateUsingBasic = user => {
return superagent.get(`${__AUTH_URL__}/login`)
.withCredentials()
.auth(user.username, user.password);
};
export const authCreateAccount = user => dispatch => {
return superagent.post(`${__AUTH_URL__}/create`)
.withCredentials()
.send(user)
.then(res => {
dispatch(setUser(res.body));
return res;
})
.catch( e => console.error('Authenticaton Error:', e.message) );
};
export const updateUser = payload => dispatch => {
let token = cookie.load('auth');
console.log('hol', payload);
let URL = `${__API_URL__}/auth/${payload._id}`;
superagent.put(URL)
.set('Authorization', "Bearer " + token)
.then( res => {
dispatch(updateUserAction(res.body));
console.log(res);
})
.catch( error => {
console.error(error.message);
})
};
export const authLogout = () => ({
type: "DELETE_AUTH_TOKEN",
});
export const setUser = auth => ({
type: "SET_AUTH_USER",
payload: auth
});
export const updateUserAction = auth => ({
type: 'UPDATE_USER',
payload: auth,
});
| 21.02439 | 68 | 0.62355 |
401c4120d8558b33a88f56aa101a341ceeb33a2e | 5,544 | js | JavaScript | imports/movies/ui/helpers/movies-create.js | andrewjrhill/kubrick | d333c24d5b64b2206919f99c0e11b8ca94d21d6c | [
"Apache-2.0"
] | 1 | 2018-05-03T13:04:09.000Z | 2018-05-03T13:04:09.000Z | imports/movies/ui/helpers/movies-create.js | andrewjrhill/kubrick | d333c24d5b64b2206919f99c0e11b8ca94d21d6c | [
"Apache-2.0"
] | 2 | 2019-08-06T08:08:09.000Z | 2021-05-09T11:02:51.000Z | imports/movies/ui/helpers/movies-create.js | andrewjrhill/kubrick | d333c24d5b64b2206919f99c0e11b8ca94d21d6c | [
"Apache-2.0"
] | null | null | null | import { _ } from 'meteor/underscore';
import { Template } from 'meteor/templating';
import { sAlert } from 'meteor/juliancwirko:s-alert';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { TheMovieDB } from '/imports/movies/api/TheMovieDB.js';
import { State } from '/imports/global/api/State.js';
import { Movies } from '/imports/movies/api/collection.js';
import '/imports/movies/ui/templates/movies-create.html';
// Called when an instance of this template is removed from the DOM and destroyed.
Template.moviesCreate.onCreated(() => {
// Clears all application state when landing on the "/movies" route
TheMovieDB.clearTMDBSearchResults();
State.clear.status();
State.clear.submissionData();
});
// Specifies helpers available to this template.
Template.moviesCreate.helpers({
/**
* Used by the template to retrieve data from the application
* state to be displayed on the view.
*/
querying: () => State.get.querying(),
submissionData: () => State.get.submissionData(),
creditsData: () => State.get.status() === 'getCreditsData',
/**
* Used by the template to show a list of the first five movie
* results returned by TheMovieDB.
*
* @return { Array } TheMovieDB movies data.
*/
tmdbSearchResults: () => {
const tmdbSearchResults = State.get.tmdbSearchResults();
if (tmdbSearchResults && !tmdbSearchResults) {
return;
}
const movies = tmdbSearchResults ? tmdbSearchResults.data.results : [];
return movies.slice(0, 5);
},
/**
* Used by the template to check if the form is in a state that
* will allow for a submission.
*
* @return { Boolean }
*/
disableSubmit: () => {
const submissionData = State.get.submissionData();
const status = State.get.status();
if (submissionData && submissionData.length === 0 || status === 'getCreditsData') {
return true;
}
return false;
},
});
// Specifies event handlers for this template.
Template.moviesCreate.events({
/**
* On keyup or focus, this event will fire the first call to search
* TheMovieDB for the string entered in the input field. This event is
* debounced to prevent excessive requests.
*/
'keyup .themoviedb input, focus .themoviedb input': _.debounce((event) => {
const searchString = event.currentTarget.value;
const whitespace = /\S/;
if (!(whitespace.test(searchString))) {
return TheMovieDB.clearTMDBSearchResults();
}
const searchURI = TheMovieDB.handleSearchURI(searchString);
TheMovieDB.searchTheMovieDB(searchURI);
}, 350),
/**
* On click, this event will make a call to get and set the raw and
* credits data from TheMovieDB to be used in our application.
*/
'click .search-results li'(event) {
const rawData = Template.currentData(event.currentTarget);
const creditsURI = TheMovieDB.handleCreditsURI(rawData.id);
TheMovieDB.setRawData(rawData);
TheMovieDB.getCreditsData(creditsURI);
TheMovieDB.clearTMDBSearchResults();
document.querySelector('.themoviedb input').value = rawData.title;
State.clear.status();
},
/**
* When changing the type select box, this event will add the selected
* movie to the array of movies we wish to add to our collection. It
* also does some basic validation and clears our inputs so the form
* may be reused.
*/
'change .type select': () => {
const title = document.querySelector('.themoviedb input');
const location = document.querySelector('.location input');
const type = document.querySelector('.type select');
const whitespace = /\S/;
if (!(whitespace.test(location.value))) {
location.value = 'Unknown';
}
TheMovieDB.addToSubmisionData(type.value, location.value);
[title, type, location].map(input => input.value = '');
},
/**
* On click, this will remove the movie item from the array of movies
* we wish to add to our collection.
*/
'click .remove': (event) => {
const submissionData = State.get.submissionData();
const targetData = Template.currentData(event.currentTarget);
const removalIndex = submissionData.findIndex(movie => movie.tmdb_id === targetData.tmdb_id);
const newSubmisionData = [
...submissionData.slice(0, removalIndex),
...submissionData.slice(removalIndex + 1),
];
return State.set.submissionData(newSubmisionData);
},
/**
* On submit, this event will map over the array of items we wish to
* add to our Mongo collection and insert them accordingly. We also
* notify our user of the addition here and redirect to the list view.
*/
'submit form': (event) => {
event.preventDefault();
const submissionData = State.get.submissionData();
submissionData.map((movie) => {
Movies.insert({ ...movie }, (error) => {
if (error) {
return sAlert.error(`There was an error adding ${submissionData[0].title} to your collection.`);
}
});
});
if (submissionData.length === 1) {
sAlert.success(`${submissionData[0].title} has been added to your collection.`);
} else {
sAlert.success('You have added several new movies to your collection.');
}
FlowRouter.go('/movies');
},
/**
* On click, this event will clear the array of movies we wish to add to
* our Mongo collection and will redirect us to the movies list view.
*/
'click .cancel': (event) => {
event.preventDefault();
State.clear.submissionData();
FlowRouter.go('/movies');
},
});
| 30.8 | 106 | 0.671717 |
401c9d7fa0f64057fee41165934b834354fde705 | 234 | js | JavaScript | src/Components/Input.js | MortezaMirjavadi/simple_graph_visualizer | 4e84c95aee7e822bdef097a09a76361db5a4ebbc | [
"MIT"
] | null | null | null | src/Components/Input.js | MortezaMirjavadi/simple_graph_visualizer | 4e84c95aee7e822bdef097a09a76361db5a4ebbc | [
"MIT"
] | null | null | null | src/Components/Input.js | MortezaMirjavadi/simple_graph_visualizer | 4e84c95aee7e822bdef097a09a76361db5a4ebbc | [
"MIT"
] | null | null | null | import React from "react";
export default ({ value, getInput, inputId }) => (
<div>
<textarea
value={value}
id={inputId}
onChange={(e) => getInput(e.target.value)}
className={"input"}
/>
</div>
);
| 18 | 50 | 0.551282 |
401e008a94929998c15ba7cd89f5dd4eaa54a935 | 4,767 | js | JavaScript | gulpfile.js | educandu/saml-test-app | 2106fcf2973f1e8a884888fd0222b46704409b2e | [
"MIT"
] | null | null | null | gulpfile.js | educandu/saml-test-app | 2106fcf2973f1e8a884888fd0222b46704409b2e | [
"MIT"
] | null | null | null | gulpfile.js | educandu/saml-test-app | 2106fcf2973f1e8a884888fd0222b46704409b2e | [
"MIT"
] | null | null | null | import url from 'url';
import del from 'del';
import gulp from 'gulp';
import log from 'fancy-log';
import mkdirp from 'mkdirp';
import selfsigned from 'selfsigned';
import { promises as fs } from 'fs';
import Graceful from 'node-graceful';
import { spawn } from 'child_process';
import { Docker } from 'docker-cli-js';
import { cleanEnv, str } from 'envalid';
import passportSaml from 'passport-saml';
const SamlStrategy = passportSaml.Strategy;
const TEST_WEBSITE_TUNNEL_IMAGE = 'educandu/inlets:1.0.0';
const TEST_WEBSITE_TUNNEL_CONTAINER_NAME = 'website-tunnel';
let server = null;
Graceful.on('exit', () => {
server?.kill();
});
const isMac = process.platform === 'darwin';
const containerCommandTimeoutMs = isMac ? 2000 : 1000;
const baseDir = url.fileURLToPath(new URL('./.tmp', import.meta.url).href);
const env = cleanEnv(process.env, {
TUNNEL_TOKEN: str(),
TUNNEL_WEBSITE_DOMAIN: str(),
IDP_NAME: str({ default: 'samltest' })
});
const runDockerCommand = async (command, waitMs = 0) => {
const result = await new Docker({ echo: false }).command(command);
await new Promise(resolve => setTimeout(resolve, waitMs));
return result;
};
const ensureContainerRunning = async ({ containerName, runArgs }) => {
const data = await runDockerCommand('ps -a');
const container = data.containerList.find(c => c.names === containerName);
if (!container) {
await runDockerCommand(`run --name ${containerName} ${runArgs}`, containerCommandTimeoutMs);
} else if (!container.status.startsWith('Up')) {
await runDockerCommand(`restart ${containerName}`, containerCommandTimeoutMs);
}
};
const ensureContainerRemoved = async ({ containerName }) => {
try {
await runDockerCommand(`rm -f ${containerName}`, containerCommandTimeoutMs);
} catch (err) {
if (!err.toString().includes('No such container')) {
throw err;
}
}
};
export async function clean() {
await del(['.tmp']);
}
export async function certificate() {
log('Generating new certificate for encryption')
const attrs = [{ name: 'commonName', value: env.TUNNEL_WEBSITE_DOMAIN }];
const pems = selfsigned.generate(attrs, { days: 3650 });
console.log(pems);
await mkdirp(baseDir);
await fs.writeFile(`${baseDir}/encrypt-${env.TUNNEL_WEBSITE_DOMAIN}.key`, pems.private, 'utf8');
await fs.writeFile(`${baseDir}/encrypt-${env.TUNNEL_WEBSITE_DOMAIN}.pub`, pems.public, 'utf8');
await fs.writeFile(`${baseDir}/encrypt-${env.TUNNEL_WEBSITE_DOMAIN}.cert`, pems.cert, 'utf8');
}
export async function metadata() {
const decryptionPvk = await fs.readFile(`${baseDir}/encrypt-${env.TUNNEL_WEBSITE_DOMAIN}.key`, 'utf8');
const cert = await fs.readFile(`${baseDir}/encrypt-${env.TUNNEL_WEBSITE_DOMAIN}.cert`, 'utf8');
const idPEntrypoint = (await fs.readFile(`./idps/${env.IDP_NAME}/entrypoint.txt`, 'utf8')).trim();
const idPCertificate = (await fs.readFile(`./idps/${env.IDP_NAME}/certificate.txt`, 'utf8')).trim();
const samlStrategy = new SamlStrategy({
callbackUrl: `https://${env.TUNNEL_WEBSITE_DOMAIN}/saml/login/callback`,
entryPoint: idPEntrypoint,
issuer: `https://${env.TUNNEL_WEBSITE_DOMAIN}`,
cert: idPCertificate,
decryptionPvk
}, () => {});
log('Generating new certificate for encryption')
const metadata = samlStrategy.generateServiceProviderMetadata(cert);
console.log(metadata);
await fs.writeFile(`${baseDir}/generated-metadata.xml`, metadata, 'utf8');
}
export async function startTunnel() {
const dockerLocalhost = isMac ? 'host.docker.internal' : 'localhost';
log('Opening tunnel connections');
await ensureContainerRunning({
containerName: TEST_WEBSITE_TUNNEL_CONTAINER_NAME,
runArgs: [
'-d',
'--net=host',
TEST_WEBSITE_TUNNEL_IMAGE,
'client',
`--token ${env.TUNNEL_TOKEN}`,
`--url=wss://${env.TUNNEL_WEBSITE_DOMAIN}`,
`--upstream=http://${dockerLocalhost}:3000`
].join(' ')
});
Graceful.on('exit', async () => {
log('Closing tunnel connections');
await Promise.all([
ensureContainerRemoved({ containerName: TEST_WEBSITE_TUNNEL_CONTAINER_NAME })
]);
});
}
function spawnServer() {
server = spawn(process.execPath, ['src/index.js', env.IDP_NAME], { env: { ...process.env }, stdio: 'inherit' });
server.once('exit', () => {
server = null;
});
}
export function startServer(done) {
spawnServer();
done();
}
export function restartServer(done) {
if (!server) {
startServer(done);
} else {
server.once('exit', () => {
startServer(done);
});
server.kill();
}
}
export function startWatching(done) {
gulp.watch(['src/**/*.js'], restartServer);
done();
}
export const watch = gulp.series(startTunnel, startServer, startWatching);
export default watch;
| 31.156863 | 114 | 0.685127 |
401e0df9d67c2bfb983fd54f7ade70d6f774e698 | 5,589 | js | JavaScript | react-app/src/pages/Houses/index.js | willtecti/mvp-cli-multas | e1ffee4f39489e0364040596c507cafa421c0155 | [
"CC0-1.0"
] | null | null | null | react-app/src/pages/Houses/index.js | willtecti/mvp-cli-multas | e1ffee4f39489e0364040596c507cafa421c0155 | [
"CC0-1.0"
] | 11 | 2021-05-10T23:56:11.000Z | 2022-03-26T01:10:25.000Z | react-app/src/pages/Houses/index.js | willtecti/mvp-cli-multas | e1ffee4f39489e0364040596c507cafa421c0155 | [
"CC0-1.0"
] | null | null | null | import React, { useState, useEffect, useRef } from "react";
import InternalTemplate from '../../templates/Internal'
import service from '../../services/api'
import MapBox from '../../containers/MapBox'
import Error from '../../components/Error'
import Loading from '../../components/Loading'
import {TOKEN} from '../../configs/MapBox'
import { getHousesAgended} from '../../services/houses'
const App = () =>{
const [config, setConfig] = useState(
{
bairro : 'centro',
preco: 1200,
quartos: 2,
vaga: 1}
)
const [houses, setHouses] = useState([])
const [error, setError] = useState('')
const targetRef = useRef();
const [dimensions, setDimensions] = useState({
width: 0,
height: 0,
});
const populateHouses = async () => {
const data = [
{ id : 1,
url: 'https://gonzagaimoveis.com.br/imovel/10091001/apartamento-1-quarto-horizonte-centro-curitiba/',
address: 'Rua Francisco Torres A, 581, Centro - Curitiba/Pr',
license_plate : "16/01/2020 09:00",
last_position: {
lat: -25.431059,
lng: -49.261382,
}
},
{ id : 2,
url:'https://pr.olx.com.br/regiao-de-curitiba-e-paranagua/imoveis/apartamento-1-dormitorio-centro-mobiliado-promocao-680245721',
address: 'R. Emiliano Perneta, 288',
license_plate : "16/01/2020 Não Marcado",
last_position: {
lat: -25.434566,
lng: -49.275062,
}
},
// { id : 4, // Muito Caro / Falta Mobilia
// url:'http://www.imobiliaria2000.com.br/imovel/?ref=02902.002-HAB',
// address: 'Avenida Marechal Floriano Peixoto 696, Centro, Curitiba - Paraná, 80001, Brazi',
// license_plate : "17/01/2020 Não Marcado",
// last_position: {
// lat: -25.436086,
// lng: -49.269517,
// }
// },
{ id : 5,
url:'http://www.imobiliaria2000.com.br/imovel/?ref=32181.003-GAL', //Não Tem mobilia
address: 'R CONSELHEIRO LAURINDO, 781 AP 1101 ',
license_plate : "17/01/2020 Não Marcado",
last_position: {
lat: -25.433645,
lng: -49.263375,
}
},
{ id : 6,
url:'http://www.imobiliaria2000.com.br/imovel/?ref=07007.001-FUT',
address: 'Rua Padre Anchieta, 2636-Ap. 706- Bl-A CEP: 80730000',
license_plate : "17/01/2020 Não Marcado",
last_position: {
lat: -25.4347,
lng: -49.3039,
}
},
{ id : 7,
url:'http://www.imobiliaria2000.com.br/imovel/?ref=02240.001-KON&imovel_id=',
address: 'Professor Guido Straube, 643 Apto 44 B CEP: 80320030',
license_plate : "17/01/2020 Não Marcado",
last_position: {
lat: -25.456497,
lng: -49.29503,
}
},
{ id : 8,
url:'http://www.imobiliaria2000.com.br/imovel/?ref=03941.002-RAZ&imovel_id=',
address: 'R BALTAZAR CARRASCO DOS REIS, 2032 AP 33 BL A CEP: 80230070',
license_plate : "17/01/2020 Não Marcado",
last_position: {
lat: -25.448988,
lng: -49.266409,
}
},
{ id : 9,
url:'http://www.imobiliaria2000.com.br/imovel/?ref=06493.001-FUT',
address: 'Rua Gonçalves Dias, 427 - Apto. 602 CEP: 80240340',
license_plate : "17/01/2020 Não Marcado",
last_position: {
lat: -25.446927,
lng: -49.295064,
}
},
{ id : 10,
url:'http://www.imobiliaria2000.com.br/imovel/?ref=02584.003-CIB&imovel_id=',
address: 'Rua Guilherme Pugsley, 1674 Apartamento 101 A CEP: 80620000',
license_plate : "17/01/2020 Não Marcado",
last_position: {
lat: -25.461349,
lng: -49.288323,
}
},
{ id : 11,
url:'https://www.quintoandar.com.br/imovel/892996069',
address: 'Rua Salustiano Cordeiro, Água Verde, Curitiba',
license_plate : "16/01/2020 16:00",
last_position: {
lat: -25.454977,
lng: -49.285958,
}
}
]
setHouses(data)
console.log('houses',houses)
}
useEffect( async () => {
populateHouses()
if (targetRef.current) {
setDimensions({
width: targetRef.current.offsetWidth,
height: targetRef.current.offsetHeight,
});
}
}, []);
return(
<InternalTemplate>
{ <MapBox parentDimensions={dimensions} cars={houses} /> }
</InternalTemplate>
)
}
export default App; | 33.872727 | 144 | 0.455359 |
401e17bd9c4e4ac9f7b195c11e0c6906b1000b69 | 2,326 | js | JavaScript | public/serviceworker.js | perepaul/forex | 77d9b737873ea766f007fb435f4121a548e03e2d | [
"MIT"
] | null | null | null | public/serviceworker.js | perepaul/forex | 77d9b737873ea766f007fb435f4121a548e03e2d | [
"MIT"
] | null | null | null | public/serviceworker.js | perepaul/forex | 77d9b737873ea766f007fb435f4121a548e03e2d | [
"MIT"
] | null | null | null | var staticCacheName = "pwa-v" + new Date().getTime();
var CACHE = 'cache-update-and-refresh';
var filesToCache = [
// '/about',
// '/faq',
// '/privacy',
// '/terms',
// '/login',
// '/register',
'/offline',
'/css/user/app.css',
'/js/user/app.js',
'/images/icons/icon-72x72.png',
'/images/icons/icon-96x96.png',
'/images/icons/icon-128x128.png',
'/images/icons/icon-144x144.png',
'/images/icons/icon-152x152.png',
'/images/icons/icon-192x192.png',
'/images/icons/icon-384x384.png',
'/images/icons/icon-512x512.png',
'https://code.jquery.com/jquery-3.6.0.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.4.0/js/iziToast.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.4.0/css/iziToast.min.css',
];
// Cache on install
self.addEventListener("install", event => {
this.skipWaiting();
event.waitUntil(
caches.open(CACHE)
.then(cache => {
return cache.addAll(filesToCache);
})
)
});
// Clear cache on activate
self.addEventListener('activate', event => {
// event.waitUntil(
// caches.keys().then(cacheNames => {
// return Promise.all(
// cacheNames
// .filter(cacheName => (cacheName.startsWith("pwa-")))
// .filter(cacheName => (cacheName !== staticCacheName))
// .map(cacheName => caches.delete(cacheName))
// );
// })
// );
});
// Serve from Cache
self.addEventListener("fetch", event => {
// Let the browser do its default thing
// for non-GET requests.
if (event.request.method != 'GET') return;
// Prevent the default, and handle the request ourselves.
event.respondWith(async function() {
// Try to get the response from a cache.
const cache = await caches.open(CACHE);
const cachedResponse = await caches.match(event.request);
if (cachedResponse) {
// If we found a match in the cache, return it, but also
// update the entry in the cache in the background.
event.waitUntil(cache.add(event.request));
return cachedResponse;
}
// If we didn't find a match in the cache, use the network.
return fetch(event.request).catch(()=>caches.match('offline'))
}());
});
| 29.820513 | 81 | 0.592863 |
401e53062501112eb7f5ac1230c1cf38e052b69f | 1,237 | js | JavaScript | js-test-suite/testsuite/8bc4ad88837b199dcab1c62f224ee41f.js | hao-wang/Montage | d1c98ec7dbe20d0449f0d02694930cf1f69a5cea | [
"MIT"
] | 16 | 2020-03-23T12:53:10.000Z | 2021-10-11T02:31:50.000Z | js-test-suite/testsuite/8bc4ad88837b199dcab1c62f224ee41f.js | hao-wang/Montage | d1c98ec7dbe20d0449f0d02694930cf1f69a5cea | [
"MIT"
] | null | null | null | js-test-suite/testsuite/8bc4ad88837b199dcab1c62f224ee41f.js | hao-wang/Montage | d1c98ec7dbe20d0449f0d02694930cf1f69a5cea | [
"MIT"
] | 1 | 2020-08-17T14:06:59.000Z | 2020-08-17T14:06:59.000Z | load("201224b0d1c296b45befd2285e95dd42.js");
function f(l, m) {
var a = NaN;
var b = 13;
var c = "test";
var d = undefined;
var e = null;
var f = 15.7;
var g = Math.fround(189777.111);
var h = "ABC";
var i = String.fromCharCode(65, 65, 65);
var j = {};
var k = Math.fround("".charCodeAt(15));
// Special case rigt here:
assertEq(a === a, false);
assertEq(a !== a, true);
assertEq(k === k, false);
assertEq(k !== k, true);
assertEq(l === l, false);
assertEq(l !== l, true);
assertEq(b === b, true);
assertEq(b !== b, false);
assertEq(c === c, true);
assertEq(c !== c, false);
assertEq(d === d, true);
assertEq(d !== d, false);
assertEq(e === e, true);
assertEq(e !== e, false);
assertEq(f === f, true);
assertEq(f !== f, false);
assertEq(g === g, true);
assertEq(g !== g, false);
assertEq(h === h, true);
assertEq(h !== h, false);
assertEq(i === i, true);
assertEq(i !== i, false);
assertEq(j === j, true);
assertEq(j !== j, false);
assertEq(m === m, true);
assertEq(m !== m, false);
}
function test() {
for (var i = 0; i < 100; i++)
f("".charCodeAt(15), 42);
}
test();
| 24.254902 | 44 | 0.506063 |
401ee1a3f0ee71c94f8c6302a1d47a02f57c3617 | 657 | js | JavaScript | src/actions/editProduct.js | meganthadev/stw-frontend | 449ab97d22c07d5a7007a743264ba17a3367d1ed | [
"Unlicense"
] | 1 | 2021-12-07T18:40:45.000Z | 2021-12-07T18:40:45.000Z | src/actions/editProduct.js | meganthadev/stw-frontend | 449ab97d22c07d5a7007a743264ba17a3367d1ed | [
"Unlicense"
] | null | null | null | src/actions/editProduct.js | meganthadev/stw-frontend | 449ab97d22c07d5a7007a743264ba17a3367d1ed | [
"Unlicense"
] | null | null | null |
export const editProduct = (data) => {
return (dispatch) => {
fetch(`http://localhost:3000/api/v1/products/${data.id}`, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
method: 'PATCH',
body: JSON.stringify(data)
})
.then(response => response.json())
.then(product => {
if (product.error) {
alert(product.error)
} else {
dispatch({ type: 'EDIT_PRODUCT', payload: product })
}
}
)
}
} | 28.565217 | 72 | 0.418569 |
401ee1fba2d4bc3a8e61398c5e4b30f3920dca6c | 1,441 | js | JavaScript | frontend/client/src/components/viewReservationsStaff/EditMealOrder.js | oSirhcel/SES10_eRestaurant | 2744792a2a21e2c1f035e7f9111b7e7771f5ea48 | [
"MIT"
] | null | null | null | frontend/client/src/components/viewReservationsStaff/EditMealOrder.js | oSirhcel/SES10_eRestaurant | 2744792a2a21e2c1f035e7f9111b7e7771f5ea48 | [
"MIT"
] | null | null | null | frontend/client/src/components/viewReservationsStaff/EditMealOrder.js | oSirhcel/SES10_eRestaurant | 2744792a2a21e2c1f035e7f9111b7e7771f5ea48 | [
"MIT"
] | null | null | null | import React from 'react';
import Grid from '@material-ui/core/Grid';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import ReservationDetailsForm from './ReservationDetailsForm';
import ReviewTable from '../createMealOrder/ReviewTable';
import MealOrderController from '../createMealOrder/MealOrderController';
import EditIcon from '@material-ui/icons/Edit';
import { format, isBefore } from 'date-fns';
const EditMealOrder = ({mealOrder, session, selectedDate}) => {
const [currentlyEditing, setEdit] = React.useState(false);
const handleEdit = () => {
setEdit(true);
}
const handleSubmit = (data) => {
setEdit(false);
console.log(data);
}
return (
<div>
<Button onClick = {handleEdit} disabled={isBefore(new Date(format(selectedDate, 'yyyy-MM-dd') ), new Date())}>
<EditIcon />
</Button>
{
currentlyEditing
? (
<MealOrderController
handleSubmitOrder = {handleSubmit}
session = {session}
currentOrder = {mealOrder}
/>
)
: (
<ReviewTable rows = {mealOrder} title = "Meal Order"/>
)
}
</div>
)
}
export default EditMealOrder; | 31.326087 | 122 | 0.5517 |
401f60d41cc58d4ce3a26058d353b9904adc1f71 | 8,600 | js | JavaScript | scripts/cheat-sheet.js | briwagner/briwagner.github.io | e5d3d3bf2700d5526d65ad6cb3d94004d18d56ca | [
"MIT"
] | null | null | null | scripts/cheat-sheet.js | briwagner/briwagner.github.io | e5d3d3bf2700d5526d65ad6cb3d94004d18d56ca | [
"MIT"
] | null | null | null | scripts/cheat-sheet.js | briwagner/briwagner.github.io | e5d3d3bf2700d5526d65ad6cb3d94004d18d56ca | [
"MIT"
] | null | null | null | var cheatSheet = [
{
title: "count {|obj| block }",
content: "Returns the number of items in enum through enumeration. If an argument is given, the number of items in enum that are equal to item are counted. If a block is given, it counts the number of elements yielding a true value.",
example: "ary = [1, 2, 4, 2] \nary.count #=> 4 \nary.count(2) #=> 2",
href: "#count",
name: "count",
},
{
title: "drop_while {|arr| block}",
content: "Drops elements up to, but not including, the first element for which the block returns nil or false and returns an array containing the remaining elements.",
example: "a = [1, 2, 3, 4, 5, 0] \na.drop_while { |i| i < 3 } #=> [3, 4, 5, 0]",
href: "#drop_while",
name: "drop_while"
},
{
title: "each_with_index(*args) {|obj, i| block}",
content: "Calls block with two arguments, the item and its index, for each item in enum. Given arguments are passed through to each().",
example: "hash.each_with_index { |item, index| hash[item] = index}\nhash #=> {'cat'=>0, 'dog'=>1, 'wombat'=>2}",
href: "#each_index",
name: "each_index",
},
{
title: "find(ifnone = nil) {|obj| block}",
content: "Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise. (AKA detect)",
example: "(1..100).find { |i| i % 5 == 0 and i % 7 == 0 } #=> 35",
href: "#find",
name: "find",
},
{
title: "find_all {|obj| block}",
content: "Returns an array containing all elements of enum for which the given block returns a true value. AKA select",
example: "(1..10).find_all { |i| i % 3 == 0 } #=> [3, 6, 9]",
href: "#find_all",
name: "find_all",
},
{
title: "find_index(value)",
content: "Compares each entry in enum with value or passes to block. Returns the index for the first for which the evaluated value is non-false. If no object matches, returns nil",
example: "(1..100).find_index(50) #=> 49\n(1..100).find_index { |i| i % 5 == 0 and i % 7 == 0 } #=> 34",
href: "#find_index",
name: "find_index",
},
{
title: "flat_map {|obj| block}",
content: "Returns a new array with the concatenated results of running block once for every element in enum.",
example: "[1, 2, 3, 4].flat_map { |e| [e, -e] } #=> [1, -1, 2, -2, 3, -3, 4, -4]",
href: "#flat_map",
name: "flat_map",
},
{
title: "inject(symb)",
content: "Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator. If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element. If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method. AKA reduce",
example: "(5..10).reduce(:+) #=> 45",
href: "#inject",
name: "inject",
},
{
title: "map",
content: "Returns a new array with the results of running block once for every element in enum.",
example: "(1..4).map { |i| i*i } #=> [1, 4, 9, 16]",
href: "#map",
name: "map",
},
{
title: "max",
content: "Returns the object in enum with the maximum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b. If max(n) then returns n number. Also min. Also minmax.",
example: "a.max(2) {|a, b| a.length <=> b.length } #=> ['albatross', 'horse']",
href: "#max",
name: "max",
},
{
title: "select",
content: "Returns an array containing all elements of enum for which the given block returns a true value. AKA find_all",
example: "[1,2,3,4,5].select { |num| num.even? } #=> [2, 4]",
href: "#select",
name: "select",
},
{
title: "sort",
content: "Returns an array containing the items in enum sorted, either according to their own <=> method, or by using the results of the supplied block. The block should return -1, 0, or +1 depending on the comparison between a and b. As of Ruby 1.8, the method Enumerable#sort_by implements a built-in Schwartzian Transform, useful when key computation or comparison is expensive.",
example: "(1..10).sort { |a, b| b <=> a } #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]",
href: "#sort",
name: "sort",
},
{
title: "take_while",
content: "Passes elements to the block until the block returns nil or false, then stops iterating and returns an array of all prior elements.",
example: "a.take_while { |i| i < 3 } #=> [1, 2]",
href: "#take_while",
name: "take_while",
},
{
title: "zip(arg...)",
content: "Takes one element from enum and merges corresponding elements from each args. This generates a sequence of n-element arrays, where n is one more than the count of arguments. The length of the resulting sequence will be enum#size. If the size of any argument is less than enum#size, nil values are supplied. If a block is given, it is invoked for each output array, otherwise an array of arrays is returned.",
example: "a = [ 4, 5, 6 ] \nb = [ 7, 8, 9 ]\n[1, 2, 3].zip(a, b) #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]",
href: "#zip",
name: "zip",
},{
title: "ARRAY collect",
content: "Creates a new array containing the values returned by the block.",
example: "a = [ 'a', 'b', 'c', 'd' ]\na.collect { |x| x + '!'' } #=> ['a!', 'b!', 'c!', 'd!']",
href: "#array_collect",
name: "array_collect",
},{
title: "ARRAY count(n)",
content: "Returns the number of elements. If an argument is given, counts the number of elements which equal obj using ==.",
example: "ary = [1, 2, 4, 2] \nary.count #=> 4\nary.count(2) #=> 2",
href: "#array_count",
name: "array_count",
},
{
title: "ARRAY flatten / flatten(level)",
content: "Returns a new array that is a one-dimensional flattening of self (recursively). That is, for every element that is an array, extract its elements into the new array.",
example: "a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]",
href: "#array_flatten",
name: "array_flatten"
},
{
title: "ARRAY include?(x)",
content: "Returns true if the given object is present in self (that is, if any element == object), otherwise returns false.",
example: "a = [ 'a', 'b', 'c' ] \na.include?('b') #=> true\na.include?('z') #=> false",
href: "#include",
name: "include",
},
{
title: "ARRAY join(optional separator)",
content: "Returns a string created by converting each element of the array to a string, separated by the given separator. If the separator is nil, it uses current $,. If both the separator and $, are nil, it uses empty string.",
example: "[ 'a', 'b', 'c' ].join('-') #=> 'a-b-c'",
href: "#join",
name: "join",
},
{
title: "ARRAY rassoc",
content: "Searches through the array whose elements are also arrays. Compares obj with the second element of each contained array using obj.==. Returns the first contained array that matches obj.",
example: "a = [ [ 1, \"one\"], [2, \"two\"], [3, \"three\"], [\"ii\", \"two\"] ]\na.rassoc(\"two\") #=> [2, \"two\"] \na.rassoc(\"four\") #=> nil",
href: "#rassoc",
name: "rassoc",
},
{
title: "shuffle",
content: "Returns a new array with elements of self shuffled.",
example: "a = [ 1, 2, 3 ] #=> [1, 2, 3]\na.shuffle #=> [2, 3, 1]\na #=> [1, 2, 3]",
href: "#shuffle",
name: "shuffle"
},
{
title: "slice",
content: "Element Reference — Returns the element at index, or returns a subarray starting at the start index and continuing for length elements, or returns a subarray specified by range of indices. Negative indices count backward from the end of the array (-1 is the last element). For start and range cases the starting index is just before an element. Additionally, an empty array is returned when the starting index for an element range is at the end of the array.",
example: "a = [ \"a\", \"b\", \"c\", \"d\", \"e\" ]\na[1, 2] #=> [ \"b\", \"c\" ]\na[1..3] #=> [ \"b\", \"c\", \"d\" ]",
href: "#slice",
name: "slice"
},
{
title: "to_a / to_ary / to_h / to_s",
content: "",
example: "[[:foo, :bar], [1, 2]].to_h\n # => {:foo => :bar, 1 => 2}",
href: "#to_a",
name: "to_a",
},
]; | 53.416149 | 534 | 0.610233 |
40201c5c1797b1a499803c7cb2e404cd6ed2430b | 1,150 | js | JavaScript | src/store.js | isratjahanen/chrome-event-countdown | ca0993c1756e1d27ad7004797c44961f1a34b4af | [
"MIT"
] | 1 | 2021-12-06T13:11:32.000Z | 2021-12-06T13:11:32.000Z | src/store.js | isratjahanen/chrome-event-countdown | ca0993c1756e1d27ad7004797c44961f1a34b4af | [
"MIT"
] | 7 | 2020-09-11T16:52:35.000Z | 2022-02-18T07:26:33.000Z | src/store.js | isratjahanen/chrome-event-countdown | ca0993c1756e1d27ad7004797c44961f1a34b4af | [
"MIT"
] | 1 | 2021-07-14T21:54:25.000Z | 2021-07-14T21:54:25.000Z | import Vue from 'vue';
import Vuex from 'vuex';
import { set } from '@/utils/storage';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
events: [],
},
mutations: {
ADD_EVENT(state, event) {
state.events.push(event);
},
REMOVE_EVENT(state, eventId) {
const index = state.events.findIndex((event) => event.eventId === eventId);
state.events.splice(index, 1);
},
SET_EVENTS(state, events) {
state.events = events;
},
UPDATE_EVENT(state, event) {
const eventIndex = state.events.findIndex((e) => e.eventId === event.eventId);
if (eventIndex > -1) {
state.events.splice(eventIndex, 1, event);
}
},
},
actions: {
setEvents({ commit }, events) {
commit('SET_EVENTS', events);
},
addEvent({ commit }, event) {
commit('ADD_EVENT', event);
},
removeEvent({ commit }, eventId) {
commit('REMOVE_EVENT', eventId);
},
syncEvents({ state }) {
set('events', state.events);
},
updateEvent({ commit }, event) {
commit('UPDATE_EVENT', event);
},
openAddEventModal() {},
},
});
| 19.491525 | 84 | 0.566087 |
402215e28b1de9619f9b9ae7fedd7221779a67d9 | 3,550 | js | JavaScript | chatty_server/server.js | jlum07/chatty-app | 188b9fa84be5b8f4828d8c3db0cca1ade77bf3fc | [
"MIT"
] | null | null | null | chatty_server/server.js | jlum07/chatty-app | 188b9fa84be5b8f4828d8c3db0cca1ade77bf3fc | [
"MIT"
] | null | null | null | chatty_server/server.js | jlum07/chatty-app | 188b9fa84be5b8f4828d8c3db0cca1ade77bf3fc | [
"MIT"
] | null | null | null | // server.js
const express = require('express');
const SocketServer = require('ws').Server;
const querystring = require('querystring');
const fetch = require('node-fetch');
const uuidv4 = require('uuid/v4');
// Set the port to 3001
const PORT = 3001;
// Create a new express server
const server = express()
// Make the express server serve static assets (html, javascript, css) from the /public folder
.use(express.static('public'))
.listen(PORT, '0.0.0.0', 'localhost', () => console.log(`Listening on ${ PORT }`));
// Create the WebSockets server
const wss = new SocketServer({ server });
// Variable to keep track of current users
let numUsers;
// Set up a callback that will run when a client connects to the server
// When a client connects they are assigned a socket, represented by
// the ws parameter in the callback.
wss.on('connection', (ws) => {
console.log('Client connected');
console.log("Current users online ", wss.clients.size);
numUsers = {
type: "userUpdate",
numUsers: wss.clients.size
};
wss.clients.forEach(function each(client) {
client.send(JSON.stringify(numUsers));
});
ws.on("message", function incoming(message) {
let data = JSON.parse(message);
// console.log(data);
switch (data.type) {
case "postMessage":
const newMessage = {
type: "incomingMessage",
id: uuidv4(),
username: data.username,
content: data.content
}
wss.clients.forEach(function each(client) {
client.send(JSON.stringify(newMessage));
});
// Query params for Dialogflow
let qs = querystring.stringify({
v: '20150910',
lang: 'en',
sessionId: '123456789',
timezone: 'America/New_York',
query: data.content
});
// Options and header auth key
let options = {
method: 'GET',
headers: {
Authorization: 'Bearer ae92ca0e4549496cb27e77e193b0116d'
}
}
// Fetch request to Dialogflow api
fetch(`https://api.dialogflow.com/v1/query?${qs}`, options)
.then(resp => { return resp.json() })
.then(json => {
// If response is successful
if (json.result.score == 1) {
// Creates new message from Df reply
let botMsg = {
type: "incomingMessage",
username: "Botty",
id: uuidv4(),
content: json.result.fulfillment.speech
};
// Sends out bot reply to clients
setTimeout(() => {
wss.clients.forEach(function each(client) {
client.send(JSON.stringify(botMsg));
});
}, 250);
}
});
break;
case "postNotification":
const newNotification = {
type: "incomingNotification",
id: uuidv4(),
content: data.content
}
wss.clients.forEach(function each(client) {
client.send(JSON.stringify(newNotification));
});
break;
}
});
// Set up a callback for when a client closes the socket. This usually means they closed their browser.
ws.on('close', () => {
console.log('Client disconnected')
numUsers = {
type: "userUpdate",
numUsers: wss.clients.size
};
wss.clients.forEach(function each(client) {
client.send(JSON.stringify(numUsers));
});
});
});
| 23.202614 | 105 | 0.567042 |
4022e2fa0d924db666934cda97f10276ace95c59 | 3,151 | js | JavaScript | gci-vci-react/src/helpers/provisional_helpers.js | ClinGen/gene-and-variant-curation-tools | 30f21d8f03d8b5c180c1ce3cb8401b5abc660080 | [
"MIT"
] | 1 | 2021-09-17T20:39:07.000Z | 2021-09-17T20:39:07.000Z | gci-vci-react/src/helpers/provisional_helpers.js | ClinGen/gene-and-variant-curation-tools | 30f21d8f03d8b5c180c1ce3cb8401b5abc660080 | [
"MIT"
] | 133 | 2021-08-29T17:24:26.000Z | 2022-03-25T17:24:31.000Z | gci-vci-react/src/helpers/provisional_helpers.js | ClinGen/gene-and-variant-curation-tools | 30f21d8f03d8b5c180c1ce3cb8401b5abc660080 | [
"MIT"
] | null | null | null |
export const individualScraper = (individuals, individualMatched) => {
if (individuals) {
individuals.forEach(individual => {
if (individual.proband === true && (individual.variantScores && individual.variantScores.length)) {
individualMatched.push(individual);
}
});
}
return individualMatched;
};
export const familyScraper = (user, families, curatorAffiliation, annotation, segregationCountCandidate, segregationCountExome, segregationPointsCandidate, segregationPointsExome, individualMatched) => {
// function for looping through family (of GDM or of group) and finding all relevent information needed for score calculations
// returns dictionary of relevant items that need to be updated within NewCalculation()
families.forEach(family => {
// get segregation of family, but only if it was made by user (may change later - MC)
if ((family.affiliation && curatorAffiliation && family.segregation && family.affiliation === curatorAffiliation)
|| (!family.affiliation && !curatorAffiliation && family.segregation && family.submitted_by.PK === user)) {
// get lod score of segregation of family
if (family.segregation.includeLodScoreInAggregateCalculation) {
if ("lodPublished" in family.segregation && family.segregation.lodPublished === true && family.segregation.publishedLodScore) {
if (family.segregation.sequencingMethod === 'Candidate gene sequencing') {
segregationCountCandidate += 1;
segregationPointsCandidate += family.segregation.publishedLodScore;
} else if (family.segregation.sequencingMethod === 'Exome/genome or all genes sequenced in linkage region') {
segregationCountExome += 1;
segregationPointsExome += family.segregation.publishedLodScore;
}
} else if ("lodPublished" in family.segregation && family.segregation.lodPublished === false && family.segregation.estimatedLodScore) {
if (family.segregation.sequencingMethod === 'Candidate gene sequencing') {
segregationCountCandidate += 1;
segregationPointsCandidate += family.segregation.estimatedLodScore;
} else if (family.segregation.sequencingMethod === 'Exome/genome or all genes sequenced in linkage region') {
segregationCountExome += 1;
segregationPointsExome += family.segregation.estimatedLodScore;
}
}
}
}
// get proband individuals of family
if (family.individualIncluded && family.individualIncluded.length) {
individualMatched = individualScraper(family.individualIncluded, individualMatched);
}
});
return {
segregationCountCandidate: segregationCountCandidate,
segregationCountExome: segregationCountExome,
segregationPointsCandidate: segregationPointsCandidate,
segregationPointsExome: segregationPointsExome,
individualMatched: individualMatched
};
};
| 57.290909 | 203 | 0.671533 |
402363cfad6ef49bd87ba8aa3e3fa36fe2f52733 | 552 | js | JavaScript | lib/commands.js | chunaft/sms-gaming | 8850620c879b24972f7069659268998e0629e505 | [
"MIT"
] | null | null | null | lib/commands.js | chunaft/sms-gaming | 8850620c879b24972f7069659268998e0629e505 | [
"MIT"
] | null | null | null | lib/commands.js | chunaft/sms-gaming | 8850620c879b24972f7069659268998e0629e505 | [
"MIT"
] | null | null | null | // const {
// singlePlayerWelcomeMsg,
// } = require('./messages');
// /**
// * Activates conversation mode
// * @param {("single-player" | "multi-player")} mode mode to activate
// * @param {Express.Request} req express request object
// * @returns {String} activated mode
// */
// async function activateMode(mode, req) {
// // const modes = ['single-player', 'multi-player'];
// req.user.mode = mode;
// await req.saveUserSession(req.user);
// return 'single-player';
// }
// module.exports = {
// singlePlayerCommands,
// };
| 22.08 | 71 | 0.619565 |
40238184d608b6352c2b1ac73b7f90e8283f4d0b | 334 | js | JavaScript | lib/plugins/fallback.js | marek-saji/suchbot | e5a5af48d0a7bd6722cb1f72f779efb14ebf82f0 | [
"MIT"
] | null | null | null | lib/plugins/fallback.js | marek-saji/suchbot | e5a5af48d0a7bd6722cb1f72f779efb14ebf82f0 | [
"MIT"
] | 55 | 2015-10-15T07:36:00.000Z | 2020-07-19T16:56:40.000Z | lib/plugins/fallback.js | marek-saji/suchbot | e5a5af48d0a7bd6722cb1f72f779efb14ebf82f0 | [
"MIT"
] | null | null | null | const answers = [
'what?',
'Does not compute',
'lol, dunno',
'I have no idea what you mean by that'
];
function onMessage (event)
{
event.respond(answers);
return true;
}
function register (backend)
{
backend.eventEmitter.on('directedmessage', onMessage);
}
module.exports = {
register: register
};
| 15.181818 | 58 | 0.640719 |
402517e8974fe44cf6fb53b47dba94de8d51344b | 509 | js | JavaScript | client/src/dictionary.js | oxctdev/anet | 434523b1b9b6987ea769704b503d0f81ddfe19e5 | [
"MIT"
] | 26 | 2017-04-24T18:04:20.000Z | 2020-10-10T10:39:32.000Z | client/src/dictionary.js | oxctdev/anet | 434523b1b9b6987ea769704b503d0f81ddfe19e5 | [
"MIT"
] | 12 | 2017-04-24T17:55:35.000Z | 2017-11-27T13:39:11.000Z | client/src/dictionary.js | oxctdev/anet | 434523b1b9b6987ea769704b503d0f81ddfe19e5 | [
"MIT"
] | 35 | 2017-05-26T22:44:48.000Z | 2022-03-30T00:49:38.000Z |
function Dictionary() {
this._dictionary = {}
this.lookup = function(key, scope = {}) {
let dictEntry = this._dictionary[key] || ""
//Replace each replacement key based on the 'with' object.
if (typeof dictEntry === 'string') {
Object.keys(scope).forEach(key =>
dictEntry = dictEntry.replace('%{' + key + '}', scope[key])
)
}
return dictEntry
}
this.setDictionary = function(newDict) {
this._dictionary = newDict
}
}
let instance = new Dictionary()
export default instance
| 18.178571 | 63 | 0.652259 |
40251a397ac67de61e4b95c35dea0595bca40488 | 137 | js | JavaScript | frontend/src/pages/Details/styles.js | matheussantiago12/CompaniesSolution | f7cfdb49a09f77688ea986ba35f958587cbf3712 | [
"PHP-3.0",
"PHP-3.01",
"IJG",
"Zend-2.0"
] | 4 | 2020-06-19T16:35:39.000Z | 2021-04-14T21:34:04.000Z | frontend/src/pages/Details/styles.js | matheussantiago12/CompaniesSolution | f7cfdb49a09f77688ea986ba35f958587cbf3712 | [
"PHP-3.0",
"PHP-3.01",
"IJG",
"Zend-2.0"
] | 1 | 2021-02-02T16:29:01.000Z | 2021-02-02T16:29:01.000Z | frontend/src/pages/Details/styles.js | matheussantiago12/CompaniesSolution | f7cfdb49a09f77688ea986ba35f958587cbf3712 | [
"PHP-3.0",
"PHP-3.01",
"IJG",
"Zend-2.0"
] | null | null | null | import styled from 'styled-components';
export const Container = styled.div`
width: 80%;
padding: 50px 0;
margin: 0 auto;
`; | 19.571429 | 39 | 0.664234 |
4025b38ac55928cdcddb56ff3ba88ec4375bd628 | 1,013 | js | JavaScript | routes/api/super_user.js | narendraiiitl/Hostel-Managment-Portal | aa71be965bd41c38c41ccd90f979142f51c89527 | [
"MIT"
] | null | null | null | routes/api/super_user.js | narendraiiitl/Hostel-Managment-Portal | aa71be965bd41c38c41ccd90f979142f51c89527 | [
"MIT"
] | null | null | null | routes/api/super_user.js | narendraiiitl/Hostel-Managment-Portal | aa71be965bd41c38c41ccd90f979142f51c89527 | [
"MIT"
] | null | null | null | const express = require("express");
const bodyParser = require("body-parser");
const auth = require("../../middleware/authsuperuser");
const Admin = require("../../models/Admin");
const { reset } = require("nodemon");
const router = express.Router();
router.use(bodyParser.urlencoded({ extended: true }));
router.get("/dashboard",auth,async (req,res)=>{
Admin.find({},(err,admins)=>{
res.render("super_user",{currentUser:req.user,clientType:req.session.client,admins:admins});
});
});
router.post("/dashboard",auth,async(req,res)=>{
Admin.create(req.body.mains,(err,admin)=>{
if(err){
res.redirect("/superuser/dashboard");
}else{
res.redirect("/superuser/dashboard");
}
});
});
router.get("/remove/:email",auth,async (req,res)=>{
Admin.deleteOne({email:req.params.email},(err,admin)=>{
if(err){
res.redirect("/superuser/dashboard");
}else{
res.redirect("/superuser/dashboard");
}
});
});
module.exports = router; | 28.138889 | 98 | 0.625864 |
4025ebad37ef7bce70463b028b39cd630556ed5d | 931 | js | JavaScript | index.js | dutake/Shake | 3bb7eaaf27ab14b3a5f868af99c7b2132d5a5ef5 | [
"MIT"
] | 1 | 2020-12-05T03:16:17.000Z | 2020-12-05T03:16:17.000Z | index.js | dutake/Shake | 3bb7eaaf27ab14b3a5f868af99c7b2132d5a5ef5 | [
"MIT"
] | 1 | 2022-01-14T03:32:19.000Z | 2022-01-14T03:32:19.000Z | index.js | dutake/Shake | 3bb7eaaf27ab14b3a5f868af99c7b2132d5a5ef5 | [
"MIT"
] | 1 | 2020-11-28T02:49:06.000Z | 2020-11-28T02:49:06.000Z | const { Plugin } = require('powercord/entities');
module.exports = class Shake extends Plugin {
startPlugin() {
powercord.api.commands.registerCommand({
command: 'shake',
description: 'Shakes your screen',
usage: '{c} <time in seconds>',
executor: async (args) => {
this.generateShake(args);
return;
},
autocomplete: (args) => {
if (args[1] === void 0) {
return {
commands: [{
command: "Enter how long you want the screen to shake for",
instruction: true,
}],
};
}
}
});
}
pluginWillUnload() {
powercord.api.commands.unregisterCommand('shake');
}
generateShake(args) {
//thanks to Juby210 for helping me find this module
require('powercord/webpack').getModule(['ComponentDispatch'], false).ComponentDispatch.dispatch('SHAKE_APP', {
duration: args.length && !isNaN(parseInt(args[0])) ? args[0] * 1000 : 200,
intensity: 2
});
}
};
| 23.871795 | 112 | 0.626208 |
4026184cd6cd09999d00c96e14e1a0b92f4edaef | 13,657 | js | JavaScript | test/test-mongo.js | alexander34ro/chimera-framework-file-support | b8c7ed46ad1ed9e90d9c4b6cd43cfd57c018f95e | [
"MIT"
] | 11 | 2017-09-17T15:02:48.000Z | 2021-12-18T16:21:12.000Z | test/test-mongo.js | goFrendiAsgard/chimera | cfa0c98af685de8696e30f507eba66a72e684b66 | [
"MIT"
] | 1 | 2018-03-21T08:20:42.000Z | 2018-03-23T06:44:16.000Z | test/test-mongo.js | goFrendiAsgard/chimera | cfa0c98af685de8696e30f507eba66a72e684b66 | [
"MIT"
] | 11 | 2017-09-23T01:26:57.000Z | 2021-07-18T15:31:30.000Z | /* eslint-env mocha */
const chai = require('chai')
const assert = chai.assert
const chimera = require('../index.js')
const mongo = chimera.mongo
let softDb = mongo.db('mongodb://localhost/test')
let hardDb = mongo.db('mongodb://localhost/test', {excludeDeleted: false, showHistory: true})
let softGod = mongo.collection(softDb, 'gods')
let hardGod = mongo.collection(hardDb, 'gods')
function closeAll () {
hardDb.close()
softDb.close()
}
describe('mongo', function () {
it('should be able to insert single data', function (done) {
softGod.insert({name: 'Odin', mythology: 'Nordic', power: 6000}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result.name, 'Odin')
return done()
})
})
it('should be able to insert multiple', function (done) {
softGod.insert([{name: 'Tyr', mythology: 'Nordic', power: 4000}, {name: 'Posseidon', mythology: 'Greek', power: 3000}, {name: 'Zeus', mythology: 'Greek', power: 7000}], function (error, result) {
if (error) {
return done(error)
}
assert.equal(result.length, 3)
return done()
})
})
it('should be able to update', function (done) {
softGod.update({name: 'Tyr'}, {name: 'Thor'}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result.n, 1)
return done()
})
})
it('should be able to soft remove', function (done) {
softGod.softRemove({name: 'Posseidon'}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result.n, 1)
return done()
})
})
it('should be able to find (excluding the soft deleted)', function (done) {
softGod.find({}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result.length, 3)
return done()
})
})
it('should be able to find (including the soft deleted)', function (done) {
hardGod.find({}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result.length, 4)
return done()
})
})
it('should be able to count (excluding the soft deleted)', function (done) {
softGod.count({}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 3)
return done()
})
})
it('should be able to count (including the soft deleted)', function (done) {
hardGod.count({}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 4)
return done()
})
})
it('should be able to aggregate (excluding the soft deleted)', function (done) {
softGod.aggregate([{'$group': {'_id': 'count', 'count': {'$sum': 1}}}], function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, [{'_id': 'count', 'count': 3}])
return done()
})
})
it('should be able to aggregate (including the soft deleted)', function (done) {
hardGod.aggregate([{'$group': {'_id': 'count', 'count': {'$sum': 1}}}], function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, [{'_id': 'count', 'count': 4}])
return done()
})
})
it('should be able to sum (excluding the soft deleted)', function (done) {
softGod.sum('power', function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 17000)
return done()
})
})
it('should be able to sum with filter (excluding the soft deleted)', function (done) {
softGod.sum('power', {'mythology': 'Greek'}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 7000)
return done()
})
})
it('should be able to sum with groupBy (excluding the soft deleted)', function (done) {
softGod.sum('power', {}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Nordic': 10000, 'Greek': 7000})
return done()
})
})
it('should be able to sum with filter and groupBy (excluding the soft deleted)', function (done) {
softGod.sum('power', {'mythology': 'Greek'}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Greek': 7000})
return done()
})
})
it('should be able to sum (including the soft deleted)', function (done) {
hardGod.sum('power', function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 20000)
return done()
})
})
it('should be able to sum with filter (including the soft deleted)', function (done) {
hardGod.sum('power', {'mythology': 'Greek'}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 10000)
return done()
})
})
it('should be able to sum with groupBy (including the soft deleted)', function (done) {
hardGod.sum('power', {}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Nordic': 10000, 'Greek': 10000})
return done()
})
})
it('should be able to sum with filter and groupBy (including the soft deleted)', function (done) {
hardGod.sum('power', {'mythology': 'Greek'}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Greek': 10000})
return done()
})
})
it('should be able to avg (excluding the soft deleted)', function (done) {
softGod.avg('power', function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 5666.666666666667)
return done()
})
})
it('should be able to avg with filter (excluding the soft deleted)', function (done) {
softGod.avg('power', {'mythology': 'Greek'}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 7000)
return done()
})
})
it('should be able to avg with groupBy (excluding the soft deleted)', function (done) {
softGod.avg('power', {}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Nordic': 5000, 'Greek': 7000})
return done()
})
})
it('should be able to avg with filter and groupBy (excluding the soft deleted)', function (done) {
softGod.avg('power', {'mythology': 'Greek'}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Greek': 7000})
return done()
})
})
it('should be able to avg (including the soft deleted)', function (done) {
hardGod.avg('power', function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 5000)
return done()
})
})
it('should be able to avg with filter (including the soft deleted)', function (done) {
hardGod.avg('power', {'mythology': 'Greek'}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 5000)
return done()
})
})
it('should be able to avg with groupBy (including the soft deleted)', function (done) {
hardGod.avg('power', {}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Nordic': 5000, 'Greek': 5000})
return done()
})
})
it('should be able to avg with filter and groupBy (including the soft deleted)', function (done) {
hardGod.avg('power', {'mythology': 'Greek'}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Greek': 5000})
return done()
})
})
it('should be able to min (excluding the soft deleted)', function (done) {
softGod.min('power', function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 4000)
return done()
})
})
it('should be able to min with filter (excluding the soft deleted)', function (done) {
softGod.min('power', {'mythology': 'Greek'}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 7000)
return done()
})
})
it('should be able to min with groupBy (excluding the soft deleted)', function (done) {
softGod.min('power', {}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Nordic': 4000, 'Greek': 7000})
return done()
})
})
it('should be able to min with filter and groupBy (excluding the soft deleted)', function (done) {
softGod.min('power', {'mythology': 'Greek'}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Greek': 7000})
return done()
})
})
it('should be able to min (including the soft deleted)', function (done) {
hardGod.min('power', function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 3000)
return done()
})
})
it('should be able to min with filter (including the soft deleted)', function (done) {
hardGod.min('power', {'mythology': 'Greek'}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 3000)
return done()
})
})
it('should be able to min with groupBy (including the soft deleted)', function (done) {
hardGod.min('power', {}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Nordic': 4000, 'Greek': 3000})
return done()
})
})
it('should be able to min with filter and groupBy (including the soft deleted)', function (done) {
hardGod.min('power', {'mythology': 'Greek'}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Greek': 3000})
return done()
})
})
it('should be able to max (excluding the soft deleted)', function (done) {
softGod.max('power', function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 7000)
return done()
})
})
it('should be able to max with filter (excluding the soft deleted)', function (done) {
softGod.max('power', {'mythology': 'Greek'}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 7000)
return done()
})
})
it('should be able to max with groupBy (excluding the soft deleted)', function (done) {
softGod.max('power', {}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Nordic': 6000, 'Greek': 7000})
return done()
})
})
it('should be able to max with filter and groupBy (excluding the soft deleted)', function (done) {
softGod.max('power', {'mythology': 'Greek'}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Greek': 7000})
return done()
})
})
it('should be able to max (including the soft deleted)', function (done) {
hardGod.max('power', function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 7000)
return done()
})
})
it('should be able to max with filter (including the soft deleted)', function (done) {
hardGod.max('power', {'mythology': 'Greek'}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result, 7000)
return done()
})
})
it('should be able to max with groupBy (including the soft deleted)', function (done) {
hardGod.max('power', {}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Nordic': 6000, 'Greek': 7000})
return done()
})
})
it('should be able to max with filter and groupBy (including the soft deleted)', function (done) {
hardGod.max('power', {'mythology': 'Greek'}, 'mythology', function (error, result) {
if (error) {
return done(error)
}
assert.deepEqual(result, {'Greek': 7000})
return done()
})
})
it('should be able to find (excluding the soft deleted, via execute)', function (done) {
mongo.execute({'mongoUrl': 'mongodb://localhost/test', 'collectionName': 'gods'}, 'find', {}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result.length, 3)
return done()
})
})
it('should be able to find (excluding the soft deleted, via $.mongoExecute)', function (done) {
chimera.coreDollar.mongoExecute({'mongoUrl': 'mongodb://localhost/test', 'collectionName': 'gods'}, 'find', {}, function (error, result) {
if (error) {
return done(error)
}
assert.equal(result.length, 3)
return done()
})
})
it('should be able to remove all record', function (done) {
hardGod.remove({}, function (error, result) {
if (error) {
closeAll()
return done(error)
}
assert.equal(result.result.n, 4)
closeAll()
return done()
})
})
})
| 28.995754 | 199 | 0.582119 |
40264ed74fda081a8bbfa2f11f429f9ea595cbb4 | 4,908 | js | JavaScript | DotVPN-2018/js/proxy.js | akalankauk/Cracked-Chrome-Extensions | 2b6e0791b0baa804d9d0a6c69115c67d1719f654 | [
"MIT"
] | 12 | 2018-03-15T22:42:16.000Z | 2021-07-12T04:56:48.000Z | DotVPN-2018/js/proxy.js | PraneethMadush/Cracked-Chrome-Extensions | 2b6e0791b0baa804d9d0a6c69115c67d1719f654 | [
"MIT"
] | 1 | 2019-03-02T15:20:13.000Z | 2021-02-27T02:36:12.000Z | DotVPN-2018/js/proxy.js | akalankauk/Cracked-Chrome-Extensions | 2b6e0791b0baa804d9d0a6c69115c67d1719f654 | [
"MIT"
] | 10 | 2018-03-17T15:44:45.000Z | 2021-12-14T15:55:01.000Z | /**
* Controls the state of the current proxy being used by Chrome.
*
* @constructor
*/
ProxyController = function()
{
// Global status that states if the custom proxy is set.
//this.proxyStatus = false;
// Listen on Proxy Errors.
chrome.proxy.onProxyError.addListener(this.onProxyError.bind(this));
};
ProxyController.prototype.init = function(email, password)
{
this.email = email;
this.password = password;
chrome.webRequest.onAuthRequired.addListener(this.handleAuthRequest.bind(this),
{urls: ['<all_urls>']}, ['asyncBlocking']);
};
/**
* To know the status when the custom proxy server is active or online.
*
* @returns {boolean} true is custom proxy is set and active.
*/
ProxyController.prototype.handleAuthRequest = function(details, callback)
{
if (details.isProxy) {
callback({authCredentials: {username: this.email,
password: this.password}});
} else {
callback();
}
};
/**
* Notifies about proxy errors.
*
* @parm {Object} details Gives the state of the error.
*/
ProxyController.prototype.onProxyError = function(details)
{
//chrome.browserAction.setIcon({ path: ProxyController.ERROR_ICON });
//chrome.browserAction.setTitle({title: details.error});
};
/**
* Sets the current proxy server.
*
* @param {boolean} status_ True to turn it on, otherwise use the auto_detect
* option to bring it back to normal.
*/
ProxyController.prototype.setProxyEnabled = function (status_)
{
if (status_) {
var config = {
mode: 'pac_script',
pacScript: {
data: "\
var d = true; \
var it = " + ((new Date().getTime()) / 1000 + 4) + "; \
var t = (new Date().getTime()) / 1000 + 4; \
\
function FindProxyForURL(url, host) { \
/*if (d) { \
if ((new Date().getTime()) / 1000 > t || \
(new Date().getTime()) / 1000 < it) { \
d = false; \
} else { \
return 'DIRECT'; \
} \
}*/ \
\
host = host.toLowerCase(); " +
'IPNotation = /^\\d+\\.\\d+\\.\\d+\\.\\d+$/g;' + " \
\
if (isPlainHostName(host)) { \
return 'DIRECT'; \
} \
\
var reservedNets = [ \
'0.*.*.*', /* 0.0.0.0/8 */ \
'10.*.*.*', /* 10.0.0.0/8 */ \
'127.*.*.*', /* 127.0.0.0/8 */ \
'169.254.*.*', /* 169.254.0.0/16 */ \
'172.1[6-9].*.*', /* 172.16.0.0/12 */ \
'172.2[0-9].*.*', /* 172.16.0.0/12 */ \
'172.3[0-1].*.*', /* 172.16.0.0/12 */ \
'192.0.0.*', /* 192.0.0.0/24 */ \
'192.0.2.*', /* 192.0.2.0/24 */ \
'192.168.*.*', /* 192.168.0.0/16 */ \
'198.1[8-9].*.*', /* 198.18.0.0/15 */ \
'198.51.100.*', /* 198.51.100.0/24 */ \
'203.0.113.*', /* 203.0.113.0/24 */ \
'22[4-9].*.*.*', /* 224.0.0.0/4 */ \
'23[0-9].*.*.*', /* 224.0.0.0/4 */ \
]; \
\
if (IPNotation.test(host)) { \
for (i = 0; i < reservedNets.length; i++) { \
if (shExpMatch(host, reservedNets[i])) { \
return 'DIRECT'; \
} \
}; \
} \
\
var direct = [ \
'local', 'intra', 'intranet', 'dev' \
]; \
for (var i = 0; i < direct.length; i++) { \
if (dnsDomainIs(host, direct[i])) { \
return 'DIRECT'; \
} \
} \
\
if (dnsDomainIs(host, 'apache-iv.com')) { \
return 'DIRECT'; \
} \
\
if (dnsDomainIs(host, 'api.apohola.com')) { \
return 'DIRECT'; \
} \
\
return 'HTTPS " + settings.nodes[settings.location] + ":443; HTTPS " +
settings.backupNodes[settings.location] + ":443'; }"
}
};
//console.log(settings.node);
} else {
var config = {
mode: 'direct'
};
//chrome.webRequest.onAuthRequired.removeListener(this.handleAuthRequest);
}
// Describes the current proxy setting being used.
var proxySettings = {
'value': config,
'scope': /*settings.incognito ? 'incognito_persistent' :*/ 'regular'
};
// Change the icon to reflect the current status of the proxy server.
//var icon =
// Clear settings for both windows.
//chrome.proxy.settings.clear({scope : 'incognito_persistent'});
//chrome.proxy.settings.clear({scope : 'regular'});
// Setup new settings for the appropriate window.
chrome.proxy.settings.set(proxySettings, function() {});
}; | 31.664516 | 84 | 0.47555 |
4026b69678f52957204b6c7cfdf2bfb74ecd4a59 | 3,415 | js | JavaScript | admin/conferences/conferences.committee.js | ejgr-mtsiw/mini-proj2 | be447d1d1d8baab89e1befadfe50660bd55903cf | [
"MIT"
] | null | null | null | admin/conferences/conferences.committee.js | ejgr-mtsiw/mini-proj2 | be447d1d1d8baab89e1befadfe50660bd55903cf | [
"MIT"
] | null | null | null | admin/conferences/conferences.committee.js | ejgr-mtsiw/mini-proj2 | be447d1d1d8baab89e1befadfe50660bd55903cf | [
"MIT"
] | null | null | null | // References to HTML objects
const tblCommittee = document.getElementById("tblCommittee");
const tabCommittee = document.getElementById("nav-committee-tab");
const renderCommittee = async (idConference, conferenceName, urlBase) => {
let strHtml = `
<thead >
<tr><th class='w-100 text-center bg-warning' colspan='5'>Membros do Comité Científico da Conferência ${conferenceName}</th></tr>
<tr class='bg-info'>
<th>#</th>
<th>Nome</th>
<th>Email</th>
<th>Instituição</th>
<th class="text-right">Participa</th>
</tr>
</thead><tbody>
`;
const response = await fetch(`${urlBase}/committee/conference/${idConference}`);
const members = await response.json();
let i = 1;
for (const member of members) {
let checked = '';
if (member.conferences && member.conferences.length > 0) {
checked = 'checked="checked"';
}
strHtml += `
<tr>
<td>${i}</td>
<td>${member.nome}</td>
<td>${member.email}</td>
<td>${member.instituicao}</td>
<td class="text-right">
<input type="checkbox" id='committeemember-${member.idCommitteeMember}' idcommitteemember='${member.idCommitteeMember}' ${checked} class='member-goes'>
</td>
</tr>
`;
i++;
}
strHtml += "</tbody>";
tblCommittee.innerHTML = strHtml;
// Gerir a participação do orador
const chkMemberGoes = document.getElementsByClassName("member-goes");
for (let i = 0; i < chkMemberGoes.length; i++) {
chkMemberGoes[i].addEventListener("click", function () {
let idCommitteeMember = this.getAttribute('idcommitteemember');
// Add / remove speaker from the conference
if (this.checked) {
fetch(`${urlBase}/conferences/${idConference}/committee/${idCommitteeMember}`, {
method: "PUT"
}).catch((error) => {
Swal.fire({
title: 'Erro!',
text: error,
icon: 'error',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Fechar'
});
});
} else {
fetch(`${urlBase}/conferences/${idConference}/committee/${idCommitteeMember}`, {
method: "DELETE"
}).catch((error) => {
Swal.fire({
title: 'Erro!',
text: error,
icon: 'error',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Fechar'
});
});
}
});
}
enableTab();
}
function enableTab() {
// Enables committee tab link
tabCommittee.classList.remove('disabled');
}
function disableTab() {
// Disables committee tab link
tabCommittee.classList.add('disabled');
}
export { renderCommittee, enableTab, disableTab };
| 35.572917 | 175 | 0.482284 |
4026e230fbe9406af5462695d438c97f58dc932d | 134 | js | JavaScript | vite-with-bws/main.js | idlist/issue-repros | c82b5b9e2aa8cc8991e46dd96e7c96c3e9d0faed | [
"MIT"
] | null | null | null | vite-with-bws/main.js | idlist/issue-repros | c82b5b9e2aa8cc8991e46dd96e7c96c3e9d0faed | [
"MIT"
] | null | null | null | vite-with-bws/main.js | idlist/issue-repros | c82b5b9e2aa8cc8991e46dd96e7c96c3e9d0faed | [
"MIT"
] | null | null | null | import { KeepLiveWS } from 'bilibili-live-ws'
new KeepLiveWS(5082)
document.querySelector('#root').innerHTML = `
<p>我加载出来了!</p>
`
| 16.75 | 45 | 0.69403 |
402762de443769ff47d4653f17182c3e7f95826b | 259 | js | JavaScript | public/src/js/comments.js | Shupscom/Developer-Digest | e02f076d74f77a9109fc93af05b4e0ae6ce62c27 | [
"MIT"
] | null | null | null | public/src/js/comments.js | Shupscom/Developer-Digest | e02f076d74f77a9109fc93af05b4e0ae6ce62c27 | [
"MIT"
] | null | null | null | public/src/js/comments.js | Shupscom/Developer-Digest | e02f076d74f77a9109fc93af05b4e0ae6ce62c27 | [
"MIT"
] | null | null | null | /**
* Created by BJ on 20/09/2016.
*/
$(document).ready(function(){
$('.delete').on('click',function(event){
event.preventDefault();
bootbox.confirm('Are you sure',function(){
});
});
function deleteComment(){
}
});
| 16.1875 | 49 | 0.540541 |
40276351fde1068c87f6ea0e21581312a452f8c2 | 52 | js | JavaScript | widgets/HomeButton/nls/vi/strings.js | chenweigis/NovMap | 60b05edcaa9090e492bd7ecfd4d36dbdc2f4ed8e | [
"Apache-2.0"
] | 1 | 2021-02-25T21:24:28.000Z | 2021-02-25T21:24:28.000Z | wab/widgets/HomeButton/nls/vi/strings.js | saurabhgis/Calcitw_WAB | fa5f2e4c11ad65812684debced258d2dd43df253 | [
"MIT"
] | 6 | 2017-05-25T17:35:14.000Z | 2018-06-22T17:49:38.000Z | wab/widgets/HomeButton/nls/vi/strings.js | saurabhgis/Calcitw_WAB | fa5f2e4c11ad65812684debced258d2dd43df253 | [
"MIT"
] | 1 | 2018-06-22T16:54:09.000Z | 2018-06-22T16:54:09.000Z | define(
({
_widgetLabel: "Trang chủ"
})
); | 10.4 | 29 | 0.5 |
4028d1ae025bf8e025d61f80b8ffb68aea09da98 | 1,023 | js | JavaScript | day04/javascript/tschulte/solution.js | matason/aoc-2018 | e3aea3906c26beafbeff32c1c5afbac9bb6a94df | [
"MIT"
] | 17 | 2018-11-24T21:47:57.000Z | 2021-12-05T18:06:27.000Z | day04/javascript/tschulte/solution.js | matason/aoc-2018 | e3aea3906c26beafbeff32c1c5afbac9bb6a94df | [
"MIT"
] | 12 | 2018-11-28T20:42:30.000Z | 2021-05-07T22:57:00.000Z | day04/javascript/tschulte/solution.js | matason/aoc-2018 | e3aea3906c26beafbeff32c1c5afbac9bb6a94df | [
"MIT"
] | 17 | 2018-11-27T10:32:45.000Z | 2018-12-16T23:51:55.000Z | #!/usr/bin/env node
const parseLine = require("./part1.js").parseLine;
const guardMostAsleep = require("./part1.js").guardMostAsleep;
const overlappingSleepTimes = require("./part1.js").overlappingSleepTimes;
const fs = require("fs");
const input = fs.readFileSync("input.txt", "utf-8");
// tag::part1[]
const lines = input
.split("\n")
.filter(line => line)
.sort();
const reduced = lines.reduce(parseLine, []);
const foundGuard = guardMostAsleep(reduced);
const id = foundGuard.guard;
const overlappingTimes = overlappingSleepTimes(foundGuard);
console.log("Day 04, part 1: " + id * overlappingTimes[0].minute);
//end::part1[]
// tag::part2[]
const part2Guards = reduced
.map(guard => {
return { guard: guard, times: overlappingSleepTimes(guard) };
})
.filter(guard => guard.times.length > 0);
part2Guards.sort((a, b) => b.times[0].days - a.times[0].days);
const part2Guard = part2Guards[0];
console.log(
"Day 04, part 2: " + part2Guard.guard.guard * part2Guard.times[0].minute
);
// end::part2[]
| 28.416667 | 74 | 0.68915 |
40292c7dc0184fe1ec9b4426208221d7cfeaa702 | 4,903 | js | JavaScript | protected/assets/ajax-upload/au.js | lamhq/yii2-cms | 38ed53815deaddca9f7b10ba89c7c7618dc8729b | [
"BSD-3-Clause"
] | null | null | null | protected/assets/ajax-upload/au.js | lamhq/yii2-cms | 38ed53815deaddca9f7b10ba89c7c7618dc8729b | [
"BSD-3-Clause"
] | null | null | null | protected/assets/ajax-upload/au.js | lamhq/yii2-cms | 38ed53815deaddca9f7b10ba89c7c7618dc8729b | [
"BSD-3-Clause"
] | null | null | null | String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
(function( $ ) {
$.fn.ajaxUpload = function($options) {
var options = $options;
var createEmptyItem = function () {
var inputName = options.name;
if (options.multiple) {
inputName += '['+$.fn.ajaxUpload.itemCount+']';
$.fn.ajaxUpload.itemCount++;
}
var itemTemplate = '<div class="item">'
+'<div class="progress hide">'
+'<div class="progress-bar progress-bar-info"></div>'
+'</div>'
+'<i class="fa fa-file-o fa-5x"></i>'
+'<img alt="" class="img-responsive"/>'
+'<div class="label"></div>'
+'<a class="remove fa fa-trash" href="javascript:void(0)"></a>'
+'<input type="hidden" name="{{name}}[value]" value="" class="value"/>'
+'<input type="hidden" name="{{name}}[url]" value="" class="url" />'
+'<input type="hidden" name="{{name}}[label]" value="" class="label" />'
+'</div>';
var item = $(itemTemplate.replaceAll('{{name}}', inputName));
return item;
};
var updateItem = function (item, data) {
data = $.extend({ label:'', url:'', value:'' }, data);
if ( (/\.(gif|jpg|jpeg|tiff|png|bmp)$/i).test(data.value) ) {
item.find('img').prop('src', data.url);
item.removeClass('not-image');
} else {
item.addClass('not-image');
}
if ( data.value=='' && data.label!='' ) {
item.addClass('uploading');
}
item.find('div.label').text(data.label);
item.find('input.label').val(data.label);
item.find('input.value').val(data.value);
item.find('input.url').val(data.url);
return item;
};
var addItem = function (widget, data) {
var item = createEmptyItem();
updateItem(item, data);
widget.find('.files').append(item);
return item;
};
var addPendingUploadItem = function (widget, file) {
if (!validateFile) return;
if (!options.multiple) {
widget.find('.files .item').each(function () {
removeItem(widget, $(this));
});
}
var item = addItem(widget, { label: file.name });
var xhr = uploadFile(file);
xhr.onreadystatechange = function(){
// handling when upload done
if(xhr.readyState == 4){
var response = $.parseJSON(xhr.response);
if (response.status=='success') {
item.find('.progress-bar').css('width', '100%');
setTimeout(function () {
item.find('.progress').addClass('hide');
updateItem(item, response);
}, 500);
widget.find('.holder').remove();
} else {
removeItem(widget, item);
app.showError({content: response.message});
}
}
};
xhr.upload.addEventListener('progress', function (e) {
// show upload progress
if (!e.lengthComputable) return;
var percentComplete = Math.ceil(100 * e.loaded / e.total);
item.find('.progress').removeClass('hide');
item.find('.progress-bar').css('width', percentComplete+'%');
}, false);
item.data('xhr', xhr);
return item;
};
var uploadFile = function (file) {
var xhr = new XMLHttpRequest();
var data = new FormData();
data.append('ajax-file', file);
xhr.open('POST', options.url);
xhr.setRequestHeader("X-File-Name", encodeURIComponent(file.name));
xhr.setRequestHeader("X-File-Size", file.size);
xhr.send(data);
return xhr;
};
var removeItem = function (widget, item) {
if (item.data('xhr')) {
item.data('xhr').abort();
}
item.remove();
if (widget.find('.files .item').length<1) {
// submit an empty value to server if no file upload
var hidden = '<input type="hidden" name="'+options.name+'" value="" class="holder" />';
widget.append(hidden);
}
};
var validateFile = function (file) {
var checkExtension = function(file) {
if (options.extensions.length < 1) return true;
var fileExt = file.name.split('.').pop();
if ( $.inArray(fileExt.toLowerCase(), options.extensions)<0 ) {
alert('File type is not allowed');
return false;
}
return true;
};
var checkMaxSize = function(file) {
if (options.maxSize==0) return true;
if ( file.size > options.maxSize*1000 ) {
alert('File is too large');
return false;
}
return true;
};
return checkExtension(file) && !checkMaxSize(file);
};
return this.each(function() {
var widget = $(this);
// display items
$.each(options.items, function() {
addItem(widget, this);
});
// remove item
widget.on('click', '.remove', function() {
var item = $(this).closest('.item');
removeItem(widget, item);
});
// upload file after choosing
widget.on('change', 'input[type="file"]', function() {
if ( this.files.length>0 ){
$(this.files).each(function () {
addPendingUploadItem(widget, this);
});
}
this.value = '';
});
// make item sortable
$('.ajax-upload-widget .files').sortable({
opacity: 0.6,
placeholder: 'item',
cursor: 'move'
});
});
};
$.fn.ajaxUpload.itemCount = 0;
}( jQuery )); | 27.700565 | 90 | 0.612482 |
40297216126040a3209a1d3fc050d7cd31e6ba68 | 582 | js | JavaScript | .eslintrc.js | skleinjung/shift | 4c18c50cfa171009a1417f8f02cc7dbd7b5694ff | [
"ISC"
] | 1 | 2021-12-07T05:04:33.000Z | 2021-12-07T05:04:33.000Z | .eslintrc.js | skleinjung/shift | 4c18c50cfa171009a1417f8f02cc7dbd7b5694ff | [
"ISC"
] | 130 | 2021-10-31T01:20:17.000Z | 2021-11-30T22:43:57.000Z | .eslintrc.js | skleinjung/shift | 4c18c50cfa171009a1417f8f02cc7dbd7b5694ff | [
"ISC"
] | null | null | null | module.exports = {
extends: [
'react-app',
'react-app/jest',
'@twindigital',
],
overrides: [
{
files: ['*.ts', '*.tsx', '*.js', '*.jsx'],
rules: {
// this rule has bugs that give nonsensical errors for our types:
// 'Member constructor should be declared before all private instance method definitions', for
// a class that has no private instance methods
'@typescript-eslint/member-ordering': ['off'],
},
},
],
rules: {
'react/jsx-uses-react': 'off',
'react/react-in-jsx-scope': 'off',
},
}
| 25.304348 | 102 | 0.560137 |
40298244e84df24aebeffd62792866db0928688d | 1,100 | js | JavaScript | config/alphabet/alphabet-aseMW.js | sutton-signwriting/signmaker | 2dd134e5f819e9e1c5e18d36941623b18c345913 | [
"MIT"
] | 3 | 2021-12-17T13:44:44.000Z | 2022-01-01T21:04:27.000Z | config/alphabet/alphabet-aseMW.js | sutton-signwriting/signmaker | 2dd134e5f819e9e1c5e18d36941623b18c345913 | [
"MIT"
] | null | null | null | config/alphabet/alphabet-aseMW.js | sutton-signwriting/signmaker | 2dd134e5f819e9e1c5e18d36941623b18c345913 | [
"MIT"
] | null | null | null | window.alphabet = {
S10000: ["S10000", "S10110", "S10610", "S10a10", "S10b10"],
S10e00: ["S10e00", "S11010", "S11210", "S11310", "S11510", "S11810", "S11b10", "S11d10"],
S11e00: ["S14110"],
S14400: ["S14510", "S14710"],
S14c00: ["S14c00", "S15010", "S15310", "S15a10", "S15b10", "S15d10", "S16d10", "S17610", "S18110", "S18210", "S18510"],
S18600: ["S19210", "S19a10", "S19c10"],
S1ba00: ["S1c510"],
S1f500: ["S20110", "S20310"],
S20500: ["S20500", "S20600", "S20700", "S20800", "S21100"],
S21600: ["S22200", "S22500"],
S22a00: ["S22a00", "S22f00", "S23400", "S24900"],
S26500: ["S26500", "S26600", "S26700", "S26800", "S26a00", "S26c00"],
S28800: ["S28800", "S28900", "S29200"],
S2a600: ["S2a600"],
S2b700: ["S2b700", "S2c300", "S2c700", "S2d200"],
S2d500: ["S2d700", "S2db00", "S2e100"],
S2e300: ["S2e300", "S2e700"],
S2f700: ["S2fb00"],
S2ff00: ["S2ff00", "S30000", "S30100"],
S30a00: ["S30a00", "S30c00", "S32100"],
S33b00: ["S33b00", "S33e00", "S34000", "S34600", "S34700"],
S36d00: ["S36d00"],
S37600: ["S37600", "S37700", "S37800", "S37900"],
};
| 40.740741 | 121 | 0.574545 |
4029ccfe7f8a15ae41b7a638dc08052bc8886d3b | 1,698 | js | JavaScript | src/components/Login/Login.js | luizmr/amazon-clone-app | 87d7bd99ce90c17dc8d87bac6d370561ebab757d | [
"MIT"
] | null | null | null | src/components/Login/Login.js | luizmr/amazon-clone-app | 87d7bd99ce90c17dc8d87bac6d370561ebab757d | [
"MIT"
] | null | null | null | src/components/Login/Login.js | luizmr/amazon-clone-app | 87d7bd99ce90c17dc8d87bac6d370561ebab757d | [
"MIT"
] | null | null | null | import React, { useState } from "react";
import { Link, useHistory } from "react-router-dom";
import logo from "../../assets/blacklogo.png";
import "./Login.css";
import { auth } from "../../firebase/firebase";
function Login() {
const history = useHistory();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const login = (e) => {
e.preventDefault();
// login
auth.signInWithEmailAndPassword(email, password)
.then((auth) => {
history.push("/");
})
.catch((e) => alert(e.message));
};
const register = (e) => {
e.preventDefault();
// register
auth.createUserWithEmailAndPassword(email, password)
.then((auth) => {
history.push("/");
})
.catch((e) => alert(e.message));
};
return (
<div className="login">
<Link to="/">
<img src={logo} alt="logo" className="login__logo" />
</Link>
<div className="login__container">
<h1>Sign in</h1>
<form>
<h5>E-mail</h5>
<input
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<h5>Password</h5>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button
className="login_signInButton"
type="submit"
onClick={login}
>
Sign In
</button>
</form>
<p>
By signing-in you agree to Amazon's Conditions of Uses &
Sale. Please sse our Privacy Notice, our Cookies Notice and
our Interest-Based Ads Notice.
</p>
<button className="login_registerButton" onClick={register}>
Create your Amazon Account
</button>
</div>
</div>
);
}
export default Login;
| 22.945946 | 64 | 0.594229 |
402c50aa6224844bd90aa0cd1aaf2f51f20bf210 | 822 | js | JavaScript | docs/api/html/da/db5/classTBela_1_1CSS_1_1Query_1_1TokenSelectorValueAttributeFunctionComment.js | tbela99/css | 11a1e5597c37cd1ddc28e76e2e5d21973dd4dcba | [
"MIT"
] | 8 | 2020-06-12T13:19:21.000Z | 2022-02-20T07:32:04.000Z | docs/api/html/da/db5/classTBela_1_1CSS_1_1Query_1_1TokenSelectorValueAttributeFunctionComment.js | tbela99/css | 11a1e5597c37cd1ddc28e76e2e5d21973dd4dcba | [
"MIT"
] | 39 | 2020-01-13T07:01:13.000Z | 2022-01-19T23:52:44.000Z | docs/api/html/da/db5/classTBela_1_1CSS_1_1Query_1_1TokenSelectorValueAttributeFunctionComment.js | tbela99/css | 11a1e5597c37cd1ddc28e76e2e5d21973dd4dcba | [
"MIT"
] | 2 | 2020-08-10T21:29:41.000Z | 2021-12-02T17:04:02.000Z | var classTBela_1_1CSS_1_1Query_1_1TokenSelectorValueAttributeFunctionComment =
[
[ "evaluate", "da/db5/classTBela_1_1CSS_1_1Query_1_1TokenSelectorValueAttributeFunctionComment.html#ac9dad18176ee7194b72e239c69575679", null ],
[ "render", "da/db5/classTBela_1_1CSS_1_1Query_1_1TokenSelectorValueAttributeFunctionComment.html#a8fd6cfba082506044eb9d98e4350c954", null ],
[ "$arguments", "da/db5/classTBela_1_1CSS_1_1Query_1_1TokenSelectorValueAttributeFunctionComment.html#a911d1cf77572ea825a089401ff03d9ce", null ],
[ "$expression", "da/db5/classTBela_1_1CSS_1_1Query_1_1TokenSelectorValueAttributeFunctionComment.html#a3c4bd4752a22ec639beb1a0b27397c06", null ],
[ "$name", "da/db5/classTBela_1_1CSS_1_1Query_1_1TokenSelectorValueAttributeFunctionComment.html#a7e59f115d12a94508f18747c043bb5b3", null ]
]; | 102.75 | 150 | 0.854015 |
402d5b858ded6399833e8135bbe0ca79b5a1fa98 | 82 | js | JavaScript | src/schemas/Graph.js | seeden/livia | 161a12877f24c5c68d20fb4f8c94d689673af40a | [
"Apache-2.0"
] | 8 | 2015-06-13T07:01:38.000Z | 2016-07-02T20:10:52.000Z | src/schemas/Graph.js | seeden/livia | 161a12877f24c5c68d20fb4f8c94d689673af40a | [
"Apache-2.0"
] | 2 | 2016-01-12T15:31:14.000Z | 2020-04-03T05:10:56.000Z | src/schemas/Graph.js | seeden/livia | 161a12877f24c5c68d20fb4f8c94d689673af40a | [
"Apache-2.0"
] | 1 | 2016-12-05T22:32:00.000Z | 2016-12-05T22:32:00.000Z | import Schema from './Schema';
export default class Graph extends Schema {
}
| 16.4 | 44 | 0.707317 |
402e0769714244e8f87957d9011242a34918382f | 2,909 | js | JavaScript | node_modules/caniuse-lite/data/regions/EC.js | thekitbag/todoodleoo-client | 4d1fb939f3a70107d51a555ec0df497e14d1b298 | [
"Apache-2.0"
] | 42 | 2021-11-17T12:53:34.000Z | 2022-03-27T12:41:39.000Z | node_modules/caniuse-lite/data/regions/EC.js | thekitbag/todoodleoo-client | 4d1fb939f3a70107d51a555ec0df497e14d1b298 | [
"Apache-2.0"
] | 14 | 2021-11-15T11:00:51.000Z | 2022-02-15T07:43:44.000Z | tokweb/node_modules/caniuse-lite/data/regions/EC.js | tokera-com/ate | 42c4ce5a0c0aef47aeb4420cc6dc788ef6ee8804 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-12-08T19:50:08.000Z | 2021-12-08T19:50:08.000Z | module.exports={C:{"51":0.00499,"52":0.02995,"58":0.00499,"64":0.00499,"66":0.00998,"68":0.00998,"72":0.01497,"73":0.01497,"78":0.05989,"80":0.00998,"81":0.00998,"84":0.00998,"88":0.04492,"89":0.02496,"90":0.01497,"91":0.04492,"92":0.01497,"93":0.00998,"94":0.01996,"95":0.02496,"96":0.02995,"97":1.05809,"98":1.9964,"99":0.00998,_:"2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 53 54 55 56 57 59 60 61 62 63 65 67 69 70 71 74 75 76 77 79 82 83 85 86 87 100 3.5 3.6"},D:{"22":0.00998,"38":0.02995,"47":0.01996,"49":0.02496,"53":0.00998,"55":0.01497,"56":0.00499,"63":0.00998,"65":0.00998,"66":0.00499,"67":0.00998,"68":0.00499,"70":0.00499,"72":0.00499,"73":0.00499,"74":0.01996,"75":0.01497,"76":0.01497,"77":0.00998,"78":0.01497,"79":0.15472,"80":0.01996,"81":0.00998,"83":0.02496,"84":0.01497,"85":0.01497,"86":0.04492,"87":0.09483,"88":0.01996,"89":0.02995,"90":0.02496,"91":0.46915,"92":0.04991,"93":0.22959,"94":0.0549,"95":0.0549,"96":0.2196,"97":0.43921,"98":7.4865,"99":26.61201,"100":0.29946,"101":0.00998,_:"4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 39 40 41 42 43 44 45 46 48 50 51 52 54 57 58 59 60 61 62 64 69 71 102 103"},F:{"28":0.00499,"78":0.00499,"82":0.00998,"83":0.73368,_:"9 11 12 15 16 17 18 19 20 21 22 23 24 25 26 27 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 60 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 79 80 81 9.5-9.6 10.5 10.6 11.1 11.5 11.6 12.1","10.0-10.1":0},B:{"18":0.01497,"92":0.01497,"96":0.00998,"97":0.02496,"98":0.56398,"99":2.221,_:"12 13 14 15 16 17 79 80 81 83 84 85 86 87 88 89 90 91 93 94 95"},E:{"4":0,"13":0.01497,"14":0.08984,"15":0.06987,_:"0 5 6 7 8 9 10 11 12 3.1 3.2 6.1 7.1 9.1 10.1","5.1":0.01996,"11.1":0.00499,"12.1":0.02496,"13.1":0.1098,"14.1":0.24955,"15.1":0.1098,"15.2-15.3":0.12977,"15.4":0.08485},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0,"5.0-5.1":0.01359,"6.0-6.1":0.00755,"7.0-7.1":0.00352,"8.1-8.4":0.0005,"9.0-9.2":0.0005,"9.3":0.02063,"10.0-10.2":0.0005,"10.3":0.01711,"11.0-11.2":0.00302,"11.3-11.4":0.00704,"12.0-12.1":0.00453,"12.2-12.5":0.24504,"13.0-13.1":0.00704,"13.2":0.00302,"13.3":0.01862,"13.4-13.7":0.06189,"14.0-14.4":0.15598,"14.5-14.8":0.64354,"15.0-15.1":0.30391,"15.2-15.3":3.1095,"15.4":0.40101},P:{"4":0.21728,"5.0-5.4":0.02021,"6.2-6.4":0.04042,"7.2-7.4":0.09312,"8.2":0.02018,"9.2":0.01035,"10.1":0.02021,"11.1-11.2":0.05173,"12.0":0.02069,"13.0":0.08277,"14.0":0.07243,"15.0":0.08277,"16.0":1.56235},I:{"0":0,"3":0,"4":0,"2.1":0,"2.2":0,"2.3":0,"4.1":0.00119,"4.2-4.3":0.00475,"4.4":0,"4.4.3-4.4.4":0.06417},K:{_:"0 10 11 12 11.1 11.5 12.1"},A:{"11":0.06987,_:"6 7 8 9 10 5.5"},J:{"7":0,"10":0},N:{"10":0.02584,_:"11"},L:{"0":36.14417},S:{"2.5":0},R:{_:"0"},M:{"0":0.14523},Q:{"10.4":0},O:{"0":0.03005},H:{"0":0.14698}};
| 1,454.5 | 2,908 | 0.58955 |
402ecdd1725d7168caf01dfe8b690372409faf31 | 272 | js | JavaScript | lib/config/awsConfig.js | alexisHetic/S3ImagesResizer | 54ad16008f712b5ea18b3408ea9df5bb249dc376 | [
"MIT"
] | null | null | null | lib/config/awsConfig.js | alexisHetic/S3ImagesResizer | 54ad16008f712b5ea18b3408ea9df5bb249dc376 | [
"MIT"
] | null | null | null | lib/config/awsConfig.js | alexisHetic/S3ImagesResizer | 54ad16008f712b5ea18b3408ea9df5bb249dc376 | [
"MIT"
] | null | null | null |
const getAWSCredentials = () => ({
s3Bucket : process.env.S3_BUCKET,
region : process.env.S3_BUCKET_REGION,
accessKeyId : process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
})
export default getAWSCredentials
| 27.2 | 53 | 0.716912 |
4032018457797467c2dbe424d222a9f662770c82 | 1,412 | js | JavaScript | webpack.prod.js | raakeshmadana/markitdown | 4cf86fed6b9d721117159c9bd75b478a9fbda230 | [
"MIT"
] | 3 | 2018-07-31T08:24:49.000Z | 2019-06-30T07:48:07.000Z | webpack.prod.js | raakeshmadana/markitdown | 4cf86fed6b9d721117159c9bd75b478a9fbda230 | [
"MIT"
] | null | null | null | webpack.prod.js | raakeshmadana/markitdown | 4cf86fed6b9d721117159c9bd75b478a9fbda230 | [
"MIT"
] | null | null | null | const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
entry: ['whatwg-fetch', 'babel-polyfill', './client/app/'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './client/public/'),
},
module: {
rules: [{
test: /\.css$/,
use: [{
loader: MiniCssExtractPlugin.loader
}, {
loader: "css-loader", options: {
sourceMap: true
}
}]
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
mode: 'production',
devtool: 'source-map',
plugins: [
new CleanWebpackPlugin(['public']),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'client/app/index.html'),
filename: 'index.html'
}),
new UglifyJsPlugin({
sourceMap: true
}),
new MiniCssExtractPlugin(),
new OptimizeCssAssetsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
};
| 26.641509 | 78 | 0.593484 |
403203205bebe97460c717d12d7e0fd465ebba54 | 32,776 | js | JavaScript | api/resolver/generic/AggregationBuilder.js | axax/lunuc | 928192c686647891c542945a9471ebe1887b46d0 | [
"MIT"
] | 4 | 2019-06-01T09:53:33.000Z | 2021-09-01T19:25:34.000Z | api/resolver/generic/AggregationBuilder.js | axax/lunuc | 928192c686647891c542945a9471ebe1887b46d0 | [
"MIT"
] | null | null | null | api/resolver/generic/AggregationBuilder.js | axax/lunuc | 928192c686647891c542945a9471ebe1887b46d0 | [
"MIT"
] | null | null | null | import Util from 'api/util'
import {getType} from 'util/types'
import {getFormFieldsByType} from 'util/typesAdmin'
import {ObjectId} from 'mongodb'
import config from 'gen/config'
import Hook from 'util/hook'
const comparatorMap = {
':': '$regex',
'=': '$regex',
'==': '$eq',
'===': '$eq',
'>': '$gt',
'>=': '$gte',
'<': '$lt',
'<=': '$lte',
'!=': '$regex',
'!==': '$ne'
}
export default class AggregationBuilder {
constructor(type, fields, options) {
this.type = type
this.fields = fields
this.options = options
}
getLimit() {
let {limit} = this.options
return limit ? parseInt(limit) : 10
}
getOffset() {
let {offset, page} = this.options
if (!offset) {
if (page && page>0) {
return (page - 1) * this.getLimit()
} else {
return 0
}
}
return offset
}
getPage() {
let {page} = this.options
if (!page) {
return 1
}
return page
}
getSort() {
let {sort, lang} = this.options
if (!sort) {
return {_id: -1}
} else {
if (sort.constructor === String) {
const typeFields = getFormFieldsByType(this.type)
// the sort string is in this format "field1 asc, field2 desc"
return sort.split(',').reduce((acc, val) => {
const a = val.trim().split(' ')
let fieldName = a[0]
if (fieldName.indexOf('.') < 0 && typeFields[fieldName] && typeFields[fieldName].localized) {
fieldName += '.' + lang
}
return {...acc, [fieldName]: (a.length > 1 && a[1].toLowerCase() == "desc" ? -1 : 1)}
}, {})
}
}
return sort
}
getParsedFilter(filterStr) {
if (filterStr) {
return Util.parseFilter(filterStr)
}
}
// Mongodb joins
createAndAddLookup({type, name, multi}, lookups, {usePipeline}) {
let lookup
/* with pipeline */
if (usePipeline) {
let $expr = {}
if (multi) {
$expr.$in = ['$_id',
{
$cond: {
if: {$isArray: '$$' + name},
then: '$$' + name,
else: ['$$' + name]
}
}]
} else {
$expr.$eq = ['$_id', '$$' + name]
}
lookup = {
$lookup: {
from: type,
as: name,
let: {
[name]: '$' + name
},
pipeline: [
{
$match: {
$expr
}
}
]
}
}
} else {
// without pipeline
lookup = {
$lookup: {
from: type,
localField: name,
foreignField: '_id',
as: name
}
}
}
lookups.push(lookup)
return {lookup}
}
createGroup({name, multi}) {
return {'$first': multi ? '$' + name : {$arrayElemAt: ['$' + name, 0]}}
}
// filter where clause
createAndAddFilterToMatch({name, reference, type, multi, localized, searchable, vagueSearchable}, match, {exact, filters}) {
let hasAtLeastOneMatch = false
if (filters && searchable !== false) {
if (localized) {
config.LANGUAGES.forEach(lang => {
if (this.createAndAddFilterToMatch({name: name + '.' + lang, reference}, match, {exact, filters})) {
hasAtLeastOneMatch = true
}
})
return hasAtLeastOneMatch
}
let filterPart = filters.parts[name]
if (!filterPart && reference) {
filterPart = filters.parts[name + '._id']
}
if (!filterPart && !exact) {
filterPart = filters.parts[name.split('.')[0]]
}
// explicit search for this field
if (filterPart) {
let filterPartArray
if (filterPart.constructor !== Array) {
filterPartArray = [filterPart]
} else {
filterPartArray = filterPart
}
for (const filterPartOfArray of filterPartArray) {
const {added, error} = this.addFilterToMatch({
filterKey: name,
filterValue: filterPartOfArray.value,
filterOptions: filterPartOfArray,
type: reference ? 'ID' : type,
multi,
match
})
if (added) {
hasAtLeastOneMatch = true
} else {
//TODO add debugging infos for search. this here is only a test
this.searchHint = error
}
}
} else if (type === 'Object') {
// filter in an Object without definition
for (const filterKey in filters.parts) {
if (filterKey.startsWith(name + '.')) {
filterPart = filters.parts[filterKey]
let filterPartArray
if (filterPart.constructor !== Array) {
filterPartArray = [filterPart]
} else {
filterPartArray = filterPart
}
for (const filterPartOfArray of filterPartArray) {
const {added} = this.addFilterToMatch({
filterKey,
filterValue: filterPartOfArray.value,
filterOptions: filterPartOfArray,
match
})
if (added) {
hasAtLeastOneMatch = true
}
}
}
}
}
if (!exact && !reference && vagueSearchable !== false && ['Boolean'].indexOf(type) < 0) {
// if it is an object only add filter if searchable is explicitly set to true
if( type !== 'Object' || vagueSearchable === true) {
filters.rest.forEach(e => {
hasAtLeastOneMatch = true
const {added} = this.addFilterToMatch({
filterKey: name,
filterValue: e.value,
filterOptions: e,
type,
multi,
match
})
if (added) {
hasAtLeastOneMatch = true
}
})
}
}
}
return hasAtLeastOneMatch
}
/**
* get a user or gobal value by a key
*
* @param {String} filterKey is the name of the collection field
* @param {String} filterValue is always a string
* @param {String} type is the type of the field. it can be Boolean, ID, Object, Float
* @param {Boolean} multi if true the field can store multiple values. it must be an array
* @param {Object} filterOptions contains information about the filter
* @param {Object} match the match where the filter should be added to
* @param {Function} callback a function that gets called at the end
*
* @returns {Object} an object that contains information about how the filter was added
*/
addFilterToMatch({filterKey, filterValue, type, multi, filterOptions, match}) {
const rawComperator = filterOptions && filterOptions.comparator
let comparator = '$regex' // default comparator
if (rawComperator && comparatorMap[rawComperator]) {
comparator = comparatorMap[rawComperator]
}
if (comparator === '$regex' && (type === 'Boolean' || type === 'ID' || type === 'Float')) {
if (rawComperator === '!=') {
comparator = '$ne'
} else {
comparator = '$eq'
}
}
if (type === 'ID') {
if (filterValue) {
if (filterValue.constructor === ObjectId) {
// do nothing
} else if (filterValue.startsWith('[') && filterValue.endsWith(']')) {
filterValue = filterValue.substring(1, filterValue.length - 1).split(',')
const ids = []
for (const id of filterValue) {
if (ObjectId.isValid(id)) {
ids.push(ObjectId(id))
} else {
return {added: false, error: 'Search for IDs. But not all ids are valid'}
}
}
filterValue = ids
if (comparator === '$ne') {
comparator = '$nin'
} else {
comparator = '$in'
}
} else if (ObjectId.isValid(filterValue)) {
// match by id
filterValue = ObjectId(filterValue)
} else {
return {added: false, error: 'Search for ID. But ID is not valid'}
}
} else {
if (!match.$or) {
match.$or = []
}
match.$or.push({
// Check about no Company key
[filterKey]: {
$exists: false,
},
})
match.$or.push({
// Check about no Company key
[filterKey]: null,
})
match.$or.push({
// Check about no Company key
[filterKey]: {
$size: 0
},
})
return {added: true}
}
} else if (type === 'Boolean') {
if (filterValue === 'true' || filterValue === 'TRUE') {
filterValue = true
} else if (filterValue === 'false' || filterValue === 'FALSE') {
filterValue = false
}
} else if (type === 'Float') {
filterValue = parseFloat(filterValue)
} else if (type === 'Object' && filterValue) {
filterValue = {
body: `function(data) {return data && Object.keys(data).some(
key => /${filterValue}/i.test( data[key] && (data[key].constructor===Object || data[key].constructor===Array)?JSON.stringify(data[key]):data[key])
)}`,
args: ['$'+filterKey],
lang: 'js'
}
comparator = '$function'
filterKey = '$expr'
}
let matchExpression
if (['$gt', '$gte', '$lt', '$lte'].indexOf(comparator) >= 0) {
matchExpression = {[comparator]: type === 'ID' ? filterValue : parseFloat(filterValue)}
} else if (comparator === '$ne' || comparator === '$eq') {
if (multi && filterValue && filterValue.constructor !== Array) {
matchExpression = {[comparator === '$eq' ? '$in' : '$nin']: [filterValue]}
} else if (filterValue === '') {
matchExpression = {[comparator === '$eq' ? '$in' : '$nin']: [null, ""]}
} else if (!filterOptions.inDoubleQuotes && filterValue === 'null') {
matchExpression = {[comparator]: null}
} else if (filterValue.constructor === ObjectId) {
matchExpression = {[comparator]: filterValue}
} else {
if (filterOptions.inDoubleQuotes) {
matchExpression = {[comparator]: filterValue}
} else if (filterValue === true || filterValue === false) {
matchExpression = {[comparator]: filterValue}
} else if (!isNaN(filterValue)) {
matchExpression = {[comparator]: parseFloat(filterValue)}
} else if (filterValue && filterValue.constructor === String && filterValue.startsWith('[') && filterValue.endsWith(']')) {
matchExpression = {'$in': filterValue.substring(1, filterValue.length - 1).split(',')}
} else {
matchExpression = {[comparator]: filterValue}
}
}
} else if (comparator === '$regex') {
if (rawComperator === '!=') {
matchExpression = {$not: {[comparator]: filterValue, $options: 'i'}}
} else {
matchExpression = {[comparator]: filterValue, $options: 'i'}
}
} else {
matchExpression = {[comparator]: filterValue}
}
if (!filterOptions || filterOptions.operator === 'or') {
if (!match.$or) {
match.$or = []
}
match.$or.push({[filterKey]: matchExpression})
} else {
if (!match.$and) {
match.$and = []
}
match.$and.push({[filterKey]: matchExpression})
/*if (match[filterKey]) {
match[filterKey] = {...match[filterKey], ...matchExpression}
} else {
match[filterKey] = matchExpression
}*/
}
return {added: true}
}
getFieldDefinition(fieldData, type) {
const typeFields = getFormFieldsByType(type)
let fieldDefinition = {}
if (fieldData.constructor === Object) {
const fieldNames = Object.keys(fieldData)
if (fieldNames.length > 0) {
// there should be only one attribute
fieldDefinition.name = fieldNames[0]
let data = fieldData[fieldDefinition.name]
if (fieldDefinition.name.indexOf('.') > 0) {
const parts = fieldDefinition.name.split('.')
fieldDefinition.name = parts[0]
data = [parts[1]]
}
if (data.constructor === Array) {
// if a value is in this format {'categories':['name']}
// we expect that the field categories is a reference to another type
// so we create a lookup for this type
fieldDefinition.fields = data
} else {
if (data.localized) {
fieldDefinition.projectLocal = true
}
if (data.substr) {
fieldDefinition.projectLocal = true
fieldDefinition.substr = data.substr
}
}
}
} else if (fieldData.indexOf('$') > 0) {
// this is a reference
// for instance image$Media --> field image is a reference to the type Media
const part = fieldData.split('$')
fieldDefinition.name = part[0]
if (part[1].startsWith('[')) {
fieldDefinition.multi = true
fieldDefinition.type = part[1].substring(1, part[1].length - 1)
} else {
fieldDefinition.multi = false
fieldDefinition.type = part[1]
}
} else {
if (fieldData.endsWith('.localized')) {
fieldDefinition.projectLocal = true
fieldDefinition.name = fieldData.split('.')[0]
} else {
fieldDefinition.name = fieldData
}
}
// extend it with default definition
if (typeFields[fieldDefinition.name]) {
fieldDefinition = {...typeFields[fieldDefinition.name], ...fieldDefinition}
} else if (fieldDefinition.name === 'createdBy') {
fieldDefinition.reference = true
fieldDefinition.type = 'User'
}
return fieldDefinition
}
projectByField(fieldName, fields, projectResultData) {
for (const subField of fields) {
if (subField.constructor === Object) {
const keys = Object.keys(subField)
this.projectByField(fieldName + '.' + keys[0], subField[keys[0]], projectResultData)
} else {
projectResultData[fieldName + '.' + subField] = 1
}
}
}
async query(db) {
const typeDefinition = getType(this.type) || {}
const {projectResult, lang, includeCount, includeUserFilter} = this.options
// limit and offset
const limit = this.getLimit(),
offset = this.getOffset(),
page = this.getPage(),
sort = this.getSort(),
typeFields = getFormFieldsByType(this.type),
filters = this.getParsedFilter(this.options.filter),
resultFilters = this.getParsedFilter(this.options.resultFilter)
let rootMatch = Object.assign({}, this.options.match),
match = {},
resultMatch = {},
groups = {},
lookups = [],
projectResultData = {},
hasMatchInReference = false
if (rootMatch.$or) {
// warp or
rootMatch.$and = [{$or:rootMatch.$or}]
delete rootMatch.$or
}
const aggHook = Hook.hooks['AggregationBuilderBeforeQuery']
if (aggHook && aggHook.length) {
for (let i = 0; i < aggHook.length; ++i) {
await aggHook[i].callback({filters, type: this.type, db})
}
}
// if there is filter like _id=12323213
if (filters) {
if (filters.parts._id) {
// if there is a filter on _id
// handle it here
let idFilters
if (filters.parts._id.constructor !== Array) {
idFilters = [filters.parts._id]
} else {
idFilters = filters.parts._id
}
idFilters.forEach((idFilter) => {
this.addFilterToMatch({
filterKey: '_id',
filterValue: idFilter.value,
filterOptions: idFilter,
type: 'ID',
match: rootMatch
})
})
}
// filter for inbuilt fields
if (includeUserFilter) {
if (filters.parts.createdBy) {
this.addFilterToMatch({
filterKey: 'createdBy',
filterValue: filters.parts['createdBy'].value,
filterOptions: filters.parts['createdBy'],
type: 'ID',
match
})
}
if (filters.parts['createdBy.username']) {
hasMatchInReference = true
this.addFilterToMatch({
filterKey: 'createdBy.username',
filterValue: filters.parts['createdBy.username'].value,
filterOptions: filters.parts['createdBy.username'],
match
})
}
}
}
this.fields.forEach((field, i) => {
const fieldDefinition = this.getFieldDefinition(field, this.type)
const fieldName = fieldDefinition.name
if (fieldDefinition.reference) {
// search in a ref field
// poor performance
let refFields = fieldDefinition.fields, projectPipeline = {}, usePipeline = false
if (!refFields) {
projectResultData[fieldName] = 1
const refFieldDefinitions = getFormFieldsByType(fieldDefinition.type)
if (refFieldDefinitions) {
refFields = Object.keys(refFieldDefinitions)
}
}
if (refFields) {
for (const refField of refFields) {
const refFieldDefinition = this.getFieldDefinition(refField, fieldDefinition.type)
const refFieldName = refFieldDefinition.name
if (fieldDefinition.fields) {
projectResultData[fieldName + '.' + refFieldName] = 1
}
if (refFieldDefinition) {
let localProjected = false
if (refFieldDefinition.fields) {
usePipeline = true
for (const subRefField of refFieldDefinition.fields) {
projectPipeline[refFieldName + '.' + subRefField] = 1
}
} else if (refFieldDefinition.localized && refFieldDefinition.projectLocal) {
usePipeline = true
localProjected = true
// project localized field in current language
projectPipeline[refFieldName] = '$' + refFieldName + '.' + lang
} else {
projectPipeline[refFieldName] = 1
}
/* if (refFieldDefinition.type === 'Object') {
console.log(refFieldDefinition)
projectPipeline[refFieldName] = {$convert: {input: '$' + refFieldName, to: "string", onError: "error" }}
}*/
if (!refFieldDefinition.reference) {
// these filters are slow
// probably it is better to do multiple queries instead
if (this.createAndAddFilterToMatch({
name: fieldName + '.' + refFieldName,
reference: false,
localized: refFieldDefinition.localized && !localProjected
}, match, {exact: true, filters})) {
hasMatchInReference = true
}
}
}
}
}
if (fieldDefinition.multi) {
// if multi it has to be an array
// this is an anditional filter to remove non array values. it is not needed if database is consistent
// without this filter you might get the error: $in requires an array as a second argument
/*this.addFilterToMatch({
filterKey:fieldName+'.0',
filterValue: { '$exists': true },
match: rootMatch
})*/
}
if (refFields && refFields.length === 1 && refFields[0] === '_id') {
// it is only the id lookup doesn't make sense
projectResultData[fieldName + '._id'] = '$' + fieldName
groups[fieldName] = {'$first': '$' + fieldName}
} else {
const {lookup} = this.createAndAddLookup(fieldDefinition, lookups, {usePipeline})
if (lookup.$lookup.pipeline) {
lookup.$lookup.pipeline.push({$project: projectPipeline})
}
groups[fieldName] = this.createGroup(fieldDefinition)
}
this.createAndAddFilterToMatch(fieldDefinition, hasMatchInReference ? match : rootMatch, {filters})
} else {
// regular field
if (fieldName !== '_id') {
groups[fieldName] = {'$first': '$' + fieldName}
if (typeFields[fieldName]) {
this.createAndAddFilterToMatch(fieldDefinition, match, {filters})
this.createAndAddFilterToMatch(fieldDefinition, resultMatch, {filters: resultFilters})
}
}
if (fieldDefinition.fields) {
this.projectByField(fieldName, fieldDefinition.fields, projectResultData)
} else {
if (fieldDefinition.projectLocal) {
// project localized field in current language
if (fieldDefinition.substr) {
projectResultData[fieldName] = {$substrCP: ['$' + fieldName + (fieldDefinition.localized ? '.' + lang : ''), fieldDefinition.substr[0], fieldDefinition.substr[1]]}
} else if (fieldDefinition.localized) {
projectResultData[fieldName] = '$' + fieldName + '.' + lang
}
} else {
projectResultData[fieldName] = 1
// mongodb 4 supports convert and toString
// for know we have to do it after the query
/*if (fieldDefinition.type === 'Object') {
projectResultData[fieldName] = {$convert: {input: '$' + fieldName, to: "string", onError: "error" }}
}*/
}
}
}
})
if (!projectResult) {
// also return extra fields
if (!typeDefinition.noUserRelation) {
this.createAndAddLookup({type: 'User', name: 'createdBy', multi: false}, lookups, {})
groups.createdBy = this.createGroup({name: 'createdBy', multi: false})
}
groups.modifiedAt = {'$first': '$modifiedAt'}
}
// compose result
let dataQuery = [], dataFacetQuery = []
const hasMatch = Object.keys(match).length > 0,
hasResultMatch = Object.keys(resultMatch).length > 0,
doMatchAfterLookup = (hasMatch && hasMatchInReference)
this.removeSingleOr(match)
this.removeSingleOr(resultMatch)
if (Object.keys(rootMatch).length > 0) {
if (!hasMatchInReference) {
// merge ors
if (rootMatch.$or && match.$or) {
match.$or.push(...rootMatch.$or)
delete rootMatch.$or
}
// merge ands
if (rootMatch.$and && match.$and) {
match.$and.push(...rootMatch.$and)
delete rootMatch.$and
}
const finalMatch = {...rootMatch, ...match}
// remove single or
this.removeSingleOr(finalMatch)
dataQuery.push({
$match: finalMatch
})
} else {
dataQuery.push({
$match: rootMatch
})
}
} else if (hasMatch && !hasMatchInReference) {
dataQuery.push({
$match: match
})
}
if (hasResultMatch) {
dataFacetQuery.push({$match: resultMatch})
}
let tempQuery
if (doMatchAfterLookup) {
tempQuery = dataQuery
// add sort
dataFacetQuery.push({$sort: sort})
dataFacetQuery.push({$skip: offset})
dataFacetQuery.push({$limit: limit})
} else {
tempQuery = dataFacetQuery
if (includeCount) {
dataFacetQuery.push({$sort: sort})
dataFacetQuery.push({$skip: offset})
dataFacetQuery.push({$limit: limit})
}
}
if (this.options.lookups) {
lookups.push(...this.options.lookups)
}
if (lookups.length > 0) {
for (const lookup of lookups) {
tempQuery.push(lookup)
}
}
// add at the beginning of the query
if (this.options.before) {
if (this.options.before.constructor === Array) {
for (let i = this.options.before.length - 1; i >= 0; i--) {
tempQuery.unshift(this.options.before[i])
}
} else {
tempQuery.unshift(this.options.before)
}
}
// add right before the group
if (this.options.beforeGroup) {
tempQuery.push(this.options.beforeGroup)
}
// Group back to arrays
tempQuery.push(
{
$group: {
_id: '$_id',
...groups,
...this.options.group
}
})
// second match
if (doMatchAfterLookup) {
dataQuery.push({
$match: match
})
}
const countQuery = dataQuery.slice(0)
countQuery.push({
"$count": "count"
})
if (!doMatchAfterLookup && !dataFacetQuery.some(f => !!f.$match) ) {
// add sort at the beginning if there is not another match
// it is much faster when skip limit is outside of facet
if (!includeCount) {
dataQuery.push({$sort: sort})
dataQuery.push({$skip: offset})
dataQuery.push({$limit: limit})
}
}
// sort again within the result
dataFacetQuery.push({$sort: sort})
// add right before the group
if (this.options.beforeProject) {
tempQuery.push(this.options.beforeProject)
}
// project
if (projectResult) {
// also remove id if it is not explicitly set
if (!projectResultData._id) {
projectResultData._id = 0
}
if (this.options.group) {
Object.keys(this.options.group).forEach((k) => {
projectResultData[k] = 1
})
}
if (this.options.project) {
Object.keys(this.options.project).forEach((k) => {
if (this.options.project[k] === null) {
delete projectResultData[k]
} else {
projectResultData[k] = this.options.project[k]
}
})
}
dataFacetQuery.push({$project: projectResultData})
}
const facet = {
$facet: {
results: dataFacetQuery,
...this.options.$facet
}
}
if (includeCount) {
facet.$facet.count = [
{$count: 'count'}
]
if (hasResultMatch) {
facet.$facet.count.unshift({$match: resultMatch})
}
}
//wrap in a facet
dataQuery.push(facet)
// return offset and limit
dataQuery.push({
$addFields: {limit, offset, page, searchHint: this.searchHint, ...this.options.$addFields}
})
return {dataQuery, countQuery}
}
removeSingleOr(match) {
if (match.$or && match.$or.length === 1) {
Object.keys(match.$or[0]).forEach(key => {
if(match[key]){
if(!match.$and){
match.$and = [{[key]:match[key]}]
}else{
match.$and.push({[key]:match[key]})
}
match.$and.push(match.$or[0])
delete match[key]
}else {
match[key] = match.$or[0][key]
}
})
delete match.$or
}
}
}
| 34.720339 | 191 | 0.443007 |
4033ab222c5fc4b9cd2b1f5aec505f4d33ceb879 | 1,745 | js | JavaScript | src/containers/_nav.js | fahim-006/impact_adminpanel | 202c812ea8b72c84fc8ea7c26a04624e1295eb4c | [
"MIT"
] | null | null | null | src/containers/_nav.js | fahim-006/impact_adminpanel | 202c812ea8b72c84fc8ea7c26a04624e1295eb4c | [
"MIT"
] | null | null | null | src/containers/_nav.js | fahim-006/impact_adminpanel | 202c812ea8b72c84fc8ea7c26a04624e1295eb4c | [
"MIT"
] | null | null | null | import React from "react";
import CIcon from "@coreui/icons-react";
const _nav = [
{
_tag: "CSidebarNavItem",
name: "Dashboard",
to: "/dashboard",
icon: <CIcon name="cil-speedometer" customClasses="c-sidebar-nav-icon" />,
badge: {
color: "info",
text: "NEW",
},
},
// Brand == social
{
_tag: "CSidebarNavItem",
name: "Socials",
to: "/social",
icon: <CIcon name="cil-speedometer" customClasses="c-sidebar-nav-icon" />,
},
// Category ==cause
{
_tag: "CSidebarNavItem",
name: "Cause",
to: "/cause",
icon: <CIcon name="cil-speedometer" customClasses="c-sidebar-nav-icon" />,
},
// supplier = terms and conditions
{
_tag: "CSidebarNavItem",
name: "Terms and Conditions",
to: "/terms",
icon: <CIcon name="cil-speedometer" customClasses="c-sidebar-nav-icon" />,
},
// Import == policy
{
_tag: "CSidebarNavItem",
name: "Policy",
to: "/policy",
icon: <CIcon name="cil-speedometer" customClasses="c-sidebar-nav-icon" />,
},
// Buy
{
_tag: "CSidebarNavItem",
name: "Buy",
to: "/buy",
icon: <CIcon name="cil-speedometer" customClasses="c-sidebar-nav-icon" />,
},
// BuyPhase
{
_tag: "CSidebarNavItem",
name: "Buy Phase Edit",
to: "/buyphase",
icon: <CIcon name="cil-speedometer" customClasses="c-sidebar-nav-icon" />,
},
// AddressToken
{
_tag: "CSidebarNavItem",
name: "Address",
to: "/address",
icon: <CIcon name="cil-speedometer" customClasses="c-sidebar-nav-icon" />,
}
];
export default _nav;
| 22.662338 | 83 | 0.538109 |
4033e9bad27f02ec81823b13accd126a1b9a8971 | 2,997 | js | JavaScript | client/src/components/cards-game-mode.js | saramorais/Flashcards | d54924a150c4cdd9a4ab95607cf46bfc64d82a44 | [
"MIT"
] | null | null | null | client/src/components/cards-game-mode.js | saramorais/Flashcards | d54924a150c4cdd9a4ab95607cf46bfc64d82a44 | [
"MIT"
] | null | null | null | client/src/components/cards-game-mode.js | saramorais/Flashcards | d54924a150c4cdd9a4ab95607cf46bfc64d82a44 | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import '../style/cards.css';
import { connect } from 'react-redux';
import { fetchCards } from '../actions';
import { Link } from 'react-router-dom';
class CardsGame extends Component {
constructor(props) {
super(props);
this.state = {
currentIndex: 0,
currentView: 'question'
}
this.nextCard = this.nextCard.bind(this);
}
componentDidMount() {
this.props.fetchCards(this.props.match.params.id);
}
renderCard() {
const index = this.state.currentIndex;
const view = this.state.currentView;
const { cards } = this.props.cards;
if (cards !== undefined) {
if(cards.length <= 0) {
return <div className='list row'><h3 className='no-items'>This set does not have any cards. Please go to List View to add a card to the set.</h3></div>;
}
if (view === 'question') {
return <div className='game'><h1>{cards[index].question}</h1></div>;
} else {
return <div className='game'><h1>{cards[index].answer}</h1></div>;
}
}
}
nextCard() {
var newIndex = 0;
if (this.state.currentIndex < this.props.cards.cards.length - 1) {
newIndex = this.state.currentIndex + 1;
} else {
newIndex = 0;
}
this.setState({
currentIndex: newIndex,
currentView: 'question'
});
this.renderCard();
}
showQuestion() {
this.setState({currentView: 'question'});
}
showAnswer() {
this.setState({currentView: 'answer'});
}
renderButtons() {
const view = this.state.currentView;
if(view === 'question') {
return <div onClick={() => this.showAnswer(this.props.state)} className='button-center'><button className='button-blue'>Show Answer</button></div>
} else {
return <div onClick={() => this.showQuestion(this.props.state)} className='button-center'><button className='button-blue'>Show Question</button></div>
}
}
render() {
// console.log(this.props.cards);
return (
<div className='container'>
<div className='row'>
<div className='row'>
<div className='col-md-6'>
<p className='set-name'>{this.props.cards.set_name}</p>
</div>
<div className='col-md-6'>
<Link to={`/sets/${this.props.match.params.id}`} className='button button-right button-blue'>List View</Link>
</div>
<div className='col-md-12'>
{this.renderCard()}
</div>
<div className='col-md-6'>
{this.renderButtons()}
</div>
<div className='col-md-6'>
<div onClick={this.nextCard} className='button-center'><button className='button-blue'>Next Question</button></div>
</div>
</div>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return { cards: state.sets };
}
export default connect(mapStateToProps, { fetchCards })(CardsGame);
| 27 | 160 | 0.582583 |
40351c2d713d711786067458790c06707784946f | 6,519 | js | JavaScript | Dashboard_front/src/components/Dashboard/components/WidgetsContainer.js | extragornax/dashboard_epitech | 41386beb3a8f347cc4cdefc8bb62140c22700ebb | [
"MIT"
] | null | null | null | Dashboard_front/src/components/Dashboard/components/WidgetsContainer.js | extragornax/dashboard_epitech | 41386beb3a8f347cc4cdefc8bb62140c22700ebb | [
"MIT"
] | null | null | null | Dashboard_front/src/components/Dashboard/components/WidgetsContainer.js | extragornax/dashboard_epitech | 41386beb3a8f347cc4cdefc8bb62140c22700ebb | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import Widget from './Widget';
import axios from 'axios'
import './Widget.css';
export default class WidgetsContainer extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
meteoData: [],
meteoDataSky: [],
apiWidgetAPI: "api/Widget/",
test: "ck",
ServiceList:"/api/Service/",
meteoURL:"",
rssURL:"",
rssData: [],
setter: 0,
celcius: 1,
cat: [],
rssFlux0: [],
rssFlux1: [],
rssFlux2: [],
rssFlux3: [],
rssFlux4: [],
rssFlux5: [],
rssFlux6: [],
rssFlux7: [],
rssFlux8: [],
rssFlux9: [],
rssFlux10: [],
rssFlux11: [],
rssFlux12: [],
rssFlux13: [],
rssFlux14: [],
rssFlux15: [],
}
this.getMeteo=this.getMeteo.bind(this);
this.changeUnity=this.changeUnity.bind(this);
}
componentDidMount() {
axios.get('/api/Service').then(res => {
this.data=res.data;
this.setState({meteoURL: this.createAPIRequest(this.data[0].widgets[0].id)});
this.setState({rssURL: this.createAPIRequest(this.data[1].widgets[0].id)});
}).then(res => {
axios.get(this.state.meteoURL).then(rep => {
this.setState({meteoData: rep.data.main})
this.setState({meteoDataSky: rep.data.weather[0]})
});
axios.get(this.state.rssURL).then(rep => {
this.setState({rssData: rep.data});
this.setState({cat: rep.data.rss.channel})
this.setState({rssFlux0: rep.data.rss.channel.item[0]})
this.setState({rssFlux1: rep.data.rss.channel.item[1]})
this.setState({rssFlux2: rep.data.rss.channel.item[2]})
this.setState({rssFlux3: rep.data.rss.channel.item[3]})
this.setState({rssFlux4: rep.data.rss.channel.item[4]})
this.setState({rssFlux5: rep.data.rss.channel.item[5]})
this.setState({rssFlux6: rep.data.rss.channel.item[6]})
this.setState({rssFlux7: rep.data.rss.channel.item[7]})
this.setState({rssFlux8: rep.data.rss.channel.item[8]})
this.setState({rssFlux9: rep.data.rss.channel.item[9]})
this.setState({rssFlux10: rep.data.rss.channel.item[10]})
this.setState({rssFlux11: rep.data.rss.channel.item[11]})
this.setState({rssFlux12: rep.data.rss.channel.item[12]})
this.setState({rssFlux13: rep.data.rss.channel.item[13]})
this.setState({rssFlux14: rep.data.rss.channel.item[14]})
});
})
}
createAPIRequest(ID) {
const APIRquest = this.state.apiWidgetAPI+ID+"/invoke"
return (APIRquest)
}
getRSSName() {
return (
<div>
{this.state.cat.title}
</div>
)
}
makeFahr(cel) {
cel = (cel * (9 / 5)) + 32;
return cel;
}
getMeteo() {
let temp = this.state.meteoData.temp - 273;
let temp_min = this.state.meteoData.temp_min - 273;
let temp_max = this.state.meteoData.temp_max - 273;
let weather = this.state.meteoDataSky.description;
if (!this.state.celcius) {
temp = this.makeFahr(temp);
temp_min = this.makeFahr(temp_min);
temp_max = this.makeFahr(temp_max);
}
return (
<div>
<p>Paris</p>
<ul>
<p>Temperature: {temp.toFixed(1)}</p>
<p>Temperature Min: {temp_min.toFixed(1)}</p>
<p>Temperature Max: {temp_max.toFixed(1)}</p>
<p>Weather: {weather}</p>
</ul>
</div>
)
}
getRSSList() {
return (
<div>
<div>
<ul>
<a href={this.state.rssFlux0.link}>{this.state.rssFlux0.title}</a>
<p>{this.state.rssFlux0.pubDate}</p>
<p>{this.state.rssFlux0.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux1.link}>{this.state.rssFlux1.title}</a>
<p>{this.state.rssFlux1.pubDate}</p>
<p>{this.state.rssFlux1.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux2.link}>{this.state.rssFlux2.title}</a>
<p>{this.state.rssFlux2.pubDate}</p>
<p>{this.state.rssFlux2.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux3.link}>{this.state.rssFlux3.title}</a>
<p>{this.state.rssFlux3.pubDate}</p>
<p>{this.state.rssFlux3.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux4.link}>{this.state.rssFlux4.title}</a>
<p>{this.state.rssFlux4.pubDate}</p>
<p>{this.state.rssFlux4.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux5.link}>{this.state.rssFlux5.title}</a>
<p>{this.state.rssFlux5.pubDate}</p>
<p>{this.state.rssFlux5.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux6.link}>{this.state.rssFlux6.title}</a>
<p>{this.state.rssFlux6.pubDate}</p>
<p>{this.state.rssFlux6.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux7.link}>{this.state.rssFlux7.title}</a>
<p>{this.state.rssFlux7.pubDate}</p>
<p>{this.state.rssFlux7.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux8.link}>{this.state.rssFlux8.title}</a>
<p>{this.state.rssFlux8.pubDate}</p>
<p>{this.state.rssFlux8.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux9.link}>{this.state.rssFlux9.title}</a>
<p>{this.state.rssFlux9.pubDate}</p>
<p>{this.state.rssFlux9.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux10.link}>{this.state.rssFlux10.title}</a>
<p>{this.state.rssFlux10.pubDate}</p>
<p>{this.state.rssFlux10.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux11.link}>{this.state.rssFlux11.title}</a>
<p>{this.state.rssFlux11.pubDate}</p>
<p>{this.state.rssFlux11.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux12.link}>{this.state.rssFlux12.title}</a>
<p>{this.state.rssFlux12.pubDate}</p>
<p>{this.state.rssFlux12.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux13.link}>{this.state.rssFlux13.title}</a>
<p>{this.state.rssFlux13.pubDate}</p>
<p>{this.state.rssFlux13.description}</p>
</ul>
<ul>
<a href={this.state.rssFlux14.link}>{this.state.rssFlux14.title}</a>
<p>{this.state.rssFlux14.pubDate}</p>
<p>{this.state.rssFlux14.description}</p>
</ul>
</div>
</div>
)
}
changeUnity() {
if (!this.state.celcius) {
this.setState({celcius: 1});
} else {
this.setState({celcius: 0});
}
}
changeMeteoValue() {
return (
<div>
<p>Météo</p>
<button onClick={this.changeUnity}>C°/F°</button>
</div>
)
}
render() {
return (
<div className="widgets-container">
<Widget
title={this.changeMeteoValue()}
content={this.getMeteo()}
/>
<Widget
title={this.getRSSName()}
content={this.getRSSList()}
/>
</div>
)
}
}; | 27.978541 | 80 | 0.612517 |
1a9a0976e0f976f255473b44742aa85dd64cbbfe | 336 | js | JavaScript | src/queries/get-countries.js | tanshunyuan/woo-next | 680d4f9890c72d69d8395d171001e7913b7e2b6c | [
"MIT"
] | null | null | null | src/queries/get-countries.js | tanshunyuan/woo-next | 680d4f9890c72d69d8395d171001e7913b7e2b6c | [
"MIT"
] | null | null | null | src/queries/get-countries.js | tanshunyuan/woo-next | 680d4f9890c72d69d8395d171001e7913b7e2b6c | [
"MIT"
] | null | null | null | import { gql } from "@apollo/client";
/**
* GraphQL countries query.
*/
const GET_COUNTRIES = gql`
query GET_COUNTRIES {
wooCountries {
billingCountries {
countryCode
countryName
}
shippingCountries {
countryCode
countryName
}
}
}
`;
export default GET_COUNTRIES;
| 15.272727 | 37 | 0.595238 |
1a9ae9d3fb557ec128ed86d0b27a679163046b40 | 1,276 | js | JavaScript | docs/.vuepress/config.js | exreplay/vuex-decorators | 46113bb13aa6f2ced1cbbae331772873742794bd | [
"MIT"
] | null | null | null | docs/.vuepress/config.js | exreplay/vuex-decorators | 46113bb13aa6f2ced1cbbae331772873742794bd | [
"MIT"
] | 4 | 2019-11-02T09:58:32.000Z | 2020-05-22T13:20:54.000Z | docs/.vuepress/config.js | exreplay/vuex-decorators | 46113bb13aa6f2ced1cbbae331772873742794bd | [
"MIT"
] | null | null | null | module.exports = {
title: 'Vuex Decorators',
description: 'Official documentation for @averjs/vuex-decorators',
themeConfig: {
repo: 'exreplay/vuex-decorators',
displayAllHeaders: true,
sidebarDepth: 1,
nav: [
{ text: 'Guide', link: '/guide/' },
{ text: 'Release Notes', link: 'https://github.com/exreplay/vuex-decorators/releases' }
],
sidebar: {
'/': [
'/',
'/guide/',
{
title: 'API',
collapsable: false,
sidebarDepth: 0,
children: [
'/api/vuex-module/',
'/api/export-vuex-store/',
'/api/config/'
]
},
{
title: 'Decorators',
path: '/decorators/',
collapsable: false,
sidebarDepth: 0,
children: [
'/decorators/vuex-class/',
'/decorators/getter/',
'/decorators/mutation/',
'/decorators/action/',
'/decorators/has-getter/',
'/decorators/has-getter-and-mutation/',
'/decorators/nested/'
]
},
{
title: 'Type Safety',
path: '/type-safety/',
collapsable: false,
sidebarDepth: 0
}
]
}
}
} | 25.52 | 93 | 0.468652 |
1a9bfacd5e2e8b4ea3b8863edbdcead1b4d34216 | 2,780 | js | JavaScript | __tests__/generic-name.test.js | fossabot/jest-serializer-functions | e4bf53e88a5e96117f8c742e44f897517ecec449 | [
"MIT"
] | null | null | null | __tests__/generic-name.test.js | fossabot/jest-serializer-functions | e4bf53e88a5e96117f8c742e44f897517ecec449 | [
"MIT"
] | 39 | 2019-03-04T11:15:20.000Z | 2021-08-10T20:39:40.000Z | __tests__/generic-name.test.js | pauldcomanici/jest-serializer-functions | fc658b504596de1baea6fe93ace476f92221043c | [
"MIT"
] | 1 | 2019-05-01T09:50:30.000Z | 2019-05-01T09:50:30.000Z | // tested
import genericName from './../src/generic-name';
// services
import utils from './../src/utils';
jest.mock('./../src/utils');
describe('genericName', () => {
const mocks = {
propName: 'nameForProp',
};
const genericNameByKey = genericName(mocks.propName);
let testSpecificMocks;
beforeAll(() => {
mocks.value = function () {/*impl*/};
mocks.value[mocks.propName] = 'prop-name-value';
});
beforeEach(() => {
testSpecificMocks = {};
});
describe('print', () => {
afterEach(() => {
utils.print.mockClear();
});
it('should print using property value from function', () => {
genericNameByKey.print(mocks.value);
expect(utils.print).toHaveBeenCalledWith(mocks.value[mocks.propName]);
});
});
describe('testFunction', () => {
it('should return true when function has desired property with truthy value', () => {
expect(genericNameByKey.testFunction(mocks.value)).toBe(true);
});
it('should return false when function does not have desired property', () => {
expect(genericNameByKey.testFunction({})).toBe(false);
});
it('should return false when function has desired property with falsy value', () => {
testSpecificMocks.value = function () {/*impl*/};
testSpecificMocks.value[mocks.propName] = false;
expect(genericNameByKey.testFunction(testSpecificMocks.value)).toBe(false);
});
});
describe('test', () => {
beforeAll(() => {
jest.spyOn(genericNameByKey, 'testFunction').mockReturnValue(true);
});
afterEach(() => {
utils.test.mockClear();
genericNameByKey.testFunction.mockClear();
});
afterAll(() => {
genericNameByKey.testFunction.mockRestore();
});
it('will use utility tester to check if value is a function', () => {
genericNameByKey.test(testSpecificMocks.value);
expect(utils.test).toHaveBeenCalledWith(testSpecificMocks.value);
});
it('will use own tester to check if value has desired property with truthy value', () => {
genericNameByKey.test(testSpecificMocks.value);
expect(genericNameByKey.testFunction).toHaveBeenCalledWith(testSpecificMocks.value);
});
it('returns true if utility tester and own tester returns true', () => {
expect(genericNameByKey.test(testSpecificMocks.value)).toBe(true);
});
it('returns false if utility tester returns false', () => {
utils.test.mockReturnValueOnce(false);
expect(genericNameByKey.test(testSpecificMocks.value)).toBe(false);
});
it('returns false if own tester returns false', () => {
genericNameByKey.testFunction.mockReturnValueOnce(false);
expect(genericNameByKey.test(testSpecificMocks.value)).toBe(false);
});
});
});
| 29.263158 | 94 | 0.65 |
1a9cddef95fca397b2605c3551499c5276192903 | 2,098 | js | JavaScript | src/pages/PetPage.js | 503292/goit-react-hw-04-pet-store | 4ac9672bd0c7726ccf16aae1e9d6203971a0e149 | [
"Unlicense"
] | null | null | null | src/pages/PetPage.js | 503292/goit-react-hw-04-pet-store | 4ac9672bd0c7726ccf16aae1e9d6203971a0e149 | [
"Unlicense"
] | 5 | 2020-09-07T14:27:48.000Z | 2022-02-26T19:00:33.000Z | src/pages/PetPage.js | 503292/goit-react-hw-04-pet-store | 4ac9672bd0c7726ccf16aae1e9d6203971a0e149 | [
"Unlicense"
] | null | null | null | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import GoBackBtn from '../components/GoBackBtn/GoBackBtn';
import pets from '../pets.json';
import css from './Pages.module.css';
class PetPage extends Component {
state = {};
findOnePet = () => {
const { match } = this.props;
return pets.find(pet => pet.id === match.params.idPets);
};
handleGoback = () => {
const { history, location } = this.props;
if (location.state) {
return history.push(location.state.from);
}
return history.push('/pets');
};
render() {
const pet = this.findOnePet();
return (
<>
<div className={css.onePetWrap}>
<GoBackBtn handleGoback={this.handleGoback} />
<p className={css.namePet}>All about {pet.name}</p>
<div className={css.cardPet}>
<div className={css.imagePetWrap}>
<img className={css.imagePet} src={pet.image} alt="pet" />
</div>
<div className={css.infoPetWrap}>
<p className={css.aboutPet}>
Age: <span className={css.dataPet}>{pet.age}</span>
</p>
<p className={css.aboutPet}>
Gender: <span className={css.dataPet}>{pet.gender}</span>
</p>
<p className={css.aboutPet}>
Color: <span className={css.dataPet}>{pet.color}</span>
</p>
<p className={css.aboutPet}>
Breed: <span className={css.dataPet}>{pet.breed}</span>
</p>
</div>
</div>
<p className={css.descriptionPet}>{pet.description}</p>
</div>
</>
);
}
}
PetPage.propTypes = {
history: PropTypes.shape({
push: PropTypes.func.isRequired,
}).isRequired,
location: PropTypes.shape({
state: PropTypes.shape({
from: PropTypes.PropTypes.shape().isRequired,
}),
}).isRequired,
match: PropTypes.shape({
params: PropTypes.shape({
idPets: PropTypes.string.isRequired,
}),
}).isRequired,
};
export default PetPage;
| 28.351351 | 73 | 0.559581 |
1a9d930861a7d1078af783a26cf4771a6af14d11 | 1,203 | js | JavaScript | csaf-validator-lib/lib/optionalTests/optionalTest_6_2_4.js | secvisogram/csaf-validator-service | 07a375c8ab81a519a6ad5fa724d7e5db3dba7c13 | [
"MIT"
] | null | null | null | csaf-validator-lib/lib/optionalTests/optionalTest_6_2_4.js | secvisogram/csaf-validator-service | 07a375c8ab81a519a6ad5fa724d7e5db3dba7c13 | [
"MIT"
] | null | null | null | csaf-validator-lib/lib/optionalTests/optionalTest_6_2_4.js | secvisogram/csaf-validator-service | 07a375c8ab81a519a6ad5fa724d7e5db3dba7c13 | [
"MIT"
] | null | null | null | import Ajv from 'ajv/dist/jtd.js'
const ajv = new Ajv()
const inputSchema = /** @type {const} */ ({
additionalProperties: true,
properties: {
document: {
additionalProperties: true,
properties: {
tracking: {
additionalProperties: true,
properties: {
revision_history: {
elements: { additionalProperties: true, properties: {} },
},
},
},
},
},
},
})
const validate = ajv.compile(inputSchema)
/**
* @param {any} doc
*/
export default function optionalTest_6_2_4(doc) {
/** @type {Array<{ message: string; instancePath: string }>} */
const warnings = []
const context = { warnings }
if (!validate(doc)) {
return context
}
doc.document.tracking.revision_history?.forEach(
(revisionHistoryItem, revisionHistoryItemIndex) => {
const { number } = revisionHistoryItem
if (typeof number === 'string' && number.includes('+')) {
warnings.push({
message: 'build metadata in revision history',
instancePath: `/document/tracking/revision_history/${revisionHistoryItemIndex}/number`,
})
}
}
)
return context
}
| 22.698113 | 97 | 0.591022 |
1a9df5c0c372be033e9409f5e15f6bd06d8f47da | 1,723 | js | JavaScript | public/javascripts/admin/application.js | hasham2/radiant | 401cb538e2695412e169b2e8d053847512bb71a2 | [
"MIT"
] | 1 | 2016-05-08T17:16:47.000Z | 2016-05-08T17:16:47.000Z | public/javascripts/admin/application.js | hasham2/radiant | 401cb538e2695412e169b2e8d053847512bb71a2 | [
"MIT"
] | null | null | null | public/javascripts/admin/application.js | hasham2/radiant | 401cb538e2695412e169b2e8d053847512bb71a2 | [
"MIT"
] | null | null | null | // Popup Images
Popup.BorderImage = '/images/admin/popup_border_background.png';
Popup.BorderTopLeftImage = '/images/admin/popup_border_top_left.png';
Popup.BorderTopRightImage = '/images/admin/popup_border_top_right.png';
Popup.BorderBottomLeftImage = '/images/admin/popup_border_bottom_left.png';
Popup.BorderBottomRightImage = '/images/admin/popup_border_bottom_right.png';
// Status Images
Status.SpinnerImage = '/images/admin/status_spinner.gif';
Status.BackgroundImage = '/images/admin/status_background.png';
Status.TopLeftImage = '/images/admin/status_top_left.png';
Status.TopRightImage = '/images/admin/status_top_right.png';
Status.BottomLeftImage = '/images/admin/status_bottom_left.png';
Status.BottomRightImage = '/images/admin/status_bottom_right.png';
Event.addBehavior.reassignAfterAjax = true;
// Behaviors
Event.addBehavior({
'a.popup': Popup.TriggerBehavior(),
'table#site_map': SiteMapBehavior(),
'input#page_title': function() {
var title = this;
var slug = $('page_slug');
var breadcrumb = $('page_breadcrumb');
var oldTitle = title.value;
if (!slug || !breadcrumb) return;
new Form.Element.Observer(title, 0.15, function() {
if (oldTitle.toSlug() == slug.value) slug.value = title.value.toSlug();
if (oldTitle == breadcrumb.value) breadcrumb.value = title.value;
oldTitle = title.value;
});
},
'div#tab_control': TabControlBehavior(),
'table.index': RuledTableBehavior(),
'form': Status.FormBehavior(),
'form input.activate': function() {
this.activate();
},
'form textarea': CodeAreaBehavior(),
'body': ShortcutKeysBehavior
}); | 33.134615 | 77 | 0.691236 |
1a9e345e946de55b1387fba8fd2396fee6d4bbb2 | 1,322 | js | JavaScript | recipe-category/recipe-category.service.js | AndreLuisReisSantos/sistoqueBackEnd | 11cf298c47eca2271f851649675191d18c721411 | [
"MIT"
] | null | null | null | recipe-category/recipe-category.service.js | AndreLuisReisSantos/sistoqueBackEnd | 11cf298c47eca2271f851649675191d18c721411 | [
"MIT"
] | null | null | null | recipe-category/recipe-category.service.js | AndreLuisReisSantos/sistoqueBackEnd | 11cf298c47eca2271f851649675191d18c721411 | [
"MIT"
] | null | null | null | const db = require('_helpers/db');
module.exports = {
getAll,
getById,
create,
update,
delete: _delete
};
async function getAll() {
return db.RecipeCategory.findAll();
}
async function getById(id) {
return getRecipeCategory(id);
}
async function create(payload) {
if (await db.RecipeCategory.findOne({ where: { nome: payload.nome } })) {
throw new Error('Categoria de receita já cadastrada!');
}
await db.RecipeCategory.create(payload);
}
async function update(id, payload) {
const recipeCategory = await getRecipeCategory(id);
const recipeCategoryChanged = payload.nome && recipeCategory.nome !== payload.nome;
if (recipeCategoryChanged && await db.RecipeCategory.findOne({ where: { nome: payload.nome } })) {
throw new Error('A categoria de receita"' + payload.nome + '" já existe!');
}
Object.assign(recipeCategory, payload);
await recipeCategory.save();
return recipeCategory.get();
}
async function _delete(id) {
const recipeCategory = await getRecipeCategory(id);
await recipeCategory.destroy();
}
async function getRecipeCategory(id) {
const recipeCategory = await db.RecipeCategory.findByPk(id);
if (!recipeCategory) throw new Error('Categoria de receita não encontrada!');
return recipeCategory;
} | 25.921569 | 102 | 0.691377 |
1a9f279e7a4bce7732df2a102fea011de67f4b19 | 5,170 | js | JavaScript | src/actionresponse.js | aarong/feedme-server-core | 3d391e6dbca82ee7c05cd942c00e115501c472e9 | [
"MIT"
] | null | null | null | src/actionresponse.js | aarong/feedme-server-core | 3d391e6dbca82ee7c05cd942c00e115501c472e9 | [
"MIT"
] | 4 | 2020-07-17T02:16:43.000Z | 2021-09-06T12:56:53.000Z | src/actionresponse.js | aarong/feedme-server-core | 3d391e6dbca82ee7c05cd942c00e115501c472e9 | [
"MIT"
] | null | null | null | import check from "check-types";
import jsonExpressible from "json-expressible";
/**
* Represents an ActionResponse message.
* @typedef {Object} ActionResponse
*/
const proto = {};
/**
* Factory function.
* @param {Server} server
* @param {ActionRequest} areq
* @returns {ActionResponse}
*/
export default function actionResponseFactory(server, areq) {
const actionResponse = Object.create(proto);
/**
* Reference to the server. Null after a call to success(),
* failure(), or _neutralize().
* @memberof ActionResponse
* @instance
* @private
* @type {?Server}
*/
actionResponse._server = server;
/**
* Reference to the associated ActionRequest object.
* @memberof ActionResponse
* @instance
* @private
* @type {ActionRequest}
*/
actionResponse._actionRequest = areq;
/**
* Flag indicating whether the application already responded.
* @memberof ActionResponse
* @instance
* @private
* @type {bool}
*/
actionResponse._appResponded = false;
/**
* Flag indicating whether the server has neutralized this object.
* @memberof ActionResponse
* @instance
* @private
* @type {bool}
*/
actionResponse._neutralized = false;
return actionResponse;
}
/**
* Called by the application to return a successful ActionResponse.
*
* After being neutralized, the first call to success() or failure() will
* still return successfully, but will do nothing. Subsequent calls will
* throw ALREADY_RESPONDED.
* @memberof ActionResponse
* @instance
* @param {Object} actionData
* @throws {Error} "INVALID_ARGUMENT: ..."
* @throws {Error} "ALREADY_RESPONDED: ..."
*/
proto.success = function success(actionData) {
// Check action data type
if (!check.object(actionData)) {
throw new Error("INVALID_ARGUMENT: Invalid action data.");
}
// Check that action data is JSON-expressible
if (!jsonExpressible(actionData)) {
throw new Error("INVALID_ARGUMENT: Action data is not JSON-expressible.");
}
// Throw if the app already responded
if (this._appResponded) {
throw new Error(
"ALREADY_RESPONDED: The success() or failure() method has already been called."
);
}
// Update state to reflect app response
this._appResponded = true;
const s = this._server;
this._server = null;
// If not neutralized, call the server function
if (!this._neutralized) {
s._appActionSuccess(
this._actionRequest.clientId,
this._actionRequest._actionCallbackId,
actionData
);
}
};
/**
* Called by the application to return an ActionResponse indicating failure.
*
* After being neutralized, the first call to success() or failure() will
* still return successfully, but will do nothing. Subsequent calls will
* throw ALREADY_RESPONDED.
* @memberof ActionResponse
* @instance
* @param {String} errorCode
* @param {Object} errorData
* @throws {Error} "INVALID_ARGUMENT: ..."
* @throws {Error} "ALREADY_RESPONDED: ..."
*/
proto.failure = function failure(errorCode, errorData) {
// Check error code - empty is spec-valid
if (!check.string(errorCode)) {
throw new Error("INVALID_ARGUMENT: Invalid error code.");
}
// Check error data type
if (!check.object(errorData)) {
throw new Error("INVALID_ARGUMENT: Invalid error data.");
}
// Check error data is JSON-expressible
if (!jsonExpressible(errorData)) {
throw new Error("INVALID_ARGUMENT: Error data is not JSON-expressible.");
}
// Throw if the app already responded
if (this._appResponded) {
throw new Error(
"ALREADY_RESPONDED: The success() or failure() method has already been called."
);
}
// Update state to reflect app response
this._appResponded = true;
const s = this._server;
this._server = null;
// If not neutralized, call the server function
if (!this._neutralized) {
s._appActionFailure(
this._actionRequest.clientId,
this._actionRequest._actionCallbackId,
errorCode,
errorData
);
}
};
/**
* Called by the server to neutralize the object.
*
* The server is not intended to call this method more than once, and is
* not intended to call it after the application has called success() or
* failure(), so both of those behaviors throw errors - indicates unintended
* server behavior.
*
* After being neutralized, the first call to success() or failure() will
* still return successfully, but will do nothing. Subsequent calls will
* throw ALREADY_RESPONDED.
* @memberof ActionResponse
* @instance
* @throws {Error} "ALREADY_NEUTRALIZED: ..."
* @throws {Error} "ALREADY_RESPONDED: ..."
*/
proto._neutralize = function _neutralize() {
// Throw if the app already responded - bad server behavior
if (this._appResponded) {
throw new Error(
"ALREADY_RESPONDED: The success() or failure() method has already been called."
);
}
// Throw if already neutralized - bad server behavior
if (this._neutralized) {
throw new Error(
"ALREADY_NEUTRALIZED: The object has already been neutralized."
);
}
// Update state to reflect the neutralization
this._neutralized = true;
this._server = null;
};
| 26.927083 | 85 | 0.69207 |
1a9f5d33f1e9c8ffe5cb605aee2fcdf111a56e9a | 337 | js | JavaScript | docs/example/process/process-umask.js | tsejx/node-guidebook | 247171b628de140819e8ae0ae962b341d9d640ec | [
"MIT"
] | 7 | 2020-09-29T09:21:28.000Z | 2022-03-18T14:37:42.000Z | docs/example/process/process-umask.js | tsejx/node-guidebook | 247171b628de140819e8ae0ae962b341d9d640ec | [
"MIT"
] | 3 | 2020-09-04T15:41:14.000Z | 2022-02-22T13:17:24.000Z | docs/example/process/process-umask.js | tsejx/node-guidebook | 247171b628de140819e8ae0ae962b341d9d640ec | [
"MIT"
] | 2 | 2021-06-13T06:14:33.000Z | 2021-08-09T02:22:58.000Z | // process.umask() 方法用于返回或设置 Node.js 进程的默认创建文件的权限掩码
// 子进程从父进程集成这个掩码
// 不传参数时,默认返回当前掩码,如果传递了参数,创建文件掩码就被设置为参数值,并且返回之前的掩码
const newmask = 0o022;
const oldmask = process.umask(newmask);
console.log(`将 umask 从 ${oldmask.toString(8)} 更改为 ${newmask.toString(8)}`);
// 输出(示例):将 umask 从 22 更改为 22
// Worker 线程能够读取 umask,但是尝试设置 umask 将会导致抛出异常
| 28.083333 | 75 | 0.744807 |
1a9f6dcdbe995316ca8a240d2701c6b0f08e5bf6 | 1,023 | js | JavaScript | db/letUsSchema.js | IceFractal/LetUs | 4602e396a5d6caa83071cd3bea59347ebabc7346 | [
"MIT"
] | null | null | null | db/letUsSchema.js | IceFractal/LetUs | 4602e396a5d6caa83071cd3bea59347ebabc7346 | [
"MIT"
] | null | null | null | db/letUsSchema.js | IceFractal/LetUs | 4602e396a5d6caa83071cd3bea59347ebabc7346 | [
"MIT"
] | null | null | null | const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = mongoose.Schema.Types.ObjectId;
// define models
const Users = new Schema({
id: { type: String, unique: true, required: true },
name: { type: String, unique: true, required: true },
pic: String,
phoneNumber: String,
friendRank: Number,
lettuceLeaves: Number,
friends: [{ type: String }],
favorites: [String],
});
const Events = new Schema({
creator: { type: String, required: true },
data: { type: String, required: true },
attendees: { type: String },
checkIns: [{ type: Boolean }],
linkHash: { type: String, required: true },
topEvent: { type: String },
});
const EventGoers = new Schema({
userId: { type: String, required: true },
event: { type: ObjectId, ref: 'Events', required: true },
});
// add models to db
module.exports.Users = mongoose.model('Users', Users);
module.exports.Events = mongoose.model('Events', Events);
module.exports.EventGoers = mongoose.model('EventGoers', EventGoers);
| 28.416667 | 69 | 0.676442 |
1a9f7fe99ae01bf3e7127548e6e22968254df4fd | 2,329 | js | JavaScript | js/main.js | isacfadoni/Responsr | 69c96e2a5669e878dc77df966c81b4952663ff15 | [
"MIT"
] | 1 | 2016-05-31T12:54:20.000Z | 2016-05-31T12:54:20.000Z | js/main.js | isacfadoni/Responsr | 69c96e2a5669e878dc77df966c81b4952663ff15 | [
"MIT"
] | 1 | 2016-01-19T01:44:26.000Z | 2016-01-19T01:44:26.000Z | js/main.js | isacfadoni/Responsr | 69c96e2a5669e878dc77df966c81b4952663ff15 | [
"MIT"
] | null | null | null | /*
* Project: Responsr.
* Description: A simple tool for testing responsive layouts.
* Last Update: 2016/04/29
*
* Author: Isac Fadoni
* GitHub: https://github.com/isacfadoni/responsr.app
* Copyright: You can use or edit this code under the MIT license.
*
*/
var Responsr = Responsr || {};
;(function (field, display, listContainer) {
'use strict';
var urlField = document.getElementById(field)
, displayContent = document.getElementById(display)
, navDrawer = document.getElementById(listContainer)
, urlFieldValue = null
, hasLocalhost = null
, hasHttp = null
;
Responsr.initialize = () => {
Responsr.loadDeviceList();
Responsr.addEventListeners();
};
Responsr.fillDisplay = () => {
urlFieldValue = urlField.value;
hasLocalhost = urlFieldValue.includes('localhost');
hasHttp = urlFieldValue.includes('http://');
if (hasLocalhost || !hasHttp) displayContent.src = `http://${urlFieldValue}`;
};
Responsr.clearDisplay = () => {
if (urlFieldValue.length === 0) displayContent.src = '';
};
Responsr.addEventListeners = () => {
urlField.addEventListener('change', () => {
Responsr.fillDisplay();
Responsr.clearDisplay();
}, false);
};
Responsr.getDevices = (callback) => {
var dbReq = new XMLHttpRequest()
, pathName = window.location.pathname
, pathIndex = pathName.lastIndexOf('/')
, rootPath = pathName.slice(0, pathIndex)
, deviceList = null
;
dbReq.open('GET', `${rootPath}devices_db/devices.json`);
dbReq.addEventListener('load', () => {
deviceList = JSON.parse(dbReq.responseText);
callback(deviceList);
}, false);
dbReq.send();
};
Responsr.renderDeviceList = (db) => {
for (var devices in db) {
if (db.hasOwnProperty(devices)) {
var all = db[devices]
var smartphones = all.Smartphones;
var tablets = all.Tablets;
var laptops = all.Laptops;
// # TODO
Responsr.createListItem('');
}
};
};
Responsr.loadDeviceList = () => {
Responsr.getDevices(Responsr.renderDeviceList);
};
Responsr.createListItem = () => {
// # TODO
};
return {
initialize: Responsr.initialize()
};
})('urlField', 'displayContent', 'navDrawer');
var app = Responsr.initialize;
| 23.29 | 81 | 0.626878 |
1aa098dea613c868d8d0a9fbb219b988dd37f5f8 | 798 | js | JavaScript | __test__/lib/color-contrast-helper.test.js | dcCoder9/Spoke | d307b4590710d92aa9ebdf838d1293e80df28f91 | [
"MIT"
] | 3 | 2018-06-13T19:32:10.000Z | 2019-11-22T12:34:36.000Z | __test__/lib/color-contrast-helper.test.js | dcCoder9/Spoke | d307b4590710d92aa9ebdf838d1293e80df28f91 | [
"MIT"
] | 3 | 2020-12-03T03:35:54.000Z | 2021-09-10T04:44:28.000Z | __test__/lib/color-contrast-helper.test.js | dcCoder9/Spoke | d307b4590710d92aa9ebdf838d1293e80df28f91 | [
"MIT"
] | 2 | 2020-08-18T19:32:05.000Z | 2022-01-29T12:52:51.000Z | import { setContrastingColor } from "../../src/lib/color-contrast-helper";
import theme from "../../src/styles/theme";
describe("test setContrastingColor", () => {
it("returns darkGray when a light color is passed in", () => {
expect(setContrastingColor("#fff")).toEqual(theme.colors.darkGray);
});
it("returns white when a dark color is passed in", () => {
expect(setContrastingColor("#000")).toEqual(theme.colors.white);
});
it("returns darkGray when a color is passed in with an opacity of less than .4", () => {
expect(setContrastingColor("rgba(0, 0, 0, .39)")).toEqual(
theme.colors.darkGray
);
});
it("returns darkGray when an invalid color is passed in", () => {
expect(setContrastingColor("incorrect")).toEqual(theme.colors.darkGray);
});
});
| 33.25 | 90 | 0.657895 |
1aa0b6459061d8aefe6d85c6a864186e34c1e50a | 859 | js | JavaScript | client/src/components/Modal/Modal.js | GlebMaca/VR_spaceXwatch_map | 32418bcd5687a0893a32425630c1384e4e2f3471 | [
"MIT"
] | 1 | 2018-10-28T23:50:35.000Z | 2018-10-28T23:50:35.000Z | client/src/components/Modal/Modal.js | GlebMaca/VR_spaceXwatch_map | 32418bcd5687a0893a32425630c1384e4e2f3471 | [
"MIT"
] | null | null | null | client/src/components/Modal/Modal.js | GlebMaca/VR_spaceXwatch_map | 32418bcd5687a0893a32425630c1384e4e2f3471 | [
"MIT"
] | 3 | 2020-04-24T02:32:05.000Z | 2022-03-14T23:46:00.000Z | import React, {Component} from 'react';
import './Modal.css'
class Modal extends Component {
render(){
if(this.props.name) {
return(
<div className="modal">
<div onClick={this.props.closeMe} className="modal-close"> X Close</div>
<h2>{this.props.name}</h2>
<span><p id="flightNumber">{this.props.flightNumber}</p></span>
<hr />
<span><p id="flightYear">{this.props.flightYear}</p></span>
<div className="img-container">
<img id="image" src={this.props.image} alt={this.props.name} />
</div>
<div id="m_desc_wrapper">
<p id="description">{this.props.desc}</p>
</div>
</div>
)
}
else {
return null;
}
}
}
export default Modal; | 28.633333 | 83 | 0.49709 |
1aa0c7f7009a1528e4912b8e43589f2884e89cac | 667 | js | JavaScript | lib/SessionManager.js | zeyongTsai/egg-auths | faf1864738473efc266a0b2dc674c965ab0a2a0b | [
"MIT"
] | 3 | 2021-01-14T06:54:00.000Z | 2021-02-05T01:44:15.000Z | lib/SessionManager.js | zeyongTsai/egg-auths | faf1864738473efc266a0b2dc674c965ab0a2a0b | [
"MIT"
] | null | null | null | lib/SessionManager.js | zeyongTsai/egg-auths | faf1864738473efc266a0b2dc674c965ab0a2a0b | [
"MIT"
] | null | null | null | /**
* @class
* @classdesc 会话管理器,主要负责会话 id 的存取,默认在 session 中放置 token 的 uuid,也从 session 中取回
*/
class SessionManager {
/**
* @constructor
* @param {object} ctx egg's ctx
*/
constructor (ctx) {
/**
* egg 的 ctx 对象,通过它来调用相关的其他资源
* @public
*/
this.ctx = ctx
}
/**
* 获取会话 id
* @returns {undefined|string|number}
*/
async getSession () {
return this.ctx.session.uuid
}
/**
* 设置会话 id
* @param {number|string} value 会话 id
*/
async setSession (value) {
this.ctx.session.uuid = value
}
/**
* 销毁会话
*/
async destroy () {
this.ctx.session.uuid = null
}
}
module.exports = SessionManager | 17.102564 | 77 | 0.571214 |
1aa159a188dacf5f2ec4ef17e570bc03d1d4a702 | 1,293 | js | JavaScript | application/Browser/_Event/Server/native/_IndexedDB/Connector.min.js | nikitabelotelov/coffee | 63cd862b827337a373301677f02d341d59ce2485 | [
"MIT"
] | null | null | null | application/Browser/_Event/Server/native/_IndexedDB/Connector.min.js | nikitabelotelov/coffee | 63cd862b827337a373301677f02d341d59ce2485 | [
"MIT"
] | null | null | null | application/Browser/_Event/Server/native/_IndexedDB/Connector.min.js | nikitabelotelov/coffee | 63cd862b827337a373301677f02d341d59ce2485 | [
"MIT"
] | null | null | null | define("Browser/_Event/Server/native/_IndexedDB/Connector",["require","exports","Core/Deferred","Browser/_Event/Server/native/_IndexedDB/Writer","Browser/_Event/Server/native/_IndexedDB/Reader"],function(e,r,d,s,t){"use strict";if(Object.defineProperty(r,"__esModule",{value:true}),"undefined"!==typeof indexedDB&&null!==indexedDB&&indexedDB instanceof IDBFactory)try{indexedDB.deleteDatabase("sbis.seb")}catch(e){}var n=function(){function o(e,r,t){this.db=e,this.storeName=r,this.adapter=t}return o.connect=function(e,t,n){var i=new d,r;if("object"!==typeof indexedDB||null===indexedDB)return d.fail("В окружении нет indexedDB");try{r=indexedDB.open(e,n.getVersion())}catch(e){return i.errback(e),i}return r.onupgradeneeded=function(e){var r=this.result;r.onerror=function(e){},new s.Writer(r,t,n).createStore()},r.onsuccess=function(e){var r=this.result;i.callback(new o(r,t,n))},r.onerror=function(e){return i.errback("You haven't rights to use IndexDB."),true},i},o.prototype.createWriter=function(){return new s.Writer(this.db,this.storeName,this.adapter)},o.prototype.createReader=function(){return new t.Reader(this.db,this.storeName,this.adapter)},o.DB_DEBUG="sbis.seb.debug",o.DB_DELIVER="sbis.seb.deliver",o.DEBUG_STORE_NAME="logs",o.EVENTS_STORE_NAME="events",o}();r.Connector=n}); | 1,293 | 1,293 | 0.766435 |
1aa1dff718e2ebe3d65bf01e2c7f15c38765d45a | 1,403 | js | JavaScript | core/examples/luigi-example-angular/src/assets/luigi-config.js | anandsgar-sap/luigi | 5d3418361f2e2fca5b959515274dfc0aa4e8ff8d | [
"Apache-2.0"
] | null | null | null | core/examples/luigi-example-angular/src/assets/luigi-config.js | anandsgar-sap/luigi | 5d3418361f2e2fca5b959515274dfc0aa4e8ff8d | [
"Apache-2.0"
] | null | null | null | core/examples/luigi-example-angular/src/assets/luigi-config.js | anandsgar-sap/luigi | 5d3418361f2e2fca5b959515274dfc0aa4e8ff8d | [
"Apache-2.0"
] | null | null | null | Luigi.setConfig({
navigation: {
nodes: () => [
{
pathSegment: 'project',
label: 'Project',
icon: 'home',
hideFromNav: true,
hideSideNav: true,
loadingIndicator: {
enabled: false
},
viewUrl: 'https://chr-16763-t1-i077611-streamlinecockpit.cfapps.sap.hana.ondemand.com',
children: [
{
pathSegment: 'overview/:projectId',
label: 'Automation',
hideFromNav: true,
hideSideNav: true,
viewUrl: 'https://chr-16763-t1-i077611-streamlinecockpit.cfapps.sap.hana.ondemand.com/project/overview/:projectId',
loadingIndicator: {
enabled: false
}
},
{
pathSegment: 'automation',
label: 'Automation',
hideFromNav: true,
hideSideNav: true,
viewUrl: 'https://chr-16763-t1--approuter--ipa-od--chryso--16763.internal.cfapps.sap.hana.ondemand.com/studio/?embed=true&artifactType=automation&artifactUid=3c253ba9-f08e-495c-a810-518b9c27a72d#84cc7c73-ba18-405b-aee3-1f3443edff48',
loadingIndicator: {
enabled: false
}
}
]
},
]
},
settings: {
header: {
title: 'Application Cockpit',
logo: '/logo.svg'
},
responsiveNavigation: 'simpleMobileOnly'
}
});
| 29.851064 | 245 | 0.546686 |
1aa26af8f39b43a1d6add01a9c899d9f3c829be0 | 215 | js | JavaScript | web/demo/server.js | vinloong/peter_notes | 93fe38dadc5b59ea85b03aff513baeb5f300049f | [
"MIT"
] | 2 | 2019-12-02T02:59:17.000Z | 2019-12-02T02:59:45.000Z | web/demo/server.js | vinloong/peter_notes | 93fe38dadc5b59ea85b03aff513baeb5f300049f | [
"MIT"
] | 6 | 2020-07-18T15:51:40.000Z | 2022-02-27T13:43:25.000Z | web/demo/server.js | uncle-dragon/peter_notes | 0054bb7f6ea4e10ca6e2b00e1c5c839aaad6de91 | [
"MIT"
] | 2 | 2018-11-23T12:42:17.000Z | 2021-10-14T03:22:15.000Z | /**
* Created by rain on 2016/1/25.
*/
'use strict';
/*jslint node:true*/
//from koa
const scaffold = require('fs-web-server-scaffold');
const config = require('./config.js');
module.exports = scaffold(config); | 17.916667 | 51 | 0.669767 |
1aa2999b858feafe0a7c4f9a934f51e19fcc0851 | 392 | js | JavaScript | test/wait.test.js | WKHAllen/dtp.js | fe0f4c934b8c92054be8ea6d16add4af915f8d8f | [
"MIT"
] | null | null | null | test/wait.test.js | WKHAllen/dtp.js | fe0f4c934b8c92054be8ea6d16add4af915f8d8f | [
"MIT"
] | null | null | null | test/wait.test.js | WKHAllen/dtp.js | fe0f4c934b8c92054be8ea6d16add4af915f8d8f | [
"MIT"
] | null | null | null | const { WaitGroup } = require('../dist/wait');
test('test wait group', async() => {
const wg = new WaitGroup();
wg.add(3);
expect(wg.getTotal()).toBe(3);
wg.done();
expect(wg.getTotal()).toBe(2);
wg.done();
expect(wg.getTotal()).toBe(1);
wg.done();
expect(wg.getTotal()).toBe(0);
wg.add();
expect(wg.getTotal()).toBe(1);
setTimeout(() => wg.done(), 100);
await wg.wait();
});
| 19.6 | 46 | 0.596939 |
1aa29ed50ded19eaa20e715807311f012d81278e | 1,126 | js | JavaScript | stories/Counter.stories.js | hitosu/duckness | 47093d77e15676d55e797d855c0f42e7ead17d9f | [
"MIT"
] | 2 | 2020-05-20T12:28:35.000Z | 2021-01-25T00:45:20.000Z | stories/Counter.stories.js | hitosu/duckness | 47093d77e15676d55e797d855c0f42e7ead17d9f | [
"MIT"
] | 116 | 2020-07-25T02:21:49.000Z | 2022-03-28T08:07:43.000Z | stories/Counter.stories.js | hitosu/duckness | 47093d77e15676d55e797d855c0f42e7ead17d9f | [
"MIT"
] | null | null | null | import ReactReduxCounterPool from './apps/Counter/react-redux-pool/CounterPool'
import UsePoolCounterPool, { render as UsePoolCounterPool_render } from './apps/Counter/use-pool/CounterPool'
import UsePoolEpicCounterPool, {
render as UsePoolEpicCounterPool_render
} from './apps/Counter/use-pool-epic/CounterPool'
import UsePoolConnectCounterPool, {
render as UsePoolConnectCounterPool_render
} from './apps/Counter/use-pool-connect/CounterPool'
ReactReduxCounterPool.build()
UsePoolCounterPool.build()
UsePoolEpicCounterPool.build()
UsePoolConnectCounterPool.build()
export default {
title: 'Counter'
}
export const ReactReduxCounterStory = () => ReactReduxCounterPool.render()
ReactReduxCounterStory.storyName = 'react-redux-pool'
export const UsePoolCounterStory = () => UsePoolCounterPool_render()
UsePoolCounterStory.storyName = 'use-pool'
export const UsePoolEpicCounterStory = () => UsePoolEpicCounterPool_render()
UsePoolEpicCounterStory.storyName = 'use-pool-epic'
export const UsePoolConnectCounterStory = () => UsePoolConnectCounterPool_render()
UsePoolConnectCounterStory.storyName = 'use-pool-connect'
| 37.533333 | 109 | 0.817052 |
1aa2d452dc3a0d85749a64e7dcd949190f275a16 | 708 | js | JavaScript | src/resolvers/Subscription.js | lfresnog/Blog_ExamenFinal | 32fa0a2f04cf1ebaf4258e9c7a7debc85e1ee184 | [
"MIT"
] | null | null | null | src/resolvers/Subscription.js | lfresnog/Blog_ExamenFinal | 32fa0a2f04cf1ebaf4258e9c7a7debc85e1ee184 | [
"MIT"
] | 3 | 2021-05-11T00:47:18.000Z | 2021-09-21T06:29:46.000Z | src/resolvers/Subscription.js | lfresnog/Blog_ExamenFinal | 32fa0a2f04cf1ebaf4258e9c7a7debc85e1ee184 | [
"MIT"
] | null | null | null | const Subscription = {
tellMe: {
subscribe: async (parent, args, ctx, info)=>{
const {mail,token,author} = args;
const {client,pubsub} = ctx;
const db = client.db("examenFinal");
const usersCollection = db.collection("users");
const userFinded = await usersCollection.findOne({mail,token});
if(!userFinded) throw new Error("Mail/Token incorrect");
const authorFinded = await usersCollection.findOne({mail:author,author:true});
if(!authorFinded) throw new Error("Author incorrect");
return pubsub.asyncIterator(author);
}
}
};
export {Subscription as default}; | 33.714286 | 90 | 0.591808 |
1aa2e2954f8efeda5034f27a6882a8ce48ccfac0 | 1,494 | js | JavaScript | js/inject.js | jsdelivrbot/huemix-blopscotch | 97cd95fbd8427323c3a73f2e5acc06648fc8d2e0 | [
"MIT"
] | null | null | null | js/inject.js | jsdelivrbot/huemix-blopscotch | 97cd95fbd8427323c3a73f2e5acc06648fc8d2e0 | [
"MIT"
] | null | null | null | js/inject.js | jsdelivrbot/huemix-blopscotch | 97cd95fbd8427323c3a73f2e5acc06648fc8d2e0 | [
"MIT"
] | null | null | null | var s = document.createElement('script');
s.src = "https://cdn.jsdelivr.net/gh/joshisa/huemix-blopscotch/js/hopscotch.highlight.js";
//s.onload = function() {
// this.parentNode.removeChild(this);
//};
(document.head || document.documentElement).appendChild(s);
chrome.extension.sendMessage({}, function(response) {
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
var prefix = "[Huemix Blopscotch]] ";
console.log(prefix + "current page URL is: " + location.href);
// https://api.github.com/repos/joshisa/huemix-blopscotch/git/trees/master?recursive=1
// Array of registered hoplets
whitelist = ["hoplet/demo.js",
"hoplet/jstart.js",
"hoplet/jupyter2.js",
"hoplet/spark.js"];
console.log(prefix + "Number of Hoplets defined : " + whitelist.length);
var i = 0;
while (whitelist[i]) {
// https://rawgit.com/joshisa/huemix-blopscotch/master/ + whitelist[i]
console.log(prefix + "Loading " + whitelist[i]);
proxyXHR.get('https://rawgit.com/joshisa/huemix-blopscotch/master/' + whitelist[i]).onSuccess(function (data) {
eval(data);
});
i++;
}
console.log(prefix + "Hopscotch Dependencies successfully injected");
}
}, 10);
});
| 41.5 | 123 | 0.589692 |
1aa5d34400e19b7b6c00c5f5d8c95b9de87bde1c | 1,707 | js | JavaScript | assets/js/adminPanel.js | fahrudinwhb/hdr | 0f73aed99b5cb9e93613ac9d64cd0e6b249243d0 | [
"MIT"
] | null | null | null | assets/js/adminPanel.js | fahrudinwhb/hdr | 0f73aed99b5cb9e93613ac9d64cd0e6b249243d0 | [
"MIT"
] | null | null | null | assets/js/adminPanel.js | fahrudinwhb/hdr | 0f73aed99b5cb9e93613ac9d64cd0e6b249243d0 | [
"MIT"
] | null | null | null | $(document).ready(function(){
$('.button-collapse').sideNav();
$('select').material_select();
$('.modal-trigger').leanModal();
$('.materialboxed').materialbox();
$('.tooltipped').tooltip({delay: 20});
// if($(".sidebar").height()>$(".content").height()){
// $(".content").height($(".sidebar").height());
// }else{
// $(".sidebar").height($(".content").height());
// }
$(".sidebar").height($(".content").height());
$("#banyak").click(function () {
var sampai = $("#sampai").val();
var mulai = $("#mulai").val();
if(mulai > sampai){
// $("#warning").html("<b>sampai</b> harus lebih besar dari <b>mulai</b>").css("color", "red");
toastfalse("volume akhir harus lebih besar dari volume awal");
return false;
}
});
$("#banyak").click(function () {
if($("#mulai").val() < 0 || $("#sampai").val() < 0 ){
// $("#warning").html("<b>mulai</b> dan <b>sampai</b> tidak boleh kurang dari 0 ").css("color", "red");
toastfalse("volume awal dan volume akhir tidak boleh kurang dari 0");
return false;
}
});
$("#satu").click(function () {
if($("#vol").val() < 0 ){
// $("#warningsatu").html("<b>volume</b> tidak boleh kurang dari 0 ").css("color", "red");
toastfalse("volume tidak boleh kurang dari 0");
return false;
}
});
function toastfalse ($content) {
var $toastContent = $content;
Materialize.toast($toastContent, 5000);
}
$(function () {
$.scrollUp({
animation: 'slide'
});
});
// $(".removefix").click(function () {
// $("#navtop").toggleClass("fix");
// });
});
| 28.45 | 112 | 0.510838 |
1aa6c63fd4174dc761bc92520ce77be29adc50a5 | 237 | js | JavaScript | src/dk/ava/constants/TextAlign.js | martinrossil/avamjs | cbe857c14139bef04b6db088f835c094f41206cb | [
"MIT"
] | null | null | null | src/dk/ava/constants/TextAlign.js | martinrossil/avamjs | cbe857c14139bef04b6db088f835c094f41206cb | [
"MIT"
] | null | null | null | src/dk/ava/constants/TextAlign.js | martinrossil/avamjs | cbe857c14139bef04b6db088f835c094f41206cb | [
"MIT"
] | null | null | null | export default class TextAlign
{
// left|right|center|justify
static get LEFT(){ return "left" };
static get CENTER(){ return "center" };
static get RIGHT(){ return "right" };
static get FILL(){ return "justify" };
} | 29.625 | 43 | 0.632911 |
1aa6ef16e0b3175a1d061bb00bef5de4b8b4d52d | 271 | js | JavaScript | src/components/common/toast/index.js | Jane710/ghymall | abb84a954853660434ad8e31eff29de6f7a3cb2d | [
"MIT"
] | null | null | null | src/components/common/toast/index.js | Jane710/ghymall | abb84a954853660434ad8e31eff29de6f7a3cb2d | [
"MIT"
] | 2 | 2022-02-19T05:51:20.000Z | 2022-02-27T09:16:49.000Z | src/components/common/toast/index.js | Jane710/ghymall | abb84a954853660434ad8e31eff29de6f7a3cb2d | [
"MIT"
] | null | null | null | import Toast from './Toast'
const obj={}
obj.install=function(Vue){
const toastContrustor=Vue.extend(Toast)
const toast=new toastContrustor()
toast.$mount(document.createElement('div'))
document.body.appendChild(toast.$el)
Vue.prototype.$toast=toast;
}
export default obj | 27.1 | 43 | 0.785978 |
1aa753d295fd761d7bfa25672b0a6f99d6a9442f | 3,417 | js | JavaScript | duckduckgo-to-google-button.user.js | hpuac/userscripts | c857eb2eea6715758c2342937153986c2554c1b6 | [
"Unlicense"
] | null | null | null | duckduckgo-to-google-button.user.js | hpuac/userscripts | c857eb2eea6715758c2342937153986c2554c1b6 | [
"Unlicense"
] | null | null | null | duckduckgo-to-google-button.user.js | hpuac/userscripts | c857eb2eea6715758c2342937153986c2554c1b6 | [
"Unlicense"
] | null | null | null | // ==UserScript==
// @name DuckDuckGo to Google Button
// @namespace https://puac.de/
// @version 0.1.1
// @description Displays a button on DuckDuckGo that redirects to the same search on Google.
// @author Hans Puac
// @match https://duckduckgo.com/*
// @run-at document-end
// ==/UserScript==
(function () {
'use strict';
var searchPattern = /[?|&]ia=([^&]*)/;
var searchTypeMap = {
'images': 'isch',
'videos': 'vid',
'news': 'nws'
};
var generateImage = function () {
var image = document.createElement("img");
image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEwAACxMBAJqcGAAABPdJREFUWIXFl31MU1cYxp9zb297S2mpUBTq/CIVBgboFKdGzYxOo1uiWRZJplG3ScT4gdNNmc6MkCULjg0TxCgbTqeLcy6bRpGRGafbzJgfIIrg12DoHIwCpbaln/fesz8mncptS53E96/b+z73fX6n555z3wM85SCRiHt378gSrN3rxZ6OSbDahglOOw8qEHAqkdUOcZDY2BZFnKHSKyi2x+fnO54YgKOsOM/XdHWrePNaPCgNq6eaaKpMN59nRg1fGrPinZuPDeDcU5rpb2io8jfUGwcC2g8kSkPV017Yr80vfIMAsuRBAew7i1d6TlbvhMPOPI75g8GYs1qZZLM5Njf3Xr+crHnpti3eyqO7noQ5ABC/TyOyNkk29+gNR1nJYk/VkS+p1xO+MKeEpFRS4nIRUNn6YFPSOumU8SbDknX2sAC9FTuMvSerb6PLoghmyo4Y4eZS0r9DXFy5dkXeWQJQaX+xxuVgXvW1t63211+cSNwuAgDsuIxOMu75sXJ/vSyAbeuGWl/NL+NlhSoeqhmzv9COblhOsr8RgxW079mVJlyp/ZEKEkMnZwYdeT8A343N0z0nGn/ynGjvNy00SkM18+Yvi1614UCoYgF9eTnXxdr4+Jzwe0HAzH/plQvorswSe+fAvtMC9I2REPALFr6rW7tx20DMIw0CAPTwQtaX8KuX8VlYAKCK5+D4VAWxwwNuwpTrQz4qTR0Mc+D+MhQyRy7oMwcAIlyCLrcFqqlDwSSNeXOwzAHg37fdb3u5X8ZvgfqlLpty8vqaUAXyD7kud/RIpkiNzWMUH7w1ly9SAAAR76XI7ZMMP7IJOBeykNMN4x0roiIFSEqQpgF9O6Hoi5ETSQrNnUgLDzS8PmL4D+ApBCHgAgCU5W2yIsE+atAAGHgCAOBibsiJBPdfg7b8eAXagb5VwBkqASx/UNDOmfBez0R9Wf3qSWvMS4O+iRnpamPWaLDB8jXNrru/d9C4R+9rVKQuAKAwKY/5/jaKjLeNBYAafh4KOmLg8Lcjhr+9F0BaMIPcLOIH4JfLlVZ7nm3t7G9OAOiV9Gvg/hQQUigxukkXJRBUKHOw4S4Hh98FADhnuZxadKF8UzCAUNFmlQ4JMl/pUfFwvj5L3RwAAACqNa/bJK2ke9osD4kpKKpbzxYV11YsicT84+PukvN/SJlyOVMCW9V3HQBQJm05x6gSL8s94BRd5GjLqf3v/7bjwMLDh4PONwAUnN7Lf3jqzJHvG8T1cvloNZX0KmFt3++HPr27mw4kHr/5850OjzVoQzJck+BJi0s6EquK2b3x2J9nUVgoFZwui9Zo+XmdbtuyRuv1ORZ3DzdBNxfN9dmQ6MO8s9PZrzbPVy+SBQCA7XX7Xvu2+YeDHtEbaqAAAIYw4KCgXuqTbW5N2hS4m1fB4dADAJKHke6Zuqhh2dkk0NDIPlhcW5F/tOVUkVf0hYUIF3qVHsOdqyE4kr0zx7Jpy2erWx7MB23LS+r25VTdPlNu8zr+93adrBvjnKF6e/KKWYmNj+ZCHkzKLh0cd6Wrqbqu+9ozj2PMEhbTEydcGJFgfHFd8pLwXXGw+KTu81WN3bcKrlpvDZUGcDRTshzM8anNabGmvDUZi6tCaSM6nH525WBGu8eW1+XuntrpvmfsFVy8JAqMklUJOi661xClbzWohpwxaKNLclIXtUVS+6nFP4ZN4ITLRid2AAAAAElFTkSuQmCC';
image.style.width = '15px';
image.style.float = 'left';
image.style.margin = '10px 7px';
image.style.cursor = 'pointer';
return image;
};
var redirect = function () {
var url = 'https://www.google.com/search?q=';
var match = searchPattern.exec(window.location.search);
var searchInput = document.getElementById('search_form_input').value;
url += encodeURI(searchInput);
if (match && match.length > 0) {
var searchType = match[1];
if (typeof searchTypeMap[searchType] !== 'undefined') {
url += '&tbm=' + searchTypeMap[searchType];
}
}
window.location.href = url;
};
var duckbar = document.getElementById('duckbar');
if (duckbar !== null) {
var image = generateImage();
duckbar.prepend(image);
image.addEventListener('click', redirect);
}
})();
| 61.017857 | 1,865 | 0.775534 |
1aa794e3f816451db75d76c57d12833b3c00d685 | 2,170 | js | JavaScript | sdk/metricsadvisor/ai-metrics-advisor/recordings/node/datasourcecredential_datasource_credential_crud_operations/recording_updates_service_principal_credential.js | AFengKK/azure-sdk-for-js | 5bad5ee4ef8407f7023bd5a7f2ab88b319b16b29 | [
"MIT"
] | 2 | 2020-01-14T11:06:26.000Z | 2022-01-12T08:31:22.000Z | sdk/metricsadvisor/ai-metrics-advisor/recordings/node/datasourcecredential_datasource_credential_crud_operations/recording_updates_service_principal_credential.js | AFengKK/azure-sdk-for-js | 5bad5ee4ef8407f7023bd5a7f2ab88b319b16b29 | [
"MIT"
] | 13 | 2019-07-17T15:53:17.000Z | 2019-07-25T22:29:53.000Z | sdk/metricsadvisor/ai-metrics-advisor/recordings/node/datasourcecredential_datasource_credential_crud_operations/recording_updates_service_principal_credential.js | AFengKK/azure-sdk-for-js | 5bad5ee4ef8407f7023bd5a7f2ab88b319b16b29 | [
"MIT"
] | 2 | 2022-01-14T20:55:04.000Z | 2022-01-14T21:22:35.000Z | let nock = require('nock');
module.exports.hash = "380cdec07305d595225bb62df352ebdc";
module.exports.testInfo = {"uniqueName":{},"newDate":{}}
nock('https://endpoint:443', {"encodedQueryParams":true})
.patch('/metricsadvisor/v1.0/credentials/3ee2df85-919c-4e6a-b0b4-dca40b2d7b10', {"dataSourceCredentialType":"ServicePrincipal","dataSourceCredentialName":"UpdatedSPCred","dataSourceCredentialDescription":"updated description","parameters":{"clientId":"updated-client","clientSecret":"updated-secret","tenantId":"updated-tenant"}})
.reply(200, {"dataSourceCredentialId":"3ee2df85-919c-4e6a-b0b4-dca40b2d7b10","dataSourceCredentialName":"UpdatedSPCred","dataSourceCredentialDescription":"updated description","dataSourceCredentialType":"ServicePrincipal","parameters":{"clientId":"updated-client","tenantId":"updated-tenant"}}, [
'Content-Length',
'281',
'Content-Type',
'application/json; charset=utf-8',
'x-request-id',
'3da75e69-34bc-4fc7-9510-cae821942e36',
'x-envoy-upstream-service-time',
'610',
'apim-request-id',
'3da75e69-34bc-4fc7-9510-cae821942e36',
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload',
'x-content-type-options',
'nosniff',
'Date',
'Fri, 04 Jun 2021 18:52:15 GMT',
'Connection',
'close'
]);
nock('https://endpoint:443', {"encodedQueryParams":true})
.get('/metricsadvisor/v1.0/credentials/3ee2df85-919c-4e6a-b0b4-dca40b2d7b10')
.reply(200, {"dataSourceCredentialId":"3ee2df85-919c-4e6a-b0b4-dca40b2d7b10","dataSourceCredentialName":"UpdatedSPCred","dataSourceCredentialDescription":"updated description","dataSourceCredentialType":"ServicePrincipal","parameters":{"clientId":"updated-client","tenantId":"updated-tenant"}}, [
'Content-Length',
'281',
'Content-Type',
'application/json; charset=utf-8',
'x-request-id',
'b326300c-d6fc-4aa1-8925-1dcbd615bbb2',
'x-envoy-upstream-service-time',
'114',
'apim-request-id',
'b326300c-d6fc-4aa1-8925-1dcbd615bbb2',
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload',
'x-content-type-options',
'nosniff',
'Date',
'Fri, 04 Jun 2021 18:52:15 GMT',
'Connection',
'close'
]);
| 41.730769 | 332 | 0.732719 |
1aa8775cab4139093a2704717913aa6102aeff60 | 2,019 | js | JavaScript | src/renderer/curve/database-helper.js | metikha5/ReportGenerator | 9f25c3e1aba02bc29dec639b5063275033ada16e | [
"WTFPL"
] | null | null | null | src/renderer/curve/database-helper.js | metikha5/ReportGenerator | 9f25c3e1aba02bc29dec639b5063275033ada16e | [
"WTFPL"
] | null | null | null | src/renderer/curve/database-helper.js | metikha5/ReportGenerator | 9f25c3e1aba02bc29dec639b5063275033ada16e | [
"WTFPL"
] | null | null | null | import sqlite from 'sqlite-sync'
export default {
initDatabase(databasePath) {
sqlite.connect(databasePath)
},
_getTableColumns(table) {
return new Promise((resolve, reject) => {
sqlite.run(`PRAGMA table_info(${table});`, function(res) {
if (res.error) {
reject(new Error(res.error))
} else {
resolve({
target: `${table.split('snapshotmodel')[0]}s`,
elements: res.map(c => c.name)
.filter(c => c !== 'id' && c !== 'date' && !c.endsWith('_id'))
})
}
})
})
},
getTablesColumns() {
const targetTables = ['tanksnapshotmodel', 'actuatorsnapshotmodel', 'providersnapshotmodel']
return Promise.all(targetTables.map(t => this._getTableColumns(t)))
},
_getTanks() {
return new Promise((resolve, reject) => {
sqlite.run('SELECT name FROM tankmodel;', function(res) {
if (res.error) {
reject(new Error(res.error))
} else {
resolve({
target: 'tanks',
elements: res.map(c => c.name)
})
}
})
})
},
_getActuators() {
return new Promise((resolve, reject) => {
sqlite.run('SELECT src, sink FROM actuatormodel;', function(res) {
if (res.error) {
reject(new Error(res.error))
} else {
resolve({
target: 'actuators',
elements: res.map(c => `${c.src}->${c.sink}`)
})
}
})
})
},
_getProviders() {
return new Promise((resolve, reject) => {
sqlite.run('SELECT reservoir_name FROM providermodel;', function(res) {
if (res.error) {
reject(new Error(res.error))
} else {
resolve({
target: 'providers',
elements: res.map(c => c.reservoir_name)
})
}
})
})
},
getElementsNames() {
return Promise.all([
this._getTanks(),
this._getActuators(),
this._getProviders()
])
}
}
| 24.621951 | 96 | 0.515106 |
1aa9af00e5c65b0636a64d3b66683a894c806a38 | 2,751 | js | JavaScript | test/day-07/instruction-test.js | gbranchaudrubenovitch/advent-of-code-2015 | 117894867c39a401dd647abf90334871856317da | [
"MIT"
] | null | null | null | test/day-07/instruction-test.js | gbranchaudrubenovitch/advent-of-code-2015 | 117894867c39a401dd647abf90334871856317da | [
"MIT"
] | null | null | null | test/day-07/instruction-test.js | gbranchaudrubenovitch/advent-of-code-2015 | 117894867c39a401dd647abf90334871856317da | [
"MIT"
] | null | null | null | var expect = require("chai").expect;
var instructions = require("../../src/day-07/instructions");
describe("Wire connection instructions", () => {
it("can parse a signal-to-wire instruction", () => {
var parsedInstruction = instructions.fromString("123 -> x");
expect(parsedInstruction.from.signal).to.equal(123);
expect(parsedInstruction.to.wireName).to.equal("x");
});
it("can parse a wire-to-wire instruction", () => {
var parsedInstruction = instructions.fromString("y -> x");
expect(parsedInstruction.from.wireName).to.equal("y");
expect(parsedInstruction.to.wireName).to.equal("x");
});
it("can parse a 2-wire AND instruction", () => {
var parsedInstruction = instructions.fromString("x AND y -> z");
expect(parsedInstruction.from.gate.in1).to.equal("x");
expect(parsedInstruction.from.gate.type).to.equal("AND");
expect(parsedInstruction.from.gate.in2).to.equal("y");
expect(parsedInstruction.to.wireName).to.equal("z");
});
it("can parse a 1-signal-1-wire AND instruction", () => {
var parsedInstruction = instructions.fromString("1 AND x -> y");
expect(parsedInstruction.from.gate.in1).to.equal(1);
expect(parsedInstruction.from.gate.type).to.equal("AND");
expect(parsedInstruction.from.gate.in2).to.equal("x");
expect(parsedInstruction.to.wireName).to.equal("y");
});
it("can parse a 2-wire OR instruction", () => {
var parsedInstruction = instructions.fromString("p OR q -> r");
expect(parsedInstruction.from.gate.in1).to.equal("p");
expect(parsedInstruction.from.gate.type).to.equal("OR");
expect(parsedInstruction.from.gate.in2).to.equal("q");
expect(parsedInstruction.to.wireName).to.equal("r");
});
it("can parse a LSHIFT instruction", () => {
var parsedInstruction = instructions.fromString("p LSHIFT 2 -> q");
expect(parsedInstruction.from.gate.in1).to.equal("p");
expect(parsedInstruction.from.gate.type).to.equal("LSHIFT");
expect(parsedInstruction.from.gate.in2).to.equal(2);
expect(parsedInstruction.to.wireName).to.equal("q");
});
it("can parse a RSHIFT instruction", () => {
var parsedInstruction = instructions.fromString("q RSHIFT 3 -> r");
expect(parsedInstruction.from.gate.in1).to.equal("q");
expect(parsedInstruction.from.gate.type).to.equal("RSHIFT");
expect(parsedInstruction.from.gate.in2).to.equal(3);
expect(parsedInstruction.to.wireName).to.equal("r");
});
it("can parse a NOT instruction", () => {
var parsedInstruction = instructions.fromString("NOT e -> f");
expect(parsedInstruction.from.gate.in1).to.equal("e");
expect(parsedInstruction.from.gate.type).to.equal("NOT");
expect(parsedInstruction.to.wireName).to.equal("f");
});
});
| 42.984375 | 71 | 0.682661 |
1aab146050cee1cb97769df164ef3d1764371edf | 1,912 | js | JavaScript | encargado_sala.js | NestorAcabal/pruebaCrud | 1b6dbf0267d256bb0e8ad64eed953d78aa6f9a26 | [
"MIT"
] | null | null | null | encargado_sala.js | NestorAcabal/pruebaCrud | 1b6dbf0267d256bb0e8ad64eed953d78aa6f9a26 | [
"MIT"
] | 1 | 2021-05-10T03:59:05.000Z | 2021-05-10T03:59:05.000Z | encargado_sala.js | NestorAcabal/pruebaCrud | 1b6dbf0267d256bb0e8ad64eed953d78aa6f9a26 | [
"MIT"
] | null | null | null | var express = require('express');
const bodyParser = require('body-parser');
const Sequelize = require('sequelize');
const sequelize = new Sequelize('pruebacruddb', 'root', '', {
dialect: 'mysql'
})
encargado_router = express.Router();
var Model = {};
Model.sequelize = sequelize;
Model.encargado_salas = sequelize.define('encargado_salas', {
id_encargado_sala: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement:true, allowNull: false },
id_dp: { type: Sequelize.INTEGER, allowNull: false }
}, {timestamps: false} );
sequelize.sync();
/*
"id_dp": 4,
*/
//-----------------queries---------------------
encargado_router.get('/', function (req, res) {
Model.encargado_salas.findAll().then(encargado_var => {
res.json(encargado_var);
});
});
encargado_router.get('/:idGet', function (req, res) {
var idGet = req.params.idGet;
Model.encargado_salas.findAll({
where: {
id_encargado_sala: idGet
}
}).then((encargado_var) => {
res.json(encargado_var);
})
});
encargado_router.post("/", function (req, res, body) {
var entrada = req.body;
Model.encargado_salas.create(entrada).then(encargado_var => {
res.json(encargado_var);
});
});
encargado_router.delete("/:idDel", function (req, res, body) {
var idDel = req.params.idDel;
Model.encargado_salas.destroy({
where: {
id_encargado_sala: idDel
}
}).then((encargado_var) => {
res.json(encargado_var);
});
});
encargado_router.put("/:idPut", function (req, res) {
var idPut = req.params.idPut;
var entrada = req.body;
Model.encargado_salas.update({
id_dp:entrada.id_dp
}, {
where: {
id_encargado_sala: idPut
}
}).then(encargado_var => {
res.json(encargado_var);
});
});
module.exports = encargado_router; | 26.555556 | 108 | 0.604603 |