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
|
---|---|---|---|---|---|---|---|
513ced0becc9803e1ce3022fb3130b377421a4e3
|
refactor for new format
|
clusterwatcher.js
|
clusterwatcher.js
|
#!/usr/bin/env node
var os = require("os");
var fs = require("fs");
var path = require("path");
var network = require("network");
var promise = require("deferred");
var child_process = require('child_process');
var glob = require('glob');
var logger = require("./log.js");
var kvstore = require("./kvstore.js");
var ClusterWatcher = function (config) {
// load the config file
this.config = config;
logger.info("ClusterWatcher initialised with config", config);
// host cache
this.lasthosts = {};
// on change handlers
this.on_change = [this.runClusterHooks];
}
ClusterWatcher.prototype.onChange = function (f) {
this.on_change.push(f);
}
ClusterWatcher.prototype.writeHosts = function (hosts) {
var deferred = promise();
// write host file in /etc/hosts format
var hostpath = "/etc/hosts.vcc";
var file = fs.createWriteStream(hostpath);
// on error we should log it
file.on('error', function(err) {
logger.error(err);
});
// once open we should write file
file.once('open', function(fd) {
for (var host in hosts) {
file.write(hosts[host]+" "+host+"\n");
}
file.end();
});
// on close we should resolve the promise
file.on('close', function() {
deferred.resolve()
})
return deferred.promise();
}
ClusterWatcher.prototype.runClusterHooks = function (hosts) {
var hook_dir = "/etc/vcc/cluster-hooks.d/*.sh";
glob(hook_dir, function (err, files) {
if (err) {
logger.error("could not enumerate cluster hooks", err);
}
for (var i = files.length - 1; i >= 0; i--) {
var script = files[i];
logger.debug("running hook", script);
var proc = child_process.spawn("/bin/sh", [script]);
proc.on('exit', function (code, signal) {
if (code > 0) {
logger.warn("hook", script, "exited with code", code);
} else {
logger.debug("hook", script, "exited with code", code);
}
});
};
})
}
ClusterWatcher.prototype.watchCluster = function () {
var me = this;
var poll_ms = 5000;
// define a function that reformats the list response to pairs
var format_list = function (list) {
var newlist = {};
for (var i = list.length - 1; i >= 0; i--) {
newlist[path.basename(list[i].key)] = list[i].value;
};
return Object.keys(newlist).sort().reduce(function (result, key) {
result[key] = newlist[key];
return result;
}, {});
}
// define a function to compare the lists
var compare_list = function (lista, listb) {
return JSON.stringify(lista) === JSON.stringify(listb);
}
// define a function that is called on the poll interval
// use the polling strategy instead of watching because it's more stable
var poll_hosts = function () {
var hosts = kvstore.list("/cluster/"+me.config.cluster+"/hosts");
if (hosts) {
var currenthosts = format_list(hosts);
logger.debug(hosts.length, "hosts in cluster");
// see if new host list matches our last cached one
if (compare_list(currenthosts, me.lasthosts)) {
logger.debug("cluster has not changed");
} else {
logger.debug("cluster has changed, writing hosts");
me.writeHosts(currenthosts).then(function () {
logger.debug("calling cluster change handlers now");
for (var i = me.on_change.length - 1; i >= 0; i--) {
me.on_change[i](currenthosts);
};
});
}
// update host cache
me.lasthosts = currenthosts;
// schedule the next poll
setTimeout(poll_hosts, poll_ms);
} else {
logger.error("No hosts in cluster? Stop polling.");
}
}
setTimeout(poll_hosts, poll_ms);
}
module.exports = {
ClusterWatcher: function (service, config, targets) {
var deferred = promise();
var clusterwatcher = new ClusterWatcher(config.cluster);
clusterwatcher.watchCluster();
deferred.resolve();
return deferred.promise();
}
};
|
JavaScript
| 0.00114 |
@@ -234,16 +234,55 @@
lob');%0A%0A
+var vccutil = require(%22./vccutil.js%22);%0A
var logg
@@ -510,16 +510,141 @@
onfig);%0A
+ // connect kvstore%0A this.kvstore = new kvstore();%0A this.kvstore.connect(config.kvstore.host, config.kvstore.port);%0A
// h
@@ -3156,16 +3156,21 @@
hosts =
+this.
kvstore.
@@ -4236,127 +4236,9 @@
%0A%7D%0A%0A
-module.exports = %7B%0A ClusterWatcher: function (service, config, targets) %7B%0A var deferred = promise();%0A
+%0A
var
@@ -4277,33 +4277,30 @@
her(
-config.cluster);%0A
+vccutil.getConfig());%0A
clus
@@ -4329,76 +4329,4 @@
r();
-%0A deferred.resolve();%0A return deferred.promise();%0A %7D%0A%7D;
|
84328e62b1968bfaebe28f918ea48e1a165d348c
|
Change CJS definition to require vex.js with relative path
|
js/vex.dialog.js
|
js/vex.dialog.js
|
(function() {
var vexDialogFactory;
vexDialogFactory = function($, vex) {
var $formToObject, dialog;
if (vex == null) {
return $.error('Vex is required to use vex.dialog');
}
$formToObject = function($form) {
var object;
object = {};
$.each($form.serializeArray(), function() {
if (object[this.name]) {
if (!object[this.name].push) {
object[this.name] = [object[this.name]];
}
return object[this.name].push(this.value || '');
} else {
return object[this.name] = this.value || '';
}
});
return object;
};
dialog = {};
dialog.buttons = {
YES: {
text: 'OK',
type: 'submit',
className: 'vex-dialog-button-primary'
},
NO: {
text: 'Cancel',
type: 'button',
className: 'vex-dialog-button-secondary',
click: function($vexContent, event) {
$vexContent.data().vex.value = false;
return vex.close($vexContent.data().vex.id);
}
}
};
dialog.defaultOptions = {
callback: function(value) {},
afterOpen: function() {},
message: 'Message',
input: "<input name=\"vex\" type=\"hidden\" value=\"_vex-empty-value\" />",
value: false,
buttons: [dialog.buttons.YES, dialog.buttons.NO],
showCloseButton: false,
onSubmit: function(event) {
var $form, $vexContent;
$form = $(this);
$vexContent = $form.parent();
event.preventDefault();
event.stopPropagation();
$vexContent.data().vex.value = dialog.getFormValueOnSubmit($formToObject($form));
return vex.close($vexContent.data().vex.id);
},
focusFirstInput: true
};
dialog.defaultAlertOptions = {
message: 'Alert',
buttons: [dialog.buttons.YES]
};
dialog.defaultConfirmOptions = {
message: 'Confirm'
};
dialog.open = function(options) {
var $vexContent;
options = $.extend({}, vex.defaultOptions, dialog.defaultOptions, options);
options.content = dialog.buildDialogForm(options);
options.beforeClose = function($vexContent) {
return options.callback($vexContent.data().vex.value);
};
$vexContent = vex.open(options);
if (options.focusFirstInput) {
$vexContent.find('input[type="submit"], textarea, input[type="date"], input[type="datetime"], input[type="datetime-local"], input[type="email"], input[type="month"], input[type="number"], input[type="password"], input[type="search"], input[type="tel"], input[type="text"], input[type="time"], input[type="url"], input[type="week"]').first().focus();
}
return $vexContent;
};
dialog.alert = function(options) {
if (typeof options === 'string') {
options = {
message: options
};
}
options = $.extend({}, dialog.defaultAlertOptions, options);
return dialog.open(options);
};
dialog.confirm = function(options) {
if (typeof options === 'string') {
return $.error('dialog.confirm(options) requires options.callback.');
}
options = $.extend({}, dialog.defaultConfirmOptions, options);
return dialog.open(options);
};
dialog.prompt = function(options) {
var defaultPromptOptions;
if (typeof options === 'string') {
return $.error('dialog.prompt(options) requires options.callback.');
}
defaultPromptOptions = {
message: "<label for=\"vex\">" + (options.label || 'Prompt:') + "</label>",
input: "<input name=\"vex\" type=\"text\" class=\"vex-dialog-prompt-input\" placeholder=\"" + (options.placeholder || '') + "\" value=\"" + (options.value || '') + "\" />"
};
options = $.extend({}, defaultPromptOptions, options);
return dialog.open(options);
};
dialog.buildDialogForm = function(options) {
var $form, $input, $message;
$form = $('<form class="vex-dialog-form" />');
$message = $('<div class="vex-dialog-message" />');
$input = $('<div class="vex-dialog-input" />');
$form.append($message.append(options.message)).append($input.append(options.input)).append(dialog.buttonsToDOM(options.buttons)).bind('submit.vex', options.onSubmit);
return $form;
};
dialog.getFormValueOnSubmit = function(formData) {
if (formData.vex || formData.vex === '') {
if (formData.vex === '_vex-empty-value') {
return true;
}
return formData.vex;
} else {
return formData;
}
};
dialog.buttonsToDOM = function(buttons) {
var $buttons;
$buttons = $('<div class="vex-dialog-buttons" />');
$.each(buttons, function(index, button) {
var $button;
$button = $("<input type=\"" + button.type + "\" />").val(button.text).addClass(button.className + ' vex-dialog-button ' + (index === 0 ? 'vex-first ' : '') + (index === buttons.length - 1 ? 'vex-last ' : '')).bind('click.vex', function(e) {
if (button.click) {
return button.click($(this).parents("." + vex.baseClassNames.content), e);
}
});
return $button.appendTo($buttons);
});
return $buttons;
};
return dialog;
};
if (typeof define === 'function' && define.amd) {
define(['jquery', 'vex'], vexDialogFactory);
} else if (typeof exports === 'object') {
module.exports = vexDialogFactory(require('jquery'), require('vex'));
} else {
window.vex.dialog = vexDialogFactory(window.jQuery, window.vex);
}
}).call(this);
|
JavaScript
| 0.000024 |
@@ -5498,19 +5498,24 @@
equire('
+./
vex
+.js
'));%0A %7D
|
9c0ae49c00f41dbd5c6e3a71d457d5072001a7c7
|
update link to GraphQL spec
|
packages/relay-runtime/network/RelayNetworkTypes.js
|
packages/relay-runtime/network/RelayNetworkTypes.js
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
import type {RequestParameters} from '../util/RelayConcreteNode';
import type {
CacheConfig,
Disposable,
Variables,
} from '../util/RelayRuntimeTypes';
import type RelayObservable, {ObservableFromValue} from './RelayObservable';
/**
* An interface for fetching the data for one or more (possibly interdependent)
* queries.
*/
export type Network = {|
execute: ExecuteFunction,
|};
export type PayloadData = {[key: string]: mixed};
export type PayloadError = {
message: string,
locations?: Array<{
line: number,
column: number,
}>,
severity?: 'CRITICAL' | 'ERROR' | 'WARNING', // Not officially part of the spec, but used at Facebook
};
export type PayloadExtensions = {[key: string]: mixed};
/**
* The shape of a GraphQL response as dictated by the
* [spec](http://facebook.github.io/graphql/#sec-Response)
*/
export type GraphQLResponseWithData = {
+data: PayloadData,
+errors?: Array<PayloadError>,
+extensions?: PayloadExtensions,
+label?: string,
+path?: Array<string | number>,
};
export type GraphQLResponseWithoutData = {
+data?: ?PayloadData,
+errors: Array<PayloadError>,
+extensions?: PayloadExtensions,
+label?: string,
+path?: Array<string | number>,
};
export type GraphQLResponse =
| GraphQLResponseWithData
| GraphQLResponseWithoutData;
/**
* A function that returns an Observable representing the response of executing
* a GraphQL operation.
*/
export type ExecuteFunction = (
request: RequestParameters,
variables: Variables,
cacheConfig: CacheConfig,
uploadables?: ?UploadableMap,
) => RelayObservable<GraphQLResponse>;
/**
* A function that executes a GraphQL operation with request/response semantics.
*
* May return an Observable or Promise of a plain GraphQL server response, or
* a composed ExecutePayload object supporting additional metadata.
*/
export type FetchFunction = (
request: RequestParameters,
variables: Variables,
cacheConfig: CacheConfig,
uploadables: ?UploadableMap,
) => ObservableFromValue<GraphQLResponse>;
/**
* A function that executes a GraphQL subscription operation, returning one or
* more raw server responses over time.
*
* May return an Observable, otherwise must call the callbacks found in the
* fourth parameter.
*/
export type SubscribeFunction = (
request: RequestParameters,
variables: Variables,
cacheConfig: CacheConfig,
observer?: LegacyObserver<GraphQLResponse>,
) => RelayObservable<GraphQLResponse> | Disposable;
// $FlowFixMe(site=react_native_fb) this is compatible with classic api see D4658012
export type Uploadable = File | Blob;
// $FlowFixMe(site=mobile,www)
export type UploadableMap = {[key: string]: Uploadable};
// Supports legacy SubscribeFunction definitions. Do not use in new code.
export type LegacyObserver<-T> = {|
+onCompleted?: ?() => void,
+onError?: ?(error: Error) => void,
+onNext?: ?(data: T) => void,
|};
|
JavaScript
| 0 |
@@ -1034,19 +1034,19 @@
http
+s
://
-facebook
+graphql
.git
@@ -1059,16 +1059,30 @@
/graphql
+-spec/June2018
/#sec-Re
@@ -1087,16 +1087,23 @@
Response
+-Format
)%0A */%0Aex
|
9cc54925a5e6ef11874d436ec00359df521d35bf
|
Refactor mobile-menu.js
|
app/src/home/mobile-menu.js
|
app/src/home/mobile-menu.js
|
require('./mobile-menu.sass');
document.addEventListener('DOMContentLoaded', () => {
const menuButton = document.querySelector('.top-bar button.ion-md-menu');
const menu = document.getElementById('mobile-menu');
menuButton.addEventListener('click', () => {
menuButton.classList.toggle('open');
menu.classList.toggle('open');
document.getElementsByClassName('top-bar')[0].classList.toggle('mobile-menu-open');
if (menu.classList.contains('open')) {
menu.style.display = 'block';
} else {
setTimeout(() => { menu.style.display = 'none'; }, 500);
}
const menuLinks = menu.getElementsByTagName('a');
for (let i = 0; i < menuLinks.length; i += 1) {
setTimeout(
() => { menuLinks[i].classList.toggle('visible'); },
// Use staggered delay when opening, 0 delay when closing
menu.classList.contains('open') ? 250 * i : 0,
);
}
});
});
|
JavaScript
| 0.000003 |
@@ -214,55 +214,182 @@
');%0A
-%0A
-menuButton.addEventListener('click', () =%3E %7B
+const topBar = document.getElementsByClassName('top-bar')%5B0%5D;%0A const menuLinks = menu.getElementsByTagName('a');%0A%0A function openMenu() %7B%0A menu.style.display = 'block';
%0A
@@ -402,38 +402,35 @@
utton.classList.
-toggle
+add
('open');%0A me
@@ -442,22 +442,19 @@
assList.
-toggle
+add
('open')
@@ -463,53 +463,14 @@
-document.getElementsByClassName('top-bar')%5B0%5D
+topBar
.cla
@@ -476,22 +476,19 @@
assList.
-toggle
+add
('mobile
@@ -510,156 +510,198 @@
-if (menu.classList.contains('open')) %7B%0A menu.style.display = 'block';%0A %7D else %7B%0A setTimeout(() =%3E %7B menu.style.display = 'non
+for (let i = 0; i %3C menuLinks.length; i += 1) %7B%0A // Use staggered delay for fading in menu links while opening%0A setTimeout(() =%3E %7B menuLinks%5Bi%5D.classList.add('visibl
e'
+)
; %7D,
+2
50
-0
+ * i
);%0A
@@ -709,63 +709,225 @@
%7D%0A
-%0A
- const menuLinks = menu.getElementsByTagName('a'
+%7D%0A%0A function closeMenu() %7B%0A menuButton.classList.remove('open');%0A menu.classList.remove('open');%0A topBar.classList.remove('mobile-menu-open');%0A setTimeout(() =%3E %7B menu.style.display = 'none'; %7D, 500
);%0A
+%0A
@@ -983,36 +983,8 @@
- setTimeout(%0A () =%3E %7B
men
@@ -1007,13 +1007,13 @@
ist.
-toggl
+remov
e('v
@@ -1025,86 +1025,54 @@
e');
- %7D,
%0A
- // Use staggered delay when opening, 0 delay when closing
+%7D%0A %7D%0A%0A function toggleMenu() %7B
%0A
-
+if (
menu
@@ -1102,42 +1102,98 @@
en')
- ? 250 * i : 0,%0A
+) closeMenu();%0A else openMenu(
);%0A
-
%7D%0A
+%0A
-%7D
+menuButton.addEventListener('click', toggleMenu
);%0A%7D
|
e70fbd2013b90af6184c869e5e82142a80c34b8f
|
Fix another lint error
|
src/conversion/view-v1-to-v2.js
|
src/conversion/view-v1-to-v2.js
|
import _ from 'lodash'
const CARRY_OVER_PROPERTIES = ['label', 'dependsOn', 'description', 'disabled', 'model', 'placeholder']
const ARRAY_CELL_PROPERTIES = ['autoAdd', 'compact', 'showLabel', 'sortable']
/**
* Turns rootContainers from V1 view into cells in v2 view
*
* @export
* @param {Object[]} rootContainers Containers to convert
* @returns {object[]} Array of cells converted from rootContainers
*/
export function generateCells (rootContainers) {
return _.chain(rootContainers).flattenDeep().map(convertCell).filter().value()
}
/**
* Converts an complex container cell for an object into a v2 cell
*
* @param {object} cell Cell that should display an object
* @returns {object} Cell converted to v2
*/
function convertObjectCell (cell) {
return _.chain(cell.rows)
.map(rowsToCells)
.assign(_.pick(cell, CARRY_OVER_PROPERTIES))
.value()
}
/**
* Converts a container cell that displays an array into a v2 cell
*
* @param {object} cell Cell that should display an array
* @returns {object} Cell converted to v2
*/
function convertArrayCell (cell) {
const {item} = cell
const arrayOptions = _.chain(item)
.pick(ARRAY_CELL_PROPERTIES)
.assign({
itemCell: convertCell(item)
})
.value()
return {
arrayOptions,
model: cell.model
}
}
/**
* Creates custom renderer information for a cell
*
* @param {string} renderer Name of the desired renderer
* @param {object} properties Info for to the custom renderer
* @returns {object} Custom renderer block
*/
function customRenderer (renderer, properties) {
return _.assign({
name: renderer
}, properties)
}
/**
* Converts v1 renderer information to v2 for a cell
*
* @param {object} cell Cell with a custom renderer
* @returns {object} Custom renderer block for the given cell
*/
function convertRenderer (cell) {
const {renderer} = cell
if (renderer === undefined) {
return
}
const basicRenderers = [
'boolean',
'string',
'number'
]
if (basicRenderers.indexOf(renderer) >= 0) {
return {name: renderer}
}
return customRenderer(renderer, cell.properties)
}
/**
* Creates class name block for v2 cell
*
* @param {object} cell Cell to get class names from
* @returns {object} Class name block for the cell
*/
function grabClassNames (cell) {
const classNames = _.pickBy({
cell: cell.className,
value: cell.inputClassName,
label: cell.labelClassName
})
if (_.size(classNames) > 0) {
return classNames
}
}
/**
* Converts a cell for simple data type (e.g. string, or number)
*
* @param {object} cell Cell in v1 to convert to v2
* @returns {object} Cell converted to v2
*/
function convertBasicCell (cell) {
return _.pickBy(_.assign({
renderer: convertRenderer(cell)
}, _.pick(cell, CARRY_OVER_PROPERTIES)))
}
/**
* Determines which cell conversion function to use to convert v1 cell to v2 and converts it
*
* @export
* @param {object} cell A v1 cell to convert to v2
* @returns {object} The cell converted to v2
*/
export function convertCell (cell) {
let cellConverter
if (cell.item) {
cellConverter = convertArrayCell
} else if (cell.rows) {
cellConverter = convertObjectCell
} else {
cellConverter = convertBasicCell
}
return _.pickBy(_.assign({
extends: cell.container,
classNames: grabClassNames(cell)
}, cellConverter(cell)))
}
/**
* Converts rows of v1 cells to v2 cells. Simplifies the row structure when possible.
*
* @param {Array<object>[]} rows A set of rows to convert
* @returns {object} A v2 cell
*/
function rowsToCells (rows) {
if (!rows) {
return {}
}
const children = rows
.map((row) => {
return {
children: _.map(row, convertCell)
}
})
return {
children
}
}
/**
* Converts the container declarations in a v1 view to cell definitions in a v2 view
*
* @export
* @param {object[]} containers Set of containers to convert
* @returns {object} cell definitions for the v2 view.
*/
export function generateCellDefinitions (containers) {
return _.chain(containers)
.map(function (container) {
const {collapsible, rows, id, className, label} = container
const cell = rowsToCells(rows)
if (className !== undefined) {
cell.classNames = {
cell: className
}
}
if (collapsible !== undefined) {
cell.collapsible = collapsible
}
if (label !== undefined) {
cell.label = label
}
return [id, cell]
})
.fromPairs()
.value()
}
/**
* Converts a bunsen version 1 view into a bunsen/ui schema version 2 view
*
* @export
* @param {any} v1View A v1 view to convert to v2
* @returns {object} The v2 view generated from the given v1 view
*/
export default function viewV1ToV2 (v1View) {
const {type} = v1View
const cells = generateCells(v1View.rootContainers)
const cellDefinitions = generateCellDefinitions(v1View.containers)
return {
version: '2.0',
type,
cells,
cellDefinitions
}
}
|
JavaScript
| 0.000036 |
@@ -4111,16 +4111,27 @@
const %7B
+className,
collapsi
@@ -4138,35 +4138,24 @@
ble,
- rows,
id,
-c
la
-ssName, label
+bel, rows
%7D =
|
46075e4dc692791877297eaac7a6bcab45292a30
|
fix FixedImage tracks broken by memory leak fixes
|
src/JBrowse/View/Track/FixedImage.js
|
src/JBrowse/View/Track/FixedImage.js
|
define(
[
'dojo/_base/declare',
'JBrowse/View/Track/BlockBased'
],
function( declare, BlockBased ) {
return declare( BlockBased,
/**
* @lends JBrowse.View.Track.FixedImage.prototype
*/
{
/**
* A track that displays tiled images (PNGs, or other images) at fixed
* intervals along the reference sequence.
* @constructs
* @extends JBrowse.View.Track.BlockBased
*/
constructor: function( args ) {
this.trackPadding = args.trackPadding || 0;
},
handleImageError: function(ev) {
var img = ev.currentTarget || ev.srcElement;
img.style.display = "none";
dojo.stopEvent(ev);
},
/**
* @private
*/
makeImageLoadHandler: function( img, blockIndex, blockWidth, composeCallback ) {
var handler = dojo.hitch( this, function() {
this.imageHeight = img.height;
img.style.height = img.height + "px";
img.style.width = (100 * (img.baseWidth / blockWidth)) + "%";
this.heightUpdate( img.height, blockIndex );
if( composeCallback )
composeCallback();
return true;
});
if( ! dojo.isIE )
return handler;
else
// in IE, have to delay calling it for a (arbitrary) 1/4
// second because the image's height is not always
// available when the onload event fires. >:-{
return function() {
window.setTimeout(handler,250);
};
},
fillBlock: function( args ) {
var blockIndex = args.blockIndex;
var block = args.block;
var leftBase = args.leftBase;
var rightBase = args.rightBase;
var scale = args.scale;
var finishCallback = args.finishCallback || function() {};
var blockWidth = rightBase - leftBase;
this.store.getImages(
{ scale: scale, start: leftBase, end: rightBase },
dojo.hitch(this, function(images) {
dojo.forEach( images, function(im) {
im.className = 'image-track';
if (!(im.parentNode && im.parentNode.parentNode)) {
im.style.position = "absolute";
im.style.left = (100 * ((im.startBase - leftBase) / blockWidth)) + "%";
switch (this.config.align) {
case "top":
im.style.top = "0px";
break;
case "bottom":
default:
im.style.bottom = this.trackPadding + "px";
break;
}
block.appendChild(im);
}
// make an onload handler for when the image is fetched that
// will update the height and width of the track
var loadhandler = this.makeImageLoadHandler( im, blockIndex, blockWidth );
if( im.complete )
// just call the handler ourselves if the image is already loaded
loadhandler();
else
// otherwise schedule it
im.onload = loadhandler;
}, this);
finishCallback();
}),
dojo.hitch( this, function( error ) {
if( error.status == 404 ) {
// do nothing
} else {
this.fillBlockError( blockIndex, block, error );
}
finishCallback();
})
);
},
startZoom: function(destScale, destStart, destEnd) {
if (this.empty) return;
},
endZoom: function(destScale, destBlockBases) {
this.clear();
},
clear: function() {
this.inherited( arguments );
},
transfer: function(sourceBlock, destBlock, scale,
containerStart, containerEnd) {
if (!(sourceBlock && destBlock)) return;
var children = sourceBlock.childNodes;
var destLeft = destBlock.startBase;
var destRight = destBlock.endBase;
var im;
for (var i = 0; i < children.length; i++) {
im = children[i];
if ("startBase" in im) {
//if sourceBlock contains an image that overlaps destBlock,
if ((im.startBase < destRight)
&& ((im.startBase + im.baseWidth) > destLeft)) {
//move image from sourceBlock to destBlock
im.style.left = (100 * ((im.startBase - destLeft) / (destRight - destLeft))) + "%";
destBlock.appendChild(im);
}
}
}
}
});
});
|
JavaScript
| 0 |
@@ -3152,24 +3152,32 @@
block.
+domNode.
appendChild(
@@ -4683,16 +4683,24 @@
ceBlock.
+domNode.
childNod
@@ -5314,16 +5314,24 @@
stBlock.
+domNode.
appendCh
|
10c4b660bf60a1fefd5c75a6eb44df6aaa740956
|
Add hello ws message
|
lib/interfaces/ws.js
|
lib/interfaces/ws.js
|
/*
* Copyright 2014-2015 Fabian Tollenaar <[email protected]>
*
* 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 flatMap = require('flatmap');
module.exports = function(app) {
'use strict';
var _ = require('lodash'),
debug = require('debug')('signalk-server:interfaces:ws'),
Primus = require('primus'),
api = {},
started = false,
primus;
api.mdns = {
name: "_signalk-ws",
type: "tcp",
port: app.config.port
};
api.start = function() {
debug('Starting Primus/WS interface');
started = true;
primus = new Primus(app.server, {
transformer: 'websockets',
pathname: '/signalk/stream/v1',
timeout: false
});
primus.on('connection', function(spark) {
debug(spark.id + " connected with params " + JSON.stringify(spark.query));
var onChange, event;
if (spark.query.stream === 'delta') {
event = 'change:delta';
onChange = function(data) {
spark.write(data);
};
} else if (spark.query.stream === 'subscribe') {
debug('stream:subscribe');
//inefficient for many sparks, should instead keep track of which sparks subscribe to which paths
spark.paths = {};
event = 'change:delta';
onChange = function(delta) {
normalizeDelta(delta).forEach(function(oneValueDelta) {
var doSend = oneValueDelta.updates.some(function(update) {
return update.values.some(function(value) {
return spark.paths[value.path];
});
});
if (doSend) {
spark.write(oneValueDelta);
}
});
};
spark.on('data', function(msg) {
debug("<" + JSON.stringify(msg));
if (msg.command === 'subscribe') {
msg.paths.forEach(function(path) {
spark.paths[path] = true;
});
}
debug(spark.paths);
});
} else {
event = 'change';
onChange = function(data) {
spark.write(app.signalk.retrieve());
};
spark.write(app.signalk.retrieve()); //output tree after connect
}
app.signalk.on(event, onChange);
spark.onDisconnect = function() {
app.signalk.removeListener(event, onChange);
}
});
primus.on('disconnection', function(spark) {
spark.onDisconnect();
debug(spark.id + " disconnected");
});
};
api.stop = function() {
if (primus.destroy && started) {
debug("Destroying primus...");
primus.destroy({
close: false,
timeout: 500
});
}
};
return api;
};
function normalizeDelta(delta) {
return flatMap(delta.updates, normalizeUpdate).map(function(update) {
return {
context: delta.context,
updates: [update]
}
})
};
function normalizeUpdate(update) {
return update.values.map(function(value) {
return {
source: update.source,
values: [value]
}
})
}
|
JavaScript
| 0.999983 |
@@ -2825,24 +2825,238 @@
);%0A %7D%0A%0A
+ spark.write(%7B%0A name: app.config.name,%0A version: app.config.version,%0A timestamp: new Date(),%0A self: app.selfId,%0A roles: %5B%22master%22, %22main%22%5D%0A %7D)%0A console.log('hep')%0A%0A
%7D);%0A%0A
|
d70220182c4e5ec2835f19eebf25aff0330345e2
|
Implement ShoppingListAddController
|
SPAWithAngularJS/module2/customServices/js/app.shoppingListAddController.js
|
SPAWithAngularJS/module2/customServices/js/app.shoppingListAddController.js
|
// app.shoppingListAddController.js
(function() {
"use strict";
angular.module("MyApp")
.controller("ShoppingListAddController", ShoppingListAddController);
function ShoppingListAddController() {
let vm = this;
}
})();
|
JavaScript
| 0.001632 |
@@ -167,65 +167,352 @@
%0A%0A
-function ShoppingListAddController() %7B%0A let vm = this;
+ShoppingListAddController.$inject = %5B%22ShoppingListService%22%5D;%0A%0A function ShoppingListAddController(ShoppingListService) %7B%0A let AddCtrl = this;%0A%0A AddCtrl.itemName = %22%22;%0A AddCtrl.itemQuantity = 0;%0A%0A AddCtrl.addItem = addItem();%0A%0A function addItem() %7B%0A ShoppingListService.addItem(AddCtrl.itemName, AddCtrl.itemQuantity);%0A %7D
%0A %7D
|
928b663d3202426ec1cea778e71b3d519dc9327d
|
add standard blocks
|
module_testing/test-p5/task.js
|
module_testing/test-p5/task.js
|
function initTask(subTask) {
subTask.gridInfos = {
hideSaveOrLoad: false,
actionDelay: 200,
buttonScaleDrawing: false,
includeBlocks: {
groupByCategory: false,
generatedBlocks: {
p5: [
'playSignal',
'playRecord',
'playStop',
'sleep'
]
},
standardBlocks: {
includeAll: false
}
},
maxInstructions: 100,
checkEndEveryTurn: false,
checkEndCondition: function(context, lastTurn) {
context.success = true;
throw(strings.complete);
}
}
subTask.data = {
easy: [{}]
}
initBlocklySubTask(subTask)
}
initWrapper(initTask, null, null)
|
JavaScript
| 0.000008 |
@@ -196,20 +196,19 @@
tegory:
-fals
+tru
e,%0A
@@ -474,20 +474,19 @@
udeAll:
-fals
+tru
e%0A
|
ec063ae8b1b5f18623144ed3ee8a3a52c7651f80
|
Update wifiInfo.js
|
www/wifiInfo.js
|
www/wifiInfo.js
|
function wifiInfo() { };
/* wifiInfo*/
wifiInfo.prototype.getConnectionInfo = function ()
{ //console.log('wifiInfo aufgerufen');
cordova.exec(null, null, 'wifiInfo', 'getConnectionInfo', []);
};
module.exports = new wifiInfo();
|
JavaScript
| 0.000001 |
@@ -83,16 +83,26 @@
nction (
+p_callback
) %0A%7B //c
@@ -151,20 +151,26 @@
va.exec(
-null
+p_callback
, null,
|
736cb0e5ee7625d705ee8d0ff94f2b0faad1a84e
|
update TransferList
|
src/_TransferList/TransferList.js
|
src/_TransferList/TransferList.js
|
/**
* @file TransferList component
* @author sunday([email protected])
*/
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import TextField from '../TextField';
import Checkbox from '../Checkbox';
export default class TransferList extends Component {
constructor(props, ...restArgs) {
super(props, ...restArgs);
this.state = {
filter: ''
};
this.select = ::this.select;
this.selectAllHandle = ::this.selectAllHandle;
this.filterChangeHandle = ::this.filterChangeHandle;
this.getItemValue = ::this.getItemValue;
}
select(item) {
if (!item.disabled) {
let data = _.cloneDeep(this.props.value);
let selectAll = this.state.selectAll;
let flag = false;
for (let i = 0; i < data.length; i++) {
if (data[i].id === item.id) {
flag = true;
break;
}
}
if (flag) {
let index = data.findIndex(function (value, index, arr) {
return value.id == item.id;
});
data.splice(index, 1);
selectAll = false;
} else {
data.push(item);
if (data.length == this.props.data.length) {
selectAll = true;
}
}
this.setState({
selectAll
}, () => {
this.props.onChange && this.props.onChange(data);
});
}
}
selectAllHandle() {
const {selectAll, filter} = this.state;
const {data} = this.props;
const filterList = this.getFilterList(data, filter);
let newData = [];
for (let i = 0; i < filterList.length; i++) {
if (!filterList[i]['disabled']) {
newData.push(filterList[i]);
}
}
let value = selectAll ? [] : newData;
this.setState({
selectAll: !selectAll
}, () => {
this.props.onChange && this.props.onChange(value);
});
}
filterChangeHandle(value) {
this.setState({
filter: value,
selectAll: false
}, () => {
this.props.onChange && this.props.onChange([]);
});
}
getItemValue(id) {
let data = this.props.value;
let flag = false;
for (let i = 0; i < data.length; i++) {
if (data[i].id === id) {
flag = true;
break;
} else {
flag = false;
}
}
return flag;
}
getFilterList(list, filter) {
return list.filter((value) => {
if (typeof value == 'object') {
return value.text.toUpperCase().indexOf(filter.toUpperCase()) != -1;
} else {
return value.toUpperCase().indexOf(filter.toUpperCase()) != -1;
}
});
}
componentWillReceiveProps(nextProps) {
if (nextProps.data.length !== this.props.data.length) {
this.setState({
selectAll: false
});
}
}
render() {
const {className, listStyle, data, value} = this.props,
{filter, selectAll} = this.state,
{filterChangeHandle, getItemValue, getFilterList, select, selectAllHandle} = this;
this.filterList = getFilterList(data, filter);
return (
<div className={`transfer-list ${className ? className : ''}`}
style={listStyle}>
<div className="transfer-header">
<Checkbox
label={value && value.length > 0 ? value.length + '/' + this.filterList.length + ' items' : this.filterList.length + ' items'}
value={selectAll}
onChange={selectAllHandle}/>
</div>
<TextField className="search"
rightIconCls={'fa fa-search'}
onChange={filterChangeHandle}
placeholder={'Search here'}
value={filter}/>
<div ref="options"
className="options">
{
this.filterList.map((item, index) => {
let itemValue = getItemValue(item.id);
return (
<div key={item.text}
className={`option ${item.disabled ? 'disabled' : ''}`}>
<Checkbox label={item.text}
value={itemValue}
disabled={item.disabled ? item.disabled : false}
onChange={() => {
select(item);
}}/>
</div>
);
})
}
</div>
</div>
);
}
};
TransferList.propTypes = {
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* Override the styles of the root element.
*/
listStyle: PropTypes.object,
/**
*
*/
data: PropTypes.array,
/**
*
*/
value: PropTypes.array
};
TransferList.defaultProps = {
className: '',
style: null
};
|
JavaScript
| 0 |
@@ -3929,21 +3929,23 @@
-value
+checked
=%7Bselect
@@ -4810,21 +4810,23 @@
-value
+checked
=%7BitemVa
|
b10d2d10a8a916c35cf32bccf935f64e99612325
|
update the stories with onClick events
|
packages/side-nav/src/__stories__/ExampleSideNav.js
|
packages/side-nav/src/__stories__/ExampleSideNav.js
|
import React from "react";
import { action } from "@storybook/addon-actions";
import { boolean, text } from "@storybook/addon-knobs/react";
import { Insight24, ProductsAndServices24, Collaboration24 } from "@hig/icons";
import Typography from "@hig/typography";
import SideNav from "../index";
const ExampleSideNav = () => (
<SideNav
headerLabel={text("Header Label", "Storybook")}
headerLink={text("Header Link", "https://www.autodesk.com")}
onMinimize={action("onMinimize")}
showMinimizeButton={boolean("Show Minimize Button", false)}
superHeaderLabel={text("Superheader Label", "HIG")}
superHeaderLink={text("Superheader Link", "https://www.autodesk.com")}
groups={
<SideNav.Group>
<SideNav.Module title="Module 1" icon={<Insight24 />} activeChildren>
<SideNav.Submodule title="Submodule 1" />
<SideNav.Submodule title="Submodule 2" active />
</SideNav.Module>
<SideNav.Module
title="Module 2"
icon={<ProductsAndServices24 />}
minimized
>
<SideNav.Submodule
title="Submodule 1"
link="https://www.autodesk.com"
/>
<SideNav.Submodule
title="Submodule 2"
link="https://www.autodesk.com"
target="_blank"
/>
</SideNav.Module>
<SideNav.Module
title="Module 3"
icon={<Collaboration24 />}
link="https://www.autodesk.com"
target="_blank"
/>
</SideNav.Group>
}
links={[
<SideNav.Link
key="Autodesk Home"
title="Autodesk Home"
link="https://www.autodesk.com"
/>,
<SideNav.Link
key="Github"
title="Github"
link="https://www.github.com/Autodesk/hig"
target="_blank"
/>
]}
search={<SideNav.Search />}
copyright={<Typography>© 2018 Autodesk Inc.</Typography>}
/>
);
export default ExampleSideNav;
|
JavaScript
| 0 |
@@ -444,24 +444,62 @@
desk.com%22)%7D%0A
+ onClickHeader=%7Baction(%22onClick%22)%7D%0A
onMinimi
@@ -715,24 +715,67 @@
desk.com%22)%7D%0A
+ onClickSuperHeader=%7Baction(%22onClick%22)%7D%0A
groups=%7B
|
e1275063a762e4748aae86bfcf9a9e60deb40e70
|
Fix dependency loading order for checkbox
|
app/assets/javascripts/ember-bootstrap-rails/all.js
|
app/assets/javascripts/ember-bootstrap-rails/all.js
|
//= require ./core
//= require ./mixins
//= require ./forms
//= require_tree ./forms
//= require_tree ./views
|
JavaScript
| 0.000001 |
@@ -45,32 +45,58 @@
require ./forms%0A
+//= require ./forms/field%0A
//= require_tree
|
70459cb61f753ce11bc85a801442de85879f716e
|
Revert "Register query on create."
|
modules/chartDataController.js
|
modules/chartDataController.js
|
var express = require('express');
var DataStore = require('./regard-data-store.js');
var Chart = require('../schemas/chart.js');
var router = express.Router();
var dataStore = new DataStore('Adobe', 'Brackets');
router.get('/chartdata', function (req, res, next) {
var id = req.query.ids[0];
dataStore.runQuery(id).then(function (result) {
res.json({
chartdata: [{
_id: id,
values: JSON.parse(result).Results
}]
});
}, next);
});
router.post('/charts', function (req, res, next) {
if (!req.body.chart.queryDefinition) {
res.send(400, 'missing query definition');
}
var queryName = req.body.chart.id;
var queryDefinition = req.body.chart.queryDefinition;
dataStore.registerQuery(queryName, queryDefinition).done(function () {
next();
}, next);
});
module.exports = router;
|
JavaScript
| 0 |
@@ -336,26 +336,24 @@
(result) %7B%0A
-
res.json(%7B
@@ -449,30 +449,24 @@
%0A %7D);%0A %7D
-, next
);%0A%7D);%0A%0Arout
@@ -473,10 +473,9 @@
er.p
-os
+u
t('/
@@ -480,16 +480,20 @@
'/charts
+/:id
', funct
@@ -630,26 +630,22 @@
e = req.
-body.chart
+params
.id;%0A v
|
1dd108a5031993755c24d0079e4281656904987d
|
fix postinstall script
|
packages/vue-inbrowser-compiler-demi/postinstall.js
|
packages/vue-inbrowser-compiler-demi/postinstall.js
|
const pkg = require('vue/package.json')
const path = require('path')
const fs = require('fs')
function updateIndexForVue3() {
// commonjs
const indexPath = path.join(__dirname, './index.cjs.js')
const indexContent = `
const Vue = require('vue')
module.exports.h = Vue.h
module.exports.resolveComponent = Vue.resolveComponent
module.exports.isVue3 = true
`
fs.writeFile(indexPath, indexContent)
// esm
const indexPathESM = path.join(__dirname, './index.esm.js')
const indexContentESM = `
export { h, resolveComponent } from 'vue'
export const isVue3 = true`
fs.writeFile(indexPathESM, indexContentESM)
}
if (pkg.version.startsWith('3.')) {
updateIndexForVue3()
}
|
JavaScript
| 0.000115 |
@@ -244,16 +244,19 @@
('vue')%0A
+ %0A
module
@@ -274,16 +274,16 @@
= Vue.h%0A
-
module
@@ -403,16 +403,68 @@
xContent
+, err =%3E %7B%0A%09%09if (err) %7B%0A%09%09%09console.error(err)%0A%09%09%7D%0A%09%7D
)%0A%0A%09// e
@@ -626,16 +626,19 @@
3 = true
+%0A
%60%0A%09fs.wr
@@ -674,16 +674,68 @@
ntentESM
+, err =%3E %7B%0A%09%09if (err) %7B%0A%09%09%09console.error(err)%0A%09%09%7D%0A%09%7D
)%0A%7D%0A%0Aif
|
282b8370cfdcb5d8fa54dc5960ff877484adcd82
|
Update tetris.js to use directions links to toggle directions display
|
tetris.js
|
tetris.js
|
var removeExcessSpaces = function(selector) {
var htmlString = document.querySelector(selector).innerHTML;
htmlString = htmlString.replace(/\s+</g, '<');
htmlString = htmlString.replace(/>\s+/g, '>');
htmlString = htmlString.replace(/_/g, ' ');
document.querySelector(selector).innerHTML = htmlString;
}
var ready = function(fn) {
if(document.readyState != 'loading') {
fn();
}
else {
document.addEventListener('DOMContentLoaded', fn);
}
}
ready(function() {
removeExcessSpaces('main');
new Controller();
});
|
JavaScript
| 0 |
@@ -1,12 +1,185 @@
+var ready = function(fn) %7B%0A if(document.readyState != 'loading') %7B%0A fn();%0A %7D%0A else %7B%0A document.addEventListener('DOMContentLoaded', fn);%0A %7D%0A%7D%0Aready(function() %7B%0A
var removeEx
@@ -208,24 +208,26 @@
selector) %7B%0A
+
var htmlSt
@@ -277,16 +277,18 @@
erHTML;%0A
+
%09htmlStr
@@ -327,16 +327,18 @@
, '%3C');%0A
+
%09htmlStr
@@ -377,16 +377,18 @@
, '%3E');%0A
+
htmlSt
@@ -425,16 +425,18 @@
, ' ');%0A
+
docume
@@ -490,22 +490,116 @@
ng;%0A
+
%7D%0A%0A
-var ready =
+ removeExcessSpaces('main');%0A%0A document.querySelector(%22#show-directions a%22).addEventListener(%22click%22,
fun
@@ -608,59 +608,172 @@
ion(
-fn
+event
) %7B%0A
-if(document.readyState != 'loading'
+ event.preventDefault();%0A var dirContainer = document.querySelector(%22#directions-container%22);%0A%0A if(dirContainer.style%5B%22display%22%5D != %22none%22
) %7B%0A
fn()
@@ -772,94 +772,819 @@
+
-fn();%0A %7D%0A else %7B%0A document.addEventListener('DOMContentLoaded', fn);%0A %7D%0A%7D%0Aready(
+ var dirTrans = document.querySelector(%22#directions-transparent-layer%22);%0A var directions = document.querySelector(%22#directions%22);%0A var main = document.querySelector(%22main%22);%0A dirContainer.style%5B%22left%22%5D = main.offsetLeft + %22px%22;%0A dirContainer.style%5B%22top%22%5D = main.offsetTop + %22px%22;%0A dirContainer.style%5B%22height%22%5D = main.offsetHeight + %22px%22;%0A dirContainer.style%5B%22width%22%5D = main.offsetWidth + %22px%22;%0A%0A directions.style%5B%22height%22%5D = (main.offsetHeight - 32) + %22px%22;%0A directions.style%5B%22width%22%5D = (main.offsetWidth - 64) + %22px%22;%0A%0A dirTrans.style%5B%22height%22%5D = main.offsetHeight + %22px%22;%0A dirTrans.style%5B%22width%22%5D = main.offsetWidth + %22px%22;%0A %7D%0A%0A dirContainer.style%5B%22display%22%5D = %22initial%22;%0A %7D);%0A%0A document.querySelector(%22#hide-directions a%22).addEventListener(%22click%22,
func
@@ -1592,39 +1592,127 @@
ion(
+event
) %7B%0A
-removeExcessSpaces('main'
+ event.preventDefault();%0A document.querySelector(%22#directions-container%22).style%5B%22display%22%5D = %22none%22;%0A %7D
);%0A%0A
|
48099b2771b22f312b4cbc916b5b4b4c15e719a4
|
debug output
|
config/express.js
|
config/express.js
|
/**
* Module dependencies.
*/
var express = require('express');
var session = require('cookie-session');
var compression = require('compression');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var csrf = require('csurf');
var swig = require('swig');
var serveStatic = require('serve-static');
var slashes = require('connect-slashes');
var favicon = require('serve-favicon');
var flash = require('connect-flash');
var winston = require('winston');
var helpers = require('view-helpers');
var config = require('./config');
var pkg = require('../package.json');
var moment = require('moment');
var path = require('path');
var env = process.env.NODE_ENV || 'development';
/**
* Expose
*/
module.exports = function (app, io) {
// Compression middleware (should be placed before express.static)
app.use(compression({
threshold: 512
}));
// Static files middleware
app.use(favicon(path.resolve(__dirname + '/../public/images/favicon.ico')));
app.use(serveStatic(config.root + '/public'));
// Use winston on production
var log;
if (env !== 'development') {
log = {
stream: {
write: function (message, encoding) {
winston.info(message);
}
}
};
} else {
log = { format: 'dev' };
}
// Don't log during tests
// Logging middleware
// if (env !== 'test') app.use(morgan(log));
app.use(slashes());
// Swig templating engine settings
if (env === 'development' || env === 'test') {
swig.setDefaults({
cache: false
});
}
// set views path, template engine and default layout
// app.engine('html', swig.renderFile);
app.set('views', config.root + '/app/views');
app.set('view engine', 'jade');
app.use(function (req, res, next) {
req.io = io;
next();
});
var static_url = '/';
if(config.url) {
static_url = 'http://' + config.url + '/';
}
// cookieParser should be above session
app.use(cookieParser());
// bodyParser should be above methodOverride
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
var getRequestStaticUrl = function(req) {
if(req.query.host) {
return req.query.host;
}
if(req.headers.host) {
return ((req.secure) ? 'https' : 'http') + '://' + req.headers.host;
}
return static_url;
};
// expose package.json to views
app.use(function (req, res, next) {
var staticUrl = getRequestStaticUrl(req);
if(staticUrl.slice(-1) !== '/') {
staticUrl += '/';
}
res.locals.pkg = pkg;
res.locals.env = env;
res.locals.moment = moment;
res.locals._ = require('lodash');
res.locals.marked = require('marked');
res.locals.STATIC_URL = staticUrl;
next();
});
app.use(methodOverride(function (req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
var method = req.body._method;
delete req.body._method;
return method;
}
}));
// express/mongo session storage
app.use(session({
secret: pkg.name,
// store: new mongoStore({
// url: config.db,
// collection : 'sessions'
// }),
cookie: {
maxAge: 1000*60*60
}
}));
// use passport session
// app.use(passport.initialize());
// app.use(passport.session());
// connect flash for flash messages - should be declared after sessions
app.use(flash());
// should be declared after session and flash
app.use(helpers(pkg.name));
// adds CSRF support
if (process.env.NODE_ENV !== 'test') {
// app.use(csrf());
// // This could be moved to view-helpers :-)
// app.use(function(req, res, next){
// res.locals.csrf_token = req.csrfToken();
// next();
// });
}
};
|
JavaScript
| 0.000011 |
@@ -2516,32 +2516,157 @@
headers.host) %7B%0A
+ console.log('req.headers.host');%0A console.log(req.headers.host);%0A console.log(req.secure);%0A
retu
|
d2178d670f2949f8c89164bdc7e94ed44ce31ecf
|
Fix identification of BitPay.
|
src/js/services/send-flow.service.js
|
src/js/services/send-flow.service.js
|
'use strict';
(function(){
angular
.module('bitcoincom.services')
.factory('sendFlowService', sendFlowService);
function sendFlowService(
sendFlowStateService, sendFlowRouterService
, bitcoinUriService, payproService, bitcoinCashJsService
, popupService, gettextCatalog
, $state, $log
) {
var service = {
// Variables
state: sendFlowStateService,
router: sendFlowRouterService,
// Functions
start: start,
goNext: goNext,
goBack: goBack
};
return service;
/**
* Start a new send flow
* @param {Object} params
* @param {Function} onError
*/
function start(params, onError) {
$log.debug('send-flow start()');
if (params && params.data) {
var res = bitcoinUriService.parse(params.data);
if (res.isValid) {
// If BIP70 (url)
if (res.url) {
var url = res.url;
var coin = res.coin || '';
payproService.getPayProDetails(url, coin, function onGetPayProDetails(err, payProData) {
if (err) {
popupService.showAlert(gettextCatalog.getString('Error'), err);
} else {
var name = payProData.domain;
// Detect some merchant that we know
if (payProData.memo.indexOf('eGifter') > -1) {
name = 'eGifter'
} else if (paymentUrl.indexOf('https://bitpay.com') > -1) {
name = 'BitPay';
}
// Init thirdParty
var thirdPartyData = {
id: 'bip70',
caTrusted: true,
name: name,
domain: payProData.domain,
expires: payProData.expires,
memo: payProData.memo,
network: 'livenet',
requiredFeeRate: payProData.requiredFeeRate,
selfSigned: 0,
time: payProData.time,
url: payProData.url,
verified: true
};
// Fill in params
params.amount = payProData.amount,
params.toAddress = payProData.toAddress,
params.coin = coin,
params.thirdParty = thirdPartyData
}
// Resolve
_next();
});
} else {
if (res.coin) {
params.coin = res.coin;
}
if (res.amountInSatoshis) {
params.amount = res.amountInSatoshis;
}
if (res.publicAddress) {
var prefix = res.isTestnet ? 'bchtest:' : 'bitcoincash:';
params.displayAddress = res.publicAddress.cashAddr || res.publicAddress.legacy || res.publicAddress.bitpay;
var formatAddress = res.publicAddress.cashAddr ? prefix + params.displayAddress : params.displayAddress;
params.toAddress = bitcoinCashJsService.readAddress(formatAddress).legacy;
}
_next();
}
} else {
if (onError) {
onError();
}
}
} else {
_next();
}
// Next used for sync the async task
function _next() {
sendFlowStateService.init(params);
// Routing strategy to -> send-flow-router.service
sendFlowRouterService.start();
}
}
/**
* Go to the next step
* @param {Object} state
*/
function goNext(state) {
$log.debug('send-flow goNext()');
// Save the current route before leaving
state.route = $state.current.name;
// Save the state and redirect the user
sendFlowStateService.push(state);
sendFlowRouterService.goNext();
}
/**
* Go to the previous step
*/
function goBack() {
$log.debug('send-flow goBack()');
// Remove the state on top and redirect the user
sendFlowStateService.pop();
sendFlowRouterService.goBack();
}
}
})();
|
JavaScript
| 0.000001 |
@@ -1443,13 +1443,17 @@
(pay
-mentU
+ProData.u
rl.i
|
f7b8a1d9f6f6568a246751fcc2b81034ba0e3ecd
|
add sourcemap generation when building the module
|
app/templates/_Gruntfile.js
|
app/templates/_Gruntfile.js
|
'use strict';
module.exports = function (grunt) {
var path = require('path');
// load npm tasks
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
/**
* Gets the index.html file from the code coverage folder.
*
* @param {!string} folder The path to the code coverage folder.
*/
function getCoverageReport (folder) {
var reports = grunt.file.expand(folder + '*/index.html');
if (reports && reports.length > 0) {
return reports[0];
}
return '';
}
// Project configuration.
grunt.initConfig({
jshintFiles: ['Gruntfile.js', <% if (isNpmPackage) { %>'lib/**/*.js', 'test/**/*.js'<% } %>],
pkg: grunt.file.readJSON('package.json'),<% if (isBowerPackage) { %>
banner: '/*!\n' +
' * <%%= pkg.title || pkg.name %> - v<%%= pkg.version %> - <%%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%%= pkg.homepage ? " * " + pkg.homepage + "\\n" : "" %>' +
' *\n' +
' * Copyright (c) <%%= grunt.template.today("yyyy") %> <%%= pkg.author.name %>\n' +
' * Licensed <%%= _.pluck(pkg.licenses, "type").join(", ") %>\n' +
' */\n\n',<% } %>
clean: {
jasmine: ['build/reports/test'],
lint: ['build/reports/lint'],
coverage: ['build/reports/coverage'],
ci: ['build/reports']<% if (isBowerPackage) { %>,
tmp: ['.tmp']<% } %>
},<% if (isBowerPackage) { %>
concat: {
dist: {
options: {
stripBanners: true
},
src: ['<% if (isNpmPackage) { %>lib<% } else { %>src<% } %>/**/*.js'],
dest: '<%%= pkg.name %>.js'
},
removeUseStrict: {
options: {
banner: '<%%= banner %>\'use strict\';\n',
process: function(src) {
return src.replace(/(^|\n)[ \t]*('use strict'|"use strict");?\s*/g, '$1');
}
},
src: ['<%%= pkg.name %>.js'],
dest: '<%%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '<%%= banner %>'
},
dist: {
src: [<% if (props.useAngular) { %>'.tmp/<%%= pkg.name %>.js'<% } else { %>'<%%= pkg.name %>.js'<% } %>],
dest: '<%%= pkg.name %>.min.js'
}
},<% } %><% if (props.useAngular) { %>
ngmin: {
dist: {
files: [
{
src: ['<%%= pkg.name %>.js'],
dest: '.tmp/<%%= pkg.name %>.js'
}]
}
},<% } %>
jshint: {
options: {
jshintrc: true
},
test: '<%%= jshintFiles %>',
jslint: {
options: {
reporter: 'jslint',
reporterOutput: 'build/reports/lint/jshint.xml'
},
files: {
src: '<%%= jshintFiles %>'
}
},
checkstyle: {
options: {
reporter: 'checkstyle',
reporterOutput: 'build/reports/lint/jshint_checkstyle.xml'
},
files: {
src: '<%%= jshintFiles %>'
}
}
},
bgShell: {
coverage: {
cmd: 'node node_modules/istanbul/lib/cli.js cover --dir build/reports/coverage node_modules/grunt-jasmine-node/node_modules/jasmine-node/bin/jasmine-node -- test --forceexit'
},
cobertura: {
cmd: 'node node_modules/istanbul/lib/cli.js report --root build/reports/coverage --dir build/reports/coverage cobertura'
}
},
open: {
coverage: {
path: function () {
return path.join(__dirname, getCoverageReport('build/reports/coverage/'));
}
}
},<% if (props.useKarma) { %>
karma: {
unit: {
configFile: 'test/karma.conf.js'
},
ci: {
configFile: 'test/karma.conf.js',
colors: false,
reporters: ['mocha', 'junit'],
junitReporter: {
outputFile: 'build/reports/tests/<%= slugname %>.xml',
suite: '<%= slugname %>'
}
},
debug: {
configFile: 'test/karma.conf.js',
singleRun: false,
detectBrowsers: {
enabled: false
}
},
coverage: {
configFile: 'test/karma.coverage.conf.js',
colors: false
},
cobertura: {
configFile: 'test/karma.coverage.conf.js',
colors: false,
coverageReporter: {
type: 'cobertura',
dir: 'build/reports/coverage'
}
}
},<% } %>
jasmine_node: {
options: {
specNameMatcher: './*.spec', // load only specs containing specNameMatcher
requirejs: false,
forceExit: true
},
test: ['test/'],
ci: {
options: {
jUnit: {
report: true,
savePath: 'build/reports/test/',
useDotNotation: true,
consolidate: true
}
},
src: ['test/']
}
},
changelog: {
options: {
}
},
bump: {
options: {
files: ['package.json' <% if (isBowerPackage) { %>, 'bower.json'<% } %>],
updateConfigs: ['pkg'],
commitFiles: ['.'],
commitMessage: 'chore: release v%VERSION%',
push: false
}
}
});
// Register tasks.
grunt.registerTask('git:commitHook', 'Install git commit hook', function () {
grunt.file.copy('validate-commit-msg.js', '.git/hooks/commit-msg');
require('fs').chmodSync('.git/hooks/commit-msg', '0755');
grunt.log.ok('Registered git hook: commit-msg');
});
grunt.registerTask('lint', ['jshint:test']);
grunt.registerTask('test', ['git:commitHook', 'clean:jasmine', 'jshint:test',<% if (props.useKarma) { %> 'karma:unit' <% } else { %> 'jasmine_node:test'<% } %>]);
grunt.registerTask('cover', ['clean:coverage', 'jshint:test', <% if (props.useKarma) { %> 'karma:coverage' <% } else { %> 'bgShell:coverage'<% } %>, 'open:coverage']);<% if (props.useKarma) { %>
grunt.registerTask('debug', ['karma:debug']);<% } %>
grunt.registerTask('ci', ['clean:ci', 'jshint:jslint', 'jshint:checkstyle',<% if (props.useKarma) { %> 'karma:ci', 'karma:coverage', 'karma:cobertura' <% } else { %> 'jasmine_node:ci', 'bgShell:coverage', 'bgShell:cobertura'<% } %>]);
grunt.registerTask('release', 'Bump version, update changelog and tag version', function (version) {
grunt.task.run([
'bump:' + (version || 'patch') + ':bump-only',
'changelog',
'bump-commit'
]);
});
<% if (isBowerPackage && props.useAngular) { %>grunt.registerTask('build', ['clean:tmp', 'concat', 'ngmin', 'uglify']);<% } else if (isBowerPackage) { %>grunt.registerTask('build', ['clean:tmp', 'concat', 'uglify']);<% } %>
// Default task.
grunt.registerTask('default', ['test']);
};
|
JavaScript
| 0 |
@@ -2352,24 +2352,57 @@
= banner %25%3E'
+,%0A sourceMap: true
%0A
|
3e46e67f6d0ff87305105f16692b5a368b21cb29
|
Remove trailing whitespace #6168
|
src/app/components/media/Media.js
|
src/app/components/media/Media.js
|
import React, { Component } from 'react';
import Relay from 'react-relay';
import CheckContext from '../../CheckContext';
import MediaRoute from '../../relay/MediaRoute';
import MediaParentComponent from './MediaParentComponent';
import MediasLoading from './MediasLoading';
const MediaContainer = Relay.createContainer(MediaParentComponent, {
initialVariables: {
contextId: null,
},
fragments: {
media: () => Relay.QL`
fragment on ProjectMedia {
id,
dbid,
quote,
published,
url,
embed,
last_status,
field_value(annotation_type_field_name: "translation_status:translation_status_status"),
log_count,
domain,
permissions,
project {
id,
dbid,
title,
get_languages
},
project_id,
project_source {
dbid,
project_id,
source {
name
}
},
pusher_channel,
verification_statuses,
translation_statuses,
overridden,
language,
language_code,
media {
url,
quote,
embed_path,
thumbnail_path
}
user {
name,
email,
source {
dbid,
accounts(first: 10000) {
edges {
node {
url
}
}
}
}
}
last_status_obj {
id
dbid
}
translation_status: annotation(annotation_type: "translation_status") {
id
dbid
}
translations: annotations(annotation_type: "translation", first: 10000) {
edges {
node {
id,
dbid,
annotation_type,
annotated_type,
annotated_id,
annotator,
content,
created_at,
updated_at
}
}
}
tags(first: 10000) {
edges {
node {
tag,
id
}
}
}
tasks(first: 10000) {
edges {
node {
id,
dbid,
label,
type,
description,
permissions,
jsonoptions,
first_response {
id,
dbid,
permissions,
content,
annotator {
name,
profile_image,
user {
name,
profile_image,
source {
dbid,
accounts(first: 10000) {
edges {
node {
url
}
}
}
}
}
}
}
}
}
}
log(first: 10000) {
edges {
node {
id,
dbid,
item_type,
item_id,
event,
event_type,
created_at,
object_after,
object_changes_json,
meta,
projects(first: 2) {
edges {
node {
id,
dbid,
title
}
}
}
user {
name,
profile_image,
email,
source {
dbid,
accounts(first: 10000) {
edges {
node {
url
}
}
}
}
}
task {
id,
dbid,
label,
type
}
annotation {
id,
dbid,
content,
annotation_type,
updated_at,
created_at,
permissions,
medias(first: 10000) {
edges {
node {
id,
dbid,
quote,
published,
url,
embed,
project_id,
last_status,
field_value(annotation_type_field_name: "translation_status:translation_status_status"),
log_count,
permissions,
verification_statuses,
translation_statuses,
domain,
team {
slug
}
media {
embed_path,
thumbnail_path,
url,
quote
}
user {
name,
source {
dbid
}
}
}
}
}
annotator {
name,
profile_image
}
version {
id
item_id
item_type
}
}
}
}
}
team {
get_suggested_tags,
private,
slug
}
}
`,
},
});
class ProjectMedia extends Component {
render() {
let projectId = this.props.params.projectId || 0;
const context = new CheckContext(this);
context.setContext();
if (projectId === 0) {
const store = context.getContextStore();
if (store.project) {
projectId = store.project.dbid;
}
}
const ids = `${this.props.params.mediaId},${projectId}`;
const route = new MediaRoute({ ids });
return (
<Relay.RootContainer
Component={MediaContainer}
route={route}
renderLoading={function () {
return <MediasLoading count={1} />;
}}
/>
);
}
}
ProjectMedia.contextTypes = {
store: React.PropTypes.object,
};
export default ProjectMedia;
|
JavaScript
| 0.999999 |
@@ -2901,17 +2901,16 @@
url
-
%0A
@@ -2921,35 +2921,32 @@
%7D
-
%0A
@@ -2947,35 +2947,32 @@
%7D
-
%0A
@@ -2971,35 +2971,32 @@
%7D
-
%0A
@@ -2993,35 +2993,32 @@
%7D
-
%0A
@@ -3021,19 +3021,16 @@
%7D
-
%0A
@@ -3039,17 +3039,16 @@
%7D
-
%0A
|
3d1a62e6280ed884f0d84e4045e9590520471545
|
fix allVotes resolveAs
|
packages/vulcan-voting/lib/modules/make_voteable.js
|
packages/vulcan-voting/lib/modules/make_voteable.js
|
export const VoteableCollections = [];
export const makeVoteable = collection => {
VoteableCollections.push(collection);
collection.addField([
/**
The current user's votes on the document, if they exists
*/
{
fieldName: 'currentUserVotes',
fieldSchema: {
type: Array,
optional: true,
viewableBy: ['guests'],
resolveAs: {
type: '[Vote]',
resolver: async (document, args, { Users, Votes, currentUser }) => {
if (!currentUser) return [];
const votes = Votes.find({userId: currentUser._id, documentId: document._id}).fetch();
if (!votes.length) return [];
return votes;
// return Users.restrictViewableFields(currentUser, Votes, votes);
},
}
}
},
{
fieldName: 'currentUserVotes.$',
fieldSchema: {
type: Object,
optional: true,
}
},
/**
All votes on the document
*/
{
fieldName: 'allVotes',
fieldSchema: {
type: Array,
optional: true,
viewableBy: ['guests'],
resolveAs: {
type: 'Vote',
resolver: async (document, args, { Users, Votes, currentUser }) => {
const votes = Votes.find({itemId: document._id}).fetch();
if (!votes.length) return null;
return votes;
// return Users.restrictViewableFields(currentUser, Votes, votes);
},
}
}
},
{
fieldName: 'allVotes.$',
fieldSchema: {
type: Object,
optional: true,
}
},
/**
An array containing the `_id`s of the document's upvoters
*/
{
fieldName: 'voters',
fieldSchema: {
type: Array,
optional: true,
viewableBy: ['guests'],
resolveAs: {
type: '[User]',
resolver: async (document, args, {currentUser, Users}) => {
const votes = Votes.find({itemId: document._id}).fetch();
const votersIds = _.pluck(votes, 'userId');
const voters = Users.find({_id: {$in: votersIds}});
return voters;
// if (!document.upvoters) return [];
// const upvoters = await Users.loader.loadMany(document.upvoters);
// return Users.restrictViewableFields(currentUser, Users, upvoters);
},
},
}
},
{
fieldName: 'voters.$',
fieldSchema: {
type: String,
optional: true
}
},
/**
The document's base score (not factoring in the document's age)
*/
{
fieldName: 'baseScore',
fieldSchema: {
type: Number,
optional: true,
defaultValue: 0,
viewableBy: ['guests'],
onInsert: () => 0
}
},
/**
The document's current score (factoring in age)
*/
{
fieldName: 'score',
fieldSchema: {
type: Number,
optional: true,
defaultValue: 0,
viewableBy: ['guests'],
onInsert: () => 0
}
},
/**
Whether the document is inactive. Inactive documents see their score recalculated less often
*/
{
fieldName: 'inactive',
fieldSchema: {
type: Boolean,
optional: true,
onInsert: () => false
}
},
]);
}
|
JavaScript
| 0.000008 |
@@ -1159,20 +1159,22 @@
type: '
+%5B
Vote
+%5D
',%0A
@@ -1277,36 +1277,41 @@
s = Votes.find(%7B
-item
+ document
Id: document._id
@@ -1302,32 +1302,33 @@
Id: document._id
+
%7D).fetch();%0A
@@ -1365,12 +1365,10 @@
urn
-null
+%5B%5D
;%0A
|
22e15baf71456be2184b536edccd26196d16e927
|
Fix bug with Vertical Flowlayout and only 1 column fits width.
|
src/react/Layout/FlowLayout/VerticalFlowLayout.js
|
src/react/Layout/FlowLayout/VerticalFlowLayout.js
|
var t = require('tcomb');
var Models = require('../../Model/Models');
var Enums = require('../../Enums/Enums');
var CollectionViewLayoutAttributes = require('../../Layout/CollectionViewLayoutAttributes');
var VerticalSectionLayoutDetails = t.struct({
Frame: Models.Rect,
NumberItems: t.Num,
NumberOfTotalRows: t.Num,
ItemTotalWidth: t.Num,
NumberOfColumns: t.Num,
ActualInteritemSpacing: t.Num,
MinimumLineSpacing: t.Num,
RowHeight: t.Num,
SectionInsets: Models.EdgeInsets,
HeaderReferenceSize: Models.Size,
FooterReferenceSize: Models.Size
}, 'SectionLayoutDetails');
VerticalSectionLayoutDetails.prototype.getEstimatedRowForPoint = function (point) {
//zero based
return Math.max(0, Math.floor((point.y - this.Frame.origin.y + this.MinimumLineSpacing) / (this.RowHeight + this.MinimumLineSpacing)));
};
VerticalSectionLayoutDetails.prototype.getStartingIndexForRow = function (row) {
//zero based
return Math.max(0, row * this.NumberOfColumns);
};
VerticalSectionLayoutDetails.prototype.getRowForIndex = function (indexPath) {
//zero based
return Math.floor(indexPath.row / this.NumberOfColumns);
};
function creationSectionLayoutDetails(indexPath, numberItemsInSection, startY, opts) {
var _constrainedHeightOrWidth = opts.width;
var numberItems = numberItemsInSection;
var availableWidth = _constrainedHeightOrWidth - opts.sectionInsets.left - opts.sectionInsets.right;
var numberOfColumns = Math.floor((availableWidth - opts.itemSize.width) / (opts.itemSize.width + opts.minimumInteritemSpacing)) + 1;
var actualInteritemSpacing = Math.floor((availableWidth - opts.itemSize.width * numberOfColumns) / (numberOfColumns - 1));
var itemTotalWidth = opts.itemSize.width;
var rowHeight = opts.itemSize.height;
var numberOfTotalRows = Math.ceil(numberItems / numberOfColumns);
var totalHeight = numberOfTotalRows * rowHeight + (numberOfTotalRows - 1) * opts.minimumLineSpacing;
totalHeight += opts.headerReferenceSize.height + opts.footerReferenceSize.height;
totalHeight += opts.sectionInsets.top + opts.sectionInsets.bottom;
var sectionSize = Models.Size({width: _constrainedHeightOrWidth, height: totalHeight});
var sectionLayout = new VerticalSectionLayoutDetails({
Frame: new Models.Rect({
origin: new Models.Point({x: 0, y: startY}),
size: sectionSize
}),
NumberItems: numberItems,
NumberOfTotalRows: numberOfTotalRows,
ItemTotalWidth: itemTotalWidth,
NumberOfColumns: numberOfColumns,
RowHeight: rowHeight,
ActualInteritemSpacing: actualInteritemSpacing,
MinimumLineSpacing: opts.minimumLineSpacing,
SectionInsets: opts.sectionInsets,
HeaderReferenceSize: opts.headerReferenceSize,
FooterReferenceSize: opts.footerReferenceSize
});
return sectionLayout;
}
function getSections(rect, sectionsLayoutDetails) {
var sections = [];
var startSection = -1;
var endSection = -1;
var numberOfSections = sectionsLayoutDetails.length;
for(var i = 0; i < numberOfSections; i++) {
var layout = sectionsLayoutDetails[i];
if(Models.Geometry.rectIntersects(rect, layout.Frame) || Models.Geometry.rectIntersects(layout.Frame, rect)) {
sections.push(i);
}
}
return sections;
};
function layoutAttributesForItemAtIndexPath(indexPath, sectionLayoutInfo, itemSize) {
Models.IndexPath.is(indexPath);
VerticalSectionLayoutDetails.is(sectionLayoutInfo);
Models.Size.is(itemSize);
var row = sectionLayoutInfo.getRowForIndex(indexPath);
var y = sectionLayoutInfo.Frame.origin.y + row * sectionLayoutInfo.RowHeight;
y += sectionLayoutInfo.MinimumLineSpacing * (row) + sectionLayoutInfo.HeaderReferenceSize.height + sectionLayoutInfo.SectionInsets.top;
var column = indexPath.row % sectionLayoutInfo.NumberOfColumns;
var x = column * sectionLayoutInfo.ItemTotalWidth + column * sectionLayoutInfo.ActualInteritemSpacing + sectionLayoutInfo.SectionInsets.left;
var origin = new Models.Point({x: x, y: y});
var size = new Models.Size({height: itemSize.height, width: itemSize.width});
var frame = new Models.Rect({origin: origin, size: size});
var layoutAttributes = new CollectionViewLayoutAttributes.Protocol({
"indexPath": indexPath,
"representedElementCategory": function(){
return "CollectionElementTypeCell";
},
"representedElementKind": function(){
return "default"
},
"frame": frame,
"size": size,
"hidden": false
});
return layoutAttributes;
};
function layoutAttributesForSupplementaryView(indexPath, sectionLayoutInfo, kind) {
var layoutAttributes = null;
if(kind == "header") {
var frame = new Models.Rect({
origin: new Models.Point({x: 0, y: sectionLayoutInfo.Frame.origin.y}),
size: new Models.Size({height: sectionLayoutInfo.HeaderReferenceSize.height, width: sectionLayoutInfo.HeaderReferenceSize.width})
});
var layoutAttributes = new CollectionViewLayoutAttributes.Protocol({
"indexPath": indexPath,
"representedElementCategory": function(){
return "CollectionElementTypeSupplementaryView";
},
"representedElementKind": function(){
return kind.toString();
},
"frame": frame,
"size": frame.size,
"hidden": false
});
} else if(kind == "footer") {
var frame = new Models.Rect({
origin: new Models.Point({x: 0, y: sectionLayoutInfo.Frame.origin.y + sectionLayoutInfo.Frame.size.height - sectionLayoutInfo.FooterReferenceSize.height}),
size: new Models.Size({height: sectionLayoutInfo.FooterReferenceSize.height, width: sectionLayoutInfo.FooterReferenceSize.width})
});
var layoutAttributes = new CollectionViewLayoutAttributes.Protocol({
"indexPath": indexPath,
"representedElementCategory": function(){
return "CollectionElementTypeSupplementaryView";
},
"representedElementKind": function(){
return kind;
},
"frame": frame,
"size": frame.size,
"hidden": false
});
}
return layoutAttributes;
}
module.exports = {
LayoutDetails: VerticalSectionLayoutDetails,
CreateLayoutDetailsForSection: creationSectionLayoutDetails,
GetSectionsForRect: getSections,
LayoutAttributesForItemAtIndexPath: layoutAttributesForItemAtIndexPath,
LayoutAttributesForSupplementaryView: layoutAttributesForSupplementaryView
}
|
JavaScript
| 0 |
@@ -1693,16 +1693,28 @@
lumns) /
+ Math.max(1,
(number
@@ -1728,16 +1728,17 @@
ns - 1))
+)
;%0A va
|
99a43f0282d5115b75a564205ca7d2db31a3a945
|
Fix #19304 (#19305)
|
app/javascript/mastodon/features/report/category.js
|
app/javascript/mastodon/features/report/category.js
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import Button from 'mastodon/components/button';
import Option from './components/option';
const messages = defineMessages({
dislike: { id: 'report.reasons.dislike', defaultMessage: 'I don\'t like it' },
dislike_description: { id: 'report.reasons.dislike_description', defaultMessage: 'It is not something you want to see' },
spam: { id: 'report.reasons.spam', defaultMessage: 'It\'s spam' },
spam_description: { id: 'report.reasons.spam_description', defaultMessage: 'Malicious links, fake engagement, or repetitive replies' },
violation: { id: 'report.reasons.violation', defaultMessage: 'It violates server rules' },
violation_description: { id: 'report.reasons.violation_description', defaultMessage: 'You are aware that it breaks specific rules' },
other: { id: 'report.reasons.other', defaultMessage: 'It\'s something else' },
other_description: { id: 'report.reasons.other_description', defaultMessage: 'The issue does not fit into other categories' },
status: { id: 'report.category.title_status', defaultMessage: 'post' },
account: { id: 'report.category.title_account', defaultMessage: 'profile' },
});
const mapStateToProps = state => ({
rules: state.get('rules'),
});
export default @connect(mapStateToProps)
@injectIntl
class Category extends React.PureComponent {
static propTypes = {
onNextStep: PropTypes.func.isRequired,
rules: ImmutablePropTypes.list,
category: PropTypes.string,
onChangeCategory: PropTypes.func.isRequired,
startedFrom: PropTypes.oneOf(['status', 'account']),
intl: PropTypes.object.isRequired,
};
handleNextClick = () => {
const { onNextStep, category } = this.props;
switch(category) {
case 'dislike':
onNextStep('thanks');
break;
case 'violation':
onNextStep('rules');
break;
default:
onNextStep('statuses');
break;
}
};
handleCategoryToggle = (value, checked) => {
const { onChangeCategory } = this.props;
if (checked) {
onChangeCategory(value);
}
};
render () {
const { category, startedFrom, rules, intl } = this.props;
const options = rules.size > 0 ? [
'dislike',
'spam',
'violation',
'other',
] : [
'dislike',
'spam',
'other',
];
return (
<React.Fragment>
<h3 className='report-dialog-modal__title'><FormattedMessage id='report.category.title' defaultMessage="Tell us what's going on with this {type}" values={{ type: intl.formatMessage(messages[startedFrom]) }} /></h3>
<p className='report-dialog-modal__lead'><FormattedMessage id='report.category.subtitle' defaultMessage='Choose the best match' /></p>
<div>
{options.map(item => (
<Option
key={item}
name='category'
value={item}
checked={category === item}
onToggle={this.handleCategoryToggle}
label={intl.formatMessage(messages[item])}
description={intl.formatMessage(messages[`${item}_description`])}
/>
))}
</div>
<div className='flex-spacer' />
<div className='report-dialog-modal__actions'>
<Button onClick={this.handleNextClick} disabled={category === null}><FormattedMessage id='report.next' defaultMessage='Next' /></Button>
</div>
</React.Fragment>
);
}
}
|
JavaScript
| 0.000003 |
@@ -1419,24 +1419,38 @@
tate.get
-(
+In(%5B'server',
'rules'
+%5D
),%0A%7D);%0A%0A
|
1090cf78a0bcaf812841ca46ff6ed81f3838a3d4
|
Avoid test ambiguity
|
lib/momentum.test.js
|
lib/momentum.test.js
|
describe('Momentum', function () {
beforeEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
});
it('should be available on window', function () {
expect(typeof Momentum).toBe('function');
});
it('should use relative path if no URL provided', function () {
var momentum = new Momentum();
expect(momentum.url).toBe('');
});
it('should have editable url prefix', function () {
var momentum = new Momentum();
expect(momentum.getUrlPrefix()).toBe('/api/mm/');
momentum.setUrlPrefix('/foo/');
expect(momentum.getUrlPrefix()).toBe('/foo/');
});
it('should expose its AJAX settings', function (done) {
var momentum = new Momentum('http://localhost:8092');
momentum.onReady(function () {
var ajax = momentum.getAjax();
expect(ajax.jsonToObject('')).toEqual({});
expect(ajax.jsonToObject('{}')).toEqual({});
expect(ajax.jsonToObject('<>')).toEqual({});
expect(ajax.jsonToObject('{"a": "a"}')).toEqual({a: 'a'});
var value = 1;
ajax.jsonCallback(null, function (input) {
value = input;
});
expect(value).toBe(null);
value = 1;
ajax.jsonCallback('{"a":4}', function (input) {
value = input;
});
expect(value).toEqual({a: 4});
var error = null;
try {
ajax.json('< no-json >');
} catch (e) {
error = e + '';
}
expect(error).toContain('in < no-json >');
var MyClass = function () {
this.a = 2;
};
MyClass.prototype.a = 8;
MyClass.prototype.b = 3;
MyClass.prototype.c = 4;
var obj = new MyClass();
obj.d = 9;
ajax.get('http://localhost:8092/reflect', obj, function (data) {
expect(data).toEqual(JSON.stringify({a: '2', d: '9'}));
expect(ajax.json(data)).toEqual({a: '2', d: '9'});
ajax.post('http://localhost:8092/reflect', obj, function (data) {
expect(data).toEqual(JSON.stringify({a: '2', d: '9'}));
ajax.postJson('http://localhost:8092/reflect', obj, function (data) {
expect(data).toEqual(JSON.stringify({a: 2, d: 9}));
done();
});
});
});
});
});
it('should allow onReady to be cancelled', function (done) {
var momentum = new Momentum('http://localhost:8092');
momentum.onReady(function () {
momentum.listenCollection('table', function () {
var test = {
method: function () {
}
};
spyOn(test, 'method');
var off = momentum.on(test.method);
off();
setTimeout(function () {
setTimeout(function () {
expect(test.method).not.toHaveBeenCalled();
momentum.on(test.method);
setTimeout(function () {
momentum.remove(['table', {tag: 'tr'}]);
setTimeout(function () {
expect(test.method).toHaveBeenCalled();
done();
}, 500);
}, 250);
}, 500);
momentum.remove(['table', {tag: 'tr'}]);
}, 250);
});
});
});
it('can access server API', function (done) {
var momentum = new Momentum('http://localhost:8092');
var count = 0;
var first = true;
var end = function () {
if (first) {
first = false;
return;
}
expect(count).toBe(7);
done();
};
var off = momentum.on(function (data) {
expect(typeof data).toBe('object', 'typeof data');
expect(typeof data.events).toBe('object', 'typeof data.events');
expect(typeof data.events[0]).toBe('object', 'typeof data.events[0]');
expect(typeof data.events[0].args).toBe('object', 'typeof data.events[0].args');
expect(data.events[0].args[0]).toBe('insert');
expect(typeof data.events[0].args[4]).toBe('object', 'typeof data.events[0].args[4]');
expect(data.events[0].args[4].tag).toBe('tr', 'data.events[0].args[4].tag');
momentum.onReady(function () {
count += 4;
});
off();
count += 2;
end();
});
setTimeout(function () {
momentum.listenCollection('table', function () {
momentum.insertOne(['table', {tag: 'tr'}], function () {
count++;
end();
});
});
}, 200);
});
it('should allow empty arguments', function () {
expect(function () {
var momentum = new Momentum('http://localhost:8092');
momentum.on();
momentum.onReady();
momentum.listenItem();
momentum.updateOne();
}).not.toThrowError();
});
it('should disallow too many connection', function (done) {
var restrictedMomentum = function () {
var momentum = new Momentum('http://localhost:8092');
momentum.setUrlPrefix('/restricted/');
return momentum;
};
var m1 = restrictedMomentum();
m1.onReady(function (error) {
expect(error).toBe(undefined);
var m2 = restrictedMomentum();
m2.onReady(function (error) {
expect(error).toBe(undefined);
var m3 = restrictedMomentum();
m3.onReady(function (error) {
expect(typeof error).toBe('object');
expect(error instanceof Error).toBe(true);
expect(error).toEqual(new Error('Too many connections'));
done();
});
});
});
});
it('should allow to stop listening', function (done) {
var momentum = new Momentum('http://localhost:8092');
var count = 0;
var off = momentum.on(function () {
/* istanbul ignore next */
count++;
});
off();
setTimeout(function () {
expect(count).toBe(0);
done();
}, 2000);
});
it('should wait until it\'s ready', function (done) {
var momentum = new Momentum('http://localhost:65535');
var self = momentum.setUrlPrefix('/not/found/');
expect(self).toBe(momentum);
var inc = function () {
this.count++;
};
var count65535 = {count: 0};
momentum
.onReady(inc.bind(count65535))
.onReady(inc.bind(count65535));
momentum = new Momentum('http://localhost:8092');
var count8092 = {count: 0};
momentum
.onReady(inc.bind(count8092))
.onReady(inc.bind(count8092));
setTimeout(function () {
expect(count65535.count).toBe(0);
expect(count8092.count).toBe(2);
done();
}, 2000);
});
});
|
JavaScript
| 0.998122 |
@@ -2741,37 +2741,39 @@
stenCollection('
-table
+rmvtest
', function () %7B
@@ -2836,32 +2836,77 @@
: function () %7B%0A
+ console.log('test');%0A
@@ -3335,37 +3335,39 @@
mentum.remove(%5B'
-table
+rmvtest
', %7Btag: 'tr'%7D%5D)
@@ -3666,29 +3666,31 @@
um.remove(%5B'
-table
+rmvtest
', %7Btag: 'tr
@@ -6515,32 +6515,67 @@
var count = 0;%0A
+ /* istanbul ignore next */%0A
var off
|
dc020af1a3d13f4c292f33da9705a0ec87aaecf0
|
remove the double import for carousel widget container
|
app/src/containers/CarouselWidgetContainer/index.js
|
app/src/containers/CarouselWidgetContainer/index.js
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as CarouselWidgetActionCreators from './actions';
import cssModules from 'react-css-modules';
import styles from './index.module.scss';
import Heading from 'grommet-udacity/components/Heading';
import Box from 'grommet-udacity/components/Box';
import Section from 'grommet-udacity/components/Section';
import { CarouselWidget, MainAside } from 'components';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { reduxForm } from 'redux-form';
import calculateLoading from './utils/loading';
import {
LoadingIndicator,
ErrorAlert,
} from 'components';
const formFields = [
'newImageInput',
'editImageInput',
];
class CarouselWidgetContainer extends Component {
componentWillReceiveProps({ spotlightImages }) {
if (spotlightImages !== this.props.images) {
this.props.actions.carouselSetImages(spotlightImages);
}
}
handleCreatingImage(image) {
const {
authToken,
createMutation,
actions,
refetch,
} = this.props;
const data = {
variables: {
token: authToken,
url: image.url,
},
};
createMutation(data)
.then(res => {
const newImage = res.data.CreateSpotlightImage.spotlight_image;
actions.carouselAddImage(newImage);
refetch();
});
}
handleUpdatingImage(index, image) {
const {
authToken,
updateMutation,
actions,
refetch,
} = this.props;
const data = {
variables: {
token: authToken,
id: image.id,
url: image.url,
},
};
updateMutation(data)
.then(res => {
const newImage = res.data.UpdateSpotlightImage.spotlight_image;
actions.carouselEditImage(index, newImage);
refetch();
});
}
handleDeletingImage(index) {
const {
deleteMutation,
actions,
images,
authToken,
refetch,
} = this.props;
const id = parseInt(images[index].id, 10);
const data = {
variables: {
token: authToken,
id,
},
};
deleteMutation(data)
.then(() => {
actions.carouselRemoveImage(index);
refetch();
});
}
render() {
const {
images,
fields,
actions,
currentlyEditing,
user,
imagesError,
imagesLoading,
createLoading,
updateLoading,
deleteLoading,
} = this.props;
return (
<div className={styles.carouselWidget}>
<Section
primary
alignContent="center"
align="center"
className={styles.mainSection}
>
{imagesError &&
<ErrorAlert
errors={[imagesError]}
onClose={this.handleCloseErrorAlert}
/>
}
<Box direction="row">
<Box
basis="2/3"
pad="large"
align="center"
justify="center"
className={styles.mainContent}
>
<Heading align="center">
Carousel Widget
</Heading>
{calculateLoading(
images,
imagesLoading,
createLoading,
updateLoading,
deleteLoading,
) ?
<LoadingIndicator
isLoading
/>
:
<CarouselWidget
{...fields}
setEditing={(index) => actions.carouselSetEditing(index)}
currentlyEditing={currentlyEditing}
onEditImage={({ index, image }) => this.handleUpdatingImage(index, image)}
cancelEditing={(index) => actions.carouselCancelEditing(index)}
onDeleteImage={(index) => this.handleDeletingImage(index)}
onAddImage={(image) => this.handleCreatingImage(image)}
images={images}
/>
}
</Box>
{user &&
<MainAside
user={user}
/>
}
</Box>
</Section>
</div>
);
}
}
CarouselWidgetContainer.propTypes = {
images: PropTypes.array,
refetch: PropTypes.func.isRequired,
imagesError: PropTypes.object,
imagesLoading: PropTypes.bool,
spotlightImages: PropTypes.array,
fields: PropTypes.object.isRequired,
actions: PropTypes.object.isRequired,
currentlyEditing: PropTypes.bool.isRequired,
user: PropTypes.object.isRequired,
createMutation: PropTypes.func.isRequired,
updateMutation: PropTypes.func.isRequired,
deleteMutation: PropTypes.func.isRequired,
authToken: PropTypes.string.isRequired,
createLoading: PropTypes.bool.isRequired,
updateLoading: PropTypes.bool.isRequired,
deleteLoading: PropTypes.bool.isRequired,
};
// mapStateToProps :: {State} -> {Props}
const mapStateToProps = (state) => ({
images: state.carouselWidgetContainer.images,
user: state.app.user,
authToken: state.app.authToken,
currentlyEditing: state.carouselWidgetContainer.currentlyEditing,
});
// mapDispatchToProps :: Dispatch -> {Action}
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(
CarouselWidgetActionCreators,
dispatch
),
});
const Container = cssModules(CarouselWidgetContainer, styles);
const allSpotlightImageQuery = gql`
query allSpotlightImages {
spotlightImages {
id
url
}
}
`;
const ContainerWithData = graphql(allSpotlightImageQuery, {
props: ({ data: { loading, spotlightImages, error, refetch } }) => ({
imagesLoading: loading,
spotlightImages,
imageError: error,
refetch,
}),
})(Container);
const createSpotlightImageMutation = gql`
mutation createSpotlightImage($token: String!, $url: String!) {
CreateSpotlightImage(input: { auth_token: $token, url: $url }) {
spotlight_image {
id
url
}
}
}
`;
const updateSpotlightImageMutation = gql`
mutation updateSpotlightImage($token: String!, $url: String!, $id: ID!) {
UpdateSpotlightImage(input: { auth_token: $token, url: $url, id: $id }) {
spotlight_image{
id
url
}
}
}
`;
const deleteSpotlightImageMutation = gql`
mutation deleteSpotlightImage($token: String!, $id: ID!) {
DeleteSpotlightImage(input: { auth_token: $token, id: $id }) {
id: deleted_id
}
}
`;
const ContainerWithCreateMutation = graphql(createSpotlightImageMutation, {
props: ({ loading, mutate, error }) => ({
createMutation: mutate,
createLoading: loading,
createError: error,
}),
})(ContainerWithData);
const ContainerWithUpdateMutation = graphql(updateSpotlightImageMutation, {
props: ({ loading, mutate, error }) => ({
updateMutation: mutate,
updateLoading: loading,
updateError: error,
}),
})(ContainerWithCreateMutation);
const ContainerWithDeleteMutation = graphql(deleteSpotlightImageMutation, {
props: ({ loading, mutate, error }) => ({
deleteMutation: mutate,
deleteLoading: loading,
deleteError: error,
}),
})(ContainerWithUpdateMutation);
const FormContainer = reduxForm({
form: 'CarouselWidget',
fields: formFields,
})(ContainerWithDeleteMutation);
export default connect(
mapStateToProps,
mapDispatchToProps
)(FormContainer);
|
JavaScript
| 0 |
@@ -444,64 +444,8 @@
n';%0A
-import %7B CarouselWidget, MainAside %7D from 'components';%0A
impo
@@ -642,16 +642,47 @@
rAlert,%0A
+ MainAside,%0A CarouselWidget,%0A
%7D from '
|
2f674f17f08852ac59c7d9a21841fd7aae02c578
|
Fix date picker on crossroads delivery page
|
app/views/month-calender.js
|
app/views/month-calender.js
|
import Ember from 'ember';
export default Ember.TextField.extend({
tagName: 'input',
classNames: 'pickadate',
attributeBindings: [ "name", "type", "value", "id", 'required', 'pattern', 'available', 'placeholder' ],
didInsertElement: function(){
var _this = this;
var list = this.get('available');
var available_count = 0, available_array = [true];
if(list) {
available_count = list.length;
for (var i = available_count - 1; i >= 0; i--) {
var date = new Date(list[i]);
var date_array = [];
date_array.push(date.getFullYear());
date_array.push(date.getMonth());
date_array.push(date.getDate());
available_array.push(date_array);
}
}
Ember.$().ready(function(){
Ember.$('.pickadate').pickadate({
format: 'ddd mmm d',
monthsFull: moment.months(),
monthsShort: moment.monthsShort(),
weekdaysShort: moment.weekdaysShort(),
disable: available_array,
min: new Date(),
clear: false,
today: false,
close: false,
onSet: function() {
var date = this.get('select') && this.get('select').obj;
_this.set("selection", date);
},
onClose: function() {
Ember.$(document.activeElement).blur();
},
onStart: function(){
var date = _this.get('selection');
if(date) {
this.set('select', new Date(date), { format: 'ddd mmm d' });
}
},
});
validateForm();
validateInputs();
});
function validateForm(){
Ember.$('.button.drop_off').click(function(){
return checkInput(Ember.$('#selectedDate'));
});
}
function validateInputs(){
Ember.$('#selectedDate').focusout(function(){
return checkInput(this);
});
Ember.$('#selectedDate').focus(function(){
return removeHighlight(this);
});
}
function checkInput(element){
var parent = Ember.$(element).parent();
var value = Ember.$(element).val();
if(value === undefined || value.length === 0) {
parent.addClass('has-error');
return false;
} else {
parent.removeClass('has-error');
return true;
}
}
function removeHighlight(element){
var parent = Ember.$(element).parent();
parent.removeClass('has-error');
}
}
});
|
JavaScript
| 0 |
@@ -362,16 +362,41 @@
%5Btrue%5D;
+%0A var setting = false;
%0A%0A if
@@ -1122,32 +1122,68 @@
t: function() %7B%0A
+ if (setting) %7B return; %7D%0A%0A
var da
@@ -1272,16 +1272,192 @@
, date);
+%0A%0A setting = true;%0A Ember.run.next(() =%3E %7B%0A this.set('select', new Date(date), %7B format: 'ddd mmm d' %7D);%0A setting = false;%0A %7D);
%0A
|
b83baa4a697e7f15e65de22b4e394b8948423d5e
|
update convertGConvertNames #524 #535
|
src/server/enrichment-map/gene-validator/index.js
|
src/server/enrichment-map/gene-validator/index.js
|
/*
Documentation for g:convert validator:
sample url: http://localhost:3000/api/validatorGconvert?genes=ATM ATP ATM
output: {"unrecogized":["ATP"],"duplicate":["ATM"],"geneInfo":[{"HGNC_symbol":"ATM","HGNC_id":"HGNC:795"}]}
*/
const request = require('request');
const _ = require('lodash');
const { validOrganism } = require('./validityInfo');
const { validTarget } = require('./validityInfo');
const defaultOptions = {
'output': 'mini',
'organism': 'hsapiens',
'target': 'HGNC'
};
const gConvertURL = 'http://biit.cs.ut.ee/gprofiler/gconvert.cgi';
class InvalidInfoError extends Error {
constructor(invalidOrganism, invalidTarget, message) {
super(message);
this.invalidTarget = invalidTarget;
this.invalidOrganism = invalidOrganism;
}
}
// convert offical synonyms to gConvert names
const convertGConvertNames = (gConvertName) => {
if (gConvertName === 'HGNC_ID') { return 'HGNC_ACC'; }
if (gConvertName === 'UNIPROT') { return 'UNIPROTSWISSPROT'; }
if (gConvertName === 'ENTREZGENE') { return 'ENTREZGENE_ACC'; }
return gConvertName;
};
const validatorGconvert = (query, userOptions) => {
const promise = new Promise((resolve, reject) => {
const formData = _.assign({}, defaultOptions, userOptions, { query: query });
formData.organism = formData.organism.toLowerCase();
formData.target = convertGConvertNames(formData.target.toUpperCase());
const invalidInfo = {invalidTarget: '', invalidOrganism: ''};
if (!validOrganism.includes(formData.organism)) {
invalidInfo.invalidOrganism = formData.organism;
}
if (!validTarget.includes(formData.target)) {
invalidInfo.invalidTarget = formData.target;
}
if (invalidInfo.invalidOrganism != '' || invalidInfo.invalidTarget != '') {
reject(new InvalidInfoError(invalidInfo.invalidOrganism, invalidInfo.invalidTarget, ''));
}
request.post({ url: gConvertURL, formData: formData }, (err, httpResponse, body) => {
if (err) {
reject(err);
}
const geneInfoList = _.map(body.split('\n'), ele => { return ele.split('\t'); });
geneInfoList.splice(-1, 1); // remove last element ''
const unrecogized = [];
const duplicate = [];
const geneInfo = [];
const initialAliasIndex = 1;
const convertedAliasIndex = 3;
_.forEach(geneInfoList, info => {
if (info[convertedAliasIndex] === 'N/A') {
if (_.filter(unrecogized, ele => ele === info[initialAliasIndex]).length === 0) {
unrecogized.push(info[initialAliasIndex]);
}
} else {
if (_.filter(geneInfoList, ele => ele[convertedAliasIndex] === info[convertedAliasIndex]).length > 1 && _.filter(duplicate, ele => ele === info[initialAliasIndex]).length === 0) {
duplicate.push(info[initialAliasIndex]);
}
if (_.filter(geneInfo, ele => ele.initialAlias === info[initialAliasIndex]).length === 0) {
geneInfo.push({ initialAlias: info[initialAliasIndex], convertedAlias: info[convertedAliasIndex] });
}
}
});
const ret = { options: {target: formData.target, organism: formData.organism}, unrecogized: unrecogized, duplicate: duplicate, geneInfo: geneInfo };
resolve(ret);
});
});
return promise;
};
module.exports = { validatorGconvert };
|
JavaScript
| 0 |
@@ -886,11 +886,64 @@
HGNC
-_ID
+SYMBOL') %7B return 'HGNC'; %7D%0A if (gConvertName === 'HGNC
') %7B
@@ -1053,22 +1053,20 @@
me === '
-ENTREZ
+NCBI
GENE') %7B
|
d216a8a09d5cadce045a3b0c384ea8d9497aa1a1
|
Fix parnswir issue
|
src/services/user/services/forcePasswordChange.js
|
src/services/user/services/forcePasswordChange.js
|
const { BadRequest } = require('@feathersjs/errors');
const { disallow } = require('feathers-hooks-common');
const { authenticate } = require('@feathersjs/authentication');
const { passwordsMatch } = require('../../../utils/passwordHelpers');
const ForcePasswordChangeServiceHooks = {
before: {
all: [],
find: disallow('external'),
get: disallow('external'),
create: [authenticate('jwt')],
update: disallow('external'),
patch: disallow('external'),
remove: disallow('external'),
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: [],
},
};
class ForcePasswordChangeService {
constructor(options) {
this.options = options || {};
this.err = Object.freeze({
missmatch: 'Die neuen Passwörter stimmen nicht überein.',
failed: 'Can not update the password. Please contact the administrator',
});
}
async newPasswordProvidedByUser(data, params) {
const newPassword = data['password-1'];
if (!passwordsMatch(newPassword, data['password-2'])) {
throw new BadRequest(this.err.missmatch);
}
const accountUpdate = {
password: newPassword,
userForcedToChangePassword: true,
};
const accountPromise = this.app.service('/accounts')
.patch(params.account._id, accountUpdate, params);
const userPromise = this.app.service('/users')
.patch(params.account.userId, { forcePasswordChange: false });
return Promise.allSettled([accountPromise, userPromise])
.then(([accountResponse, userResponse]) => {
if (accountResponse.status === 'rejected') {
throw new Error(accountResponse.reason);
}
if (userResponse.status === 'rejected') {
throw new Error(userResponse.reason);
}
return Promise.resolve(userResponse.value);
})
.catch((err) => {
throw new BadRequest(this.err.failed, err);
});
}
create(data, params) {
return this.newPasswordProvidedByUser(data, params);
}
setup(app) {
this.app = app;
}
}
module.exports = function () {
const app = this;
app.use('/forcePasswordChange', new ForcePasswordChangeService());
const forcePasswordChangeService = app.service('forcePasswordChange');
forcePasswordChangeService.hooks(ForcePasswordChangeServiceHooks);
};
|
JavaScript
| 0.000044 |
@@ -1965,40 +1965,18 @@
s =
-function () %7B%0A%09const
+(
app
+)
=
- this;
+%3E %7B
%0A%09ap
|
2241d67d4baf50fbe9a504b83114742fe64091f4
|
Add ability to type negative numbers in smpl mode (#168)
|
src/Components/FormattedNumberInput/FormattedNumberInput.js
|
src/Components/FormattedNumberInput/FormattedNumberInput.js
|
// @flow
import * as React from "react";
import numeral from "numeral";
import FilteredInput from "../FilteredInput/FilteredInput";
import type { FilterValueResult } from "../FilteredInput/FilteredInput";
type FormattedNumberInputProps = {
viewFormat?: ?string,
editFormat?: ?string,
value: ?number,
align?: "left" | "center" | "right",
onChange: (event: SyntheticEvent<>, value: ?number) => any,
width: string | number,
};
export default class FormattedNumberInput extends React.Component<FormattedNumberInputProps> {
props: FormattedNumberInputProps;
static numberRegexp = /^\s*\d*(\.\d*)?\s*$/;
handleFilterValue(value: string): FilterValueResult<?number> | null {
const str = value ? value.replace(",", ".") : value;
if (FormattedNumberInput.numberRegexp.test(str)) {
if (str.trim() === "") {
return {
displayValue: null,
actualValue: null,
};
}
return {
displayValue: str,
actualValue: parseFloat(str),
};
}
return null;
}
handleValueForView(value: ?number): string {
return value != null
? numeral(value).format(this.props.viewFormat || this.props.editFormat || "0.0[00000]")
: "";
}
handleValueForEdit(value: ?number): string {
return value != null ? numeral(value).format(this.props.editFormat || "0.0[00000]") : "";
}
render(): React.Node {
// eslint-disable-next-line no-unused-vars
const { value, viewFormat: _viewFormat, editFormat: _editFormat, ...restProps } = this.props;
return (
<FilteredInput
ref={"filteredInput"}
{...restProps}
value={value}
filterValue={value => this.handleFilterValue(value)}
valueForView={value => this.handleValueForView(value)}
valueForEdit={value => this.handleValueForEdit(value)}
/>
);
}
}
|
JavaScript
| 0 |
@@ -606,16 +606,19 @@
xp = /%5E%5C
+-?%5C
s*%5Cd*(%5C.
|
4848df51d4895e7ef4a65a3074de91db3f78aed8
|
remove g in regex test
|
jquery.actual.js
|
jquery.actual.js
|
/*! Copyright 2012, Ben Lin (http://dreamerslab.com/)
* Licensed under the MIT License (LICENSE.txt).
*
* Version: 1.0.13
*
* Requires: jQuery 1.2.3 ~ 1.8.2
*/
;( function ( $ ){
$.fn.extend({
actual : function ( method, options ){
// check if the jQuery method exist
if( !this[ method ]){
throw '$.actual => The jQuery method "' + method + '" you called does not exist';
}
var defaults = {
absolute : false,
clone : false,
includeMargin : false
};
var configs = $.extend( defaults, options );
var $target = this.eq( 0 );
var fix, restore;
if( configs.clone === true ){
fix = function (){
var style = 'position: absolute !important; top: -1000 !important; ';
// this is useful with css3pie
$target = $target.
clone().
attr( 'style', style ).
appendTo( 'body' );
};
restore = function (){
// remove DOM element after getting the width
$target.remove();
};
}else{
var tmp = [];
var style = '';
var $hidden;
fix = function (){
// get all hidden parents
$hidden = $target.
parents().
andSelf().
filter( ':hidden' );
style += 'visibility: hidden !important; display: block !important; ';
if( configs.absolute === true ) style += 'position: absolute !important; ';
// save the origin style props
// set the hidden el css to be got the actual value later
$hidden.each( function (){
var $this = $( this );
// Save original style. If no style was set, attr() returns undefined
tmp.push( $this.attr( 'style' ));
$this.attr( 'style', style );
});
};
restore = function (){
// restore origin style values
$hidden.each( function ( i ){
var $this = $( this );
var _tmp = tmp[ i ];
if( _tmp === undefined ){
$this.removeAttr( 'style' );
}else{
$this.attr( 'style', _tmp );
}
});
};
}
fix();
// get the actual value with user specific methed
// it can be 'width', 'height', 'outerWidth', 'innerWidth'... etc
// configs.includeMargin only works for 'outerWidth' and 'outerHeight'
var actual = /(outer)/g.test( method ) ?
$target[ method ]( configs.includeMargin ) :
$target[ method ]();
restore();
// IMPORTANT, this plugin only return the value of the first element
return actual;
}
});
})( jQuery );
|
JavaScript
| 0.000004 |
@@ -2504,17 +2504,16 @@
(outer)/
-g
.test( m
|
fb7b84e0586b433aa620ce5890ef0d784f5e0c5e
|
fix answer agrees bug
|
lib/parser/answer.js
|
lib/parser/answer.js
|
const cheerio = require('cheerio')
const util = require('./util')
const urls = require('../urls')
const getAttr = util.getAttr
const getText = util.getText
const getData = util.getData
const toNum = util.toNum
module.exports = {
parseAnswersByVote,
parseAnswersByPage,
parseUserAnswers,
parseAnswer
}
function parseAnswersByVote(htmls) {
return htmls.map(parseAnswer)
}
function parseAnswersByPage(html) {
var answers = []
var $ = cheerio.load(html)
var items = $('#zh-question-answer-wrap .zm-item-answer')
for (var i = 0; i < items.length; i++) {
var answer = _parseAnswer($, $(items[i]))
answers.push(answer)
}
return answers
}
function parseUserAnswers(html) {
var answers = []
var $ = cheerio.load(html)
var items = $('#zh-profile-answer-list .zm-item-answer')
for (var i = 0; i < items.length; i++) {
var answer = _parseAnswer($, $(items[i]))
answers.push(answer)
}
return answers
}
function parseAnswer(html) {
var $ = cheerio.load(html)
var item = $('.zm-item-answer')
return _parseAnswer($, item)
}
function _parseAnswer($, item) {
var agreesEle = $('.zm-votebar .up .count', item)
var authorEle = $('.zm-item-answer-author-info .author-link', item)
var contentEle = $('> .zm-item-rich-text', item)
var answerEle = $('.zm-editable-content', contentEle)
if (!answerEle.length) {
var contentHtml = '<div id="custom-wrapper">' +
$('textarea.content', contentEle).html() + '</div>'
var $$ = cheerio.load(contentHtml)
$$('.answer-date-link-wrap').remove()
$$ = cheerio.load('<div id="custom-wrapper">' +
$$('#custom-wrapper').text() + '</div>')
answerEle = $$('#custom-wrapper')
}
var link = getAttr(authorEle, 'href')
var answer = {
id: getData(item, 'aid'),
token: getData(item, 'atoken'),
createdtime: toNum(getData(item, 'created')) * 1000,
agrees: toNum(getText(agreesEle)),
author: {
name: getText(authorEle),
uname: link.substring('/people/'.length),
link: urls.full(link)
},
resourceid: getData(contentEle, 'resourceid'),
link: urls.full(getData(contentEle, 'entry-url')),
content: getText(answerEle).trim(),
crawltime: Date.now()
}
return answer
}
|
JavaScript
| 0.001018 |
@@ -1188,21 +1188,18 @@
.zm-
-votebar .up .
+item-vote-
coun
@@ -2005,32 +2005,38 @@
es:
-toNum(getText(agreesEle)
+getData(agreesEle, 'votecount'
),%0A
|
bd402809283fe6e01c5f1a355be4f25f4eb679fd
|
Add file path and file content
|
lib/parser/parser.js
|
lib/parser/parser.js
|
'use babel'
var fs = require('fs');
var _ = require('lodash');
export default class Parser {
constructor() {
}
/*
let storeData = {
"md_act_get_by_event_type_service_id":{
"return":"integer",
"params": {
"in": [{"name":"m_event_type_service_id", "type":"integer"}],
}
},
"md_comm_type_get_by_name":{
"return":"record",
"params": {
"in": [{"name":"m_name", "type":"text"}],
"out": [
{"name":"m_name", "type":"text"},
{"name":"m_comm_type_id", "type":"integer"}
],
}
},
"md_et_get_by_nt_name_act_name_at_name":{
"return":"record",
"params": {
"in": [
{"name": "m_name_nt", "type":"text"},
{"name": "m_name_act", "type":"text"},
{"name": "m_name_at", "type":"text"}
],
"out": [
{"name": "m_event_type_id", "type":"integer"},
{"name": "m_notification_type_id", "type":"integer"},
{"name": "m_action_id", "type":"integer"},
{"name": "m_action_type_id", "type":"integer"},
{"name": "m_action_category_id", "type":"integer"},
{"name": "m_name_acc", "type":"text"}
]
}
}
};
*/
parseFunctions(basePath, callBack) {
functions = {};
var filesPath = Parser.getFiles(basePath);
_.map(filesPath, (filePath, index) => {
fs.readFile(filePath, 'utf8', function (err, fileContent){
functionData = Parser.parseFunction(fileContent);
functions[functionData.functionName] = functionData;
if (index === filesPath.length - 1) {
return callBack(functions);
}
});
});
}
static parseFunction(fileContent) {
parseFunctionRegex = /CREATE\s+(OR\s+REPLACE\s+)?FUNCTION\s+(\w+)\.([^(]*)([(\s+\w+,)='\[\]]*)\s+RETURNS\s+([(\s+\w+,)=\[\]]*)\s+AS/i;
var matches = fileContent.match(parseFunctionRegex);
var functionData = {
schema: matches[2],
functionName: matches[3],
params: Parser.parseParameters(matches[4]),
returnType: matches[5]
};
return functionData;
}
static parseParameters(paramsIn) {
var params = {"in":[], "out":[]};
var re = /\s*(INOUT|IN|OUT)?\s*(\w+)\s*(\w+)\s*([^,]*)/i;
paramsIn = paramsIn.trim().replace(/\)$/, '').replace(/^\(/, '');
var parameters = paramsIn.split(',');
parameters.forEach(function (value) {
if (value != null && value.length > 0) {
var matches = value.match(re);
var argmode = matches[1] == undefined ? 'IN' : matches[1];
var name = matches[2];
var type = matches[3];
var hasDefault = matches[4] != '';
if (argmode.toUpperCase().indexOf("IN") != -1) {
params['in'].push({"name": name, "type": type, "argmode": argmode, "default": hasDefault});
}
if (argmode.toUpperCase().indexOf("OUT") != -1) {
params['out'].push({"name": name, "type": type, "argmode": argmode, "default": hasDefault});
}
}
});
return params;
}
static getFiles(dir) {
var results = [];
var list = fs.readdirSync(dir)
list.forEach(function (file) {
file = dir + '/' + file
var stat = fs.statSync(file)
if (stat && stat.isDirectory()) {
results = results.concat(Parser.getFiles(file))
} else if (Parser.fileMustBeProcess(file)) {
results.push(file);
}
});
return results;
}
static fileMustBeProcess(filePath) {
var directories = ['functions'];
var extensions = ['sql'];
var pathArray = filePath.split("/");
var intersectionArray = _.intersection(pathArray, directories);
var extension = filePath.substr(filePath.lastIndexOf('.') + 1);
var validExtension = _.indexOf(extensions, extension) !== -1;
return intersectionArray.length > 0 && validExtension;
}
}
|
JavaScript
| 0 |
@@ -1428,16 +1428,104 @@
ntent);%0A
+ functionData%5B'path'%5D = filePath;%0A functionData%5B'content'%5D = fileContent;%0A
|
75554404f39a41b0eb8912e6f236b666acf36640
|
Add styling for select tag.
|
lib/periodic-view.js
|
lib/periodic-view.js
|
'use babel';
/* @flow */
import {$, View} from "space-pen";
import path from "path";
import sqlite3 from "sqlite3";
export default class PeriodicView extends View {
static content() {
this.div({class: "periodic"}, () => {
this.div({class: "structure periodic-tab"}, () => {
this.ul({class: "tables-list"});
this.div({class: "table-structure"}, () => {
this.table({class: "table-structure-table"});
});
});
this.div({class: "browser periodic-tab"}, () => {
this.div({class: "periodic-browser-options"}, () => {
this.select({class: "periodic-dropdown"});
this.button({class: "btn btn-primary"}, "Refresh");
});
this.div({class: "table-browser"}, () => {
this.table({class: "table-browser-table"});
});
});
});
}
initialize(filePath: string) {
this.filePath = filePath;
this.fileName = path.basename(this.filePath);
this.selectedDataElts = [];
this.selectedStructureElts = [];
this.openFile();
this.find("button").click(() => { this.refreshData(); });
}
destroy() {
this.empty();
}
getTitle() { return `Periodic Table - ${this.fileName}`;}
tableNameForId(id: number): string {
for (let table of this.tables)
if (id.toString() === table.rootpage.toString())
return table.name;
return "";
}
refreshData() {
let tableName: string = this.tableNameForId(this.find("select.periodic-dropdown").val());
this.db.all(`SELECT * FROM ${tableName}`, (err, contents) => {
if (err || !contents)
return;
let titles = [];
if (contents.length > 0) {
for (let p in contents[0])
titles.push(p);
this.createTable(contents, "browser", titles);
}
});
}
openFile() {
this.db = new sqlite3.Database(this.filePath, sqlite3.OPEN_READONLY);
this.db.all("SELECT * FROM sqlite_master WHERE type='table'", {}, (err, rows) => {
this.tables = rows;
for (let row of rows) {
this.find("ul.tables-list").append($("<li></li>").text(row.name).click((e) => { this.onClick(e); this.loadStructureTable(e); }));
this.find("select.periodic-dropdown").append($("<option></option>").val(row.rootpage).text(row.name));
this.find("select.periodic-dropdown").change((e) => { this.refreshData(); });
}
});
}
onClick(e: any) {
console.log(this.selectedStructureElts);
e.preventDefault();
e.target.classList.add("selected");
if (e.target.classList.contains("browser")) {
for (let elt of this.selectedDataElts)
elt.classList.remove("selected");
this.selectedDataElts = [ e.target ];
}
else {
for (let elt of this.selectedStructureElts)
elt.classList.remove("selected");
this.selectedStructureElts = [ e.target ];
}
}
loadStructureTable(e: any) {
this.db.all(`PRAGMA table_info(${e.target.innerText})`, {}, (err, rows) => {
if (err)
return;
this.createTable(rows);
});
}
createTable(rows:Array<any>=[], loc?:string="structure", titles?:Array<string>) {
let table = this.find(`table.table-${loc}-table`);
table.empty();
let tr = $("<tr></tr>");
titles = typeof titles !== 'undefined' ? titles : ["cid", "Name", "Type", "Not null", "Default value", "Pk"];
for (let title of titles)
tr.append($("<th></th>").text(title));
table.append(tr);
for (let row of rows) {
let rowElt = $("<tr></tr>");
for (let property in row)
rowElt.append($("<td></td>").text(typeof row[property] !== 'undefined' ? row[property] : "Null").click((e) => { this.onClick(e); }).addClass(loc));
table.append(rowElt);
}
}
}
|
JavaScript
| 0 |
@@ -590,21 +590,115 @@
his.
-select(%7Bclass
+div(%7Bclass: %22settings-view select-container%22%7D, () =%3E %7B%0A this.select(%7Bclass: %22form-control%22, %22id%22
: %22p
@@ -709,21 +709,21 @@
dic-
-dropdown
+select
%22%7D);%0A
+
@@ -776,24 +776,38 @@
%22Refresh%22);%0A
+ %7D);%0A
%7D);%0A
@@ -1565,33 +1565,33 @@
his.find(%22select
-.
+#
periodic-dropdow
@@ -1583,24 +1583,22 @@
eriodic-
-dropdown
+select
%22).val()
@@ -2290,33 +2290,33 @@
his.find(%22select
-.
+#
periodic-dropdow
@@ -2308,24 +2308,22 @@
eriodic-
-dropdown
+select
%22).appen
@@ -2407,17 +2407,17 @@
(%22select
-.
+#
periodic
@@ -2421,16 +2421,14 @@
dic-
-dropdown
+select
%22).c
|
9d9abbf5ca332dfe7b752dbaedf23f018a27ce4f
|
Fix sidebar collapse states, fixes #3
|
Wikipedia_ToggleSidebar/wikipedia_toggle-sidebar.user.js
|
Wikipedia_ToggleSidebar/wikipedia_toggle-sidebar.user.js
|
// ==UserScript==
// @name Wikipedia - Toggle Sidebar
// @description Adds a small button to hide or show the sidebar. Makes reading easier.
// @version 0.2.1
// @author Arthur Hammer
// @namespace https://github.com/arthurhammer
// @license MIT
// @homepage https://github.com/arthurhammer/userscripts/tree/master/Wikipedia_ToggleSidebar
// @updateURL https://github.com/arthurhammer/userscripts/raw/master/Wikipedia_ToggleSidebar/wikipedia_toggle-sidebar.user.js
// @downloadURL https://github.com/arthurhammer/userscripts/raw/master/Wikipedia_ToggleSidebar/wikipedia_toggle-sidebar.user.js
// @match *.wikipedia.org/wiki/*
// @run-at document-body
// @grant none
// ==/UserScript==
(function() {
var prefs = {
hiddenByDefault: true
};
var css = '\
body { \
background-color: white; \
} \
#content { \
border-color: #ddd; \
border-left-width: 0; \
margin-left: 5em; \
margin-right: 5em; \
} \
#content.with-sidebar { \
margin-left: 10em; \
margin-right: 0em; \
} \
#mw-panel { \
display: none; \
} \
#sidebar-toggle { \
position: absolute; \
top: 0; \
left: 5; \
z-index: 999; \
padding: 10px; \
font-size: 20px; \
opacity: 0.5; \
cursor: pointer; \
transition: all 0.1s; \
} \
#sidebar-toggle:hover { \
font-size: 23px; \
opacity: 1; \
top: -2px; \
}';
function rotate(element, degrees) {
var rotation = 'rotate(' + degrees + 'deg)';
element.style.WebkitTransform = rotation;
element.style.transform = rotation;
}
function addCSS(css) {
var style = document.createElement('style');
style.textContent = css;
document.head.appendChild(style);
}
function addSidebarToggle() {
if (!document.body || document.getElementById('sidebar-toggle')) return;
var sidebarToggle = document.createElement('div');
sidebarToggle.id = 'sidebar-toggle';
sidebarToggle.title = 'Toggle Sidebar';
sidebarToggle.textContent = '▸';
sidebarToggle.addEventListener('click', function() {
var sidebar = document.getElementById('mw-panel');
var mainContent = document.getElementById('content');
rotate(sidebarToggle, mainContent.classList.contains('with-sidebar') ? 0 : 90);
mainContent.classList.toggle('with-sidebar');
sidebar.style.display =
(sidebar.style.display && sidebar.style.display === 'none') ? 'block' : 'none';
});
if (! prefs.hiddenByDefault) sidebarToggle.click();
document.body.insertBefore(sidebarToggle, document.body.firstElementChild);
}
document.addEventListener('DOMContentLoaded', addSidebarToggle);
addCSS(css);
// DOMContentLoaded can fire before the listener was installed. Double-check.
addSidebarToggle();
})();
|
JavaScript
| 0 |
@@ -164,17 +164,17 @@
0.2.
-1
+2
%0A// @aut
@@ -2728,16 +2728,17 @@
(
+!
sidebar.
@@ -2755,10 +2755,10 @@
lay
-&&
+%7C%7C
sid
|
f602bcc896f92e8953a74c801e05bd9a3febc8a8
|
clean up loging
|
lib/plugins/bgnow.js
|
lib/plugins/bgnow.js
|
'use strict';
var _ = require('lodash');
var times = require('../times');
var offset = times.mins(2.5).msecs;
function init() {
var bgnow = {
name: 'bgnow'
, label: 'BG Now'
, pluginType: 'pill-primary'
};
bgnow.setProperties = function setProperties (sbx) {
sbx.offerProperty('bgnow', function setBGNow ( ) {
var buckets = bgnow.fillBuckets(sbx);
var property = bgnow.analyzeBuckets(buckets, sbx);
return property;
});
};
bgnow.fillBuckets = function fillBuckets (sbx, opts) {
var bucketCount = (opts && opts.bucketCount) || 4;
var bucketMins = (opts && opts.bucketMins) || 5;
var bucketMsecs = times.mins(bucketMins).msecs;
var lastSGVMills = sbx.lastSGVMills();
var buckets = _.times(bucketCount, function createBucket (index) {
var fromMills = lastSGVMills + offset - (index * bucketMsecs);
return {
index: index
, fromMills: fromMills
, toMills: fromMills + bucketMsecs
, sgvs: [ ]
};
});
_.takeRightWhile(sbx.data.sgvs, function addToBucket (sgv) {
//if in the future, return true and keep taking right
if (sgv.mills > sbx.time) {
return true;
}
var bucket = _.find(buckets, function containsSGV (bucket) {
return sgv.mills >= bucket.fromMills && sgv.mills <= bucket.toMills;
});
if (bucket) {
bucket.sgvs.push(sgv);
}
return bucket;
});
_.forEach(buckets, bgnow.analyzeBucket);
// _.forEach(buckets, function log (bucket) {
// console.info('>>>bucket', bucket);
// });
return buckets;
};
function notError (entry) {
return entry.mgdl > 39; //TODO maybe lower instead of expecting dexcom?
}
function isError (entry) {
return entry.mgdl < 39;
}
bgnow.analyzeBucket = function analyzeBucket (bucket) {
if (_.isEmpty(bucket.sgvs)) {
bucket.isEmpty = true;
return;
}
var details = { };
var mean = _.chain(bucket.sgvs)
.filter(notError)
.meanBy('mgdl')
.value();
if (_.isNumber(mean)) {
details.mean = mean;
}
var mostRecent = _.chain(bucket.sgvs)
.filter(notError)
.maxBy('mills')
.value();
var mills = mostRecent && mostRecent.mills;
if (_.isNumber(mills)) {
details.mills = mills;
}
var errors = _.filter(bucket.sgvs, isError);
if (!_.isEmpty(errors)) {
details.errors = errors;
}
_.merge(bucket, details);
};
bgnow.analyzeBuckets = function analyzeBuckets(buckets, sbx) {
var property = { };
var recent = _.find(buckets, function notEmpty(bucket) {
return bucket && !bucket.isEmpty;
});
if (_.isObject(recent)) {
property.recent = recent;
var previous = _.chain(buckets).find(function afterFirstNotEmpty(bucket) {
return bucket.mills < recent.mills && !bucket.isEmpty;
}).value();
if (_.isObject(previous)) {
property.previous = previous;
}
}
property.buckets = buckets;
var delta = bgnow.calcDelta(property, sbx);
if (!_.isEmpty(delta)) {
property.delta = delta;
}
return property;
};
bgnow.calcDelta = function calcDelta (property, sbx) {
if (_.isEmpty(property.recent)) {
console.info('>>>all buckets are empty', property.buckets);
return null;
}
if (_.isEmpty(property.previous)) {
console.info('>>>next bucket not found', property.buckets);
return null;
}
console.info('found buckets, last:', property.recent, 'previous:', property.previous);
var delta = {
absolute: property.recent.mean - property.previous.mean
, elapsedMins: (property.recent.mills - property.previous.mills) / times.min().msecs
};
delta.interpolated = delta.elapsedMins > 9;
delta.mean5MinsAgo = delta.interpolated ?
property.recent.mean - delta.absolute / delta.elapsedMins * 5 : property.recent.mean - delta.absolute;
delta.mgdl = Math.round(property.recent.mean - delta.mean5MinsAgo);
delta.scaled = sbx.settings.units === 'mmol' ?
sbx.roundBGToDisplayFormat(sbx.scaleMgdl(property.recent.mean) - sbx.scaleMgdl(delta.mean5MinsAgo)) : delta.mgdl;
delta.display = (delta.scaled >= 0 ? '+' : '') + delta.scaled;
return delta;
};
bgnow.updateVisualisation = function updateVisualisation (sbx) {
var prop = sbx.properties.bgnow && sbx.properties.bgnow.delta;
var info = [];
var display = prop && prop.display;
if (prop && prop.interpolated) {
display += ' *';
info.push({label: 'Elapsed Time', value: Math.round(prop.elapsedMins) + ' mins'});
info.push({label: 'Absolute Delta', value: sbx.roundBGToDisplayFormat(sbx.scaleMgdl(prop.absolute)) + ' ' + sbx.unitsLabel});
info.push({label: 'Interpolated', value: sbx.roundBGToDisplayFormat(sbx.scaleMgdl(prop.mean5MinsAgo)) + ' ' + sbx.unitsLabel});
}
sbx.pluginBase.updatePillText({
name: 'delta'
, label: 'BG Delta'
, pluginType: 'pill-major'
, pillFlip: true
}, {
value: display
, label: sbx.unitsLabel
, info: info
});
};
return bgnow;
}
module.exports = init;
|
JavaScript
| 0 |
@@ -1504,111 +1504,8 @@
);%0A%0A
-// _.forEach(buckets, function log (bucket) %7B%0A// console.info('%3E%3E%3Ebucket', bucket);%0A// %7D);%0A%0A
@@ -3203,19 +3203,16 @@
e.info('
-%3E%3E%3E
all buck
@@ -3336,15 +3336,16 @@
fo('
-%3E%3E%3Enext
+previous
buc
@@ -3357,16 +3357,39 @@
ot found
+, not calculating delta
', prope
@@ -3432,100 +3432,8 @@
%7D%0A%0A
- console.info('found buckets, last:', property.recent, 'previous:', property.previous);%0A%0A
|
dc67806505e325d5747a98247c75c0ca672701aa
|
add differenceFromLast position to drag event
|
js/Event/drag.js
|
js/Event/drag.js
|
/*
"Drag" event proxy (1+ fingers).
----------------------------------------------------
CONFIGURE: maxFingers, position.
----------------------------------------------------
Event.add(window, "drag", function(event, self) {
console.log(self.gesture, self.state, self.start, self.x, self.y, self.bbox);
});
*/
if (typeof(Event) === "undefined") var Event = {};
if (typeof(Event.proxy) === "undefined") Event.proxy = {};
Event.proxy = (function(root) { "use strict";
root.dragElement = function(that, event) {
root.drag({
event: event,
target: that,
position: "move",
listener: function(event, self) {
that.style.left = self.x + "px";
that.style.top = self.y + "px";
Event.prevent(event);
}
});
};
root.drag = function(conf) {
conf.gesture = "drag";
conf.onPointerDown = function (event) {
if (root.pointerStart(event, self, conf)) {
if (!conf.monitor) {
Event.add(conf.doc, "mousemove", conf.onPointerMove);
Event.add(conf.doc, "mouseup", conf.onPointerUp);
}
}
// Process event listener.
conf.onPointerMove(event, "down");
};
conf.onPointerMove = function (event, state) {
if (!conf.tracker) return conf.onPointerDown(event);
var bbox = conf.bbox;
var touches = event.changedTouches || root.getCoords(event);
var length = touches.length;
for (var i = 0; i < length; i ++) {
var touch = touches[i];
var identifier = touch.identifier || Infinity;
var pt = conf.tracker[identifier];
// Identifier defined outside of listener.
if (!pt) continue;
pt.pageX = touch.pageX;
pt.pageY = touch.pageY;
// Record data.
self.state = state || "move";
self.identifier = identifier;
self.start = pt.start;
self.fingers = conf.fingers;
if (conf.position === "relative") {
self.x = (pt.pageX + bbox.scrollLeft - pt.offsetX) * bbox.scaleX;
self.y = (pt.pageY + bbox.scrollTop - pt.offsetY) * bbox.scaleY;
} else {
self.x = (pt.pageX - pt.offsetX);
self.y = (pt.pageY - pt.offsetY);
}
///
conf.listener(event, self);
}
};
conf.onPointerUp = function(event) {
// Remove tracking for touch.
if (root.pointerEnd(event, self, conf, conf.onPointerMove)) {
if (!conf.monitor) {
Event.remove(conf.doc, "mousemove", conf.onPointerMove);
Event.remove(conf.doc, "mouseup", conf.onPointerUp);
}
}
};
// Generate maintenance commands, and other configurations.
var self = root.pointerSetup(conf);
// Attach events.
if (conf.event) {
conf.onPointerDown(conf.event);
} else { //
Event.add(conf.target, "mousedown", conf.onPointerDown);
if (conf.monitor) {
Event.add(conf.doc, "mousemove", conf.onPointerMove);
Event.add(conf.doc, "mouseup", conf.onPointerUp);
}
}
// Return this object.
return self;
};
Event.Gesture = Event.Gesture || {};
Event.Gesture._gestureHandlers = Event.Gesture._gestureHandlers || {};
Event.Gesture._gestureHandlers.drag = root.drag;
return root;
})(Event.proxy);
|
JavaScript
| 0 |
@@ -1741,16 +1741,202 @@
tion ===
+ %22differenceFromLast%22) %7B%0A%09%09%09%09self.x = (pt.pageX - pt.offsetX);%0A%09%09%09%09self.y = (pt.pageY - pt.offsetY);%0A%09%09%09%09pt.offsetX = pt.pageX;%0A%09%09%09%09pt.offsetY = pt.pageY;%0A%09%09%09%7D else if (conf.position ===
%22relati
@@ -2000,22 +2000,8 @@
etX)
- * bbox.scaleX
;%0A%09%09
@@ -2055,22 +2055,8 @@
etY)
- * bbox.scaleY
;%0A%09%09
|
8ef94e4941bdfe42ff570388c0d8b9d2ca8cdff7
|
Refactor Group#match
|
lib/pointer/group.js
|
lib/pointer/group.js
|
'use strict';
var getSortedKeys = require('./common').getSortedKeys;
////////////////////////////////////////////////////////////////////////////////
function Group() {
this.__routes__ = {};
this.__prefixes__ = [];
}
// Group#push(route) -> Void
// - route (Route):
//
// Adds `route` to the group.
//
Group.prototype.push = function push(route) {
var prefix = '';
if ('string' === route.__ast__[0].type) {
prefix = route.__ast__[0].string;
}
if (!this.__routes__[prefix]) {
this.__routes__[prefix] = [];
}
this.__routes__[prefix].push(route);
this.__prefixes__ = getSortedKeys(this.__routes__);
};
// Group#match(path) -> Object|Void
// - path (String):
//
// Returns first matching route data.
//
Group.prototype.match = function match(path) {
var self = this,
prefix,
prefixIndex,
prefixCount,
route,
routeIndex,
routeCount,
result;
for (prefixIndex = 0, prefixCount = self.__prefixes__.length;
prefixIndex < prefixCount;
prefixIndex += 1) {
prefix = self.__prefixes__[prefixIndex];
// Match prefix. If not - go on with next prefix.
if (prefix !== path.slice(0, prefix.length)) {
continue;
}
// Walk over routes by prefix and return a first matched if any.
for (routeIndex = 0, routeCount = self.__routes__[prefix].length;
routeIndex < routeCount;
routeIndex += 1) {
route = self.__routes__[prefix][routeIndex];
result = route.match(path);
if (result) {
return result;
}
}
}
// Not found.
return null;
};
// MODULE EXPORTS //////////////////////////////////////////////////////////////
module.exports = Group;
|
JavaScript
| 0 |
@@ -1152,22 +1152,17 @@
if (
-prefix
+0
!== pat
@@ -1167,30 +1167,22 @@
ath.
-slice(0, prefix.length
+indexOf(prefix
)) %7B
|
6498610aea70f42487b17d08a35417b553e9a26f
|
remove redundant
|
lib/postcssToCsso.js
|
lib/postcssToCsso.js
|
var parse = require('csso').parse;
function isDecl(node) {
return node.type === 'decl';
}
function appendNodes(cssoNode, postcssNode) {
cssoNode.push.apply(cssoNode, postcssNode.nodes.map(walk));
return cssoNode;
}
function walk(node) {
function parseToCsso(str, scope, node) {
var cssoNode = parse(str, scope, {
needInfo: true
});
cssoNode[0] = getInfo(node);
return cssoNode;
}
function getInfo(node) {
var filename = node.source.input.file || node.source.input.id;
return {
source: filename,
line: node.source.start.line,
column: node.source.start.column,
postcssNode: node
};
}
switch (node.type) {
case 'root':
return appendNodes([getInfo(node), 'stylesheet'], node);
case 'rule':
return [getInfo(node), 'ruleset',
node.selector ? parseToCsso(node.selector, 'selector', node) : [getInfo(node), 'selector'],
appendNodes([{}, 'block'], node)
];
case 'atrule':
var atruleStr = '@' + node.name +
(node.raws.afterName || ' ') +
node.params +
(node.raws.between || '');
if (node.nodes) {
if (node.nodes.some(isDecl)) {
atruleStr += '{}';
} else {
atruleStr += '{a{}}';
}
}
var cssoNode = parseToCsso(
atruleStr,
'atruler',
node
);
if (node.nodes) {
appendNodes(cssoNode[cssoNode.length - 1], node);
}
return cssoNode;
case 'decl':
return parseToCsso(
(node.raws.before || '').trimLeft() +
node.prop +
(node.raws.between || ':') +
node.value +
(node.important ? '!important' : ''),
'declaration',
node
);
case 'comment':
return [getInfo(node), 'comment', node.raws.left + node.text + node.raws.right];
}
}
module.exports = function postcssToCsso(node) {
return walk(node);
};
|
JavaScript
| 0.999999 |
@@ -191,20 +191,29 @@
des.map(
-walk
+postcssToCsso
));%0A
@@ -241,20 +241,29 @@
unction
-walk
+postcssToCsso
(node) %7B
@@ -902,30 +902,63 @@
return %5B
-getInfo(node),
+%0A getInfo(node),%0A
'rulese
@@ -1206,127 +1206,26 @@
me +
-%0A (node.raws.afterName %7C%7C
' '
-)
+
-%0A node.params +%0A (node.raws.between %7C%7C '')
+ node.params
;%0A%0A
@@ -1849,69 +1849,14 @@
op +
-%0A (node.raws.between %7C%7C
':'
-)
+
-%0A
nod
@@ -2035,33 +2035,82 @@
rn %5B
-getInfo(node), 'comment',
+%0A getInfo(node),%0A 'comment',%0A
nod
@@ -2150,16 +2150,29 @@
ws.right
+%0A
%5D;%0A %7D
@@ -2191,25 +2191,16 @@
xports =
- function
postcss
@@ -2209,39 +2209,6 @@
Csso
-(node) %7B%0A return walk(node);%0A%7D
;%0A
|
30ff77291bbe958f4d1a080ad781dd71bac0d9a0
|
Update ocRolesService.UserIsAuthorize to support RoleGroups
|
src/app/common/services/oc-roles/oc-roles.js
|
src/app/common/services/oc-roles/oc-roles.js
|
angular.module('orderCloud')
.factory('ocRolesService', OrderCloudRolesService)
.provider('ocRoles', OrderCloudRolesProvider)
;
function OrderCloudRolesService($window, OrderCloudSDK) {
var service = {
Set: _set,
Get: _get,
Remove: _remove,
UserIsAuthorized: _userIsAuthorized
};
var roles;
function base64Decode(string) {
var output = string.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0: { break; }
case 2: { output += '=='; break; }
case 3: { output += '='; break; }
default: {
console.warn('Illegal base64url string');
return;
}
}
return $window.decodeURIComponent(escape($window.atob(output))); //polyfill https://github.com/davidchambers/Base64.js
}
//Parse roles array from token and store as local service variable
function _set(token) {
if (!token) return;
var tokenParts = token.split('.');
if (tokenParts.length != 3) {
console.warn('ocRoles', 'Token is not valid');
return;
}
var decodedToken = base64Decode(tokenParts[1]);
if (!decodedToken) {
console.warn('ocRoles', 'Cannot decode token');
return;
}
var decodedTokenObject = JSON.parse(decodedToken);
roles = decodedTokenObject.role;
if (typeof roles == 'string') roles = [roles];
return roles || [];
}
//Returns local service variable or obtains roles again from token
function _get() {
return roles || _set(OrderCloudSDK.GetToken());
}
//Removes local service variable
function _remove() {
roles = null;
}
//Returns boolean whether user's claimed roles cover a required array of roles
function _userIsAuthorized(requiredRoles, any) {
var userRoles = _get();
if (!userRoles) return;
if (userRoles.indexOf('FullAccess') > -1) {
return true;
}
else if (any) {
return _.intersection(requiredRoles, userRoles).length > 0;
}
else {
return _.difference(requiredRoles, userRoles).length == 0;
}
}
return service;
}
function OrderCloudRolesProvider() {
var roleGroups = {};
return {
$get: function() {
return {
GetRoleGroups: function() {
return roleGroups;
}
};
},
AddRoleGroup: function(roleGroup) {
if (!roleGroup.Name) throw 'ocRoles: RoleGroup must have a Name value';
if (!roleGroup.Roles || !roleGroup.Roles.length) throw 'ocRoles: RoleGroup must have Roles';
if (!angular.isArray(roleGroup.Roles)) throw 'ocRoles: RoleGroup Roles must be an array';
if (!roleGroup.Type || ['All', 'Any'].indexOf(roleGroup.Type) == -1) throw 'ocRoles: RoleGroup Type must be \'All\' or \'Any\'';
roleGroups[roleGroup.Name] = roleGroup;
}
};
}
|
JavaScript
| 0 |
@@ -170,16 +170,25 @@
$window,
+ ocRoles,
OrderCl
@@ -1852,17 +1852,8 @@
r a
-required
arra
@@ -1862,16 +1862,360 @@
of roles
+ and/or Role Groups%0A //Role Groups use the group's Type setting. Individual roles use the any parameter when combined%0A //Ex: ocRolesService.UserIsAuthorized(%5B'CategoryReader', 'CatalogReader', 'RoleGroupA'%5D, any);%0A //Evaluates whether user is authorized for RoleGroupA's configuration AND has either CategoryReader or CatalogReader
%0A fun
@@ -2239,27 +2239,23 @@
orized(r
-equiredRole
+oleItem
s, any)
@@ -2403,32 +2403,33 @@
;%0A %7D%0A
+%0A
else if (any
@@ -2420,24 +2420,77 @@
-else
+function analyzeRoles(roles, hasAny) %7B%0A
if (
-a
+hasA
ny) %7B%0A
+
@@ -2520,24 +2520,16 @@
ection(r
-equiredR
oles, us
@@ -2558,28 +2558,24 @@
- %7D%0A
+%7D
else %7B%0A
@@ -2570,16 +2570,20 @@
else %7B%0A
+
@@ -2611,55 +2611,625 @@
ce(r
-equiredRoles, userRoles).length == 0;%0A %7D
+oles, userRoles).length == 0;%0A %7D%0A %7D%0A%0A var authorized = true;%0A var roleGroups = ocRoles.GetRoleGroups();%0A var roles = %5B%5D;%0A %0A angular.forEach(roleItems, function(item) %7B%0A if (roleGroups%5Bitem%5D) %7B%0A var roleGroup = roleGroups%5Bitem%5D;%0A authorized = analyzeRoles(roleGroup.Roles, roleGroup.Type == 'Any');%0A %7D %0A else %7B%0A roles.push(item);%0A %7D%0A %7D);%0A%0A if (authorized && roles.length) %7B%0A authorized = analyzeRoles(roles, any);%0A %7D%0A%0A return authorized;
%0A
@@ -3288,16 +3288,21 @@
rovider(
+scope
) %7B%0A
@@ -3644,16 +3644,157 @@
value';%0A
+ if (scope.indexOf(roleGroup.Name) %3E -1) throw 'ocRole: RoleGroup Name cannot match an OrderCloud role name: ' + roleGroup.Name;%0A
|
41bf9741ffb4c18851ae2383d511562dde604541
|
rearrange initialisation
|
examples/basic-site-integration-overlay/src/index.js
|
examples/basic-site-integration-overlay/src/index.js
|
import React from "react";
import ReactDOM from "react-dom";
import Analytics from "sajari-react/pipeline/analytics";
import { State } from "sajari-react/pipeline/state";
import loaded from "./loaded";
import Overlay from "./Overlay";
import InPage from "./InPage";
import SearchResponse from "./SearchResponse";
import stateProxy from "./stateProxy";
import "./styles.css";
const ESCAPE_KEY_CODE = 27;
const _state = State.default();
const error = message => {
if (console && console.error) {
console.error(message);
}
};
const checkConfig = () => {
const config = window._sjui.config;
if (!config) {
error('global value "window._sjui.config" not found');
return false;
}
if (!config.project) {
error("'project' not set in config");
return false;
}
if (!config.collection) {
error("'collection' not set in config");
return false;
}
if (!config.pipeline) {
error("'pipeline' not set in config");
return false;
}
return true;
};
const initialiseStateValues = (config, firstTime) => {
let initialValues = {};
// Only include initial values the first time App is initialise0d
if (config.initialValues && firstTime) {
initialValues = config.initialValues;
}
const tabValues = {};
// Set the initial tab filter
if (config.tabFilters && config.tabFilters.defaultTab) {
config.tabFilters.tabs.forEach(t => {
if (t.title === config.tabFilters.defaultTab) {
tabValues.filter = t.filter;
}
});
}
const userValues = config.values;
const combinedValues = {
...initialValues,
...tabValues,
...userValues
};
const isQueryValueSet = Boolean(combinedValues.q);
_state.setValues(combinedValues, isQueryValueSet);
return isQueryValueSet;
};
const initOverlay = config => {
const active = initialiseStateValues(config, true);
const setOverlayControls = controls => {
const show = () => {
document.getElementsByTagName("body")[0].style.overflow = "hidden";
initialiseStateValues(config, false);
controls.show();
};
const hide = () => {
document.getElementsByTagName("body")[0].style.overflow = "";
_state.reset();
controls.hide();
};
window._sjui.overlay.show = show;
window._sjui.overlay.hide = hide;
return { show, hide };
};
// Create a container to render the overlay into
const overlayContainer = document.createElement("div");
overlayContainer.id = "sj-overlay-holder";
document.body.appendChild(overlayContainer);
// Set up global overlay values
document.addEventListener("keydown", e => {
if (e.keyCode === ESCAPE_KEY_CODE) {
window._sjui.overlay.hide();
}
});
ReactDOM.render(
<Overlay
config={config}
active={active}
setOverlayControls={setOverlayControls}
/>,
overlayContainer
);
};
const initInPage = config => {
initialiseStateValues(config, true);
ReactDOM.render(<InPage config={config} />, config.attachSearchBox);
ReactDOM.render(
<SearchResponse config={config} />,
config.attachSearchResponse
);
};
const initInterface = () => {
if (!checkConfig()) {
return;
}
const config = window._sjui.config;
const noOverlay = () => error("no overlay exists");
window._sjui.overlay = { show: noOverlay, hide: noOverlay };
window._sjui.state = stateProxy;
_state.setProject(config.project);
_state.setCollection(config.collection);
_state.setPipeline(config.pipeline);
if (!config.disableGA) {
new Analytics("default");
}
if (config.overlay) {
initOverlay(config);
return;
}
if (config.attachSearchBox && config.attachSearchResponse) {
initInPage(config);
return;
}
error(
"no render mode found, need to specify either overlay or attachSearchBox and attachSearchResponse in config"
);
};
loaded(window, initInterface);
|
JavaScript
| 0.00126 |
@@ -995,31 +995,24 @@
%0A%0Aconst
-initialiseState
+combined
Values =
@@ -1494,45 +1494,8 @@
%7D%0A%0A
- const userValues = config.values;%0A%0A
co
@@ -1568,13 +1568,16 @@
...
-userV
+config.v
alue
@@ -1587,231 +1587,68 @@
%7D;%0A
-%0A
-const isQueryValueSet = Boolean(combinedValues.q);%0A _state.setValues(combinedValues, isQueryValueSet);%0A return isQueryValueSet;%0A%7D;%0A%0Aconst initOverlay = config =%3E %7B%0A const active = initialiseStateValues(config, true);%0A
+return combinedValues;%0A%7D;%0A%0Aconst initOverlay = config =%3E %7B
%0A c
@@ -1701,24 +1701,35 @@
nst show = (
+values = %7B%7D
) =%3E %7B%0A
@@ -1807,44 +1807,73 @@
-initialiseState
+_state.setValues(combined
Values(
+%7B ...
config,
+ ...values %7D,
false)
+)
;%0A
@@ -2556,22 +2556,16 @@
%3COverlay
-%0A
config=
@@ -2576,36 +2576,8 @@
fig%7D
-%0A active=%7Bactive%7D%0A
set
@@ -2612,20 +2612,16 @@
ontrols%7D
-%0A
/%3E,%0A
@@ -2646,82 +2646,255 @@
);
-%0A%7D;
%0A%0A
+
const
-initInPage = config =%3E %7B%0A initialiseStateValues(config, true);
+values = combinedValues(config, true);%0A const query = Boolean(values.q);%0A if (query) %7B%0A _state.setValues(values, true);%0A window._sjui.overlay.show();%0A %7D else %7B%0A _state.setValues(values);%0A %7D%0A%7D;%0A%0Aconst initInPage = config =%3E %7B
%0A R
@@ -3052,24 +3052,110 @@
esponse%0A );
+%0A%0A const values = combinedValues(config, true);%0A _state.setValues(values, values.q);
%0A%7D;%0A%0Aconst i
|
2617b481eabeff7bdf2d4c1f3cd6fd88d3752eb8
|
Move to single line Components declar.
|
bootstrap.js
|
bootstrap.js
|
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
Cu.import('resource://gre/modules/Services.jsm');
const EXAMPLE_URI = 'http://rss.cnn.com/rss/cnn_topstories.rss';
var menuID;
// TODO: Not this.
function log(s) { Services.console.logStringMessage(s); }
function replaceDocWithFeed(window, feedURI) {
feedURI = feedURI || EXAMPLE_URI;
// TODO: Get results well.
parseFeed(feedURI, function (title, entryText) {
let doc = window.BrowserApp.selectedBrowser.contentDocument;
doc.body.innerHTML = '<html><body><h1>' + title + '</h1>' + entryText + '</body></html>';
});
}
function parseFeed(rssURL, onFinish) {
// via mfinkle.
let listener = {
handleResult: function handleResult(feedResult) {
//Services.console.logStringMessage('VERSION: ' + feedResult.version);
let feedDoc = feedResult.doc;
let feed = feedDoc.QueryInterface(Ci.nsIFeed);
if (feed.items.length == 0)
return;
//Services.console.logStringMessage('FEED TITLE: ' + feed.title.plainText());
log('Feed received with ' + feed.items.length + ' items.');
let entries = [];
for (let i = 0; i < feed.items.length; ++i) {
let entry = feed.items.queryElementAt(i, Ci.nsIFeedEntry);
entry.QueryInterface(Ci.nsIFeedContainer);
entries.push(entry.summary.plainText());
//Services.console.logStringMessage('SUMMARY: ' + entry.summary.plainText());
}
onFinish(feed.title.plainText(), entries.join('\n\n'));
}
};
let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1'].createInstance(Ci.nsIXMLHttpRequest);
xhr.open('GET', rssURL, true);
xhr.overrideMimeType('text/xml');
xhr.addEventListener('load', (function () {
if (xhr.status == 200) {
let processor = Cc['@mozilla.org/feed-processor;1'].createInstance(Ci.nsIFeedProcessor);
processor.listener = listener;
let uri = Services.io.newURI(rssURL, null, null);
processor.parseFromString(xhr.responseText, uri);
}
}), false);
xhr.send(null);
}
function loadIntoWindow(window) {
if (!window) { return; }
// When button clicked, read for feeds, "subscribe", open HTML page?
// TODO: Get feeds from page.
menuID = window.NativeWindow.menu.add({
name: 'Replace doc w/ feed contents',
icon: null,
callback: function () { replaceDocWithFeed(window); }
});
}
function unloadFromWindow(window) {
if (!window) { return; }
window.NativeWindow.menu.remove(menuID);
menuID = null;
}
function install(aData, aReason) {}
function uninstall(aData, aReason) {}
// via https://developer.mozilla.org/en-US/Add-ons/Firefox_for_Android/Initialization_and_Cleanup:
var windowListener = {
onOpenWindow: function (aWindow) {
// Wait for the window to finish loading
let domWindow = aWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
domWindow.addEventListener('load', function onLoad() {
domWindow.removeEventListener('load', onLoad, false);
loadIntoWindow(domWindow);
}, false);
},
onCloseWindow: function (aWindow) {},
onWindowTitleChange: function (aWindow, aTitle) {}
};
function startup(aData, aReason) {
let wm = Cc['@mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
// Load into any existing windows
let windows = wm.getEnumerator('navigator:browser');
while (windows.hasMoreElements()) {
let domWindow = windows.getNext().QueryInterface(Ci.nsIDOMWindow);
loadIntoWindow(domWindow);
}
// Load into any new windows
wm.addListener(windowListener);
}
function shutdown(aData, aReason) {
// When the application is shutting down we normally don't have to clean
// up any UI changes made
if (aReason == APP_SHUTDOWN)
return;
let wm = Cc['@mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
// Stop listening for new windows
wm.removeListener(windowListener);
// Unload from any existing windows
let windows = wm.getEnumerator('navigator:browser');
while (windows.hasMoreElements()) {
let domWindow = windows.getNext().QueryInterface(Ci.nsIDOMWindow);
unloadFromWindow(domWindow);
}
}
|
JavaScript
| 0 |
@@ -3,75 +3,50 @@
nst
-Cc = Components.classes;%0Aconst Ci = Components.interfaces;%0Aconst
+%7B classes: Cc, interfaces: Ci, utils:
Cu
+ %7D
= C
@@ -58,14 +58,8 @@
ents
-.utils
;%0A%0AC
|
b159ff3fa6a7cd5a3cd45cbaf38173790d7e3229
|
Fix accidental exclusion of coffeelint from CI
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp'),
mocha = require('gulp-mocha'),
jshint = require('gulp-jshint'),
coffeelint = require('gulp-coffeelint'),
jshintStylish = require('jshint-stylish');
//
// fail builds if jshint reports an error
gulp.task('jshint', function () {
gulp.src(['**/*.js', '!node_modules/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter(jshintStylish))
.pipe(jshint.reporter('fail'));
});
//
// fail builds if coffeelint reports an error
gulp.task('coffeelint', function () {
gulp.src(['**/*.coffee', '!node_modules/**/*.coffee'])
.pipe(coffeelint())
.pipe(coffeelint.reporter())
.pipe(coffeelint.reporter('fail'));
});
//
// fail mocha builds for test failures
// the .on event handler is to overcome an unknown bug with gulp/supertest/mocha
gulp.task('test', function () {
require('coffee-script/register');
return gulp.src(['test/**/test-*.coffee'], { read: false })
.pipe(mocha({
reporter: 'spec',
timeout: 2000
}))
.on('end', function () {
process.exit(0);
})
.on('error', function (err) {
var errorMessage = err.stack || err.toString();
console.log(errorMessage);
process.exit(1);
});
});
//The default task (called when you run `gulp`)
gulp.task('default', ['test', 'jshint']);
|
JavaScript
| 0.000018 |
@@ -1385,21 +1385,35 @@
, %5B'
-test', 'jshin
+jshint', 'coffeelint', 'tes
t'%5D)
|
7a808e6d536c91655f68a7b290b773ae1b320e75
|
Fix location name and absent values in ZA adapter
|
adapters/southafrica.js
|
adapters/southafrica.js
|
/**
* This code is responsible for implementing all methods related to fetching
* and returning data for the South African data sources.
*/
'use strict';
import { REQUEST_TIMEOUT } from '../lib/constants';
import { default as baseRequest } from 'request';
import { default as moment } from 'moment-timezone';
import _ from 'lodash';
import { unifyMeasurementUnits, removeUnwantedParameters, unifyParameters } from '../lib/utils';
const request = baseRequest.defaults({timeout: REQUEST_TIMEOUT});
exports.name = 'southafrica';
/**
* Fetches the data for a given source and returns an appropriate object
* @param {object} source A valid source object
* @param {function} cb A callback of the form cb(err, data)
*/
exports.fetchData = function (source, cb) {
request(source.url, function (err, res, body) {
if (err || res.statusCode !== 200) {
return cb({message: 'Failure to load data url.'});
}
// Wrap everything in a try/catch in case something goes wrong
try {
// Format the data
const data = formatData(body);
// Make sure the data is valid
if (data === undefined) {
return cb({message: 'Failure to parse data.'});
}
cb(null, data);
} catch (e) {
return cb({message: 'Unknown adapter error.'});
}
});
};
/**
* Given fetched data, turn it into a format our system can use.
* @param {array} results Fetched source data and other metadata
* @return {object} Parsed and standarized data our system can use
*/
const formatData = function (data) {
// Wrap the JSON.parse() in a try/catch in case it fails
try {
data = JSON.parse(data);
} catch (e) {
// Return undefined to be caught elsewhere
return undefined;
}
/**
* Given a measurement object, convert to system appropriate times.
* @param {object} m A source measurement object
* @return {object} An object containing both UTC and local times
*/
var parseDate = function (m) {
var date = moment.tz(m, 'YYYY-MM-DDHH:mm', 'Africa/Johannesburg');
return {utc: date.toDate(), local: date.format()};
};
var measurements = [];
_.forEach(data, function (s) {
const base = {
location: (s.location==="N/A") ? s.name : s.location,
city: s.city,
coordinates: {
latitude: Number(s.latitude),
longitude: Number(s.longitude)
},
attribution: [{name: 'South African Air Quality Information System', url: 'http://saaqis.environment.gov.za'}],
averagingPeriod: {unit: 'hours', value: 1}
};
_.forOwn(s.monitors, function (v, key) {
if (v.value !== null && v.DateVal !== null) {
var m = _.clone(base);
m.parameter = v.Pollutantname;
m.value = (v.value==="") ? 0 : Number(v.value);
m.unit = v.unit;
m.date = parseDate(v.DateVal);
m = unifyMeasurementUnits(m);
m = unifyParameters(m);
measurements.push(m);
}
});
});
measurements = removeUnwantedParameters(measurements);
return {name: 'unused', measurements: measurements};
};
|
JavaScript
| 0 |
@@ -2185,50 +2185,14 @@
on:
-(s.location===%22N/A%22) ? s.name : s.location
+s.name
,%0A
@@ -2564,16 +2564,34 @@
null &&
+ v.value !== '' &&
v.DateV
@@ -2604,17 +2604,16 @@
null) %7B
-
%0A
@@ -2696,29 +2696,8 @@
ue =
- (v.value===%22%22) ? 0 :
Num
|
29ebeea3ab9c664985f94d129de5061dd273d3e3
|
Put all failures on top of report
|
tools/ivwpy/regression/resources/main.js
|
tools/ivwpy/regression/resources/main.js
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2012-2016 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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 OWNER 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.
*
*********************************************************************************/
function sparkOptions(formater, extra) {
opts = {
type : 'line',
width : '75px',
enableTagOptions: true,
fillColor : false,
lineColor : '#473386',
spotColor : '#222222',
highlightSpotColor : '#777777',
highlightLineColor : '#777777',
spotRadius : 2,
minSpotColor : false,
maxSpotColor : false,
normalRangeColor: '#B3EEB3',
drawNormalOnTop: false,
chartRangeClip: true,
tooltipFormatFieldlist : ['x', 'y'],
tooltipFormatter : function(sp, options, fields) {
var retval = "";
if (!fields.isNull) {
retval += '<div class="jqsfield">';
retval += formater(new Date(1000*fields.x), fields.y);
retval += '</div>';
}
return retval;
}
};
jQuery.extend(opts, extra);
return opts;
}
$(document).ready(function() {
$('div.lihead').click(function() {
body = $(this).next(".libody")
body.slideToggle(100);
$.sparkline_display_visible();
});
$('.sparkline_elapsed_time').sparkline('html', sparkOptions(function(date, val) {
return 'Run time ' + date.toLocaleString() + ' : ' + val.toPrecision(6) + 's';
}, {}));
$('.sparkline_img_diff').sparkline('html', sparkOptions(function(date, val) {
return 'Diff ' + date.toLocaleString() + ' : ' + val.toPrecision(8) + '%';
}, {}));
$('.sparkline-failues').sparkline('html', sparkOptions(function(date, val) {
return 'Failures ' + date.toLocaleString() + ' : ' + val;
}, {
chartRangeMin : 0,
chartRangeMax : 6,
normalRangeMin : -0.5,
normalRangeMax : 0.5
}));
$('.zoomset').zoom({magnify : 4, on : 'grab', duration : 400});
userList.sort('testname');
userList.sort('testfailures', { order: "desc" });
userList.sort('testmodule');
new Clipboard('.copylinkbtn');
});
|
JavaScript
| 0.000001 |
@@ -3220,66 +3220,66 @@
test
-failures', %7B order: %22desc%22 %7D);%0A%09userList.sort('testmodule'
+module');%0A%09userList.sort('testfailures', %7B order: %22desc%22 %7D
);%0A%0A
|
bb0cf652be8c424751f7f7d55c38eff62659b748
|
Patch for issue #329
|
lib/recurly/relay.js
|
lib/recurly/relay.js
|
var bind = require('component-bind');
var events = require('component-event');
var errors = require('../errors');
var debug = require('debug')('recurly:relay');
module.exports = relay;
/**
* Relay mixin.
*
* Inspects the window for intent to relay a message,
* then attempts to send it off. closes the window once
* dispatched.
*
* @param {Function} done
* @private
*/
function relay (done) {
var self = this;
debug('relay');
if (false === this.configured) {
throw errors('not-configured');
}
events.bind(window, 'message', function listener (event) {
var data = JSON.parse(event.data);
var name = data.recurly_event;
var body = data.recurly_message;
var err = body.error ? errors('api-error', body.error) : null;
events.unbind(window, 'message', listener);
if (name) self.emit(name, err, body);
if (frame) document.body.removeChild(frame);
});
if ('documentMode' in document) {
var frame = document.createElement('iframe');
frame.width = frame.height = 0;
frame.src = this.url('/relay');
frame.name = 'recurly_relay';
frame.style.display = 'none';
frame.onload = bind(this, done);
document.body.appendChild(frame);
} else {
done();
}
}
|
JavaScript
| 0 |
@@ -570,24 +570,82 @@
r (event) %7B%0A
+ if (event.origin === 'https://api.recurly.com') %7B%0A
var data
@@ -671,24 +671,28 @@
.data);%0A
+
+
var name = d
@@ -710,16 +710,20 @@
_event;%0A
+
var
@@ -751,16 +751,20 @@
essage;%0A
+
var
@@ -822,16 +822,20 @@
: null;%0A
+
even
@@ -874,24 +874,28 @@
tener);%0A
+
+
if (name) se
@@ -920,16 +920,20 @@
body);%0A
+
if (
@@ -973,16 +973,22 @@
frame);%0A
+ %7D%0A
%7D);%0A%0A
|
396273b79afcd65662aef76982b68849d8774b5d
|
Fix FigureConverter.
|
src/article/converter/r2t/FigureConverter.js
|
src/article/converter/r2t/FigureConverter.js
|
export default class FigureConverter {
get type () { return 'figure' }
// ATTENTION: this converter will create either a <fig> or a <fig-group>
// element depending on the number of Figure panels
get tagName () { return 'fig' }
matchElement (el, importer) {
if (el.is('fig') || el.is('fig-group')) {
// Note: do not use this converter if we are already converting a figure
let context = importer.state.getCurrentContext()
return context && context.tagName !== 'fig'
} else {
return false
}
}
import (el, node, importer) {
// single panel figure
let panelIds = []
if (el.is('fig')) {
let panel = importer.convertElement(el)
panelIds.push(panel.id)
// multi-panel figure
} else if (el.is('fig-group')) {
panelIds = el.findAll('fig').map(child => importer.convertElement(child).id)
}
node.panels = panelIds
}
export (node, el, exporter) {
let doc = exporter.getDocument()
if (node.panels.length === 1) {
return exporter.convertNode(doc.get(node.panels[0]))
} else {
el.tagName = 'fig-group'
el.attr('id', node.id)
el.append(node.panels.map(id => exporter.convertNode(doc.get(id))))
return el
}
}
}
|
JavaScript
| 0 |
@@ -226,16 +226,19 @@
urn 'fig
+ure
' %7D%0A%0A m
@@ -482,25 +482,26 @@
ext.
-tagName !== 'fig'
+converter !== this
%0A
|
49b5bd01337efe6e80137a378e116030fc16b4a2
|
include new class
|
src/main/resources/static/js/main.js
|
src/main/resources/static/js/main.js
|
import SideNav from "./side-nav";
import CheckBoxes from "./checkboxes";
import AutoCompleteSubjects from "./autocomplete-subjects";
import AutoCompleteLecturerForSubjects from "./autocomplete-lecturer-for-subject";
import Select from "./select";
import Modals from "./modals";
// Flash Messages
const showMessage = (message) => {
"use strict";
setTimeout(() => {
Materialize.toast(message, 5000);
}, 1000);
};
const init = () => {
"use strict";
const checkboxes = new CheckBoxes();
checkboxes.initialize();
const sideNav = new SideNav();
sideNav.initialize();
const autoCompleteSubjects = new AutoCompleteSubjects();
autoCompleteSubjects.initialize();
const $wrapper = $('.autocomplete-wrapper');
const autocompleteLecturersToSubjects = new AutoCompleteLecturerForSubjects($wrapper);
autocompleteLecturersToSubjects.initialize();
const select = new Select();
select.initialize('select');
const modals = new Modals();
modals.initialize();
};
init();
// Exports for calls from HTML
window.showMessage = showMessage;
|
JavaScript
| 0.000013 |
@@ -62,24 +62,88 @@
heckboxes%22;%0A
+import AutoCompleteCourseTags from %22./autocomplete-course-tags%22%0A
import AutoC
@@ -656,32 +656,139 @@
.initialize();%0A%0A
+ const autoCompleteCourseTags = new AutoCompleteCourseTags();%0A autoCompleteCourseTags.initialize();%0A%0A
const autoCo
|
4ca5b657acf484bd479362cb3beb1ff9c10445c4
|
Remove console logger.
|
src/article/shared/ReferenceListComponent.js
|
src/article/shared/ReferenceListComponent.js
|
import { Component } from 'substance'
import { NodeModelFactory } from '../../kit'
export default class ReferenceListComponent extends Component {
didMount () {
// TODO: as we have a node for references now, we should turn this into a NodeComponent instead
this.context.appState.addObserver(['document'], this.rerender, this, { stage: 'render', document: { path: ['references'] } })
}
dispose () {
// TODO: as we have a node for references now, we should turn this into a NodeComponent instead
this.context.appState.removeObserver(this)
}
getInitialState () {
let bibliography = this._getBibliography()
return {
hidden: (bibliography.length === 0)
}
}
render ($$) {
console.log('MEH')
const ReferenceComponent = this.getComponent('bibr')
const bibliography = this._getBibliography()
let el = $$('div').addClass('sc-ref-list')
.attr('data-id', 'ref-list')
if (this.state.hidden) {
el.addClass('sm-hidden')
return el
}
if (bibliography.length > 0) {
el.append(
$$('div').addClass('se-title').append(
this.getLabel('references')
)
)
}
// ATTENTION: bibliography still works with document nodes
bibliography.forEach(refNode => {
let model = NodeModelFactory.create(this.context.api, refNode)
el.append(
$$('div').addClass('se-ref-item').append(
$$(ReferenceComponent, { model })
)
)
})
return el
}
_getBibliography () {
const api = this.context.api
const referenceManager = api.getReferenceManager()
return referenceManager.getBibliography()
}
}
|
JavaScript
| 0 |
@@ -715,31 +715,8 @@
) %7B%0A
- console.log('MEH')%0A
|
31b9344d5649a4cef21ac2bc4814bb001777dabf
|
update spec for audience tags
|
tutor/specs/models/course.spec.js
|
tutor/specs/models/course.spec.js
|
import { map, cloneDeep, shuffle } from 'lodash';
import Courses from '../../src/models/courses-map';
import Course from '../../src/models/course';
import PH from '../../src/helpers/period';
import { autorun } from 'mobx';
import { bootstrapCoursesList } from '../courses-test-data';
import COURSE from '../../api/courses/1.json';
jest.mock('shared/src/model/ui-settings');
describe('Course Model', () => {
beforeEach(() => bootstrapCoursesList());
it('can be bootstrapped and size observed', () => {
Courses.clear();
const lenSpy = jest.fn();
autorun(() => lenSpy(Courses.size));
expect(lenSpy).toHaveBeenCalledWith(0);
bootstrapCoursesList();
expect(lenSpy).toHaveBeenCalledWith(3);
expect(Courses.size).toEqual(3);
});
it('#isStudent', () => {
expect(Courses.get(1).isStudent).toBe(true);
expect(Courses.get(2).isStudent).toBe(false);
expect(Courses.get(3).isStudent).toBe(true);
});
it('#isTeacher', () => {
expect(Courses.get(1).isTeacher).toBe(false);
expect(Courses.get(2).isTeacher).toBe(true);
expect(Courses.get(3).isTeacher).toBe(true);
});
it('#userStudentRecord', () => {
expect(Courses.get(1).userStudentRecord).not.toBeNull();
expect(Courses.get(1).userStudentRecord.student_identifier).toEqual('1234');
expect(Courses.get(2).userStudentRecord).toBeNull();
});
it('calculates audience tags', () => {
expect(Courses.get(1).tourAudienceTags).toEqual(['student']);
const teacher = Courses.get(2);
expect(teacher.tourAudienceTags).toEqual(['teacher']);
teacher.primaryRole.joined_at = new Date();
expect(teacher.tourAudienceTags).toEqual(['teacher', 'teacher-settings-roster-split']);
teacher.is_preview = true;
expect(teacher.tourAudienceTags).toEqual(['teacher-preview']);
const course = Courses.get(3);
expect(course.tourAudienceTags).toEqual(['teacher', 'student']);
course.is_preview = false;
expect(course.isTeacher).toEqual(true);
course.taskPlans.set('1', { id: 1, type: 'reading', is_publishing: true, isPublishing: true });
expect(course.taskPlans.reading.hasPublishing).toEqual(true);
expect(course.tourAudienceTags).toEqual(['teacher', 'teacher-reading-published', 'student' ]);
});
it('should return expected roles for courses', function() {
expect(Courses.get(1).primaryRole.type).to.equal('student');
expect(Courses.get(2).primaryRole.type).to.equal('teacher');
expect(Courses.get(3).primaryRole.type).to.equal('teacher');
expect(Courses.get(1).primaryRole.joinedAgo('days')).toEqual(7);
});
it('sunsets cc courses', () => {
const course = Courses.get(2);
expect(course.isSunsetting).toEqual(false);
course.is_concept_coach = true;
course.appearance_code = 'physics';
expect(course.isSunsetting).toEqual(false);
course.appearance_code = 'micro_econ';
expect(course.isSunsetting).toEqual(true);
});
it('restricts joining to links', () => {
const course = Courses.get(2);
expect(course.is_lms_enabling_allowed).toEqual(false);
expect(course.canOnlyUseEnrollmentLinks).toEqual(true);
course.is_lms_enabling_allowed = true;
expect(course.canOnlyUseEnrollmentLinks).toEqual(false);
course.is_lms_enabled = true;
course.is_access_switchable = false;
expect(course.canOnlyUseEnrollmentLinks).toEqual(false);
expect(course.canOnlyUseLMS).toEqual(true);
course.is_lms_enabled = false;
expect(course.canOnlyUseEnrollmentLinks).toEqual(true);
expect(course.canOnlyUseLMS).toEqual(false);
});
it('extends periods', () => {
const data = cloneDeep(COURSE);
data.periods = shuffle(data.periods);
jest.spyOn(PH, 'sort');
const course = new Course(data);
const len = course.periods.length;
expect(map(course.periods, 'id')).not.toEqual(
map(course.periods.sorted, 'id')
);
expect(PH.sort).toHaveBeenCalledTimes(1);
const sortedSpy = jest.fn(() => course.periods.sorted);
autorun(sortedSpy);
expect(course.periods.sorted).toHaveLength(len - 2);
expect(sortedSpy).toHaveBeenCalledTimes(1);
expect(PH.sort).toHaveBeenCalledTimes(2);
course.periods.remove(course.periods.find(p => p.id == 1));
expect(course.periods.length).toEqual(len - 1);
expect(course.periods.sorted.length).toEqual(len - 3);
expect(PH.sort).toHaveBeenCalledTimes(3);
expect(sortedSpy).toHaveBeenCalledTimes(2);
expect(map(course.periods, 'id')).not.toEqual(
map(course.periods.sorted, 'id')
);
expect(PH.sort).toHaveBeenCalledTimes(3);
expect(sortedSpy).toHaveBeenCalledTimes(2);
});
it('calculates if terms are before', () => {
const course = Courses.get(2);
expect(course.isBeforeTerm('spring', 2013)).toBe(false);
expect(course.isBeforeTerm('spring', (new Date()).getFullYear()+1)).toBe(true);
expect(course.isBeforeTerm(course.term, course.year)).toBe(false);
});
});
|
JavaScript
| 0 |
@@ -1,16 +1,71 @@
+import UiSettings from 'shared/src/model/ui-settings';%0A
import %7B map, cl
@@ -1449,32 +1449,70 @@
tags', () =%3E %7B%0A
+ UiSettings.get = jest.fn(() =%3E 2)%0A
expect(Cours
|
d007a2367c52cb8d9038de3bcde26519bd27b4f3
|
Fix output options
|
src/endpoints/Data.js
|
src/endpoints/Data.js
|
"use strict";
const RequestResults = require("../constants/RequestResults");
const Utils = require("../utils/Utils");
let _token = null;
let _requester = null;
function setOpt(request, opts, name) {
const temp = {};
if (opts[name]) {
temp[name] = opts[name];
request.query(temp);
}
}
module.exports = {
initialize: function(token, requester) {
Utils.assertValidToken(token);
Utils.assertValidRequester(requester);
_token = token;
_requester = requester;
},
query: function(namespace = "input", callback, opts = {}, context = {}) {
Utils.assertValidToken(_token);
let endpoint = "/data/" + namespace + "/";
if (context.seriesName) {
endpoint = endpoint + context.seriesName + "/";
} if (context.deviceID) {
opts.where = opts.where || [];
opts.where.push("eq(device_id," + context.deviceID + ")");
}
const URL = _requester.getFullEndpoint(endpoint);
context.options = context.options || opts;
const req = _requester.getRequest(URL, _token);
setOpt(req, opts, "limit");
setOpt(req, opts, "limit_by");
setOpt(req, opts, "time");
setOpt(req, opts, "timefmt");
//special cases for options
if (opts.where) {
//statement format: comparator(field, value)
opts.where.forEach((statement) => {
req.query({where: statement});
});
}
if (opts.group_by && opts.operator) {
req.query({group_by: opts.group_by});
req.query({operator: opts.operator});
if (opts.limit_periods) {
req.query({limit_periods: opts.limit_periods});
}
} if (opts.timefmt) {
req.query({timefmt: opts.timefmt});
}
if (opts.output === "csv" || opts.output === "json") {
req.query({output: opts.output});
} else {
console.log("Invalid format for query output");
}
const bodyHandler = function(resp, body, status) {
if (status === RequestResults.SUCCESS) {
resp.body = body;
} else if (status === RequestResults.FAILURE) {
resp.error = body.errors[0].message;
}
};
const innerCb = Utils.createInnerCb(callback, context, bodyHandler);
_requester.execute(req, innerCb);
}
};
|
JavaScript
| 0.999999 |
@@ -708,30 +708,29 @@
if (context.
-series
+field
Name) %7B%0A
@@ -771,14 +771,13 @@
ext.
-series
+field
Name
@@ -813,17 +813,17 @@
.deviceI
-D
+d
) %7B%0A
@@ -926,9 +926,9 @@
iceI
-D
+d
+ %22
@@ -1971,16 +1971,33 @@
%7D else
+ if (opts.output)
%7B%0A
@@ -2020,40 +2020,75 @@
og(%22
-Invalid format for
+Output set to json format%22);%0A req.
query
-
+(%7B
output
-%22
+: %22json%22%7D
);%0A
|
2179e84969fc908aa4f7652086b5e18d6f03a718
|
check params first
|
src/administrative-sdk/speech-challenge/speech-challenge.js
|
src/administrative-sdk/speech-challenge/speech-challenge.js
|
/**
* @class SpeechChallenge domain model.
*/
export default class SpeechChallenge {
/**
* Create a speech SpeechChallenge domain model.
*
* @param {?string} id - The speech challenge identifier. If none is given, one is generated.
* @param {?string} topic - A question or topic serving as guidance.
* @param {?string} referenceAudioUrl - The reference audio fragment URL. If one is not yet available or audio is
* not yet registered to the challenge it can be set to 'null'.
* @param {?string} srtUrl - URL of a possible .srt file to accompany this challenge.
* @param {?string} imageUrl - URL of a possible image file to accompany this challenge.
* @throws {Error} srtUrl parameter of type "string|null" is required.
* @throws {Error} imageUrl parameter of type "string|null" is required.
*/
constructor(id = null, topic = null, referenceAudioUrl = null, srtUrl = null, imageUrl = null) {
if (id !== null && typeof id !== 'string') {
throw new Error(
'id parameter of type "string|null" is required');
}
/**
* The speech challenge identifier. If none is given, one is generated.
* @type {string}
*/
this.id = id;
if (topic !== null && typeof topic !== 'string') {
throw new Error(
'topic parameter of type "string|null" is required');
}
/**
* A question or topic serving as guidance.
* @type {string}
*/
this.topic = topic;
if (referenceAudioUrl !== null && typeof referenceAudioUrl !== 'string') {
throw new Error(
'referenceAudioUrl parameter of type "string|null" is required');
}
/**
* The reference audio fragment as streaming audio link.
* @type {string}
*/
this.referenceAudioUrl = referenceAudioUrl;
if (srtUrl !== null && typeof srtUrl !== 'string') {
throw new Error('srtUrl parameter of type "string|null" is required');
}
/**
* URL of a possible .srt file to accompany this challenge.
* @type {string}
*/
this.srtUrl = srtUrl;
if (imageUrl !== null && typeof imageUrl !== 'string') {
throw new Error('imageUrl parameter of type "string|null" is required');
}
/**
* URL of a possible image file to accompany this challenge.
* @type {string}
*/
this.imageUrl = imageUrl;
/**
* The creation date of the entity.
* @type {Date}
*/
this.created = null;
/**
* The most recent update date of the entity.
* @type {Date}
*/
this.updated = null;
}
}
|
JavaScript
| 0.000001 |
@@ -1063,140 +1063,8 @@
%7D
-%0A /**%0A * The speech challenge identifier. If none is given, one is generated.%0A * @type %7Bstring%7D%0A */%0A this.id = id;
%0A%0A
@@ -1210,118 +1210,8 @@
%7D
-%0A /**%0A * A question or topic serving as guidance.%0A * @type %7Bstring%7D%0A */%0A this.topic = topic;
%0A%0A
@@ -1399,150 +1399,143 @@
-/**%0A * The reference audio fragment as streaming audio link.%0A * @type %7B
+if (srtUrl !== null && typeof srtUrl !== '
string
-%7D
+') %7B
%0A
-*/%0A this.referenceAudioUrl = referenceAudioUrl;
+ throw new Error('srtUrl parameter of type %22string%7Cnull%22 is required');%0A %7D
%0A%0A
@@ -1532,35 +1532,37 @@
%0A %7D%0A%0A if (
-srt
+image
Url !== null &&
@@ -1560,35 +1560,37 @@
null && typeof
-srt
+image
Url !== 'string'
@@ -1608,35 +1608,37 @@
hrow new Error('
-srt
+image
Url parameter of
@@ -1698,267 +1698,512 @@
*
-URL of a possible .srt file to accompany this challenge.%0A * @type %7Bstring%7D%0A */%0A this.srtUrl = srtUrl;%0A%0A if (imageUrl !== null && typeof imageUrl !== 'string') %7B%0A throw new Error('imageUrl parameter of
+The speech challenge identifier. If none is given, one is generated.%0A * @type %7Bstring%7D%0A */%0A this.id = id;%0A%0A /**%0A * A question or topic serving as guidance.%0A * @type %7Bstring%7D%0A */%0A this.topic = topic;%0A%0A /**%0A * The reference audio fragment as streaming audio link.%0A * @type %7Bstring%7D%0A */%0A this.referenceAudioUrl = referenceAudioUrl;%0A%0A /**%0A * URL of a possible .srt file to accompany this challenge.%0A * @
type
-%22
+%7B
string
-%7Cnull%22 is required');%0A %7D
+%7D%0A */%0A this.srtUrl = srtUrl;
%0A%0A
|
c5835f41716d8291716717cb6b202ccc9ee595dd
|
Update contact_me.js
|
js/contact_me.js
|
js/contact_me.js
|
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
// Prevent spam click and default submit behaviour
$("#btnSubmit").attr("disabled", true);
event.preventDefault();
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var domain = "1";
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "https://mail.daniil.it/",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
domain: domain
},
cache: false,
success: function() {
// Enable button & show success message
$("#btnSubmit").attr("disabled", false);
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
$('#success').html('');
});
|
JavaScript
| 0 |
@@ -1192,32 +1192,33 @@
message: message
+,
%0A
|
ef9ca41982e53290270c4b1ebd541b507034ccad
|
handle null options in button api
|
src/runtime/button-api.js
|
src/runtime/button-api.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.
*/
import {createElement} from '../utils/dom';
import {msg} from '../utils/i18n';
import {SmartSubscriptionButtonApi, Theme} from './smart-button-api';
/**
* The button title should match that of button's SVG.
*/
/** @type {!Object<string, string>} */
const TITLE_LANG_MAP = {
'en': 'Subscribe with Google',
'ar': 'Google اشترك مع',
'de': 'Abonnieren mit Google',
'es': 'Suscríbete con Google',
'es-latam': 'Suscríbete con Google',
'es-latn': 'Suscríbete con Google',
'fr': 'S\'abonner avec Google',
'hi': 'Google के ज़रिये सदस्यता',
'id': 'Berlangganan dengan Google',
'it': 'Abbonati con Google',
'jp': 'Google で購読',
'ko': 'Google 을 통한구독',
'ms': 'Langgan dengan Google',
'nl': 'Abonneren via Google',
'no': 'Abonner med Google',
'pl': 'Subskrybuj z Google',
'pt': 'Subscrever com o Google',
'pt-br': 'Assine com o Google',
'ru': 'Подпиcka через Google',
'se': 'Prenumerera med Google',
'th': 'สมัครฟาน Google',
'tr': 'Google ile Abone Ol',
'uk': 'Підписатися через Google',
'zh-tw': '透過 Google 訂閱',
};
/**
* The button stylesheet can be found in the `/assets/swg-button.css`.
* It's produced by the `gulp assets` task and deployed to
* `https://news.google.com/swg/js/v1/swg-button.css`.
*/
export class ButtonApi {
/**
* @param {!../model/doc.Doc} doc
*/
constructor(doc) {
/** @private @const {!../model/doc.Doc} */
this.doc_ = doc;
}
/**
*/
init() {
const head = this.doc_.getHead();
if (!head) {
return;
}
const url = '$assets$/swg-button.css';
const existing = head.querySelector(`link[href="${url}"]`);
if (existing) {
return;
}
// <link rel="stylesheet" href="..." type="text/css">
head.appendChild(createElement(this.doc_.getWin().document, 'link', {
'rel': 'stylesheet',
'type': 'text/css',
'href': url,
}));
}
/**
* @param {!../api/subscriptions.ButtonOptions|function()} optionsOrCallback
* @param {function()=} opt_callback
* @return {!Element}
*/
create(optionsOrCallback, opt_callback) {
const button = createElement(this.doc_.getWin().document, 'button', {});
return this.attach(button, optionsOrCallback, opt_callback);
}
/**
* @param {!Element} button
* @param {!../api/subscriptions.ButtonOptions|function()} optionsOrCallback
* @param {function()=} opt_callback
* @return {!Element}
*/
attach(button, optionsOrCallback, opt_callback) {
const options = this.getOptions_(optionsOrCallback);
const callback = this.getCallback_(optionsOrCallback, opt_callback);
const theme = options['theme'];
button.classList.add(`swg-button-${theme}`);
button.setAttribute('role', 'button');
if (options['lang']) {
button.setAttribute('lang', options['lang']);
}
button.setAttribute('title', msg(TITLE_LANG_MAP, button) || '');
button.addEventListener('click', callback);
return button;
}
/**
*
* @param {!../api/subscriptions.ButtonOptions|function()} optionsOrCallback
* @return {!../api/subscriptions.ButtonOptions}
* @private
*/
getOptions_(optionsOrCallback) {
const options = /** @type {!../api/subscriptions.ButtonOptions} */
(typeof optionsOrCallback != 'function' ?
optionsOrCallback : {'theme': Theme.LIGHT});
const theme = options['theme'];
if (theme !== Theme.LIGHT && theme !== Theme.DARK) {
options['theme'] = Theme.LIGHT;
}
return options;
}
/**
*
* @param {?../api/subscriptions.ButtonOptions|function()} optionsOrCallback
* @param {function()=} opt_callback
* @return {function()|function(Event):boolean}
* @private
*/
getCallback_(optionsOrCallback, opt_callback) {
const callback = /** @type {function()|function(Event):boolean} */ (
(typeof optionsOrCallback == 'function' ? optionsOrCallback : null) ||
opt_callback);
return callback;
}
/**
* @param {!./deps.DepsDef} deps
* @param {!Element} button
* @param {!../api/subscriptions.ButtonOptions|function()} optionsOrCallback
* @param {function()=} opt_callback
* @return {!Element}
*/
attachSmartButton(deps, button, optionsOrCallback, opt_callback) {
const options = this.getOptions_(optionsOrCallback);
const callback = /** @type {function()} */
(this.getCallback_(optionsOrCallback, opt_callback));
// Add required CSS class, if missing.
button.classList.add('swg-smart-button');
return new SmartSubscriptionButtonApi(
deps, button, options, callback).start();
}
}
|
JavaScript
| 0 |
@@ -2901,33 +2901,32 @@
on%0A * @param %7B
-!
../api/subscript
@@ -2966,32 +2966,32 @@
tionsOrCallback%0A
+
* @param %7Bfun
@@ -3596,33 +3596,32 @@
*%0A * @param %7B
-!
../api/subscript
@@ -3851,24 +3851,45 @@
*/%0A (
+optionsOrCallback &&
typeof optio
@@ -4646,32 +4646,32 @@
Element%7D button%0A
+
* @param %7B!..
@@ -4659,33 +4659,32 @@
on%0A * @param %7B
-!
../api/subscript
|
189dcc16fca88d1c958d7531663dfa43c92dcaf6
|
stringify the data. duh (#21448)
|
src/applications/personalization/dashboard/actions/notifications.js
|
src/applications/personalization/dashboard/actions/notifications.js
|
import recordEvent from 'platform/monitoring/record-event';
import { apiRequest } from '~/platform/utilities/api';
import environment from '~/platform/utilities/environment';
export const NOTIFICATIONS_RECEIVED_STARTED = 'NOTIFICATIONS_RECEIVED_STARTED';
export const NOTIFICATIONS_RECEIVED_SUCCEEDED =
'NOTIFICATIONS_RECEIVED_SUCCEEDED';
export const NOTIFICATIONS_RECEIVED_FAILED = 'NOTIFICATIONS_RECEIVED_FAILED';
export const NOTIFICATION_DISMISSAL_STARTED = 'NOTIFICATION_DISMISSAL_STARTED';
export const NOTIFICATION_DISMISSAL_SUCCEEDED =
'NOTIFICATION_DISMISSAL_SUCCEEDED';
export const NOTIFICATION_DISMISSAL_FAILED = 'NOTIFICATION_DISMISSAL_FAILED';
export const fetchNotifications = () => async dispatch => {
const getNotifications = () => {
const options = {
method: 'GET',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'X-Key-Inflection': 'camel',
'Source-App-Name': window.appName,
},
};
return apiRequest(
`${environment.API_URL}/v0/onsite_notifications`,
options,
);
};
try {
const response = await getNotifications();
if (response.errors) {
recordEvent({
event: `api_call`,
'error-key': `server error`,
'api-name': 'GET on-site notifications',
'api-status': 'failed',
});
return dispatch({
type: NOTIFICATIONS_RECEIVED_FAILED,
notificationError: true,
errors: response.errors,
});
}
recordEvent({
event: `api_call`,
'api-name': 'GET on-site notifications',
'api-status': 'successful',
});
const filteredNotifications = response.data.filter(
n => !n.attributes?.dismissed,
);
return dispatch({
type: NOTIFICATIONS_RECEIVED_SUCCEEDED,
notifications: filteredNotifications,
});
} catch (error) {
recordEvent({
event: `api_call`,
'error-key': `internal error`,
'api-name': 'GET onsite notifications',
'api-status': 'failed',
});
throw new Error(error);
}
};
export const dismissNotificationById = id => async dispatch => {
const dismissNotification = () => {
const options = {
method: 'PATCH',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'X-Key-Inflection': 'camel',
'Source-App-Name': window.appName,
},
body: {
onsiteNotification: {
dismissed: true,
},
},
};
return apiRequest(
`${environment.API_URL}/v0/onsite_notifications/${id}`,
options,
);
};
try {
const response = await dismissNotification();
if (response.errors) {
recordEvent({
event: `api_call`,
'error-key': `server error`,
'api-name': 'PATCH dismiss on-site notification',
'api-status': 'failed',
});
return dispatch({
type: NOTIFICATION_DISMISSAL_FAILED,
dismissalError: true,
errors: response.errors,
});
}
recordEvent({
event: `api_call`,
'api-name': 'PATCH dismiss on-site notification',
'api-status': 'successful',
});
const notification = response.data[0];
const successful = notification.attributes.dismissed;
return dispatch({
type: NOTIFICATION_DISMISSAL_SUCCEEDED,
successful,
id: notification.id,
});
} catch (error) {
recordEvent({
event: `api_call`,
'error-key': `internal error`,
'api-name': 'PATCH dismiss on-site notification',
'api-status': 'failed',
});
throw new Error(error);
}
};
|
JavaScript
| 1 |
@@ -2492,16 +2492,31 @@
body:
+JSON.stringify(
%7B%0D%0A
@@ -2580,32 +2580,33 @@
%7D,%0D%0A %7D
+)
,%0D%0A %7D;%0D%0A%0D%0A
|
005e7cce80deb576d514b3b50282b2a151235254
|
Remove overloaded API from explicit module (one or t'other)
|
explicit.js
|
explicit.js
|
function P(target){
for(var i = 1; i < arguments.length; i++)
for(var key in arguments[i])
if(arguments[i].hasOwnProperty(key))
(arguments[i][key] === D || arguments[i][key] === O)
? delete target[key]
: target[key] =
arguments[i][key] instanceof S
? arguments[i][key].apply(target[key])
: arguments[i][key]
return target
}
function S(closure){
if(!(this instanceof S))
return new S(closure)
this.apply = function(definition){
return closure(definition)
}
}
function PS(target, input){
return new S(
arguments.length === 2
? function(definition){
return P(target, definition, input)
}
: function(definition){
return P(definition, target)
}
)
}
function D(){}
function O(x){
return arguments.length
? 1 < arguments.length
? P.apply(null, arguments)
: typeof x === 'function'
? new S(x)
: PS(x)
: D
}
try {
module.exports = {P: P, S: S, PS: PS, D: D, O: O}
} catch(e) {}
|
JavaScript
| 0 |
@@ -780,187 +780,8 @@
%7B%7D%0A%0A
-function O(x)%7B%0A return arguments.length%0A ? 1 %3C arguments.length%0A ? P.apply(null, arguments)%0A : typeof x === 'function'%0A ? new S(x)%0A : PS(x)%0A : D%0A%7D%0A%0A
try
@@ -830,14 +830,8 @@
D: D
-, O: O
%7D%0A%7D
|
bcf74c0c5f87c9839535f8e1d851f0514232541d
|
Add support for http proxy environment variables
|
lib/requests/http.js
|
lib/requests/http.js
|
var http = require('http');
var https = require('https');
var url = require('url');
var parseResponse = require('./helpers/parseResponse');
/**
* Sends a request to given URL with given parameters
*
* @param {string} method - Method of the request.
* @param {string} uri - Request URI.
* @param {any} responseParams - parameters for parsing the response
* @param {Function} successCallback - A callback called on success of the request.
* @param {Function} errorCallback - A callback called when a request failed.
* @param {string} [data] - Data to send in the request.
* @param {Object} [additionalHeaders] - Additional headers. IMPORTANT! This object does not contain default headers needed for every request.
*/
var httpRequest = function (method, uri, data, additionalHeaders, responseParams, successCallback, errorCallback) {
var headers = {};
if (data) {
headers["Content-Type"] = additionalHeaders['Content-Type'];
headers["Content-Length"] = data.length;
delete additionalHeaders['Content-Type'];
}
//set additional headers
for (var key in additionalHeaders) {
headers[key] = additionalHeaders[key];
}
var parsedUrl = url.parse(uri);
var isHttp = parsedUrl.protocol === 'http:';
var options = {
hostname: parsedUrl.hostname,
port: parsedUrl.port,
path: parsedUrl.path,
method: method,
headers: headers
};
var interface = isHttp ? http : https;
var request = interface.request(options, function (res) {
var rawData = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
rawData += chunk;
})
res.on('end', function () {
switch (res.statusCode) {
case 200: // Success with content returned in response body.
case 201: // Success with content returned in response body.
case 204: // Success with no content returned in response body.
case 304: {// Success with Not Modified
var responseData = parseResponse(rawData, res.headers, responseParams);
var response = {
data: responseData,
headers: res.headers,
status: res.statusCode
};
successCallback(response);
break;
}
default: // All other statuses are error cases.
var error;
try {
var errorParsed = JSON.parse(rawData);
error = errorParsed.hasOwnProperty('error') && errorParsed.error
? errorParsed.error
: { message: errorParsed.Message };
} catch (e) {
if (rawData.length > 0) {
error = { message: rawData };
}
else {
error = { message: "Unexpected Error" };
}
}
error.status = res.statusCode;
error.statusText = request.statusText;
errorCallback(error);
break;
}
responseParams.length = 0;
});
});
request.on('error', function (error) {
responseParams.length = 0;
errorCallback(error);
});
if (data) {
request.write(data);
}
request.end();
};
module.exports = httpRequest;
|
JavaScript
| 0 |
@@ -1219,22 +1219,24 @@
var
-isHttp
+protocol
= parse
@@ -1252,20 +1252,80 @@
ocol
- === 'http:'
+.replace(':','');%0A var interface = protocol === 'http' ? http : https
;%0A%0A
@@ -1506,46 +1506,698 @@
-var interface = isHttp ? http : https;
+if (process.env%5B%60$%7Bprotocol%7D_proxy%60%5D) %7B%0A /*%0A * Proxied requests don't work with Node's https module so use http to%0A * talk to the proxy server regardless of the endpoint protocol. This%0A * is unsuitable for environments where requests are expected to be%0A * using end-to-end TLS.%0A */%0A interface = http;%0A const proxyUrl = url.parse(process.env.http_proxy);%0A options = %7B%0A hostname: proxyUrl.hostname,%0A port: proxyUrl.port,%0A path: parsedUrl.href,%0A method: method,%0A headers: %7B%0A host: parsedUrl.host,%0A ...headers,%0A %7D%0A %7D;%0A %7D
%0A%0A
@@ -4322,8 +4322,9 @@
Request;
+%0A
|
c61208afe1c24548aedf38f826d3ae34ea59991f
|
Make helper function for dependencies
|
config/make_webpack_config.js
|
config/make_webpack_config.js
|
var path = require('path'),
baseDir = path.resolve(__dirname, '..'),
HtmlWebpackPlugin = require('html-webpack-plugin'),
CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin"),
node_modules = path.resolve(baseDir, 'node_modules'),
pathToReact = path.resolve(node_modules, 'react/dist/react.min.js'),
pathToMain = path.resolve(baseDir, 'app/main.jsx'),
jade = require('jade'),
indexHtml = jade.compileFile(path.resolve(baseDir, 'app/index.jade'));
module.exports = function(options) {
var entry = options.devServer
? ['webpack/hot/dev-server', pathToMain]
: pathToMain;
var config = {
entry: {
app: entry,
vendor: ['react']
},
resolve: {
alias: {
'react': pathToReact
}
},
devtool: options.devtool,
debug: options.debug,
output: {
path: path.resolve(baseDir, options.outputDir),
filename: 'bundle.js',
},
plugins: [
new HtmlWebpackPlugin({
title: 'CircuitSim',
templateContent: function(templateParams, webpackCompiler) {
var files = templateParams.htmlWebpackPlugin.files; // js, css, chunks
return indexHtml(files);
}
}),
new CommonsChunkPlugin('vendor', 'common.js')
],
module: {
loaders: [
{
test: /\.css$/,
loaders: ['style','css']
},
{
test: /\.jsx?$/,
exclude: [node_modules],
loaders: options.flowcheck
? ['babel?whitelist[]=flow','flowcheck','babel?blacklist[]=flow'] // hack from flowcheck/issues#18
: ['babel']
},
{
test: /\.scss$/,
loader: ['style','css', 'sass']
},
{
test: /\.(png|jpg)$/,
loader: 'url?limit=25000'
},
{
test: /\.woff$/, // should maybe be .svg instead?
loader: 'url?limit=100000'
}
],
noParse: [pathToReact]
}
};
return config;
};
|
JavaScript
| 0.000004 |
@@ -262,81 +262,8 @@
s'),
-%0A pathToReact = path.resolve(node_modules, 'react/dist/react.min.js'),
%0A%0A
@@ -418,16 +418,68 @@
.jade'))
+%0A%0A deps = %5B%0A 'react/dist/react.min.js'%0A %5D
;%0A%0Amodul
@@ -696,24 +696,24 @@
resolve: %7B%0A
+
alias:
@@ -718,44 +718,8 @@
s: %7B
-%0A 'react': pathToReact%0A
%7D%0A
@@ -1914,30 +1914,210 @@
e: %5B
-pathToReact%5D%0A %7D
+%5D%0A %7D%0A %7D;%0A%0A deps.forEach(function (dep) %7B%0A var depPath = path.resolve(node_modules, dep);%0A config.resolve.alias%5Bdep.split(path.sep)%5B0%5D%5D = depPath;%0A config.module.noParse.push(depPath);
%0A %7D
+)
;%0A%0A
|
01a053dbca0574900a64a4075bb84f5ae16aee54
|
add lookup unit tests
|
tests/unit/instance-initializers/router-service-test.js
|
tests/unit/instance-initializers/router-service-test.js
|
import { initialize } from 'dummy/instance-initializers/router-service';
import { module, test } from 'qunit';
import sinon from 'sinon';
module('Unit | Instance Initializer | router service');
test('ensure register is called for 1.13', function(assert) {
let register = sinon.spy();
let appInstance = {
container: {
lookup: sinon.stub().returns({}),
},
application: {
register
}
};
initialize(appInstance);
assert.ok(register.calledOnce);
});
test('ensure register is called for 2.x', function(assert) {
let register = sinon.spy();
let appInstance = {
lookup: sinon.stub().returns({}),
register
};
initialize(appInstance);
assert.ok(register.calledOnce);
});
|
JavaScript
| 0 |
@@ -115,153 +115,312 @@
ort
-sinon from 'sinon';%0A%0Amodule('Unit %7C Instance Initializer %7C router service');%0A%0Atest('ensure register is called for 1.13', function(assert) %7B%0A let
+%7B copy %7D from 'ember-metal/utils';%0Aimport sinon from 'sinon';%0A%0Aconst router = %7B testProp: 'test val' %7D;%0A%0Alet lookup;%0Alet register;%0Alet ember1Application;%0Alet ember2AppInstance;%0A%0Amodule('Unit %7C Instance Initializer %7C router service', %7B%0A beforeEach() %7B%0A lookup = sinon.stub().returns(copy(router));%0A
reg
@@ -443,36 +443,42 @@
y();%0A%0A
-let appInstance
+ ember1Application
= %7B%0A
+
cont
@@ -496,42 +496,20 @@
+
lookup
-: sinon.stub().returns(%7B%7D)
,%0A
+
@@ -515,16 +515,18 @@
%7D,%0A
+
applicat
@@ -528,24 +528,26 @@
lication: %7B%0A
+
regist
@@ -557,75 +557,383 @@
-%7D%0A %7D;%0A%0A initialize(appInstance);%0A%0A assert.ok(register.calledOnce
+ %7D%0A %7D;%0A ember2AppInstance = %7B%0A lookup,%0A register%0A %7D;%0A %7D%0A%7D);%0A%0Atest('ensure lookup is called for 1.13', function(assert) %7B%0A initialize(ember1Application);%0A%0A assert.deepEqual(lookup.args, %5B%5B'router:main'%5D%5D);%0A%7D);%0A%0Atest('ensure lookup is called for 2.x', function(assert) %7B%0A initialize(ember2AppInstance);%0A%0A assert.deepEqual(lookup.args, %5B%5B'router:main'%5D%5D
);%0A%7D
@@ -964,35 +964,36 @@
r is called for
-2.x
+1.13
', function(asse
@@ -1004,115 +1004,227 @@
%7B%0A
-let register = sinon.spy();%0A%0A let appInstance = %7B%0A lookup: sinon.stub().returns(%7B%7D),%0A register%0A %7D;%0A
+initialize(ember1Application);%0A%0A assert.deepEqual(register.args, %5B%5B%0A 'service:router',%0A router,%0A %7B singleton: true, instantiate: false %7D%0A %5D%5D);%0A%7D);%0A%0Atest('ensure register is called for 2.x', function(assert) %7B
%0A i
@@ -1233,17 +1233,23 @@
tialize(
-a
+ember2A
ppInstan
@@ -1263,18 +1263,25 @@
assert.
-ok
+deepEqual
(registe
@@ -1286,18 +1286,99 @@
ter.
-calledOnce
+args, %5B%5B%0A 'service:router',%0A router,%0A %7B singleton: true, instantiate: false %7D%0A %5D%5D
);%0A%7D
|
246636896f5be3b8e4a0a21847d3c4bd5f29adc7
|
Update contact_me js to prevent additional dialogs
|
js/contact_me.js
|
js/contact_me.js
|
// Contact Form Scripts
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success alert-dismissable fade show'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("Your message has been sent.");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger alert-dismissable fade show'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
|
JavaScript
| 0 |
@@ -1,29 +1,4 @@
-// Contact Form Scripts%0A%0A
$(fu
@@ -753,16 +753,174 @@
%7D%0A
+ $this = $(%22#sendMessageButton%22);%0A $this.prop(%22disabled%22, true); // Disable submit button until AJAX call is complete to prevent duplicate messages%0A
$.
@@ -1258,36 +1258,8 @@
cess
- alert-dismissable fade show
'%3E%22)
@@ -1489,16 +1489,24 @@
append(%22
+%3Cstrong%3E
Your mes
@@ -1524,16 +1524,26 @@
en sent.
+ %3C/strong%3E
%22);%0A
@@ -1610,17 +1610,16 @@
div%3E');%0A
-%0A
@@ -1814,36 +1814,8 @@
nger
- alert-dismissable fade show
'%3E%22)
@@ -2029,16 +2029,35 @@
.append(
+$(%22%3Cstrong%3E%22).text(
%22Sorry %22
@@ -2147,16 +2147,17 @@
later!%22)
+)
;%0A
@@ -2290,24 +2290,216 @@
%0A %7D,%0A
+ complete: function() %7B%0A setTimeout(function() %7B%0A $this.prop(%22disabled%22, false); // Re-enable submit button when AJAX call is complete%0A %7D, 1000);%0A %7D%0A
%7D);%0A
@@ -2689,17 +2689,16 @@
);%0A%7D);%0A%0A
-%0A
/*When c
|
7e1acd309333ee24a7e8fdadb9cc21a4bf00aad4
|
Fix invalid reassign
|
Sources/Rendering/OpenGL/Skybox/test/testSkyboxBackground.js
|
Sources/Rendering/OpenGL/Skybox/test/testSkyboxBackground.js
|
import vtkSkybox from 'vtk.js/Sources/Rendering/Core/Skybox';
import vtkHttpDataSetReader from 'vtk.js/Sources/IO/Core/HttpDataSetReader';
import vtkOpenGLRenderWindow from 'vtk.js/Sources/Rendering/OpenGL/RenderWindow';
import vtkTexture from 'vtk.js/Sources/Rendering/Core/Texture';
import vtkRenderer from 'vtk.js/Sources/Rendering/Core/Renderer';
import vtkRenderWindow from 'vtk.js/Sources/Rendering/Core/RenderWindow';
import test from 'tape-catch';
import testUtils from 'vtk.js/Sources/Testing/testUtils';
import baseline from './testSkyboxBackground.png';
test.onlyIfWebGL('Test vtkOpenGLSkybox Background Rendering', (t) => {
const gc = testUtils.createGarbageCollector(t);
t.ok('Rendering', 'Filter: OpenGLTexture');
function callBackfunction(loadedTexture) {
// Create come control UI
const container = document.querySelector('body');
const renderWindowContainer = gc.registerDOMElement(
document.createElement('div')
);
container.appendChild(renderWindowContainer);
// Create view
const renderWindow = gc.registerResource(vtkRenderWindow.newInstance());
const renderer = gc.registerResource(vtkRenderer.newInstance());
renderWindow.addRenderer(renderer);
const texture = gc.registerResource(vtkTexture.newInstance());
const scalarName = loadedTexture
.getPointData()
.getArrayByIndex(0)
.getName();
loadedTexture.getPointData().setActiveScalars(scalarName);
texture.setInputData(loadedTexture, 0);
const actor = gc.registerResource(vtkSkybox.newInstance());
actor.setFormat('background');
actor.addTexture(texture);
renderer.addActor(actor);
const glwindow = gc.registerResource(vtkOpenGLRenderWindow.newInstance());
glwindow.setContainer(renderWindowContainer);
renderWindow.addView(glwindow);
glwindow.setSize(400, 400);
glwindow.captureNextImage().then((image) => {
testUtils.compareImages(
image,
[baseline],
'Rendering/OpenGL/Skybox/',
t,
0.5,
gc.releaseResources
);
});
renderWindow.render();
}
// function to load texture
function loadTexture(texturePath, textureImage, endCallBack) {
const reader = gc.registerResource(
vtkHttpDataSetReader.newInstance({ fetchGzip: true })
);
reader.setUrl(texturePath).then(() => {
reader.loadData().then(() => {
textureImage = reader.getOutputData();
if (endCallBack) {
// check if endcallback exists
endCallBack(textureImage);
}
}); // end loadData
}); // end set url
}
const path = `${__BASE_PATH__}/Data/skybox/mountains/right.jpg`;
// It will contains all vtkImageData which will textured the cube
const texture = null;
loadTexture(path, texture, callBackfunction);
});
|
JavaScript
| 0 |
@@ -2174,22 +2174,8 @@
ath,
- textureImage,
end
@@ -2378,24 +2378,30 @@
%3E %7B%0A
+const
textureImage
@@ -2736,32 +2736,8 @@
ube%0A
- const texture = null;%0A
lo
@@ -2755,17 +2755,8 @@
ath,
- texture,
cal
|
e685df36511750914ca8d1a3cf89508c70e1ffed
|
update attributes values
|
codeacad_this3.js
|
codeacad_this3.js
|
var rectangle = new Object();
rectangle.height = 3;
rectangle.width = 4;
// here is our method to set the height
rectangle.setHeight = function (newHeight) {
this.height = newHeight;
};
// help by finishing this method
rectangle.setWidth = function (newWidth){
this.width = newWidth;
};
|
JavaScript
| 0.000001 |
@@ -290,8 +290,124 @@
;%0A%7D;%0A %0A
+// here change the width to 8 and height to 6 using our new methods%0Arectangle.setWidth (8);%0Arectangle.setHeight (6);
|
77d5ce030665a01149bfe92dddb203a1fdcb43b9
|
Update contact_me.js
|
js/contact_me.js
|
js/contact_me.js
|
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "//formspree.io/[email protected]",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
dataType: "json",
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
|
JavaScript
| 0 |
@@ -906,16 +906,51 @@
o.za%22, %0A
+ crossDomain: true,%0A
|
2ed2e4776c3506b995888ab282a39f699b6638e1
|
Make compatible with RN 0.26
|
index.ios.js
|
index.ios.js
|
'use strict';
import React, {
AppRegistry,
Component,
View,
PickerIOS,
StyleSheet
} from 'react-native';
export default class TimePicker extends Component {
constructor(props) {
super(props);
this._hours = [];
this._minutes = [];
for (let j = 0; j < 24 * (this.props.loop ? 100 : 1); j++) {
this._hours.push(j);
}
for (let j = 0; j < 60 * (this.props.loop ? 100 : 1); j += this._getInterval(this.props.minuteInterval || 1)) {
this._minutes.push(j);
}
this.state = {
selectedHour: this._getHourIndex(this.props.selectedHour || 0),
selectedMinute: this._getMinuteIndex(this.props.selectedMinute || 0, this.props.minuteInterval || 1)
}
};
_getInterval = (interval) => {
let matched = false;
for (let i of [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30]) {
if (i === interval) {
return interval;
}
}
if (!matched) {
return 1;
}
};
_getHourIndex = (h) => {
return (this.props.loop ? (this._hours.length / 2) : 0) + h;
};
_getMinuteIndex = (m, interval) => {
return (this.props.loop ? (this._minutes.length / 2 * this._getInterval(interval)) : 0) + (m % this._getInterval(interval) === 0 ? m : 0);
};
_getHourValue = (h) => {
return h % 24;
};
_getMinuteValue = (m) => {
return m % 60;
};
_onValueChangeCallback = () => {
if ('onValueChange' in this.props) {
this.props.onValueChange(this._getHourValue(this.state.selectedHour), this._getMinuteValue(this.state.selectedMinute));
}
};
_setHour = (hour) => {
this.setState({
selectedHour: hour
});
this._onValueChangeCallback();
};
_setMinute = (minute) => {
this.setState({
selectedMinute: minute
});
this._onValueChangeCallback();
};
render() {
let hours = [];
for (let hour of this._hours) {
hours.push(<PickerIOS.Item key={hour} value={hour} label={this._getHourValue(hour).toString()}/>);
}
let minutes = [];
for (let minute of this._minutes) {
minutes.push(<PickerIOS.Item key={minute} value={minute} label={this._getMinuteValue(minute).toString()}/>);
}
return (
<View style={[styles.container, this.props.style]}>
<PickerIOS style={styles.picker}
selectedValue={this.state.selectedHour}
onValueChange={this._setHour}>
{hours}
</PickerIOS>
<PickerIOS style={styles.picker}
selectedValue={this.state.selectedMinute}
onValueChange={this._setMinute}>
{minutes}
</PickerIOS>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row'
},
picker: {
flex: 1
}
});
AppRegistry.registerComponent('TimePicker', () => TimePicker);
|
JavaScript
| 0 |
@@ -23,16 +23,51 @@
React, %7B
+ Component %7D from 'react';%0Aimport %7B
%0A%09AppReg
@@ -77,20 +77,8 @@
ry,%0A
-%09Component,%0A
%09Vie
|
4da0ca8810b94f0f58d4495b8dd4df32a624e100
|
Fix item opacity
|
src/chart/common/opacityVisual.js
|
src/chart/common/opacityVisual.js
|
export default function (seriesType, ecModel, api) {
return {
seriesType: seriesType,
reset: function (seriesModel, ecModel) {
var data = seriesModel.getData();
var opacityAccessPath = seriesModel.visualColorAccessPath.split('.');
opacityAccessPath[opacityAccessPath.length - 1] ='opacity';
var opacity = seriesModel.get(opacityAccessPath);
data.setVisual('opacity', opacity == null ? 1 : opacity);
function dataEach(idx) {
var itemModel = data.getItemModel(idx);
var opacity = itemModel.get(opacityAccessPath);
if (opacity != null) {
data.setItemVisual(idx, 'opacity', opacity);
}
}
return {
dataEach: data.hasItemOption ? dataEach : null
};
}
};
}
|
JavaScript
| 0.000001 |
@@ -505,16 +505,22 @@
ataEach(
+data,
idx) %7B%0A
@@ -635,16 +635,22 @@
cessPath
+, true
);%0A
|
1f00ed6cc6b69cb07ae67d8164a8bd369f173c26
|
Remove unused initAvailableOptionsList method.
|
jquery.roland.js
|
jquery.roland.js
|
/**
* Add and delete 'rows' to any container element.
*
* @author Stephen Lewis (http://github.com/experience/)
* @copyright Experience Internet
* @version 1.1.0
*/
(function($) {
$.fn.roland = function(options) {
var opts = $.extend({}, $.fn.roland.defaults, options);
return this.each(function() {
var $container = $(this);
updateIndexes($container, opts);
updateNav($container, opts);
// Adds a row.
$container.find('.' + opts.addRowClass).bind('click', function(e) {
e.preventDefault();
var $link = $(this);
var $parentRow = $link.closest('.' + opts.rowClass);
var $lastRow = $container.find('.' + opts.rowClass + ':last');
var $cloneRow = $lastRow.clone(true);
var eventData = {};
// Reset the field values.
$cloneRow.find('input').each(function() {
var type = $(this).attr('type');
switch (type.toLowerCase()) {
case 'checkbox':
case 'radio':
$(this).attr('checked', false);
break;
case 'email':
case 'password':
case 'search':
case 'text':
$(this).val('');
break;
}
});
// Pre-add event. Only checks return value from last listener.
if ($link.data('events').preAddRow !== undefined) {
eventData = {container : $container, options : opts, newRow : $cloneRow};
$cloneRow = $link.triggerHandler('preAddRow', [eventData]);
// Returning FALSE prevents the row being added.
if ($cloneRow === false) {
return;
}
}
// If the 'add row' link lives inside a row, insert the new row after it.
// Otherwise, just tag it on the end.
typeof $parentRow === 'object' ? $parentRow.after($cloneRow) : $lastRow.append($cloneRow);
// Post-add event.
if ($link.data('events').postAddRow !== undefined) {
eventData = {container : $container, options : opts};
$link.triggerHandler('postAddRow', [eventData]);
}
// Update everything.
updateIndexes($container, opts);
updateNav($container, opts);
});
// Removes a row.
$container.find('.' + opts.removeRowClass).bind('click', function(e) {
e.preventDefault();
var $row = $(this).closest('.' + opts.rowClass);
// Can't remove the last row.
if ($row.siblings().length == 0) {
return false;
}
$row.remove();
// Update everything.
updateIndexes($container, opts);
updateNav($container, opts);
});
});
};
// Defaults.
$.fn.roland.defaults = {
rowClass : 'row',
addRowClass : 'add_row',
removeRowClass : 'remove_row'
};
/* ------------------------------------------
* PRIVATE METHODS
* -----------------------------------------*/
// Initialises the 'available options' list for the specified select field.
function initAvailableOptionsList($select)
{
var options = {};
$select.find('option').each(function() {
options[$(this).attr('value')] = $(this).text();
});
return options;
}
// Updates the indexes of any form elements.
function updateIndexes($container, opts) {
$container.find('.' + opts.rowClass).each(function(rowCount) {
regex = /^([a-z_]+)\[(?:[0-9]+)\]\[([a-z_]+)\]$/;
$(this).find('input, select, textarea').each(function(fieldCount) {
var fieldName = $(this).attr('name');
fieldName = fieldName.replace(regex, '$1[' + rowCount + '][$2]');
$(this).attr('name', fieldName);
});
});
};
// Updates the navigation buttons.
function updateNav($container, opts) {
var $remove = $container.find('.' + opts.removeRowClass);
var $rows = $container.find('.' + opts.rowClass);
$rows.size() == 1 ? $remove.hide() : $remove.show();
};
})(jQuery);
/* End of file : jquery.roland.js */
|
JavaScript
| 0 |
@@ -3585,321 +3585,8 @@
*/%0A%0A
- // Initialises the 'available options' list for the specified select field.%0A function initAvailableOptionsList($select)%0A %7B%0A var options = %7B%7D;%0A $select.find('option').each(function() %7B%0A options%5B$(this).attr('value')%5D = $(this).text();%0A %7D);%0A return options;%0A %7D%0A%0A%0A
|
7a0efd67b74c3cd2ba8866faac95b1df8e8fb0c2
|
fix spelling mistake
|
index.web.js
|
index.web.js
|
/* eslint no-console:0 */
// export components to browser's window for `dist/antd-mobile.js`
var req = require.context('./components', true, /^\.\/[^_][\w-]+\/style\/index\.web\.tsx?$/);
req.keys().forEach((mod) => {
req(mod);
});
module.exports = require('./components');
if (typeof console !== 'undefined' && console.warn) {
console.warn(`you are using prebuild antd-mobile,
please use https://github.com/ant-design/babel-plugin-import to reduce app bundle size.`);
}
|
JavaScript
| 0.999999 |
@@ -342,17 +342,17 @@
e.warn(%60
-y
+Y
ou are u
@@ -363,17 +363,17 @@
prebuil
-d
+t
antd-mo
|
6bf462afd8fcb44df3ad62f0a157ce69e5c4c1a8
|
Update production task🚀
|
gulpfile.js
|
gulpfile.js
|
/* eslint-disable */
const gulp = require('gulp');
const tasks = require('strt-gulpfile')({
src: 'src',
dist: 'public/dist',
});
gulp.task('default', gulp.series(
tasks.clean,
gulp.parallel(
tasks.styles,
tasks.images,
tasks.files,
tasks.icons,
tasks.scripts
),
tasks.serve
));
gulp.task('production', gulp.series(
gulp.parallel(
tasks.styles,
tasks.images,
tasks.files,
tasks.icons,
tasks.scripts
)
));
|
JavaScript
| 0 |
@@ -329,31 +329,16 @@
uction',
- gulp.series(%0A
gulp.pa
@@ -337,34 +337,32 @@
gulp.parallel(%0A
-
tasks.styles,%0A
@@ -353,34 +353,32 @@
tasks.styles,%0A
-
tasks.images,%0A
@@ -369,34 +369,32 @@
tasks.images,%0A
-
tasks.files,%0A
@@ -386,34 +386,32 @@
tasks.files,%0A
-
-
tasks.icons,%0A
@@ -401,34 +401,32 @@
tasks.icons,%0A
-
-
tasks.scripts%0A
@@ -427,12 +427,8 @@
pts%0A
- )%0A
));%0A
|
341c3e1e494da8d1454ded0af23fb880f048e9a7
|
Remove unused validation function and leverage ajv directly
|
lib/schemas/index.js
|
lib/schemas/index.js
|
const Ajv = require('ajv');
const predefined = require('./predefined');
const logger = require('../../lib/logger').gateway;
const ajv = new Ajv({
schemas: predefined,
useDefaults: true
});
const buildKey = (type, name) => `${type}:${name}`;
const registeredKeys = predefined.map((predefinedSchema) => ({
type: 'core',
key: predefinedSchema.$id,
name: predefinedSchema.$id
}));
function register (type, name, schema) {
const key = buildKey(type, name);
/*
This piece of code is checking that the schema isn't already registered.
This is not optimal and it's happening because the testing helpers aren't
removing the schemas when we're shutting down the gateway. Hopefully we'll
get back to this once we'll have a better story for programmatic startup/shutdown
*/
if (!schema) {
logger.warn(`${name} ${type} hasn't provided a schema. Validation for this ${type} will be skipped.`);
} else if (registeredKeys.findIndex(keys => keys.key === key) === -1) {
ajv.addSchema(schema, key);
registeredKeys.push({ type, name, key });
}
return (data) => validate(type, name, data);
}
function validate (type, name, data) {
const key = buildKey(type, name);
const compiled = ajv.getSchema(key);
if (compiled) {
const isValid = compiled(data);
return { isValid, error: ajv.errorsText(compiled.errors) };
}
return { isValid: true };
}
function find (type = null, name = null) {
if (type && name) {
const item = ajv.getSchema(buildKey(type, name));
if (item) {
return { type, name, schema: item.schema };
}
} else {
return registeredKeys
.filter(item => !type || item.type === type)
.map(key => ({ key: key.key, type: key.type, name: key.name, schema: ajv.getSchema(key.key).schema }));
}
}
module.exports = {
register,
validate,
find
};
|
JavaScript
| 0 |
@@ -916,16 +916,54 @@
ped.%60);%0A
+ return () =%3E (%7B isValid: true %7D);%0A
%7D else
@@ -1133,227 +1133,43 @@
=%3E
-validate(type, name, data);%0A%7D%0A%0Afunction validate (type, name, data) %7B%0A const key = buildKey(type, name);%0A const compiled = ajv.getSchema(key);%0A if (compiled) %7B%0A const isValid = compiled(data);%0A return %7B isValid
+(%7B isValid: ajv.validate(key, data)
, er
@@ -1192,16 +1192,11 @@
ext(
-compiled
+ajv
.err
@@ -1205,41 +1205,9 @@
s) %7D
-;%0A %7D%0A%0A return %7B isValid: true %7D
+)
;%0A%7D%0A
@@ -1638,20 +1638,8 @@
er,%0A
- validate,%0A
fi
|
9a1da7ba454313cd2c24e6b74ed4ed8937d1bd04
|
fix field
|
src/garment-purchasing/delivery-order-item-fulfillment-validator.js
|
src/garment-purchasing/delivery-order-item-fulfillment-validator.js
|
require("should");
var validateProduct = require('../master/product-validator');
var validateSupplier = require('../master/supplier-validator');
var validateUom = require('../master/uom-validator');
var validateCurrency = require('../master/currency-validator');
module.exports = function (data) {
data.should.have.property('purchaseOrderId');
data.purchaseOrderId.should.instanceOf(Object);
data.should.have.property('purchaseOrderNo');
data.purchaseOrderNo.should.instanceOf(String);
data.should.have.property('purchaseRequestId');
data.purchaseRequestId.should.instanceOf(Object);
data.should.have.property('purchaseRequestRefNo');
data.purchaseRequestRefNo.should.instanceOf(String);
data.should.have.property('purchaseRequestRefNo');
data.purchaseRequestRefNo.should.instanceOf(String);
data.should.have.property('productId');
data.productId.should.instanceOf(Object);
data.should.have.property('product');
data.product.should.instanceOf(Object);
data.product.should.have.property('code');
data.product.code.should.instanceOf(String);
data.product.should.have.property('name');
data.product.name.should.instanceOf(String);
data.should.have.property('purchaseOrderQuantity');
data.purchaseOrderQuantity.should.instanceOf(Number);
data.should.have.property('purchaseOrderUom');
data.purchaseOrderUom.should.instanceOf(Object);
data.purchaseOrderUom.should.have.property('unit');
data.purchaseOrderUom.unit.should.instanceOf(String);
data.should.have.property('deliveredQuantity');
data.deliveredQuantity.should.instanceOf(Number);
data.should.have.property('realizationQuantity');
data.realizationQuantity.should.instanceOf(Array);
data.should.have.property('remainsQuantity');
data.remainsQuantity.should.instanceOf(Number);
data.should.have.property('pricePerDealUnit');
data.pricePerDealUnit.should.instanceOf(Number);
data.should.have.property('currency');
data.currency.should.instanceof(Object);
validateCurrency(data.currency);
data.should.have.property('remark');
data.remark.should.instanceOf(String);
data.should.have.property('corrections');
data.corrections.should.instanceOf(Array);
data.should.have.property('quantityConversion');
data.quantityConversion.should.instanceOf(Number);
data.should.have.property('conversion');
data.conversion.should.instanceOf(Number);
data.should.have.property('uomConversion');
data.uomConversion.should.instanceOf(Object);
data.uomConversion.should.have.property('unit');
data.uomConversion.unit.should.instanceOf(String);
};
|
JavaScript
| 0.000001 |
@@ -644,35 +644,32 @@
'purchaseRequest
-Ref
No');%0A data.p
@@ -674,35 +674,32 @@
.purchaseRequest
-Ref
No.should.instan
|
8add3dde5bc36d881017415118c6b4ee5a66e145
|
add "px" while creating css for box
|
js/dataloader.js
|
js/dataloader.js
|
//add or update label box
function updateLabelBox(box_el){
var imgName = $('#img').attr("label");
var boxlbl = $(box_el).attr("label");
if(!boxlbl || boxlbl === "") {
throw Error("All the label boxes must be labelled");
}else{
if(!images[imgName]){
images[imgName] = {
boxes : {}
}
}
images[imgName].boxes[boxlbl] = {
left: $(box_el).position().left,
top: $(box_el).position().top,
width: $(box_el).width(),
height: $(box_el).height()
}
}
}
function deleteLabelBox(box_el){
var imgName = $('#img').attr("label");
var boxlbl = $(box_el).attr("label");
delete images[imgName].boxes[boxlbl] ;
}
function updateLabelBoxLabel(oldLabel,newLabel){
var imgName = $('#img').attr("label");
if(!images[imgName] || !images[imgName].boxes || !images[imgName].boxes[oldLabel]){
console.log("Label box is not created yet");
}else{
images[imgName].boxes[newLabel] = images[imgName].boxes[oldLabel] ;
delete images[imgName].boxes[oldLabel] ;
}
}
function deleteLabelBoxPoints(box_el){
var imgName = $('#img').attr("label");
var boxlbl = $(box_el).attr("label");
images[imgName].boxes[boxlbl].points = {} ;
}
function deleteLabels(){
var imgName = $('#img').attr("label");
images[imgName].boxes = {} ;
}
//add or update a feature point
function updateFeaturePoint(point_el){
var imgName = $('#img').attr("label");
var boxlbl = $(point_el).parent().attr("label");
var pointlbl = $(point_el).attr("label");
if(!pointlbl || pointlbl === ""){
throw Error("All the feature points must be labelled");
}else{
//Considering that label box has already been created
if(! images[imgName].boxes[boxlbl].points){
images[imgName].boxes[boxlbl].points = {}
}
images[imgName].boxes[boxlbl].points[pointlbl] = {
label: $(point_el).attr("label"),
x: $(point_el).position().left,
y: $(point_el).position().top,
}
}
}
function deleteFeaturePoint(point_el){
var imgName = $('#img').attr("label");
var boxlbl = $(point_el).parent().attr("label");
var pointlbl = $(point_el).attr("label");
delete images[imgName].boxes[boxlbl].points[pointlbl] ;
}
function updateFeaturePointLabel(point_el,oldLabel,newLabel){
var imgName = $('#img').attr("label");
var boxLabel = $(point_el).parent().attr("label");
if(!images[imgName] || !images[imgName].boxes || !images[imgName].boxes[boxLabel]
|| !images[imgName].boxes[boxLabel].points || !images[imgName].boxes[boxLabel].points[oldLabel]){
console.log("Feature point is not created yet");
}else{
images[imgName].boxes[boxLabel].points[newLabel] = images[imgName].boxes[boxLabel].points[oldLabel] ;
delete images[imgName].boxes[boxLabel].points[oldLabel] ;
}
}
function drawAllBoxData(boxes){
if(boxes){
for (var boxlbl in boxes) {
if (boxes.hasOwnProperty(boxlbl)) {
var tmpBox = appendBox({
top: boxes[boxlbl].top,
left: boxes[boxlbl].left,
width: boxes[boxlbl].width,
height: boxes[boxlbl].height
});
tmpBox.attr("label", boxlbl);
// Add points
var points = boxes[boxlbl].points;
for (var pointlbl in points) {
if (points.hasOwnProperty(pointlbl)) {
drawPoint(points[pointlbl],tmpBox,pointlbl);
}
}
}
}
}
}
function drawPoint(coordinates,el,lbl){
var point = $('<div class="ptn"></div>')
.css('top', coordinates.y + 'px')
.css('left', coordinates.x + 'px')
.appendTo(el);
if(!lbl){
lbl = $(el).find(".ptn").length;
}
point.attr("label" ,lbl);
jsPlumb.draggable(point,{
drag: function(e){
displayPointWidget($(e.el));
},
stop: function(e){
updateFeaturePoint(e.el);
}
});
return point;
}
/*Add box on the image*/
function appendBox(css){
var tmpBox = $("<div class='facebox'></div>")
.css(css)
.appendTo($("#img_overlay"));
makeItDraggable(tmpBox);
return tmpBox;
}
/* make a box dragabble*/
function makeItDraggable(el){
jsPlumb.draggable(el,{
start: function(e){
select(el);
},
drag: function(e){
displayBoxWidget($(e.el));
},
stop: function(e){
updateLabelBox(e.el);
//displayBoxWidget($(e.el));
}
});
}
/* Save given data to a file */
function download(data, filename, type) {
var blobData = new Blob([data], {type: type + ";charset=utf-8"})
saveAs(blobData, filename);
}
|
JavaScript
| 0.000001 |
@@ -3183,24 +3183,31 @@
%5Bboxlbl%5D.top
+ + %22px%22
,%0A
@@ -3236,24 +3236,32 @@
boxlbl%5D.left
+ + %22px%22
,%0A
@@ -3296,16 +3296,23 @@
l%5D.width
+ + %22px%22
,%0A
@@ -3353,16 +3353,23 @@
%5D.height
+ + %22px%22
%0A
@@ -3623,32 +3623,205 @@
ty(pointlbl)) %7B%0A
+ /* var pointXY = %7B%0A x: points%5Bpointlbl%5D.x,%0A y: points%5Bpointlbl%5D.y%0A %7D */%0A
@@ -3938,32 +3938,122 @@
%7D%0A %7D%0A%7D%0A%0A
+//points are relative to image. But while displaying they should be relative to label box%0A
function drawPoi
@@ -5026,182 +5026,4 @@
%0A%7D%0A%0A
-/* Save given data to a file */%0Afunction download(data, filename, type) %7B%0A var blobData = new Blob(%5Bdata%5D, %7Btype: type + %22;charset=utf-8%22%7D)%0A saveAs(blobData, filename);%0A%7D%0A%0A
|
9dd4febad670c662db31f6590d77cb5dff6b21ce
|
mangle false
|
config/webpack.prod.config.js
|
config/webpack.prod.config.js
|
// ```
// @datatype_void
// [email protected]
// webpack.prod.js may be freely distributed under the MIT license
// ```
//# Common Configuration and Helpers
var helpers = require('./helpers');
// Use `webpack-merge` to merge configs
var webpackMerge = require('webpack-merge');
// Common `webpack` configuration for `dev` and `prod`
var commonConfig = require('./webpack.common.js');
// Webpack Plugins
var ProvidePlugin = require('webpack/lib/ProvidePlugin');
var DedupePlugin = require('webpack/lib/optimize/DedupePlugin');
var DefinePlugin = require('webpack/lib/DefinePlugin');
var UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
var CompressionPlugin = require('compression-webpack-plugin');
var WebpackMd5Hash = require('webpack-md5-hash');
//# Webpack Constants
const ENV = process.env.ENV = process.env.NODE_ENV = 'production';
const HOST = process.env.HOST || '0.0.0.0';
const PORT = process.env.PORT || 8080;
const METADATA = {
host: HOST,
port: PORT,
ENV: ENV,
HMR: false
};
module.exports = webpackMerge(commonConfig, {
// Developer tool to enhance debugging
//
// See: http://webpack.github.io/docs/configuration.html#devtool
// See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
devtool: 'source-map',
// Switch loaders to debug mode.
//
// See: http://webpack.github.io/docs/configuration.html#debug
debug: false,
// Options affecting the output of the compilation.
//
// See: http://webpack.github.io/docs/configuration.html#output
output: {
// The output directory as absolute path (required).
//
// See: http://webpack.github.io/docs/configuration.html#output-path
path: helpers.root('dist'),
// Specifies the name of each output file on disk.
// IMPORTANT: You must not specify an absolute path here!
//
// See: http://webpack.github.io/docs/configuration.html#output-filename
filename: '[name].[chunkhash].bundle.js',
// The filename of the SourceMaps for the JavaScript files.
// They are inside the output.path directory.
//
// See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
sourceMapFilename: '[name].[chunkhash].bundle.map',
// The filename of non-entry chunks as relative path
// inside the output.path directory.
//
// See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
chunkFilename: '[id].[chunkhash].chunk.js'
},
// Add additional plugins to the compiler.
//
// See: http://webpack.github.io/docs/configuration.html#plugins
plugins: [
// Plugin: WebpackMd5Hash
// Description: Plugin to replace a standard webpack chunkhash with md5.
//
// See: https://www.npmjs.com/package/webpack-md5-hash
new WebpackMd5Hash(),
// Plugin: DedupePlugin
// Description: Prevents the inclusion of duplicate code into your bundle
// and instead applies a copy of the function at runtime.
//
// See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
// See: https://github.com/webpack/docs/wiki/optimization#deduplication
new DedupePlugin(),
// Plugin: DefinePlugin
// Description: Define free variables.
// Useful for having development builds with debug logging or adding global constants.
//
// Environment helpers
//
// See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
// NOTE: when adding more properties make sure you include them in custom-typings.d.ts
new webpack.DefinePlugin({
'ENV': JSON.stringify(METADATA.ENV),
'HMR': HMR
}),
// Plugin: UglifyJsPlugin
// Description: Minimize all JavaScript output of chunks.
// Loaders are switched into minimizing mode.
//
// See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
// NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
new UglifyJsPlugin({
// beautify: true, //debug
// mangle: false, //debug
// dead_code: false, //debug
// unused: false, //debug
// deadCode: false, //debug
// compress: {
// screw_ie8: true,
// keep_fnames: true,
// drop_debugger: false,
// dead_code: false,
// unused: false
// }, // debug
// comments: true, //debug
beautify: false, //prod
// mangle: { screw_ie8 : true }, //prod
mangle: {
screw_ie8: true,
except: [
'App',
'About',
'Contact',
'Home',
'Menu',
'Footer',
'XLarge',
'RouterActive',
'RouterLink',
'RouterOutlet',
'NgFor',
'NgIf',
'NgClass',
'NgSwitch',
'NgStyle',
'NgSwitchDefault',
'NgControl',
'NgControlName',
'NgControlGroup',
'NgFormControl',
'NgModel',
'NgFormModel',
'NgForm',
'NgSelectOption',
'DefaultValueAccessor',
'NumberValueAccessor',
'CheckboxControlValueAccessor',
'SelectControlValueAccessor',
'RadioControlValueAccessor',
'NgControlStatus',
'RequiredValidator',
'MinLengthValidator',
'MaxLengthValidator',
'PatternValidator',
'AsyncPipe',
'DatePipe',
'JsonPipe',
'NumberPipe',
'DecimalPipe',
'PercentPipe',
'CurrencyPipe',
'LowerCasePipe',
'UpperCasePipe',
'SlicePipe',
'ReplacePipe',
'I18nPluralPipe',
'I18nSelectPipe'
] // Needed for uglify RouterLink problem
}, // prod
compress: {
screw_ie8: true
}, //prod
comments: false //prod
}),
// Plugin: CompressionPlugin
// Description: Prepares compressed versions of assets to serve
// them with Content-Encoding
//
// See: https://github.com/webpack/compression-webpack-plugin
new CompressionPlugin({
regExp: /\.css$|\.html$|\.js$|\.map$/,
threshold: 2 * 1024
})
],
// Static analysis linter for TypeScript advanced options configuration
// Description: An extensible linter for the TypeScript language.
//
// See: https://github.com/wbuchwalter/tslint-loader
tslint: {
emitErrors: true,
failOnHint: true,
resourcePath: 'src'
},
// Html loader advanced options
//
// See: https://github.com/webpack/html-loader#advanced-options
// TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
htmlLoader: {
minimize: true,
removeAttributeQuotes: false,
caseSensitive: true,
customAttrSurround: [
[/#/, /(?:)/],
[/\*/, /(?:)/],
[/\[?\(?/, /(?:)/]
],
customAttrAssign: [/\)?\]?=/]
},
node: {
global: 'window',
crypto: 'empty',
process: false,
module: false,
clearImmediate: false,
setImmediate: false
}
});
|
JavaScript
| 0.999952 |
@@ -4408,24 +4408,54 @@
e %7D, //prod%0A
+ mangle: false,%0A /*%0A
mangle
@@ -5864,24 +5864,33 @@
%7D, // prod%0A
+ */%0A
compre
|
c8d1c693eb5b0823818f44bc246462f36d4e9c3e
|
fix 404 in deployment
|
config/index.js
|
config/index.js
|
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/sw-shop-vuejs',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}
|
JavaScript
| 0 |
@@ -320,16 +320,19 @@
th: '/sw
+api
-shop-vu
@@ -332,18 +332,21 @@
shop-vue
-js
+-vuex
',%0A p
|
deef6104e75f2ff339661a94dad62f7cfceb26f8
|
Tweak embed vid playing
|
js/docs.video.js
|
js/docs.video.js
|
// From http://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-get-parameters
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
return query_string;
}();
// 2. This code loads the IFrame Player API code asynchronously.
if ($('#main-video').is('*')) {
var $videoOuter = $('#subpage-intro-video');
var $videoInner = $videoOuter.find('.docs-video-inner');
var $videoOverlay = $videoOuter.find('.video-overlay');
var videoId = $('#main-video').data().video;
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube mainPlayer)
// after the API code downloads.
var mainPlayer, embeddedPlayers = [];
function onYouTubeIframeAPIReady() {
mainPlayer = new YT.Player('main-video', {
height: '385',
width: '690',
videoId: videoId,
mainPlayerVars: {showinfo: '0'},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
$('[data-linkable-video]').each(function() {
var $vid= $(this);
var id = this.id;
var videoId = $vid.data().linkableVideo;
embeddedPlayers.push({id: id, video: videoId, player: new YT.Player(id, {
events: {
'onReady': onPlayerReady
}
})});
});
}
// 4. The API will call this function when the video mainPlayer is ready.
function onPlayerReady(event) {
if(QueryString.video == videoId) {
mainPlayer.playVideo();
} else if(QueryString.video) {
for(var i = 0; i < embeddedPlayers.length; i++) {
if(QueryString.video == embeddedPlayers[i].video) {
$(window).scrollTop($('#' + embeddedPlayers[i].id).offset() - 200);
embeddedPlayers[i].player.playVideo();
// Don't show the main vid if we're autoplaying a different one.
$videoInner.removeClass('autostick').removeClass('expanded');
$videoOverlay.removeClass('expanded');
}
}
}
}
// 5. The API calls this function when the mainPlayer's state changes.
// The function indicates that when playing a video (state=1),
// the mainPlayer should play for six seconds and then stop.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
$videoInner.addClass('playing').addClass('autostick');
} else {
$videoInner.removeClass('playing');
}
}
var $window = $(window);
$(window).on("scroll", function() {
var videoOffset = $videoOuter.offset().top;
var videoHeight = $videoOuter.height();
var myScrollPosition = $(this).scrollTop();
if (myScrollPosition > (videoOffset + videoHeight - 300)) {
$videoInner.addClass('is-stuck');
$videoOverlay.addClass('is-stuck');
} else {
$videoInner.removeClass('is-stuck');
$videoOverlay.removeClass('is-stuck');
}
});
$('[data-close-video]').on('click', function() {
mainPlayer.stopVideo();
$videoInner.removeClass('autostick').removeClass('expanded');
$videoOverlay.removeClass('expanded');
});
$('[data-expand-contract-video]').on('click', function() {
$videoInner.toggleClass('expanded');
$videoOverlay.toggleClass('expanded');
});
var getSeconds = function(link) {
var time = $(link).data().openVideo;
var sections = String(time).split(':');
var seconds;
if(sections.length > 1) {
seconds = (60 * Number(sections[0])) + Number(sections[1]);
} else {
seconds = Number(sections[0]);
}
return seconds;
}
var href = $('#docs-mobile-video-link').attr('href');
$('[data-open-video]').each(function() {
var seconds = getSeconds(this);
this.href = href + '&time_continue=' + seconds;
this.target = '_blank';
});
$('[data-open-video]').on('click', function(e) {
if(Foundation.MediaQuery.is('small only')) {
return;
}
e.preventDefault();
var seconds = getSeconds(this)
mainPlayer.seekTo(seconds, true);
mainPlayer.playVideo();
$videoOverlay.addClass('expanded');
$videoInner.addClass('expanded').addClass('autostick');
});
}
|
JavaScript
| 0 |
@@ -2640,16 +2640,20 @@
et()
+.top
- 200);
%0A
@@ -2652,57 +2652,8 @@
00);
-%0A embeddedPlayers%5Bi%5D.player.playVideo();
%0A%0A
@@ -2838,32 +2838,81 @@
ss('expanded');%0A
+ embeddedPlayers%5Bi%5D.player.playVideo();%0A
%7D%0A
|
95ea3fd47302e66a7fe8005629c05abec1461d48
|
handle minute:seconds format for Rafi
|
js/docs.video.js
|
js/docs.video.js
|
// 2. This code loads the IFrame Player API code asynchronously.
if ($('#main-video').is('*')) {
var $videoOuter = $('#subpage-intro-video');
var $videoInner = $videoOuter.find('.docs-video-inner');
var videoId = $('#main-video').data().video;
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('main-video', {
height: '385',
width: '690',
videoId: videoId,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
$videoInner.addClass('playing');
} else {
$videoInner.removeClass('playing');
}
}
var $window = $(window);
$(window).on("scroll", function() {
var videoOffset = $videoOuter.offset().top;
var myScrollPosition = $(this).scrollTop();
if (myScrollPosition > videoOffset) {
$videoInner.addClass('is-stuck');
} else {
$videoInner.removeClass('is-stuck');
}
});
$('[data-close-video]').on('click', function() {
player.stopVideo();
});
$('[data-open-video]').on('click', function() {
var seconds = Number($(this).data().openVideo);
player.seekTo(seconds, true);
player.playVideo();
});
}
|
JavaScript
| 0.000009 |
@@ -1810,16 +1810,147 @@
var
+time = $(this).data().openVideo;%0A var sections = String(time).split(':');%0A var seconds;%0A if(sections.length %3E 1) %7B %0A
seconds
@@ -1954,16 +1954,22 @@
ds =
+ (60 *
Number(
$(th
@@ -1968,34 +1968,100 @@
ber(
-$(this).data().openVideo);
+sections%5B0%5D)) + Number(sections%5B1%5D);%0A %7D else %7B%0A seconds = Number(sections%5B0%5D);%0A %7D
%0A
|
e26a90cc57a19b5623d92333a0667aad24b19925
|
copy fonts for dist
|
gulpfile.js
|
gulpfile.js
|
/* jshint node: true */
var gulp = require("gulp"),
plumber = require("gulp-plumber")
watch = require("gulp-watch"),
less = require("gulp-less"),
webserver = require("gulp-webserver");
gulp.task("less-prod", function() {
gulp.src("src/less/suurjako.less")
.pipe(plumber())
.pipe(less({
compress: true,
paths: ["src/less", "bower_components"],
}))
.pipe(gulp.dest("app"));
});
gulp.task("less-dev", function() {
gulp.src("src/less/suurjako.less")
.pipe(plumber())
.pipe(less({
paths: ["src/less", "bower_components"],
}))
.pipe(gulp.dest("target/dev/app"));
});
gulp.task("server", function() {
gulp.src("index.html")
.pipe(gulp.dest("target/dev"));
gulp.src("bower_components/fontawesome/fonts/*")
.pipe(gulp.dest("target/dev/fonts"));
gulp.watch("src/less/**/*.less", ["less-dev"]);
gulp.src("target/dev")
.pipe(webserver({
port: 8080,
livereload: true
}));
});
gulp.task("dist", ["less-prod"]);
gulp.task("default", ["less-dev", "server"]);
|
JavaScript
| 0 |
@@ -1003,19 +1003,121 @@
s-prod%22%5D
+, function() %7B%0A gulp.src(%22bower_components/fontawesome/fonts/*%22)%0A .pipe(gulp.dest(%22app/fonts%22))%0A%7D
);%0A
+%0A
gulp.tas
|
fbe343c8697c8ef3ccb1eddd2a5cb163024c8b79
|
clean build/img before writing new images on the default task - prevents deleted images from still existing there
|
gulpfile.js
|
gulpfile.js
|
// Gulp
var gulp = require('gulp');
// Plugins
var browserSync = require('browser-sync');
var cache = require('gulp-cache');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var htmlv = require('gulp-html-validator');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var minifyCSS = require('gulp-minify-css');
var notify = require('gulp-notify'); // requires Growl on Windows
var plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var runSequence = require('run-sequence');
var sass = require('gulp-ruby-sass'); // Requires ruby
var uglify = require('gulp-uglify');
var cp = require('child_process');
// Define our paths
var paths = {
scripts: 'js/**/*.js',
styles: 'sass/**/*.scss',
fonts: 'sass/fonts/*',
images: 'img/**/*.{png,jpg,jpeg,gif}'
};
var destPaths = {
scripts: 'build/js',
styles: 'build/css',
fonts: 'build/fonts',
images: 'build/img/',
html: 'build/validated'
};
// Error Handling
// Send error to notification center with gulp-notify
var handleErrors = function() {
notify.onError({
title: "Compile Error",
message: "<%= error.message %>"
}).apply(this, arguments);
this.emit('end');
};
// Compile our Sass
gulp.task('styles', function() {
return gulp.src(paths.styles)
.pipe(plumber())
.pipe(sass({sourcemap: true, sourcemapPath: paths.styles}))
.pipe(gulp.dest(destPaths.styles))
.pipe(notify('Styles task complete!'));
});
// Compile our Sass
gulp.task('build-styles', function() {
return gulp.src(paths.styles)
.pipe(plumber())
.pipe(sass())
.pipe(minifyCSS())
.pipe(rename('main.css'))
.pipe(gulp.dest(destPaths.styles))
.pipe(notify('Build styles task complete!'));
});
// Lint, minify, and concat our JS
gulp.task('scripts', function() {
return gulp.src(paths.scripts)
.pipe(plumber())
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(uglify())
.pipe(concat('main.min.js'))
.pipe(gulp.dest(destPaths.scripts))
.pipe(notify('Scripts tasks complete!'));
});
// Compress Images
gulp.task('images', function() {
return gulp.src(paths.images)
.pipe(plumber())
.pipe(cache(imagemin({
progressive: true,
interlaced: true
})))
.pipe(gulp.dest(destPaths.images))
.pipe(notify('Image optimized!'));
});
// Compress Images for Build
gulp.task('build-images', function() {
return gulp.src(paths.images)
.pipe(plumber())
.pipe(imagemin({
progressive: true,
interlaced: true
}))
.pipe(gulp.dest(destPaths.images))
.pipe(notify('Image optimized!'));
});
// Validate HTML
gulp.task('validate', function() {
return gulp.src('*.html')
.pipe(plumber())
.pipe(htmlv())
.pipe(gulp.dest(destPaths.html))
.pipe(notify('HTML validated!'));
});
// Watch for changes made to files
gulp.task('watch', function() {
gulp.watch(paths.scripts, ['scripts']);
gulp.watch(paths.styles, ['styles']);
gulp.watch(paths.images, ['images']);
gulp.watch('*.html', ['validate']);
});
// Browser Sync - autoreload the browser
// Additional Settings: http://www.browsersync.io/docs/options/
gulp.task('browser-sync', function () {
var files = [
'**/*.html',
'**/*.php',
'build/css/style.css',
'build/js/main.min.js',
'build/img/**/*.{png,jpg,jpeg,gif}'
];
browserSync.init(files, {
server: {
baseDir: './'
},
// proxy: 'sitename.dev', // Proxy for local dev sites
// port: 5555, // Sets the port in which to serve the site
// open: false // Stops BS from opening a new browser window
});
});
gulp.task('clean', function() {
return gulp.src('build').pipe(clean());
});
gulp.task('move-fonts', function() {
gulp.src(paths.fonts)
.pipe(gulp.dest(destPaths.fonts));
});
// Default Task
gulp.task('default', function(cb) {
runSequence('clean', 'images', 'scripts', 'styles', 'move-fonts', 'browser-sync', 'watch', cb);
});
// Build Task
gulp.task('build', function(cb) {
runSequence('clean', 'build-images', 'build-styles', 'scripts', 'move-fonts', cb);
});
|
JavaScript
| 0 |
@@ -2008,32 +2008,137 @@
plete!'));%0A%7D);%0A%0A
+gulp.task('clean-images', function() %7B%0A%09return gulp.src(destPaths.images+'/**/*')%0A%09%09.pipe(clean());%0A%7D);%0A%0A
// Compress Imag
@@ -2151,32 +2151,50 @@
p.task('images',
+ %5B'clean-images'%5D,
function() %7B%0A%09r
|
13975ebc0b8253e12b746d88f97d2a2d7f4c91ea
|
Throw errors that cause a redirect to make debugging easier
|
ui/app/controllers/application.js
|
ui/app/controllers/application.js
|
import Ember from 'ember';
const { Controller, computed } = Ember;
export default Controller.extend({
error: null,
errorStr: computed('error', function() {
return this.get('error').toString();
}),
errorCodes: computed('error', function() {
const error = this.get('error');
const codes = [error.code];
if (error.errors) {
error.errors.forEach(err => {
codes.push(err.status);
});
}
return codes
.compact()
.uniq()
.map(code => '' + code);
}),
is404: computed('errorCodes.[]', function() {
return this.get('errorCodes').includes('404');
}),
is500: computed('errorCodes.[]', function() {
return this.get('errorCodes').includes('500');
}),
});
|
JavaScript
| 0 |
@@ -49,16 +49,39 @@
computed
+, inject, run, observer
%7D = Emb
@@ -120,16 +120,45 @@
xtend(%7B%0A
+ config: inject.service(),%0A%0A
error:
@@ -776,13 +776,173 @@
);%0A %7D),
+%0A%0A throwError: observer('error', function() %7B%0A if (this.get('config.isDev')) %7B%0A run.next(() =%3E %7B%0A throw this.get('error');%0A %7D);%0A %7D%0A %7D),
%0A%7D);%0A
|
3cf7af934aadf6f27db6256768ff7c3962aa6570
|
Add more semi-colons
|
uw-frame-components/portal/notifications/controllers.js
|
uw-frame-components/portal/notifications/controllers.js
|
'use strict';
define(['angular'], function(angular) {
var app = angular.module('portal.notifications.controllers ', []);
app.controller('PortalNotificationController', [ '$scope',
'$rootScope',
'$location',
'$localStorage',
'NOTIFICATION',
'SERVICE_LOC',
'filterFilter',
'notificationsService',
function($scope,
$rootScope,
$location,
$localStorage,
NOTIFICATION,
SERVICE_LOC,
filterFilter,
notificationsService){
var configurePriorityNotificationScope = function(data){
$scope.priorityNotifications = filterFilter(data, {priority : true});
if ($scope.priorityNotifications && $scope.priorityNotifications.length > 0) {
$scope.hasPriorityNotifications = true;
$('.page-content').addClass('has-priority-nots');
if($scope.headerCtrl) {
$scope.headerCtrl.hasPriorityNotifications = true;
}
} else {
$('.page-content').removeClass('has-priority-nots');
$scope.hasPriorityNotifications = false;
if($scope.headerCtrl) {
$scope.headerCtrl.hasPriorityNotifications = false;
}
}
};
var clearPriorityNotificationFlags = function(duringOnEvent) {
$scope.priorityNotifications = [];
$scope.hasPriorityNotifications = false;
if($scope.headerCtrl) {
$scope.headerCtrl.hasPriorityNotifications = false;
}
$('.page-content').removeClass('has-priority-nots');
if(!duringOnEvent) {
$rootScope.$broadcast('portalShutdownPriorityNotifications', { disable : true});
}
}
var successFn = function(data){
//success state
$scope.count = data ? data.length : 0;
$scope.isEmpty = ($scope.count === 0);
$scope.status = "You have "+ ($scope.isEmpty ? "no " : "") + "notifications";
$scope.notifications = data;
if($location.url().indexOf('notifications') === -1) {
configurePriorityNotificationScope(data);
} else {
clearPriorityNotificationFlags();
}
};
var errorFn = function(data){
//error state (logging of error happens at service layer)
$scope.count = 0;
$scope.isEmpty = true;
};
var dismissedSuccessFn = function(data) {
if(Array.isArray(data))
$rootScope.dismissedNotificationIds = data;
};
$scope.dismissedCount = function() {
return $rootScope.dismissedNotificationIds ? $rootScope.dismissedNotificationIds.length : 0;
};
$scope.countWithDismissed = function() {
var count = 0;
if($rootScope.dismissedNotificationIds && $scope.notifications) {
for(var i = 0; i < $scope.notifications.length; i++) {
var curNot = $scope.notifications[i];
var dismissed = false;
if(curNot.dismissable) {
for(var j =0; j < $rootScope.dismissedNotificationIds.length; j++) {
dismissed = curNot.id === $rootScope.dismissedNotificationIds[j];
if(dismissed) {
break;
}
}
}
if(!dismissed) {
count++;
}
}
}
return count;
};
$scope.isDismissed = function(notification) {
for(var i = 0; i < $rootScope.dismissedNotificationIds.length; i++) {
if(notification.id === $rootScope.dismissedNotificationIds[i]) {
return true;
}
}
return false;
};
$scope.dismiss = function (notification, fromPriority) {
$rootScope.dismissedNotificationIds.push(notification.id);
if(SERVICE_LOC.kvURL) { //key value store enabled, we can store dismiss of notifications
notificationsService.setDismissedNotifications($rootScope.dismissedNotificationIds);
}
if(fromPriority) {
clearPriorityNotificationFlags();
}
};
$scope.undismiss = function(notification) {
var index = $rootScope.dismissedNotificationIds.indexOf(notification.id);
if(index !== -1) {
$rootScope.dismissedNotificationIds.splice(index,1);
}
if(SERVICE_LOC.kvURL) { //key value store enabled, we can store dismiss of notifications
notificationsService.setDismissedNotifications($rootScope.dismissedNotificationIds);
}
};
$scope.switch = function(mode) {
$scope.mode = mode;
}
var init = function(){
$scope.notifications = [];
$rootScope.dismissedNotificationIds = $rootScope.dismissedNotificationIds || [];
$scope.count = 0;
$scope.isEmpty = false;
$scope.notificationUrl = NOTIFICATION.notificationFullURL;
$scope.notificationsEnabled = NOTIFICATION.enabled;
if(NOTIFICATION.enabled && !$rootScope.GuestMode) {
if(SERVICE_LOC.kvURL && $rootScope.dismissedNotificationIds.length === 0) {
//key value store enabled, we can store dismiss of notifications
notificationsService.getDismissedNotificationIds().then(dismissedSuccessFn);
}
if(NOTIFICATION.groupFiltering && !$localStorage.disableGroupFilteringForNotifications) {
notificationsService.getNotificationsByGroups().then(successFn, errorFn);
} else {
notificationsService.getAllNotifications().then(successFn, errorFn);
}
$scope.$on('$locationChangeStart', function(event) {
if ($location.url().indexOf('notification') === -1) {
configurePriorityNotificationScope($scope.notifications);
} else {
clearPriorityNotificationFlags();
}
});
$scope.$on('portalShutdownPriorityNotifications', function(event, data) {
clearPriorityNotificationFlags(true);
});
}
}
init();
}]);
return app;
});
|
JavaScript
| 0.000084 |
@@ -2293,24 +2293,25 @@
%7D%0A %7D
+;
%0A%0A var su
@@ -5035,24 +5035,25 @@
mode;%0A %7D
+;
%0A%0A var in
@@ -6406,24 +6406,25 @@
%7D%0A%0A %7D
+;
%0A%0A init()
|
cb72eb087324cbec360e41c5306d7c25ac100308
|
Fix data count returned
|
config/model.js
|
config/model.js
|
"use strict";
define(['settings'],function(settings){
function model(value,registry){
var DEFAULT_PAGE = 1;
var DEFAULT_ITEM = 5;
var __meta = {},__data = [],__uses=[],object = {meta:__meta,data:__data};
var registered = false;
if(registry!=undefined){
DEMO_REGISTRY[registry.name] = {};
if(registry.uses){
var models = registry.uses;
for(var i in models){
var endpoint = models[i];
require([settings.TEST_DIRECTORY+'/'+endpoint]);
}
}
registered = true;
}
function list(){
var config = arguments[0]||{};
var page = config.page||DEFAULT_PAGE;
var limit = __meta.limit||DEFAULT_ITEM;
var keyword = config.keyword;
var fields = config.fields;
var index = limit=='less'?null:((page - 1) * limit);
var data = __data;
var __class = __meta.class;
if(keyword&&fields){
var _d=[];
var regex = new RegExp(keyword, 'i');
for(var i in data){
var d = data[i];
var t = false;
for(var ii in fields){
var f = fields[ii];
t = t || regex.test(d[f]);
}
if(t){
_d.push(d);
}
}
data = _d;
}
var regEx = new RegExp('page|limit|keyword|fields');
for(var field in config){
var match = config[field];
if(!regEx.test(field)){
var _d=[];
for(var i in data){
var d = data[i];
var t = d[field]==match;
if(!d.hasOwnProperty(field))
t = t && true;
if(t){
_d.push(d);
}
}
data = _d;
}
}
if(index!=null&&__class!="SystemDefault")
data = data.slice(index,index+limit);
var meta = __meta;
meta.page = page;
meta.limit = limit;
if(__class!="SystemDefault"){
meta.count = data.length;
meta.last = limit=='less'?1:Math.ceil(meta.count/limit);
meta.next = page<meta.last?page+1:null;
}
meta.prev = page>1?page-1:null;
return angular.copy({meta:meta,data:data});
};
function error(){
return angular.copy({meta:__meta});
};
function save(data){
var saved = false;
if(!data.hasOwnProperty('id')){
data.id = __data.length;
}else{
for(var i in __data){
var datum = __data[i];
if(datum.id==data.id){
for(var ii in data){
__data[i][ii] = data[ii];
}
saved=true;
break;
}
}
}
if(!saved){
__data.push(data);
}
if(registered)
DEMO_REGISTRY[registry.name]=__data;
return angular.copy({meta:__meta,data:data});
}
function remove(data){
if(data.hasOwnProperty('id')){
for(var i in __data){
var datum = __data[i];
if(datum.id==data.id){
__data.splice(i,1);
break;
}
}
}
if(registered)
DEMO_REGISTRY[registry.name]=__data;
return angular.copy({meta:__meta,data:data});
}
function setMeta(meta){
__meta = meta;
}
function setData(data){
var __class = __meta.class;
if(__class=="SystemDefault"){
__data = data;
return;
}
for(var i in data){
var datum = data[i];
if( typeof datum=='object'){
if(!datum.hasOwnProperty('id'))
datum.id= __data.length;
__data.push(datum);
}else{
__data[i] = datum;
}
}
if(registered)
DEMO_REGISTRY[registry.name]=__data;
}
object.GET = function(data){
return {success:list(data),error:error()};
}
object.POST = function(data){
return {success:save(data),error:error()};
}
object.DELETE = function(data){
return {success:remove(data),error:error()};
}
object.PUT = function(data){
return {success:save(data),error:error()};
}
object.save = save;
object.remove = remove;
if(value.hasOwnProperty('meta'))setMeta(value.meta);
if(value.hasOwnProperty('data'))setData(value.data);
return object;
}
return model;
});
|
JavaScript
| 0.000008 |
@@ -1488,24 +1488,52 @@
%0A%09%09%09%09%7D%0A%09%09%09%7D%0A
+%09%09%09var count = data.length;
%0A%09%09%09if(index
@@ -1724,27 +1724,21 @@
count =
-data.length
+count
;%0A%09%09%09%09me
|
9d10d873fb159dc71fec8974914d08b868468499
|
Remove unused main.js
|
gulpfile.js
|
gulpfile.js
|
/**
* Copyright 2015 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* osu!web is distributed 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 osu!web. If not, see <http://www.gnu.org/licenses/>.
*
*/
var
elixir = require("laravel-elixir"),
path = require("path"),
bower_root = "../../../bower_components/", // relative from resources/assets/*
composer_root = "../../../vendor/",
node_root = "../../../node_modules/";
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Less
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix
.copy("node_modules/font-awesome/fonts", "public/vendor/fonts/font-awesome")
.copy("node_modules/photoswipe/dist/default-skin", "public/vendor/_photoswipe-default-skin")
.less("app.less")
.scripts([
path.join(node_root, "jquery/dist/jquery.js"),
path.join(composer_root, "helthe/turbolinks/Resources/public/js/turbolinks.js"),
path.join(bower_root, "jquery-ujs/src/rails.js"),
path.join(node_root, "bootstrap/dist/js/bootstrap.js"),
path.join(bower_root, "jquery-timeago/jquery.timeago.js"),
path.join(bower_root, "jquery-zoom/jquery.zoom.js"),
path.join(node_root, "blueimp-file-upload/js/vendor/jquery.ui.widget.js"),
path.join(node_root, "blueimp-file-upload/js/jquery.iframe-transport.js"),
path.join(node_root, "blueimp-file-upload/js/jquery.fileupload.js"),
path.join(bower_root, "history.js/scripts/bundled-uncompressed/html5/jquery.history.js"),
path.join(bower_root, "ResponsiveSlides.js/responsiveslides.js"),
path.join(node_root, "photoswipe/dist/photoswipe.js"),
path.join(node_root, "photoswipe/dist/photoswipe-ui-default.js"),
path.join(node_root, "lodash/index.js"),
path.join(node_root, "layzr.js/dist/layzr.js"),
path.join(node_root, "react/dist/react-with-addons.js"),
"ga.js",
], "public/js/vendor.js")
.scripts("messages.js", "public/js/messages.js")
.coffee([
"osu!live.coffee",
"osu_common.coffee",
"turbolinks-mod.coffee",
"bbcode.coffee",
"main.coffee",
"store.coffee",
"forum.coffee",
"forum/post-box.coffee",
"forum/topic-ajax.coffee",
"ujs-common.coffee",
"bootstrap-modal.coffee",
"login-modal.coffee",
"logout.coffee",
"shared.coffee",
], "public/js/app.js")
.browserify("jsx/modding_react.jsx", "public/js/jsx/modding_react.js")
.browserify("jsx/profile_page.jsx", "public/js/jsx/profile_page.js")
.version([
"css/app.css",
"js/app.js",
"js/main.js",
"js/messages.js",
"js/jsx/modding_react.js",
"js/jsx/profile_page.js",
"js/vendor.js",
])
});
|
JavaScript
| 0 |
@@ -3324,24 +3324,8 @@
s%22,%0A
-%09%09%22js/main.js%22,%0A
%09%09%22j
|
58aee3544bca8cb6646f7a3d518b15ba5a342abb
|
Improve performance Creating a new room object for each recursive pass has a lot of overhead
|
mapGenerator.js
|
mapGenerator.js
|
(function () {
var Room = function (x, y) {
this.x = x;
this.y = y;
};
var Map = function () {
var numRooms = 35,
startRoom = new Room(0, 0);
this.width = 600; // Ensure this matches width of canvas tag
this.height = 600; // Same
this.roomSize = 25;
this.innerRoomSize = this.roomSize / 2;
this.draw(this.generate([startRoom], numRooms, startRoom));
};
Map.prototype = {
generate: function (roomsArray, numRooms, currentRoom) {
// Base case
if (roomsArray.length >= numRooms) {
return roomsArray;
}
// Recursive case
var availableRoomCoords = this.getAdjacent(currentRoom),
roomCoords = this.getRandomRoomCoords(availableRoomCoords),
nextRoom = new Room(roomCoords[0], roomCoords[1]);
if (!this.roomExists(roomsArray, roomCoords)) {
// Add if it wasn't already there
roomsArray.push(nextRoom);
}
// Use it as the next stop regardless
return roomsArray.concat(this.generate(roomsArray, numRooms, nextRoom));
},
roomExists: function (roomsArray, nextRoomCoords) {
var roomsArrayLength = roomsArray.length;
if (roomsArrayLength == 0) {
return true;
}
for (var i = 0; i < roomsArrayLength; i++) {
if (nextRoomCoords[0] === roomsArray[i].x &&
nextRoomCoords[1] === roomsArray[i].y) {
return true;
}
}
return false;
},
getAdjacent: function (currentRoom) {
var maxDistance = Math.floor(24 / 2),
availableRoomCoords = [];
var adjacentRoomCoords = [[currentRoom.x + 1, currentRoom.y],
[currentRoom.x - 1, currentRoom.y],
[currentRoom.x, currentRoom.y + 1],
[currentRoom.x, currentRoom.y - 1]];
for (var i = 0; i < adjacentRoomCoords.length; i++) {
var absX = Math.abs(adjacentRoomCoords[i][0]) + 1,
absY = Math.abs(adjacentRoomCoords[i][1]) + 1;
if (absX < maxDistance && absY < maxDistance) {
availableRoomCoords.push(adjacentRoomCoords[i]);
}
}
console.log(availableRoomCoords.length);
return availableRoomCoords;
},
getRandomRoomCoords: function (availableRoomCoords) {
return availableRoomCoords[Math.floor(Math.random()*availableRoomCoords.length)];
},
convertRoomCoordsToPixels: function (roomCoords) {
var x = (this.width / 2) + (this.roomSize * roomCoords.x);
var y = (this.height / 2) + (this.roomSize * roomCoords.y);
return [x, y];
},
draw: function (roomsArray) {
var canvas = document.getElementById('map'),
context = canvas.getContext('2d'),
coords,
x,
y;
// Fill every visited node
for (var i = 0; i < roomsArray.length; i++) {
coords = this.convertRoomCoordsToPixels(roomsArray[i]);
x = coords[0];
y = coords[1];
context.fillStyle = '#000000';
context.fillRect (x, y, this.roomSize, this.roomSize);
context.fillStyle = '#333333';
context.fillRect (x + (this.roomSize / 4),
y + (this.roomSize / 4),
this.innerRoomSize,
this.innerRoomSize);
}
// Set the start room to green
coords = this.convertRoomCoordsToPixels(roomsArray[0]);
x = coords[0];
y = coords[1];
context.fillStyle = '#88d800';
context.fillRect (x + (this.roomSize / 4),
y + (this.roomSize / 4),
this.innerRoomSize,
this.innerRoomSize);
// Set the end room to red
coords = this.convertRoomCoordsToPixels(roomsArray[roomsArray.length - 1]);
x = coords[0];
y = coords[1];
context.fillStyle = '#b53120';
context.fillRect (x + (this.roomSize / 4),
y + (this.roomSize / 4),
this.innerRoomSize,
this.innerRoomSize);
}
};
window.onload = function () {
new Map();
};
})();
|
JavaScript
| 0.000031 |
@@ -370,17 +370,16 @@
ze / 2;%0A
-%0A
@@ -538,32 +538,8 @@
) %7B%0A
- // Base case
%0A
@@ -579,24 +579,37 @@
numRooms) %7B
+ // Base case
%0A
@@ -649,33 +649,15 @@
%7D
-%0A %0A
+ else %7B
//
@@ -679,24 +679,28 @@
+
var availabl
@@ -744,16 +744,20 @@
tRoom),%0A
+
@@ -840,24 +840,28 @@
+
nextRoom
= new R
@@ -856,52 +856,119 @@
Room
- = new Room(roomCoords%5B0%5D, roomCoords%5B1%5D);%0A%0A
+Exists = this.getRoomIndexIfExists(roomsArray, roomCoords),%0A nextRoom;%0A %0A
@@ -983,15 +983,13 @@
if (
-!this.r
+nextR
oomE
@@ -997,86 +997,93 @@
ists
-(roomsArray, roomCoords)) %7B%0A // Add if it wasn't already there%0A
+ == -1) %7B%0A nextRoom = new Room(roomCoords%5B0%5D, roomCoords%5B1%5D);%0A
@@ -1121,16 +1121,20 @@
tRoom);%0A
+
@@ -1130,32 +1130,39 @@
%7D
+ else %7B
%0A //
@@ -1162,83 +1162,98 @@
-// Use it as the next stop regardless%0A return roomsArray.concat(
+ nextRoom = roomsArray%5BnextRoomExists%5D; %0A %7D%0A%0A return
this
@@ -1289,27 +1289,40 @@
s, nextRoom)
-)
;%0A
+ %7D%0A
%7D,%0A%0A
@@ -1329,20 +1329,30 @@
-room
+getRoomIndexIf
Exists:
@@ -1481,16 +1481,17 @@
ength ==
+=
0) %7B%0A
@@ -1735,36 +1735,33 @@
return
-true
+i
;%0A
@@ -1801,13 +1801,10 @@
urn
-false
+-1
;%0A
@@ -2569,61 +2569,8 @@
%7D%0A%0A
- console.log(availableRoomCoords.length);%0A
|
35aa80f5988d8aa1ef9e0b6aea57206eea186b96
|
fix authorizations not updating
|
src/server/models/user.js
|
src/server/models/user.js
|
var uuid = require('node-uuid');
var userSchema = require('./../schemata/user');
/*
* A user will login with local credentials (provider=local)
* or with 3rd party credentials (provider=github) in either case
* we want to findOrCreate a User and grant a fresh token. */
userSchema.statics.findOrCreateByAuthorization = function(data, providers, callback) {
var authorizer = providers[data.provider].authorizer;
authorizer(data.uid, data.pw)(function (err, providerData) {
if (err) {
callback(new Error("Login Failed"));
} else {
if (data.provider === 'local') {
var user = providerData.user;
user.token = uuid.v4();
user.save(function () {
callback(null, user)
});
} else {
this.findOne()
.where('authorizations.'+data.provider+'.login')
.equals(providerData.login)
.exec(function (err, user) {
if (err) { return callback(err); }
else if (user) {
// Found the user
if (! user.authorizations) user.authorizations = {};
user.authorizations[data.provider] = providerData;
user.token = uuid.v4();
user.save(function () {
callback(null, user)
});
} else {
// Create the user
var user = new User();
if (! user.authorizations) user.authorizations = {};
user.authorizations[data.provider] = providerData;
user.token = uuid.v4();
user.save(function () {
callback(null, user)
});
}
})
}
}
}.bind(this))
};
var User = require('mongoose').model('User', userSchema);
module.exports = User;
|
JavaScript
| 0.000002 |
@@ -25,16 +25,49 @@
-uuid');
+%0Avar logger = require('winston');
%0A%0Avar us
@@ -1036,37 +1036,43 @@
ser%0A
-if (!
+var auths =
user.authorizat
@@ -1067,33 +1067,100 @@
r.authorizations
-)
+ %7C%7C %7B%7D;%0A auths%5Bdata.provider%5D = providerData;%0A
user.authorizat
@@ -1158,35 +1158,50 @@
uthorizations =
-%7B%7D;
+null; // important
%0A use
@@ -1220,38 +1220,16 @@
ions
-%5Bdata.provider%5D = providerData
+ = auths
;%0A
@@ -1286,32 +1286,46 @@
.save(function (
+err, savedUser
) %7B%0A
@@ -1318,32 +1318,75 @@
%7B%0A
+if (err) callback(err);%0A else
callback(null, u
@@ -1376,33 +1376,38 @@
callback(null,
-u
+savedU
ser)%0A
@@ -1512,53 +1512,16 @@
-if (! user.authorizations) user.authorization
+var auth
s =
@@ -1536,34 +1536,20 @@
-user.authorization
+auth
s%5Bdata.p
@@ -1565,32 +1565,73 @@
= providerData;%0A
+ user.authorizations = auths;%0A
user
@@ -1674,32 +1674,40 @@
.save(function (
+err, res
) %7B%0A
@@ -1699,32 +1699,75 @@
%7B%0A
+
+if (err) callback(err);%0A else
callback(null,
|
b1bbb0e2d1482a78df29fcd0353662fa6e17f63a
|
add methods to vector3
|
math/Vector3.js
|
math/Vector3.js
|
import { vec3 } from "gl-matrix";
export default class Vector3 {
static get elements() {
return vec3;
}
constructor(x = 0, y = 0, z = 0) {
this.elements = vec3.create();
this.x = x;
this.y = y;
this.z = z;
return this;
}
get x() {
return this.elements[0];
}
set x(value) {
this.elements[0] = value;
}
get y() {
return this.elements[1];
}
set y(value) {
this.elements[1] = value;
}
get z() {
return this.elements[2];
}
set z(value) {
this.elements[2] = value;
}
get length() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
}
set(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
copy(vector3) {
this.x = vector3.x;
this.y = vector3.y;
this.z = vector3.z;
return this;
}
add(vector3) {
this.x += vector3.x;
this.y += vector3.y;
this.z += vector3.z;
return this;
}
normalize() {
this.divideScalar(this.length);
}
divideScalar(scalar) {
if (scalar !== 0) {
let invScalar = 1 / scalar;
this.x *= invScalar;
this.y *= invScalar;
this.z *= invScalar;
} else {
this.x = 0;
this.y = 0;
this.z = 0;
}
return this;
}
dot(vector3) {
return this.x * vector3.x + this.y * vector3.y + this.z * vector3.z;
}
angleTo(vector3) {
// TODO: To test(from three.js)
let theta = this.dot(vector3) / (this.length() * vector3.length());
return Math.acos((theta < -1) ? -1 : ((theta > 1) ? 1 : theta));
}
}
|
JavaScript
| 0.000001 |
@@ -665,50 +665,40 @@
-this.x = x;%0A this.y = y;%0A this.z = z
+vec3.set(this.elements, x, y, z)
;%0A
@@ -943,16 +943,108 @@
s;%0A %7D%0A%0A
+ scale(value) %7B%0A vec3.scale(this.elements, this.elements, value);%0A return this;%0A %7D%0A%0A
normal
@@ -1364,24 +1364,24 @@
(vector3) %7B%0A
-
return t
@@ -1446,16 +1446,223 @@
z;%0A %7D%0A%0A
+ equals(vector3) %7B%0A return vec3.exactEquals(this.elements, vector3.elements);%0A %7D%0A%0A applyMatrix4(matrix4) %7B%0A vec3.transformMat4(this.elements, this.elements, matrix4.elements);%0A return this;%0A %7D%0A%0A
angleT
|
46408746433d2fa8edb791d8842a6cda512d931d
|
Fix check for new text measurement results
|
src/gameobjects/text/MeasureText.js
|
src/gameobjects/text/MeasureText.js
|
/**
* @author Richard Davey <[email protected]>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var CanvasPool = require('../../display/canvas/CanvasPool');
/**
* Calculates the ascent, descent and fontSize of a given font style.
*
* @function Phaser.GameObjects.MeasureText
* @since 3.0.0
*
* @param {Phaser.GameObjects.TextStyle} textStyle - The TextStyle object to measure.
*
* @return {Phaser.Types.GameObjects.Text.TextMetrics} An object containing the ascent, descent and fontSize of the TextStyle.
*/
var MeasureText = function (textStyle)
{
var canvas = CanvasPool.create(this);
var context = canvas.getContext('2d');
textStyle.syncFont(canvas, context);
var metrics = context.measureText(textStyle.testString);
if (metrics.hasOwnProperty('actualBoundingBoxAscent'))
{
var ascent = metrics.actualBoundingBoxAscent;
var descent = metrics.actualBoundingBoxDescent;
CanvasPool.remove(canvas);
return {
ascent: ascent,
descent: descent,
fontSize: ascent + descent
};
}
var width = Math.ceil(metrics.width * textStyle.baselineX);
var baseline = width;
var height = 2 * baseline;
baseline = baseline * textStyle.baselineY | 0;
canvas.width = width;
canvas.height = height;
context.fillStyle = '#f00';
context.fillRect(0, 0, width, height);
context.font = textStyle._font;
context.textBaseline = 'alphabetic';
context.fillStyle = '#000';
context.fillText(textStyle.testString, 0, baseline);
var output = {
ascent: 0,
descent: 0,
fontSize: 0
};
var imagedata = context.getImageData(0, 0, width, height);
if (!imagedata)
{
output.ascent = baseline;
output.descent = baseline + 6;
output.fontSize = output.ascent + output.descent;
CanvasPool.remove(canvas);
return output;
}
var pixels = imagedata.data;
var numPixels = pixels.length;
var line = width * 4;
var i;
var j;
var idx = 0;
var stop = false;
// ascent. scan from top to bottom until we find a non red pixel
for (i = 0; i < baseline; i++)
{
for (j = 0; j < line; j += 4)
{
if (pixels[idx + j] !== 255)
{
stop = true;
break;
}
}
if (!stop)
{
idx += line;
}
else
{
break;
}
}
output.ascent = baseline - i;
idx = numPixels - line;
stop = false;
// descent. scan from bottom to top until we find a non red pixel
for (i = height; i > baseline; i--)
{
for (j = 0; j < line; j += 4)
{
if (pixels[idx + j] !== 255)
{
stop = true;
break;
}
}
if (!stop)
{
idx -= line;
}
else
{
break;
}
}
output.descent = (i - baseline);
output.fontSize = output.ascent + output.descent;
CanvasPool.remove(canvas);
return output;
};
module.exports = MeasureText;
|
JavaScript
| 0 |
@@ -833,31 +833,8 @@
if
-(metrics.hasOwnProperty
('ac
@@ -855,17 +855,27 @@
xAscent'
-)
+ in metrics
)%0A %7B%0A
|
94b08206212cc9cd288cb48f14b4cdcdf908b111
|
Add missing semicolons.
|
app/assets/javascripts/apps/placeslist/placeslist_app.js
|
app/assets/javascripts/apps/placeslist/placeslist_app.js
|
Teikei.module("PlacesList", function(PlacesList, Teikei, Backbone, Marionette, $, _) {
PlacesList.Controller = {
showEntryList: function() {
var currentUser = Teikei.currentUser;
var filteredCollection;
if (currentUser) {
filteredCollection = Teikei.Places.collection.byUser(currentUser.get('id'));
filteredCollection.comparator = function(model) {
return [model.get("type"), model.get("name")];
}
filteredCollection.sort();
}
var entryListView = new Teikei.PlacesList.EntryListView({
collection: filteredCollection
});
Teikei.modalRegion.show(entryListView);
}
}
Teikei.vent.on("user:show:entrylist", PlacesList.Controller.showEntryList, PlacesList.Controller);
});
|
JavaScript
| 0.001384 |
@@ -444,24 +444,25 @@
%5D;%0A %7D
+;
%0A fil
@@ -661,16 +661,17 @@
%7D%0A %7D
+;
%0A%0A Teik
|
d6d8b3d5eda6ebec6c6a611c38bf2f5e146cc5a5
|
Update app.js
|
build/app.js
|
build/app.js
|
'use strict';
//var Menu = React.createClass({
// displayName: 'Menu',
// render: function render() {
// var menus = [{ name: 'Home', link: '#home' }, { name: 'Portfolio', link: '#portfolio' }, { name: 'Article', link: '#article' }, { name: 'About', link: '#about' }];
// return React.createElement(
// 'ul',
// { className: 'menu' },
// menus.map(function (item) {
// return React.createElement(
// 'li',
// null,
// React.createElement(
// 'a',
// { href: item.link },
// item.name
// )
// );
// })
// );
// }
//});
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var _ReactRouter = ReactRouter;
var Router = _ReactRouter.Router;
var Link = _ReactRouter.Link;
var Route = _ReactRouter.Route;
var IndexRoute = _ReactRouter.IndexRoute;
var App = React.createClass({
displayName: 'App',
render: function render() {
var pathname = this.props.location.pathname;
return React.createElement(
'div',
{ className: 'container' },
React.createElement(
'div',
{ className: 'header' },
React.createElement(
'div',
{ className: 'row' },
//React.createElement(
// 'div',
// { className: 'four columns' },
//React.createElement(
// Link,
//{ to: 'home' },
// React.createElement('div', { className: 'logo' })
//)
//)
//React.createElement(
// 'div',
//{ className: 'eight columns' },
//React.createElement(Menu, null)
//)
)
),
React.createElement(
'div',
{ className: 'content' },
React.createElement(
ReactCSSTransitionGroup,
{ component: 'div', transitionName: 'example', transitionEnterTimeout: 500, transitionLeaveTimeout: 500 },
React.cloneElement(this.props.children || React.createElement('div', null), { key: pathname })
)
)
);
}
});
ReactDOM.render(React.createElement(
Router,
null,
React.createElement(
Route,
{ path: '/', component: App },
React.createElement(IndexRoute, { component: Home }),
React.createElement(Route, { path: 'home', component: Home }),
React.createElement(Route, { path: 'portfolio', component: Portfolio }),
React.createElement(Route, { path: 'article', component: Article }),
React.createElement(Route, { path: 'about', component: About }),
React.createElement(Route, { path: 'post/:slug', component: Post })
)
), document.getElementById('root'));
|
JavaScript
| 0.000002 |
@@ -1448,34 +1448,32 @@
-//
React.createElem
@@ -1498,18 +1498,16 @@
-//
'div'
@@ -1531,18 +1531,16 @@
-//
%7B class
@@ -1812,34 +1812,32 @@
-//
)%0A
|
943969335f6c00c290991b5fb82a86a191e7f3c2
|
update to grant compatibility with older versions
|
gulpfile.js
|
gulpfile.js
|
const gulp = require('gulp');
const args = require('yargs').argv;
const sequence = require('run-sequence');
const $ = require('gulp-load-plugins')({lazy: true});
gulp.task('build', () => {
return gulp.src('./src/**/*.js')
.pipe($.babel({
presets: ['es2015']
}))
.pipe(gulp.dest('lib'));
});
gulp.task('test', done => {
if (args.coverage) {
sequence(
'pre-tests',
'run-tests',
done);
} else {
sequence(
'run-tests',
done);
}
});
gulp.task('pre-tests', () => {
return gulp.src('./lib/**/*.js')
.pipe($.istanbul({
includeUntested: true
}))
.pipe($.istanbul.hookRequire());
});
gulp.task('run-tests', () => {
let stream = gulp.src('./test/*.spec.js', {read: false})
.pipe($.mocha());
if (args.coverage) {
stream.pipe($.istanbul.writeReports({
reportOpts: {
dir: './coverage'
}
}));
}
return stream;
});
|
JavaScript
| 0 |
@@ -1,13 +1,11 @@
-const
+var
gulp =
@@ -21,21 +21,19 @@
gulp');%0A
-const
+var
args =
@@ -55,21 +55,19 @@
).argv;%0A
-const
+var
sequenc
@@ -100,13 +100,11 @@
);%0A%0A
-const
+var
$ =
@@ -168,21 +168,26 @@
build',
-() =%3E
+function()
%7B%0A ret
@@ -326,15 +326,22 @@
t',
+function(
done
- =%3E
+)
%7B%0A
@@ -512,29 +512,34 @@
pre-tests',
-() =%3E
+function()
%7B%0A return
@@ -692,21 +692,26 @@
s',
-() =%3E
+function()
%7B%0A
-let
+var
str
|
cc2e5aca56e546480932ee028f775f219a1d3933
|
improve tests for eagerCreate=true
|
tests/integration/components/ember-tree/component-test.js
|
tests/integration/components/ember-tree/component-test.js
|
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('/ember-tree', 'Integration | Component | ember tree', {
integration: true
});
const fixtureTreeModel = {
id: 1,
label: 'Level',
isExpanded: true,
children: [
{
id: 2,
label: 'Level1',
children: []
},
{
id: 3,
label: 'Level1-2nd',
children: [
{
id: 4,
label: 'Level2',
children: [
{
id: 5,
label: 'Level3'
}
]
}
]
}
]
};
test('call expandAction on inner node', function(assert){
assert.expect(3);
this.set('node', Ember.$.extend(true, {}, fixtureTreeModel));
this.render(
hbs`{{#ember-tree expandAction="expandActionHandler" node=node as |node isExpanded|}}{{#ember-tree/trigger-expand}}expand-{{node.id}}{{/ember-tree/trigger-expand}}{{node.label}}{{/ember-tree}}`
);
this.on('expandActionHandler', (node, obj)=>{
assert.equal(node.label, 'Level1-2nd', 'correct node');
assert.deepEqual(obj, { isExpanded: true }, 'is expanded');
});
const $tree = this.$();
assert.ok($tree);
$tree.find('span:contains("expand-3")').click();
});
test('showOnly property', function(assert){
assert.expect(2);
this.set('node', Ember.$.extend(true, {}, fixtureTreeModel));
this.render(
hbs`{{#ember-tree showOnly=1 showOtherTextFmt="rest %@" node=node as |node isExpanded|}}{{#ember-tree/trigger-expand}}expand{{/ember-tree/trigger-expand}}{{node.label}}{{/ember-tree}}`
);
const $tree = this.$();
assert.equal($tree.find('.other-children.hidden').size(), 1);
$tree.find('a:contains("rest 1")').click();
assert.equal($tree.find('.other-children.hidden').size(), 0);
});
test('eagerCreate=true', function(assert){
assert.expect(1);
this.set('node', Ember.$.extend(true, {}, fixtureTreeModel));
this.render(
hbs`{{#ember-tree eagerCreate=true node=node as |node isExpanded|}}{{#ember-tree/trigger-expand}}expand{{/ember-tree/trigger-expand}}{{node.label}}{{/ember-tree}}`
);
const $tree = this.$();
assert.equal($tree.find('li').size(), 5);
// TODO: add more asserts
$tree.find('span:contains("expand-3")').click();
});
test('eagerCreate=false', function(assert){
assert.expect(1);
const treeHead = Ember.$.extend(true, {}, fixtureTreeModel);
treeHead.isExpanded = false;
this.set('node', treeHead);
this.render(
hbs`{{#ember-tree eagerCreate=false node=node as |node isExpanded|}}{{#ember-tree/trigger-expand}}expand{{/ember-tree/trigger-expand}}{{node.label}}{{/ember-tree}}`
);
const $tree = this.$();
assert.equal($tree.find('li').size(), 1);
// TODO: add more asserts
$tree.find('span:contains("expand-3")').click();
});
|
JavaScript
| 0.018676 |
@@ -643,16 +643,41 @@
%5D%0A%7D;%0A%0A
+const %7B copy %7D = Ember;%0A%0A
test('ca
@@ -770,33 +770,13 @@
e',
-Ember.$.extend(true, %7B%7D,
+copy(
fixt
@@ -779,32 +779,38 @@
fixtureTreeModel
+, true
));%0A this.rende
@@ -1385,33 +1385,13 @@
e',
-Ember.$.extend(true, %7B%7D,
+copy(
fixt
@@ -1394,32 +1394,38 @@
fixtureTreeModel
+, true
));%0A this.rende
@@ -1849,16 +1849,32 @@
ate=true
+, expand subtree
', funct
@@ -1898,25 +1898,25 @@
sert.expect(
-1
+3
);%0A%0A this.s
@@ -1930,33 +1930,13 @@
e',
-Ember.$.extend(true, %7B%7D,
+copy(
fixt
@@ -1947,16 +1947,22 @@
reeModel
+, true
));%0A th
@@ -2217,38 +2217,120 @@
), 5
-);%0A // TODO: add more asserts
+, 'total number of nodes');%0A assert.equal($tree.find('.hidden').size(), 4, 'all children hidden except first');
%0A $
@@ -2353,38 +2353,39 @@
contains(%22expand
--3
%22)')
+%5B2%5D
.click();%0A%7D);%0A%0At
@@ -2370,32 +2370,81 @@
)')%5B2%5D.click();%0A
+ assert.equal($tree.find('.hidden').size(), 3);%0A
%7D);%0A%0Atest('eager
@@ -2520,33 +2520,13 @@
d =
-Ember.$.extend(true, %7B%7D,
+copy(
fixt
@@ -2537,16 +2537,22 @@
reeModel
+, true
);%0A tre
|
dea7bdf3307da3abfdb006c4bf3bbc690da4bae6
|
add getPOJO on address
|
addon/models/address.js
|
addon/models/address.js
|
import Ember from 'ember';
import attr from 'ember-data/attr';
import Fragment from 'ember-data-model-fragments/fragment';
const { computed } = Ember;
const { isBlank } = Ember;
export default Fragment.extend({
countryCode: attr('string'),
administrativeArea: attr('string'),
locality: attr('string'),
dependentLocality: attr('string'),
postalCode: attr('string'),
sortingCode: attr('string'),
addressLine1: attr('string'),
addressLine2: attr('string'),
copyAddress(){
let newAddress = this.get('store').createFragment('address');
newAddress.set('countryCode', this.get('countryCode'));
newAddress.set('administrativeArea', this.get('administrativeArea'));
newAddress.set('locality', this.get('locality'));
newAddress.set('dependentLocality', this.get('dependentLocality'));
newAddress.set('postalCode', this.get('postalCode'));
newAddress.set('sortingCode', this.get('sortingCode'));
newAddress.set('addressLine1', this.get('addressLine1'));
newAddress.set('addressLine2', this.get('addressLine2'));
return newAddress;
},
clear(){
this.set('countryCode', null);
this.set('administrativeArea', null);
this.set('locality', null);
this.set('dependentLocality', null);
this.set('postalCode', null);
this.set('sortingCode', null);
this.set('addressLine1', null);
this.set('addressLine2', null);
},
clearExceptAddressLines(){
this.set('countryCode', null);
this.set('administrativeArea', null);
this.set('locality', null);
this.set('dependentLocality', null);
this.set('postalCode', null);
this.set('sortingCode', null);
},
isBlankModel: computed('countryCode', 'administrativeArea', 'locality', 'dependentLocality', 'postalCode', 'sortingCode', 'addressLine1', 'addressLine2', function(){
const { countryCode, administrativeArea, locality, dependentLocality, postalCode, sortingCode, addressLine1, addressLine2 } = this.getProperties('countryCode', 'administrativeArea', 'locality', 'dependentLocality', 'postalCode', 'sortingCode', 'addressLine1', 'addressLine2');
return isBlank(countryCode) && isBlank(administrativeArea) && isBlank(locality) && isBlank(dependentLocality) && isBlank(postalCode) && isBlank(sortingCode) && isBlank(addressLine1) && isBlank(addressLine2);
}),
isValidModel: computed('format', 'countryCode', 'administrativeArea', 'locality', 'dependentLocality', 'postalCode', 'sortingCode', 'addressLine1', 'addressLine2', function(){
const { format, countryCode, administrativeArea, locality, dependentLocality, postalCode, sortingCode, addressLine1, addressLine2 } = this.getProperties('format', 'countryCode', 'administrativeArea', 'locality', 'dependentLocality', 'postalCode', 'sortingCode', 'addressLine1', 'addressLine2');
const ignoreFields = ['organization', 'givenName', 'additionalName', 'familyName'];
let returnValue = false;
if(isBlank(format)) {
returnValue = false;
} else {
returnValue = true;
const requiredFields = format.data.attributes['required-fields'];
requiredFields.some((requiredField) => {
if(!ignoreFields.includes(requiredField)){
if(isBlank(this.get(requiredField))) {
returnValue = false;
return !returnValue;
}
}
});
}
return returnValue;
}),
});
|
JavaScript
| 0 |
@@ -1380,24 +1380,486 @@
null);%0A %7D,%0A
+ getPOJO()%7B%0A const pojo = %7B%7D;%0A pojo.countryCode = this.get('countryCode');%0A pojo.administrativeArea = this.get('administrativeArea');%0A pojo.locality = this.get('locality');%0A pojo.dependentLocality = this.get('dependentLocality');%0A pojo.postalCode = this.get('postalCode');%0A pojo.sortingCode = this.get('sortingCode');%0A pojo.addressLine1 = this.get('addressLine1');%0A pojo.addressLine2 = this.get('addressLine2');%0A return pojo;%0A %7D,%0A
clearExcep
|
86b82ddca5377926b35e89e5b321bb5b84307499
|
Fix conflict
|
build/app.js
|
build/app.js
|
function requireAll(r) { r.keys().forEach(r); }
// HTML
require('file-loader?name=[name].[ext]!../src/assets/index.html');
// CSS
require('bootstrap/dist/css/bootstrap.css');
require('../src/css/app.scss');
// JS
require('lodash');
window.jQuery = require('jquery');
require('bootstrap');
require('../src/js/app.js');
|
JavaScript
| 0.00644 |
@@ -1,53 +1,4 @@
-function requireAll(r) %7B r.keys().forEach(r); %7D%0A%0A
// H
@@ -261,12 +261,82 @@
s/app.js');%0A
+%0A// JSON%0Arequire('file-loader?name=%5Bname%5D.%5Bext%5D!../src/config.json');%0A
|
ba6db5469a3bb2510d08d5149f066fe3ed7a3760
|
remove debug info
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var debug = require('gulp-debug');
var gulpTypescript = require('gulp-typescript');
var typescript = require('typescript');
var merge = require('merge2');
var webpack = require('webpack');
var webpackStream = require('webpack-stream');
var path = require('path');
var foreach = require('gulp-foreach');
var stylus = require('gulp-stylus');
var nib = require('nib');
var liveReload = require('gulp-livereload');
var replace = require('gulp-replace');
var gulpIf = require('gulp-if');
gulp.task('default', ['copyFromDocs','copyFromBootstrap','copyFromFontAwesome','webpack'], watchTask);
gulp.task('copyFromGrid', copyFromGrid);
gulp.task('tscGrid', ['copyFromGrid'], tscGrid);
gulp.task('stylusGrid', ['copyFromGrid'], stylusGrid);
gulp.task('copyFromEnterprise', copyFromEnterprise);
gulp.task('copyGridToEnterprise', ['webpackGrid'], copyGridToEnterprise);
gulp.task('tscEnterprise', ['copyFromEnterprise','copyGridToEnterprise','stylusGrid','tscGrid'], tscEnterprise);
gulp.task('webpack', ['webpackEnterprise','webpackGrid'], liveReloadTask);
gulp.task('webpackEnterprise', ['tscEnterprise'], webpackEnterprise);
gulp.task('webpackGrid', ['stylusGrid','tscGrid'], webpackGrid);
gulp.task('liveReloadAfterCopyFromDocs', ['copyFromDocsExclNodeModules'], liveReloadTask);
gulp.task('copyFromDocsExclNodeModules', copyFromDocsExclNodeModules);
gulp.task('copyFromDocs', copyFromDocs);
gulp.task('copyFromBootstrap', copyFromBootstrap);
gulp.task('copyFromFontAwesome', copyFromFontAwesome);
function watchTask() {
liveReload.listen();
gulp.watch(['../ag-grid/src/**/*','../ag-grid-enterprise/src/**/*'], ['webpack']);
gulp.watch('../ag-grid-docs/src/**/*', ['liveReloadAfterCopyFromDocs']);
}
function copyFromGrid() {
return gulp.src(['../ag-grid/*', '../ag-grid/src/**/*'], {base: '../ag-grid'})
.pipe(gulp.dest('./node_modules/ag-grid'));
}
function copyFromEnterprise() {
return gulp.src(['../ag-grid-enterprise/*', '../ag-grid-enterprise/src/**/*'], {base: '../ag-grid-enterprise'})
.pipe(gulp.dest('./node_modules/ag-grid-enterprise'));
}
function copyGridToEnterprise() {
return gulp.src('./node_modules/ag-grid/**/*')
.pipe(gulp.dest('../ag-grid-enterprise/node_modules/ag-grid'));
}
function tscGrid() {
var tsResult = gulp
.src('./node_modules/ag-grid/src/ts/**/*.ts')
.pipe(gulpTypescript({
typescript: typescript,
module: 'commonjs',
experimentalDecorators: true,
emitDecoratorMetadata: true,
declarationFiles: true,
target: 'es5',
noImplicitAny: true
}));
return merge([
tsResult.dts
.pipe(gulp.dest('./node_modules/ag-grid/dist/lib')),
tsResult.js
.pipe(gulp.dest('./node_modules/ag-grid/dist/lib'))
])
}
function tscEnterprise() {
var tsResult = gulp
.src('./node_modules/ag-grid-enterprise/src/**/*.ts')
.pipe(gulpTypescript({
typescript: typescript,
module: 'commonjs',
experimentalDecorators: true,
emitDecoratorMetadata: true,
declarationFiles: true,
target: 'es5',
noImplicitAny: true
}));
return merge([
tsResult.dts
.pipe(gulp.dest('./node_modules/ag-grid-enterprise/dist/lib')),
tsResult.js
.pipe(gulp.dest('./node_modules/ag-grid-enterprise/dist/lib'))
])
}
function stylusGrid() {
// Uncompressed
gulp.src(['./node_modules/ag-grid/src/styles/*.styl', '!./node_modules/ag-grid/src/styles/theme-common.styl'])
.pipe(foreach(function(stream, file) {
var currentTheme = path.basename(file.path, '.styl');
var themeName = currentTheme.replace('theme-','');
return stream
.pipe(stylus({
use: nib(),
compress: false
}))
.pipe(gulpIf(currentTheme !== 'ag-grid', replace('ag-common','ag-' + themeName)))
.pipe(gulp.dest('./node_modules/ag-grid/dist/styles/'));
}));
}
function liveReloadTask() {
return gulp.src('./gulpfile.js').pipe(liveReload());
}
function webpackEnterprise() {
var mainFile = './node_modules/ag-grid-enterprise/webpack-with-styles.js';
var fileName = 'ag-grid-enterprise.js';
return gulp.src('src/entry.js')
.pipe(webpackStream({
entry: {
main: mainFile
},
output: {
path: path.join(__dirname, "dist"),
filename: fileName,
library: ["agGrid"],
libraryTarget: "umd"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
}
}))
.pipe(gulp.dest('./web-root/dist'));
}
function webpackGrid() {
var mainFile = './node_modules/ag-grid/main-with-styles.js';
var fileName = 'ag-grid.js';
return gulp.src('src/entry.js')
.pipe(webpackStream({
entry: {
main: mainFile
},
output: {
path: path.join(__dirname, "dist"),
filename: fileName,
library: ["agGrid"],
libraryTarget: "umd"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
}
}))
.pipe(gulp.dest('./web-root/dist'));
}
function copyFromDocs() {
return gulp.src(
['../ag-grid-docs/src/**/*'])
.pipe(gulp.dest('./web-root'));
}
function copyFromDocsExclNodeModules() {
return gulp.src(
['!../ag-grid-docs/src/ng2-example/node_modules',
'../ag-grid-docs/src/**/*'
])
.pipe(debug())
.pipe(gulp.dest('./web-root'));
}
function copyFromBootstrap() {
return gulp.src([
'./node_modules/bootstrap/dist/js/bootstrap.js',
'./node_modules/bootstrap/dist/css/bootstrap.css',
'./node_modules/bootstrap/dist/css/bootstrap-theme.css'
])
.pipe(gulp.dest('./web-root/dist'));
}
function copyFromFontAwesome() {
return gulp.src([
'./node_modules/font-awesome/css/font-awesome.css',
'./node_modules/font-awesome/fonts/*'
]
, {base: './node_modules/font-awesome'}
)
.pipe(gulp.dest('./web-root/font-awesome'));
}
|
JavaScript
| 0 |
@@ -25,43 +25,8 @@
');%0A
-var debug = require('gulp-debug');%0A
var
@@ -5883,31 +5883,8 @@
%5D)%0A
- .pipe(debug())%0A
|
2edcff57f4299dbbe1e6d244b3712375e46d6271
|
remove file override node env declarations, https://github.com/phetsims/tasks/issues/972
|
js/grunt/lint.js
|
js/grunt/lint.js
|
// Copyright 2015, University of Colorado Boulder
/**
* Runs the lint rules on the specified files.
*
* @author Sam Reid (PhET Interactive Simulations)
*/
/* eslint-env node */
'use strict';
// modules
const eslint = require( 'eslint' );
const grunt = require( 'grunt' );
const md5 = require( 'md5' );
const path = require( 'path' );
const child_process = require( 'child_process' );
const getDataFile = require( './getDataFile' );
/**
* Lints the specified repositories.
* @public
*
* @param {Array.<string>} repos
* @param {boolean} cache
* @param {boolean} say - whether errors should be read out loud
* @returns {Object} - ESLint report object.
*/
module.exports = function( repos, cache, say = false ) {
// get a list of all the repos that can't be linted
const eslintBlacklist = getDataFile( 'no-lint' );
// filter out all unlintable repo. An unlintable repo is one that has no js in it, so it will fail when trying to
// lint it.
const filteredRepos = repos.filter( repo => {
return eslintBlacklist.indexOf( repo ) < 0;
} );
const cli = new eslint.CLIEngine( {
cwd: path.dirname( process.cwd() ),
// Caching only checks changed files or when the list of rules is changed. Changing the implementation of a
// custom rule does not invalidate the cache. Caches are declared in .eslintcache files in the directory where
// grunt was run from.
cache: cache,
// Our custom rules live here
rulePaths: [ 'chipper/eslint/rules' ],
// Where to store the target-specific cache file
cacheFile: `chipper/eslint/cache/${md5( repos.join( ',' ) )}.eslintcache`,
// Files to skip for linting
ignorePattern: [
'**/.git',
'**/build',
'**/node_modules',
'**/snapshots',
'sherpa/**',
'**/js/parser/svgPath.js',
'**/templates/chipper-initialization.js',
'**/templates/chipper-strings.js',
'**/templates/sim-config.js',
'phet-io-website/root/assets/js/ua-parser-0.7.12.min.js',
'phet-io-website/root/assets/js/jquery-1.12.3.min.js',
'phet-io-website/root/assets/highlight.js-9.1.0/highlight.pack.js',
'phet-io-website/root/assets/highlight.js-9.1.0/highlight.js',
'phet-io-website/root/assets/bootstrap-3.3.6-dist/js/npm.js',
'phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.min.js',
'phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.js',
'phet-io-website/root/assets/js/phet-io-ga.js',
'installer-builder/temp/**'
]
} );
grunt.verbose.writeln( 'linting: ' + filteredRepos.join( ', ' ) );
// run the eslint step
const report = cli.executeOnFiles( filteredRepos );
// pretty print results to console if any
( report.warningCount || report.errorCount ) && grunt.log.write( cli.getFormatter()( report.results ) );
say && report.warningCount && child_process.execSync( 'say Lint warnings detected!' );
say && report.errorCount && child_process.execSync( 'say Lint errors detected!' );
report.warningCount && grunt.fail.warn( report.warningCount + ' Lint Warnings' );
report.errorCount && grunt.fail.fatal( report.errorCount + ' Lint Errors' );
return report;
};
|
JavaScript
| 0 |
@@ -157,29 +157,8 @@
*/%0A
-/* eslint-env node */
%0A'us
|
4c582c39b707a66c30548016f7bb324c5aa88f8b
|
remove unused find import
|
tests/integration/components/new-version-notifier-test.js
|
tests/integration/components/new-version-notifier-test.js
|
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, find, waitUntil } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import setupMirage from '../../helpers/setup-mirage';
import Mirage from 'ember-cli-mirage';
import { set } from '@ember/object';
module('Integration | Component | new version notifier', function(hooks) {
setupRenderingTest(hooks);
setupMirage(hooks);
test('it yields the current and last version to the block', async function(assert) {
assert.expect(9);
let callCount = 0;
this.server.get('/VERSION.txt', function(){
++callCount;
return callCount < 4 ? 'v1.0.' + callCount : 'v1.0.3';
});
render(hbs`
{{#new-version-notifier updateInterval=100 enableInTests=true as |version lastVersion reload close|}}
<div id="version-value">{{version}}</div>
<div id="last-version-value">{{lastVersion}}</div>
{{/new-version-notifier}}
`);
await waitUntil(() => callCount === 1, { timeout: 95 });
assert.equal(callCount, 1, "1 call was made");
assert.dom("#version-value").doesNotExist("no version displayed when no upgrade available");
assert.dom("#last-version-value").doesNotExist("no last version displayed when no upgrade available");
await waitUntil(() => callCount === 2, { timeout: 190 });
assert.equal(callCount, 2);
assert.dom("#version-value").hasText('v1.0.2');
assert.dom("#last-version-value").hasText('v1.0.1');
await waitUntil(() => callCount === 6, { timeout: 490 });
assert.equal(callCount, 6);
assert.dom("#version-value").hasText('v1.0.3');
assert.dom("#last-version-value").hasText('v1.0.2');
});
test('it calls onNewVersion when a new version is detected', async function(assert) {
assert.expect(4);
let done = assert.async(2);
let callCount = 0;
this.server.get('/VERSION.txt', function(){
++callCount;
return `v1.0.${callCount}`;
});
set(this, "onNewVersion", (newVersion, oldVersion) => {
assert.equal(newVersion, "v1.0.2", "newVersion v1.0.2 is sent to onNewVersion");
assert.equal(oldVersion, "v1.0.1", "oldVersion v1.0.1 is sent to onNewVersion");
done();
});
set(this, "enableInTests", true);
render(hbs`{{new-version-notifier updateInterval=100 enableInTests=enableInTests onNewVersion=onNewVersion}}`);
await waitUntil(() => callCount === 1, { timeout: 95 });
assert.equal(callCount, 1, "1 call was made");
await waitUntil(() => callCount === 2, { timeout: 190 });
assert.equal(callCount, 2);
set(this, "enableInTests", false); // stop the loop from continuing
done();
});
test('one version', async function(assert) {
assert.expect(2);
let callCount = 0;
this.server.get('/VERSION.txt', function(){
++callCount;
return 'v1.0.3';
});
set(this, "onNewVersion", (newVersion, oldVersion) => {
throw `unexpected call to onNewVersion with ${newVersion}, ${oldVersion}`;
});
render(hbs`{{new-version-notifier updateInterval=100 enableInTests=true onNewVersion=onNewVersion}}`);
await waitUntil(() => callCount === 4, { timeout: 490 });
assert.dom('*').hasText('');
assert.equal(callCount, 4);
});
test('repeat on bad response', async function(assert) {
assert.expect(2);
let callCount = 0;
this.server.get('/VERSION.txt', function(){
++callCount;
if (callCount === 1) {
return new Mirage.Response(500, {}, { message: '' });
}
return 'v1.0.3';
});
set(this, "onNewVersion", (newVersion, oldVersion) => {
throw `unexpected call to onNewVersion with ${newVersion}, ${oldVersion}`;
});
render(hbs`{{new-version-notifier updateInterval=100 enableInTests=true onNewVersion=onNewVersion}}`);
await waitUntil(() => callCount === 4, { timeout: 490 });
assert.dom('*').hasText('');
assert.equal(callCount, 4);
});
test('it calls onError when request fails', async function(assert) {
assert.expect(1);
let called = false;
this.server.get('/VERSION.txt', function() {
called = true;
return new Mirage.Response(500, {}, { message: '' });
});
let onErrorCalled = false;
set(this, "onError", () => {
onErrorCalled = true;
});
render(hbs`{{new-version-notifier updateInterval=100 enableInTests=true onError=onError}}`);
await waitUntil(() => called, { timeout: 95 });
assert.ok(onErrorCalled, 'onError was called');
});
});
|
JavaScript
| 0.000003 |
@@ -101,14 +101,8 @@
der,
- find,
wai
|
46d6db71c7867f02c743858f5b7b068e9d206427
|
Create Sample Dialog
|
app/assets/javascripts/components/actions/UserActions.js
|
app/assets/javascripts/components/actions/UserActions.js
|
import alt from '../alt';
import UsersFetcher from '../fetchers/UsersFetcher';
import cookie from 'react-cookie';
import DocumentHelper from '../utils/DocumentHelper';
class UserActions {
fetchUsers() {
UsersFetcher.fetchUsers()
.then((result) => {
this.dispatch(result.users);
}).catch((errorMessage) => {
console.log(errorMessage);
});
}
fetchCurrentUser() {
UsersFetcher.fetchCurrentUser()
.then((result) => {
this.dispatch(result.user);
}).catch((errorMessage) => {
console.log(errorMessage);
});
}
logout() {
fetch('/users/sign_out', {
method: 'delete',
credentials: 'same-origin',
data: {authenticity_token: DocumentHelper.getMetaContent("csrf-token")}
})
.then(response => {
console.log(response);
if (response.status == 204) {
location.reload();
}
});
}
}
export default alt.createActions(UserActions);
|
JavaScript
| 0 |
@@ -909,17 +909,16 @@
%7D);%0A %7D%0A
-%0A
%7D%0A%0Aexpor
|
953d2ca55a89ccec810d6e302e60b6d52b730dea
|
refresh timeline & watchlist after removing a doc
|
app/assets/javascripts/controllers/Profile.controller.js
|
app/assets/javascripts/controllers/Profile.controller.js
|
(function() {
'use-strict';
angular.module('dailyDocumentary')
.controller('ProfileController', ProfileController);
function ProfileController(profileFactory, $state, $mdToast, timeline, watchlist) {
var vm = this;
vm.hello = "Hello, Steve";
vm.removeDoc = removeDoc;
vm.getTimeline = getTimeline;
vm.getWatchlist = getWatchlist;
vm.timeline = timeline;
vm.watchlist = watchlist;
function getTimeline() {
profileFactory.getTimeline()
.then(function(response) {
vm.timeline = response.data;
});
}
function getWatchlist() {
profileFactory.getWatchlist()
.then(function(response) {
vm.watchlist = response.data;
});
}
function removeDoc(docId) {
return profileFactory.removeDoc(docId)
.then(showMessage);
function showMessage(message) {
$mdToast.showSimple(message);
}
}
}
}());
|
JavaScript
| 0 |
@@ -563,39 +563,34 @@
eline = response
-.data
;%0A
+
%7D);%0A %7D%0A
@@ -752,13 +752,8 @@
onse
-.data
;%0A
@@ -888,24 +888,24 @@
wMessage);%0A%0A
-
functi
@@ -926,24 +926,77 @@
(message) %7B%0A
+ vm.getTimeline();%0A vm.getWatchlist();%0A
$mdT
|
7ec607d4413b05461771e66b69ba8e332524bf55
|
fix "Cannot read property 'getAttribute' of null" error
|
app/assets/javascripts/shortcuts_dashboard_navigation.js
|
app/assets/javascripts/shortcuts_dashboard_navigation.js
|
/**
* Helper function that finds the href of the fiven selector and updates the location.
*
* @param {String} selector
*/
export default (selector) => {
const link = document.querySelector(selector).getAttribute('href');
if (link) {
window.location = link;
}
};
|
JavaScript
| 0.000004 |
@@ -135,25 +135,24 @@
default
-(
selector
) =%3E %7B%0A
@@ -143,17 +143,16 @@
selector
-)
=%3E %7B%0A
@@ -157,20 +157,23 @@
const
-link
+element
= docum
@@ -199,16 +199,51 @@
elector)
+;%0A const link = element && element
.getAttr
|
286154de6f5fc18ef128cefc018091984f66888f
|
fix counter spaces
|
src/components/Counter/Counter.js
|
src/components/Counter/Counter.js
|
import React from 'react';
import classes from './Counter.scss';
export const Counter = ({counter, doubleAsync, increment}) => (
<div>
<h2 className={classes.counterContainer}>
Counter:
{' '}
<span className={classes['counter--green']}>
{counter}
</span>
</h2>
<button className='btn btn-default' onClick={increment}>
Increment
</button>
{' '}
<button className='btn btn-default' onClick={doubleAsync}>
Double (Async)
</button>
</div>
);
Counter.propTypes = {
counter: React.PropTypes.number.isRequired,
doubleAsync: React.PropTypes.func.isRequired,
increment: React.PropTypes.func.isRequired,
};
export default Counter;
|
JavaScript
| 0.000006 |
@@ -84,16 +84,17 @@
ter = (%7B
+
counter,
@@ -116,16 +116,17 @@
ncrement
+
%7D) =%3E (%0A
|
7a376de166b8f506510858034f79cb2e8b9f0f36
|
Update BoS suggestion to be consistent with guide
|
src/parser/deathknight/frost/modules/features/BreathOfSindragosa.js
|
src/parser/deathknight/frost/modules/features/BreathOfSindragosa.js
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import Analyzer from 'parser/core/Analyzer';
const GOOD_BREATH_DURATION_MS = 20000;
class BreathOfSindragosa extends Analyzer {
beginTimestamp = 0;
casts = 0;
badCasts = 0;
totalDuration = 0;
breathActive = false;
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.BREATH_OF_SINDRAGOSA_TALENT.id) {
return;
}
this.casts += 1;
this.beginTimestamp = event.timestamp;
this.breathActive = true;
}
on_byPlayer_removebuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.BREATH_OF_SINDRAGOSA_TALENT.id) {
return;
}
this.breathActive = false;
const duration = event.timestamp - this.beginTimestamp;
if (duration < GOOD_BREATH_DURATION_MS) {
this.badCasts +=1;
}
this.totalDuration += duration;
}
on_fightend(event) {
if (this.breathActive) {
this.casts -=1;
}
}
suggestions(when){
when(this.suggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<> You are not getting good uptime from your <SpellLink id={SPELLS.BREATH_OF_SINDRAGOSA_TALENT.id} /> casts. Your cast should last <b>at least</b> 15 seconds to take full advantage of the <SpellLink id={SPELLS.PILLAR_OF_FROST.id} /> buff. A good cast is one that lasts20 seconds or more. To ensure a good duration, make you sure have 3 Runes ready and 70 Runic Power pooled before you start the cast. Also make sure to use <SpellLink id={SPELLS.EMPOWER_RUNE_WEAPON.id} /> before you cast Breath of Sindragosa. {this.tickingOnFinishedString}</>)
.icon(SPELLS.BREATH_OF_SINDRAGOSA_TALENT.icon)
.actual(`You averaged ${(this.averageDuration).toFixed(1)} seconds of uptime per cast`)
.recommended(`>${recommended} seconds is recommended`);
});
}
get tickingOnFinishedString() {
return this.breathActive ? "Your final cast was not counted in the average since it was still ticking when the fight ended" : "";
}
get averageDuration() {
return ((this.totalDuration / this.casts) || 0) / 1000;
}
get suggestionThresholds() {
return {
actual: this.averageDuration,
isLessThan: {
minor: 20.0,
average: 17.5,
major: 15.0,
},
style: 'seconds',
suffix: 'Average',
};
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.BREATH_OF_SINDRAGOSA_TALENT.id} />}
value={`${(this.averageDuration).toFixed(1)} seconds`}
label="Average Breath of Sindragosa Duration"
tooltip={`You cast Breath of Sindragosa ${this.casts} times for a combined total of ${(this.totalDuration / 1000).toFixed(1)} seconds. ${this.badCasts} casts were under 20 seconds. ${this.tickingOnFinishedString}`}
position={STATISTIC_ORDER.CORE(60)}
/>
);
}
}
export default BreathOfSindragosa;
|
JavaScript
| 0 |
@@ -1558,16 +1558,17 @@
at lasts
+
20 secon
@@ -1630,47 +1630,67 @@
ave
-3
+60+
Run
-es ready and 70 Runic Power poo
+ic Power pooled and have less than 2 Runes availab
le
-d
bef
|
763510d70b1e659d7a7735fdb774f9a9dbd6bfcc
|
Put record service buttons in alphabetical order
|
app/assets/javascripts/student_profile/record_service.js
|
app/assets/javascripts/student_profile/record_service.js
|
(function() {
window.shared || (window.shared = {});
var dom = window.shared.ReactHelpers.dom;
var createEl = window.shared.ReactHelpers.createEl;
var merge = window.shared.ReactHelpers.merge;
var PropTypes = window.shared.PropTypes;
var ReactSelect = window.Select;
var Datepicker = window.shared.Datepicker;
var serviceColor = window.shared.serviceColor;
var ProvidedByEducatorDropdown = window.shared.ProvidedByEducatorDropdown;
var styles = {
dialog: {
border: '1px solid #ccc',
borderRadius: 2,
padding: 20,
marginBottom: 20,
marginTop: 10
},
cancelRecordServiceButton: { // overidding CSS
color: 'black',
background: '#eee',
marginLeft: 10,
marginRight: 10
},
datepickerInput: {
fontSize: 14,
padding: 5,
width: '50%'
},
serviceButton: {
background: '#eee', // override CSS
color: 'black'
},
buttonWidth: {
width: '12em',
fontSize: 12,
padding: 8
}
};
/*
Pure UI form for recording that a student is receiving a service.
Tracks its own local state and submits values to prop callbacks.
*/
var RecordService = window.shared.RecordService = React.createClass({
displayName: 'RecordService',
propTypes: {
studentFirstName: React.PropTypes.string.isRequired,
studentId: React.PropTypes.number.isRequired,
onSave: React.PropTypes.func.isRequired,
onCancel: React.PropTypes.func.isRequired,
requestState: PropTypes.nullable(React.PropTypes.string.isRequired),
// context
nowMoment: React.PropTypes.object.isRequired,
serviceTypesIndex: React.PropTypes.object.isRequired,
educatorsIndex: React.PropTypes.object.isRequired,
currentEducator: React.PropTypes.object.isRequired
},
getInitialState: function() {
return {
serviceTypeId: null,
providedByEducatorName: "",
momentStarted: moment.utc() // TODO should thread through
}
},
onDateChanged: function(dateText) {
var textMoment = moment.utc(dateText, 'MM/DD/YYYY');
var updatedMoment = (textMoment.isValid()) ? textMoment : null;
this.setState({ momentStarted: updatedMoment });
},
onProvidedByEducatorTyping: function(event) {
this.setState({ providedByEducatorName: event.target.value });
},
onProvidedByEducatorDropdownSelect: function(string) {
this.setState({ providedByEducatorName: string });
},
onServiceClicked: function(serviceTypeId, event) {
this.setState({ serviceTypeId: serviceTypeId });
},
onClickCancel: function(event) {
this.props.onCancel();
},
onClickSave: function(event) {
// Get the value of the autocomplete input
this.props.onSave({
serviceTypeId: this.state.serviceTypeId,
providedByEducatorName: this.state.providedByEducatorName,
dateStartedText: this.state.momentStarted.format('YYYY-MM-DD'),
recordedByEducatorId: this.props.currentEducator.id
});
},
render: function() {
return dom.div({ className: 'RecordService', style: styles.dialog },
this.renderWhichService(),
this.renderWhoAndWhen(),
this.renderButtons()
);
},
renderWhichService: function() {
return dom.div({},
dom.div({ style: { marginBottom: 5, display: 'inline' }}, 'Which service?'),
dom.div({ style: { display: 'flex', justifyContent: 'flex-start' } },
dom.div({ style: styles.buttonWidth },
this.renderServiceButton(505),
this.renderServiceButton(506),
this.renderServiceButton(507)
),
dom.div({ style: styles.buttonWidth },
this.renderServiceButton(502),
this.renderServiceButton(503),
this.renderServiceButton(504)
)
)
);
},
renderServiceButton: function(serviceTypeId, options) {
var serviceText = this.props.serviceTypesIndex[serviceTypeId].name;
var color = serviceColor(serviceTypeId);
return dom.button({
className: 'btn service-type',
onClick: this.onServiceClicked.bind(this, serviceTypeId),
tabIndex: -1,
style: merge(styles.serviceButton, styles.buttonWidth, {
background: color,
outline: 0,
border: (this.state.serviceTypeId === serviceTypeId)
? '4px solid rgba(49, 119, 201, 0.75)'
: '4px solid white'
})
}, serviceText);
},
renderEducatorSelect: function() {
return createEl(ProvidedByEducatorDropdown, {
onUserTyping: this.onProvidedByEducatorTyping,
onUserDropdownSelect: this.onProvidedByEducatorDropdownSelect,
studentId: this.props.studentId
});
},
renderWhoAndWhen: function() {
return dom.div({},
dom.div({ style: { marginTop: 20 } },
dom.div({}, 'Who is working with ' + this.props.studentFirstName + '?'),
dom.div({}, this.renderEducatorSelect())
),
dom.div({ style: { marginTop: 20 } }, 'When did they start?'),
createEl(Datepicker, {
styles: { input: styles.datepickerInput },
defaultValue: (this.state.momentStarted && this.state.momentStarted.format('MM/DD/YYYY')),
onChange: this.onDateChanged,
datepickerOptions: {
showOn: 'both',
dateFormat: 'mm/dd/yy',
minDate: undefined
}
})
);
},
renderButtons: function() {
var isFormComplete = (this.state.serviceTypeId && this.state.momentStarted);
return dom.div({ style: { marginTop: 15 } },
dom.button({
style: {
marginTop: 20,
background: (isFormComplete) ? undefined : '#ccc'
},
disabled: !isFormComplete,
className: 'btn save',
onClick: this.onClickSave
}, 'Record service'),
dom.button({
className: 'btn cancel',
style: styles.cancelRecordServiceButton,
onClick: this.onClickCancel
}, 'Cancel'),
(this.props.requestState === 'pending') ? dom.span({}, 'Saving...') : this.props.requestState
);
}
});
})();
|
JavaScript
| 0.000001 |
@@ -3597,17 +3597,17 @@
utton(50
-5
+3
),%0A
@@ -3644,9 +3644,9 @@
n(50
-6
+2
),%0A
@@ -3683,17 +3683,17 @@
utton(50
-7
+4
)%0A
@@ -3779,33 +3779,33 @@
ServiceButton(50
-2
+5
),%0A t
@@ -3822,33 +3822,33 @@
ServiceButton(50
-3
+6
),%0A t
@@ -3865,33 +3865,33 @@
ServiceButton(50
-4
+7
)%0A )%0A
|
da4c52e2ba3dfc46f6523616df9ecad489266835
|
Make sure there actually is an object
|
js/background.js
|
js/background.js
|
var txt_cache='604800';chrome.webRequest.onHeadersReceived.addListener(function(object){'use strict';var object_type=object.type.toLowerCase();if((object_type!=='main_frame')&&(object_type!=='sub_frame')&&(object_type!=='xmlhttprequest')){var headers=object.responseHeaders,len=headers.length-1,f=false,elem=null;do{elem=headers[len];switch(elem.name.toLowerCase()){case'cache-control':if(!f){f=true;elem.value='private, max-age='+txt_cache;}else{headers.splice(len,1);}
break;case'expires':case'last-modified':case'etag':headers.splice(len,1);break;default:break;}}while(len--);if(!f){var obj=null;obj={};obj.name='Cache-Control';obj.value='private, max-age='+txt_cache;headers.push(obj);}
return{responseHeaders:headers};}},{urls:['<all_urls>']},['blocking','responseHeaders']);chrome.runtime.onInstalled.addListener(function(){localStorage.run=true;txt_cache=localStorage.txt_cache='604800';});if(localStorage.run){txt_cache=localStorage.txt_cache;}else{localStorage.run=true;txt_cache=localStorage.txt_cache='604800';}
|
JavaScript
| 0.001165 |
@@ -94,16 +94,27 @@
strict';
+if(object)%7B
var obje
@@ -729,16 +729,17 @@
ders%7D;%7D%7D
+%7D
,%7Burls:%5B
@@ -1007,28 +1007,29 @@
Storage.txt_cache='604800';%7D
+%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.