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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8b71ee2ea3f5aa236451aa38bc229ac723e93439 | 1,653 | js | JavaScript | app/controllers/item.js | fulltom/wallpict-api | 79ef279df92e15ef42602382ea766a01b245a479 | [
"MIT"
] | null | null | null | app/controllers/item.js | fulltom/wallpict-api | 79ef279df92e15ef42602382ea766a01b245a479 | [
"MIT"
] | null | null | null | app/controllers/item.js | fulltom/wallpict-api | 79ef279df92e15ef42602382ea766a01b245a479 | [
"MIT"
] | null | null | null | var Item = require('../models/item');
var awsUpload = require('../../aws-streaming');
// Create endpoint /api/beers for POSTS
exports.postItems = function(req, res) {
return awsUpload(req, function(err) {
//res.json({ message: 'Item created in db' });
res.redirect('/')
});
};
// Create endpoint api/items?page=1 for GET
exports.getItems = function(req, res) {
var page = (req.param('page') > 0 ? req.param('page') : 1) - 1;
var limit = req.param('limit') || 5
Item
.find()
.populate('_created_by', 'username')
.limit(limit)
.populate('created_by')
.skip(limit * page)
.sort({createdAt: 'desc'})
.exec(function (err, items) {
console.log('The creator is %s', items);
Item.count().exec(function (err, count) {
res.json('items', {
items: items
, page: page
, pages: Math.floor(count / limit)
})
})
})
};
// Create endpoint /api/items/:item_id for GET
exports.getItem = function(req, res) {
Item.findById(req.params.item_id, function(err, item) {
if (err)
res.send(err);
res.json(item);
});
};
// Create endpoint /api/items/:item_id for PUT
exports.putItem = function(req, res) {
Item.findById(req.params.item_id, function(err, item) {
if (err)
res.send(err);
item.pseudo = req.body.pseudo;
item.tags = req.body.tags;
item.imageURI = req.body.imageURI;
item.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Item updated!' });
});
});
}
exports.deleteItem = function(req, res) {
Item.remove({
_id: req.params.item_id
}, function(err, item) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
}; | 23.956522 | 64 | 0.623109 |
8b729e28302f1a899d3bdb2aa0a93373edd231d8 | 301 | js | JavaScript | Doxygen/html/search/namespaces_0.js | carla-simulator/carla-simulator.github.io | dadc3c6c9ea82ceb4365c3f8a25d97bd550f9548 | [
"MIT"
] | 9 | 2018-03-23T09:42:14.000Z | 2022-01-16T18:56:02.000Z | Doxygen/html/search/namespaces_0.js | carla-simulator/carla-simulator.github.io | dadc3c6c9ea82ceb4365c3f8a25d97bd550f9548 | [
"MIT"
] | 12 | 2018-03-23T13:43:37.000Z | 2020-02-25T06:48:18.000Z | Doxygen/html/search/namespaces_0.js | carla-simulator/carla-simulator.github.io | dadc3c6c9ea82ceb4365c3f8a25d97bd550f9548 | [
"MIT"
] | 8 | 2018-07-21T04:17:27.000Z | 2020-04-23T16:37:00.000Z | var searchData=
[
['ad',['ad',['../d5/d72/namespacead.html',1,'']]],
['rss',['rss',['../d2/d36/namespacead_1_1rss.html',1,'ad']]],
['state',['state',['../d2/da1/namespacead_1_1rss_1_1state.html',1,'ad::rss']]],
['world',['world',['../d7/db5/namespacead_1_1rss_1_1world.html',1,'ad::rss']]]
];
| 37.625 | 81 | 0.591362 |
8b7385f7bc37ddfa3e193f9271fb6f2640ecce59 | 344 | js | JavaScript | examples/adventureworks/product.js | wheelspinner/nitrodata | a7c46281933a132f2ca02944d09c644284b380d8 | [
"Apache-2.0"
] | null | null | null | examples/adventureworks/product.js | wheelspinner/nitrodata | a7c46281933a132f2ca02944d09c644284b380d8 | [
"Apache-2.0"
] | null | null | null | examples/adventureworks/product.js | wheelspinner/nitrodata | a7c46281933a132f2ca02944d09c644284b380d8 | [
"Apache-2.0"
] | null | null | null | var faker = require('faker');
var nitro = require('nitro-client');
var f = require('../adventureworks/factories');
var m = nitro.nsModels;
var productModel = f.product.generic()
.withName(faker.commerce.productName())
.createNew();
nitro.createAsync(productModel)
.then(function(results) {
console.log(results);
});
| 21.5 | 47 | 0.674419 |
8b73c3db317db5b4744cdfb27bb3d03bfeb69ac5 | 2,522 | js | JavaScript | apps/communications/dialer/js/action_menu.js | allstarschh/gaia | 216ca858b69ec3c090893feb4d2f4b906e38e368 | [
"Apache-2.0"
] | null | null | null | apps/communications/dialer/js/action_menu.js | allstarschh/gaia | 216ca858b69ec3c090893feb4d2f4b906e38e368 | [
"Apache-2.0"
] | null | null | null | apps/communications/dialer/js/action_menu.js | allstarschh/gaia | 216ca858b69ec3c090893feb4d2f4b906e38e368 | [
"Apache-2.0"
] | null | null | null | /*
How to:
var action = new ActionMenu('Dummy title 1', [
{
label: 'Dummy element',
callback: function() {
alert('Define an action here!');
}
}
]);
action.addAction('Another action', function(){alert('Another action');});
action.show();
*/
function ActionMenu(title, list) {
var init, show, hide, render, setTitle, addAction,
data, el;
init = function() {
var strPopup, body, section, btnCancel;
data = {};
body = document.body;
el = document.createElement('section');
el.setAttribute('role', 'dialog');
strPopup = '<menu class="actions">';
strPopup += ' <h3>No Title</h3>';
strPopup += ' <ul>';
strPopup += ' </ul>';
strPopup += '</menu>';
el.innerHTML += strPopup;
body.appendChild(el);
// Apply optional actions while initializing
if (typeof title === 'string') {
setTitle(title);
}
if (Object.prototype.toString.call(list) == '[object Array]') {
data.list = list;
}
}
show = function() {
el.classList.remove('hide');
el.querySelector('menu').classList.add('visible');
render();
}
hide = function() {
document.body.removeChild(el);
}
render = function() {
var title = el.querySelector('h3'),
list = el.querySelector('ul');
title.innerHTML = data.title;
list.innerHTML = '';
for (var i = 0; i < data.list.length; i++) {
var li = document.createElement('li'),
button = document.createElement('button'),
text = document.createTextNode(data.list[i].label);
button.appendChild(text);
if (data.list[i].callback) {
var theCallback = data.list[i].callback;
button.addEventListener('click', theCallback);
}
li.appendChild(button);
list.appendChild(li);
}
// Always add the last element, the cancel action
var li = document.createElement('li'),
button = document.createElement('button');
text = document.createTextNode(_('cancel'));
button.appendChild(text);
button.addEventListener('click', function hideActions() {
hide();
});
li.appendChild(button);
list.appendChild(li);
}
setTitle = function(str) {
data.title = str;
}
addAction = function(label, callback) {
data.list.push({
label: label,
callback: callback
});
}
init();
return{
init: init,
show: show,
hide: hide,
setTitle: setTitle,
addAction: addAction,
List: list
};
}
| 21.930435 | 75 | 0.58525 |
8b74152a12f8dd1f178bf347251380da80eec90e | 429 | js | JavaScript | samples/javascript-azurefunction/InvokeMethodTrigger/index.js | cgillum/azure-functions-dapr-extension | bfbf2d7944c8169577b755f77a03f104cc0c6056 | [
"MIT"
] | null | null | null | samples/javascript-azurefunction/InvokeMethodTrigger/index.js | cgillum/azure-functions-dapr-extension | bfbf2d7944c8169577b755f77a03f104cc0c6056 | [
"MIT"
] | 3 | 2020-03-20T04:59:20.000Z | 2020-04-02T21:03:28.000Z | samples/javascript-azurefunction/InvokeMethodTrigger/index.js | cgillum/azure-functions-dapr-extension | bfbf2d7944c8169577b755f77a03f104cc0c6056 | [
"MIT"
] | null | null | null | module.exports = async function (context) {
let args = context.bindings.daprInput;
context.log(`JavaScript processed a request from the Dapr runtime. Content: ${JSON.stringify(args)}`);
// input binding
const [operandOne, operandTwo] = [Number(args['arg1']), Number(args['arg2'])];
// the return value of the function is the output
let result = operandOne / operandTwo;
return result.toString();
};
| 35.75 | 106 | 0.687646 |
8b7441aa2dcea37ceab3ecf40483c177e710f68d | 6,462 | js | JavaScript | demo/index.js | BaurAubakir/react-mapbox-gl-leaflet | fb580c662e56f1ec8f6585327a16a7b984a050f6 | [
"MIT"
] | 8 | 2019-07-16T12:35:19.000Z | 2021-02-11T20:28:42.000Z | demo/index.js | BaurAubakir/react-mapbox-gl-leaflet | fb580c662e56f1ec8f6585327a16a7b984a050f6 | [
"MIT"
] | null | null | null | demo/index.js | BaurAubakir/react-mapbox-gl-leaflet | fb580c662e56f1ec8f6585327a16a7b984a050f6 | [
"MIT"
] | 11 | 2019-10-29T14:39:36.000Z | 2022-03-11T07:47:56.000Z | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ReactMapboxGlLeaflet=t():e.ReactMapboxGlLeaflet=t()}(window,function(){return function(e){function t(t){for(var n,i,u=t[0],c=t[1],f=t[2],p=0,s=[];p<u.length;p++)i=u[p],o[i]&&s.push(o[i][0]),o[i]=0;for(n in c)Object.prototype.hasOwnProperty.call(c,n)&&(e[n]=c[n]);for(l&&l(t);s.length;)s.shift()();return a.push.apply(a,f||[]),r()}function r(){for(var e,t=0;t<a.length;t++){for(var r=a[t],n=!0,u=1;u<r.length;u++){var c=r[u];0!==o[c]&&(n=!1)}n&&(a.splice(t--,1),e=i(i.s=r[0]))}return e}var n={},o={0:0},a=[];function i(t){if(n[t])return n[t].exports;var r=n[t]={i:t,l:!1,exports:{}};return e[t].call(r.exports,r,r.exports,i),r.l=!0,r.exports}i.m=e,i.c=n,i.d=function(e,t,r){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(i.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)i.d(r,n,function(t){return e[t]}.bind(null,n));return r},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="demo";var u=window.webpackJsonpReactMapboxGlLeaflet=window.webpackJsonpReactMapboxGlLeaflet||[],c=u.push.bind(u);u.push=t,u=u.slice();for(var f=0;f<u.length;f++)t(u[f]);var l=c;return a.push([39,1]),r()}({11:function(e,t){e.exports={root:"_8ovzY",map:"_1J5s6","mapboxgl-spin":"_3USsL","mapboxgl-user-location-dot-pulse":"_38b1W"}},34:function(e,t){},39:function(e,t,r){"use strict";r.r(t);var n=r(0),o=r.n(n),a=r(10),i=r(17),u=r(14),c=r.n(u),f=(r(30),r(34),r(6)),l=r.n(f),p=r(15),s=r.n(p),y=r(40),b=r(3),m=r.n(b),d=(r(13),r(35),r(41)),v=r(7);function h(e){return(h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function g(e){return(g=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function w(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function O(e,t){return(O=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function j(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var x=function(e){function t(e){var r,n,o;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),n=this,(r=!(o=g(t).call(this,e))||"object"!==h(o)&&"function"!=typeof o?w(n):o)._addLayer=r._addLayer.bind(w(r)),r._removeLayer=r._removeLayer.bind(w(r)),r}var r,n,o;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&O(e,t)}(t,d["a"]),r=t,(n=[{key:"createLeafletElement",value:function(e){var t=this,r=(e.leaflet||this.context).map;return r.on("layeradd",function(e){t._addLayer(e)}),r.on("layerremove",function(e){t._removeLayer(e)}),m.a.mapboxGL(e)}},{key:"_addLayer",value:function(e){var t=e.layer;this._layer=t;var r=this._layer._map;r&&setTimeout(r._onResize,200)}},{key:"_removeLayer",value:function(){this._layer=null}}])&&_(r.prototype,n),o&&_(r,o),t}();j(x,"propTypes",{accessToken:l.a.string,style:l.a.string.isRequired}),j(x,"defaultProps",{accessToken:"your-access-token-if-using-mapbox-api"});var P=Object(v.b)(x),S=r(11),L=r.n(S);function k(e){return(k="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function E(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function T(e,t){return!t||"object"!==k(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function M(e){return(M=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function R(e,t){return(R=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function C(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var G=function(e){function t(){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),T(this,M(t).apply(this,arguments))}var r,a,i;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&R(e,t)}(t,n["PureComponent"]),r=t,(a=[{key:"render",value:function(){var e=this.props.className,t=s()(L.a.root,e);return o.a.createElement("div",{ref:"mapContainer",className:t},o.a.createElement(y.a,{className:L.a.map,ref:"map",preferCanvas:!0,center:[-33.86785,151.20732],zoom:12,minZoom:0,maxZoom:14},o.a.createElement(P,{ref:"mapboxGL",style:"https://maps.tilehosting.com/styles/bright/style.json?key=2CLrASB61Gj6GPxI8aKe",attribution:'\n <a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a>\n <a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>\n'})))}}])&&E(r.prototype,a),i&&E(r,i),t}();C(G,"propTypes",{className:l.a.string}),C(G,"defaultProps",{className:""});var N=G,z=document.createElement("div");z.id="root",document.body.appendChild(z);var J;J=N,Object(a.render)(o.a.createElement(i.AppContainer,{errorReporter:c.a},o.a.createElement(J,null)),document.getElementById("root"))}})});
//# sourceMappingURL=index.js.map | 3,231 | 6,428 | 0.702878 |
8b74b812e2194c7d8e327251e4fb8bb5ffbd1604 | 1,499 | js | JavaScript | examples/lorenzAttractor.js | imaphatduc/cubecubed | b337eba7f772f1f53f0693e3ca83e5d18a727809 | [
"MIT"
] | 47 | 2021-12-08T11:39:33.000Z | 2022-02-13T12:24:19.000Z | examples/lorenzAttractor.js | imaphatduc/cubecubed | b337eba7f772f1f53f0693e3ca83e5d18a727809 | [
"MIT"
] | 9 | 2022-01-03T06:12:01.000Z | 2022-01-20T06:16:43.000Z | examples/lorenzAttractor.js | imaphatduc/cubecubed | b337eba7f772f1f53f0693e3ca83e5d18a727809 | [
"MIT"
] | 1 | 2022-01-02T17:31:06.000Z | 2022-01-02T17:31:06.000Z | import {
CanvasGroup,
Scene,
Vector3,
StreamLine,
SimulateStream,
} from "../src/index";
function lorenzAttractorSimulation() {
const scene = new Scene("lorenz-attractor-simulation");
const group = new CanvasGroup("lorenz-attractor", scene);
const sigma = 14;
const rho = 28;
const beta = 8 / 3;
const getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
};
const lorenz = ({ x, y, z }) => {
const dx = sigma * (y - x);
const dy = x * (rho - z) - y;
const dz = x * y - beta * z;
return new Vector3(dx, dy, dz);
};
const lorenzSystemParticles = [...Array(1000)].map(
() =>
new StreamLine({
group,
position: new Vector3(
getRandomInt(1, sigma),
getRandomInt(1, rho),
getRandomInt(1, beta)
),
scaleFactor: 0.2,
maxVertices: 10,
functionDef: lorenz,
CONFIG: {
strokeColor: "#5e2eff",
strokeWidth: 0.5,
},
})
);
const lorenzSystemAnims = lorenzSystemParticles.map((particle) => {
return new SimulateStream({
cubicon: particle,
});
});
group.play(lorenzSystemAnims);
}
lorenzAttractorSimulation();
| 24.57377 | 71 | 0.485657 |
8b74eada459bedda22d7af49d6b8274aa927e226 | 424 | js | JavaScript | define-version.js | neves/wpc | 8138a82e1f81c655ac2963654c4b76278f1d781c | [
"MIT"
] | 1 | 2017-01-23T11:26:50.000Z | 2017-01-23T11:26:50.000Z | define-version.js | neves/wpc | 8138a82e1f81c655ac2963654c4b76278f1d781c | [
"MIT"
] | 1 | 2017-01-23T11:47:26.000Z | 2017-08-11T15:19:33.000Z | define-version.js | neves/wpc | 8138a82e1f81c655ac2963654c4b76278f1d781c | [
"MIT"
] | null | null | null | const webpack = require('webpack')
const resolve = require('path').resolve
const fs = require('fs')
function getVersionFromPackage (context) {
const pkg = resolve(context, 'package.json')
return fs.existsSync(pkg) ? require(pkg).version : '0.0.0'
}
module.exports = ({context}) => ({
plugins: [
new webpack.DefinePlugin({
'process.env.VERSION': JSON.stringify(getVersionFromPackage(context))
})
]
})
| 24.941176 | 75 | 0.681604 |
8b774d774311a0b71ef7272a3338f53a7d9a4dc0 | 4,913 | js | JavaScript | public/js/checkout.js | TuyenBoss/phonestore | df8a1fc659fc2d90cb1026b874904c4fbacab95a | [
"MIT"
] | null | null | null | public/js/checkout.js | TuyenBoss/phonestore | df8a1fc659fc2d90cb1026b874904c4fbacab95a | [
"MIT"
] | null | null | null | public/js/checkout.js | TuyenBoss/phonestore | df8a1fc659fc2d90cb1026b874904c4fbacab95a | [
"MIT"
] | null | null | null | $(document).ready(function(){
$('.payment-methods .list-content label').click(function() {
$('.payment-methods .list-content>li').removeClass('active');
$(this).parent('li').addClass('active');
});
});
// validate form
$(document).ready(function(){
var constraints = {
email: {
presence: {
message: "^Email không được trống!"
},
email: {
message: "^Email không đúng định dạng!"
}
},
name: {
presence: {
message: "^Tên không được trống!"
},
length: {
minimum: 3,
maximum: 25,
message: "^Độ dài từ 3 đến 25 ký tự"
}
},
phone: {
presence: {
message: "^Số điện thoại không được trống!"
},
format: {
pattern: "0[^6421][0-9]{8}",
flags: "i",
message: "^Số điện thoại không đúng định dạng!"
}
},
address: {
presence: {
message: "^Địa chỉ không được trống!"
}
},
};
var form_checkout = $('.form-checkout>form');
var form = document.querySelector('.form-checkout>form');
var inputs = document.querySelectorAll(".form-checkout>form input, .form-checkout>form textarea, .form-checkout>form select")
for (var i = 0; i < inputs.length; ++i) {
inputs.item(i).addEventListener("change", function(ev) {
var errors = validate(form, constraints) || {};
showErrorsForInput(this, errors[this.name])
});
}
$('button[type="submit"]').click(function() {
var errors = validate(form, constraints);
showErrors(form, errors || {});
if(!errors) {
var token = $('meta[name="csrf-token"]').attr('content');
form_checkout.append($('<input type="hidden" name="_token">').val(token));
var payment_method = $('input[type="radio"]:checked').val();
form_checkout.append($('<input type="hidden" name="payment_method">').val(payment_method));
var buy_method = form_checkout.attr('buy-method');
form_checkout.append($('<input type="hidden" name="buy_method">').val(buy_method));
if(buy_method == 'buy_now') {
var product = $('.col-order .col-content .section-items .item').attr('data-product');
form_checkout.append($('<input type="hidden" name="product_id">').val(product));
var qty = $('.col-order .col-header h2 span').attr('data-qty');
form_checkout.append($('<input type="hidden" name="totalQty">').val(qty));
var price = $('.col-order .col-content .section-items .item').attr('data-price');
form_checkout.append($('<input type="hidden" name="price">').val(price));
}
form_checkout.submit();
}
});
});
// Updates the inputs with the validation errors
function showErrors(form, errors) {
// We loop through all the inputs and show the errors for that input
_.each(form.querySelectorAll(".form-checkout>form input[name], .form-checkout>form select[name]"), function(input) {
// Since the errors can be null if no errors were found we need to handle
// that
showErrorsForInput(input, errors && errors[input.name]);
});
}
// Shows the errors for a specific input
function showErrorsForInput(input, errors) {
// This is the root of the input
var formGroup = closestParent(input.parentNode, "form-group")
// Find where the error messages will be insert into
,
messages = formGroup.querySelector(".messages");
// First we remove any old messages and resets the classes
resetFormGroup(formGroup);
// If we have errors
if (errors) {
// we first mark the group has having errors
formGroup.classList.add("has-error");
// then we append all the errors
_.each(errors, function(error) {
addError(messages, error);
});
} else {
// otherwise we simply mark it as success
formGroup.classList.add("has-success");
}
}
// Recusively finds the closest parent that has the specified class
function closestParent(child, className) {
if (!child || child == document) {
return null;
}
if (child.classList.contains(className)) {
return child;
} else {
return closestParent(child.parentNode, className);
}
}
function resetFormGroup(formGroup) {
// Remove the success and error classes
formGroup.classList.remove("has-error");
formGroup.classList.remove("has-success");
// and remove any old messages
_.each(formGroup.querySelectorAll(".help-block.error"), function(el) {
el.parentNode.removeChild(el);
});
}
// Adds the specified error with the following markup
// <p class="help-block error">[message]</p>
function addError(messages, error) {
var block = document.createElement("p");
block.classList.add("help-block");
block.classList.add("error");
block.innerText = error;
messages.appendChild(block);
}
| 32.322368 | 128 | 0.614492 |
8b7762226c23eadcc081dbe36e3746ddf6e85987 | 1,671 | js | JavaScript | src/store/user/userReducer.js | InfiniteCoder100/Dev_cart_shopping_webApp | 0dced98e4ff2e37a73288028b85c61fd6d70e5a5 | [
"MIT"
] | 1 | 2020-07-16T16:07:50.000Z | 2020-07-16T16:07:50.000Z | src/store/user/userReducer.js | InfiniteCoder100/Dev_cart_shopping_webApp | 0dced98e4ff2e37a73288028b85c61fd6d70e5a5 | [
"MIT"
] | 7 | 2021-04-18T05:38:39.000Z | 2021-07-19T04:51:37.000Z | src/store/user/userReducer.js | InfiniteCoder100/Dev_cart_shopping_webApp | 0dced98e4ff2e37a73288028b85c61fd6d70e5a5 | [
"MIT"
] | 1 | 2021-07-21T05:16:56.000Z | 2021-07-21T05:16:56.000Z | import * as userActionTypes from "./userActionType";
const updateUserLogin = (state, { isLoggedIn }) => {
if (!isLoggedIn) {
localStorage.removeItem("devCartAuth");
}
return { ...state, isLoggedIn: isLoggedIn };
};
const syncAddresses = (state, { addresses }) => {
const stateCopy = { ...state };
stateCopy.shippingAddresses = addresses;
return stateCopy;
};
const addAddress = (state, { address }) => {
const stateCopy = { ...state };
stateCopy.shippingAddresses = state.shippingAddresses.concat(address);
return stateCopy;
};
const editAddress = (state, { address }) => {
const stateCopy = { ...state };
stateCopy.shippingAddresses = state.shippingAddresses.map((currAddress) => {
if (currAddress._id === address._id) {
return { ...address };
}
return currAddress;
});
return stateCopy;
};
const removeAddress = (state, { addressId }) => {
const stateCopy = { ...state };
stateCopy.shippingAddresses = state.shippingAddresses.filter(
(currAddress) => {
return currAddress._id !== addressId;
}
);
return stateCopy;
};
export default function userReducer(state, action) {
switch (action.type) {
case userActionTypes.UPDATE_USER_LOGIN:
return updateUserLogin(state, action.payload);
case userActionTypes.SYNC_ADDRESSES:
return syncAddresses(state, action.payload);
case userActionTypes.ADD_ADDRESS:
return addAddress(state, action.payload);
case userActionTypes.EDIT_ADDRESS:
return editAddress(state, action.payload);
case userActionTypes.REMOVE_ADDRESS:
return removeAddress(state, action.payload);
default:
return state;
}
}
| 26.52381 | 78 | 0.680431 |
8b78425fe582608349038a5402d9831aeb236bc9 | 580 | js | JavaScript | Frontend/src/pages/Home.js | japerry911/Skylord_Depot | 6e1270bfa84f81f5d78f29aebd70d239dc4426b3 | [
"MIT"
] | null | null | null | Frontend/src/pages/Home.js | japerry911/Skylord_Depot | 6e1270bfa84f81f5d78f29aebd70d239dc4426b3 | [
"MIT"
] | 6 | 2021-03-10T17:15:00.000Z | 2022-02-26T07:40:28.000Z | Frontend/src/pages/Home.js | japerry911/Skylord_Depot | 6e1270bfa84f81f5d78f29aebd70d239dc4426b3 | [
"MIT"
] | null | null | null | import React from 'react';
import { Link } from 'react-router-dom';
const Home = () => {
return (
<div className='main-div-home'>
<div className='title-content-div'>
<img
src='https://skylord-depot.s3.us-east-2.amazonaws.com/Logos/logo_transparent_background.png'
alt='Skylord Depot Logo'
className='logo'
/>
<Link to='/shop'><button>Checkout the Store</button></Link>
</div>
</div>
);
};
export default Home; | 29 | 112 | 0.498276 |
8b79bd4abc8b08a418528419e3ee7f9841042d57 | 1,442 | js | JavaScript | js/lib/objects/Overlay.js | sackh/here-map-widget-for-jupyter | 4d762a5733740bd6821afba7b19b322ceb725ada | [
"MIT"
] | 26 | 2021-02-03T15:07:15.000Z | 2022-02-27T14:52:06.000Z | js/lib/objects/Overlay.js | sackh/here-map-widget-for-jupyter | 4d762a5733740bd6821afba7b19b322ceb725ada | [
"MIT"
] | 12 | 2021-02-22T16:28:13.000Z | 2022-01-04T09:23:38.000Z | js/lib/objects/Overlay.js | sackh/here-map-widget-for-jupyter | 4d762a5733740bd6821afba7b19b322ceb725ada | [
"MIT"
] | 6 | 2021-02-03T16:14:01.000Z | 2021-12-12T17:05:56.000Z | /*
Copyright (C) 2019-2021 HERE Europe B.V.
SPDX-License-Identifier: MIT
*/
const object = require('./Object.js');
const widgets = require('@jupyter-widgets/base');
const _ = require('lodash');
export class OverlayModel extends object.ObjectModel {
defaults() {
return {
// ...super.defaults(),
_view_name: 'OverlayView',
_model_name: 'OverlayModel',
boundingBox: null,
bitmap: '',
min: Infinity,
max: Infinity,
opacity: 1,
visibility: true,
volatility: false,
};
}
}
OverlayModel.serializers = _.extend({
boundingBox: {
deserialize: widgets.unpack_models
},
}, widgets.DOMWidgetModel.serializers);
export class OverlayView extends object.ObjectView {
create_obj() {
return this.create_child_view(this.model.get('boundingBox'), {
map_view: this.map_view,
}).then((view) => {
this.obj = new H.map.Overlay(
view.obj,
this.model.get('bitmap'), {
min: this.model.get('min'),
max: this.model.get('max'),
opacity: this.model.get('opacity'),
visibility: this.model.get('visibility'),
volatility: this.model.get('volatility'),
}
);
});
}
mapjs_events() {
}
model_events() {
this.listenTo(
this.model,
'change:bitmap',
function() {
this.obj.setBitmap(this.model.get('bitmap'));
},
this
);
}
} | 21.848485 | 66 | 0.586685 |
8b7c20fec4e56da495d9820461fd118abe562edb | 522 | js | JavaScript | _data/posts.js | carlwood/11ty-contentful | 467d197373b2d3e1ed5d7fdc773f247af3056c36 | [
"MIT"
] | null | null | null | _data/posts.js | carlwood/11ty-contentful | 467d197373b2d3e1ed5d7fdc773f247af3056c36 | [
"MIT"
] | null | null | null | _data/posts.js | carlwood/11ty-contentful | 467d197373b2d3e1ed5d7fdc773f247af3056c36 | [
"MIT"
] | null | null | null | const contentful = require("contentful");
const client = contentful.createClient({
space: process.env.CTFL_SPACE,
accessToken: process.env.CTFL_ACCESSTOKEN
});
module.exports = function() {
return client.getEntries({ content_type: 'blogPost', order: 'sys.createdAt' })
.then(function(response) {
const post = response.items
.map(function(post) {
post.fields.date= new Date(post.sys.updatedAt);
return post.fields;
});
console.log(post)
return post;
})
.catch(console.error);
}; | 27.473684 | 80 | 0.685824 |
8b7c59a9d5103ea22080216382e85e41e1ea922c | 791 | js | JavaScript | FoodDamas_cus-master/FoodDamas_Cus/src/main/webapp/resources/js/menubar.js | MobileSeoul/2016seoul-25 | 3aa8981ae36e5f5f3ee42929fc6fa7915a610197 | [
"MIT"
] | 5 | 2019-05-23T01:17:50.000Z | 2019-05-24T08:20:17.000Z | FoodDamas_cus-master/FoodDamas_Cus/src/main/webapp/resources/js/menubar.js | MobileSeoul/2016seoul-25 | 3aa8981ae36e5f5f3ee42929fc6fa7915a610197 | [
"MIT"
] | null | null | null | FoodDamas_cus-master/FoodDamas_Cus/src/main/webapp/resources/js/menubar.js | MobileSeoul/2016seoul-25 | 3aa8981ae36e5f5f3ee42929fc6fa7915a610197 | [
"MIT"
] | 1 | 2019-05-23T01:17:50.000Z | 2019-05-23T01:17:50.000Z | function menu() {
//variabele link hamburger menu (icon)
var $toggle = document.getElementById('menu_toggle');
//variabele navigatie (volledige navigatie)
var $sideMenu = document.getElementById('side-menu');
//variabele kruisje (sluiten nav)
var $close = document.getElementById('close');
//klikken op hamburger icon
$toggle.addEventListener('click', function(){
//toggleClass van jquery ( verwijderd en voegt classes toe), toevoegen en verwijderen van sideMenuToggle bij klik op hamburger icon
classie.toggle($sideMenu, "sideMenuToggle");
});
//klikken op kruisje
$close.addEventListener('click', function(){
//verwijderen van de klasse sideMenuToggle
classie.remove($sideMenu, "sideMenuToggle");
});
}
//uitvoeren van de functie menu
menu(); | 32.958333 | 135 | 0.723135 |
8b7d48f7cf6aa4cf03de332d75a10ad3d8fc7889 | 252 | js | JavaScript | survivalGame.js | kmykoh97/survivalGame | 174ff712b94a895ba7a5aa508b8b19a4c5a923d5 | [
"Apache-2.0"
] | null | null | null | survivalGame.js | kmykoh97/survivalGame | 174ff712b94a895ba7a5aa508b8b19a4c5a923d5 | [
"Apache-2.0"
] | null | null | null | survivalGame.js | kmykoh97/survivalGame | 174ff712b94a895ba7a5aa508b8b19a4c5a923d5 | [
"Apache-2.0"
] | null | null | null | /*JS for page-staring alert only. Rest combined in <script>html</script>*/
alert("Try to stay alive as long as possible! \nThe game starts at 50 scores. GOOD LUCK \nIf you have suggestion, do let me know in my github \nFollow me on github: kmykoh97")
| 63 | 175 | 0.746032 |
8b7e6db5c3d9b25c958474f96ce931f451713e37 | 1,278 | js | JavaScript | node_modules/unsplash-wallpaper/lib/help.js | arihantdaga/unvielD | 2b1af0d385859d66b76312583fb117a1c418a54f | [
"MIT"
] | 1 | 2017-03-22T18:02:44.000Z | 2017-03-22T18:02:44.000Z | node_modules/unsplash-wallpaper/lib/help.js | arihantdaga/unvielD | 2b1af0d385859d66b76312583fb117a1c418a54f | [
"MIT"
] | null | null | null | node_modules/unsplash-wallpaper/lib/help.js | arihantdaga/unvielD | 2b1af0d385859d66b76312583fb117a1c418a54f | [
"MIT"
] | null | null | null | module.exports = `
latest
Get the latest image.
example:
$ unsplash-wallpaper latest
random
Get a random image.
example:
$ unsplash-wallpaper random
-w, --width {Number}
Set the width of desired download.
-h, --height {Number}
Set the height of desired download.
-d, --dir {String} or "."
Download the image to a specific directory.
"." uses the current working directory.
"./" stores the current working directory even when it changes.
example:
$ unsplash-wallpaper --dir "/Users/Shared"
$ unsplash-wallpaper --dir "C:UsersPublic"
$ unsplash-wallpaper -d .
-s, --save-config
Saves any width, height or dir value in a config file.
example:
$ unsplash-wallpaper random -s --width 1600 --height 1200
-i, --image {Number}
Get a specific unsplash image if you know the number.
(https://unsplash.it/images)
example:
$ unsplash-wallpaper -i 580
-x, --gravity "north|east|south|west|center"
Choose the direction to crop.
example:
$ unsplash-wallpaper --image 327 --gravity south
-g, --grayscale
-b, --blur
-v, --version
`;
| 22.421053 | 71 | 0.58216 |
8b7eaac91f6aa1896e3a5c28ed1d99735c094083 | 1,485 | js | JavaScript | index.js | pgesek/ksgmet-transformer | 7e33e6f33b256ccf5aa47990329349a015a5d368 | [
"MIT"
] | null | null | null | index.js | pgesek/ksgmet-transformer | 7e33e6f33b256ccf5aa47990329349a015a5d368 | [
"MIT"
] | 3 | 2021-03-09T00:41:24.000Z | 2022-01-22T03:31:11.000Z | index.js | pgesek/ksgmet-transformer | 7e33e6f33b256ccf5aa47990329349a015a5d368 | [
"MIT"
] | null | null | null | 'use strict';
const CsvSorter = require('./src/csv_sorter');
const log = require('./src/util/log');
const settings = require('./src/util/settings');
const validateTarPath = require('./src/s3/tar_path_validator');
const S3File = require('./src/s3/s3_file');
const plFilter = fileName => fileName.startsWith('pl_csv_');
const sorter = new CsvSorter();
exports.handler = async event => {
const records = event.Records;
if (records) {
log.info('Event has ' + records.length + ' records');
await Promise.all(records.map(async record => {
const type = record.eventName;
log.info('Handling record of event type: ' + type);
await handleCreateEvent(record);
}));
} else {
log.info('No records in event');
}
}
async function handleCreateEvent(record) {
const bucket = record.s3.bucket.name;
if (bucket === settings.S3_BUCKET_NAME) {
log.info('Event from bucket: ' + bucket);
const key = record.s3.object.key;
if (validateTarPath(key, plFilter)) {
await executeSort(key);
} else {
log.info('Path does match filter: ' + key);
}
} else {
log.info('Ignoring bucket: ' + bucket);
}
}
async function executeSort(key) {
// was already validated
const [ path, name ] = key.split('/');
const s3File = new S3File(name, path, settings.S3_BUCKET_NAME);
await sorter.processTarFile(s3File);
}
| 28.018868 | 67 | 0.607407 |
8b7f00c38e3d58463155c00e216e7d58b55d8203 | 2,247 | js | JavaScript | server/api/policies/userPolicies.js | Real-Music/infinytel | 6ab9febb95ac70dc3d6c979ec9419f974563a9a0 | [
"MIT"
] | null | null | null | server/api/policies/userPolicies.js | Real-Music/infinytel | 6ab9febb95ac70dc3d6c979ec9419f974563a9a0 | [
"MIT"
] | 1 | 2021-05-10T01:16:45.000Z | 2021-05-10T01:16:45.000Z | server/api/policies/userPolicies.js | Real-Music/infinytel | 6ab9febb95ac70dc3d6c979ec9419f974563a9a0 | [
"MIT"
] | null | null | null | const Joi = require("@hapi/joi");
module.exports = {
createUser(req, res, next) {
const schema = Joi.object().keys({
firstname: Joi.string()
.alphanum()
.min(3)
.max(15)
.required(),
lastname: Joi.string()
.alphanum()
.min(3)
.max(15)
.required(),
email: Joi.string()
.email({ minDomainSegments: 2 })
.required(),
password: Joi.string().regex(/^[a-zA-Z0-9]{8,32}$/),
phone: Joi.string().regex(/^[0-9]{9,9}$/),
gender: Joi.string()
.min(4)
.max(6)
.required()
});
// Joi validation
Joi.validate(req.body, schema, error => {
if (error) {
switch (error.details[0].context.key) {
case "firstname":
res.status(400).json({
message: "error",
response: "",
error: "Please provide a valid first name"
});
break;
case "lastname":
res.status(400).json({
message: "error",
response: "",
error: "Please provide a valid last name"
});
break;
case "email":
res.status(400).json({
message: "error",
response: "",
error: "Please provide a valid email"
});
break;
case "password":
res.status(400).json({
message: "error",
response: "",
error: "Password must be 8 char long"
});
break;
case "phone":
res.status(400).json({
message: "error",
response: "",
error: "Phone number must be 9 digit long"
});
break;
case "gender":
res.status(400).json({
message: "error",
response: "",
error: "Male or Female"
});
break;
default:
res.status(400).json({
message: "error",
response: "",
error: "Invalid Registration Information"
});
}
} else {
next();
}
});
}
};
| 26.127907 | 58 | 0.418336 |
8b7f5beee224b62036d52e081547fa0179440b7c | 2,097 | js | JavaScript | src/tabs.js | chrisrossx/cncjs-raspi-tablet | de048cb97028bfd90674048b42567ace5ebe7180 | [
"MIT"
] | null | null | null | src/tabs.js | chrisrossx/cncjs-raspi-tablet | de048cb97028bfd90674048b42567ace5ebe7180 | [
"MIT"
] | null | null | null | src/tabs.js | chrisrossx/cncjs-raspi-tablet | de048cb97028bfd90674048b42567ace5ebe7180 | [
"MIT"
] | null | null | null | import $ from 'jQuery';
export class Tabs {
constructor(){
this.el = {
tab_jog: $("#tab-jog"),
tab_gcode: $("#tab-gcode"),
tab_mdi: $("#tab-mdi"),
tab_errors: $("#tab-errors"),
btn_tab_jog: $("#btn-tab-jog"),
btn_tab_gcode: $("#btn-tab-gcode"),
btn_tab_mdi: $("#btn-tab-mdi"),
btn_tab_errors: $("#btn-tab-errors"),
}
this.tab = null;
this.el.btn_tab_jog.on("click", () => {
this.change("jog");
});
this.el.btn_tab_gcode.on("click", () => {
this.change("gcode");
});
this.el.btn_tab_mdi.on("click", () => {
this.change("mdi");
});
this.el.btn_tab_errors.on("click", () => {
this.change("errors");
});
}
change(new_tab) {
this.tab = new_tab;
this.el.tab_gcode.css('visibility', 'hidden');
this.el.tab_mdi.css('visibility', 'hidden');
this.el.tab_jog.css('visibility', 'hidden');
this.el.tab_errors.css('visibility', 'hidden');
this.el.btn_tab_gcode.removeClass(["btn-primary", "btn-dark"]);
this.el.btn_tab_mdi.removeClass(["btn-primary", "btn-dark"]);
this.el.btn_tab_jog.removeClass(["btn-primary", "btn-dark"]);
this.el.btn_tab_errors.removeClass(["btn-danger-not-selected", "btn-danger"]);
if(new_tab == "jog"){
this.el.tab_jog.css('visibility', 'visible');
this.el.btn_tab_jog.addClass("btn-primary")
}else{
this.el.btn_tab_jog.addClass("btn-dark")
}
if(new_tab == "gcode"){
this.el.tab_gcode.css('visibility', 'visible');
this.el.btn_tab_gcode.addClass("btn-primary")
}else{
this.el.btn_tab_gcode.addClass("btn-dark")
}
if(new_tab == "mdi"){
this.el.tab_mdi.css('visibility', 'visible');
this.el.btn_tab_mdi.addClass("btn-primary")
}else{
this.el.btn_tab_mdi.addClass("btn-dark")
}
if(new_tab == "errors"){
this.el.tab_errors.css('visibility', 'visible');
this.el.btn_tab_errors.addClass("btn-danger")
}else{
this.el.btn_tab_errors.addClass("btn-danger-not-selected")
}
}
}
| 24.670588 | 82 | 0.582737 |
8b7f929938984359b13fe62af1325ec1f52f35d3 | 155 | js | JavaScript | src/context/redirectContext.js | CLantigua2/blogging_site | 3f46c3e7de44ade82e868c65ddbd3b83c59fd2b7 | [
"0BSD"
] | null | null | null | src/context/redirectContext.js | CLantigua2/blogging_site | 3f46c3e7de44ade82e868c65ddbd3b83c59fd2b7 | [
"0BSD"
] | null | null | null | src/context/redirectContext.js | CLantigua2/blogging_site | 3f46c3e7de44ade82e868c65ddbd3b83c59fd2b7 | [
"0BSD"
] | 1 | 2021-11-08T01:11:35.000Z | 2021-11-08T01:11:35.000Z | import { createContext } from "react"
const RedirectContext = createContext({
redirect: "",
setRedirect: () => {},
})
export default RedirectContext
| 17.222222 | 39 | 0.696774 |
8b80189a1a91674f622ca93e1d322fb00fe4e941 | 827 | js | JavaScript | assets/courses/c50141/misc-labs/WebStorageLab/Exercise4/js/session_storage.js | g00341288/g00341288.github.io | cdffef4879df1198071c844e1d6cadc3d3b98198 | [
"MIT"
] | null | null | null | assets/courses/c50141/misc-labs/WebStorageLab/Exercise4/js/session_storage.js | g00341288/g00341288.github.io | cdffef4879df1198071c844e1d6cadc3d3b98198 | [
"MIT"
] | 3 | 2016-11-02T18:16:53.000Z | 2016-12-01T16:53:34.000Z | assets/courses/c50141/misc-labs/WebStorageLab/Exercise4/js/session_storage.js | g00341288/g00341288.github.io | cdffef4879df1198071c844e1d6cadc3d3b98198 | [
"MIT"
] | null | null | null | // add javascript code here for web storage lab exercise
function book(name) {
this.name = name;
}
function add(){
var uniqueKey = "obj-key"+sessionStorage.length;
var bookName = document.getElementById('fld1').value;
var newBook = new book(bookName);
sessionStorage.setItem(uniqueKey, JSON.stringify(newBook));
console.log(JSON.parse(sessionStorage.getItem(uniqueKey)));
setTimeout(function(){
//window.location.reload();
}, 1000);
}
// Q2. Clear Web Storage
function clear_storage() {
console.log("Clearing sessionStorage now...");
sessionStorage.clear();
}
function fromStorage() {
var i;
var uniqueKey = "obj-key";
var jObject;
for(i = 0; i < sessionStorage.length; i++) {
jObject = JSON.parse(sessionStorage.getItem(uniqueKey+i));
alert(jObject.name);
}
}
| 22.972222 | 61 | 0.680774 |
8b8170b6482446ff2e1f9b80ac5fd44d7559ba3a | 1,805 | js | JavaScript | cardkit/ui/actionview.js | douban-f2e/CardKit | c7ed56f22782e73016cc68607467f7e607078537 | [
"MIT"
] | 104 | 2015-01-03T08:20:13.000Z | 2016-03-02T07:52:32.000Z | cardkit/ui/actionview.js | douban-f2e/CardKit | c7ed56f22782e73016cc68607467f7e607078537 | [
"MIT"
] | 1 | 2015-01-30T13:10:37.000Z | 2015-01-30T13:10:37.000Z | cardkit/ui/actionview.js | douban-f2e/CardKit | c7ed56f22782e73016cc68607467f7e607078537 | [
"MIT"
] | 26 | 2015-01-17T01:55:58.000Z | 2016-01-22T01:50:49.000Z | define([
'moui/actionview',
'../bus',
'./util'
], function(actionView, bus, util) {
var exports = util.singleton({
flag: '_ckActionViewUid',
forceOptions: {
className: 'ck-actionview'
},
factory: function(elm, opt){
return actionView(opt);
},
config: function(o, opt){
o.set(opt);
},
extend: function(o, source){
var eprops = {
component: o
};
o.event.bind('prepareOpen', function(o){
exports.current = o;
}).bind('cancelOpen', function(){
exports.current = null;
}).bind('open', function(o){
bus.fire('actionView:open', [o]);
if (source) {
source.trigger('actionView:open', eprops);
}
}).bind('close', function(){
exports.current = null;
bus.unbind('actionView:confirmOnThis');
bus.fire('actionView:close', [o]);
if (source) {
source.trigger('actionView:close', eprops);
}
}).bind('cancel', function(){
bus.fire('actionView:cancel', [o]);
if (source) {
source.trigger('actionView:cancel', eprops);
}
}).bind('confirm', function(o, picker){
bus.fire('actionView:confirmOnThis', [o])
.fire('actionView:confirm', [o]);
if (source) {
source.trigger('actionView:confirm', eprops);
}
if (picker && picker._lastSelected) {
var elm = picker._lastSelected._node[0];
if (elm.nodeName === 'A') {
bus.fire('actionView:jump', [o, elm.href, elm.target]);
}
}
});
}
});
return exports;
});
| 26.544118 | 75 | 0.477008 |
8b81d4b92f0f64d566cfdeee69368164cd37632a | 10,070 | js | JavaScript | assets/js/orgalog.js | joocer/OrgaLog | 8e8cfe885bfddf40e222a1da348e0b87c5e0faea | [
"Apache-2.0"
] | null | null | null | assets/js/orgalog.js | joocer/OrgaLog | 8e8cfe885bfddf40e222a1da348e0b87c5e0faea | [
"Apache-2.0"
] | null | null | null | assets/js/orgalog.js | joocer/OrgaLog | 8e8cfe885bfddf40e222a1da348e0b87c5e0faea | [
"Apache-2.0"
] | null | null | null | const timestampFormat = "DD MMM YYYY HH:mm"
class OrgaLog {
constructor() {
this._date_range = undefined;
this._date_field = undefined;
this._value_range = undefined;
this._data = [];
this._data_index = [];
this._date_fields = [];
this._deduped = false;
this._columns = [];
this._filters = [];
}
static version() { return "0.1" }
process(data, deduplicate) {
let self = this;
if (data.columns !== undefined) { this._columns = data.columns }
var stime = Date.now();
if (deduplicate) {
var unique = {};
data.forEach(function(x) {
let rowhash = JSON.stringify(x).hashCode();
if (!unique[rowhash]) {
self._data.push(x);
unique[rowhash] = true;
}
});
unique = undefined;
self._data.columns = self._columns;
self._deduped = true;
} else {
self._data = data;
}
console.log('DEDUPE: ', Date.now() - stime);
// find the date field
console.log('TODO: if the field has been specificed but isnt in the data, thrown an error');
self._date_fields = get_date_fields(data);
if (self._date_field === undefined) {
if (self.date_fields.length > 0) {
self._date_field = self._date_fields[0];
} else {
throw ("No columns contain a known date format")
}
} else if (!self._date_fields.includes(self._date_field)) {
throw ("No columns contain a known date format")
}
console.log('DEBUG: using ', self._date_field, ' as data column');
const date_field = self._date_field;
// sort by the date field
self._data = self._data.sort(function compare(a, b) {
return new Date(a[date_field]) - new Date(b[date_field]);
});
let interval = get_interval(self._data[0][date_field], self._data[self._data.length - 1][date_field]);
var simplified = self._data.map(function(value) {
return ({ timestamp: interval.floor(new Date(value[date_field])).getTime(), value: 1 })
});
let interval_range = interval.range(new Date(self._data[0][date_field]), new Date(self._data[self._data.length - 2][date_field]));
for (var i = 0; i <= interval_range.length; i++) {
simplified.push({ timestamp: new Date(interval_range[i]).getTime(), value: 1 });
}
// bin the events by timestamps
var eventCount = d3.nest()
.key(function(d) { return d.timestamp; })
.rollup(function(v) { return v.length - 1; })
.entries(simplified);
var stime = Date.now();
// rename the 'key' field to be 'timestamp' (changed by the nest function above)
eventCount = eventCount.map(function(value) {
return ({
timestamp: Number(value['key']), // this feels like a hack, why is this a string?
value: value['value']
})
});
console.log('MAP: ', Date.now() - stime);
// sort the data by the timestamps
self._data_index = eventCount.sort(function compare(a, b) {
return a.timestamp - b.timestamp;
});
//fille zeros into the index
console.log(this._data_index)
var min_date = d3.min(self._data_index, function(d) {
return d.timestamp;
});
var max_date = d3.max(self._data_index, function(d) {
return d.timestamp;
});
self._date_range = [new Date(min_date), new Date(max_date)];
var max_value = d3.max(self._data_index, function(d) {
return d.value;
});
var min_value = d3.min(self._data_index, function(d) {
return d.value;
});
self._value_range = [min_value, max_value];
}
// expose this data so it can be user selected
get date_field() { return this._date_field }
set date_field(value) {
this._date_field = value;
this._process(this._data);
}
get date_fields() { return this._date_fields }
// range of dates from the data set
get date_range() {
return this._date_range;
}
// range of values from the data set
get value_range() { return this._value_range }
get data() { return this._data }
get data_index() { return this._data_index }
//#################################################################################################
//## FILTERS
//#################################################################################################
get filters() { return this._filters; }
add_filter(display, field, value) {
console.log('TODO: check the display name is unique')
let filter = { "Display": display, "Field": field, "Value": value };
this._filters.push(filter);
this._filters.sort(filter_compare);
}
remove_filter(display) {
for (var i = 0; i < this._filters.length; i++) {
if (this._filters[i].Display == display) { this._filters.splice(i, 1); }
}
}
// find the filter from the list of all of the known filters
find_filter(description) {
for (var i = 0; i < this._filters.length; i++) {
if (this._filters[i].Display == description) { return this._filters[i]; }
}
return null;
}
// remove a filter from the list of active filters
remove_filter(description) {
for (var i = 0; i < this._filters.length; i++) {
if (this._filters[i].Display == description) { this._filters.splice(i, 1); }
}
}
// this is the compare required to sort the list of filters
filter_compare(a, b) {
if (a.Display < b.Display) { return -1; }
return 1;
}
// execute the filters what have been selected
execute_filters(filters) {
var stime = Date.now();
filtered_data = data.slice();
for (var i = 0; i < filters.length; i++) {
filtered_data = filtered_data.filter(function(f) { return f[filters[i].Field] == filters[i].Value })
}
console.log('FILTER: ', Date.now() - stime);
return filtered_data;
}
//#################################################################################################
//## DISPLAY
//#################################################################################################
// this limits the range, applies filters and orders entries
// the data is not affected, it returns indices to the data
view(range, filters, order) {
let self = this;
if (range === undefined && filters === undefined && order === undefined) {
return self._data;
}
if (range === undefined) { range = self._date_range }
if (filters === undefined) { filters = [] }
if (order === undefined) { order = self._date_field }
var filtered_data = self._data.slice();
filtered_data.columns = self._columns;
// apply range
filtered_data = filtered_data.filter(function(f) {
let timestamp = new Date(f[self._date_field]);
return (timestamp >= new Date(range[0]) && timestamp <= new Date(range[1]))
})
// apply filters
// sort by field
// reverse if the fist character is '-' (ascii 45)
let modifier = 1;
if (order.charCodeAt[0] = 45) { modifier = -1 }
filtered_data.columns = self._columns;
return filtered_data;
}
}
function is_date(sDate) {
if (sDate.toString() == parseInt(sDate).toString()) return false;
var tryDate = new Date(sDate);
var m = moment(sDate, ['YYYY-MM-DD', 'YYYYMMDD', 'DD/MM/YYYY', moment.ISO_8601, 'L', 'LL', 'LLL', 'LLLL'], true);
return (tryDate && tryDate.toString() != "NaN" && tryDate != "Invalid Date" && m.isValid());
}
// find all of the fields that appear to have dates in them
function get_date_fields(data) {
console.log('TODO: check the first five rows')
var date_fields = [];
var num_columns = data.columns.length;
for (var h = 0; h < num_columns; h++) {
var cell_value = data[0][data.columns[h]];
if (is_date(cell_value)) {
date_fields.push(data.columns[h]);
}
}
console.log("DEBUG: get_date_fields found " + date_fields.length + " date fields", date_fields)
return date_fields;
}
// slightly faster than the copy from Stack Overflow, but still slow
// about 2x faster than MD5, but this has more clashes
String.prototype.hashCode = function() {
let hash = 0
for (var i = this.length, chr; i > 0; i--) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash = hash & hash; // Convert to 32-bit integer
}
return hash;
}
function get_interval(date1, date2) {
let difference = Math.abs(Date.parse(date2) - Date.parse(date1));
const time_formats = [
[60000, 'milliseconds', d3.timeMillisecond], // 60
[3600000, 'seconds', d3.timeSecond], // 60*60
[86400000, 'minutes', d3.timeMinute], // 60*60*24
[6048000000, 'hours', d3.timeHour], // 60*60*24*7 <-- less than 10 days do in hours
//[2629800000, 'days', d3.timeDay], // 60*60*24*30.4375 <-- technically redundant
//[31557600000, 'weeks', d3.timeWeek], // 60*60*24*365.25 <-- not granular enough
[31557600000, 'days', d3.timeDay], // 60*60*24*365.25 *10
[3155760000000, 'months', d3.timeMonth], // 60*60*24*365.25*100
[31557600000000, 'years', d3.timeYear] // 60*60*24*365.25*100*10
];
var i = 0;
let format;
while (format = time_formats[i++]) {
if (difference < format[0]) {
console.log('DEBUG: interval units:', format[1]);
return format[2]
}
}
throw new error("Dates too far apart");
} | 36.485507 | 138 | 0.546475 |
8b820e742445b98f1087345becfcf96b165f238d | 1,028 | js | JavaScript | src/modules/room/room.service.js | AYehia0/Gimme | 9c410e48137e8946749d8d6c9cc31a92505603a3 | [
"MIT"
] | null | null | null | src/modules/room/room.service.js | AYehia0/Gimme | 9c410e48137e8946749d8d6c9cc31a92505603a3 | [
"MIT"
] | null | null | null | src/modules/room/room.service.js | AYehia0/Gimme | 9c410e48137e8946749d8d6c9cc31a92505603a3 | [
"MIT"
] | 1 | 2022-03-15T07:57:04.000Z | 2022-03-15T07:57:04.000Z | import error from '../../helpers/error'
import Request from '../../models/Request'
import Room from '../../models/Room'
import roomValidation from './room.validation'
const initChatRoom = async (maker, data) => {
const {reqId, modId} = roomValidation.validateRoomInit(data)
// check if the user in the comments
// get object of all the comments in one request
const request = await Request.findById(reqId)
if (! request)
throw new error.ServerError(error.request.notfound, 404)
// can't start a chat, if you're not the request maker
if (! request.userId.equals(maker._id))
throw new error.ServerError(error.user.auth, 404)
const comment = request.participants.find((comment) => {
return comment.userId.equals(modId)
})
if (!comment)
throw new error.ServerError(error.comment.notfound, 404)
// now create the room
const status = await Room.startChatRoom(reqId, maker._id, modId)
return status
}
export default {
initChatRoom
} | 29.371429 | 68 | 0.677043 |
8b82c1f5898d70e05ce4bffca9440c0994cd3391 | 1,989 | js | JavaScript | src/subscriptions/__tests__/reducer.spec.js | andrewmclagan/ethical-jobs-redux-modules | bd8538b1867ffe3abaf759887feb603c21d3e5b1 | [
"MIT"
] | 1 | 2019-07-29T07:08:22.000Z | 2019-07-29T07:08:22.000Z | src/subscriptions/__tests__/reducer.spec.js | andrewmclagan/ethical-jobs-redux-modules | bd8538b1867ffe3abaf759887feb603c21d3e5b1 | [
"MIT"
] | 3 | 2017-07-13T12:03:12.000Z | 2018-03-13T03:57:24.000Z | src/subscriptions/__tests__/reducer.spec.js | andrewmclagan/ethical-jobs-redux-modules | bd8538b1867ffe3abaf759887feb603c21d3e5b1 | [
"MIT"
] | null | null | null | import Immutable from 'immutable';
import { REQUEST, SUCCESS, FAILURE, Assertions } from '@ethical-jobs/redux';
import { initialState } from 'subscriptions/reducer';
import * as Fixtures from './_fixtures';
import Subscriptions from 'subscriptions';
const Reducer = Subscriptions.reducer;
const Actions = Subscriptions.actions;
/*
|--------------------------------------------------------------------------
| Initial state
|--------------------------------------------------------------------------
*/
test('should return correct initial state ', () => {
const expectedState = Immutable.fromJS({
fetching: false,
error: false,
filters: {},
entities: {},
results: [],
result: false,
});
expect(Assertions.initialState(Reducer, expectedState)).toBe(true);
});
/*
|--------------------------------------------------------------------------
| REQUEST actions
|--------------------------------------------------------------------------
*/
test('should handle REQUEST actions correctly', () => {
const actionTypes = [
REQUEST(Actions.CREATE),
REQUEST(Actions.FETCH_COLLECTION),
REQUEST(Actions.FETCH_ENTITY),
REQUEST(Actions.DELETE),
REQUEST(Actions.CONFIRM),
];
expect(
Assertions.requestState(Reducer, actionTypes, initialState)
).toBe(true);
});
test('should handle SUCCESS actions correctly', () => {
const actionTypes = [
SUCCESS(Actions.CREATE),
SUCCESS(Actions.FETCH_ENTITY),
SUCCESS(Actions.DELETE),
SUCCESS(Actions.CONFIRM),
];
expect(
Assertions.successState(Reducer, actionTypes, initialState, Fixtures.success)
).toBe(true);
});
test('should handle FAILURE actions correctly', () => {
const actionTypes = [
FAILURE(Actions.CREATE),
FAILURE(Actions.FETCH_COLLECTION),
FAILURE(Actions.FETCH_ENTITY),
FAILURE(Actions.DELETE),
FAILURE(Actions.CONFIRM),
];
expect(
Assertions.failureState(Reducer, actionTypes, initialState, Fixtures.error)
).toBe(true);
});
| 28.014085 | 81 | 0.590246 |
8b83306d996a21f680baf6c060424fb195fad06f | 188 | js | JavaScript | packages/babel-plugin-transform-react-jsx/src/index.js | Delta-CI/babel | 6e18bc7a7882faf0a27b5f5860e791dd41f31a79 | [
"MIT"
] | 2 | 2019-10-16T08:42:17.000Z | 2021-11-09T10:46:48.000Z | packages/babel-plugin-transform-react-jsx/src/index.js | Delta-CI/babel | 6e18bc7a7882faf0a27b5f5860e791dd41f31a79 | [
"MIT"
] | 1 | 2019-07-24T04:41:06.000Z | 2019-07-24T04:52:58.000Z | packages/babel-plugin-transform-react-jsx/src/index.js | Delta-CI/babel | 6e18bc7a7882faf0a27b5f5860e791dd41f31a79 | [
"MIT"
] | 3 | 2019-12-20T13:48:49.000Z | 2020-06-11T13:35:11.000Z | /* eslint-disable @babel/development/plugin-name */
import createPlugin from "./create-plugin.js";
export default createPlugin({
name: "transform-react-jsx",
development: false,
});
| 20.888889 | 51 | 0.728723 |
8b842c23dfc98d596a8b559f448e68f1a6aa7a60 | 230 | js | JavaScript | src/server/gateways/coin-market-cap.js | Fabryprog/iotex-explorer | f822c65215adbef9436c490abf6efb0cf962ddde | [
"Apache-2.0"
] | null | null | null | src/server/gateways/coin-market-cap.js | Fabryprog/iotex-explorer | f822c65215adbef9436c490abf6efb0cf962ddde | [
"Apache-2.0"
] | null | null | null | src/server/gateways/coin-market-cap.js | Fabryprog/iotex-explorer | f822c65215adbef9436c490abf6efb0cf962ddde | [
"Apache-2.0"
] | null | null | null | import axios from 'axios';
export class CoinMarketCap {
fetchCoinPrice() {
// there are usd, btc and eth prices
const url = 'https://api.coinmarketcap.com/v1/ticker/iotex/?convert=ETH';
return axios.get(url);
}
}
| 23 | 77 | 0.678261 |
8b8452ef630c5491f5e5d2cf621e94420dd892bc | 3,018 | js | JavaScript | app/imports/startup/server/accounts/newAccountCreationHook.js | skykode/kl-rooms | e1a9dd057d01052db2b2a6836c9c6d78b54ae48a | [
"Apache-2.0"
] | null | null | null | app/imports/startup/server/accounts/newAccountCreationHook.js | skykode/kl-rooms | e1a9dd057d01052db2b2a6836c9c6d78b54ae48a | [
"Apache-2.0"
] | null | null | null | app/imports/startup/server/accounts/newAccountCreationHook.js | skykode/kl-rooms | e1a9dd057d01052db2b2a6836c9c6d78b54ae48a | [
"Apache-2.0"
] | null | null | null | import { HTTP } from 'meteor/http';
import { Accounts } from 'meteor/accounts-base';
// this code needs some refactoring later.
// modifies user document before creating it.
// http://docs.meteor.com/api/accounts-multi.html#AccountsServer-onCreateUser
Accounts.onCreateUser((options, user) => {
/* eslint-disable */
if (user.services.facebook) {
// user.emails=[];
user.loginService = 'facebook';
options.profile.loginService = 'Facebook';
const facebookId = user.services.facebook.id;
options.profile.picture = `https://graph.facebook.com/${facebookId}/picture?width=500`;
options.profile.gender = user.services.facebook.gender;
} else if (user.services.google) {
user.loginService = 'google';
options.profile.loginService = 'Google';
const pictureLink = user.services.google.picture;
delete user.services.google.picture;
options.profile.picture = pictureLink;
// GOOGLE PICTURE IS TOO BIG
options.profile.gender = user.services.google.gender;
} else if (user.services.twitter) {
user.loginService = 'twitter';
options.profile.loginService = 'Twitter';
options.profile.picture = `https://twitter.com/${options.profile.name}/profile_image?size=original`;
options.profile.firstName = user.services.twitter.screenName;
user.profile = options.profile;
} else if (user.services.github) {
user.loginService = 'github';
const { github } = user.services;
user.profile = {
firstName: github.username,
lastName: null,
loginService: 'Github',
picture: `https://github.com/${github.username}.png?size=500`,
};
} else if (user.services.linkedin) {
user.loginService = 'linkedin';
const { linkedin } = user.services;
// get picture from linkedIn api
const { data } = HTTP.call(
'GET',
'https://api.linkedin.com/v1/people/~/picture-urls::(original)?format=json',
{
headers: {
Authorization: `Bearer ${linkedin.accessToken}`,
},
timeout: 5000,
}
);
// console.log(data);
user.profile = {
firstName: linkedin.firstName,
lastName: linkedin.lastName,
loginService: 'LinkedIn',
picture: data.values ? data.values[0] : null,
publicProfile: linkedin.publicProfileUrl,
bio: linkedin.headline,
};
} else if (user.services.twitch) {
user.loginService = 'twitch';
const { twitch } = user.services;
user.profile = {
firstName: twitch.display_name,
bio: twitch.bio,
loginService: 'Twitch',
publicProfile: twitch._links.self,
picture: twitch.logo,
};
}
if (user.services.facebook || user.services.google) {
const name = options.profile.name;
delete options.profile.name;
options.profile.firstName = name.split(' ')[0];
options.profile.lastName = name.split(' ')[1];
user.profile = options.profile;
}
return user;
/* eslint-enable */
});
// setups profile
/*
{
firstName,
lastName,
picture
}
*/
| 30.795918 | 104 | 0.654738 |
8b846d1441934eb780607103ff181e352e49b410 | 390 | js | JavaScript | CS568/Codes/State props/Counter.js | yghimiray/MSD | da13ea53bf661cbe4d40de14633d2c5f833fccab | [
"Apache-2.0"
] | null | null | null | CS568/Codes/State props/Counter.js | yghimiray/MSD | da13ea53bf661cbe4d40de14633d2c5f833fccab | [
"Apache-2.0"
] | null | null | null | CS568/Codes/State props/Counter.js | yghimiray/MSD | da13ea53bf661cbe4d40de14633d2c5f833fccab | [
"Apache-2.0"
] | null | null | null | import React from 'react'
class Counter extends React.Component {
render() {
return (
<div>
<p>{this.props.currentValue}</p>
<input type='button'
value='Increment'
onClick={this.props.incrementButtonClickHandler}
/>
</div>
)
}
}
export default Counter | 21.666667 | 68 | 0.476923 |
8b84834b1d369a8047d61b3d2a0c2482bc250221 | 1,138 | js | JavaScript | web/src/App.js | yekibud/yawc | 973c086af18871c6e709acc29007bb512d0c3d17 | [
"BSD-3-Clause"
] | null | null | null | web/src/App.js | yekibud/yawc | 973c086af18871c6e709acc29007bb512d0c3d17 | [
"BSD-3-Clause"
] | null | null | null | web/src/App.js | yekibud/yawc | 973c086af18871c6e709acc29007bb512d0c3d17 | [
"BSD-3-Clause"
] | null | null | null | import React from 'react';
import {BrowserRouter, Switch, Route, Redirect} from 'react-router-dom';
import ApolloProvider from 'lib/apollo-provider';
import ChatUI from 'components/chat';
import LoginUI from 'components/login';
import styles from './App.scss';
export default function App() {
return <ApolloProvider>
<BrowserRouter>
<div className={styles.App}>
<Switch>
<Route exact path="/" component={HomeComponent} />
<Route exact path="/chat"
render={({match: {params: {channel}}}) =>
<ChatUI channel={null} />} />
<Route exact path="/chat/:channel"
render={({match: {params: {channel}}}) =>
<ChatUI channel={channel} />} />
<Route exact path="/login" component={LoginUI} />
<Route component={HomeComponent} />
</Switch>
</div>
</BrowserRouter>
</ApolloProvider>;
}
function HomeComponent() {
return <Redirect to="/chat" />;
}
| 32.514286 | 72 | 0.517575 |
8b863ea90f22d95a658f94c9fc87c231466269f9 | 146 | js | JavaScript | stories/Core/shared/index.js | max3a3/react-paperjs | 1510435a2a32bbc383ace7aa01885642ea02f545 | [
"MIT"
] | 93 | 2017-12-18T20:15:53.000Z | 2022-03-01T21:05:14.000Z | stories/Core/shared/index.js | max3a3/react-paperjs | 1510435a2a32bbc383ace7aa01885642ea02f545 | [
"MIT"
] | 23 | 2018-08-22T15:19:13.000Z | 2021-12-29T22:00:25.000Z | stories/Core/shared/index.js | max3a3/react-paperjs | 1510435a2a32bbc383ace7aa01885642ea02f545 | [
"MIT"
] | 22 | 2018-03-21T07:33:08.000Z | 2022-01-06T15:17:26.000Z | export { default as Mountable } from './Mountable';
export const ref = instanceRef => console.log(instanceRef); // eslint-disable-line no-console
| 48.666667 | 93 | 0.746575 |
8b8754b9e7464bd7490fb1091b4f1c450da0f565 | 1,529 | js | JavaScript | src/routes.js | sarveshtiw/fbf8-app | 59fea0bda24440a52a5988202df936d84a8493d0 | [
"MIT"
] | null | null | null | src/routes.js | sarveshtiw/fbf8-app | 59fea0bda24440a52a5988202df936d84a8493d0 | [
"MIT"
] | null | null | null | src/routes.js | sarveshtiw/fbf8-app | 59fea0bda24440a52a5988202df936d84a8493d0 | [
"MIT"
] | null | null | null | import React from 'react';
import { Router, Route } from 'react-router';
import App from './App';
import App1 from './App1';
import NotFound from './pages/NotFound/NotFound';
import Home from './pages/Home/Home';
import About from './pages/About/About';
import Contact from './pages/Contact/Contact';
import Schedule from './pages/Schedule/Schedule';
import Getting from './pages/Getting-here/Getting-here';
import Meetups from './pages/Meetups/Meetups';
import Watch from './pages/Watch/Watch';
import Registration from './pages/Registration/Registration';
import Login from './pages/Login/Login';
import Faqs from './pages/Faqs/Faqs';
import ForgetPassword from './pages/ForgetPassword/ForgetPassword';
const Routes = (props) => (
<Router {...props}>
<Route path="/" component={App1}>
<Route path="/home" component={Home} />
</Route>
<Route path="/" component={App}>
<Route path="/about" component={About} />
<Route path="/schedule" component={Schedule} />
<Route path="/getting-here" component={Getting} />
<Route path="/meetups" component={Meetups} />
<Route path="/watch" component={Watch} />
<Route path="/registration" component={Registration} />
<Route path="/login" component={Login} />
<Route path="/faqs" component={Faqs} />
<Route path="/forgetpassword" component={ForgetPassword} />
<Route path="/contact" component={Contact} />
<Route path="*" component={NotFound} />
</Route>
</Router>
);
export default Routes;
| 37.292683 | 67 | 0.667757 |
8b8944c3a29789427ac296b5cdd7cfb31679c8b5 | 373 | js | JavaScript | arr/first.js | WebQit/util | 1f6df3d1e446fe8b299d25a84ab2caf3c4f90748 | [
"MIT"
] | 2 | 2020-02-13T21:30:40.000Z | 2020-02-15T12:53:43.000Z | arr/first.js | WebQit/util | 1f6df3d1e446fe8b299d25a84ab2caf3c4f90748 | [
"MIT"
] | null | null | null | arr/first.js | WebQit/util | 1f6df3d1e446fe8b299d25a84ab2caf3c4f90748 | [
"MIT"
] | null | null | null |
/**
* Returns THE FIRST ENTRY OR A NUMBER OF ENTRIES counting forward from the begining.
*
* @param array arr
* @param int amount
*
* @return mixed|array
*/
export default function(arr, amount = 1) {
var count = 0;
arr.forEach(itm => {
count ++;
});
var firsts = arr.slice(arr.length - count, amount);
return arguments.length > 1 ? firsts : firsts[0];
};
| 20.722222 | 85 | 0.646113 |
8b89eafb5a55af8a12aeb067ae71a7b5125f3b0e | 175 | js | JavaScript | public/admin/assets/js/forms-chosen.js | ridwannoor/con10 | c9da1d40d45e864e162e38683034760a9ee09eb4 | [
"MIT"
] | null | null | null | public/admin/assets/js/forms-chosen.js | ridwannoor/con10 | c9da1d40d45e864e162e38683034760a9ee09eb4 | [
"MIT"
] | 2 | 2021-02-02T19:57:59.000Z | 2021-05-11T18:09:48.000Z | public/admin/assets/js/forms-chosen.js | ridwannoor/con10 | c9da1d40d45e864e162e38683034760a9ee09eb4 | [
"MIT"
] | null | null | null | $(document).ready(function() {
'use strict';
/* ===== Bootstrap Time Picker ==== */
/* Ref: https://github.com/jdewit/bootstrap-timepicker */
$('.chosen').chosen();
});
| 19.444444 | 58 | 0.588571 |
8b89fe4fa646862e567fa1a02421fe18e0d05d8d | 1,964 | js | JavaScript | components/progress/__tests__/index.test.js | caojian123/cuke-ui | 67752ec0403d07c86bebf90b3f0d699990217f48 | [
"MIT"
] | 1 | 2019-01-04T08:18:31.000Z | 2019-01-04T08:18:31.000Z | components/progress/__tests__/index.test.js | RyanWlx/cuke-ui | 7e7ed81b9ec0192ee6e42538927c6cfaf064e37a | [
"MIT"
] | null | null | null | components/progress/__tests__/index.test.js | RyanWlx/cuke-ui | 7e7ed81b9ec0192ee6e42538927c6cfaf064e37a | [
"MIT"
] | null | null | null | import React from "react";
import assert from "power-assert";
import { render } from "enzyme";
import toJson from "enzyme-to-json";
import Progress from "../index";
describe("<Progress/>", () => {
it("should render a <Progress/> components", () => {
const wrapper = render(
<div>
<Progress percent={70} />
<Progress percent={70} animation={false} />
</div>
);
expect(toJson(wrapper)).toMatchSnapshot();
});
it("should render five type width <Progress/> ", () => {
const wrapper = render(
<div>
<Progress percent={20} type="default" />
<Progress percent={30} type="success" />
<Progress percent={40} type="info" />
<Progress percent={50} type="warning" />
<Progress percent={60} type="error" />
<Progress percent={20} type="default" animation={false} />
<Progress percent={30} type="success" animation={false} />
<Progress percent={40} type="info" animation={false} />
<Progress percent={50} type="warning" animation={false} />
<Progress percent={60} type="error" animation={false} />
</div>
);
expect(toJson(wrapper)).toMatchSnapshot();
});
it("should find cuke-progress classnames", () => {
const wrapper = render(
<div>
<Progress percent={20} />
<Progress percent={20} animation={true} />
</div>
);
assert(wrapper.find(".cuke-progress").length >= 1);
assert(wrapper.find(".cuke-progress-enter").length >= 1);
assert(wrapper.find(".cuke-progress-bg-animation").length === 1);
assert(wrapper.find(".cuke-progress-bg").length >= 1);
assert(wrapper.find(".cuke-progress-num").length >= 1);
});
it("should can not render info when set showInfo with false", () => {
const wrapper = render(
<div>
<Progress percent={20} showInfo={false} />
</div>
);
assert(wrapper.find(".cuke-progress-num").length === 0);
});
});
| 32.196721 | 71 | 0.588086 |
8b8aa9eabe40fd8b408f5e05b5434eec87f5424c | 882 | js | JavaScript | server/middlewares/authorization.js | shahonov/ReactReduxMongoBoilerplate | 55870b0c42c5d67f706587e7076c53678fd7d839 | [
"MIT"
] | 1 | 2022-03-08T02:01:25.000Z | 2022-03-08T02:01:25.000Z | server/middlewares/authorization.js | shahonov/ReactReduxMongoBoilerplate | 55870b0c42c5d67f706587e7076c53678fd7d839 | [
"MIT"
] | null | null | null | server/middlewares/authorization.js | shahonov/ReactReduxMongoBoilerplate | 55870b0c42c5d67f706587e7076c53678fd7d839 | [
"MIT"
] | null | null | null | const { getUserByToken } = require("../data/usersData");
function authorize(roles = []) {
if (typeof roles === 'string') {
roles = [roles];
}
return [
async (req, res, next) => {
const token = req.headers['x-auth'];
if (token) {
const user = await getUserByToken(token);
if (!user) {
return res.status(401).send('You are not authorized to perform this action');
}
if (roles.includes(user.role)) {
next();
} else {
return res.status(401).send('You are not authorized to perform this action');
}
} else {
return res.status(401).send('You are not authorized to perform this action');
}
}
];
};
module.exports = authorize;
| 30.413793 | 97 | 0.475057 |
8b8bc2bfcb288534e6cbf088860000964480a5d2 | 484 | js | JavaScript | lib/tasks/cpuTaskWorkerThread.js | matvi3nko/decomposed-main-thread | 16411841a67dd0a1efcff0924a9a7cbe08d0797b | [
"MIT"
] | 35 | 2018-10-06T08:36:19.000Z | 2021-03-20T22:50:04.000Z | lib/tasks/cpuTaskWorkerThread.js | nickkooper/decomposed-main-thread | 16411841a67dd0a1efcff0924a9a7cbe08d0797b | [
"MIT"
] | null | null | null | lib/tasks/cpuTaskWorkerThread.js | nickkooper/decomposed-main-thread | 16411841a67dd0a1efcff0924a9a7cbe08d0797b | [
"MIT"
] | 19 | 2018-10-08T07:59:56.000Z | 2022-02-08T13:42:45.000Z | /**
* Created by Nikolay Matvienko on 4/15/18.
*/
'use strict';
const CpuTask = require('./CpuTask');
const { parentPort } = require('worker_threads');
parentPort.on('message', (value) => {
const cpuTask = new CpuTask(value.sum, value.set);
cpuTask.start()
.then(data => {
parentPort.postMessage({ event: 'end', data: data });
})
.catch(error => {
parentPort.postMessage({ event: 'error', error: error });
})
}); | 22 | 69 | 0.56405 |
8b8c49f57f9c8a49e828173d23cef07dca1cb9d4 | 43 | js | JavaScript | public/test.js | chengjunjian2020/low-code-large-screen | 405b5a009f4a9261078a4ea5d038bd2f0c04d0ef | [
"Apache-2.0"
] | null | null | null | public/test.js | chengjunjian2020/low-code-large-screen | 405b5a009f4a9261078a4ea5d038bd2f0c04d0ef | [
"Apache-2.0"
] | null | null | null | public/test.js | chengjunjian2020/low-code-large-screen | 405b5a009f4a9261078a4ea5d038bd2f0c04d0ef | [
"Apache-2.0"
] | null | null | null | let arr = [
{
children: [{}],
},
]
| 7.166667 | 19 | 0.325581 |
8b8c4c7cdf6028cb739385ca7d3d8a1cad648365 | 4,030 | js | JavaScript | node/ipfsHelper.js | wenjinge0424/webasm | 222090aa44487e3409811177de0ea2cf6bcf1a91 | [
"MIT"
] | 73 | 2017-09-19T12:31:11.000Z | 2022-01-21T09:50:30.000Z | node/ipfsHelper.js | wenjinge0424/webasm | 222090aa44487e3409811177de0ea2cf6bcf1a91 | [
"MIT"
] | 49 | 2017-09-18T15:33:34.000Z | 2018-07-31T18:58:15.000Z | node/ipfsHelper.js | wenjinge0424/webasm | 222090aa44487e3409811177de0ea2cf6bcf1a91 | [
"MIT"
] | 18 | 2017-09-20T14:03:08.000Z | 2020-11-10T17:02:56.000Z |
const Web3 = require("../web3.js/packages/web3")
const web3 = new Web3()
const fs = require("fs")
var ipfsAPI = require('ipfs-api')
var config = JSON.parse(fs.readFileSync("config.json"))
var host = config.host || "localhost"
var ipfshost = config.ipfshost || host
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/truebit')
const File = mongoose.model('File', { root: String, data: String })
var ipfs = ipfsAPI(ipfshost, '5001', {protocol: 'http'})
web3.setProvider(new web3.providers.WebsocketProvider('ws://' + host + ':8546'))
const contract_dir = "../compiled/"
var send_opt = {gas:4700000, from:config.base}
function arrange(buf) {
var res = []
var arr = []
for (var i = 0; i < buf.length; i++) {
if (buf[i] > 15) arr.push(buf[i].toString(16))
else arr.push("0" + buf[i].toString(16))
}
var acc = ""
arr.forEach(function (b) { acc += b; if (acc.length == 64) { res.push("0x"+acc); acc = "" } })
if (acc != "") res.push("0x"+acc)
return res
}
function bufferSize(n) {
return Math.ceil(Math.log(n)/Math.log(2));
}
function completeArray(arr) {
var tlen = Math.pow(2, bufferSize(arr.length));
while (arr.length < tlen) arr.push(["0x00", "0x00"])
}
function chunkify(arr) {
// make chunks of length 1024
var res = []
var acc = []
for (var i = 0; i < arr.length; i++) {
acc.push(arr[i])
if (acc.length == 1024) {
res.push(acc)
acc = []
}
}
if (acc.length > 0) res.push(acc.concat(["0x00", "0x00"]))
completeArray(res)
return res
}
async function uploadBuffer(fs, buf) {
var arr = arrange(buf)
var chunks = chunkify(arr)
var acc = []
for (var i = 0; i < chunks.length; i++) {
// console.log(arr)
console.log("len", chunks[i].length)
var hash = await fs.methods.addChunk(chunks[i], 10).call(send_opt)
var res = await fs.methods.addChunk(chunks[i], 10).send(send_opt)
console.log("got hash", hash, "tx", res)
acc.push(hash)
}
if (chunks.length == 1) return
console.log("Combining chunks")
var res = await fs.methods.combineChunks(acc, 10, bufferSize(chunks.length)).send(send_opt)
var hash = await fs.methods.combineChunks(acc, 10, bufferSize(chunks.length)).call(send_opt)
console.log(res)
// still have to make this into file id
var res = await fs.methods.fileFromChunk("block.data", hash, buf.length).send(send_opt)
var file_id = await fs.methods.fileFromChunk("block.data", hash, buf.length).call(send_opt)
return {hash: hash, file_id: file_id, size: buf.length}
}
function createContract(name, addr) {
var abi = JSON.parse(fs.readFileSync(contract_dir + name + ".abi"))
return new web3.eth.Contract(abi, addr)
}
var filesystem = new web3.eth.Contract(JSON.parse(fs.readFileSync(contract_dir + "Filesystem.abi")), config.fs)
var ipfs_store = new web3.eth.Contract(JSON.parse(fs.readFileSync(contract_dir + "Ipfs.abi")), config.ipfs)
var ipfs_load = new web3.eth.Contract(JSON.parse(fs.readFileSync(contract_dir + "IpfsLoad.abi")), config.ipfs_load)
async function readData(hash) {
var asd = await File.find({root: hash})
return asd[0].data
}
// Load a block to ipfs contracts
async function handleIpfsLoad(ev) {
var id = ev.returnValues.id
var root = ev.returnValues.state
var fname = await readData(root)
ipfs_load.methods.resolveName(id, fname, 6).send(send_opt)
var bl = await ipfs.block.get(fname)
var obj = await uploadBuffer(filesystem, bl.data)
ipfs_store.methods.submitBlock(obj.file_id).send(send_opt)
var pollBlock = async function () {
var res = ipfs_store.methods.load(fname).call(send_opt)
if (parseInt(res) != 0) ipfs_load.methods.resolveBlock(id, obj.hash, obj.size)
}
setInterval(pollBlock, 3000)
}
async function main() {
ipfs_load.events.LoadToIpfs((err,ev) => handleIpfsLoad(ev))
console.log("Listening events")
}
main()
| 31.24031 | 115 | 0.645906 |
8b8eb12680ad670f4d3ba3e2994f09409a310bd9 | 10,562 | js | JavaScript | public/js/ajax-crud.js | MaxBernard/l5articles | fdec0763d48ba7f39f0dbd5530480df50777a1dc | [
"MIT"
] | null | null | null | public/js/ajax-crud.js | MaxBernard/l5articles | fdec0763d48ba7f39f0dbd5530480df50777a1dc | [
"MIT"
] | null | null | null | public/js/ajax-crud.js | MaxBernard/l5articles | fdec0763d48ba7f39f0dbd5530480df50777a1dc | [
"MIT"
] | null | null | null | /* $(document).ready(function() {
tinymce.init({ selector:'textarea' });
});
*/
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//===================================
/*
tinymce.init({
mode: "specific_textareas",
editor_selector: "mceEditor",
plugins: ['advlist autolink lists link image charmap print preview anchor textcolor',
'searchreplace visualblocks code fullscreen emoticons spellchecker',
'insertdatetime media table contextmenu paste code help wordcount'],
toolbar: 'insert | undo redo | formatselect | fontselect | fontsizeselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | emoticons | help',
content_css : "/css/app.css",
theme_advanced_font_sizes: "10px,12px,13px,14px,16px,18px,20px",
font_size_style_values : "10px,11px,12px,13px,14px,16px,18px,20px",
//width : "90%",
height: "536"
});
*/
//=================================
//== Add a new article
$(document).on('click', '.add-modal', function() {
console.log('Add button clicked!');
$('.modal-title').text('Create Article');
$('#a_body').val('');
$('#addModal').modal('show');
$('#addModal input[0]').focus();
});
$(document).on('click', '.crud_add', function(e) {
// console.log('Save button clicked!');
e.preventDefault();
$('#a_body').val(tinymce.activeEditor.getContent());
$.ajax({
url: 'api/article',
method: 'POST',
data: new FormData($('#addArticleForm')[0]),
//dataType: 'json',
cache: false,
processData: false,
contentType: false,
success: function(res) {
// console.log('Back from Ajax POST request');
// console.log(res.responseJSON.message);
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((res.errors)) {
console.log('Error...');
setTimeout(function () {
$('#addModal').modal('show');
toastr.error('Validation error!', 'Error Alert', {timeOut: 5000});
}, 500);
if (res.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(res.errors.title);
}
if (res.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(res.errors.content);
}
} else {
// console.log('Success... Data: ');
// console.log(res);
var rData =
'<tr>' +
'<td align="center">' + res.data.id + '</td>' +
'<td align="center" width="3%"><img src="/storage/cover_images/noimage.png" style="width:50%"/>' +
'<td>' + res.data.title +
'<td>' + res.data.category +
'<td>' + res.data.tag +
'<td align="center">' +
"<button class='show-modal btn btn-info btn-xs' data-id='" + res.data.id + "' data-title='.' data-content='.'><i class='fa fa-eye ml-1'></i> Show></button>"+
"<button class='edit-modal btn btn-warning btn-xs' data-id='" + res.data.id + "' data-title='.' data-content='.'><i class='fa fa-edit ml-1'></i> Edit</button>"+
"<button class='delete-modal btn btn-danger btn-xs' data-id='" + res.data.id + "' data-title='.' data-content='.'><i class='fa fa-trash ml-1'></i> Delete</button>"+
'</tr>';
$("#articleTable").append(rData);
toastr.success('Successfully added Article!' + res.data.id, 'Success Alert', {timeOut: 5000});
}
},
});
});
//=================================
// Show an article
$(document).on('click', '.show-modal', function() {
console.log('Show button clicked!');
$('.modal-title').text('Show Article - ' + $(this).data('id'));
$('#s_id').val($(this).data('id'));
//$('#s_title').val($(this).data('title'));
var id = $('#s_id').val();
//$('.s_body').html($(this).data('content'));
//tinymce.activeEditor.setContent($(this).data('content'));
//$('#showModal').modal('show');
console.log('Sending Ajax Get request.');
$.ajax({
url: 'api/article/' + id,
method: 'GET',
dataType: 'json',
success: function(res) {
console.log('Back from Ajax GET request');
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((res.errors)) {
setTimeout(function () {
$('#showModal').modal('show');
toastr.error('Validation error!', 'Error Alert', {timeOut: 5000});
}, 500);
if (res.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(res.errors.title);
}
if (res.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(res.errors.content);
}
} else {
//console.log('Success...');
//console.log('Body: ', res.data.body);
toastr.success('Successfully received article!', 'Success Alert', {timeOut: 5000});
// $('#s_title').val(res.data.title);
$('.modal-title').text(res.data.title);
$('.s_body').html(res.data.body);
$('#showModal').modal('show');
}
}
});
});
//=================================
//== Edit an article
$(document).on('click', '.edit-modal', function() {
console.log('Edit button clicked!');
$('.modal-title').text('Edit Article - '+$(this).data('id'));
$('#e_id').val($(this).data('id'));
//$('#e_title').val($(this).data('title'));
var id = $('#e_id').val();
//$('#e_body').html($(this).data('content'));
//tinymce.activeEditor.setContent($(this).data('content'));
//$('#editModal').modal('show');
$.ajax({
url: 'api/article/' + id,
method: 'GET',
dataType: 'json',
success: function(res) {
console.log('Back from Ajax GET request');
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((res.errors)) {
setTimeout(function () {
$('#showModal').modal('show');
toastr.error('Validation error!', 'Error Alert', {timeOut: 5000});
}, 500);
if (res.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(res.errors.title);
}
if (res.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(res.errors.content);
}
} else {
console.log('Success...');
console.log(res);
toastr.success('Successfully received Article: ' + res.data.id, 'Success Alert', {timeOut: 3000});
$('#e_title').val(res.data.title);
$('#e_category').val(res.data.category);
$('#e_tag').val(res.data.tag);
tinymce.activeEditor.setContent(res.data.body);
//$('.modal-title').text(res.data.title);
$('#editModal').modal('show');
$('#e_title').focus();
//$('#editModal input[0]').focus();
}
}
});
});
// When 'Update' is clicked we send the edit data to the server
// and also use it to update the row
$(document).on('click', '.crud_update', function(e) {
console.log('Update button clicked!');
e.preventDefault();
var id = $('#e_id').val();
$('#e_body').val(tinymce.activeEditor.getContent());
//-- Send edited data to the server to update the post
console.log('Sending Ajax POST request.');
$.ajax({
url: 'api/article/' + id,
method: 'POST',
data: new FormData($('#editArticleForm')[0]),
//dataType: 'json',
cache: false,
processData: false,
contentType: false,
success: function(res) {
console.log('Back from Ajax POST request');
//console.log(res.responseJSON.message);
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((res.errors)) {
setTimeout(function () {
$('#editModal').modal('show');
toastr.error('Validation error!', 'Error Alert', {timeOut: 5000});
}, 500);
if (res.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(res.errors.title);
}
if (res.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(res.errors.content);
}
} else {
// console.log('Success...');
// console.log(res);
toastr.success('Successfully updated Article: ', 'Success Alert', {timeOut: 2000});
//$("#articleTable").ajax.reload();
//$('#articleTable').load(window.location + '#articleTable');
/*var r = table.row( {selected: true} );
r.data( {
"id" : data.id,
"title" : data.title,
"action" : "<button class='show-modal btn btn-info btn-xs' data-id='" + data.id + "' data-title='.' data-content='.'><i class='fa fa-eye ml-1'></i> Show></button>"+
"<button class='edit-modal btn btn-primary btn-xs' data-id='" + data.id + "' data-title='.' data-content='.'><i class='fa fa-pencil ml-1'></i> Edit</button>"+
"<button class='delete-modal btn btn-danger btn-xs' data-id='" + data.id + "' data-title='.' data-content='.'><i class='fa fa-trash ml-1'></i> Delete</button>"
} ).draw(false);*/
}
}
});
});
//=================================
// delete a post
/*
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('id'));
$('#title_delete').val($(this).data('title'));
$('#deleteModal').modal('show');
id = $('#id_delete').val();
});
$('.modal-footer').on('click', '.delete', function() {
$.ajax({
type: 'DELETE',
url: 'posts/' + id,
data: {
'_token': $('input[name=_token]').val(),
},
success: function(data) {
toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
$('.item' + data['id']).remove();
$('.col1').each(function (index) {
$(this).html(index+1);
});
}
});
});
*/
| 37.587189 | 220 | 0.515527 |
8b8ed6419072861c668e80548b38ad2925e764c7 | 778 | js | JavaScript | tests/unit/mixins/unsubscribe-route-test.js | DiogenesPolanco/ember-apollo-client | 6296bb61228e0818d624a59668df309f43bab617 | [
"MIT"
] | null | null | null | tests/unit/mixins/unsubscribe-route-test.js | DiogenesPolanco/ember-apollo-client | 6296bb61228e0818d624a59668df309f43bab617 | [
"MIT"
] | null | null | null | tests/unit/mixins/unsubscribe-route-test.js | DiogenesPolanco/ember-apollo-client | 6296bb61228e0818d624a59668df309f43bab617 | [
"MIT"
] | null | null | null | import Ember from 'ember';
import UnsubscribeRoute from 'ember-apollo-client/mixins/unsubscribe-route';
import { module, test } from 'qunit';
const { Route } = Ember;
module('Unit | Mixin | unsubscribe route');
let route;
test('it calls _apolloUnsubscribe on deactivate', function(assert) {
assert.expect(1);
let unsubscribeCalled = false;
let model = Ember.Object.create({
id: 'fakeID',
name: 'foo',
_apolloUnsubscribe: () => {
unsubscribeCalled = true;
}
});
let controller = Ember.Object.create({});
route = Route.extend(UnsubscribeRoute, {});
let subject = route.create({ controller });
subject.setupController(controller, model);
subject.resetController();
assert.ok(unsubscribeCalled, '_apolloUnsubscribe() was called');
});
| 26.827586 | 76 | 0.694087 |
8b8f090735ce11f648c874345939a1d07c94f3b6 | 353 | js | JavaScript | src/sdk/globals.js | humansapp/adjust_web_sdk | f8e0b5facba94d6dfe8eda9e24f9fabce9680e83 | [
"Unlicense",
"MIT"
] | 27 | 2018-03-29T15:44:34.000Z | 2022-03-28T11:11:58.000Z | src/sdk/globals.js | humansapp/adjust_web_sdk | f8e0b5facba94d6dfe8eda9e24f9fabce9680e83 | [
"Unlicense",
"MIT"
] | 18 | 2019-05-20T10:31:22.000Z | 2022-03-25T22:35:55.000Z | src/sdk/globals.js | humansapp/adjust_web_sdk | f8e0b5facba94d6dfe8eda9e24f9fabce9680e83 | [
"Unlicense",
"MIT"
] | 20 | 2018-05-11T20:41:08.000Z | 2022-03-04T06:31:50.000Z | // @flow
declare var __ADJUST__NAMESPACE: string
declare var __ADJUST__SDK_VERSION: string
declare var process: {|
env: {|
NODE_ENV: 'development' | 'production' | 'test'
|}
|}
const Globals = {
namespace: __ADJUST__NAMESPACE || 'adjust-sdk',
version: __ADJUST__SDK_VERSION || '5.0.0',
env: process.env.NODE_ENV
}
export default Globals
| 20.764706 | 51 | 0.708215 |
8b907feb77d6c8ea16e0ef30af0d84509aafdd8a | 1,571 | js | JavaScript | backend/src/product.js | Theryston/product-crud | ce283281bffde5430adb178eb711537c86321f42 | [
"MIT"
] | 1 | 2021-04-01T17:17:13.000Z | 2021-04-01T17:17:13.000Z | backend/src/product.js | Theryston/product-crud | ce283281bffde5430adb178eb711537c86321f42 | [
"MIT"
] | null | null | null | backend/src/product.js | Theryston/product-crud | ce283281bffde5430adb178eb711537c86321f42 | [
"MIT"
] | null | null | null | const Product = require('../database/Product')
module.exports = {
create: async (req, res) => {
var product = req.body
try {
var newProduct = await Product.create({
name: product.name, price: product.price
})
res.status(201)
res.json(newProduct)
} catch(err) {
res.status(500)
res.json({
err: err
})
}
},
read: async (req, res) => {
try {
var products = await Product.findAll({
attributes: ['name', 'price', 'id'], row: true
})
res.status(200)
res.json(products)
} catch(err) {
res.status(500)
res.json({
err: err
})
}
},
readById: async (req, res) => {
var {id} = req.params
try {
var products = await Product.findOne({
where: {
id: id
}})
res.status(200)
res.json(products)
} catch(err) {
res.status(500)
res.json({
err: err
})
}
},
update: async (req, res) => {
var {id} = req.params
var data = req.body
try {
await Product.update({...data}, {where: {id: id}})
res.status(200)
res.json({message: 'Produto atualizado com sucesso!'})
} catch(err) {
res.status(500)
res.json({err: err})
}
},
delete: async (req, res) => {
var {id} = req.params
try {
await Product.destroy({where: {id: id}})
res.status(200)
res.json({message: 'Produto deletado com sucesso!'})
} catch (err) {
res.status(500)
res.json({err: err})
}
}
} | 20.671053 | 60 | 0.503501 |
b9503ce98a15c899056992e2a0e5ada6949862da | 3,674 | js | JavaScript | node_modules/apiconnect/node_modules/apiconnect-assembly/src/js/assembly/PolicyFactory.js | katerinachinnappan/SeatFinder | 89aaff128c44807b796a7bf0cd5cb35af5a06654 | [
"MIT"
] | null | null | null | node_modules/apiconnect/node_modules/apiconnect-assembly/src/js/assembly/PolicyFactory.js | katerinachinnappan/SeatFinder | 89aaff128c44807b796a7bf0cd5cb35af5a06654 | [
"MIT"
] | null | null | null | node_modules/apiconnect/node_modules/apiconnect-assembly/src/js/assembly/PolicyFactory.js | katerinachinnappan/SeatFinder | 89aaff128c44807b796a7bf0cd5cb35af5a06654 | [
"MIT"
] | null | null | null | /********************************************************* {COPYRIGHT-TOP} ***
* Licensed Materials - Property of IBM
* 5725-Z22, 5725-Z63, 5725-U33, 5725-Z63
*
* (C) Copyright IBM Corporation 2016, 2017
*
* All Rights Reserved.
* US Government Users Restricted Rights - Use, duplication or disclosure
* restricted by GSA ADP Schedule Contract with IBM Corp.
********************************************************** {COPYRIGHT-END} **/
// Node module: apiconnect-assembly
'use strict';
angular.module('apiconnect-assembly').factory('ApimPolicyFactory', ['$q', function($q) {
var policies = [];
policies.push({
info: {
name: 'switch',
categories: ['Logic'],
display: {
color: 'inherit',
icon: 'call_split'
},
description: "Define sets of policies to execute for specific conditions. Multiple cases can be defined, and each case may be associated with an arbitrary condition. Only the first matching case will be executed."
},
classes: ["logic"],
logic: true,
gateways: ["micro-gateway", "datapower-gateway"],
properties: {
"type": "object",
"additionalProperties": false,
"required": ["case"],
"properties": {
"title": {
"type": "string"
},
"description": {
"type": "string"
},
"case": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": false,
"oneOf": [
{"required": ["condition", "execute"]},
{"required": ["otherwise"]}
],
"properties": {
"condition": {
"type": "string"
},
"execute": {
"type": "array"
},
"otherwise": {
"type": "array"
}
}
}
}
}
}
});
policies.push({
info: {
name: 'if',
categories: ['Logic'],
display: {
color: 'inherit',
icon: 'call_made'
}
},
classes: ["logic"],
logic: true,
gateways: ["micro-gateway", "datapower-gateway"],
properties: {
"type": "object",
"additionalProperties": false,
"required": ["condition"],
"properties": {
"title": {
"type": "string"
},
"description": {
"type": "string"
},
"condition": {
"type": "string"
},
"execute": {
type: "array"
}
}
}
});
policies.push({
info: {
name: 'throw',
categories: ['Logic'],
display: {
color: '#D0021B',
icon: 'report_problem'
}
},
gateways: ["micro-gateway", "datapower-gateway"],
properties: {
"type": "object",
"additionalProperties": false,
"required": ["name"],
"properties": {
"title": {
"type": "string"
},
"name": {
"type": "string"
},
"message": {
"type": "string"
}
}
}
});
var policyPartials = {
"if": "src/html/policies/if.html",
"throw": "src/html/policies/throw.html",
"switch": "src/html/policies/switch.html"
};
return {
getPolicies: function() {
return $q(function(resolve) {
var allPolicies = angular.copy(policies);
resolve(allPolicies);
});
},
getPolicyPartial: function(policyName) {
var customPartial = policyPartials[policyName];
return (customPartial) ? customPartial : "src/html/policies/generator.html";
}
};
}]);
| 24.993197 | 219 | 0.477137 |
b95061f1b1f0438ea125c4781a615d02746f0134 | 3,313 | js | JavaScript | plugins/xmpp/js/XmppRosterEntry.js | jelly/zarafa-webapp | 24c024da7e0d6e5ab39eca3be252440b9c8dd092 | [
"MIT"
] | 4 | 2015-05-21T03:56:32.000Z | 2019-11-21T22:01:12.000Z | plugins/xmpp/js/XmppRosterEntry.js | jelly/zarafa-webapp | 24c024da7e0d6e5ab39eca3be252440b9c8dd092 | [
"MIT"
] | null | null | null | plugins/xmpp/js/XmppRosterEntry.js | jelly/zarafa-webapp | 24c024da7e0d6e5ab39eca3be252440b9c8dd092 | [
"MIT"
] | null | null | null | Ext.namespace('Zarafa.plugins.xmpp');
/**
* @class Zarafa.plugins.xmpp.XmppRosterEntry
* @extends Object
*
* Represents an entry (user) in the roster.
*
*/
Zarafa.plugins.xmpp.XmppRosterEntry = Ext.extend(Object, {
/**
* @constructor
* @param {String} jid Unique XMPP ID ('Jabber ID')
* @param {String} name user name
* @param {String} subscription subscription type ('none', 'to', 'from', 'both')
*/
constructor : function(jid, name, subscription)
{
// Copy parameters
this.jid = jid;
this.setName(name);
this.subscription = subscription;
// Initialise group list
this.groups = [];
// Create a vCard for this entry
this.vCard = new Zarafa.plugins.xmpp.XmppVCard();
// Create a presence object
this.presence = new Zarafa.plugins.xmpp.XmppPresence('offline', '');
// Parent constructor
Zarafa.plugins.xmpp.XmppRosterEntry.superclass.constructor.call(this);
},
/**
* @return {String} JID ('Jabber ID') of this entry.
*/
getJID : function()
{
return this.jid;
},
/**
* @return {String} returns the user name of this entry.
*/
getName : function()
{
return this.name;
},
/**
* Returns a display-friendly representation of the entry.
* @return {String} the name of the entry if this has been set, the JID otherwise.
*/
getDisplayName : function()
{
return this.getVCard().getFullName() || this.name || this.jid;
},
/**
* @return {String} subscription type ('none', 'to', 'from', 'both')
*/
getSubscription : function()
{
return this.subscription;
},
/**
* Sets the entry's JID.
* @param {String} jid Unique XMPP ID ('Jabber ID')
*/
setJID : function(jid)
{
this.jid = jid;
},
/**
* Sets the entry's user name.
* @param {String} name user name
*/
setName : function(name)
{
this.name = Ext.util.Format.htmlEncode(name);
},
/**
* Sets the entry's subscription type.
* @param {String} subscription subscription type ('none', 'to', 'from', 'both')
*/
setSubscription : function(subscription)
{
this.subscription = subscription;
},
/**
* @return {String[]} the set of groups this entry is a member of
*/
getGroups : function()
{
return this.groups;
},
/**
* Clears the list of groups in this entry.
*/
clearGroups : function()
{
this.groups = [];
},
/**
* Adds a group to this entry.
*
* @param {String} group a group this entry is a part of.
*/
addGroup : function(group)
{
this.groups.push(Ext.util.Format.htmlEncode(group));
},
/**
* Removes a group from this entry.
*
* @param {String} group a group this entry is a part of.
*/
removeGroup : function(group)
{
this.groups.remove(group);
},
/**
* Returns the vCard for this entry.
*
* @return {Zarafa.plugins.xmpp.XmppVCard} the vCard for this entry.
*/
getVCard : function()
{
return this.vCard;
},
/**
* Gets the presence of this entry.
*
* @return {Zarafa.plugins.xmpp.XmppPresence} presence object.
*/
getPresence : function()
{
return this.presence;
},
/**
* Sets the presence of the entry.
*
* @param show user availability. One of 'chat', 'dnd', 'away', 'xa', or null
* @param status user status message
*/
setPresence : function(show, status)
{
this.presence.set(show, status);
}
});
| 19.838323 | 84 | 0.630546 |
b950b9a18a6ab83cf3eadf5bfdca490d054ede78 | 1,242 | js | JavaScript | service-workers/service-worker/resources/fetch-variants-worker.js | meyerweb/wpt | f04261533819893c71289614c03434c06856c13e | [
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | service-workers/service-worker/resources/fetch-variants-worker.js | meyerweb/wpt | f04261533819893c71289614c03434c06856c13e | [
"BSD-3-Clause"
] | 7,642 | 2018-05-28T09:38:03.000Z | 2022-03-31T20:55:48.000Z | service-workers/service-worker/resources/fetch-variants-worker.js | meyerweb/wpt | f04261533819893c71289614c03434c06856c13e | [
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | importScripts('/common/get-host-info.sub.js');
importScripts('test-helpers.sub.js');
importScripts('/resources/testharness.js');
const storedResponse = new Response(new Blob(['a simple text file']))
const absolultePath = `${base_path()}/simple.txt`
self.addEventListener('fetch', event => {
const search = new URLSearchParams(new URL(event.request.url).search.substr(1))
const variant = search.get('variant')
const delay = search.get('delay')
if (!variant)
return
switch (variant) {
case 'forward':
event.respondWith(fetch(event.request.url))
break
case 'redirect':
event.respondWith(fetch(`/xhr/resources/redirect.py?location=${base_path()}/simple.txt`))
break
case 'delay-before-fetch':
event.respondWith(
new Promise(resolve => {
step_timeout(() => fetch(event.request.url).then(resolve), delay)
}))
break
case 'delay-after-fetch':
event.respondWith(new Promise(resolve => {
fetch(event.request.url)
.then(response => step_timeout(() => resolve(response), delay))
}))
break
}
});
| 34.5 | 101 | 0.583736 |
b95122f1fadf5dcfeffa784ef5c7984cfd933232 | 51 | js | JavaScript | spec/fixtures/fixture.js | friends-of-js/include-import-loader | 0fb6a76196c0dad1d01965efe1b0f4c0f943d7b3 | [
"MIT"
] | null | null | null | spec/fixtures/fixture.js | friends-of-js/include-import-loader | 0fb6a76196c0dad1d01965efe1b0f4c0f943d7b3 | [
"MIT"
] | 543 | 2018-04-14T18:55:04.000Z | 2021-08-02T08:09:15.000Z | spec/fixtures/fixture.js | friends-of-js/include-import-loader | 0fb6a76196c0dad1d01965efe1b0f4c0f943d7b3 | [
"MIT"
] | null | null | null | export function test () {
return Math.random()
}
| 12.75 | 25 | 0.666667 |
b951a36af9b9846aecd63f6a0481bacf1aa54806 | 420 | js | JavaScript | src/pages/DashboardCrashes.js | gladstargtschool6/SafetyMaster | 42269a524052d558ad70f0519c095825f4800d08 | [
"MIT"
] | 1 | 2020-05-05T22:01:34.000Z | 2020-05-05T22:01:34.000Z | src/pages/DashboardCrashes.js | gladstargtschool6/SafetyMaster | 42269a524052d558ad70f0519c095825f4800d08 | [
"MIT"
] | 5 | 2020-05-04T13:38:01.000Z | 2022-02-27T06:15:09.000Z | src/pages/DashboardCrashes.js | gladstargtschool6/SafetyMaster | 42269a524052d558ad70f0519c095825f4800d08 | [
"MIT"
] | 9 | 2020-05-01T16:39:19.000Z | 2020-08-20T11:11:31.000Z | import React from "react";
import DashboardNav from "../components/Header/DashboardNav";
import Crashes from '../components/Charts/Crashes';
const DashboardCrashes = () => {
const body = (
<div className="container-fluid my-4 pt-4">
<div className="bg-white shadow m-1 p-3">
<Crashes/>
</div>
</div>
);
return <DashboardNav body={body} />;
};
export default DashboardCrashes;
| 24.705882 | 61 | 0.640476 |
b951a912d51072c4b640f2fdad164b75ce2645de | 10,051 | js | JavaScript | js/charts.js | mami-project/pto-web | bfff74cf404aaba6a1936b5e7ca1e963bef0821b | [
"MIT"
] | null | null | null | js/charts.js | mami-project/pto-web | bfff74cf404aaba6a1936b5e7ca1e963bef0821b | [
"MIT"
] | null | null | null | js/charts.js | mami-project/pto-web | bfff74cf404aaba6a1936b5e7ca1e963bef0821b | [
"MIT"
] | null | null | null | function initChartPage () {
let page = new URLSearchParams(window.location.search).get('page');
fetch(baseUrl + '/static/json/config.json')
.then(response => response.json())
.then(data => fetch(baseUrl + '/static/json/' + data['pages'][page]['pageConfig']))
.then(response => response.json())
.then(data => drawPage(data))
.catch(e => console.log(e));
}
function drawPage (pageConfig) {
drawHeader(pageConfig);
drawContainers(pageConfig);
drawCharts(pageConfig);
}
function drawHeader (pageConfig) {
const header = document.querySelector('header');
const h1 = document.createElement('h1');
h1.classList.add('w3-xxxlarge');
h1.innerText = pageConfig['title'];
header.appendChild(h1);
const h4 = document.createElement('h4');
h4.innerText = pageConfig['description'];
header.appendChild(h4);
}
function drawContainers (pageConfig) {
const chartsDiv = document.getElementById('chartsDiv');
for (let chartConfig of pageConfig['charts']) {
const chartDiv = document.createElement('div');
chartDiv.classList.add('chart-div');
const title = document.createElement('h2');
title.innerText = chartConfig['title'];
chartDiv.appendChild(title);
const description = document.createElement('h4');
description.innerText = chartConfig['description'];
chartDiv.appendChild(description);
const conditionDescriptions = document.createElement('p');
conditionDescriptions.style.fontSize = '10pt';
for (let condition of chartConfig['conditions']) {
conditionDescriptions.innerHTML = conditionDescriptions.innerHTML + "<b>" + condition + "</b>: " + chartConfig['descriptions'][condition] + "<br>";
}
chartDiv.appendChild(conditionDescriptions);
const sharesDiv = document.createElement('div');
chartDiv.appendChild(sharesDiv);
const volumeDiv = document.createElement('div');
chartDiv.appendChild(volumeDiv);
chartsDiv.appendChild(chartDiv);
}
// show footer after all containers
document.getElementsByTagName('footer')[0].style.display = 'block';
}
function drawCharts (pageConfig) {
drawChart(pageConfig['charts'], 0)
}
function drawChart (chartConfigs, index) {
if (chartConfigs.length <= index) {
return;
}
const chartsDiv = document.getElementById('chartsDiv');
const chartDiv = chartsDiv.children[index];
const sharesDiv = chartDiv.children[3];
const volumeDiv = chartDiv.children[4];
encodedQueryToQueryResultOrSubmit(
chartConfigs[index]['query'],
function (data) {
drawC3Chart(sharesDiv, volumeDiv, chartConfigs, index, data);
},
function () {
sharesDiv.innerText = 'The query behind this chart is still pending.';
drawChart(chartConfigs, index + 1);
},
function () {
sharesDiv.innerText = 'The query behind this chart failed.';
drawChart(chartConfigs, index + 1);
},
function () {
sharesDiv.innerText = 'The query behind this chart was submitted but is still pending.';
drawChart(chartConfigs, index + 1);
},
function () {
sharesDiv.innerText = 'The query submission failed. Make sure you have permission.';
drawChart(chartConfigs, index + 1);
},
function () {
sharesDiv.innerText = 'The query was not submitted.';
drawChart(chartConfigs, index + 1);
},
function () {
sharesDiv.innerText = 'No API Key available to submit a query.';
drawChart(chartConfigs, index + 1);
},
function (e) {
console.log(e);
sharesDiv.innerText = 'An error occured whil building this chart.';
drawChart(chartConfigs, index + 1);
});
}
function drawC3Chart(sharesDiv, volumeDiv, chartConfigs, index, chartData) {
let chartConfig = chartConfigs[index];
let conditions = chartConfig['conditions'];
let groups = chartData['groups'];
let timeline = getTimeline(groups);
c3.generate({
bindto: sharesDiv,
padding: {
top: 35,
left: 80
},
size: {
height: 350
},
data: {
x: 'x',
columns: getShares(timeline, groups, conditions),
type: 'bar',
groups: [conditions],
colors: chartConfig['colors'],
onclick: d => showObsList(timeline[d.index], d.name),
order: null
},
axis: {
x: {
type: 'category',
tick: {
format: function () {return ''}
},
height: 15
},
y: {
tick: {
outer: false,
format: d3.format('.2%')
},
padding: {
top: 10
}
}
},
grid: {
x: {
lines: getLines(timeline)
},
y: {
show: true
}
},
regions: getRegions(timeline),
bar: {
width: {
ratio: 0.7
}
},
legend: {
position: 'inset',
inset: {
anchor: 'top-left',
x: -80,
y: -35,
step: 1
}
},
tooltip: {
format: {
title: x => timeline[x],
name: name => name.substring(name.lastIndexOf('.') + 1, name.length),
value: function(value, ratio, id, index) {return d3.format('.2%')(value) + ' (' + getCount(groups, id, timeline[index]) + ')'}
}
}
});
c3.generate({
bindto: volumeDiv,
padding: {
top: 0,
left: 80
},
size: {
height: 200
},
data: {
x: 'x',
columns: getVolumes(timeline, groups, conditions),
type: 'bar',
groups: [conditions],
colors: getVolumeColors(conditions),
onclick: d => showObsList(timeline[d.index], d.name),
order: null
},
axis: {
x: {
type: 'category',
tick: {
multiline: false,
rotate: -60
}
},
y: {
tick: {
outer: false,
format: d3.format(',')
},
padding: {
top: 10
}
}
},
grid: {
x: {
lines: getLines(timeline)
},
y: {
show: true
}
},
regions: getRegions(timeline),
bar: {
width: {
ratio: 0.7
}
},
legend: {
position: 'inset'
},
tooltip: {
show: false
}
});
drawChart(chartConfigs, index + 1);
}
function getTimeline (groups) {
let timeline = [];
for (let group of groups) {
let date = getDateFromGroup(group);
if (timeline.indexOf(date) === -1) {
timeline.push(getDateFromGroup(group));
}
}
timeline.sort();
return timeline;
}
function getShares (timeline, groups, conditions) {
let result = [['x'].concat(timeline)];
for (let condition of conditions) {
result.push([condition]);
for (let date of timeline) {
result[result.length - 1].push(getCount(groups, condition, date) / getVolume(groups, conditions, date));
}
}
return result;
}
function getVolumes (timeline, groups, conditions) {
let result = [['x'].concat(timeline)];
for (let condition of conditions) {
result.push([condition]);
for (let date of timeline) {
result[result.length - 1].push(getCount(groups, condition, date));
}
}
return result;
}
function getLines (timeline) {
let lines = [];
for (let i = 0; i < timeline.length - 1; i++) {
if (timeline[i].substring(0, 4) !== timeline[i + 1].substring(0, 4)) {
lines.push({value: i + 0.5});
}
}
return lines;
}
function getRegions (timeline) {
let regions = [{axis: 'x', opacity: 0.3}];
for (let i = 0; i < timeline.length - 1; i++) {
if (timeline[i].substring(0, 4) !== timeline[i + 1].substring(0, 4)) {
if(!regions[regions.length - 1].hasOwnProperty('end')) {
regions[regions.length - 1]['end'] = i + 0.5;
} else {
regions.push({axis: 'x', start: i + 0.5, opacity: 0.3});
}
}
}
return regions;
}
function getCount (groups, condition, date) {
for (let group of groups) {
if (condition === getConditionFromGroup(group) && date === getDateFromGroup(group)) {
return getCountFromGroup(group);
}
}
return 0;
}
function getVolume (groups, conditions, date) {
let result = 0;
for (let group of groups) {
if (conditions.indexOf(getConditionFromGroup(group)) !== -1 && date === getDateFromGroup(group)) {
result += getCountFromGroup(group);
}
}
return result;
}
function getConditionFromGroup (group) {
return group[0];
}
function getDateFromGroup (group) {
return group[1].substring(0, 10);
}
function getCountFromGroup (group) {
return group[2];
}
function getVolumeColors(conditions) {
let result = [];
for (let condition of conditions) {
let darkness = 64 + 64 / conditions.length * (conditions.indexOf(condition) + 1);
result[condition] = d3.rgb(darkness, darkness, darkness);
}
return result;
}
| 29.049133 | 159 | 0.52154 |
b9542445479d05b364ade713db3df433532f9c26 | 2,076 | js | JavaScript | lib/plugins/pagination.js | MediaComem/orm-query-builder | c64efdda11d6589201e46441b2468198d8768cbb | [
"MIT"
] | null | null | null | lib/plugins/pagination.js | MediaComem/orm-query-builder | c64efdda11d6589201e46441b2468198d8768cbb | [
"MIT"
] | null | null | null | lib/plugins/pagination.js | MediaComem/orm-query-builder | c64efdda11d6589201e46441b2468198d8768cbb | [
"MIT"
] | null | null | null | const { get } = require('lodash');
const { resolveGetter } = require('../utils');
const ORIGINAL_QUERY = Symbol('pagination-plugin-original-query');
class OrmQueryPaginationPlugin {
constructor(options = {}) {
this.getOffset = resolveGetter(options.getOffset, context => context.options.offset);
this.getLimit = resolveGetter(options.getLimit, context => context.options.limit);
// FIXME: using lodash get should not be possible here
this.getDefaultLimit = resolveGetter(options.getDefaultLimit, context => context.options.defaultLimit || 100);
this.getMaxLimit = resolveGetter(options.getMaxLimit, context => context.options.maxLimit || 250);
}
use(builder) {
builder.after('start', context => this.start(context));
builder.on('countTotal', context => this.countTotal(context));
builder.on('paginate', context => this.paginate(context));
}
start(context) {
let offset = this.getOffset(context);
let limit = this.getLimit(context);
offset = parseInt(offset, 10);
if (isNaN(offset) || offset < 0) {
offset = 0;
}
limit = parseInt(limit, 10);
if (isNaN(limit) || limit < 0 || limit > this.getMaxLimit(context)) {
limit = this.getDefaultLimit(context);
}
context.set('pagination', { offset, limit });
context.addStages('countTotal', 'paginate');
}
async countTotal(context) {
context.set('pagination.total', await context.count());
context[ORIGINAL_QUERY] = context.adapter.getQueryIdentifier(context.get('query'), context);
}
async paginate(context) {
const id = context.adapter.getQueryIdentifier(context.get('query'), context);
if (id !== context[ORIGINAL_QUERY]) {
context.set('pagination.filteredTotal', await context.count());
} else {
context.set('pagination.filteredTotal', context.get('pagination.total'));
}
const { offset, limit } = context.get('pagination');
context.set('query', context.adapter.paginateQuery(context.get('query'), offset, limit, context));
}
}
module.exports = OrmQueryPaginationPlugin;
| 34.032787 | 114 | 0.684008 |
b955d4187d381c07e49a8345d235a1e477018c3d | 8,402 | js | JavaScript | node_modules_bak/cost-of-modules/lib/helpers.js | npmtest/node-npmtest-cost-of-modules | aa03a8cfafdecd47f7385c6e48b3f66bb5761b86 | [
"MIT"
] | null | null | null | node_modules_bak/cost-of-modules/lib/helpers.js | npmtest/node-npmtest-cost-of-modules | aa03a8cfafdecd47f7385c6e48b3f66bb5761b86 | [
"MIT"
] | null | null | null | node_modules_bak/cost-of-modules/lib/helpers.js | npmtest/node-npmtest-cost-of-modules | aa03a8cfafdecd47f7385c6e48b3f66bb5761b86 | [
"MIT"
] | null | null | null | 'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var fs = require('fs-extra');
var syncExec = require('sync-exec');
var Table = require('cli-table2');
var _require = require('colors'),
yellow = _require.yellow;
var argv = require('yargs-parser')(process.argv.slice(2));
var path = require('path');
/*
By default, this assumes production mode
you can disable that by using --include-dev
or by passing includeDev to setup
*/
var productionModifier = '--production';
var setup = function setup(includeDev) {
console.log();
if (argv.includeDev || includeDev) productionModifier = '';
/*
Check if package.json exists
Need it to build dependency tree
*/
var packageJSONExists = fs.existsSync('package.json');
if (!packageJSONExists) {
console.log('package.json not found!');
console.log();
process.exit();
}
/* Do not install dependencies based --no-install flag */
if (argv.install != null && !argv.install) return;
/*
Make sure dependencies are installed
Ignore devDependencies/bundledDependencies by default
Adds them with --include-dev
*/
console.log('Making sure dependencies are installed');
var command = 'npm install ' + productionModifier;
if (argv.yarn) command = command.replace('npm', 'yarn');
console.log(command);
console.log();
/* Check if node modules exist and then backup */
var nodeModulesExist = fs.existsSync('node_modules');
if (nodeModulesExist) fs.copySync('node_modules', 'node_modules_bak');
/* Run install command */
syncExec(command, { stdio: [0, 1, 2] });
console.log();
};
/*
Get dependency tree with npm -ls
Ignore devDependencies/bundledDependencies by default
Adds them with --include-dev
*/
var getDependencyTree = function getDependencyTree() {
var result = syncExec('npm ls --json ' + productionModifier);
return JSON.parse(result.stdout).dependencies;
};
/*
Get root dependencies from tree
These are the ones declared as dependendies in package.json
[a, b, c, d]
*/
var getRootDependencies = function getRootDependencies() {
var dependencyTree = getDependencyTree();
if (!dependencyTree) {
console.log('There are no dependencies!');
console.log();
process.exit(1);
}
return Object.keys(dependencyTree).sort();
};
/* to fix the missing du problem on windows */
var dirSize = function dirSize(root) {
var out = 0;
var _getDirSizeRecursively = void 0;
(_getDirSizeRecursively = function getDirSizeRecursively(rootLocal) {
var itemStats = fs.lstatSync(rootLocal);
if (itemStats.isDirectory()) {
var allSubs = fs.readdirSync(rootLocal);
allSubs.forEach(function (file) {
_getDirSizeRecursively(path.join(rootLocal, file));
});
} else {
out += itemStats.size;
}
})(root);
return Math.floor(out / 1024); /* in KB */
};
/*
Get scoped modules
*/
var getScopedModules = function getScopedModules(scope) {
var modules = {};
var allScopes = fs.readdirSync(path.join('node_modules', scope));
allScopes.forEach(function (name) {
var itemStats = fs.lstatSync(path.join('node_modules', scope, name));
if (itemStats.isDirectory()) {
var size = dirSize(path.join('node_modules', scope, name));
if (name) {
modules[scope + '/' + name] = size;
}
}
});
return modules;
};
var getSizeForNodeModules = function getSizeForNodeModules() {
var modules = {};
var allModules = fs.readdirSync('node_modules');
allModules.forEach(function (name) {
var itemStats = fs.lstatSync(path.join('node_modules', name));
if (itemStats.isDirectory()) {
if (name && name[0] === '@') {
var scopedModules = getScopedModules(name);
Object.assign(modules, scopedModules);
} else if (name) {
var size = dirSize(path.join('node_modules', name));
modules[name] = size;
}
}
});
return modules;
};
/*
Get all nested dependencies for a root dependency
Traverse recursively through the tree
and return all the nested dependendies in a flat array
*/
var getDependenciesRecursively = function getDependenciesRecursively() {
var modules = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var tree = arguments[1];
var deps = Object.keys(tree);
for (var i = 0; i < deps.length; i++) {
var dep = deps[i];
if (_typeof(tree[dep]) === 'object' && tree[dep] !== null) {
if (tree[dep].dependencies !== null) {
if (dep !== 'dependencies') modules.push(dep);
getDependenciesRecursively(modules, tree[dep]);
} else if (tree[dep].version !== null) modules.push(dep);
}
}
return modules;
};
/*
Attach the flat array from getDependenciesRecursively
to it's parent
[{
name: rootDependency,
children: [a, b, c, d]
}]
*/
var attachNestedDependencies = function attachNestedDependencies(rootDependencies) {
var flatDependencies = [];
var dependencyTree = getDependencyTree();
for (var i = 0; i < rootDependencies.length; i++) {
var dep = rootDependencies[i];
flatDependencies.push({
name: dep,
/* Get flat child dependencies array */
children: getDependenciesRecursively([], dependencyTree[dep])
});
}
return flatDependencies.sort();
};
/*
Get all dependencies in a flat array:
Root dependencies + all their children
Deduplicate
*/
var getAllDependencies = function getAllDependencies(flatDependencies) {
var allDependencies = [];
for (var i = 0; i < flatDependencies.length; i++) {
var dep = flatDependencies[i];
allDependencies.push(dep.name); // Root dependency
allDependencies = allDependencies.concat(dep.children); // Children
}
/* Deduplicate */
allDependencies = allDependencies.filter(function (dep, index) {
return allDependencies.indexOf(dep) === index;
});
return allDependencies.sort();
};
var displayResults = function displayResults(flatDependencies, allDependencies, totalSize) {
/* Sort by size */
var sortedDependencies = flatDependencies.sort(function (a, b) {
return b.actualSize - a.actualSize;
});
var table = new Table({ head: ['name', 'children', 'size'] });
for (var i = 0; i < sortedDependencies.length; i++) {
var dep = sortedDependencies[i];
/* Showing only top 10 results in less mode */
if (argv.less && i === 10) {
table.push(['+ ' + (sortedDependencies.length - 10) + ' modules', null, null]);
break;
}
table.push([dep.name, dep.numberOfChildren, (dep.actualSize / 1024).toFixed(2) + 'M' // Converting to M
]);
}
/* Total */
table.push([yellow(sortedDependencies.length + ' modules'), yellow(allDependencies.length - sortedDependencies.length + ' children'), yellow((totalSize / 1024).toFixed(2) + 'M')]); // Converting to M
/* Print the table with some padding */
console.log();
console.log(table.toString());
console.log();
};
/* Return to original state */
var teardown = function teardown() {
/*
If the command is running with no-install,
there is no need for teardown
*/
if (argv.install != null && !argv.install) return;
/*
Restore node_modules backup if it exists
*/
var backupExist = fs.existsSync('node_modules_bak');
if (backupExist) {
fs.removeSync('node_modules');
fs.moveSync('node_modules_bak', 'node_modules');
}
};
module.exports = {
setup: setup,
getSizeForNodeModules: getSizeForNodeModules,
getRootDependencies: getRootDependencies,
attachNestedDependencies: attachNestedDependencies,
getAllDependencies: getAllDependencies,
displayResults: displayResults,
teardown: teardown
}; | 31.946768 | 269 | 0.626637 |
b955e4ff00b33e0735cc32b35b195a6df4084ccb | 390 | js | JavaScript | src/component/project/PDFFindList/PDFFindListItem.js | azu/mu-pdf-viewer | d100cc0848d425e9367dfea9cbcd76a645ef3432 | [
"MIT"
] | 15 | 2016-08-21T07:20:23.000Z | 2021-07-18T01:20:56.000Z | src/component/project/PDFFindList/PDFFindListItem.js | azu/mu-pdf-viewer | d100cc0848d425e9367dfea9cbcd76a645ef3432 | [
"MIT"
] | null | null | null | src/component/project/PDFFindList/PDFFindListItem.js | azu/mu-pdf-viewer | d100cc0848d425e9367dfea9cbcd76a645ef3432 | [
"MIT"
] | 1 | 2016-11-24T08:40:32.000Z | 2016-11-24T08:40:32.000Z | // LICENSE : MIT
"use strict";
const React = require("react");
export default class PDFFindListItem extends React.Component {
render() {
return <li
className={this.props.className}
onClick={this.props.onClick}>
<span className="PDFFindListItem-pageNumber">{this.props.pageNumber}</span>
{this.props.children}
</li>
}
} | 30 | 87 | 0.612821 |
b95661f6134ad1731e074018445deb202a882e05 | 827 | js | JavaScript | electron/lib/env.js | roman0x58/jenia | 7891c15327030fc62afdbde326d66faecf828a7d | [
"0BSD"
] | 8 | 2017-05-31T03:39:33.000Z | 2021-05-14T07:53:03.000Z | electron/lib/env.js | roman0x58/jenia | 7891c15327030fc62afdbde326d66faecf828a7d | [
"0BSD"
] | 6 | 2017-08-23T10:02:22.000Z | 2018-10-05T09:30:57.000Z | electron/lib/env.js | roman0x58/jenia | 7891c15327030fc62afdbde326d66faecf828a7d | [
"0BSD"
] | 1 | 2017-07-20T17:33:01.000Z | 2017-07-20T17:33:01.000Z | 'use strict'
const R = require('ramda')
let ex = {
set: (env) => process.env.NODE_ENV = env,
get: () => process.env.NODE_ENV
}
const modes = { dev: Symbol('development'), prod: Symbol('production') }
const env = () => process.env.NODE_ENV === 'production' ? modes.prod : modes.dev
const platforms = ['darwin', 'linux', 'win32']
const capitalize = R.compose(
R.join(''),
R.juxt([R.compose(R.toUpper, R.head), R.tail])
)
Object.keys(modes).forEach((k) => ex[k] = () => R.equals(env(), modes[k]))
R.forEach((k) => ex[k] = R.always(R.equals(process.platform, k)), platforms)
R.forEach((logic) =>
R.forEach(([m, p]) => ex[m] = (v) => R[logic](ex[p], R.is(Function, v) ? v : R.always(v))(R.F)
, R.map((p) => [R.concat(logic, capitalize(p)), p], platforms)),
['unless', 'when'])
module.exports = ex
| 34.458333 | 98 | 0.588875 |
b95670de748b25f1ad5b5c5637ad09367d22c757 | 1,355 | js | JavaScript | bin/yargsConfig.js | gcyStar/server-cli | cf8d56baddd026e7256f7c9cc1533a99cdd21a04 | [
"MIT"
] | 4 | 2018-03-03T06:55:57.000Z | 2018-03-12T13:57:39.000Z | bin/yargsConfig.js | gcyStar/server-cli | cf8d56baddd026e7256f7c9cc1533a99cdd21a04 | [
"MIT"
] | null | null | null | bin/yargsConfig.js | gcyStar/server-cli | cf8d56baddd026e7256f7c9cc1533a99cdd21a04 | [
"MIT"
] | null | null | null | /**
* Created by chunyang.gao on 2018/2/26.
*/
let yargs = require('yargs')
let fs = require('fs')
let path = require('path')
let argv = yargs.option('d', {
alias: 'root',
demand: 'false',
type: 'string',
default: process.cwd(),
description: 'server root path'
}).option('a', {
alias: 'host',
demand: 'false',
default: '127.0.0.1',
type: 'string',
description: 'Address to use'
}).option('p', {
alias: 'port',
demand: 'false',
type: 'number',
default: 8080,
description: 'Port to use'
}).option('o', {
demand: 'false',
default: false
})
.option('cors', {
demand: 'false',
type: 'string',
default: true
})
.option('P', {
alias: 'proxy',
demand: false //非必须 默认为false 有参数为true
})
.option('v', {
alias: 'version',
demand: 'false',
type: 'boolean',
default: false //
})
.option('D',{
alias: 'deamon',
demand: 'false',
default: false,
type: 'boolean',
})
.option('c',{
alias: 'cacheSupport',
demand: 'false',
default: false,
type: 'boolean'
})
.usage('hs-server [options]')
.example(
'hs-server -d / -p 8080 -a 127.0.0.1', 'listening on localhost:8080'
).help('h').argv;
module.exports = argv | 21.854839 | 76 | 0.511439 |
b9574b0ed041b1b5aebdc9977a739597a1cda194 | 264 | js | JavaScript | src/wwwroot/js/site.js | hkami/gig-local | 26db4692943f0bed342debaa1fcfabea3babb0c5 | [
"MIT"
] | null | null | null | src/wwwroot/js/site.js | hkami/gig-local | 26db4692943f0bed342debaa1fcfabea3babb0c5 | [
"MIT"
] | 19 | 2021-12-11T02:19:02.000Z | 2022-03-14T04:55:45.000Z | src/wwwroot/js/site.js | marcusturewicz/gig-local | 588294493b6a1ce3e8c49c135962351746f92d20 | [
"MIT"
] | 1 | 2022-03-31T09:57:35.000Z | 2022-03-31T09:57:35.000Z | // Function that allows only future dates on an html date input element
function setDateInputMinToToday(elementName) {
var today = `${new Date().toISOString().split('T')[0]}T00:00`;
document.getElementsByName(elementName)[0].setAttribute('min', today);
}
| 44 | 74 | 0.731061 |
b9577c46d36ed81880324be4a391ca1e7599a932 | 2,283 | js | JavaScript | password-generator.js | EunsooJung/unit03-password-generator | 446340eb135a8cd47d3dd122936ebe319cbc18fd | [
"MIT"
] | null | null | null | password-generator.js | EunsooJung/unit03-password-generator | 446340eb135a8cd47d3dd122936ebe319cbc18fd | [
"MIT"
] | null | null | null | password-generator.js | EunsooJung/unit03-password-generator | 446340eb135a8cd47d3dd122936ebe319cbc18fd | [
"MIT"
] | null | null | null | var inputLength = document.querySelector('#inputLength');
var checkboxes = document.querySelectorAll('.checkbox');
var textarea = document.querySelector('#generatedPassword');
function _getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const generator = {
createNumber: function(count) {
let str = '';
for (let i = 0; i < count; i++) {
str += _getRandomNumber(0, 9);
}
return str;
},
createLower: function(count) {
let letters = 'abcdefghijklmnoppqrstuvwxyz',
str = '';
for (let i = 0; i < count; i++) {
str += letters.charAt(_getRandomNumber(0, letters.length - 1));
}
return str;
},
createUpper: function(count) {
let capitalLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
str = '';
for (let i = 0; i < count; i++) {
str += capitalLetters.charAt(
_getRandomNumber(0, capitalLetters.length - 1)
);
}
return str;
},
createSymbol: function(count) {
let specialLetters = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~',
str = '';
for (let i = 0; i < count; i++) {
str += specialLetters.charAt(
_getRandomNumber(0, specialLetters.length - 1)
);
}
return str;
}
};
function _generatePassword(rules, length) {
const count = Math.ceil(length / rules.length);
let str = '';
rules.forEach(function(rule) {
const method = `create${rule.charAt(0).toUpperCase()}${rule.slice(1)}`;
str += generator[method](count);
});
_mixup(str);
}
function onClickGenerateButton() {
const rules = [];
checkboxes.forEach(function(checkbox) {
if (checkbox.checked) {
rules.push(checkbox.value);
}
});
_generatePassword(rules, inputLength.value);
}
function _mixup(str, mixedStr = '') {
let arr = str.split('');
let index = _getRandomNumber(0, arr.length - 1);
if (arr.length) {
mixedStr += arr[index];
arr.splice(index, 1);
str = arr.join('');
_mixup(str, mixedStr);
} else {
renderPassword(mixedStr.slice(0, inputLength.value));
}
}
function renderPassword(str) {
textarea.value = str;
}
function copyPassword() {
textarea.select();
document.execCommand('copy');
}
textarea.addEventListener('change', function(event) {
if (event.target.value) {
}
});
| 24.548387 | 75 | 0.611914 |
b957913cab1e6b13fa0ee8af60ad8ade50396c3c | 7,397 | js | JavaScript | web/app/src/pages/Invite/index.js | kiteco/kiteco-public | 74aaf5b9b0592153b92f7ed982d65e15eea885e3 | [
"BSD-3-Clause"
] | 17 | 2022-01-10T11:01:50.000Z | 2022-03-25T03:21:08.000Z | web/app/src/pages/Invite/index.js | kiteco/kiteco-public | 74aaf5b9b0592153b92f7ed982d65e15eea885e3 | [
"BSD-3-Clause"
] | 1 | 2022-01-13T14:28:47.000Z | 2022-01-13T14:28:47.000Z | web/app/src/pages/Invite/index.js | kiteco/kiteco-public | 74aaf5b9b0592153b92f7ed982d65e15eea885e3 | [
"BSD-3-Clause"
] | 7 | 2022-01-07T03:58:10.000Z | 2022-03-24T07:38:20.000Z | import React from 'react'
import { connect } from 'react-redux'
import Helmet from 'react-helmet'
import queryString from 'query-string'
import ScrollToTop from '../../components/ScrollToTop'
import Header from '../../components/Header'
import TwitterLink from './components/TwitterLink'
import LinkCopy from './components/LinkCopy'
import MessageCopy from './components/MessageCopy'
import GmailImport from './components/GmailImport'
import * as account from '../../redux/actions/account'
import { Domains } from '../../utils/domains'
import {
wrapGoogleLoad,
initGoogle,
} from '../../utils/google'
import { track } from '../../utils/analytics'
import './assets/invite.css'
import coworkers from './assets/coworkers.svg'
class Invite extends React.Component {
constructor(props) {
super(props)
this.state = {
showGmailImport: false,
showSlackMessage: false,
showLinkCopy: false,
showTextCopy: false,
}
}
componentDidMount() {
initGoogle({ props: this.props })
const { tpt } = this.props
track({
event: "webapp: invite page loaded",
props: {
tpt,
},
})
}
componentDidUpdate(prevProps) {
initGoogle({ props: this.props, prevProps })
}
inviteFromGmailClicked = () => {
track({
event: "webapp: invite: invite from gmail clicked"
})
this.setState({ showGmailImport: true })
}
slackCoworkersClicked = () => {
track({
event: "webapp: invite: slack coworkers clicked"
})
this.setState({ showSlackMessage: true })
}
copyReferralLinkClicked = () => {
track({
event: "webapp: invite: copy referral link clicked"
})
this.setState({ showLinkCopy: true })
}
moreActionsClicked = () => {
track({
event: "webapp: invite: more actions clicked"
})
this.setState({ showTextCopy: true })
}
openSlack = () => {
window.open('https://slack.com/app_redirect?channel=random')
track({event: "webapp: invite: slack opened"})
}
render() {
const { showGmailImport, showLinkCopy, showSlackMessage, showTextCopy } = this.state
const { referralCode, email } = this.props
// This was used in the referral link CTA, which we've removed below
// const url = `${window.location.origin}/ref/${referralCode}`
return (
<div className="invite-wrapper">
<ScrollToTop/>
<Header className="header__dark invite-header" type="root" downloadButton={false} />
<div className="invite">
<Helmet>
<title>Invite friends and coworkers to Kite!</title>
</Helmet>
<h1 className="invite__tagline invite__appear">
Invite friends & coworkers!
</h1>
<img
className="invite__header-logo"
src={coworkers}
alt="Invite friends and coworkers"
/>
<div className="invite__options invite__appear">
<div className="invite-option gmail-option">
{ showGmailImport ?
<div className="invite__gmail__wrapper invite__code invite__appear">
<p className="invite__top-text">Invite from your Gmail</p>
<GmailImport email={email}/>
</div> :
<div className="invite__show-gmail__wrapper">
<button
className="invite__options__button"
onClick={this.inviteFromGmailClicked}
>
<div className="invite__options__gmail">
Invite from your Gmail
</div>
</button>
</div>
}
<p className='invite-option__bottom-text'>We never store your contacts</p>
</div>
<div className="invite-option">
{ showLinkCopy && referralCode &&
<div className="invite__code invite__appear">
<LinkCopy
referralCode={referralCode}
/>
</div>
}
<TwitterLink
onClick={() => track({ event: "webapp: invite: twitter clicked" })}
className="invite__options__button"
message={`Kite is the best autocompletions engine available for Python, powered by AI. Check it out — It's free! https://${Domains.PrimaryHost} @kitehq`}
>
<div className="invite__options__twitter">
Share on twitter
</div>
</TwitterLink>
</div>
<div className="invite-option">
{ showSlackMessage ?
<div className="invite__code invite__appear">
<p className="invite__top-text">Slack your coworkers</p>
<MessageCopy
className='slack__copy-message'
eventPlace='slack'
buttonText="Copy Message"
buttonTextCopied="Copied! Click Again to Open Slack."
onSecondClick={this.openSlack}
messageBlock={
<div>
Hey team! I've been using Kite, an AI-powered autocompletions engine for Python & JavaScript, to boost my productivity. You can get it for free at https://{Domains.PrimaryHost}.
<br/><br/>
Check it out in action!
https://giphy.com/gifs/python-kite-Y4c5RiOeUGfcX4mgee
</div>
}
messageValue={`Hey team! I've been using Kite, an AI-powered autocompletions engine for Python & JavaScript, to boost my productivity. You can get it for free at https://${Domains.PrimaryHost}.
Check it out in action!
https://giphy.com/gifs/python-kite-Y4c5RiOeUGfcX4mgee`}
/>
</div> :
<button
className="invite__options__button"
onClick={this.slackCoworkersClicked}
>
<div className="invite__options__slack">
Slack your coworkers
</div>
</button>
}
</div>
<div className="invite-option">
{showTextCopy ?
<div className="invite__code invite__appear">
<p className="invite__top-text">Share Kite</p>
<MessageCopy
eventPlace='share button'
buttonText="Copy Message"
buttonTextCopied="Message Copied - Share Kite Now!"
/>
</div> :
<div
onClick={this.moreActionsClicked}
className='invite__more-options'
>
More options
</div>
}
</div>
</div>
</div>
</div>
)
}
}
const mapStateToProps = (state, ownProps) => ({
tpt: queryString.parse(ownProps.location.search).tpt,
// TODO: Bring this back when the referral homepage works again
// referralCode: state.account.planDetails.referral_code,
})
const mapDispatchToProps = dispatch => ({
email: sub => dispatch(account.inviteEmails(sub)),
})
export default wrapGoogleLoad(connect(mapStateToProps, mapDispatchToProps)(Invite))
| 33.931193 | 213 | 0.556442 |
b95837c9a9f14e7863806fe7df4bebddf2edd604 | 72 | js | JavaScript | test/form/samples/empty-for-in-statement/_config.js | passcod/rollup | 7166d793f181f8476c7a7799189a1006bd576c7b | [
"MIT"
] | 23,201 | 2015-05-27T20:13:57.000Z | 2022-03-31T18:07:42.000Z | test/form/samples/empty-for-in-statement/_config.js | passcod/rollup | 7166d793f181f8476c7a7799189a1006bd576c7b | [
"MIT"
] | 3,981 | 2015-05-26T16:24:14.000Z | 2022-03-31T09:52:35.000Z | test/form/samples/empty-for-in-statement/_config.js | passcod/rollup | 7166d793f181f8476c7a7799189a1006bd576c7b | [
"MIT"
] | 1,557 | 2015-05-26T21:30:26.000Z | 2022-03-31T03:58:14.000Z | module.exports = {
description: 'removes an empty for-in statement'
};
| 18 | 49 | 0.722222 |
b95948333cb7c3840f6422daab2bcbc14144532f | 54 | js | JavaScript | packages/core/app/models/dashboard.js | Ruiqian1/navi | 2348ea4f6ff8c1683f597fdb83a25a5c3c3f65c2 | [
"MIT"
] | 59 | 2018-02-20T21:51:04.000Z | 2020-09-20T10:04:43.000Z | packages/core/app/models/dashboard.js | Ruiqian1/navi | 2348ea4f6ff8c1683f597fdb83a25a5c3c3f65c2 | [
"MIT"
] | 536 | 2018-02-19T21:38:07.000Z | 2020-12-14T18:01:40.000Z | packages/core/app/models/dashboard.js | Ruiqian1/navi | 2348ea4f6ff8c1683f597fdb83a25a5c3c3f65c2 | [
"MIT"
] | 35 | 2018-02-22T19:29:41.000Z | 2020-11-23T19:42:31.000Z | export { default } from 'navi-core/models/dashboard';
| 27 | 53 | 0.740741 |
b95961064df6d30bc71a1e40f0ebbcc7f841fe59 | 4,163 | js | JavaScript | src/views/Trades/Trade.js | nmgpradeep/admin | 5b07162f92f4628cb9aedbd068c1b1b1f25d22bd | [
"MIT"
] | null | null | null | src/views/Trades/Trade.js | nmgpradeep/admin | 5b07162f92f4628cb9aedbd068c1b1b1f25d22bd | [
"MIT"
] | null | null | null | src/views/Trades/Trade.js | nmgpradeep/admin | 5b07162f92f4628cb9aedbd068c1b1b1f25d22bd | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import { Link } from "react-router-dom";
import { Badge} from 'reactstrap';
import Moment from 'moment';
import axios from 'axios';
import { If, Then, ElseIf, Else } from 'react-if-elseif-else-render';
var FD = require('form-data');
var fs = require('fs');
// import PropTypes from 'prop-types';
class Trade extends Component {
constructor(props){
super(props)
this.state = {
tradeStatus :[],
conditionsShippingStatus :[]
};
}
toggle() {
this.setState({
modal: !this.state.modal
});
}
componentWillMount(){
axios.get('/trade/tradeStatus').then(result => {
this.setState({tradeStatus: result.data.result});
});
axios.get('/donation/getdonationshippingStatus').then(result => {
this.setState({conditionshippingStatus: result.data.result});
});
}
render() {
let tradeStatusOption;
if(this.state.tradeStatus){
let statusOption = this.state.tradeStatus;
tradeStatusOption = statusOption.map(v => (<option value={v.id}>{v.name}</option>));
}
let optionShippings;
if(this.state.conditionshippingStatus){
let conditionsShippings = this.state.conditionshippingStatus;
optionShippings = conditionsShippings.map(v => (<option value={v.id}>{v.name}</option>));
}
return (
<tr key={this.props.trade._id}>
<td>{this.props.sequenceNo + 1} </td>
<td>{(this.props.trade.offerTradeId && this.props.trade.offerTradeId.pitchUserId)?this.props.trade.offerTradeId.pitchUserId.firstName:''}</td>
<td>{(this.props.trade.offerTradeId && this.props.trade.tradePitchProductId)?this.props.trade.tradePitchProductId.productName:''}</td>
<td>{(this.props.trade.offerTradeId && this.props.trade.offerTradeId.SwitchUserId)?this.props.trade.offerTradeId.SwitchUserId.firstName:''}</td>
<td>{(this.props.trade.offerTradeId && this.props.trade.tradeSwitchProductId)?this.props.trade.tradeSwitchProductId.productName:''}</td>
<td>{ Moment(this.props.trade.createdAt).format('d MMM YYYY')} </td>
<td>
{/* <Badge color={(this.props.trade.status == '1')?'success':'danger'}>
<If condition={this.props.trade.status == '1'}>
<Then>Switch
</Then>
<ElseIf condition={this.props.trade.status === '2'}>
Completed
</ElseIf>
<Else>
Rejected
</Else>
</If>
</Badge>
{' '}
<Badge onClick={this.props.returnRaised.bind(this, this.props.trade)} color={(this.props.trade.Status == '1')?'success':'danger'}>
<If condition={this.props.trade.Status === '0'}>
<Then>{' '}</Then>
<ElseIf condition={this.props.trade.Status === '1'}>
<If condition={this.props.trade.sendReturnStatus ==='1'}>
<Then>
Returned
</Then>
<Else>
Return
</Else>
</If>
</ElseIf>
<Else>
Rejected
</Else>
</If>
</Badge> */}
<select id="select"
innerRef={input => (this.shippingStatus = input)}
className="dropdown-toggle btn btn-info"
onChange={(e) => this.props.changeShippingStatus(e, this.props.trade._id)}
value={this.props.trade.shippingStatus}>
{optionShippings}
</select>
</td>
<td>
<select id="select"
innerRef={input => (this.tradeStatus = input)}
className="dropdown-toggle btn btn-info"
onChange={(e) => this.props.returnRaised(e, this.props.trade._id)}
value={this.props.trade.status}
disabled={this.props.trade.shippingStatus !== "4"}>
{tradeStatusOption}
</select>
</td>
<td>
<Link to={'/trades/view/' + this.props.trade._id}><i className="fa fa-eye fa-md"></i> </Link>
</td>
</tr>
);
}
}
// ProjectItem.propTypes = {
// project: PropTypes.object
// };
export default Trade;
| 34.404959 | 152 | 0.575066 |
b95a297a5761593b7df03223bb846598dfcf7386 | 155 | js | JavaScript | resources/js/config/axios.js | oolivos/catalogo-productos | a357201d4d1234ab9345a6ef63d71238e23baac8 | [
"MIT"
] | null | null | null | resources/js/config/axios.js | oolivos/catalogo-productos | a357201d4d1234ab9345a6ef63d71238e23baac8 | [
"MIT"
] | null | null | null | resources/js/config/axios.js | oolivos/catalogo-productos | a357201d4d1234ab9345a6ef63d71238e23baac8 | [
"MIT"
] | null | null | null | import Vue from 'vue'
import axios from 'axios'
axios.defaults.baseURL = window.location.origin + '/api/'
Vue.prototype.$http = axios
export default axios
| 25.833333 | 57 | 0.76129 |
b95c6363409124e4e1da82d4ae53304cda6e1f8d | 3,156 | js | JavaScript | js/foursquare.js | pursaa/cipher | 17b7926fa98cab2bec915a1da54fc654d0296c41 | [
"MIT"
] | 1 | 2021-02-10T17:33:36.000Z | 2021-02-10T17:33:36.000Z | js/foursquare.js | langlk/substitution-ciphers | 3d0555070da7d7b38053bace6a85a35172886612 | [
"MIT"
] | null | null | null | js/foursquare.js | langlk/substitution-ciphers | 3d0555070da7d7b38053bace6a85a35172886612 | [
"MIT"
] | null | null | null | function FourSquare(key1, key2) {
if (this.checkKey(key1) || this.checkKey(key2)) {
this.error = "Error: Invalid Key";
} else {
this.key1 = this.makeKey(key1);
this.key2 = this.makeKey(key2);
this.alphabet = this.makeKey("");
}
}
FourSquare.prototype.checkKey = function(key) {
if(/[^a-z]/.test(key)) {
return "Error: Invalid Key";
}
}
FourSquare.prototype.makeKey = function(key) {
var result = "";
var keyArray = key.toLowerCase().split("");
keyArray.forEach(function(letter) {
if (/[a-pr-z]/.test(letter)) {
if (!result.includes(letter)) {
result += letter;
}
}
});
for (var i = 97; i < 123; i++) {
var letter = String.fromCharCode(i);
if (!result.includes(letter) && letter !== "q") {
result += letter;
}
}
keySquare = this.makeSquare(result);
return keySquare;
}
FourSquare.prototype.makeSquare = function(string) {
var square = [[], [], [], [], []];
var counter = 0;
for (var i = 0; i < 25; i++) {
square[counter].push(string.charAt(i));
counter += 1;
if (counter >= 5) {
counter = 0;
}
}
return square;
}
FourSquare.prototype.getCoordinates = function(character, keysquare) {
var coordinates = [];
for (var i = 0; i < 5; i++) {
var index = keysquare[i].indexOf(character);
if (index > -1) {
coordinates = [i, index];
}
}
return coordinates;
}
FourSquare.prototype.encode = function(message) {
message = message.toLowerCase().replace(/[^a-pr-z]/g, "");
if (message.length % 2 !== 0) {
message = message + "x";
}
var messageArray = message.split("");
var result = "";
for (var i = 0; i < messageArray.length; i += 2) {
var coordinate1 = this.getCoordinates(messageArray[i], this.alphabet);
var coordinate2 = this.getCoordinates(messageArray[i+1], this.alphabet);
var code1 = this.key1[coordinate2[0]][coordinate1[1]];
var code2 = this.key2[coordinate1[0]][coordinate2[1]];
result += code1 + code2;
}
return result;
}
FourSquare.prototype.decode = function(message) {
message = message.toLowerCase();
if (message.match(/[^a-pr-z]/) || message.length % 2 !== 0) {
return "Invalid Ciphertext";
} else {
var messageArray = message.split("");
var result = "";
for (var i = 0; i < message.length; i += 2) {
var coordinate1 = this.getCoordinates(messageArray[i], this.key1);
var coordinate2 = this.getCoordinates(messageArray[i+1], this.key2);
var letter1 = this.alphabet[coordinate2[0]][coordinate1[1]];
var letter2 = this.alphabet[coordinate1[0]][coordinate2[1]];
result += letter1 + letter2;
}
return result;
}
}
function encodeFourSquare(key1, key2, message) {
var cipher = new FourSquare(key1, key2);
if (cipher.error === "Error: Invalid Key") {
return cipher.error;
} else {
var result = cipher.encode(message);
return result;
}
}
function decodeFourSquare(key1, key2, message) {
var cipher = new FourSquare(key1, key2);
if (cipher.error === "Error: Invalid Key") {
return cipher.error;
} else {
var result = cipher.decode(message);
return result;
}
}
| 27.443478 | 76 | 0.615019 |
b95cb63de227c430266a976d600009f2a4d3d3e0 | 3,342 | js | JavaScript | qle/search/enumvalues_5.js | rkapl123/OREAnnotatedSource | 71816f923c64c0b37af660736c5e4a3cd091f3d4 | [
"MIT"
] | 1 | 2021-11-14T14:45:29.000Z | 2021-11-14T14:45:29.000Z | qle/search/enumvalues_5.js | rkapl123/OREAnnotatedSource | 71816f923c64c0b37af660736c5e4a3cd091f3d4 | [
"MIT"
] | null | null | null | qle/search/enumvalues_5.js | rkapl123/OREAnnotatedSource | 71816f923c64c0b37af660736c5e4a3cd091f3d4 | [
"MIT"
] | null | null | null | var searchData=
[
['financialcubic_8329',['FinancialCubic',['../class_quant_ext_1_1_interpolated_smile_section.html#aa0081e804011c551ea0f4a596a64b284a4644397bf6d81d548c63fb5d2517ea78',1,'QuantExt::InterpolatedSmileSection']]],
['flat_8330',['Flat',['../class_quant_ext_1_1_black_variance_surface_sparse.html#adaa6b40627fb4b52f124405f219e18c6a745e3db6a7ffd50e1a72b39482f0882d',1,'QuantExt::BlackVarianceSurfaceSparse']]],
['flatfwd_8331',['flatFwd',['../class_quant_ext_1_1_interpolated_discount_curve.html#a8e2df513f6590afb6c85a22a458745c5a789a161003c226bb123d8a5dbe47eae7',1,'QuantExt::InterpolatedDiscountCurve::flatFwd()'],['../class_quant_ext_1_1_interpolated_discount_curve2.html#a8e2df513f6590afb6c85a22a458745c5a789a161003c226bb123d8a5dbe47eae7',1,'QuantExt::InterpolatedDiscountCurve2::flatFwd()'],['../class_quant_ext_1_1_spreaded_discount_curve.html#a8e2df513f6590afb6c85a22a458745c5a789a161003c226bb123d8a5dbe47eae7',1,'QuantExt::SpreadedDiscountCurve::flatFwd()']]],
['flatzero_8332',['flatZero',['../class_quant_ext_1_1_interpolated_discount_curve.html#a8e2df513f6590afb6c85a22a458745c5a1a222221219e39220fcbbd80a934c13c',1,'QuantExt::InterpolatedDiscountCurve::flatZero()'],['../class_quant_ext_1_1_interpolated_discount_curve2.html#a8e2df513f6590afb6c85a22a458745c5a1a222221219e39220fcbbd80a934c13c',1,'QuantExt::InterpolatedDiscountCurve2::flatZero()'],['../class_quant_ext_1_1_spreaded_discount_curve.html#a8e2df513f6590afb6c85a22a458745c5a1a222221219e39220fcbbd80a934c13c',1,'QuantExt::SpreadedDiscountCurve::flatZero()']]],
['floor_8333',['Floor',['../class_quant_ext_1_1_cap_floor_helper.html#a1d1cfd8ffb84e947f82999c682b666a7a94e95e4b8360855608dfad0b1f43a301',1,'QuantExt::CapFloorHelper::Floor()'],['../namespace_quant_ext.html#a4b5ced842f614fe2ff1f799d28c2509fa94e95e4b8360855608dfad0b1f43a301',1,'QuantExt::Floor()']]],
['forwardforward_8334',['ForwardForward',['../group__termstructures.html#gga3d14939b6009218bf529700f2a9a9a54a13fa980fdfc850c599785a6470414f33',1,'QuantExt']]],
['forwardforwardvariance_8335',['ForwardForwardVariance',['../group__termstructures.html#ggab34c882cbe4ad41fff0faecff9a280f8af56d722a00735017873ac40e2d6605e8',1,'QuantExt']]],
['futureseu_8336',['FuturesEU',['../class_quant_ext_1_1_i_c_e.html#abe41cfffd960e29a5d8b07be00aeda42a11767a57ab6cffea5552ed924ca77ddf',1,'QuantExt::ICE']]],
['futureseu_5f1_8337',['FuturesEU_1',['../class_quant_ext_1_1_i_c_e.html#abe41cfffd960e29a5d8b07be00aeda42a0b9946b822a5f64db9cf697aeba2bd56',1,'QuantExt::ICE']]],
['futuressingapore_8338',['FuturesSingapore',['../class_quant_ext_1_1_i_c_e.html#abe41cfffd960e29a5d8b07be00aeda42a248ddc88afd7a09f391f45d495e0a3f1',1,'QuantExt::ICE']]],
['futuresus_8339',['FuturesUS',['../class_quant_ext_1_1_i_c_e.html#abe41cfffd960e29a5d8b07be00aeda42a66dcf192b1777b9351c5b63b03421d17',1,'QuantExt::ICE']]],
['futuresus_5f1_8340',['FuturesUS_1',['../class_quant_ext_1_1_i_c_e.html#abe41cfffd960e29a5d8b07be00aeda42a5fbfcf55924accba82329e54e3191128',1,'QuantExt::ICE']]],
['futuresus_5f2_8341',['FuturesUS_2',['../class_quant_ext_1_1_i_c_e.html#abe41cfffd960e29a5d8b07be00aeda42a23d15ebdca140872b9de61218371bd12',1,'QuantExt::ICE']]],
['fx_8342',['FX',['../group__crossassetmodel.html#gga72d924d1cb8e1544b6d5198e98d52ca9a48b424735b6e21a4a4fe044feaee5a50',1,'QuantExt::CrossAssetModelTypes']]]
];
| 185.666667 | 564 | 0.844704 |
b95cfbe30e71b3a44f3ec16bccbf7fed9b380cbd | 934 | js | JavaScript | script.js | mytechthingz/vftvk-Simple-Interest-Calculator | 0576f50e55376d440fb6b1c419b3ee687d3f5bd9 | [
"Apache-2.0"
] | null | null | null | script.js | mytechthingz/vftvk-Simple-Interest-Calculator | 0576f50e55376d440fb6b1c419b3ee687d3f5bd9 | [
"Apache-2.0"
] | null | null | null | script.js | mytechthingz/vftvk-Simple-Interest-Calculator | 0576f50e55376d440fb6b1c419b3ee687d3f5bd9 | [
"Apache-2.0"
] | null | null | null | function compute()
{
let principal = document.getElementById("principal").value;
let rate = document.getElementById("rate").value;
let years = document.getElementById("years").value;
let interest = ((principal * rate * years) /100);
let total = parseInt(principal) + interest;
let date = new Date().getFullYear() + parseInt(years);
document.getElementById("result").innerHTML = `If you deposit <mark>${principal}</mark>,<br> at an interest rate of <mark>${rate}%</mark>.<br>You will receive an amount of <mark>${total}</mark>,<br>in the year <mark>${date}</mark>`;
console.log(`${rate} ${principal} ${years}`)
}
function updateRate(){
document.getElementById("rate_val").innerHTML = document.getElementById("rate").value;
}
function principalCheck(){
let principal = document.getElementById("principal").value;
if(principal <=0 ){
alert("Enter a positive number");
}
} | 42.454545 | 236 | 0.671306 |
b95e238c96271e473eaaa4e8510b3950cc0bc045 | 1,446 | js | JavaScript | src/components/menu.js | juliescript/gatsby-blog | dbd91fe5191efe2a6465496b23ebe038a0fc8d80 | [
"MIT"
] | null | null | null | src/components/menu.js | juliescript/gatsby-blog | dbd91fe5191efe2a6465496b23ebe038a0fc8d80 | [
"MIT"
] | 6 | 2021-06-28T20:31:09.000Z | 2022-02-27T10:51:53.000Z | src/components/menu.js | juliescript/gatsby-blog | dbd91fe5191efe2a6465496b23ebe038a0fc8d80 | [
"MIT"
] | null | null | null | import React from "react"
import { useStaticQuery, graphql, Link } from "gatsby"
import "./menu.scss"
const Menu = () => {
const data = useStaticQuery(graphql`
query MenuQuery {
site {
siteMetadata {
social {
twitter
instagram
github
}
}
}
}
`)
const { social } = data.site.siteMetadata
return (
<nav className="menu">
<ul className="menu__site-navigation">
<li>
<Link to="about">sobre mí</Link>
</li>
</ul>
<ul className="menu__social-media">
<li>
<a
target="_blank"
rel="noopener noreferrer"
className="menu__social-media--instagram"
href={`https://instagram.com/${social.instagram}`}
>
Instagram
</a>
</li>
<li>
<a
target="_blank"
rel="noopener noreferrer"
className="menu__social-media--twitter"
href={`https://twitter.com/${social.instagram}`}
>
Twitter
</a>
</li>
<li>
<a
target="_blank"
rel="noopener noreferrer"
className="menu__social-media--github"
href={`https://github.com/${social.instagram}`}
>
Github
</a>
</li>
</ul>
</nav>
)
}
export default Menu
| 21.909091 | 62 | 0.467497 |
b95e7cd23c86d3e938fc167a92d636df575f0983 | 1,277 | js | JavaScript | complete-practice/src/components/NewUser/UserForm.js | kryshenp/react-advanced-course | a31ac8df65c56732c728bcf7966785af05bb6fa3 | [
"MIT"
] | null | null | null | complete-practice/src/components/NewUser/UserForm.js | kryshenp/react-advanced-course | a31ac8df65c56732c728bcf7966785af05bb6fa3 | [
"MIT"
] | null | null | null | complete-practice/src/components/NewUser/UserForm.js | kryshenp/react-advanced-course | a31ac8df65c56732c728bcf7966785af05bb6fa3 | [
"MIT"
] | null | null | null | import React, { useState } from "react";
import Button from "../UI/Button";
import "./UserForm.css";
const UserForm = (props) => {
const [enteredName, setEnteredName] = useState("");
const [enteredAge, setEnteredAge] = useState("");
const userNameChangeHandler = (event) => {
setEnteredName(event.target.value);
};
const userAgeChangeHandler = (event) => {
setEnteredAge(event.target.value);
};
const submitHandler = (event) => {
event.preventDefault();
const userData = {
name: enteredName,
age: enteredAge,
};
props.onSaveUserData(userData);
setEnteredName("");
setEnteredAge("");
};
return (
<form onSubmit={submitHandler}>
<div className="new-user__controls">
<div className="new-user__control">
<label>Username</label>
<input type="text" onChange={userNameChangeHandler} value={enteredName} />
</div>
<div className="new-user__control">
<label>Age (years)</label>
<input type="number" step="1" onChange={userAgeChangeHandler} value={enteredAge} />
</div>
</div>
<div className="new-user__actions">
<Button label="Add User" type="submit" />
</div>
</form>
);
};
export default UserForm;
| 24.557692 | 93 | 0.613939 |
b95e9014381d852452ed19e919d590a6f902a886 | 7,666 | js | JavaScript | modules/users/server/controllers/users/users.profile.server.controller.js | eliavmaman/noti888 | 8fe5adce1841ec5c9c891d46caf92bcb4f48bdb5 | [
"MIT"
] | null | null | null | modules/users/server/controllers/users/users.profile.server.controller.js | eliavmaman/noti888 | 8fe5adce1841ec5c9c891d46caf92bcb4f48bdb5 | [
"MIT"
] | null | null | null | modules/users/server/controllers/users/users.profile.server.controller.js | eliavmaman/noti888 | 8fe5adce1841ec5c9c891d46caf92bcb4f48bdb5 | [
"MIT"
] | null | null | null | 'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
mongoose = require('mongoose'),
multer = require('multer'),
config = require(path.resolve('./config/config')),
User = mongoose.model('User');
/**
* Update user details
*/
exports.update = function (req, res) {
// Init Variables
var user = req.user;
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
if (user) {
// Merge existing user
user = _.extend(user, req.body);
user.updated = Date.now();
user.displayName = user.firstName + ' ' + user.lastName;
user.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function (err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
} else {
res.status(400).send({
message: 'User is not signed in'
});
}
};
/**
* Update profile picture
*/
exports.changeProfilePicture = function (req, res) {
var user = req.user;
var message = null;
var upload = multer(config.uploads.profileUpload).single('newProfilePicture');
var profileUploadFileFilter = require(path.resolve('./config/lib/multer')).profileUploadFileFilter;
// Filtering to upload only images
upload.fileFilter = profileUploadFileFilter;
if (user) {
upload(req, res, function (uploadError) {
if (uploadError) {
return res.status(400).send({
message: 'Error occurred while uploading profile picture'
});
} else {
user.profileImageURL = config.uploads.profileUpload.dest + req.file.filename;
user.save(function (saveError) {
if (saveError) {
return res.status(400).send({
message: errorHandler.getErrorMessage(saveError)
});
} else {
req.login(user, function (err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
}
});
} else {
res.status(400).send({
message: 'User is not signed in'
});
}
};
/**
* Send User
*/
exports.me = function (req, res) {
res.json(req.user || null);
};
exports.addTag = function (req, res) {
var tagId = req.body.tagId;
var tagName = req.body.tagName;
var category = req.body.category;
var email = req.body.email;
var exist_user = req.user;
console.log('EMAIL -' + email);
console.log('tagId -' + tagId + ' tagna- ' + tagName + ' category- ' + category);
return User.findOne({
email: email
}, function (err, user) {
if (err) {
return done(err);
}
//if (!user || !user.authenticate(password)) {
// return done(null, false, {
// message: 'Invalid username or password'
// });
//}
user.tags.push({
_id: tagId,
name: tagName,
category: category,
});
user.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function (err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user.tags);
}
});
}
});
});
// res.json(req.user || null);
};
exports.removeTag = function (req, res) {
var tagId = req.params.tagId;
var email = req.query.email;
//var exist_user = req.user;
console.log('USERID -' + email._id);
console.log('tagId -' + tagId);
return User.findOne({
email: email
}, function (err, user) {
if (err) {
return done(err);
}
var tags = [];
user.tags.forEach(function (t) {
if (t._id.toString() !== tagId.toString()) {
tags.push(t);
}
});
user.tags = tags;
user.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function (err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user.tags);
}
});
}
});
});
// res.json(req.user || null);
};
exports.setToken = function (req, res) {
var token = req.body.token;
var email = req.body.email;
console.log('Token -----------' + token);
console.log('EMAIL -----------' + email);
return User.findOne({
username: email
}, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
var u = {};
u.username = req.body.email;
u.firstName = req.body.email;
u.lastName = req.body.email;
u.password = 'qwe123';
u.email = req.body.email;
u.token = token;
console.log('AFTER-----------------' + JSON.stringify(u));
var user = new User(u);
var message = null;
// Add missing user fields
user.provider = 'local';
user.displayName = user.firstName + ' ' + user.lastName;
// Then save the user
user.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function (err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
} else {
user.token = token;
user.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function (err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user.token);
}
});
}
});
}
});
// res.json(req.user || null);
};
| 28.392593 | 103 | 0.430342 |
b95f018fd4c9d71909c011b9e7f6c35a93f6a98d | 1,529 | js | JavaScript | .cz.js | b-zurg/electron-forge | 8b4e0cf8f96206aabc2c4b85c29cd97a1fc3d7fe | [
"MIT"
] | 2 | 2022-01-27T20:51:30.000Z | 2022-01-31T03:19:50.000Z | .cz.js | DustinBrett/electron-forge | b2b8c6de6c8e09e46908ff288b340cc95c3462a0 | [
"MIT"
] | 233 | 2020-12-18T11:32:16.000Z | 2022-03-31T06:12:30.000Z | .cz.js | DustinBrett/electron-forge | b2b8c6de6c8e09e46908ff288b340cc95c3462a0 | [
"MIT"
] | 1 | 2022-02-06T06:08:35.000Z | 2022-02-06T06:08:35.000Z | const fs = require('fs');
const path = require('path');
const BASE_DIR = __dirname;
const PACKAGES_DIR = path.resolve(BASE_DIR, 'packages');
const packages = [];
for (const subDir of fs.readdirSync(PACKAGES_DIR)) {
for (const packageDir of fs.readdirSync(path.resolve(PACKAGES_DIR, subDir))) {
const pj = JSON.parse(fs.readFileSync(path.resolve(PACKAGES_DIR, subDir, packageDir, 'package.json')));
const name = pj.name.substr('@electron-forge/'.length);
packages.push(name);
}
}
module.exports = {
types: [
{value: 'feat', name: 'feat: A new feature'},
{value: 'fix', name: 'fix: A bug fix'},
{value: 'docs', name: 'docs: Documentation only changes'},
{value: 'style', name: 'style: Changes that do not affect the meaning of the code\n (white-space, formatting, missing semi-colons, etc)'},
{value: 'refactor', name: 'refactor: A code change that neither fixes a bug nor adds a feature'},
{value: 'perf', name: 'perf: A code change that improves performance'},
{value: 'test', name: 'test: Adding missing tests'},
{value: 'chore', name: 'chore: Changes to the build process or auxiliary tools\n and libraries such as documentation generation'},
{value: 'revert', name: 'revert: Revert to a commit'},
{value: 'WIP', name: 'WIP: Work in progress'},
],
scopes: packages.map(package => ({ name: package })),
allowCustomScopes: true,
allowBreakingChanges: ['feat', 'fix'],
}
| 46.333333 | 159 | 0.634402 |
b95f8171dbdbcf417b9599693a7e0484e8736d5f | 1,458 | js | JavaScript | server/mysql/idea.js | alex123bob/GoldenIdea | 66b91c5bafc7740199cc9bbf3c95d050b6eb82ff | [
"MIT"
] | null | null | null | server/mysql/idea.js | alex123bob/GoldenIdea | 66b91c5bafc7740199cc9bbf3c95d050b6eb82ff | [
"MIT"
] | null | null | null | server/mysql/idea.js | alex123bob/GoldenIdea | 66b91c5bafc7740199cc9bbf3c95d050b6eb82ff | [
"MIT"
] | null | null | null | const conn = require('./conn');
const Q = require('Q');
const dateFormat = require('dateformat');
module.exports = (action) => {
const deferred = Q.defer();
const params = action.params;
switch (action.type) {
case 'add':
let fields = [];
let values = [];
for (const key in params) {
if (params.hasOwnProperty(key)) {
let val = params[key];
fields.push('`' + key + '`');
val = "'" + val.replace(/'/g, "\\'") + "'";
values.push(val);
}
}
fields = fields.join(', ');
values = values.join(', ');
conn.query(
'insert into `ideas` (' + fields + ') values(' + values + ')',
(err, rows, fields) => {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(rows);
}
}
);
break;
case 'get':
let sql;
if (params.type === 'latest') {
sql = 'select * from `ideas` where `isDeleted` = \'false\' limit 0, 10 ';
} else {
sql = 'select * from `ideas` where `isDeleted` = \'false\' and `type` = \'' + params.type + '\' ';
}
conn.query(sql, (err, rows, fields) => {
const recs = rows.map((rec) => {
rec.createTime = dateFormat(rec.createTime, 'yyyy-mm-dd HH:MM:ss');
return rec;
});
if (err) {
deferred.reject(err);
} else {
deferred.resolve(recs);
}
});
break;
default:
break;
}
return deferred.promise;
};
| 25.578947 | 104 | 0.496571 |
b9607a057c4f5c04d4958ab3c904f5b22ac84454 | 2,647 | js | JavaScript | aspnet-core/src/Snow.Template.Web.Mvc/wwwroot/view-resources/Views/Users/Index.min.js | snowchenlei/AbpCustomerAuth | 5d2cda561f041bb5115353b1fb07fa6f3dd4f280 | [
"MIT"
] | null | null | null | aspnet-core/src/Snow.Template.Web.Mvc/wwwroot/view-resources/Views/Users/Index.min.js | snowchenlei/AbpCustomerAuth | 5d2cda561f041bb5115353b1fb07fa6f3dd4f280 | [
"MIT"
] | null | null | null | aspnet-core/src/Snow.Template.Web.Mvc/wwwroot/view-resources/Views/Users/Index.min.js | snowchenlei/AbpCustomerAuth | 5d2cda561f041bb5115353b1fb07fa6f3dd4f280 | [
"MIT"
] | null | null | null | function queryParams(n){return{maxResultCount:n.limit,skipCount:n.offset}}(function(){function u(){var n=[];return n.push('<div class="btn-group" role="group" aria-label="Row Operation">'),abp.auth.isGranted("Pages.Administration.Users.Edit")&&n.push('<button type="button" class="btn btn-sm btn-warning edit" title="'+app.localize("Edit")+'"><i class="fas fa-edit"><\/i>'+app.localize("Edit")+"<\/button>"),abp.auth.isGranted("Pages.Administration.Users.Delete")&&n.push('<button type="button" class="btn btn-sm btn-danger remove" title="'+app.localize("Delete")+'"><i class="fas fa-trash"><\/i>'+app.localize("Delete")+"<\/button>"),n.push("<\/div>"),n.join("")}function f(){var f,o,i,r,u,s;if(abp.ui.setBusy(n),f=$("#modelForm"),!f.valid())return abp.ui.clearBusy(n),!1;if(o=e(),i=f.serializeFormToObject(),i.SetRandomPassword&&(i.Password=null),r=$("input[name='role']:checked"),r)for(u=0;u<r.length;u++)s=$(r[u]),i.roleNames.push(s.val());t.createOrUpdate({user:i,assignedRoleNames:o}).done(function(){abp.notify.info(app.localize("SavedSuccessfully"));n.modal("hide");refreshTable()}).always(function(){abp.ui.clearBusy(n)})}function e(){var t=[];return n.find(".user-role-checkbox-list input[type=checkbox]").each(function(){$(this).is(":checked")&&t.push($(this).attr("name"))}),t}function r(t,i){n=bootbox.dialog({title:t,message:'<p><i class="fa fa-spin fa-spinner"><\/i> '+app.localize("Loading")+"<\/p>",size:"large",buttons:{cancel:{label:app.localize("Cancel"),className:"btn-danger"},confirm:{label:app.localize("OK"),className:"btn-success",callback:function(n){if(n)return f(),!1}}}});n.init(function(){$.get(abp.appPath+"users/createOrEditModal",{id:i},function(t){n.find(".bootbox-body").html(t);n.find("input:not([type=hidden]):first").focus()})})}var t=abp.services.app.user,n,i;window.operateEvents={"click .edit":function(n,t,i){n.preventDefault();r(app.localize("EditUser",i.name),i.id)},"click .remove":function(n,i,r){bootbox.confirm({size:"small",title:app.localize("Delete"),message:abp.utils.formatString(abp.localization.localize("AreYouSureWantToDelete","Template"),r.name),callback:function(n){n&&t.delete({id:r.id}).done(function(){var n=$("#tb-body");n.bootstrapTable("remove",{field:"id",values:[r.id]})})}})}};i=[{checkbox:!0},{field:"id",title:"Id",visible:!1},{field:"userName",title:app.localize("UserName")},{field:"name",title:app.localize("Name")},{field:"emailAddress",title:app.localize("EmailAddress")},{title:app.localize("Operation"),formatter:u,events:operateEvents}];$(function(){table.init("api/services/app/user/getPaged",i);$("#create").click(function(){r(app.localize("CreateNewUser"))})})})(); | 2,647 | 2,647 | 0.700038 |
b9610481b28522ad71a156175ace39f4bc864035 | 229 | js | JavaScript | POPBOOK/assets/js/ex.js | Ehimeh/POPBOOK | 048089c581adadd4a6fd847cf00a424159f1f86c | [
"Apache-2.0"
] | null | null | null | POPBOOK/assets/js/ex.js | Ehimeh/POPBOOK | 048089c581adadd4a6fd847cf00a424159f1f86c | [
"Apache-2.0"
] | null | null | null | POPBOOK/assets/js/ex.js | Ehimeh/POPBOOK | 048089c581adadd4a6fd847cf00a424159f1f86c | [
"Apache-2.0"
] | null | null | null | // Number(prompt('input number'))
// Number(prompt('input number'))
// var number= num1 + num2
var firstNumber = Number(prompt("input firstnumber"));
var secondNumber = Number(prompt("input secondnumber"));
var answer | 25.444444 | 57 | 0.689956 |
b9648f899231d7ccd64299ce5f5edc673cf9e6e4 | 604 | js | JavaScript | packages/utils/array-utils/src/insertSorted.test.js | heristhesiya/OpenJSCAD.org | 4b8cbecd826a3e37d93009e624b75b75ae19feb0 | [
"MIT"
] | 1,435 | 2017-05-09T01:51:20.000Z | 2022-03-31T12:35:31.000Z | packages/utils/array-utils/src/insertSorted.test.js | heristhesiya/OpenJSCAD.org | 4b8cbecd826a3e37d93009e624b75b75ae19feb0 | [
"MIT"
] | 634 | 2017-05-07T11:32:09.000Z | 2022-03-30T22:44:27.000Z | packages/utils/array-utils/src/insertSorted.test.js | heristhesiya/OpenJSCAD.org | 4b8cbecd826a3e37d93009e624b75b75ae19feb0 | [
"MIT"
] | 313 | 2017-05-09T21:42:26.000Z | 2022-03-31T16:37:23.000Z | const test = require('ava')
const { fnNumberSort, insertSorted } = require('./index')
test('array-utils: insertSorted() should insert elements properly', (t) => {
const numbers = []
const result = insertSorted(numbers, 3, fnNumberSort)
t.is(result, numbers)
t.deepEqual(numbers, [3])
insertSorted(numbers, 1, fnNumberSort)
t.deepEqual(numbers, [1, 3])
insertSorted(numbers, 5, fnNumberSort)
t.deepEqual(numbers, [1, 3, 5])
insertSorted(numbers, 2, fnNumberSort)
t.deepEqual(numbers, [1, 2, 3, 5])
insertSorted(numbers, 4, fnNumberSort)
t.deepEqual(numbers, [1, 2, 3, 4, 5])
})
| 30.2 | 76 | 0.68543 |
b964f1e61110d32e5070b6135f1c0a39c8f7360f | 2,729 | js | JavaScript | packages/vega-time/test/util-test.js | yuicer/vega | 83e5bb53f12527c4732b755bb49482283634fade | [
"BSD-3-Clause"
] | 1 | 2020-04-28T08:15:30.000Z | 2020-04-28T08:15:30.000Z | packages/vega-time/test/util-test.js | yuicer/vega | 83e5bb53f12527c4732b755bb49482283634fade | [
"BSD-3-Clause"
] | null | null | null | packages/vega-time/test/util-test.js | yuicer/vega | 83e5bb53f12527c4732b755bb49482283634fade | [
"BSD-3-Clause"
] | 1 | 2021-07-30T15:01:48.000Z | 2021-07-30T15:01:48.000Z | var tape = require('tape'),
vega = require('../'),
{local, utc} = require('./util');
tape('dayofyear extracts day of year from datetime', function(t) {
t.equal(vega.dayofyear(local(2012, 0, 1)), 1);
t.equal(vega.dayofyear(local(2012, 11, 31)), 366);
t.equal(vega.dayofyear(local(2011, 0, 1)), 1);
t.equal(vega.dayofyear(local(2011, 11, 31)), 365);
t.end();
});
tape('dayofyear extracts day of year from timestamp', function(t) {
t.equal(vega.dayofyear(+local(2012, 0, 1)), 1);
t.equal(vega.dayofyear(+local(2012, 11, 31)), 366);
t.equal(vega.dayofyear(+local(2011, 0, 1)), 1);
t.equal(vega.dayofyear(+local(2011, 11, 31)), 365);
t.end();
});
tape('week extracts week number of year from datetime', function(t) {
t.equal(vega.week(local(2012, 0, 1)), 1);
t.equal(vega.week(local(2012, 0, 8)), 2);
t.equal(vega.week(local(2012, 11, 31)), 53);
t.equal(vega.week(local(2011, 0, 1)), 0);
t.equal(vega.week(local(2011, 0, 8)), 1);
t.equal(vega.week(local(2011, 11, 31)), 52);
t.end();
});
tape('week extracts week number of year from timestamp', function(t) {
t.equal(vega.week(+local(2012, 0, 1)), 1);
t.equal(vega.week(+local(2012, 0, 8)), 2);
t.equal(vega.week(+local(2012, 11, 31)), 53);
t.equal(vega.week(+local(2011, 0, 1)), 0);
t.equal(vega.week(+local(2011, 0, 8)), 1);
t.equal(vega.week(+local(2011, 11, 31)), 52);
t.end();
});
tape('utcdayofyear extracts day of year from utc datetime', function(t) {
t.equal(vega.utcdayofyear(utc(2012, 0, 1)), 1);
t.equal(vega.utcdayofyear(utc(2012, 11, 31)), 366);
t.equal(vega.utcdayofyear(utc(2011, 0, 1)), 1);
t.equal(vega.utcdayofyear(utc(2011, 11, 31)), 365);
t.end();
});
tape('utcdayofyear extracts day of year from timestamp', function(t) {
t.equal(vega.utcdayofyear(+utc(2012, 0, 1)), 1);
t.equal(vega.utcdayofyear(+utc(2012, 11, 31)), 366);
t.equal(vega.utcdayofyear(+utc(2011, 0, 1)), 1);
t.equal(vega.utcdayofyear(+utc(2011, 11, 31)), 365);
t.end();
});
tape('utcweek extracts week number of year from utc datetime', function(t) {
t.equal(vega.utcweek(utc(2012, 0, 1)), 1);
t.equal(vega.utcweek(utc(2012, 0, 8)), 2);
t.equal(vega.utcweek(utc(2012, 11, 31)), 53);
t.equal(vega.utcweek(utc(2011, 0, 1)), 0);
t.equal(vega.utcweek(utc(2011, 0, 8)), 1);
t.equal(vega.utcweek(utc(2011, 11, 31)), 52);
t.end();
});
tape('utcweek extracts week number of year from timestamp', function(t) {
t.equal(vega.utcweek(+utc(2012, 0, 1)), 1);
t.equal(vega.utcweek(+utc(2012, 0, 8)), 2);
t.equal(vega.utcweek(+utc(2012, 11, 31)), 53);
t.equal(vega.utcweek(+utc(2011, 0, 1)), 0);
t.equal(vega.utcweek(+utc(2011, 0, 8)), 1);
t.equal(vega.utcweek(+utc(2011, 11, 31)), 52);
t.end();
});
| 35.907895 | 76 | 0.628069 |
b9656d8eb15cc7bb716fe35429bd5b5fb05260c5 | 5,252 | js | JavaScript | packages/koot-redux/lib/action.middleware.js | websage-team/super | 6ff33c21c45d1864ec402a795b39643ec2ff65af | [
"Apache-2.0"
] | 66 | 2018-08-27T08:16:39.000Z | 2021-08-05T09:42:28.000Z | packages/koot-redux/lib/action.middleware.js | cmux/koot | 6ff33c21c45d1864ec402a795b39643ec2ff65af | [
"Apache-2.0"
] | 185 | 2018-08-28T07:08:57.000Z | 2021-11-18T12:06:49.000Z | packages/koot-redux/lib/action.middleware.js | cmux/super | 6ff33c21c45d1864ec402a795b39643ec2ff65af | [
"Apache-2.0"
] | 12 | 2018-11-02T03:51:58.000Z | 2021-09-07T06:29:22.000Z | import { isObject, isString } from './utils.js';
const __STATIC_DATA__ = {};
/**
* 从 action 中获取 name
* @param {[type]} _action [description]
* @return {[type]} [description]
*/
const getName = ( action ) => {
if( isObject(action) ){
return action.type;
}
if( isString(action) ){
return action;
}
return null;
}
/**
* 获取对象类型的 action 的 payload
* @param {[type]} _action [description]
* @return {[type]} [description]
*/
const getObjectActionPayload = ( action ) => {
let payload = {};
if( isObject(action) ){
if( 'payload' in action ){
payload = action.payload
}else{
let tempObject = Object.assign({}, action);
delete tempObject.type;
payload = tempObject;
}
}
return payload;
}
const commitHandler = ( store ) => ( action, payload ) => {
const reducerName = getName(action);
const reducerFn = getReducerFnByName(reducerName);
if( isObject(action) ){
payload = getObjectActionPayload(action);
}
if( reducerFn ){
store.dispatch({
type: reducerName,
payload,
isModuleReducer: true,
})
}else{
throw new Error(
`ActionMiddlewareError: The reducer function '${reducerName}' is not registered!`
)
}
}
/**
* Action的执行处理函数
*
* @param {[type]} options.actionName [description]
* @param {[type]} options.actionFn [description]
* @param {[type]} options.store [description]
* @param {[type]} options.payload [description]
* @return {[type]} [description]
*/
const actionHandler = ({ actionName, actionFn, store, payload }) => {
const getScopeState = () => {
return __STATIC_DATA__['moduleInstance'].getStateByActionName(actionName) || {};
}
return actionFn({
commit: commitHandler(store),
rootState: Object.assign(store.getState()),
state: getScopeState(),
dispatch: store.dispatch,
}, payload);
// {
// state, // same as `store.state`, or local state if in modules
// rootState, // same as `store.state`, only in modules
// commit, // same as `store.commit`
// dispatch, // same as `store.dispatch`
// getters, // same as `store.getters`, or local getters if in modules
// rootGetters // same as `store.getters`, only in modules
// }
}
const getActionFnByName = ( actionName ) => {
const actionCollection = __STATIC_DATA__['moduleInstance'].actionCollection;
return actionCollection[actionName];
}
const getReducerFnByName = ( reducerName ) => {
const reducerCollection = __STATIC_DATA__['moduleInstance'].reducerCollection;
return reducerCollection[reducerName];
}
/**
* actionMiddleware 创建函数
*
* @param {Object} moduleInstance [description]
* @return {[type]} [description]
*/
const createActionMiddleware = function( moduleInstance = {} ){
__STATIC_DATA__['moduleInstance'] = moduleInstance;
// const actionCollection = moduleInstance.actionCollection;
// if( Object.keys(actionCollection).length === 0 ){
// throw new Error(
// `A valid actions collection was not received!`
// )
// }
/**
* 中间件主体函数
*
* @param {[type]} store [description]
* @return {[type]} [description]
*/
const actionMiddleware = store => next => ( action, payload ) => {
const actionName = getName(action);
const actionFn = getActionFnByName(actionName);
// 判断 是否为我们定义的 action
if( actionFn ){
// 判断 是否为传统对象形式参数
if( isObject(action) ){
const { isModuleReducer } = action;
if( isModuleReducer ){
delete action.isModuleReducer;
next(action);
return;
}
payload = getObjectActionPayload(action);
next({
type: actionName,
payload
});
return;
}else{
return actionHandler({
actionName,
actionFn,
store,
payload
})
}
}else{
// 不是我们的 action 且为传统 action 对象
if( isObject(action) ){
const { isModuleReducer } = action;
if( isModuleReducer ){
delete action.isModuleReducer;
next(action);
return;
}
// 检查是否为我们的reducers
const reducer = getReducerFnByName(actionName);
if( reducer ){
throw new Error(`ActionMiddlewareError: You Must call the reducer '${actionName}' in a Action`)
}
next(action);
return;
}else{
throw new Error(
`ActionMiddlewareError: The Action function '${actionName}' is not registered!`
)
}
}
}
return actionMiddleware;
}
export default createActionMiddleware;
| 28.699454 | 115 | 0.536938 |
b967e242068e99734f175d8442fa9ca215d70966 | 4,202 | js | JavaScript | scripts/seedDB.js | prabin544/HPI | d0ff4c690bf8d942fbbf2afe09718d150134c679 | [
"Unlicense",
"MIT"
] | null | null | null | scripts/seedDB.js | prabin544/HPI | d0ff4c690bf8d942fbbf2afe09718d150134c679 | [
"Unlicense",
"MIT"
] | null | null | null | scripts/seedDB.js | prabin544/HPI | d0ff4c690bf8d942fbbf2afe09718d150134c679 | [
"Unlicense",
"MIT"
] | null | null | null | const mongoose = require("mongoose");
const db = require("../models");
// This file empties the Books collection and inserts the books below
mongoose.connect(
process.env.MONGODB_URI ||
"mongodb://localhost/hpigenerator"
);
const patientRecordSeed = [
{
patientName: "Amy K",
dob: "2020-11-18",
apptDate: new Date(Date.now()),
patientId: "001",
symptom: "Trauma",
assocSymptoms: ["back pain", "neck pain", "trouble walking"],
palliative: ["massage", "hot compress"],
provocative: ["arching", "bending"],
qualityType: ["stabbing", "numbness"],
radiation: ["lower back", "legs"],
severity: 7,
symptomStart: new Date(Date.now()),
hpi: "Patient reports back pain after coding bootcamp",
status: 'closed'
},
{
patientName: "Amy K",
dob: "2020-11-18",
apptDate: new Date(Date.now()),
patientId: "001",
symptom: "Trauma",
assocSymptoms: ["back pain", "neck pain", "trouble walking"],
palliative: ["massage", "hot compress"],
provocative: ["arching", "bending"],
qualityType: ["stabbing", "numbness"],
radiation: ["lower back", "legs"],
severity: 7,
symptomStart: new Date(Date.now()),
hpi: "Patient reports back pain after coding bootcamp"
},
{
patientName: "Marlon P",
dob: "2020-11-18",
apptDate: new Date(Date.now()),
patientId: "002",
symptom: "Flu/COVID symptoms",
assocSymptoms: ["fever", "chills", "sore throat", "congestion"],
palliative: ["tylenol", "ibuprofen"],
provocative: [],
qualityType: ["aching", "sore"],
radiation: ["chest"],
severity: 7,
symptomStart: new Date(Date.now()),
hpi: "Patient reports brainfreeze while eating ice cream"
},
{
patientName: "Robin R",
dob: "2020-11-18",
apptDate: new Date(Date.now()),
patientId: "003",
symptom: "abdomen",
assocSymptoms: ["fever", "chills", "nausea", "vomiting", "diarrhea"],
palliative: [],
provocative: ["eating"],
qualityType: ["burning", "sharp"],
radiation: ["right upper abdomen"],
severity: 7,
symptomStart: new Date(Date.now()),
hpi: "Robin is a 22 year-old Female who reports pain for 0 days. Patient describes their symptom as quality. Patient has radiation to their . Patient rates their pain as a /10. The patient's symptom is . The patient's symptom is worse with and better with . The patient admits to . The patient denies associated symptoms** fever, chills, or fatigue."
},
{
patientName: "Prabin",
dob: "2020-11-18",
apptDate: new Date(Date.now()),
patientId: "003",
symptom: "fracture",
assocSymptoms: ["fever", "chills", "nausea", "vomiting", "diarrhea"],
palliative: [],
provocative: ["eating"],
qualityType: ["burning", "sharp"],
radiation: ["right upper abdomen"],
severity: 7,
symptomStart: new Date(Date.now()),
hpi: "Patient reports fun times after visiting Disneyland"
}
];
const userSeed = [
{
email: "admin@email.com",
firstName: "Admin",
lastName: "User",
gender: "Hermaphrodite",
userType: "admin",
dob: "2020-11-18",
password: "$2b$10$3fi4525qV1oTpCTuh7lX.ucASZ5yl6vysezZCHDmdVIneTuZ9.ssu"
},
{
email: "patient1@email.com",
firstName: "John",
lastName: "Doe",
gender: "Male",
userType: "patient",
dob: "1980-01-31",
password: "$2b$10$3fi4525qV1oTpCTuh7lX.ucASZ5yl6vysezZCHDmdVIneTuZ9.ssu"
},
{
email: "doctor1@email.com",
firstName: "Amy",
lastName: "Nguyen",
gender: "Female",
dob: "1990-12-25",
userType: "physician",
password: "$2b$10$3fi4525qV1oTpCTuh7lX.ucASZ5yl6vysezZCHDmdVIneTuZ9.ssu"
}
];
db.PatientRecord
.deleteMany({})
.then(() => db.PatientRecord.collection.insertMany(patientRecordSeed))
.then(data => {
console.log(data.result.n + " records inserted!");
process.exit(0);
})
.catch(err => {
console.error(err);
process.exit(1);
});
db.User
.deleteMany({})
.then(() => db.User.collection.insertMany(userSeed))
.then(data => {
console.log(data.result.n + " records inserted!");
process.exit(0);
})
.catch(err => {
console.error(err);
process.exit(1);
});
| 29.384615 | 354 | 0.628034 |
b968a2df399b725ed8f031d2d3229c71a624be4a | 1,380 | js | JavaScript | src/index.js | nyabongoedgar/unifyre-web-wallet-components2 | 5c4b4a50886b3ee31d9bbce634376f8beb7e5f24 | [
"MIT"
] | null | null | null | src/index.js | nyabongoedgar/unifyre-web-wallet-components2 | 5c4b4a50886b3ee31d9bbce634376f8beb7e5f24 | [
"MIT"
] | 3 | 2021-03-02T01:12:43.000Z | 2021-07-20T06:32:09.000Z | src/index.js | nyabongoedgar/unifyre-web-wallet-components2 | 5c4b4a50886b3ee31d9bbce634376f8beb7e5f24 | [
"MIT"
] | null | null | null | export * from "./lib/components/hello";
export * from "./lib/components/Gap";
export * from "./lib/components/ThemedText";
export * from "./lib/components/ThemedButton";
export * from "./lib/components/ThemedLink";
export * from "./lib/components/common/BigLogo";
export * from "./lib/components/common/Card";
export * from "./lib/components/common/CardSlider";
export * from "./lib/components/common/HeaderLabel";
export * from "./lib/components/common/IconLabel";
export * from "./lib/components/common/InputGroupAddon";
export * from "./lib/components/common/InputSearch";
export * from "./lib/components/common/InputSwitch";
export * from "./lib/components/common/Layout";
export * from "./lib/components/common/List";
export * from "./lib/components/common/ListItem";
export * from "./lib/components/common/Logo";
export * from "./lib/components/common/Notification";
export * from "./lib/components/common/PageTitle";
export * from "./lib/components/common/ScaledImage";
export * from "./lib/components/common/PageTopSection";
export * from "./lib/components/user/account/AccountListItem";
export * from "./lib/components/user/account/CoinBalance";
export * from "./lib/components/user/account/UserActivity";
export * from "./lib/components/user/dashboard/Coin";
export * from "./lib/components/user/account/CoinDeposit";
export * from "./lib/components/user/search/Item";
| 47.586207 | 62 | 0.744203 |
b968a377c1a29ddbf5fcca6b6fd2559ac2af0698 | 747 | js | JavaScript | src/config/firebase/index.js | dimasdh842/notes-reactjs | cfe5dc70ea6156795d3a642c700fd32a611099f1 | [
"MIT"
] | null | null | null | src/config/firebase/index.js | dimasdh842/notes-reactjs | cfe5dc70ea6156795d3a642c700fd32a611099f1 | [
"MIT"
] | null | null | null | src/config/firebase/index.js | dimasdh842/notes-reactjs | cfe5dc70ea6156795d3a642c700fd32a611099f1 | [
"MIT"
] | null | null | null | import firebase from "firebase/app";
import "firebase/analytics";
import "firebase/firestore";
import "firebase/database";
require("firebase/auth");
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "AIzaSyBGl7KNYKd1D2DRU5wlEa5-PIBZNjGL-fI",
authDomain: "doing-nothing-firebase.firebaseapp.com",
projectId: "doing-nothing-firebase",
storageBucket: "doing-nothing-firebase.appspot.com",
messagingSenderId: "54813910745",
appId: "1:54813910745:web:20e5d922ad75133ba240c8",
measurementId: "G-LRPZ39MSNL"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
export default firebase | 33.954545 | 69 | 0.751004 |
b968c36f6d608ab780cec82f98bb7de8be5b907c | 615 | js | JavaScript | src/index.js | evanhurd/QuickStep | 8233bfa3cc1cd7ee5c8f0eafde832f12f2fe6922 | [
"MIT"
] | null | null | null | src/index.js | evanhurd/QuickStep | 8233bfa3cc1cd7ee5c8f0eafde832f12f2fe6922 | [
"MIT"
] | null | null | null | src/index.js | evanhurd/QuickStep | 8233bfa3cc1cd7ee5c8f0eafde832f12f2fe6922 | [
"MIT"
] | null | null | null | var QuickStep = require('./QuickStep.js');
var Model = require('./Model.js');
var Collection = require('./Collection.js');
var CollectionElement = require('./CollectionElement.js');
var ModelValue = require('./ModelValue.js');
var Primitives = require('./primitives/index.js');
var SubPub = require('./subpub.js');
QuickStep.Model = Model;
QuickStep.Collection = Collection;
QuickStep.CollectionElement = CollectionElement;
QuickStep.ModelValue = ModelValue;
QuickStep.Primitives = Primitives;
QuickStep.Primitives = Primitives;
QuickStep.SubPub = SubPub;
module.exports = QuickStep;
window.QuickStep = QuickStep; | 34.166667 | 58 | 0.760976 |
b968f4c48bb8673ebed21fe04eb434c5c4f4996b | 1,378 | js | JavaScript | packages/core/icon/glyph/export.js | varijkapil13/atlaskit | 655fb6a8edaff9db07211803f788ae0995f3862b | [
"Apache-2.0"
] | 7 | 2020-05-12T11:46:06.000Z | 2021-05-12T02:10:34.000Z | packages/core/icon/glyph/export.js | varijkapil13/atlaskit | 655fb6a8edaff9db07211803f788ae0995f3862b | [
"Apache-2.0"
] | 1 | 2019-05-08T06:48:30.000Z | 2019-05-08T06:48:30.000Z | packages/core/icon/glyph/export.js | varijkapil13/atlaskit | 655fb6a8edaff9db07211803f788ae0995f3862b | [
"Apache-2.0"
] | 1 | 2020-04-30T09:40:37.000Z | 2020-04-30T09:40:37.000Z | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _index = require('../es5/index');
var _index2 = _interopRequireDefault(_index);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ExportIcon = function ExportIcon(props) {
return _react2.default.createElement(_index2.default, _extends({ dangerouslySetGlyph: '<svg width="24" height="24" viewBox="0 0 24 24" focusable="false" role="presentation"><path d="M13 6.491V16a1 1 0 0 1-2 0V6.491L9.784 7.697a1.051 1.051 0 0 1-1.478 0 1.029 1.029 0 0 1 0-1.465l2.955-2.929a1.051 1.051 0 0 1 1.478 0l2.955 2.93c.408.404.408 1.06 0 1.464a1.051 1.051 0 0 1-1.478 0L13 6.49zM9 9v2H7c-.002 0 0 7.991 0 7.991 0 .004 9.994.009 9.994.009.003 0 .006-7.991.006-7.991 0-.006-2-.009-2-.009V9h2c1.105 0 2 .902 2 2.009v7.982c0 1.11-.897 2.009-2.006 2.009H7.006A2.009 2.009 0 0 1 5 18.991V11.01A2 2 0 0 1 7 9h2z" fill="currentColor"/></svg>' }, props));
};
ExportIcon.displayName = 'ExportIcon';
exports.default = ExportIcon; | 59.913043 | 658 | 0.70029 |
b9698bd1b943bd503a0c7d91073fb75350e2f13c | 6,263 | js | JavaScript | app/webpacker/src/traits/data_viz/taxon_summary.js | EOL/publishing | f0076291521a1b3dbeba2d565b2bbb653f504028 | [
"MIT"
] | 21 | 2016-10-05T03:52:57.000Z | 2021-09-09T14:38:45.000Z | app/webpacker/src/traits/data_viz/taxon_summary.js | EOL/publishing | f0076291521a1b3dbeba2d565b2bbb653f504028 | [
"MIT"
] | 61 | 2016-12-22T18:02:25.000Z | 2021-09-09T14:16:42.000Z | app/webpacker/src/traits/data_viz/taxon_summary.js | EOL/publishing | f0076291521a1b3dbeba2d565b2bbb653f504028 | [
"MIT"
] | 5 | 2018-03-06T18:34:34.000Z | 2019-09-02T20:00:32.000Z | import * as d3 from 'd3'
window.TaxonSummaryViz = (function(exports) {
const width = 800
, height = 800
, pad = 3
, bgColor = '#fff' //'rgb(163, 245, 207)'
, outerCircColor = 'rgb(185, 233, 240)'
, innerCircColor = '#fff'
, labelTspanOffset = 13
;
let view
, root
, focus
, node
, label
, svg
, filterText
, outerFilterPrompt
;
function build($contain) {
const $viz = $contain.find('.js-taxon-summary')
, data = $viz.data('json')
;
filterText = $viz.data('prompt');
root = pack(data);
const initFocusIsRoot = root.children.length > 1;
focus = initFocusIsRoot ? root : root.children[0]
d3.select($viz[0])
.style('width', `${width}px`)
.style('height', `${height}px`)
.style('position', 'relative')
.style('margin', '0 auto')
;
svg = d3.select($viz[0])
.append('svg')
.attr('viewBox', `-${width / 2} -${height / 2} ${width} ${height}`)
.attr('width', width)
.style('width', width)
.attr('height', height)
.style('height', height)
.style('margin', '0 auto')
.style('display', 'block')
.style('background', bgColor)
node = svg.append('g')
.selectAll('circle')
.data(root.descendants().slice(1))
.join('circle')
.attr('fill', d => d.children ? outerCircColor : innerCircColor)
.on('click', handleNodeClick)
;
if (initFocusIsRoot) {
svg
.on('click', (e, d) => zoom(root))
.style('cursor', 'pointer')
} else {
node.style('cursor', 'pointer');
}
label = svg.append('g')
.style('font', '12px sans-serif')
.attr('fill', '#222')
.attr('text-anchor', 'middle')
.attr('pointer-events', 'none')
.selectAll('text')
.data(root.descendants().slice(1))
.join('text')
.attr('id', labelId)
.style('fill-opacity', d => d.children ? 1 : 0)
.style('mix-blend-mode', 'multiply')
.style('display', labelDisplay)
label.append('tspan')
.attr('font-style', d => d.data.name.includes('<i>') ? 'italic' : null)
.text(d => d.data.name.includes('<i>') ? d.data.name.replaceAll('<i>', '').replaceAll('</i>', '') : d.data.name);
label.append('tspan')
.attr('x', 0)
.attr('dy', -labelTspanOffset)
.text(d => `(${d.data.count})`);
if (initFocusIsRoot) {
outerFilterPrompt = d3.select($viz[0])
.append('button')
.style('position', 'absolute')
.style('top', '5px')
.style('right', '5px')
.style('text-anchor', 'end')
.style('padding', '2px 4px')
.style('font', 'bold 14px sans-serif')
.style('display', 'none')
.style('cursor', 'pointer');
}
zoomTo(zoomCoords(focus));
styleLabelsForZoom();
}
exports.build = build;
function pack(data) {
return d3.pack()
.size([width, height])
.padding(pad)
(d3.hierarchy(data)
.sum(d => d.count)
.sort((a, b) => b.count - a.count))
}
function zoom(d) {
focus = d;
if (outerFilterPrompt) {
if (focus !== root && focus.children) {
outerFilterPrompt.html(focus.data.promptText);
outerFilterPrompt.style('display', 'block');
outerFilterPrompt.on('click', () => window.location = d.data.searchPath);
} else {
outerFilterPrompt.style('display', 'none');
}
}
const transition = svg.transition()
.duration(750)
.tween("zoom", d => {
const i = d3.interpolateZoom(view, zoomCoords(focus));
return t => zoomTo(i(t));
});
styleLabelsForZoom();
}
function zoomCoords(node) {
return [node.x, node.y, node.r * 2];
}
function styleLabelsForZoom() {
label
.filter(function(d) { return d.parent === focus || this.style.display === "inline"; })
.style('fill-opacity', d => d.parent === focus ? 1 : 0)
.style('display', d => d.parent === focus ? 'inline' : 'none')
}
function zoomTo(v) {
const k = width / v[2];
view = v;
label.attr("transform", (d) => nodeTransform(d, v, k));
node.attr("transform", (d) => nodeTransform(d, v, k));
node.attr("r", d => d.r * k);
node
.attr('pointer-events', d => d.parent && d.parent === focus ? null : 'none')
.on('mouseover', handleNodeMouseover)
.on('mouseout', handleNodeMouseout)
;
}
function handleNodeClick(e, d) {
if (d !== focus) {
if (d.children) {
zoom(d);
} else {
window.location = d.data.searchPath;
}
e.stopPropagation();
}
}
function handleNodeMouseover(e, d) {
d3.select(this).attr('stroke', '#000');
if (!d.children) {
label.style('fill-opacity', '.5');
d3.select(`#${labelId(d)}`)
.style('fill-opacity', 1)
.style('font-weight', 'bold')
.append('tspan')
.attr('class', 'click-prompt')
.attr('x', 0)
.attr('dy', 2 * labelTspanOffset)
.text('click to filter');
}
}
function handleNodeMouseout(e, d) {
d3.select(this).attr('stroke', null)
if (!d.children) {
label
.style('fill-opacity', 1)
.style('font-weight', 'normal');
d3.select(`#${labelId(d)}`)
.select('.click-prompt')
.remove();
}
}
function labelId(d) {
return `label-${d.data.pageId}`;
}
function labelDisplay(d) {
return d.parent === focus ? 'inline' : 'none';
}
function nodeTransform(d, v, k) {
let x, y;
// layout is better with child nodes rotated 90 deg. about center of parent circle
if (!d.children) {
const parentX = transformCoord(d.parent.x, v[0], k);
const parentY = transformCoord(d.parent.y, v[1], k);
const xNew = transformCoord(d.x, v[0], k);
const yNew = transformCoord(d.y, v[1], k);
x = yNew - parentY + parentX;
y = xNew - parentX + parentY;
} else {
x = transformCoord(d.x, v[0], k);
y = transformCoord(d.y, v[1], k);
}
return `translate(${x},${y})`;
}
function transformCoord(nVal, vVal, k) {
return (nVal - vVal) * k;
}
return exports;
})({});
| 25.668033 | 119 | 0.532333 |
b96bfac621f98a39ccccec68d6ab05bbf0af1f7b | 2,417 | js | JavaScript | test/display/scripts/example.js | omatoro/tmlib.js | 829f48ba0041373b12cb91c7a79564a19ae392ca | [
"MIT"
] | 78 | 2015-01-06T01:42:56.000Z | 2021-05-29T14:55:36.000Z | test/display/scripts/example.js | omatoro/tmlib.js | 829f48ba0041373b12cb91c7a79564a19ae392ca | [
"MIT"
] | 37 | 2015-01-04T15:41:51.000Z | 2015-12-07T02:50:24.000Z | test/display/scripts/example.js | omatoro/tmlib.js | 829f48ba0041373b12cb91c7a79564a19ae392ca | [
"MIT"
] | 28 | 2015-01-05T15:20:37.000Z | 2020-05-17T13:08:54.000Z | /*
* main scene
*/
tm.define("tests.example.Shodo", {
superClass: "tm.app.Scene",
init: function() {
this.superInit();
this.shape = tm.display.Shape(SCREEN_WIDTH, SCREEN_HEIGHT).addChildTo(this);
this.shape.origin.set(0, 0);
this.shape.canvas.clearColor("#eee");
this.sodouImage = tm.asset.Texture("http://jsrun.it/assets/a/h/k/M/ahkMh.png");
},
update: function(app) {
if (app.pointing.getPointing()) {
this.drawShodo(app.pointing);
}
},
drawShodo: function(p) {
var c = this.shape.canvas;
c.save();
var image = this.sodouImage;
var deltaLength = p.deltaPosition.length();
console.log(deltaLength);
if (deltaLength == 0) {
var finalX = p.x;
var finalY = p.y;
c.translate(-image.width/2, -image.height/2);
c.drawTexture(image, finalX, finalY);
this.prevScale = 1;
}
else {
var index = 0;
var next = tm.geom.Vector2.add(p.position, p.deltaPosition);
var scale = (400-deltaLength)/400;
for (var t=0; t<1;) {
index++;
var finalPos = tm.geom.Vector2.lerp(p.prevPosition, p.position, t);
var finalScale = this.prevScale + (scale-this.prevScale)*t;
c.save();
c.translate(finalPos.x+Math.random()*4-2, finalPos.y+Math.random()*4-2);
c.scale(finalScale, finalScale);
c.globalAlpha = 0.25;
c.translate(-image.width/2, -image.height/2);
c.drawTexture(image, 0, 0);
c.globalAlpha = 1.0;
c.restore();
t += 1 / deltaLength;
};
this.prevScale = scale;
}
c.restore();
}
});
/*
* main scene
*/
tm.define("tests.example.Keyboard", {
superClass: "tm.app.Scene",
init: function() {
this.superInit();
this.player = tm.display.TriangleShape().addChildTo(this);
this.player.setPosition(320, 240);
},
update: function(app) {
var direction = app.keyboard.getKeyDirection();
this.player.position.add(direction.mul(8));
}
});
| 25.712766 | 88 | 0.493173 |
b96bfd26dbd52a68e135db8967dd768260970ac5 | 1,417 | js | JavaScript | backend/src/routes/v1/whoishiring.js | weisisheng/whoishiring.work | 0d22cad169ae0020a97ad6a7bc85453574e8d1fb | [
"MIT"
] | 5 | 2020-01-08T02:09:44.000Z | 2020-10-20T03:52:18.000Z | backend/src/routes/v1/whoishiring.js | weisisheng/whoishiring.work | 0d22cad169ae0020a97ad6a7bc85453574e8d1fb | [
"MIT"
] | 6 | 2020-01-08T20:48:39.000Z | 2022-01-22T13:02:21.000Z | backend/src/routes/v1/whoishiring.js | weisisheng/whoishiring.work | 0d22cad169ae0020a97ad6a7bc85453574e8d1fb | [
"MIT"
] | 1 | 2020-01-09T04:51:55.000Z | 2020-01-09T04:51:55.000Z | /**
* API endpoints:
* /latest
* /months
* /months/December+2019/posts
*/
const router = require('express').Router();
const whoishiring = require('../../services/whoishiring');
function send405Status(allowed = 'GET') {
return (req, res) => {
res.set('Allow', allowed);
res.sendStatus(405);
};
}
router
.route('/latest')
.get(async (req, res) => {
const posts = await whoishiring.getPostsByMonth('latest');
const months = await whoishiring.getListOfMonthLabel();
res.status(200).json({
page: 1,
postsTotal: posts.length,
postsPerPage: posts.length,
months,
posts,
});
})
.all(send405Status());
router
.route('/months/:month/posts')
.get(async (req, res) => {
const { month } = req.params;
const posts = await whoishiring.getPostsByMonth(month);
if (posts.length === 0) {
req.log.error({ month }, 'month not found for /months/:month/posts');
return res.sendStatus(404);
}
res.status(200).json({
page: 1,
postsTotal: posts.length,
postsPerPage: posts.length,
posts,
});
})
.all(send405Status());
router.route('/months/:month').all((req, res) => res.sendStatus(400));
router
.route('/months')
.get(async (req, res) => {
const labels = await whoishiring.getListOfMonthLabel();
res.status(200).json(labels);
})
.all(send405Status());
module.exports = router;
| 22.140625 | 75 | 0.613973 |
b96d074309b732eb4de572d96b9b9fca3be01e5e | 991 | js | JavaScript | src/common/components/Navi.js | jessicatsengj/Serendipity-Site | b38e87d1eb47474bf0e37fc8c7d3d1af1e36420f | [
"MIT"
] | null | null | null | src/common/components/Navi.js | jessicatsengj/Serendipity-Site | b38e87d1eb47474bf0e37fc8c7d3d1af1e36420f | [
"MIT"
] | null | null | null | src/common/components/Navi.js | jessicatsengj/Serendipity-Site | b38e87d1eb47474bf0e37fc8c7d3d1af1e36420f | [
"MIT"
] | null | null | null | // var react = require('react');
import React, { Component } from 'react';
import {Link} from 'react-router-dom';
import {NavLink} from 'react-router-dom';
class Navi extends Component {
render() {
return (
<div className="ts fluid container nav navi">
<div className="ts menu black">
<NavLink className="myLink" to="/"><img className="logo" src="/Image/logo-white.png"></img></NavLink>
<div className="right menu">
<div className="item navi_item"><NavLink className="myLink myOtherLink" activeClassName="selected" to="/about" >ABOUT</NavLink></div>
<div className="item navi_item"><NavLink className="myLink myOtherLink" activeClassName="selected" to="/portfolio" >PORTFOLIO</NavLink></div>
<div className="item navi_item"><NavLink className="myLink myOtherLink" activeClassName="selected" to="/writings" >WRITINGS</NavLink></div>
</div>
</div>
</div>
);
}
}
export default Navi;
| 38.115385 | 153 | 0.64884 |
b970a52696a9f516105c776e90b090312d0f862d | 3,408 | js | JavaScript | lib/util.js | danmasta/deploy | a4423213b8793679c68565bb89dd11f90a0e72a8 | [
"MIT"
] | null | null | null | lib/util.js | danmasta/deploy | a4423213b8793679c68565bb89dd11f90a0e72a8 | [
"MIT"
] | null | null | null | lib/util.js | danmasta/deploy | a4423213b8793679c68565bb89dd11f90a0e72a8 | [
"MIT"
] | null | null | null | const path = require('path');
const cp = require('child_process');
const Promise = require('bluebird');
const _ = require('lodash');
const defaults = {
// base options
'name': 'app',
'version': null,
'ecrUri': null,
'region': ['us-east-1'],
// eb options
'eb': true,
'ebApp': null,
'ebEnv': null,
'ebBucket': null,
'dockerrun': './Dockerrun.aws.json',
'outputDir': './dist/deploy',
// optional modifiers
'silent': false,
'interactive': true,
'regionList': []
};
const constants = {
REGIONS: [
'us-east-1', // north virgina
'us-east-2', // ohio
'us-west-1', // north california
'us-west-2', // oregon
'ca-central-1', // central canada
'ap-south-1', // mumbai
'ap-northeast-1', // tokyo
'ap-northeast-2', // seoul
'ap-southeast-1', // singapore
'ap-southeast-2', // sydney
'eu-central-1', // frankfurt
'eu-west-1', // ireland
'eu-west-2', // london
'sa-east-1' // sao paulo
],
CHECK_ENV_ERROR: `Error: %s not found in path, please install`,
CHECK_ENV_SUCCESS: `All checks passed successfully`,
EB_CONFIG_PATH: `./.elasticbeanstalk/config.yml`
};
// returns promise with buffered output
function exec(cmd) {
return new Promise((resolve, reject) => {
cp.exec(cmd, { silent: true }, (err, stdout, stderr) => {
if (err) {
reject(err);
} else if (stderr) {
reject(new Error(stderr));
} else {
resolve({ err, stdout, stderr });
}
});
});
}
// [in, out, err]
// can stream output to parent
// returns promise with buffered output
function spawn(cmd, pipeOut = false, pipeErr = false) {
return new Promise((resolve, reject) => {
let stdout = '';
let stderr = '';
let err = null;
let child = cp.spawn(cmd, { shell: true, stdio: ['inherit', 'pipe', 'pipe'] });
child.stdout.on('data', chunk => {
return stdout += chunk.toString();
});
child.stderr.on('data', chunk => {
return stderr += chunk.toString();
});
if (pipeOut) {
child.stdout.pipe(process.stdout);
}
if (pipeErr) {
child.stderr.pipe(process.stderr);
}
child.on('error', res => {
err = res;
});
child.on('close', code => {
if (err) {
reject(err);
} else if (stderr) {
reject(new Error(stderr));
} else {
resolve({ err, code, stdout, stderr });
}
});
});
}
function zipPath(opts) {
return path.resolve(path.join(opts.outputDir, opts.version + '.zip'));
}
function merge(dest, ...args) {
_.map(args, (obj, index) => {
_.map(obj, (val, key) => {
if (/region/.test(key)) {
dest[key] = _.uniq(_.compact(_.concat(dest[key], _.concat(val))));
} else if (val !== undefined) {
dest[key] = val;
}
});
});
return dest;
}
exports.defaults = defaults;
exports.constants = constants;
exports.exec = exec;
exports.spawn = spawn;
exports.zipPath = zipPath;
exports.merge = merge;
| 21.56962 | 87 | 0.497066 |
b9725ea8562b2d9f54fb69f1f3316847498065ff | 711 | js | JavaScript | fuzzer_output/interesting/sample_1554171166604.js | patil215/v8 | bb941b58df9ee1e4048b69a555a2ce819fb819ed | [
"BSD-3-Clause"
] | null | null | null | fuzzer_output/interesting/sample_1554171166604.js | patil215/v8 | bb941b58df9ee1e4048b69a555a2ce819fb819ed | [
"BSD-3-Clause"
] | null | null | null | fuzzer_output/interesting/sample_1554171166604.js | patil215/v8 | bb941b58df9ee1e4048b69a555a2ce819fb819ed | [
"BSD-3-Clause"
] | null | null | null | function main() {
let v2 = 0;
const v3 = v2 + 1;
v2 = v3;
const v6 = [1337,1337];
let v7 = 13.37;
const v12 = [13.37,13.37,13.37];
const v14 = [];
const v15 = {keys:v12,sqrt:13.37,trimEnd:v14,slice:"undefined",log2:"undefined",dotAll:1337,padStart:"undefined"};
const v16 = {getInt16:v15,trimEnd:v14,prototype:this,trim:v15,getOwnPropertyDescriptors:"undefined",input:"undefined",padStart:13.37};
const v19 = [1337,1337,1337];
const v23 = [1337,1337,1337];
function v24(v25,v26,v27,v28) {
const v31 = new Uint32Array(2879);
for (const v32 in v31) {
}
v31[1612619043] = v28;
}
const v33 = v24("number",v7,0,v23);
const v34 = v24(-1244269720,v19,1,v6,v16);
}
%NeverOptimizeFunction(main);
main();
| 29.625 | 134 | 0.679325 |
b9751aa3084875911932152c2305fbd0451b9052 | 4,869 | js | JavaScript | env-demo.js | andres-torres-2020/TwilioEnvVarDemo | cd84299797a6fbf2703a2d7215af2dee4718ff68 | [
"MIT"
] | null | null | null | env-demo.js | andres-torres-2020/TwilioEnvVarDemo | cd84299797a6fbf2703a2d7215af2dee4718ff68 | [
"MIT"
] | null | null | null | env-demo.js | andres-torres-2020/TwilioEnvVarDemo | cd84299797a6fbf2703a2d7215af2dee4718ff68 | [
"MIT"
] | null | null | null | // env-demo.js
//
// This is a demo app to use Twilio Environment and Variable APIs
const client = require('./app_client.js').APP_CLIENT;
const twilio_environment = require('./twilio_environment.js').twilio_environment;
const twilio_environment_variable = require('./twilio_environment_variable.js').twilio_environment_variable;
//const appFlow = new Promise(DemoApp)
//appFlow.then(x => console.log('Done'))
DemoClosureApp();
function DemoClosureApp()
{
let ServiceSid = "ZS25d338c254b17b3faac24bf9d2ce5ca2";
let f = new closureTestGetEnvironment(client, ServiceSid);
f.readEnvironment(environments => {
console.log(`getEnvironments for Twilio ServiceSID=${ServiceSid}\n============`);
environments.forEach(e => console.log(`Environment: {sid: ${e.sid}, unique_name: ${e.unique_name}}`))
})
console.log(`done: ${JSON.stringify(f)}`)
}
function closureTestGetEnvironment(client, serviceSid)
{
let env = new twilio_environment(client, serviceSid);
this.readEnvironment = function reader(ProcessorCallback)
{
env.read()
.then(envList => ProcessorCallback(envList))
}
}
function DemoApp()
{
let ServiceSid = "ZS25d338c254b17b3faac24bf9d2ce5ca2";
let EnvironmentSid = "ZE7e5c5a7c731bdea7940b9055b19a1d91";
testCreateVariable(ServiceSid, EnvironmentSid);
testGetEnvironment(client, ServiceSid)
let VariableSid = "ZV73b81fe69ef8bbd27e7f4d2bb217d825";
testDeleteVariable(ServiceSid, EnvironmentSid, VariableSid);
testGetEnvironment(client, ServiceSid);
let updateVariableSid = "ZV582bcbb756a10d4a1c4f94746ecd85f0";
testUpdateVariable(ServiceSid, EnvironmentSid, updateVariableSid, "r2-potatu");
testGetEnvironment(client, ServiceSid);
}
function testCreateVariable(serviceSid, environmentSid)
{
let variableKey = "newKey999111sss"
let variableValue = "newValue"
let variableObj = new twilio_environment_variable(client, serviceSid, environmentSid, null);
variableObj.create(environmentSid, variableKey, variableValue)
.then(variable => {
console.log(`variable created: ${JSON.stringify(variable)}`)
})
.catch(err => console.log(`variable creation failed: ${err}`));
}
function testUpdateVariable(serviceSid, environmentSid, variableSid, variableValue)
{
let variableObj = new twilio_environment_variable(client, serviceSid, null);
variableObj.update(environmentSid, variableSid, variableValue)
.then((some_promise) => {
console.log(`variable updated: ${variableSid}`)
})
.catch(err => console.log(`variable update failed: ${err}`));
}
function testDeleteVariable(serviceSid, environmentSid, variableSid)
{
let variableObj = new twilio_environment_variable(client, serviceSid, null);
variableObj.delete(environmentSid, variableSid)
.then((some_promise) => {
console.log(`variable deleted: ${variableSid}`)
})
.catch(err => console.log(`variable deletion failed: ${err}`));
}
async function testGetEnvironment(client, serviceSid)
{
let variableObj = new twilio_environment_variable(client, serviceSid, null);
let env = new twilio_environment(client, serviceSid);
let variableList = [];
await env.read()
.then(envList =>
{
console.log(`get_environments for Twilio ServiceSID=${serviceSid}\n============`);
envList.forEach(e => {
console.log(`Environment: {sid: ${e.sid}, unique_name: ${e.unique_name}}\n----------------------`)
variableObj.read(e.sid).then(vars => {
vars.forEach(v => {
console.log(`\tvarSid=${v.sid}, key:${v.key}, value:${v.value}`);
variableList.push(v);
})
})
.catch(err => {console.error(`var read error: ${err}`)})
});
})
.finally(()=>{
console.log(`variableList.length=${variableList.length}`);
variableList.forEach(v => {console.log(`\t\tvarSid=${v.sid}, key:${v.key}, value:${v.value}`);})
});
return variableList;
}
function test_list_env_vars(client, serviceSid)
{
let env = new twilio_environment(client, serviceSid);
let variableObj = new twilio_environment_variable(client, EnvServiceSid, null);
env.read().then(envList =>
{
console.log('environments\n============');
envList.forEach(e => {
console.log(`sid: ${e.sid}, unique_name: ${e.unique_name}\n----------------------`)
let vars = variableObj.read(e.sid).then(vars => {
vars.forEach(v => console.log(`\tvarSid=${v.sid}, var=<${v.key} : ${v.value}`))
})
.catch(err => {console.error(`var read error: ${err}`)})
});
});
}
| 38.642857 | 114 | 0.640583 |
b97532254dcefd830f88fab25c047da65f3a67e9 | 368 | js | JavaScript | framework/templates/angularjs/js/controller.js | Dmutryk/Code-Alchemy-MVC-Framework-for-PHP-and-PostgreSQL | 97e9fd74452b13436ab220d1a46c04d5d151d5aa | [
"MIT"
] | null | null | null | framework/templates/angularjs/js/controller.js | Dmutryk/Code-Alchemy-MVC-Framework-for-PHP-and-PostgreSQL | 97e9fd74452b13436ab220d1a46c04d5d151d5aa | [
"MIT"
] | null | null | null | framework/templates/angularjs/js/controller.js | Dmutryk/Code-Alchemy-MVC-Framework-for-PHP-and-PostgreSQL | 97e9fd74452b13436ab220d1a46c04d5d151d5aa | [
"MIT"
] | 1 | 2018-03-05T15:17:18.000Z | 2018-03-05T15:17:18.000Z | define(['__module_name__'],function(__module_name__){
var controller = __module_name__.controller('__controller_name__',
[ '$scope', '$http', '$routeParams',
function (scope, http, routeParams){
// BEGIN CONTROLLER BODY
// END CONTROLLER BODY
}]);
return controller;
});
| 24.533333 | 70 | 0.546196 |
b9757b31f034083d108785af9b4ae50e1d970a98 | 562 | js | JavaScript | .eslintrc.js | WeAreGenki/marko-bind | 3a6f2ad0f37eaee630fd440248a854f94791ede7 | [
"Apache-2.0"
] | 4 | 2018-02-14T15:09:27.000Z | 2021-05-17T20:19:11.000Z | .eslintrc.js | WeAreGenki/marko-bind | 3a6f2ad0f37eaee630fd440248a854f94791ede7 | [
"Apache-2.0"
] | 10 | 2018-01-23T23:45:34.000Z | 2018-03-25T09:13:13.000Z | .eslintrc.js | WeAreGenki/marko-bind | 3a6f2ad0f37eaee630fd440248a854f94791ede7 | [
"Apache-2.0"
] | null | null | null | 'use strict';
module.exports = {
root: true,
extends: ['@wearegenki/eslint-config'],
parserOptions: {
ecmaVersion: 6,
},
rules: {
/**
* Runtimes are to be written in es5 but there are some extra cross-browser
* caveats to take notice of.
*/
'func-names': 'off', // no arrow functions so we need oldschool anonymous functions
'no-var': 'off', // let/const not supported in IE10
'prefer-destructuring': 'off', // not supported in IE
'prefer-arrow-callback': 'off', // arrow functions not supported in IE10
},
};
| 28.1 | 87 | 0.637011 |
b975a662a9dd2173e849cb17066aa634348fb31d | 2,302 | js | JavaScript | dop-web/src/pages/Pipeline/components/chosenSteps/Shell.js | 552000264/dop | 7091ca7f90ae16860821f455d96bfe0eac75b2c3 | [
"Apache-2.0"
] | 1 | 2020-04-05T12:12:09.000Z | 2020-04-05T12:12:09.000Z | dop-web/src/pages/Pipeline/components/chosenSteps/Shell.js | 552000264/dop | 7091ca7f90ae16860821f455d96bfe0eac75b2c3 | [
"Apache-2.0"
] | null | null | null | dop-web/src/pages/Pipeline/components/chosenSteps/Shell.js | 552000264/dop | 7091ca7f90ae16860821f455d96bfe0eac75b2c3 | [
"Apache-2.0"
] | null | null | null | import React, {Component} from 'react';
import '../Styles.scss'
import {Input, Select, Form, Loading} from '@icedesign/base';
import {Feedback} from "@icedesign/base/index";
import {injectIntl} from "react-intl";
const {Combobox} = Select;
const {toast} = Feedback;
const FormItem = Form.Item;
class Shell extends Component {
constructor(props) {
super(props);
this.state = {
visible: false,
myScript: ["shell"]
}
}
buildShell(value) {
this.props.onShellChange(value)
}
render() {
const formItemLayout = {
labelCol: {
span: 10
},
wrapperCol: {
span: 10
}
};
return (
<Loading shape="fusion-reactor" visible={this.state.visible}>
<h3 className="chosen-task-detail-title">{this.props.intl.messages["pipeline.info.step.shell.title"]}</h3>
<Form
labelAlign="left"
labelTextAlign="left"
>
<FormItem
label={this.props.intl.messages["pipeline.info.step.shell.type"]+ ": "}
{...formItemLayout}
>
<Combobox
style={{'width': '200px'}}
filterLocal={false}
placeholder={this.props.intl.messages["pipeline.info.step.shell.type.placeholder"]}
dataSource={this.state.myScript}
/>
</FormItem>
<FormItem
label={this.props.intl.messages["pipeline.info.step.shell.content"]+ ": "}
{...formItemLayout}
required
>
<Input
multiple
value={this.props.shell}
className="area"
onChange={this.buildShell.bind(this)}
style={{'width': '200px'}}
/>
</FormItem>
</Form>
</Loading>
)
}
}
export default injectIntl(Shell)
| 32.422535 | 122 | 0.435708 |
b975abdf0eb86f817de75f46b9e9f75692cb62a6 | 3,153 | js | JavaScript | src/ledger/applyDistributions.js | hammadj/sourcecred | 9c3785351dfb8a301146b96be3747d9dae23a47c | [
"Apache-2.0",
"MIT"
] | null | null | null | src/ledger/applyDistributions.js | hammadj/sourcecred | 9c3785351dfb8a301146b96be3747d9dae23a47c | [
"Apache-2.0",
"MIT"
] | 189 | 2020-09-16T06:06:43.000Z | 2022-03-25T12:15:03.000Z | src/ledger/applyDistributions.js | hammadj/sourcecred | 9c3785351dfb8a301146b96be3747d9dae23a47c | [
"Apache-2.0",
"MIT"
] | 1 | 2020-11-03T22:12:10.000Z | 2020-11-03T22:12:10.000Z | // @flow
import {type TimestampMs} from "../util/timestamp";
import {Ledger} from "./ledger";
import {type AllocationPolicy} from "./grainAllocation";
import {CredView} from "../analysis/credView";
import {computeCredAccounts} from "./credAccounts";
import {computeDistribution} from "./computeDistribution";
import {type Distribution} from "./distribution";
export type DistributionPolicy = {|
// Each distribution will include each of the specified allocation policies
+allocationPolicies: $ReadOnlyArray<AllocationPolicy>,
// How many old distributions we may create (e.g. if the project has never
// had a Grain distribution in the past, do you want to create distributions
// going back the whole history, or limit to only 1 or 2 recent distributions).
+maxSimultaneousDistributions: number,
|};
/**
* Iteratively compute and distribute Grain, based on the provided CredView,
* into the provided Ledger, according to the specified DistributionPolicy.
*
* Here are some examples of how it works:
*
* - The last time there was a distribution was two days ago. Since then,
* no new Cred Intervals have been completed. This method will no-op.
*
* - The last time there was a distribution was last week. Since then, one new
* Cred Interval has been completed. The method will apply one Distribution.
*
* - The last time there was a distribution was a month ago. Since then, four
* Cred Intervals have been completed. The method will apply four Distributions,
* unless maxOldDistributions is set to a lower number (e.g. 2), in which case
* that maximum number of distributions will be applied.
*
* It returns the list of applied distributions, which may be helpful for
* diagnostics, printing a summary, etc.
*/
export function applyDistributions(
policy: DistributionPolicy,
view: CredView,
ledger: Ledger
): $ReadOnlyArray<Distribution> {
const credIntervals = view.credResult().credData.intervalEnds;
const distributionIntervals = _chooseDistributionIntervals(
credIntervals,
ledger.lastDistributionTimestamp(),
policy.maxSimultaneousDistributions
);
return distributionIntervals.map((endpoint) => {
// Recompute for every endpoint because the Ledger will be in a different state
// (wrt paid balances)
const accountsData = computeCredAccounts(ledger, view);
const distribution = computeDistribution(
policy.allocationPolicies,
accountsData,
endpoint
);
ledger.distributeGrain(distribution);
return distribution;
});
}
export function _chooseDistributionIntervals(
credIntervals: $ReadOnlyArray<TimestampMs>,
lastDistributionTimestamp: TimestampMs,
maxSimultaneousDistributions: number
): $ReadOnlyArray<TimestampMs> {
// Slice off the final interval--we may assume that it is not yet finished.
const completeIntervals = credIntervals.slice(0, credIntervals.length - 1);
const undistributedIntervals = completeIntervals.filter(
(i) => i > lastDistributionTimestamp
);
return undistributedIntervals.slice(
undistributedIntervals.length - maxSimultaneousDistributions,
undistributedIntervals.length
);
}
| 39.4125 | 83 | 0.754837 |
b9766250d1416ea4c5f7ca4bc505096af00fefba | 286 | js | JavaScript | src/shared/guard/userRouteGuard.js | SILINDATN-T05/move-app-react | 3433b0c52a3567835e0670437858ee707874a099 | [
"MIT"
] | null | null | null | src/shared/guard/userRouteGuard.js | SILINDATN-T05/move-app-react | 3433b0c52a3567835e0670437858ee707874a099 | [
"MIT"
] | null | null | null | src/shared/guard/userRouteGuard.js | SILINDATN-T05/move-app-react | 3433b0c52a3567835e0670437858ee707874a099 | [
"MIT"
] | null | null | null |
export class UserRouteGuard{
shouldRoute() {
// Sync API call here, and the final return value must be `map` to `boolean` if not
const resultFromSyncApiCall = sessionStorage.getItem('isLoggedIn') == 'true' ? true: false;
return resultFromSyncApiCall
}
} | 35.75 | 99 | 0.674825 |
b9766f9387e659cc64c1ae4c709881524dbe5c70 | 358 | js | JavaScript | docs/html/search/enumvalues_8.js | boingoing/panga | eef2aeef41d9d9954413352b243b078b2addbe67 | [
"MIT"
] | null | null | null | docs/html/search/enumvalues_8.js | boingoing/panga | eef2aeef41d9d9954413352b243b078b2addbe67 | [
"MIT"
] | null | null | null | docs/html/search/enumvalues_8.js | boingoing/panga | eef2aeef41d9d9954413352b243b078b2addbe67 | [
"MIT"
] | null | null | null | var searchData=
[
['tournament',['Tournament',['../classpanga_1_1GeneticAlgorithm.html#a3653afdb62876d5d18254dba4de27a6ea4f4dc29df9d29cbec61a725ff3ce6e72',1,'panga::GeneticAlgorithm']]],
['twopoint',['TwoPoint',['../classpanga_1_1GeneticAlgorithm.html#a121354609fbc300abfb96556935f4b35a331d16a2885c7f82ba949f286f48143d',1,'panga::GeneticAlgorithm']]]
];
| 59.666667 | 170 | 0.818436 |
b977671b3c6c9e6a136a6ede887cd4cf211d327b | 7,254 | js | JavaScript | moxy-conditions.js | dcmox/moxyscript-conditions | 0f716230e967d688549190b3e861790fe80d472d | [
"Apache-2.0"
] | null | null | null | moxy-conditions.js | dcmox/moxyscript-conditions | 0f716230e967d688549190b3e861790fe80d472d | [
"Apache-2.0"
] | null | null | null | moxy-conditions.js | dcmox/moxyscript-conditions | 0f716230e967d688549190b3e861790fe80d472d | [
"Apache-2.0"
] | null | null | null | "use strict";
exports.__esModule = true;
var fs = require('fs');
exports.opMap = {
eq: '===',
gt: '>',
gte: '>=',
lt: '<',
lte: '<=',
neq: '!=='
};
exports.funcMap = {
between: true,
len: 'length'
};
exports.opKeys = Object.keys(exports.opMap);
exports.funcKeys = Object.keys(exports.funcMap);
exports.REGEX_STRIP_UNSAFE_KEYS = /[^A-Z_a-z.-]/g;
/*
TODO: add expression parser?
* age eq value and residence eq house and registered between date1, date2
*/
exports.conditionsValidate = function (conditions) {
var ret = [];
var pass = true;
conditions.forEach(function (cond, index) {
var key = cond.key, operator = cond.operator, value = cond.value, valueB = cond.valueB;
var keyReplaced = key.replace(exports.REGEX_STRIP_UNSAFE_KEYS, '');
operator = operator.toLowerCase();
if (keyReplaced.length !== key.length) {
pass = false;
ret.push({ index: index, reason: 'Key contains unsafe character', valid: false });
return;
}
if (typeof value === 'string' && !value.indexOf('`')) {
pass = false;
ret.push({ index: index, reason: 'Value contains unsafe character', valid: false });
return;
}
// tslint:disable no-bitwise
if (~exports.opKeys.indexOf(operator)) {
if (typeof value === 'object') { // Date support
if (!value.hasOwnProperty('valueOf')) {
pass = false;
ret.push({ index: index, reason: 'Value can only be of type Date | string',
valid: false });
return;
}
}
else {
if (~['string', 'boolean'].indexOf(typeof value) && !~['eq', 'neq'].indexOf(operator)) {
pass = false;
ret.push({ index: index, reason: typeof value + " comparisons must only be eq | neq", valid: false });
return;
}
}
}
else if (~exports.funcKeys.indexOf(operator)) {
if (operator === 'between' && valueB) {
if (typeof value !== typeof valueB) {
pass = false;
ret.push({ index: index, reason: 'Both values must be of same type', valid: false });
return;
}
if (~['string', 'boolean'].indexOf(typeof value) || ~['string', 'boolean'].indexOf(typeof valueB)) {
pass = false;
ret.push({ index: index, reason: 'Between operator can only be used on Dates | numbers', valid: false });
return;
}
if (typeof value === 'object') { // Date support
if (!value.hasOwnProperty('valueOf')) {
pass = false;
ret.push({ index: index, reason: 'Value can only be of type Date | string', valid: false });
return;
}
}
}
}
else {
pass = false;
ret.push({ index: index, reason: 'Operator is not valid.', valid: false });
return;
}
ret.push({ index: index, valid: true });
});
return pass ? true : ret;
};
exports.conditionsToString = function (conditions) {
var evalString = '';
conditions.forEach(function (cond) {
var key = cond.key, operator = cond.operator, value = cond.value, valueB = cond.valueB;
key = key.replace(exports.REGEX_STRIP_UNSAFE_KEYS, '');
if (typeof value === 'string') {
value = '`' + value.replace(/`/g, '') + '`';
} // Prevents Injections
// tslint:disable no-bitwise
if (~exports.opKeys.indexOf(operator)) {
if (typeof value === 'object') { // Date support
evalString += "(new Date(item." + key + ".valueOf()) " + exports.opMap[operator] + " " + value.valueOf() + ") && ";
}
else {
evalString += "(item." + key + " " + exports.opMap[operator] + " " + value + ") && ";
}
}
else if (~exports.funcKeys.indexOf(operator)) {
if (operator === 'between' && valueB) {
if (typeof value === 'object') { // Date support
evalString += "(new Date(item." + key + ".valueOf()) >= " + value.valueOf() + " && new Date(item." + key + ".valueOf()) <= " + valueB.valueOf() + ") && ";
}
else {
evalString += "(item." + key + " >= " + value + " && item." + key + " <= " + valueB + ") && ";
}
}
}
});
return evalString.slice(0, evalString.length - 4);
};
exports.itemsMatchConditions = function (items, conditions) {
// tslint:disable-next-line: no-eval
return items.filter(function (item) { return eval(conditions); });
};
exports.itemsFailConditions = function (items, conditions) {
// tslint:disable-next-line: no-eval
return items.filter(function (item) { return !(eval(conditions)); });
};
var ConditionEditor = /** @class */ (function () {
function ConditionEditor(exportPath) {
this.exportPath = exportPath || '';
this._condMap = {};
if (this.exportPath) {
this.loadConditions(this.exportPath);
}
}
ConditionEditor.prototype.addCondition = function (name, conditions) {
if (this._condMap[name]) {
return false;
}
var validationResult = exports.conditionsValidate(conditions);
if (validationResult) {
this._condMap[name] = exports.conditionsToString(conditions);
}
else {
return validationResult;
}
return true;
};
ConditionEditor.prototype.getCondition = function (name) { return this._condMap[name] ? this._condMap[name] : false; };
ConditionEditor.prototype.runMatchCondition = function (name, data) {
return this._condMap[name] ? exports.itemsMatchConditions(data, this._condMap[name]) : false;
};
ConditionEditor.prototype.runFailCondition = function (name, data) {
return this._condMap[name] ? exports.itemsFailConditions(data, this._condMap[name]) : false;
};
ConditionEditor.prototype.saveConditions = function () {
if (this.exportPath === '' || this.exportPath.indexOf('.') === -1) {
return false;
}
fs.writeFile(this.exportPath, JSON.stringify(this._condMap, null, 2), function (err) {
if (err) {
throw new Error(err);
}
});
return true;
};
ConditionEditor.prototype.toJSON = function (prettify) {
if (prettify === void 0) { prettify = false; }
return prettify ? JSON.stringify(this._condMap, null, 2) : JSON.stringify(this._condMap);
};
ConditionEditor.prototype.loadConditions = function (path) {
if (!fs.existsSync(path)) {
return false;
}
this._condMap = JSON.parse(fs.readFileSync(path).toString());
return true;
};
return ConditionEditor;
}());
exports.ConditionEditor = ConditionEditor;
| 40.52514 | 174 | 0.529639 |
b9777b1e5d72a8da4d49b4130853d57c34498a76 | 327 | js | JavaScript | util/allowcrossorigin/background.js | dronus/VisSynthWeb | de6a04d505f299964ab5bd1c8151ba4915b672ec | [
"MIT"
] | 4 | 2015-12-31T14:30:01.000Z | 2021-12-27T09:22:45.000Z | util/allowcrossorigin/background.js | dronus/VisSynthWeb | de6a04d505f299964ab5bd1c8151ba4915b672ec | [
"MIT"
] | 15 | 2015-12-31T15:39:40.000Z | 2018-02-15T22:03:05.000Z | util/allowcrossorigin/background.js | dronus/VisSynthWeb | de6a04d505f299964ab5bd1c8151ba4915b672ec | [
"MIT"
] | 1 | 2015-12-31T14:41:00.000Z | 2015-12-31T14:41:00.000Z |
chrome.webRequest.onHeadersReceived.addListener(
function(info) {
var headers=info.responseHeaders;
headers.push({name:'Access-Control-Allow-Origin',value:'*'});
return {responseHeaders: headers};
},
// filters
{
urls: [
"*://*/*"
]
},
// extraInfoSpec
["blocking","responseHeaders"]);
| 20.4375 | 65 | 0.623853 |
b9779917f2501a92ecc42dbe5050158d31cb346f | 100 | js | JavaScript | JS-Advanced-Softuni/02.Arrays-Lab/sumFirstLast.js | borisboychev/SoftUni | 22062312f08e29a1d85377a6d41ef74966d37e99 | [
"MIT"
] | 1 | 2020-12-14T23:25:19.000Z | 2020-12-14T23:25:19.000Z | JS-Advanced-Softuni/02.Arrays-Lab/sumFirstLast.js | borisboychev/SoftUni | 22062312f08e29a1d85377a6d41ef74966d37e99 | [
"MIT"
] | null | null | null | JS-Advanced-Softuni/02.Arrays-Lab/sumFirstLast.js | borisboychev/SoftUni | 22062312f08e29a1d85377a6d41ef74966d37e99 | [
"MIT"
] | null | null | null | let sum = (arr) => console.log(Numbers(arr[0]) + Numbers(arr[arr.length - 1]));
sum([20, 30, 40]);
| 25 | 79 | 0.59 |
b978b85ef3dd776497080da8b4d7ee2058766b7e | 737 | js | JavaScript | WyFramework/Docs/html/class_game_framework_1_1_game_structure_1_1_game_1_1_editor_1_1_conditional_action_editor.js | nwy140/TheWYGameDevelopmentFramework | 5ab47b9dc2554a3d73e07d19a27a97969c9b6479 | [
"Apache-2.0"
] | null | null | null | WyFramework/Docs/html/class_game_framework_1_1_game_structure_1_1_game_1_1_editor_1_1_conditional_action_editor.js | nwy140/TheWYGameDevelopmentFramework | 5ab47b9dc2554a3d73e07d19a27a97969c9b6479 | [
"Apache-2.0"
] | 1 | 2019-06-24T03:04:20.000Z | 2019-06-24T03:04:20.000Z | WyFramework/Docs/html/class_game_framework_1_1_game_structure_1_1_game_1_1_editor_1_1_conditional_action_editor.js | nwy140/TheWYGameDevelopmentFramework | 5ab47b9dc2554a3d73e07d19a27a97969c9b6479 | [
"Apache-2.0"
] | null | null | null | var class_game_framework_1_1_game_structure_1_1_game_1_1_editor_1_1_conditional_action_editor =
[
[ "DrawGUI", "class_game_framework_1_1_game_structure_1_1_game_1_1_editor_1_1_conditional_action_editor.html#a63bd953662274f17a81f195e361e8a0c", null ],
[ "OnDisable", "class_game_framework_1_1_game_structure_1_1_game_1_1_editor_1_1_conditional_action_editor.html#aca212ccfbe2707f138f45be760ca9be4", null ],
[ "OnEnable", "class_game_framework_1_1_game_structure_1_1_game_1_1_editor_1_1_conditional_action_editor.html#a6c67ff3389ab2a7f730c2df4785a8326", null ],
[ "OnInspectorGUI", "class_game_framework_1_1_game_structure_1_1_game_1_1_editor_1_1_conditional_action_editor.html#a245bb250c213215785a70c5773e6f425", null ]
]; | 105.285714 | 162 | 0.881954 |
b97a6659b40c95063e53d5e92c2c9ddcb945245a | 1,804 | js | JavaScript | config_pg_storage.js | byudaniel/config-sync | 74f9d049a19e5128782495c09db808e7949f4fcf | [
"MIT"
] | null | null | null | config_pg_storage.js | byudaniel/config-sync | 74f9d049a19e5128782495c09db808e7949f4fcf | [
"MIT"
] | null | null | null | config_pg_storage.js | byudaniel/config-sync | 74f9d049a19e5128782495c09db808e7949f4fcf | [
"MIT"
] | null | null | null | class ConfigPgStorage {
#pgClient = null
#log = null
constructor({ pgClient, log = { error: console.error } }) {
this.#pgClient = pgClient
this.#log = log
}
#setFromRow = (row, configManager) => {
let scopeOpts = undefined
if (row.scopeKey && row.scopeValue) {
scopeOpts = {
[row.scopeKey]: row.scopeValue,
}
}
configManager.set(row.key, row.value, scopeOpts, {
silent: true,
})
}
async load(configManager) {
const res = await this.#pgClient.query(
'SELECT * FROM configuration_manager_values'
)
res.rows.forEach((row) => {
this.#setFromRow(row, configManager)
})
}
async loadFromStorage(key, configManager) {
const res = await this.#pgClient.query(
'SELECT * FROM configuration_manager_values WHERE key = $1',
[key]
)
res.rows.forEach((row) => this.#setFromRow(row, configManager))
}
async saveKey(key, value, scopeKey, scopeValue) {
try {
if (typeof value === 'undefined') {
await this.#pgClient.query(
'DELETE FROM configuration_manager_values WHERE key = $ AND scope_key = $',
[key, scopeKey]
)
} else {
await this.#pgClient.query(
'INSERT INTO configuration_manager_values(key, value, scope_key, scope_value, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $5) ON CONFLICT ON CONSTRAINT key_scope_key DO UPDATE SET value = $2, updated_at = $5',
[key, JSON.stringify(value), scopeKey, scopeValue, new Date()]
)
}
} catch (err) {
this.#log.error(
{ err, key, value, scopeKey, scopeValue },
'Unable to save configuration value'
)
throw new Error('Unable to save configuration value')
}
}
}
module.exports = ConfigPgStorage
| 27.333333 | 227 | 0.609756 |
b97be67d865e08263cd8f74572f5c2fd8465e1fd | 180 | js | JavaScript | js/dropdownselect.js | Dev-Ojash/ChatApp | fa8badb93ad476c26fe4347f3509b15c98ce9132 | [
"MIT"
] | null | null | null | js/dropdownselect.js | Dev-Ojash/ChatApp | fa8badb93ad476c26fe4347f3509b15c98ce9132 | [
"MIT"
] | null | null | null | js/dropdownselect.js | Dev-Ojash/ChatApp | fa8badb93ad476c26fe4347f3509b15c98ce9132 | [
"MIT"
] | null | null | null | $(function () {
$('#country').on('change', function() {
// $.ajax({url: "<?php echo base_url()?>getstate", data:{"country" : this.value}});
// alert( this.value );
});
})
| 16.363636 | 84 | 0.527778 |
b97d0b7b49e2c609bcd5dff5ab2a7a436ba7aa85 | 1,434 | js | JavaScript | src/components/Projects.js | davidleger95/gatsby-starter-netlify-cms | ee6d809d3dffb08c2cdd894bb81490582d8f1913 | [
"MIT"
] | null | null | null | src/components/Projects.js | davidleger95/gatsby-starter-netlify-cms | ee6d809d3dffb08c2cdd894bb81490582d8f1913 | [
"MIT"
] | 8 | 2021-03-09T04:14:01.000Z | 2022-02-26T10:59:27.000Z | src/components/Projects.js | davidleger95/gatsby-starter-netlify-cms | ee6d809d3dffb08c2cdd894bb81490582d8f1913 | [
"MIT"
] | null | null | null | import React from 'react';
import styled from 'styled-components';
const ProjectStyle = styled.li`
display: grid;
grid-gap: 1em;
& > * {
padding: 0;
margin: 0;
}
h3, .stack {
font-family: 'Roboto Mono', monospace;
font-weight: 400;
}
.stack {
font-size: 0.8em;
opacity: 0.7;
}
.links {
display: grid;
grid-auto-flow: column;
justify-content: start;
grid-gap: 1em;
font-size: 0.8em;
}
a {
color: inherit;
text-decoration: none;
display: block;
font-weight: 600;
}
a::before {
content: '> ';
}
a:hover, a::before {
color: ${props => props.theme.colors.accent};
}
`;
const Project = ({ title, stack, description, links: { demo, repo} }) => (
<ProjectStyle>
<h3>{title}</h3>
<p className="stack">{stack}</p>
<p>{description}</p>
<div className="links">
{demo && <a href={demo} target="_blank" rel="noopener noreferrer">Check it out!</a>}
{repo && <a href={repo} target="_blank" rel="noopener noreferrer">Repo</a>}
</div>
</ProjectStyle>
);
const ProjectsStyle = styled.ul`
list-style: none;
padding: 0;
margin: 0;
display: grid;
grid-gap: 2.5rem;
`;
const Projects = ({ projects }) => (
<div>
<h2>Some of my projects.</h2>
<ProjectsStyle>
{projects.map(project => <Project key={project.id} {...project} />)}
</ProjectsStyle>
</div>
);
export default Projects; | 19.12 | 90 | 0.58159 |
b97e4a770a688250a98cbd8c7602cd3d46d16c53 | 7,698 | js | JavaScript | src/components/Sections/styledSections.js | benehurp/quadfinancial-pwa | b27d947cc631c15c98108bda51c683b88ed8d489 | [
"0BSD"
] | null | null | null | src/components/Sections/styledSections.js | benehurp/quadfinancial-pwa | b27d947cc631c15c98108bda51c683b88ed8d489 | [
"0BSD"
] | 4 | 2022-01-28T01:33:05.000Z | 2022-02-01T01:07:44.000Z | src/components/Sections/styledSections.js | benehurp/quadfinancial-pwa | b27d947cc631c15c98108bda51c683b88ed8d489 | [
"0BSD"
] | null | null | null | import styled, { css } from "styled-components"
export const SectionsWrapper = styled.section`
hr {
width: 80%;
margin: 1.5rem 0;
background: ${({ theme }) => theme.colors.red};
height: 1px;
border: 0px;
}
grid-template-columns: ${({ theme }) => theme.breakingPoints.normal};
display: grid;
align-items: center;
${props =>
props.backgroundType === "color" &&
css`
background-color: ${props =>
props.backgroundColor
? ({ theme }) => theme.colors[props.backgroundColor]
: ({ theme }) => theme.colors.gray};
`}
${props =>
props.backgroundType === "gradient" &&
css`
background-image: linear-gradient(
${props => (props.gradientDeg ? props.gradientDeg : "94deg")},
${props =>
props.gradientColor1
? ({ theme }) => theme.colors[props.gradientColor1]
: ({ theme }) => theme.colors.red2}
${props => (props.gradientPercent1 ? props.gradientPercent1 : "15%")},
${props =>
props.gradientColor2
? ({ theme }) => theme.colors[props.gradientColor2]
: ({ theme }) => theme.colors.gray2}
${props => (props.gradientPercent2 ? props.gradientPercent2 : "125%")}
);
`}
${props =>
props.backgroundType === "image" &&
css`
background-image: url(${props => props.backgroundImage});
background-position: ${props =>
props.backgroundPosition ? props.backgroundPosition : "top left"};
background-repeat: no-repeat;
background-size: cover;
`}
padding: 10rem 5rem;
@media screen and (max-width: 620px) {
padding: 5rem 2rem;
}
`
export const CardGradientBase = styled.div`
width: ${props => (props.width ? props.width : "100%")};
height: auto;
display: flex;
padding: 5rem;
align-items: center;
background-image: linear-gradient(
${props => (props.gradientDeg ? props.gradientDeg : "221deg")},
${props =>
props.gradientColor1
? ({ theme }) => theme.colors[props.gradientColor1]
: ({ theme }) => theme.colors.gray4}
${props => (props.gradientPercent1 ? props.gradientPercent1 : "0%")},
${props =>
props.gradientColor2
? ({ theme }) => theme.colors[props.gradientColor2]
: ({ theme }) => theme.colors.gray3}
${props => (props.gradientPercent2 ? props.gradientPercent2 : "90%")}
);
border-radius: ${props => (props.borderRadius ? props.borderRadius : "2rem")};
box-sizing: border-box;
&:hover {
filter: drop-shadow(3px 5px 20px #141414);
}
`
export const SectionsH1 = styled.h1`
width: ${props => (props.width ? props.width : "100%")};
text-align: ${props => (props.textAlign ? props.textAlign : "left")};
font-size: ${({ theme }) => theme.font.size.xxextra};
font-weight: ${({ theme }) => theme.font.weight.extrabold};
text-transform: uppercase;
line-height: 10rem;
letter-spacing: -5px;
& > span {
color: ${({ theme }) => theme.colors.red};
}
& + p {
margin-top: 2rem;
}
@media screen and (max-width: 520px) {
font-size: calc(${({ theme }) => theme.font.size.xxextra} * 0.4);
line-height: 4.5rem;
}
@media screen and (min-width: 520px) and (max-width: 690px) {
font-size: calc(${({ theme }) => theme.font.size.xxextra} * 0.6);
line-height: 6rem;
}
@media screen and (min-width: 690px) and (max-width: 1023px) {
font-size: calc(${({ theme }) => theme.font.size.xxextra} * 0.8);
line-height: 8rem;
}
`
export const SectionsH2 = styled.h2`
width: ${props => (props.width ? props.width : "100%")};
text-align: ${props => (props.textAlign ? props.textAlign : "left")};
font-size: ${({ theme }) => theme.font.size.xextra};
font-weight: ${({ theme }) => theme.font.weight.extrabold};
text-transform: uppercase;
line-height: 6rem;
letter-spacing: -3px;
& > span {
color: ${({ theme }) => theme.colors.red};
}
& + p {
margin-top: 2rem;
}
@media screen and (max-width: 376px) {
font-size: calc(${({ theme }) => theme.font.size.xextra} * 0.6);
line-height: 4rem;
}
@media screen and (min-width: 376px) and (max-width: 1023px) {
font-size: calc(${({ theme }) => theme.font.size.xextra} * 0.8);
line-height: 5rem;
}
`
export const SectionsH3 = styled.h3`
width: ${props => (props.width ? props.width : "100%")};
text-align: ${props => (props.textAlign ? props.textAlign : "left")};
font-size: ${({ theme }) => theme.font.size.extra};
font-weight: ${({ theme }) => theme.font.weight.extrabold};
text-transform: uppercase;
line-height: 4rem;
letter-spacing: -1px;
& > span {
color: ${({ theme }) => theme.colors.red};
}
& + p {
margin-top: 2rem;
}
@media screen and (max-width: 376px) {
font-size: calc(${({ theme }) => theme.font.size.extra} * 0.6);
line-height: 2.8rem;
}
@media screen and (min-width: 376px) and (max-width: 1023px) {
font-size: calc(${({ theme }) => theme.font.size.extra} * 0.8);
line-height: 3.4rem;
}
`
export const SectionsH4 = styled.h4`
width: ${props => (props.width ? props.width : "100%")};
text-align: ${props => (props.textAlign ? props.textAlign : "left")};
font-size: ${({ theme }) => theme.font.size.xxlarge};
font-weight: ${({ theme }) => theme.font.weight.extrabold};
text-transform: uppercase;
line-height: 3.4rem;
letter-spacing: 0px;
& > span {
color: ${({ theme }) => theme.colors.red};
}
& + p {
margin-top: 2rem;
}
@media screen and (max-width: 376px) {
font-size: calc(${({ theme }) => theme.font.size.xxlarge} * 0.6);
line-height: 2.6rem;
}
@media screen and (min-width: 376px) and (max-width: 1023px) {
font-size: calc(${({ theme }) => theme.font.size.xxlarge} * 0.8);
line-height: 3rem;
}
`
export const SectionsH5 = styled.h5`
width: ${props => (props.width ? props.width : "100%")};
text-align: ${props => (props.textAlign ? props.textAlign : "left")};
font-size: ${({ theme }) => theme.font.size.xlarge};
font-weight: ${({ theme }) => theme.font.weight.extrabold};
text-transform: uppercase;
line-height: 3.2rem;
letter-spacing: 0px;
& > span {
color: ${({ theme }) => theme.colors.red};
}
& + p {
margin-top: 2rem;
}
@media screen and (max-width: 376px) {
font-size: calc(${({ theme }) => theme.font.size.xlarge} * 0.6);
line-height: 2.4rem;
}
@media screen and (min-width: 376px) and (max-width: 1023px) {
font-size: calc(${({ theme }) => theme.font.size.xlarge} * 0.8);
line-height: 2.8rem;
}
`
export const SectionsH6 = styled.h6`
width: ${props => (props.width ? props.width : "100%")};
text-align: ${props => (props.textAlign ? props.textAlign : "left")};
font-size: ${({ theme }) => theme.font.size.medium};
font-weight: ${props =>
props.fontWeight
? ({ theme }) => theme.font.weight[props.fontWeight]
: ({ theme }) => theme.font.weight.extrabold};
text-transform: uppercase;
line-height: 2.4rem;
letter-spacing: 0px;
& > span {
color: ${({ theme }) => theme.colors.red};
}
& + p {
margin-top: ${props => (props.marginTop ? props.marginTop : "2rem")};
}
`
export const SectionsP = styled.p`
width: ${props => (props.width ? props.width : "100%")};
text-transform: ${props =>
props.textTransform ? props.textTransform : "none"};
text-align: ${props => (props.textAlign ? props.textAlign : "left")};
font-size: ${props =>
props.fontSize
? ({ theme }) => theme.font.size[props.fontSize]
: ({ theme }) => theme.font.size.small};
& + div {
margin-top: ${props => (props.marginTop ? props.marginTop : "2rem")};
}
`
| 30.669323 | 80 | 0.587295 |