commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
---|---|---|---|---|---|---|---|
294a9e925d70aef06e21441dfec03a57346d219e
|
add infra catalog
|
src/components/NaviMenu/ChildrenMenu/Catalog.js
|
src/components/NaviMenu/ChildrenMenu/Catalog.js
|
/*
*
* NaviMenu
*
*/
import React, { useState } from 'react'
// import T from 'prop-types'
import { buildLog } from '@utils'
import { ICON_CMD } from '@config'
import { SpaceGrow } from '@components/BaseStyled'
import ChildrenItems from './ChildrenItems'
import { Wrapper, Item, Icon } from '../styles/children_menu/catalog'
/* eslint-disable-next-line */
const log = buildLog('c:NaviMenu:index')
const menu = [
{
id: '0',
title: '开发效率',
icon: `${ICON_CMD}/navi_fire.svg`,
children: [
{
id: '101',
title: '全部',
icon: `${ICON_CMD}/navi_china.svg`,
},
{
id: '102',
title: '项目管理',
icon: `${ICON_CMD}/navi_china.svg`,
},
{
id: '103',
title: 'GTD 工具',
icon: `${ICON_CMD}/navi_china.svg`,
},
{
id: '104',
title: '写作 / 笔记',
icon: `${ICON_CMD}/navi_china.svg`,
},
// {
// id: '105',
// title: '建站平台',
// icon: `${ICON_CMD}/navi_china.svg`,
// }, --> 云服务
{
id: '106',
title: '隐私安全',
icon: `${ICON_CMD}/navi_china.svg`,
},
],
},
{
id: '101',
title: '设计工具',
icon: `${ICON_CMD}/navi_china.svg`,
},
{
id: '102',
title: '云服务',
icon: `${ICON_CMD}/navi_fire.svg`,
},
{
id: '12',
title: '公共数据',
icon: `${ICON_CMD}/navi_group.svg`,
},
{
// 非 IT,设计类的网站
id: '103',
title: '创投服务',
icon: `${ICON_CMD}/navi_china.svg`,
},
{
id: '14',
title: '数据可视化',
icon: `${ICON_CMD}/navi_china.svg`,
},
{
id: '15',
title: '运营分析',
icon: `${ICON_CMD}/navi_china.svg`,
},
{
id: '16',
title: '多媒体',
icon: `${ICON_CMD}/navi_china.svg`,
},
// {
// id: '17',
// title: '视频相关',
// icon: `${ICON_CMD}/navi_china.svg`,
// },
]
/* <ActiveDot /> */
const Catalog = () => {
const [activeMenuId, setActiveMenuId] = useState(null)
return (
<Wrapper>
{menu.map(item => (
<div key={item.id}>
<Item
active={item.id === '0'}
onClick={() => setActiveMenuId(item.id)}
>
<Icon active={item.id === '0'} src={item.icon} />
<SpaceGrow />
{item.title}
</Item>
{item.children && (
<ChildrenItems
activeMenuId={activeMenuId}
parentId={item.id}
items={item.children}
itemOnClick={id => {
console.log('click child item d: ', id)
}}
/>
)}
</div>
))}
</Wrapper>
)
}
Catalog.propTypes = {
// goBack: T.func.isRequired,
}
Catalog.defaultProps = {}
export default React.memo(Catalog)
|
JavaScript
| 0.000001 |
@@ -1242,32 +1242,444 @@
.svg%60,%0A %7D,%0A %7B%0A
+ id: '108',%0A title: '%E5%9F%BA%E7%A1%80%E8%AE%BE%E6%96%BD',%0A icon: %60$%7BICON_CMD%7D/navi_fire.svg%60,%0A children: %5B%0A %7B%0A id: '101',%0A title: '%E5%85%A8%E9%83%A8',%0A icon: %60$%7BICON_CMD%7D/navi_china.svg%60,%0A %7D,%0A %7B%0A id: '102',%0A title: '%E6%95%B0%E6%8D%AE%E5%BA%93',%0A icon: %60$%7BICON_CMD%7D/navi_china.svg%60,%0A %7D,%0A %7B%0A id: '103',%0A title: '%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F ',%0A icon: %60$%7BICON_CMD%7D/navi_china.svg%60,%0A %7D,%0A %5D,%0A %7D,%0A %7B%0A
id: '102',%0A
|
0aa076f79988be8029a9c2d008156f91194935a4
|
Update index.js
|
js/index.js
|
js/index.js
|
$.getJSON("assets/english.json", function(data){
var treasures = data.treasures;
$(document).ready(function(){
for (var treasure in treasures)
{
console.log(treasure);
opt = $('<option/>', {value: treasure.id, text: treasure.name});
$('#select-item').append(opt);
}
});
});
|
JavaScript
| 0.000002 |
@@ -121,24 +121,17 @@
or (var
-treasure
+i
in trea
@@ -147,37 +147,8 @@
%7B%0A
- console.log(treasure);%0A
@@ -186,16 +186,20 @@
treasure
+s%5Bi%5D
.id, tex
@@ -209,16 +209,20 @@
treasure
+s%5Bi%5D
.name%7D);
|
2885d4b1a03b2ee9feee603cde947ba66abea734
|
add more error handling to handlebars task
|
lib/tasks/handlebars.js
|
lib/tasks/handlebars.js
|
"use strict";
var assemble = require('assemble');
var runSequence = require('run-sequence').use(assemble);
var extname = require('gulp-extname');
var controller = require('../assemble/plugins/controller.js');
var errorHandler = require('../assemble/plugins/error');
var livereload = require('gulp-livereload');
var taskGenerator = require('../taskGenerator');
var upath = require('upath');
module.exports = function(name, config, server) {
return taskGenerator(name, config, server, function(taskName, task) {
assemble.option("assets", config.assets);
assemble.task(taskName, function() {
assemble.layouts(config.layouts);
assemble.partials(config.partials);
if(task.data) {
assemble.data(task.data.src, {
namespace: function(filename, options) {
return upath.relative(options.cwd, filename).replace(upath.extname(filename), '');
},
cwd: process.cwd() + '/' + task.data.cwd
});
}
return assemble.src(task.files.src, getData(task.layout, config.scripts, server))
.on('error', errorHandler)
.pipe(extname())
.pipe(assemble.dest(task.files.dest))
.pipe(controller.collect());
});
}, function(config, tasks, cb) {
controller.reset();
runSequence.call(null, tasks, function() {
controller.createRegistry(cb);
livereload.changed('all');
});
});
};
function getData(layout, scripts, server) {
return {
layout: layout,
server: server,
scripts: scripts
};
}
|
JavaScript
| 0 |
@@ -1230,16 +1230,59 @@
name())%0A
+ .on('error', errorHandler)%0A
@@ -1348,33 +1348,119 @@
.
-pipe(controller.collect()
+on('error', errorHandler)%0A .pipe(controller.collect())%0A .on('error', errorHandler
);%0A
|
dfac3e5ee543f2a7e3e033672a589aa49e1569ba
|
remove redundant comment
|
src/openlmis-form/openlmis-datepicker.directive.js
|
src/openlmis-form/openlmis-datepicker.directive.js
|
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should have received a copy of
* the GNU Affero General Public License along with this program. If not, see
* http://www.gnu.org/licenses. For additional information contact [email protected].
*/
(function() {
'use strict';
/**
* @ngdoc directive
* @restrict E
* @name openlmis-form.directive:openlmisDatepicker
*
* @description
* Directive allows to add date picker input.
*
* @example
* To make this directive work only 'value' attribute is required, however there are more attributes to use.
* In order to make datepicker input use id you can add 'input-id' attribute.
* The 'change-method' attribute takes function that will be executed after datepicker value change.
* Datepicker directive also can take max-date and min-date attributes. Their values can be set from other datepickers or manually.
* ```
* <openlmis-datepicker
* value="startDate"
* input-id="datepicker-id"
* change-method="afterChange()"
* min-date="10/05/2016"
* max-date="endDate">
* </openlmis-datepicker>
*
* <openlmis-datepicker
* value="endDate">
* </openlmis-datepicker>
* ```
*/
angular
.module('openlmis-form')
.directive('openlmisDatepicker', datepicker);
datepicker.$inject = ['$filter', 'jQuery', 'messageService', 'DEFAULT_DATE_FORMAT', 'DEFAULT_DATEPICKER_FORMAT'];
function datepicker($filter, jQuery, messageService, DEFAULT_DATE_FORMAT, DEFAULT_DATEPICKER_FORMAT) {
return {
restrict: 'E',
scope: {
value: '=',
inputId: '@?',
minDate: '=?',
maxDate: '=?',
changeMethod: '=?',
dateFormat: '=?',
language: '=?',
required: '=?'
},
templateUrl: 'openlmis-form/openlmis-datepicker.html',
link: link
};
function link(scope, element, attrs, modelCtrl) {
setupFormatting(scope);
if (scope.value) {
// Populate initial value, if passed to directive
scope.dateString = $filter('openlmisDate')(scope.value);
}
scope.$watch('dateString', function() {
var date = element.find('input').datepicker('getUTCDate');
if (!date && scope.value) {
date = scope.value;
}
scope.value = date ? date : undefined;
if (scope.changeMethod && scope.changeMethod instanceof Function) {
scope.changeMethod();
}
});
scope.$watch('value', function() {
// Necessary if scope.value changed, angular.copy will prevent from digest dateString
var dateString = $filter('openlmisDate')(scope.value);
if (dateString !== scope.dateString) {
scope.dateString = dateString;
}
});
}
function setupFormatting(scope) {
scope.language = messageService.getCurrentLocale();
scope.dateFormat = angular.isDefined(scope.dateFormat) ? scope.dateFormat : DEFAULT_DATEPICKER_FORMAT;
var datepickerSettings = jQuery.fn.datepicker.dates;
if (!datepickerSettings[scope.language]) {
// We explicitly pass titleFormat, because datepicker doesn't apply it automatically
// for each language, while this property is required.
var localization = getDatepickerLabels();
localization.titleFormat = "MM yyyy";
datepickerSettings[scope.language] = localization;
}
}
function getDatepickerLabels() {
var labels = {
months: [],
monthsShort: [],
days: [],
daysShort: [],
daysMin: [],
today: messageService.get('openlmisForm.datepicker.today'),
clear: messageService.get('openlmisForm.datepicker.clear')
};
for (var i = 1; i <= 12; i++) {
var longKey = 'openlmisForm.datepicker.monthNames.long.' + i;
labels.months.push(messageService.get(longKey));
var shortKey = 'openlmisForm.datepicker.monthNames.short.' + i;
labels.monthsShort.push(messageService.get(shortKey));
}
for (var i = 1; i <= 7; i++) {
var longKey = 'openlmisForm.datepicker.dayNames.long.' + i;
labels.days.push(messageService.get(longKey));
var shortKey = 'openlmisForm.datepicker.dayNames.short.' + i;
labels.daysShort.push(messageService.get(shortKey));
var minKey = 'openlmisForm.datepicker.dayNames.min.' + i;
labels.daysMin.push(messageService.get(minKey));
}
return labels;
}
}
})();
|
JavaScript
| 0.000002 |
@@ -3468,110 +3468,8 @@
) %7B%0A
- // Necessary if scope.value changed, angular.copy will prevent from digest dateString%0A
|
812bc271cde30433b6beb23b7430c6ccd2b5dd09
|
fix edit task title bug
|
public/javascripts/angular/controllers.js
|
public/javascripts/angular/controllers.js
|
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
function findArrayIndex(array, id){
var index = -1;
var len = array.length;
for(var i=0; i<len; i++){
if (id == array[i].id){
index = i;
break;
}
}
return index;
}
function ProjectListCtrl($scope, Project) {
$scope.projects = {};
Project.query(function(json){
if(json.stat == 'ok')
{
json.projects.forEach(function(project){
$scope.projects[project.id] = project;
});
}
});
$scope.newProject = new Project();
$scope.orderProp = '-id';
$scope.save = function() {
var post_data = {title: $scope.newProject.title};
alert(post_data.title);
Project.save(post_data, function(json) {
if(json.stat == 'ok'){
hide("projectForm");
$scope.projects[json.project.id] = json.project;
$scope.newProject = new Project();
}
});
};
$scope.delete = function(id){
Project.remove({id:id}, function(json){
if(json.stat == 'ok'){
delete $scope.projects[json.project.id];
}
});
};
}
function UserListCtrl($scope, User) {
}
function ProjectDetailCtrl($scope, $http, $location, $routeParams, Project, TaskList, Task) {
$scope.orderProp = 'id';
Project.get({id: $routeParams.projectId}, function(json) {
$scope.model = json;
$scope.projectId = $routeParams.projectId;
$scope.newTasklist = new TaskList();
$scope.project = json.project;
$scope.tasks = {};
$scope.tasklists = [];
for(var k in json.tasklists){
var v = json.tasklists[k];
$scope.tasklists.push(json.tasklists[k]);
}
});
$scope.saveTaskList = function(){
var post_data = {title: $scope.newTasklist.title,
projectId: $scope.projectId};
if($scope.newTasklist.title==undefined){
return;
}
TaskList.save(post_data, function(json){
if(json.stat == "ok")
{
hide("tasklistForm");
// $scope.tasklists[json.tasklist.id] = json.tasklist;
$scope.tasklists.push(json.tasklist);
}
});
};
}
function TaskListDetailCtrl($scope, $routeParams, TaskList, Task) {
TaskList.get({projectId: $routeParams.projectId, tasklistId: $routeParams.tasklistId}, function(json) {
if(json.stat == 'ok'){
$scope.tasklist = json.tasklist;
$scope.project = json.project;
}else{
}
});
}
function TaskDetailCtrl($scope, $routeParams, Task) {
Task.get({projectId: $routeParams.projectId, taskId: $routeParams.taskId}, function(json) {
if(json.stat == 'ok'){
$scope.project = json.project;
$scope.task = json.task;
}else{
}
});
}
function TasklistTemplateCtrl($scope, $http, $routeParams, Task){
$scope.newTask = new Task();
$scope.taskSave = function(){
var post_data = {title: $scope.newTask.title,
projectId: $scope.project.id, tasklistId: $scope.tasklist.id };
if($scope.newTask.title==undefined){
return;
}
Task.save(post_data, function(json){
if(json.stat == "ok"){
$scope.newTask = new Task();
hide("taskForm"+$scope.tasklist.id);
if($scope.tasklist.tasks == undefined){
$scope.tasklist.tasks = [json.task];
}else
{
$scope.tasklist.tasks.push(json.task);
}
}
});
};
$scope.tasklistDelete = function(){
var r=confirm("Are you sure you want to delete this tasklist?");
if (r!=true)
{
return;
}
var tasklistId = $scope.tasklist.id;
var projectId = $scope.project.id;
$http({method: 'DELETE', url: "/tasklists/"+$scope.tasklist.id, data:{projectId: $scope.project.id}}).
success(function(json, status) {
if(json.stat == "ok"){
if($scope.tasklists == null){
window.location = "#/projects/"+projectId;
}
else{
var tls = $scope.tasklists;
var index = findArrayIndex(tls, $scope.tasklist.id);
if (index != -1){
Array.remove(tls, index);
}
}
}
}).
error(function(json, status) {
});
};
$scope.tasklistUpdate = function(){
var title = $scope.title;
$http({method: 'PUT', url: "/tasklists/"+$scope.tasklist.id, data: {title: $scope.title, projectId: $scope.tasklist.projectId}}).
success(function(json, status) {
if(json.stat == "ok"){
$scope.tasklist.title = $scope.title;
hide("tasklistEditForm"+$scope.tasklist.id);
}
}).
error(function(json, status) {
});
};
}
function TaskTemplateCtrl($scope, $http, $routeParams, Task){
$scope.taskDone = function(task){
$http({method: 'PUT', url: "/tasks/"+task.id, data: {projectId: $scope.project.id, status: task.status}}).
success(function(data, status) {
if(data.stat == "ok"){
}
}).
error(function(data, status) {
});
};
$scope.taskDelete = function(){
var r=confirm("Are you sure you want to delete this task?");
if (r!=true)
{
return;
}
var tasklistId = $scope.task.tasklistId;
var taskId = $scope.task.id;
var projectId = $scope.task.id;
$http({method: 'DELETE', url: "/tasks/"+taskId, data:{projectId: projectId}}).
success(function(json, status) {
if(json.stat == "ok"){
if($scope.tasklist == null){
window.location = "#/projects/"+$scope.project.id+"/tasklists/"+tasklistId;
}
else{
var tls = $scope.tasklist;
var index = findArrayIndex(tls.tasks, taskId);
if (index != -1){
Array.remove(tls.tasks, index);
}
}
}
}).
error(function(json, status) {
});
};
$scope.taskUpdate = function(task){
var title = $scope.title;
alert($scope.title);
if(title == "" || title == null){
return;
}
$http({method: 'PUT', url: "/tasks/"+task.id, data: {title: title, projectId:task.projectId, tasklistId: task.tasklistId}}).
success(function(json, status) {
if(json.stat == "ok"){
$scope.task.title = $scope.oldtitle;
hide("taskEditForm"+$scope.task.id);
}
}).
error(function(json, status) {
});
};
}
|
JavaScript
| 0.000001 |
@@ -6236,35 +6236,8 @@
le;%0A
- alert($scope.title);%0A
@@ -6545,11 +6545,8 @@
ope.
-old
titl
|
843141c6c8690dcc48c2067cc52f0e63ad136b44
|
make correct hashIntPair + add unhash
|
core/hashNumberPair.js
|
core/hashNumberPair.js
|
'use strict';
// http://stackoverflow.com/a/13871379
export function hashUIntPair(a, b) {
return a >= b ? a * a + a + b : a + b * b;
}
export function hashIntPair(a, b) {
var A = (a >= 0 ? 2 * a : -2 * a - 1);
var B = (b >= 0 ? 2 * b : -2 * b - 1);
var C = ((A >= B ? A * A + A + B : A + B * B) / 2);
return a < 0 && b < 0 || a >= 0 && b >= 0 ? C : -C - 1;
}
|
JavaScript
| 0.000171 |
@@ -97,17 +97,20 @@
urn
+(
a %3E= b
+)
?
+(
a *
@@ -122,21 +122,276 @@
+ b
+)
:
-a + b * b;
+(b * b + a);%0A%7D%0A%0Aexport function unhashUIntPair(n) %7B%0A let x = Math.sqrt(n) %7C 0; // x = a %3C b ? b : a%0A let r = n - x * x; // r = a %3C b ? a : a+b%0A if (r %3C x) %7B // r = a, x = b, a %3C b%0A return %5Br, x%5D;%0A %7D else %7B // r = a+b, x = a%0A return %5Bx, r - x%5D;%0A %7D
%0A%7D%0A%0A
@@ -432,17 +432,16 @@
%7B%0A
-var
+let
A =
-(
a %3E=
@@ -467,22 +467,20 @@
- 1
-)
;%0A
-var
+let
B =
-(
b %3E=
@@ -506,32 +506,32 @@
- 1
-)
;%0A
-var
+let
C =
-(
(A %3E= B
+)
?
+(
A *
@@ -543,84 +543,1207 @@
+ B
+)
:
-A + B * B) / 2);%0A return a %3C 0 && b %3C 0 %7C%7C a %3E= 0 && b %3E= 0 ? C : -C - 1;%0A%7D
+(B * B + A);%0A return (C & 1) ? -(C - 1) / 2 - 1 : C / 2;%0A%7D%0A%0Aexport function unhashIntPair(n) %7B%0A let C = n %3E= 0 ? n * 2 : (-(n + 1) * 2 + 1);%0A let %5BA, B%5D = unhashUIntPair(C);%0A let a = (A & 1) ? -(A + 1) / 2 : A / 2;%0A let b = (B & 1) ? -(B + 1) / 2 : B / 2;%0A return %5Ba, b%5D;%0A%7D%0A%0A// import assert from 'assert';%0A// let n;%0A// for (let i = 0; i %3C 10; i++) %7B%0A// for (let j = 0; j %3C 10; j++) %7B%0A// n = hashIntPair(i, j);%0A// let %5Bi_, j_%5D = unhashIntPair(n);%0A// assert.equal(i, i_);%0A// assert.equal(j, j_);%0A// if (i !== 0) %7B%0A// n = hashIntPair(-i, j);%0A// let %5Bi_, j_%5D = unhashIntPair(n);%0A// assert.equal(-i, i_);%0A// assert.equal(j, j_);%0A// %7D%0A// if (j !== 0) %7B%0A// n = hashIntPair(i, -j);%0A// let %5Bi_, j_%5D = unhashIntPair(n);%0A// assert.equal(i, i_);%0A// assert.equal(-j, j_);%0A// %7D%0A// if (i !== 0 && j !== 0) %7B%0A// n = hashIntPair(-i, -j);%0A// let %5Bi_, j_%5D = unhashIntPair(n);%0A// assert.equal(-i, i_);%0A// assert.equal(-j, j_);%0A// %7D%0A// %7D%0A// assert.equal(i, hashIntPair(...unhashIntPair(i)))%0A// assert.equal(-i, hashIntPair(...unhashIntPair(-i)))%0A// %7D%0A// console.log('passed')%0A// assert(false)
%0A
|
1c99de43fbb279e844f3e3da3508b1e44ebeb54e
|
Remove enableAgent config
|
lib/config/config.js
|
lib/config/config.js
|
/**
* default config
*/
module.exports = {
port: 8360, // server port
// host: '127.0.0.1', // server host
workers: 0, // server workers num, if value is 0 then get cpus num
stickyCluster: false, // sticky cluster
createServer: undefined, // create server function
startServerTimeout: 3000, // before start server time
reloadSignal: 'SIGUSR2', // reload process signal
onUnhandledRejection: err => think.logger.error(err), // unhandledRejection handle
onUncaughtException: err => think.logger.error(err), // uncaughtException handle
processKillTimeout: 10 * 1000, // process kill timeout, default is 10s
enableAgent: false, // enable agent worker
jsonpCallbackField: 'callback', // jsonp callback field
jsonContentType: 'application/json', // json content type
errnoField: 'errno', // errno field
errmsgField: 'errmsg', // errmsg field
defaultErrno: 1000, // default errno
validateDefaultErrno: 1001 // validate default errno
};
|
JavaScript
| 0.000001 |
@@ -623,53 +623,8 @@
10s%0A
- enableAgent: false, // enable agent worker%0A
js
|
abf86fcceb17cd308c1c6c6a6751bbe86cd28d17
|
Move add and remove layer into functions
|
lib/tileLayerManager.js
|
lib/tileLayerManager.js
|
'use strict';
var EventEmitter = require('events').EventEmitter
var moment = require('moment')
var assert = require('assert')
function nowIsWithin(on, off) {
if (!on || !off) return false
on = on.split(':')
off = off.split(':')
var now = moment()
var start = moment()
start.hour(on[0])
start.minute(on[1])
var end = moment()
end.hour(off[0])
end.minute(off[1])
if (now >= start && now <= end) return true
return false
}
class TileLayerManager extends EventEmitter {
constructor(config) {
this.config = config
this.layers = new Map()
this.interval = null
}
emitLayers() {
Object.keys(this.config).forEach((key) => {
var config = this.config[key]
if (config.time && !nowIsWithin(config.time.on, config.time.off)) {
//if theres some reason to add a layer
//either theres no time set
//or theres time set and time matches now
if (!!this.layers.get(key)) {
this.emit('remove', key)
this.layers.set(key, false)
}
} else {
//if theres some reason to remove a layer
//time must be set and time does not match now
if (!this.layers.get(key)) {
this.emit('add', key, this.config[key])
this.layers.set(key, true)
}
}
}, this)
}
start() {
this.interval = setInterval(() => {
this.emitLayers()
}, 1000 * 60)
this.emitLayers()
}
stop() {
clearTimeout(this.interval)
}
}
module.exports = (config) => {
assert.equal(typeof(config), 'object', 'tilelayer `config` must be an object')
assert.ok(Object.keys(config).length > 0, 'tilelayer `config` must specify at least 1 tilelayer')
Object.keys(config).forEach((key) => {
assert(!!config[key].url, 'tilelayer ' + key + ' must specify a url property')
})
return new TileLayerManager(config)
}
|
JavaScript
| 0 |
@@ -798,141 +798,129 @@
-//if theres some reason to add a layer%0A //either theres no time set%0A //or theres time set and time matches now%0A
+this.removeLayer(key)%0A %7D else %7B%0A this.addLayer(key)%0A %7D%0A %7D, this)%0A %7D%0A%0A removeLayer(layerName) %7B%0A
-
if (
@@ -929,35 +929,41 @@
this.layers.get(
-key
+layerName
)) %7B%0A t
@@ -949,36 +949,32 @@
rName)) %7B%0A
-
-
this.emit('remov
@@ -977,25 +977,27 @@
emove',
-key)%0A
+layerName)%0A
th
@@ -1010,19 +1010,25 @@
ers.set(
-key
+layerName
, false)
@@ -1036,138 +1036,39 @@
- %7D%0A %7D else %7B%0A //if theres some reason to remove a layer%0A //time must be set and time does not match now%0A
+%7D%0A %7D%0A%0A addLayer(layerName) %7B%0A
@@ -1092,20 +1092,22 @@
get(
-key
+layerName
)) %7B%0A
-
@@ -1125,19 +1125,25 @@
('add',
-key
+layerName
, this.c
@@ -1152,18 +1152,20 @@
fig%5B
-key%5D)%0A
+layerName%5D)%0A
@@ -1182,19 +1182,25 @@
ers.set(
-key
+layerName
, true)%0A
@@ -1207,34 +1207,9 @@
-
- %7D%0A %7D%0A %7D, this)
+%7D
%0A %7D
|
8c7dc9e602cc3730a4ca5d6ff3c7200ef5540a5f
|
Add update Patient selector query for patient history
|
src/selectors/patient.js
|
src/selectors/patient.js
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import { UIDatabase } from '../database';
import { sortDataBy } from '../utilities';
export const selectPatientHistory = ({ patient }) => {
const { currentPatient } = patient;
const { transactions } = currentPatient;
// Create a query string `transaction.id == "{id} OR transaction.id == "{id}" ...`
// finding all transaction batches for the patient.
const queryString = transactions.map(({ id }) => `transaction.id == "${id}"`).join(' OR ');
return queryString ? UIDatabase.objects('TransactionBatch').filtered(queryString) : [];
};
export const selectSortedPatientHistory = ({ patient }) => {
const { sortKey, isAscending } = patient;
const patientHistory = selectPatientHistory({ patient });
return patientHistory ? sortDataBy(patientHistory.slice(), sortKey, isAscending) : patientHistory;
};
export const selectCurrentPatient = ({ patient }) => {
const { currentPatient } = patient;
return currentPatient;
};
export const selectPatientName = ({ patient }) => {
const currentPatient = selectCurrentPatient({ patient });
return `${currentPatient?.firstName} ${currentPatient?.lastName}`.trim();
};
export const selectAvailableCredit = ({ patient }) => patient?.currentPatient?.availableCredit;
|
JavaScript
| 0 |
@@ -444,16 +444,20 @@
tring =
+%60($%7B
transact
@@ -460,16 +460,21 @@
sactions
+%0A
.map((%7B
@@ -510,16 +510,21 @@
$%7Bid%7D%22%60)
+%0A
.join('
@@ -528,16 +528,41 @@
(' OR ')
+%7D) AND type != %22cash_in%22%60
;%0A retu
|
80d4630fcc293ddbf0600a3f96cd9584394d7bdf
|
check mqtt.retain env var bolean value
|
lib/configService.js
|
lib/configService.js
|
/*
* Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of iotagent-json
*
* iotagent-json is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* iotagent-json is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with iotagent-json.
* If not, seehttp://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with::[[email protected]]
*/
'use strict';
var config = {},
logger = require('logops');
function anyIsSet(variableSet) {
for (var i = 0; i < variableSet.length; i++) {
if (process.env[variableSet[i]]) {
return true;
}
}
return false;
}
function processEnvironmentVariables() {
var environmentVariables = [
'IOTA_MQTT_HOST',
'IOTA_MQTT_PORT',
'IOTA_MQTT_USERNAME',
'IOTA_MQTT_PASSWORD',
'IOTA_MQTT_QOS',
'IOTA_MQTT_RETAIN',
'IOTA_HTTP_HOST',
'IOTA_HTTP_PORT'
],
mqttVariables = [
'IOTA_MQTT_HOST',
'IOTA_MQTT_PORT',
'IOTA_MQTT_USERNAME',
'IOTA_MQTT_PASSWORD',
'IOTA_MQTT_QOS',
'IOTA_MQTT_RETAIN'
],
httpVariables = [
'IOTA_HTTP_HOST',
'IOTA_HTTP_PORT'
];
for (var i = 0; i < environmentVariables.length; i++) {
if (process.env[environmentVariables[i]]) {
logger.info('Setting %s to environment value: %s',
environmentVariables[i], process.env[environmentVariables[i]]);
}
}
if (anyIsSet(mqttVariables)) {
config.mqtt = {};
}
if (process.env.IOTA_MQTT_HOST) {
config.mqtt.host = process.env.IOTA_MQTT_HOST;
}
if (process.env.IOTA_MQTT_PORT) {
config.mqtt.port = process.env.IOTA_MQTT_PORT;
}
if (process.env.IOTA_MQTT_USERNAME) {
config.mqtt.username = process.env.IOTA_MQTT_USERNAME;
}
if (process.env.IOTA_MQTT_PASSWORD) {
config.mqtt.password = process.env.IOTA_MQTT_PASSWORD;
}
if (process.env.IOTA_MQTT_QOS) {
config.mqtt.qos = process.env.IOTA_MQTT_QOS;
}
if (process.env.IOTA_MQTT_RETAIN) {
config.mqtt.retain = process.env.IOTA_MQTT_RETAIN;
}
if (anyIsSet(httpVariables)) {
config.http = {};
}
if (process.env.IOTA_HTTP_HOST) {
config.http.host = process.env.IOTA_HTTP_HOST;
}
if (process.env.IOTA_HTTP_PORT) {
config.http.port = process.env.IOTA_HTTP_PORT;
}
}
function setConfig(newConfig) {
config = newConfig;
processEnvironmentVariables();
}
function getConfig() {
return config;
}
function setLogger(newLogger) {
logger = newLogger;
}
function getLogger() {
return logger;
}
exports.setConfig = setConfig;
exports.getConfig = getConfig;
exports.setLogger = setLogger;
exports.getLogger = getLogger;
|
JavaScript
| 0.000005 |
@@ -2762,16 +2762,26 @@
T_RETAIN
+ == 'true'
;%0A %7D%0A
|
15a6346f784d0689faff54e417c61259293f1b95
|
Put back the general "require from node_modules" case
|
lib/index.js
|
lib/index.js
|
/**
* Module dependencies
*/
var generate = require('./generate');
var path = require('path');
var reportback = require('reportback')();
/**
* Generate module(s)
*
* @param {Object} scope [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
module.exports = function(scope, cb) {
cb = cb || {};
cb = reportback.extend(cb, {
error: cb.error,
invalid: cb.invalid,
success: function(output) {
cb.log.info('ok!');
},
notSailsApp: function() {
cb.log.error('Not a sails app.');
},
alreadyExists: function() {
return cb.error();
}
});
if (!scope.generatorType) {
return cb.error('Sorry, `scope.generatorType` must be defined.');
}
// Use configured module name for this generatorType if applicable.
var module =
(scope.modules && scope.modules[scope.generatorType]) ||
'sails-generate-' + scope.generatorType;
var Generator;
var requirePath;
var requireError;
function throwIfModuleNotFoundError (e, module) {
var isModuleNotFoundError = e && e.code === 'MODULE_NOT_FOUND' && e.message.match(new RegExp(module));
if (!isModuleNotFoundError) {
cb.log.error('Error in "'+scope.generatorType+'" generator (loaded from '+module+')');
throw e;
}
else return e;
}
// Allow `scope.generator` to be specified as an inline generator
// ... todo ...
// Try requiring it directly as a path resolved from process.cwd()
if (!Generator) {
try {
requirePath = path.resolve(process.cwd(), module);
Generator = require(requirePath);
} catch (e) {
requireError = throwIfModuleNotFoundError(e, module);
}
}
// Try requiring the generator from the rootPath
if (!Generator) {
try {
requirePath = path.resolve(scope.rootPath, 'node_modules', module);
Generator = require(requirePath);
} catch (e) {
requireError = throwIfModuleNotFoundError(e, module);
}
}
// If that doesn't work, try `require()`ing it from console user's cwd
if (!Generator) {
try {
requirePath = path.resolve(process.cwd(), 'node_modules', module);
Generator = require(requirePath);
} catch (e) {
requireError = throwIfModuleNotFoundError(e, module);
}
}
// Finally, try to load the generator module from sails-generate's dependencies
if (!Generator) {
try {
Generator = require(path.resolve(scope.rootPath || process.cwd(), module));
} catch (e) {
requireError = throwIfModuleNotFoundError(e, module);
}
}
if (!Generator) {
return cb.log.error("No generator called `" + scope.generatorType + "` found; perhaps you meant `sails generate api " + scope.generatorType + "`?");
}
generate(Generator, scope, cb);
};
|
JavaScript
| 0.000162 |
@@ -1413,16 +1413,173 @@
do ...%0A%0A
+ // Try requiring from node_modules%0A try %7B%0A Generator = require(module);%0A %7D catch (e) %7B%0A requireError = throwIfModuleNotFoundError(e, module);%0A %7D%0A%0A
// Try
|
b2746b539affb1efe39a9a3737760bf9f77d23b0
|
Fix bugs in SerialConnection.
|
src/serial-connection.js
|
src/serial-connection.js
|
/*! resol-vbus | Copyright (c) 2013-2014, Daniel Wippermann | MIT license */
'use strict';
var _ = require('lodash');
var Q = require('q');
var serialport;
try {
serialport = require('serialport');
} catch (ex) {
// eat it
}
var Connection = require('./connection');
var optionKeys = [
'path',
];
var SerialConnection = Connection.extend({
path: null,
reconnectTimeout: 0,
reconnectTimeoutIncr: 10000,
reconnectTimeoutMax: 60000,
serialPort: null,
constructor: function(options) {
Connection.call(this, options);
_.extend(this, _.pick(options, optionKeys));
},
connect: function() {
if (this.connectionState !== SerialConnection.STATE_DISCONNECTED) {
throw new Error('Connection is not disconnected (' + this.connectionState + ')');
}
this._setConnectionState(SerialConnection.STATE_CONNECTING);
return this._connect();
},
disconnect: function() {
if (this.connectionState !== SerialConnection.STATE_DISCONNECTED) {
this._setConnectionState(SerialConnection.STATE_DISCONNECTING);
if (this.serialPort) {
this.serialPort.destroy();
} else {
this._setConnectionState(SerialConnection.STATE_DISCONNECTED);
}
}
},
_connect: function() {
var _this = this;
var deferred = Q.defer();
var promise = deferred.promise;
var done = function(err, result) {
if (deferred) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(result);
}
deferred = null;
}
};
var onConnectionData = function(chunk) {
serialPort.write(chunk);
};
var onSerialPortData = function(chunk) {
_this._write(chunk);
};
var onSerialPortTermination = function() {
_this.removeListener('data', onConnectionData);
if (_this.serialPort !== serialPort) {
// nop
} else if (_this.connectionState === SerialConnection.STATE_CONNECTING) {
_this._setConnectionState(SerialConnection.STATE_DISCONNECTED);
_this.serialPort = null;
done(new Error('Unable to connect'));
} else if (_this.connectionState === SerialConnection.STATE_DISCONNECTING) {
_this._setConnectionState(SerialConnection.STATE_DISCONNECTED);
_this.serialPort = null;
} else {
_this._setConnectionState(SerialConnection.STATE_INTERRUPTED);
_this.serialPort = null;
var timeout = _this.reconnectTimeout;
if (_this.reconnectTimeout < _this.reconnectTimeoutMax) {
_this.reconnectTimeout += _this.reconnectTimeoutIncr;
}
setTimeout(function() {
_this._setConnectionState(SerialConnection.STATE_RECONNECTING);
_this._connect();
}, timeout);
}
};
var onEnd = function() {
onSerialPortTermination();
};
var onError = function() {
serialPort.close();
onSerialPortTermination();
};
this.on('data', onConnectionData);
var serialPort = new serialport.SerialPort(this.path);
serialPort.on('data', onSerialPortData);
serialPort.on('end', onEnd);
serialPort.on('error', onError);
this.serialPort = serialPort;
return promise;
}
});
module.exports = SerialConnection;
|
JavaScript
| 0 |
@@ -1199,15 +1199,13 @@
ort.
-destroy
+close
();%0A
@@ -3401,107 +3401,474 @@
-this.on('data', onConnectionData);%0A%0A var serialPort = new serialport.SerialPort(this.path
+var onConnectionEstablished = function() %7B%0A _this.reconnectTimeout = 0;%0A%0A _this._setConnectionState(SerialConnection.STATE_CONNECTED);%0A%0A done();%0A %7D;%0A%0A this.on('data', onConnectionData);%0A%0A var serialPort = new serialport.SerialPort(this.path, %7B%0A baudrate: 9600,%0A databits: 8,%0A stopbits: 1,%0A parity: 'none',%0A %7D
);%0A
+%0A
+ serialPort.once('open', function() %7B%0A
@@ -3912,32 +3912,36 @@
tData);%0A
+
+
serialPort.on('e
@@ -3953,32 +3953,36 @@
onEnd);%0A
+
+
serialPort.on('e
@@ -3995,24 +3995,76 @@
onError);%0A%0A
+ onConnectionEstablished();%0A %7D);%0A%0A
this
|
e451bdc36f0ff58345eecd6d1aab6aeeaec2b933
|
fix ^^
|
src/core/fontmetrics.js
|
src/core/fontmetrics.js
|
/**
This library rewrites the Canvas2D "measureText" function
so that it returns a more complete metrics object.
This library is licensed under the MIT (Expat) license,
the text for which is included below.
** -----------------------------------------------------------------------------
CHANGELOG:
2012-01-21 - Whitespace handling added by Joe Turner
(https://github.com/oampo)
2015-06-08 - Various hacks added by Steve Johnson
** -----------------------------------------------------------------------------
Copyright (C) 2011 by Mike "Pomax" Kamermans
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**/
(function(){
var NAME = "FontMetrics Library"
var VERSION = "1-2012.0121.1300";
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml (string) {
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
// if there is no getComputedStyle, this library won't work.
if(!document.defaultView.getComputedStyle) {
throw("ERROR: 'document.defaultView.getComputedStyle' not found. This library only works in browsers that can report computed CSS values.");
}
// store the old text metrics function on the Canvas2D prototype
CanvasRenderingContext2D.prototype.measureTextWidth = CanvasRenderingContext2D.prototype.measureText;
/**
* shortcut function for getting computed CSS values
*/
var getCSSValue = function(element, property) {
return document.defaultView.getComputedStyle(element,null).getPropertyValue(property);
};
// debug function
var show = function(canvas, ctx, xstart, w, h, metrics)
{
document.body.appendChild(canvas);
ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
ctx.beginPath();
ctx.moveTo(xstart,0);
ctx.lineTo(xstart,h);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
ctx.moveTo(xstart+metrics.bounds.maxx,0);
ctx.lineTo(xstart+metrics.bounds.maxx,h);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0,h/2-metrics.ascent);
ctx.lineTo(w,h/2-metrics.ascent);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0,h/2+metrics.descent);
ctx.lineTo(w,h/2+metrics.descent);
ctx.closePath();
ctx.stroke();
}
/**
* The new text metrics function
*/
CanvasRenderingContext2D.prototype.measureText2 = function(
textstring, fontSize, fontString) {
var metrics = this.measureTextWidth(textstring),
isSpace = !(/\S/.test(textstring));
metrics.fontsize = fontSize;
// for text lead values, we meaure a multiline text container.
var leadDiv = document.createElement("div");
leadDiv.style.position = "absolute";
leadDiv.style.opacity = 0;
leadDiv.style.font = fontString;
leadDiv.innerHTML = escapeHTML(textstring) + "<br/>" + escapeHTML(textstring);
document.body.appendChild(leadDiv);
// make some initial guess at the text leading (using the standard TeX ratio)
metrics.leading = 1.2 * fontSize;
// then we try to get the real value from the browser
var leadDivHeight = getCSSValue(leadDiv,"height");
leadDivHeight = leadDivHeight.replace("px","");
if (leadDivHeight >= fontSize * 2) { metrics.leading = (leadDivHeight/2) | 0; }
document.body.removeChild(leadDiv);
// if we're not dealing with white space, we can compute metrics
if (!isSpace) {
// Have characters, so measure the text
var canvas = document.createElement("canvas");
var padding = 100;
canvas.width = metrics.width + padding;
canvas.height = 3*fontSize;
canvas.style.opacity = 1;
canvas.style.font = fontString;
var ctx = canvas.getContext("2d");
ctx.font = fontString;
var w = canvas.width,
h = canvas.height,
baseline = h/2;
// Set all canvas pixeldata values to 255, with all the content
// data being 0. This lets us scan for data[i] != 255.
ctx.fillStyle = "white";
ctx.fillRect(-1, -1, w+2, h+2);
ctx.fillStyle = "black";
ctx.fillText(textstring, padding/2, baseline);
var pixelData = ctx.getImageData(0, 0, w, h).data;
// canvas pixel data is w*4 by h*4, because R, G, B and A are separate,
// consecutive values in the array, rather than stored as 32 bit ints.
var i = 0,
w4 = w * 4,
len = pixelData.length;
// Finding the ascent uses a normal, forward scanline
while (++i < len && pixelData[i] === 255) {}
var ascent = (i/w4)|0;
// Finding the descent uses a reverse scanline
i = len - 1;
while (--i > 0 && pixelData[i] === 255) {}
var descent = (i/w4)|0;
// find the min-x coordinate
for(i = 0; i<len && pixelData[i] === 255; ) {
i += w4;
if(i>=len) { i = (i-len) + 4; }}
var minx = ((i%w4)/4) | 0;
// find the max-x coordinate
var step = 1;
for(i = len-3; i>=0 && pixelData[i] === 255; ) {
i -= w4;
if(i<0) { i = (len - 3) - (step++)*4; }}
var maxx = ((i%w4)/4) + 1 | 0;
// set font metrics
metrics.ascent = (baseline - ascent);
metrics.descent = (descent - baseline);
metrics.bounds = { minx: minx - (padding/2),
maxx: maxx - (padding/2),
miny: 0,
maxy: descent-ascent };
metrics.height = 1+(descent - ascent);
}
// if we ARE dealing with whitespace, most values will just be zero.
else {
// Only whitespace, so we can't measure the text
metrics.ascent = 0;
metrics.descent = 0;
metrics.bounds = { minx: 0,
maxx: metrics.width, // Best guess
miny: 0,
maxy: 0 };
metrics.height = 0;
}
return metrics;
};
}());
|
JavaScript
| 0.000001 |
@@ -1904,18 +1904,16 @@
;'%0A %7D;%0A
-
%0A funct
@@ -1927,11 +1927,11 @@
apeH
-tml
+TML
(st
|
7db7e5a594381ac6f2744b99652177fa0b5c60fb
|
use new valuesForSaving method
|
lib/index.js
|
lib/index.js
|
var Mobware = require('mobware2'),
_ = require('lodash'),
pkginfo = require('pkginfo')(module),
pkginfo = module.exports,
MongoDB = require('mongodb'),
MongoClient = MongoDB.MongoClient,
ObjectID = MongoDB.ObjectID;
exports = module.exports = Connector;
// --------- Mongo DB connector -------
function Connector(obj) {
return Mobware.createConnector(obj||{},{
// pull in metadata from our package.json for this connector
pkginfo: _.pick(pkginfo,'name','version','description','author','license','keywords','repository'),
// implementation methods
name: 'mongodb',
customFieldTypeConverter: function(field,value,type){
// we are going to convert an ObjectID to a String for serialization
if (value instanceof ObjectID) {
return String(value);
}
},
fetchConfig: function(next) {
next(null, this.config);
},
fetchMetadata: function(next){
next(null, {
fields: [
Mobware.Metadata.URL({
name: 'url',
description: 'url for connector',
required: true
})
]
});
},
connect: function(next) {
this.logger.info('connect',this.config.url);
MongoClient.connect(this.config.url, function(err,db){
if (err) return next(err);
this.db = db;
next();
}.bind(this));
},
disconnect: function(next){
this.logger.info('disconnect');
if (this.db) {
this.db.close(next);
}
else {
next();
}
},
readOne: function(model, id, next) {
var connector = this,
collection = getCollection(model, this.db),
query = createPrimaryKeyQuery(model,id);
collection.findOne(query,function(err,doc){
if (err) return next(err);
if (!doc) return connector.notFoundError(next);
model.set(doc);
next(null,model);
});
},
readAll: function(model, next){
var name = model.getMetadata('collection'),
collection = getCollection(model, this.db);
collection.find().toArray(function(err,results){
if (err) return next(err);
var array = [];
for (var c=0;c<results.length;c++) {
array.push(model.new(results[c]));
}
next(null, array);
});
},
create: function(model, next){
var connector = this,
doc = model.values(false,true),
collection = getCollection(model, this.db);
collection.insert(doc, function(err,result){
if (err) return next(err);
if (!result) return connector.notFoundError(next);
next(null, model);
});
},
update: function(model, next){
var connector = this,
doc = model.values(true,true),
collection = getCollection(model, this.db),
query = createPrimaryKeyQuery(model);
collection.update(query,doc,function(err,doc){
if (err) return next(err);
if (!doc) return connector.notFoundError(next);
next(null,model);
});
},
delete: function(model, id, next) {
var connector = this,
collection = getCollection(model, this.db),
query = createPrimaryKeyQuery(model, id);
collection.remove(query, function(err,doc){
if (err) return next(err);
if (!doc) return connector.notFoundError(next);
next(null,model);
});
}
});
}
/**
* build a primary key query
*/
function createPrimaryKeyQuery(model, id) {
var query = {},
field = model.getPrimaryKey();
query[field] = ObjectID(id || model.getPrimaryKeyValue());
return query;
}
/**
* return the collection based on the model name or configured from metadata
*/
function getCollection(model, db){
var name = model.getMetadata('collection');
return db.collection(name || model.name);
}
|
JavaScript
| 0 |
@@ -2183,19 +2183,18 @@
lues
-(false,true
+ForSaving(
),%0A%09
@@ -2493,18 +2493,18 @@
lues
-(true,true
+ForSaving(
),%0A%09
|
618b4e378e290fe73db0af76c2b4409ad51b2c23
|
Reposition logic for video
|
app/assets/javascripts/lentil/addfancybox.js
|
app/assets/javascripts/lentil/addfancybox.js
|
var FancyBoxCloseFunctionState = {
// object literal for tracking important
// state information so we know
// how to change the url in response
// to user actions such as
// dismissing fancybox from clicking or using back button
popcalled: false,
fancyboxvisible: false,
pathname: window.location.pathname.replace(/\/?$/, '/')
};
// listen for popstate (back/forward, etc.)
function listenforpopstate() {
window.onpopstate = function(){
if ($('body').is(".lentil-images_show")) {
// if we're on the images page
// and this doesn't look like an image url
// switch to page that matches the url
if (!/images\/[0-9]/.test(window.location.pathname)) {
window.location.href = window.location.pathname;
}
} else {
// if we're on any other page (not an image)
// but the url looks like an image url
// switch to the image page that matches the url
if (/images\/[0-9]/.test(window.location.pathname)) {
window.location.href = window.location.pathname;
}
}
};
}
function pushimageurl() {
// extract application root url
var approot = FancyBoxCloseFunctionState.pathname.replace(/(photographers\/\d+|images|thisorthat\/battle|thisorthat\/battle_leaders)\/\D*\/?/, "");
// construct an image show url with the right image id
replacementUrl = approot + "images/" + imageId.replace("image_","");
// get rid of any double slashes (TO DO: remove this?)
if (/\/\//.test(replacementUrl)) {
replacementUrl = replacementUrl.replace("//","/");
}
// push the url for the displayed image to the browser
window.history.pushState(null, null, replacementUrl);
Lentil.ga_track(['_trackPageview', replacementUrl]);
// listen for popstate (back/forward button)
window.onpopstate = function(){
if (/images\/[0-9]/.test(window.location.pathname)) {
// if this url looks like an image show url then switch
// the browser to the displayed url
window.location.href = window.location.pathname;
} else {
// otherwise switch the popcalled state to true
// and close the fancybox
FancyBoxCloseFunctionState.popcalled = true;
$.fancybox.close();
// switch the popcalled flag to false
// and the fancybox visible flag to false
FancyBoxCloseFunctionState.popcalled = false;
FancyBoxCloseFunctionState.fancyboxvisible = false;
}
};
}
function addfancybox() {
$(".fancybox").fancybox({
openEffect : 'none',
closeEffect : 'none',
nextEffect : 'none',
prevEffect : 'none',
loop : false,
minWidth : '250px',
type: 'html',
helpers : {
title : { type : 'inside' },
overlay : { locked : false }
},
afterLoad: function(current, previous) {
// pushing base url so that back/close returns to image gallery
// instead of image show
window.history.pushState(null,null,FancyBoxCloseFunctionState.pathname);
},
beforeShow : function() {
var img = $(this.element).children(".instagram-img");
if($(img).attr("data-media-type") === "video") {
var video_url = $(img).attr("src");
//this.content = "<video src='" + video_url + "' height='320' width='320' controls='controls'></video>";
$(".fancybox-inner").html('<video controls="controls" height="100%" width="100%" src="' + video_url + '"></video>');
//return;
}
else {
var image_url = $(img).attr("src");
$(".fancybox-inner").html('<img class="fancybox-image" src="' + image_url + '" />');
}
this.title = $(this.element).next(".text-overlay").html();
imageId = $(this.element).parents("div").attr("id");
$(".fancybox-wrap").attr('id', imageId);
pushimageurl(imageId);
},
afterShow : function() {
// checks whether browser understands touch events
// if so the next/prev buttons are disabled
// and swipe down/right is added to advance slides
if ('ontouchstart' in document.documentElement){
$('.fancybox-nav').css('display','none');
$('.fancybox-wrap').swipe({
swipe : function(event, direction) {
if (direction === 'right' || direction === 'down') {
$.fancybox.prev( direction );
} else {
$.fancybox.next( direction );
}
}
});
}
// adds button handling script to displayed fancybox buttons
buttonhandler();
// this is to check that the fancybox is really visible
// afterClose is fired off on fancybox open -- a bug
FancyBoxCloseFunctionState.fancyboxvisible = true;
imageId = $(this.element).parents("div").attr("id");
// check whether we're on the last image in the gallery
// and whether there's more than one page of images
// if so, launch the spinner, fetch the next set of images
// and scroll to the current image
// (callback on addininfintescroll() does the work of reloading fancybox)
if (this.index == this.group.length - 1 && $("div#paging a").length > 0) {
$('#spinner-overlay').show();
$('#spinner-overlay').css("z-index", 10000000);
target = document.getElementById('spinner-overlay');
FANCYBOX_SPINNER = new Spinner(opts).spin(target);
//$("body").animate({scrollTop: $("div#" + imageId).offset().top }, 1500);
$('div.images').infinitescroll('retrieve');
}
},
afterClose : function() {
if (FancyBoxCloseFunctionState.popcalled === false && FancyBoxCloseFunctionState.fancyboxvisible === true) {
// if after closing the fancybox there is no pop event
// and the fancybox is visible
// (this afterClose event also fires when fancybox opens
// -- a bug we're getting around with this hack)
// switch the flags and point the url at the previous page
// should be an image tile view (recent, popular, staff picks, etc.)
FancyBoxCloseFunctionState.fancyboxvisible = false;
window.history.back();
}
}
});
}
|
JavaScript
| 0 |
@@ -3666,16 +3666,170 @@
deo%3E');%0A
+%09%09%09%09var vid = $(%22.fancybox-inner%22).children(%22video%22)%5B0%5D;%0A%09%09%09%09vid.oncanplay = function() %7B%0A%09%09%09%09%09console.log(%22Ready!%22);%0A%09%09%09%09%09$.fancybox.reposition();%0A%09%09%09%09%7D%0A
%09%09%09%09//re
|
e3bdb412bf5338da9161caa9cca400509a7b7fbd
|
Add CustomerRequisition pageInfoColumns
|
src/pages/dataTableUtilities/getPageInfoColumns.js
|
src/pages/dataTableUtilities/getPageInfoColumns.js
|
/* eslint-disable dot-notation */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2016
*/
import { pageInfoStrings, programStrings } from '../../localization';
import { formatDate } from '../../utilities';
import { MODAL_KEYS } from '../../utilities/getModalTitle';
/**
* PageInfo rows/columns for use with the PageInfo component.
*
*
* To add a page, add the pages routeName (see: pages/index.js)
* and a 2d array of page info rows to PER_PAGE_INFO_COLUMNS,
* of the desired pageinfo rows needed on the page.
*
* To use in the new page: use the usePageReducer hook.
* usePageReducer will inject a your pages reducer with a field
* pageInfo - a function returned by getPageInfo. Passing
* this function the particular pages base object - i.e,
* transaction, requisition or stock and it's dispatch will return the
* required pageInfo columns for the page.
*/
const PER_PAGE_INFO_COLUMNS = {
customerInvoice: [
['entryDate', 'confirmDate', 'enteredBy'],
['customer', 'theirRef', 'transactionComment'],
],
supplierInvoice: [['entryDate', 'confirmDate'], ['otherParty', 'theirRef', 'transactionComment']],
supplierRequisition: [
['entryDate', 'enteredBy'],
['otherParty', 'monthsToSupply', 'requisitionComment'],
],
supplierRequisitionWithProgram: [
['program', 'orderType', 'entryDate', 'enteredBy'],
['period', 'otherParty', 'programMonthsToSupply', 'requisitionComment'],
],
stocktakeEditor: [['stocktakeName', 'stocktakeComment']],
stocktakeEditorWithReasons: [['stocktakeName', 'stocktakeComment']],
};
const PAGE_INFO_ROWS = (pageObject, dispatch, PageActions) => ({
entryDate: {
title: `${pageInfoStrings.entry_date}:`,
info: formatDate(pageObject.entryDate) || 'N/A',
},
confirmDate: {
title: `${pageInfoStrings.confirm_date}:`,
info: formatDate(pageObject.confirmDate),
},
enteredBy: {
title: `${pageInfoStrings.entered_by}:`,
info: pageObject.enteredBy && pageObject.enteredBy.username,
},
customer: {
title: `${pageInfoStrings.customer}:`,
info: pageObject.otherParty && pageObject.otherParty.name,
},
theirRef: {
title: `${pageInfoStrings.their_ref}:`,
info: pageObject.theirRef,
onPress: () => dispatch(PageActions.openModal(MODAL_KEYS.THEIR_REF_EDIT)),
editableType: 'text',
},
transactionComment: {
title: `${pageInfoStrings.comment}:`,
info: pageObject.comment,
onPress: () => dispatch(PageActions.openModal(MODAL_KEYS.TRANSACTION_COMMENT_EDIT)),
editableType: 'text',
},
stocktakeComment: {
title: `${pageInfoStrings.comment}:`,
info: pageObject.comment,
onPress: () => dispatch(PageActions.openModal(MODAL_KEYS.STOCKTAKE_COMMENT_EDIT)),
editableType: 'text',
},
requisitionComment: {
title: `${pageInfoStrings.comment}:`,
info: pageObject.comment,
onPress: () => dispatch(PageActions.openModal(MODAL_KEYS.REQUISITION_COMMENT_EDIT)),
editableType: 'text',
},
otherParty: {
title: `${pageInfoStrings.supplier}:`,
info: pageObject.otherPartyName,
},
program: {
title: `${programStrings.program}:`,
info: pageObject.program && pageObject.program.name,
},
orderType: {
title: `${programStrings.order_type}:`,
info: pageObject.orderType,
},
monthsToSupply: {
title: `${pageInfoStrings.months_stock_required}:`,
info: pageObject.monthsToSupply,
onPress: () => dispatch(PageActions.openModal(MODAL_KEYS.SELECT_MONTH)),
editableType: 'selectable',
},
period: {
title: `${programStrings.period}:`,
info: pageObject.period && pageObject.period.toInfoString(),
},
programMonthsToSupply: {
title: `${pageInfoStrings.months_stock_required}:`,
info: pageObject.monthsToSupply,
},
stocktakeName: {
title: `${pageInfoStrings.stocktake_name}:`,
info: pageObject.name,
onPress: null,
editableType: 'text',
},
});
const getPageInfoColumns = page => {
const pageInfoColumns = PER_PAGE_INFO_COLUMNS[page];
if (!pageInfoColumns) return null;
return (pageObjectParameter, dispatch, PageActions) => {
const pageInfoRows = PAGE_INFO_ROWS(pageObjectParameter, dispatch, PageActions);
return pageInfoColumns.map(pageInfoColumn =>
pageInfoColumn.map(pageInfoKey => pageInfoRows[pageInfoKey])
);
};
};
export default getPageInfoColumns;
|
JavaScript
| 0 |
@@ -1380,23 +1380,24 @@
arty', '
-program
+editable
MonthsTo
@@ -1564,16 +1564,110 @@
ent'%5D%5D,%0A
+ customerRequisition: %5B%5B'monthsToSupply', 'entryDate'%5D, %5B'customer', 'requisitionComment'%5D%5D,%0A
%7D;%0A%0Acons
@@ -3373,17 +3373,25 @@
%0A %7D,%0A
-m
+editableM
onthsToS
@@ -3734,16 +3734,9 @@
,%0A
-programM
+m
onth
|
ba1675b7c3a9025190b03feefa5f24878f865653
|
Move poweroff and reboot to index.js
|
js/index.js
|
js/index.js
|
// Copyright 2014-2015 runtime.js project authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
/* global isolate */
var packagejson = require('./package.json');
require('module-singleton')(packagejson);
require('./version');
console.log(`v${packagejson.version} core library`);
console.log('loading...');
var isDebug = packagejson.runtimejs.debug;
global.debug = isDebug ? isolate.log : function() {};
// Load runtime.js core
var runtime = require('./core');
// Start services
require('./service/dhcp-client');
runtime.shell = require('./service/shell');
runtime.dns = require('./service/dns-resolver');
runtime.debug = isDebug;
// Example shell command
runtime.shell.setCommand('1', function(args, env, cb) {
env.stdio.writeLine('OK.');
runtime.dns.resolve('www.google.com', {}, function(err, data) {
if (err) {
return cb(1);
}
console.log(JSON.stringify(data));
cb(0);
});
});
// Builtin shell commands
require('./shell/clear');
require('./shell/echo');
require('./shell/power');
// Start device drivers
require('./driver/ps2');
require('./driver/virtio');
module.exports = runtime;
|
JavaScript
| 0.000001 |
@@ -1440,110 +1440,303 @@
);%0A%0A
-// Builtin shell commands%0Arequire('./shell/clear');%0Arequire('./shell/echo');%0Arequire('./shell/power');
+runtime.shell.setCommand('poweroff', function(args, env, cb) %7B%0A env.stdio.writeLine('Going down, now!');%0A runtime.machine.shutdown();%0A cb(0);%0A%7D);%0A%0Aruntime.shell.setCommand('reboot', function(args, env, cb) %7B%0A env.stdio.writeLine('Restarting, now!');%0A runtime.machine.reboot();%0A cb(0);%0A%7D);%0A
%0A%0A//
|
9a747852c87f706cc53c7a9128c28d4e6643ee13
|
Transform arguments to array
|
src/ggrc/assets/javascripts/models/mixins.js
|
src/ggrc/assets/javascripts/models/mixins.js
|
/*!
Copyright (C) 2014 Google Inc., authors, and contributors <see AUTHORS file>
Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
Created By: [email protected]
Maintained By: [email protected]
*/
(function (can) {
can.Construct('can.Model.Mixin', {
extend: function (fullName, klass, proto) {
var tempname;
var parts;
var shortName;
var Constructor;
if (typeof fullName === "string") {
// Mixins do not go into the global namespace.
tempname = fullName;
fullName = '';
}
Constructor = this._super(fullName, klass, proto);
// instead mixins sit under CMS.Models.Mixins
if (tempname) {
parts = tempname.split('.');
shortName = parts.pop();
Constructor.fullName = tempname;
} else {
Constructor.fullName = shortName =
'Mixin_' + Math.floor(Math.random() * Math.pow(36, 8)).toString(36);
parts = [];
}
can.getObject('CMS.Models.Mixins' + (parts.length ? '.' + parts.join('.') : ''), window, true)[shortName] = Constructor;
return Constructor;
},
newInstance: function () {
throw 'Mixins cannot be directly instantiated';
},
add_to: function (cls) {
var setupfns;
if (this === can.Model.Mixin) {
throw 'Must only add a subclass of Mixin to an object, not Mixin itself';
}
setupfns = function (obj) {
return function (fn, key) {
var blockedKeys = ['fullName', 'defaults', '_super', 'constructor'];
var aspect = ~key.indexOf(':') ? key.substr(0, key.indexOf(':')) : 'after';
var oldfn;
key = ~key.indexOf(':') ? key.substr(key.indexOf(':') + 1) : key;
if (fn !== can.Model.Mixin[key] && !~can.inArray(key, blockedKeys)) {
oldfn = obj[key];
// TODO support other ways of adding functions.
// E.g. "override" (doesn't call super fn at all)
// "sub" (sets this._super for mixin function)
// "chain" (pushes result of oldfn onto args)
// "before"/"after" (overridden function)
// TODO support extension for objects.
// Necessary for "attributes"/"serialize"/"convert"
// Defaults will always be "after" for functions
// and "override" for non-function values
if (oldfn && typeof oldfn === 'function') {
switch (aspect) {
case 'before':
obj[key] = function () {
fn.apply(this, arguments);
return oldfn.apply(this, arguments);
};
break;
case 'after':
obj[key] = function () {
oldfn.apply(this, arguments);
return fn.apply(this, arguments);
};
break;
default:
break;
}
} else if (aspect === 'extend') {
obj[key] = $.extend(obj[key], fn);
} else {
obj[key] = fn;
}
}
};
};
if (!~can.inArray(this.fullName, cls._mixins)) {
cls._mixins = cls._mixins || [];
cls._mixins.push(this.fullName);
can.each(this, setupfns(cls));
can.each(this.prototype, setupfns(cls.prototype));
}
}
}, {
});
can.Model.Mixin('ownable', {
'after:init': function () {
if (!this.owners) {
this.attr('owners', []);
}
}
});
can.Model.Mixin('contactable', {
// NB : Because the attributes object
// isn't automatically cloned into subclasses by CanJS (this is an intentional
// exception), when subclassing a class that uses this mixin, be sure to pull in the
// parent class's attributes using `can.extend(this.attributes, <parent_class>.attributes);`
// in the child class's static init function.
'extend:attributes': {
contact: 'CMS.Models.Person.stub',
secondary_contact: 'CMS.Models.Person.stub'
}
}, {
before_create: function () {
if (!this.contact) {
this.attr('contact', {
id: GGRC.current_user.id,
type: 'Person'
});
}
},
form_preload: function (newObjectForm) {
if (newObjectForm && !this.contact) {
this.attr('contact', {
id: GGRC.current_user.id, type: 'Person'
});
}
}
});
can.Model.Mixin('unique_title', {
'after:init': function () {
this.validate(['title', '_transient:title'], function (newVal, prop) {
if (prop === 'title') {
return this.attr('_transient:title');
} else if (prop === '_transient:title') {
return newVal; // the title error is the error
}
});
}
}, {
save_error: function (val) {
if (/title values must be unique\.$/.test(val)) {
this.attr('_transient:title', val);
}
},
after_save: function () {
this.removeAttr('_transient:title');
},
'before:attr': function (key, val) {
if (key === 'title' && arguments.length > 1) {
this.attr('_transient:title', null);
}
}
});
can.Model.Mixin('relatable', {
}, {
related_self: function () {
return this._related(
CMS.Models[this.type].relatable_options.relevantTypes);
},
_related: function (relevantTypes) {
var that = this;
var relatable = $.Deferred();
var connectionsCount = {};
var mappedObjectDeferreds = _.map(relevantTypes, function (rtype) {
return this.get_binding(rtype.objectBinding).refresh_instances();
}.bind(this));
var relatedObjectsDeferreds = [];
$.when.apply($, mappedObjectDeferreds).done(function () {
_.each(arguments, function (mappedObjectInstances) {
if (!mappedObjectInstances.length) {
return;
}
relatedObjectsDeferreds = relatedObjectsDeferreds.concat(
_.map(mappedObjectInstances, function (mappedObj) {
var insttype = mappedObj.instance.type;
var binding = relevantTypes[insttype].relatableBinding;
return mappedObj.instance.get_binding(
binding).refresh_instances();
}));
});
$.when.apply($, relatedObjectsDeferreds).done(function () {
_.each(arguments, function (relatedObjects) {
_.each(relatedObjects, function (relObj) {
var type = relObj.binding.instance.type;
var weight = relevantTypes[type].weight;
if (relObj.instance.id !== that.id) {
if (connectionsCount[relObj.instance.id] === undefined) {
connectionsCount[relObj.instance.id] = {
count: weight,
object: relObj
};
} else {
connectionsCount[relObj.instance.id].count += weight;
}
}
});
});
relatable.resolve(
_.map(_.sortBy(connectionsCount, 'count').reverse(),
function (item) {
return item.object;
}));
});
});
return relatable;
}
});
})(this.can);
|
JavaScript
| 0.001051 |
@@ -5585,16 +5585,56 @@
t = %7B%7D;%0A
+ var relatedObjectsDeferreds = %5B%5D;%0A
va
@@ -5799,48 +5799,8 @@
);%0A%0A
- var relatedObjectsDeferreds = %5B%5D;%0A
@@ -5866,32 +5866,42 @@
%0A _.each(
+_.toArray(
arguments, funct
@@ -5885,32 +5885,33 @@
oArray(arguments
+)
, function (mapp
@@ -6480,16 +6480,26 @@
_.each(
+_.toArray(
argument
@@ -6499,16 +6499,17 @@
rguments
+)
, functi
|
7fa2cee42d2d3935bbe0120ebf3c8a4c20b44f94
|
Fix .native
|
src/modules/app/controls/OrbitControlsModule.js
|
src/modules/app/controls/OrbitControlsModule.js
|
import {Vector3} from 'three';
import {ControlsModule} from '../ControlsModule';
import {ThreeOrbitControls} from './lib/ThreeOrbitControls';
export class OrbitControlsModule extends ControlsModule {
constructor(params = {}, patchEvents = true) {
super(params, patchEvents);
this.params = Object.assign({
follow: false,
object: null,
target: new Vector3(0, 0, 0)
}, params);
}
manager(manager) {
const object = this.params.object
? this.params.object
: manager.get('camera').native;
const controls = new ThreeOrbitControls(
object,
manager.get('element'),
manager.handler
);
const {params} = this;
const updateProcessor = params.follow ? c => {
controls.update(c.getDelta());
controls.target.copy(params.target);
} : c => {
controls.update(c.getDelta());
};
this.setControls(controls);
this.setUpdate(updateProcessor);
manager.update({
camera: camera => {
if (this.params.object) return;
controls.object = camera.native;
}
});
controls.target.copy(params.target);
}
}
|
JavaScript
| 0.000068 |
@@ -489,24 +489,31 @@
arams.object
+.native
%0A : man
|
04161b13c9718620afc31f0fde5410d1fc3ca923
|
Fix FIXME
|
scripts/pageContent.js
|
scripts/pageContent.js
|
'use strict';
const VideoViewer = window.VideoViewer = (function () {
const self = {};
const videoviewer = $('.videoviewer')[0];
const video = $(videoviewer).find('video')[0];
self.hide = () => {
$(video).find('source').remove();
video.pause();
videoviewer.dataset.show = 'false';
};
self.show = videoId => {
$(video).find('source').remove();
const source = document.createElement('source');
source.src = `/content/video/${videoId}`;
$(video).append(source);
videoviewer.dataset.show = 'true';
};
$(videoviewer).click(self.hide);
return self;
})();
window.attachResponseClicks = function () {
$('.responselink').each((idx, element) => {
$(element).off('click'); // Ensure we only have one click event
$(element).click(event => {
VideoViewer.show(element.dataset.id);
});
});
};
window.attachLiveContent = function (path) {
const startTime = encodeURIComponent(new Date().toISOString());
const getRequestURI = (function () {
let postOffset = 0;
return function (path) {
const uri = `/content/${path}?time=${startTime}&offset=${postOffset}`;
postOffset += 5;
return uri;
};
})();
const getResponseListURI = (function () {
const offsetMap = {};
return function (challenge) {
if (offsetMap[challenge] === undefined) offsetMap[challenge] = 0;
const encChallenge = encodeURIComponent(challenge);
const uri = `/content/responselist?challenge=${encChallenge}&time=${startTime}&offset=${offsetMap[challenge]}`;
offsetMap[challenge] += 5;
return uri;
};
})();
function getVideos(challengeElement, moreElement) {
$.get(getResponseListURI(challengeElement.dataset.challengeName), (data, textStatus) => {
if (textStatus === 'nocontent') {
$(moreElement).remove();
return;
}
$(challengeElement).find('.responses').append(data.rendered);
$(challengeElement).find('.no-responses').remove();
attachResponseClicks();
}).fail(response => {
console.error(response);
});
}
let lastIdx = 0;
function appendContent(renderedHtml) {
$('main').append(renderedHtml);
$('main').find('section').each((idx, challengeElement) => {
// Make sure that we do not run init code again for sections we already processed
if (idx < lastIdx) return;
const moreElement = $(challengeElement).find('.responses-more');
getVideos(challengeElement, moreElement);
$(moreElement).click(event => getVideos(challengeElement, moreElement));
lastIdx = idx;
});
$('main').append(`<section class="loading">${i18n.loadingMore}</section>`);
}
$.get(getRequestURI(path), data => {
appendContent(data.rendered);
}, 'json').fail(response => {
console.error(response);
$('main')[0].dataset.error = 'true';
$('div.error-no-content')[0].dataset.show = 'true';
});
function isLoadingVisible() {
const loader = $('section.loading')[0];
return loader.getBoundingClientRect().top >= 0 &&
loader.getBoundingClientRect().bottom <= window.innerHeight;
}
let noContent = false;
$('main')[0].addEventListener('scroll', () => {
if (noContent) return;
if (!isLoadingVisible()) return;
$.get(getRequestURI(path), (data, textStatus) => {
if (textStatus === 'nocontent') {
// FIXME this doesn't trigger when content < page height
noContent = true;
$('section.loading')[0].innerHTML = i18n.noMoreContent;
return;
}
$('section.loading').remove();
appendContent(data.rendered);
}, 'json').fail(response => {
console.error(response);
$('section.loading')[0].innerHtml = i18n.loadingMoreFail;
});
}, {
passive: true
});
};
|
JavaScript
| 0.000002 |
@@ -2743,16 +2743,128 @@
dered);%0A
+ if ($('main')%5B0%5D.children.length %3C 6) %7B%0A $('section.loading')%5B0%5D.innerHTML = i18n.noMoreContent;%0A %7D%0A
%7D, 'js
@@ -3460,73 +3460,8 @@
) %7B%0A
- // FIXME this doesn't trigger when content %3C page height%0A
|
9f54ddf575b873fd7c15ff4ee56afc189a409fb7
|
Update app_test.js
|
gr-socket-server/app_test.js
|
gr-socket-server/app_test.js
|
var assert = require('assert')
, http = require('http')
, greenroom = require('./app')
, callbackFired = false;
greenroom.server.listen(80);
http
.cat('http://localhost')
.addCallback(function(data) {
callbackFired = true;
//assert.equal('hello world', data);
greenroom.server.close();
console.write('tes');
});
process.addListener('exit', function() {
assert.ok(callbackFired);
});
|
JavaScript
| 0.000004 |
@@ -55,25 +55,19 @@
p')%0A ,
-greenroom
+app
= requi
@@ -271,25 +271,19 @@
a);%0A
-greenroom
+app
.server.
@@ -392,8 +392,9 @@
ed);%0A%7D);
+%0A
|
383d6a577a74629851e08ab8b2a8e229a60e5375
|
check latest version
|
packages/cli/src/bin/flint.js
|
packages/cli/src/bin/flint.js
|
#!/usr/bin/env node
var Program = require('commander')
var colors = require('colors')
/* START -- make `flint run` default command -- */
var flintIndex = getFlintIndex()
// find where index of flint is
function getFlintIndex() {
let index = 0
for (let arg of process.argv) {
if (arg.indexOf('flint') > 0) return index
index++
}
}
// make sure flags are still passed to `flint run`
var firstFlag = process.argv[flintIndex + 1]
if (flintIndex === process.argv.length - 1 || (firstFlag && firstFlag[0] === '-')) {
process.flintArgs = [].concat(process.argv);
process.flintArgs.splice(flintIndex + 1, 0, 'run');
}
/* END -- make `flint run` default command -- */
// check flint version
let path = require('path')
let exec = require('child_process').exec
let checkversion = 'npm view flint version -loglevel silent'
let pkg = require(path.join('..', '..', 'package.json'))
const getversion = v => (''+v).trim()
let pkgV = getversion(pkg.version)
exec(checkversion, (err, version) => {
if (err) return
if (version) {
let curV = getversion(version)
if (curV != pkgV) {
console.log(
`──────────────────────────────────\n`.yellow.bold +
` Flint update available: v${curV} \n`.bold +
`──────────────────────────────────`.yellow.bold
)
}
}
})
Program
.version(require('../../package.json').version)
.command('new [name] [template]', 'start a new Flint app')
.command('run', 'run your flint app')
.command('build', 'run your flint app')
.command('update', 'update to the new flint cli')
.command('*', () => {
console.log('what')
})
Program.parse(process.flintArgs || process.argv)
|
JavaScript
| 0 |
@@ -795,24 +795,31 @@
m view flint
+@latest
version -lo
|
4cb406caf4795da5026a891922a56904eb78b9df
|
Fix $.ajax().success() for jQuery 3.0
|
app/assets/javascripts/subdivision_select.js
|
app/assets/javascripts/subdivision_select.js
|
var SubdivisionSelect = (function() {
SubdivisionSelect.subdivisionSelector = "select[data-subdivision-selector]";
SubdivisionSelect.countrySelector = "select[id$=country]";
function SubdivisionSelect(element) {
this._countrySelect = element;
this._subdivisionSelect = $(element).
closest("form").
find(SubdivisionSelect.subdivisionSelector);
};
SubdivisionSelect.init = function () {
var klass = this;
return $(klass.countrySelector).each(function() {
return new klass(this).init();
});
};
SubdivisionSelect.prototype.init = function() {
var self = this;
self._enabledInputsBeforeSubmit();
$(this._countrySelect).change(function() {
$.ajax( {
url: "/subdivisions",
data: { country_code: $(this).val() }
}).success(function(newSubdivisions) {
self._clearSubdivisionSelect();
self._updateSubdivisionSelect(newSubdivisions);
});
});
};
SubdivisionSelect.prototype._updateSubdivisionSelect = function(newSubdivisions) {
var self = this;
var isEmpty = $.isEmptyObject(newSubdivisions);
$.each(newSubdivisions, function(alpha2, name) {
self._subdivisionSelect.append($("<option></option>").attr("value", alpha2).text(name));
});
// Disable the select if there are no newSubdivisions (and un-do that once there are some)
self._subdivisionSelect.prop("disabled", isEmpty);
// If there are none, make it say "none"
if (isEmpty) {
self._subdivisionSelect.append($("<option></option>").text("none"));
}
};
// Disabling selects means they won't POST with the form.
// Solution: right before submiting a form, enabled them.
SubdivisionSelect.prototype._enabledInputsBeforeSubmit = function() {
$('form').bind('submit', function() {
$(this).find('select').removeAttr('disabled');
});
};
// Not only empty the select, but:
// if the first element is blank, add a blank element before all others
SubdivisionSelect.prototype._clearSubdivisionSelect = function() {
var includeBlank = this._subdivisionSelect.children().first().text() === "";
this._subdivisionSelect.empty();
if (includeBlank) {
this._subdivisionSelect.append($("<option></option>"));
}
};
return SubdivisionSelect;
})();
$(function() {
SubdivisionSelect.init();
});
|
JavaScript
| 0 |
@@ -801,15 +801,12 @@
%7D).
-success
+done
(fun
|
69d0a311b6d9124c1b17a8077d56efb02d9c2892
|
Update scrollbar.js
|
drawing/scrollbar.js
|
drawing/scrollbar.js
|
var isInScrollBar = function(canvas, context, x, y){
var height = 400;
var width = 30;
var distanceFromTop = 100;
return x > canvas.width - width && y > distanceFromTop && y < distanceFromTop + height;
}
var getScrollPositionFromScrollBar = function(canvas, context, y, maxScroll){
var height = 400;
var width = 20;
var distanceFromTop = 100;
return (y - distanceFromTop) * maxScroll / height;
}
var drawScrollBar = function(canvas, context, scrollPosition, maxScroll){
var height = 400;
var width = 30;
var distanceFromTop = 100;
context.beginPath();
context.strokeStyle=staveColour;
context.rect(canvas.width - width, distanceFromTop, width, height);
context.stroke();
context.beginPath();
context.strokeStyle=noteColour;
context.lineWidth =4;
context.moveTo(canvas.width - width, scrollPosition * height / maxScroll + distanceFromTop);
context.lineTo(canvas.width, scrollPosition * height / maxScroll + distanceFromTop);
context.stroke();
context.lineWidth = 1;
}
function getCurrentLine(y, lines, maxScroll){
var height = 400;
var distanceFromTop = 100;
for(var i = 0; i < lines.length; i++){
if(lines[i].y > (y - distanceFromTop) * maxScroll / height )
return lines[i].barNumber;
}
return false;
}
var drawScrollPreview = function(canvas, context, y, lines, maxScroll){
var rightMargin = 30;
var width = 100;
var height = 100;
var farLeft = canvas.width - (rightMargin + width) - 15;
context.beginPath();
context.moveTo(farLeft, y);
context.lineTo(farLeft + width + 10, y);
context.lineTo(farLeft + width, y + 5)
context.lineTo(farLeft + width, y + height);
context.lineTo(farLeft, y + height);
context.lineTo(farLeft, y);
context.strokeStyle = "black";
context.lineWidth = 4;
context.stroke();
context.fillStyle="white";
context.fill();
context.lineWidth = 1;
var tempCurrentLine = getCurrentLine(y, lines, maxScroll);
if(tempCurrentLine != false){
context.font = "bold 10px Arial";
context.fillStyle="black";
context.fillText(tempCurrentLine + "", farLeft + 5, y + 10 );
}
}
|
JavaScript
| 0.000001 |
@@ -1941,17 +1941,17 @@
%22bold 1
-0
+2
px Arial
|
f973a2dfbf7d5cf5dd4d1f6059016b1bbb69899e
|
add RAF polypill to utils index
|
src/core/utils/index.js
|
src/core/utils/index.js
|
var CONST = require('../const');
/**
* @namespace PIXI.utils
*/
var utils = module.exports = {
_uid: 0,
_saidHello: false,
Ticker: require('./Ticker'),
EventData: require('./EventData'),
eventTarget: require('./eventTarget'),
pluginTarget: require('./pluginTarget'),
PolyK: require('./PolyK'),
/**
* Gets the next uuid
*
* @return {number} The next uuid to use.
*/
uuid: function ()
{
return ++utils._uid;
},
/**
* Converts a hex color number to an [R, G, B] array
*
* @param hex {number}
* @return {number[]} An array representing the [R, G, B] of the color.
*/
hex2rgb: function (hex, out)
{
out = out || [];
out[0] = (hex >> 16 & 0xFF) / 255;
out[1] = (hex >> 8 & 0xFF) / 255;
out[2] = (hex & 0xFF) / 255;
return out;
},
/**
* Converts a hex color number to a string.
*
* @param hex {number}
* @return {string} The string color.
*/
hex2string: function (hex)
{
hex = hex.toString(16);
hex = '000000'.substr(0, 6 - hex.length) + hex;
return '#' + hex;
},
/**
* Converts a color as an [R, G, B] array to a hex number
*
* @param rgb {number[]}
* @return {number} The color number
*/
rgb2hex: function (rgb)
{
return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255);
},
/**
* Checks whether the Canvas BlendModes are supported by the current browser
*
* @return {boolean} whether they are supported
*/
canUseNewCanvasBlendModes: function ()
{
if (typeof document === 'undefined')
{
return false;
}
var pngHead = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/';
var pngEnd = 'AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==';
var magenta = new Image();
magenta.src = pngHead + 'AP804Oa6' + pngEnd;
var yellow = new Image();
yellow.src = pngHead + '/wCKxvRF' + pngEnd;
var canvas = document.createElement('canvas');
canvas.width = 6;
canvas.height = 1;
var context = canvas.getContext('2d');
context.globalCompositeOperation = 'multiply';
context.drawImage(magenta, 0, 0);
context.drawImage(yellow, 2, 0);
var data = context.getImageData(2,0,1,1).data;
return (data[0] === 255 && data[1] === 0 && data[2] === 0);
},
/**
* Given a number, this function returns the closest number that is a power of two
* this function is taken from Starling Framework as its pretty neat ;)
*
* @param number {number}
* @return {number} the closest number that is a power of two
*/
getNextPowerOfTwo: function (number)
{
// see: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two
if (number > 0 && (number & (number - 1)) === 0)
{
return number;
}
else
{
var result = 1;
while (result < number)
{
result <<= 1;
}
return result;
}
},
/**
* checks if the given width and height make a power of two rectangle
*
* @param width {number}
* @param height {number}
* @return {boolean}
*/
isPowerOfTwo: function (width, height)
{
return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0);
},
/**
* get the resolution of an asset by looking for the prefix
* used by spritesheets and image urls
*
* @param url {string} the image path
* @return {boolean}
*/
getResolutionOfUrl: function (url)
{
var resolution = CONST.RETINA_PREFIX.exec(url);
if (resolution)
{
return parseFloat(resolution[1]);
}
return 1;
},
/**
* Logs out the version and renderer information for this running instance of PIXI.
* If you don't want to see this message you can set `PIXI.utils._saidHello = true;`
* so the library thinks it already said it. Keep in mind that doing that will forever
* makes you a jerk face.
*
* @param {string} type - The string renderer type to log.
* @constant
* @static
*/
sayHello: function (type)
{
if (utils._saidHello)
{
return;
}
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
{
var args = [
'%c %c %c Pixi.js ' + CONST.VERSION + ' - ' + type + ' %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ ',
'background: #ff66a5',
'background: #ff66a5',
'color: #ff66a5; background: #030307;',
'background: #ff66a5',
'background: #ffc3dc',
'background: #ff66a5',
'color: #ff2424; background: #fff',
'color: #ff2424; background: #fff',
'color: #ff2424; background: #fff'
];
window.console.log.apply(console, args); //jshint ignore:line
}
else if (window.console)
{
window.console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line
}
utils._saidHello = true;
},
TextureCache: {},
BaseTextureCache: {}
};
|
JavaScript
| 0 |
@@ -128,16 +128,80 @@
false,%0A%0A
+ RAFramePolyfill:require('./requestAnimationFramePolyfill'),%0A
Tick
@@ -411,16 +411,17 @@
lyK'),%0A%0A
+%0A
/**%0A
|
ec720c304062672d859c1bcbe9270e94306239cd
|
fix metrics reporting of request size
|
lib/utilities/monitoringHandler.js
|
lib/utilities/monitoringHandler.js
|
const errors = require('arsenal');
const client = require('prom-client');
const collectDefaultMetrics = client.collectDefaultMetrics;
let crrStatsPulled = false;
const numberOfBuckets = new client.Gauge({
name: 'cloud_server_number_of_buckets',
help: 'Total number of buckets',
});
const numberOfObjects = new client.Gauge({
name: 'cloud_server_number_of_objects',
help: 'Total number of objects',
});
const numberOfIngestedObjects = new client.Gauge({
name: 'cloud_server_number_of_ingested_objects',
help: 'Number of out of band ingestion',
});
const dataIngested = new client.Gauge({
name: 'cloud_server_data_ingested',
help: 'Cumulative size of data ingested in bytes',
});
const dataDiskAvailable = new client.Gauge({
name: 'cloud_server_data_disk_available',
help: 'Available data disk storage in bytes',
});
const dataDiskFree = new client.Gauge({
name: 'cloud_server_data_disk_free',
help: 'Free data disk storage in bytes',
});
const dataDiskTotal = new client.Gauge({
name: 'cloud_server_data_disk_total',
help: 'Total data disk storage in bytes',
});
const labelNames = ['method', 'service', 'code'];
const httpRequestsTotal = new client.Counter({
labelNames,
name: 'cloud_server_http_requests_total',
help: 'Total number of HTTP requests',
});
const httpRequestSizeBytes = new client.Summary({
labelNames,
name: 'cloud_server_http_request_size_bytes',
help: 'The HTTP request sizes in bytes.',
});
const httpResponseSizeBytes = new client.Summary({
labelNames,
name: 'cloud_server_http_response_size_bytes',
help: 'The HTTP response sizes in bytes.',
});
function promMetrics(requestType, bucketName, code, typeOfRequest,
newByteLength, oldByteLength, isVersionedObj,
numOfObjectsRemoved, ingestSize) {
let bytes;
httpRequestsTotal.labels(requestType, 'cloud_server', code).inc();
if ((typeOfRequest === 'putObject' ||
typeOfRequest === 'copyObject' ||
typeOfRequest === 'putOjectPart') &&
code === '200') {
bytes = newByteLength - (isVersionedObj ? 0 : oldByteLength);
httpRequestSizeBytes
.labels(requestType, 'cloud_server', code)
.observe(bytes);
dataDiskAvailable.dec(bytes);
dataDiskFree.dec(bytes);
if (ingestSize) {
numberOfIngestedObjects.inc();
dataIngested.inc(ingestSize);
}
numberOfObjects.inc();
}
if (typeOfRequest === 'createBucket' && code === '200') {
numberOfBuckets.inc();
}
if (typeOfRequest === 'getObject' && code === '200') {
httpResponseSizeBytes
.labels(requestType, 'cloud_server', code)
.observe(newByteLength);
}
if ((typeOfRequest === 'deleteBucket' ||
typeOfRequest === 'deleteBucketWebsite')
&& (code === '200' || code === '204')) {
numberOfBuckets.dec();
}
if ((typeOfRequest === 'deleteObject' ||
typeOfRequest === 'abortMultipartUpload' ||
typeOfRequest === 'multiObjectDelete')
&& code === '200') {
dataDiskAvailable.inc(newByteLength);
dataDiskFree.inc(newByteLength);
const objs = numOfObjectsRemoved || 1;
numberOfObjects.dec(objs);
if (ingestSize) {
numberOfIngestedObjects.dec(objs);
dataIngested.dec(ingestSize);
}
}
}
function crrCacheToProm(crrResults) {
if (!crrStatsPulled && crrResults) {
if (crrResults.getObjectCount) {
numberOfBuckets.set(crrResults.getObjectCount.buckets || 0);
numberOfObjects.set(crrResults.getObjectCount.objects || 0);
}
if (crrResults.getDataDiskUsage) {
dataDiskAvailable.set(crrResults.getDataDiskUsage.available || 0);
dataDiskFree.set(crrResults.getDataDiskUsage.free || 0);
dataDiskTotal.set(crrResults.getDataDiskUsage.total || 0);
}
}
crrStatsPulled = true;
}
function writeResponse(res, error, log, results, cb) {
let statusCode = 200;
if (error) {
if (Number.isInteger(error.code)) {
statusCode = error.code;
} else {
statusCode = 500;
}
}
res.writeHead(statusCode, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(results));
res.end(() => {
cb(error, results);
});
}
function routeHandler(req, res, log, cb) {
if (req.method !== 'GET') {
return cb(errors.BadRequest, []);
}
const promMetrics = client.register.metrics();
const contentLen = Buffer.byteLength(promMetrics, 'utf8');
res.setHeader('content-length', contentLen);
res.setHeader('content-type', client.register.contentType);
res.end(promMetrics);
return undefined;
}
/**
* Checks if client IP address is allowed to make http request to
* S3 server. Defines function 'montiroingEndHandler', which is
* called if IP not allowed or passed as callback.
* @param {object} clientIP - IP address of client
* @param {object} req - http request object
* @param {object} res - http response object
* @param {object} log - werelogs logger instance
* @return {undefined}
*/
function monitoringHandler(clientIP, req, res, log) {
function monitoringEndHandler(err, results) {
writeResponse(res, err, log, results, error => {
if (error) {
return log.end().warn('monitoring error', { err: error });
}
return log.end();
});
}
if (req.method !== 'GET') {
return monitoringEndHandler(res, errors.MethodNotAllowed);
}
const monitoring = (req.url === '/_/monitoring/metrics');
if (!monitoring) {
return monitoringEndHandler(res, errors.MethodNotAllowed);
}
return routeHandler(req, res, log, monitoringEndHandler);
}
module.exports = {
monitoringHandler,
client,
collectDefaultMetrics,
promMetrics,
crrCacheToProm,
};
|
JavaScript
| 0 |
@@ -2218,21 +2218,29 @@
observe(
-bytes
+newByteLength
);%0A
|
4265eef20198eb0b876d87de884dc261d9b6b61d
|
Rename delete method to remove
|
packages/dom/cookie/cookie.js
|
packages/dom/cookie/cookie.js
|
/**
* @module cookie
* @category DOM
*/
module.exports = (function () {
/**
* Creates a new cookie.
*
* @function set
* @param {String} name The name of the cookie to create.
* @param {String} value The value of the cookie to create.
* @param {Object} [options]
* @param {String} [options.path="/"] The path where cookie is visible. If not specified, defaults to the current path of the current document location.
* @param {String} [options.domain] The domain where cookie is visible. If not specified, this defaults to the host portion of the current document location. If a domain is specified, subdomains are always included.
* @param {String} [options.expires] A date in GMTString format that tells when cookie expires. If not specified it will expire at the end of session. If date is in the past, then the cookie is deleted. Use `Date.prototype.toUTCString()` to properly format it.
* @param {Number} [options['max-age']] Max age in seconds from the time the cookie is set; alternative to `expires`. If not specified it will expire at the end of session. If zero or negative, then the cookie is deleted.
* @param {String} [options.secure] Cookie to only be transmitted over secure protocol as https.
* @param {String} [options.samesite] SameSite prevents the browser from sending this cookie along with cross-site requests. Possible values are "lax", "strict" or "none".
* @throws {TypeError} If `name` is not string.
* @throws {TypeError} If `value` is not string.
* @returns {void}
* @example
*
* cookie.set('foo', 'bar', {
* path: '/',
* domain: 'example.com',
* 'max-age': 3600, // value in seconds; expires after one hour from the current time
* secure: true,
* samesite: 'strict'
* });
* // -> undefined
*/
function setCookie(name, value, options) {
var cookie, optionKey, optionValue;
if (typeof name !== 'string' || typeof value !== 'string') {
throw new TypeError('Expected a string for first and second argument');
}
if (!options || typeof options !== 'object') {
options = {};
}
options.path = options.path || '/';
cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
for (optionKey in options) {
if (Object.prototype.hasOwnProperty.call(options, optionKey)) {
optionValue = options[optionKey];
cookie += '; ' + optionKey;
if (optionValue !== true) {
cookie += '=' + optionValue;
}
}
}
document.cookie = cookie;
}
/**
* Get a cookie by its name.
*
* @function get
* @param {String} [name] The name of the cookie to get.
* @throws {TypeError} If `name` is not string.
* @returns {String} Returns the value of the cookie if exists; otherwise an empty string.
* @example
*
* cookie.get('foo');
* // -> 'bar'
*
* cookie.get('cookie-that-does-not-exist');
* // -> ''
*/
function getCookie(name) {
var matches;
if (typeof name !== 'string') {
throw new TypeError('Expected a string for first argument');
}
if (typeof name === 'undefined') {
return document.cookie;
}
matches = document.cookie.match(
new RegExp('(?:^|; )' + name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1') + '=([^;]*)')
);
return matches ? decodeURIComponent(matches[1]) : '';
}
/**
* Deletes a cookie by its name.
*
* @function delete
* @param {String} name The name of the cookie to delete.
* @throws {TypeError} If `name` is not string.
* @returns {void}
* @example
*
* cookie.delete('foo');
* // -> undefined
*/
function deleteCookie(name) {
if (typeof name !== 'string') {
throw new TypeError('Expected a string for first argument');
}
setCookie(name, '', {
'max-age': -1
});
}
return {
set: setCookie,
get: getCookie,
delete: deleteCookie
};
}());
|
JavaScript
| 0.000001 |
@@ -3107,84 +3107,8 @@
%7D%0A%0A
- if (typeof name === 'undefined') %7B%0A return document.cookie;%0A %7D%0A%0A
@@ -3363,21 +3363,21 @@
unction
-delet
+remov
e%0A * @
@@ -3532,21 +3532,21 @@
cookie.
-delet
+remov
e('foo')
@@ -3585,21 +3585,21 @@
unction
-delet
+remov
eCookie(
@@ -3834,21 +3834,21 @@
-delete: delet
+remove: remov
eCoo
|
5b5a166b7660ab49b16bebd59e2a4ff8452120dd
|
Convert images that are also in the base stylesheet.
|
lib/css-transform.js
|
lib/css-transform.js
|
const chokidar = require('chokidar')
const fs = require('fs')
const mimeType = require('mime')
const mkdirp = require('mkdirp')
const path = require('path')
const postcss = require('postcss')
const postcssNext = require('postcss-cssnext')
const postcssImport = require('postcss-import')
const postcssReporter = require('postcss-reporter')
const postcssSafeParser = require('postcss-safe-parser')
module.exports = function ({
config,
entry,
outfile,
watch
}) {
let watcher
const transform = () =>
postcss([
postcssImport({
plugins: [
base64ify(process.cwd()) // inline all url files
],
onImport: (sources) => {
if (watch) {
sources.forEach((source) => watcher.add(source))
}
}
}),
postcssNext(),
postcssReporter({clearMessages: true})
])
.process(`${fs.readFileSync(entry, 'utf8')}\n\n${config.style || ''}`, {
parser: postcssSafeParser,
map: true,
to: outfile
})
.then(function (results) {
if (outfile) {
mkdirp.sync(path.dirname(outfile))
fs.writeFileSync(outfile, results.css)
if (results.map) {
fs.writeFile(`${outfile}.map`, results.map, handleErr)
}
console.log(`updated css file: ${outfile}`)
}
return results
})
if (watch) {
watcher = chokidar.watch(entry)
watcher.on('add', transform)
.on('change', transform)
.on('unlink', transform)
}
return transform()
}
const base64ify = postcss.plugin('postcss-base64ify', function () {
return function (css, result) {
const source = css.source.input.file
const dir = path.dirname(source)
css.replaceValues(/url\((\s*)(['"]?)(.+?)\2(\s*)\)/g, function (string) {
const filename = getUrl(string)
.split('?')[0]
.split('#')[0]
let file
if (filename.indexOf('data') === 0 || filename.length === 0) {
return string
} else if (filename[0] === '/') {
file = path.join(process.cwd(), filename)
} else {
file = path.resolve(dir, filename)
}
if (!fs.existsSync(file)) {
throw new Error(`File ${file} does not exist`)
}
const buffer = fs.readFileSync(file)
return 'url("data:' + mimeType.lookup(filename) + ';base64,' + buffer.toString('base64') + '")'
})
}
})
function getUrl (value) {
const reg = /url\((\s*)(['"]?)(.+?)\2(\s*)\)/g
const match = reg.exec(value)
const url = match[3]
return url
}
function handleErr (err) {
if (err) {
console.error(err.stack)
}
}
|
JavaScript
| 0 |
@@ -776,16 +776,48 @@
%7D),%0A
+ base64ify(process.cwd()),%0A
po
@@ -1679,86 +1679,8 @@
) %7B%0A
- const source = css.source.input.file%0A const dir = path.dirname(source)%0A
@@ -2048,16 +2048,102 @@
else %7B%0A
+ const source = css.source.input.file%0A const dir = path.dirname(source)%0A
|
7d73da01fc77b61c8e0022fe512796622dd66720
|
Simplify maxDate
|
app/client/views/activities/form/autoform.js
|
app/client/views/activities/form/autoform.js
|
import SlimSelect from 'slim-select';
import 'slim-select/dist/slimselect.min.css';
import flatpickr from "flatpickr";
import 'flatpickr/dist/flatpickr.min.css';
import moment from 'moment';
import { Finnish } from "flatpickr/dist/l10n/fi.js"
AutoForm.addHooks(['activityForm'], {
'onSuccess': function (formType) {
// Hide the modal dialogue
Modal.hide('activityForm');
// placeholder for success message text
let successMessage;
// Get relevant success message for form type
if (formType === 'update') {
successMessage = TAPi18n.__("activityForm-update-success");
} else {
successMessage = TAPi18n.__("activityForm-add-success");
}
const successMessageWithIcon = '<i class="fa fa-check"></i> ' + successMessage
// Alert user that activity was added
FlashMessages.sendSuccess(successMessageWithIcon);
}
});
Template.autoForm.onRendered(function () {
const instance = this;
// Make sure the new activity form is being rendered
if (instance.data.id === "activityForm") {
// Locale used for calendar widget; undefined means English (default locale)
let locale;
// Get localized placeholder text
const placeholder = TAPi18n.__('activityForm-residentSelect-placeholder');
// Get user locale
const userLocale = TAPi18n.getLanguage();
// Render multi-select widget on 'select residents' field
new SlimSelect({
select: '[name=residentIds]',
closeOnSelect: false,
placeholder,
});
// Localize calendar widget based on user locale
if (userLocale === 'fi') {
locale = Finnish;
}
// Render cross-platform date picker on date field
flatpickr("#activityDate", {
// Minimum day should be within previous seven days, including today
minDate: moment().subtract(6, 'days').startOf('day').toDate(),
maxDate: moment().endOf('day').toDate(),
locale,
});
}
});
|
JavaScript
| 0.999999 |
@@ -1863,38 +1863,15 @@
te:
-moment().endOf('day').toDate()
+%22today%22
,%0A
|
bcbba9625a84ae494745c008e9725371fbbb93cc
|
fix icons
|
packages/icons/fa4/styled.es6
|
packages/icons/fa4/styled.es6
|
import { createComponent } from 'olymp-fela';
export default Wrapped =>
createComponent(
({ theme, color }) => ({
fill:
color === true
? theme.color
: typeof color === 'string' ? color : 'rgba(0, 0, 0, 0.85)',
}),
Wrapped,
[
'width',
'height',
'size',
'onClick',
'onMouseEnter',
'onMouseLeave',
'onMouseOver',
],
);
|
JavaScript
| 0.000001 |
@@ -30,13 +30,13 @@
om '
-olymp
+react
-fel
@@ -95,30 +95,277 @@
(%7B
+%0A
theme,
- color %7D) =%3E (%7B
+%0A color,%0A width,%0A height,%0A size,%0A onClick,%0A margin,%0A marginLeft,%0A marginRight,%0A marginTop,%0A marginBottom,%0A %7D) =%3E (%7B%0A margin,%0A marginLeft,%0A marginRight,%0A marginTop,%0A marginBottom,
%0A
@@ -464,37 +464,42 @@
' ?
-color : 'rgba(0, 0, 0, 0.85)'
+theme%5Bcolor%5D %7C%7C color : theme.dark
,%0A
@@ -646,24 +646,45 @@
MouseOver',%0A
+ 'onMouseDown',%0A
%5D,%0A );%0A
|
96d46c78aac8147038a1fb895849651a0ff5d702
|
update console.logs for improper script usage
|
scripts/prepConsent.js
|
scripts/prepConsent.js
|
const fs = require('fs');
const path = require('path');
const syncCsvParse = require('csv-parse/lib/sync');
const _ = require('lodash');
const moment = require('moment');
// Check command line arguments
if (process.argv.length !== 3) {
console.log('Command line argument missing, aborting...');
console.log('');
console.log('Usage: node tools/consent-teacher-moments.js tmp/PRIVATE_SENSITIVE_DATA/consent-teacher-moments/UserConsent.csv');
process.exit(1);
}
const csvFilename = process.argv[2];
const csvString = fs.readFileSync(csvFilename).toString();
const rows = syncCsvParse(csvString, { columns: true});
// Take most recent entry only, if participant filled it
// out several times.
const rowsByEmail = _.groupBy(rows, 'Email');
const latestRows = _.values(rowsByEmail).map(rows => _.last(rows));
const KEYS = {
'photos': 'May we include you in photographs taken during this event in our materials (website, brochures)?',
'audio': 'I give my permission to be.....',
'permission': 'I give my permission for the following information to be included in publications resulting from this study:',
'email': 'Email',
'consent': 'Consent'
};
const VALUES = {
'audioRecording': 'audio recorded during testing activities and interviews',
'allRecording': 'audio recorded during testing activities and interviews., video recorded during testing activities and interviews.',
'allPermission': 'my name., my title., direct quotes.',
'directQuotes': 'direct quotes',
'giveConsent': 'Yes, I consent to be a part of this study.'
}
// The actual substance of the filters are here
// TODO(kr) should defer these to each analysis
const consentedRows = latestRows.filter((row) => {
if (row[KEYS.audio].indexOf(VALUES.audioRecording) === -1) return false;
if (row[KEYS.permission].indexOf(VALUES.directQuotes) === -1) return false;
if (row[KEYS.consent] !== VALUES.giveConsent) return false;
return true;
});
console.log(`Of ${rows.length} total rows, found ${consentedRows.length} consented email addresses.`);
// Write out to disk
function writeConsentToDisk(consentedRows, filename) {
console.log(`Writing consent information to ${filename}...`);
const output = JSON.stringify({
consented: consentedRows.map(row => row[KEYS.email].toLowerCase())
}, null, 2);
fs.writeFileSync(filename, output);
}
const dateString = moment().format('YYYY-MM-DD');
const filenameWithDate = path.resolve(__dirname, `../tmp/consented-${dateString}.json`);
const filenameLatest = path.resolve(__dirname, `../tmp/consented-latest.json`);
writeConsentToDisk(consentedRows, filenameLatest);
writeConsentToDisk(consentedRows, filenameWithDate);
console.log('Done.');
|
JavaScript
| 0 |
@@ -342,103 +342,55 @@
ode
-tools/consent-teacher-moments.js tmp/PRIVATE_SENSITIVE_DATA/consent-teacher-moments/UserConsent
+scripts/prepConsent.js tmp/consented-latest-raw
.csv
|
edcc824c41ea8c99b375a725d252c769e36d9e2b
|
Remove zoomable prop; add zoomDisabled prop
|
autoHeightWebView/index.js
|
autoHeightWebView/index.js
|
'use strict';
import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react';
import { StyleSheet, Platform, ViewPropTypes } from 'react-native';
import PropTypes from 'prop-types';
import { WebView } from 'react-native-webview';
import { reduceData, getWidth, isSizeChanged, shouldUpdate } from './utils';
const AutoHeightWebView = React.memo(
forwardRef((props, ref) => {
const { style, onMessage, onSizeUpdated, scrollEnabledWithZoomedin, scrollEnabled, source } = props;
if (!source) {
return null;
}
let webView = useRef();
useImperativeHandle(ref, () => ({
stopLoading: () => webView.current.stopLoading(),
goForward: () => webView.current.goForward(),
goBack: () => webView.current.goBack(),
reload: () => webView.current.reload(),
injectJavaScript: script => webView.current.injectJavaScript(script)
}));
const [size, setSize] = useState({
height: style && style.height ? style.height : 0,
width: getWidth(style)
});
const [scrollable, setScrollable] = useState(false);
const handleMessage = event => {
onMessage && onMessage(event);
if (!event.nativeEvent) {
return;
}
let data = {};
// Sometimes the message is invalid JSON, so we ignore that case
try {
data = JSON.parse(event.nativeEvent.data);
} catch (error) {
console.error(error);
return;
}
const { height, width, zoomin } = data;
!scrollEnabled && scrollEnabledWithZoomedin && setScrollable(zoomin);
const { height: previousHeight, width: previousWidth } = size;
isSizeChanged({ height, previousHeight, width, previousWidth }) &&
setSize({
height,
width
});
};
const currentScrollEnabled = scrollEnabled === false && scrollEnabledWithZoomedin ? scrollable : scrollEnabled;
const { currentSource, script } = reduceData(props);
const { width, height } = size;
useEffect(
() =>
onSizeUpdated &&
onSizeUpdated({
height,
width
}),
[width, height, onSizeUpdated]
);
return (
<WebView
{...props}
ref={webView}
onMessage={handleMessage}
style={[
styles.webView,
{
width,
height
},
style
]}
injectedJavaScript={script}
source={currentSource}
scrollEnabled={currentScrollEnabled}
/>
);
}),
(prevProps, nextProps) => !shouldUpdate({ prevProps, nextProps })
);
AutoHeightWebView.propTypes = {
onSizeUpdated: PropTypes.func,
files: PropTypes.arrayOf(
PropTypes.shape({
href: PropTypes.string,
type: PropTypes.string,
rel: PropTypes.string
})
),
style: ViewPropTypes.style,
customScript: PropTypes.string,
customStyle: PropTypes.string,
zoomable: PropTypes.bool,
scrollEnabledWithZoomedin: PropTypes.bool,
// webview props
originWhitelist: PropTypes.arrayOf(PropTypes.string),
onMessage: PropTypes.func,
scalesPageToFit: PropTypes.bool,
source: PropTypes.object
};
let defaultProps = {
showsVerticalScrollIndicator: false,
showsHorizontalScrollIndicator: false,
originWhitelist: ['*'],
zoomable: true
};
Platform.OS === 'android' &&
Object.assign(defaultProps, {
scalesPageToFit: false
});
AutoHeightWebView.defaultProps = defaultProps;
const styles = StyleSheet.create({
webView: {
backgroundColor: 'transparent'
}
});
export default AutoHeightWebView;
|
JavaScript
| 0.000001 |
@@ -2932,20 +2932,24 @@
,%0A zoom
+Dis
able
+d
: PropTy
@@ -3302,26 +3302,8 @@
'*'%5D
-,%0A zoomable: true
%0A%7D;%0A
|
fbbad7cbb205afcc96e8718d8b9823d0d7ab49f7
|
improve isGroupWithServices boolean
|
plugins/services/src/js/components/modals/ServiceDestroyModal.js
|
plugins/services/src/js/components/modals/ServiceDestroyModal.js
|
import { Confirm } from "reactjs-components";
import { routerShape } from "react-router";
import PureRender from "react-addons-pure-render-mixin";
import React, { PropTypes } from "react";
import { injectIntl, intlShape } from "react-intl";
import ModalHeading from "#SRC/js/components/modals/ModalHeading";
import StringUtil from "#SRC/js/utils/StringUtil";
import UserActions from "#SRC/js/constants/UserActions";
import AppLockedMessage from "./AppLockedMessage";
import Framework from "../../structs/Framework";
import Pod from "../../structs/Pod";
import Service from "../../structs/Service";
import ServiceTree from "../../structs/ServiceTree";
// This needs to be at least equal to @modal-animation-duration
const REDIRECT_DELAY = 300;
const METHODS_TO_BIND = [
"handleChangeInputFieldDestroy",
"handleModalClose",
"handleRightButtonClick",
"handleChangeInputGroupDestroy"
];
class ServiceDestroyModal extends React.Component {
constructor() {
super(...arguments);
this.state = {
errorMsg: null,
serviceNameConfirmationValue: "",
forceDeleteGroupWithServices: false
};
this.shouldComponentUpdate = PureRender.shouldComponentUpdate.bind(this);
METHODS_TO_BIND.forEach(method => {
this[method] = this[method].bind(this);
});
}
componentWillUpdate(nextProps) {
const requestCompleted = this.props.isPending && !nextProps.isPending;
const shouldClose = requestCompleted && !nextProps.errors;
if (shouldClose) {
this.redirectToServices();
}
}
componentWillReceiveProps(nextProps) {
const { errors } = nextProps;
if (!errors) {
this.setState({ errorMsg: null });
return;
}
if (typeof errors === "string") {
this.setState({ errorMsg: errors });
return;
}
let { message: errorMsg = "", details } = errors;
const hasDetails = details && details.length !== 0;
if (hasDetails) {
errorMsg = details.reduce(function(memo, error) {
return `${memo} ${error.errors.join(" ")}`;
}, "");
}
if (!errorMsg || !errorMsg.length) {
errorMsg = null;
}
this.setState({ errorMsg });
}
shouldForceUpdate() {
return (
(this.state.errorMsg && /force=true/.test(this.state.errorMsg)) ||
this.state.forceDeleteGroupWithServices
);
}
isGroupWithServices(service) {
if (service instanceof ServiceTree && service.getItems().length > 0) {
return true;
}
return false;
}
handleModalClose() {
this.setState({ serviceNameConfirmationValue: "" });
this.props.onClose();
}
handleRightButtonClick() {
if (!this.getIsRightButtonDisabled()) {
this.props.deleteItem(this.shouldForceUpdate());
this.setState({ serviceNameConfirmationValue: "" });
}
}
handleChangeInputFieldDestroy(event) {
this.setState({
serviceNameConfirmationValue: event.target.value
});
}
handleChangeInputGroupDestroy(event) {
this.setState({
forceDeleteGroupWithServices: event.target.checked
});
}
getIsRightButtonDisabled() {
return (
this.props.service.getName() !== this.state.serviceNameConfirmationValue
);
}
getErrorMessage() {
const { errorMsg = null } = this.state;
if (!errorMsg) {
return null;
}
if (this.shouldForceUpdate()) {
return <AppLockedMessage service={this.props.service} />;
}
return (
<h4 className="text-align-center text-danger flush-top">{errorMsg}</h4>
);
}
redirectToServices() {
const { router } = this.context;
// Close the modal and redirect after the close animation has completed
this.handleModalClose();
setTimeout(() => {
router.push({ pathname: "/services/overview" });
}, REDIRECT_DELAY);
}
getCloseButton() {
return (
<div className="row text-align-center">
<button
className="button button-primary button-medium"
onClick={this.handleModalClose}
>
Close
</button>
</div>
);
}
getGroupHeader() {
const { service } = this.props;
if (!this.isGroupWithServices(service)) {
return null;
}
return (
<div className="modal-service-delete-center">
<p>
This group needs to be empty to delete it. Please delete any services in the group first.
</p>
<p>
<label className="modal-service-delete-force">
<input
type="checkbox"
checked={this.state.forceDeleteGroupWithServices}
onChange={this.handleChangeInputGroupDestroy}
/>
<b>FORCE DELETE SERVICES IN GROUP</b>
</label>
</p>
</div>
);
}
getServiceDeleteForm() {
const { service } = this.props;
const serviceName = service.getName();
const serviceLabel = this.getServiceLabel();
if (
this.isGroupWithServices(service) &&
!this.state.forceDeleteGroupWithServices
) {
return null;
}
return (
<div className="modal-service-delete-center">
<p>
This action
{" "}
<strong>CANNOT</strong>
{" "}
be undone. This will permanently delete the
{" "}
<strong>{serviceName}</strong>
{" "}
{serviceLabel.toLowerCase()}
{this.state.forceDeleteGroupWithServices &&
<span>and any services in the group</span>}
.
</p>
<p>
Type ("
<strong>{serviceName}</strong>
") below to confirm you want to delete the
{" "}
{serviceLabel.toLowerCase()}.
</p>
<input
className="form-control filter-input-text"
onChange={this.handleChangeInputFieldDestroy}
type="text"
value={this.state.serviceNameConfirmationValue}
autoFocus
/>
</div>
);
}
getDestroyServiceModal() {
const { open } = this.props;
const serviceLabel = this.getServiceLabel();
const itemText = `${StringUtil.capitalize(UserActions.DELETE)} ${serviceLabel}`;
return (
<Confirm
disabled={this.getIsRightButtonDisabled()}
header={this.getModalHeading()}
open={open}
onClose={this.handleModalClose}
leftButtonText="Cancel"
leftButtonCallback={this.handleModalClose}
rightButtonText={itemText}
rightButtonClassName="button button-danger"
rightButtonCallback={this.handleRightButtonClick}
showHeader={true}
>
{this.getGroupHeader()}
{this.getServiceDeleteForm()}
{this.getErrorMessage()}
</Confirm>
);
}
getModalHeading() {
const serviceLabel = this.getServiceLabel();
return (
<ModalHeading className="text-danger">
{StringUtil.capitalize(UserActions.DELETE)} {serviceLabel}
</ModalHeading>
);
}
getSubHeader() {
if (!this.props.subHeaderContent) {
return null;
}
return (
<p className="text-align-center flush-bottom">
{this.props.subHeaderContent}
</p>
);
}
getServiceLabel() {
const { service } = this.props;
if (service instanceof Pod) {
return "Pod";
}
if (service instanceof ServiceTree) {
return "Group";
}
return "Service";
}
render() {
return this.getDestroyServiceModal();
}
}
ServiceDestroyModal.contextTypes = {
router: routerShape
};
ServiceDestroyModal.propTypes = {
deleteItem: PropTypes.func.isRequired,
errors: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
intl: intlShape.isRequired,
isPending: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
open: PropTypes.bool.isRequired,
service: PropTypes.oneOfType([
PropTypes.instanceOf(Framework),
PropTypes.instanceOf(Pod),
PropTypes.instanceOf(ServiceTree),
PropTypes.instanceOf(Service)
]).isRequired
};
module.exports = injectIntl(ServiceDestroyModal);
|
JavaScript
| 0.000001 |
@@ -2367,28 +2367,31 @@
vice) %7B%0A
-if (
+return
service inst
@@ -2445,54 +2445,8 @@
%3E 0
-) %7B%0A return true;%0A %7D%0A%0A return false
;%0A
|
68b32e891a08b3b24217f59493283e5891119a4b
|
Update github-toggle-expanders.user.js
|
github-toggle-expanders.user.js
|
github-toggle-expanders.user.js
|
// ==UserScript==
// @name GitHub Toggle Expanders
// @version 1.0.4
// @description A userscript that toggles all expanders when one expander is shift-clicked
// @license https://creativecommons.org/licenses/by-sa/4.0/
// @author Rob Garrison
// @namespace https://github.com/Mottie
// @include https://github.com/*
// @run-at document-idle
// @icon https://github.com/fluidicon.png
// @updateURL https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-toggle-expanders.user.js
// @downloadURL https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-toggle-expanders.user.js
// ==/UserScript==
(() => {
"use strict";
function toggle(el) {
const state = closest(".commits-list-item, .js-details-container", el)
.classList.contains("open"),
// target buttons inside commits_bucket - fixes #8
selector = `.commits-listing .commits-list-item, #commits_bucket .js-details-container`;
Array.from(document.querySelectorAll(selector)).forEach(el => {
el.classList.toggle("open", state);
});
}
function closest(selector, el) {
while (el && el.nodeType === 1) {
if (el.matches(selector)) {
return el;
}
el = el.parentNode;
}
return null;
}
document.body.addEventListener("click", event => {
const target = event.target;
if (
target && event.getModifierState("Shift") &&
target.matches(".ellipsis-expander")
) {
// give GitHub time to add the class
setTimeout(() => {
toggle(target);
}, 100);
}
});
})();
|
JavaScript
| 0 |
@@ -939,16 +939,63 @@
_bucket
+.js-details-container, .release-timeline-tags
.js-deta
|
aa494b2e564b2f2b3ff8efb2a9112edef0d928ff
|
Add the fucking NewRelic key
|
newrelic.js
|
newrelic.js
|
/**
* New Relic agent configuration.
*
* See lib/config.defaults.js in the agent distribution for a more complete
* description of configuration variables and their potential values.
*/
exports.config = {
/**
* Array of application names.
*/
app_name : ['Segment'],
/**
* Your New Relic license key.
*/
license_key : 'license key here',
logging : {
/**
* Level at which to log. 'trace' is most useful to New Relic when diagnosing
* issues with the agent, 'info' and higher will impose the least overhead on
* production applications.
*/
level : 'info'
}
};
|
JavaScript
| 0.000009 |
@@ -203,16 +203,17 @@
fig = %7B%0A
+%0A
/**%0A
@@ -259,17 +259,16 @@
app_name
-
: %5B'Segm
@@ -274,16 +274,17 @@
ment'%5D,%0A
+%0A
/**%0A
@@ -337,31 +337,55 @@
_key
-
: '
-license key here
+3b27fea0ee497bbeb501cab516c9599f25fe942d
',%0A
+%0A
lo
@@ -393,13 +393,13 @@
ging
-
: %7B%0A
+%0A
@@ -619,21 +619,22 @@
evel
-
: '
-info
+trace
'%0A %7D%0A
+%0A
%7D;%0A
|
4931e69a4fa2f5f28259218a8f14fb542e41f339
|
remove log
|
lib/index.js
|
lib/index.js
|
var Readable = require('readable-stream').Readable;
/**
* Tests that two readable streams are equal.
*
* @param {Readable|Stream} readStream2
* @param {Readable|Stream} readStream2
* @param {Function(!Error, Boolean)} callback
*/
module.exports = function streamEqual(readStream1, readStream2, callback) {
readStream1 = getReadable(readStream1);
readStream1.id = 1;
readStream2 = getReadable(readStream2);
readStream2.id = 2;
var stream1 = {
stream: readStream1,
data: null, pos: 0,
ended: false,
readable: false,
onreadable: function onreadable() {
stream1.readable = true;
}
};
var stream2 = {
stream: readStream2,
data: null,
pos: 0,
ended: false,
readable: false,
onreadable: function onreadable() {
stream2.readable = true;
}
};
var read1 = createRead(stream1, stream2, cleanup);
var read2 = createRead(stream2, stream1, cleanup);
var onend1 = createOnEnd(stream1, stream2, cleanup);
var onend2 = createOnEnd(stream2, stream1, cleanup);
function cleanup(err, equal) {
readStream1.removeListener('readable', stream1.onreadable);
readStream1.removeListener('error', cleanup);
readStream1.removeListener('end', onend1);
readStream2.removeListener('readable', stream2.onreadable);
readStream2.removeListener('error', cleanup);
readStream2.removeListener('end', onend2);
callback(err, equal);
}
stream1.read = read1;
readStream1.on('readable', stream1.onreadable);
readStream1.on('end', onend1);
readStream1.on('error', cleanup);
stream2.read = read2;
readStream2.on('readable', stream2.onreadable);
readStream2.on('end', onend2);
readStream2.on('error', cleanup);
// Start by reading from the first stream.
read1();
};
/**
* Returns a function that compares emitted `read()` call with that of the
* most recent `read` call from another stream.
*
* @param {Object} stream
* @param {Object} otherStream
* @param {Function(Error, Boolean)} callback
* @return {Function(Buffer|String)}
*/
function createRead(stream, otherStream, callback) {
return function read() {
if (!stream.readable) {
return stream.stream.once('readable', stream.read);
}
stream.readable = false;
var data = stream.stream.read();
if (!data) {
console.log('no data', stream.stream.id);
return stream.stream.once('readable', stream.read);
}
// Make sure `data` is a buffer.
if (!Buffer.isBuffer(data)) {
var type = typeof data;
if (type === 'string') {
data = new Buffer(data);
} else if (type === 'object') {
data = JSON.stringify(data);
} else {
data = new Buffer(data.toString());
}
}
var newPos = stream.pos + data.length;
if (stream.pos < otherStream.pos) {
var minLength = Math.min(data.length, otherStream.data.length);
var streamData = data.slice(0, minLength);
stream.data = data.slice(minLength);
var otherStreamData = otherStream.data.slice(0, minLength);
otherStream.data = otherStream.data.slice(minLength);
// Compare.
for (var i = 0, len = streamData.length; i < len; i++) {
if (streamData[i] !== otherStreamData[i]) {
return callback(null, false);
}
}
} else if (stream.data && stream.data.length) {
stream.data = Buffer.concat([stream.data, data]);
} else {
stream.data = data;
}
stream.pos = newPos;
if (newPos > otherStream.pos) {
if (otherStream.ended) {
// If this stream is still emitting `data` events but the other has
// ended, then this is longer than the other one.
return callback(null, false);
}
// If this stream has caught up to the other,
// read from other one.
otherStream.read();
} else {
stream.read();
}
};
}
/**
* Creates a function that gets called when a stream ends.
*
* @param {Object} stream
* @param {Object} otherStream
* @param {Function(!Error, Boolean)} callback
*/
function createOnEnd(stream, otherStream, callback) {
return function onend() {
stream.ended = true;
if (otherStream.ended) {
callback(null, stream.pos === otherStream.pos);
} else {
otherStream.read();
}
};
}
/**
* Returns a readable new stream API stream if the stream is using the
* old API. Otherwise it returns the same stream.
*
* @param {Readable|Stream} stream
* @return {Readable}
*/
function getReadable(stream) {
var readable;
if (isOldStyleStream(stream)) {
readable = new Readable();
readable.wrap(stream);
stream = readable;
}
return stream;
}
/**
* Returns true if a stream is an old style API stream.
*
* @param {Readable|Stream} stream
* @return {Boolean}
*/
function isOldStyleStream(stream) {
return typeof stream.read !== 'function' ||
typeof stream._read !== 'function' ||
typeof stream.push !== 'function' ||
typeof stream.unshift !== 'function' ||
typeof stream.wrap !== 'function';
}
|
JavaScript
| 0.000001 |
@@ -2303,56 +2303,8 @@
) %7B%0A
- console.log('no data', stream.stream.id);%0A
|
cfb4e3f25bbe1579b96d30d81b7a82a5bcf6ce43
|
Set reserved usernames
|
lib/api.js
|
lib/api.js
|
// /api endpoint and authentication.
var log = require('./log');
var pg = require('pg');
var configuration = require('./conf');
var pgConfig = configuration.pg;
pgConfig.pg = pg;
var EmailLogin = require('email-login');
var emailLogin = new EmailLogin({
db: new EmailLogin.PgDb(pgConfig),
mailer: configuration.mailer,
});
var website = "http://127.0.0.1:1234";
exports.main = function (camp) {
camp.get('/api/1/signup', signup);
camp.get('/api/1/login', login);
camp.get('/~', home);
camp.handle(authenticate);
};
function error(code, msg, err, res) {
log.error(err);
res.statusCode = code || 500;
res.end(msg || 'Internal server error\n');
}
function signup(req, res) {
var email = req.data.email;
var name = req.data.name;
emailLogin.login(function(err, token, session) {
if (err != null) { error(500, "Sign up failed", err, res); return; }
req.cookies.set('token', token);
emailLogin.proveEmail({
token: token,
email: email,
name: 'TheFileTree account creation: confirm your email address',
confirmUrl: function(tok) {
return website + "/api/1/login?name=" + encodeURIComponent(name) +
"&token=" + tok;
},
}, function(err) {
if (err != null) {
error(500, "Sending the email confirmation failed", err, res);
return;
}
res.redirect('/app/account/signed-up.html');
});
});
}
function login(req, res) {
var name = req.data.name;
emailLogin.confirmEmail(req.cookies.get('token'), req.data.token,
function(err, token, session) {
if (err != null) { error(500, "Login failed", err, res); return; }
if (token) {
emailLogin.setAccountData(session.email, {name: name}, function(err) {
if (err != null) { error(500, "Login failed", err, res); return; }
req.cookies.set('token', token);
res.redirect('/app/account/logged-in.html');
});
} else {
res.redirect('/app/account/email-not-confirmed.html');
}
});
}
function home(req, res) {
if (req.user && (typeof req.user.name === 'string')) {
res.redirect('/' + req.user.name);
} else { res.redirect('/'); }
}
function authenticate(req, res, next) {
emailLogin.authenticate(req.cookies.get('token'),
function(err, authenticated, session, token) {
if (token) { req.cookies.set('token', token); }
if (authenticated && session.emailVerified()) {
req.user = {
email: session.email,
name: session.account.data.name,
};
}
next();
});
}
exports.authenticate = authenticate;
|
JavaScript
| 0.000001 |
@@ -562,16 +562,27 @@
res) %7B%0A
+ if (err) %7B
log.err
@@ -589,16 +589,18 @@
or(err);
+ %7D
%0A res.s
@@ -634,12 +634,23 @@
res.
-end(
+json(%7Berrors: %5B
msg
@@ -666,114 +666,598 @@
nal
-server error%5Cn');%0A%7D%0A%0Afunction signup(req, res) %7B%0A var email = req.data.email;%0A var name = req.data.name;
+Server Error'%5D%7D);%0A%7D%0A%0A// The following should be considered a valid name: 0%C3%A9e%CC%81%CE%BB%E7%B5%B1%F0%9D%8C%86%0Avar allowedUsernames = /%5E%5B%5Cw%5Cxa0-%5Cu1fff%5Cu2c00-%5Cu2dff%5Cu2e80-%5Cud7ff%5Cuf900-%5Cuffef%5Cu%7B10000%7D-%5Cu%7B2fa1f%7D%5D%7B1,20%7D$/u;%0Avar reservedNames = /%5E(root%7Capp%7Cabout%7Cdemo%7Clib%7Capi%7Cdoc%7Ctest%7C%5Cw%7C%5Cw%5Cw)$/;%0A%0Afunction allowedUsername(name) %7B%0A // FIXME: Verify inexistence in database.%0A return allowedUsernames.test(name) && !reservedNames.test(name);%0A%7D%0A%0Afunction signup(req, res) %7B%0A var email = req.data.email;%0A var name = req.data.name;%0A if (!allowedUsernames(name)) %7B%0A error(400, %22Disallowed name%22, null, res);%0A return;%0A %7D
%0A e
|
a1f38851a9deafed8e8ef23b1fd1db9f200721db
|
Use event.which to get keycode
|
app/components/Fields/Group/NewBlockModal.js
|
app/components/Fields/Group/NewBlockModal.js
|
import React, { Component, PropTypes } from 'react';
import Input from 'components/Input';
import Button from 'components/Button';
import { slugify } from 'utils/helpers';
export default class NewBlockModal extends Component {
static propTypes = {
confirm: PropTypes.func.isRequired,
close: PropTypes.func,
}
static defaultProps = {
close: null,
}
constructor(props) {
super(props);
this.confirm = this.confirm.bind(this);
this.handleTitleChange = this.handleTitleChange.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
state = { title: '' }
confirm() {
this.props.confirm({
name: this.name.value,
handle: slugify(this.state.title),
fields: [{
label: 'Blank',
handle: 'blank-0',
}],
});
this.props.close();
}
handleTitleChange(title) {
this.setState({ title });
}
handleKeyPress(e) {
if (e.key === 'Enter') this.confirm();
}
render() {
const { close } = this.props;
return (
<div className="modal--newblock">
<Input
name="name"
label="Name"
required
ref={(r) => { this.name = r; }}
instructions="What this block will be called in the dashboard."
onChange={this.handleTitleChange}
full
autoFocus
onKeyPress={this.handleKeyPress}
/>
<Input
name="handle"
label="Handle"
required
readOnly
ref={(r) => { this.handle = r; }}
instructions="How you'll refer to this block type in your templates."
full
code
value={slugify(this.state.title)}
/>
<div className="modal__buttons">
<Button small onClick={this.confirm}>Confirm</Button>
<Button small onClick={close} kind="subtle">Cancel</Button>
</div>
</div>
);
}
}
|
JavaScript
| 0.000001 |
@@ -925,23 +925,20 @@
(e.
-key === 'Enter'
+which === 13
) th
|
d6dc1ffb0d21716a0afbc9de3de075b0e22b472d
|
Add find method to Collection.
|
fileshack/static/fileshack/js/collections.js
|
fileshack/static/fileshack/js/collections.js
|
/*
* Copyright (c) 2012 Peter Kuma
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var Collection = new Class({
Implements: Events,
initialize: function() {
this.views = {};
},
get: function(id) {
return this.views[id];
},
all: function() {
return this.views;
},
add: function(view) {
var this_ = this;
var id = view.model.id;
this.views[id] = view;
view.model.addEvent('change', function() {
if (id != view.model.id) {
this_.views[view.model.id] = view;
delete this_.views[id];
id = view.model.id;
}
this_.fireEvent('change', view);
});
view.model.addEvent('remove', function() {
this_.remove(view);
});
this.fireEvent('add', view);
},
remove: function(view) {
delete this.views[view.model.id];
this.fireEvent('remove', view);
},
contains: function(id) {
return (id in this.views);
}
});
|
JavaScript
| 0 |
@@ -1337,16 +1337,200 @@
;%0A %7D,
+%0A %0A find: function(func) %7B%0A%09var view = null;%0A%09Object.each(this.views, function(v) %7B%0A%09 if (view) return; // Already found.%0A%09 if (func(v)) view = v;%0A%09%7D);%0A%09return view;%0A %7D,
%0A%0A ad
|
0dea69099014c0ebc0e624f1d651968259c372a6
|
clear box timeout on rerender
|
src/RenderingMonitor.js
|
src/RenderingMonitor.js
|
import mobservable from 'mobservable';
import mobservableReact from 'mobservable-react';
const getCost = renderTime => {
switch(true) {
case renderTime < 25: return 'cheap';
case renderTime < 100: return 'acceptable';
default: return 'expensive'
}
};
export default class RenderingMonitor {
boxesList = [];
_boxesRegistry = typeof WeakMap !== 'undefined' ? new WeakMap() : new Map();
constructor({ hightlightTimeout, onUpdate, shouldReport, getCoordinates }) {
this.handleUpdate = onUpdate;
this._disposeRenderReporter = mobservableReact.renderReporter.on(report => {
if (shouldReport() !== true) return;
switch (report.event) {
case 'render':
if (!report.node) return;
const offset = getCoordinates(report.node);
const box = this.getBoxForNode(report.node);
box.type = 'rendering';
box.y = offset.top;
box.x = offset.left;
box.width = report.node.offsetWidth;
box.height = report.node.offsetHeight;
box.renderInfo = {
count: box.renderInfo && ++box.renderInfo.count || 1,
renderTime: report.renderTime,
totalTime: report.totalTime,
cost: getCost(report.renderTime),
};
if (this.boxesList.indexOf(box) === -1) this.boxesList = this.boxesList.concat([box]);
this.handleUpdate();
setTimeout(() => this.removeBox(report.node, true), hightlightTimeout);
return;
case 'destroy':
this.removeBox(report.node);
this._boxesRegistry.delete(report.node);
return;
default:
return;
}
});
}
getBoxForNode(node) {
if (this._boxesRegistry.has(node)) return this._boxesRegistry.get(node);
const box = {
id: Math.random().toString(32).substr(2),
};
this._boxesRegistry.set(node, box);
return box;
};
dispose() {
this._disposeRenderReporter();
}
removeBox(node) {
if (this._boxesRegistry.has(node) === false) return;
const index = this.boxesList.indexOf(this._boxesRegistry.get(node));
if (index !== -1) {
this.boxesList = this.boxesList.slice(0, index).concat(this.boxesList.slice(index + 1));
this.handleUpdate();
}
};
}
|
JavaScript
| 0 |
@@ -1406,16 +1406,87 @@
+ if (box._timeout) clearTimeout(box._timeout);%0A box._timeout =
setTime
|
e40b4d799a2a4246dd870379124c1c8a5a3b00f3
|
save view in local storage if possible
|
js/index.js
|
js/index.js
|
d3.layout = {};
window.minute = window.minute || {views:{}};
minute.dataFrom = null;
minute.lines = null;
minute.csv = null;
minute.view = 'basic';
minute.timeout = null;
minute.loadingDom = d3.select('#load').node();
minute.wrapDom = document.getElementById("keystrokes");
minute.gather = function(cb){
minute.loadingDom.style.visibility = "visible";
d3.csv("keystrokes.log", function(csv) {
minute.loadingDom.style.visibility = "hidden";
if (!csv) {
d3.select('#help')
.style('display', 'block');
return;
}
minute.csv = csv;
minute.lines = [];
for(var i=0; i<csv.length; i++){
minute.lines.push(csv[i].minute+","+csv[i].strokes);
}
minute.dataFrom = Date.now();
cb();
});
}
minute.draw = function(){
if(minute.timeout){
clearTimeout(minute.timeout);
}
var dataFrom = minute.dataFrom ? minute.dataFrom : 0;
var dataAge = Date.now() - dataFrom;
var twoMinutes = 1000*60*2;
if(dataAge > twoMinutes){
minute.gather(minute.draw);
}
else{
minute.wrapDom.innerHTML = "<div id='keystrokes-canvas'></div>";
var w = window.innerWidth,
h = window.innerHeight-24,
top = 24;
minute.views[minute.view](minute.csv, minute.lines, w, h, top);
minute.timeout = setTimeout(minute.draw, twoMinutes);
}
}
minute.changeView = function(view){
d3.select("#"+minute.view+"-button").node().classList.remove("selected");
minute.view = view;
d3.select("#"+minute.view+"-button").node().classList.add("selected");
minute.draw();
}
|
JavaScript
| 0 |
@@ -269,16 +269,180 @@
kes%22);%0A%0A
+minute.start = function()%7B%0A%09var view = window.localStorage === undefined ? 'basic' : (window.localStorage.getItem(%22view%22) %7C%7C 'basic');%0A%09minute.changeView(view);%0A%7D%0A%0A
minute.g
@@ -1646,9 +1646,85 @@
draw();%0A
-%7D
+%0A%09if(window.localStorage)%7B%0A%09%09window.localStorage.setItem(%22view%22, view);%0A%09%7D%0A%7D%0A
|
057b8cce2faa4f0528a68a6b71b265349294ce80
|
allow for earlier versions of node
|
src/RunWrappers/Node.js
|
src/RunWrappers/Node.js
|
/**
* Wrapper to manage services via PM2
*/
var _ = require('lodash');
var path = require('path');
var pm2 = require('pm2');
var semver = require('semver');
require('colors');
function Runner() {
}
Runner.prototype.init = function(bosco, next) {
this.bosco = bosco;
pm2.connect(next);
}
Runner.prototype.disconnect = function(next) {
pm2.disconnect(next);
}
/**
* List running services
*/
Runner.prototype.listRunning = function(detailed, next) {
pm2.list(function(err, list) {
var filteredList = _.filter(list, function(pm2Process){ return pm2Process.pm2_env.status === 'online' || pm2Process.pm2_env.status === 'errored' })
if(!detailed) return next(err, _.pluck(filteredList,'name'));
next(err, filteredList);
});
}
/**
* List services that have been created but are not running
*/
Runner.prototype.listNotRunning = function(detailed, next) {
pm2.list(function(err, list) {
var filteredList = _.filter(list, function(pm2Process){ return pm2Process.pm2_env.status !== 'online' })
if(!detailed) return next(err, _.pluck(filteredList,'name'));
next(err, filteredList);
});
}
/**
* Start a specific service
* options = {cmd, cwd, name}
*/
Runner.prototype.start = function(options, next) {
var self = this;
// Remove node from the start script as not req'd for PM2
var startCmd = options.service.start, startArr, start, ext;
if(startCmd.split(' ')[0] == 'node') {
startArr = startCmd.split(' ');
startArr.shift();
start = startArr.join(' ');
ext = path.extname(startCmd);
if(!path.extname(start)) {
ext = '.js';
start = start + '.js';
}
} else {
start = startCmd;
}
// Always execute as a forked process to allow node version selection
var executeCommand = true;
// If the command has a -- in it then we know it is passing parameters
// to pm2
var argumentPos = start.indexOf(' -- ');
var location = start;
var scriptArgs = [];
if (argumentPos > -1) {
scriptArgs = start.substring(argumentPos + 4, start.length).split(' ');
location = start.substring(0, argumentPos);
}
if(!self.bosco.exists(options.cwd + '/' + location)) {
self.bosco.warn('Can\'t start ' + options.name.red + ', as I can\'t find script: ' + location.red);
return next();
}
var startOptions = { name: options.name, cwd: options.cwd, watch: options.watch, executeCommand: executeCommand, force: true, scriptArgs: scriptArgs };
var interpreter = getInterpreter(this.bosco, options.service);
if(interpreter) {
if(!self.bosco.exists(interpreter)) {
self.bosco.warn('Unable to locate node version requested: ' + interpreter.cyan + '. Reverting to default.');
} else {
startOptions.interpreter = interpreter;
self.bosco.log('Starting ' + options.name.cyan + ' via ' + interpreter + ' ...');
}
} else {
self.bosco.log('Starting ' + options.name.cyan + ' via ...');
}
pm2.start(location, startOptions, next);
}
/**
* List running services
*/
Runner.prototype.stop = function(options, next) {
var self = this;
self.bosco.log('Stopping ' + options.name.cyan);
pm2.stop(options.name, function(err) {
if(err) return next(err);
pm2.delete(options.name, function(err) {
next(err);
});
});
}
function getInterpreter(bosco, service) {
if(!service.nodeVersion) {
return;
}
var homeFolder = bosco.findHomeFolder(), nvmNodePath;
if(semver.gt(service.nodeVersion, '0.12.0')) {
nvmNodePath = path.join('/.nvm/versions/io.js/','v' + service.nodeVersion,'/bin/node');
} else {
nvmNodePath = path.join('/.nvm/versions/node/','v' + service.nodeVersion,'/bin/node');
}
return path.join(homeFolder, nvmNodePath);
}
module.exports = new Runner();
|
JavaScript
| 0 |
@@ -3380,16 +3380,17 @@
emver.gt
+e
(service
@@ -3408,12 +3408,11 @@
n, '
-0.12
+1.0
.0')
@@ -3507,16 +3507,164 @@
node');%0A
+ %7D else if(semver.gte(service.nodeVersion, '0.12.0')) %7B%0A nvmNodePath = path.join('/.nvm/versions/node/','v' + service.nodeVersion,'/bin/node');%0A
%7D else
@@ -3697,38 +3697,24 @@
join('/.nvm/
-versions/node/
','v' + serv
|
6ee34e1ced9e8d089d8ef21a7d04855e568f4b53
|
Fix errors pointed out by JSCS from `gulpfile.js`
|
gulpfile.js
|
gulpfile.js
|
var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')(); // Load all gulp plugins
// automatically and attach
// them to the `plugins` object
var runSequence = require('run-sequence'); // Temporary solution until gulp 4
// https://github.com/gulpjs/gulp/issues/355
var pkg = require('./package.json');
var dirs = pkg['h5bp-configs'].directories;
// ---------------------------------------------------------------------
// | Helper tasks |
// ---------------------------------------------------------------------
gulp.task('archive:create_archive_dir', function () {
fs.mkdirSync(path.resolve(dirs.archive), '0755');
});
gulp.task('archive:zip', function (done) {
var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip');
var archiver = require('archiver')('zip');
var files = require('glob').sync('**/*.*', {
'cwd': dirs.dist,
'dot': true // include hidden files
});
var output = fs.createWriteStream(archiveName);
archiver.on('error', function (error) {
done();
throw error;
});
output.on('close', done);
files.forEach(function (file) {
var filePath = path.resolve(dirs.dist, file);
// `archiver.bulk` does not maintain the file
// permissions, so we need to add files individually
archiver.append(fs.createReadStream(filePath), {
'name': file,
'mode': fs.statSync(filePath)
});
});
archiver.pipe(output);
archiver.finalize();
});
gulp.task('clean', function (done) {
require('del')([
dirs.archive,
dirs.dist
], done);
});
gulp.task('copy', [
'copy:.htaccess',
'copy:index.html',
'copy:jquery',
'copy:license',
'copy:main.css',
'copy:misc',
'copy:normalize'
]);
gulp.task('copy:.htaccess', function () {
return gulp.src('node_modules/apache-server-configs/dist/.htaccess')
.pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument'))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:index.html', function () {
return gulp.src(dirs.src + '/index.html')
.pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:jquery', function () {
return gulp.src(['node_modules/jquery/dist/jquery.min.js'])
.pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js'))
.pipe(gulp.dest(dirs.dist + '/js/vendor'));
});
gulp.task('copy:license', function () {
return gulp.src('LICENSE.txt')
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:main.css', function () {
var banner = '/*! HTML5 Boilerplate v' + pkg.version +
' | ' + pkg.license.type + ' License' +
' | ' + pkg.homepage + ' */\n\n';
return gulp.src(dirs.src + '/css/main.css')
.pipe(plugins.header(banner))
.pipe(plugins.autoprefixer({
browsers: ['last 2 versions', 'ie >= 8', '> 1%'],
cascade: false
}))
.pipe(gulp.dest(dirs.dist + '/css'));
});
gulp.task('copy:misc', function () {
return gulp.src([
// Copy all files
dirs.src + '/**/*',
// Exclude the following files
// (other tasks will handle the copying of these files)
'!' + dirs.src + '/css/main.css',
'!' + dirs.src + '/index.html'
], {
// Include hidden files by default
dot: true
}).pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:normalize', function () {
return gulp.src('node_modules/normalize.css/normalize.css')
.pipe(gulp.dest(dirs.dist + '/css'));
});
gulp.task('lint:js', function () {
return gulp.src([
'gulpfile.js',
dirs.src + '/js/*.js',
dirs.test + '/*.js'
]).pipe(plugins.jscs())
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter('jshint-stylish'))
.pipe(plugins.jshint.reporter('fail'));
});
// ---------------------------------------------------------------------
// | Main tasks |
// ---------------------------------------------------------------------
gulp.task('archive', function (done) {
runSequence(
'build',
'archive:create_archive_dir',
'archive:zip',
done);
});
gulp.task('build', function (done) {
runSequence(
['clean', 'lint:js'],
'copy',
done);
});
gulp.task('default', ['build']);
|
JavaScript
| 0.000001 |
@@ -78,127 +78,33 @@
');%0A
-var plugins = require('gulp-load-plugins')(); // Load all gulp plugins%0A //
+%0A// Load all gulp plugins
aut
@@ -113,16 +113,19 @@
atically
+%0A//
and att
@@ -131,57 +131,8 @@
tach
-%0A //
the
@@ -161,24 +161,19 @@
ect%0A
-%0A
var
-runSequence
+plugins
= r
@@ -184,27 +184,32 @@
re('
-run-sequence');
+gulp-load-plugins')();%0A%0A
// T
@@ -243,54 +243,8 @@
p 4%0A
-
// h
@@ -283,16 +283,59 @@
sues/355
+%0Avar runSequence = require('run-sequence');
%0A%0Avar pk
@@ -3140,17 +3140,16 @@
-
browsers
@@ -3186,25 +3186,24 @@
', '%3E 1%25'%5D,%0A
-
|
d327f35f7f3d1ccaa1493e58eedfe03e8fe735dc
|
Fix exception
|
lib/web/routes/hooks.js
|
lib/web/routes/hooks.js
|
/*
* Copyright 2011 Rackspace
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
var util = require('util');
var express = require('express');
var url = require('url');
var _ = require('underscore');
var async = require('async');
var et = require('elementtree');
var urls = require('../urls');
var db = require('../db');
var utils = require('../../utils');
var settings = require('../../settings');
var events = require('../events');
var middleware = require('../middleware');
var EVENTS = events.EVENTS;
exports.install = function(app, devops){
var v1_request = function(project, pull_request_title){
var options;
var path;
var v1_spec;
var split;
var type;
var str_number;
var str_number_id;
var v1_info = utils.version_one_match(pull_request_title);
if (!v1_info){
return;
}
v1_spec = devops[project].version_one;
path = ['/',
v1_spec.name,
"/rest-1.v1/Data/",
type === "B" ? "Story" : "Defect",
util.format("?sel=Estimate&where=Number='%s'", v1_info.number)
];
options = {
port: v1_spec.port,
host: v1_spec.host,
path: encodeURI(path.join("")),
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + new Buffer(v1_spec.auth).toString('base64')
}
};
return _.bind(utils.request_maker, utils, options);
};
var github_commits_request = function(project, pull_request_url){
var github_spec = devops[project].github;
var options;
var parsed_url = url.parse(pull_request_url);
options = {
host: parsed_url.host,
path: parsed_url.path+'/commits',
port: 443,
headers: utils.create_basic_auth(github_spec.username, github_spec.apikey)
};
return _.bind(utils.request_maker, utils, options);
};
app.post(urls.GITHUB_PUSH_API, [express.bodyParser()], function(req, res){
var state, number_matches, str_number, title, merged_by_user, event;
// any http requests we need to send off
var requests = {};
// any new events to add
var events_list = [];
var event_type = null;
var story_points = 500;
res.send('', 204);
var project = req.params.project;
var e = req.body;
var action = e.action;
var pr = e.pull_request;
var user = pr.user.login;
console.log("new request from github", action, pr.title, pr.user.login, e.sender.login,
pr.merged, pr.merged_by);
if (action === "synchronize") {
event_type = EVENTS.sync;
story_points = 1;
}
if (action === "reopened"){
event_type = EVENTS.reopened;
story_points = 500;
user = req.body.sender.login;
}
if (action === "closed" && pr.merged === false){
event_type = EVENTS.closed;
story_points = 500;
}
debugger;
if (event_type !== null) {
event = events.Git_Event(user, event_type, story_points, pr);
return db.add_event(event, project);
}
//TODO: this is fucking terrible variable spanning
merged_by_user = pr.merged_by.login;
// get all the committers
requests.github = github_commits_request(project, pr.url);
// look up story points
requests.version_one = v1_request(project, pr.title);
async.parallel(requests, function(err, results){
var committers=[];
var json;
var new_estimate;
var asset;
var story_points = 1;
json = JSON.parse(results.github.data);
_.each(json, function(commit){
try{
committers.push(commit.committer.login);
}catch(e){}
});
committers = _.uniq(committers);
console.log(committers);
// try to get story points out
if (results.version_one){
var etree = et.parse(results.version_one.data);
if (!_.isEmpty(results.version_one.error)){
return;
}
asset = etree.getroot().findall('./Asset');
if (asset && asset[0]._children[0].attrib.name === "Estimate") {
story_points = asset[0]._children[0].text || 1;
}
}
// loop over committers and the like
if (merged_by_user){
events_list.push(events.Git_Event(merged_by_user, EVENTS.merged, story_points, pr));
}
_.each(committers, function(git_user){
events_list.push(events.Git_Event(git_user, EVENTS.commits_merged, story_points, pr));
});
return db.add_multiple_events(events_list, project);
});
});
};
|
JavaScript
| 0.000264 |
@@ -3588,22 +3588,44 @@
erged_by
-.login
+ ? pr.merged_by.login : null
;%0A //
@@ -4280,17 +4280,16 @@
n_one)%7B%0A
-%0A
|
5b2a834aa5b8f946862823b70d88974f6db6a12f
|
fix problem when permission is granted
|
notifyMe.js
|
notifyMe.js
|
typeof null
notifyMe = function() {
this.delayTime = 0;
this.appearTime = 10000;
this.iconUrl = "drawable/Logo256.png";
this.onClick;
this.requestPermission = function () {
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification;
if (this.iconUrl == null) {
notification = new Notification(displayString);
} else {
var options = {
icon: this.iconUrl
}
notification = new Notification(displayString, options);
}
notification.onclick = this.onClick;
setTimeout(notification.close.bind(notification), this.appearTime);
}
});
}
}
this.sendNotification = function (displayString) {
if (!("Notification" in window)) {
// alert("This browser does not support desktop notification");
}
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification;
if (this.iconUrl == null) {
notification = new Notification(displayString);
} else {
var options = {
icon: this.iconUrl
}
notification = new Notification(displayString, options);
}
notification.onclick = this.onClick;
setTimeout(notification.close.bind(notification), this.appearTime);
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification;
if (this.iconUrl == null) {
notification = new Notification(displayString);
} else {
var options = {
icon: this.iconUrl
}
notification = new Notification(displayString, options);
}
notification.onclick = this.onClick;
setTimeout(notification.close.bind(notification), this.appearTime);
}
});
}
}
this.setAppearTime = function (appearTime) {
this.appearTime = appearTime;
}
this.setIconUrl = function (iconUrl) {
this.iconUrl = iconUrl;
}
this.setOnClick = function (onClickCallBack) {
this.onClick = onClickCallBack;
}
};
|
JavaScript
| 0.000007 |
@@ -543,367 +543,14 @@
%09%09%09%09
-var notification;%0A%09%09%09%09%09if (this.iconUrl == null) %7B%0A%09%09%09%09%09%09notification = new Notification(displayString);%0A%09%09%09%09%09%7D else %7B%0A%09%09%09%09%09%09var options = %7B%0A%09%09%09%09%09%09%09%09icon: this.iconUrl%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09notification = new Notification(displayString, options);%0A%09%09%09%09%09%7D%0A%09%09%09%09%09notification.onclick = this.onClick;%0A%09%09%09%09%09setTimeout(notification.close.bind(notification), this.appearTime)
+return
;%0A%09%09
|
b3b6a9c0f7bac4f0a52c9715b596f93708b36f72
|
update gulp release
|
gulpfile.js/tasks/release.js
|
gulpfile.js/tasks/release.js
|
'use strict';
/**
* @param {Object} gulp The gulp object
* @param {Object} config The configuration for gulp tasks. To get a property using `config.a.b.c` or `config.get('a.b.c')`
* @param {Object} LL Lazy required libraries and other data
* @param {Object} args The parsed arguments from comment line
*/
module.exports = function(gulp, config, LL, args) { // eslint-disable-line no-unused-vars
gulp.task('release:license', ['clean:release'], function() {
var conf = config.get('tasks.release.license');
var license = LL.license;
var filter = LL.filter;
var matches = conf.get('matches');
var author = conf.get('author');
var defaultLicense = conf.get('license');
var stream = gulp.src(conf.get('src'), conf.get('srcOpts'));
matches.forEach(function(matchObj) {
var f = filter(matchObj.glob, {restore: true});
stream = stream.pipe(f)
.pipe(license(matchObj.license || defaultLicense, {
organization: matchObj.author || author,
}))
.pipe(f.restore);
});
return stream.pipe(gulp.dest(conf.get('dest')));
});
gulp.task('release:npm-pack', ['clean:npm-package'], function(done) {
var conf = config.get('tasks.release.npm');
var Path = LL.Path;
var CP = LL.CP;
var util = LL.nodeUtil;
var packageJSON = LL.packageJSON;
var src = Path.resolve(conf.get('src'));
var dest = Path.resolve(conf.get('dest'));
var destFile = util.format('%s/%s.tgz', dest, packageJSON.name);
var packageName = src.split('/').pop();
var command = util.format('tar -czf %s -C %s %s', destFile, Path.resolve(src, '..'), packageName);
CP.exec(command, done);
});
gulp.task('release:npm-publish', function(done) {
var conf = config.get('tasks.release.npm');
var Path = LL.Path;
var CP = LL.CP;
var util = LL.nodeUtil;
var packageJSON = LL.packageJSON;
var dest = Path.resolve(conf.get('dest'));
var destFile = util.format('%s/%s.tgz', dest, packageJSON.name);
var command = util.format('npm publish --access public %s', destFile);
CP.exec(command, done);
});
gulp.task('release:pre', function(done) {
var CP = LL.CP;
var command = '\
git add . && \
git stash save "stash for release" && \
git fetch --prune && \
git rebase origin/develop release \
';
CP.exec(command, done);
});
gulp.task('release:changelog:touch', function(done) {
var name = config.get('tasks.release.changelog.name');
LL.CP.exec('touch ' + name, done);
});
gulp.task('release:changelog', ['release:changelog:touch'], function(done) {
var CP = LL.CP;
var util = LL.nodeUtil;
var changelog = LL.changelog;
var conf = config.get('tasks.release.changelog');
var name = conf.get('name');
gulp.src(name, {
buffer: false,
})
.pipe(changelog({
preset: 'angular',
}))
.pipe(gulp.dest('./'))
.on('end', function() {
var command = util.format('git add %s', name);
CP.exec(command, done);
})
.on('error', done);
});
/**
* gulp release:bump [options]
*
* options:
* -t --type [major, minor, patch] Semver 2.0. default to patch
* -v --version VERSION Bump to a specific version
*/
gulp.task('release:bump', function(done) {
var Path = LL.Path;
var CP = LL.CP;
var util = LL.nodeUtil;
var bumpOpts = {
key: 'version',
indent: 2,
};
var version = args.v || args.version;
var type = args.t || args.type || 'patch';
if (version) {
bumpOpts.version = version;
} else {
bumpOpts.type = type;
}
gulp.src(Path.resolve('./package.json'))
.pipe(LL.bump(bumpOpts))
.pipe(gulp.dest('./'))
.on('end', function() {
var packageJSON = LL.reload('packageJSON');
var tag = packageJSON.version;
var command = util.format('\
git add package.json && \
git commit -m "update version to %s" --no-edit \
', tag);
CP.exec(command, done);
})
.on('error', done);
});
gulp.task('release:branch', function(done) {
var CP = LL.CP;
var util = LL.nodeUtil;
var command = util.format('\
git fetch --prune && \
git rebase origin/develop develop && \
git merge --no-ff --no-edit release && \
git rebase origin/master master && \
git merge --no-ff --no-edit release \
');
CP.exec(command, done);
});
gulp.task('release:tag', function(done) {
var CP = LL.CP;
var util = LL.nodeUtil;
var packageJSON = LL.reload('packageJSON');
var tag = packageJSON.version;
var conf = config.get('tasks.release.git-tag');
var commitHash = conf.get('dest');
var command = util.format('git tag -a v%s %s -m "release version %s"', tag, commitHash, tag);
CP.exec(command, done);
});
gulp.task('release:push', function(done) {
var CP = LL.CP;
var command = '\
git push origin develop && \
git push origin master && \
git push --tags \
';
CP.exec(command, done);
});
gulp.task('release:code', function(done) {
LL.runSequence(
'lint',
'test',
'release:pre',
'release:changelog',
'release:bump',
'release:branch',
'release:tag',
'release:push',
done
);
});
gulp.task('release', function(done) {
LL.runSequence(
'release:code',
'release:license',
'release:npm-pack',
'release:npm-publish',
done
);
});
};
|
JavaScript
| 0 |
@@ -3307,48 +3307,273 @@
var
-command = util.format('git add %25s
+packageJSON = LL.reload('packageJSON');%0A var tag = packageJSON.version;%0A var command = util.format('%5C%0A git add %25s && %5C%0A git commit -m %22update version to %25s%22 --no-edit %5C%0A
', name
+, tag
);%0A
@@ -3976,40 +3976,8 @@
.CP;
-%0A var util = LL.nodeUtil;
%0A%0A
@@ -4462,316 +4462,38 @@
-var packageJSON = LL.reload('packageJSON');%0A var tag = packageJSON.version;%0A%0A var command = util.format('%5C%0A git add package.json && %5C%0A git commit -m %22update version to %25s%22 --no-edit %5C%0A ', tag);%0A CP.exec(command
+CP.exec('git add package.json'
, do
@@ -5840,25 +5840,20 @@
release:
-changelog
+bump
',%0A
@@ -5860,36 +5860,41 @@
'release:
-bump
+changelog
',%0A '
|
70b7deab7e772fbedd65d22781fee81fd98b5955
|
Update build script to include shadow
|
create_build_script.js
|
create_build_script.js
|
var fs = require('fs'),
execSync = require('execSync').exec;
var modules = [
'text',
'cufon',
'gestures',
'easing',
'parser',
'freedrawing',
'interaction',
'serialization',
'image_filters',
'gradient',
'pattern',
'node'
];
// http://stackoverflow.com/questions/5752002/find-all-possible-subset-combos-in-an-array
var combine = function(a, min) {
var fn = function(n, src, got, all) {
if (n == 0) {
if (got.length > 0) {
all[all.length] = got;
}
return;
}
for (var j = 0, len = src.length; j < len; j++) {
fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
}
return;
}
var all = [];
for (var i = min, _len = a.length; i < _len; i++) {
fn(i, a, [], all);
}
all.push(a);
return all;
}
var combinations = combine(modules, 1);
var startTime = new Date;
fs.writeFile('build.sh', '#!/usr/bin/env sh\n\n', function() {
for (var i = 0, len = combinations.length; i < len; i++) {
var modulesStr = combinations[i].join(',');
var command = 'node build.js build-sh modules=' + modulesStr;
execSync(command);
}
// create basic (minimal) build
execSync('node build.js build-sh modules=');
});
|
JavaScript
| 0 |
@@ -233,16 +233,28 @@
ttern',%0A
+ 'shadow',%0A
'node'
|
a9da5be9c569760140d4f70e35cda0044027f55e
|
rename action test
|
tests/integration/components/pagination-pager-test.js
|
tests/integration/components/pagination-pager-test.js
|
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, click } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('Integration | Component | pagination-pager', function(hooks) {
setupRenderingTest(hooks);
test('it renders', async function(assert) {
await render(hbs`{{pagination-pager}}`);
assert.ok(this.element.textContent.includes('«'));
});
test('it renders', async function(assert) {
assert.expect(2);
this.setProperties({
change(current, last) {
assert.equal(current, 2, 'New value is next');
assert.equal(last, 1, 'Old value is previous');
}
});
await render(hbs`{{pagination-pager count=5 change=(action change)}}`);
await click('.next a');
});
test('when set to false and count is 1 it sets isHidden to false', async function(assert) {
await render(hbs`{{pagination-pager autoHide=false count=1}}`);
assert.notOk(this.element.firstChild.classList.contains('hidden'));
});
test('when set to true and count is 1 it sets isHidden to true', async function(assert) {
await render(hbs`{{pagination-pager autoHide=true count=1}}`);
assert.ok(this.element.firstChild.classList.contains('hidden'));
});
test('when set to true and count is 2 it sets isHidden to false', async function(assert) {
await render(hbs`{{pagination-pager autoHide=true count=2}}`);
assert.notOk(this.element.firstChild.classList.contains('hidden'));
});
});
|
JavaScript
| 0.000949 |
@@ -439,39 +439,51 @@
%7D);%0A%0A test('it
-renders
+fires change action
', async functio
|
0d3773045dcade29b8a847c230a51e3831c2d317
|
Print response to debug
|
js/index.js
|
js/index.js
|
$(document).ready(function() {
var page = 1;
var data;
if (typeof pagination !== 'undefined') {
if (pagination === true) {
$(".pagination").css("display", "block");
}
}
if (typeof top_active !== 'undefined') {
$("nav a." + top_active).addClass("active");
}
if (typeof channel !== 'undefined') {
if (channel != 'company' && channel != 'engineering') {
$(".subheader a.category").removeClass("active");
$(".subheader a.category#" + channel).addClass("active");
}
}
if ($("div.pagination").length > 0) {
check_page();
} else {
$(".posts").css("visibility", "visible");
}
function check_page() {
var href = window.location.hash;
var matched = href.match('^#page');
if (matched) {
var page_num = href.split("#page")[1];
if (page_num = parseInt(page_num)) {
page = page_num;
}
}
$.getJSON(prefix + "/json/index.json", function(response) {
if (response) {
var result = [];
for (key in response.posts) {
var post = response.posts[key];
if (post.draft) continue;
if (typeof channel !== 'undefined') {
if (post.tags.indexOf(channel) == - 1) {
continue;
}
}
if (typeof author_id !== 'undefined') {
if (post.author != author_id) {
continue;
}
}
result.push(post);
}
response.posts = result;
data = response;
console.log(data);
set_page(page);
// Set total pages
$("span.page.total_pages").html(Math.max(Math.floor(data.posts.length / 5), 1));
// Bind page clicks
$("a.page").click(function() {
var selected_page = ($(this).hasClass("older") ? page + 1 : page - 1);
if (valid_page(selected_page)) {
set_page(selected_page);
}
});
$(window).hashchange(function() {
var selected_page = parseInt(window.location.hash.substr(5));
if (valid_page(selected_page)) {
set_page(selected_page);
}
})
}
});
}
function set_page(page_num) {
var max = Math.floor(data.posts.length / 5);
if (data == null) return;
if (!valid_page(page_num)) {
if (page_num > max) page_num = max;
}
page = page_num;
if (typeof pagination !== 'undefined' && pagination === true) {
window.location.hash = "#page" + page_num.toString();
}
$(window).scrollTop(0);
var next = page_num + 1;
var previous = page_num - 1;
$("span.page.current_page").html(page_num);
$("a.page.older").css("visibility", page_num >= max ? "hidden" : "visible");
$("a.page.newer").css("visibility", page_num <= 1 ? "hidden" : "visible");
var offset = (page_num - 1) * 5;
var authors_posted = [];
for (var i = 0; i < 5; i++) {
var post = data.posts[offset + i];
var article = $("article.post:eq(" + i + ")");
article.css("border-bottom", i == data.posts.length - 1 ? "none" : null);
if (i >= data.posts.length || typeof post == 'undefined') {
article.css("display", "none");
continue;
}
var author = data.authors[post.author];
article.find(".title").html(post.title).attr("href", post.url);
article.find(".avatar").attr("src", author.avatar);
var post_info = [];
post_info.push(post.date);
post_info.push('By ' + author.name);
post_info.push('In ' + post.tags.join(", "))
article.find(".post-info").html(post_info.join(" • "));
article.find("img.hero").attr("src", post.hero);
article.find("a.hero_url").attr("href", post.url);
article.find(".excerpt").html(post.content);
article.find("a.read-more").attr("href", post.url);
article.css("display", "block");
var podcast = (post.tags.indexOf('podcasts') > -1);
article.find(".podcast-container").css("display", podcast ? "block" : "none");
var no_background = (podcast || post.hero.length == 0);
article.find(".hero-container").css("display", no_background ? "none" : "block");
var auth = $("#authors-container .author-container:eq(" + i + ")");
if (auth && authors_posted.indexOf(author.twitter) == -1) {
auth.find(".avatar-link").attr("href", author.url);
auth.find(".avatar").attr("src", author.avatar);
auth.find(".name-link").attr("href", author.url).html(author.name);
auth.find("p.job").html(author.job);
authors_posted.push(author.twitter);
auth.css("display", "block");
} else {
auth.css("display", "none");
}
}
$(".posts").css("visibility", "visible");
}
function valid_page(page_num) {
return (page_num > 0 && page_num <= Math.max(Math.floor(data.posts.length / 5), 1))
}
});
|
JavaScript
| 0.000001 |
@@ -1367,20 +1367,24 @@
ole.log(
-data
+response
);%0A%0A%09%09%09%09
|
ac91fe789ff1361845810058732b1a56d0509f0a
|
prepare to release 0.3.1
|
lib/index.js
|
lib/index.js
|
import Backbone from 'backbone'
import objectPath from './object-path'
import deepCopy from './deep-copy'
const DEFAULTS = Object.freeze({
pathSeparator: '.',
pathParser: null
})
const _defaults = Object.assign({}, DEFAULTS)
function updateObjectPath () {
objectPath.pathSeparator = _defaults.pathSeparator
const pathParser = _defaults.pathParser
if (typeof pathParser === 'function' || pathParser === null) {
objectPath.pathParser = pathParser
}
return objectPath
}
function isObject (value) {
return value !== null && typeof value === 'object'
}
/**
* @class
* @see http://backbonejs.org/#Model
*
* @example
* // ES5
* var Person = DeepModel.extend({...})
*
* // ES2015(ES6)
* class Person extends DeepModel {...}
*/
export default class DeepModel extends Backbone.Model {
/**
* this module's version.
*/
static get VERSION () { return '0.3.0' }
/**
* Update default settings.
*
* @param {Object} [settings={}] reset if `null`
* @param {string} [settings.pathSeparator='/']
* @param {function(path: string): Array.<string>} [settings.pathParser] ignore if returns `[]`
* @returns {Object}
*
* @example
* DeepModel.defaults({anySetting: true})
* DeepModel.defaults(null) // reset!
*
* @example
* DeepModel.defaults({pathSeparator: '/'})
*
* let model = new DeepModel()
* model.set('a', {})
* model.set('a/b', 1)
* model.get('a/b') //=> 1
*
* @example
* DeepModel.defaults({
* pathParser(path) {
* if (path === '*') { return [] } // ignore!
* return path.split('_')
* }
* })
*
* let model = new DeepModel()
* model.set('a', {})
* model.set('a_b', 1)
* model.get('a_b') //=> 1
* model.set('*', 2)
* model.get('*') //=> undefined
*/
static defaults (settings = {}) {
return Object.assign(_defaults, settings === null ? DEFAULTS : settings)
}
/**
* @see http://backbonejs.org/#Model-get
* @override
* @param {string} attribute
* @returns {*}
*
* @example
* model.get('a.b')
*/
get (attribute) {
return updateObjectPath().get(this.attributes, attribute)
}
/**
* @see http://backbonejs.org/#Model-set
* @override
* @param {string} attribute
* @param {*} value
* @param {Object} [options]
* @returns {DeepModel}
*
* @example
* model.set({'a.b': 'value'})
* model.set('a.b', 'value')
*/
set (attribute, value, options) {
if (attribute == null) {
return this
}
const _ = updateObjectPath()
let attrs
if (typeof attribute === 'object') {
attrs = attribute
options = value
} else {
if (!_.pathParser && !_.hasSeparator(attribute)) {
return super.set(attribute, value, options)
}
attrs = {}
attrs[attribute] = value
}
const newAttrs = Object.keys(attrs).reduce((newObj, path) => {
const paths = _.parse(path)
if (paths.length === 0) {
return newObj
}
if (paths.length === 1) {
newObj[paths[0]] = attrs[path]
return newObj
}
const rootPath = paths[0]
let obj = newObj[rootPath]
if (obj == null) {
obj = deepCopy(this.attributes[rootPath])
}
if (!isObject(obj)) {
throw new Error(`"${path}" does not exist in ${JSON.stringify(this)}`)
}
newObj[rootPath] = obj
return _.set(newObj, paths, attrs[path])
}, {})
return super.set(newAttrs, options)
}
}
DeepModel.extend = Backbone.Model.extend
|
JavaScript
| 0.000008 |
@@ -884,17 +884,17 @@
rn '0.3.
-0
+1
' %7D%0A%0A /
|
0c9fc7e3dd673d244ec2c74f30a4411f66f0f8aa
|
Use autoloadTranspiler
|
lib/extension-es6.js
|
lib/extension-es6.js
|
/*
* Extension to detect ES6 and auto-load Traceur or Babel for processing
*/
function es6(loader) {
loader._extensions.push(es6);
var transpiler, transpilerModule, transpilerRuntimeModule, transpilerRuntimeGlobal;
var isBrowser = typeof window !== 'undefined' && !!window.Window && window instanceof window.Window;
var isWorker = typeof self !== 'undefined' && !!self.WorkerGlobalScope && self instanceof WorkerGlobalScope;
function setTranspiler(name) {
transpiler = name;
transpilerModule = '@' + transpiler;
transpilerRuntimeModule = transpilerModule + (transpiler == 'babel' ? '-helpers' : '-runtime');
transpilerRuntimeGlobal = transpiler == 'babel' ? transpiler + 'Helpers' : '$' + transpiler + 'Runtime';
// auto-detection of paths to loader transpiler files
var scriptBase;
if ($__curScript && $__curScript.src)
scriptBase = $__curScript.src.substr(0, $__curScript.src.lastIndexOf('/') + 1);
else
scriptBase = loader.baseURL + (loader.baseURL.lastIndexOf('/') == loader.baseURL.length - 1 ? '' : '/');
if (!loader.paths[transpilerModule])
loader.paths[transpilerModule] = $__curScript && $__curScript.getAttribute('data-' + loader.transpiler + '-src') || scriptBase + loader.transpiler + '.js';
if (!loader.paths[transpilerRuntimeModule])
loader.paths[transpilerRuntimeModule] = $__curScript && $__curScript.getAttribute('data-' + transpilerRuntimeModule.substr(1) + '-src') || scriptBase + transpilerRuntimeModule.substr(1) + '.js';
}
// good enough ES6 detection regex - format detections not designed to be accurate, but to handle the 99% use case
var es6RegEx = /(^\s*|[}\);\n]\s*)(import\s+(['"]|(\*\s+as\s+)?[^"'\(\)\n;]+\s+from\s+['"]|\{)|export\s+\*\s+from\s+["']|export\s+(\{|default|function|class|var|const|let|async\s+function))/;
var loaderTranslate = loader.translate;
loader.translate = function(load) {
var self = this;
return loaderTranslate.call(loader, load)
.then(function(source) {
// update transpiler info if necessary
if (self.transpiler !== transpiler)
setTranspiler(self.transpiler);
var loader = self;
if (load.name == transpilerModule || load.name == transpilerRuntimeModule)
return loaderTranslate.call(loader, load);
// detect ES6
else if (load.metadata.format == 'es6' || !load.metadata.format && source.match(es6RegEx)) {
load.metadata.format = 'es6';
// dynamically load transpiler for ES6 if necessary
if ((isBrowser || isWorker) && !loader.global[transpiler])
return loader['import'](transpilerModule).then(function() {
return source;
});
}
// dynamically load transpiler runtime if necessary
if ((isBrowser || isWorker) && !loader.global[transpilerRuntimeGlobal] && source.indexOf(transpilerRuntimeGlobal) != -1) {
var System = $__global.System;
return loader['import'](transpilerRuntimeModule).then(function() {
// traceur runtme annihilates System global
$__global.System = System;
return source;
});
}
return source;
});
}
// always load transpiler as a global
var loaderInstantiate = loader.instantiate;
loader.instantiate = function(load) {
var loader = this;
if ((isBrowser || isWorker) && (load.name == transpilerModule || load.name == transpilerRuntimeModule)) {
loader.__exec(load);
return {
deps: [],
execute: function() {
return loader.newModule({});
}
};
}
return loaderInstantiate.call(loader, load);
}
}
|
JavaScript
| 0 |
@@ -223,23 +223,32 @@
%0A%0A var
-isBrows
+autoloadTranspil
er = typ
@@ -278,172 +278,51 @@
ed'
-&& !!window.Window && window instanceof window.Window;%0A var isWorker = typeof self !== 'undefined' && !!self.WorkerGlobalScope && self instanceof WorkerGlobalScope
+%7C%7C typeof WorkerGlobalScope !== 'undefined'
;%0A%0A
@@ -2423,39 +2423,34 @@
if (
-(isBrowser %7C%7C isWork
+autoloadTranspil
er
-)
&& !loa
@@ -2661,39 +2661,34 @@
if (
-(isBrowser %7C%7C isWork
+autoloadTranspil
er
-)
&& !loa
@@ -3222,31 +3222,26 @@
if (
-(isBrowser %7C%7C isWork
+autoloadTranspil
er
-)
&&
|
b7b9165a9d49a232a1e9ad583b971e7df492a703
|
fix example-minimal ball color sometimes being invalid
|
examples/example-minimal/javascript/main.js
|
examples/example-minimal/javascript/main.js
|
/**
* @fileoverview Minimal is the smalles GameJs app I could think of, which still shows off
* most of the concepts GameJs introduces.
*
* It's a pulsating, colored circle. You can make the circle change color
* by clicking.
*
*/
var gamejs = require('gamejs');
var SCREEN_WIDTH = 400;
var SCREEN_HEIGHT = 400;
// ball is a colored circle.
// ball can circle through color list.
// ball constantly pulsates in size.
function Ball(center) {
this.center = center;
this.growPerSec = Ball.GROW_PER_SEC;
this.radius = this.growPerSec * 2;
this.color = 0;
return this;
};
Ball.MAX_SIZE = 200;
Ball.GROW_PER_SEC = 50;
Ball.COLORS = ['#ff0000', '#00ff00', '#0000cc'];
Ball.prototype.nextColor = function() {
this.color += 1;
if (this.color > Ball.COLORS.length) {
this.color = 0;
}
};
Ball.prototype.draw = function(display) {
var rgbColor = Ball.COLORS[this.color];
var lineWidth = 0; // lineWidth zero fills the circle
gamejs.draw.circle(display, rgbColor, this.center, this.radius, lineWidth);
};
Ball.prototype.update = function(msDuration) {
this.radius += this.growPerSec * (msDuration / 1000);
if (this.radius > Ball.MAX_SIZE || this.radius < Math.abs(this.growPerSec)) {
this.radius = this.radius > Ball.MAX_SIZE ? Ball.MAX_SIZE : Math.abs(this.growPerSec);
this.growPerSec = -this.growPerSec;
}
};
function main() {
// ball changes color on mouse up
function handleEvent(event) {
switch(event.type) {
case gamejs.event.MOUSE_UP:
ball.nextColor();
break;
};
};
// handle events.
// update models.
// clear screen.
// draw screen.
// called ~ 30 times per second by fps.callback
// msDuration = actual time in milliseconds since last call
function gameTick(msDuration) {
gamejs.event.get().forEach(function(event) {
handleEvent(event);
});
ball.update(msDuration);
display.clear();
ball.draw(display);
};
// setup screen and ball.
// ball in screen center.
// start game loop.
var display = gamejs.display.setMode([SCREEN_WIDTH, SCREEN_HEIGHT]);
var ballCenter = [SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2];
var ball = new Ball(ballCenter);
gamejs.time.fpsCallback(gameTick, this, 30);
};
// call main after all resources have finished loading
gamejs.ready(main);
|
JavaScript
| 0.000004 |
@@ -758,16 +758,17 @@
.color %3E
+=
Ball.CO
|
ba1c4e4d8046594717a28e59ef7df64432db941a
|
Swap shallow for mount in workflow selection tests This allows us to test the full component lifecycle.
|
app/pages/project/workflow-selection.spec.js
|
app/pages/project/workflow-selection.spec.js
|
import React from 'react';
import assert from 'assert';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import apiClient from 'panoptes-client/lib/api-client';
import WorkflowSelection from './workflow-selection';
function StubPage() {
return <p>Hello</p>;
}
const location = {
query: {}
};
const context = {
initialLoadComplete: true,
router: {}
};
const projectRoles = [
{
roles: ['owner'],
links: {
owner: {
id: '1'
}
}
},
{
roles: ['collaborator'],
links: {
owner: {
id: '2'
}
}
},
{
roles: ['tester'],
links: {
owner: {
id: '3'
}
}
}
];
function mockPanoptesResource(type, options) {
const resource = apiClient.type(type).create(options);
apiClient._typesCache = {};
sinon.stub(resource, 'save').callsFake(() => Promise.resolve(resource));
sinon.stub(resource, 'get');
sinon.stub(resource, 'delete');
return resource;
}
const project = mockPanoptesResource('projects',
{
id: 'a',
display_name: 'A test project',
experimental_tools: [],
links: {
active_workflows: ['1', '2', '3', '4', '5'],
owner: { id: '1' }
}
}
);
const owner = mockPanoptesResource(
'users',
{
id: project.links.owner.id
}
);
const preferences = mockPanoptesResource(
'project_preferences',
{
preferences: {},
links: {
project: project.id
}
}
);
describe('WorkflowSelection', function () {
const actions = {
translations: {
load: () => null
}
};
const translations = {
locale: 'en'
};
const wrapper = shallow(
<WorkflowSelection
actions={actions}
project={project}
preferences={preferences}
projectRoles={projectRoles}
location={location}
translations={translations}
>
<StubPage />
</WorkflowSelection>,
{ context }
);
const controller = wrapper.instance();
const workflowSpy = sinon.spy(controller, 'getWorkflow');
before(function () {
sinon.stub(apiClient, 'request').callsFake((method, url, payload) => {
let response = [];
if (url === '/workflows') {
const workflow = mockPanoptesResource(
'workflows',
{
id: payload.id,
tasks: []
}
);
response = [workflow];
}
return Promise.resolve(response);
});
});
beforeEach(function () {
workflowSpy.resetHistory();
wrapper.update();
});
afterEach(function () {
project.experimental_tools = [];
location.query = {};
});
after(function () {
apiClient.request.restore();
});
it('should fetch a random active workflow by default', function () {
controller.getSelectedWorkflow({ project });
const selectedWorkflowID = workflowSpy.getCall(0).args[0];
sinon.assert.calledOnce(workflowSpy);
assert.notEqual(project.links.active_workflows.indexOf(selectedWorkflowID), -1);
});
it('should respect the workflow query param if "allow workflow query" is set', function () {
location.query.workflow = '6';
project.experimental_tools = ['allow workflow query'];
controller.getSelectedWorkflow({ project });
sinon.assert.calledOnce(workflowSpy);
sinon.assert.calledWith(workflowSpy, '6', true);
});
describe('with a logged-in user', function () {
beforeEach(function () {
controller.setupSplits = () => null;
location.query.workflow = '6';
});
it('should load the specified workflow for the project owner', function () {
const user = owner;
controller.getSelectedWorkflow({ project, preferences, user });
sinon.assert.calledOnce(workflowSpy);
sinon.assert.calledWith(workflowSpy, '6', false);
});
it('should load the specified workflow for a collaborator', function () {
const user = apiClient.type('users').create({ id: '2' });
controller.getSelectedWorkflow({ project, preferences, user });
sinon.assert.calledOnce(workflowSpy);
sinon.assert.calledWith(workflowSpy, '6', false);
});
it('should load the specified workflow for a tester', function () {
const user = apiClient.type('users').create({ id: '3' });
controller.getSelectedWorkflow({ project, preferences, user });
sinon.assert.calledOnce(workflowSpy);
sinon.assert.calledWith(workflowSpy, '6', false);
});
});
describe('with a workflow saved in preferences', function () {
beforeEach(function () {
location.query = {};
preferences.update({ preferences: {}});
const user = mockPanoptesResource('users', { id: '4' });
wrapper.setProps({ user });
});
it('should try to load the stored workflow', function () {
preferences.update({ 'preferences.selected_workflow': '4' });
controller.getSelectedWorkflow({ project, preferences });
sinon.assert.calledOnce(workflowSpy);
sinon.assert.calledWith(workflowSpy, '4', true);
});
it('should try to load a stored project workflow', function () {
preferences.update({ 'settings.workflow_id': '2' });
controller.getSelectedWorkflow({ project, preferences });
sinon.assert.calledOnce(workflowSpy);
sinon.assert.calledWith(workflowSpy, '2', true);
});
});
describe('without a saved workflow', function () {
beforeEach(function () {
location.query = {};
project.update({ 'configuration.default_workflow': '1' });
preferences.update({ settings: {}, preferences: {}});
});
it('should load the project default workflow', function () {
const user = apiClient.type('users').create({ id: '4' });
controller.getSelectedWorkflow({ project, preferences, user });
sinon.assert.calledOnce(workflowSpy);
sinon.assert.calledWith(workflowSpy, '1', true);
});
});
});
|
JavaScript
| 0 |
@@ -58,23 +58,21 @@
mport %7B
-shallow
+mount
%7D from
@@ -324,37 +324,8 @@
= %7B%0A
- initialLoadComplete: true,%0A
ro
@@ -1589,15 +1589,13 @@
r =
-shallow
+mount
(%0A
|
068c8b6bdcc46c7542c32ce2400caa850aa8a395
|
fix gulpfile packaging
|
client/gulpfile.js
|
client/gulpfile.js
|
// Include gulp
var gulp = require('gulp');
var del = require('del');
var runSequence = require('run-sequence');
var exec = require('child_process').exec;
var bump = require('gulp-bump');
var args = require('yargs').argv;
// The default task (called when you run `gulp` from cli)
gulp.task('default', ['build']);
gulp.task('clean', function () {
return del(['vendor'])
})
gulp.task('copy_language_server', function () {
return gulp.src(['../server/lib/**/*',
'../server/vendor/**/*',
'../server/puppet-languageserver'
], { base: '../server'})
.pipe(gulp.dest('./vendor/languageserver'));
})
gulp.task('build_extension', function (callback) {
exec('node ./node_modules/vsce/out/vsce package',
function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
callback;
});
})
gulp.task('build', function (callback) {
runSequence('clean','copy_language_server','build_extension',callback);
})
gulp.task('bump', function () {
/// <summary>
/// It bumps revisions
/// Usage:
/// 1. gulp bump : bumps the package.json and bower.json to the next minor revision.
/// i.e. from 0.1.1 to 0.1.2
/// 2. gulp bump --version 1.1.1 : bumps/sets the package.json and bower.json to the
/// specified revision.
/// 3. gulp bump --type major : bumps 1.0.0
/// gulp bump --type minor : bumps 0.1.0
/// gulp bump --type patch : bumps 0.0.2
/// gulp bump --type prerelease : bumps 0.0.1-2
/// </summary>
var type = args.type;
var version = args.version;
var options = {};
if (version) {
options.version = version;
} else {
options.type = type;
}
return gulp
.src(['package.json'])
.pipe(bump(options))
.pipe(gulp.dest('.'));
});
|
JavaScript
| 0.000002 |
@@ -273,17 +273,16 @@
rom cli)
-
%0Agulp.ta
@@ -761,16 +761,145 @@
package
+ --baseContentUrl https://github.com/jpogran/puppet-vscode/client --baseImagesUrl https://github.com/jpogran/puppet-vscode/client
',%0A f
@@ -1436,17 +1436,16 @@
n to the
-
%0A ///
@@ -1521,17 +1521,16 @@
ps 1.0.0
-
%0A ///
|
1e8ef9b7b32541241f75a53dd0cff8860aa27c2d
|
Fix #20
|
lib/index.js
|
lib/index.js
|
import inquirer from 'inquirer'
import semafor from 'semafor'
import packager from 'electron-packager'
import path from 'path'
import util from 'util'
export default function interactive () {
// Logging library.
const log = semafor()
// Get the name from the package.json file.
function getPackageName () {
try {
const pkg = require(path.join(process.cwd(), 'package.json'))
return pkg.name
} catch (e) {
return ''
}
}
function runElectronPackager (settings) {
log.log('Electron packager settings:')
log.log(settings)
packager(settings, (err, appPath) => {
if (err) {
return error(err)
}
log.ok(`Application packaged successfully to '${appPath}'`)
})
}
// Default values for answers.
const settings = {
dir: process.cwd(),
name: getPackageName(),
platform: 'all',
arch: 'all',
version: '1.2.2',
out: path.join(process.cwd(), 'releases'),
'app-bundle-id': '',
'app-version': '',
overwrite: true,
asar: false
}
// Log and close the process.
function error (msg) {
log.log('')
log.fail(msg.toString())
process.exit(1)
}
// Start the cli.
inquirer.prompt([
{
type: 'confirm',
name: 'overwrite',
message: 'Overwrite output directory ?',
default: true
},
{
type: 'confirm',
name: 'asar',
message: 'Use asar source packaging ?',
default: settings.asar
},
{
type: 'input',
name: 'sourcedir',
message: 'Select Electron app source directory:',
default: settings.dir
},
{
type: 'input',
name: 'out',
message: 'Select Electron app output directory:',
default: settings.out
},
{
type: 'input',
name: 'appname',
message: 'Select Application name:',
default: settings.name
},
{
type: 'input',
name: 'bundle_id',
message: 'Select App Bundle Id (optional):'
},
{
type: 'input',
name: 'app_version',
message: 'Select App Version(optional):',
default: '0.0.1'
},
{
type: 'input',
name: 'icon',
message: 'Select Electron icon file:'
},
{
type: 'input',
name: 'version',
message: 'Select Electron version release:',
default: settings.version
},
{
type: 'checkbox',
name: 'platform',
message: 'Select platforms:',
choices: ['all', 'linux', 'darwin', 'win32']
},
{
type: 'checkbox',
name: 'arch',
message: 'Select architecture:',
choices: ['all', 'ia32', 'x64', 'armv7l']
}
], answers => {
// Get the options and defaults.
const options = util._extend(settings, answers)
// Fix two answers.
options.arch = answers.arch.join(',')
if (options.arch === '') {
options.arch = null
log.warn(`No arch specified, defaulting to ${process.arch}`)
}
options.platform = answers.platform.join(',')
if (options.platform === '') {
options.platform = null
log.warn(`No platform specified, defaulting to ${process.platform}`)
}
if (options.arch && options.platform) {
// Warn user selection darwin ia32, since
// electron-packager will silently fail
// Read mode here:
// https://github.com/Urucas/electron-packager-interactive/issues/7
if (
(options.arch.indexOf('darwin') || options.arch.indexOf('all')) &&
(options.platform.indexOf('ia32') || options.platform.indexOf('all'))) {
error('Sorry, building for darwin ia32 is not supported by Electron')
}
if (options.arch === 'armv7l' && options.platform !== 'linux') {
error('Sorry, Electron only supports building Linux targets using the armv7l arch')
}
}
// Add output folder to ignore
options.ignore = answers.out
// Build
runElectronPackager(options)
})
}
|
JavaScript
| 0 |
@@ -3384,25 +3384,16 @@
if (
-%0A
(options
@@ -3385,36 +3385,40 @@
if ((options.
-arch
+platform
.indexOf('darwin
@@ -3431,20 +3431,24 @@
options.
-arch
+platform
.indexOf
@@ -3467,16 +3467,18 @@
+
(options
@@ -3474,32 +3474,28 @@
(options.
-platform
+arch
.indexOf('ia
@@ -3506,32 +3506,28 @@
%7C%7C options.
-platform
+arch
.indexOf('al
|
398419f3bdd0c9be245adc7b087a4da436621958
|
remove composition event listeners in v-model unbind
|
src/directives/model.js
|
src/directives/model.js
|
var utils = require('../utils'),
isIE9 = navigator.userAgent.indexOf('MSIE 9.0') > 0
module.exports = {
bind: function () {
var self = this,
el = self.el,
type = el.type,
tag = el.tagName
self.lock = false
// determine what event to listen to
self.event =
(self.compiler.options.lazy ||
tag === 'SELECT' ||
type === 'checkbox' || type === 'radio')
? 'change'
: 'input'
// determin the attribute to change when updating
var attr = self.attr = type === 'checkbox'
? 'checked'
: (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA')
? 'value'
: 'innerHTML'
var compositionLock = false
el.addEventListener('compositionstart', function () {
compositionLock = true
})
el.addEventListener('compositionend', function () {
compositionLock = false
})
// attach listener
self.set = self.filters
? function () {
if (compositionLock) return
// if this directive has filters
// we need to let the vm.$set trigger
// update() so filters are applied.
// therefore we have to record cursor position
// so that after vm.$set changes the input
// value we can put the cursor back at where it is
var cursorPos
try {
cursorPos = el.selectionStart
} catch (e) {}
self.vm.$set(self.key, el[attr])
// since updates are async
// we need to reset cursor position async too
utils.nextTick(function () {
if (cursorPos !== undefined) {
el.setSelectionRange(cursorPos, cursorPos)
}
})
}
: function () {
// no filters, don't let it trigger update()
self.lock = true
self.vm.$set(self.key, el[attr])
utils.nextTick(function () {
self.lock = false
})
}
el.addEventListener(self.event, self.set)
// fix shit for IE9
// since it doesn't fire input on backspace / del / cut
if (isIE9) {
self.onCut = function () {
// cut event fires before the value actually changes
utils.nextTick(function () {
self.set()
})
}
self.onDel = function (e) {
if (e.keyCode === 46 || e.keyCode === 8) {
self.set()
}
}
el.addEventListener('cut', self.onCut)
el.addEventListener('keyup', self.onDel)
}
},
update: function (value) {
if (this.lock) return
/* jshint eqeqeq: false */
var self = this,
el = self.el
if (el.tagName === 'SELECT') { // select dropdown
// setting <select>'s value in IE9 doesn't work
var o = el.options,
i = o.length,
index = -1
while (i--) {
if (o[i].value == value) {
index = i
break
}
}
o.selectedIndex = index
} else if (el.type === 'radio') { // radio button
el.checked = value == el.value
} else if (el.type === 'checkbox') { // checkbox
el.checked = !!value
} else {
el[self.attr] = utils.toText(value)
}
},
unbind: function () {
this.el.removeEventListener(this.event, this.set)
if (isIE9) {
this.el.removeEventListener('cut', this.onCut)
this.el.removeEventListener('keyup', this.onDel)
}
}
}
|
JavaScript
| 0 |
@@ -827,47 +827,102 @@
-el.addEventListener('compositionstart',
+this.cLock = function () %7B%0A compositionLock = true%0A %7D%0A this.cUnlock =
fun
@@ -954,35 +954,36 @@
mpositionLock =
-tru
+fals
e%0A %7D)%0A
@@ -969,33 +969,32 @@
false%0A %7D
-)
%0A el.addE
@@ -1022,73 +1022,86 @@
tion
-end', function () %7B%0A compositionLock = false%0A %7D
+start', this.cLock)%0A el.addEventListener('compositionend', this.cUnlock
)%0A%0A
@@ -3879,37 +3879,57 @@
on () %7B%0A
-this.
+var el = this.el%0A
el.removeEventLi
@@ -3957,16 +3957,142 @@
is.set)%0A
+ el.removeEventListener('compositionstart', this.cLock)%0A el.removeEventListener('compositionend', this.cUnlock)%0A
@@ -4108,37 +4108,32 @@
) %7B%0A
-this.
el.removeEventLi
@@ -4170,21 +4170,16 @@
-this.
el.remov
|
eeeb05fa4367fe6acf253dd5e8fa597badcb715c
|
Remove not needed import
|
embark-ui/src/components/ContractLayout.js
|
embark-ui/src/components/ContractLayout.js
|
import PropTypes from "prop-types";
import React from 'react';
import { TabContent, TabPane, Nav, NavItem, NavLink, Card, Button, CardTitle, CardText, Row, Col } from 'reactstrap';
import classnames from 'classnames';
import ContractOverview from '../components/ContractOverview';
import ContractLoggerContainer from '../containers/ContractLoggerContainer';
import ContractFunctionsContainer from '../containers/ContractFunctionsContainer';
class ContractLayout extends React.Component {
constructor(props) {
super(props);
this.state = {
activeTab: '1'
};
}
toggle(tab) {
if (this.state.activeTab !== tab) {
this.setState({
activeTab: tab
});
}
}
render() {
return (
<React.Fragment>
<Nav tabs>
<NavItem>
<NavLink
className={classnames({ active: this.state.activeTab === '1' })}
onClick={() => { this.toggle('1'); }}
>
Overview
</NavLink>
</NavItem>
<NavItem>
<NavLink
className={classnames({ active: this.state.activeTab === '2' })}
onClick={() => { this.toggle('2'); }}
>
Functions
</NavLink>
</NavItem>
<NavItem>
<NavLink
className={classnames({ active: this.state.activeTab === '3' })}
onClick={() => { this.toggle('3'); }}
>
Logger
</NavLink>
</NavItem>
</Nav>
<TabContent activeTab={this.state.activeTab}>
<TabPane tabId="1">
<ContractOverview contract={this.props.contract} />
</TabPane>
<TabPane tabId="2">
<ContractFunctionsContainer contract={this.props.contract} />
</TabPane>
<TabPane tabId="3">
<ContractLoggerContainer contract={this.props.contract} />
</TabPane>
</TabContent>
</React.Fragment>
)
}
}
ContractLayout.propTypes = {
contract: PropTypes.object
};
export default ContractLayout;
|
JavaScript
| 0.000001 |
@@ -111,53 +111,8 @@
Link
-, Card, Button, CardTitle, CardText, Row, Col
%7D f
|
2e74f9ea202cc8cf7ab2f40c1752ea82baa859ca
|
Update index.js
|
js/index.js
|
js/index.js
|
var mySwiper = new Swiper ('.swiper-container', {
onInit: function(swiper){
swiperAnimateCache(swiper); //隐藏动画元素
swiperAnimate(swiper); //初始化完成开始动画
},
onSlideChangeEnd: function(swiper){
swiperAnimate(swiper); //每个slide切换结束时也运行当前slide动画
},
pagination: '.swiper-pagination',
paginationClickable: true,
mousewheelControl:true,
direction: 'vertical'
})
var flash = document.getElementById('web-swipe-tip');
var i = 0;
var next_move = setInterval(function(){
i++;
flash.style.bottom = i + "px";
if(i == 10){
i = 5;
}
},120);
//
|
JavaScript
| 0.000002 |
@@ -575,7 +575,4 @@
0);%0A
-//%0A
|
c3f0ca58d48bd685209be58e968747ff0ba84e28
|
Add auth parameter to cookie
|
sdk/src/Application.js
|
sdk/src/Application.js
|
import Style from './style.css';
import ChatHeaderTemplate from './chat-header.html';
import ChatFooterTemplate from './chat-footer.html';
import Constants from './Constants';
import AuthType from './AuthType';
export default class Application {
constructor() {
//Default options
this.options = {
authType: AuthType.GUEST_AUTH,
title: 'Estamos online',
onEnter: () => { },
onLeave: () => { },
}
Application.IFRAMEURL = Constants.IFRAMEURL_LOCAL;
if (process.env.NODE_ENV === 'homolog') {
Application.IFRAMEURL = Constants.IFRAMEURL_HMG;
}
else if (process.env.NODE_ENV === 'production') {
Application.IFRAMEURL = Constants.IFRAMEURL_PRD;
}
//Div container for SDK
let chatEl = document.createElement('div');
//Div ID
chatEl.id = 'take-chat';
this.chatEl = chatEl;
}
/* Init chat and set values and styles*/
openBlipThread(options) {
let chatOpts = { ...this.options, ...options };
this.options = chatOpts;
//Chat HTML element
this.buildChat(chatOpts);
}
/* Build chat HTML element */
buildChat(opts) {
let params = 'apikey=' + this._apiKey + '&authType=' + this.options.authType;
if (this.options.authType === 'Dev') {
var userAccount = {
userIdentity: opts.user.id,
userPassword: btoa(opts.user.password)
}
_setCookie(Constants.USER_ACCOUNT_KEY, btoa(JSON.stringify(userAccount)), Constants.COOKIES_EXPIRATION)
}
//Chat iframe
this.chatIframe = document.createElement('iframe');
this.chatIframe.id = 'iframe-chat';
this.chatIframe.src = Application.IFRAMEURL + '?' + params;
window.addEventListener('message', _receiveUserFromCommon);
let widgetMode = opts.target === undefined;
if (widgetMode) {
this.chatEl.innerHTML = ChatHeaderTemplate;
this.chatEl.innerHTML += ChatFooterTemplate;
this.chatEl.appendChild(this.chatIframe);
this.chatEl.className = 'blip-hidden-chat';
this.chatEl.className += ' fixed-window';
this.chatIframe.width = 300;
this.chatIframe.height = 460;
//Set zIndex
this._setZIndex(opts.zIndex);
//Set chat title
this._setChatTitle(opts.title);
let body = document.getElementsByTagName('body')[0];
body.appendChild(this.chatEl);
let closeBtn = document.getElementById('blip-close-btn');
closeBtn.addEventListener('click', () => {
if (this.chatEl.getAttribute('class').indexOf('blip-hidden-chat') == ! -1) {
this.chatEl.setAttribute('class', 'blip-show-chat fixed-window');
//Enter chat callback
setTimeout(() => {
opts.onEnter();
}, 500);
}
else {
this.chatEl.setAttribute('class', 'blip-hidden-chat fixed-window');
//Leave chat callback
setTimeout(() => {
opts.onLeave();
}, 500);
}
});
} else {
this.chatEl.className = 'target-window';
this.chatEl.appendChild(this.chatIframe);
this.chatIframe.className += ' target-window';
let chatTarget = document.getElementById(opts.target);
chatTarget.appendChild(this.chatEl);
}
}
destroy() {
if (this.options.target !== undefined) {
let element = document.getElementById(this.options.target);
element.removeChild(this.chatEl);
} else {
let body = document.getElementsByTagName('body')[0];
body.removeChild(this.chatEl);
}
}
_setChatTitle(title) {
let chatTitle = title ? title : Constants.SDK_DEFAULT_TITLE;
this.chatEl.querySelector('#chat-header-text').innerHTML = chatTitle;
}
_setZIndex(value) {
let zIndex = value ? value : 16000001;
this.chatEl.style.zIndex = zIndex;
}
_sendMessage(message) {
var postMessage = { code: Constants.SEND_MESSAGE_CODE, content: message }
document.getElementById('iframe-chat').contentWindow.postMessage(message, Application.IFRAMEURL);
}
}
function _getCookie(name) {
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
let value = c.substring(name.length + 1, c.length);
_setCookie(name, value, Constants.COOKIES_EXPIRATION);
return value;
}
}
return null;
}
function _setCookie(name, value, exdays) {
var date = new Date();
date.setTime(date.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = 'expires=' + date.toUTCString();
document.cookie = name + '=' + value + ';' + expires + ';path=/';
}
function _receiveUserFromCommon(event) {
var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
if (Application.IFRAMEURL.indexOf(origin) === -1) {
return;
}
if (event.data.code === Constants.COOKIE_DATA_CODE) {
_setCookie(Constants.USER_ACCOUNT_KEY, event.data.userAccount, Constants.COOKIES_EXPIRATION);
}
else if (event.data.code === Constants.REQUEST_COOKIE_CODE) {
var iframe = document.getElementById('iframe-chat');
var account = _getCookie(Constants.USER_ACCOUNT_KEY);
var message =
{
code: Constants.COOKIE_DATA_CODE,
userAccount: account,
};
iframe.contentWindow.postMessage(message, Application.IFRAMEURL);
}
}
|
JavaScript
| 0.000001 |
@@ -1245,13 +1245,25 @@
===
-'Dev'
+AuthType.DEV_AUTH
) %7B%0A
@@ -1309,16 +1309,37 @@
dentity:
+ this._apiKey + '_' +
opts.us
@@ -1391,16 +1391,57 @@
assword)
+,%0A authType: this.options.authType
%0A %7D
|
560222d40a2c8d9217164ad3ceef2aebcb16eed6
|
Fix typo
|
app/scripts/configs/available-for-plugins.js
|
app/scripts/configs/available-for-plugins.js
|
/**
* Code that is available to plugin tracks.
*/
// Libraries
import * as PIXI from 'pixi.js';
// Tracks
import Annotations2dTrack from '../Annotations2dTrack';
import ArrowheadDomainsTrack from '../ArrowheadDomainsTrack';
import BarTrack from '../BarTrack';
import BedLikeTrack from '../BedLikeTrack';
import CNVIntervalTrack from '../CNVIntervalTrack';
import CombinedTrack from '../CombinedTrack';
import DivergentBarTrack from '../DivergentBarTrack';
import HeatmapTiledPixiTrack from '../HeatmapTiledPixiTrack';
import Horizontal2DDomainsTrack from '../Horizontal2DDomainsTrack';
import HorizontalChromosomeLabels from '../HorizontalChromosomeLabels';
import HorizontalGeneAnnotationsTrack from '../HorizontalGeneAnnotationsTrack';
import HorizontalHeatmapTrack from '../HorizontalHeatmapTrack';
import HorizontalLine1DPixiTrack from '../HorizontalLine1DPixiTrack';
import HorizontalMultivecTrack from '../HorizontalMultivecTrack';
import HorizontalPoint1DPixiTrack from '../HorizontalPoint1DPixiTrack';
import HorizontalTiledPlot from '../HorizontalTiledPlot';
import HorizontalTrack from '../HorizontalTrack';
import Id2DTiledPixiTrack from '../Id2DTiledPixiTrack';
import IdHorizontal1DTiledPixiTrack from '../IdHorizontal1DTiledPixiTrack';
import IdVertical1DTiledPixiTrack from '../IdVertical1DTiledPixiTrack';
import ImageTilesTrack from '../ImageTilesTrack';
import LeftAxisTrack from '../LeftAxisTrack';
import MapboxTilesTrack from '../MapboxTilesTrack';
import MoveableTrack from '../MoveableTrack';
import OSMTilesTrack from '../OSMTilesTrack';
import PixiTrack from '../PixiTrack';
import SVGTrack from '../SVGTrack';
import SquareMarkersTrack from '../SquareMarkersTrack';
import StackedBarTrack from '../StackedBarTrack';
import Tiled1DPixiTrack from '../Tiled1DPixiTrack';
import TiledPixiTrack from '../TiledPixiTrack';
import TopAxisTrack from '../TopAxisTrack';
import Track from '../Track';
import ValueIntervalTrack from '../ValueIntervalTrack';
import VerticalTiled1DPixiTrack from '../VerticalTiled1DPixiTrack';
import VerticalTrack from '../VerticalTrack';
// Factories
import ContextMenuItem from '../ContextMenuItem';
import DataFetcher from '../DataFetcher';
import { LruCache } from '../factories';
// Services
import * as services from '../services';
// Utils
import * as utils from '../utils';
// Configs
import * as configs from '../configs';
const libraries = {
PIXI,
};
const tracks = {
Annotations2dTrack,
ArrowheadDomainsTrack,
BarTrack,
BedLikeTrack,
CNVIntervalTrack,
CombinedTrack,
DivergentBarTrack,
HeatmapTiledPixiTrack,
Horizontal2DDomainsTrack,
HorizontalChromosomeLabels,
HorizontalGeneAnnotationsTrack,
HorizontalHeatmapTrack,
HorizontalLine1DPixiTrack,
HorizontalMultivecTrack,
HorizontalPoint1DPixiTrack,
HorizontalTiledPlot,
HorizontalTrack,
Id2DTiledPixiTrack,
IdHorizontal1DTiledPixiTrack,
IdVertical1DTiledPixiTrack,
ImageTilesTrack,
LeftAxisTrack,
MapboxTilesTrack,
MoveableTrack,
OSMTilesTrack,
PixiTrack,
SVGTrack,
SquareMarkersTrack,
StackedBarTrack,
Tiled1DPixiTrack,
TiledPixiTrack,
TopAxisTrack,
Track,
ValueIntervalTrack,
VerticalTiled1DPixiTrack,
VerticalTrack,
};
const facotries = {
ContextMenuItem,
DataFetcher,
LruCache
};
export default {
libraries,
tracks,
facotries,
services,
utils,
configs
};
|
JavaScript
| 0.999999 |
@@ -3213,26 +3213,26 @@
;%0A%0Aconst fac
-o
t
+o
ries = %7B%0A C
@@ -3322,18 +3322,18 @@
s,%0A fac
-o
t
+o
ries,%0A
|
2695fc83ef252d9ddc7f335852845f790bb0a6b2
|
Modify 'searchToUpperCase()' function to work on every word in a string
|
helpers/searchToUpperCase.js
|
helpers/searchToUpperCase.js
|
module.exports.searchToUpperCase = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
};
|
JavaScript
| 0.002382 |
@@ -46,9 +46,12 @@
%3E %7B%0A
-%09
+
retu
@@ -60,16 +60,61 @@
string.
+replace(/%5Cw%5CS*/g, (txt) =%3E %7B%0A %09return txt.
charAt(0
@@ -135,23 +135,42 @@
) +
-string.slic
+txt.substr(1).toLowerCas
e(
-1
);%0A
+ %7D);%0A
%7D
-;
|
2313a55e56c2c497e51f63be02412c7d7779ea75
|
Fix potential bug of referencing super ctor dynamically instead of statically
|
library/services/storage-compat.js
|
library/services/storage-compat.js
|
/*
* IFrameTransport - Storage Service Extension
*
* Use a cookie to capture which key changed for IE8
* Use a cookie to ignore "storage" events that I triggered
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) define('ift-storage-service-compat', ['localstorage-events', 'ift-storage-service'], factory);
else if (typeof exports === 'object') module.exports = factory(require('localstorage-events'), require('./storage'));
else root.ift = factory(root.LSEvents, root.ift);
}(this, function(LSEvents, ift) {
var support = ift.support,
mixin = ift.util.mixin;
mixin(support, {
myWritesTrigger: ('onstoragecommit' in document)
});
// Only override the Storage service if necessary.
if (!support.myWritesTrigger) return ift;
var Service = ift.service('storage').extend({
constructor: function(transport, storage) {
ift.service('storage').apply(this, arguments);
var service = this;
this.storage = new LSEvents(this.storage, function() {
service.onStorage.apply(service, arguments);
});
},
// `LSEvents` will handle "storage" events for us.
listen: function() {}
});
ift.registerService('storage', Service);
return ift;
}));
|
JavaScript
| 0 |
@@ -786,16 +786,23 @@
%0A%0A var
+Storage
Service
@@ -825,16 +825,62 @@
torage')
+;%0A%0A var StorageCompatService = StorageService
.extend(
@@ -936,38 +936,30 @@
%7B%0A
-ift.service('storage')
+StorageService
.apply(t
@@ -1255,16 +1255,29 @@
orage',
+StorageCompat
Service)
|
73f0b3d05199b816c59fac65c11ab6bcdcaf9f3f
|
revert zero-width character change
|
src/main/js/ephox/phoenix/wrap/Navigation.js
|
src/main/js/ephox/phoenix/wrap/Navigation.js
|
define(
'ephox.phoenix.wrap.Navigation',
[
'ephox.bud.Unicode',
'ephox.perhaps.Option',
'ephox.phoenix.api.data.Spot'
],
function (Unicode, Option, Spot) {
/**
* Return the last available cursor position in the node.
*/
var toLast = function (universe, node) {
if (universe.property().isText(node)) {
return Spot.point(node, universe.property().getText(node).length);
} else {
var children = universe.property().children(node);
// keep descending if there are children.
return children.length > 0 ? toLast(universe, children[children.length - 1]) : Spot.point(node, children.length);
}
};
var toLower = function (universe, node) {
var lastOffset = universe.property().isText(node) ?
universe.property().getText(node).length :
universe.property().children(node).length;
return Spot.point(node, lastOffset);
};
/**
* Descend down to a leaf node at the given offset.
*/
var toLeaf = function (universe, element, offset) {
var children = universe.property().children(element);
if (children.length > 0 && offset < children.length) {
return toLeaf(universe, children[offset], 0);
} else if (children.length > 0 && universe.property().isElement(element) && children.length === offset) {
return toLast(universe, children[children.length - 1]);
} else {
return Spot.point(element, offset);
}
};
var scan = function (universe, element, direction) {
if (! universe.property().isText(element)) return Option.none();
var text = universe.property().getText(element);
if (Unicode.trimNative(text).length > 0) return Option.none();
return direction(element).bind(function (elem) {
return scan(universe, elem, direction).orThunk(function () {
return Option.some(elem);
});
});
};
var freefallLtr = function (universe, element) {
var candidate = scan(universe, element, universe.query().nextSibling).getOr(element);
if (universe.property().isText(candidate)) return Spot.point(candidate, 0);
var children = universe.property().children(candidate);
return children.length > 0 ? freefallLtr(universe, children[0]) : Spot.point(candidate, 0);
};
var toEnd = function (universe, element) {
if (universe.property().isText(element)) return universe.property().getText(element).length;
var children = universe.property().children(element);
return children.length;
};
var freefallRtl = function (universe, element) {
var candidate = scan(universe, element, universe.query().prevSibling).getOr(element);
if (universe.property().isText(candidate)) return Spot.point(candidate, toEnd(universe, candidate));
var children = universe.property().children(candidate);
return children.length > 0 ? freefallRtl(universe, children[children.length - 1]) : Spot.point(candidate, toEnd(universe, candidate));
};
return {
toLast: toLast,
toLeaf: toLeaf,
toLower: toLower,
freefallLtr: freefallLtr,
freefallRtl: freefallRtl
};
}
);
|
JavaScript
| 0.000002 |
@@ -45,33 +45,8 @@
%5B%0A
- 'ephox.bud.Unicode',%0A
@@ -125,17 +125,8 @@
on (
-Unicode,
Opti
@@ -1651,31 +1651,18 @@
if (
-Unicode.trimNative(text
+text.trim(
).le
|
8149c479e639293cff82f4f1423acc0ad18d099f
|
Make sure to only scope nodes once
|
src/document-watcher.js
|
src/document-watcher.js
|
/**
@license
Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
'use strict';
import {nativeShadow} from './style-settings.js';
import StyleTransformer from './style-transformer.js';
import {getIsExtends} from './style-util.js';
export let flush = function() {};
/**
* @param {HTMLElement} element
* @return {!Array<string>}
*/
function getClasses(element) {
let classes = [];
if (element.classList) {
classes = Array.from(element.classList);
} else if (element instanceof window['SVGElement'] && element.hasAttribute('class')) {
classes = element.getAttribute('class').split(/\s+/);
}
return classes;
}
/**
* @param {HTMLElement} element
* @return {string}
*/
function getCurrentScope(element) {
let classes = getClasses(element);
let idx = classes.indexOf(StyleTransformer.SCOPE_NAME);
if (idx > -1) {
return classes[idx + 1];
}
return '';
}
/**
* @param {Array<MutationRecord|null>|null} mxns
*/
function handler(mxns) {
for (let x=0; x < mxns.length; x++) {
let mxn = mxns[x];
if (mxn.target === document.documentElement ||
mxn.target === document.head) {
continue;
}
for (let i=0; i < mxn.addedNodes.length; i++) {
let n = mxn.addedNodes[i];
if (n.nodeType !== Node.ELEMENT_NODE) {
continue;
}
n = /** @type {HTMLElement} */(n); // eslint-disable-line no-self-assign
let root = n.getRootNode();
let currentScope = getCurrentScope(n);
// node was scoped, but now is in document
if (currentScope && root === n.ownerDocument) {
StyleTransformer.dom(n, currentScope, true);
} else if (root.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
let newScope;
let host = /** @type {ShadowRoot} */(root).host;
// element may no longer be in a shadowroot
if (!host) {
continue;
}
newScope = getIsExtends(host).is;
// make sure all the subtree elements are scoped correctly
let unscopedNodes = window['ShadyDOM']['nativeMethods']['querySelectorAll'].call(
n, `:not(.${StyleTransformer.SCOPE_NAME})`);
for (let j = 0; j < unscopedNodes.length; j++) {
// it's possible, during large batch inserts, that nodes that aren't
// scoped within the current scope were added.
// To make sure that any unscoped nodes that were inserted in the current batch are correctly styled,
// query all unscoped nodes and force their style-scope to be applied.
// This could happen if a sub-element appended an unscoped node in its shadowroot and this function
// runs on a parent element of the host of that unscoped node:
// parent-element -> element -> unscoped node
// Here unscoped node should have the style-scope element, not parent-element.
const unscopedNode = unscopedNodes[j];
const rootForUnscopedNode = unscopedNode.getRootNode();
const hostForUnscopedNode = rootForUnscopedNode .host;
if (!hostForUnscopedNode) {
continue;
}
const scopeForPreviouslyUnscopedNode = getIsExtends(hostForUnscopedNode).is;
StyleTransformer.element(unscopedNode, scopeForPreviouslyUnscopedNode);
}
if (newScope === currentScope) {
continue;
}
if (currentScope) {
StyleTransformer.dom(n, currentScope, true);
}
StyleTransformer.dom(n, newScope);
}
}
}
}
if (!nativeShadow) {
let observer = new MutationObserver(handler);
let start = (node) => {
observer.observe(node, {childList: true, subtree: true});
}
let nativeCustomElements = (window['customElements'] &&
!window['customElements']['polyfillWrapFlushCallback']);
// need to start immediately with native custom elements
// TODO(dfreedm): with polyfilled HTMLImports and native custom elements
// excessive mutations may be observed; this can be optimized via cooperation
// with the HTMLImports polyfill.
if (nativeCustomElements) {
start(document);
} else {
let delayedStart = () => {
start(document.body);
}
// use polyfill timing if it's available
if (window['HTMLImports']) {
window['HTMLImports']['whenReady'](delayedStart);
// otherwise push beyond native imports being ready
// which requires RAF + readystate interactive.
} else {
requestAnimationFrame(function() {
if (document.readyState === 'loading') {
let listener = function() {
delayedStart();
document.removeEventListener('readystatechange', listener);
}
document.addEventListener('readystatechange', listener);
} else {
delayedStart();
}
});
}
}
flush = function() {
handler(observer.takeRecords());
}
}
|
JavaScript
| 0 |
@@ -2341,24 +2341,276 @@
s(host).is;%0A
+ // rescope current node and subtree if necessary%0A if (newScope !== currentScope) %7B%0A if (currentScope) %7B%0A StyleTransformer.dom(n, currentScope, true);%0A %7D%0A StyleTransformer.dom(n, newScope);%0A %7D%0A
// m
@@ -2664,16 +2664,16 @@
rrectly%0A
-
@@ -3001,17 +3001,16 @@
e added.
-
%0A
@@ -3695,17 +3695,16 @@
opedNode
-
.host;%0A
@@ -3939,24 +3939,24 @@
copedNode);%0A
+
%7D%0A
@@ -3957,215 +3957,8 @@
%7D%0A
- if (newScope === currentScope) %7B%0A continue;%0A %7D%0A if (currentScope) %7B%0A StyleTransformer.dom(n, currentScope, true);%0A %7D%0A StyleTransformer.dom(n, newScope);%0A
|
9d2d1aaba3b7a55f828e1d7955521dd3800d34f2
|
Change to manage reactive data by cell.
|
js/index.js
|
js/index.js
|
const slice = (() => {
const splitAt = (array, n) => [array.slice(0, n), array.slice(n)];
const reduceConcat = a => a.length ? a.reduce((a, b) => [a].concat(reduceConcat(b))) : [];
return (array, n) => {
const splitted = splitAt(array, n);
var p = splitted;
while (p[1].length !== 0) {
p[1] = splitAt(p[1], n);
p = p[1];
}
return reduceConcat(splitted);
};
})();
/**
* manage each number cell by the object
* {
* index :: Number, -- row based index of the cell.
* value :: Number, -- a number between 0 to 9. Non zero number represents 'given'.
* memo :: Array, -- array of the numbers, those of which can be placed, user considers.
* }
*/
const rootVm = new Vue({
el: '#app-sudoku',
template: `
<div class="boxes"
tabindex="0"
@keydown.49="hoveringCells.forEach(cell => cell.memo[0] = '')"
@keydown.50="hoveringCells.forEach(cell => cell.memo[1] = '')"
@keydown.51="hoveringCells.forEach(cell => cell.memo[2] = '')"
@keydown.52="hoveringCells.forEach(cell => cell.memo[3] = '')"
@keydown.53="hoveringCells.forEach(cell => cell.memo[4] = '')"
@keydown.54="hoveringCells.forEach(cell => cell.memo[5] = '')"
@keydown.55="hoveringCells.forEach(cell => cell.memo[6] = '')"
@keydown.56="hoveringCells.forEach(cell => cell.memo[7] = '')"
@keydown.57="hoveringCells.forEach(cell => cell.memo[8] = '')"
>
<div class="box-row" v-for="span in [[0, 3], [3, 6], [6, 9]]">
<div class="box" v-for="values in boxes.slice(span[0], span[1])">
<div class="row-in-box" v-for="span in [[0, 3], [3, 6], [6, 9]]">
<span v-for="cell in values.slice(span[0], span[1])"
:class="{cell: 1, hover: hovering.includes(cell.index), }"
@mouseenter="hover = cell.index" @mouseleave="hover = null"
>
<span v-if="cell.value" class="given">{{ cell.value }}</span>
<div v-else class="memo" v-for="memo in slice(cell.memo, 3)">
<span v-for="n in memo">{{ n }}</span>
</div>
</span>
</div>
</div>
</div>
</div>`,
computed: {
hovering: (() => {
const ONE_TO_EIGHT = Array.from({length: 9}).map((_, index) => index);
return function() {
const hover = this.hover;
if (hover) {
const col = hover % 9;
const row = (hover - col) / 9;
const idx = ~~(col / 3) + ~~(row / 3) * 3;
const boxOffset = [0, 3, 6, 27, 30, 33, 54, 57, 60][idx];
return [].concat(ONE_TO_EIGHT.map(v => v + row * 9),
ONE_TO_EIGHT.map(v => v * 9 + col),
[0, 1, 2, 9, 10, 11, 18, 19, 20].map(v => v + boxOffset)
);
} else {
return [];
}
};
})(),
hoveringCells: function() {
const hovering = this.hovering;
return this.boxes.reduce((a, b) => a.concat(b)).filter(cell => hovering.includes(cell.index));
},
},
created: function() {
const OFFSETS = [0, 3, 6, 27, 30, 33, 54, 57, 60,];
const INDICES = [0, 1, 2, 9, 10, 11, 18, 19, 20,];
const makeCellObject = (n, index) => new Object({ index: index, value: Number(n), memo: [1,2,3,4,5,6,7,8,9,], });
const cells = Array.from(this.board).map(makeCellObject);
this.boxes = OFFSETS.map(offset => INDICES.map(index => cells[index + offset]));
},
data: () => new Object({
board: '060003001200500600007090500000400090800000006010005000002010700004009003700200040', // 朝日新聞beパズル 2017/10/07 掲載分
boxes: undefined,
hover: null,
}),
methods: {
slice: slice,
},
});
|
JavaScript
| 0 |
@@ -3279,22 +3279,17 @@
-%7D,%0A
-created
+boxes
: fu
@@ -3303,24 +3303,28 @@
) %7B%0A
+
+
const OFFSET
@@ -3367,24 +3367,28 @@
,%5D;%0A
+
const INDICE
@@ -3422,24 +3422,160 @@
, 19, 20,%5D;%0A
+ return OFFSETS.map(offset =%3E INDICES.map(index =%3E this.cells%5Bindex + offset%5D));%0A %7D,%0A %7D,%0A created: function() %7B%0A
cons
@@ -3692,22 +3692,21 @@
-const
+this.
cells =
@@ -3753,97 +3753,8 @@
t);%0A
- this.boxes = OFFSETS.map(offset =%3E INDICES.map(index =%3E cells%5Bindex + offset%5D));%0A
@@ -3921,20 +3921,20 @@
-boxe
+cell
s: undef
|
3518f89cb825261ad758f04bbfb463b0caedbd41
|
change start rule for peg grammar
|
gulpfile.js
|
gulpfile.js
|
const gulp = require('gulp');
const peg = require('gulp-peg');
const mocha = require('gulp-mocha');
const babel = require('gulp-babel');
const GRAMMAR_PATH = 'src/grammar/*.pegjs';
const HELPER_PATH = 'src/helper/**/*.js';
gulp.task('make:grammar', () => {
gulp.src(GRAMMAR_PATH)
.pipe(peg({ allowedStartRules: ['Programm', 'Statement'] }))
.pipe(gulp.dest('build/grammar/'));
});
gulp.task('make:helpers', () => {
gulp.src(HELPER_PATH)
.pipe(babel())
.pipe(gulp.dest('build/'));
});
gulp.task('default', [
'make:grammar',
'make:helpers',
]);
gulp.task('test:grammar', () => {
gulp.src('test/grammar/*.test.js')
.pipe(mocha());
});
gulp.task('watch', () => {
gulp.watch(GRAMMAR_PATH, ['make:grammar']);
gulp.watch(HELPER_PATH, ['make:helpers']);
});
|
JavaScript
| 0.000004 |
@@ -318,29 +318,17 @@
: %5B'
-Programm', 'Statement
+InitBlock
'%5D %7D
|
d9494acf72213cb4dd4f08acff7c72ffe7dfdfd0
|
Revert enable overlay for grunt serve
|
grunt/config/openui5_connect.js
|
grunt/config/openui5_connect.js
|
// configure the openui5 connect server
module.exports = function(grunt, config) {
// libraries are sorted alphabetically
var aLibraries = config.allLibraries.slice();
aLibraries.sort(function(a, b) {
// ensure that the wrapper is handled before the
// original library to allow an overlay
if (b.name == `${a.name}-wrapper`) {
return 1;
}
if (a.name == `${b.name}-wrapper`) {
return -1;
}
return a.name.localeCompare(b.name);
});
var openui5_connect = {
options: {
contextpath: config.testsuite.name,
proxypath: 'proxy',
proxyOptions: {
secure: false
},
cors: {
origin: "*"
}
},
src: {
options: {
appresources: [config.testsuite.path + '/src/main/webapp', 'target/openui5-sdk/'],
resources: aLibraries.map(function(lib) {
return lib.src;
}),
testresources: aLibraries.map(function(lib) {
return lib.test;
})
}
},
target: {
options: {
appresources: 'target/openui5-testsuite',
resources: aLibraries.map(function(lib) {
return 'target/openui5-' + lib.name + '/resources';
}),
testresources: aLibraries.map(function(lib) {
return 'target/openui5-' + lib.name + '/test-resources';
})
}
}
};
return openui5_connect;
};
|
JavaScript
| 0 |
@@ -202,214 +202,8 @@
) %7B%0A
-%09%09// ensure that the wrapper is handled before the%0A%09%09// original library to allow an overlay%0A%09%09if (b.name == %60$%7Ba.name%7D-wrapper%60) %7B%0A%09%09%09return 1;%0A%09%09%7D%0A%09%09if (a.name == %60$%7Bb.name%7D-wrapper%60) %7B%0A%09%09%09return -1;%0A%09%09%7D%0A
%09%09re
|
027e3e648bc19a6daad28ea871c4b91793045a10
|
Update .eslintrc.js
|
.eslintrc.js
|
.eslintrc.js
|
module.exports = {
env: {
es6: true,
mocha: true,
node: true
},
'extends': 'eslint:recommended',
parserOptions: {
ecmaVersion: 2019
},
rules: {
'brace-style': [2, '1tbs', { allowSingleLine: true }],
'comma-dangle': [2, 'never'],
'dot-notation': 2,
'no-array-constructor': 2,
'no-console': 0,
'no-fallthrough': 0,
'no-inline-comments': 1,
'no-trailing-spaces': 2,
'object-curly-spacing': [2, 'always'],
quotes: [2, 'single'],
semi: [2, 'always']
}
};
|
JavaScript
| 0 |
@@ -174,10 +174,10 @@
: 20
-19
+20
%0A
|
518604c609e7840dc3c23377f777bf7fd3dba2c6
|
Add '@private' annotation.
|
observer.js
|
observer.js
|
/* vim: set filetype=javascript shiftwidth=4 tabstop=4 expandtab: */
/*
* @repository
* https://github.com/saneyuki/observer-js
* @license
* BSD 2-Clause License.
*
* Copyright (c) 2014, Tetsuharu OHZEKI <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
(function(global){
/**
* Observer Subject
* @constructor
*/
var ObserverSubject = function () {
/**
* @type {Object.<string, Array.<{ handleMessage: function }>>}
*
* FIXME: Use ES6 Map
*/
this._map = {};
Object.freeze(this);
};
ObserverSubject.prototype = Object.freeze({
/**
* Regiseter the observer related to the topic.
*
* This method doesn't ensure that the subject broadcasts
* the message SYNCHRONOUSLY. You must design your codes
* as it can work async.
*
* @param {string} aTopic
* @param {*} aData
*/
notify: function (aTopic, aData) {
if (!aTopic) {
throw new Error("Not specified any topic.");
}
var list = this._map[aTopic];
if (!list) {
return;
}
for (var i = 0, l = list.length; i < l; ++i) {
list[i].handleMessage(aTopic, aData);
}
},
/**
* Regiseter the observer to the related topic.
*
* @param {string} aTopic
* @param {{ handleMessage : function }} aObserver
*/
add: function (aTopic, aObserver) {
if (!aTopic || !aObserver) {
throw new Error("Aruguments are not passed fully.");
}
if (!"handleMessage" in aObserver ||
typeof aObserver.handleMessage !== "function") {
throw new Error("Not implement observer interface.");
}
var list = null;
if (this._map.hasOwnProperty(aTopic)) {
list = this._map[aTopic];
}
else {
list = [];
}
// check whether it has been regisetered
var inList = list.indexOf(aObserver);
if (inList !== -1) {
return;
}
list.push(aObserver);
this._map[aTopic] = list;
},
/**
* Unregiseter the observer from the related topic.
*
* @param {string} aTopic
* @param {{ handleMessage : function }} aObserver
*/
remove: function (aTopic, aObserver) {
if (!aTopic || !aObserver) {
throw new Error("Arguments are not passed fully.");
}
if ( !this._map.hasOwnProperty(aTopic) ) {
return;
}
var list = this._map[aTopic];
var index = list.indexOf(aObserver);
if (index === -1) {
return;
}
list.splice(aObserver, 1);
// if the list doesn't have any object,
// this remove the message id related to it.
if (list.length === 0) {
delete this._map[aTopic];
}
},
/**
* Unregiseter all observers from the related topic.
*
* @param {string} aTopic
*/
removeAll: function (aTopic) {
if (!aTopic) {
throw new Error("Not specified any topic.");
}
if ( !this._map.hasOwnProperty(aTopic) ) {
return;
}
var list = this._map[aTopic];
for (var i = 0, l = list.length; i < l; ++i) {
list[i] = null;
}
delete this._map[aTopic];
}
});
// export
global.ObserverSubject = ObserverSubject;
})(this);
|
JavaScript
| 0.000035 |
@@ -1733,24 +1733,41 @@
%0A%0D%0A /**%0D%0A
+ * @private%0D%0A
* @type
|
b1f14b14adc17fbcb73fb21cfcf8e3be8f4ec75d
|
fix .eslintrc prettier error
|
.eslintrc.js
|
.eslintrc.js
|
module.exports = {
extends: ['airbnb-base', 'prettier', 'plugin:promise/recommended'],
rules: {
'prettier/prettier': ['error'],
'no-process-env': 'error',
'no-multiple-empty-lines': [
'error',
{
max: 2,
maxBOF: 0,
maxEOF: 0,
},
],
'no-tabs': 'off',
'no-restricted-syntax': 'off',
'class-methods-use-this': 'off',
'no-underscore-dangle': [
'error',
{
allow: ['_id', '_v', '__v'],
},
],
'no-shadow': [
'error',
{
allow: ['err', 'error'],
},
],
'prefer-destructuring': [
'warn',
{
object: true,
array: false,
},
],
'no-param-reassign': [
'warn',
{
props: false,
},
],
'no-unused-vars': [
'warn',
{
args: 'after-used',
argsIgnorePattern: 'app|req|res|next|options|params|^_',
},
],
'arrow-parens': ['error', 'always'],
},
plugins: ['import', 'prettier', 'promise'],
env: {
node: true,
mocha: true,
},
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.ts'],
},
},
},
ignorePatterns: [
// should not be applied on nest apps
'apps/**',
],
overrides: [
{
// nest.js server in 'apps/server/**' */ which is excluded from outer rules
// this section is more less (parserOptions/project path) only what nest.js defines
files: ['apps/server/**/*.*'],
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'apps/server/tsconfig.app.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: ['plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'],
env: {
node: true,
jest: true,
},
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
},
{
// legacy test files js/ts
files: ['{test,src}/**/*.test.js', '{test,src}/**/*.test.ts'],
rules: {
'no-unused-expressions': 'off',
'global-require': 'warn',
},
},
{
// legacy typescript
files: ['{test,src}/**/*.ts'],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: ['plugin:@typescript-eslint/recommended', 'prettier/@typescript-eslint', 'plugin:prettier/recommended'],
},
],
};
|
JavaScript
| 0.000001 |
@@ -2278,39 +2278,8 @@
ed',
- 'prettier/@typescript-eslint',
'pl
|
4195cf89130828399f7bace1d302d4a447ce7d56
|
Update build-system/extern.js
|
build-system/extern.js
|
build-system/extern.js
|
/**
* Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @externs */
/**
* @template T
* @constructor
*/
const ArrayLike = function () {};
/**
* @type {number}
*/
ArrayLike.prototype.length;
/**
* A type for Objects that can be JSON serialized or that come from
* JSON serialization. Requires the objects fields to be accessed with
* bracket notation object['name'] to make sure the fields do not get
* obfuscated.
* @constructor
* @dict
*/
function JsonObject() {}
/**
* Google JS APIs.
* @type {{
* load: function(string, function(): void),
* auth2: {
* init: function(!Object=): !Promise,
* getAuthInstance: function(): {
* signOut: function(): !Promise,
* },
* },
* signin2: {
* render: function(string, !Object): void
* },
* }}
*/
window.gapi;
/**
* GSI (Google Identity Services) API.
* @type {{
* accounts: {
* id: {
* initialize: function(!Object): !Promise,
* renderButton: function(Element, !Object): !Promise,
* },
* },
* }}
*/
window.google;
|
JavaScript
| 0 |
@@ -1402,18 +1402,18 @@
/**%0A * G
-S
I
+S
(Google
|
36863b5c96631505b5b8ad98bbb36fdd364e6615
|
Remove gulp clean task
|
gulpfile.js
|
gulpfile.js
|
'use strict'
const fs = require('fs')
const path = require('path')
const del = require('del')
const gitRevSync = require('git-rev-sync')
const ghpages = require('gh-pages')
const runSequence = require('run-sequence')
const gulp = require('gulp')
const gulplog = require('gulplog')
const $ = require('gulp-load-plugins')()
const pkg = require('./package.json')
let paths = {
src: 'app',
build: 'public',
dist: 'dist'
}
paths = Object.assign(paths, {
html: `${paths.build}/**/*.html`,
images: `${paths.build}/**/*.{gif,jpg,png}`,
styles: `${paths.src}/**/*.css`,
scripts: [
'*.js',
'vendor/initialize.js',
`${paths.src}/**/*.js`
]
})
const dist = {
client: `${paths.dist}/client`
}
gulp.task('default', [
'lint',
'watch'
])
gulp.task('lint', [
'stylelint',
'standard'
])
gulp.task('minify', [
'htmlmin',
'imagemin'
])
gulp.task('optimize', (done) => (
runSequence(
'minify',
'rev'
)
))
gulp.task('watch', [
'watch:html',
'watch:scripts',
'watch:styles'
])
gulp.task('clean', () => (
del([
paths.build,
paths.dist
])
))
gulp.task('htmlhint', () => (
gulp.src(paths.html)
.pipe($.htmlhint())
.pipe($.htmlhint.failReporter())
))
gulp.task('standard', () => (
gulp.src(paths.scripts)
.pipe($.standard())
.pipe($.standard.reporter('default', {
breakOnError: true
}))
))
gulp.task('stylelint', () => (
gulp.src(paths.styles)
.pipe($.stylelint({
reporters: [
{formatter: 'string', console: true}
]
}))
))
gulp.task('watch:html', () => (
gulp.src(paths.html)
.pipe($.watch(paths.html, vinyl => {
if (vinyl.event === 'change') {
gulplog.info(`Linted ${vinyl.relative}`)
}
}))
.pipe($.plumber())
.pipe($.htmlhint())
.pipe($.htmlhint.reporter())
))
gulp.task('watch:scripts', () => (
gulp.src(paths.scripts)
.pipe($.watch(paths.scripts, vinyl => {
if (vinyl.event === 'change') {
gulplog.info(`Linted ${vinyl.relative}`)
}
}))
.pipe($.plumber())
.pipe($.standard())
.pipe($.standard.reporter('default'))
))
gulp.task('watch:styles', () => (
gulp.watch(paths.styles, ['stylelint'])
))
gulp.task('imagemin', () => (
gulp.src(paths.images)
.pipe($.imagemin())
.pipe(gulp.dest(paths.build))
))
gulp.task('htmlmin', () => (
gulp.src(paths.html)
.pipe($.htmlmin({
collapseBooleanAttributes: true,
collapseWhitespace: true,
preserveLineBreaks: true,
removeComments: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
minifyCSS: true,
minifyJS: true
}))
.pipe(gulp.dest(paths.build))
))
gulp.task('rev', () => {
const dontRev = [
'404.html',
'index.html',
'humans.txt',
'robots.txt',
'crossdomain.xml',
'image.png'
]
return gulp.src(`${paths.build}/**`)
.pipe($.revAll.revision({
prefix: typeof process.env.ASSET_PREFIX === 'string'
? process.env.ASSET_PREFIX
: '/tasty-brunch',
dontRenameFile: dontRev,
dontUpdateReference: dontRev
}))
.pipe(gulp.dest(dist.client))
})
gulp.task('deploy', (done) => {
fs.openSync(path.join(dist.client, '.nojekyll'), 'w')
return ghpages.publish(dist.client, {
clone: '.deploy',
depth: 2,
dotfiles: true,
message: `Deploy ${gitRevSync.short()} from v${pkg.version} [ci skip]`,
repo: process.env.DEPLOY_REPO || `[email protected]:${pkg.repository}.git`,
branch: process.env.DEPLOY_BRANCH || 'gh-pages',
logger: (message) => {
console.log(`[ deploy ] ${message}`)
},
user: {
name: process.env.DEPLOY_NAME || pkg.author.name,
email: process.env.DEPLOY_EMAIL || pkg.author.email
}
}, done)
})
|
JavaScript
| 0.000042 |
@@ -1023,84 +1023,8 @@
%5D)%0A%0A
-gulp.task('clean', () =%3E (%0A del(%5B%0A paths.build,%0A paths.dist%0A %5D)%0A))%0A%0A
gulp
|
8ebae588e8bb06aff6e1695e0fc6a067a5a47940
|
Modify no-console rule
|
.eslintrc.js
|
.eslintrc.js
|
module.exports = {
"extends": "airbnb",
"installedESLint": true,
"plugins": [
"react"
]
};
|
JavaScript
| 0.000003 |
@@ -18,36 +18,29 @@
%7B%0A
- %22
extends
-%22
:
-%22
+'
airbnb
-%22
+'
,%0A
- %22
inst
@@ -50,17 +50,16 @@
edESLint
-%22
: true,%0A
@@ -64,27 +64,23 @@
,%0A
- %22
plugins
-%22
: %5B%0A
@@ -79,24 +79,107 @@
- %22react%22%0A %5D
+'react',%0A %5D,%0A rules: %7B%0A 'no-console': %5B'error', %7B%0A allow: %5B'warn', 'error'%5D,%0A %7D%5D,%0A %7D,
%0A%7D;
+%0A
|
14b8e9550fc2ba764cdf72971d354c11be61576f
|
Check if login form is complete before login
|
js/login.js
|
js/login.js
|
function login() {
var url = $('#serv').val();
var realm = $('#realm').val();
var auth = $('#auth').val();
if (auth == 'no') {
$('#login-btn').html('...');
wsConnectAnonymous(url, realm);
} else if (auth == 'wampcra') {
$('#login-btn').html('...');
var id = {
user: $('#user').val(),
password: $('#password').val()
}
$('#user').val('');
$('#password').val('');
wsConnectWampcra(url, realm, id);
}
}
function loginSuccess(url, realm) {
$('#login-page').hide();
$('#login-margin').hide();
$('#dashboard').show();
$('#login-btn').html('Connection');
$('#connection-state').html('You are connected on<br>'+url+' (Realm : '+realm+')');
displaySessions();
getAllSubscription();
runSubListener();
getAllRpc();
}
function loginError(msg) {
$('#login-btn').html('Connection');
$('#connection-state').html('');
$('#dashboard').hide();
$('#login-margin').show();
$('#login-page').show();
$('#login-error').html('Error : '+msg);
$('#login-error').show();
}
function changeAuthType() {
var auth = $('#auth').val();
if (auth == "wampcra") {
$('#auth-wampcra').show();
} else {
$('#auth-wampcra').hide();
}
}
|
JavaScript
| 0.000001 |
@@ -254,54 +254,8 @@
) %7B%0A
- $('#login-btn').html('...');%0A %0A
@@ -365,24 +365,113 @@
%0A
+if (id.user != '' && id.password != '') %7B%0A %09$('#login-btn').html('...');%0A %09
$('#user').v
@@ -478,28 +478,26 @@
al('');%0A
-
+%09%09
$('#password
@@ -517,32 +517,33 @@
%0A
+%09
wsConnectWampcra
@@ -560,16 +560,26 @@
m, id);%0A
+ %7D%0A
%7D%0A%7D%0A
|
ac8045b96931e1ca35f5bf9b880e963a92ed7cd1
|
add custom info request types
|
lib/graphql/types.js
|
lib/graphql/types.js
|
const { gql } = require('apollo-server-express')
module.exports = gql`
type Coin {
cryptoCode: String!
display: String!
minimumTx: String!
cashInFee: String!
cashInCommission: String!
cashOutCommission: String!
cryptoNetwork: String!
cryptoUnits: String!
batchable: Boolean!
}
type LocaleInfo {
country: String!
fiatCode: String!
languages: [String!]!
}
type OperatorInfo {
name: String!
phone: String!
email: String!
website: String!
companyNumber: String!
}
type MachineInfo {
deviceId: String!
deviceName: String
}
type ReceiptInfo {
paper: Boolean!
sms: Boolean!
operatorWebsite: Boolean!
operatorEmail: Boolean!
operatorPhone: Boolean!
companyNumber: Boolean!
machineLocation: Boolean!
customerNameOrPhoneNumber: Boolean!
exchangeRate: Boolean!
addressQRCode: Boolean!
}
type SpeedtestFile {
url: String!
size: Int!
}
# True if automatic, False otherwise
type TriggersAutomation {
sanctions: Boolean!
idCardPhoto: Boolean!
idCardData: Boolean!
facephoto: Boolean!
usSsn: Boolean!
}
type Trigger {
id: String!
customInfoRequestId: String!
direction: String!
requirement: String!
triggerType: String!
suspensionDays: Float
threshold: Int
thresholdDays: Int
}
type TermsDetails {
tcPhoto: Boolean!
delay: Boolean!
title: String!
accept: String!
cancel: String!
}
type Terms {
hash: String!
text: String
details: TermsDetails
}
type StaticConfig {
configVersion: Int!
coins: [Coin!]!
enablePaperWalletOnly: Boolean!
hasLightning: Boolean!
serverVersion: String!
timezone: Int!
twoWayMode: Boolean!
localeInfo: LocaleInfo!
operatorInfo: OperatorInfo
machineInfo: MachineInfo!
receiptInfo: ReceiptInfo
speedtestFiles: [SpeedtestFile!]!
urlsToPing: [String!]!
triggersAutomation: TriggersAutomation!
triggers: [Trigger!]!
}
type DynamicCoinValues {
# NOTE: Doesn't seem to be used anywhere outside of lib/plugins.js.
# However, it can be used to generate the cache key, if we ever move to an
# actual caching mechanism.
#timestamp: String!
cryptoCode: String!
balance: String!
# Raw rates
ask: String!
bid: String!
# Rates with commissions applied
cashIn: String!
cashOut: String!
zeroConfLimit: Int!
}
type PhysicalCassette {
denomination: Int!
count: Int!
}
type Cassettes {
physical: [PhysicalCassette!]!
virtual: [Int!]!
}
type DynamicConfig {
areThereAvailablePromoCodes: Boolean!
cassettes: Cassettes
coins: [DynamicCoinValues!]!
reboot: Boolean!
shutdown: Boolean!
restartServices: Boolean!
}
type Configs {
static: StaticConfig
dynamic: DynamicConfig!
}
type Query {
configs(currentConfigVersion: Int): Configs!
terms(currentHash: String, currentConfigVersion: Int): Terms
}
`
|
JavaScript
| 0 |
@@ -1055,24 +1055,409 @@
Boolean!%0A%7D%0A%0A
+type CustomScreen %7B%0A text: String!%0A title: String!%0A%7D%0A%0Atype CustomInput %7B %0A type: String!%0A constraintType: String!%0A label1: String%0A label2: String%0A choiceList: %5BString%5D%0A%7D%0A%0Atype CustomRequest %7B%0A name: String!%0A input: CustomInput!%0A screen1: CustomScreen!%0A screen2: CustomScreen!%0A%7D %0A%0Atype CustomInfoRequest %7B%0A id: String!%0A enabled: Boolean!%0A customRequest: CustomRequest!%0A%7D%0A%0A
type Trigger
@@ -1634,16 +1634,55 @@
ys: Int%0A
+ customInfoRequest: CustomInfoRequest%0A
%7D%0A%0Atype
|
7c75ba8d830aaa2d809d6b1cb525fa382c14e91a
|
return raw response as JSON
|
lib/app.js
|
lib/app.js
|
/*jshint node:true, strict:false */
var express = require('express'),
url = require('url'),
request = require('request'),
u = require('underscore');
var app = express();
app.use(express.logger());
app.use(express['static'](__dirname + '/..'));
app.configure('production', function(){
var airbrakeKey = process.env.JSONP_AIRBRAKE_KEY;
if (airbrakeKey){
var airbrake = require('airbrake').createClient(airbrakeKey);
airbrake.handleExceptions();
console.log('Aibrake enabled');
}
});
// returns a copy of the object without the specified properties
function except(obj /*, properties */){
var result = u.extend({}, obj),
properties = u.rest(arguments);
properties.forEach(function(prop){
delete result[prop];
});
return result;
}
function isValidJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
app.get('/', function(req, res) {
var params = url.parse(req.url, true).query,
apiUrl = params.url || params.src;
if (!apiUrl){
// serve landing page
res.render('index.ejs', {
layout: false,
host: req.headers.host
});
} else {
// do proxy
// copy headers from the external request, but remove those that node should generate
var externalReqHeaders = except(req.headers, 'accept-encoding', 'connection', 'cookie', 'host', 'user-agent');
externalReqHeaders.accept = 'application/json';
request({
uri: apiUrl,
strictSSL: false, // node(jitsu?) has some SSL problems
headers: externalReqHeaders
}, function(error, response, body){
var callbackName = params.callback || params.jsonp,
raw = params.raw, // undocumented, for now
status;
if (error){
status = 502; // bad gateway
body = JSON.stringify({
error: error.message || body
});
} else if (!raw && !isValidJson(body)){
// invalid JSON
status = 502; // bad gateway
body = JSON.stringify({ error: body });
} else {
// proxy successful
status = response.statusCode;
// copy headers from the external response, but remove those that node should generate
res.set(except(response.headers, 'content-length', 'connection', 'server', 'x-frame-options'));
}
// enable cross-domain-ness
res.set('access-control-allow-origin', '*'); // CORS
if (!callbackName){
// treat as an AJAX request (CORS)
if (raw){
res.set('content-type', 'text/plain');
} else {
res.set('content-type', 'application/json');
}
} else {
// JSONP
res.set('content-type', 'text/javascript'); // use instead of 'application/javascript' for IE < 8 compatibility
if (raw){
// escape and pass as string
body = '"' + body.replace(/"/g, '\\"') + '"';
}
body = callbackName + '(' + body + ');';
}
res.send(status, body);
});
}
});
module.exports = app;
|
JavaScript
| 0.999901 |
@@ -2815,17 +2815,16 @@
ass
-as string
+via JSON
%0A
@@ -2841,45 +2841,36 @@
y =
-'%22' + body.replace(/%22/g, '%5C%5C%22') + '%22'
+JSON.stringify(%7Bdata: body%7D)
;%0A
|
70142e96af8959d472c2b820cfebc039e1ca7082
|
Fix --proxy argument to ember server
|
gulpfile.js
|
gulpfile.js
|
/* global require */
var gulp = require('gulp'),
spawn = require('child_process').spawn,
ember,
node;
gulp.task('server', function () {
if (node) node.kill(); // Kill server if one is running
node = spawn('node', ['server.js'], {cwd: 'node', stdio: 'inherit'});
node.on('close', function (code) {
if (code === 8) {
console.log('Node error detected, waiting for changes...');
}
});
});
gulp.task('ember', function () {
ember = spawn('./node_modules/.bin/ember', ['server', '--port=4900', '--proxy-port=3900'], {cwd: 'ember', stdio: 'inherit'});
ember.on('close', function (code) {
if (code === 8) {
console.log('Ember error detected, waiting for changes...');
}
});
});
gulp.task('default', function () {
gulp.run('server');
gulp.run('ember');
// Reload server if files changed
gulp.watch(['node/**/*.js'], function () {
gulp.run('server');
});
});
// kill node server on exit
process.on('exit', function() {
if (node) node.kill();
if (ember) ember.kill();
});
|
JavaScript
| 0 |
@@ -529,22 +529,34 @@
'--proxy
--port=
+=http://localhost:
3900'%5D,
|
37ae1a94daa87e1dd8333604ba7df2f62632ccdd
|
Update templating-engine.js
|
src/templating-engine.js
|
src/templating-engine.js
|
import {createScopeForTest} from 'aurelia-binding';
import {Container, inject} from 'aurelia-dependency-injection';
import {DOM} from 'aurelia-pal';
import {Controller} from './controller';
import {ModuleAnalyzer} from './module-analyzer';
import {Animator} from './animator';
import {ViewResources} from './view-resources';
import {CompositionEngine} from './composition-engine';
import {ViewFactory} from './view-factory';
import {ViewCompiler} from './view-compiler';
import {BehaviorInstruction} from './instructions';
/**
* Instructs the framework in how to enhance an existing DOM structure.
*/
interface EnhanceInstruction {
/**
* The DI container to use as the root for UI enhancement.
*/
container?: Container;
/**
* The element to enhance.
*/
element: Element;
/**
* The resources available for enhancement.
*/
resources?: ViewResources;
/**
* A binding context for the enhancement.
*/
bindingContext?: Object;
}
/**
* A facade of the templating engine capabilties which provides a more user friendly API for common use cases.
*/
@inject(Container, ModuleAnalyzer, ViewCompiler, CompositionEngine)
export class TemplatingEngine {
/**
* Creates an instance of TemplatingEngine.
* @param container The root DI container.
* @param moduleAnalyzer The module analyzer for discovering view resources.
* @param viewCompiler The view compiler...for compiling views ;)
* @param compositionEngine The composition engine used during dynamic component composition.
*/
constructor(container: Container, moduleAnalyzer: ModuleAnalyzer, viewCompiler: ViewCompiler, compositionEngine: CompositionEngine) {
this._container = container;
this._moduleAnalyzer = moduleAnalyzer;
this._viewCompiler = viewCompiler;
this._compositionEngine = compositionEngine;
container.registerInstance(Animator, Animator.instance = new Animator());
}
/**
* Configures the default animator.
* @param animator The animator instance.
*/
configureAnimator(animator: Animator): void {
this._container.unregister(Animator);
this._container.registerInstance(Animator, Animator.instance = animator);
}
/**
* Dynamically composes components and views.
* @param context The composition context to use.
* @return A promise for the resulting Controller or View. Consumers of this API
* are responsible for enforcing the Controller/View lifecyle.
*/
compose(context: CompositionContext): Promise<View | Controller> {
return this._compositionEngine.compose(context);
}
/**
* Enhances existing DOM with behaviors and bindings.
* @param instruction The element to enhance or a set of instructions for the enhancement process.
* @return A View representing the enhanced UI. Consumers of this API
* are responsible for enforcing the View lifecyle.
*/
enhance(instruction: Element | EnhanceInstruction): View {
if (instruction instanceof DOM.Element) {
instruction = { element: instruction };
}
let compilerInstructions = {};
let resources = instruction.resources || this._container.get(ViewResources);
this._viewCompiler._compileNode(instruction.element, resources, compilerInstructions, instruction.element.parentNode, 'root', true);
let factory = new ViewFactory(instruction.element, compilerInstructions, resources);
let container = instruction.container || this._container.createChild();
let view = factory.create(container, BehaviorInstruction.enhance());
view.bind(instruction.bindingContext || {});
return view;
}
/**
* Creates a behavior's controller for use in unit testing.
* @param viewModelType The constructor of the behavior view model to test.
* @param attributesFromHTML A key/value lookup of attributes representing what would be in HTML (values can be literals or binding expressions).
* @return The Controller of the behavior.
*/
createControllerForUnitTest(viewModelType: Function, attributesFromHTML?: Object): Controller {
let exportName = viewModelType.name;
let resourceModule = this._moduleAnalyzer.analyze('test-module', { [exportName]: viewModelType }, exportName);
let description = resourceModule.mainResource;
description.initialize(this._container);
let viewModel = this._container.get(viewModelType);
let instruction = BehaviorInstruction.unitTest(description, attributesFromHTML);
return new Controller(description.metadata, instruction, viewModel);
}
/**
* Creates a behavior's view model for use in unit testing.
* @param viewModelType The constructor of the behavior view model to test.
* @param attributesFromHTML A key/value lookup of attributes representing what would be in HTML (values can be literals or binding expressions).
* @param bindingContext
* @return The view model instance.
*/
createViewModelForUnitTest(viewModelType: Function, attributesFromHTML?: Object, bindingContext?: any): Object {
let controller = this.createControllerForUnitTest(viewModelType, attributesFromHTML);
controller.bind(createScopeForTest(bindingContext));
return controller.viewModel;
}
}
|
JavaScript
| 0 |
@@ -2821,32 +2821,33 @@
the View lifecy
+c
le.%0A */%0A enha
|
547e8f6111443fd9488413c3bee7d89696fbc51e
|
Add spacebars->tracker package dependency
|
packages/spacebars/package.js
|
packages/spacebars/package.js
|
Package.describe({
summary: "Handlebars-like template language for Meteor",
version: '1.0.4'
});
// For more, see package `spacebars-compiler`, which is used by
// the build plugin and not shipped to the client unless you
// ask for it by name.
//
// The Spacebars build plugin is in package `templating`.
//
// Additional tests are in `spacebars-tests`.
Package.onUse(function (api) {
api.export('Spacebars');
api.use('htmljs');
api.use('blaze');
api.use('observe-sequence');
api.use('templating');
api.addFiles(['spacebars-runtime.js']);
api.addFiles(['dynamic.html', 'dynamic.js'], 'client');
});
Package.onTest(function (api) {
api.use(["spacebars", "tinytest", "test-helpers", "reactive-var"]);
api.use("templating", "client");
api.addFiles(["dynamic_tests.html", "dynamic_tests.js"], "client");
});
|
JavaScript
| 0 |
@@ -430,24 +430,46 @@
('htmljs');%0A
+ api.use('tracker');%0A
api.use('b
|
385d67936b27521d344fb4834981ec77009e65d3
|
format usage
|
lib/ask.js
|
lib/ask.js
|
var path = require('path'),
flatiron = require('flatiron'),
argv = require('optimist').argv,
_ = require('underscore'),
remote = require('./commandlinefu'),
local = require('./mongo')
var cli = exports
var help = ['usage: ask [action] [options]', '', 'query and add commands right from the terminal.', '', 'actions:', 'add open your $EDITOR edit and submit your last command(!!).', 'exec <id> exec the command with given id.', 'query <words> query for commands containing the keywords.', 'copy <id> paste in the command with given id.', '', 'options:', '--local query local database', '--remote query remote database', '--desc add description right from terminal', '']
var app = flatiron.app
app.config.use('argv', argvOptions)
var actions = ['add', 'exec', 'query', 'copy']
var argvOptions = {
'local': {
alias: 'l'
},
'remote': {
alias: 'r'
},
'desc': {
alias: 'd'
}
}
app.use(flatiron.plugins.cli, {
argv: argvOptions,
usage: help
})
cli.start = app.start
app.cmd(/exec (.+)/, function(id) {
execId = parseInt(id, 10)
if (_.isNaN(execId)) {
app.log.error('need a valid id for command to be executed.')
} else {
local.getCommand(execId, function(err) {
if (err) throw err
console.log('local execution will be added later.')
})
}
})
app.cmd(/query (.+)/, function(query) {
if (argv.local) {
local.query(query, function(err) {
if (err) app.log.error('failed to query, please try again.')
process.exit()
})
} else {
remote.query(query)
}
})
app.cmd(/add (.+)/, function(options) {
var cmd, desc
cmd = argv.cmd || options
desc = argv.desc
if (!cmd) {
app.log.error('please add the commands you want to add.')
} else if (!desc) {
app.log.error('please add some descriptions to the command')
} else {
cmd_data = {
cmd: cmd,
desc: desc
}
local.add(cmd_data, function(err) {
if (err) app.log.error('failed to add new command, please try again.')
process.exit()
})
}
})
|
JavaScript
| 0.000007 |
@@ -221,16 +221,21 @@
help = %5B
+%0A
'usage:
@@ -258,20 +258,28 @@
tions%5D',
- '',
+%0A '',%0A
'query
@@ -321,20 +321,28 @@
minal.',
- '',
+%0A '',%0A
'action
@@ -345,16 +345,20 @@
tions:',
+%0A
'add
@@ -425,16 +425,20 @@
d(!!).',
+%0A
'exec %3C
@@ -480,16 +480,20 @@
en id.',
+%0A
'query
@@ -547,16 +547,20 @@
words.',
+%0A
'copy %3C
@@ -558,24 +558,25 @@
'copy %3Cid%3E
+
paste
@@ -606,20 +606,28 @@
en id.',
- '',
+%0A '',%0A
'option
@@ -630,16 +630,20 @@
tions:',
+%0A
'--loca
@@ -670,24 +670,28 @@
l database',
+%0A
'--remote
@@ -719,16 +719,20 @@
tabase',
+%0A
'--desc
@@ -778,16 +778,20 @@
rminal',
+%0A
''%5D%0A%0Ava
@@ -2131,20 +2131,21 @@
exit()%0A %7D)%0A %7D%0A%7D)
+%0A
|
e7aaae24d3644fd2d238b057aa2643414af0744c
|
Add `gulp netlify` task
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var file = require('gulp-file');
var rename = require('gulp-rename');
var replace = require('gulp-replace');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var gutil = require('gulp-util');
var zip = require('gulp-zip');
var merge = require('merge2');
var path = require('path');
var rollup = require('rollup-stream');
var source = require('vinyl-source-stream');
var {exec} = require('mz/child_process');
var pkg = require('./package.json');
var argv = require('yargs')
.option('output', {alias: 'o', default: 'dist'})
.option('samples-dir', {default: 'samples'})
.option('docs-dir', {default: 'docs'})
.argv;
function watch(glob, task) {
gutil.log('Waiting for changes...');
return gulp.watch(glob, function(e) {
gutil.log('Changes detected for', path.relative('.', e.path), '(' + e.type + ')');
var r = task();
gutil.log('Waiting for changes...');
return r;
});
}
gulp.task('default', ['build']);
gulp.task('build', function() {
var out = argv.output;
var task = function() {
return rollup('rollup.config.js')
.pipe(source(pkg.name + '.js'))
.pipe(gulp.dest(out))
.pipe(rename(pkg.name + '.min.js'))
.pipe(streamify(uglify({preserveComments: 'license'})))
.pipe(gulp.dest(out));
};
var tasks = [task()];
if (argv.watch) {
tasks.push(watch('src/**/*.js', task));
}
return tasks;
});
gulp.task('lint', function() {
var files = [
'samples/**/*.js',
'src/**/*.js',
'*.js'
];
return gulp.src(files)
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('docs', function(done) {
var script = require.resolve('gitbook-cli/bin/gitbook.js');
var out = path.join(argv.output, argv.docsDir);
var cmd = process.execPath;
exec([cmd, script, 'install', './'].join(' ')).then(() => {
return exec([cmd, script, 'build', './', out].join(' '));
}).then(() => {
done();
}).catch((err) => {
done(new Error(err.stdout || err));
});
});
gulp.task('samples', function() {
// since we moved the dist files one folder up (package root), we need to rewrite
// samples src="../dist/ to src="../ and then copy them in the /samples directory.
var out = path.join(argv.output, argv.samplesDir);
return gulp.src('samples/**/*', {base: 'samples'})
.pipe(streamify(replace(/src="((?:\.\.\/)+)dist\//g, 'src="$1', {skipBinary: true})))
.pipe(gulp.dest(out));
});
gulp.task('package', ['build', 'samples'], function() {
var out = argv.output;
return merge(
gulp.src(path.join(out, argv.samplesDir, '**/*'), {base: out}),
gulp.src([path.join(out, '*.js'), 'LICENSE.md'])
)
.pipe(zip(pkg.name + '.zip'))
.pipe(gulp.dest(out));
});
gulp.task('bower', function() {
var json = JSON.stringify({
name: pkg.name,
description: pkg.description,
homepage: pkg.homepage,
license: pkg.license,
version: pkg.version,
main: argv.output + '/' + pkg.name + '.js'
}, null, 2);
return file('bower.json', json, {src: true})
.pipe(gulp.dest('./'));
});
|
JavaScript
| 0.999999 |
@@ -714,16 +714,54 @@
docs'%7D)%0A
+%09.option('www-dir', %7Bdefault: 'www'%7D)%0A
%09.argv;%0A
@@ -2763,32 +2763,514 @@
est(out));%0A%7D);%0A%0A
+gulp.task('netlify', %5B'build', 'docs', 'samples'%5D, function() %7B%0A%09var root = argv.output;%0A%09var out = path.join(root, argv.wwwDir);%0A%0A%09return merge(%0A%09%09gulp.src(path.join(root, argv.docsDir, '**/*'), %7Bbase: path.join(root, argv.docsDir)%7D),%0A%09%09gulp.src(path.join(root, argv.samplesDir, '**/*'), %7Bbase: root%7D),%0A%09%09gulp.src(path.join(root, '*.js'))%0A%09)%0A%09.pipe(streamify(replace(/https?:%5C/%5C/chartjs-plugin-datalabels%5C.netlify%5C.com%5C/?/g, '/', %7BskipBinary: true%7D)))%0A%09.pipe(gulp.dest(out));%0A%7D);%0A%0A
gulp.task('bower
|
97e639725e14647466c7fbf6626ecee4878648f3
|
Exit on Ctrl+C.
|
lib/index.js
|
lib/index.js
|
/**
* Module dependencies
*/
var server = require('./server')
var service = require('./service')
var discovery = require('./discovery')
var Superpipe = require('superpipe')
/**
* Micromono constructor
*/
var Micromono = function() {
var micromono = this
// Store instances of services
micromono.services = {}
// Make instance of superpipe
var superpipe = new Superpipe()
micromono.superpipe = superpipe.autoBind(true)
// Assign submodules to the main object
micromono.startService = service.startService.bind(null, micromono)
micromono.startBalancer = server.startBalancer.bind(micromono)
micromono.require = discovery.require.bind(micromono)
micromono.register = discovery.register.bind(micromono)
micromono.Service = service.Service
micromono.createService = service.createService
// Expose constructor
micromono.Micromono = Micromono
// Apply default configurations
this.defaultConfig()
return micromono
}
// Add configurable api using superpipe
Micromono.prototype.set = function(name, deps, props) {
this.superpipe.setDep(name, deps, props)
return this
}
Micromono.prototype.get = function(name, deps, props) {
return this.superpipe.getDep(name, deps, props)
}
Micromono.prototype.defaultConfig = function() {
// Bundle asset for dev?
if ('development' === process.env.NODE_ENV
&& undefined === this.get('bundle dev'))
this.set('bundle dev', true)
this.set('services', this.services)
}
/**
* Exports the main MicroMono instance object.
*
* @type {Object}
*/
module.exports = new Micromono()
|
JavaScript
| 0 |
@@ -1451,16 +1451,126 @@
ervices)
+%0A%0A process.on('SIGINT', function() %7B%0A console.log('%5CnShutting down micromono...')%0A process.exit(0)%0A %7D)
%0A%7D%0A%0A/**%0A
|
dfdbd13eb96c9e9b3649adb9a9babfe2f1a32da3
|
Fix overwritten property in .eslintrc.js
|
.eslintrc.js
|
.eslintrc.js
|
module.exports = {
extends: './.eslintrc.google.js',
parserOptions: {
"ecmaVersion": 2017,
"sourceType": "module",
},
env: {
es6: true,
},
rules: {
'arrow-parens': 0,
'block-spacing': 0,
'brace-style': 0,
'camelcase': 0,
'comma-dangle': 0,
'comma-style': [2, 'last'],
'curly': 0,
'indent': [0, 4],
'key-spacing': 0,
'linebreak-style': 0,
'linebreak-style': 2,
'max-len': 0,
'new-cap': 0,
'no-invalid-this': 0,
'no-multi-spaces': 0,
'no-undef': 2,
'no-unused-vars': 1,
'object-curly-spacing': 0,
'padded-blocks': [0, 'never'],
'quote-props': 0,
'quotes': 0,
'require-jsdoc': 0,
'semi': [1, 'always'],
'space-before-function-paren': [0, {"anonymous": "never"}],
'valid-jsdoc': 0,
},
globals: {
// $: true,
_: true,
rdfstore: true,
FormData: true,
Backbone: true,
document: true,
require: true,
define: true,
console: true,
window: true,
process: true,
module: true,
Image: true,
exports: true,
parent: true,
setTimeout: true,
setInterval: true,
clearTimeout: true,
clearInterval: true,
__dirname: true,
GM_registerMenuCommand: true,
__filename: true,
Buffer: true,
fetch: true,
},
}
|
JavaScript
| 0.000001 |
@@ -433,38 +433,8 @@
0,%0A
- 'linebreak-style': 0,%0A
|
f370716ed2d864f0f37e672d7ce7c8c8b22362f5
|
update eslintrc
|
.eslintrc.js
|
.eslintrc.js
|
module.exports = {
"extends": "airbnb"
};
|
JavaScript
| 0.000001 |
@@ -40,6 +40,61 @@
nb%22%0A
+ rules: %7B%0A 'import/no-unresolved': 0,%0A %7D%0A
%7D;
+%0A
|
eaba6439393f942c4409e670f485102ae7fbb37d
|
i need sleep
|
lib/box.js
|
lib/box.js
|
var mongoose = require('mongoose');
var boxSchema = new mongoose.Schema({
timestamp: { type: Date, default: Date.now, expires: 7*24*60*60 },
tags: [ String ],
street1: { type: String, required: true },
street2: { type: String, required: true },
city: { type: String, required: true },
state: { type: String, required: true },
zip: { type: Number, required: true },
geo: geo: { type: [ Number ], index: '2d' }
module.exports.schema = boxSchema;
module.exports.model = mongoose.model('Box', boxSchema);
|
JavaScript
| 0.998474 |
@@ -435,16 +435,19 @@
: '2d' %7D
+%0A%7D)
%0A%0Amodule
|
47f8540b0d594aceb726dda96e64d346fc9e1e6e
|
Method 2
|
lib/index.js
|
lib/index.js
|
/**
*
* STREAM: moving median
*
*
* DESCRIPTION:
* - Transform stream factory to find sliding-window median values (moving median) over a numeric data stream.
*
*
* NOTES:
*
*
* TODO:
*
*
* HISTORY:
* - 2014/08/04: Created. [RJSmith]
*
* DEPENDENCIES:
* [1] through2
*
* LICENSE:
* MIT
*
* COPYRIGHT (C) 2014. Rebekah Smith.
*
*
* AUTHOR:
* Rebekah Smith. [email protected]. 2014.
*
*/
(function() {
'use strict';
// MODULES //
var through2 = require( 'through2' );
// FUNCTIONS //
/**
* FUNCTION: getBuffer(W)
* Returns a buffer array pre-initialized to 0.
*
* @private
* @param {Number} W - buffer size
* @returns {Array} buffer
*/
function getBuffer(W) {
var buffer = new Array(W);
for (var i = 0; i < W; i++) {
buffer[i] = 0;
}
return buffer;
} // end FUNCTION getBuffer()
/**
* FUNCTION: compFunc(a,b)
* Finds difference between two numbers, used as compare function for sorting.
*
* @private
* @param {Number} a, b - numeric values in an array
* @returns {Number} difference, sign used to sort a and b
*/
function compFunc(a,b) {
return a-b;
} // end FUNCTION compFunc()
/**
* FUNCTION: findMedian(sArray)
* Finds the middle array element(s) and returns the median value
*
* @private
* @param {Number} B - size of window buffer
* @param {Array} sArray - sorted array containing window values
* @returns {Number} median value
*/
function findMedian(B, sArray) {
var median = 0;
if(B%2 === 0) {
median = ( sArray[ B/2 ] + sArray[ (B/2) - 1 ] )/2;
}
else {
median = sArray[ (B - 1)/2 ];
}
return median;
} // end FUNCTION findMedian()
/**
* FUNCTION: onData(W)
* Returns a callback which calculates a moving median.
*
* @private
* @param {Number} W - window size
* @returns {Function} callback
*/
function onData(W) {
var buffer = getBuffer(W), // first buffer, contains values in current window
findMed = getBuffer(W), // second buffer, to be sorted
full = false,
median = 0,
N = 0;
/**
* FUNCTION: onData(newVal, encoding, clbk)
* Data event handler. Calculates the moving median.
*
* @private
* @param {Number} newVal - streamed data value
* @param {String} encoding
* @param {Function} clbk - callback to invoke after finding a median value. Function accepts two arguments: [ error, chunk ].
*/
return function onData(newVal, encoding, clbk) {
// Fill buffers of size W and find initial median:
if (!full) {
buffer[N] = newVal;
findMed[N] = newVal;
N++;
if (N===W) {
full = true;
// Sort copy of first buffer:
findMed.sort(compFunc);
// Get first median value:
median = findMedian(W, findMed);
this.push(median);
}
clbk();
return;
}
// Update buffer: (drop old value, add new)
buffer.shift();
buffer.push(newVal);
// Copy updated buffer
findMed = buffer.slice();
// Sort copy of buffer
findMed.sort(compFunc);
median = findMedian(W, findMed);
clbk(null, median);
}; // end FUNCTION onData()
} // end FUNCTION onData()
// STREAM //
/**
* FUNCTION: Stream()
* Stream constructor.
*
* @constructor
* @returns {Stream} Stream instance
*/
function Stream() {
this._window = 5; //default window size
return this;
} // end FUNCTION Stream()
/**
* METHOD: window(value)
* Window size setter/getter. If a value is provided, sets the window size. If no value is provided, returns the window size.
*
* @param {Number} value - window size
* @returns {Stream|Number} stream instance or window size
*/
Stream.prototype.window = function(value) {
if (!arguments.length) {
return this._window;
}
if(typeof value !== 'number' || value !== value) {
throw new Error('window()::invalid input argument. Window must be numeric.');
}
this._window = value;
return this;
}; // end METHOD window()
/**
* METHOD: stream()
* Returns a through stream which finds the sliding-window median.
*
* @returns {Object} through stream
*/
Stream.prototype.stream = function(){
return through2({'objectMode': true}, onData(this._window));
}; // end METHOD stream()
// EXPORTS //
module.exports = function createStream() {
return new Stream();
};
})();
|
JavaScript
| 0.999941 |
@@ -26,16 +26,27 @@
g median
+ - method 2
%0A*%0A*%0A*
|
0412d238a94b0da2e8d9ecf54422c6d053ec6fc5
|
Use Browser environment
|
.eslintrc.js
|
.eslintrc.js
|
module.exports = {
extends: 'airbnb',
rules: {
'import/no-extraneous-dependencies': ["error", { "devDependencies": true }],
'max-len': ["warn", 160, 4, {"ignoreUrls": true}],
'no-multi-spaces': ["error", { exceptions: { "ImportDeclaration": true } }],
'no-param-reassign': ["error", { props: false }],
'no-unused-vars': ["error", { args: 'none' }],
'react/jsx-filename-extension': ["error", { "extensions": [".js"] }],
'no-mixed-operators': ["error", {"allowSamePrecedence": true}],
// Should fix that at some point but too much work...
'react/no-is-mounted': "warn",
'no-var': 0,
'one-var': 0,
'react/prefer-es6-class': 0,
'no-nested-ternary': 0,
// Not for us ;-)
'jsx-a11y/label-has-for': 0,
'no-console': 0,
'no-plusplus': 0,
// Not for vtk.js
'import/no-named-as-default': 0,
'import/no-named-as-default-member': 0,
// eslint-3.3.0
"no-global-assign": 0,
"no-unsafe-negation": 0,
},
globals: {
vtkDebugMacro: false,
vtkErrorMacro: false,
vtkWarningMacro: false,
}
};
|
JavaScript
| 0.000001 |
@@ -1079,12 +1079,46 @@
lse,%0A %7D
+,%0A env: %7B%0A browser: true,%0A %7D,
%0A%7D;%0A
|
21c9fbf928fdc85ffc1e016446552594b0603a5b
|
store global again in js
|
html/tests/js/test-webbox.js
|
html/tests/js/test-webbox.js
|
var host = document.location.host;
if (host.indexOf(':') >= 0) {
host = host.slice(0,host.indexOf(':'));
}
$(document).ready(function() {
console.log('http://'+host+':8211/js/webbox-backbone.js');
var test_pasta = function() {
store.login('webbox', 'foobar').then(function(x) {
console.log('logged in ');
store.load_box('hamburgers').then(function(box) {
console.log("got a box of pastas ", box.id, box);
var dinnergraph = box.get_or_create('dinner');
window.dinnergraph = dinnergraph;
dinnergraph.fetch().then(function(d) {
console.log('fetched dinner ', dinnergraph.objs().length);
var carbonara = dinnergraph.get_or_create('puttanesca');
carbonara.set({name:"carbonara", calories:10293, carbs: 92389, fats: 2398, yumminess:2398 });
dinnergraph.save();
});
});
});
};
$.getScript('http://'+host+':8211/js/webbox-backbone.js', function() {
console.log('get script done');
var store = new ObjectStore.Store([], { server_url : "http://"+host+":8211/" });
// window.store = store;
// test_pasta(store);
$('#login').click(function() {
var username = $('#username').val(), pass = $('#password').val()
console.log('logging in as user ', username, pass)
store.login(username,pass).then(function() {
console.log('logged in ');
}).fail(function(err) {
console.log('fail ', err);
});
});
});
});
|
JavaScript
| 0 |
@@ -1030,19 +1030,16 @@
%22 %7D);%0A%09%09
-//
window.s
|
935e6251b74bdc27c7717b2fefa29a99fdee60aa
|
update interface for collectHostSnmp
|
lib/jobs/snmp-job.js
|
lib/jobs/snmp-job.js
|
// Copyright 2014-2015, Renasar Technologies Inc.
/* jshint: node:true */
'use strict';
var di = require('di');
module.exports = snmpJobFactory;
di.annotate(snmpJobFactory, new di.Provide('Job.Snmp'));
di.annotate(snmpJobFactory, new di.Inject(
'Job.Base',
'JobUtils.Snmptool',
'JobUtils.SnmpParser',
'Logger',
'Util',
'Assert',
'Q',
'_',
'Services.Encryption'
));
function snmpJobFactory(BaseJob, Snmptool, parser, Logger, util, assert, Q, _, encryption) {
var logger = Logger.initialize(snmpJobFactory);
function createMetricLabel(mibBaseType, oidSubTreeValue) {
return mibBaseType + '-' + oidSubTreeValue;
}
/**
*
* @param {Object} options
* @param {Object} context
* @param {String} taskId
* @constructor
*/
function SnmpJob(options, context, taskId) {
SnmpJob.super_.call(this, logger, options, context, taskId);
this.routingKey = context.graphId;
assert.uuid(this.routingKey);
// Currently a noop data structure, but a placeholder for future work
// when we gather data from certain IF-MIB mibs to correlate numeric OID values
// to human readable interface names
this.mibNameMap = {};
}
util.inherits(SnmpJob, BaseJob);
/**
* @memberOf SnmpJob
*/
SnmpJob.prototype._run = function run() {
// NOTE: this job will run indefinitely absent user intervention
var self = this;
self._subscribeRunSnmpCommand(self.routingKey, function(data) {
return self.collectHostSnmp(data, Snmptool, parser, logger, Q, _, self.mibNameMap)
.then(function(result) {
data.mibs = result;
return self._publishSnmpCommandResult(self.routingKey, data);
})
.catch(function (err) {
logger.warning("Failed to capture data through SNMP.", {
data: data,
error: err
});
});
});
};
SnmpJob.prototype.collectHostSnmp = function (
machine, Snmptool, parser, logger, Q, _, mibNameMap
) {
var mibsToQuery = [
//'IF-MIB::ifXTable',
//'IF-MIB::ifTable',
//'LLDP-MIB::lldpStatsRxPortTable',
//'LLDP-MIB::lldpStatsTxPortTable',
//'ENTITY-SENSOR-MIB::entPhySensorValue',
// Raritan
//'PDU-MIB::outletVoltage',
//'PDU-MIB::outletCurrent',
//'PDU-MIB::outletOperationalState'
// APC
//'PowerNet-MIB::rPDULoadDevMaxPhaseLoad', // max load for this PDU
//'PowerNet-MIB::sPDUOutletCtl', // state of each outlet (1 on, 2 off)
//'PowerNet-MIB::rPDULoadStatusLoad', // current in 10ths of amps
//'PowerNet-MIB::rPDUIdentDeviceLinetoLineVoltage' // voltage
];
var allMibs = mibsToQuery;
var hostIp = machine.host;
var communityString = machine.communityString;
var snmpTool = new Snmptool(hostIp, encryption.decrypt(communityString));
if (!_.isEmpty(machine.extensionMibs) &&
_.isArray(machine.extensionMibs)) {
allMibs = _.union(allMibs, _.compact(machine.extensionMibs));
} else if (machine.extensionMibs !== undefined) {
logger.warning("User specified MIBs are not in valid format, " +
"expected an array of strings");
}
return Q.allSettled(_.map(allMibs, function (mibTableOrEntry) {
var parsed;
return snmpTool.walk(mibTableOrEntry)
.then(function (mibs) {
// First we parse all of our mibs that we got from the table.
// If we did a walk for a mib value and not a table, it
// shouldn't make a difference in the code...
var allParsed = _.map(mibs[0].trim().split('\n'), function (mib) {
// No threshold rule for now
mib = mib.trim();
try {
parsed = parser.parseSnmpData(mib);
} catch (e) {
return e;
}
return parsed;
});
// Then we need to update the label names for each sample
return _.map(allParsed, function (p) {
var rawLabel = createMetricLabel(p.mibBaseType, p.oidSubTreeValue);
p.metricLabel = mibNameMap[rawLabel] || rawLabel;
return {
value: p.value,
name: p.metricLabel
};
});
});
}))
.then(function (results) {
_.forEach(results, function (result) {
if (result.state !== 'fulfilled') {
throw new Error(result.reason);
}
});
return _.map(results, function(result) {
return result.value;
});
});
};
return SnmpJob;
}
|
JavaScript
| 0 |
@@ -1593,57 +1593,8 @@
data
-, Snmptool, parser, logger, Q, _, self.mibNameMap
)%0A
@@ -2039,85 +2039,56 @@
on (
-%0A machine, Snmptool, parser, logger, Q, _, mibNameMap
+machine) %7B%0A var self = this,
%0A
-) %7B%0A
var
@@ -2083,20 +2083,16 @@
-var
mibsToQu
@@ -4436,16 +4436,21 @@
Label =
+self.
mibNameM
|
2459a4d976b7faa9e65362aa7135277c0d7d1ee2
|
Edit database details
|
server/models/index.js
|
server/models/index.js
|
'use strict';
import dotenv from 'dotenv';
import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';
dotenv.config();
const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || 'development';
const config = require('../../server/config/config')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env.DB_URL, {
dialect: 'postgres'
});
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter((file) => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach((file) => {
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
|
JavaScript
| 0 |
@@ -480,65 +480,57 @@
ize(
-config.database, config.username, config.password, config
+process.env.DB_URL, %7B%0A dialect: 'postgres'%0A %7D
);%0A%7D
|
0318bb88830e80bc891e08bb5132d0f670f057e8
|
Fix tests.
|
src/__tests__/parser.js
|
src/__tests__/parser.js
|
import ava from 'ava';
import Parser from '../parser';
const suite = [
['block | inline', {
nodes: [{
type: 'keyword',
value: 'block',
exclusive: true
}, {
type: 'keyword',
value: 'inline',
exclusive: true
}]
}],
['<string>+', {
nodes: [{
type: 'data',
value: 'string',
exclusive: false,
repeat: {
min: 1,
max: false,
separator: ' '
}
}]
}],
['<time>#', {
nodes: [{
type: 'data',
value: 'time',
exclusive: false,
repeat: {
min: 1,
max: false,
separator: ','
}
}]
}],
['<length> <length>?', {
nodes: [{
type: 'data',
value: 'length',
exclusive: false
}, {
type: 'data',
value: 'length',
exclusive: false,
optional: true
}]
}],
['[ over | under ] && [ right | left ]', {
nodes: [{
type: 'group',
nodes: [{
type: 'keyword',
value: 'over',
exclusive: true
}, {
type: 'keyword',
value: 'under',
exclusive: true
}],
exclusive: false,
required: true,
order: 'any'
}, {
type: 'group',
nodes: [{
type: 'keyword',
value: 'right',
exclusive: true
}, {
type: 'keyword',
value: 'left',
exclusive: true
}],
required: true,
order: 'any'
}]
}],
['[ <length> | <number> ]{1,4}', {
nodes: [{
type: 'group',
nodes: [{
type: 'data',
value: 'length',
exclusive: true
}, {
type: 'data',
value: 'number',
exclusive: true
}],
exclusive: false,
repeat: {
min: 1,
max: 4,
separator: ' '
}
}]
}],
['none | [ weight || style ]', {
nodes: [{
type: 'keyword',
value: 'none',
exclusive: true
}, {
type: 'group',
nodes: [{
type: 'keyword',
value: 'weight',
exclusive: false,
order: 'any',
optional: true
}, {
type: 'keyword',
value: 'style',
exclusive: false,
order: 'any',
optional: true
}]
}]
}],
["<'grid-column-gap'> <'grid-row-gap'>?", {
nodes: [{
type: 'data',
value: 'length',
exclusive: false
}, {
type: 'data',
value: 'length',
exclusive: false,
optional: true
}]
}],
["normal | [<number> <integer>?]", {
nodes: [{
type: 'keyword',
value: 'normal',
exclusive: true
}, {
type: 'group',
nodes: [{
type: 'data',
value: 'number',
exclusive: false
}, {
type: 'data',
value: 'integer',
exclusive: false,
optional: true
}]
}]
}]
];
suite.forEach(spec => ava(spec[0], t => t.same(new Parser(spec[0]), spec[1])));
|
JavaScript
| 0 |
@@ -3069,44 +3069,244 @@
e: '
-length',%0A exclusive: fals
+percentage',%0A exclusive: true%0A %7D, %7B%0A type: 'data',%0A value: 'length',%0A exclusive: false%0A %7D, %7B%0A type: 'data',%0A value: 'percentage',%0A exclusive: tru
e%0A
@@ -3979,12 +3979,17 @@
%3E t.
-same
+deepEqual
(new
|
928f4c32b2af5c747de1645a6a38d6509a0093da
|
Allow es6 syntax
|
.eslintrc.js
|
.eslintrc.js
|
module.exports = {
extends: ["eslint:recommended", "plugin:prettier/recommended"],
plugins: ["prettier"],
rules: {
"prettier/prettier": "error",
"no-console": [
"error",
{
allow: ["error"]
}
]
},
env: {
node: true
}
};
|
JavaScript
| 0.000002 |
@@ -253,16 +253,31 @@
node:
+ true,%0A es6:
true%0A
|
8c193a77d5e44ca2ae5708cbb65b47ca8e197dce
|
Fix the sound in the menu
|
renanbrg/dropstory/js/states/Menu.js
|
renanbrg/dropstory/js/states/Menu.js
|
/*global State, Config*/
State.Menu = function(game) {
"use strict";
this.game = game;
this.inicioSound = null;
};
State.Menu.prototype = {
preload: function() {
"use strict";
this.game.load.image('level1preloaderbg', Config.preloaderLevel1.dir);
this.game.load.spritesheet('button-back', Config.Menu.buttonBack.dir,
Config.Menu.buttonBack.width, Config.Menu.buttonBack.height);
},
create: function() {
"use strict";
this.game.add.sprite(Config.Menu.x, Config.Menu.y,
'game-splash');
var playButton = this.game.add.button(Config.Menu.buttonPlay.x,
Config.Menu.buttonPlay.y, 'button-play', this.clickPlay,
this, 1, 0, 1, 0);
var howToButton = this.game.add.button(Config.Menu.buttonHowToPlay.x,
Config.Menu.buttonHowToPlay.y, 'button-how-to-play',
this.clickHowToPlay, this, 1, 0, 1, 0);
var creditsButton = this.game.add.button(Config.Menu.buttonCredits.x,
Config.Menu.buttonCredits.y, 'button-credits',
this.clickCredits, this, 1, 0, 1, 0);
if (this.inicioSound == null) {
this.inicioSound = this.game.add.audio('som-inicio');
this.inicioSound.loop = true;
this.inicioSound.play();
}
},
clickPlay: function () {
"use strict";
this.inicioSound.stop();
this.game.state.start('level2preloader-state');
},
clickHowToPlay: function () {
"use strict";
this.game.state.start('howtoplay-state');
},
clickCredits: function () {
"use strict";
this.game.state.start('credits-state');
}
};
|
JavaScript
| 0 |
@@ -1307,16 +1307,69 @@
= true;%0A
+ %7D%0A if (!this.inicioSound.isPlaying) %7B%0A
|
ce4902f436f65440be22afa1b5823ef3d038b4ca
|
fix commonjs shim
|
build/js/twgl-start.js
|
build/js/twgl-start.js
|
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} if (typeof exports !== 'undefined') {
exports = factory();
} else {
root.twgl = factory();
}
}(this, function () {
|
JavaScript
| 0.000003 |
@@ -121,23 +121,22 @@
(typeof
-exports
+module
!== 'un
@@ -143,16 +143,34 @@
defined'
+ && module.exports
) %7B%0A
@@ -173,16 +173,23 @@
+module.
exports
|
132dd7f18eda078a79ac486c6f63763ae8321b97
|
create http server
|
src/events/http/Http.js
|
src/events/http/Http.js
|
import HttpEventDefinition from './HttpEventDefinition.js'
import HttpServer from './HttpServer.js'
export default class Http {
#httpServer = null
constructor(serverless, options, lambda) {
this.#httpServer = new HttpServer(serverless, options, lambda)
}
start() {
return this.#httpServer.start()
}
// stops the server
stop(timeout) {
return this.#httpServer.stop(timeout)
}
async createServer() {
await this.#httpServer.createServer()
}
#createEvent(functionKey, rawHttpEventDefinition, handler) {
const httpEvent = new HttpEventDefinition(rawHttpEventDefinition)
this.#httpServer.createRoutes(functionKey, httpEvent, handler)
}
create(events) {
events.forEach(({ functionKey, handler, http }) => {
this.#createEvent(functionKey, http, handler)
})
this.#httpServer.writeRoutesTerminal()
}
createResourceRoutes() {
this.#httpServer.createResourceRoutes()
}
create404Route() {
this.#httpServer.create404Route()
}
// TEMP FIXME quick fix to expose gateway server for testing, look for better solution
getServer() {
return this.#httpServer.getServer()
}
}
|
JavaScript
| 0.000322 |
@@ -150,117 +150,197 @@
%0A%0A
-constructor(serverless, options, lambda) %7B%0A this.#httpServer = new HttpServer(serverless, options, lambda)
+#lambda = null%0A%0A #options = null%0A%0A #serverless = null%0A%0A constructor(serverless, options, lambda) %7B%0A this.#lambda = lambda%0A this.#options = options%0A this.#serverless = serverless
%0A %7D
@@ -481,16 +481,16 @@
t)%0A %7D%0A%0A
-
async
@@ -502,24 +502,135 @@
eServer() %7B%0A
+ this.#httpServer = new HttpServer(%0A this.#serverless,%0A this.#options,%0A this.#lambda,%0A )%0A%0A
await th
|
7d97e7cedcc6dd24328c28b1ce4bb16c84fb4ca4
|
Add flow types to Scanner class
|
lib/lexer/scanner.js
|
lib/lexer/scanner.js
|
export default class Scanner {
constructor (code = "", options = {indexOffset: 0, lineOffset: 0, lineStartOffset: 0}) {
const indexOffset = (options.indexOffset > 0 ? options.indexOffset : 0);
const lineOffset = (options.lineOffset > 0 ? options.lineOffset : 0);
const lineStartOffset = (options.lineStartOffset > 0 ? options.lineStartOffset : 0);
this[Symbol.iterator] = () => this;
this.code = code.split("");
this.index = -1 + indexOffset;
this.line = (code.length > 0) ? 1 + lineOffset : 0;
this.lineStart = 0 + lineStartOffset;
this.char = "";
this.lineCache = null;
}
isLineTerminator (char) {
return ["\n", "\r", "\r\n", "\u2028", "\u2029"].indexOf(char) !== -1;
}
next () {
if (this.lineCache) {
this.line = this.lineCache.line;
this.lineStart = this.lineCache.lineStart;
this.lineCache = null;
}
this.char = this.code.shift();
this.index++;
if (this.isLineTerminator(this.char + this.peek())) {
this.char += this.peek();
this.code.shift();
}
if (this.isLineTerminator(this.char)) {
this.lineCache = {
line: this.line + 1,
lineStart: this.index
};
}
return {
value: this.char,
done: !this.char
};
}
peek () {
return this.code[0] || "";
}
}
|
JavaScript
| 0 |
@@ -1,8 +1,18 @@
+// @flow%0A%0A
export d
@@ -41,329 +41,327 @@
%0A%09co
-nstructor (code = %22%22, options = %7BindexOffset: 0, lineOffset: 0, lineStartOffset: 0%7D) %7B%0A%09%09const indexOffset = (options.indexOffset %3E 0 ? options.indexOffset : 0);%0A%09
+de: Array%3Cstring%3E;%0A%09index: number;%0A%09line: number;%0A%09lineStart: number;%0A%09char: string;%0A%09lineCache: ?%7B%0A%09%09line: number;%0A%09%09lineStart: number%0A%09%7D;%0A%0A
%09const
- lineOffset = (options.lineOffset %3E 0 ? options.line
+ructor (code: string = %22%22, options: Object = %7B%7D) %7B%0A%09%09const opts = Object.assign(%7B%0A%09%09%09index
Offset
-
: 0
-);%0A%09%09const lineStartOffset = (options.lineStartOffset %3E 0 ? options.lineStartOffset : 0);%0A
+,%0A%09%09%09lineOffset: 0,%0A%09%09%09lineStartOffset: 0%0A%09%09%7D, options);%0A%0A%09%09// $FlowIssue
%0A%09%09t
@@ -385,16 +385,22 @@
or%5D = ()
+: this
=%3E this
@@ -451,16 +451,21 @@
= -1 +
+opts.
indexOff
@@ -507,16 +507,21 @@
) ? 1 +
+opts.
lineOffs
@@ -551,16 +551,21 @@
t = 0 +
+opts.
lineStar
@@ -643,17 +643,34 @@
or (char
-)
+: string): boolean
%7B%0A%09%09ret
@@ -748,16 +748,48 @@
%09next ()
+: %7Bvalue: string; done: boolean%7D
%7B%0A%09%09if
@@ -1277,16 +1277,24 @@
%09peek ()
+: string
%7B%0A%09%09ret
|
0dfdf520edef6606f2aa64fa7edac5748d311270
|
remove uneeded dependency
|
server/routes/admin.js
|
server/routes/admin.js
|
var express = require('express');
var bodyParser = require('body-parser');
var router = express.Router();
var bcrypt = require('bcryptjs');
var fs = require('fs');
var logger = require('../log');
var path = require('path');
var util = require('util');
var passport = require('passport');
require('../config/passport')(passport); // pass passport for configuration
router.use(function (req, res, next) {
res.locals.login = req.isAuthenticated();
next();
});
var nconf = require('nconf');
var conf_file = './config/config.json';
var conf_backup = './config/backup.json';
nconf.file({file: conf_file});
nconf.load();
router.use(bodyParser.json()); // to support JSON-encoded bodies
router.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
router.route('/login')
.get(function(req, res, next) {
res.render('login', {
title: 'PagerMon - Login',
message: req.flash('loginMessage'),
user: req.user
});
})
// process the login form
.post(passport.authenticate('local-login', {
successRedirect : '/admin', // redirect to the secure profile section
failureRedirect : '/login', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
router.post('/resetPass', isLoggedIn, function(req, res, next) {
nconf.load();
// find a user via passport
var password = req.body.password;
// bcrypt function
if (password) {
bcrypt.hash(password, 8, function(err, hash) {
if (err) {
res.status(500);
res.json({'error': err});
} else {
nconf.set('auth:encPass', hash);
nconf.save();
res.status(200).send({'status': 'ok'});
}
});
} else {
res.status(500);
res.json({'error': 'Password empty'});
}
// save the password to config
});
router.route('/settingsData')
.get(isLoggedIn, function(req, res, next) {
nconf.load();
let settings = nconf.get();
// logger.main.debug(util.format('Config:\n\n%o',settings));
let plugins = [];
fs.readdirSync('./plugins').forEach(file => {
if (file.endsWith('.json')) {
let pConf = require(`../plugins/${file}`);
if (!pConf.disable)
plugins.push(pConf);
}
});
let themes = [];
fs.readdirSync('./themes').forEach(file => {
themes.push(file)
});
// logger.main.debug(util.format('Plugin Config:\n\n%o',plugins));
let data = {"settings": settings, "plugins": plugins, "themes": themes}
res.json(data);
})
.post(isLoggedIn, function(req, res, next) {
nconf.load();
if (req.body) {
//console.log(req.body);
var currentConfig = nconf.get();
fs.writeFileSync( conf_backup, JSON.stringify(currentConfig,null, 2) );
fs.writeFileSync( conf_file, JSON.stringify(req.body,null, 2) );
nconf.load();
res.status(200).send({'status': 'ok'});
} else {
res.status(500).send({error: 'request body empty'});
}
});
router.get('*', isLoggedIn, function(req, res, next) {
res.render('admin', { title: 'PagerMon - Admin' });
});
module.exports = router;
// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/login');
}
|
JavaScript
| 0.000003 |
@@ -193,36 +193,8 @@
');%0A
-var path = require('path');%0A
var
|
58fc9cb05e30ca4e0798000e1149592f1fd38e2b
|
enforce curley brace if statements with eslint
|
.eslintrc.js
|
.eslintrc.js
|
module.exports = {
"env": {
"browser": true,
"es2021": true,
"node": true,
"amd": true,
},
globals: {
'luxon': 'readonly',
'XLSX': 'readonly',
'jspdf': 'readonly'
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {
"semi": "error",
"indent": ["error", "tab", {VariableDeclarator:0, "SwitchCase": 1}],
"no-unused-vars": ["warn", { "vars": "all", "args": "none", "ignoreRestSiblings": false }],
"no-fallthrough": "off",
"no-inner-declarations": "off",
"no-prototype-builtins": "off",
"no-empty": ["error", { "allowEmptyCatch": true }],
}
}
|
JavaScript
| 0 |
@@ -633,13 +633,33 @@
rue %7D%5D,%0A
+%09%09%22curly%22: %22error%22,%0A
%09%7D%0A%7D%0A
|
2fc510911f9a5a70ad4e07f28ef04c3f32acd962
|
Fix isBN not always returning a boolean
|
lib/is-bn.js
|
lib/is-bn.js
|
'use strict'
var BN = require('bn.js')
module.exports = isBN
//Test if x is a bignumber
//FIXME: obviously this is the wrong way to do it
function isBN(x) {
return x && typeof x === 'object' && x.words
}
|
JavaScript
| 0.000269 |
@@ -196,14 +196,23 @@
&&
+Boolean(
x.words
+)
%0A%7D%0A
|
2f390ceb5df7ed733e873686ba2d4faba70cac1f
|
add missing JS file
|
build/lib/swc/index.js
|
build/lib/swc/index.js
|
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSwcClientStream = void 0;
const child_process_1 = require("child_process");
const stream_1 = require("stream");
const path_1 = require("path");
const util = require("util");
const gulp = require("gulp");
function createSwcClientStream() {
const execAsync = util.promisify(child_process_1.exec);
const cwd = (0, path_1.join)(__dirname, '../../../');
const srcDir = (0, path_1.join)(__dirname, '../../../src');
const outDir = (0, path_1.join)(__dirname, '../../../out');
const pathConfigAmd = (0, path_1.join)(__dirname, '.swcrc-amd');
const pathConfigNoModule = (0, path_1.join)(__dirname, '.swcrc-no-mod');
return new class extends stream_1.Readable {
constructor() {
super({ objectMode: true, highWaterMark: Number.MAX_SAFE_INTEGER });
this._isStarted = false;
}
async exec(print) {
const t1 = Date.now();
const errors = [];
try {
const data1 = await execAsync(`npx swc --config-file ${pathConfigAmd} ${srcDir}/ --out-dir ${outDir}`, { encoding: 'utf-8', cwd });
errors.push(data1.stderr);
const data2 = await execAsync(`npx swc --config-file ${pathConfigNoModule} ${srcDir}/vs/base/worker/workerMain.ts --out-dir ${outDir}`, { encoding: 'utf-8', cwd });
errors.push(data2.stderr);
return true;
}
catch (error) {
console.error(errors);
console.error(error);
this.destroy(error);
return false;
}
finally {
if (print) {
console.log(`DONE with SWC after ${Date.now() - t1}ms`);
}
}
}
async _read(_size) {
if (this._isStarted) {
return;
}
this._isStarted = true;
if (!this.exec()) {
this.push(null);
return;
}
for await (const file of gulp.src(`${outDir}/**/*.js`, { base: outDir })) {
this.push(file);
}
this.push(null);
}
};
}
exports.createSwcClientStream = createSwcClientStream;
if (process.argv[1] === __filename) {
createSwcClientStream().exec(true);
}
|
JavaScript
| 0.000001 |
@@ -640,16 +640,412 @@
gulp%22);%0A
+/**%0A * SWC transpile stream. Can be used as stream but %60exec%60 is the prefered way because under the%0A * hood this simply shells out to swc-cli. There is room for improvement but this already works.%0A * Ideas%0A * * use API, not swc-cli%0A * * invoke binaries directly, don't go through swc-cli%0A * * understand how to configure both setups in one (https://github.com/swc-project/swc/issues/4989)%0A */%0A
function
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.